From bd52b4d5ad36c3ea336d28066522fb6f02fcb3ce Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Fri, 4 Sep 2026 22:48:45 -0500 Subject: [PATCH 001/484] feat!: fence aggregate snapshot projections by source version Add explicit aggregate_snapshot projection authoring, atomic source fences in memory/SQLite/PostgreSQL, tombstone-aware late confirmation, and adapter regression proofs. BREAKING CHANGE: ProjectionRecordMetadata gains source_snapshot. Existing unversioned read-model rows require an explicit rebuild before opting into source-snapshot semantics. Apply framework migration 0005 before using SQL-backed stores. --- README.md | 58 ++ migrations/inventory.json | 12 + .../0005_projection_source_snapshots.sql | 3 + .../0005_projection_source_snapshots.sql | 3 + src/command_ledger/tests.rs | 1 + src/graphql/protocol/tests.rs | 1 + .../projection_protocol/direct_projection.rs | 5 + .../projection_protocol/state_impl.rs | 26 +- .../projection_protocol/store_impl.rs | 6 + src/lib.rs | 16 +- src/projection/executor.rs | 97 +++- src/projection/mod.rs | 3 + src/projection/placement.rs | 6 + src/projection/plan.rs | 8 + src/projection/program.rs | 32 ++ src/projection/source_snapshot_tests.rs | 503 ++++++++++++++++++ src/projection_protocol.rs | 6 +- src/projection_protocol/source_snapshot.rs | 99 ++++ src/projection_protocol/store/commit.rs | 8 + src/projection_protocol/store/identity.rs | 19 +- src/projection_protocol/store/query.rs | 2 + src/projection_protocol/store/replay.rs | 1 + src/projection_protocol/store/tests.rs | 1 + src/projection_protocol/workspace.rs | 33 +- src/sqlx_repo/projection_protocol/reads.rs | 38 +- .../projection_protocol/store_impl.rs | 8 +- src/sqlx_repo/projection_protocol/writes.rs | 58 +- src/sqlx_repo/repo/backend.rs | 18 +- tests/fixtures/source_snapshot_delete.graphql | 3 + tests/fixtures/source_snapshot_save.graphql | 3 + 30 files changed, 1020 insertions(+), 57 deletions(-) create mode 100644 migrations/postgres/0005_projection_source_snapshots.sql create mode 100644 migrations/sqlite/0005_projection_source_snapshots.sql create mode 100644 src/projection/source_snapshot_tests.rs create mode 100644 src/projection_protocol/source_snapshot.rs create mode 100644 tests/fixtures/source_snapshot_delete.graphql create mode 100644 tests/fixtures/source_snapshot_save.graphql diff --git a/README.md b/README.md index 1a8b209ea..b75315d00 100644 --- a/README.md +++ b/README.md @@ -267,6 +267,64 @@ mutation SaveTodo { } ``` +#### Full-state projections and out-of-order events + +Broker delivery order is not necessarily aggregate commit order. For a read +model whose rows are complete snapshots owned by one aggregate stream, opt in +to source-version fencing: + +```rust,ignore +distributed::projection! { + pub const TODOS: ProjectionDescriptor = { + name: "project_todos", + version: 2, + epoch: "todos-source-snapshots-v1", + model: Todos, + source: aggregate_snapshot, + on { + events: [TodoCreatedDomainEvent, TodoCompletedDomainEvent], + mutation: SaveTodo, + input: { todo: body }, + }, + on { + events: [TodoPurgedDomainEvent], + mutation: DeleteTodo, + input: { todo_id: aggregate_id }, + }, + }; +} +``` + +The framework compares canonical `(aggregate_sequence, publication_ordinal)` +within the owning `(aggregate_type, aggregate_id)` stream. A late snapshot +cannot overwrite a newer row or resurrect a deleted one. Even deletion before +creation leaves a durable tombstone. A newer snapshot can recreate the row. +Source fences, physical rows, row revisions, broker checkpoints and causal +observations commit atomically in the memory, SQLite and PostgreSQL adapters. +A stale input confirms the current row revision without generating a fake row +update; a concurrent change makes that confirmation retry through the normal +projection conflict path. + +Use this only for complete replacement snapshots with stable row keys. Every +affected key must be owned by one aggregate stream; joins, counters, partial +patches and relationship side effects need their own ordering/fold semantics. +This mode rejects delta operations, expression partitions and direct placement. +Different aggregate streams cannot take over an existing fenced key. Matching +source versions with conflicting occurrence content fail closed. + +Migration `0005_projection_source_snapshots` persists the fence alongside each +record, including tombstones; compaction does not remove it. Enabling this on +an existing unversioned projection requires an explicit read-model rebuild +from retained canonical events. Merely changing the projection version or epoch +does not infer a source version for existing rows. The normal ordered-delivery +contract and transport identity checks still apply; this is not a replacement +for reliable broker delivery or an incremental-event reorder buffer. + +Custom program factories can use `ProjectionProgram::with_source_snapshots()`; +the policy is part of the canonical program identity. Browser optimism continues +to use the same mutation program, and authoritative confirmation uses committed +row revisions rather than comparing browser timestamps. + Handlers stay thin: most Todo commands are `portable_command!` — shard, invoke one domain method, commit Eventual. `todo.create` keeps a `handle:` escape hatch when the body needs extra checks. diff --git a/migrations/inventory.json b/migrations/inventory.json index 1580c1173..f241a8742 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -48,6 +48,18 @@ "path": "migrations/postgres/0004_command_ledger_atomic_state.sql", "sha256": "bc49ca9c58a294b7c5876c9fcde8a14a8b6110594a06c48b37720d320a22d97e" } + }, + { + "version": 5, + "description": "projection source snapshots", + "sqlite": { + "path": "migrations/sqlite/0005_projection_source_snapshots.sql", + "sha256": "2cb605be4ec190d9b3f156bdbbeb83a76e5f1f37287a8a7f3c2653dafbede442" + }, + "postgres": { + "path": "migrations/postgres/0005_projection_source_snapshots.sql", + "sha256": "2cb605be4ec190d9b3f156bdbbeb83a76e5f1f37287a8a7f3c2653dafbede442" + } } ] } diff --git a/migrations/postgres/0005_projection_source_snapshots.sql b/migrations/postgres/0005_projection_source_snapshots.sql new file mode 100644 index 000000000..2d7f5b4a1 --- /dev/null +++ b/migrations/postgres/0005_projection_source_snapshots.sql @@ -0,0 +1,3 @@ +-- Fences survive deletion, process restart and change-log compaction. +-- NULL denotes a delivery-ordered (not source-snapshot) projection. +ALTER TABLE projection_records ADD COLUMN source_snapshot TEXT; diff --git a/migrations/sqlite/0005_projection_source_snapshots.sql b/migrations/sqlite/0005_projection_source_snapshots.sql new file mode 100644 index 000000000..2d7f5b4a1 --- /dev/null +++ b/migrations/sqlite/0005_projection_source_snapshots.sql @@ -0,0 +1,3 @@ +-- Fences survive deletion, process restart and change-log compaction. +-- NULL denotes a delivery-ordered (not source-snapshot) projection. +ALTER TABLE projection_records ADD COLUMN source_snapshot TEXT; diff --git a/src/command_ledger/tests.rs b/src/command_ledger/tests.rs index da9e426e5..a3ccd1bd8 100644 --- a/src/command_ledger/tests.rs +++ b/src/command_ledger/tests.rs @@ -123,6 +123,7 @@ fn direct_projection_evidence(marker: &str) -> SameTransactionProjectionEvidence let revision = RecordRevision::new(scope.clone(), 1, 1).unwrap(); let cursor = ProjectionChangeCursor::new(topology, partition, epoch, 1).unwrap(); let record = ProjectionRecordMetadata { + source_snapshot: None, revision: revision.clone(), tombstone: false, change: cursor.clone(), diff --git a/src/graphql/protocol/tests.rs b/src/graphql/protocol/tests.rs index e2fc204b7..17fe657f4 100644 --- a/src/graphql/protocol/tests.rs +++ b/src/graphql/protocol/tests.rs @@ -146,6 +146,7 @@ fn direct_projected_receipt() -> CausalCommandReceiptSource { receipt.obligations.clear(); receipt.direct_projection = Some(SameTransactionProjectionEvidence { records: vec![ProjectionRecordMetadata { + source_snapshot: None, revision: revision.clone(), tombstone: false, change: change.clone(), diff --git a/src/in_memory_repo/projection_protocol/direct_projection.rs b/src/in_memory_repo/projection_protocol/direct_projection.rs index d41f32e58..da90e0e8c 100644 --- a/src/in_memory_repo/projection_protocol/direct_projection.rs +++ b/src/in_memory_repo/projection_protocol/direct_projection.rs @@ -31,6 +31,10 @@ pub(in crate::in_memory_repo) fn stage_same_transaction_projection( protocol.register_same_transaction_ownership(&partition_key, batch)?; let mutation = &batch.mutations[0]; + crate::projection_protocol::validate_snapshot_write( + protocol.records.get(&mutation.scope), + None, + )?; let lock_key = mutation.mutation.lock_key(); let row_exists = staged_rows.contains_key(&lock_key); let revision = match protocol.records.get(&mutation.scope) { @@ -69,6 +73,7 @@ pub(in crate::in_memory_repo) fn stage_same_transaction_projection( }, )?; let metadata = ProjectionRecordMetadata { + source_snapshot: None, revision: revision.clone(), tombstone: false, change: change.cursor.clone(), diff --git a/src/in_memory_repo/projection_protocol/state_impl.rs b/src/in_memory_repo/projection_protocol/state_impl.rs index 3161b9bef..fbd37abcf 100644 --- a/src/in_memory_repo/projection_protocol/state_impl.rs +++ b/src/in_memory_repo/projection_protocol/state_impl.rs @@ -537,12 +537,16 @@ impl InMemoryProjectionProtocolState { scope: &ProjectionRecordScope, expectation: &ProjectionRecordExpectation, kind: ProjectionMutationKind, + source_snapshot: bool, ) -> Result<(RecordRevision, bool), ProjectionProtocolError> { let current = self.records.get(scope); match (expectation, current, kind) { (ProjectionRecordExpectation::Missing, None, ProjectionMutationKind::Upsert) => { Ok((RecordRevision::new(scope.clone(), 1, 1)?, false)) } + (ProjectionRecordExpectation::Missing, None, ProjectionMutationKind::Delete) => { + Ok((RecordRevision::new(scope.clone(), 1, 1)?, true)) + } (ProjectionRecordExpectation::Missing, Some(metadata), _) if metadata.tombstone => { Err(ProjectionProtocolError::RecordTombstoned { model: scope.model().to_string(), @@ -582,7 +586,7 @@ impl InMemoryProjectionProtocolState { )?, false, )), - ProjectionMutationKind::Delete if metadata.tombstone => { + ProjectionMutationKind::Delete if metadata.tombstone && !source_snapshot => { Err(ProjectionProtocolError::RecordTombstoned { model: scope.model().to_string(), }) @@ -610,11 +614,9 @@ impl InMemoryProjectionProtocolState { )), } } - (_, _, ProjectionMutationKind::Delete | ProjectionMutationKind::Recreate) => { - Err(ProjectionProtocolError::InvalidBatch( - "delete/recreate requires an exact record expectation".into(), - )) - } + (_, _, ProjectionMutationKind::Recreate) => Err(ProjectionProtocolError::InvalidBatch( + "delete/recreate requires an exact record expectation".into(), + )), } } @@ -626,12 +628,16 @@ impl InMemoryProjectionProtocolState { row_exists: bool, ) -> Result<(), ProjectionProtocolError> { let should_exist = match (expectation, kind) { - (ProjectionRecordExpectation::Missing, ProjectionMutationKind::Upsert) => false, - (ProjectionRecordExpectation::Exact(_), ProjectionMutationKind::Recreate) => false, ( - ProjectionRecordExpectation::Exact(_), + ProjectionRecordExpectation::Missing, ProjectionMutationKind::Upsert | ProjectionMutationKind::Delete, - ) => true, + ) => false, + (ProjectionRecordExpectation::Exact(_), ProjectionMutationKind::Recreate) => false, + (ProjectionRecordExpectation::Exact(_), ProjectionMutationKind::Delete) => !self + .records + .get(scope) + .is_some_and(|record| record.tombstone), + (ProjectionRecordExpectation::Exact(_), ProjectionMutationKind::Upsert) => true, _ => { return Err(ProjectionProtocolError::InvalidBatch( "projection mutation has no valid physical-row expectation".into(), diff --git a/src/in_memory_repo/projection_protocol/store_impl.rs b/src/in_memory_repo/projection_protocol/store_impl.rs index 3dd70847d..dca270437 100644 --- a/src/in_memory_repo/projection_protocol/store_impl.rs +++ b/src/in_memory_repo/projection_protocol/store_impl.rs @@ -179,6 +179,11 @@ impl ProjectionProtocolStore for InMemoryRepository { &mutation.scope, &mutation.expectation, mutation.kind, + mutation.source_snapshot.is_some(), + )?; + crate::projection_protocol::validate_snapshot_write( + staged_protocol.records.get(&mutation.scope), + mutation.source_snapshot.as_ref(), )?; staged_protocol.validate_physical_record( &mutation.scope, @@ -201,6 +206,7 @@ impl ProjectionProtocolStore for InMemoryRepository { revision, tombstone, change: change.cursor.clone(), + source_snapshot: mutation.source_snapshot.clone(), }; staged_protocol.ensure_live_record_identity_available(&metadata)?; staged_protocol diff --git a/src/lib.rs b/src/lib.rs index a11837770..9b8e56861 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -169,6 +169,7 @@ macro_rules! projection { version: $version:expr, epoch: $epoch:literal, model: $model:ty, + $(source: $source:ident,)? $( on { events: [ $($event_ty:ty),+ $(,)? ], @@ -206,12 +207,14 @@ macro_rules! projection { )+ } )+ - $crate::compile_projection( + let program = $crate::compile_projection( $name, $version, $crate::ProjectionPartition::Unit, handlers, - ) + )?; + $(let program = $crate::__projection_source_policy!(program, $source)?;)? + Ok(program) } fn __resolve( occurrence: &$crate::DomainEventOccurrence, @@ -300,6 +303,15 @@ macro_rules! projection { }; } +/// Declaration helper for the closed source-ordering policy. +#[doc(hidden)] +#[macro_export] +macro_rules! __projection_source_policy { + ($program:expr, aggregate_snapshot) => { + $program.with_source_snapshots() + }; +} + /// Map `input: { key: body | aggregate_id }` keywords for [`projection!`]. #[macro_export] #[doc(hidden)] diff --git a/src/projection/executor.rs b/src/projection/executor.rs index 1a97efe2d..a67deaa74 100644 --- a/src/projection/executor.rs +++ b/src/projection/executor.rs @@ -39,6 +39,7 @@ struct ExecutionMutation { scope: ProjectionRecordScope, intent: LifecycleIntent, mutation: TableMutation, + source_snapshot: Option, } /// Store-free execution preflight produced before any adapter read. @@ -118,7 +119,7 @@ impl PreparedProjectionExecution { )); } - let mut staged = Vec::with_capacity(self.mutations.len()); + let mut next = workspace.clone(); for mutation in self.mutations { let snapshot = snapshots.get(&mutation.scope).ok_or_else(|| { ProjectionProtocolError::InvalidBatch(format!( @@ -127,12 +128,32 @@ impl PreparedProjectionExecution { )) })?; validate_snapshot_scope(snapshot)?; - staged.push(stage_for_snapshot(mutation, snapshot)?); - } - - let mut next = workspace.clone(); - for (mutation, expectation, kind) in staged { - next.stage_execution_mutation(mutation, expectation, kind)?; + let source = mutation.source_snapshot.clone(); + if let Some(record) = &snapshot.record { + match (&source, &record.source_snapshot) { + (Some(incoming), Some(current)) if !incoming.advances(current)? => { + // A stale command still observes the current authoritative + // revision. The commit validates that exact revision, so a + // racing writer cannot turn this into a false confirmation. + let (schema, _) = mutation_schema_key(&mutation.mutation); + next.confirm_existing(schema, record.revision.clone())?; + continue; + } + (Some(_), None) | (None, Some(_)) => { + return Err(ProjectionProtocolError::InvalidBatch( + "projection source-ordering policy changed; rebuild the read model" + .into(), + )); + } + _ => {} + } + } + let (physical, expectation, kind) = if source.is_some() { + stage_source_snapshot(mutation, snapshot)? + } else { + stage_for_snapshot(mutation, snapshot)? + }; + next.stage_execution_mutation(physical, expectation, kind, source)?; } *workspace = next; Ok(()) @@ -164,6 +185,15 @@ pub(crate) fn prepare_portable_projection( }; validate_execution_bounds(lowered.write_plan.mutations.len(), client_visible)?; lowered.write_plan.validate()?; + let source_snapshot = lowered + .resolved + .source_snapshots() + .then(|| { + crate::projection_protocol::SourceSnapshotVersion::from_occurrence( + lowered.resolved.occurrence(), + ) + }) + .transpose()?; let mut used_logical = vec![false; lowered.resolved.mutations().len()]; let mut mutations = Vec::with_capacity(lowered.write_plan.mutations.len()); @@ -203,6 +233,7 @@ pub(crate) fn prepare_portable_projection( scope, intent, mutation: physical, + source_snapshot: source_snapshot.clone(), }); } if used_logical.iter().any(|used| !used) { @@ -241,6 +272,7 @@ pub(crate) fn prepare_graph_projection( scope, intent: intent_for_physical(&mutation), mutation, + source_snapshot: None, }); } prepare(workspace, mutations, cached) @@ -433,6 +465,55 @@ pub(crate) fn validate_snapshot_scope( } } +fn stage_source_snapshot( + execution: ExecutionMutation, + snapshot: &ProjectionScopedRowSnapshot, +) -> Result< + ( + TableMutation, + ProjectionRecordExpectation, + ProjectionMutationKind, + ), + ProjectionProtocolError, +> { + let expected = snapshot + .record + .as_ref() + .map_or(ProjectionRecordExpectation::Missing, |record| { + ProjectionRecordExpectation::Exact(record.revision.clone()) + }); + match execution.intent { + LifecycleIntent::Upsert => { + let tombstone = snapshot + .record + .as_ref() + .is_some_and(|record| record.tombstone); + let mutation = if snapshot.row.is_some() { + normalize_save(execution.mutation)? + } else { + normalize_create(execution.mutation)? + }; + Ok(( + mutation, + expected, + if tombstone { + ProjectionMutationKind::Recreate + } else { + ProjectionMutationKind::Upsert + }, + )) + } + LifecycleIntent::Delete => Ok(( + normalize_delete(execution.mutation)?, + expected, + ProjectionMutationKind::Delete, + )), + _ => Err(ProjectionProtocolError::InvalidBatch( + "source snapshots cannot apply partial/delta mutations".into(), + )), + } +} + fn stage_for_snapshot( execution: ExecutionMutation, snapshot: &ProjectionScopedRowSnapshot, @@ -1067,6 +1148,7 @@ mod tests { scope: workspace.record_scope(schema, key).unwrap(), intent, mutation, + source_snapshot: None, } } @@ -1076,6 +1158,7 @@ mod tests { revision: u64, ) -> ProjectionRecordMetadata { ProjectionRecordMetadata { + source_snapshot: None, revision: RecordRevision::new(scope, 1, revision).unwrap(), tombstone, change: ProjectionChangeCursor::new( diff --git a/src/projection/mod.rs b/src/projection/mod.rs index 46b8d98b6..d3be10603 100644 --- a/src/projection/mod.rs +++ b/src/projection/mod.rs @@ -54,3 +54,6 @@ pub use provenance::{ #[cfg(test)] mod tests; + +#[cfg(all(test, feature = "graphql"))] +mod source_snapshot_tests; diff --git a/src/projection/placement.rs b/src/projection/placement.rs index a4ed8e41b..489522be2 100644 --- a/src/projection/placement.rs +++ b/src/projection/placement.rs @@ -1358,6 +1358,12 @@ fn validate_direct_eligibility( program: &ProjectionProgram, outputs: &[ProjectionOutput], ) -> Result<(), ProjectionTopologyError> { + if program.source_snapshots() { + return Err(ProjectionTopologyError::DirectIneligible { + reason: "source snapshots require canonical occurrences at the eventual projector" + .into(), + }); + } let [output] = outputs else { return Err(ProjectionTopologyError::DirectIneligible { reason: "direct evidence requires exactly one registered output schema".to_owned(), diff --git a/src/projection/plan.rs b/src/projection/plan.rs index b872d4c41..18327a42e 100644 --- a/src/projection/plan.rs +++ b/src/projection/plan.rs @@ -369,6 +369,8 @@ pub struct ResolvedProjectionPlan { arm_id: String, partition: ResolvedProjectionPartition, mutations: Vec, + #[serde(skip_serializing_if = "std::ops::Not::not")] + source_snapshots: bool, } impl ResolvedProjectionPlan { @@ -429,9 +431,15 @@ impl ResolvedProjectionPlan { arm_id: arm.arm_id().to_owned(), partition, mutations, + source_snapshots: program.source_snapshots(), }) } + /// Whether full-state writes require authoritative source-version fencing. + pub fn source_snapshots(&self) -> bool { + self.source_snapshots + } + /// Return the canonical program identity. pub fn program_id(&self) -> ProjectionProgramId { self.program_id diff --git a/src/projection/program.rs b/src/projection/program.rs index a40b3c149..23dd83e53 100644 --- a/src/projection/program.rs +++ b/src/projection/program.rs @@ -643,6 +643,8 @@ pub struct ProjectionProgram { version: u64, partition: ProjectionPartition, arms: Vec, + #[serde(skip_serializing_if = "std::ops::Not::not")] + source_snapshots: bool, } impl ProjectionProgram { @@ -691,9 +693,39 @@ impl ProjectionProgram { version, partition, arms, + source_snapshots: false, }) } + /// Fence complete row snapshots by their canonical aggregate occurrence. + /// + /// This is not appropriate for delta folds: dropping an older increment + /// would lose work. Snapshot programs must use a unit partition and only + /// full-row upserts or deletes, without relationship side effects. + pub fn with_source_snapshots(mut self) -> Result { + if !matches!(self.partition, ProjectionPartition::Unit) + || self.arms.iter().flat_map(|arm| arm.operations()).any(|op| { + !matches!( + op.kind(), + ProjectionMutationKind::Upsert | ProjectionMutationKind::Delete + ) || !op.relationship_effects().is_empty() + || !op.invalidations().is_empty() + }) + { + return Err(ProjectionProgramError::InvalidOperation { + operation: self.name.clone(), + reason: "source snapshots require unit-partition full-row upserts/deletes without relationship effects".into(), + }); + } + self.source_snapshots = true; + Ok(self) + } + + /// Whether authoritative row snapshots are fenced by aggregate version. + pub fn source_snapshots(&self) -> bool { + self.source_snapshots + } + /// Return the stable program name. pub fn name(&self) -> &str { &self.name diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs new file mode 100644 index 000000000..75518b91f --- /dev/null +++ b/src/projection/source_snapshot_tests.rs @@ -0,0 +1,503 @@ +//! Same modeled execution proof across memory, SQLite and PostgreSQL. +use std::sync::Arc; + +use crate::domain_event::DomainEventContract; +use crate::projection::executor::prepare_portable_projection; +use crate::projection::lower::{EventualOnly, ProjectionDescriptor}; +use crate::projection_protocol::*; +use crate::{ + DomainEventDescriptor, DomainEventEnvelope, DomainEventOccurrence, RelationalReadModel, RowKey, + RowValue, +}; + +#[derive( + Clone, Debug, serde::Serialize, serde::Deserialize, crate::DomainState, crate::ReadModel, +)] +#[domain_state(version = 1)] +#[readmodel(table = "source_snapshot_rows", primary_key = ["id"])] +struct SnapshotRow { + id: String, + title: String, +} +type SourceSnapshotRows = SnapshotRow; + +struct Changed; +impl DomainEventContract for Changed { + const EVENT_NAME: &'static str = "snapshot.changed"; + const EVENT_VERSION: u64 = 1; + fn descriptor() -> DomainEventDescriptor { + DomainEventDescriptor::state::("snapshot.changed", 1) + } +} +struct Removed; +impl DomainEventContract for Removed { + const EVENT_NAME: &'static str = "snapshot.removed"; + const EVENT_VERSION: u64 = 1; + fn descriptor() -> DomainEventDescriptor { + DomainEventDescriptor::state::("snapshot.removed", 1) + } +} +#[allow(non_snake_case)] +fn SaveSnapshot() -> crate::Mutation<()> { + crate::mutation_file!("tests/fixtures/source_snapshot_save.graphql") +} +#[allow(non_snake_case)] +fn DeleteSnapshot() -> crate::Mutation<()> { + crate::mutation_file!("tests/fixtures/source_snapshot_delete.graphql") +} +crate::projection! { + const SNAPSHOTS: ProjectionDescriptor = { + name: "source-snapshot-test", + version: 1, + epoch: "snapshot-v1", + model: SnapshotRow, + source: aggregate_snapshot, + on { events: [Changed], mutation: SaveSnapshot, input: { row: body }, }, + on { events: [Removed], mutation: DeleteSnapshot, input: { id: aggregate_id }, }, + }; +} + +fn event(id: &str, sequence: u64, title: &str, delete: bool) -> DomainEventOccurrence { + occurrence(id, sequence, 0, id, title, delete) +} + +fn occurrence( + id: &str, + sequence: u64, + ordinal: u32, + row_id: &str, + title: &str, + delete: bool, +) -> DomainEventOccurrence { + let mut occurrence = DomainEventOccurrence::capture( + if delete { + Removed::descriptor() + } else { + Changed::descriptor() + }, + DomainEventEnvelope { + aggregate_type: "snapshot-item".into(), + aggregate_id: id.into(), + aggregate_sequence: sequence, + publication_ordinal: ordinal, + occurred_at: std::time::UNIX_EPOCH, + metadata: Default::default(), + }, + &SnapshotRow { + id: row_id.into(), + title: title.into(), + }, + ) + .unwrap(); + occurrence.overwrite_causation_id(&format!("cause-{id}-{sequence}")); + occurrence +} + +struct Harness { + codec: Arc, +} +impl Harness { + async fn new(store: &impl ProjectionProtocolStore) -> Self { + let topology = ProjectorTopologyId::new(1, "source-snapshot-test", [0x8e; 32]).unwrap(); + let codec = Arc::new( + ProjectionScopeCodec::with_models( + topology.clone(), + [("SnapshotRow", SnapshotRow::schema())], + ) + .unwrap(), + ); + store + .register_projection_models( + &topology, + &[ProjectionModelOwnership::new("SnapshotRow", "source_snapshot_rows").unwrap()], + ) + .await + .unwrap(); + Self { codec } + } + + async fn prepare( + &self, + store: &impl ProjectionProtocolStore, + occurrence: &DomainEventOccurrence, + delivery: u64, + ) -> Result { + let partition = self.codec.encode_partition(None).unwrap(); + let input = TrustedProjectionInput::mint( + ProjectionInputCursor::new( + self.codec.topology().clone(), + partition, + ProjectionSource::new("test-broker", b"stream".to_vec()).unwrap(), + ProjectionEpoch::new("broker-v1").unwrap(), + delivery, + ) + .unwrap(), + ProjectionInputFingerprint::from_canonical_bytes( + &occurrence.canonical_bytes().unwrap(), + ), + occurrence.id(), + occurrence.causation_id().unwrap(), + ProjectionGeneration::initial(), + false, + ) + .unwrap(); + let mut workspace = ProjectionWorkspace::new( + self.codec.clone(), + None, + input, + ProjectionEpoch::new("snapshot-v1").unwrap(), + ) + .unwrap(); + let lowered = SNAPSHOTS + .server_executor() + .unwrap() + .plan(occurrence) + .unwrap(); + let prepared = prepare_portable_projection(&workspace, lowered)?; + let snapshots = store + .projection_execution_snapshot_batch(prepared.snapshot_request()) + .await?; + prepared.stage(&mut workspace, snapshots)?; + workspace.into_batch() + } + + async fn apply( + &self, + store: &impl ProjectionProtocolStore, + occurrence: &DomainEventOccurrence, + delivery: u64, + ) -> Result { + store + .commit_projection(self.prepare(store, occurrence, delivery).await?) + .await + } + + async fn read( + &self, + store: &impl ProjectionProtocolStore, + id: &str, + ) -> ProjectionQuerySnapshot { + store + .projection_query_snapshot( + &ProjectionQuerySnapshotRequest::new( + &self.codec, + None, + "SnapshotRow", + RowKey::new([("id", RowValue::String(id.into()))]), + Vec::new(), + ) + .unwrap(), + ) + .await + .unwrap() + } +} + +async fn matrix(store: &impl ProjectionProtocolStore) { + let h = Harness::new(store).await; + let first = h + .apply(store, &event("a", 3, "new", false), 1) + .await + .unwrap(); + assert_eq!(first.records.len(), 1); + for (delivery, sequence) in [(2, 2), (3, 1)] { + let stale = h + .apply(store, &event("a", sequence, "old", false), delivery) + .await + .unwrap(); + assert!( + stale.records.is_empty(), + "stale source must not allocate a row revision" + ); + let observations: Vec<_> = stale + .changes + .iter() + .filter(|change| change.kind == ProjectionChangeKind::Observation) + .collect(); + assert_eq!( + observations.len(), + 1, + "stale causation must observe current state" + ); + assert_eq!( + observations[0].revision, + Some(first.records[0].revision.clone()) + ); + } + let snapshot = h.read(store, "a").await; + assert_eq!( + snapshot.row.unwrap().get_serde::("title").unwrap(), + "new" + ); + assert_eq!(snapshot.record.unwrap().revision, first.records[0].revision); + + // Deletion before every earlier write must still establish a durable fence. + h.apply(store, &event("b", 5, "", true), 4).await.unwrap(); + h.apply(store, &event("b", 1, "late create", false), 5) + .await + .unwrap(); + let deleted = h.read(store, "b").await; + assert!(deleted.row.is_none()); + assert!(deleted.record.unwrap().tombstone); + // A newer snapshot explicitly recreates the row; stale deletion cannot undo it. + h.apply(store, &event("b", 6, "recreated", false), 6) + .await + .unwrap(); + h.apply(store, &event("b", 4, "", true), 7).await.unwrap(); + let recreated = h.read(store, "b").await; + assert_eq!( + recreated.row.unwrap().get_serde::("title").unwrap(), + "recreated" + ); + assert_eq!(recreated.record.unwrap().revision.incarnation(), 2); + // Repeated newer deletions advance the fence even while the row is absent. + h.apply(store, &event("b", 7, "", true), 8).await.unwrap(); + h.apply(store, &event("b", 9, "", true), 9).await.unwrap(); + h.apply(store, &event("b", 8, "delayed recreate", false), 10) + .await + .unwrap(); + assert!(h.read(store, "b").await.row.is_none()); + + // Occurrence IDs alone do not authenticate the body at an equal version. + assert!(h + .prepare(store, &event("a", 3, "conflict", false), 11) + .await + .is_err()); + // A different stream cannot overwrite another aggregate's row. + assert!(h + .prepare( + store, + &occurrence("intruder", 99, 0, "a", "takeover", false), + 11 + ) + .await + .is_err()); + // Different aggregates with equal sequence have independent clocks. + h.apply(store, &event("c", 1, "independent", false), 11) + .await + .unwrap(); + assert!(h.read(store, "c").await.row.is_some()); + + // Exact occurrence replay is a transport duplicate, not a second mutation. + let e = event("a", 4, "latest", false); + h.apply(store, &e, 12).await.unwrap(); + let replay = h.apply(store, &e, 12).await.unwrap(); + assert_eq!(replay.outcome, ProjectionCommitOutcome::Duplicate); + assert!(replay.records.is_empty()); + + // A stale-read observer cannot falsely confirm a row changed by a concurrent commit. + h.apply(store, &event("race", 3, "initial", false), 13) + .await + .unwrap(); + let stale = h + .prepare(store, &event("race", 2, "old", false), 15) + .await + .unwrap(); + h.apply(store, &event("race", 5, "racing", false), 14) + .await + .unwrap(); + assert!(matches!( + store.commit_projection(stale).await, + Err(ProjectionProtocolError::RecordRevisionConflict { .. }) + )); + + // Multiple publications in one aggregate commit share a causation but have + // an ordered publication ordinal. Late confirmation is still idempotent. + h.apply( + store, + &occurrence("ordinal", 1, 1, "ordinal", "second", false), + 16, + ) + .await + .unwrap(); + h.apply( + store, + &occurrence("ordinal", 1, 0, "ordinal", "first", false), + 17, + ) + .await + .unwrap(); + assert_eq!( + h.read(store, "ordinal") + .await + .row + .unwrap() + .get_serde::("title") + .unwrap(), + "second" + ); + + // Even a lower-level writer cannot clear an existing source fence. + let mut unfenced = h + .prepare(store, &event("a", 6, "unsafe", false), 19) + .await + .unwrap(); + unfenced.mutations[0].source_snapshot = None; + assert!(matches!( + store.commit_projection(unfenced).await, + Err(ProjectionProtocolError::InvalidBatch(_)) + )); + assert_eq!( + h.read(store, "a") + .await + .row + .unwrap() + .get_serde::("title") + .unwrap(), + "latest" + ); + + // Migration does not invent a source version for old read-model rows. + let mut unversioned = h + .prepare(store, &event("unversioned", 1, "old schema", false), 19) + .await + .unwrap(); + unversioned.mutations[0].source_snapshot = None; + store.commit_projection(unversioned).await.unwrap(); + assert!(h + .prepare(store, &event("unversioned", 2, "new schema", false), 20) + .await + .is_err()); +} + +#[tokio::test] +async fn source_snapshots_memory_reordering_and_atomic_confirmation() { + matrix(&crate::InMemoryRepository::new()).await; +} + +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn source_snapshots_sqlite_reordering_and_restart() { + use crate::table::TableSchemaRegistry; + let path = std::env::temp_dir().join(format!( + "distributed-source-snapshots-{}.sqlite", + uuid::Uuid::now_v7() + )); + let url = format!("sqlite:{}?mode=rwc", path.display()); + let store = crate::SqliteRepository::connect_and_migrate(&url) + .await + .unwrap(); + let mut registry = TableSchemaRegistry::new(); + registry + .register_schema(SnapshotRow::schema().clone()) + .unwrap(); + store + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + matrix(&store).await; + store.pool().close().await; + let restarted = crate::SqliteRepository::connect_and_migrate(&url) + .await + .unwrap(); + let h = Harness::new(&restarted).await; + h.apply(&restarted, &event("b", 2, "after restart", false), 21) + .await + .unwrap(); + assert!(h.read(&restarted, "b").await.row.is_none()); + restarted.pool().close().await; + std::fs::remove_file(path).unwrap(); +} + +#[cfg(feature = "postgres")] +#[tokio::test] +async fn source_snapshots_postgres_reordering_and_restart() { + let Ok(url) = std::env::var("DISTRIBUTED_SNAPSHOT_TEST_POSTGRES_URL") else { + return; + }; + let store = crate::PostgresRepository::connect_and_migrate(&url) + .await + .unwrap(); + let mut registry = crate::table::TableSchemaRegistry::new(); + registry + .register_schema(SnapshotRow::schema().clone()) + .unwrap(); + store + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + matrix(&store).await; + store.pool().close().await; + let restarted = crate::PostgresRepository::connect_and_migrate(&url) + .await + .unwrap(); + let h = Harness::new(&restarted).await; + h.apply(&restarted, &event("b", 2, "after restart", false), 21) + .await + .unwrap(); + assert!(h.read(&restarted, "b").await.row.is_none()); +} + +#[test] +fn source_snapshots_policy_is_explicit_hashed_and_rejects_delta_programs() { + use crate::projection::{ + ProjectionArm, ProjectionMutationKind as Kind, ProjectionOperation, ProjectionPartition, + ProjectionProgram, + }; + let snapshots = SNAPSHOTS.program().unwrap(); + let ordered = ProjectionProgram::try_new( + snapshots.name(), + snapshots.version(), + ProjectionPartition::Unit, + snapshots.arms().to_vec(), + ) + .unwrap(); + assert!(snapshots.source_snapshots()); + assert!(!ordered.source_snapshots()); + assert_ne!(snapshots.id().unwrap(), ordered.id().unwrap()); + let arm = &snapshots.arms()[0]; + let op = &arm.operations()[0]; + for kind in [Kind::Insert, Kind::Patch, Kind::UpsertPatch, Kind::Recreate] { + let operation = ProjectionOperation::try_new( + op.operation_id(), + 0, + kind, + op.target().clone(), + op.key().to_vec(), + op.fields().to_vec(), + vec![], + vec![], + ) + .unwrap(); + let arm = + ProjectionArm::try_new(arm.arm_id(), arm.selector().clone(), vec![operation]).unwrap(); + let program = + ProjectionProgram::try_new("delta", 1, ProjectionPartition::Unit, vec![arm]).unwrap(); + assert!( + program.with_source_snapshots().is_err(), + "{kind:?} cannot silently become a snapshot" + ); + } + let partitioned = ProjectionProgram::try_new( + "partitioned", + 1, + ProjectionPartition::Expression(op.key()[0].expression().clone()), + snapshots.arms().to_vec(), + ) + .unwrap(); + assert!(partitioned.with_source_snapshots().is_err()); +} + +#[test] +fn source_snapshots_reject_direct_materialization() { + use crate::projection::placement::*; + let result = ProjectionBinding::materialize_direct( + DirectProjectionPlacement::new(&SNAPSHOTS), + ProjectionSourceBinding::try_new("snapshot-domain", "ordered-domain-events", 1).unwrap(), + ProjectionOwner::try_new("snapshot-direct").unwrap(), + "distributed-projection-partition", + 1, + vec![ProjectionOutput::try_new( + "SnapshotRow", + "source_snapshot_rows", + SnapshotRow::schema().clone(), + ) + .unwrap()], + vec![], + None, + ); + assert!(matches!( + result, + Err(ProjectionTopologyError::DirectIneligible { .. }) + )); +} diff --git a/src/projection_protocol.rs b/src/projection_protocol.rs index 17293d241..7173c1f19 100644 --- a/src/projection_protocol.rs +++ b/src/projection_protocol.rs @@ -1,8 +1,9 @@ //! Adapter-neutral identities and ordering vocabulary for durable projections. //! -//! These types deliberately separate three different notions of progress: +//! These types deliberately separate four different notions of progress: //! //! - [`ProjectionInputCursor`] orders trusted inputs from one exact source; +//! - [`SourceSnapshotVersion`] fences snapshots from one aggregate stream; //! - [`RecordRevision`] orders versions of one exact projected record; and //! - [`ProjectionChangeCursor`] orders durable changes emitted by a projector. //! @@ -16,8 +17,11 @@ use std::num::{NonZeroU32, NonZeroU64}; use serde::{Deserialize, Serialize}; mod codec; +mod source_snapshot; mod store; mod workspace; +pub(crate) use source_snapshot::validate_snapshot_write; +pub use source_snapshot::SourceSnapshotVersion; pub(crate) use codec::{ canonical_projection_topology_bytes, compile_projection_topology, digest_projection_binding, diff --git a/src/projection_protocol/source_snapshot.rs b/src/projection_protocol/source_snapshot.rs new file mode 100644 index 000000000..7b676ecd4 --- /dev/null +++ b/src/projection_protocol/source_snapshot.rs @@ -0,0 +1,99 @@ +//! Authoritative source versions, separate from broker and row revisions. + +use super::ProjectionProtocolError; +use crate::DomainEventOccurrence; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Durable fence for a full-state projection of one aggregate stream. +/// +/// Constructed by the framework from a validated canonical occurrence, never +/// from transport headers or application-supplied timestamps. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SourceSnapshotVersion { + aggregate_type: String, + aggregate_id: String, + sequence: u64, + publication_ordinal: u32, + occurrence_id: String, + occurrence_fingerprint: [u8; 32], +} + +impl SourceSnapshotVersion { + #[cfg(any(feature = "sqlite", feature = "postgres"))] + pub(crate) fn validate_stored(&self) -> Result<(), ProjectionProtocolError> { + if self.sequence == 0 + || crate::bus::validate_message_name(&self.aggregate_type).is_err() + || crate::bus::validate_stable_message_id(Some(&self.aggregate_id)).is_err() + || crate::bus::validate_stable_message_id(Some(&self.occurrence_id)).is_err() + { + return Err(ProjectionProtocolError::InvalidBatch( + "invalid stored source snapshot identity".into(), + )); + } + Ok(()) + } + + pub(crate) fn from_occurrence( + event: &DomainEventOccurrence, + ) -> Result { + let canonical = event + .canonical_bytes() + .map_err(|error| ProjectionProtocolError::InvalidBatch(error.to_string()))?; + Ok(Self { + aggregate_type: event.aggregate_type().into(), + aggregate_id: event.aggregate_id().into(), + sequence: event.aggregate_sequence(), + publication_ordinal: event.publication_ordinal(), + occurrence_id: event.id().into(), + occurrence_fingerprint: Sha256::digest(canonical).into(), + }) + } + + /// True only when this occurrence advances the same authoritative stream. + pub(crate) fn advances(&self, current: &Self) -> Result { + if self.aggregate_type != current.aggregate_type + || self.aggregate_id != current.aggregate_id + { + return Err(ProjectionProtocolError::InvalidBatch( + "source snapshot row is owned by another aggregate stream".into(), + )); + } + let incoming = (self.sequence, self.publication_ordinal); + let stored = (current.sequence, current.publication_ordinal); + if incoming == stored + && (self.occurrence_id != current.occurrence_id + || self.occurrence_fingerprint != current.occurrence_fingerprint) + { + return Err(ProjectionProtocolError::InvalidBatch( + "source snapshot version has conflicting occurrence identities".into(), + )); + } + Ok(incoming > stored) + } +} + +/// Defense at the atomic commit boundary, including non-modeled writers. +pub(crate) fn validate_snapshot_write( + current: Option<&super::ProjectionRecordMetadata>, + incoming: Option<&SourceSnapshotVersion>, +) -> Result<(), ProjectionProtocolError> { + match (current, incoming) { + (Some(record), Some(incoming)) => match &record.source_snapshot { + Some(stored) if incoming.advances(stored)? => Ok(()), + Some(_) => Err(ProjectionProtocolError::InvalidBatch( + "source snapshot write does not advance the stored version".into(), + )), + None => Err(ProjectionProtocolError::InvalidBatch( + "source snapshot requires rebuilding an unversioned row".into(), + )), + }, + (Some(record), None) if record.source_snapshot.is_some() => { + Err(ProjectionProtocolError::InvalidBatch( + "unversioned write cannot replace a source-fenced row".into(), + )) + } + _ => Ok(()), + } +} diff --git a/src/projection_protocol/store/commit.rs b/src/projection_protocol/store/commit.rs index 525a35f04..5a50f58b5 100644 --- a/src/projection_protocol/store/commit.rs +++ b/src/projection_protocol/store/commit.rs @@ -34,6 +34,14 @@ impl ProjectionCommitBatch { let mut scopes = std::collections::HashSet::new(); for mutation in &self.mutations { validate_scope(topology, partition, &mutation.scope)?; + if mutation.kind == ProjectionMutationKind::Delete + && matches!(mutation.expectation, ProjectionRecordExpectation::Missing) + && mutation.source_snapshot.is_none() + { + return Err(ProjectionProtocolError::InvalidBatch( + "delete of an unseen row requires an authoritative source snapshot".into(), + )); + } let schema = match &mutation.mutation { TableMutation::UpsertRow(mutation) => mutation.schema, TableMutation::PatchRow(mutation) => mutation.schema, diff --git a/src/projection_protocol/store/identity.rs b/src/projection_protocol/store/identity.rs index 791d42025..14d55028d 100644 --- a/src/projection_protocol/store/identity.rs +++ b/src/projection_protocol/store/identity.rs @@ -231,6 +231,7 @@ pub(crate) struct ProjectionRecordMutation { pub(crate) mutation: TableMutation, pub(crate) expectation: ProjectionRecordExpectation, pub(crate) kind: ProjectionMutationKind, + pub(crate) source_snapshot: Option, } impl ProjectionRecordMutation { @@ -239,6 +240,16 @@ impl ProjectionRecordMutation { mutation: TableMutation, expectation: ProjectionRecordExpectation, kind: ProjectionMutationKind, + ) -> Result { + Self::with_source_snapshot(scope, mutation, expectation, kind, None) + } + + pub(crate) fn with_source_snapshot( + scope: ProjectionRecordScope, + mutation: TableMutation, + expectation: ProjectionRecordExpectation, + kind: ProjectionMutationKind, + source_snapshot: Option, ) -> Result { if let ProjectionRecordExpectation::Exact(revision) = &expectation { if revision.scope() != &scope { @@ -253,10 +264,9 @@ impl ProjectionRecordMutation { "projection delete kind and table mutation disagree".into(), )); } - if matches!( - kind, - ProjectionMutationKind::Delete | ProjectionMutationKind::Recreate - ) && !matches!(expectation, ProjectionRecordExpectation::Exact(_)) + if (kind == ProjectionMutationKind::Recreate + || (kind == ProjectionMutationKind::Delete && source_snapshot.is_none())) + && !matches!(expectation, ProjectionRecordExpectation::Exact(_)) { return Err(ProjectionProtocolError::InvalidBatch( "projection delete/recreate requires an exact record revision".into(), @@ -267,6 +277,7 @@ impl ProjectionRecordMutation { mutation, expectation, kind, + source_snapshot, }) } } diff --git a/src/projection_protocol/store/query.rs b/src/projection_protocol/store/query.rs index eb611470a..035207498 100644 --- a/src/projection_protocol/store/query.rs +++ b/src/projection_protocol/store/query.rs @@ -6,6 +6,8 @@ pub struct ProjectionRecordMetadata { pub revision: RecordRevision, pub tombstone: bool, pub change: ProjectionChangeCursor, + /// Authoritative source fence for explicitly declared snapshot projections. + pub source_snapshot: Option, } /// One exact input-source checkpoint requested alongside a physical query row. diff --git a/src/projection_protocol/store/replay.rs b/src/projection_protocol/store/replay.rs index 9bcc2d102..df6a257e0 100644 --- a/src/projection_protocol/store/replay.rs +++ b/src/projection_protocol/store/replay.rs @@ -280,6 +280,7 @@ impl ReplayCursor { impl ReplayRecord { fn into_record(self) -> Result { Ok(ProjectionRecordMetadata { + source_snapshot: None, revision: self.revision.into_revision()?, tombstone: self.tombstone, change: self.change.into_cursor()?, diff --git a/src/projection_protocol/store/tests.rs b/src/projection_protocol/store/tests.rs index bb401dd79..0c7d6685c 100644 --- a/src/projection_protocol/store/tests.rs +++ b/src/projection_protocol/store/tests.rs @@ -42,6 +42,7 @@ fn same_transaction_evidence() -> SameTransactionProjectionEvidence { .unwrap(); SameTransactionProjectionEvidence { records: vec![ProjectionRecordMetadata { + source_snapshot: None, revision: revision.clone(), tombstone: false, change: change.clone(), diff --git a/src/projection_protocol/workspace.rs b/src/projection_protocol/workspace.rs index 8f67b0144..e6bdb9c21 100644 --- a/src/projection_protocol/workspace.rs +++ b/src/projection_protocol/workspace.rs @@ -317,11 +317,21 @@ impl ProjectionWorkspace { mutation: TableMutation, expectation: ProjectionRecordExpectation, kind: ProjectionMutationKind, + source: Option, ) -> Result<&mut Self, ProjectionProtocolError> { validate_execution_mutation_shape(&mutation, &expectation, kind)?; let (schema, key) = mutation_schema_key(&mutation); let scope = self.record_scope(schema, key)?; - self.stage(schema, scope, mutation, expectation, kind) + self.push_staged( + schema, + ProjectionRecordMutation::with_source_snapshot( + scope, + mutation, + expectation, + kind, + source, + )?, + ) } #[allow(dead_code)] @@ -434,6 +444,18 @@ impl ProjectionWorkspace { expectation: ProjectionRecordExpectation, kind: ProjectionMutationKind, ) -> Result<&mut Self, ProjectionProtocolError> { + self.push_staged( + schema, + ProjectionRecordMutation::new(scope, mutation, expectation, kind)?, + ) + } + + fn push_staged( + &mut self, + schema: &'static TableSchema, + mutation: ProjectionRecordMutation, + ) -> Result<&mut Self, ProjectionProtocolError> { + let scope = mutation.scope.clone(); if !self.staged_scopes.insert(scope.clone()) { return Err(ProjectionProtocolError::InvalidBatch(format!( "projection workspace repeats model `{}` record scope", @@ -441,12 +463,7 @@ impl ProjectionWorkspace { ))); } self.register_ownership(schema)?; - self.mutations.push(ProjectionRecordMutation::new( - scope.clone(), - mutation, - expectation, - kind, - )?); + self.mutations.push(mutation); self.observations.push(ProjectionObservationRequest { kind: ProjectionObservationKind::Record, target: ProjectionObservationTarget::StagedRecord(scope), @@ -486,7 +503,7 @@ fn validate_execution_mutation_shape( ) => row.mode == PatchMode::UpdateExisting && row.expected_version == ExpectedVersion::Any, ( TableMutation::DeleteRow(row), - ProjectionRecordExpectation::Exact(_), + ProjectionRecordExpectation::Exact(_) | ProjectionRecordExpectation::Missing, ProjectionMutationKind::Delete, ) => row.expected_version == ExpectedVersion::Any, ( diff --git a/src/sqlx_repo/projection_protocol/reads.rs b/src/sqlx_repo/projection_protocol/reads.rs index f71807e94..fd163ffbc 100644 --- a/src/sqlx_repo/projection_protocol/reads.rs +++ b/src/sqlx_repo/projection_protocol/reads.rs @@ -200,6 +200,10 @@ where } let current = record_in_tx(tx, &staged.scope, &state.change_epoch).await?; + crate::projection_protocol::validate_snapshot_write( + current.as_ref().map(|record| &record.metadata), + None, + )?; let physical_exists = physical_row_exists_in_tx(tx, &staged.mutation).await?; match current.as_ref().map(|record| &record.metadata) { None if physical_exists => { @@ -228,6 +232,7 @@ where &expectation, ProjectionMutationKind::Upsert, current.as_ref(), + false, )?; debug_assert!(!tombstone); let change = allocate_change( @@ -242,6 +247,7 @@ where None, )?; let metadata = ProjectionRecordMetadata { + source_snapshot: None, revision: revision.clone(), tombstone, change: change.cursor.clone(), @@ -358,6 +364,7 @@ where record.tombstone AS ps_record_tombstone, \ record.change_epoch AS ps_record_change_epoch, \ record.change_position AS ps_record_change_position, \ + record.source_snapshot AS ps_source_snapshot, \ checkpoint.source_bytes AS ps_cursor_source_bytes, \ checkpoint.source_hash AS ps_cursor_source_hash, \ checkpoint.source_partition_bytes AS ps_cursor_partition_bytes, \ @@ -671,6 +678,11 @@ where )?, )?, tombstone, + source_snapshot: decode_source_snapshot( + first.try_get("ps_source_snapshot").map_err(|error| { + protocol_storage_error::("decode source snapshot", error) + })?, + )?, change: ProjectionChangeCursor::new( request.scope.topology().clone(), request.scope.projection_partition().clone(), @@ -1845,7 +1857,7 @@ where "SELECT record.topology_hash AS live_topology_hash, record.partition_hash AS \ live_partition_hash, record.model_name AS live_model_name, \ record.canonical_key_bytes, record.canonical_key_hash, record.incarnation, \ - record.revision, record.tombstone, record.change_epoch, record.change_position, \ + record.revision, record.tombstone, record.change_epoch, record.change_position, record.source_snapshot, \ partition.topology_bytes AS live_topology_bytes, \ partition.partition_bytes AS live_partition_bytes, \ partition.change_epoch AS live_partition_epoch, \ @@ -1998,16 +2010,20 @@ where "projection live-record change exceeds its partition head", )); } - let metadata = ProjectionRecordMetadata { - revision: RecordRevision::new(scope.clone(), incarnation, revision)?, - tombstone: false, - change: ProjectionChangeCursor::new( - scope.topology().clone(), - scope.projection_partition().clone(), - change_epoch, - change_position, - )?, - }; + let metadata = + ProjectionRecordMetadata { + source_snapshot: decode_source_snapshot(row.try_get("source_snapshot").map_err( + |error| protocol_storage_error::("decode source snapshot", error), + )?)?, + revision: RecordRevision::new(scope.clone(), incarnation, revision)?, + tombstone: false, + change: ProjectionChangeCursor::new( + scope.topology().clone(), + scope.projection_partition().clone(), + change_epoch, + change_position, + )?, + }; if records[*index].replace(metadata).is_some() { return Err(corrupt_storage(format!( "projection live-record identity for model `{}` is ambiguous across partitions", diff --git a/src/sqlx_repo/projection_protocol/store_impl.rs b/src/sqlx_repo/projection_protocol/store_impl.rs index 5d5f28236..3a2b1e9da 100644 --- a/src/sqlx_repo/projection_protocol/store_impl.rs +++ b/src/sqlx_repo/projection_protocol/store_impl.rs @@ -410,6 +410,11 @@ where &mutation.expectation, mutation.kind, current.as_ref(), + mutation.source_snapshot.is_some(), + )?; + crate::projection_protocol::validate_snapshot_write( + current.as_ref().map(|record| &record.metadata), + mutation.source_snapshot.as_ref(), )?; let change = allocate_change( &mut state, @@ -426,6 +431,7 @@ where revision, tombstone, change: change.cursor.clone(), + source_snapshot: mutation.source_snapshot.clone(), }; records_by_scope.insert(mutation.scope.clone(), metadata.clone()); records.push(metadata); @@ -469,7 +475,7 @@ where actual_revision: metadata.revision.revision(), }); } - if metadata.tombstone { + if metadata.tombstone && metadata.source_snapshot.is_none() { return Err(ProjectionProtocolError::RecordTombstoned { model: expected.scope().model().to_string(), }); diff --git a/src/sqlx_repo/projection_protocol/writes.rs b/src/sqlx_repo/projection_protocol/writes.rs index 6c93f2809..1711222c4 100644 --- a/src/sqlx_repo/projection_protocol/writes.rs +++ b/src/sqlx_repo/projection_protocol/writes.rs @@ -196,7 +196,7 @@ where let key_hash = scope.key_digest(); let mut builder = QueryBuilder::::new( "SELECT canonical_key_bytes, canonical_key_hash, incarnation, revision, tombstone, \ - change_epoch, change_position FROM projection_records WHERE topology_hash = ", + change_epoch, change_position, source_snapshot FROM projection_records WHERE topology_hash = ", ); builder.push_bind(topology_hash.as_slice()); builder.push(" AND partition_hash = "); @@ -268,6 +268,11 @@ where )?; Ok(Some(StoredRecord { metadata: ProjectionRecordMetadata { + source_snapshot: decode_source_snapshot( + row.try_get("source_snapshot").map_err(|error| { + protocol_storage_error::("decode source snapshot", error) + })?, + )?, revision: RecordRevision::new(scope.clone(), incarnation, revision)?, tombstone, change: ProjectionChangeCursor::new( @@ -285,12 +290,16 @@ pub(super) fn next_record( expectation: &ProjectionRecordExpectation, kind: ProjectionMutationKind, current: Option<&StoredRecord>, + source_snapshot: bool, ) -> Result<(RecordRevision, bool), ProjectionProtocolError> { let current = current.map(|record| &record.metadata); match (expectation, current, kind) { (ProjectionRecordExpectation::Missing, None, ProjectionMutationKind::Upsert) => { Ok((RecordRevision::new(scope.clone(), 1, 1)?, false)) } + (ProjectionRecordExpectation::Missing, None, ProjectionMutationKind::Delete) => { + Ok((RecordRevision::new(scope.clone(), 1, 1)?, true)) + } (ProjectionRecordExpectation::Missing, Some(metadata), _) if metadata.tombstone => { Err(ProjectionProtocolError::RecordTombstoned { model: scope.model().to_string(), @@ -330,7 +339,7 @@ pub(super) fn next_record( )?, false, )), - ProjectionMutationKind::Delete if metadata.tombstone => { + ProjectionMutationKind::Delete if metadata.tombstone && !source_snapshot => { Err(ProjectionProtocolError::RecordTombstoned { model: scope.model().to_string(), }) @@ -358,11 +367,9 @@ pub(super) fn next_record( )), } } - (_, _, ProjectionMutationKind::Delete | ProjectionMutationKind::Recreate) => { - Err(ProjectionProtocolError::InvalidBatch( - "delete/recreate requires an exact record expectation".into(), - )) - } + (_, _, ProjectionMutationKind::Recreate) => Err(ProjectionProtocolError::InvalidBatch( + "delete/recreate requires an exact record expectation".into(), + )), } } @@ -508,7 +515,7 @@ where let mut builder = QueryBuilder::::new( "INSERT INTO projection_records \ (topology_hash, partition_hash, model_name, canonical_key_bytes, canonical_key_hash, \ - incarnation, revision, tombstone, change_epoch, change_position) VALUES (", + incarnation, revision, tombstone, change_epoch, change_position, source_snapshot) VALUES (", ); builder.push_bind(topology_hash.as_slice()); builder.push(", "); @@ -538,12 +545,24 @@ where metadata.change.position(), "projection record change position", )?); + builder.push(", "); + let source_json = metadata + .source_snapshot + .as_ref() + .map(serde_json::to_string) + .transpose() + .map_err(|error| corrupt_storage(format!("encode source snapshot: {error}")))?; + if let Some(value) = &source_json { + builder.push_bind(value.as_str()); + } else { + builder.push("NULL"); + } builder.push( ") ON CONFLICT (topology_hash, partition_hash, model_name, canonical_key_hash) \ DO UPDATE SET canonical_key_bytes = excluded.canonical_key_bytes, \ incarnation = excluded.incarnation, revision = excluded.revision, \ tombstone = excluded.tombstone, change_epoch = excluded.change_epoch, \ - change_position = excluded.change_position", + change_position = excluded.change_position, source_snapshot = excluded.source_snapshot", ); builder .build() @@ -553,6 +572,27 @@ where Ok(()) } +pub(super) fn decode_source_snapshot( + value: Option, +) -> Result, ProjectionProtocolError> { + value + .map(|value| { + if value.len() > 16384 { + return Err(corrupt_storage( + "source snapshot exceeds bounded metadata size", + )); + } + let snapshot: crate::projection_protocol::SourceSnapshotVersion = + serde_json::from_str(&value) + .map_err(|error| corrupt_storage(format!("decode source snapshot: {error}")))?; + snapshot + .validate_stored() + .map_err(|error| corrupt_storage(error.to_string()))?; + Ok(snapshot) + }) + .transpose() +} + pub(super) fn decode_observation_row( row: &DB::Row, causation_id: &str, diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 53535cf8d..f93a034e5 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -51,14 +51,15 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4]); + assert_eq!(versions, vec![1, 2, 3, 4, 5]); assert_eq!( descriptions, vec![ "initial", "command ledger", "projection protocol", - "command ledger atomic state" + "command ledger atomic state", + "projection source snapshots" ] ); assert_eq!( @@ -80,6 +81,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0004_command_ledger_atomic_state.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0005_projection_source_snapshots.sql" + )), ] ); } @@ -99,14 +104,15 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4]); + assert_eq!(versions, vec![1, 2, 3, 4, 5]); assert_eq!( descriptions, vec![ "initial", "command ledger", "projection protocol", - "command ledger atomic state" + "command ledger atomic state", + "projection source snapshots" ] ); assert_eq!( @@ -128,6 +134,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0004_command_ledger_atomic_state.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0005_projection_source_snapshots.sql" + )), ] ); } diff --git a/tests/fixtures/source_snapshot_delete.graphql b/tests/fixtures/source_snapshot_delete.graphql new file mode 100644 index 000000000..c91a2c30a --- /dev/null +++ b/tests/fixtures/source_snapshot_delete.graphql @@ -0,0 +1,3 @@ +mutation DeleteSnapshot { + delete_source_snapshot_rows_by_pk(id: $input.id) +} diff --git a/tests/fixtures/source_snapshot_save.graphql b/tests/fixtures/source_snapshot_save.graphql new file mode 100644 index 000000000..71cdd6c78 --- /dev/null +++ b/tests/fixtures/source_snapshot_save.graphql @@ -0,0 +1,3 @@ +mutation SaveSnapshot { + upsert_source_snapshot_rows(object: $input.row) +} From 5ef1bb6d1f6e55990a6e7aa50dc06f7470625a75 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 5 Sep 2026 00:35:41 -0500 Subject: [PATCH 002/484] feat: rebuild snapshot projections from canonical history --- README.md | 41 +++ src/bus/nats_bus.rs | 164 +++++++++ src/in_memory_repo/projection_protocol/mod.rs | 2 + .../projection_protocol/rebuild.rs | 111 ++++++ .../projection_protocol/store_impl.rs | 16 + src/projection/mod.rs | 2 + src/projection/rebuild.rs | 347 ++++++++++++++++++ src/projection/source_snapshot_tests.rs | 207 +++++++++++ src/projection_protocol/store/trait.rs | 25 ++ src/queued_repo/repository.rs | 17 + src/sqlx_repo/projection_protocol/mod.rs | 2 + src/sqlx_repo/projection_protocol/rebuild.rs | 181 +++++++++ .../projection_protocol/store_impl.rs | 16 + 13 files changed, 1131 insertions(+) create mode 100644 src/in_memory_repo/projection_protocol/rebuild.rs create mode 100644 src/projection/rebuild.rs create mode 100644 src/sqlx_repo/projection_protocol/rebuild.rs diff --git a/README.md b/README.md index b75315d00..74acfbbdd 100644 --- a/README.md +++ b/README.md @@ -325,6 +325,47 @@ the policy is part of the canonical program identity. Browser optimism continues to use the same mutation program, and authoritative confirmation uses committed row revisions rather than comparing browser timestamps. +#### Rebuilding existing snapshot projections + +Use explicit maintenance, not a startup fallback or republishing loop: + +```rust,ignore +use distributed::projection::rebuild::SnapshotProjectionRebuild; + +// Stop producers, drain outboxes, stop consumers, and back up the read model. +// Reuse the same generated SurfaceProjector mounted by the application. +let rebuild = SnapshotProjectionRebuild::begin(&repository, &projector).await?; +// Read history AFTER capturing the target inventory. Another authoritative +// archive can supply these canonical occurrences; rebuilding is bus-neutral. +let events = nats_bus.retained_domain_events().await?; +let plan = rebuild.from_complete_history(&events)?; +println!("{} records to rebuild", plan.record_count()); +plan.apply(&repository).await?; +``` + +Memory, SQLite and PostgreSQL commit complete rows/tombstones, source fences, +new record revisions and live-query changes atomically. A concurrent update, +insertion or deletion invalidates the captured inventory. Failure rolls back the +whole projection. Broker checkpoints, inbox receipts, command ledgers and prior +causal observations are preserved; maintenance does not claim a domain command +occurred. No domain handlers, external effects or queue sends run. + +The archive must cover every existing record and retain its stored source +occurrence, where present. Conflicting duplicate occurrences, missing aggregate +sequence prefixes and stale source heads fail closed. The caller must establish +history completeness: even a broker stream starting at sequence one may have +been created after its aggregates. The NATS reader verifies a stable, gap-free +retained stream without creating consumers or acknowledging messages, but cannot +prove that unpublished events or earlier deleted streams never existed. + +This first API is bounded offline maintenance for one active local, +unit-partition snapshot binding: at most 10,000 records and 100,000 occurrences / +64 MiB of canonical history. It intentionally rejects delta folds and histories +whose publication sequences have gaps. It does not migrate schemas/topologies, +perform online shadow swaps, or make several independent projections one +transaction. Keep services stopped if a multi-projection maintenance run fails; +capture fresh inventories and rerun before resuming them. + Handlers stay thin: most Todo commands are `portable_command!` — shard, invoke one domain method, commit Eventual. `todo.create` keeps a `handle:` escape hatch when the body needs extra checks. diff --git a/src/bus/nats_bus.rs b/src/bus/nats_bus.rs index 020ab9811..77e9e9f97 100644 --- a/src/bus/nats_bus.rs +++ b/src/bus/nats_bus.rs @@ -218,6 +218,98 @@ impl NatsBus { .map_err(|err| retryable("nats get_or_create_stream", err)) } + /// Read a bounded, stable archive of retained canonical domain events. + /// + /// Does not create streams/consumers, acknowledge deliveries, or publish. + /// Rejects truncated, gapped, changing, or oversized streams. Noncanonical + /// integration events and commands are excluded. A complete broker archive + /// is NOT proof that every historical aggregate publication reached it: + /// stop producers and drain outboxes before using this for maintenance. + pub async fn retained_domain_events( + &self, + ) -> Result, TransportError> { + let namespace = self.validated_namespace()?; + let mut stream = self + .jetstream + .get_stream(Self::stream_name(&namespace)) + .await + .map_err(|e| retryable("open domain-event archive", e))?; + let before = stream + .info() + .await + .map_err(|e| retryable("read archive boundary", e))? + .clone(); + let state = &before.state; + if state.last_sequence > 100_000 + || state.bytes > 64 * 1024 * 1024 + || state.messages != state.last_sequence + || (state.messages > 0 && state.first_sequence != 1) + { + return Err(TransportError::permanent( + "domain-event archive is truncated, gapped, or exceeds 100000 messages / 64 MiB", + )); + } + let prefix = format!("{namespace}.evt."); + let mut events = Vec::new(); + let mut bytes = 0usize; + for sequence in 1..=state.last_sequence { + let message = stream + .get_raw_message(sequence) + .await + .map_err(|e| retryable("read retained domain-event archive message", e))?; + bytes = bytes + .checked_add(message.payload.len()) + .ok_or_else(|| TransportError::permanent("domain-event archive size overflow"))?; + if bytes > 64 * 1024 * 1024 { + return Err(TransportError::permanent( + "domain-event archive exceeds 64 MiB", + )); + } + if message.sequence != sequence { + return Err(TransportError::permanent( + "domain-event archive returned a different sequence", + )); + } + let Some(name) = message.subject.as_str().strip_prefix(&prefix) else { + continue; + }; + if message + .headers + .get("x-sourced-payload-codec") + .map(|v| v.as_str()) + != Some("distributed.domain-event-occurrence+json") + { + continue; + } + let event = crate::DomainEventOccurrence::from_canonical_bytes(&message.payload) + .map_err(|e| { + TransportError::permanent(format!("invalid archived occurrence: {e}")) + })?; + if event.descriptor().name != name + || message.headers.get("Nats-Msg-Id").map(|v| v.as_str()) != Some(event.id()) + { + return Err(TransportError::permanent( + "archived occurrence differs from its transport identity", + )); + } + events.push(event); + } + let after = stream + .info() + .await + .map_err(|e| retryable("verify archive boundary", e))?; + if before.created != after.created + || before.state.last_sequence != after.state.last_sequence + || before.state.messages != after.state.messages + || before.state.first_sequence != after.state.first_sequence + { + return Err(TransportError::permanent( + "domain-event archive changed while reading; quiesce producers and retry", + )); + } + Ok(events) + } + /// Build a durable pull source over the bus stream, filtered to `subjects`, /// stripping `strip_prefix` so the dispatched message name is the bare name. async fn source( @@ -278,6 +370,78 @@ impl NatsBus { } } +#[cfg(test)] +mod archive_tests { + use super::*; + + #[derive(serde::Serialize, serde::Deserialize, crate::DomainState)] + #[domain_state(version = 1)] + struct ArchiveState { + title: String, + } + + #[tokio::test] + async fn retained_archive_is_non_consuming_and_rejects_missing_history() { + let Ok(url) = std::env::var("DISTRIBUTED_ARCHIVE_TEST_NATS_URL") else { + return; + }; + let namespace = format!("archive-test-{}", uuid::Uuid::now_v7().simple()); + let bus = NatsBus::connect(&url).namespace(&namespace).await.unwrap(); + let mut stream = bus.ensure_stream().await.unwrap(); + for sequence in 1..=3 { + let event = crate::DomainEventOccurrence::capture( + crate::DomainEventDescriptor::state::("archive.changed", 1), + crate::DomainEventEnvelope { + aggregate_type: "archive-item".into(), + aggregate_id: "a".into(), + aggregate_sequence: sequence, + publication_ordinal: 0, + occurred_at: std::time::UNIX_EPOCH, + metadata: Default::default(), + }, + &ArchiveState { + title: sequence.to_string(), + }, + ) + .unwrap(); + let mut headers = async_nats::HeaderMap::new(); + headers.insert( + "x-sourced-payload-codec", + "distributed.domain-event-occurrence+json", + ); + headers.insert("Nats-Msg-Id", event.id()); + bus.jetstream + .publish_with_headers( + format!("{namespace}.evt.archive.changed"), + headers, + event.canonical_bytes().unwrap().into(), + ) + .await + .unwrap() + .await + .unwrap(); + } + let first = bus.retained_domain_events().await.unwrap(); + assert_eq!(first.len(), 3); + assert_eq!(bus.retained_domain_events().await.unwrap(), first); + let info = stream.info().await.unwrap(); + assert_eq!(info.state.consumer_count, 0); + assert_eq!(info.state.messages, 3); + // Delete only a message in this test's fresh UUID-scoped stream. + stream.delete_message(2).await.unwrap(); + assert!(bus + .retained_domain_events() + .await + .unwrap_err() + .to_string() + .contains("gapped")); + bus.jetstream + .delete_stream(NatsBus::stream_name(&namespace)) + .await + .unwrap(); + } +} + impl Bus for NatsBus { async fn send_message(&self, message: Message) -> Result<(), TransportError> { self.validated_namespace()?; diff --git a/src/in_memory_repo/projection_protocol/mod.rs b/src/in_memory_repo/projection_protocol/mod.rs index d4eb1c95b..67bb5572e 100644 --- a/src/in_memory_repo/projection_protocol/mod.rs +++ b/src/in_memory_repo/projection_protocol/mod.rs @@ -46,6 +46,8 @@ mod state; mod state_impl; mod store_impl; mod util; +#[cfg(feature = "graphql")] +mod rebuild; pub(super) use direct_projection::stage_same_transaction_projection; pub(super) use state::{reject_causal_owned_plans, InMemoryProjectionProtocolState}; diff --git a/src/in_memory_repo/projection_protocol/rebuild.rs b/src/in_memory_repo/projection_protocol/rebuild.rs new file mode 100644 index 000000000..cde839eab --- /dev/null +++ b/src/in_memory_repo/projection_protocol/rebuild.rs @@ -0,0 +1,111 @@ +use super::*; +use crate::projection::rebuild::{ + invalid, RebuildContext, SnapshotProjectionRebuildPlan, MAX_REBUILD_RECORDS, +}; + +fn inventory( + protocol: &InMemoryProjectionProtocolState, + context: &RebuildContext, +) -> Result, ProjectionProtocolError> { + protocol.require_registered_topology(context.compiled.topology())?; + let partition = context.partition()?; + let mut records = Vec::new(); + for (scope, record) in &protocol.records { + if scope.topology() == context.compiled.topology() { + if scope.projection_partition() != &partition || record.change.epoch() != &context.epoch + { + return Err(invalid( + "snapshot rebuild requires the registered unit partition and epoch", + )); + } + records.push(record.clone()); + if records.len() > MAX_REBUILD_RECORDS { + return Err(invalid("snapshot rebuild exceeds 10000 records")); + } + } + } + Ok(records) +} + +impl InMemoryRepository { + pub(super) async fn snapshot_rebuild_records( + &self, + context: &RebuildContext, + ) -> Result, ProjectionProtocolError> { + let protocol = self + .projection_protocol + .read() + .map_err(|_| invalid("projection rebuild inventory lock poisoned"))?; + inventory(&protocol, context) + } + + pub(super) async fn apply_snapshot_rebuild( + &self, + plan: SnapshotProjectionRebuildPlan, + ) -> Result { + // Same lock order as ordinary commits. Stage both stores before publication. + let mut rows = self + .model_store + .relational_rows + .write() + .map_err(|_| invalid("projection rebuild rows lock poisoned"))?; + let mut protocol = self + .projection_protocol + .write() + .map_err(|_| invalid("projection rebuild protocol lock poisoned"))?; + plan.verify_inventory(&inventory(&protocol, &plan.context)?)?; + let mut staged = protocol.clone(); + let mut staged_rows = rows.clone(); + let partition = + PartitionKey::new(plan.context.compiled.topology(), &plan.context.partition()?); + staged.ensure_partition(&partition, &plan.context.epoch)?; + for owner in plan.context.compiled.ownership() { + let registered = RegisteredModelKey { + topology: partition.topology.clone(), + model: owner.model.clone(), + }; + if staged.registered_models.get(®istered) != Some(&owner.table) + || staged.authoritative_table_owners.get(&owner.table) != Some(®istered) + { + return Err(invalid("snapshot rebuild does not own the target table")); + } + staged.ownership.insert( + OwnershipKey { + partition: partition.clone(), + model: owner.model.clone(), + }, + owner.table.clone(), + ); + } + for row in &plan.rows { + let current = staged.records.get(&row.scope); + row.verify_physical(current, staged_rows.contains_key(&row.mutation.lock_key()))?; + let (kind, expectation) = row.transition(current); + let (revision, tombstone) = staged.next_record(&row.scope, &expectation, kind, true)?; + let change = staged.append_change( + &partition, + PendingChange { + kind: change_kind_for_mutation(kind), + causation_id: "distributed:snapshot-rebuild".into(), + observation_kind: None, + scope: Some(row.scope.clone()), + revision: Some(revision.clone()), + failure_id: None, + }, + )?; + let record = ProjectionRecordMetadata { + revision, + tombstone, + change: change.cursor, + source_snapshot: Some(row.source.clone()), + }; + staged.ensure_live_record_identity_available(&record)?; + staged.records.insert(row.scope.clone(), record); + } + apply_read_model_write_plan(plan.write_plan(), &mut staged_rows)?; + staged.retain_change_suffix(&partition, self.projection_change_retention)?; + *rows = staged_rows; + *protocol = staged; + Ok(plan.rows.len()) + } +} diff --git a/src/in_memory_repo/projection_protocol/store_impl.rs b/src/in_memory_repo/projection_protocol/store_impl.rs index dca270437..655ef9bff 100644 --- a/src/in_memory_repo/projection_protocol/store_impl.rs +++ b/src/in_memory_repo/projection_protocol/store_impl.rs @@ -1,6 +1,22 @@ use super::*; impl ProjectionProtocolStore for InMemoryRepository { + #[cfg(feature = "graphql")] + async fn projection_rebuild_records( + &self, + context: &crate::projection::rebuild::RebuildContext, + ) -> Result, ProjectionProtocolError> { + self.snapshot_rebuild_records(context).await + } + + #[cfg(feature = "graphql")] + async fn commit_projection_rebuild( + &self, + plan: crate::projection::rebuild::SnapshotProjectionRebuildPlan, + ) -> Result { + self.apply_snapshot_rebuild(plan).await + } + fn register_projection_models<'a>( &'a self, topology: &'a ProjectorTopologyId, diff --git a/src/projection/mod.rs b/src/projection/mod.rs index d3be10603..9c287ad3c 100644 --- a/src/projection/mod.rs +++ b/src/projection/mod.rs @@ -19,6 +19,8 @@ mod provenance; // contract before their owning tasks define one. pub mod catalog; pub mod executor; +#[cfg(feature = "graphql")] +pub mod rebuild; pub mod local_mounts; pub mod lower; pub mod placement; diff --git a/src/projection/rebuild.rs b/src/projection/rebuild.rs new file mode 100644 index 000000000..26506ffc1 --- /dev/null +++ b/src/projection/rebuild.rs @@ -0,0 +1,347 @@ +//! Explicit, bounded maintenance for full-state snapshot projections. +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use crate::graphql::SurfaceProjector; +use crate::projection::lower::ProjectionServerExecutorDescriptor; +use crate::projection_protocol::*; +use crate::table::{TableMutation, TableWritePlan}; +use crate::DomainEventOccurrence; + +pub(crate) const MAX_REBUILD_RECORDS: usize = 10_000; +const MAX_HISTORY_EVENTS: usize = 100_000; +const MAX_HISTORY_BYTES: usize = 64 * 1024 * 1024; + +pub(crate) fn invalid(detail: impl ToString) -> ProjectionProtocolError { + ProjectionProtocolError::InvalidBatch(detail.to_string()) +} + +/// Captured maintenance boundary for one registered snapshot projector. +/// +/// Stop producers and drain their outboxes before beginning. Read the complete, +/// retained canonical history *after* beginning, then call +/// `from_complete_history`. A broker retention boundary is not proof of +/// aggregate-history completeness. This API never runs event handlers, changes +/// broker checkpoints, or republishes messages. +/// +/// Concurrent row changes (including new records) invalidate the captured +/// boundary. Applying a plan is one adapter transaction; failures leave the +/// projection untouched. This bounded API is not an online shadow rebuild or +/// a schema/topology migration. +pub struct SnapshotProjectionRebuild { + pub(crate) context: RebuildContext, + executor: ProjectionServerExecutorDescriptor, + pub(crate) expected: Vec, +} + +#[derive(Clone, Debug)] +pub(crate) struct RebuildContext { + pub(crate) compiled: CompiledProjectionTopology, + pub(crate) epoch: ProjectionEpoch, +} + +impl RebuildContext { + pub(crate) fn partition(&self) -> Result { + self.compiled + .codec() + .encode_partition(None) + .map_err(invalid) + } +} + +/// Opaque, validated replacement plan. It contains no transport input authority. +pub struct SnapshotProjectionRebuildPlan { + pub(crate) context: RebuildContext, + pub(crate) expected: Vec, + pub(crate) rows: Vec, +} + +#[derive(Clone, Debug)] +pub(crate) struct RebuildRow { + pub(crate) scope: ProjectionRecordScope, + pub(crate) mutation: TableMutation, + pub(crate) source: SourceSnapshotVersion, +} + +impl RebuildRow { + pub(crate) fn transition( + &self, + current: Option<&ProjectionRecordMetadata>, + ) -> (ProjectionMutationKind, ProjectionRecordExpectation) { + let kind = match (&self.mutation, current) { + (TableMutation::DeleteRow(_), _) => ProjectionMutationKind::Delete, + (_, Some(record)) if record.tombstone => ProjectionMutationKind::Recreate, + _ => ProjectionMutationKind::Upsert, + }; + let expectation = current + .map(|r| ProjectionRecordExpectation::Exact(r.revision.clone())) + .unwrap_or(ProjectionRecordExpectation::Missing); + (kind, expectation) + } + + pub(crate) fn verify_physical( + &self, + current: Option<&ProjectionRecordMetadata>, + exists: bool, + ) -> Result<(), ProjectionProtocolError> { + if exists != current.is_some_and(|r| !r.tombstone) { + return Err(invalid( + "snapshot rebuild found inconsistent row/protocol metadata", + )); + } + Ok(()) + } +} + +#[allow(private_bounds)] +impl SnapshotProjectionRebuild { + /// Capture the current record inventory before reading the source archive. + pub async fn begin( + store: &impl ProjectionProtocolStore, + projector: &SurfaceProjector, + ) -> Result { + let [projection] = projector.modeled.as_slice() else { + return Err(invalid( + "snapshot rebuild requires exactly one modeled binding", + )); + }; + if !projection.is_causally_eligible() + || !matches!( + projection.route(), + crate::projection::placement::ProjectionExecutorRoute::Local { .. } + ) + { + return Err(invalid( + "snapshot rebuild requires an active local eventual binding", + )); + } + let (program, binding) = projection + .raw() + .ok_or_else(|| invalid("snapshot rebuild requires a generated binding"))?; + if !program.source_snapshots() { + return Err(invalid( + "snapshot rebuild requires source: aggregate_snapshot", + )); + } + let physical = binding + .physical_topology() + .ok_or_else(|| invalid("snapshot rebuild requires a physical topology"))?; + let topology = + ProjectorTopologyId::new(physical.version(), physical.name(), physical.digest())?; + let compiled = CompiledProjectionTopology::from_modeled_binding( + topology, + binding + .outputs() + .iter() + .map(|o| (o.model(), o.storage(), o.schema())), + )?; + let executor = projection + .server_executor() + .cloned() + .ok_or_else(|| invalid("snapshot rebuild requires a generated executor"))?; + let context = RebuildContext { + compiled, + epoch: ProjectionEpoch::new(projection.epoch().as_str())?, + }; + let expected = store.projection_rebuild_records(&context).await?; + Ok(Self { + context, + executor, + expected, + }) + } + + /// Resolve retained canonical history through the original typed projection. + /// + /// The caller must supply the entire publication history through the + /// quiescent source head, not a filtered consumer window. This method checks + /// covered record identities, sequence prefixes and conflicting duplicates; + /// it cannot discover unpublished or externally deleted source history. + pub fn from_complete_history( + self, + history: &[DomainEventOccurrence], + ) -> Result { + if history.len() > MAX_HISTORY_EVENTS { + return Err(invalid( + "snapshot rebuild history exceeds 100000 occurrences", + )); + } + let mut bytes = 0usize; + let mut identities = BTreeMap::new(); + let mut sequences: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + let mut rows: HashMap = HashMap::new(); + let mut relevant = BTreeSet::new(); + let mut versions: HashMap> = + HashMap::new(); + for event in history { + let canonical = event.canonical_bytes().map_err(invalid)?; + bytes = bytes + .checked_add(canonical.len()) + .ok_or_else(|| invalid("history size overflow"))?; + if bytes > MAX_HISTORY_BYTES { + return Err(invalid("snapshot rebuild history exceeds 64 MiB")); + } + let stream = ( + event.aggregate_type().to_owned(), + event.aggregate_id().to_owned(), + ); + sequences + .entry(stream.clone()) + .or_default() + .insert(event.aggregate_sequence()); + let identity = ( + stream.clone(), + event.aggregate_sequence(), + event.publication_ordinal(), + ); + if let Some(previous) = identities.insert(identity, canonical.clone()) { + if previous != canonical { + return Err(invalid( + "snapshot rebuild history contains conflicting occurrences", + )); + } + continue; + } + if !self.executor.matches(event) { + continue; + } + relevant.insert(stream); + let lowered = self.executor.plan(event).map_err(invalid)?; + if !lowered.resolved.source_snapshots() { + return Err(invalid("snapshot rebuild resolved a non-snapshot program")); + } + lowered.write_plan.validate()?; + let source = SourceSnapshotVersion::from_occurrence(event)?; + for mut mutation in lowered.write_plan.mutations { + // Protocol inventory CAS, not a domain version column, fences maintenance. + match &mut mutation { + TableMutation::UpsertRow(row) => { + row.expected_version = crate::table::ExpectedVersion::Any; + row.mode = crate::table::RowWriteMode::Upsert; + } + TableMutation::DeleteRow(row) => { + row.expected_version = crate::table::ExpectedVersion::Any + } + _ => {} + } + let (schema, key) = match &mutation { + TableMutation::UpsertRow(row) => (row.schema, &row.key), + TableMutation::DeleteRow(row) => (row.schema, &row.key), + TableMutation::PatchRow(_) => { + return Err(invalid("snapshot rebuild cannot apply patches")) + } + }; + let scope = self + .context + .compiled + .codec() + .encode_row_scope_in_partition( + &schema.model_name, + self.context.partition()?, + key, + ) + .map_err(invalid)?; + versions + .entry(scope.clone()) + .or_default() + .push(source.clone()); + if let Some(previous) = rows.get(&scope) { + if !source.advances(&previous.source)? { + continue; + } + } + rows.insert( + scope.clone(), + RebuildRow { + scope, + mutation, + source: source.clone(), + }, + ); + if rows.len() > MAX_REBUILD_RECORDS { + return Err(invalid("snapshot rebuild exceeds 10000 records")); + } + } + } + for stream in relevant { + let sequence = &sequences[&stream]; + if sequence + .iter() + .copied() + .ne(1..=sequence.last().copied().unwrap_or(0)) + { + return Err(invalid( + "snapshot rebuild requires a complete aggregate sequence prefix", + )); + } + } + for current in &self.expected { + let scope = current.revision.scope(); + let row = rows.get(scope).ok_or_else(|| { + invalid(format!( + "snapshot rebuild history does not cover an existing {} record", + scope.model(), + )) + })?; + if let Some(source) = ¤t.source_snapshot { + if !versions[scope].contains(source) { + return Err(invalid( + "snapshot rebuild history omits the stored source occurrence", + )); + } + // Also validates same-stream ownership and equal-version conflicts. + if source.advances(&row.source)? { + return Err(invalid( + "snapshot rebuild history ends before the stored source version", + )); + } + } + } + let mut rows: Vec<_> = rows.into_values().collect(); + rows.sort_by(|a, b| { + (a.scope.model(), a.scope.canonical_key_bytes()) + .cmp(&(b.scope.model(), b.scope.canonical_key_bytes())) + }); + Ok(SnapshotProjectionRebuildPlan { + context: self.context, + expected: self.expected, + rows, + }) + } +} + +#[allow(private_bounds)] +impl SnapshotProjectionRebuildPlan { + /// Number of complete rows/tombstones represented by this plan. + pub fn record_count(&self) -> usize { + self.rows.len() + } + + /// Atomically apply if the captured inventory has not changed. + pub async fn apply( + self, + store: &impl ProjectionProtocolStore, + ) -> Result { + store.commit_projection_rebuild(self).await + } + + pub(crate) fn verify_inventory( + &self, + current: &[ProjectionRecordMetadata], + ) -> Result<(), ProjectionProtocolError> { + let map = |rows: &[ProjectionRecordMetadata]| { + rows.iter() + .map(|r| (r.revision.scope().clone(), r.clone())) + .collect::>() + }; + if map(current) != map(&self.expected) { + return Err(invalid( + "projection changed during rebuild; begin again with fresh history", + )); + } + Ok(()) + } + + pub(crate) fn write_plan(&self) -> TableWritePlan { + TableWritePlan::new(self.rows.iter().map(|row| row.mutation.clone()).collect()) + } +} diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs index 75518b91f..44de952c4 100644 --- a/src/projection/source_snapshot_tests.rs +++ b/src/projection/source_snapshot_tests.rs @@ -501,3 +501,210 @@ fn source_snapshots_reject_direct_materialization() { Err(ProjectionTopologyError::DirectIneligible { .. }) )); } + +fn rebuild_projector() -> crate::graphql::SurfaceProjector { + let mounts = crate::LocalProjectionMountsBuilder::new("snapshot-test", "events") + .unwrap() + .eventual_model::("rebuild-test", SNAPSHOTS, "snapshot-v1") + .unwrap() + .build() + .unwrap(); + mounts.projector("rebuild-test").unwrap() +} + +async fn rebuild_matrix(store: &impl ProjectionProtocolStore) { + use crate::projection::rebuild::SnapshotProjectionRebuild; + let projector = rebuild_projector(); + let (_, binding) = projector.modeled[0].raw().unwrap(); + let physical = binding.physical_topology().unwrap(); + let compiled = CompiledProjectionTopology::from_modeled_binding( + ProjectorTopologyId::new(physical.version(), physical.name(), physical.digest()).unwrap(), + binding + .outputs() + .iter() + .map(|o| (o.model(), o.storage(), o.schema())), + ) + .unwrap(); + store + .register_projection_models(compiled.topology(), compiled.ownership()) + .await + .unwrap(); + let h = Harness { + codec: compiled.codec(), + }; + let first = event("a", 1, "old", false); + let second = event("a", 2, "new", false); + let removed = event("a", 3, "deleted", true); + let mut old = h.prepare(store, &first, 1).await.unwrap(); + old.mutations[0].source_snapshot = None; + let applied = store.commit_projection(old).await.unwrap(); + let checkpoint = applied.checkpoint.unwrap(); + let original = h.read(store, "a").await; + + // Neither a missing record nor a suffix masquerading as full history passes. + for history in [ + vec![], + vec![second.clone()], + vec![first.clone(), removed.clone()], + ] { + assert!(SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap() + .from_complete_history(&history) + .is_err()); + } + let mut conflicting = second.clone(); + conflicting.overwrite_causation_id("another-cause"); + assert!(SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap() + .from_complete_history(&[first.clone(), second.clone(), conflicting]) + .is_err()); + assert_eq!(h.read(store, "a").await.record, original.record); + + let rebuild = SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap(); + // Reverse delivery and exact duplicate occurrences are deterministic. + let plan = rebuild + .from_complete_history(&[second.clone(), first.clone(), second.clone()]) + .unwrap(); + assert_eq!(plan.record_count(), 1); + assert_eq!(plan.apply(store).await.unwrap(), 1); + let row = h.read(store, "a").await; + assert_eq!( + row.row.unwrap().get("title"), + Some(&RowValue::String("new".into())) + ); + assert!(row.record.unwrap().source_snapshot.is_some()); + assert_eq!( + store + .projection_checkpoint(checkpoint.input(), ProjectionGeneration::initial()) + .await + .unwrap(), + Some(checkpoint.clone()) + ); + // Inbox/checkpoint identity remains intact; no domain event was republished. + assert_eq!( + h.apply(store, &first, 1).await.unwrap().outcome, + ProjectionCommitOutcome::Duplicate + ); + h.apply(store, &first, 2).await.unwrap_err(); // same message, different position is still rejected + h.apply(store, &removed, 3).await.unwrap(); + + // Exact inventory CAS rejects modifications made after begin, including inserts. + let pending = SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap() + .from_complete_history(&[first.clone(), second.clone(), removed.clone()]) + .unwrap(); + let other = event("b", 1, "other", false); + h.apply(store, &other, 4).await.unwrap(); + assert!(pending.apply(store).await.is_err()); + assert!(h.read(store, "a").await.row.is_none()); + // Missing the stored tombstone occurrence cannot resurrect it. + assert!(SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap() + .from_complete_history(&[first.clone(), second.clone(), other.clone()]) + .is_err()); + let recreated = event("a", 4, "recreated", false); + let history = [first, second, removed, other, recreated.clone()]; + SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap() + .from_complete_history(&history) + .unwrap() + .apply(store) + .await + .unwrap(); + let restored = h.read(store, "a").await; + assert_eq!(restored.record.unwrap().revision.incarnation(), 2); + assert_eq!( + restored.row.unwrap().get("title"), + Some(&RowValue::String("recreated".into())) + ); +} + +async fn rebuild_rollback(store: &impl ProjectionProtocolStore) { + use crate::projection::rebuild::SnapshotProjectionRebuild; + let projector = rebuild_projector(); + let before = SnapshotProjectionRebuild::begin(store, &projector) + .await + .unwrap(); + let h = Harness { + codec: before.context.compiled.codec(), + }; + let original_a = h.read(store, "a").await; + let original_b = h.read(store, "b").await; + let history = [ + event("a", 1, "old", false), + event("a", 2, "new", false), + event("a", 3, "deleted", true), + event("a", 4, "recreated", false), + event("a", 5, "valid first write", false), + event("b", 1, "other", false), + event("b", 2, "reject me", false), + ]; + let error = before + .from_complete_history(&history) + .unwrap() + .apply(store) + .await + .unwrap_err(); + assert!(error.to_string().contains("rebuild_test_reject"), "{error}"); + let after_a = h.read(store, "a").await; + let after_b = h.read(store, "b").await; + assert_eq!(after_a.row, original_a.row); + assert_eq!(after_b.row, original_b.row); + assert_eq!(after_a.record, original_a.record); + assert_eq!(after_b.record, original_b.record); +} + +#[tokio::test] +async fn snapshot_rebuild_memory() { + rebuild_matrix(&crate::InMemoryRepository::new()).await; +} + +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn snapshot_rebuild_sqlite() { + let store = crate::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let mut registry = crate::table::TableSchemaRegistry::new(); + registry + .register_schema(SnapshotRow::schema().clone()) + .unwrap(); + store + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + rebuild_matrix(&store).await; + sqlx::query("CREATE TRIGGER rebuild_test_reject BEFORE UPDATE ON source_snapshot_rows WHEN NEW.title = 'reject me' BEGIN SELECT RAISE(ABORT, 'rebuild_test_reject'); END") + .execute(store.pool()).await.unwrap(); + rebuild_rollback(&store).await; +} + +#[cfg(feature = "postgres")] +#[tokio::test] +async fn snapshot_rebuild_postgres() { + let Ok(url) = std::env::var("DISTRIBUTED_REBUILD_TEST_POSTGRES_URL") else { + return; + }; + let store = crate::PostgresRepository::connect_and_migrate(&url) + .await + .unwrap(); + let mut registry = crate::table::TableSchemaRegistry::new(); + registry + .register_schema(SnapshotRow::schema().clone()) + .unwrap(); + store + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + rebuild_matrix(&store).await; + sqlx::query("ALTER TABLE source_snapshot_rows ADD CONSTRAINT rebuild_test_reject CHECK (title <> 'reject me')") + .execute(store.pool()).await.unwrap(); + rebuild_rollback(&store).await; +} diff --git a/src/projection_protocol/store/trait.rs b/src/projection_protocol/store/trait.rs index b8fda9b4c..378b6699c 100644 --- a/src/projection_protocol/store/trait.rs +++ b/src/projection_protocol/store/trait.rs @@ -15,6 +15,31 @@ pub enum ProjectionChangeRead { /// Adapter contract for atomic causal projection persistence. pub(crate) trait ProjectionProtocolStore: Send + Sync { + #[cfg(feature = "graphql")] + fn projection_rebuild_records<'a>( + &'a self, + _context: &'a crate::projection::rebuild::RebuildContext, + ) -> impl Future, ProjectionProtocolError>> + Send + 'a + { + async { + Err(ProjectionProtocolError::InvalidBatch( + "this store does not support snapshot projection rebuilds".into(), + )) + } + } + + #[cfg(feature = "graphql")] + fn commit_projection_rebuild( + &self, + _plan: crate::projection::rebuild::SnapshotProjectionRebuildPlan, + ) -> impl Future> + Send + '_ { + async { + Err(ProjectionProtocolError::InvalidBatch( + "this store does not support snapshot projection rebuilds".into(), + )) + } + } + /// Install model-wide causal ownership before projector traffic begins. /// This bootstrap marker closes the absent-row race with legacy/raw write /// plans; per-partition ownership is still verified inside each commit. diff --git a/src/queued_repo/repository.rs b/src/queued_repo/repository.rs index 0bb295279..3c19d3e67 100644 --- a/src/queued_repo/repository.rs +++ b/src/queued_repo/repository.rs @@ -301,6 +301,23 @@ where R: ProjectionProtocolStore, L: LockManager, { + #[cfg(feature = "graphql")] + async fn projection_rebuild_records( + &self, + context: &crate::projection::rebuild::RebuildContext, + ) -> Result, ProjectionProtocolError> + { + self.inner.projection_rebuild_records(context).await + } + + #[cfg(feature = "graphql")] + async fn commit_projection_rebuild( + &self, + plan: crate::projection::rebuild::SnapshotProjectionRebuildPlan, + ) -> Result { + self.inner.commit_projection_rebuild(plan).await + } + fn register_projection_models<'a>( &'a self, topology: &'a ProjectorTopologyId, diff --git a/src/sqlx_repo/projection_protocol/mod.rs b/src/sqlx_repo/projection_protocol/mod.rs index 4fec8f891..d9daea29f 100644 --- a/src/sqlx_repo/projection_protocol/mod.rs +++ b/src/sqlx_repo/projection_protocol/mod.rs @@ -60,6 +60,8 @@ mod reads; mod store_impl; mod types; mod writes; +#[cfg(feature = "graphql")] +mod rebuild; use helpers::*; use identity::*; diff --git a/src/sqlx_repo/projection_protocol/rebuild.rs b/src/sqlx_repo/projection_protocol/rebuild.rs new file mode 100644 index 000000000..1f48a7ade --- /dev/null +++ b/src/sqlx_repo/projection_protocol/rebuild.rs @@ -0,0 +1,181 @@ +use super::*; +use crate::projection::rebuild::{ + invalid, RebuildContext, SnapshotProjectionRebuildPlan, MAX_REBUILD_RECORDS, +}; + +impl SqlxRepository +where + DB: SqlxRepoBackend, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + for<'c> &'c Pool: Executor<'c, Database = DB>, + DB::Arguments: IntoArguments, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, + for<'q> &'q str: Encode<'q, DB> + Type, + for<'q> &'q [u8]: Encode<'q, DB> + Type, + for<'r> &'r str: sqlx::ColumnIndex, +{ + // Caller holds the normal writer partition lock throughout inventory/commit. + async fn rebuild_inventory( + tx: &mut Transaction<'_, DB>, + context: &RebuildContext, + ) -> Result, ProjectionProtocolError> { + let topology = context.compiled.topology(); + let hash = topology.digest(); + let partition = context.partition()?; + let mut query = QueryBuilder::::new( + "SELECT model_name, canonical_key_bytes, partition_hash FROM projection_records WHERE topology_hash = " + ); + query.push_bind(hash.as_slice()); + query.push(" LIMIT "); + query.push_bind((MAX_REBUILD_RECORDS + 1) as i64); + let keys = query + .build() + .fetch_all(&mut **tx) + .await + .map_err(|e| protocol_storage_error::("read rebuild inventory", e))?; + if keys.len() > MAX_REBUILD_RECORDS { + return Err(invalid("snapshot rebuild exceeds 10000 records")); + } + let mut records = Vec::with_capacity(keys.len()); + for key in keys { + let model: String = key + .try_get("model_name") + .map_err(|e| protocol_storage_error::("decode rebuild model", e))?; + let bytes: Vec = key + .try_get("canonical_key_bytes") + .map_err(|e| protocol_storage_error::("decode rebuild key", e))?; + let stored_partition: Vec = key + .try_get("partition_hash") + .map_err(|e| protocol_storage_error::("decode rebuild partition", e))?; + verify_digest( + &stored_partition, + partition.digest(), + "snapshot rebuild partition", + )?; + let scope = + ProjectionRecordScope::new(topology.clone(), partition.clone(), model, bytes)?; + records.push( + record_in_tx(tx, &scope, &context.epoch) + .await? + .ok_or_else(|| invalid("snapshot rebuild record disappeared"))? + .metadata, + ); + } + Ok(records) + } + + pub(super) async fn snapshot_rebuild_records( + &self, + context: &RebuildContext, + ) -> Result, ProjectionProtocolError> { + let mut tx = self + .pool() + .begin() + .await + .map_err(|e| protocol_storage_error::("begin rebuild inventory", e))?; + verify_registered_topology_in_tx(&mut tx, context.compiled.topology()).await?; + lock_partition_in_tx( + &mut tx, + context.compiled.topology(), + &context.partition()?, + &context.epoch, + ) + .await?; + let records = Self::rebuild_inventory(&mut tx, context).await?; + // No bootstrap, metadata changes, or maintenance locks survive capture. + tx.rollback() + .await + .map_err(|e| protocol_storage_error::("close rebuild inventory", e))?; + Ok(records) + } + + pub(super) async fn apply_snapshot_rebuild( + &self, + plan: SnapshotProjectionRebuildPlan, + ) -> Result { + let context = &plan.context; + let topology = context.compiled.topology(); + let partition = context.partition()?; + let write_plan = plan.write_plan(); + validate_sql_write_plan(&write_plan)?; + let mut tx = self + .pool() + .begin() + .await + .map_err(|e| protocol_storage_error::("begin snapshot rebuild", e))?; + verify_registered_topology_in_tx(&mut tx, topology).await?; + let mut state = lock_partition_in_tx(&mut tx, topology, &partition, &context.epoch).await?; + plan.verify_inventory(&Self::rebuild_inventory(&mut tx, context).await?)?; + ensure_partition_ownership_in_tx( + &mut tx, + topology, + &partition, + context.compiled.ownership(), + ) + .await?; + for row in &plan.rows { + let current = record_in_tx(&mut tx, &row.scope, &context.epoch).await?; + let metadata = current.as_ref().map(|r| &r.metadata); + row.verify_physical( + metadata, + physical_row_exists_in_tx(&mut tx, &row.mutation).await?, + )?; + let (kind, expectation) = row.transition(metadata); + let (revision, tombstone) = + next_record(&row.scope, &expectation, kind, current.as_ref(), true)?; + let change = allocate_change( + &mut state, + topology, + &partition, + change_kind_for_mutation(kind), + "distributed:snapshot-rebuild".into(), + None, + Some(row.scope.clone()), + Some(revision.clone()), + None, + )?; + let record = ProjectionRecordMetadata { + revision, + tombstone, + change: change.cursor.clone(), + source_snapshot: Some(row.source.clone()), + }; + insert_change_in_tx(&mut tx, &change).await?; + upsert_record_in_tx(&mut tx, &record).await?; + } + apply_read_model_write_plan_in_tx(&mut tx, write_plan).await?; + update_partition_head_in_tx( + &mut tx, + topology, + &partition, + state.change_head, + state.pending_retry_failure_id.as_deref(), + ) + .await?; + retain_projection_change_suffix_in_tx( + &mut tx, + topology, + &partition, + &state, + self.projection_change_retention(), + ) + .await?; + let mut tables = context + .compiled + .ownership() + .iter() + .map(|o| o.table.clone()) + .collect::>(); + tables.insert(PROJECTION_CHANGE_NOTIFY_TABLE.to_string()); + if self.projection_notify_enabled() { + DB::push_change_notify(&mut *tx, &tables).await?; + } + tx.commit() + .await + .map_err(|e| protocol_storage_error::("commit snapshot rebuild", e))?; + self.publish_read_model_change(crate::ReadModelChange { tables }); + Ok(plan.rows.len()) + } +} diff --git a/src/sqlx_repo/projection_protocol/store_impl.rs b/src/sqlx_repo/projection_protocol/store_impl.rs index 3a2b1e9da..5e60a00ff 100644 --- a/src/sqlx_repo/projection_protocol/store_impl.rs +++ b/src/sqlx_repo/projection_protocol/store_impl.rs @@ -13,6 +13,22 @@ where for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { + #[cfg(feature = "graphql")] + async fn projection_rebuild_records( + &self, + context: &crate::projection::rebuild::RebuildContext, + ) -> Result, ProjectionProtocolError> { + self.snapshot_rebuild_records(context).await + } + + #[cfg(feature = "graphql")] + async fn commit_projection_rebuild( + &self, + plan: crate::projection::rebuild::SnapshotProjectionRebuildPlan, + ) -> Result { + self.apply_snapshot_rebuild(plan).await + } + fn register_projection_models<'a>( &'a self, topology: &'a ProjectorTopologyId, From 72d63c58023975fd7bd6299b57aa10095e94e010 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 5 Sep 2026 19:55:26 -0500 Subject: [PATCH 003/484] fix(nats): reconcile durable subscription filters Preserve acknowledgement progress and broker tuning when an application changes its registered commands or events. Historical catch-up remains explicit. Refs incidents/nats-durable-subscription-drift --- src/bus/nats_bus.rs | 162 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 160 insertions(+), 2 deletions(-) diff --git a/src/bus/nats_bus.rs b/src/bus/nats_bus.rs index 77e9e9f97..6f0a9feb3 100644 --- a/src/bus/nats_bus.rs +++ b/src/bus/nats_bus.rs @@ -15,6 +15,10 @@ //! //! The `group` is the logical consumer identity (the service/deployment name). //! Same group ⇒ competing; different groups ⇒ independent fan-out copies. +//! Startup reconciles that durable's subject filters without resetting its +//! acknowledgement cursor or broker tuning. Replicas sharing a group must use +//! the same subscription inventory. Adding a filter does not replay messages +//! previously skipped by that consumer; historical catch-up is explicit. //! //! Requires the `nats` feature. Integration-tested in `tests/nats_transport`. @@ -319,17 +323,41 @@ impl NatsBus { strip_prefix: String, ) -> Result { let stream = self.ensure_stream().await?; - let consumer = stream + let mut consumer = stream .get_or_create_consumer( durable, PullConfig { durable_name: Some(durable.to_string()), - filter_subjects: subjects, + filter_subjects: subjects.clone(), ..Default::default() }, ) .await .map_err(|err| retryable("nats get_or_create_consumer", err))?; + // Opening a durable does not reconcile its existing configuration. An + // added route otherwise never receives events after an application + // upgrade. Update filters in place, preserving progress and tuning. + let current = &consumer.cached_info().config; + let mut actual = current.filter_subjects.clone(); + if !current.filter_subject.is_empty() { + actual.push(current.filter_subject.clone()); + } + actual.sort(); + actual.dedup(); + let mut desired = subjects; + desired.sort(); + desired.dedup(); + if actual != desired { + use async_nats::jetstream::consumer::FromConsumer; + let mut config = PullConfig::try_from_consumer_config(current.clone()) + .map_err(|err| retryable("nats read durable config", err))?; + config.filter_subject.clear(); + config.filter_subjects = desired; + consumer = stream + .update_consumer(config) + .await + .map_err(|err| retryable("nats update consumer filters", err))?; + } Ok(NatsJetStreamSource::new(consumer) .with_fetch_timeout(self.fetch_timeout) .with_strip_prefix(strip_prefix) @@ -374,6 +402,136 @@ impl NatsBus { mod archive_tests { use super::*; + #[tokio::test] + #[ignore = "requires DISTRIBUTED_ARCHIVE_TEST_NATS_URL with JetStream"] + async fn durable_filter_updates_preserve_progress_and_broker_tuning() { + use futures::StreamExt; + let url = std::env::var("DISTRIBUTED_ARCHIVE_TEST_NATS_URL").expect("test JetStream URL"); + let namespace = format!("filter-test-{}", uuid::Uuid::now_v7().simple()); + let bus = NatsBus::connect(&url).namespace(&namespace).await.unwrap(); + let stream = bus.ensure_stream().await.unwrap(); + let first = format!("{namespace}.evt.first"); + let added = format!("{namespace}.evt.added"); + let mut consumer = stream + .create_consumer(PullConfig { + durable_name: Some("filter-proof".into()), + filter_subjects: vec![first.clone()], + ack_wait: Duration::from_secs(17), + max_ack_pending: 29, + ..Default::default() + }) + .await + .unwrap(); + let created = consumer.cached_info().created; + bus.jetstream + .publish(first.clone(), "first".into()) + .await + .unwrap() + .await + .unwrap(); + let mut messages = consumer + .fetch() + .max_messages(1) + .expires(Duration::from_secs(2)) + .messages() + .await + .unwrap(); + let message = messages.next().await.unwrap().unwrap(); + message.double_ack().await.unwrap(); + drop(messages); + let acknowledged = consumer.info().await.unwrap().ack_floor.stream_sequence; + assert_eq!(acknowledged, 1); + bus.jetstream + .publish(added.clone(), "retained-new".into()) + .await + .unwrap() + .await + .unwrap(); + // Simulate the old application polling past an unmatched input. + let mut unmatched = consumer + .fetch() + .max_messages(1) + .expires(Duration::from_millis(100)) + .messages() + .await + .unwrap(); + assert!(unmatched.next().await.is_none()); + drop(unmatched); + drop( + bus.source( + "filter-proof", + vec![added.clone(), first.clone()], + format!("{namespace}.evt."), + ) + .await + .unwrap(), + ); + let info = consumer.info().await.unwrap(); + assert_eq!( + info.created, created, + "must update, not replace, the consumer" + ); + assert_eq!(info.ack_floor.stream_sequence, acknowledged); + assert_eq!(info.config.ack_wait, Duration::from_secs(17)); + assert_eq!(info.config.max_ack_pending, 29); + assert_eq!(info.config.filter_subjects.len(), 2); + bus.jetstream + .publish(added.clone(), "future-new".into()) + .await + .unwrap() + .await + .unwrap(); + let mut messages = consumer + .fetch() + .max_messages(2) + .expires(Duration::from_secs(2)) + .messages() + .await + .unwrap(); + let mut delivered = Vec::new(); + while let Some(message) = messages.next().await { + let message = message.unwrap(); + delivered.push(String::from_utf8(message.payload.to_vec()).unwrap()); + message.double_ack().await.unwrap(); + } + assert!(delivered.contains(&"future-new".into())); + assert!( + !delivered.contains(&"first".into()), + "acknowledged effects must not replay" + ); + // NATS does not promise historical catch-up for an added filter. Keep + // any observed retained delivery visible in the test output. + eprintln!("filter update delivered: {delivered:?}"); + drop( + bus.source( + "filter-proof", + vec![added.clone()], + format!("{namespace}.evt."), + ) + .await + .unwrap(), + ); + drop( + bus.source( + "filter-proof", + vec![added.clone()], + format!("{namespace}.evt."), + ) + .await + .unwrap(), + ); + assert_eq!( + consumer.info().await.unwrap().config.filter_subjects, + vec![added] + ); + assert_eq!(consumer.cached_info().created, created); + // The stream was created only by this test under a fresh UUID namespace. + bus.jetstream + .delete_stream(NatsBus::stream_name(&namespace)) + .await + .unwrap(); + } + #[derive(serde::Serialize, serde::Deserialize, crate::DomainState)] #[domain_state(version = 1)] struct ArchiveState { From 8565a69f2b481fb30c8be5748b1e63c672128915 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 5 Sep 2026 20:48:45 -0500 Subject: [PATCH 004/484] fix!: authorize retained dev process instances Publish the active process cohort after readiness, retain launch identity across client-only generations, and fence replaced, preparing, and retired instances. Derive GraphQL generation metadata from verified membership and classify pre-dispatch reload rejections without accepting invalid receipts. BREAKING CHANGE: supervised development requires matching CLI and runtime versions with process-instance membership. Upgrade both and restart distributed dev. Tests: 11 lifecycle process tests, 4 native gate tests, 344 JavaScript tests; live application commands across two UI-only activations with unchanged API PID. Public lifecycle e2e proof extended but not executed in this change. --- distributed_cli/README.md | 7 + distributed_cli/src/lifecycle/dev.rs | 128 ++++++++++++---- distributed_cli/tests/cli_lifecycle.rs | 67 ++++++++- js/src/replica/command-runtime/create.ts | 11 ++ js/tests/replica-command-runtime.test.mjs | 17 +++ src/graphql/protocol/types.rs | 11 ++ src/microsvc/lifecycle.rs | 169 ++++++++++++++++++++++ src/microsvc/mod.rs | 59 +------- tests/e2e-ui/scripts/lifecycle-reload.mjs | 29 +++- 9 files changed, 413 insertions(+), 85 deletions(-) create mode 100644 src/microsvc/lifecycle.rs diff --git a/distributed_cli/README.md b/distributed_cli/README.md index e444c85ca..95ff55e7e 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -59,6 +59,13 @@ document, boundary binding, or UI build therefore leaves the prior generation active. Lifecycle receipts, the application manifest, and generated client trees are tool-owned state under `.distributed/lifecycle/`. +During `distributed dev`, each process launch has a supervisor-owned identity. +Client-only generations can retain an unchanged API process: the active cohort +explicitly admits that instance, and its GraphQL responses advertise the current +generation. Preparing, replaced and retired instances cannot dispatch mutations. +Rollback launches receive new identities; schema compatibility alone never +authorizes an old process. Upgrade the CLI and runtime together and restart dev +after an upgrade so every member receives the matching lifecycle contract. Rust binaries remain in Cargo's target directory and SvelteKit output remains in its adapter-selected output directory. diff --git a/distributed_cli/src/lifecycle/dev.rs b/distributed_cli/src/lifecycle/dev.rs index 25ecedaed..63d6179f1 100644 --- a/distributed_cli/src/lifecycle/dev.rs +++ b/distributed_cli/src/lifecycle/dev.rs @@ -291,7 +291,7 @@ pub fn run_lifecycle_project_dev( initial_options.cancel = Some(Arc::clone(&options.stop)); let initial = run_lifecycle_project_build(&options.project, &initial_options)?; let state = DevStateStore::new(&root, &options.project.out)?; - state.write_active(&initial)?; + state.write_active(&initial, &BTreeMap::new())?; for process in dev.processes.values_mut() { process.env.insert( "DISTRIBUTED_LIFECYCLE_DIR".to_string(), @@ -299,6 +299,10 @@ pub fn run_lifecycle_project_dev( ); } let mut children = ChildSet::start(&root, &dev, &initial, &options.stop)?; + if let Err(error) = state.write_active(&initial, &children.members) { + let _ = children.shutdown(Duration::from_millis(dev.shutdown_ms)); + return Err(error); + } if options.progress { for (name, process) in &dev.processes { if let Some(url) = &process.url { @@ -416,13 +420,18 @@ pub fn run_lifecycle_project_dev( // acknowledgements to this attempt so a persisted response from a // rejected/superseded attempt can never authorize the next one. let transition = state.begin_transition()?; - state.write_preparing(&active, &generation, transition.id(), dev.prepare_ms)?; + state.write_preparing( + &active, + &generation, + transition.id(), + dev.prepare_ms, + &children.members, + )?; if let Err(error) = state.wait_for_prepare( transition.id(), Duration::from_millis(dev.prepare_ms), &options.stop, ) { - state.write_active(&active)?; if options.stop.load(Ordering::SeqCst) && error.reason() == LifecycleErrorReason::Canceled { @@ -433,6 +442,7 @@ pub fn run_lifecycle_project_dev( "pending generation preparation failed: {error}; prior generation is no longer serving: {serving}" )) })?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during preparation; prior generation remains active: {}", @@ -460,15 +470,14 @@ pub fn run_lifecycle_project_dev( if options.stop.load(Ordering::SeqCst) && error.reason() == LifecycleErrorReason::Canceled { - state.write_active(&active)?; return Ok(()); } - state.write_active(&active)?; children.ensure_running().map_err(|serving| { LifecycleError::new(format!( "pending generation readiness failed: {error}; prior generation rollback is not serving: {serving}" )) - })?; + })?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during readiness; prior generation remains active: {}", @@ -493,7 +502,8 @@ pub fn run_lifecycle_project_dev( ); return match rollback { Ok(()) => { - state.write_active(&active)?; + children.ensure_running()?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during activation; prior generation remains active: {}", @@ -510,7 +520,8 @@ pub fn run_lifecycle_project_dev( } final_generation = generation.generation_id.clone(); active = generation.clone(); - state.write_active(&active)?; + children.ensure_running()?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: activated generation={} invalidated={} restarted={}", @@ -528,8 +539,10 @@ pub fn run_lifecycle_project_dev( Ok(()) })(); + let retired = state.write_active(&active, &BTreeMap::new()); let shutdown = children.shutdown(Duration::from_millis(dev.shutdown_ms)); result?; + retired?; shutdown?; Ok(LifecycleDevReport { initial_generation: initial.generation_id, @@ -554,6 +567,7 @@ struct DevLifecycleState<'a> { schema_version: u32, phase: &'static str, active: DevGenerationState<'a>, + members: &'a BTreeMap, #[serde(skip_serializing_if = "Option::is_none")] pending: Option>, #[serde(skip_serializing_if = "Option::is_none")] @@ -580,11 +594,16 @@ impl DevStateStore { }) } - fn write_active(&self, active: &LifecycleBuildReport) -> Result<(), LifecycleError> { + fn write_active( + &self, + active: &LifecycleBuildReport, + members: &BTreeMap, + ) -> Result<(), LifecycleError> { self.write(&DevLifecycleState { schema_version: 1, phase: "active", active: generation_state(active), + members, pending: None, transition_id: None, deadline_unix_ms: None, @@ -617,12 +636,14 @@ impl DevStateStore { pending: &LifecycleBuildReport, transition_id: &str, prepare_ms: u64, + members: &BTreeMap, ) -> Result<(), LifecycleError> { let deadline = unix_ms()?.saturating_add(prepare_ms); self.write(&DevLifecycleState { schema_version: 1, phase: "preparing", active: generation_state(active), + members, pending: Some(generation_state(pending)), transition_id: Some(transition_id), deadline_unix_ms: Some(deadline), @@ -865,8 +886,36 @@ fn changed_paths( .collect() } +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct DevMemberState { + instance_id: String, + generation_id: String, +} + +impl DevMemberState { + fn new(generation: &LifecycleBuildReport) -> Result { + let identity = tempfile::Builder::new() + .prefix("member-") + .rand_bytes(16) + .tempfile() + .map_err(dev_io("allocate lifecycle process identity"))?; + let instance_id = identity + .path() + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| LifecycleError::new("invalid lifecycle process identity"))? + .to_owned(); + Ok(Self { + instance_id, + generation_id: generation.generation_id.clone(), + }) + } +} + struct ChildSet { children: BTreeMap, + members: BTreeMap, } impl ChildSet { @@ -878,11 +927,17 @@ impl ChildSet { ) -> Result { let mut set = Self { children: BTreeMap::new(), + members: BTreeMap::new(), }; for (name, process) in &config.processes { - match spawn_process(root, name, process, generation) { - Ok(child) => { + let spawned = DevMemberState::new(generation).and_then(|member| { + spawn_process(root, name, process, generation, &member.instance_id) + .map(|child| (child, member)) + }); + match spawned { + Ok((child, member)) => { set.children.insert(name.clone(), child); + set.members.insert(name.clone(), member); } Err(error) => { let _ = set.shutdown(Duration::from_millis(config.shutdown_ms)); @@ -907,6 +962,12 @@ impl ChildSet { } fn ensure_running(&mut self) -> Result<(), LifecycleError> { + if self.children.len() != self.members.len() || self.children.keys().ne(self.members.keys()) + { + return Err(LifecycleError::new( + "lifecycle process cohort is incomplete", + )); + } for (name, child) in &mut self.children { if let Some(status) = child.try_wait().map_err(|error| { LifecycleError::new(format!("failed to inspect dev process `{name}`: {error}")) @@ -946,20 +1007,27 @@ impl ChildSet { self.children.insert(name.clone(), previous_child); return Err(error); } - let replacement = - spawn_process(root, name, process, generation).and_then(|mut child| { - if let Err(error) = - wait_ready(root, name, process, generation, &mut child, stop) - { - let _ = - stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)); - return Err(error); - } - Ok(child) - }); + let replacement = DevMemberState::new(generation).and_then(|member| { + spawn_process(root, name, process, generation, &member.instance_id).and_then( + |mut child| { + if let Err(error) = + wait_ready(root, name, process, generation, &mut child, stop) + { + let _ = stop_child( + name, + &mut child, + Duration::from_millis(config.shutdown_ms), + ); + return Err(error); + } + Ok((child, member)) + }, + ) + }); match replacement { - Ok(child) => { + Ok((child, member)) => { self.children.insert(name.clone(), child); + self.members.insert(name.clone(), member); replaced.insert(name.clone()); } Err(error) => { @@ -1008,21 +1076,21 @@ impl ChildSet { for name in names { let process = &config.processes[name]; if let Some(mut child) = self.children.remove(name) { - if let Err(error) = stop_child( - name, - &mut child, - Duration::from_millis(config.shutdown_ms), - ) { + if let Err(error) = + stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)) + { self.children.insert(name.clone(), child); return Err(error); } } - let mut child = spawn_process(root, name, process, replacement)?; + let member = DevMemberState::new(replacement)?; + let mut child = spawn_process(root, name, process, replacement, &member.instance_id)?; if let Err(error) = wait_ready(root, name, process, replacement, &mut child, stop) { let _ = stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)); return Err(error); } self.children.insert(name.clone(), child); + self.members.insert(name.clone(), member); } Ok(()) } @@ -1187,6 +1255,7 @@ fn spawn_process( name: &str, process: &LifecycleDevProcess, generation: &LifecycleBuildReport, + instance_id: &str, ) -> Result { let cwd = resolve_working_dir(root, process.cwd.as_deref(), process.external_cwd)?; let args = process @@ -1205,6 +1274,7 @@ fn spawn_process( .env("DISTRIBUTED_TOPOLOGY_ID", &generation.graph_id) .env("DISTRIBUTED_COMPATIBILITY_ID", &generation.compatibility_id) .env("DISTRIBUTED_MEMBER_ID", name) + .env("DISTRIBUTED_PROCESS_INSTANCE_ID", instance_id) .stdin(Stdio::null()); #[cfg(unix)] command.process_group(0); diff --git a/distributed_cli/tests/cli_lifecycle.rs b/distributed_cli/tests/cli_lifecycle.rs index 9ec12e873..b1cc46428 100644 --- a/distributed_cli/tests/cli_lifecycle.rs +++ b/distributed_cli/tests/cli_lifecycle.rs @@ -186,6 +186,7 @@ else fi printf '%s:%s:%s\n' "$name" "$barrier" "$DISTRIBUTED_GENERATION_ID" >> "$root/dev-process.log" printf '%s:%s:%s\n' "$name" "$DEV_FIXTURE_NAME" "$PWD" >> "$root/dev-environment.log" +printf '%s:%s\n' "$name" "$DISTRIBUTED_PROCESS_INSTANCE_ID" >> "$root/dev-instances.log" trap 'exit 0' TERM /bin/sh -c 'trap "" TERM; while :; do sleep 1; done' & descendant=$! @@ -586,12 +587,54 @@ fn dev_waits_for_initial_generation_and_restarts_only_invalidated_processes() { &root.join("dist/distributed/active.json"), Duration::from_secs(5), ); + wait_until(Duration::from_secs(5), || { + dev_state(&root)["members"]["api"].is_object() + }); + let initial_state = dev_state(&root); + let instances = fs::read_to_string(root.join("dev-instances.log")).unwrap(); + for name in ["api", "ui"] { + assert!(instances.lines().any(|line| line + == format!( + "{name}:{}", + initial_state["members"][name]["instanceId"] + .as_str() + .unwrap() + ))); + } + let mut previous_generation = initial_state["active"]["generationId"].clone(); + // Changes outside either process's restart inventory retain both instances + // while their authorized application generation advances repeatedly. + for input in ["client-one", "client-two"] { + fs::write(root.join("plan/input.txt"), input).unwrap(); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" && state["active"]["generationId"] != previous_generation + }); + let state = dev_state(&root); + assert_eq!(state["members"], initial_state["members"]); + previous_generation = state["active"]["generationId"].clone(); + } fs::write(root.join("src/input.txt"), "second\n").unwrap(); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 3) }); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" && state["active"]["generationId"] != previous_generation + }); + let replaced = dev_state(&root); + assert_ne!( + replaced["members"]["api"]["instanceId"], + initial_state["members"]["api"]["instanceId"] + ); + assert_eq!( + replaced["members"]["api"]["generationId"], + replaced["active"]["generationId"] + ); + assert_eq!(replaced["members"]["ui"], initial_state["members"]["ui"]); let report = supervisor.stop_and_join(); - assert_eq!(report.rebuilds, 1); + assert_eq!(report.rebuilds, 3); + assert!(!root.join("dist/distributed/dev.json").exists()); assert_eq!(report.restarts["api"], 1); assert_eq!(report.restarts["ui"], 0); let log = fs::read_to_string(root.join("dev-process.log")).unwrap(); @@ -617,6 +660,13 @@ fn dev_waits_for_initial_generation_and_restarts_only_invalidated_processes() { } } +fn dev_state(root: &Path) -> Value { + fs::read(root.join("dist/distributed/dev.json")) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or(Value::Null) +} + #[test] fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { let fixture = temporary_root("dev-rollback"); @@ -632,6 +682,10 @@ fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { &root.join("dist/distributed/active.json"), Duration::from_secs(5), ); + wait_until(Duration::from_secs(5), || { + dev_state(&root)["members"]["api"].is_object() + }); + let initial_members = dev_state(&root)["members"].clone(); fs::write(root.join("src/input.txt"), "replacement\n").unwrap(); wait_until(Duration::from_secs(5), || { @@ -642,6 +696,17 @@ fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { fs::read_to_string(root.join("accepted-readiness.log")) .is_ok_and(|log| log.lines().count() == 2) }); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" + && state["members"]["api"]["instanceId"] != initial_members["api"]["instanceId"] + }); + let rollback = dev_state(&root); + assert_eq!( + rollback["members"]["api"]["generationId"], + initial_members["api"]["generationId"] + ); + assert_eq!(rollback["members"]["ui"], initial_members["ui"]); let report = supervisor.stop_and_join(); assert_eq!(report.initial_generation, report.final_generation); assert_eq!( diff --git a/js/src/replica/command-runtime/create.ts b/js/src/replica/command-runtime/create.ts index ba93716af..c5a040d79 100644 --- a/js/src/replica/command-runtime/create.ts +++ b/js/src/replica/command-runtime/create.ts @@ -1289,6 +1289,17 @@ export function createReplicaCommandRuntime< ); } + // The HTTP lifecycle gate rejects before dispatch and before a receipt + // exists. Classify only its exact failure shape, never a success/receipt. + if (result.status === 503 && result.data == null && result.extensions === undefined && + result.errors?.length === 1 && result.errors[0].extensions?.code === 'APPLICATION_RELOADING') { + rejectUnmanagedLayer(prepared.commandId); + revalidateInBackground(prepared, authority); + throw new ReplicaCommandRuntimeError('REPLICA_COMMAND_RELOADING', { + commandId: prepared.commandId + }); + } + const rejection = graphqlCommandRejection(result); if (rejection !== undefined) { try { diff --git a/js/tests/replica-command-runtime.test.mjs b/js/tests/replica-command-runtime.test.mjs index 889bfda19..af63f6080 100644 --- a/js/tests/replica-command-runtime.test.mjs +++ b/js/tests/replica-command-runtime.test.mjs @@ -712,6 +712,23 @@ test('coherent reload gate rejects before optimism or transport dispatch', async runtime.dispose(); }); +test('HTTP reload gate rolls back optimism and reports a reload, not an invalid receipt', async () => { + for (const status of [503, 200]) { + const replica = new TestReplica(); + const runtime = createReplicaCommandRuntime(replica, { + dispatch() { + assert.ok(replica.layer(COMMAND_A), 'optimism exists before the response'); + return { status, errors: [{message: 'application generation is reloading', + extensions: {code: 'APPLICATION_RELOADING'}}] }; + } + }, {change: artifact()}); + await assert.rejects(runtime.commands.change({id: 'todo-1', title: 'blocked'}, {commandId: COMMAND_A}), + {code: status === 503 ? 'REPLICA_COMMAND_RELOADING' : 'REPLICA_COMMAND_PROTOCOL_INVALID'}); + assert.equal(replica.layer(COMMAND_A), undefined); + runtime.dispose(); + } +}); + test('actual delta rebases later optimism while same-record dispatch retains invocation order', async () => { const replica = new TestReplica(); const first = deferred(); diff --git a/src/graphql/protocol/types.rs b/src/graphql/protocol/types.rs index 46e8c522b..64f4b7291 100644 --- a/src/graphql/protocol/types.rs +++ b/src/graphql/protocol/types.rs @@ -259,6 +259,17 @@ pub(crate) struct DistributedGenerationEnvelope { impl DistributedGenerationEnvelope { fn from_environment() -> Option { + if let Some(member) = crate::microsvc::lifecycle::membership_from_environment() { + let active = member.generation; + return Some(Self { + version: 1, + generation_id: active.generation_id, + release_id: active.release_id, + topology_id: Some(active.topology_id), + compatibility_id: Some(active.compatibility_id), + member_id: optional_environment_identity("DISTRIBUTED_MEMBER_ID"), + }); + } let generation_id = std::env::var("DISTRIBUTED_GENERATION_ID").ok()?; let release_id = std::env::var("DISTRIBUTED_RELEASE_ID").ok()?; if !bounded_identity(&generation_id) || !bounded_identity(&release_id) { diff --git a/src/microsvc/lifecycle.rs b/src/microsvc/lifecycle.rs new file mode 100644 index 000000000..ef30522c8 --- /dev/null +++ b/src/microsvc/lifecycle.rs @@ -0,0 +1,169 @@ +//! Supervisor-owned membership, independent of a process's startup generation. +//! No compatibility-only shortcut: a retained process must be explicitly named +//! by its launch identity in the active cohort. This is dev coordination, not +//! a security boundary against an operator who can edit the lifecycle directory. +use serde::Deserialize; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ActiveGeneration { + pub generation_id: String, + pub release_id: String, + pub topology_id: String, + pub compatibility_id: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Member { + instance_id: String, + generation_id: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct State { + schema_version: u32, + phase: String, + active: ActiveGeneration, + members: BTreeMap, +} + +pub(crate) struct Membership { + pub generation: ActiveGeneration, + pub mutations_open: bool, +} + +fn identity(value: &str) -> bool { + !value.is_empty() + && value.len() <= 512 + && value == value.trim() + && !value.chars().any(char::is_control) +} + +fn resolve(source: &[u8], member_id: &str, instance_id: &str, startup: &str) -> Option { + if source.len() > 1024 * 1024 || ![member_id, instance_id, startup].into_iter().all(identity) { + return None; + } + let state: State = serde_json::from_slice(source).ok()?; + if state.schema_version != 1 + || !matches!(state.phase.as_str(), "active" | "preparing") + || state.members.len() > 64 + { + return None; + } + let member = state.members.get(member_id)?; + if member.instance_id != instance_id || member.generation_id != startup { + return None; + } + let generation = state.active; + if ![ + &generation.generation_id, + &generation.release_id, + &generation.topology_id, + &generation.compatibility_id, + ] + .into_iter() + .all(|value| identity(value)) + { + return None; + } + Some(Membership { + generation, + mutations_open: state.phase == "active", + }) +} + +pub(crate) fn membership_from_environment() -> Option { + let root = std::path::PathBuf::from(std::env::var_os("DISTRIBUTED_LIFECYCLE_DIR")?); + if !root.is_absolute() { + return None; + } + let state = root.join("dev.json"); + let metadata = std::fs::symlink_metadata(&state).ok()?; + if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > 1024 * 1024 { + return None; + } + // Bound the actual read too, even if the file changes after metadata lookup. + use std::io::Read; + let mut source = Vec::new(); + std::fs::File::open(state) + .ok()? + .take(1024 * 1024 + 1) + .read_to_end(&mut source) + .ok()?; + resolve( + &source, + &std::env::var("DISTRIBUTED_MEMBER_ID").ok()?, + &std::env::var("DISTRIBUTED_PROCESS_INSTANCE_ID").ok()?, + &std::env::var("DISTRIBUTED_GENERATION_ID").ok()?, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn state(phase: &str, active: &str, instance: &str, startup: &str) -> serde_json::Value { + json!({"schemaVersion":1,"phase":phase,"active":{ + "generationId":active,"releaseId":format!("release:{active}"), + "topologyId":"topology","compatibilityId":"compatibility"}, + "members":{"api":{"instanceId":instance,"generationId":startup}}}) + } + fn check(value: &serde_json::Value, instance: &str, startup: &str) -> Option { + resolve( + &serde_json::to_vec(value).unwrap(), + "api", + instance, + startup, + ) + } + #[test] + fn retained_member_follows_active_generation_without_restart() { + for active in ["one", "two", "three"] { + let resolved = + check(&state("active", active, "api-one", "one"), "api-one", "one").unwrap(); + assert!(resolved.mutations_open); + assert_eq!(resolved.generation.generation_id, active); + assert_eq!(resolved.generation.release_id, format!("release:{active}")); + } + } + #[test] + fn preparing_preserves_old_reader_identity_but_fences_all_writes() { + let value = state("preparing", "one", "api-one", "one"); + let old = check(&value, "api-one", "one").unwrap(); + assert!(!old.mutations_open); + assert_eq!(old.generation.generation_id, "one"); + assert!(check(&value, "candidate", "two").is_none()); + } + #[test] + fn replacement_and_rollback_retire_old_launches_even_with_identical_generations() { + for (active, instance, startup) in [("two", "api-two", "two"), ("one", "rollback", "one")] { + let value = state("active", active, instance, startup); + assert!(check(&value, instance, startup).unwrap().mutations_open); + assert!(check(&value, "api-one", "one").is_none()); + assert!(check(&value, "api-two", "one").is_none()); + } + } + #[test] + fn missing_malformed_unknown_and_retired_members_fail_closed() { + let original = state("active", "one", "api-one", "one"); + for key in ["schemaVersion", "phase", "active", "members"] { + let mut value = original.clone(); + value.as_object_mut().unwrap().remove(key); + assert!(check(&value, "api-one", "one").is_none()); + } + for phase in ["stopped", "failed", ""] { + assert!(check(&state(phase, "one", "api-one", "one"), "api-one", "one").is_none()); + } + let mut retired = original.clone(); + retired["members"] = json!({}); + assert!(check(&retired, "api-one", "one").is_none()); + let mut malformed = original; + malformed["active"]["releaseId"] = json!("\ninvalid"); + assert!(check(&malformed, "api-one", "one").is_none()); + assert!(resolve(b"not json", "api", "api-one", "one").is_none()); + } +} diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index e2baac522..80d15ad53 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -61,6 +61,7 @@ mod context; mod descriptor; mod dependencies; mod error; +pub(crate) mod lifecycle; mod message_router; mod projector; mod runtime; @@ -145,64 +146,14 @@ pub use session::{Session, ROLE_KEY, USER_ID_KEY}; #[cfg(feature = "http")] pub const MAX_HTTP_BODY_BYTES: usize = 1024 * 1024; -/// Fail closed for writes while a `distributed dev` process is not the active -/// application generation. Outside the dev supervisor there is no lifecycle +/// Fail closed for writes unless the supervisor admits this process instance +/// to the active application generation. Outside dev there is no lifecycle /// directory, so ordinary production/runtime embedding remains unchanged. pub(crate) fn lifecycle_mutations_open() -> bool { - let Some(root) = std::env::var_os("DISTRIBUTED_LIFECYCLE_DIR") else { + if std::env::var_os("DISTRIBUTED_LIFECYCLE_DIR").is_none() { return true; - }; - let Some(generation) = std::env::var_os("DISTRIBUTED_GENERATION_ID") else { - return false; - }; - let root = std::path::PathBuf::from(root); - let Some(generation) = generation.to_str() else { - return false; - }; - if !root.is_absolute() { - return false; - } - let state = root.join("dev.json"); - let Ok(metadata) = std::fs::symlink_metadata(&state) else { - return false; - }; - if metadata.file_type().is_symlink() - || !metadata.is_file() - || metadata.len() > 1024 * 1024 - { - return false; - } - std::fs::read(&state) - .ok() - .is_some_and(|source| lifecycle_state_allows_mutations(&source, generation)) -} - -fn lifecycle_state_allows_mutations(source: &[u8], generation: &str) -> bool { - let Ok(state) = serde_json::from_slice::(source) else { - return false; - }; - state.get("phase").and_then(serde_json::Value::as_str) == Some("active") - && state - .get("active") - .and_then(|active| active.get("generationId")) - .and_then(serde_json::Value::as_str) - == Some(generation) -} - -#[cfg(test)] -mod lifecycle_gate_tests { - use super::lifecycle_state_allows_mutations; - - #[test] - fn mutations_open_only_for_the_exact_active_generation() { - let active = br#"{"phase":"active","active":{"generationId":"sha256:one"}}"#; - let preparing = - br#"{"phase":"preparing","active":{"generationId":"sha256:one"}}"#; - assert!(lifecycle_state_allows_mutations(active, "sha256:one")); - assert!(!lifecycle_state_allows_mutations(active, "sha256:two")); - assert!(!lifecycle_state_allows_mutations(preparing, "sha256:one")); - assert!(!lifecycle_state_allows_mutations(b"not-json", "sha256:one")); } + lifecycle::membership_from_environment().is_some_and(|member| member.mutations_open) } // HTTP transport (requires "http" feature) diff --git a/tests/e2e-ui/scripts/lifecycle-reload.mjs b/tests/e2e-ui/scripts/lifecycle-reload.mjs index 9315477d0..dd5a9de79 100644 --- a/tests/e2e-ui/scripts/lifecycle-reload.mjs +++ b/tests/e2e-ui/scripts/lifecycle-reload.mjs @@ -8,6 +8,7 @@ import { chromium } from 'playwright'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const frameworkRoot = resolve(root, '../../js'); const application = resolve(root, 'crates/todo-domain/src/commands/force_archive.rs'); +const clientPage = resolve(root, 'ui/src/routes/todos/+page.svelte'); const framework = resolve(frameworkRoot, 'src/sveltekit/lifecycle.ts'); const lifecycleFile = resolve(root, '.distributed/lifecycle/dev.json'); const baseURL = process.env.E2E_UI_ORIGIN || 'http://127.0.0.1:5180'; @@ -85,6 +86,7 @@ const fixtureIO = kubeWorkload }; const original = fixtureIO.read(application); const frameworkOriginal = fixtureIO.read(framework); +const clientOriginal = fixtureIO.read(clientPage); async function waitFor(predicate, label, timeout = timeoutMs) { const started = Date.now(); @@ -229,6 +231,25 @@ async function transition(page, path, source, expectedReplicaRestore, assertGate } page.off('framenavigated', onNavigation); page.off('request', onRequest); + // Readability alone does not prove the retained API reopened its write gate. + const title = `after-reload-${Date.now()}`; + const response = page.waitForResponse((result) => result.request().method() === 'POST' && + (result.request().postData() ?? '').includes('todos_create')); + await page.locator('#todo-title').fill(title); + await page.getByRole('button', { name: /^add$/i }).click(); + const mutation = await response; + assert.equal(mutation.status(), 200, 'active generation must accept commands'); + const body = await mutation.json(); + assert.ok(!body.errors?.length); + assert.equal(body.extensions.distributed.generation.generationId, after.active.generationId); + assert.equal(body.extensions.distributed.generation.releaseId, after.active.releaseId); + assert.ok(body.extensions.distributed.command, 'actual command receipt required'); + // Discard browser optimism and confirm the persisted read model on a new page. + await page.reload({waitUntil: 'domcontentloaded'}); + await page.locator('[data-todo-id]').filter({hasText: title}).waitFor({timeout: timeoutMs}); + await waitFor(() => page.evaluate(() => globalThis.__distributedReloadState !== undefined), 'hydration after command proof'); + await page.evaluate(() => { globalThis.__distributedReloadState.value = 'preserve-me'; }); + await waitForBrowserParticipant(page); } const browser = await chromium.launch({ headless: true }); @@ -267,6 +288,11 @@ try { await page.evaluate(() => { globalThis.__distributedReloadState.value = 'preserve-me'; }); + for (const suffix of ['first', 'second']) { + await transition(page, clientPage, `${clientOriginal}\n\n`, true); + assert.deepEqual((await lifecycleState()).members.api, baseline.members.api, + 'client-only reload must retain the same verified API instance'); + } const compatible = `${original}\n// lifecycle-compatible source-only rebuild\n`; await transition(page, application, compatible, true, true); @@ -280,10 +306,11 @@ try { ); assert.notEqual(incompatible, compatible, 'incompatible fixture edit must apply'); await transition(page, application, incompatible, false); - console.log('lifecycle-reload: application + framework + incompatible transitions OK'); + console.log('lifecycle-reload: client-only + application + framework + incompatible transitions accept commands'); } finally { fixtureIO.write(application, original); fixtureIO.write(framework, frameworkOriginal); + fixtureIO.write(clientPage, clientOriginal); await waitFor(async () => { const state = await lifecycleState(); return state?.phase === 'active' && From 20e84ccbfd58a33f07b7accc90530e72d94ffc56 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 15:38:41 -0500 Subject: [PATCH 005/484] style: format runtime and client contracts --- distributed_cli/src/cli.rs | 12 +- distributed_cli/src/client_compiler/mod.rs | 9 +- .../client_compiler/projection_delta/wire.rs | 4 +- .../src/client_compiler/render/commands.rs | 8 +- distributed_cli/src/client_compiler/tests.rs | 34 ++- .../src/contracts/classification.rs | 9 +- distributed_cli/src/contracts/closeout.rs | 10 +- distributed_cli/src/contracts/mod.rs | 4 +- distributed_cli/src/contracts/program.rs | 19 +- distributed_cli/src/contracts/snapshots.rs | 10 +- distributed_cli/src/contracts/transaction.rs | 17 +- distributed_cli/src/generate/service_crate.rs | 2 +- distributed_cli/src/js_framework.rs | 4 +- distributed_cli/src/lib.rs | 45 ++-- distributed_cli/src/lifecycle/build.rs | 13 +- distributed_cli/src/wasm_pures.rs | 12 +- distributed_cli/tests/cli_client.rs | 10 +- distributed_cli/tests/cli_scaffold.rs | 3 +- distributed_macros/src/digest.rs | 4 +- distributed_macros/src/domain_event.rs | 4 +- distributed_macros/src/lib.rs | 2 +- distributed_macros/src/portable_command.rs | 17 +- distributed_macros/tests/application.rs | 10 +- examples/graphiql.rs | 4 +- src/application/capability.rs | 14 +- src/application/command.rs | 63 ++--- src/application/manifest.rs | 221 ++++++++++++------ src/application/module.rs | 54 +++-- src/application/plan.rs | 14 +- src/application/registration.rs | 8 +- src/application/runtime_host.rs | 2 +- src/bus/sql_bus_common.rs | 5 +- src/graphql/client_manifest/export.rs | 55 +++-- src/graphql/client_manifest/identity.rs | 4 +- src/graphql/client_manifest/mod.rs | 12 +- src/graphql/client_manifest/tests.rs | 43 ++-- src/graphql/command_contract/tests.rs | 9 +- src/graphql/engine/request.rs | 26 ++- src/graphql/http.rs | 15 +- src/graphql/projection_delta/types.rs | 16 +- src/graphql/protocol/mod.rs | 2 +- src/graphql/surface/tests.rs | 10 +- src/graphql/surface/types.rs | 27 ++- src/in_memory_repo/projection_protocol/mod.rs | 4 +- src/lib.rs | 40 ++-- src/microsvc/mod.rs | 36 ++- src/microsvc/service/defaults.rs | 5 +- src/microsvc/service/mod.rs | 6 +- src/microsvc/service/runtime.rs | 33 +-- src/projection/mod.rs | 4 +- src/sqlx_repo/projection_protocol/mod.rs | 4 +- src/table/mod.rs | 10 +- src/table/mutation.rs | 3 +- tests/application_composition.rs | 188 +++++++-------- tests/application_plans.rs | 10 +- tests/causal_public_invoke/main.rs | 14 +- .../checkout_saga_service/service.rs | 14 +- tests/graphql_harden/authz.rs | 4 +- tests/graphql_harden/dos.rs | 12 +- tests/graphql_harden/residual.rs | 4 +- tests/graphql_query_protocol/main.rs | 5 +- tests/graphql_query_protocol_postgres/main.rs | 2 +- tests/graphql_sqlite/main.rs | 3 +- tests/graphql_subscriptions_sqlite/main.rs | 3 +- tests/metrics_exposition/main.rs | 15 +- tests/microsvc/transport_http.rs | 16 +- tests/typed_commands/main.rs | 15 +- 67 files changed, 715 insertions(+), 601 deletions(-) diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index a8f46d0cc..76b5ca628 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -19,8 +19,8 @@ use std::sync::Arc; use std::time::Duration; use crate::client_compiler::{ - compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, - GeneratedClientFile, GeneratedClientProject, + compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, GeneratedClientFile, + GeneratedClientProject, }; use crate::contracts::{ contracts_accept, contracts_check, unknown_scope_diagnostic, ContractAcceptScope, @@ -2129,9 +2129,8 @@ fn stale_generated_client_files( .starts_with("/** GENERATED by distributed client. Do not edit. */") || (compiler_manifest_version == Some(1) && relative == "routes.ts" - && contents.starts_with( - "/** GENERATED framework-neutral `@load` ownership plan. */", - )); + && contents + .starts_with("/** GENERATED framework-neutral `@load` ownership plan. */")); if !has_compatible_marker { return Err(format!( "refusing to remove {} because its compiler ownership marker is missing", @@ -2895,8 +2894,7 @@ mod tests { "/** GENERATED framework-neutral `@load` ownership plan. */\nexport const DISTRIBUTED_ROUTES = [];\n", ) .expect("write legacy routes"); - let current_manifest = - "{\"compiler_manifest_version\":2,\"operations\":[]}\n".to_string(); + let current_manifest = "{\"compiler_manifest_version\":2,\"operations\":[]}\n".to_string(); let project = GeneratedClientProject { files: vec![GeneratedClientFile { path: "manifest.json".to_string(), diff --git a/distributed_cli/src/client_compiler/mod.rs b/distributed_cli/src/client_compiler/mod.rs index 278cbb7a3..09a1fee2f 100644 --- a/distributed_cli/src/client_compiler/mod.rs +++ b/distributed_cli/src/client_compiler/mod.rs @@ -54,7 +54,9 @@ impl ClientCompileInput { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum ClientSurfaceSelector { - Role { name: String }, + Role { + name: String, + }, Application { name: String, eligible_roles: Vec, @@ -72,7 +74,10 @@ impl ClientSurfaceSelector { eligible_roles: impl IntoIterator>, schema_roles: impl IntoIterator>, ) -> Self { - let mut eligible_roles = eligible_roles.into_iter().map(Into::into).collect::>(); + let mut eligible_roles = eligible_roles + .into_iter() + .map(Into::into) + .collect::>(); let mut schema_roles = schema_roles.into_iter().map(Into::into).collect::>(); eligible_roles.sort(); eligible_roles.dedup(); diff --git a/distributed_cli/src/client_compiler/projection_delta/wire.rs b/distributed_cli/src/client_compiler/projection_delta/wire.rs index 63830091e..623b8a790 100644 --- a/distributed_cli/src/client_compiler/projection_delta/wire.rs +++ b/distributed_cli/src/client_compiler/projection_delta/wire.rs @@ -210,7 +210,9 @@ impl ProjectionDeltaIdentity { #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub(crate) enum ProjectionSurfaceIdentity { - Role { name: String }, + Role { + name: String, + }, Application { name: String, eligible_roles: Vec, diff --git a/distributed_cli/src/client_compiler/render/commands.rs b/distributed_cli/src/client_compiler/render/commands.rs index 1998b390c..45b6dd01f 100644 --- a/distributed_cli/src/client_compiler/render/commands.rs +++ b/distributed_cli/src/client_compiler/render/commands.rs @@ -155,7 +155,9 @@ fn pure_function_inventory( } /// Generate `pures.ts` mapping pure fn ids to hosts / hand imports. -pub(super) fn render_pures(manifest: &ClientManifest) -> Result, ClientCompileError> { +pub(super) fn render_pures( + manifest: &ClientManifest, +) -> Result, ClientCompileError> { let inventory = pure_function_inventory(manifest)?; if inventory.is_empty() { return Ok(None); @@ -168,9 +170,7 @@ pub(super) fn render_pures(manifest: &ClientManifest) -> Result, .iter() .any(|(_, d)| matches!(d, PureDelivery::WasmPackage { .. })); if needs_wasm { - sections.push( - "import { createWasmJsonPure } from '@hops-ops/distributed/replica';".into(), - ); + sections.push("import { createWasmJsonPure } from '@hops-ops/distributed/replica';".into()); } let mut entries = Vec::new(); let mut ready_calls = Vec::new(); diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 90d1f0ae0..24aeeafdf 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -2,9 +2,7 @@ use serde_json::{json, Value as JsonValue}; use sha2::{Digest, Sha256}; use super::manifest::{refresh_schema_fingerprint, ClientManifest}; -use super::{ - compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, -}; +use super::{compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector}; fn fingerprint(label: &str) -> String { let digest = Sha256::digest(label.as_bytes()); @@ -1183,22 +1181,20 @@ fn component_load_compiles_to_a_framework_neutral_island_inventory() { #[test] fn multiple_load_islands_may_share_one_future_boundary() { - let project = compile_client( - ClientCompileInput::new( - manifest(), - ClientSurfaceSelector::role("user"), - vec![ - ClientDocument::new( - "src/lib/todos/TodoCount.graphql", - "query TodoCount @load { todos { id } }", - ), - ClientDocument::new( - "src/lib/todos/TodoTitles.graphql", - "query TodoTitles @load { todos { title } }", - ), - ], - ), - ) + let project = compile_client(ClientCompileInput::new( + manifest(), + ClientSurfaceSelector::role("user"), + vec![ + ClientDocument::new( + "src/lib/todos/TodoCount.graphql", + "query TodoCount @load { todos { id } }", + ), + ClientDocument::new( + "src/lib/todos/TodoTitles.graphql", + "query TodoTitles @load { todos { title } }", + ), + ], + )) .expect("route ownership is no longer one-operation-per-route"); assert_eq!(project.islands.len(), 2); diff --git a/distributed_cli/src/contracts/classification.rs b/distributed_cli/src/contracts/classification.rs index a07661381..6ef321512 100644 --- a/distributed_cli/src/contracts/classification.rs +++ b/distributed_cli/src/contracts/classification.rs @@ -111,10 +111,11 @@ pub fn decisions_are_distinct(changes: &[ClassifiedChange]) -> bool { // Distinctness is only meaningful when both families appear. let has_wire = seen.contains(&LifecycleDecision::AcceptManifestWire); let has_protocol = seen.contains(&LifecycleDecision::AcceptProtocolSemantic); - !(has_wire && has_protocol && changes.iter().any(|c| { - c.decision == LifecycleDecision::AcceptManifestWire - && c.path.contains("protocol") - })) + !(has_wire + && has_protocol + && changes.iter().any(|c| { + c.decision == LifecycleDecision::AcceptManifestWire && c.path.contains("protocol") + })) } #[cfg(test)] diff --git a/distributed_cli/src/contracts/closeout.rs b/distributed_cli/src/contracts/closeout.rs index 22cf7ed1d..1297983de 100644 --- a/distributed_cli/src/contracts/closeout.rs +++ b/distributed_cli/src/contracts/closeout.rs @@ -70,10 +70,7 @@ mod tests { #[test] fn local_chain_closeout_accepts_matching_predecessors() { - let app = ArtifactIdentity::new( - ContractArtifactKind::ApplicationManifest, - "sha256:app", - ); + let app = ArtifactIdentity::new(ContractArtifactKind::ApplicationManifest, "sha256:app"); let plan = ArtifactIdentity::new(ContractArtifactKind::DeploymentPlan, "sha256:plan"); let result = close_local_contract_chain(&app, &plan, true, None); assert!(result.diagnostics.is_empty()); @@ -90,10 +87,7 @@ mod tests { )); fs::create_dir_all(&root).unwrap(); fs::write(root.join("a.js"), b"1").unwrap(); - let app = ArtifactIdentity::new( - ContractArtifactKind::ApplicationManifest, - "sha256:app", - ); + let app = ArtifactIdentity::new(ContractArtifactKind::ApplicationManifest, "sha256:app"); let plan = ArtifactIdentity::new(ContractArtifactKind::DeploymentPlan, "sha256:plan"); let program = ClientProgramDescriptor::builder("e2e-ui") .surface(ClientProgramSurface { diff --git a/distributed_cli/src/contracts/mod.rs b/distributed_cli/src/contracts/mod.rs index 68f3fe2c3..201165ff7 100644 --- a/distributed_cli/src/contracts/mod.rs +++ b/distributed_cli/src/contracts/mod.rs @@ -8,8 +8,8 @@ mod artifact; mod catalog; mod chain; -mod closeout; mod classification; +mod closeout; mod diagnostic; mod migrations; mod program; @@ -31,10 +31,10 @@ pub use catalog::{ MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, }; pub use chain::{check_predecessor_chain, ObservedPredecessor}; -pub use closeout::{classify_release_programs, close_local_contract_chain}; pub use classification::{ classify_snapshot_diff, decisions_are_distinct, ClassifiedChange, LifecycleDecision, }; +pub use closeout::{classify_release_programs, close_local_contract_chain}; pub use diagnostic::{ ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, SafeDiagnosticValue, }; diff --git a/distributed_cli/src/contracts/program.rs b/distributed_cli/src/contracts/program.rs index 0b9da7d20..d6a717676 100644 --- a/distributed_cli/src/contracts/program.rs +++ b/distributed_cli/src/contracts/program.rs @@ -118,7 +118,9 @@ impl ClientProgramDescriptor { return Err("program must declare at least one surface".into()); } if self.assets.len() > MAX_PROGRAM_ASSETS { - return Err(format!("program exceeds max asset count {MAX_PROGRAM_ASSETS}")); + return Err(format!( + "program exceeds max asset count {MAX_PROGRAM_ASSETS}" + )); } let mut paths = BTreeSet::new(); for asset in &self.assets { @@ -291,7 +293,10 @@ fn contract_set_id( ); } for artifact in artifacts { - material.insert(format!("artifact:{}", artifact.path), artifact.digest.clone()); + material.insert( + format!("artifact:{}", artifact.path), + artifact.digest.clone(), + ); } let bytes = serde_json::to_vec(&material).unwrap_or_default(); identity_digest("distributed.client-program.contract-set.v1", &bytes) @@ -319,7 +324,10 @@ fn program_id( fn collect_assets(root: &Path) -> Result, String> { if !root.is_dir() { - return Err(format!("asset root `{}` is not a directory", root.display())); + return Err(format!( + "asset root `{}` is not a directory", + root.display() + )); } let root = root.canonicalize().map_err(|e| e.to_string())?; let mut assets = Vec::new(); @@ -439,7 +447,10 @@ mod tests { fs::write(root.join("app.js"), b"console.log(1)").unwrap(); let first = base_builder(&root).build().unwrap(); let second = base_builder(&root).build().unwrap(); - assert_eq!(first.canonical_bytes().unwrap(), second.canonical_bytes().unwrap()); + assert_eq!( + first.canonical_bytes().unwrap(), + second.canonical_bytes().unwrap() + ); assert_eq!( first.classify_against(&second).unwrap(), ProgramCompatibility::Current diff --git a/distributed_cli/src/contracts/snapshots.rs b/distributed_cli/src/contracts/snapshots.rs index 6c387e620..94a6a1d1e 100644 --- a/distributed_cli/src/contracts/snapshots.rs +++ b/distributed_cli/src/contracts/snapshots.rs @@ -161,10 +161,7 @@ fn flatten_value( Value::String(text) if text.len() > MAX_SNAPSHOT_VALUE_BYTES => { out.insert( prefix.to_string(), - Value::String(format!( - "", - text.len() - )), + Value::String(format!("", text.len())), ); } other => { @@ -243,10 +240,7 @@ mod tests { .unwrap(); let changes = diff_snapshots(&left, &drifted).changes; assert_eq!(changes.len(), 1); - assert_eq!( - changes[0].path, - "models.TodoView.fields.title.nullable" - ); + assert_eq!(changes[0].path, "models.TodoView.fields.title.nullable"); assert_eq!(changes[0].before, Some(json!(false))); assert_eq!(changes[0].after, Some(json!(true))); } diff --git a/distributed_cli/src/contracts/transaction.rs b/distributed_cli/src/contracts/transaction.rs index cdd6b6643..4bd354285 100644 --- a/distributed_cli/src/contracts/transaction.rs +++ b/distributed_cli/src/contracts/transaction.rs @@ -5,9 +5,7 @@ use super::catalog::ContractCatalog; use super::chain::{check_predecessor_chain, ObservedPredecessor}; -use super::diagnostic::{ - ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, -}; +use super::diagnostic::{ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode}; use super::ContractArtifactKind; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -25,7 +23,9 @@ pub enum ContractAcceptScope { ApplicationManifest, DeploymentPlan, /// Exact client-program scope: `program:`. - Program { id: String }, + Program { + id: String, + }, } impl ContractAcceptScope { @@ -190,10 +190,7 @@ pub fn contracts_accept( }) } -fn rollback( - root: &Path, - prior: &BTreeMap>>, -) -> Result<(), String> { +fn rollback(root: &Path, prior: &BTreeMap>>) -> Result<(), String> { for (relative, contents) in prior { let path = resolve_under_root(root, relative)?; match contents { @@ -224,9 +221,7 @@ fn resolve_under_root(root: &Path, relative: &str) -> Result { "accept path `{relative}` escapes or is not a portable relative path" )); } - let root = root - .canonicalize() - .unwrap_or_else(|_| root.to_path_buf()); + let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); let candidate = root.join(relative); if let Ok(canonical) = candidate.canonicalize() { if !canonical.starts_with(&root) { diff --git a/distributed_cli/src/generate/service_crate.rs b/distributed_cli/src/generate/service_crate.rs index 77521fe5b..922db3183 100644 --- a/distributed_cli/src/generate/service_crate.rs +++ b/distributed_cli/src/generate/service_crate.rs @@ -213,7 +213,7 @@ async fn main() -> Result<(), {error_type}> {{ .map(|model| format!(" .read_model::<{}>()\n", model.view_ident)) .collect::(); format!( -r#"use distributed::{{ + r#"use distributed::{{ Application, ApplicationManifest, ReadModelCatalog, SurfaceSpec, }}; diff --git a/distributed_cli/src/js_framework.rs b/distributed_cli/src/js_framework.rs index 117602a96..b4c001833 100644 --- a/distributed_cli/src/js_framework.rs +++ b/distributed_cli/src/js_framework.rs @@ -182,9 +182,7 @@ impl JavascriptFrameworkPackage { pub(crate) fn wasm_pack_launcher(&self, ui_root: &Path) -> PathBuf { match &self.source { - JavascriptPackageSource::Local { root } => { - root.join("node_modules/wasm-pack/run.js") - } + JavascriptPackageSource::Local { root } => root.join("node_modules/wasm-pack/run.js"), JavascriptPackageSource::Registry => ui_root.join("node_modules/wasm-pack/run.js"), } } diff --git a/distributed_cli/src/lib.rs b/distributed_cli/src/lib.rs index 32c899050..3fde9d3df 100644 --- a/distributed_cli/src/lib.rs +++ b/distributed_cli/src/lib.rs @@ -33,31 +33,32 @@ pub use client_compiler::{ }; pub use contracts::{ check_migration_history, check_migration_inventory, check_predecessor_chain, - classify_release_programs, classify_snapshot_diff, close_local_contract_chain, contracts_accept, - contracts_check, diff_snapshots, snapshot_from_json, ArtifactIdentity, ArtifactPredecessor, - ArtifactProvenance, BaselineAvailability, ClassifiedChange, ClientDeclaration, ClientInventory, - ClientProgramArtifact, ClientProgramAsset, ClientProgramDescriptor, ClientProgramSurface, - ContractAcceptScope, ContractArtifactKind, ContractCatalog, ContractCheckResult, - ContractDiagnostic, ContractDiagnosticCode, ContractEntry, ContractError, ContractScope, - ContractsAcceptReport, ContractsCheckReport, EnvironmentPolicyReference, LifecycleDecision, - MigrationDialect, MigrationEntry, MigrationFile, MigrationHistoryCheck, MigrationInventory, - ObservedPredecessor, ProgramCompatibility, SafeDiagnosticValue, - SemanticSnapshot, SnapshotChange, SnapshotDiff, SnapshotEntry, MAX_CATALOG_BYTES, - MAX_CATALOG_DIRECTORIES, MAX_CATALOG_DIRECTORY_DEPTH, MAX_CATALOG_DIRECTORY_ENTRIES, - MAX_CATALOG_ENTRIES, MAX_CATALOG_FILES, MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, - MAX_MIGRATIONS, MAX_MIGRATION_INVENTORY_BYTES, MAX_MIGRATION_SQL_BYTES, MAX_SNAPSHOT_DEPTH, - MAX_SNAPSHOT_PATHS, MAX_SNAPSHOT_VALUE_BYTES, MIGRATION_INVENTORY_PATH, - MIGRATION_INVENTORY_SCHEMA_VERSION, MIGRATION_OWNER, MIGRATION_SCOPE, + classify_release_programs, classify_snapshot_diff, close_local_contract_chain, + contracts_accept, contracts_check, diff_snapshots, snapshot_from_json, ArtifactIdentity, + ArtifactPredecessor, ArtifactProvenance, BaselineAvailability, ClassifiedChange, + ClientDeclaration, ClientInventory, ClientProgramArtifact, ClientProgramAsset, + ClientProgramDescriptor, ClientProgramSurface, ContractAcceptScope, ContractArtifactKind, + ContractCatalog, ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, + ContractEntry, ContractError, ContractScope, ContractsAcceptReport, ContractsCheckReport, + EnvironmentPolicyReference, LifecycleDecision, MigrationDialect, MigrationEntry, MigrationFile, + MigrationHistoryCheck, MigrationInventory, ObservedPredecessor, ProgramCompatibility, + SafeDiagnosticValue, SemanticSnapshot, SnapshotChange, SnapshotDiff, SnapshotEntry, + MAX_CATALOG_BYTES, MAX_CATALOG_DIRECTORIES, MAX_CATALOG_DIRECTORY_DEPTH, + MAX_CATALOG_DIRECTORY_ENTRIES, MAX_CATALOG_ENTRIES, MAX_CATALOG_FILES, + MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, MAX_MIGRATIONS, + MAX_MIGRATION_INVENTORY_BYTES, MAX_MIGRATION_SQL_BYTES, MAX_SNAPSHOT_DEPTH, MAX_SNAPSHOT_PATHS, + MAX_SNAPSHOT_VALUE_BYTES, MIGRATION_INVENTORY_PATH, MIGRATION_INVENTORY_SCHEMA_VERSION, + MIGRATION_OWNER, MIGRATION_SCOPE, }; pub use generate::{generate_service_scaffold, package_name}; pub use lifecycle::{ - run_lifecycle_build, run_lifecycle_dev, ArtifactNodeReceipt, BuildDrift, DistributedSourceIdentity, - GenerationManifest, LifecycleBuildConfig, LifecycleBuildOptions, LifecycleBuildReport, - LifecycleConfig, LifecycleDevConfig, LifecycleDevOptions, LifecycleDevProbe, - LifecycleDevProcess, LifecycleDevReport, LifecycleError, LifecycleExecutor, LifecycleGraph, LifecycleNode, - ReleaseManifest, ReleaseMember, GENERATION_MANIFEST_SCHEMA_VERSION, - LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, LIFECYCLE_CONFIG_SCHEMA_VERSION, - LIFECYCLE_GRAPH_SCHEMA_VERSION, NODE_RECEIPT_SCHEMA_VERSION, + run_lifecycle_build, run_lifecycle_dev, ArtifactNodeReceipt, BuildDrift, + DistributedSourceIdentity, GenerationManifest, LifecycleBuildConfig, LifecycleBuildOptions, + LifecycleBuildReport, LifecycleConfig, LifecycleDevConfig, LifecycleDevOptions, + LifecycleDevProbe, LifecycleDevProcess, LifecycleDevReport, LifecycleError, LifecycleExecutor, + LifecycleGraph, LifecycleNode, ReleaseManifest, ReleaseMember, + GENERATION_MANIFEST_SCHEMA_VERSION, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, + LIFECYCLE_CONFIG_SCHEMA_VERSION, LIFECYCLE_GRAPH_SCHEMA_VERSION, NODE_RECEIPT_SCHEMA_VERSION, RELEASE_MANIFEST_SCHEMA_VERSION, }; pub use skills::{embedded_skills, generate_skills, EmbeddedFile, EmbeddedSkill, SkillsInitSpec}; diff --git a/distributed_cli/src/lifecycle/build.rs b/distributed_cli/src/lifecycle/build.rs index c8dcdb66f..2779de55f 100644 --- a/distributed_cli/src/lifecycle/build.rs +++ b/distributed_cli/src/lifecycle/build.rs @@ -424,9 +424,7 @@ pub fn run_lifecycle_project_build( let drift = if request.check { match request.check_baseline { LifecycleCheckBaseline::Workspace => compare_workspace_outputs(&root, &generation)?, - LifecycleCheckBaseline::ActiveGeneration => { - compare_active_outputs(&out, &generation)? - } + LifecycleCheckBaseline::ActiveGeneration => compare_active_outputs(&out, &generation)?, } } else { if request @@ -487,7 +485,9 @@ fn compare_active_outputs( generation: &GenerationManifest, ) -> Result, LifecycleError> { let active = read_active_generation(out)?; - let active_root = active.as_ref().map(|identity| out.join("generations").join(identity)); + let active_root = active + .as_ref() + .map(|identity| out.join("generations").join(identity)); let mut drift = Vec::new(); for receipt in generation.receipts.values() { for (output, built_identity) in &receipt.output_identities { @@ -675,10 +675,7 @@ fn execute_node( .env("DISTRIBUTED_LIFECYCLE_ROOT", root) .env("DISTRIBUTED_LIFECYCLE_STAGE", stage) .env("DISTRIBUTED_LIFECYCLE_NODE", node_id) - .env( - "DISTRIBUTED_LIFECYCLE_CHECK", - if check { "1" } else { "0" }, - ) + .env("DISTRIBUTED_LIFECYCLE_CHECK", if check { "1" } else { "0" }) .stdout(stdout) .stderr(Stdio::piped()); let mut child = command.spawn().map_err(|error| { diff --git a/distributed_cli/src/wasm_pures.rs b/distributed_cli/src/wasm_pures.rs index 305286a1f..859f0a986 100644 --- a/distributed_cli/src/wasm_pures.rs +++ b/distributed_cli/src/wasm_pures.rs @@ -86,9 +86,8 @@ pub(crate) fn build_declared_wasm_pures( return Ok(0); }; let ui_lib = ui_root.join("src/lib"); - let wasm_pack_launcher = wasm_pack_launcher.ok_or( - "browser WASM pures require @hops-ops/distributed in the application UI", - )?; + let wasm_pack_launcher = wasm_pack_launcher + .ok_or("browser WASM pures require @hops-ops/distributed in the application UI")?; let compiler_identity = compiler_identity(wasm_pack_launcher)?; let mut outputs = BTreeMap::::new(); for pure in &pures { @@ -437,7 +436,11 @@ fn compiler_identity(launcher: &Path) -> Result> { ) .into()); } - hash.update(file.strip_prefix(package_root)?.to_string_lossy().as_bytes()); + hash.update( + file.strip_prefix(package_root)? + .to_string_lossy() + .as_bytes(), + ); hash.update([0]); hash.update(&content); hash.update([0]); @@ -927,5 +930,4 @@ mod tests { .to_string() .contains("more than one local Cargo package")); } - } diff --git a/distributed_cli/tests/cli_client.rs b/distributed_cli/tests/cli_client.rs index 3b0f73dd4..1d814a2a2 100644 --- a/distributed_cli/tests/cli_client.rs +++ b/distributed_cli/tests/cli_client.rs @@ -584,7 +584,7 @@ fn unmatched_document_glob_fails_before_creating_output() { #[test] fn component_load_intent_remains_framework_neutral_outside_route_conventions() { - let project = project_dir("client-component-load"); + let project = project_dir("client-component-load"); write_document(&project, "queries/todos.graphql", LOAD_TODOS_QUERY); let unplaced = generate(&project, "queries/*.graphql", &[]); @@ -596,10 +596,10 @@ fn component_load_intent_remains_framework_neutral_outside_route_conventions() { "unplaced component island must retain its load intent for the adapter" ); - assert!( - !project.join("generated/routes.ts").exists(), - "the framework-neutral compiler must not invent adapter route ownership" - ); + assert!( + !project.join("generated/routes.ts").exists(), + "the framework-neutral compiler must not invent adapter route ownership" + ); } #[test] diff --git a/distributed_cli/tests/cli_scaffold.rs b/distributed_cli/tests/cli_scaffold.rs index 6710a2e17..da553eb53 100644 --- a/distributed_cli/tests/cli_scaffold.rs +++ b/distributed_cli/tests/cli_scaffold.rs @@ -84,7 +84,8 @@ fn scaffold_generates_a_service_tree() { assert!(deploy_values.starts_with("local: false\npreview: false\n")); assert!(deploy_values.contains("tag: \"\"")); assert!(!read(&out_dir, ".gitops/local/templates/deployment.yaml").contains(".Values.local")); - assert!(read(&out_dir, ".gitops/deploy/templates/deployment.yaml").contains("image.tag must be an immutable build tag")); + assert!(read(&out_dir, ".gitops/deploy/templates/deployment.yaml") + .contains("image.tag must be an immutable build tag")); let cargo = read(&out_dir, "Cargo.toml"); assert!(cargo.contains("\"postgres\""), "Cargo.toml: {cargo}"); diff --git a/distributed_macros/src/digest.rs b/distributed_macros/src/digest.rs index fa5378747..9b95a32a8 100644 --- a/distributed_macros/src/digest.rs +++ b/distributed_macros/src/digest.rs @@ -3,8 +3,8 @@ use quote::{format_ident, quote}; use syn::{parse::Parser, Expr, Ident, ItemFn, LitStr, Token}; use crate::shared::{ - ensure_sourced_result_signature, extract_params_with_types, generate_digest_call, - framework_path, wrap_result_body_with_guard, + ensure_sourced_result_signature, extract_params_with_types, framework_path, + generate_digest_call, wrap_result_body_with_guard, }; pub(crate) fn expand_digest(attr: TokenStream2, item: TokenStream2) -> syn::Result { diff --git a/distributed_macros/src/domain_event.rs b/distributed_macros/src/domain_event.rs index b03be56fa..f94934981 100644 --- a/distributed_macros/src/domain_event.rs +++ b/distributed_macros/src/domain_event.rs @@ -4,8 +4,8 @@ use quote::quote; use syn::{Data, DeriveInput, Fields, LitInt, LitStr}; use crate::shared::{ - canonical_object_schema, projection_body_metadata_tokens, schema_fingerprint, - validate_domain_event_name_literal, framework_path, + canonical_object_schema, framework_path, projection_body_metadata_tokens, schema_fingerprint, + validate_domain_event_name_literal, }; pub(crate) fn derive_domain_event(input: TokenStream) -> TokenStream { diff --git a/distributed_macros/src/lib.rs b/distributed_macros/src/lib.rs index b075a46f0..d1fae7a82 100644 --- a/distributed_macros/src/lib.rs +++ b/distributed_macros/src/lib.rs @@ -2,7 +2,6 @@ mod aggregate; mod application; mod command; mod command_input_defaults; -mod portable_command; mod digest; mod domain_event; mod domain_state; @@ -10,6 +9,7 @@ mod enqueue; mod graphql_types; mod module; mod mutation; +mod portable_command; // Event-owning `projection!` authoring removed (mutation projectors cutover). mod read_model; mod shared; diff --git a/distributed_macros/src/portable_command.rs b/distributed_macros/src/portable_command.rs index a1a2e6ed0..5ca69efdb 100644 --- a/distributed_macros/src/portable_command.rs +++ b/distributed_macros/src/portable_command.rs @@ -221,16 +221,13 @@ pub fn expand(input: TokenStream) -> syn::Result { let field = &value.field; quote! { .authenticated_user_field::<#event, #state>(#field) } }); - let preview_reduce_known_record = args - .preview_reduce_known_record - .as_ref() - .map(|preview| { - quote! { - .preview_reduce_known_record( - (#preview).declared_in_rust_package(env!("CARGO_PKG_NAME")) - ) - } - }); + let preview_reduce_known_record = args.preview_reduce_known_record.as_ref().map(|preview| { + quote! { + .preview_reduce_known_record( + (#preview).declared_in_rust_package(env!("CARGO_PKG_NAME")) + ) + } + }); let install_body = if let Some(handle) = &args.handle { if args.invoke.is_some() || args.payload.is_some() { diff --git a/distributed_macros/tests/application.rs b/distributed_macros/tests/application.rs index 3fb9f1146..a3d29efb5 100644 --- a/distributed_macros/tests/application.rs +++ b/distributed_macros/tests/application.rs @@ -98,8 +98,14 @@ fn command_module_and_application_macros_share_one_portable_spec() { assert_eq!(spec.id, "todo.create"); assert_eq!(spec.roles, ["admin", "user"]); assert_eq!(spec.emits[0].name, "todo.created"); - assert!(spec.applies.as_array().is_some_and(|values| !values.is_empty())); - assert!(spec.defaults.as_array().is_some_and(|values| !values.is_empty())); + assert!(spec + .applies + .as_array() + .is_some_and(|values| !values.is_empty())); + assert!(spec + .defaults + .as_array() + .is_some_and(|values| !values.is_empty())); assert!(!spec.effects.is_null()); assert!(!spec.fingerprint.is_empty()); assert_eq!( diff --git a/examples/graphiql.rs b/examples/graphiql.rs index ac4bd1cc6..7722210ff 100644 --- a/examples/graphiql.rs +++ b/examples/graphiql.rs @@ -18,9 +18,7 @@ use std::sync::Arc; use distributed::graphql::GraphqlEngine; use distributed::microsvc::{serve, Service}; -use distributed::{ - ColumnType, ReadModelCatalog, PrimaryKey, TableColumn, TableKind, TableSchema, -}; +use distributed::{ColumnType, PrimaryKey, ReadModelCatalog, TableColumn, TableKind, TableSchema}; use sqlx::sqlite::SqlitePoolOptions; fn orders_schema() -> TableSchema { diff --git a/src/application/capability.rs b/src/application/capability.rs index 2a8cad36a..8ace05cdd 100644 --- a/src/application/capability.rs +++ b/src/application/capability.rs @@ -186,9 +186,7 @@ pub fn derive_process_capabilities( &mut reasons, Capability::DirectProjectionTransaction, Some(mount), - format!( - "atomic command `{id}` requires collocated direct projection" - ), + format!("atomic command `{id}` requires collocated direct projection"), ); push( &mut reasons, @@ -289,7 +287,10 @@ pub fn derive_process_capabilities( Some(mount), format!("surface `{id}` dispatches commands remotely"), ); - } else if mounts.iter().any(|m| matches!(m, MountSelector::Command { .. })) { + } else if mounts + .iter() + .any(|m| matches!(m, MountSelector::Command { .. })) + { push( &mut reasons, Capability::LocalCommandDispatch, @@ -358,10 +359,7 @@ pub fn derive_process_capabilities( return Err(ApplicationError::Collision { kind: "schema lifecycle owner", identity: schema_owner.clone().unwrap_or_default(), - reason: format!( - "expected single logical owner `{}`", - manifest.name - ), + reason: format!("expected single logical owner `{}`", manifest.name), }); } } diff --git a/src/application/command.rs b/src/application/command.rs index 42b639a50..0f571d3ea 100644 --- a/src/application/command.rs +++ b/src/application/command.rs @@ -113,9 +113,7 @@ pub fn admit_command_session( user_id: Option<&str>, session_roles: &[&str], ) -> Result<(), &'static str> { - if command_roles_require_principal(roles) - && user_id.map(str::trim).unwrap_or("").is_empty() - { + if command_roles_require_principal(roles) && user_id.map(str::trim).unwrap_or("").is_empty() { return Err("unauthenticated"); } if roles.is_empty() { @@ -234,8 +232,7 @@ fn validate_mount_spec(spec: &CommandSpec, mount: &CommandMount) -> ApplicationR return Err(ApplicationError::Collision { kind: "command", identity: spec.id.clone(), - reason: "command definition and executable mount do not share one spec identity" - .into(), + reason: "command definition and executable mount do not share one spec identity".into(), }); } Ok(()) @@ -291,7 +288,8 @@ impl CommandSpec { proof: serde_json::Value, ) -> ApplicationResult { self.consistency = CommandConsistency::Atomic; - self.projected_model = Some(LogicalId::try_new("projected model", projected_model)?.into_string()); + self.projected_model = + Some(LogicalId::try_new("projected model", projected_model)?.into_string()); self.direct_projection = Some(proof); self.refresh_fingerprint()?; self.validate()?; @@ -397,11 +395,16 @@ impl CommandSpec { }) .collect(); emits.sort_by(|left, right| { - (left.name.as_str(), left.version, left.body_fingerprint.as_str()).cmp(&( - right.name.as_str(), - right.version, - right.body_fingerprint.as_str(), - )) + ( + left.name.as_str(), + left.version, + left.body_fingerprint.as_str(), + ) + .cmp(&( + right.name.as_str(), + right.version, + right.body_fingerprint.as_str(), + )) }); let mut roles = contract.roles.clone(); roles.sort(); @@ -597,11 +600,7 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl super::manifest::MAX_MANIFEST_JSON_BYTES ))); } - fn walk( - kind: &'static str, - value: &serde_json::Value, - depth: usize, - ) -> ApplicationResult<()> { + fn walk(kind: &'static str, value: &serde_json::Value, depth: usize) -> ApplicationResult<()> { if depth > super::manifest::MAX_MANIFEST_JSON_DEPTH { return Err(ApplicationError::InvalidSpec(format!( "{kind} exceeds JSON depth {}", @@ -610,7 +609,8 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl } match value { serde_json::Value::String(value) => { - if value.len() > super::manifest::MAX_MANIFEST_STRING_BYTES || value.contains('\0') { + if value.len() > super::manifest::MAX_MANIFEST_STRING_BYTES || value.contains('\0') + { return Err(ApplicationError::InvalidSpec(format!( "{kind} contains oversized or NUL string material" ))); @@ -633,8 +633,7 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl ))); } for (key, value) in fields { - if key.len() > super::manifest::MAX_MANIFEST_STRING_BYTES - || key.contains('\0') + if key.len() > super::manifest::MAX_MANIFEST_STRING_BYTES || key.contains('\0') { return Err(ApplicationError::InvalidSpec(format!( "{kind} contains oversized or NUL object-key material" @@ -643,7 +642,8 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl walk(kind, value, depth + 1)?; } } - serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {} + serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => { + } } Ok(()) } @@ -656,9 +656,11 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl /// `Any` value: a runtime can invoke it without knowing the concrete function /// item type or attempting a downcast. pub type CommandMountFuture<'a> = Pin< - Box> - + Send - + 'a>, + Box< + dyn Future> + + Send + + 'a, + >, >; pub trait CommandMountHandler: Send + Sync { @@ -669,7 +671,10 @@ pub trait CommandMountHandler: Send + Sync { /// not executable merely because it contains a value; an adapter must accept /// it into its registry before it can be dispatched. pub trait CommandMountRegistrar { - fn register_command_mount(&mut self, mount: CommandMount) -> Result<(), crate::microsvc::HandlerError>; + fn register_command_mount( + &mut self, + mount: CommandMount, + ) -> Result<(), crate::microsvc::HandlerError>; } /// Invocation context for the heterogeneous runtime boundary. The ordinary @@ -728,9 +733,8 @@ pub(crate) enum CommandMountExecutionError { #[allow(dead_code)] pub(crate) type CommandMountExecutionFuture<'a> = Pin< Box< - dyn Future< - Output = Result, - > + Send + dyn Future> + + Send + 'a, >, >; @@ -819,9 +823,8 @@ impl CommandMount { pub fn from_request_handler(spec: CommandSpec, handler: H) -> Self where H: Fn(crate::microsvc::CommandRequest) -> F + Send + Sync + 'static, - F: Future< - Output = Result, - > + Send + F: Future> + + Send + 'static, { Self::from_handler(spec, RequestCommandMountHandler(handler)) diff --git a/src/application/manifest.rs b/src/application/manifest.rs index ada263fab..a609859f4 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -256,7 +256,10 @@ impl ApplicationManifest { } pub fn module_ids(&self) -> Vec<&str> { - self.modules.iter().map(|module| module.id.as_str()).collect() + self.modules + .iter() + .map(|module| module.id.as_str()) + .collect() } /// Return exact deterministic manifest bytes, including the explicit @@ -363,15 +366,26 @@ impl ApplicationManifest { validate_collection_len("models", self.models.len())?; validate_collection_len("surfaces", self.surfaces.len())?; validate_collection_len("extensions", self.extensions.len())?; - validate_unique_ids("module", self.modules.iter().map(|module| module.id.clone()))?; - validate_unique_ids("command", self.commands.iter().map(|command| command.id.clone()))?; + validate_unique_ids( + "module", + self.modules.iter().map(|module| module.id.clone()), + )?; + validate_unique_ids( + "command", + self.commands.iter().map(|command| command.id.clone()), + )?; validate_unique_ids("event", self.events.iter().map(|event| event.name.clone()))?; validate_unique_ids( "projection", - self.projections.iter().map(|projection| projection.id.clone()), + self.projections + .iter() + .map(|projection| projection.id.clone()), )?; validate_unique_ids("model", self.models.iter().map(|model| model.id.clone()))?; - validate_unique_ids("surface", self.surfaces.iter().map(|surface| surface.id.clone()))?; + validate_unique_ids( + "surface", + self.surfaces.iter().map(|surface| surface.id.clone()), + )?; let model_ids = self .models @@ -480,13 +494,19 @@ impl ApplicationManifest { self.modules.sort_by(|left, right| left.id.cmp(&right.id)); self.commands.sort_by(|left, right| left.id.cmp(&right.id)); self.events.sort_by(|left, right| { - (left.name.as_str(), left.version, left.body_fingerprint.as_str()).cmp(&( - right.name.as_str(), - right.version, - right.body_fingerprint.as_str(), - )) + ( + left.name.as_str(), + left.version, + left.body_fingerprint.as_str(), + ) + .cmp(&( + right.name.as_str(), + right.version, + right.body_fingerprint.as_str(), + )) }); - self.projections.sort_by(|left, right| left.id.cmp(&right.id)); + self.projections + .sort_by(|left, right| left.id.cmp(&right.id)); self.models.sort_by(|left, right| left.id.cmp(&right.id)); self.surfaces.sort_by(|left, right| left.id.cmp(&right.id)); self.required_capabilities.sort(); @@ -550,21 +570,41 @@ fn validate_module( module, require_nested_fingerprints, )?; - validate_unique_ids("module command", module.commands.iter().map(|item| item.id.clone()))?; + validate_unique_ids( + "module command", + module.commands.iter().map(|item| item.id.clone()), + )?; validate_unique_ids( "module projection", module.projections.iter().map(|item| item.id.clone()), )?; - validate_unique_ids("module event", module.events.iter().map(|item| item.name.clone()))?; - validate_unique_ids("module model", module.models.iter().map(|item| item.id.clone()))?; - validate_unique_ids("module surface", module.surfaces.iter().map(|item| item.id.clone()))?; + validate_unique_ids( + "module event", + module.events.iter().map(|item| item.name.clone()), + )?; + validate_unique_ids( + "module model", + module.models.iter().map(|item| item.id.clone()), + )?; + validate_unique_ids( + "module surface", + module.surfaces.iter().map(|item| item.id.clone()), + )?; validate_sorted_unique( "module commands", - &module.commands.iter().map(|item| item.id.clone()).collect::>(), + &module + .commands + .iter() + .map(|item| item.id.clone()) + .collect::>(), )?; validate_sorted_unique( "module events", - &module.events.iter().map(|item| item.name.clone()).collect::>(), + &module + .events + .iter() + .map(|item| item.name.clone()) + .collect::>(), )?; validate_sorted_unique( "module projections", @@ -576,26 +616,40 @@ fn validate_module( )?; validate_sorted_unique( "module models", - &module.models.iter().map(|item| item.id.clone()).collect::>(), + &module + .models + .iter() + .map(|item| item.id.clone()) + .collect::>(), )?; validate_sorted_unique( "module surfaces", - &module.surfaces.iter().map(|item| item.id.clone()).collect::>(), + &module + .surfaces + .iter() + .map(|item| item.id.clone()) + .collect::>(), )?; let module_model_ids = module .models .iter() .map(|model| model.id.as_str()) - .chain(module.surfaces.iter().flat_map(|surface| { - surface.models.iter().map(|model| model.id.as_str()) - })) + .chain( + module + .surfaces + .iter() + .flat_map(|surface| surface.models.iter().map(|model| model.id.as_str())), + ) .collect::>(); let module_projection_ids = module .projections .iter() .map(|projection| projection.id.as_str()) .chain(module.surfaces.iter().flat_map(|surface| { - surface.projections.iter().map(|projection| projection.id.as_str()) + surface + .projections + .iter() + .map(|projection| projection.id.as_str()) })) .collect::>(); for command in &module.commands { @@ -686,7 +740,10 @@ fn validate_projection( validate_sorted_unique("projection facts", &projection.facts)?; validate_sorted_unique("projection models", &projection.models)?; validate_sorted_unique("projection dependencies", &projection.dependencies)?; - validate_sorted_unique("modeled projection program IDs", &projection.modeled_programs)?; + validate_sorted_unique( + "modeled projection program IDs", + &projection.modeled_programs, + )?; for fact in &projection.facts { validate_portable_text("projection fact", fact)?; } @@ -793,7 +850,10 @@ fn validate_model( ))); } validate_sorted_unique("model primary key", &model.primary_key)?; - let field_names = field_names.iter().map(String::as_str).collect::>(); + let field_names = field_names + .iter() + .map(String::as_str) + .collect::>(); for field in &model.fields { validate_portable_text("model field", &field.name)?; validate_portable_text("model field scalar", &field.scalar)?; @@ -988,7 +1048,10 @@ fn validate_surface( validate_json_contract("surface command defaults", &command.defaults)?; validate_json_contract("surface command effects", &command.effects)?; validate_json_contract("surface command confirmations", &command.confirmations)?; - validate_json_contract("surface command projection contract", &command.projection_contract)?; + validate_json_contract( + "surface command projection contract", + &command.projection_contract, + )?; validate_json_contract("surface command applies", &command.applies)?; if let Some(model) = &command.projected_model { require_reference("model", model, model_scope)?; @@ -1030,7 +1093,11 @@ fn validate_surface_selection(surface: &SurfaceSpec) -> ApplicationResult<()> { ))); } } - value if value.strip_prefix("application:").is_some_and(|name| !name.is_empty()) => { + value + if value + .strip_prefix("application:") + .is_some_and(|name| !name.is_empty()) => + { let name = value.strip_prefix("application:").expect("matched above"); LogicalId::try_new("surface application", name.to_owned())?; if surface.eligible_roles.is_empty() { @@ -1045,11 +1112,12 @@ fn validate_surface_selection(surface: &SurfaceSpec) -> ApplicationResult<()> { surface.id ))); } - if surface - .schema_roles - .iter() - .any(|role| !surface.eligible_roles.iter().any(|eligible| eligible == role)) - { + if surface.schema_roles.iter().any(|role| { + !surface + .eligible_roles + .iter() + .any(|eligible| eligible == role) + }) { return Err(ApplicationError::InvalidSpec(format!( "application surface `{}` schema roles must be a subset of eligible roles", surface.id @@ -1079,7 +1147,9 @@ fn validate_roles(kind: &'static str, roles: &[String]) -> ApplicationResult<()> Ok(()) } -fn validate_surface_argument(argument: &super::module::SurfaceArgumentSpec) -> ApplicationResult<()> { +fn validate_surface_argument( + argument: &super::module::SurfaceArgumentSpec, +) -> ApplicationResult<()> { validate_portable_text("surface argument", &argument.name)?; validate_portable_text("surface argument kind", &argument.kind)?; validate_portable_text("surface argument type", &argument.type_name)?; @@ -1149,11 +1219,15 @@ fn validate_relationship_keys(value: &serde_json::Value) -> ApplicationResult<() let local = fields .get("local") .and_then(serde_json::Value::as_array) - .ok_or_else(|| ApplicationError::InvalidSpec("relationship keys need local columns".into()))?; + .ok_or_else(|| { + ApplicationError::InvalidSpec("relationship keys need local columns".into()) + })?; let remote = fields .get("remote") .and_then(serde_json::Value::as_array) - .ok_or_else(|| ApplicationError::InvalidSpec("relationship keys need remote columns".into()))?; + .ok_or_else(|| { + ApplicationError::InvalidSpec("relationship keys need remote columns".into()) + })?; if local.is_empty() || local.len() != remote.len() { return Err(ApplicationError::InvalidSpec( "relationship key columns must be non-empty and paired".into(), @@ -1278,9 +1352,7 @@ fn validate_command_type_spec_at_depth( fn validate_surface_contract(surface: &SurfaceSpec) -> ApplicationResult<()> { let expected = surface_contract_from_spec(surface)?; if canonical_json(&surface.contract) != expected { - return Err(ApplicationError::NonCanonical( - "surface contract material", - )); + return Err(ApplicationError::NonCanonical("surface contract material")); } Ok(()) } @@ -1297,8 +1369,7 @@ fn validate_manifest_ownership(manifest: &ApplicationManifest) -> ApplicationRes return Err(ApplicationError::Collision { kind: "command", identity: manifest.name.clone(), - reason: "application command inventory does not equal explicit module ownership" - .into(), + reason: "application command inventory does not equal explicit module ownership".into(), }); } @@ -1312,8 +1383,7 @@ fn validate_manifest_ownership(manifest: &ApplicationManifest) -> ApplicationRes return Err(ApplicationError::Collision { kind: "event", identity: manifest.name.clone(), - reason: "application event inventory does not equal explicit module ownership" - .into(), + reason: "application event inventory does not equal explicit module ownership".into(), }); } @@ -1360,7 +1430,10 @@ fn validate_manifest_ownership(manifest: &ApplicationManifest) -> ApplicationRes for module in &manifest.modules { for owned_surface in &module.surfaces { - let Some(surface) = manifest.surfaces.iter().find(|surface| surface.id == owned_surface.id) + let Some(surface) = manifest + .surfaces + .iter() + .find(|surface| surface.id == owned_surface.id) else { return Err(ApplicationError::Missing { kind: "surface", @@ -1419,8 +1492,9 @@ fn validate_manifest_ownership(manifest: &ApplicationManifest) -> ApplicationRes return Err(ApplicationError::Collision { kind: "projection", identity: exposed.id.clone(), - reason: "surface projection differs from the application projection declaration" - .into(), + reason: + "surface projection differs from the application projection declaration" + .into(), }); } } @@ -1503,17 +1577,15 @@ fn surface_command_closure( .iter() .filter(|command| match surface.selection.as_str() { "catalog" => true, - "role" => surface - .eligible_roles - .first() - .is_some_and(|role| { - command.roles.is_empty() || command.roles.iter().any(|allowed| allowed == role) - }), + "role" => surface.eligible_roles.first().is_some_and(|role| { + command.roles.is_empty() || command.roles.iter().any(|allowed| allowed == role) + }), value if value.starts_with("application:") => { command.roles.is_empty() - || surface.schema_roles.iter().all(|role| { - command.roles.iter().any(|allowed| allowed == role) - }) + || surface + .schema_roles + .iter() + .all(|role| command.roles.iter().any(|allowed| allowed == role)) } _ => false, }) @@ -1686,7 +1758,10 @@ fn validate_fingerprint( } let mut value = serde_json::to_value(value)?; if let serde_json::Value::Object(fields) = &mut value { - fields.insert("fingerprint".into(), serde_json::Value::String(String::new())); + fields.insert( + "fingerprint".into(), + serde_json::Value::String(String::new()), + ); } let expected = sha256_fingerprint(&serde_json::to_vec(&canonical_json(&value))?); if expected != fingerprint { @@ -1780,11 +1855,7 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl "{kind} exceeds {MAX_MANIFEST_JSON_BYTES} JSON bytes" ))); } - fn walk( - kind: &'static str, - value: &serde_json::Value, - depth: usize, - ) -> ApplicationResult<()> { + fn walk(kind: &'static str, value: &serde_json::Value, depth: usize) -> ApplicationResult<()> { if depth > MAX_MANIFEST_JSON_DEPTH { return Err(ApplicationError::InvalidSpec(format!( "{kind} exceeds JSON depth {MAX_MANIFEST_JSON_DEPTH}" @@ -1815,7 +1886,8 @@ fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> Appl walk(kind, value, depth + 1)?; } } - serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {} + serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => { + } } Ok(()) } @@ -1832,17 +1904,23 @@ fn dedup_events( mut values: Vec, ) -> ApplicationResult> { values.sort_by(|left, right| { - (left.name.as_str(), left.version, left.body_fingerprint.as_str()).cmp(&( - right.name.as_str(), - right.version, - right.body_fingerprint.as_str(), - )) + ( + left.name.as_str(), + left.version, + left.body_fingerprint.as_str(), + ) + .cmp(&( + right.name.as_str(), + right.version, + right.body_fingerprint.as_str(), + )) }); let mut out = Vec::new(); for value in values { - if let Some(existing) = out.iter().find(|existing: &&super::command::EventSpec| { - existing.name == value.name - }) { + if let Some(existing) = out + .iter() + .find(|existing: &&super::command::EventSpec| existing.name == value.name) + { if *existing != value { return Err(ApplicationError::Collision { kind: "event", @@ -1867,7 +1945,10 @@ fn dedup_models(mut values: Vec) -> ApplicationResult> values.sort_by(|left, right| left.id.cmp(&right.id)); let mut out = Vec::new(); for value in values { - if let Some(existing) = out.iter().find(|existing: &&ModelSpec| existing.id == value.id) { + if let Some(existing) = out + .iter() + .find(|existing: &&ModelSpec| existing.id == value.id) + { if *existing != value { return Err(ApplicationError::Collision { kind: "model", diff --git a/src/application/module.rs b/src/application/module.rs index 18fb7f84f..629e30d5d 100644 --- a/src/application/module.rs +++ b/src/application/module.rs @@ -84,10 +84,7 @@ impl ModelSpec { let table = LogicalId::try_new("model table", table)?.into_string(); let mut fields = fields.into_iter().collect::>(); fields.sort_by(|left, right| left.name.cmp(&right.name)); - let mut primary_key = primary_key - .into_iter() - .map(Into::into) - .collect::>(); + let mut primary_key = primary_key.into_iter().map(Into::into).collect::>(); primary_key.sort(); primary_key.dedup(); if fields.is_empty() { @@ -127,7 +124,6 @@ impl ModelSpec { self.fingerprint = sha256_fingerprint(&serde_json::to_vec(&canonical_json(&value))?); Ok(()) } - } /// Portable projection-owner identity aggregated into a module. @@ -258,11 +254,13 @@ impl ProjectionSpec { pub fn canonical_bytes(&self) -> ApplicationResult> { let mut value = serde_json::to_value(self)?; if let serde_json::Value::Object(fields) = &mut value { - fields.insert("fingerprint".into(), serde_json::Value::String(String::new())); + fields.insert( + "fingerprint".into(), + serde_json::Value::String(String::new()), + ); } serde_json::to_vec(&canonical_json(&value)).map_err(Into::into) } - } /// A root field identity retained by a surface contract. @@ -423,7 +421,8 @@ impl SurfaceSpec { spec.fields .sort_by(|left, right| left.name.cmp(&right.name)); spec.primary_key.sort(); - spec.relationships.sort_by(|left, right| left.name.cmp(&right.name)); + spec.relationships + .sort_by(|left, right| left.name.cmp(&right.name)); spec.refresh_fingerprint()?; Ok(spec) }) @@ -434,7 +433,12 @@ impl SurfaceSpec { .query_fields .iter() .map(|root| ("query", root)) - .chain(surface.subscription_fields.iter().map(|root| ("subscription", root))) + .chain( + surface + .subscription_fields + .iter() + .map(|root| ("subscription", root)), + ) .map(|(operation, root)| SurfaceRootSpec { operation: operation.into(), name: root.name.clone(), @@ -512,7 +516,10 @@ impl SurfaceSpec { pub fn canonical_bytes(&self) -> ApplicationResult> { let mut value = serde_json::to_value(self)?; if let serde_json::Value::Object(fields) = &mut value { - fields.insert("fingerprint".into(), serde_json::Value::String(String::new())); + fields.insert( + "fingerprint".into(), + serde_json::Value::String(String::new()), + ); } serde_json::to_vec(&canonical_json(&value)).map_err(Into::into) } @@ -577,16 +584,19 @@ fn surface_relationship_spec( .collect(), keys: surface_relationship_keys(&relationship.keys), dependencies: relationship.dependencies.clone(), - aggregate: relationship.aggregate.as_ref().map(|aggregate| SurfaceAggregateSpec { - name: aggregate.name.clone(), - type_name: aggregate.type_name.clone(), - arguments: aggregate - .arguments - .iter() - .map(surface_argument_spec) - .collect(), - dependencies: aggregate.dependencies.clone(), - }), + aggregate: relationship + .aggregate + .as_ref() + .map(|aggregate| SurfaceAggregateSpec { + name: aggregate.name.clone(), + type_name: aggregate.type_name.clone(), + arguments: aggregate + .arguments + .iter() + .map(surface_argument_spec) + .collect(), + dependencies: aggregate.dependencies.clone(), + }), }) } @@ -973,7 +983,9 @@ impl ModuleBuilder { .flat_map(|surface| surface.projections.iter().cloned()), ); projections.sort_by(|left, right| left.id.cmp(&right.id)); - projections = dedup_identical("projection", projections, |projection| projection.id.clone())?; + projections = dedup_identical("projection", projections, |projection| { + projection.id.clone() + })?; let mut events = commands .iter() diff --git a/src/application/plan.rs b/src/application/plan.rs index 07f4af6cd..2ddaf5c2e 100644 --- a/src/application/plan.rs +++ b/src/application/plan.rs @@ -14,9 +14,7 @@ use super::capability::{ use super::error::{ApplicationError, ApplicationResult}; use super::identity::{canonical_json, sha256_fingerprint, LogicalId}; use super::manifest::{ApplicationManifest, APPLICATION_MANIFEST_SCHEMA_VERSION}; -use super::mount::{ - validate_mounts_against_manifest, MountSelector, ProcessPreset, -}; +use super::mount::{validate_mounts_against_manifest, MountSelector, ProcessPreset}; use super::topology::{derive_topology, TopologyIntent}; use crate::graphql::command_contract::CommandConsistency; @@ -207,8 +205,10 @@ pub fn compile_deployment_plan( .insert(process.id.clone()); } MountSelector::Projector { id } => { - if let Some(projection) = - manifest.projections.iter().find(|projection| projection.id == *id) + if let Some(projection) = manifest + .projections + .iter() + .find(|projection| projection.id == *id) { if projection.direct { direct_projection_hosts @@ -425,7 +425,9 @@ impl DeploymentPlan { } let expected = expected_fingerprints(self)?; if self.fingerprints != expected { - return Err(ApplicationError::NonCanonical("deployment plan fingerprints")); + return Err(ApplicationError::NonCanonical( + "deployment plan fingerprints", + )); } // Silence unused import when APPLICATION_MANIFEST_SCHEMA_VERSION is only // for documentation linkage in validate paths. diff --git a/src/application/registration.rs b/src/application/registration.rs index afffdeebc..92593a599 100644 --- a/src/application/registration.rs +++ b/src/application/registration.rs @@ -4,7 +4,9 @@ use super::error::ApplicationResult; use super::manifest::{ApplicationExtension, ApplicationManifest, ManifestProvenance}; use super::module::{Module, SurfaceSpec}; use crate::graphql::surface::Surface; -use crate::graphql::{ClientManifestError, DistributedClientManifest, DistributedClientSurfaceExport}; +use crate::graphql::{ + ClientManifestError, DistributedClientManifest, DistributedClientSurfaceExport, +}; /// Explicit application registration. No linker inventory or source scan is /// consulted; only the values supplied to this constructor participate. @@ -217,7 +219,9 @@ impl ContractCompiler { "ContractCompiler already has a different authoritative Surface contract" )); } - return Err("ContractCompiler accepts exactly one authoritative Surface contract".into()); + return Err( + "ContractCompiler accepts exactly one authoritative Surface contract".into(), + ); } self.surface = Some(surface); self.surface_spec = Some(spec); diff --git a/src/application/runtime_host.rs b/src/application/runtime_host.rs index e0ad550b1..0237c66a7 100644 --- a/src/application/runtime_host.rs +++ b/src/application/runtime_host.rs @@ -183,7 +183,7 @@ mod tests { use crate::command_dispatch::{CommandDispatchError, CommandDispatcher}; use crate::microsvc::{CommandRequest, CommandResponse}; use async_trait::async_trait; - + struct Stub; #[async_trait] impl CommandDispatcher for Stub { diff --git a/src/bus/sql_bus_common.rs b/src/bus/sql_bus_common.rs index e2d7fe39e..0ad20698d 100644 --- a/src/bus/sql_bus_common.rs +++ b/src/bus/sql_bus_common.rs @@ -688,8 +688,9 @@ impl MessageSource for SqlLogSource { ), ) })?; - let source = ProjectionSource::new(format!("{}.bus_log", B::BACKEND), b"global".to_vec()) - .map_err(|error| corrupt_row(B::BACKEND, error.to_string()))?; + let source = + ProjectionSource::new(format!("{}.bus_log", B::BACKEND), b"global".to_vec()) + .map_err(|error| corrupt_row(B::BACKEND, error.to_string()))?; let ordered = OrderedDelivery::new(source, self.source_epoch.clone(), position, false) .map_err(|error| corrupt_row(B::BACKEND, error.to_string()))?; self.last_delivered = Some(row.seq); diff --git a/src/graphql/client_manifest/export.rs b/src/graphql/client_manifest/export.rs index 533d29bb4..a7be2ffb9 100644 --- a/src/graphql/client_manifest/export.rs +++ b/src/graphql/client_manifest/export.rs @@ -63,13 +63,11 @@ impl DistributedClientSurfaceExport { name, eligible_roles, schema_roles, - } => { - ClientSurfaceIdentity::application_with_schema_roles( - name, - eligible_roles.clone(), - schema_roles.clone(), - ) - } + } => ClientSurfaceIdentity::application_with_schema_roles( + name, + eligible_roles.clone(), + schema_roles.clone(), + ), }; validate_service_provenance(&service_id, &surface)?; Ok(Self::new(service_id, identity, surface, execution)) @@ -98,13 +96,11 @@ impl DistributedClientSurfaceExport { name, eligible_roles, schema_roles, - } => { - ClientSurfaceIdentity::application_with_schema_roles( - name, - eligible_roles.clone(), - schema_roles.clone(), - ) - } + } => ClientSurfaceIdentity::application_with_schema_roles( + name, + eligible_roles.clone(), + schema_roles.clone(), + ), }; if surface.service_binding.is_some() { return Err(ClientManifestError( @@ -175,17 +171,15 @@ pub fn prune_client_manifest( ))); } } - manifest.models.retain(|model| { - allowed.contains(&model.id) || allowed.contains(&model.typename) - }); + manifest + .models + .retain(|model| allowed.contains(&model.id) || allowed.contains(&model.typename)); let kept: BTreeSet = manifest .models .iter() .flat_map(|model| [model.id.clone(), model.typename.clone()]) .collect(); - manifest - .roots - .retain(|root| kept.contains(&root.model)); + manifest.roots.retain(|root| kept.contains(&root.model)); for projector in &mut manifest.projectors { projector.models.retain(|model| kept.contains(model)); } @@ -194,19 +188,22 @@ pub fn prune_client_manifest( .retain(|projector| !projector.models.is_empty()); for program in &mut manifest.projection_programs { for arm in &mut program.arms { - arm.operations.retain(|operation| kept.contains(&operation.model)); + arm.operations + .retain(|operation| kept.contains(&operation.model)); for operation in &mut arm.operations { operation.relationships.retain(|rel| { kept.contains(&rel.source_model) && kept.contains(&rel.target_model) }); - operation.invalidations.retain(|invalidation| match invalidation { - ClientProjectionInvalidation::Model { model } => kept.contains(model), - ClientProjectionInvalidation::Relationship { - source_model, - target_model, - .. - } => kept.contains(source_model) && kept.contains(target_model), - }); + operation + .invalidations + .retain(|invalidation| match invalidation { + ClientProjectionInvalidation::Model { model } => kept.contains(model), + ClientProjectionInvalidation::Relationship { + source_model, + target_model, + .. + } => kept.contains(source_model) && kept.contains(target_model), + }); } } program.arms.retain(|arm| !arm.operations.is_empty()); diff --git a/src/graphql/client_manifest/identity.rs b/src/graphql/client_manifest/identity.rs index eb059670c..e5cc72f8e 100644 --- a/src/graphql/client_manifest/identity.rs +++ b/src/graphql/client_manifest/identity.rs @@ -3,7 +3,9 @@ use super::*; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum ClientSurfaceIdentity { - Role { name: String }, + Role { + name: String, + }, /// `eligible_roles` is the canonical wire identity for principals who may /// open the application surface. `schema_roles` is the distinct role set /// used to derive the shared schema/command contract. diff --git a/src/graphql/client_manifest/mod.rs b/src/graphql/client_manifest/mod.rs index 22c7e2d9b..022c6b580 100644 --- a/src/graphql/client_manifest/mod.rs +++ b/src/graphql/client_manifest/mod.rs @@ -57,9 +57,10 @@ pub use identity::ClientSurfaceIdentity; pub use limits::{ClientComplexityWeights, ClientExecutionLimits}; pub use types::{ ClientAggregateSemantics, ClientArgument, ClientArgumentKind, ClientCapabilities, - ClientCommand, ClientCommandExtensionSlots, ClientCommandShape, ClientField, ClientFilterField, - ClientFilterInput, ClientFilterInputRelationship, ClientFilterSemantics, ClientKeyField, - ClientModel, ClientOrderSemantics, ClientPaginationSemantics, ClientProjectionArm, + ClientCommand, ClientCommandExtensionSlots, ClientCommandPureArg, ClientCommandPureReduce, + ClientCommandShape, ClientField, ClientFilterField, ClientFilterInput, + ClientFilterInputRelationship, ClientFilterSemantics, ClientKeyField, ClientModel, + ClientOrderSemantics, ClientPaginationSemantics, ClientProjectionArm, ClientProjectionAssignment, ClientProjectionBinding, ClientProjectionBindingState, ClientProjectionEnvelopeField, ClientProjectionEventRef, ClientProjectionExecutionClass, ClientProjectionExpression, ClientProjectionFallback, ClientProjectionField, @@ -74,9 +75,8 @@ pub use types::{ ClientRootKind, ClientRootOperation, ClientRowPolicy, ClientTrustedPresetDescriptor, ClientTypeDef, ClientTypeField, CommandConfirmationsExtension, CommandConsistencyExtension, CommandDirectProjectionExtension, CommandEffectsExtension, CommandInputDefaultsExtension, - ClientCommandPureArg, ClientCommandPureReduce, CommandProjectionArmRef, - CommandProjectionExtension, CommandProjectionPreviewOccurrence, CommandProjectionPreviewValue, - DistributedClientManifest, ModelNormalization, + CommandProjectionArmRef, CommandProjectionExtension, CommandProjectionPreviewOccurrence, + CommandProjectionPreviewValue, DistributedClientManifest, ModelNormalization, RelationshipKeyMapping, ScalarCodec, }; pub(crate) use validation::trusted_preset_descriptors; diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 81ed853e1..e51ce989c 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -908,7 +908,14 @@ fn role_and_application_partition_manifests_hide_raw_paths_and_denied_values() { ); let all_grants = grants(); let role = surface_for_role(&full, "user", &all_grants["user"]).unwrap(); - let application = surface_for_application(&full, "web", &["user".into()], &["user".into()], &all_grants).unwrap(); + let application = surface_for_application( + &full, + "web", + &["user".into()], + &["user".into()], + &all_grants, + ) + .unwrap(); for (identity, selected) in [ (ClientSurfaceIdentity::role("user"), role), @@ -1832,15 +1839,14 @@ fn bigint_keys_embed_until_decimal_string_identity_is_available() { fn application_surface_is_common_contract_with_safe_role_limit_semantics() { let full = full_surface(); let all_grants = grants(); - let selected = - surface_for_application( - &full, - "web", - &["user".into(), "admin".into()], - &["user".into(), "admin".into()], - &all_grants, - ) - .unwrap(); + let selected = surface_for_application( + &full, + "web", + &["user".into(), "admin".into()], + &["user".into(), "admin".into()], + &all_grants, + ) + .unwrap(); let manifest = client_manifest_from_surface( "todos-service", ClientSurfaceIdentity::application("web", ["admin", "user"], ["admin", "user"]), @@ -2315,15 +2321,14 @@ fn relational_row_policy_is_server_only_when_relationship_key_is_hidden() { #[test] fn application_role_sets_are_canonical_before_fingerprinting() { let full = full_surface(); - let selected = - surface_for_application( - &full, - "web", - &["admin".into(), "user".into()], - &["admin".into(), "user".into()], - &grants(), - ) - .unwrap(); + let selected = surface_for_application( + &full, + "web", + &["admin".into(), "user".into()], + &["admin".into(), "user".into()], + &grants(), + ) + .unwrap(); let first = client_manifest_from_surface( "todos-service", ClientSurfaceIdentity::Application { diff --git a/src/graphql/command_contract/tests.rs b/src/graphql/command_contract/tests.rs index 4894268ae..e028e4f2e 100644 --- a/src/graphql/command_contract/tests.rs +++ b/src/graphql/command_contract/tests.rs @@ -236,11 +236,10 @@ fn command_transition_fills_emits_from_domain_event_set() { #[test] fn authenticated_user_field_reuses_generated_event_schema_metadata() { - let contract = super::command_transition::>( - "todo.complete", - ) - .authenticated_user_field::("status") - .into_contract(); + let contract = + super::command_transition::>("todo.complete") + .authenticated_user_field::("status") + .into_contract(); let field = contract.projections.inferred_values[0] .preview .fields diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index 86dd15def..7cd88b2a2 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -2,7 +2,8 @@ use super::*; impl GraphqlEngine { pub async fn execute(&self, session: &Session, mut request: Request) -> Response { - if selected_operation_type(&mut request) == Some(async_graphql::parser::types::OperationType::Mutation) + if selected_operation_type(&mut request) + == Some(async_graphql::parser::types::OperationType::Mutation) && !crate::microsvc::lifecycle_mutations_open() { return lifecycle_mutation_rejected(); @@ -70,7 +71,8 @@ impl GraphqlEngine { session: &Session, mut request: Request, ) -> BoxStream<'static, async_graphql::Response> { - if selected_operation_type(&mut request) == Some(async_graphql::parser::types::OperationType::Mutation) + if selected_operation_type(&mut request) + == Some(async_graphql::parser::types::OperationType::Mutation) && !crate::microsvc::lifecycle_mutations_open() { return stream::once(async { lifecycle_mutation_rejected() }).boxed(); @@ -313,17 +315,19 @@ mod lifecycle_request_tests { #[test] fn selected_operation_type_fails_closed_for_ambiguous_documents() { let mut mutation = Request::new("mutation Write { __typename }"); - assert_eq!(selected_operation_type(&mut mutation), Some(OperationType::Mutation)); - - let mut selected = Request::new( - "query Read { __typename } mutation Write { __typename }", - ) - .operation_name("Write"); - assert_eq!(selected_operation_type(&mut selected), Some(OperationType::Mutation)); + assert_eq!( + selected_operation_type(&mut mutation), + Some(OperationType::Mutation) + ); - let mut ambiguous = Request::new( - "query Read { __typename } mutation Write { __typename }", + let mut selected = Request::new("query Read { __typename } mutation Write { __typename }") + .operation_name("Write"); + assert_eq!( + selected_operation_type(&mut selected), + Some(OperationType::Mutation) ); + + let mut ambiguous = Request::new("query Read { __typename } mutation Write { __typename }"); assert_eq!(selected_operation_type(&mut ambiguous), None); } } diff --git a/src/graphql/http.rs b/src/graphql/http.rs index b5e9591a9..8a738870d 100644 --- a/src/graphql/http.rs +++ b/src/graphql/http.rs @@ -283,7 +283,10 @@ async fn graphql_handler( ) -> Response { let request = req.into_inner(); if !crate::microsvc::lifecycle_mutations_open() - && matches!(websocket_operation_type(&request), Ok(OperationType::Mutation)) + && matches!( + websocket_operation_type(&request), + Ok(OperationType::Mutation) + ) { return lifecycle_reloading_response(); } @@ -312,7 +315,10 @@ async fn graphql_handler_with_service( ) -> Response { let request = req.into_inner(); if !crate::microsvc::lifecycle_mutations_open() - && matches!(websocket_operation_type(&request), Ok(OperationType::Mutation)) + && matches!( + websocket_operation_type(&request), + Ok(OperationType::Mutation) + ) { return lifecycle_reloading_response(); } @@ -343,7 +349,10 @@ pub async fn microsvc_graphql_handler( ) -> Response { let request = req.into_inner(); if !crate::microsvc::lifecycle_mutations_open() - && matches!(websocket_operation_type(&request), Ok(OperationType::Mutation)) + && matches!( + websocket_operation_type(&request), + Ok(OperationType::Mutation) + ) { return lifecycle_reloading_response(); } diff --git a/src/graphql/projection_delta/types.rs b/src/graphql/projection_delta/types.rs index 8af91baa0..c2d3b623b 100644 --- a/src/graphql/projection_delta/types.rs +++ b/src/graphql/projection_delta/types.rs @@ -99,7 +99,9 @@ pub struct ProjectionDeltaIdentity { #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum ProjectionDeltaSurfaceIdentity { - Role { name: String }, + Role { + name: String, + }, Application { name: String, eligible_roles: Vec, @@ -461,13 +463,11 @@ impl From<&crate::graphql::client_manifest::ClientSurfaceIdentity> name, eligible_roles, schema_roles, - } => { - Self::Application { - name: name.clone(), - eligible_roles: eligible_roles.clone(), - schema_roles: schema_roles.clone(), - } - } + } => Self::Application { + name: name.clone(), + eligible_roles: eligible_roles.clone(), + schema_roles: schema_roles.clone(), + }, } } } diff --git a/src/graphql/protocol/mod.rs b/src/graphql/protocol/mod.rs index d70b8325d..21d99c9e0 100644 --- a/src/graphql/protocol/mod.rs +++ b/src/graphql/protocol/mod.rs @@ -12,8 +12,8 @@ mod tests; mod token; mod types; -pub use accumulator::ProtocolResponseAccumulator; pub(crate) use accumulator::issue_projection_obligation_token; +pub use accumulator::ProtocolResponseAccumulator; pub(crate) use projection_metadata::{ CommandProjectionLifecycleProofV1, CommandProjectionMetadataError, CommandProjectionMetadataV1, CommandProjectionObligationV1, MAX_COMMAND_PROJECTION_OBLIGATIONS, diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index 4d2bc2ab8..5041b2d40 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -779,8 +779,14 @@ fn selected_surfaces_reject_command_and_projector_reattachment() { .contains("before authorization selection")); let grants_by_role = BTreeMap::from([("user".into(), grants)]); - let application = - surface_for_application(&full, "web", &["user".into()], &["user".into()], &grants_by_role).unwrap(); + let application = surface_for_application( + &full, + "web", + &["user".into()], + &["user".into()], + &grants_by_role, + ) + .unwrap(); assert!(application .clone() .with_typed_commands(&TypedCommandInventory::empty()) diff --git a/src/graphql/surface/types.rs b/src/graphql/surface/types.rs index 6b485d14f..06443a3b5 100644 --- a/src/graphql/surface/types.rs +++ b/src/graphql/surface/types.rs @@ -564,7 +564,9 @@ impl std::fmt::Debug for Surface { #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum SurfaceSelection { Catalog, - Role { name: String }, + Role { + name: String, + }, Application { name: String, eligible_roles: Vec, @@ -640,7 +642,8 @@ impl Surface { }) }) .collect::>(); - relationships.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str())); + relationships + .sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str())); serde_json::json!({ "model_name": model.model_name, "table_name": model.table_name, @@ -658,7 +661,11 @@ impl Surface { .query_fields .iter() .map(|root| root_value("query", root)) - .chain(self.subscription_fields.iter().map(|root| root_value("subscription", root))) + .chain( + self.subscription_fields + .iter() + .map(|root| root_value("subscription", root)), + ) .collect::>(); roots.sort_by(|left, right| { (left["operation"].as_str(), left["name"].as_str()) @@ -685,7 +692,11 @@ impl Surface { }) }) .collect::>(); - commands.sort_by(|left, right| left["command_name"].as_str().cmp(&right["command_name"].as_str())); + commands.sort_by(|left, right| { + left["command_name"] + .as_str() + .cmp(&right["command_name"].as_str()) + }); let mut projectors = self .projectors .iter() @@ -805,10 +816,7 @@ impl Surface { /// Bind several explicit logical modules before role/application /// authorization selection. - pub fn with_modules<'a, I>( - mut self, - modules: I, - ) -> Result + pub fn with_modules<'a, I>(mut self, modules: I) -> Result where I: IntoIterator, { @@ -825,7 +833,8 @@ impl Surface { for module in modules { contracts.extend(module.typed_command_contracts()?); } - let inventory = crate::graphql::commands::TypedCommandInventory::from_contracts(&contracts)?; + let inventory = + crate::graphql::commands::TypedCommandInventory::from_contracts(&contracts)?; self = self.with_typed_commands(&inventory)?; Ok(self) } diff --git a/src/in_memory_repo/projection_protocol/mod.rs b/src/in_memory_repo/projection_protocol/mod.rs index 67bb5572e..0242f3462 100644 --- a/src/in_memory_repo/projection_protocol/mod.rs +++ b/src/in_memory_repo/projection_protocol/mod.rs @@ -42,12 +42,12 @@ use crate::table::{ mod direct_projection; mod read_helpers; +#[cfg(feature = "graphql")] +mod rebuild; mod state; mod state_impl; mod store_impl; mod util; -#[cfg(feature = "graphql")] -mod rebuild; pub(super) use direct_projection::stage_same_transaction_projection; pub(super) use state::{reject_causal_owned_plans, InMemoryProjectionProtocolState}; diff --git a/src/lib.rs b/src/lib.rs index 9b8e56861..473dd9a09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,8 +23,8 @@ mod time; pub mod aggregate; pub mod application; -pub mod command_dispatch; pub mod bus; +pub mod command_dispatch; pub mod domain_event; pub mod entity; pub mod repository; @@ -96,13 +96,13 @@ pub use domain_event::{ // Logical projection contracts. Physical read-model lowering deliberately lives // behind adapters and is not part of this semantic surface. -pub use projection::{LocalProjectionMounts, LocalProjectionMountsBuilder, - ProjectionArm, ProjectionAssignment, ProjectionEnvelopeField, ProjectionEventSelector, - ProjectionEventSet, ProjectionExpression, ProjectionField, ProjectionInvalidation, - ProjectionKeyField, ProjectionMutationKind, ProjectionMutationProvenance, - ProjectionObjectValueField, ProjectionOccurrenceProvenance, ProjectionOperation, - ProjectionPartition, ProjectionPlanTemplate, ProjectionProgram, ProjectionProgramError, - ProjectionProgramId, ProjectionProgramLimits, ProjectionRelationship, +pub use projection::{ + LocalProjectionMounts, LocalProjectionMountsBuilder, ProjectionArm, ProjectionAssignment, + ProjectionEnvelopeField, ProjectionEventSelector, ProjectionEventSet, ProjectionExpression, + ProjectionField, ProjectionInvalidation, ProjectionKeyField, ProjectionMutationKind, + ProjectionMutationProvenance, ProjectionObjectValueField, ProjectionOccurrenceProvenance, + ProjectionOperation, ProjectionPartition, ProjectionPlanTemplate, ProjectionProgram, + ProjectionProgramError, ProjectionProgramId, ProjectionProgramLimits, ProjectionRelationship, ProjectionRelationshipEffect, ProjectionRelationshipEffectKind, ProjectionScalarTransform, ProjectionTarget, ProjectionValue, ProjectionValueRef, ProjectionValueType, ResolvedProjectionKey, ResolvedProjectionMutation, ResolvedProjectionMutationScope, @@ -368,10 +368,6 @@ pub use outbox::{ // `DEFAULT_OUTBOX_SOURCE_BATCH`, `DEFAULT_OUTBOX_SOURCE_LEASE`) stay reachable // under `distributed::outbox_worker::*` and are intentionally NOT re-exported // at the crate root. -pub use outbox_worker::{ - BusOutboxPublishHook, BusPublisher, ClaimOutboxMessages, OutboxClaimRef, OutboxDispatchOutcome, - OutboxDispatcher, OutboxPublishFailureAction, OutboxSource, OutboxStore, ReceivedOutboxMessage, -}; #[cfg(any( feature = "http", feature = "grpc", @@ -386,6 +382,10 @@ pub use outbox_worker::{ drain_worker_id, OutboxDrainHandle, OutboxDrainRunner, OutboxPublishMailbox, DEFAULT_OUTBOX_HINT_CAPACITY, }; +pub use outbox_worker::{ + BusOutboxPublishHook, BusPublisher, ClaimOutboxMessages, OutboxClaimRef, OutboxDispatchOutcome, + OutboxDispatcher, OutboxPublishFailureAction, OutboxSource, OutboxStore, ReceivedOutboxMessage, +}; pub use queued_repo::{ // WithOpts + unlock traits for the queued repository variant. @@ -418,12 +418,12 @@ pub use read_model::{ // `distributed::table::*`. pub use table::{ ColumnType, DeleteTableRowMutation, ExpectedVersion, ForeignKey, PatchMode, - PatchTableRowMutation, PrimaryKey, RelationshipDef, RelationshipKind, RowKey, RowPatch, - RowValue, RowValues, RowWriteMode, TableAdapterCapabilities, TableColumn, TableCommitOutcome, - TableIndex, TableKind, TableMigrationArtifact, TableModel, TableMutation, TableRowMutation, - TableSchema, TableSchemaAdapter, TableSchemaAdapterCapabilities, TableSchemaBootstrap, - TableSchemaIssue, TableSchemaIssueKind, TableSchemaRegistry, TableSchemaRegistryExt, - ReadModelCatalog, TableSchemaVerification, TableStoreError, TableWritePlan, + PatchTableRowMutation, PrimaryKey, ReadModelCatalog, RelationshipDef, RelationshipKind, RowKey, + RowPatch, RowValue, RowValues, RowWriteMode, TableAdapterCapabilities, TableColumn, + TableCommitOutcome, TableIndex, TableKind, TableMigrationArtifact, TableModel, TableMutation, + TableRowMutation, TableSchema, TableSchemaAdapter, TableSchemaAdapterCapabilities, + TableSchemaBootstrap, TableSchemaIssue, TableSchemaIssueKind, TableSchemaRegistry, + TableSchemaRegistryExt, TableSchemaVerification, TableStoreError, TableWritePlan, DEFAULT_TABLE_VERSION_COLUMN, }; pub use trace_context::{ @@ -457,9 +457,9 @@ macro_rules! graphql_models { // Session convenience re-exports used by GraphQL permission filters. pub use microsvc::{ - MessageEndpointDescriptor, MetricsEndpointDescriptor, ROLE_KEY, ServiceDescriptor, + MessageEndpointDescriptor, MetricsEndpointDescriptor, ServiceDescriptor, ServiceObservabilityDescriptor, TraceExportMode, TracePropagationMode, TracingDescriptor, - TransportDescriptor, USER_ID_KEY, + TransportDescriptor, ROLE_KEY, USER_ID_KEY, }; // Re-export proc macros. The old event-owning projection proc-macro and diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index 80d15ad53..54c17d96c 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -58,8 +58,8 @@ mod causal; pub mod cell_host; mod context; -mod descriptor; mod dependencies; +mod descriptor; mod error; pub(crate) mod lifecycle; mod message_router; @@ -88,12 +88,12 @@ pub use dependencies::{ CausalRouteDependencies, ConfigurableOutboxPublisher, HasOutboxStore, HasReadModelStore, HasRepo, ReadModelStoreDependencies, RepoDependencies, RepoReadModelDependencies, }; -pub use error::HandlerError; pub use descriptor::{ MessageEndpointDescriptor, MetricsEndpointDescriptor, ServiceDescriptor, ServiceObservabilityDescriptor, TraceExportMode, TracePropagationMode, TracingDescriptor, TransportDescriptor, }; +pub use error::HandlerError; pub use projector::{ CausalProjectorContext, CausalProjectorRouteBuilder, LoadedProjection, ProjectionRepairHandle, ProjectionRepairHandleParseError, @@ -105,6 +105,20 @@ pub use runtime::{DEFAULT_MAX_PUBLISH_ATTEMPTS, DEFAULT_PUBLISH_LEASE}; pub(crate) use service::CausalCommandProjectionEvidence; #[cfg(feature = "graphql")] pub use service::GraphqlServiceBindError; +pub use service::{ + direct_read_model, invoke_transition, require_loaded, CausalCommandContext, + CausalCommitBuilder, CausalRepository, CommandRequest, CommandResponse, DeliveryKind, + DirectReadModelProjection, HandlerNames, HandlerSpec, PortableCommand, PreparedCausalCommit, + PreparedCommandHandler, RouteBuilder, Routes, Service, ThinCommandBuilder, ThinCommandInvoked, + ThinCommandLoaded, TypedRouteBuilder, +}; +#[cfg(feature = "graphql")] +pub(crate) use service::{ + CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandReceiptSource, + CausalProjectionEvidenceState, +}; +#[cfg(feature = "graphql")] +pub use service::{CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult}; #[cfg(any( feature = "http", feature = "grpc", @@ -114,23 +128,7 @@ pub use service::GraphqlServiceBindError; feature = "rabbitmq", feature = "kafka", ))] -pub use workers::{ - spawn_outbox_publish_loop, spawn_service_consumer_loop, CONSUMER_IDLE_POLL, -}; -pub use service::{ - direct_read_model, invoke_transition, require_loaded, CausalCommandContext, CausalCommitBuilder, - CausalRepository, CommandRequest, CommandResponse, DeliveryKind, DirectReadModelProjection, - HandlerNames, HandlerSpec, PortableCommand, PreparedCausalCommit, PreparedCommandHandler, - RouteBuilder, Routes, Service, ThinCommandBuilder, ThinCommandInvoked, ThinCommandLoaded, - TypedRouteBuilder, -}; -#[cfg(feature = "graphql")] -pub use service::{CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult}; -#[cfg(feature = "graphql")] -pub(crate) use service::{ - CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandReceiptSource, - CausalProjectionEvidenceState, -}; +pub use workers::{spawn_outbox_publish_loop, spawn_service_consumer_loop, CONSUMER_IDLE_POLL}; #[cfg(feature = "graphql")] pub(crate) mod wait_path; pub use session::{Session, ROLE_KEY, USER_ID_KEY}; diff --git a/src/microsvc/service/defaults.rs b/src/microsvc/service/defaults.rs index c8a172bf4..6c0e86123 100644 --- a/src/microsvc/service/defaults.rs +++ b/src/microsvc/service/defaults.rs @@ -25,10 +25,7 @@ impl Routes<()> { locks: L, read_models: S, ) -> Routes< - RepoReadModelDependencies< - crate::AggregateRepository, A>, - S, - >, + RepoReadModelDependencies, A>, S>, > where R: crate::GetStream + crate::TransactionalCommit + Clone + Send + Sync + 'static, diff --git a/src/microsvc/service/mod.rs b/src/microsvc/service/mod.rs index 034e187fd..c5cb368c8 100644 --- a/src/microsvc/service/mod.rs +++ b/src/microsvc/service/mod.rs @@ -30,8 +30,8 @@ mod causal; mod defaults; mod handlers; -mod invoke; mod helpers; +mod invoke; mod request; mod routes; mod runtime; @@ -41,12 +41,12 @@ pub(crate) use causal::CausalCommandProjectionEvidence; #[cfg(feature = "graphql")] pub use causal::GraphqlServiceBindError; #[cfg(feature = "graphql")] -pub use causal::{CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult}; -#[cfg(feature = "graphql")] pub(crate) use causal::{ CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandReceiptSource, CausalProjectionEvidenceState, }; +#[cfg(feature = "graphql")] +pub use causal::{CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult}; #[allow(unused_imports)] // public API surface for handler-owned projected commits pub use handlers::StagedProjectedRow; pub use handlers::{ diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 441066dba..00e0ee26a 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -322,10 +322,7 @@ impl Service { /// Register one explicit command mount against the already-installed /// typed route inventory. The route's canonical command spec is the only /// authority; a stale or lookalike mount is rejected before dispatch. - pub fn register_command_mount( - &mut self, - mount: CommandMount, - ) -> Result<(), HandlerError> { + pub fn register_command_mount(&mut self, mount: CommandMount) -> Result<(), HandlerError> { self.register_command_mount_inner(mount) } @@ -359,12 +356,10 @@ impl Service { mount.spec().id ))); } - if !self - .registered_command_mounts - .iter() - .any(|registered| registered.spec().id == mount.spec().id - && registered.spec().fingerprint == mount.spec().fingerprint) - { + if !self.registered_command_mounts.iter().any(|registered| { + registered.spec().id == mount.spec().id + && registered.spec().fingerprint == mount.spec().fingerprint + }) { return Err(HandlerError::Rejected( "command mount was not registered against this service".into(), )); @@ -404,10 +399,7 @@ impl Service { .await } - fn register_command_mount_inner( - &mut self, - mount: CommandMount, - ) -> Result<(), HandlerError> { + fn register_command_mount_inner(&mut self, mount: CommandMount) -> Result<(), HandlerError> { let Some(indices) = self .index .get(&MessageKind::Command) @@ -449,9 +441,11 @@ impl Service { mount.spec().id ))); } - if self.registered_command_mounts.iter().any(|registered| { - registered.spec().id == mount.spec().id - }) { + if self + .registered_command_mounts + .iter() + .any(|registered| registered.spec().id == mount.spec().id) + { return Err(HandlerError::Rejected(format!( "command mount `{}` is registered more than once", mount.spec().id @@ -1192,10 +1186,7 @@ impl Service { } impl CommandMountRegistrar for Service { - fn register_command_mount( - &mut self, - mount: CommandMount, - ) -> Result<(), HandlerError> { + fn register_command_mount(&mut self, mount: CommandMount) -> Result<(), HandlerError> { self.register_command_mount_inner(mount) } } diff --git a/src/projection/mod.rs b/src/projection/mod.rs index 9c287ad3c..6620e0523 100644 --- a/src/projection/mod.rs +++ b/src/projection/mod.rs @@ -19,11 +19,11 @@ mod provenance; // contract before their owning tasks define one. pub mod catalog; pub mod executor; -#[cfg(feature = "graphql")] -pub mod rebuild; pub mod local_mounts; pub mod lower; pub mod placement; +#[cfg(feature = "graphql")] +pub mod rebuild; pub use local_mounts::{ LocalDirectMount, LocalEventualMount, LocalProjectionMounts, LocalProjectionMountsBuilder, diff --git a/src/sqlx_repo/projection_protocol/mod.rs b/src/sqlx_repo/projection_protocol/mod.rs index d9daea29f..b26cf20d9 100644 --- a/src/sqlx_repo/projection_protocol/mod.rs +++ b/src/sqlx_repo/projection_protocol/mod.rs @@ -57,11 +57,11 @@ mod identity; mod locks; mod partitions; mod reads; +#[cfg(feature = "graphql")] +mod rebuild; mod store_impl; mod types; mod writes; -#[cfg(feature = "graphql")] -mod rebuild; use helpers::*; use identity::*; diff --git a/src/table/mod.rs b/src/table/mod.rs index 5b893b541..5533b69ab 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -6,16 +6,16 @@ //! vocabulary. This module owns the canonical types; `read_model` builds its //! typed staging/load surface on top of them. -mod error; mod catalog; +mod error; mod metadata; mod mutation; mod plan; mod registry; mod sql; -pub use error::TableStoreError; pub use catalog::ReadModelCatalog; +pub use error::TableStoreError; pub use metadata::{ ColumnType, ForeignKey, PrimaryKey, RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, TableColumn, TableIndex, TableKind, TableSchema, DEFAULT_TABLE_VERSION_COLUMN, @@ -32,9 +32,9 @@ pub use mutation::{ pub use plan::{TableAdapterCapabilities, TableCommitOutcome, TableWritePlan}; pub use registry::{ resolve_direct_join_keys, resolve_m2m_join_keys, DirectJoinPair, JoinColumnPair, M2mJoinKeys, - TableMigrationArtifact, TableSchemaAdapter, - TableSchemaAdapterCapabilities, TableSchemaBootstrap, TableSchemaIssue, TableSchemaIssueKind, - TableSchemaRegistry, TableSchemaVerification, + TableMigrationArtifact, TableSchemaAdapter, TableSchemaAdapterCapabilities, + TableSchemaBootstrap, TableSchemaIssue, TableSchemaIssueKind, TableSchemaRegistry, + TableSchemaVerification, }; pub use sql::{ bootstrap_result as table_schema_bootstrap_result, generate_table_migration_artifacts, diff --git a/src/table/mutation.rs b/src/table/mutation.rs index 737d7f2d5..adc3633ba 100644 --- a/src/table/mutation.rs +++ b/src/table/mutation.rs @@ -377,7 +377,8 @@ pub(crate) fn has_many_join_columns( relationship.field_name ))); } - let pairs = super::registry::resolve_direct_join_keys(root_schema, relationship, target_schema)?; + let pairs = + super::registry::resolve_direct_join_keys(root_schema, relationship, target_schema)?; match pairs.as_slice() { [pair] => Ok(( pair.foreign_key_column.clone(), diff --git a/tests/application_composition.rs b/tests/application_composition.rs index dc2a783bb..d5b6f0029 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -17,7 +17,9 @@ use distributed::graphql::{ use distributed::projection::{ PROJECTION_OPERATION_SEMANTICS_VERSION, PROJECTION_PROGRAM_IR_VERSION, }; -use distributed::{ApplicationManifest, GraphqlInput, GraphqlOutput, ReadModel, RelationalReadModel}; +use distributed::{ + ApplicationManifest, GraphqlInput, GraphqlOutput, ReadModel, RelationalReadModel, +}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Default, Deserialize, ReadModel, Serialize)] @@ -49,11 +51,8 @@ struct ContractCommandOutput { } fn typed_definition(id: &'static str, roles: &[&str]) -> CommandDefinition { - let command = typed_command::< - ContractCommandInput, - Succeeded, - >(id) - .roles(roles.iter().copied()); + let command = typed_command::>(id) + .roles(roles.iter().copied()); CommandDefinition::from_typed_command(command, None) .expect("typed contract should compile without an executable mount") } @@ -152,14 +151,8 @@ fn selected_surface() -> Surface { .rows(col("status").eq("open")), )]), )]); - surface_for_application_contract( - &full, - "web", - &["user".into()], - &["user".into()], - &grants, - ) - .expect("role/application-selected Surface should compile") + surface_for_application_contract(&full, "web", &["user".into()], &["user".into()], &grants) + .expect("role/application-selected Surface should compile") } #[test] @@ -229,19 +222,19 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere let mut missing = valid.clone(); missing.commands.clear(); missing.contract["commands"] = serde_json::json!([]); - missing.fingerprint = distributed::application::sha256_fingerprint( - &missing.canonical_bytes().unwrap(), - ); + missing.fingerprint = + distributed::application::sha256_fingerprint(&missing.canonical_bytes().unwrap()); let error = Application::try_new("missing-command", [module.clone()], [missing]) .expect_err("missing selected command must fail closed"); - assert!(error.to_string().contains("exact authorized command closure")); + assert!(error + .to_string() + .contains("exact authorized command closure")); let mut tampered = valid.clone(); tampered.commands[0].roles = vec!["admin".into()]; tampered.contract["commands"][0]["roles"] = serde_json::json!(["admin"]); - tampered.fingerprint = distributed::application::sha256_fingerprint( - &tampered.canonical_bytes().unwrap(), - ); + tampered.fingerprint = + distributed::application::sha256_fingerprint(&tampered.canonical_bytes().unwrap()); let error = Application::try_new("tampered-command", [module.clone()], [tampered]) .expect_err("tampered selected command must fail closed"); assert!(error.to_string().contains("not compatible")); @@ -259,18 +252,20 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere let forbidden_contract = admin_spec.contract["commands"][0].clone(); let mut unauthorized = valid; unauthorized.commands.push(forbidden_command.clone()); - unauthorized.commands.sort_by(|left, right| left.id.cmp(&right.id)); unauthorized - .contract["commands"] + .commands + .sort_by(|left, right| left.id.cmp(&right.id)); + unauthorized.contract["commands"] .as_array_mut() .expect("surface command contract array") .push(forbidden_contract.clone()); - unauthorized.fingerprint = distributed::application::sha256_fingerprint( - &unauthorized.canonical_bytes().unwrap(), - ); + unauthorized.fingerprint = + distributed::application::sha256_fingerprint(&unauthorized.canonical_bytes().unwrap()); let error = Application::try_new("unauthorized-command", [module], [unauthorized]) .expect_err("unauthorized selected command must fail closed"); - assert!(error.to_string().contains("exact authorized command closure")); + assert!(error + .to_string() + .contains("exact authorized command closure")); let role_surface = surface_for_role(&catalog, "user", &user_grants).unwrap(); let role_valid = SurfaceSpec::from_surface("user", &role_surface).unwrap(); @@ -280,28 +275,27 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere role_unauthorized .commands .sort_by(|left, right| left.id.cmp(&right.id)); - role_unauthorized - .contract["commands"] + role_unauthorized.contract["commands"] .as_array_mut() .expect("surface command contract array") .push(forbidden_contract); - role_unauthorized.fingerprint = distributed::application::sha256_fingerprint( - &role_unauthorized.canonical_bytes().unwrap(), - ); + role_unauthorized.fingerprint = + distributed::application::sha256_fingerprint(&role_unauthorized.canonical_bytes().unwrap()); let error = Application::try_new( "unauthorized-role-command", [command_module()], [role_unauthorized], ) .expect_err("unauthorized role command must fail closed"); - assert!(error.to_string().contains("exact authorized command closure")); + assert!(error + .to_string() + .contains("exact authorized command closure")); let mut role_tampered = role_valid.clone(); role_tampered.commands[0].roles = vec!["admin".into()]; role_tampered.contract["commands"][0]["roles"] = serde_json::json!(["admin"]); - role_tampered.fingerprint = distributed::application::sha256_fingerprint( - &role_tampered.canonical_bytes().unwrap(), - ); + role_tampered.fingerprint = + distributed::application::sha256_fingerprint(&role_tampered.canonical_bytes().unwrap()); let error = Application::try_new("tampered-role-command", [command_module()], [role_tampered]) .expect_err("tampered role command must fail closed"); assert!(error.to_string().contains("not compatible")); @@ -309,12 +303,13 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere let mut role_missing = role_valid; role_missing.commands.clear(); role_missing.contract["commands"] = serde_json::json!([]); - role_missing.fingerprint = distributed::application::sha256_fingerprint( - &role_missing.canonical_bytes().unwrap(), - ); + role_missing.fingerprint = + distributed::application::sha256_fingerprint(&role_missing.canonical_bytes().unwrap()); let error = Application::try_new("missing-role-command", [command_module()], [role_missing]) .expect_err("role command closure must fail closed"); - assert!(error.to_string().contains("exact authorized command closure")); + assert!(error + .to_string() + .contains("exact authorized command closure")); } #[test] @@ -383,14 +378,19 @@ fn application_manifest_is_byte_deterministic_and_contains_no_executable_data() .unwrap(); assert_eq!(ui["value"]["literal_url"], "https://domain.example/view"); assert_eq!(ui["value"]["literal_path"], "orders/today"); - assert!(!String::from_utf8(first.clone()).unwrap().contains("handler")); + assert!(!String::from_utf8(first.clone()) + .unwrap() + .contains("handler")); assert!(!String::from_utf8(first.clone()) .unwrap() .contains("application_composition")); assert!(ApplicationManifest::from_canonical_bytes(&first).is_ok()); let mut missing_version = value.clone(); - missing_version.as_object_mut().unwrap().remove("schema_version"); + missing_version + .as_object_mut() + .unwrap() + .remove("schema_version"); let missing_version = serde_json::to_vec(&missing_version).unwrap(); assert!(ApplicationManifest::from_canonical_bytes(&missing_version).is_err()); @@ -417,7 +417,13 @@ fn application_manifest_is_byte_deterministic_and_contains_no_executable_data() .to_string() .contains("does not match compiling framework")); - for field in ["tables", "services", "endpoints", "transport", "observability"] { + for field in [ + "tables", + "services", + "endpoints", + "transport", + "observability", + ] { let mut legacy_owner = value.clone(); legacy_owner[field] = serde_json::json!([]); let legacy_owner = serde_json::to_vec(&legacy_owner).unwrap(); @@ -447,23 +453,20 @@ fn manifest_provenance_separates_logical_and_artifact_identity() { assert_ne!(first.fingerprint().unwrap(), second.fingerprint().unwrap()); let decoded = ApplicationManifest::from_canonical_bytes(&first.canonical_bytes().unwrap()).unwrap(); - assert_eq!(decoded.provenance.source_revision.as_deref(), Some("git:one")); - assert!( - String::from_utf8(first.canonical_bytes().unwrap()) - .unwrap() - .contains("git:one") + assert_eq!( + decoded.provenance.source_revision.as_deref(), + Some("git:one") ); + assert!(String::from_utf8(first.canonical_bytes().unwrap()) + .unwrap() + .contains("git:one")); } #[test] fn contract_compiler_pins_manifest_sdl_and_client_to_one_surface() { let selected = selected_surface(); - let compiler = ContractCompiler::from_surface( - "contract-only", - "web", - Arc::new(selected.clone()), - ) - .unwrap(); + let compiler = + ContractCompiler::from_surface("contract-only", "web", Arc::new(selected.clone())).unwrap(); let manifest = compiler.manifest().unwrap(); let sdl = compiler.graphql_sdl().unwrap(); let client = compiler.client_manifest().unwrap(); @@ -471,7 +474,10 @@ fn contract_compiler_pins_manifest_sdl_and_client_to_one_surface() { assert!(sdl.contains("TodoView")); assert_eq!(manifest.surfaces.len(), 1); assert_eq!(manifest.surfaces[0].selection, "application:web"); - assert!(client.models.iter().any(|model| model.typename == "TodoView")); + assert!(client + .models + .iter() + .any(|model| model.typename == "TodoView")); assert!(ContractCompiler::new("contract-only") .with_surface("web", Arc::new(selected)) .unwrap() @@ -506,7 +512,9 @@ fn explicit_definition_mount_identity_and_missing_pairing_fail_closed() { let other = command("todo.other"); let mount = CommandMount::contract(other); let error = CommandDefinition::with_mount(spec, mount).unwrap_err(); - assert!(error.to_string().contains("definition and executable mount")); + assert!(error + .to_string() + .contains("definition and executable mount")); let duplicate = Module::new("todo") .command_definitions([definition("todo.create"), definition("todo.create")]) @@ -535,17 +543,12 @@ fn nested_fingerprints_and_projection_references_are_fail_closed() { ) .is_err()); - let mut projection = ProjectionSpec::try_new( - "todo.list", - std::iter::empty::(), - ["TodoView"], - ) - .unwrap(); + let mut projection = + ProjectionSpec::try_new("todo.list", std::iter::empty::(), ["TodoView"]).unwrap(); projection.dependencies.push("projection:missing".into()); projection.dependencies.sort(); - projection.fingerprint = distributed::application::sha256_fingerprint( - &projection.canonical_bytes().unwrap(), - ); + projection.fingerprint = + distributed::application::sha256_fingerprint(&projection.canonical_bytes().unwrap()); let module = Module::new("todo") .surface( distributed::application::SurfaceSpec::from_surface("web", &selected_surface()) @@ -561,7 +564,8 @@ fn nested_fingerprints_and_projection_references_are_fail_closed() { #[test] fn module_commands_only_keeps_command_identity() { - let projection = ProjectionSpec::try_new("project_todos", ["todo.created"], ["TodoView"]).unwrap(); + let projection = + ProjectionSpec::try_new("project_todos", ["todo.created"], ["TodoView"]).unwrap(); let module = Module::new("todo") .command_definitions([definition("todo.create")]) .projection(projection) @@ -641,8 +645,8 @@ fn runtime_rejects_atomic_with_unrelated_direct_projection() { #[test] fn runtime_from_database_url_rejects_unsupported_schemes() { - let error = Runtime::from_database_url("mysql://localhost/app") - .expect_err("unsupported scheme"); + let error = + Runtime::from_database_url("mysql://localhost/app").expect_err("unsupported scheme"); assert!(error.to_string().contains("unsupported"), "{error}"); } @@ -700,14 +704,9 @@ fn contract_export_prunes_unselected_read_models() { ("ChatView".to_string(), RoleGrant::all_columns()), ]), )]); - let selected = surface_for_application_contract( - &full, - "web", - &["user".into()], - &["user".into()], - &grants, - ) - .unwrap(); + let selected = + surface_for_application_contract(&full, "web", &["user".into()], &["user".into()], &grants) + .unwrap(); let export = DistributedClientSurfaceExport::from_contract("todo-app", selected).unwrap(); let todos_only = prune_client_manifest(export.manifest().unwrap(), ["TodoView"]).unwrap(); assert!(todos_only @@ -754,7 +753,10 @@ fn prune_drops_unselected_command_optimism_and_causal_slots() { attach_todo_and_chat_command_optimism(&mut manifest); let before = serde_json::to_string(&manifest).unwrap(); - assert!(before.contains("ChatView"), "setup must include ChatView optimism"); + assert!( + before.contains("ChatView"), + "setup must include ChatView optimism" + ); assert!(before.contains("TodoView")); let todos_only = prune_client_manifest(manifest, ["TodoView"]).unwrap(); @@ -798,7 +800,9 @@ fn prune_drops_unselected_command_optimism_and_causal_slots() { } } -fn attach_todo_and_chat_command_optimism(manifest: &mut distributed::graphql::DistributedClientManifest) { +fn attach_todo_and_chat_command_optimism( + manifest: &mut distributed::graphql::DistributedClientManifest, +) { let todo_event = ClientProjectionEventRef { id: "todo.completed".into(), name: "todo.completed".into(), @@ -809,14 +813,16 @@ fn attach_todo_and_chat_command_optimism(manifest: &mut distributed::graphql::Di name: "chat.posted".into(), version: 1, }; - manifest.projectors.push(distributed::graphql::ClientProjector { - version: 1, - name: "project_mixed".into(), - facts: vec!["todo.completed".into(), "chat.posted".into()], - models: vec!["TodoView".into(), "ChatView".into()], - dependencies: Vec::new(), - causal_confirmation: false, - }); + manifest + .projectors + .push(distributed::graphql::ClientProjector { + version: 1, + name: "project_mixed".into(), + facts: vec!["todo.completed".into(), "chat.posted".into()], + models: vec!["TodoView".into(), "ChatView".into()], + dependencies: Vec::new(), + causal_confirmation: false, + }); manifest.projection_programs.push(ClientProjectionProgram { version: 2, program_id: "project_todos".into(), @@ -928,10 +934,7 @@ fn explicit_dispatch_route_map() { .unwrap() .graphql() .dispatch_route("todo.*", "http://commands"); - assert_eq!( - runtime.route_for("todo.create"), - Some("http://commands") - ); + assert_eq!(runtime.route_for("todo.create"), Some("http://commands")); assert!(runtime.starts_graphql()); assert!(!runtime.starts_outbox()); } @@ -942,9 +945,8 @@ fn application_surface_must_expose_a_schema_role() { distributed::application::SurfaceSpec::from_surface("web", &selected_surface()).unwrap(); surface.schema_roles.clear(); surface.contract["selection"]["schema_roles"] = serde_json::json!([]); - surface.fingerprint = distributed::application::sha256_fingerprint( - &surface.canonical_bytes().unwrap(), - ); + surface.fingerprint = + distributed::application::sha256_fingerprint(&surface.canonical_bytes().unwrap()); let error = Application::try_new("role-owner", [], [surface]) .expect_err("application surfaces without schema roles must fail closed"); assert!(error.to_string().contains("schema role")); diff --git a/tests/application_plans.rs b/tests/application_plans.rs index 258f92bc3..6a72c1eeb 100644 --- a/tests/application_plans.rs +++ b/tests/application_plans.rs @@ -213,12 +213,10 @@ fn atomic_separation_fails_and_eventual_split_succeeds() { let collocated = compile_deployment_plan( "atomic-local", &manifest, - [ProcessIntent::new("writer") - .unwrap() - .mounts([ - MountSelector::command("todo.force").unwrap(), - MountSelector::projector("project_todos_direct").unwrap(), - ])], + [ProcessIntent::new("writer").unwrap().mounts([ + MountSelector::command("todo.force").unwrap(), + MountSelector::projector("project_todos_direct").unwrap(), + ])], ); assert!(collocated.is_ok(), "{collocated:?}"); } diff --git a/tests/causal_public_invoke/main.rs b/tests/causal_public_invoke/main.rs index 40ab8ff24..d58980ca3 100644 --- a/tests/causal_public_invoke/main.rs +++ b/tests/causal_public_invoke/main.rs @@ -6,8 +6,8 @@ #![cfg(feature = "graphql")] use distributed::graphql::{ - typed_command, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, Succeeded, - VerifiedPrincipal, + typed_command, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, + Succeeded, VerifiedPrincipal, }; use distributed::microsvc::{Routes, Service, Session, USER_ID_KEY}; use distributed::{Aggregate, AggregateBuilder, Entity, InMemoryRepository, Snapshot}; @@ -94,7 +94,9 @@ impl GraphqlOutputType for CompletePayload { async fn public_causal_invoke_returns_receipt_without_sqlx_or_celld() { let routes = Routes::new() .with_repo(InMemoryRepository::new().aggregate::()) - .typed_command(typed_command::>("todo.create")) + .typed_command(typed_command::>( + "todo.create", + )) .create() .invoke(|aggregate, input, _owner| { aggregate.record(input.id.clone())?; @@ -103,9 +105,9 @@ async fn public_causal_invoke_returns_receipt_without_sqlx_or_celld() { .succeeded(|aggregate| CompletePayload { id: aggregate.entity().id().to_string(), }) - .typed_command( - typed_command::>("todo.complete"), - ) + .typed_command(typed_command::>( + "todo.complete", + )) .load_by(|input: &CompleteInput| input.id.clone()) .invoke(|aggregate, input, _owner| { aggregate.record(input.id.clone())?; diff --git a/tests/distributed_read_model/checkout_saga_service/service.rs b/tests/distributed_read_model/checkout_saga_service/service.rs index 43a8d309d..ef1822fba 100644 --- a/tests/distributed_read_model/checkout_saga_service/service.rs +++ b/tests/distributed_read_model/checkout_saga_service/service.rs @@ -5,11 +5,15 @@ use distributed::microsvc::{Routes, Service}; use super::{handlers, CheckoutRepo}; pub fn service(repo: CheckoutRepo) -> Arc { - Arc::new(Service::new().with_http_command_routes().routes(distributed::routes!( - Routes::new().with_repo(repo), - command handlers::start, - event handlers::record_seat_reserved, - ))) + Arc::new( + Service::new() + .with_http_command_routes() + .routes(distributed::routes!( + Routes::new().with_repo(repo), + command handlers::start, + event handlers::record_seat_reserved, + )), + ) } #[cfg(feature = "http")] diff --git a/tests/graphql_harden/authz.rs b/tests/graphql_harden/authz.rs index 9f9348bdd..c4164eaf1 100644 --- a/tests/graphql_harden/authz.rs +++ b/tests/graphql_harden/authz.rs @@ -3,9 +3,7 @@ use async_graphql::Request; use distributed::graphql::{claim, col, read, GraphqlEngine, ModelPermissions}; -use distributed::{ - ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind, -}; +use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; use super::common::{ engine_all_columns, error_messages, exec_json, seed_orders, session, ChildView, OrderView, diff --git a/tests/graphql_harden/dos.rs b/tests/graphql_harden/dos.rs index 09ad199d5..57cf39522 100644 --- a/tests/graphql_harden/dos.rs +++ b/tests/graphql_harden/dos.rs @@ -249,9 +249,7 @@ async fn d7_concurrent_with_timeout_bound_terminates() { async fn d8_nested_has_many_exceeds_complexity_budget() { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; - use distributed::{ - ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind, - }; + use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] @@ -366,9 +364,7 @@ async fn d8_nested_has_many_exceeds_complexity_budget() { async fn d8_shallow_nested_has_many_within_budget() { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; - use distributed::{ - ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind, - }; + use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] @@ -443,9 +439,7 @@ async fn d8_shallow_nested_has_many_within_budget() { async fn d8_low_max_complexity_rejects_single_nest() { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; - use distributed::{ - ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind, - }; + use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] diff --git a/tests/graphql_harden/residual.rs b/tests/graphql_harden/residual.rs index fb8974569..ef41200e4 100644 --- a/tests/graphql_harden/residual.rs +++ b/tests/graphql_harden/residual.rs @@ -2,9 +2,7 @@ use async_graphql::Request; use distributed::graphql::{claim, col, read, GraphqlEngine, ModelPermissions}; -use distributed::{ - ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind, -}; +use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; use super::common::{ assert_no_sql_leak, engine_all_columns, error_messages, extension_code, seed_orders, session, diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 6d856fa1b..9c453cb5e 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -13,7 +13,7 @@ use distributed::microsvc::{ CausalProjectorContext, HandlerError, Routes, Service, Session, ROLE_KEY, }; use distributed::projection_protocol::ProjectionChangeRetention; -use distributed::{ReadModelCatalog, ReadModel, RelationalReadModel, SqliteRepository}; +use distributed::{ReadModel, ReadModelCatalog, RelationalReadModel, SqliteRepository}; use futures_util::{stream::BoxStream, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -596,8 +596,7 @@ async fn embedded_models_emit_index_evidence_without_record_evidence() { let repository = SqliteRepository::connect_and_migrate("sqlite::memory:") .await .expect("migrated embedded SQLite repository"); - let manifest = - ReadModelCatalog::new(EMBEDDED_SERVICE_ID).read_model::(); + let manifest = ReadModelCatalog::new(EMBEDDED_SERVICE_ID).read_model::(); repository .bootstrap_table_schema_for_dev( &manifest diff --git a/tests/graphql_query_protocol_postgres/main.rs b/tests/graphql_query_protocol_postgres/main.rs index c7d7f141f..8b76bda23 100644 --- a/tests/graphql_query_protocol_postgres/main.rs +++ b/tests/graphql_query_protocol_postgres/main.rs @@ -18,7 +18,7 @@ use distributed::microsvc::{ CausalProjectorContext, HandlerError, Routes, Service, Session, ROLE_KEY, }; use distributed::projection_protocol::ProjectionChangeRetention; -use distributed::{ReadModelCatalog, PostgresRepository, ReadModel}; +use distributed::{PostgresRepository, ReadModel, ReadModelCatalog}; use futures_util::{stream::BoxStream, StreamExt}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; diff --git a/tests/graphql_sqlite/main.rs b/tests/graphql_sqlite/main.rs index a599c4475..0785b613f 100644 --- a/tests/graphql_sqlite/main.rs +++ b/tests/graphql_sqlite/main.rs @@ -540,8 +540,7 @@ async fn belongs_to_joins_source_fk_to_target_primary_key() { #[tokio::test] async fn permissions_filter_by_claim() { let schema = orders_schema(); - let manifest = - distributed::ReadModelCatalog::new("orders").table_schema(schema.clone()); + let manifest = distributed::ReadModelCatalog::new("orders").table_schema(schema.clone()); let pool = setup_pool().await; // Value-based path: grant_all then we need typed permission — use builder diff --git a/tests/graphql_subscriptions_sqlite/main.rs b/tests/graphql_subscriptions_sqlite/main.rs index 266cac4b4..53ca427e4 100644 --- a/tests/graphql_subscriptions_sqlite/main.rs +++ b/tests/graphql_subscriptions_sqlite/main.rs @@ -62,8 +62,7 @@ async fn setup_fixed() -> ( let change_rx = repo.read_model_changes(); - let manifest = - distributed::ReadModelCatalog::new("items").table_schema(items_schema()); + let manifest = distributed::ReadModelCatalog::new("items").table_schema(items_schema()); let engine = GraphqlEngine::from_schema_catalog(&manifest, pool.clone()) .unwrap() .roles(&["user"]) diff --git a/tests/metrics_exposition/main.rs b/tests/metrics_exposition/main.rs index c28c48d61..d8cf988ae 100644 --- a/tests/metrics_exposition/main.rs +++ b/tests/metrics_exposition/main.rs @@ -45,12 +45,15 @@ impl MessagePublisher for SelectivePublisher { async fn spawn_http_service(name: &str) -> String { let service = Arc::new( - Service::new().named(name).with_http_command_routes().routes( - Routes::new() - .with_dependencies(()) - .command("orders.create") - .handle(|_ctx: &Context<()>| async move { Ok(json!({"ok": true})) }), - ), + Service::new() + .named(name) + .with_http_command_routes() + .routes( + Routes::new() + .with_dependencies(()) + .command("orders.create") + .handle(|_ctx: &Context<()>| async move { Ok(json!({"ok": true})) }), + ), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); diff --git a/tests/microsvc/transport_http.rs b/tests/microsvc/transport_http.rs index 823fccc2a..e4811c31d 100644 --- a/tests/microsvc/transport_http.rs +++ b/tests/microsvc/transport_http.rs @@ -12,12 +12,16 @@ use crate::handlers; use crate::models::counter::Counter; fn counter_service() -> Arc { - Arc::new(Service::new().with_http_command_routes().routes(distributed::routes!( - Routes::new().with_repo(InMemoryRepository::new().queued().aggregate::()), - command handlers::counter_create, - command handlers::counter_increment, - command handlers::whoami, - ))) + Arc::new( + Service::new() + .with_http_command_routes() + .routes(distributed::routes!( + Routes::new().with_repo(InMemoryRepository::new().queued().aggregate::()), + command handlers::counter_create, + command handlers::counter_increment, + command handlers::whoami, + )), + ) } /// Bind to port 0 and return the actual address. diff --git a/tests/typed_commands/main.rs b/tests/typed_commands/main.rs index f0011eab6..c868a0ad7 100644 --- a/tests/typed_commands/main.rs +++ b/tests/typed_commands/main.rs @@ -37,12 +37,12 @@ use distributed::{ body_bindings_for_model, body_field_binding, command_input_defaults, compile_projection, descriptor_from_factories, inventory_single_model, lower_single_model, resolve_mutation_program, state_upsert_program_for_model, Aggregate, AggregateRepository, - ReadModelCatalog, DomainEventDescriptor, DomainEventOccurrence, Entity, EventRecord, - GraphqlInput, GraphqlOutput, InMemoryRepository, MutationAssignment, MutationEventBinding, - MutationExpression, MutationField, MutationKeyField, MutationKind, MutationOperation, - MutationProgram, MutationProgramError, ProjectionExpression, ProjectionHandler, - ProjectionPartition, ProjectionProgram, ProjectionProgramError, ProjectionValue, - ProjectionValueType, ReadModel, RelationalReadModel, ResolvedProjectionPlan, SqliteRepository, + DomainEventDescriptor, DomainEventOccurrence, Entity, EventRecord, GraphqlInput, GraphqlOutput, + InMemoryRepository, MutationAssignment, MutationEventBinding, MutationExpression, + MutationField, MutationKeyField, MutationKind, MutationOperation, MutationProgram, + MutationProgramError, ProjectionExpression, ProjectionHandler, ProjectionPartition, + ProjectionProgram, ProjectionProgramError, ProjectionValue, ProjectionValueType, ReadModel, + ReadModelCatalog, RelationalReadModel, ResolvedProjectionPlan, SqliteRepository, }; use serde::{Deserialize, Serialize}; use tower::util::ServiceExt; @@ -1628,8 +1628,7 @@ fn pool_free_typed_export_preserves_service_provenance_and_rejects_relabeling() assert_eq!(manifest.service_id, "plans"); assert_eq!(manifest.commands[0].name, "plan.create"); - let error = DistributedClientSurfaceExport::from_selected("other-plans", selected) - .unwrap_err(); + let error = DistributedClientSurfaceExport::from_selected("other-plans", selected).unwrap_err(); assert!(error .to_string() .contains("does not match typed Surface provenance")); From f153288152e2691fb57641249e9bfc04ba8aa2a0 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 16:44:49 -0500 Subject: [PATCH 006/484] test: verify projection completion before reload persistence Update migration-five integration expectations and distinguish eventual projection completion from fresh SSR visibility. Preserve command receipts, process membership, and durable browser proof. Refs: incidents/distributed-pr226-ci --- .github/workflows/integration-e2e-ui.yaml | 1 + distributed_cli/src/contracts/tests.rs | 2 +- tests/e2e-ui/package.json | 2 +- .../scripts/lifecycle-command-proof.mjs | 22 ++++++++++++ .../scripts/lifecycle-command-proof.test.mjs | 35 +++++++++++++++++++ tests/e2e-ui/scripts/lifecycle-reload.mjs | 32 ++++++++++++++++- tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 8 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 tests/e2e-ui/scripts/lifecycle-command-proof.mjs create mode 100644 tests/e2e-ui/scripts/lifecycle-command-proof.test.mjs diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index 3b3567301..8e403824c 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -158,6 +158,7 @@ jobs: path: | tests/e2e-ui/playwright-report tests/e2e-ui/test-results + tests/e2e-ui/.distributed-dev.log if-no-files-found: ignore retention-days: 7 diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 9c2bb4538..d86419575 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4]); + assert_eq!(versions, vec![1, 2, 3, 4, 5]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/tests/e2e-ui/package.json b/tests/e2e-ui/package.json index 9b0f3b3c5..6b1d08ac5 100644 --- a/tests/e2e-ui/package.json +++ b/tests/e2e-ui/package.json @@ -4,7 +4,7 @@ "type": "module", "scripts": { "test:browser": "playwright test", - "test:lifecycle-reload": "node scripts/lifecycle-reload.mjs", + "test:lifecycle-reload": "node --test scripts/lifecycle-command-proof.test.mjs && node scripts/lifecycle-reload.mjs", "test:browser:ui": "playwright test --ui", "test:browser:headed": "playwright test --headed", "test:browser:report": "playwright show-report" diff --git a/tests/e2e-ui/scripts/lifecycle-command-proof.mjs b/tests/e2e-ui/scripts/lifecycle-command-proof.mjs new file mode 100644 index 000000000..89312cf18 --- /dev/null +++ b/tests/e2e-ui/scripts/lifecycle-command-proof.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { setTimeout as delay } from 'node:timers/promises'; + +// Eventual command receipts prove the aggregate commit, not projector completion. +// Query outside the browser replica before asking a fresh SSR page to prove it. +export async function waitForProjectedTodo(query, expected, timeoutMs = 120_000) { + const deadline = Date.now() + timeoutMs; + let attempts = 0; + while (Date.now() < deadline) { + const body = await query(Math.max(1, deadline - Date.now())); + attempts += 1; + assert.ok(!body.errors?.length, 'authoritative Todo query must not return GraphQL errors'); + assert.ok(Array.isArray(body.data?.todos), 'authoritative Todo query must return rows'); + const row = body.data.todos.find((todo) => todo.todo_id === expected.todo_id); + if (row) { + assert.deepEqual(row, expected, 'projected Todo must match the committed command payload'); + return attempts; + } + await delay(Math.min(50, Math.max(0, deadline - Date.now()))); + } + throw new Error(`Todo ${expected.todo_id} was accepted but not projected after ${attempts} queries`); +} diff --git a/tests/e2e-ui/scripts/lifecycle-command-proof.test.mjs b/tests/e2e-ui/scripts/lifecycle-command-proof.test.mjs new file mode 100644 index 000000000..5f0ed78c3 --- /dev/null +++ b/tests/e2e-ui/scripts/lifecycle-command-proof.test.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { waitForProjectedTodo } from './lifecycle-command-proof.mjs'; + +const todo = { todo_id: 'proof-1', owner_id: 'alice', title: 'Persisted', status: 'open' }; + +test('an empty SSR-era read is retried until the exact authoritative row exists', async () => { + let calls = 0; + const attempts = await waitForProjectedTodo(async () => ({ + data: { todos: ++calls < 3 ? [] : [todo] } + }), todo); + assert.equal(attempts, 3); +}); + +test('matching title on another aggregate does not prove this command', async () => { + await assert.rejects(waitForProjectedTodo(async () => ({ + data: { todos: [{ ...todo, todo_id: 'other' }] } + }), todo, 20), /accepted but not projected/); +}); + +test('a stalled projector fails instead of falling back to the receipt or optimism', async () => { + await assert.rejects(waitForProjectedTodo(async () => ({ data: { todos: [] } }), todo, 20), + /accepted but not projected/); +}); + +test('a wrong persisted value fails rather than merely checking row presence', async () => { + await assert.rejects(waitForProjectedTodo(async () => ({ + data: { todos: [{ ...todo, title: 'Wrong' }] } + }), todo), /must match the committed command payload/); +}); + +test('GraphQL failures are not retried as eventual projection lag', async () => { + await assert.rejects(waitForProjectedTodo(async () => ({ errors: [{ message: 'Denied' }] }), todo), + /must not return GraphQL errors/); +}); diff --git a/tests/e2e-ui/scripts/lifecycle-reload.mjs b/tests/e2e-ui/scripts/lifecycle-reload.mjs index dd5a9de79..78f01799c 100644 --- a/tests/e2e-ui/scripts/lifecycle-reload.mjs +++ b/tests/e2e-ui/scripts/lifecycle-reload.mjs @@ -4,6 +4,7 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { chromium } from 'playwright'; +import { waitForProjectedTodo } from './lifecycle-command-proof.mjs'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const frameworkRoot = resolve(root, '../../js'); @@ -244,9 +245,38 @@ async function transition(page, path, source, expectedReplicaRestore, assertGate assert.equal(body.extensions.distributed.generation.generationId, after.active.generationId); assert.equal(body.extensions.distributed.generation.releaseId, after.active.releaseId); assert.ok(body.extensions.distributed.command, 'actual command receipt required'); - // Discard browser optimism and confirm the persisted read model on a new page. + const todo = body.data.todos_create; + assert.equal(todo.title, title); + assert.equal(typeof todo.todo_id, 'string'); + const requestHeaders = await mutation.request().allHeaders(); + const headers = Object.fromEntries( + ['authorization', 'x-user-id', 'x-roles'] + .filter((name) => requestHeaders[name] !== undefined) + .map((name) => [name, requestHeaders[name]]) + ); + const attempts = await waitForProjectedTodo(async (remainingMs) => { + const result = await page.request.post(mutation.url(), { + headers, + timeout: remainingMs, + data: { + query: `query ReloadTodoProof($id: String!) { + todos(where: { todo_id: { _eq: $id } }, limit: 1) { + todo_id owner_id title status + } + }`, + variables: { id: todo.todo_id } + } + }); + assert.equal(result.status(), 200, 'authoritative Todo query must succeed'); + return result.json(); + }, todo, timeoutMs); + console.log(`lifecycle-reload: ${relative(root, path)} command accepted and projected (${attempts} queries)`); + // @load is not @live. Reloading before projection can seed an empty result + // that never changes, even though the projector subsequently commits the row. + // Now discard browser optimism and prove fresh SSR + hydration independently. await page.reload({waitUntil: 'domcontentloaded'}); await page.locator('[data-todo-id]').filter({hasText: title}).waitFor({timeout: timeoutMs}); + console.log(`lifecycle-reload: ${relative(root, path)} fresh page confirmed ${todo.todo_id}`); await waitFor(() => page.evaluate(() => globalThis.__distributedReloadState !== undefined), 'hydration after command proof'); await page.evaluate(() => { globalThis.__distributedReloadState.value = 'preserve-me'; }); await waitForBrowserParticipant(page); diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index 02c732b7d..858dc1314 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 4); + assert_eq!(latest_version, 5); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 3a288f293..af0cb0e9d 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 4); + assert_eq!(latest_version, 5); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From 99d5b797630d1f974c57636ea3de30b50e23f41c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 17:00:47 -0500 Subject: [PATCH 007/484] ci: exercise snapshot fencing and durable NATS recovery Run the live adapter cases explicitly and retain lifecycle diagnostics. Document the eventual projection barrier used by the browser reload proof. Refs: incidents/distributed-pr226-ci --- .github/workflows/integration-e2e-ui.yaml | 2 ++ .github/workflows/integration-nats.yaml | 4 ++++ .github/workflows/integration-postgres.yaml | 9 +++++++++ tests/e2e-ui/README.md | 9 +++++++++ 4 files changed, 24 insertions(+) diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index 8e403824c..fb7899f19 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -155,6 +155,8 @@ jobs: uses: actions/upload-artifact@v4 with: name: e2e-ui-playwright-report + # Only the explicit paths below; never include e2e/.auth or env files. + include-hidden-files: true path: | tests/e2e-ui/playwright-report tests/e2e-ui/test-results diff --git a/.github/workflows/integration-nats.yaml b/.github/workflows/integration-nats.yaml index 7385a4b92..951e3025f 100644 --- a/.github/workflows/integration-nats.yaml +++ b/.github/workflows/integration-nats.yaml @@ -30,3 +30,7 @@ jobs: done - name: Run NATS transport integration tests run: cargo test --test nats_transport --features nats --verbose + - name: Verify retained history and durable filter reconciliation + env: + DISTRIBUTED_ARCHIVE_TEST_NATS_URL: nats://localhost:4222 + run: cargo test --lib --features nats bus::nats_bus::archive_tests -- --include-ignored diff --git a/.github/workflows/integration-postgres.yaml b/.github/workflows/integration-postgres.yaml index 0dac77468..a7eb33c0f 100644 --- a/.github/workflows/integration-postgres.yaml +++ b/.github/workflows/integration-postgres.yaml @@ -44,3 +44,12 @@ jobs: cargo test --test postgres_transport --no-default-features --features postgres --verbose cargo test --test distributed_read_model --no-default-features --features postgres --verbose cargo test --test sql_lock_manager --no-default-features --features postgres --verbose + - name: Verify source fencing and snapshot rebuild against PostgreSQL + env: + DISTRIBUTED_SNAPSHOT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:5432/distributed_snapshots + DISTRIBUTED_REBUILD_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:5432/distributed_rebuild + run: | + docker exec ${{ job.services.postgres.id }} createdb -U postgres distributed_snapshots + docker exec ${{ job.services.postgres.id }} createdb -U postgres distributed_rebuild + cargo test --lib --no-default-features --features graphql,postgres projection::source_snapshot_tests::source_snapshots_postgres_reordering_and_restart -- --exact + cargo test --lib --no-default-features --features graphql,postgres projection::source_snapshot_tests::snapshot_rebuild_postgres -- --exact diff --git a/tests/e2e-ui/README.md b/tests/e2e-ui/README.md index a87a08185..0dba81318 100644 --- a/tests/e2e-ui/README.md +++ b/tests/e2e-ui/README.md @@ -80,6 +80,15 @@ transition, browser rejection before GraphQL dispatch, direct API rejection while generations disagree, URL/app-state retention, compatible replica restoration, and incompatible replica revalidation. +The same proof covers two consecutive UI-only edits retaining the API process. +After each transition it submits a real Todo command, checks the command receipt +and active generation, waits for the exact persisted row through GraphQL, then +reloads the page and checks its rendered data independently of browser optimism. +Todo creation is Eventual: its receipt is not a projection-completion barrier. +Because the Todos query is `@load`, not `@live`, an immediate reload can capture +pre-projection data that will not update by itself. The test therefore waits on +authoritative data, not a fixed sleep or a longer DOM timeout. + This is the **default one-process playground**. Optional celld: ```bash From f93d9854172b03b782d18d2039a0fa9998be806a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 30 Aug 2026 20:56:03 -0500 Subject: [PATCH 008/484] fix: align surface and manifest size limits (cherry picked from commit 97003f3cce5aa073d39dd3d8126232968e79ef3c) --- src/application/manifest.rs | 61 +++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/src/application/manifest.rs b/src/application/manifest.rs index a609859f4..c0fdd09e0 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -11,10 +11,16 @@ use super::module::{ModelSpec, Module, ModuleManifest, ProjectionSpec, SurfaceSp pub const APPLICATION_MANIFEST_SCHEMA_VERSION: u32 = 1; /// Bounds applied before a portable application artifact is accepted. -pub const MAX_APPLICATION_MANIFEST_BYTES: usize = 1024 * 1024; +/// +/// A complete manifest intentionally carries authoritative module declarations, +/// their flattened application inventory, and selected Surface contracts. Keep +/// the total bounded while leaving room for a production-sized application. +pub const MAX_APPLICATION_MANIFEST_BYTES: usize = 4 * 1024 * 1024; pub const MAX_MANIFEST_COLLECTION_ITEMS: usize = 4096; pub const MAX_MANIFEST_STRING_BYTES: usize = 4096; -pub const MAX_MANIFEST_JSON_BYTES: usize = 256 * 1024; +/// Per-value JSON bound. Several independently bounded contracts may comprise +/// one application manifest, but no opaque value receives the whole budget. +pub const MAX_MANIFEST_JSON_BYTES: usize = 1024 * 1024; pub const MAX_MANIFEST_JSON_DEPTH: usize = 32; /// Reserved manifest extension carrying the framework release that compiled it. pub const FRAMEWORK_COMPATIBILITY_EXTENSION_ID: &str = "distributed.framework"; @@ -2002,3 +2008,54 @@ fn validate_sorted_unique(kind: &'static str, identities: &[String]) -> Applicat } Ok(()) } + +#[cfg(test)] +mod size_limit_tests { + use super::*; + + #[test] + fn json_contract_can_exceed_the_old_256_kib_limit() { + let chunk = "x".repeat(MAX_MANIFEST_STRING_BYTES); + let within_budget = serde_json::json!(vec![chunk.clone(); 96]); + assert!(serde_json::to_vec(&within_budget).unwrap().len() > 256 * 1024); + validate_json_contract("surface canonical contract", &within_budget).unwrap(); + + let over_budget = serde_json::json!(vec![chunk; 257]); + assert!(serde_json::to_vec(&over_budget).unwrap().len() > MAX_MANIFEST_JSON_BYTES); + assert!(validate_json_contract("surface canonical contract", &over_budget).is_err()); + } + + #[test] + fn manifest_accepts_multiple_bounded_contracts_beyond_one_mib() { + let value = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 200]); + assert!(serde_json::to_vec(&value).unwrap().len() < MAX_MANIFEST_JSON_BYTES); + let mut manifest = ApplicationManifest::new("large-app"); + for index in 0..2 { + manifest.extensions.push( + ApplicationExtension::try_new(format!("large.contract.{index}"), 1, value.clone()) + .unwrap(), + ); + } + + let bytes = manifest.canonical_bytes().unwrap(); + assert!(bytes.len() > 1024 * 1024); + assert!(bytes.len() < MAX_APPLICATION_MANIFEST_BYTES); + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(); + } + + #[test] + fn manifest_rejects_multiple_contracts_beyond_four_mib() { + let value = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 230]); + assert!(serde_json::to_vec(&value).unwrap().len() < MAX_MANIFEST_JSON_BYTES); + let mut manifest = ApplicationManifest::new("oversized-app"); + for index in 0..5 { + manifest.extensions.push( + ApplicationExtension::try_new(format!("large.contract.{index}"), 1, value.clone()) + .unwrap(), + ); + } + + let error = manifest.canonical_bytes().unwrap_err().to_string(); + assert!(error.contains("application manifest exceeds 4194304 bytes")); + } +} From fc11e4320f423acb63a96825cd315de20bd14260 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 30 Aug 2026 21:12:37 -0500 Subject: [PATCH 009/484] feat: assemble applications from typed services (cherry picked from commit d843e828d9ffdf5d34a02b75a1b1057abafe49f4) --- src/microsvc/service/runtime.rs | 59 ++++++++++++++++++++++++++++++++- src/microsvc/service/tests.rs | 51 ++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 00e0ee26a..569d975af 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -18,7 +18,10 @@ use super::helpers::{ use super::helpers::{microsvc_dispatch_span, microsvc_handler_span}; use super::request::{CommandRequest, CommandResponse}; use super::routes::{CausalCommandPolicy, DynBusPublisher, ErasedRoutes, HandlerSpec, Routes}; -use crate::application::{CommandMount, CommandMountRegistrar, CommandSpec}; +use crate::application::{ + Application, ApplicationError, ApplicationResult, CommandDefinition, CommandMount, + CommandMountRegistrar, CommandSpec, Module, SurfaceSpec, +}; use crate::bus::{ Message, MessageKind, OrderedDelivery, RunOptions, SubscriptionPlan, TransportError, }; @@ -586,6 +589,60 @@ impl Service { Ok(specs) } + /// Compile this Service's typed command inventory and an authorized Surface + /// into one logical application. + /// + /// Command namespaces (the segment before the first `.`) become modules. + /// Every Service command must exist in the Surface so its authorization and + /// projection contract can be bound, and application validation rejects any + /// Surface command that is not owned by the Service. + pub fn application( + &self, + name: impl Into, + surface: SurfaceSpec, + ) -> ApplicationResult { + let mut modules = BTreeMap::>::new(); + for command in self.command_specs()? { + let namespace = command + .id + .split_once('.') + .map(|(namespace, _)| namespace) + .filter(|namespace| !namespace.is_empty()) + .ok_or_else(|| { + ApplicationError::InvalidSpec(format!( + "typed command `{}` has no module namespace; expected `.`", + command.id + )) + })? + .to_string(); + let exposed = surface + .commands + .iter() + .find(|exposed| exposed.id == command.id) + .ok_or_else(|| ApplicationError::Missing { + kind: "surface command", + identity: command.id.clone(), + })?; + let command = command.with_surface_binding(exposed)?; + modules + .entry(namespace) + .or_default() + .push(CommandDefinition::contract(command)); + } + + let modules = modules + .into_iter() + .map(|(namespace, commands)| { + Module::new(namespace).command_definitions(commands).build() + }) + .collect::>>()?; + + Application::new(name) + .modules(modules) + .surface(surface) + .build() + } + /// Attach Eventual projection metadata to a cell wait-path result using this /// process's command contract (no second aggregate write). #[cfg(feature = "graphql")] diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 7cf9340b6..b11f54b7f 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -1085,6 +1085,57 @@ fn named_service_preserves_identity_with_route_bundles() { ); } +#[cfg(feature = "graphql")] +#[test] +fn service_compiles_exact_application_modules_from_command_namespaces() { + let repository = InMemoryRepository::new(); + let service = Service::new().named("catalog").routes( + Routes::new() + .with_repo(repository.queued().aggregate::()) + .typed_command( + typed_command::>("access.grant") + .roles(["user"]), + ) + .handle(typed_handler) + .typed_command( + typed_command::>("repository.create") + .roles(["user"]), + ) + .handle(typed_handler), + ); + let surface = crate::graphql::build_surface( + &[], + &crate::graphql::SurfaceOptions::sqlite(), + ) + .expect("empty read-model Surface should build") + .with_service(&service) + .expect("typed Service should bind to the Surface"); + let surface = crate::application::SurfaceSpec::from_surface("catalog", &surface) + .expect("Surface should become a portable application contract"); + + let application = service + .application("catalog", surface) + .expect("Service and Surface should compile into one application"); + + assert_eq!( + application + .modules() + .iter() + .map(crate::application::Module::id) + .collect::>(), + ["access", "repository"] + ); + assert_eq!( + application + .manifest() + .commands + .iter() + .map(|command| command.id.as_str()) + .collect::>(), + ["access.grant", "repository.create"] + ); +} + #[tokio::test] async fn typed_direct_dispatch_fails_before_invoking_handler() { TYPED_HANDLER_INVOKED.store(false, Ordering::SeqCst); From 68abd4c2d2bc0ad459a0760dd1ccb99d4efc3930 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 30 Aug 2026 22:22:06 -0500 Subject: [PATCH 010/484] fix: preserve NATS event content types (cherry picked from commit d864fa931ea132c5d00982cbbfdd634484cdf07b) --- src/bus/message.rs | 23 +++++++++++++++++++++-- src/bus/nats.rs | 24 ++++++++++++++++++++---- tests/nats_transport/main.rs | 4 ++++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/bus/message.rs b/src/bus/message.rs index 45bc33bfa..1edf4cdae 100644 --- a/src/bus/message.rs +++ b/src/bus/message.rs @@ -218,9 +218,9 @@ pub(crate) fn message_from_wire( let mut kind = MessageKind::Event; let mut metadata = Vec::new(); for (key, value) in headers { - if id_key == Some(key.as_str()) { + if id_key.is_some_and(|id_key| key.eq_ignore_ascii_case(id_key)) { id = Some(value); - } else if key == kind_key { + } else if key.eq_ignore_ascii_case(kind_key) { kind = MessageKind::from_str_lossy(&value); } else { metadata.push((key, value)); @@ -292,4 +292,23 @@ mod tests { 1 ); } + + #[cfg(any(feature = "nats", feature = "kafka", feature = "rabbitmq"))] + #[test] + fn wire_reserved_headers_are_case_insensitive() { + let message = message_from_wire( + "checkout.started".into(), + Vec::new(), + Some("Nats-Msg-Id"), + "X-Sourced-Kind", + [ + ("nats-msg-id".into(), "event-1".into()), + ("x-sourced-kind".into(), "command".into()), + ], + ); + + assert_eq!(message.id(), Some("event-1")); + assert_eq!(message.kind, MessageKind::Command); + assert!(message.metadata.is_empty()); + } } diff --git a/src/bus/nats.rs b/src/bus/nats.rs index 554c2d349..563853662 100644 --- a/src/bus/nats.rs +++ b/src/bus/nats.rs @@ -28,6 +28,8 @@ use super::{retryable, MessagePublisher, TransportError}; const MESSAGE_ID_HEADER: &str = "Nats-Msg-Id"; /// Header carrying the canonical message kind. const MESSAGE_KIND_HEADER: &str = "X-Sourced-Kind"; +/// Header carrying the canonical payload media type. +const CONTENT_TYPE_HEADER: &str = "Content-Type"; /// Publishes canonical messages to a NATS JetStream subject. /// @@ -75,13 +77,20 @@ impl MessagePublisher for NatsPublisher { async fn publish(&self, mut message: Message) -> Result<(), TransportError> { let subject = self.subject(&message); let mut headers = async_nats::HeaderMap::new(); + for (key, value) in &message.metadata { + if [MESSAGE_ID_HEADER, MESSAGE_KIND_HEADER, CONTENT_TYPE_HEADER] + .iter() + .any(|reserved| key.eq_ignore_ascii_case(reserved)) + { + continue; + } + headers.insert(key.as_str(), value.as_str()); + } if let Some(id) = message.id() { headers.insert(MESSAGE_ID_HEADER, id); } headers.insert(MESSAGE_KIND_HEADER, message.kind.as_str()); - for (key, value) in &message.metadata { - headers.insert(key.as_str(), value.as_str()); - } + headers.insert(CONTENT_TYPE_HEADER, message.content_type.as_str()); // `message` is owned and dropped here, so move its payload out instead of // cloning. `Bytes::from(Vec)` takes ownership of the buffer (no copy). @@ -243,13 +252,20 @@ impl NatsReceived { .map(|value| (key.to_string(), value.to_string())) }) .collect(); - let message = message_from_wire( + let mut message = message_from_wire( name, payload, Some(MESSAGE_ID_HEADER), MESSAGE_KIND_HEADER, headers, ); + if let Some(index) = message + .metadata + .iter() + .position(|(key, _)| key.eq_ignore_ascii_case(CONTENT_TYPE_HEADER)) + { + message.content_type = message.metadata.remove(index).1; + } let ordered = jetstream_ordered(&raw); Self { raw, diff --git a/tests/nats_transport/main.rs b/tests/nats_transport/main.rs index d434fa95f..4ba7d937a 100644 --- a/tests/nats_transport/main.rs +++ b/tests/nats_transport/main.rs @@ -105,6 +105,8 @@ async fn message_id_and_metadata_survive_the_round_trip() { TRACEPARENT, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", ); + let mut message = message; + message.content_type = "application/vnd.example+binary".into(); publisher.publish(message).await.expect("publish"); let observed = Arc::new(Mutex::new(None)); @@ -121,6 +123,7 @@ async fn message_id_and_metadata_survive_the_round_trip() { m.correlation_id().map(str::to_string), m.traceparent().map(str::to_string), m.payload().to_vec(), + m.content_type.clone(), )); *o.lock().unwrap() = recorded; async move { Ok(json!({})) } @@ -139,6 +142,7 @@ async fn message_id_and_metadata_survive_the_round_trip() { Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") ); assert_eq!(got.3, br#"{"k":"v"}"#.to_vec()); + assert_eq!(got.4, "application/vnd.example+binary"); } /// Build a namespaced `NatsBus` for `group` (empty `group` = no group), with From b0b9c7cc9e8b91fac9cbb39ec76d92d2aca72289 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 30 Aug 2026 22:22:06 -0500 Subject: [PATCH 011/484] feat: propagate handler causation (cherry picked from commit 475f1ba61582885d5f726500f70ab296416529c9) --- src/microsvc/context.rs | 84 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/src/microsvc/context.rs b/src/microsvc/context.rs index 4737390f4..c3ccefa96 100644 --- a/src/microsvc/context.rs +++ b/src/microsvc/context.rs @@ -11,6 +11,7 @@ use super::dependencies::{HasReadModelStore, HasRepo}; use super::error::HandlerError; use super::session::Session; use crate::bus::Message; +use crate::Aggregate; /// The context passed to every handler. /// @@ -82,6 +83,22 @@ impl<'a, D> Context<'a, D> { self.message } + /// Carry the current message's causal command identity into events emitted + /// by a downstream aggregate. + /// + /// Event-driven policies should call this before invoking aggregate + /// transitions. Captured and explicitly published domain events then retain + /// the same causal projection qualification as the event being handled. + pub fn inherit_causation(&self, aggregate: &mut A) -> Result<(), HandlerError> { + let causation_id = self.message.causation_id().ok_or_else(|| { + HandlerError::DecodeFailed( + "causal event handler input is missing a causation ID".into(), + ) + })?; + aggregate.entity_mut().set_causation_id(causation_id); + Ok(()) + } + /// Get the session. pub fn session(&self) -> &Session { &self.session @@ -130,3 +147,70 @@ impl<'a, D> Context<'a, D> { fields.iter().all(|f| self.has_field(f)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::bus::MessageKind; + use crate::trace_context::CAUSATION_ID; + use crate::{Entity, EventRecord}; + + #[derive(Default)] + struct DownstreamAggregate { + entity: Entity, + } + + impl Aggregate for DownstreamAggregate { + type ReplayError = String; + + fn entity(&self) -> &Entity { + &self.entity + } + + fn entity_mut(&mut self) -> &mut Entity { + &mut self.entity + } + + fn replay_event(&mut self, _event: &EventRecord) -> Result<(), Self::ReplayError> { + Ok(()) + } + } + + #[test] + fn handler_context_propagates_causation_to_new_events() { + let message = Message::new("source.event", MessageKind::Event, b"{}".to_vec()) + .with_metadata(CAUSATION_ID, "cause-1"); + let dependencies = (); + let context = Context::new( + &message, + Value::Object(Default::default()), + Session::new(), + &dependencies, + ); + let mut aggregate = DownstreamAggregate::default(); + + context.inherit_causation(&mut aggregate).unwrap(); + aggregate + .entity + .digest_empty("downstream.recorded") + .unwrap(); + + assert_eq!(aggregate.entity.events()[0].causation_id(), Some("cause-1")); + } + + #[test] + fn handler_context_rejects_missing_causation() { + let message = Message::new("source.event", MessageKind::Event, b"{}".to_vec()); + let dependencies = (); + let context = Context::new( + &message, + Value::Object(Default::default()), + Session::new(), + &dependencies, + ); + let mut aggregate = DownstreamAggregate::default(); + + assert!(context.inherit_causation(&mut aggregate).is_err()); + assert!(aggregate.entity.events().is_empty()); + } +} From 5ccccaa426ee3af18bd83f875dc5e4d3a8d13a53 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 31 Aug 2026 00:14:28 -0500 Subject: [PATCH 012/484] fix: strip duplicate NATS content-type metadata (cherry picked from commit ef8b4ff5d5fe1a1129e07f5285a20ab34b03cc23) --- src/bus/nats.rs | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/src/bus/nats.rs b/src/bus/nats.rs index 563853662..f18b72a30 100644 --- a/src/bus/nats.rs +++ b/src/bus/nats.rs @@ -259,13 +259,7 @@ impl NatsReceived { MESSAGE_KIND_HEADER, headers, ); - if let Some(index) = message - .metadata - .iter() - .position(|(key, _)| key.eq_ignore_ascii_case(CONTENT_TYPE_HEADER)) - { - message.content_type = message.metadata.remove(index).1; - } + take_content_type(&mut message); let ordered = jetstream_ordered(&raw); Self { raw, @@ -290,6 +284,25 @@ impl NatsReceived { } } +/// Select the first inbound content type and remove every reserved spelling +/// from user-visible metadata. +fn take_content_type(message: &mut Message) { + let mut content_type = None; + message.metadata.retain(|(key, value)| { + if key.eq_ignore_ascii_case(CONTENT_TYPE_HEADER) { + if content_type.is_none() { + content_type = Some(value.clone()); + } + false + } else { + true + } + }); + if let Some(content_type) = content_type { + message.content_type = content_type; + } +} + fn jetstream_ordered(raw: &jetstream::Message) -> Option { let info = raw.info().ok()?; let source = ProjectionSource::new("nats.jetstream", info.stream.as_bytes()).ok()?; @@ -325,3 +338,25 @@ impl ReceivedMessage for NatsReceived { self.settle(AckKind::Term).await } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::bus::MessageKind; + + #[test] + fn content_type_selection_removes_every_case_variant() { + let mut message = Message::new("example.recorded", MessageKind::Event, Vec::new()) + .with_metadata("Content-Type", "application/vnd.example+binary") + .with_metadata("x-correlation-id", "corr-1") + .with_metadata("content-type", "application/json"); + + take_content_type(&mut message); + + assert_eq!(message.content_type, "application/vnd.example+binary"); + assert_eq!( + message.metadata, + vec![("x-correlation-id".into(), "corr-1".into())] + ); + } +} From 56f2f85a54f0f91f2d11dc2b01574fc66ce14056 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 17:21:46 -0500 Subject: [PATCH 013/484] test: validate consolidated typed application assembly Documents the APIs carried from #217 and checks missing and unowned surface commands. --- README.md | 28 ++++++++++++++++++++++++++++ src/microsvc/service/tests.rs | 30 ++++++++++++++++++++---------- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 74acfbbdd..c63f202d2 100644 --- a/README.md +++ b/README.md @@ -2191,6 +2191,34 @@ a smaller target: model fields, event methods, handler bodies, and projection shapes. Boilerplate service setup, manifest discovery, schema output, and GitOps artifacts stay deterministic. +For an existing typed `Service`, derive the logical application from its command +inventory and the same full GraphQL `Surface` used by the runtime: + +```rust,ignore +let surface = distributed::SurfaceSpec::from_surface("catalog", &full_surface)?; +let application = service.application("catalog", surface)?; +let manifest = application.manifest(); +``` + +Command namespaces such as `orders.submit` supply module names; there is no +second module list to maintain. Assembly rejects commands missing from the +Surface or exposed by the Surface without a Service owner. Role-selected client +exports remain authorization views of that full contract. Complete application +manifests are bounded at 4 MiB; each opaque JSON contract remains bounded at +1 MiB, with the existing collection, string and nesting limits still enforced. + +An event-driven policy that emits through another aggregate can explicitly carry +the incoming command's causal identity before recording its events: + +```rust,ignore +ctx.inherit_causation(&mut downstream)?; +downstream.record(observation)?; +``` + +This requires an incoming causation ID and does not manufacture one for external +events. NATS preserves the message's payload content type and keeps reserved +transport headers out of user metadata across delivery. + ```bash cargo install distributed_cli # installs `distributed` diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index b11f54b7f..0bc0ac633 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -1093,8 +1093,7 @@ fn service_compiles_exact_application_modules_from_command_namespaces() { Routes::new() .with_repo(repository.queued().aggregate::()) .typed_command( - typed_command::>("access.grant") - .roles(["user"]), + typed_command::>("access.grant").roles(["user"]), ) .handle(typed_handler) .typed_command( @@ -1103,18 +1102,15 @@ fn service_compiles_exact_application_modules_from_command_namespaces() { ) .handle(typed_handler), ); - let surface = crate::graphql::build_surface( - &[], - &crate::graphql::SurfaceOptions::sqlite(), - ) - .expect("empty read-model Surface should build") - .with_service(&service) - .expect("typed Service should bind to the Surface"); + let surface = crate::graphql::build_surface(&[], &crate::graphql::SurfaceOptions::sqlite()) + .expect("empty read-model Surface should build") + .with_service(&service) + .expect("typed Service should bind to the Surface"); let surface = crate::application::SurfaceSpec::from_surface("catalog", &surface) .expect("Surface should become a portable application contract"); let application = service - .application("catalog", surface) + .application("catalog", surface.clone()) .expect("Service and Surface should compile into one application"); assert_eq!( @@ -1134,6 +1130,20 @@ fn service_compiles_exact_application_modules_from_command_namespaces() { .collect::>(), ["access.grant", "repository.create"] ); + + let mut missing = surface.clone(); + missing + .commands + .retain(|command| command.id != "access.grant"); + assert!(matches!( + service.application("catalog", missing), + Err(crate::ApplicationError::Missing { kind: "surface command", identity }) + if identity == "access.grant" + )); + assert!( + Service::new().application("catalog", surface).is_err(), + "a Surface cannot expose commands absent from the owning Service" + ); } #[tokio::test] From 7f600d64155f16d4fe1a9b4253ecc5d388474344 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Fri, 4 Sep 2026 22:54:46 -0500 Subject: [PATCH 014/484] perf: add opt-in lazy generated command loading Register authority before loading, preserve command lifecycle and dispatch order, and expose generated preload support. Implements [[tasks/client-artifact-loading-2]] --- .../src/client_compiler/render/commands.rs | 48 +++ .../src/client_compiler/render/project.rs | 24 +- distributed_cli/src/client_compiler/tests.rs | 26 ++ .../tests/fixtures/generated-lazy-commands.ts | 32 ++ js/README.md | 30 ++ js/package.json | 6 +- js/scripts/pack-smoke.mjs | 3 + js/src/replica/command-runtime.ts | 6 + js/src/replica/command-runtime/index.ts | 6 + js/src/replica/command-runtime/lazy.ts | 330 ++++++++++++++++++ js/src/replica/index.ts | 6 + js/src/replica/lazy.ts | 7 + js/src/sveltekit/lifecycle.ts | 7 +- js/src/sveltekit/replica.ts | 7 + js/src/sveltekit/vite.ts | 4 + js/tests/lazy-command-bundle.test.mjs | 81 +++++ js/tests/reload-state.test.mjs | 14 +- js/tests/replica-command-runtime.test.mjs | 164 +++++++++ js/tests/sveltekit-ssr.test.mjs | 27 ++ js/tests/sveltekit-vite.test.mjs | 6 + js/tsconfig.generated-tests.json | 1 + js/type-tests/replica-command-runtime.ts | 17 + 22 files changed, 844 insertions(+), 8 deletions(-) create mode 100644 distributed_cli/tests/fixtures/generated-lazy-commands.ts create mode 100644 js/src/replica/command-runtime/lazy.ts create mode 100644 js/src/replica/lazy.ts create mode 100644 js/tests/lazy-command-bundle.test.mjs diff --git a/distributed_cli/src/client_compiler/render/commands.rs b/distributed_cli/src/client_compiler/render/commands.rs index 45b6dd01f..7f44ddf78 100644 --- a/distributed_cli/src/client_compiler/render/commands.rs +++ b/distributed_cli/src/client_compiler/render/commands.rs @@ -13,6 +13,54 @@ use super::common::quoted_property; const COMMAND_ARTIFACT_VERSION: u32 = 2; +pub(super) fn render_lazy_commands( + manifest: &ClientManifest, +) -> Result { + let catalog = manifest + .commands + .iter() + .map(|command| { + ( + command.name.clone(), + serde_json::json!({ + "operationHash": command.operation_hash, + "hasInput": !matches!(command.input, ManifestCommandShape::None), + }), + ) + }) + .collect::>(); + let catalog = serde_json::to_string_pretty(&catalog).map_err(|error| { + ClientCompileError::manifest("client.render.lazy_commands", error.to_string()) + })?; + let pures = if pure_function_inventory(manifest)?.is_empty() { + "import('./commands.js').then(({ COMMANDS }) => ({ entries: COMMANDS }))" + } else { + "Promise.all([import('./commands.js'), import('./pures.js')]).then(([{ COMMANDS }, { PURE_FUNCTIONS }]) => ({ entries: COMMANDS, pureFunctions: PURE_FUNCTIONS }))" + }; + Ok(format!( + r#"/** GENERATED by distributed client. Do not edit. */ + +import {{ createLazyReplicaCommandRuntime }} from '@hops-ops/distributed/replica/lazy'; +import type {{ DistributedReplica, ReplicaCommandTransport, ReplicaLazyCommandRuntime }} from '@hops-ops/distributed/replica'; +import type {{ COMMANDS, GeneratedCommandRuntimeOptions }} from './commands.js'; +import {{ COMMAND_STATUS }} from './protocol.js'; + +const COMMAND_CATALOG = {catalog} as const; + +/** Register authority now; import one shared runtime on preload or first command. */ +export function createLazyCommands( + replica: DistributedReplica, + transport: ReplicaCommandTransport, + options?: GeneratedCommandRuntimeOptions +): ReplicaLazyCommandRuntime {{ + return createLazyReplicaCommandRuntime(replica, transport, + {{ commands: COMMAND_CATALOG, status: COMMAND_STATUS }}, + () => {pures}, options); +}} +"# + )) +} + pub(super) fn render_commands(manifest: &ClientManifest) -> Result { validate_command_namespaces(&manifest.commands)?; let projectors = serde_json::to_string_pretty(&manifest.projectors).map_err(|error| { diff --git a/distributed_cli/src/client_compiler/render/project.rs b/distributed_cli/src/client_compiler/render/project.rs index 581bb009c..a070313e4 100644 --- a/distributed_cli/src/client_compiler/render/project.rs +++ b/distributed_cli/src/client_compiler/render/project.rs @@ -8,7 +8,7 @@ use super::super::manifest::{canonical_json_value, ClientManifest, ManifestSurfa use super::super::{ ClientCompileError, GeneratedClientFile, GeneratedClientProject, GeneratedOperationSummary, }; -use super::commands::render_commands; +use super::commands::{render_commands, render_lazy_commands}; use super::common::json_string; use super::operation::render_operation_module; @@ -40,6 +40,12 @@ pub(crate) fn render_project( path: "commands.ts".into(), contents: render_commands(manifest)?, }); + if !manifest.commands.is_empty() { + files.push(GeneratedClientFile { + path: "lazy-commands.ts".into(), + contents: render_lazy_commands(manifest)?, + }); + } let pures = super::commands::render_pures(manifest)?; let has_pures = pures.is_some(); if let Some(pures) = pures { @@ -345,6 +351,8 @@ fn render_sveltekit( ]); if !manifest.commands.is_empty() { value_exports.insert("createCommands".into()); + value_exports.insert("createLazyCommands".into()); + value_exports.insert("provideDistributedLazy".into()); } for command in &manifest.commands { value_exports.insert(format!("Command_{}", command.mutation_field)); @@ -405,6 +413,8 @@ fn render_sveltekit( "} from './commands.js';", "", "export type { GeneratedCommands } from './commands.js';", + "import { createLazyCommands } from './lazy-commands.js';", + "export { createLazyCommands } from './lazy-commands.js';", ] .join("\n"), ); @@ -483,6 +493,18 @@ fn render_sveltekit( .map(str::to_string), ); sections.push(bindings.join("\n")); + if !manifest.commands.is_empty() { + sections.push(format!(r#"/** Opt-in deferred commands; query, SSR and boundary loading stay unchanged. */ +export function provideDistributedLazy( + options: Omit, 'createCommands' | 'reload'> & {{ reload?: Omit }} +): DistributedSvelteKitClient {{ + return provideDistributedSvelteKitClient(createDistributedSvelteKit({{ + ...options, + createCommands: createLazyCommands, + reload: {{ ...options.reload, key: {reload_key} }} + }})); +}}"#)); + } Ok(format!("{}\n", sections.join("\n\n"))) } diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 24aeeafdf..865631687 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -4075,3 +4075,29 @@ fn source_paths_fail_closed_before_they_can_inject_generated_typescript() { assert_eq!(error.code, "client.documents.invalid_path"); assert!(!error.message.contains("export const compromised")); } + +#[test] +fn generated_lazy_commands_defer_definitions_and_preserve_command_signatures() { + let project = compile_client(ClientCompileInput::new( + generated_command_types_manifest(), + ClientSurfaceSelector::role("user"), + vec![ClientDocument::new( + "todos.graphql", + "query Todos { todos { id } }", + )], + )) + .expect("compile lazy commands"); + let lazy = file(&project, "lazy-commands.ts"); + assert!(lazy.contains("import type { COMMANDS, GeneratedCommandRuntimeOptions }")); + assert!(lazy.contains("import('./commands.js')")); + assert!(lazy.contains("\"hasInput\": false")); + assert!(lazy.contains("\"hasInput\": true")); + let wrapper = file(&project, "sveltekit.ts"); + assert!(wrapper.contains("export function provideDistributedLazy(")); + assert!(wrapper.contains("createCommands: createLazyCommands")); + assert!(wrapper.contains("createCommands: createGeneratedCommands")); + assert_eq!( + lazy.replace("'./commands.js'", "'./generated-commands.js'"), + include_str!("../../tests/fixtures/generated-lazy-commands.ts") + ); +} diff --git a/distributed_cli/tests/fixtures/generated-lazy-commands.ts b/distributed_cli/tests/fixtures/generated-lazy-commands.ts new file mode 100644 index 000000000..be31fc2dc --- /dev/null +++ b/distributed_cli/tests/fixtures/generated-lazy-commands.ts @@ -0,0 +1,32 @@ +/** GENERATED by distributed client. Do not edit. */ + +import { createLazyReplicaCommandRuntime } from '@hops-ops/distributed/replica/lazy'; +import type { DistributedReplica, ReplicaCommandTransport, ReplicaLazyCommandRuntime } from '@hops-ops/distributed/replica'; +import type { COMMANDS, GeneratedCommandRuntimeOptions } from './generated-commands.js'; +import { COMMAND_STATUS } from './protocol.js'; + +const COMMAND_CATALOG = { + "todo.import": { + "hasInput": true, + "operationHash": "sha256:e8e54238fd7618fa94e90ae60b1dfac8833943027d04e71be84cb03702f1cebf" + }, + "todo.ping": { + "hasInput": false, + "operationHash": "sha256:3cb3c1e96331b4e98191cc725ab6b01c0e9b04cc7cc0f37f4fa0ef394fee9acf" + }, + "todo.project": { + "hasInput": true, + "operationHash": "sha256:f986d060555cdedfe94621914116306af704d8bb90e75289722a3b7119211d32" + } +} as const; + +/** Register authority now; import one shared runtime on preload or first command. */ +export function createLazyCommands( + replica: DistributedReplica, + transport: ReplicaCommandTransport, + options?: GeneratedCommandRuntimeOptions +): ReplicaLazyCommandRuntime { + return createLazyReplicaCommandRuntime(replica, transport, + { commands: COMMAND_CATALOG, status: COMMAND_STATUS }, + () => import('./generated-commands.js').then(({ COMMANDS }) => ({ entries: COMMANDS })), options); +} diff --git a/js/README.md b/js/README.md index d99fb1e76..ba10e2f35 100644 --- a/js/README.md +++ b/js/README.md @@ -304,6 +304,36 @@ await client.prefetchLocation(target.pathname, { }); ``` +### Optional lazy command loading + +For read-heavy applications, switch the root layout's generated provider import: + +```ts +import { provideDistributedLazy as provideDistributed } from '$distributed'; +``` + +Use the same provider options and `useCommands()` methods. The lazy provider +registers the generated surface authority immediately after hydration, and imports +one shared command runtime and its definitions on the first command. Queries, +SSR, hydration, and route prefetch keep their existing behavior. The default +`provideDistributed` and framework-neutral `createCommands` remain eager. + +To load command code before an interaction, call `await client.preloadCommands()` +when opening an editor or focusing an editing control. This imports code without +sending a command. The first cold command waits for this import before optimistic +feedback can appear; failed imports reject and can be retried. Imports never +replay commands. Pending receipts and status recovery remain owned by the shared +client across route changes. On controlled reload, an existing +`reload.recoverPendingCommands` callback runs after lazy command code is ready; +applications still own that callback's recovery policy. + +Regenerate the client with the matching CLI/runtime release to obtain +`provideDistributedLazy` and `createLazyCommands`. Framework-neutral consumers +can use `createLazyCommands` from the generated `lazy-commands.js` module and +call its `preload()` method. Directly importing `COMMANDS`, command artifacts, +`createCommands`, or command-dependent pure functions elsewhere in the browser +can keep those definitions eager. Verify the production bundle for your app. + Route components import only their generated surface. Static operation wrappers resolve the nearest tree-local client when used: diff --git a/js/package.json b/js/package.json index 3d0a79f1e..9ddee7f00 100644 --- a/js/package.json +++ b/js/package.json @@ -34,7 +34,11 @@ "types": "./dist/react/index.d.ts", "import": "./dist/react/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./replica/lazy": { + "types": "./dist/replica/lazy.d.ts", + "import": "./dist/replica/lazy.js" + } }, "scripts": { "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", diff --git a/js/scripts/pack-smoke.mjs b/js/scripts/pack-smoke.mjs index 1f15fc159..8cd5771b1 100644 --- a/js/scripts/pack-smoke.mjs +++ b/js/scripts/pack-smoke.mjs @@ -82,6 +82,7 @@ function inspectPackageContract(packageJson) { './package.json', './react', './replica', + './replica/lazy', './sveltekit', './sveltekit/vite' ]); @@ -275,6 +276,8 @@ void [ const consumerRuntimeSource = ` import assert from 'node:assert/strict'; import * as rootSurface from '@hops-ops/distributed'; +import * as lazySurface from '@hops-ops/distributed/replica/lazy'; +assert.deepEqual(Object.keys(lazySurface), ['createLazyReplicaCommandRuntime']); import * as replicaSurface from '@hops-ops/distributed/replica'; import * as diagnosticsSurface from '@hops-ops/distributed/diagnostics'; import { diff --git a/js/src/replica/command-runtime.ts b/js/src/replica/command-runtime.ts index 64998cfb6..b68affce6 100644 --- a/js/src/replica/command-runtime.ts +++ b/js/src/replica/command-runtime.ts @@ -33,3 +33,9 @@ export type { ReplicaCommandTransportResult, ReplicaResultObservationRegistration } from './command-runtime/index.js'; + +export type { + ReplicaLazyCommandCatalog, + ReplicaLazyCommandModule, + ReplicaLazyCommandRuntime +} from './command-runtime/lazy.js'; diff --git a/js/src/replica/command-runtime/index.ts b/js/src/replica/command-runtime/index.ts index 88bb07fbd..83880f96c 100644 --- a/js/src/replica/command-runtime/index.ts +++ b/js/src/replica/command-runtime/index.ts @@ -32,3 +32,9 @@ export type { export { ReplicaCommandRuntimeError } from './errors.js'; export { replicaCommandProjectedLifecycleOf } from './lifecycle.js'; export { createReplicaCommandRuntime } from './create.js'; + +export type { + ReplicaLazyCommandCatalog, + ReplicaLazyCommandModule, + ReplicaLazyCommandRuntime +} from './lazy.js'; diff --git a/js/src/replica/command-runtime/lazy.ts b/js/src/replica/command-runtime/lazy.ts new file mode 100644 index 000000000..e2907675e --- /dev/null +++ b/js/src/replica/command-runtime/lazy.ts @@ -0,0 +1,330 @@ +import { matchReplicaTrustedPresetInventory } from '../commands.js'; +import { SHA256 } from './constants.js'; +import { ReplicaCommandRuntimeError } from './errors.js'; +import { defineBoundCommand, freezeCommandTree } from './lib/binding.js'; +import { + commandStatusArtifact, + commandSurfaceContract, + normalizeInventory +} from './lib/inventory.js'; +import { + cloneScope, + cloneSurface, + linkAbortSignals, + sameScope, + sameSurface +} from './lib/util.js'; +import { replicaCommandAuthority } from './symbols.js'; +import type { ReplicaResultEnvelope } from '../types.js'; +import type { + CommandEntry, + ReplicaBoundCommands, + ReplicaCommandAuthorityHost, + ReplicaCommandCallOptions, + ReplicaCommandRuntime, + ReplicaCommandRuntimeOptions, + ReplicaCommandStatusArtifact, + ReplicaCommandSurfaceContract, + ReplicaCommandTransport +} from './types.js'; + +/** Small compiler-owned inventory; definitions and pure implementations stay in the lazy chunk. */ +export type ReplicaLazyCommandCatalog = Readonly<{ + commands: Readonly< + Record> + >; + status: ReplicaCommandStatusArtifact; +}>; + +export type ReplicaLazyCommandModule< + TEntries extends Readonly> +> = Readonly<{ + entries: TEntries; + pureFunctions?: ReplicaCommandRuntimeOptions['pureFunctions']; +}>; + +export type ReplicaLazyCommandRuntime< + TEntries extends Readonly> +> = ReplicaCommandRuntime & Readonly<{ preload(): Promise }>; + +/** + * Register authority synchronously, then load one shared command runtime on demand. + * Only immutable code may be cached by the loader; runtime state belongs to this client. + */ +export function createLazyReplicaCommandRuntime< + TEntries extends Readonly> +>( + replica: ReplicaCommandAuthorityHost, + transport: ReplicaCommandTransport, + catalog: ReplicaLazyCommandCatalog, + load: () => Promise>, + options: Omit = {} +): ReplicaLazyCommandRuntime { + const protocol = catalog.status.protocol; + if (protocol.surface === undefined) + throw new TypeError('lazy commands require a client surface'); + const contract: ReplicaCommandSurfaceContract = Object.freeze({ + protocolVersion: 1, + schemaHash: protocol.schemaHash, + protocolHash: protocol.protocolHash, + surface: cloneSurface(protocol.surface), + trustedPresets: Object.freeze( + protocol.trustedPresets.map((value) => Object.freeze({ ...value })) + ) + }); + const status = commandStatusArtifact(catalog.status, contract); + if (transport.status === undefined) + throw new TypeError( + 'generated command status artifact requires transport.status' + ); + const hashes = Object.freeze( + Object.fromEntries( + Object.entries(catalog.commands).map(([key, value]) => [ + key, + Object.freeze({ ...value }) + ]) + ) + ); + const commands = Object.create(null) as Record; + if (Object.keys(hashes).length === 0) + throw new TypeError('lazy command inventory must not be empty'); + for (const [name, descriptor] of Object.entries(hashes)) { + if ( + typeof descriptor.hasInput !== 'boolean' || + !SHA256.test(descriptor.operationHash) + ) + throw new TypeError('invalid lazy command operation hash'); + defineBoundCommand( + commands, + name, + descriptor.hasInput + ? (input: unknown, callOptions = {}) => invoke(name, input, callOptions) + : (callOptions = {}) => invoke(name, undefined, callOptions) + ); + } + freezeCommandTree(commands); + const registration = replica[replicaCommandAuthority]?.(contract); + const lifetime = new AbortController(); + let disposed = false; + let runtime: ReplicaCommandRuntime | undefined; + let loading: Promise | undefined; + let startTail: Promise | undefined; + // Reserve preparation order before importing. A warm call must not overtake + // earlier cold calls; release after dispatch starts, not after its receipt. + const reserveStart = () => { + const previous = startTail; + let resolve!: () => void; + const tail = new Promise((done) => { + resolve = done; + }); + startTail = tail; + return { + previous, + release() { + const complete = () => { + resolve(); + if (startTail === tail) startTail = undefined; + }; + if (previous === undefined) complete(); + else void previous.then(complete); + } + }; + }; + const readAuthority = () => + registration?.read() ?? { + generation: replica.authorizationGeneration, + scope: replica.scope, + trustedPresets: [] + }; + const assertAlive = () => { + if (disposed) + throw new ReplicaCommandRuntimeError('REPLICA_COMMAND_DISPOSED'); + }; + const preload = (): Promise => { + try { + assertAlive(); + } catch (error) { + return Promise.reject(error); + } + if (runtime !== undefined) return Promise.resolve(); + if (loading !== undefined) return loading; + loading = Promise.all([Promise.resolve().then(load), import('./create.js')]) + .then(([module, implementation]) => { + assertAlive(); + const inventory = normalizeInventory(module.entries); + if ( + inventory.length !== Object.keys(hashes).length || + inventory.some( + ({ key, artifact }) => + !Object.hasOwn(hashes, key) || + artifact.name !== key || + artifact.operationHash !== hashes[key].operationHash || + (artifact.input.kind !== 'none') !== hashes[key].hasInput + ) + ) + throw new TypeError( + 'loaded command inventory does not match its catalog' + ); + const actual = commandSurfaceContract( + inventory.map(({ artifact }) => artifact), + status.protocol.trustedPresets + ); + if ( + actual.schemaHash !== contract.schemaHash || + actual.protocolHash !== contract.protocolHash || + !sameSurface(actual.surface, contract.surface) || + JSON.stringify(actual.trustedPresets) !== + JSON.stringify(status.protocol.trustedPresets) + ) + throw new TypeError( + 'loaded command surface does not match its catalog' + ); + // The real runtime retains all existing validation, dispatch scheduling, + // result observation, optimistic layers, status readers and recovery. + runtime = implementation.createReplicaCommandRuntime( + replica, + transport, + module.entries, + { + ...options, + pureFunctions: { + ...module.pureFunctions, + ...options.pureFunctions + }, + status + } + ); + }) + .finally(() => { + loading = undefined; + }); + return loading; + }; + + async function invoke( + name: string, + input: unknown, + callOptions: ReplicaCommandCallOptions + ) { + assertAlive(); + try { + options.lifecycle?.assertDispatchOpen(); + } catch (cause) { + throw new ReplicaCommandRuntimeError('REPLICA_COMMAND_RELOADING', { + cause + }); + } + const captured = readAuthority(); + if ( + captured.scope === undefined || + captured.scope.schemaHash !== contract.schemaHash || + captured.scope.protocolVersion !== contract.protocolVersion + ) { + throw new ReplicaCommandRuntimeError( + 'REPLICA_COMMAND_AUTHORITY_UNAVAILABLE' + ); + } + matchReplicaTrustedPresetInventory( + contract.trustedPresets, + captured.trustedPresets + ); + const scope = cloneScope(captured.scope); + const current = () => { + assertAlive(); + const next = readAuthority(); + if ( + captured.signal?.aborted || + next.generation !== captured.generation || + next.scope === undefined || + !sameScope(next.scope, scope) + ) { + throw new ReplicaCommandRuntimeError( + 'REPLICA_COMMAND_SCOPE_INVALIDATED' + ); + } + }; + const signals = linkAbortSignals([ + captured.signal, + callOptions.signal, + lifetime.signal + ]); + const reservation = reserveStart(); + try { + current(); + if (signals.signal?.aborted) + throw new ReplicaCommandRuntimeError('REPLICA_COMMAND_ABORTED'); + // Snapshot before the new asynchronous boundary, just as eager preparation + // consumes the caller's input before its first await. + const savedInput = + runtime === undefined || reservation.previous !== undefined + ? structuredClone(input) + : input; + const savedOptions = { + ...callOptions, + ...(callOptions.generators === undefined + ? {} + : { generators: { ...callOptions.generators } }) + }; + if (runtime === undefined) await waitForLoad(preload(), signals.signal); + if (reservation.previous !== undefined) + await waitForLoad(reservation.previous, signals.signal); + current(); + if (signals.signal?.aborted) + throw new ReplicaCommandRuntimeError('REPLICA_COMMAND_ABORTED'); + let command: unknown = runtime!.commands; + for (const part of name.split('.')) + command = (command as Record)[part]; + return hashes[name].hasInput + ? ( + command as ( + input: unknown, + options: ReplicaCommandCallOptions + ) => unknown + )(savedInput, savedOptions) + : (command as (options: ReplicaCommandCallOptions) => unknown)( + savedOptions + ); + } catch (error) { + current(); + throw error; + } finally { + reservation.release(); + signals.dispose(); + } + } + + return Object.freeze({ + commands: commands as ReplicaBoundCommands, + preload, + observeResult: (envelope: ReplicaResultEnvelope) => + runtime?.observeResult(envelope), + pendingCommandIds: () => runtime?.pendingCommandIds() ?? Object.freeze([]), + dispose() { + if (disposed) return; + disposed = true; + lifetime.abort(); + try { + runtime?.dispose(); + } finally { + registration?.dispose(); + } + } + }); +} + +/** A cancelled caller releases its wait immediately; other callers still share the import. */ +function waitForLoad( + load: Promise, + signal: AbortSignal | undefined +): Promise { + if (signal === undefined) return load; + return new Promise((resolve, reject) => { + const abort = () => + reject(new ReplicaCommandRuntimeError('REPLICA_COMMAND_ABORTED')); + if (signal.aborted) abort(); + else signal.addEventListener('abort', abort, { once: true }); + load + .then(resolve, reject) + .finally(() => signal.removeEventListener('abort', abort)); + }); +} diff --git a/js/src/replica/index.ts b/js/src/replica/index.ts index 2bf775d11..773296df3 100644 --- a/js/src/replica/index.ts +++ b/js/src/replica/index.ts @@ -252,3 +252,9 @@ export type { MutationProgram, MutationTarget, } from './mutation-cache.js'; + +export type { + ReplicaLazyCommandCatalog, + ReplicaLazyCommandModule, + ReplicaLazyCommandRuntime +} from './command-runtime/lazy.js'; diff --git a/js/src/replica/lazy.ts b/js/src/replica/lazy.ts new file mode 100644 index 000000000..882f9ea7f --- /dev/null +++ b/js/src/replica/lazy.ts @@ -0,0 +1,7 @@ +/** Dedicated entry point keeps eager command exports out of a lazy client's initial import graph. */ +export { createLazyReplicaCommandRuntime } from './command-runtime/lazy.js'; +export type { + ReplicaLazyCommandCatalog, + ReplicaLazyCommandModule, + ReplicaLazyCommandRuntime +} from './command-runtime/lazy.js'; diff --git a/js/src/sveltekit/lifecycle.ts b/js/src/sveltekit/lifecycle.ts index 9dfe680b6..674b3b09c 100644 --- a/js/src/sveltekit/lifecycle.ts +++ b/js/src/sveltekit/lifecycle.ts @@ -124,7 +124,7 @@ export function validateDistributedReloadLocation(location: URL): string { /** Register one generated client with the shared browser reload transaction. */ export function registerDistributedReloadClient( replica: DistributedReplica, - runtime: Readonly<{ pendingCommandIds?(): readonly string[] }> | undefined, + runtime: Readonly<{ pendingCommandIds?(): readonly string[]; preload?(): Promise }> | undefined, options: DistributedReloadOptions ): () => void { const state = new Map( @@ -177,8 +177,9 @@ export function registerDistributedReloadClient( await declaration.restore(candidate.value); } } - if (saved.pendingCommandIds.length > 0) { - await options.recoverPendingCommands?.(saved.pendingCommandIds); + if (saved.pendingCommandIds.length > 0 && options.recoverPendingCommands !== undefined) { + await runtime?.preload?.(); + await options.recoverPendingCommands(saved.pendingCommandIds); } window.dispatchEvent( new CustomEvent('distributed:reload-restored', { diff --git a/js/src/sveltekit/replica.ts b/js/src/sveltekit/replica.ts index 59464df11..cdc51bbcd 100644 --- a/js/src/sveltekit/replica.ts +++ b/js/src/sveltekit/replica.ts @@ -100,6 +100,7 @@ export type SveltekitCommandRuntimeLike = Pick< > & Readonly<{ commands: TCommands; + preload?(): Promise; }>; export type SveltekitCommandRuntimeFactory = ( @@ -249,6 +250,8 @@ export type DistributedSvelteKitClient = Readonly<{ artifact: ReplicaOperationArtifact, variables: GraphqlVariables ): Promise; + /** Load deferred command code without dispatching a command. */ + preloadCommands(): Promise; invalidateAuthorization(): void; destroy(): void; }>; @@ -499,6 +502,10 @@ export function createDistributedSvelteKit { + if (destroyed) return Promise.reject(new Error('Distributed SvelteKit client is destroyed')); + return commandRuntime?.preload?.() ?? Promise.resolve(); + }, invalidateAuthorization(): void { if (!destroyed) { boundaryController!.disposeScope(); diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 97125610f..3e722c1cf 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -448,6 +448,9 @@ export function distributedSvelteKit( }, resolveId(source, importer): string | undefined { if (lifecycleOwnsCompile && frameworkDist !== undefined) { + if (source === '@hops-ops/distributed/replica/lazy') { + return join(frameworkDist, 'replica', 'lazy.js'); + } if (source === '@hops-ops/distributed/replica') { return join(frameworkDist, 'replica', 'index.js'); } @@ -868,6 +871,7 @@ export function distributedSvelteKitAliases( ]); if (frameworkDist !== undefined) { aliases.push( + ['@hops-ops/distributed/replica/lazy', join(frameworkDist, 'replica', 'lazy.js')], ['@hops-ops/distributed/replica', join(frameworkDist, 'replica')], ['@hops-ops/distributed/sveltekit', join(frameworkDist, 'sveltekit')] ); diff --git a/js/tests/lazy-command-bundle.test.mjs b/js/tests/lazy-command-bundle.test.mjs new file mode 100644 index 000000000..c8ebfe7c9 --- /dev/null +++ b/js/tests/lazy-command-bundle.test.mjs @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; +import { build } from 'esbuild'; + +// Bundle the compiler's exact fixture, not a hand-written approximation of it. +test('generated lazy factory keeps command definitions and runtime outside the initial browser closure', async () => { + const root = fileURLToPath(new URL('../', import.meta.url)); + const fixture = path.resolve( + root, + '../distributed_cli/tests/fixtures/generated-lazy-commands.ts' + ); + const result = await build({ + entryPoints: [fixture], + bundle: true, + splitting: true, + format: 'esm', + platform: 'browser', + minify: true, + write: false, + metafile: true, + outdir: path.join(root, '.bundle-test'), + alias: { + '@hops-ops/distributed/replica/lazy': path.join( + root, + 'dist/replica/lazy.js' + ), + '@hops-ops/distributed/replica': path.join(root, 'dist/replica/index.js') + }, + plugins: [ + { + name: 'fixture-status', + setup(plugin) { + plugin.onResolve({ filter: /^\.\/protocol\.js$/ }, (args) => + args.importer.includes('/tests/fixtures/') + ? { path: 'status', namespace: 'fixture' } + : undefined + ); + plugin.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ + contents: 'export const COMMAND_STATUS = {};' + })); + } + } + ] + }); + const outputs = result.metafile.outputs; + const initial = Object.keys(outputs).find( + (file) => outputs[file].entryPoint === path.relative(process.cwd(), fixture) + ); + assert.ok(initial); + const seen = new Set(); + function visit(file) { + if (seen.has(file)) return; + seen.add(file); + for (const dependency of outputs[file].imports) { + if (dependency.kind !== 'dynamic-import' && !dependency.external) + visit(dependency.path); + } + } + visit(initial); + const deferredInputs = ['generated-commands.ts', 'command-runtime/create.js']; + for (const suffix of deferredInputs) { + assert.ok( + Object.values(outputs).some((output) => + Object.entries(output.inputs).some( + ([name, info]) => name.endsWith(suffix) && info.bytesInOutput > 0 + ) + ), + `${suffix} must remain available` + ); + assert.ok( + [...seen].every((file) => + Object.entries(outputs[file].inputs).every( + ([name, info]) => !name.endsWith(suffix) || info.bytesInOutput === 0 + ) + ), + `${suffix} must be deferred` + ); + } +}); diff --git a/js/tests/reload-state.test.mjs b/js/tests/reload-state.test.mjs index 481cff722..612ef4e01 100644 --- a/js/tests/reload-state.test.mjs +++ b/js/tests/reload-state.test.mjs @@ -75,7 +75,7 @@ test('reload waits for replica authority and a resumed stale document reloads', participants: [{ key: 'public-surface', replica: { records: [] }, - pendingCommandIds: [], + pendingCommandIds: ['pending-command'], state: [] }] })); @@ -124,8 +124,15 @@ test('reload waits for replica authority and a resumed stale document reloads', return true; } }; - const unregister = registerDistributedReloadClient(replica, undefined, { - key: 'public-surface' + const recoveryOrder = []; + const unregister = registerDistributedReloadClient(replica, { + async preload() { recoveryOrder.push('preload'); }, + }, { + key: 'public-surface', + async recoverPendingCommands(ids) { + assert.deepEqual(ids, ['pending-command']); + recoveryOrder.push('recover'); + } }); try { await new Promise((resolve) => setTimeout(resolve, 50)); @@ -135,6 +142,7 @@ test('reload waits for replica authority and a resumed stale document reloads', scope = { tenant: 'tenant-1', roles: [] }; await waitFor(() => hydrations === 1, 'replica restoration was not retried'); assert.equal(values.get(capsuleKey), undefined); + assert.deepEqual(recoveryOrder, ['preload', 'recover']); activeGeneration = 'generation-c'; await waitFor(() => reloads === 1, 'stale document did not reload after activation'); diff --git a/js/tests/replica-command-runtime.test.mjs b/js/tests/replica-command-runtime.test.mjs index af63f6080..74e11de41 100644 --- a/js/tests/replica-command-runtime.test.mjs +++ b/js/tests/replica-command-runtime.test.mjs @@ -1,3 +1,4 @@ +import { createLazyReplicaCommandRuntime } from '../dist/replica/command-runtime/lazy.js'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; @@ -2814,3 +2815,166 @@ async function directProjectionRuntime() { ); return { replica, runtime }; } + +function lazyRuntime(replica, transport, load, options) { + return createLazyReplicaCommandRuntime(replica, transport, + { commands: { 'todo.upsert': { operationHash: HASH_A, hasInput: true } }, status: STATUS }, + load ?? (async () => ({ entries: { 'todo.upsert': artifact() } })), options); +} + +test('lazy commands register authority before loading, share imports, and snapshot invocation inputs', async () => { + const replica = new TestReplica(); + let registrations = 0; + const register = replica[replicaCommandAuthority].bind(replica); + replica[replicaCommandAuthority] = (contract) => { registrations++; return register(contract); }; + const gate = deferred(); + let loads = 0; + const requests = []; + const runtime = lazyRuntime(replica, { + dispatch: async request => { requests.push(request); return envelope(request); }, + status: async () => { throw new Error('not requested'); } + }, () => { loads++; return gate.promise; }); + assert.equal(registrations, 1); + assert.equal(loads, 0); + assert.deepEqual(runtime.pendingCommandIds(), []); + const input = { id: 'todo-1', title: 'original' }; + const first = runtime.commands.todo.upsert(input, { commandId: COMMAND_A }); + input.title = 'edited while loading'; + const second = runtime.commands.todo.upsert({ id: 'todo-2', title: 'second' }, { commandId: COMMAND_B }); + await tick(); + assert.equal(loads, 1); + assert.equal(requests.length, 0); + gate.resolve({ entries: { 'todo.upsert': artifact() } }); + const receipts = await Promise.all([first, second]); + assert.deepEqual(receipts.map(r => r.commandId), [COMMAND_A, COMMAND_B]); + assert.equal(requests[0].variables.input.title, 'original'); + assert.equal(replica.record('todo-1').fields.title, 'original'); + await runtime.preload(); + assert.equal(loads, 1); + runtime.dispose(); +}); + +for (const failure of ['scope', 'dispose', 'abort']) { + test(`lazy commands reject ${failure} while the chunk is still loading without dispatch`, async () => { + const replica = new TestReplica(); + const gate = deferred(); + const abort = new AbortController(); + let dispatches = 0; + const runtime = lazyRuntime(replica, { + dispatch: async request => { dispatches++; return envelope(request); }, status: async () => {} + }, () => gate.promise); + const pending = runtime.commands.todo.upsert({ id: 'todo-1', title: 'stale' }, { commandId: COMMAND_A, signal: abort.signal }); + if (failure === 'scope') replica.invalidate(); + if (failure === 'dispose') runtime.dispose(); + if (failure === 'abort') abort.abort(); + await assert.rejects(pending, { code: failure === 'scope' ? 'REPLICA_COMMAND_SCOPE_INVALIDATED' : failure === 'dispose' ? 'REPLICA_COMMAND_DISPOSED' : 'REPLICA_COMMAND_ABORTED' }); + assert.equal(dispatches, 0); + gate.resolve({ entries: { 'todo.upsert': artifact() } }); + await tick(); + assert.equal(dispatches, 0); + assert.equal(replica.record('todo-1'), undefined); + runtime.dispose(); + }); +} + +test('lazy chunk failures retry without dispatch and reject mismatched inventory', async () => { + const replica = new TestReplica(); + let loads = 0; + let dispatches = 0; + const runtime = lazyRuntime(replica, { + dispatch: async request => { dispatches++; return envelope(request); }, status: async () => {} + }, async () => { + if (++loads === 1) throw new Error('chunk unavailable'); + return { entries: { 'todo.upsert': artifact() } }; + }); + await assert.rejects(runtime.preload(), /chunk unavailable/); + await runtime.preload(); + assert.equal(loads, 2); + assert.equal(dispatches, 0); + runtime.dispose(); + const mismatch = lazyRuntime(replica, { status: async () => {} }, async () => ({ entries: { 'todo.upsert': { ...artifact(), operationHash: HASH_D } } })); + await assert.rejects(mismatch.preload(), /does not match its catalog/); + mismatch.dispose(); +}); + +test('lazy commands preserve transport retry identity, status recovery and pending IDs', async () => { + const replica = new TestReplica(); + const requests = []; + const runtime = lazyRuntime(replica, { + dispatch(request) { requests.push(request); return Promise.reject(new Error('ambiguous')); }, + status(request) { + return Promise.resolve(statusEnvelope(request, commandMetadata(requests[0], { state: 'rejected', projection: false }))); + } + }); + let recovery; + await assert.rejects(runtime.commands.todo.upsert({ id: 'todo-1', title: 'preview' }, { commandId: COMMAND_A, transportRetries: 1 }), error => { + recovery = error.recovery; + return error.code === 'REPLICA_COMMAND_TRANSPORT_AMBIGUOUS'; + }); + assert.equal(requests.length, 2); + assert.equal(requests[0].variables, requests[1].variables); + assert.deepEqual(runtime.pendingCommandIds(), [COMMAND_A]); + assert.equal(replica.layer(COMMAND_A), 'optimistic'); + await runtime.preload(); + assert.equal((await recovery.status()).state, 'rejected'); + assert.equal(replica.record('todo-1'), undefined); + assert.deepEqual(runtime.pendingCommandIds(), []); + runtime.dispose(); +}); + +test('lazy commands recheck the reload dispatch gate after import', async () => { + const replica = new TestReplica(); + const gate = deferred(); + let reloading = false; + let dispatches = 0; + const runtime = lazyRuntime(replica, { dispatch: async () => { dispatches++; }, status: async () => {} }, () => gate.promise, + { lifecycle: { assertDispatchOpen() { if (reloading) throw new Error('reload'); } } }); + const pending = runtime.commands.todo.upsert({ id: 'todo-1', title: 'preview' }, { commandId: COMMAND_A }); + reloading = true; + gate.resolve({ entries: { 'todo.upsert': artifact() } }); + await assert.rejects(pending, { code: 'REPLICA_COMMAND_RELOADING' }); + assert.equal(dispatches, 0); + assert.equal(replica.record('todo-1'), undefined); + runtime.dispose(); +}); + +test('lazy no-input commands keep options, cancellation, command ID and callbacks in the first argument', async () => { + const replica = new TestReplica(); + const gate = deferred(); + const noInput = { ...artifact({ modeled: false, revalidate: true }), name: 'todo.ping', input: { kind: 'none' } }; + let calls = 0; + let succeeded = 0; + const runtime = createLazyReplicaCommandRuntime(replica, { + dispatch: async request => { calls++; assert.equal(request.commandId, COMMAND_A); return envelope(request, { command: commandReceipt({ commandId: request.commandId, causationId: `cause:${request.commandId}`, state: 'succeeded', consistency: 'eventual', expects: [], observations: [], records: [] }) }); }, + status: async () => {} + }, { commands: { 'todo.ping': { operationHash: HASH_A, hasInput: false } }, status: STATUS }, () => gate.promise); + const abort = new AbortController(); + const cancelled = runtime.commands.todo.ping({ signal: abort.signal, commandId: COMMAND_B }); + abort.abort(); + await assert.rejects(cancelled, { code: 'REPLICA_COMMAND_ABORTED' }); + gate.resolve({ entries: { 'todo.ping': noInput } }); + await runtime.preload(); + const receipt = await runtime.commands.todo.ping({ commandId: COMMAND_A, onSucceeded() { succeeded++; } }); + assert.equal(receipt.commandId, COMMAND_A); + assert.equal(calls, 1); + assert.equal(succeeded, 1); + runtime.dispose(); +}); + +test('calls made after preload cannot overtake earlier commands waiting for the same import', async () => { + const replica = new TestReplica(); + const gate = deferred(); + const requests = []; + const runtime = lazyRuntime(replica, { + dispatch: async request => { requests.push(request.commandId); return envelope(request); }, status: async () => {} + }, () => gate.promise); + const preload = runtime.preload(); + // This continuation runs before the cold callers' import continuations. + const warm = preload.then(() => runtime.commands.todo.upsert({ id: 'todo-3', title: 'third' }, { commandId: COMMAND_C })); + const first = runtime.commands.todo.upsert({ id: 'todo-1', title: 'first' }, { commandId: COMMAND_A }); + const second = runtime.commands.todo.upsert({ id: 'todo-2', title: 'second' }, { commandId: COMMAND_B }); + gate.resolve({ entries: { 'todo.upsert': artifact() } }); + await Promise.all([first, second, warm]); + assert.deepEqual(requests, [COMMAND_A, COMMAND_B, COMMAND_C]); + runtime.dispose(); +}); diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index f24b93360..d98316f42 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import {createLazyReplicaCommandRuntime} from '../dist/replica/command-runtime/lazy.js'; import test from 'node:test'; import { @@ -480,3 +481,29 @@ test('one browser replica refuses to mix user and elevated generated surfaces', ); client.destroy(); }); + + +test('lazy command authority preserves isolated SSR hydration and query prefetch without importing commands', async () => { + const harness = serverHarness(); + const [alice, bob] = await Promise.all([harness.server.load(harness.event('alice')), harness.server.load(harness.event('bob'))]); + const hash = `sha256:${'d'.repeat(64)}`; + const status = {name:'Status',document:'query Status { commandStatus { state } }', operationHash:hash, protocol:{...TodosArtifact.protocol, protocolHash:`sha256:${'c'.repeat(64)}`, operation:hash}}; + let imports=0;let fetches=0; + const clients=[alice,bob].map((data,i)=>createDistributedSvelteKit({ + browser:false, boundaries:[todosBoundary], session:{getAuth:()=>({accessToken:i===0?'alice':'bob'})}, + hydration:data.distributed, authority:data.distributedAuthority, + fetch:async()=>{fetches++;throw Error('hydrated selection must not refetch')}, + createCommands:(replica,transport)=>createLazyReplicaCommandRuntime(replica,transport, + {commands:{'todo.ping':{operationHash:hash,hasInput:false}},status},async()=>{imports++;throw Error('commands must stay deferred')}) + })); + for(const [i,client] of clients.entries()){ + const store=client.operation(TodosArtifact).use(); + const release=store.subscribe(()=>{}); + assert.equal(store.get().data.todos[0].id,i===0?'todo-alice':'todo-bob'); + await client.prefetchLocation('/todos',{search:new URLSearchParams(),session:{},props:{}}); + release(); + } + assert.equal(imports,0);assert.equal(fetches,0); + clients.forEach(client=>client.destroy()); + await assert.rejects(clients[0].preloadCommands(),/destroyed/); +}); diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index cca64d4c8..19baa475c 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -1143,8 +1143,14 @@ test('supervised Vite defers generated-client compilation to the lifecycle', asy process.env.DISTRIBUTED_LIFECYCLE_PROJECT_ROOT = previousProjectRoot; } }); + const frameworkDist = join(root, 'node_modules/@hops-ops/distributed/dist'); + await mkdir(join(frameworkDist, 'replica'), { recursive: true }); const plugin = distributedSvelteKit(pluginOptions(root, script)); await plugin.configResolved({ root }); + const lazyEntry = join(await realpath(frameworkDist), 'replica/lazy.js'); + assert.equal(plugin.resolveId('@hops-ops/distributed/replica/lazy'), lazyEntry); + const aliases = distributedSvelteKitAliases({ cwd: root, clients: [clients()[0]] }); + assert.equal(aliases['@hops-ops/distributed/replica/lazy'], lazyEntry); await writeFile(activePointer, 'not-json'); assert.equal( plugin.resolveId('./ordinary-relative-import.js', join(root, 'src/app.ts')), diff --git a/js/tsconfig.generated-tests.json b/js/tsconfig.generated-tests.json index ed51963c1..3a19aed02 100644 --- a/js/tsconfig.generated-tests.json +++ b/js/tsconfig.generated-tests.json @@ -11,6 +11,7 @@ "outDir": "./dist-type-tests", "paths": { "@hops-ops/distributed/replica": ["./src/replica/index.ts"], + "@hops-ops/distributed/replica/lazy": ["./src/replica/lazy.ts"], "@hops-ops/distributed/react": ["./src/react/index.ts"], "@hops-ops/distributed/sveltekit": ["./src/sveltekit/index.ts"], "@hops-ops/distributed/sveltekit/vite": ["./src/sveltekit/vite.ts"] diff --git a/js/type-tests/replica-command-runtime.ts b/js/type-tests/replica-command-runtime.ts index ee8069ac1..e1e96c0fd 100644 --- a/js/type-tests/replica-command-runtime.ts +++ b/js/type-tests/replica-command-runtime.ts @@ -1,5 +1,7 @@ +import { createLazyReplicaCommandRuntime } from '@hops-ops/distributed/replica/lazy'; import { createReplicaCommandRuntime, + type ReplicaCommandStatusArtifact, type DistributedReplica, type ReplicaCommandArtifact, type ReplicaCommandTransport @@ -54,3 +56,18 @@ runtime.commands.create(); runtime.commands.ping({ id: 'todo-1' }); // @ts-expect-error Result types cannot bleed between generated commands. runtime.commands.create({ id: 'todo-1' }).then((receipt) => receipt.result.pong); + + +declare const status: ReplicaCommandStatusArtifact; +const lazy = createLazyReplicaCommandRuntime(replica, transport, { + commands: { 'todo.create': { operationHash: 'hash', hasInput: true }, 'todo.ping': { operationHash: 'hash', hasInput: false } }, status +}, async () => ({ entries: { 'todo.create': createArtifact, 'todo.ping': pingArtifact } })); +lazy.commands.todo.create({ id: 'todo-1' }).then(receipt => { const ok: boolean = receipt.result.ok; return ok; }); +lazy.commands.todo.ping({ commandId: 'id' }).then(receipt => { const pong: true = receipt.result.pong; return pong; }); +lazy.preload(); +// @ts-expect-error Lazy commands preserve required input. +lazy.commands.todo.create(); +// @ts-expect-error No-input commands still accept only options. +lazy.commands.todo.ping({ id: 'todo-1' }); +// @ts-expect-error Lazy output inference stays specific to each command. +lazy.commands.todo.create({ id: 'todo-1' }).then(receipt => receipt.result.pong); From 971c877bd0f9eb0f39eb7a39749ddf461633bd86 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 14:32:54 -0500 Subject: [PATCH 015/484] refactor: extract transport-neutral command contracts Move command outcomes, shape metadata, validation, and consistency contracts into distributed::command. Adapt GraphQL and legacy derives at the boundary while retaining canonical artifacts and fingerprints. Implements [[tasks/core-command-contract-1]] --- README.md | 38 ++++ distributed_macros/src/command.rs | 8 +- .../src/command_input_defaults.rs | 6 +- .../{graphql_types.rs => command_types.rs} | 125 ++++++++++--- distributed_macros/src/lib.rs | 26 ++- .../src/read_model/relational.rs | 12 +- distributed_macros/src/read_model/types.rs | 20 +-- distributed_macros/src/sourced.rs | 18 +- .../input_default_list.stderr | 4 +- .../input_default_nullable.stderr | 4 +- .../input_default_wrong_type.stderr | 4 +- .../application_command_duplicate_id.stderr | 3 +- src/application/capability.rs | 2 +- src/application/command.rs | 26 +-- src/application/module.rs | 6 +- src/application/plan.rs | 2 +- src/application/runtime.rs | 2 +- src/application/runtime_host.rs | 2 +- .../direct_projection.rs | 0 .../effect_wire.rs | 2 +- .../command_contract => command}/effects.rs | 0 .../command_input.rs => command/input.rs} | 35 ++-- .../command_contract => command}/mod.rs | 6 + .../command_contract => command}/outcomes.rs | 14 +- .../projection_obligations.rs | 0 .../projection_proof.rs | 0 .../projections.rs | 28 +-- .../command_contract => command}/tests.rs | 39 +++-- .../typed_command.rs | 31 ++-- src/command/types.rs | 134 ++++++++++++++ src/graphql/client_manifest/projections.rs | 13 +- src/graphql/client_manifest/tests.rs | 14 +- src/graphql/commands.rs | 4 +- src/graphql/engine/public_api.rs | 2 +- src/graphql/engine/tests.rs | 11 +- src/graphql/mod.rs | 3 +- src/graphql/naming.rs | 11 +- src/graphql/projection_delta/tests.rs | 23 +-- src/graphql/protocol/accumulator.rs | 2 +- src/graphql/protocol/tests.rs | 2 +- src/graphql/schema.rs | 2 +- src/graphql/sdl.rs | 2 +- src/graphql/surface/tests.rs | 8 +- src/graphql/surface/types.rs | 5 +- src/graphql/types.rs | 100 +++++++---- src/lib.rs | 5 +- src/microsvc/causal.rs | 20 +-- src/microsvc/cell_host/tests.rs | 2 +- src/microsvc/service/causal.rs | 6 +- src/microsvc/service/handlers.rs | 10 +- src/microsvc/service/routes.rs | 40 ++--- src/microsvc/service/runtime.rs | 2 +- src/microsvc/service/tests.rs | 20 +-- tests/core_command_contract.rs | 164 ++++++++++++++++++ .../todo-domain/src/commands/archive.rs | 4 +- .../todo-domain/src/commands/complete.rs | 6 +- .../crates/todo-domain/src/commands/create.rs | 6 +- .../todo-domain/src/commands/force_archive.rs | 6 +- .../crates/todo-domain/src/commands/purge.rs | 6 +- .../crates/todo-domain/src/commands/rename.rs | 6 +- .../crates/todo-domain/src/commands/reopen.rs | 4 +- .../crates/todo-domain/src/models/todo.rs | 2 +- tests/fixtures/core-command-contract-v1.json | 83 +++++++++ .../tests/fixtures/renamed_dependency.rs | 8 +- tests/legacy_authoring_absence.rs | 7 +- 65 files changed, 879 insertions(+), 327 deletions(-) rename distributed_macros/src/{graphql_types.rs => command_types.rs} (86%) rename src/{graphql/command_contract => command}/direct_projection.rs (100%) rename src/{graphql/command_contract => command}/effect_wire.rs (99%) rename src/{graphql/command_contract => command}/effects.rs (100%) rename src/{graphql/command_input.rs => command/input.rs} (95%) rename src/{graphql/command_contract => command}/mod.rs (95%) rename src/{graphql/command_contract => command}/outcomes.rs (97%) rename src/{graphql/command_contract => command}/projection_obligations.rs (100%) rename src/{graphql/command_contract => command}/projection_proof.rs (100%) rename src/{graphql/command_contract => command}/projections.rs (97%) rename src/{graphql/command_contract => command}/tests.rs (96%) rename src/{graphql/command_contract => command}/typed_command.rs (97%) create mode 100644 src/command/types.rs create mode 100644 tests/core_command_contract.rs create mode 100644 tests/fixtures/core-command-contract-v1.json diff --git a/README.md b/README.md index c63f202d2..559749f88 100644 --- a/README.md +++ b/README.md @@ -1396,6 +1396,44 @@ use distributed::bus::{run_source, RunOptions}; run_source(service, source, RunOptions::idempotent()).await?; ``` +## Command contracts + +Command semantics live in `distributed::command`, independently of the query +transport. Use `CommandInput` and `CommandOutput` to describe Serde input/output +shapes, and `command::{typed_command, Succeeded, Eventual, Atomic, PreparedCommand}` +to declare and prepare commands. The GraphQL adapter derives its surface from +those contracts; GraphQL naming restrictions are checked when exposing them. + +```rust +# use distributed::command; +use distributed::{CommandInput, CommandOutput}; +use distributed::command::{typed_command, Succeeded}; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, CommandInput)] +struct RenameInput { id: String, title: String } + +#[derive(Serialize, CommandOutput)] +struct RenameOutput { id: String } + +# fn main() { +let declaration = typed_command::>("todo.rename"); +# } +``` + +To migrate existing command DTOs, replace `GraphqlInput`/`GraphqlOutput` with +`CommandInput`/`CommandOutput` throughout the DTO's nested types and import +command APIs from `distributed::command`. Manual metadata implementations use +`CommandInputType`/`CommandOutputType`, `command_type()`, and +`CommandTypeDef`/`CommandTypeField`. Existing GraphQL derives, manual GraphQL +trait implementations, and command re-exports remain compatible through the +GraphQL adapter. Choose one metadata implementation per direction on each DTO. +Equivalent declarations retain their wire shapes and command fingerprints. + +`Atomic` continues to obtain its response shape from the relational read +model and requires the existing transaction proof. Moving command ownership +does not change Eventual projection confirmation or Atomic response sealing. + ## Microservice Framework (`microsvc`) The `microsvc` module provides a convention-based async command/event handler framework. Register handlers on typed `Routes` bundles, collect them into a non-generic `Service`, then expose that service over HTTP, gRPC, the bus, or direct dispatch. diff --git a/distributed_macros/src/command.rs b/distributed_macros/src/command.rs index f3871497d..f9975417a 100644 --- a/distributed_macros/src/command.rs +++ b/distributed_macros/src/command.rs @@ -287,7 +287,7 @@ pub fn expand( let defaults = args.defaults; let generated_defaults = args.generated_defaults; let mut builder = quote! { - #framework::graphql::typed_command::<#input, #outcome>(#id) + #framework::command::typed_command::<#input, #outcome>(#id) .field_name(#field_name) }; builder.extend(quote! { .roles([#(#roles),*]) }); @@ -315,12 +315,12 @@ pub fn expand( #[cfg(feature = "application-runtime")] #function - #visibility fn #command_name() -> #framework::graphql::TypedCommand<#input, #outcome> { + #visibility fn #command_name() -> #framework::command::TypedCommand<#input, #outcome> { #builder } #visibility static #command_static: ::std::sync::LazyLock< - #framework::graphql::TypedCommand<#input, #outcome> + #framework::command::TypedCommand<#input, #outcome> > = ::std::sync::LazyLock::new(#command_name); #visibility fn #spec_name() -> #framework::application::ApplicationResult< @@ -368,7 +368,7 @@ pub fn expand( + 'static, #aggregate: #framework::Aggregate + Send + Sync + 'static, #input: #framework::__private::serde::de::DeserializeOwned + Send + 'static, - #outcome: #framework::graphql::CommandOutcome, + #outcome: #framework::command::CommandOutcome, { routes .typed_command((#command_static).clone()) diff --git a/distributed_macros/src/command_input_defaults.rs b/distributed_macros/src/command_input_defaults.rs index 24bebfd50..8f5ea5f81 100644 --- a/distributed_macros/src/command_input_defaults.rs +++ b/distributed_macros/src/command_input_defaults.rs @@ -65,7 +65,7 @@ impl CommandInputDefaults { .into_iter() .map(|default| default.expand(&input, &framework)); quote! { - #framework::graphql::__command_input_defaults::<#input>( + #framework::command::__command_input_defaults::<#input>( vec![#(#defaults),*] ) } @@ -123,10 +123,10 @@ impl InputDefault { let marker = marker_path(input, marker_name); match self.generator { InputDefaultGenerator::UuidV7 => quote! { - #framework::graphql::__input_default_uuid_v7::<#input, #marker>() + #framework::command::__input_default_uuid_v7::<#input, #marker>() }, InputDefaultGenerator::Ulid => quote! { - #framework::graphql::__input_default_ulid::<#input, #marker>() + #framework::command::__input_default_ulid::<#input, #marker>() }, } } diff --git a/distributed_macros/src/graphql_types.rs b/distributed_macros/src/command_types.rs similarity index 86% rename from distributed_macros/src/graphql_types.rs rename to distributed_macros/src/command_types.rs index dc2d50953..a989328be 100644 --- a/distributed_macros/src/graphql_types.rs +++ b/distributed_macros/src/command_types.rs @@ -1,4 +1,4 @@ -//! GraphqlInput / GraphqlOutput derive macros. +//! Command data-shape derives and legacy GraphQL adapters. use proc_macro2::TokenStream; use quote::{format_ident, quote}; @@ -41,6 +41,8 @@ enum RenameRule { CamelCase, SnakeCase, ScreamingSnakeCase, + KebabCase, + ScreamingKebabCase, } impl RenameRule { @@ -52,10 +54,8 @@ impl RenameRule { "camelCase" => Ok(Self::CamelCase), "snake_case" => Ok(Self::SnakeCase), "SCREAMING_SNAKE_CASE" => Ok(Self::ScreamingSnakeCase), - "kebab-case" | "SCREAMING-KEBAB-CASE" => Err(syn::Error::new_spanned( - value, - "serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case", - )), + "kebab-case" => Ok(Self::KebabCase), + "SCREAMING-KEBAB-CASE" => Ok(Self::ScreamingKebabCase), other => Err(syn::Error::new_spanned( value, format!( @@ -67,6 +67,8 @@ impl RenameRule { fn apply(self, field: &str) -> String { match self { + Self::KebabCase => field.replace('_', "-"), + Self::ScreamingKebabCase => field.replace('_', "-").to_ascii_uppercase(), Self::LowerCase | Self::SnakeCase => field.to_string(), Self::UpperCase | Self::ScreamingSnakeCase => field.to_ascii_uppercase(), Self::PascalCase => { @@ -104,6 +106,7 @@ pub fn expand_graphql_input(input: DeriveInput) -> syn::Result { quote! { #framework::graphql::GraphqlInputType }, framework, SerdeDirection::Deserialize, + false, ) } @@ -115,6 +118,45 @@ pub fn expand_graphql_output(input: DeriveInput) -> syn::Result { quote! { #framework::graphql::GraphqlOutputType }, framework, SerdeDirection::Serialize, + false, + ) +} + +/// Neutral derives share serialization analysis with the legacy GraphQL derives. +pub fn expand_command_input(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; + expand( + input, + quote! { #framework::command::CommandInputType }, + quote! { #framework::command::CommandInputType }, + framework, + SerdeDirection::Deserialize, + true, + ) + .map_err(command_error) +} + +pub fn expand_command_output(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; + expand( + input, + quote! { #framework::command::CommandOutputType }, + quote! { #framework::command::CommandOutputType }, + framework, + SerdeDirection::Serialize, + true, + ) + .map_err(command_error) +} + +fn command_error(error: syn::Error) -> syn::Error { + syn::Error::new( + error.span(), + error + .to_string() + .replace("GraphqlInput", "CommandInput") + .replace("GraphqlOutput", "CommandOutput") + .replace("GraphQL", "command"), ) } @@ -124,11 +166,39 @@ fn expand( nested_trait: TokenStream, framework: TokenStream, serde_direction: SerdeDirection, + neutral: bool, ) -> syn::Result { + let method = if neutral { + quote! { command_type } + } else { + quote! { graphql_type } + }; + let (type_def, type_field) = if neutral { + ( + quote! { #framework::command::CommandTypeDef }, + quote! { #framework::command::CommandTypeField }, + ) + } else { + ( + quote! { #framework::graphql::GraphqlTypeDef }, + quote! { #framework::graphql::GraphqlTypeField }, + ) + }; let name = &input.ident; let visibility = &input.vis; validate_serde_container_shape(&input.attrs, serde_direction)?; let rename_all = serde_rename_all(&input.attrs, serde_direction)?; + if !neutral + && matches!( + rename_all, + Some(RenameRule::KebabCase | RenameRule::ScreamingKebabCase) + ) + { + if let Some(value) = serde_name_value(&input.attrs, "rename_all", serde_direction)? { + return Err(syn::Error::new_spanned(value, + "serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case")); + } + } let Data::Struct(data) = &input.data else { return Err(syn::Error::new_spanned( &input, @@ -160,13 +230,15 @@ fn expand( .map(|rule| rule.apply(rust_field_name)) .unwrap_or_else(|| rust_field_name.to_string()) }); - validate_graphql_field_name(&field_name_str, field)?; + if !neutral { + validate_graphql_field_name(&field_name_str, field)?; + } let (type_name, nullable, list, item_nullable, nested) = - map_type(&field.ty, field, &nested_trait)?; + map_type(&field.ty, field, &nested_trait, &method)?; let effect_path_kind = if !list && nested.is_some() { - quote! { #framework::graphql::EffectInputObjectKind } + quote! { #framework::command::EffectInputObjectKind } } else { - quote! { #framework::graphql::EffectInputTerminalKind } + quote! { #framework::command::EffectInputTerminalKind } }; let effect_wire = effect_input_wire_tokens(&framework, &type_name, list, nested.is_some()); let nested_tokens = match nested { @@ -174,7 +246,7 @@ fn expand( None => quote! { None }, }; field_tokens.push(quote! { - #framework::graphql::GraphqlTypeField { + #type_field { name: #field_name_str.to_string(), type_name: #type_name.to_string(), nullable: #nullable, @@ -189,16 +261,16 @@ fn expand( let nested_ty = effect_nested_type(field_ty); let non_null_ty = effect_non_null_type(field_ty); let nullability = if extract_path_arg(field_ty, "Option").is_some() { - quote! { #framework::graphql::EffectNullable } + quote! { #framework::command::EffectNullable } } else { - quote! { #framework::graphql::EffectRequired } + quote! { #framework::command::EffectRequired } }; effect_input_markers.push(quote! { #[doc(hidden)] #[allow(non_camel_case_types)] #visibility struct #marker; - impl #framework::graphql::EffectInputFieldMarker for #marker { + impl #framework::command::EffectInputFieldMarker for #marker { type Input = #name; type Value = #field_ty; type NonNullValue = #non_null_ty; @@ -217,8 +289,8 @@ fn expand( let type_name_str = name.to_string(); Ok(quote! { impl #trait_path for #name { - fn graphql_type() -> #framework::graphql::GraphqlTypeDef { - #framework::graphql::GraphqlTypeDef::new( + fn #method() -> #type_def { + #type_def::new( #type_name_str, vec![#(#field_tokens),*], ).with_type_id(::std::any::TypeId::of::<#name>()) @@ -236,20 +308,20 @@ fn effect_input_wire_tokens( nested: bool, ) -> proc_macro2::TokenStream { if list { - return quote! { #framework::graphql::EffectWireList }; + return quote! { #framework::command::EffectWireList }; } if nested { - return quote! { #framework::graphql::EffectWireObject }; + return quote! { #framework::command::EffectWireObject }; } match type_name { - "String" | "ID" => quote! { #framework::graphql::EffectWireString }, - "Boolean" => quote! { #framework::graphql::EffectWireBoolean }, - "BigInt" | "Int" => quote! { #framework::graphql::EffectWireBigInt }, - "Float" => quote! { #framework::graphql::EffectWireFloat }, - "JSON" => quote! { #framework::graphql::EffectWireJson }, - "Bytea" => quote! { #framework::graphql::EffectWireBytea }, - "Timestamptz" => quote! { #framework::graphql::EffectWireTimestamp }, - _ => quote! { #framework::graphql::EffectWireUnsupported }, + "String" | "ID" => quote! { #framework::command::EffectWireString }, + "Boolean" => quote! { #framework::command::EffectWireBoolean }, + "BigInt" | "Int" => quote! { #framework::command::EffectWireBigInt }, + "Float" => quote! { #framework::command::EffectWireFloat }, + "JSON" => quote! { #framework::command::EffectWireJson }, + "Bytea" => quote! { #framework::command::EffectWireBytea }, + "Timestamptz" => quote! { #framework::command::EffectWireTimestamp }, + _ => quote! { #framework::command::EffectWireUnsupported }, } } @@ -277,6 +349,7 @@ fn map_type( ty: &Type, span: &syn::Field, nested_trait: &TokenStream, + method: &TokenStream, ) -> syn::Result<(String, bool, bool, bool, Option)> { let mut current = ty; let mut nullable = false; @@ -333,7 +406,7 @@ fn map_type( return Ok((s.to_string(), nullable, list, item_nullable, None)); } - let nested = quote! { <#current as #nested_trait>::graphql_type() }; + let nested = quote! { <#current as #nested_trait>::#method() }; Ok((ident, nullable, list, item_nullable, Some(nested))) } diff --git a/distributed_macros/src/lib.rs b/distributed_macros/src/lib.rs index d1fae7a82..bdde44f47 100644 --- a/distributed_macros/src/lib.rs +++ b/distributed_macros/src/lib.rs @@ -2,11 +2,11 @@ mod aggregate; mod application; mod command; mod command_input_defaults; +mod command_types; mod digest; mod domain_event; mod domain_state; mod enqueue; -mod graphql_types; mod module; mod mutation; mod portable_command; @@ -182,11 +182,31 @@ pub fn mutation_file(input: TokenStream) -> TokenStream { mutation::expand_file(input) } +/// Derive transport-neutral command input metadata from Serde field shapes. +#[proc_macro_derive(CommandInput, attributes(serde))] +pub fn derive_command_input(input: TokenStream) -> TokenStream { + let input = syn::parse_macro_input!(input as DeriveInput); + match command_types::expand_command_input(input) { + Ok(tokens) => tokens.into(), + Err(err) => err.to_compile_error().into(), + } +} + +/// Derive transport-neutral command output metadata from Serde field shapes. +#[proc_macro_derive(CommandOutput, attributes(serde))] +pub fn derive_command_output(input: TokenStream) -> TokenStream { + let input = syn::parse_macro_input!(input as DeriveInput); + match command_types::expand_command_output(input) { + Ok(tokens) => tokens.into(), + Err(err) => err.to_compile_error().into(), + } +} + /// Derive `GraphqlInputType` for command mutation input structs. #[proc_macro_derive(GraphqlInput, attributes(serde))] pub fn derive_graphql_input(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); - match graphql_types::expand_graphql_input(input) { + match command_types::expand_graphql_input(input) { Ok(tokens) => tokens.into(), Err(err) => err.to_compile_error().into(), } @@ -196,7 +216,7 @@ pub fn derive_graphql_input(input: TokenStream) -> TokenStream { #[proc_macro_derive(GraphqlOutput, attributes(serde))] pub fn derive_graphql_output(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); - match graphql_types::expand_graphql_output(input) { + match command_types::expand_graphql_output(input) { Ok(tokens) => tokens.into(), Err(err) => err.to_compile_error().into(), } diff --git a/distributed_macros/src/read_model/relational.rs b/distributed_macros/src/read_model/relational.rs index 13ccb55ed..89472e67b 100644 --- a/distributed_macros/src/read_model/relational.rs +++ b/distributed_macros/src/read_model/relational.rs @@ -70,10 +70,10 @@ pub(super) fn expand_relational_read_model( let ty = &field.ty; let marker = format_ident!("__Distributed{}EffectModelField_{}", name, ident); effect_key_fields.push(quote! { - pub #ident: distributed::graphql::TypedEffectExpression<#ty> + pub #ident: distributed::command::TypedEffectExpression<#ty> }); effect_key_values.push(quote! { - distributed::graphql::__effect_key_field::<#marker>(value.#ident) + distributed::command::__effect_key_field::<#marker>(value.#ident) }); } @@ -123,7 +123,7 @@ pub(super) fn expand_relational_read_model( #[allow(non_camel_case_types)] #visibility struct #marker; - impl distributed::graphql::EffectRelationshipMarker for #marker { + impl distributed::command::EffectRelationshipMarker for #marker { type Source = #name; type Target = #target_ty; const FIELD: &'static str = #field_name; @@ -153,7 +153,7 @@ pub(super) fn expand_relational_read_model( #[allow(non_camel_case_types)] #visibility struct #effect_marker; - impl distributed::graphql::EffectModelFieldMarker for #effect_marker { + impl distributed::command::EffectModelFieldMarker for #effect_marker { type Model = #name; type Value = #field_ty; type Wire = #effect_wire; @@ -311,10 +311,10 @@ pub(super) fn expand_relational_read_model( } impl ::core::convert::From<#effect_key_name> - for distributed::graphql::TypedEffectKey<#name> + for distributed::command::TypedEffectKey<#name> { fn from(value: #effect_key_name) -> Self { - distributed::graphql::__effect_key::<#name>(vec![#(#effect_key_values),*]) + distributed::command::__effect_key::<#name>(vec![#(#effect_key_values),*]) } } diff --git a/distributed_macros/src/read_model/types.rs b/distributed_macros/src/read_model/types.rs index f500a2554..1bd2e2385 100644 --- a/distributed_macros/src/read_model/types.rs +++ b/distributed_macros/src/read_model/types.rs @@ -54,27 +54,27 @@ pub(super) fn effect_model_wire_tokens( text: bool, ) -> proc_macro2::TokenStream { if jsonb { - return quote! { distributed::graphql::EffectWireJson }; + return quote! { distributed::command::EffectWireJson }; } if text { - return quote! { distributed::graphql::EffectWireString }; + return quote! { distributed::command::EffectWireString }; } let ty = option_inner_type(ty).unwrap_or(ty); let Some(last) = last_type_segment(ty) else { - return quote! { distributed::graphql::EffectWireUnsupported }; + return quote! { distributed::command::EffectWireUnsupported }; }; match last.ident.to_string().as_str() { - "String" | "str" => quote! { distributed::graphql::EffectWireString }, - "bool" => quote! { distributed::graphql::EffectWireBoolean }, + "String" | "str" => quote! { distributed::command::EffectWireString }, + "bool" => quote! { distributed::command::EffectWireBoolean }, "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize" => { - quote! { distributed::graphql::EffectWireBigInt } + quote! { distributed::command::EffectWireBigInt } } - "f32" | "f64" => quote! { distributed::graphql::EffectWireFloat }, - "Vec" if vec_inner_is_u8(last) => quote! { distributed::graphql::EffectWireBytea }, + "f32" | "f64" => quote! { distributed::command::EffectWireFloat }, + "Vec" if vec_inner_is_u8(last) => quote! { distributed::command::EffectWireBytea }, "Vec" | "HashMap" | "BTreeMap" | "Value" => { - quote! { distributed::graphql::EffectWireJson } + quote! { distributed::command::EffectWireJson } } - _ => quote! { distributed::graphql::EffectWireUnsupported }, + _ => quote! { distributed::command::EffectWireUnsupported }, } } diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index e1ca50e83..1b24b7a95 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -1242,16 +1242,16 @@ fn expand_domain_commands_module( let field = value.field.to_string(); let source = match &value.source { KnownStateValueSource::Constant(expression) => quote! { - distributed::graphql::__command_projection_preview_constant(#expression) + distributed::command::__command_projection_preview_constant(#expression) }, KnownStateValueSource::Null => quote! { - distributed::graphql::CommandProjectionPreviewSource::Null + distributed::command::CommandProjectionPreviewSource::Null }, }; quote! { (#field, #source) } }); Some(quote! { - distributed::graphql::__command_projection_state_known_values::< + distributed::command::__command_projection_state_known_values::< super::#event_type, #state, >(vec![#(#fields),*]) @@ -1264,7 +1264,7 @@ fn expand_domain_commands_module( let known_values_method = has_known_values.then(|| { quote! { fn command_event_known_values( - ) -> Vec { + ) -> Vec { #[allow(unused_imports)] use super::*; vec![#(#known_value_items),*] @@ -1275,17 +1275,17 @@ fn expand_domain_commands_module( "Outward domain-event set for `{aggregate_name}::{method_name}`.\n\n\ Derived from direct `self.()` calls to `#[event(..., domain)]` \ methods in this `#[sourced]` impl. Use with \ - [`distributed::graphql::TypedCommand::emits_events`]." + [`distributed::command::TypedCommand::emits_events`]." ); quote! { #[doc = #doc] pub enum #type_name {} - impl distributed::graphql::CommandEventSet for #type_name { - fn command_event_set() -> distributed::graphql::CommandProjectionEventSet { - distributed::graphql::__command_projection_events([ + impl distributed::command::CommandEventSet for #type_name { + fn command_event_set() -> distributed::command::CommandProjectionEventSet { + distributed::command::__command_projection_events([ #( - distributed::graphql::__command_projection_event_descriptor::< + distributed::command::__command_projection_event_descriptor::< super::#event_types, >() ),* diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr index 7111ab6e4..994eef3d9 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr @@ -11,8 +11,8 @@ note: expected this to be `std::string::String` | ^^^^^^^^^^^ = note: expected struct `std::string::String` found struct `Vec` -note: required by a bound in `distributed::graphql::__input_default_ulid` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs +note: required by a bound in `distributed::command::__input_default_ulid` + --> $WORKSPACE/src/command/effect_wire.rs | | pub fn __input_default_ulid() -> CompiledInputDefault | -------------------- required by a bound in this function diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr index 217ed22db..0fc9282ad 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr @@ -11,8 +11,8 @@ note: expected this to be `std::string::String` | ^^^^^^^^^^^^^^ = note: expected struct `std::string::String` found enum `std::option::Option` -note: required by a bound in `distributed::graphql::__input_default_uuid_v7` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs +note: required by a bound in `distributed::command::__input_default_uuid_v7` + --> $WORKSPACE/src/command/effect_wire.rs | | pub fn __input_default_uuid_v7() -> CompiledInputDefault | ----------------------- required by a bound in this function diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr index 1785685f8..e47640a93 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr @@ -9,8 +9,8 @@ note: expected this to be `std::string::String` | 5 | count: i64, | ^^^ -note: required by a bound in `distributed::graphql::__input_default_uuid_v7` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs +note: required by a bound in `distributed::command::__input_default_uuid_v7` + --> $WORKSPACE/src/command/effect_wire.rs | | pub fn __input_default_uuid_v7() -> CompiledInputDefault | ----------------------- required by a bound in this function diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr index 5377eae50..ed8715148 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr @@ -12,8 +12,7 @@ error[E0080]: evaluation panicked: duplicate command identity in module declarat note: inside `assert_unique_command_ids` --> $RUST/core/src/panic.rs | - | $crate::panicking::panic_fmt($crate::const_format_args!($($t)+)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here + = note: the failure occurred here | ::: $WORKSPACE/src/application/mod.rs | diff --git a/src/application/capability.rs b/src/application/capability.rs index 8ace05cdd..7da3491ae 100644 --- a/src/application/capability.rs +++ b/src/application/capability.rs @@ -10,7 +10,7 @@ use super::error::{ApplicationError, ApplicationResult}; use super::identity::{canonical_json, sha256_fingerprint}; use super::manifest::ApplicationManifest; use super::mount::MountSelector; -use crate::graphql::command_contract::CommandConsistency; +use crate::command::CommandConsistency; /// A named logical capability required by one or more mounts. #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] diff --git a/src/application/command.rs b/src/application/command.rs index 0f571d3ea..f3a604c11 100644 --- a/src/application/command.rs +++ b/src/application/command.rs @@ -7,12 +7,12 @@ use serde::{Deserialize, Serialize}; use super::error::{ApplicationError, ApplicationResult}; use super::identity::{canonical_json, sha256_fingerprint, LogicalId}; -use crate::graphql::command_contract::{ - CommandConsistency, CommandOutcome, TypedCommand, TypedCommandContract, +use crate::command::{ + CommandConsistency, CommandInputType, CommandOutcome, CommandTypeDef, TypedCommand, + TypedCommandContract, }; -use crate::graphql::{GraphqlInputType, GraphqlTypeDef}; -/// Serializable GraphQL type field used by a portable command contract. +/// Serializable command type field used by a portable command contract. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct CommandTypeField { @@ -25,7 +25,7 @@ pub struct CommandTypeField { pub nested: Option>, } -/// Serializable GraphQL input/output type used by a portable command contract. +/// Serializable command input/output type used by a portable command contract. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct CommandTypeSpec { @@ -35,8 +35,8 @@ pub struct CommandTypeSpec { pub type TypeSpec = CommandTypeSpec; -impl From<&GraphqlTypeDef> for CommandTypeSpec { - fn from(definition: &GraphqlTypeDef) -> Self { +impl From<&CommandTypeDef> for CommandTypeSpec { + fn from(definition: &CommandTypeDef) -> Self { Self { name: definition.name.clone(), fields: definition @@ -199,7 +199,7 @@ impl CommandDefinition { mount: Option, ) -> ApplicationResult where - I: GraphqlInputType + serde::de::DeserializeOwned + Send + 'static, + I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, K: CommandOutcome, { let (_, typed_contract) = command.into_parts(); @@ -358,7 +358,7 @@ impl CommandSpec { /// Build a portable spec from the framework's existing typed declaration. pub fn from_typed_command(command: &TypedCommand) -> ApplicationResult where - I: GraphqlInputType + serde::de::DeserializeOwned + Send + 'static, + I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, K: CommandOutcome, { let (_, contract) = command.clone().into_parts(); @@ -366,19 +366,19 @@ impl CommandSpec { } pub(crate) fn from_contract( - contract: &crate::graphql::command_contract::TypedCommandContract, + contract: &crate::command::TypedCommandContract, ) -> ApplicationResult { let projection_contract = serde_json::to_value(&contract.projections)?; let applies = serde_json::to_value(&contract.projections.previews)?; let confirmations = contract .confirmations .iter() - .map(crate::graphql::command_contract::CommandProjectionConfirmation::canonical_value) + .map(crate::command::CommandProjectionConfirmation::canonical_value) .collect(); let direct_projection = contract .direct_projection .as_ref() - .map(crate::graphql::command_contract::CommandDirectProjectionTarget::canonical_value); + .map(crate::command::CommandDirectProjectionTarget::canonical_value); let mut emits: Vec = contract .projections .selectors @@ -889,7 +889,7 @@ impl CommandMount { impl TypedCommand where - I: GraphqlInputType + serde::de::DeserializeOwned + Send + 'static, + I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, K: CommandOutcome, { /// Compile the exact declaration into its portable, serializable spec. diff --git a/src/application/module.rs b/src/application/module.rs index 629e30d5d..e7122991f 100644 --- a/src/application/module.rs +++ b/src/application/module.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use super::command::{CommandDefinition, CommandMount, CommandSpec, CommandTypeSpec, EventSpec}; use super::error::{ApplicationError, ApplicationResult}; use super::identity::{canonical_json, sha256_fingerprint, LogicalId}; -use crate::graphql::command_contract::TypedCommandContract; +use crate::command::TypedCommandContract; use crate::graphql::surface::{ RootKind, Surface, SurfaceArgument, SurfaceCommand, SurfaceCommandShape, SurfaceProjectionOwner, SurfaceRelationshipKeys, SurfaceSelection, SurfaceTypeDef, @@ -287,7 +287,7 @@ pub struct SurfaceCommandSpec { pub roles: Vec, pub input: Option, pub output: Option, - pub consistency: crate::graphql::CommandConsistency, + pub consistency: crate::command::CommandConsistency, pub defaults: serde_json::Value, pub effects: serde_json::Value, pub confirmations: serde_json::Value, @@ -541,7 +541,7 @@ fn surface_command_spec(command: &SurfaceCommand) -> ApplicationResult crate::application::ApplicationManifest { diff --git a/src/graphql/command_contract/direct_projection.rs b/src/command/direct_projection.rs similarity index 100% rename from src/graphql/command_contract/direct_projection.rs rename to src/command/direct_projection.rs diff --git a/src/graphql/command_contract/effect_wire.rs b/src/command/effect_wire.rs similarity index 99% rename from src/graphql/command_contract/effect_wire.rs rename to src/command/effect_wire.rs index 361074824..94028b62e 100644 --- a/src/graphql/command_contract/effect_wire.rs +++ b/src/command/effect_wire.rs @@ -84,7 +84,7 @@ impl TypedEffectExpression { } } -/// Marker implemented only by `GraphqlInput` derive output in normal use. +/// Marker generated by command input derives (including the legacy GraphQL adapter). /// /// The trait must be public because derive output lives in downstream crates. /// All marker metadata is still revalidated against the final command Surface; diff --git a/src/graphql/command_contract/effects.rs b/src/command/effects.rs similarity index 100% rename from src/graphql/command_contract/effects.rs rename to src/command/effects.rs diff --git a/src/graphql/command_input.rs b/src/command/input.rs similarity index 95% rename from src/graphql/command_input.rs rename to src/command/input.rs index 2ae2beadb..f8fc5bc7e 100644 --- a/src/graphql/command_input.rs +++ b/src/command/input.rs @@ -1,8 +1,7 @@ -//! Canonical typed GraphQL command-input validation. +//! Canonical typed command-input validation. //! -//! Authenticated GraphQL causal dispatch passes through this one validator -//! before ledger reservation. Direct and bus transports currently fail closed; -//! any future verified framework envelope must enter through this same path. +//! Every authenticated command host passes through this validator before +//! ledger reservation. Transport adapters must retain these normalization rules. //! The retained wire value is the source of hashing and declaration-expression //! resolution, so decoding the Rust input never becomes a second, potentially //! differently named serialization path. @@ -14,7 +13,7 @@ use serde::de::DeserializeOwned; use serde_json::{Number, Value}; use sha2::{Digest, Sha256}; -use super::{GraphqlTypeDef, GraphqlTypeField}; +use super::{CommandTypeDef, CommandTypeField}; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct CommandInputError { @@ -43,7 +42,7 @@ impl std::fmt::Display for CommandInputError { impl std::error::Error for CommandInputError {} -/// Validated, recursively key-sorted GraphQL wire input and its stable digest. +/// Validated, recursively key-sorted command wire input and its stable digest. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct CanonicalCommandInput { wire: Value, @@ -110,7 +109,7 @@ impl CanonicalTypedCommandInput { } pub(crate) fn canonicalize_command_input( - definition: &GraphqlTypeDef, + definition: &CommandTypeDef, input: Value, ) -> Result { let wire = canonicalize_object(definition, input, "$")?; @@ -132,7 +131,7 @@ fn hex_digest(digest: &[u8; 32]) -> String { } fn canonicalize_object( - definition: &GraphqlTypeDef, + definition: &CommandTypeDef, value: Value, path: &str, ) -> Result { @@ -183,7 +182,7 @@ fn canonicalize_object( } fn canonicalize_field( - field: &GraphqlTypeField, + field: &CommandTypeField, value: Value, path: &str, ) -> Result { @@ -218,7 +217,7 @@ fn canonicalize_field( } fn canonicalize_leaf( - field: &GraphqlTypeField, + field: &CommandTypeField, value: Value, path: &str, ) -> Result { @@ -399,9 +398,9 @@ mod tests { nullable: bool, list: bool, item_nullable: bool, - nested: Option, - ) -> GraphqlTypeField { - GraphqlTypeField { + nested: Option, + ) -> CommandTypeField { + CommandTypeField { name: name.into(), type_name: type_name.into(), nullable, @@ -411,8 +410,8 @@ mod tests { } } - fn definition() -> GraphqlTypeDef { - GraphqlTypeDef::new( + fn definition() -> CommandTypeDef { + CommandTypeDef::new( "Input", vec![ field("id", "String", false, false, false, None), @@ -424,7 +423,7 @@ mod tests { false, false, false, - Some(GraphqlTypeDef::new( + Some(CommandTypeDef::new( "NestedInput", vec![field("count", "BigInt", false, false, false, None)], )), @@ -508,7 +507,7 @@ mod tests { #[test] fn graphql_int_is_limited_to_the_signed_32_bit_range() { - let definition = GraphqlTypeDef::new( + let definition = CommandTypeDef::new( "IntInput", vec![field("value", "Int", false, false, false, None)], ); @@ -527,7 +526,7 @@ mod tests { #[test] fn decoding_retains_the_original_wire_instead_of_reserializing_rust() { - let definition = GraphqlTypeDef::new( + let definition = CommandTypeDef::new( "RenamedInput", vec![field("wireId", "String", false, false, false, None)], ); diff --git a/src/graphql/command_contract/mod.rs b/src/command/mod.rs similarity index 95% rename from src/graphql/command_contract/mod.rs rename to src/command/mod.rs index 410c5dff1..991e6beff 100644 --- a/src/graphql/command_contract/mod.rs +++ b/src/command/mod.rs @@ -8,6 +8,12 @@ #![cfg_attr(not(feature = "graphql"), allow(dead_code))] +pub(crate) mod input; +mod types; + +pub(crate) use types::scalar_type_name; +pub use types::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; + mod direct_projection; mod effect_wire; mod effects; diff --git a/src/graphql/command_contract/outcomes.rs b/src/command/outcomes.rs similarity index 97% rename from src/graphql/command_contract/outcomes.rs rename to src/command/outcomes.rs index d279e59c7..e399378b1 100644 --- a/src/graphql/command_contract/outcomes.rs +++ b/src/command/outcomes.rs @@ -8,7 +8,7 @@ use super::projection_proof::{ validate_resolved_direct_plan, CommandCommitProofError, ProjectionCommitProof, }; use super::typed_command::TypedCommandContract; -use crate::graphql::types::{read_model_graphql_type, GraphqlOutputType, GraphqlTypeDef}; +use super::types::{read_model_command_type, CommandOutputType, CommandTypeDef}; use crate::outbox::OutboxMessage; use crate::projection::lower::LoweredProjectionPlan; use crate::projection_protocol::SameTransactionProjectionBatch; @@ -70,7 +70,7 @@ macro_rules! committed_outcome { impl CommandOutcome for $wrapper where - T: GraphqlOutputType + Serialize + Send + Sync + 'static, + T: CommandOutputType + Serialize + Send + Sync + 'static, { type Payload = T; const CONSISTENCY: CommandConsistency = $kind; @@ -83,8 +83,8 @@ macro_rules! committed_outcome { Self::from_committed_payload(payload) } - fn __graphql_output_type() -> GraphqlTypeDef { - T::graphql_type() + fn __command_output_type() -> CommandTypeDef { + T::command_type() } } }; @@ -110,8 +110,8 @@ where Self::from_committed_payload(payload) } - fn __graphql_output_type() -> GraphqlTypeDef { - read_model_graphql_type::() + fn __command_output_type() -> CommandTypeDef { + read_model_command_type::() } fn __projected_model() -> Option<(TypeId, &'static TableSchema)> { @@ -172,7 +172,7 @@ pub trait CommandOutcome: sealed::Outcome + Send + Sync + 'static { fn __finalize_committed(payload: Self::Payload) -> Self; #[doc(hidden)] - fn __graphql_output_type() -> GraphqlTypeDef; + fn __command_output_type() -> CommandTypeDef; /// Compiler-only model identity retained by an ordinary /// `typed_command::>` declaration. The sealed default keeps diff --git a/src/graphql/command_contract/projection_obligations.rs b/src/command/projection_obligations.rs similarity index 100% rename from src/graphql/command_contract/projection_obligations.rs rename to src/command/projection_obligations.rs diff --git a/src/graphql/command_contract/projection_proof.rs b/src/command/projection_proof.rs similarity index 100% rename from src/graphql/command_contract/projection_proof.rs rename to src/command/projection_proof.rs diff --git a/src/graphql/command_contract/projections.rs b/src/command/projections.rs similarity index 97% rename from src/graphql/command_contract/projections.rs rename to src/command/projections.rs index 59db4b96f..20c00e587 100644 --- a/src/graphql/command_contract/projections.rs +++ b/src/command/projections.rs @@ -100,7 +100,7 @@ impl CommandProjectionPreview { } /// Bind this preview to the exact outward event-set value also passed to - /// [`crate::graphql::TypedCommand::emits`]. + /// [`crate::command::TypedCommand::emits`]. #[must_use] pub fn events(mut self, events: CommandProjectionEventSet) -> Self { self.selectors = events.selectors; @@ -767,7 +767,7 @@ pub fn __command_projection_preview_constant( /// - `#[sourced]`-generated `domain_commands::*` transition witnesses (public /// aggregate methods that call domain-marked `#[event]` recorders) /// -/// Prefer [`crate::graphql::TypedCommand::emits_events`] with these types over +/// Prefer [`crate::command::TypedCommand::emits_events`] with these types over /// hand-maintaining a parallel event list when the domain already owns the /// transition. pub trait CommandEventSet { @@ -814,8 +814,8 @@ impl_command_event_set_tuple!(E1, E2, E3, E4, E5, E6, E7, E8); #[macro_export] macro_rules! events { ($($event:ty),+ $(,)?) => { - $crate::graphql::__command_projection_events([ - $($crate::graphql::__command_projection_event_descriptor::<$event>()),+ + $crate::command::__command_projection_events([ + $($crate::command::__command_projection_event_descriptor::<$event>()),+ ]) }; } @@ -829,7 +829,7 @@ macro_rules! state_preview { ( $event:ty => $state:ty { $($fields:tt)* } ) => {{ - $crate::graphql::__command_projection_state_preview::<$event, $state>( + $crate::command::__command_projection_state_preview::<$event, $state>( $crate::__distributed_state_preview_fields!(@collect [] ; $($fields)*) ) }}; @@ -841,7 +841,7 @@ macro_rules! event_preview { ( $event:ty => $body:ty { $($fields:tt)* } ) => {{ - $crate::graphql::__command_projection_event_preview::<$event, $body>( + $crate::command::__command_projection_event_preview::<$event, $body>( $crate::__distributed_state_preview_fields!(@collect [] ; $($fields)*) ) }}; @@ -865,7 +865,7 @@ macro_rules! __distributed_state_preview_fields { $($out,)* ( stringify!($field), - $crate::graphql::CommandProjectionPreviewSource::input([ + $crate::command::CommandProjectionPreviewSource::input([ stringify!($first) $(, stringify!($rest))* ]) ), @@ -882,7 +882,7 @@ macro_rules! __distributed_state_preview_fields { $($out,)* ( stringify!($field), - $crate::graphql::CommandProjectionPreviewSource::generated_default([ + $crate::command::CommandProjectionPreviewSource::generated_default([ stringify!($first) $(, stringify!($rest))* ]) ), @@ -899,7 +899,7 @@ macro_rules! __distributed_state_preview_fields { $($out,)* ( stringify!($field), - $crate::graphql::CommandProjectionPreviewSource::trusted($name, $codec) + $crate::command::CommandProjectionPreviewSource::trusted($name, $codec) ), ]; $($tail)* @@ -907,19 +907,19 @@ macro_rules! __distributed_state_preview_fields { }; (@collect [$($out:expr,)*] ; $field:ident : unknown, $($tail:tt)*) => { $crate::__distributed_state_preview_fields!( - @collect [$($out,)* (stringify!($field), $crate::graphql::CommandProjectionPreviewSource::Unknown),]; + @collect [$($out,)* (stringify!($field), $crate::command::CommandProjectionPreviewSource::Unknown),]; $($tail)* ) }; (@collect [$($out:expr,)*] ; $field:ident : absent, $($tail:tt)*) => { $crate::__distributed_state_preview_fields!( - @collect [$($out,)* (stringify!($field), $crate::graphql::CommandProjectionPreviewSource::Absent),]; + @collect [$($out,)* (stringify!($field), $crate::command::CommandProjectionPreviewSource::Absent),]; $($tail)* ) }; (@collect [$($out:expr,)*] ; $field:ident : null, $($tail:tt)*) => { $crate::__distributed_state_preview_fields!( - @collect [$($out,)* (stringify!($field), $crate::graphql::CommandProjectionPreviewSource::Null),]; + @collect [$($out,)* (stringify!($field), $crate::command::CommandProjectionPreviewSource::Null),]; $($tail)* ) }; @@ -929,7 +929,7 @@ macro_rules! __distributed_state_preview_fields { $($out,)* ( stringify!($field), - $crate::graphql::__command_projection_preview_constant($constant) + $crate::command::__command_projection_preview_constant($constant) ), ]; $($tail)* @@ -941,7 +941,7 @@ macro_rules! __distributed_state_preview_fields { $($out,)* ( stringify!($field), - $crate::graphql::__command_projection_preview_constant($constant) + $crate::command::__command_projection_preview_constant($constant) ), ]; $($tail)* diff --git a/src/graphql/command_contract/tests.rs b/src/command/tests.rs similarity index 96% rename from src/graphql/command_contract/tests.rs rename to src/command/tests.rs index e028e4f2e..9ae7d2eb9 100644 --- a/src/graphql/command_contract/tests.rs +++ b/src/command/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::graphql::{GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField}; +use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; use crate::microsvc::Session; use crate::outbox::OutboxMessage; use crate::projection_protocol::{ @@ -9,17 +9,30 @@ use crate::table::{ColumnType, PrimaryKey, TableColumn, TableKind, TableSchema}; use serde::{Deserialize, Serialize}; use std::any::TypeId; +#[test] +fn command_ledger_fingerprint_preserves_the_v1_canonical_contract() { + // The v1 digest includes historical field/scalar names. Module ownership + // must not change the identity used to recognize a command retry. + let (_, contract) = typed_command::>("core.fingerprint").into_parts(); + let digest = contract.fingerprint_bytes(); + let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect(); + assert_eq!( + hex, + "39cd9dbf7a1b3a17e0ee5c04841af2af95b0ba391c07eced4c4e1a80d9e55be5" + ); +} + #[allow(dead_code)] #[derive(Deserialize)] struct Input { id: String, } -impl GraphqlInputType for Input { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for Input { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "Input", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -123,11 +136,11 @@ impl crate::domain_event::DomainEventContract for DishonestStateContract { impl crate::domain_event::DomainEventBodyContract for DishonestStateContract {} -impl GraphqlOutputType for Payload { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for Payload { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "Payload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -847,11 +860,11 @@ fn command_fingerprints_canonicalize_nested_json_object_keys() { } #[test] -fn binding_rejects_missing_graphql_type_ids() { +fn binding_rejects_missing_command_type_ids() { let mut contract = typed_command::>("todo.create").into_contract(); contract.input.type_id = None; let error = TypedServiceCommandBinding::from_contracts("todos", &[contract]).unwrap_err(); - assert!(error.contains("input GraphQL metadata is missing")); + assert!(error.contains("input command metadata is missing")); } #[test] @@ -859,7 +872,7 @@ fn binding_canonicalizes_fields_and_roles_but_preserves_effect_order() { let mut first = typed_command::>("todo.create") .roles(["writer", "admin"]) .into_contract(); - first.input.fields.push(GraphqlTypeField { + first.input.fields.push(CommandTypeField { name: "z_extra".into(), type_name: "String".into(), nullable: true, @@ -886,7 +899,7 @@ fn binding_canonicalizes_fields_and_roles_but_preserves_effect_order() { let mut reordered = typed_command::>("todo.create") .roles(["writer", "admin"]) .into_contract(); - reordered.input.fields.push(GraphqlTypeField { + reordered.input.fields.push(CommandTypeField { name: "z_extra".into(), type_name: "String".into(), nullable: true, diff --git a/src/graphql/command_contract/typed_command.rs b/src/command/typed_command.rs similarity index 97% rename from src/graphql/command_contract/typed_command.rs rename to src/command/typed_command.rs index 3f2ef88f1..221b0ffe8 100644 --- a/src/graphql/command_contract/typed_command.rs +++ b/src/command/typed_command.rs @@ -24,8 +24,7 @@ use super::projections::{ CommandProjectionEvents, CommandProjectionPreview, CommandProjectionPreviewSource, CommandProjectionPureReduce, }; -use crate::graphql::naming; -use crate::graphql::types::{GraphqlInputType, GraphqlTypeDef}; +use super::types::{scalar_type_name, CommandInputType, CommandTypeDef}; use crate::microsvc::Session; use crate::outbox::OutboxMessage; use crate::projection_protocol::{ @@ -39,8 +38,8 @@ pub(crate) struct TypedCommandContract { pub name: String, pub field_name: String, pub roles: Vec, - pub input: GraphqlTypeDef, - pub output: GraphqlTypeDef, + pub input: CommandTypeDef, + pub output: CommandTypeDef, pub input_type_id: TypeId, pub output_type_id: TypeId, pub consistency: CommandConsistency, @@ -111,8 +110,8 @@ impl TypedCommandContract { "name": self.name, "field_name": self.field_name, "roles": roles, - "input": canonical_graphql_type(&self.input), - "output": canonical_graphql_type(&self.output), + "input": canonical_command_type(&self.input), + "output": canonical_command_type(&self.output), "consistency": self.consistency, "input_defaults": input_defaults, "effects": effects, @@ -166,7 +165,7 @@ impl TypedCommandContract { .iter() .find(|column| column.column_name == field.field) }) - .and_then(|column| naming::scalar_type_name(&column.column_type)), + .and_then(|column| scalar_type_name(&column.column_type)), ) .map(|value| ResolvedProjectionKeyField { field: field.field.clone(), @@ -343,7 +342,7 @@ fn resolve_projection_obligation_expression( } } -fn canonical_graphql_type(definition: &GraphqlTypeDef) -> serde_json::Value { +fn canonical_command_type(definition: &CommandTypeDef) -> serde_json::Value { let mut fields = definition.fields.iter().collect::>(); fields.sort_by(|left, right| left.name.cmp(&right.name)); serde_json::json!({ @@ -354,7 +353,7 @@ fn canonical_graphql_type(definition: &GraphqlTypeDef) -> serde_json::Value { "nullable": field.nullable, "list": field.list, "item_nullable": field.item_nullable, - "nested": field.nested.as_deref().map(canonical_graphql_type), + "nested": field.nested.as_deref().map(canonical_command_type), })).collect::>(), }) } @@ -399,13 +398,13 @@ impl TypedServiceCommandBinding { } if contract.input.type_id != Some(contract.input_type_id) { return Err(format!( - "typed command `{}` input GraphQL metadata is missing or has a different Rust TypeId", + "typed command `{}` input command metadata is missing or has a different Rust TypeId", contract.name )); } if contract.output.type_id != Some(contract.output_type_id) { return Err(format!( - "typed command `{}` output GraphQL metadata is missing or has a different Rust TypeId", + "typed command `{}` output command metadata is missing or has a different Rust TypeId", contract.name )); } @@ -565,7 +564,7 @@ impl Clone for TypedCommand { /// Begin a typed command declaration. pub fn typed_command(name: &'static str) -> TypedCommand where - I: GraphqlInputType + DeserializeOwned + Send + 'static, + I: CommandInputType + DeserializeOwned + Send + 'static, K: CommandOutcome, { let route_name = name; @@ -577,8 +576,8 @@ where other => other, }) .collect(); - let input = I::graphql_type(); - let output = K::__graphql_output_type(); + let input = I::command_type(); + let output = K::__command_output_type(); let projected_model = K::__projected_model() .map(|(output_type_id, schema)| CommandProjectedModel::new(output_type_id, schema)); TypedCommand { @@ -616,7 +615,7 @@ where pub fn command_transition(name: &'static str) -> TypedCommand where S: super::CommandEventSet, - I: GraphqlInputType + DeserializeOwned + Send + 'static, + I: CommandInputType + DeserializeOwned + Send + 'static, K: CommandOutcome, { typed_command::(name).emits_events::() @@ -750,7 +749,7 @@ impl TypedCommand { impl TypedCommand> where - I: GraphqlInputType + DeserializeOwned + Send + 'static, + I: CommandInputType + DeserializeOwned + Send + 'static, M: RelationalReadModel + Serialize + Send + Sync + 'static, { /// Attach compiler-generated direct projection ownership metadata. diff --git a/src/command/types.rs b/src/command/types.rs new file mode 100644 index 000000000..4e38cc946 --- /dev/null +++ b/src/command/types.rs @@ -0,0 +1,134 @@ +//! Transport-neutral command data shapes. +//! +//! Scalar names are stable codec identifiers shared by command validation, +//! fingerprints, and client artifacts. Their historical spellings are retained +//! for wire compatibility; adapters own syntax and representability checks. + +use std::any::TypeId; + +use crate::read_model::RelationalReadModel; +use crate::table::ColumnType; + +/// One field on a command input or output object. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommandTypeField { + pub name: String, + pub type_name: String, + pub nullable: bool, + pub list: bool, + /// Whether list elements are nullable. Always `false` for non-list fields. + pub item_nullable: bool, + /// Nested object type definition when `type_name` is not a scalar. + pub nested: Option>, +} + +/// Full type definition for a derive-emitted input or output object. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommandTypeDef { + pub name: String, + pub fields: Vec, + pub type_id: Option, +} + +impl CommandTypeDef { + pub fn new(name: impl Into, fields: Vec) -> Self { + Self { + name: name.into(), + fields, + type_id: None, + } + } + + pub fn with_type_id(mut self, id: TypeId) -> Self { + self.type_id = Some(id); + self + } + + /// Transitive nested type defs (depth-first, deduped by name). + pub fn transitive_nested(&self) -> Vec { + let mut out = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + self.collect_nested(&mut out, &mut seen); + out + } + + fn collect_nested( + &self, + out: &mut Vec, + seen: &mut std::collections::BTreeSet, + ) { + for field in &self.fields { + if let Some(nested) = &field.nested { + if seen.insert(nested.name.clone()) { + out.push((**nested).clone()); + nested.collect_nested(out, seen); + } + } + } + } +} + +/// Structural description of the serialized input accepted by a command. +/// +/// Prefer deriving [`CommandInput`](crate::CommandInput). Field names follow +/// Serde's deserialization direction. Transport-specific naming restrictions +/// are checked when an adapter exposes the declaration. +pub trait CommandInputType { + fn command_type() -> CommandTypeDef; +} + +/// Structural description of a command result, following Serde serialization. +/// +/// Prefer deriving [`CommandOutput`](crate::CommandOutput). Atomic read-model +/// outcomes derive their shape directly from the relational schema instead. +pub trait CommandOutputType { + fn command_type() -> CommandTypeDef; +} + +/// Build a command-output object from the same relational schema that owns +/// the stored read model. +/// +/// Atomic command results contain stored columns only. Relationships stay +/// query-time fields and are never invented by a same-transaction row result. +pub(crate) fn read_model_command_type() -> CommandTypeDef +where + M: RelationalReadModel + 'static, +{ + let schema = M::schema(); + let fields = schema + .columns + .iter() + .filter(|column| !column.skipped) + .map(|column| { + let type_name = scalar_type_name(&column.column_type).unwrap_or_else(|| { + panic!( + "read model `{}` column `{}` has no command scalar mapping", + schema.model_name, column.column_name + ) + }); + CommandTypeField { + name: column.column_name.clone(), + type_name: type_name.into(), + nullable: column.nullable, + list: false, + item_nullable: false, + nested: None, + } + }) + .collect(); + CommandTypeDef::new(schema.model_name.clone(), fields).with_type_id(TypeId::of::()) +} + +/// Stable scalar codec name for a relational column in a command result. +pub(crate) fn scalar_type_name(column_type: &ColumnType) -> Option<&'static str> { + match column_type { + ColumnType::Text => Some("String"), + ColumnType::Boolean => Some("Boolean"), + ColumnType::Integer | ColumnType::UnsignedInteger => Some("BigInt"), + ColumnType::Float => Some("Float"), + ColumnType::Json => Some("JSON"), + ColumnType::Timestamp => Some("Timestamptz"), + ColumnType::Bytes => Some("Bytea"), + ColumnType::Unsupported(_) => None, + } +} diff --git a/src/graphql/client_manifest/projections.rs b/src/graphql/client_manifest/projections.rs index 4ef863fa0..bc79d5025 100644 --- a/src/graphql/client_manifest/projections.rs +++ b/src/graphql/client_manifest/projections.rs @@ -4,7 +4,7 @@ use serde::Serialize; use sha2::{Digest, Sha256}; use super::*; -use crate::graphql::command_contract::CommandProjectionPreviewSource; +use crate::command::CommandProjectionPreviewSource; use crate::graphql::surface::{ SurfaceProjectionArm, SurfaceProjectionOperation, SurfaceSelectedProjectionProgram, }; @@ -301,8 +301,8 @@ pub(super) fn command_projection_extension( .pure_reduces .iter() .map(|reduce| { + use crate::command::CommandProjectionPreviewSource as ServerSource; use crate::graphql::client_manifest::ClientProjectionPreviewSource as ClientSource; - use crate::graphql::command_contract::CommandProjectionPreviewSource as ServerSource; let map_source = |source: &ServerSource| -> Result { Ok(match source { ServerSource::InputPath { path } => ClientSource::Input { path: path.clone() }, @@ -1341,9 +1341,9 @@ fn mutation_kind(kind: ProjectionMutationKind) -> ClientProjectionMutationKind { #[cfg(test)] mod tests { use super::*; + use crate::command::{CommandProjectionPreview, CommandProjectionPreviewSource}; use crate::graphql::{ - build_surface, CommandProjectionPreview, CommandProjectionPreviewSource, SurfaceOptions, - SurfaceProjector, SurfaceTypeDef, SurfaceTypeField, + build_surface, SurfaceOptions, SurfaceProjector, SurfaceTypeDef, SurfaceTypeField, }; use crate::projection::lower::ProjectionPortableType; use crate::projection::placement::{ @@ -1656,7 +1656,8 @@ mod tests { #[test] fn auto_optimism_maps_input_defaults_and_row_policy_claims() { - use crate::graphql::command_contract::{CommandInputDefault, InputDefaultGenerator}; + use crate::command::{CommandInputDefault, InputDefaultGenerator}; + use crate::graphql::{claim, col}; let selector = typed_selector::(); @@ -1842,7 +1843,7 @@ mod tests { command.consistency = consistency; command.projections.add_event_set(crate::events![PreviewA]); command.projections.add_inferred_values( - crate::graphql::__command_projection_event_preview::(vec![( + crate::command::__command_projection_event_preview::(vec![( "value", CommandProjectionPreviewSource::constant(ProjectionValue::string( "transition-value", diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index e51ce989c..3df26c721 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -1,9 +1,9 @@ use super::*; +use crate::command::{typed_command, Eventual, PreparedCommand, Succeeded}; use crate::graphql::{ - build_surface, claim, col, rel, surface_for_application, surface_for_role, typed_command, - Eventual, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, - PreparedCommand, RoleGrant, Succeeded, SurfaceCommand, SurfaceOptions, SurfaceProjector, - SurfaceTypeField, + build_surface, claim, col, rel, surface_for_application, surface_for_role, GraphqlInputType, + GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, RoleGrant, SurfaceCommand, SurfaceOptions, + SurfaceProjector, SurfaceTypeField, }; use crate::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use crate::table::{ @@ -897,11 +897,11 @@ fn role_and_application_partition_manifests_hide_raw_paths_and_denied_values() { .unwrap() .projections .add_preview( - crate::graphql::CommandProjectionPreview::new() + crate::command::CommandProjectionPreview::new() .events(crate::events![ManifestTodoProjected]) .field( ["private_partition_path"], - crate::graphql::CommandProjectionPreviewSource::constant( + crate::command::CommandProjectionPreviewSource::constant( crate::ProjectionValue::string("denied-partition-value"), ), ), @@ -1413,7 +1413,7 @@ fn denied_modeled_projection_exports_no_program_event_slot_or_preset_identity() .find(|command| command.command_name == "todo.complete") .unwrap(); command.projections.previews[0].preview.fields[0].source = - crate::graphql::CommandProjectionPreviewSource::trusted("denied-owner-secret", "string"); + crate::command::CommandProjectionPreviewSource::trusted("denied-owner-secret", "string"); let selected = surface_for_role( &full, "user", diff --git a/src/graphql/commands.rs b/src/graphql/commands.rs index bdff37aed..2e59b30f9 100644 --- a/src/graphql/commands.rs +++ b/src/graphql/commands.rs @@ -17,14 +17,14 @@ use super::surface::{ SurfaceProjectionOwner, }; use super::surface::{SurfaceCommand, SurfaceCommandShape, SurfaceTypeDef, SurfaceTypeField}; -use super::types::GraphqlTypeDef; +use crate::command::CommandTypeDef; #[derive(Clone, Debug, Default)] pub(crate) struct TypedCommandInventory { contracts: Vec, } -fn surface_type(definition: &GraphqlTypeDef) -> SurfaceTypeDef { +fn surface_type(definition: &CommandTypeDef) -> SurfaceTypeDef { SurfaceTypeDef { name: definition.name.clone(), fields: definition diff --git a/src/graphql/engine/public_api.rs b/src/graphql/engine/public_api.rs index 05e5889c0..d3bced410 100644 --- a/src/graphql/engine/public_api.rs +++ b/src/graphql/engine/public_api.rs @@ -63,7 +63,7 @@ impl GraphqlEngine { pub(crate) fn typed_command_contracts_for_service( &self, - ) -> Result, String> { + ) -> Result, String> { Ok(self.inner.typed_commands.contracts_for_binding()) } diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index 17ab123d1..6c5b93b0a 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -9,13 +9,14 @@ mod client_surface_parity_tests { use sha2::{Digest, Sha256}; use super::*; - use crate::graphql::command_contract::{CommandEffects, TypedCommandContract}; + use crate::command::CommandConsistency; + use crate::command::{CommandEffects, TypedCommandContract}; use crate::graphql::commands::TypedCommandInventory; #[cfg(feature = "sqlite")] use crate::graphql::ModelNormalization; use crate::graphql::{ - claim, col, ClientRootOperation, CommandConsistency, DistributedClientSurfaceExport, - GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, RoleGrant, + claim, col, ClientRootOperation, DistributedClientSurfaceExport, GraphqlInputType, + GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, RoleGrant, }; use crate::table::{ColumnType, PrimaryKey, TableColumn, TableKind, TableSchema}; #[cfg(feature = "sqlite")] @@ -71,8 +72,8 @@ mod client_surface_parity_tests { name: command_name.into(), field_name: field_name.into(), roles: roles.iter().map(|role| (*role).into()).collect(), - input: I::graphql_type().with_type_id(TypeId::of::()), - output: O::graphql_type().with_type_id(TypeId::of::()), + input: I::graphql_type().with_type_id(TypeId::of::()).into(), + output: O::graphql_type().with_type_id(TypeId::of::()).into(), input_type_id: TypeId::of::(), output_type_id: TypeId::of::(), consistency: CommandConsistency::Succeeded, diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index 0710e8568..a546d46a2 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -6,7 +6,7 @@ //! `feature = "graphql"`. pub mod client_manifest; -pub(crate) mod command_contract; +pub(crate) use crate::command as command_contract; pub mod naming; pub mod projection_delta; pub mod sdl; @@ -70,7 +70,6 @@ pub use permissions::{ }; pub use types::{GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField}; -pub(crate) mod command_input; #[cfg(feature = "graphql")] mod compile; #[cfg(feature = "graphql")] diff --git a/src/graphql/naming.rs b/src/graphql/naming.rs index 39f07fa2f..834f7f1a1 100644 --- a/src/graphql/naming.rs +++ b/src/graphql/naming.rs @@ -88,16 +88,7 @@ pub fn max_fields_type_name(schema: &TableSchema) -> String { /// Map a column type to its GraphQL scalar type name (without nullability). pub fn scalar_type_name(column_type: &ColumnType) -> Option<&'static str> { - match column_type { - ColumnType::Text => Some("String"), - ColumnType::Boolean => Some("Boolean"), - ColumnType::Integer | ColumnType::UnsignedInteger => Some("BigInt"), - ColumnType::Float => Some("Float"), - ColumnType::Json => Some("JSON"), - ColumnType::Timestamp => Some("Timestamptz"), - ColumnType::Bytes => Some("Bytea"), - ColumnType::Unsupported(_) => None, - } + crate::command::scalar_type_name(column_type) } pub fn comparison_exp_name(scalar: &str) -> String { diff --git a/src/graphql/projection_delta/tests.rs b/src/graphql/projection_delta/tests.rs index fddf3dad9..906bbb401 100644 --- a/src/graphql/projection_delta/tests.rs +++ b/src/graphql/projection_delta/tests.rs @@ -17,6 +17,7 @@ use super::types::{ ProjectionMutationSource, }; use super::*; + use crate::graphql::{ build_surface, surface_for_role, DistributedClientSurfaceExport, RoleGrant, SurfaceDirectProjection, SurfaceOptions, SurfaceProjector, @@ -687,7 +688,7 @@ fn zero_obligation_modeled_metadata_is_revalidated_on_every_receipt_emission() { command_id: "0190a000-0000-7000-8000-000000000011".into(), command_name: Some(TEST_COMMAND_NAME.into()), causation_id: Some(TEST_CAUSATION_ID.into()), - consistency: Some(crate::graphql::command_contract::CommandConsistency::Eventual), + consistency: Some(crate::command::CommandConsistency::Eventual), outcome: None, obligations: Vec::new(), projection_metadata: Some(metadata), @@ -702,7 +703,7 @@ fn zero_obligation_modeled_metadata_is_revalidated_on_every_receipt_emission() { command_id: "modeled-status-command".into(), command_name: TEST_COMMAND_NAME.into(), causation_id: TEST_CAUSATION_ID.into(), - consistency: crate::graphql::command_contract::CommandConsistency::Eventual, + consistency: crate::command::CommandConsistency::Eventual, state: crate::command_ledger::CommandLedgerState::SucceededPendingProjection, outcome: serde_json::json!({"ok": true}), obligations: Vec::new(), @@ -880,7 +881,7 @@ fn zero_occurrence_metadata_is_classified_from_the_current_causal_command_contra command_id: "0190a000-0000-7000-8000-000000000012".into(), command_name: TEST_COMMAND_NAME.into(), causation_id: TEST_CAUSATION_ID.into(), - consistency: crate::graphql::command_contract::CommandConsistency::Eventual, + consistency: crate::command::CommandConsistency::Eventual, state: crate::command_ledger::CommandLedgerState::Succeeded, outcome: serde_json::json!({"accepted": true}), obligations: Vec::new(), @@ -1424,7 +1425,7 @@ fn active_metadata_revalidates_but_remains_queryable_while_projection_is_drainin command_id: "0190a000-0000-7000-8000-000000000018".into(), command_name: TEST_COMMAND_NAME.into(), causation_id: TEST_CAUSATION_ID.into(), - consistency: crate::graphql::command_contract::CommandConsistency::Eventual, + consistency: crate::command::CommandConsistency::Eventual, state: crate::command_ledger::CommandLedgerState::Atomic, outcome: serde_json::json!({"id": "todo-draining-status"}), obligations: Vec::new(), @@ -1485,7 +1486,7 @@ fn active_metadata_revalidates_but_remains_queryable_while_projection_is_drainin command_id: "0190a000-0000-7000-8000-000000000019".into(), command_name: Some(TEST_COMMAND_NAME.into()), causation_id: Some(TEST_CAUSATION_ID.into()), - consistency: Some(crate::graphql::command_contract::CommandConsistency::Eventual), + consistency: Some(crate::command::CommandConsistency::Eventual), outcome: None, obligations: Vec::new(), projection_metadata: Some(metadata.clone()), @@ -1523,7 +1524,7 @@ fn active_metadata_revalidates_but_remains_queryable_while_projection_is_drainin command_id: "0190a000-0000-7000-8000-000000000019".into(), command_name: TEST_COMMAND_NAME.into(), causation_id: TEST_CAUSATION_ID.into(), - consistency: crate::graphql::command_contract::CommandConsistency::Eventual, + consistency: crate::command::CommandConsistency::Eventual, state: crate::command_ledger::CommandLedgerState::SucceededPendingProjection, outcome: serde_json::json!({"id": "todo-draining-status"}), obligations: Vec::new(), @@ -1591,7 +1592,7 @@ fn lifecycle_status_rejects_changed_deployment_identity_and_mixed_fanout_tamperi command_id: "0190a000-0000-7000-8000-000000000020".into(), command_name: TEST_COMMAND_NAME.into(), causation_id: TEST_CAUSATION_ID.into(), - consistency: crate::graphql::command_contract::CommandConsistency::Eventual, + consistency: crate::command::CommandConsistency::Eventual, state: crate::command_ledger::CommandLedgerState::SucceededPendingProjection, outcome: serde_json::json!({"id": "todo-lifecycle-hostile"}), obligations: Vec::new(), @@ -3527,16 +3528,16 @@ fn selected_export_join(surface: &crate::graphql::Surface) -> DistributedClientS } fn surface_with_modeled_command(surface: &crate::graphql::Surface) -> crate::graphql::Surface { - let contract = crate::graphql::typed_command::< + let contract = crate::command::typed_command::< ModeledCommandInput, - crate::graphql::Eventual, + crate::command::Eventual, >(TEST_COMMAND_NAME) .roles(["delta-user"]) - .emits(crate::graphql::__command_projection_events([Ok( + .emits(crate::command::__command_projection_events([Ok( event_descriptor(), )])) .into_contract(); - let binding = crate::graphql::command_contract::TypedServiceCommandBinding::from_contracts( + let binding = crate::command::TypedServiceCommandBinding::from_contracts( "delta-service", std::slice::from_ref(&contract), ) diff --git a/src/graphql/protocol/accumulator.rs b/src/graphql/protocol/accumulator.rs index aff28148b..b41a70301 100644 --- a/src/graphql/protocol/accumulator.rs +++ b/src/graphql/protocol/accumulator.rs @@ -13,8 +13,8 @@ use super::{ OpaqueProtocolToken, ProtocolTokenCodec, ProtocolTokenError, ProtocolTokenPurpose, RequestedLiveResume, }; +use crate::command::CommandConsistency; use crate::command_ledger::CommandLedgerState; -use crate::graphql::command_contract::CommandConsistency; use crate::graphql::projection_delta::runtime::ModeledProjectionStatusDisposition; use crate::microsvc::{ CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandPublicStatus, diff --git a/src/graphql/protocol/tests.rs b/src/graphql/protocol/tests.rs index 17fe657f4..abef4469f 100644 --- a/src/graphql/protocol/tests.rs +++ b/src/graphql/protocol/tests.rs @@ -1,7 +1,7 @@ use super::accumulator::ProtocolAccumulatorError; use super::*; +use crate::command::CommandConsistency; use crate::command_ledger::CommandLedgerState; -use crate::graphql::command_contract::CommandConsistency; use crate::microsvc::{ CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandPublicStatus, CausalCommandReceiptSource, CausalProjectionEvidenceState, diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 6e012a4f2..49537fe11 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -1139,8 +1139,8 @@ mod causal_command_schema_tests { use std::sync::Arc; use super::*; + use crate::command::{CommandConsistency, CommandEffects}; use crate::command_dispatch::{LocalCommandHost, SharedCommandHost}; - use crate::graphql::command_contract::{CommandConsistency, CommandEffects}; use crate::graphql::protocol::{ DistributedEnvelopeV1, ProtocolResponseAccumulator, ProtocolTokenCodec, ProtocolTokenPurpose, diff --git a/src/graphql/sdl.rs b/src/graphql/sdl.rs index 1721edef2..8af2e41fd 100644 --- a/src/graphql/sdl.rs +++ b/src/graphql/sdl.rs @@ -588,7 +588,7 @@ pub fn graphql_sdl_from_schemas( #[cfg(test)] mod causal_command_sdl_tests { use super::*; - use crate::graphql::command_contract::{CommandConsistency, CommandEffects}; + use crate::command::{CommandConsistency, CommandEffects}; use crate::graphql::surface::{SurfaceCommandShape, SurfaceTypeDef}; fn command_surface() -> crate::graphql::surface::Surface { diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index 5041b2d40..3e4048fdd 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -1,8 +1,9 @@ use std::any::TypeId; use super::*; -use crate::graphql::command_contract::{CommandEffects, TypedCommandContract}; +use crate::command::{CommandEffects, TypedCommandContract}; use crate::graphql::commands::TypedCommandInventory; + use crate::graphql::{GraphqlTypeDef, GraphqlTypeField}; use crate::table::{ ColumnType, PrimaryKey, RelationshipDef, RelationshipKind, TableColumn, TableKind, @@ -243,8 +244,9 @@ fn test_command( nested: None, }], ) - .with_type_id(input_type_id), - output: output.with_type_id(output_type_id), + .with_type_id(input_type_id) + .into(), + output: output.with_type_id(output_type_id).into(), input_type_id, output_type_id, consistency: CommandConsistency::Succeeded, diff --git a/src/graphql/surface/types.rs b/src/graphql/surface/types.rs index 06443a3b5..628622cae 100644 --- a/src/graphql/surface/types.rs +++ b/src/graphql/surface/types.rs @@ -540,8 +540,7 @@ pub struct Surface { pub(crate) projectors_attached: bool, /// Non-serializable provenance proving typed commands came from one /// executable Service inventory rather than a lookalike command list. - pub(crate) service_binding: - Option, + pub(crate) service_binding: Option, } /// Debug output is intentionally limited to already-authorized public IDs. @@ -865,7 +864,7 @@ impl Surface { #[cfg(any(test, feature = "graphql"))] pub(crate) fn with_service_binding( mut self, - binding: Option, + binding: Option, ) -> Self { self.service_binding = binding; self diff --git a/src/graphql/types.rs b/src/graphql/types.rs index bb50ebd28..1be5da675 100644 --- a/src/graphql/types.rs +++ b/src/graphql/types.rs @@ -2,8 +2,7 @@ use std::any::TypeId; -use crate::graphql::naming::scalar_type_name; -use crate::read_model::RelationalReadModel; +use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; /// One field on a GraphQL input or output object. #[derive(Clone, Debug, PartialEq, Eq)] @@ -72,40 +71,6 @@ pub trait GraphqlOutputType { fn graphql_type() -> GraphqlTypeDef; } -/// Build a command-output object from the same relational schema that owns -/// the generated query object. -/// -/// Atomic command results contain stored columns only. Relationships stay -/// query-time fields and are never invented by a same-transaction row result. -pub(crate) fn read_model_graphql_type() -> GraphqlTypeDef -where - M: RelationalReadModel + 'static, -{ - let schema = M::schema(); - let fields = schema - .columns - .iter() - .filter(|column| !column.skipped) - .map(|column| { - let type_name = scalar_type_name(&column.column_type).unwrap_or_else(|| { - panic!( - "read model `{}` column `{}` has no GraphQL scalar mapping", - schema.model_name, column.column_name - ) - }); - GraphqlTypeField { - name: column.column_name.clone(), - type_name: type_name.into(), - nullable: column.nullable, - list: false, - item_nullable: false, - nested: None, - } - }) - .collect(); - GraphqlTypeDef::new(schema.model_name.clone(), fields).with_type_id(TypeId::of::()) -} - // Builtin scalar mappings for free-standing helpers used by derives. #[allow(dead_code)] pub fn scalar_for_rust_type(ty: &str) -> Option<&'static str> { @@ -120,3 +85,66 @@ pub fn scalar_for_rust_type(ty: &str) -> Option<&'static str> { _ => None, } } + +// Legacy GraphQL authors can keep their derives/manual implementations. The core +// depends only on command traits; the adapter translates legacy metadata here. +impl CommandInputType for T { + fn command_type() -> CommandTypeDef { + T::graphql_type().into() + } +} +impl CommandOutputType for T { + fn command_type() -> CommandTypeDef { + T::graphql_type().into() + } +} + +impl From for CommandTypeDef { + fn from(value: GraphqlTypeDef) -> Self { + Self { + name: value.name, + type_id: value.type_id, + fields: value + .fields + .into_iter() + .map(|field| CommandTypeField { + name: field.name, + type_name: field.type_name, + nullable: field.nullable, + list: field.list, + item_nullable: field.item_nullable, + nested: field.nested.map(|nested| Box::new((*nested).into())), + }) + .collect(), + } + } +} + +/// Derive GraphQL metadata from a transport-neutral command descriptor. +impl From for GraphqlTypeDef { + fn from(value: CommandTypeDef) -> Self { + Self { + name: value.name, + type_id: value.type_id, + fields: value + .fields + .into_iter() + .map(|field| GraphqlTypeField { + name: field.name, + type_name: field.type_name, + nullable: field.nullable, + list: field.list, + item_nullable: field.item_nullable, + nested: field.nested.map(|nested| Box::new((*nested).into())), + }) + .collect(), + } + } +} + +// Preserve the existing public conversion at the compatibility boundary. +impl From<&GraphqlTypeDef> for crate::application::CommandTypeSpec { + fn from(value: &GraphqlTypeDef) -> Self { + Self::from(&CommandTypeDef::from(value.clone())) + } +} diff --git a/src/lib.rs b/src/lib.rs index 473dd9a09..118aa27fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,7 @@ mod time; pub mod aggregate; pub mod application; pub mod bus; +pub mod command; pub mod command_dispatch; pub mod domain_event; pub mod entity; @@ -468,8 +469,8 @@ pub use microsvc::{ // mount); commands predict events via `.emits`/`.preview`. pub use distributed_macros::{ aggregate, application, command, command_input_defaults, digest, module, mutation, - mutation_file, portable_command, sourced, DomainEvent, DomainState, GraphqlInput, - GraphqlOutput, ReadModel, Snapshot, + mutation_file, portable_command, sourced, CommandInput, CommandOutput, DomainEvent, + DomainState, GraphqlInput, GraphqlOutput, ReadModel, Snapshot, }; // Re-export enqueue macro (requires "emitter" feature) diff --git a/src/microsvc/causal.rs b/src/microsvc/causal.rs index 3ba2e54b8..3eb650802 100644 --- a/src/microsvc/causal.rs +++ b/src/microsvc/causal.rs @@ -17,13 +17,13 @@ use std::sync::Mutex; use serde::Serialize; use crate::aggregate::{hydrate, Aggregate, AggregateRepository}; +use crate::command::{ + validate_resolved_direct_plan, Atomic, CommandCommitProofError, CommandOutcome, + PrepareCommandError, PreparedCommand, ProjectionCommitProof, ResolvedDirectProjectionTarget, + TypedCommandContract, +}; use crate::command_ledger::CausalGetStream; use crate::domain_event::{DomainEventCaptureError, DomainEventCommitGuardError}; -use crate::graphql::command_contract::{ - validate_resolved_direct_plan, CommandCommitProofError, CommandOutcome, ProjectionCommitProof, - ResolvedDirectProjectionTarget, TypedCommandContract, -}; -use crate::graphql::{Atomic, PrepareCommandError, PreparedCommand}; use crate::outbox::{OutboxMessage, PreparedDomainEvent}; use crate::projection::lower::{ DirectCandidate, LoweredProjectionPlan, ProjectionDescriptor, @@ -1292,7 +1292,7 @@ mod tests { workspace.stage(aggregate).unwrap(); let mut parts = workspace.into_parts().unwrap(); - let contract = crate::graphql::typed_command::>("test.project") + let contract = crate::command::typed_command::>("test.project") .into_contract(); parts.validate_prepared(&contract, &mut prepared).unwrap(); } @@ -1308,7 +1308,7 @@ mod tests { }) .unwrap(); let mut parts = workspace.into_parts().unwrap(); - let contract = crate::graphql::typed_command::>("test.project") + let contract = crate::command::typed_command::>("test.project") .into_contract(); assert!(matches!( @@ -1339,7 +1339,7 @@ mod tests { .unwrap(); workspace.stage_read_models(conflicting).unwrap(); let mut parts = workspace.into_parts().unwrap(); - let contract = crate::graphql::typed_command::>("test.project") + let contract = crate::command::typed_command::>("test.project") .into_contract(); assert!(matches!( @@ -1368,7 +1368,7 @@ mod tests { mutation .values .insert("title", RowValue::String("different".into())); - let contract = crate::graphql::typed_command::>("test.project") + let contract = crate::command::typed_command::>("test.project") .into_contract(); assert!(matches!( @@ -1384,7 +1384,7 @@ mod tests { } fn modeled_direct_contract() -> TypedCommandContract { - crate::graphql::typed_command::>("test.modeled-direct") + crate::command::typed_command::>("test.modeled-direct") .into_contract() } diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index a6f536b5c..97fe536c1 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -3,8 +3,8 @@ use super::{ CellNamespace, CellStreamStore, DURABLE_AGGREGATE_CELL_STATE_VERSION, }; use crate::aggregate::{Aggregate, AggregateRepository}; +use crate::command::{typed_command, PreparedCommand, Succeeded}; use crate::entity::Entity; -use crate::graphql::{typed_command, PreparedCommand, Succeeded}; use crate::microsvc::service::{CausalCommandContext, PortableCommand, Routes}; use crate::microsvc::session::{Session, USER_ID_KEY}; use crate::microsvc::HandlerError; diff --git a/src/microsvc/service/causal.rs b/src/microsvc/service/causal.rs index 4f0448ea6..75abb65e2 100644 --- a/src/microsvc/service/causal.rs +++ b/src/microsvc/service/causal.rs @@ -4,6 +4,8 @@ use std::time::Duration; #[cfg(feature = "graphql")] use serde_json::Value; +#[cfg(feature = "graphql")] +use crate::command::{CommandConsistency, TypedCommandContract}; #[cfg(feature = "graphql")] use crate::command_ledger::CausalTransactionalCommit; #[cfg(feature = "graphql")] @@ -13,8 +15,6 @@ use crate::command_ledger::{ TerminalCommandState, }; #[cfg(feature = "graphql")] -use crate::graphql::command_contract::{CommandConsistency, TypedCommandContract}; -#[cfg(feature = "graphql")] use crate::microsvc::error::HandlerError; #[cfg(feature = "graphql")] use crate::microsvc::session::Session; @@ -445,7 +445,7 @@ impl CausalDispatchResult { command_id: wire.receipt.command_id, command_name: String::new(), causation_id: wire.receipt.causation_id, - consistency: crate::graphql::CommandConsistency::Succeeded, + consistency: crate::command::CommandConsistency::Succeeded, state, outcome: Value::Null, obligations: Vec::new(), diff --git a/src/microsvc/service/handlers.rs b/src/microsvc/service/handlers.rs index b64fa38e6..c7d5a891f 100644 --- a/src/microsvc/service/handlers.rs +++ b/src/microsvc/service/handlers.rs @@ -8,9 +8,11 @@ use serde_json::Value; use crate::aggregate::Aggregate; use crate::bus::Message; +use crate::command::{ + Atomic, CommandOutcome, CommandOutputType, Eventual, PreparedCommand, Succeeded, +}; use crate::domain_event::DomainEvent; -use crate::graphql::command_contract::CommandOutcome; -use crate::graphql::{Atomic, Eventual, GraphqlOutputType, PreparedCommand, Succeeded}; + use crate::microsvc::causal::{AggregatePublication, CausalWorkspace, CausalWorkspaceError}; use crate::microsvc::context::Context; use crate::microsvc::error::HandlerError; @@ -431,7 +433,7 @@ where /// Prepare a successful command result with no causal visibility promise. pub fn succeeded(self, payload: T) -> Result>, HandlerError> where - T: GraphqlOutputType + Serialize + Send + Sync + 'static, + T: CommandOutputType + Serialize + Send + Sync + 'static, { let _ = self.projection; PreparedCommand::prepare(payload).map_err(|error| HandlerError::Other(Box::new(error))) @@ -446,7 +448,7 @@ where /// leg; the dispatcher additionally proves actual durable outbox coverage. pub fn eventual(self, payload: T) -> Result>, HandlerError> where - T: GraphqlOutputType + Serialize + Send + Sync + 'static, + T: CommandOutputType + Serialize + Send + Sync + 'static, { let _ = self.projection; PreparedCommand::prepare(payload).map_err(|error| HandlerError::Other(Box::new(error))) diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 420dd0d5b..2f610443b 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -23,6 +23,11 @@ use super::handlers::{ use crate::aggregate::Aggregate; use crate::application::{CommandMount, CommandMountRegistrar, CommandSpec}; use crate::bus::{Bus, Message, MessageKind, MessagePublisher, OrderedDelivery, TransportError}; +use crate::command::input::canonicalize_command_input; +use crate::command::{ + command_transition, CommandConsistency, CommandEventSet, CommandInputType, CommandOutcome, + CompiledInputDefaults, TypedCommand, TypedCommandContract, +}; use crate::command_ledger::{ CanonicalInputHash, CausalCommitBatch, CausalTransactionalCommit, CommandContractFingerprint, CommandLedgerStore, CommandReservation, ReservationOutcome, TerminalCommandState, @@ -32,14 +37,9 @@ use crate::command_ledger::{ CausalRepositoryIdentity, CommandId, CommandLedgerKey, CommandLookup, CommandLookupScope, PrincipalPartitionId, }; -use crate::graphql::command_contract::CommandConsistency; -use crate::graphql::command_contract::{ - CommandEventSet, CommandOutcome, CompiledInputDefaults, TypedCommandContract, -}; -use crate::graphql::command_input::canonicalize_command_input; #[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; -use crate::graphql::{command_transition, GraphqlInputType, SurfaceProjector, TypedCommand}; +use crate::graphql::SurfaceProjector; use crate::microsvc::causal::CausalWorkspace; use crate::microsvc::cell_host::{CellCommandIdentity, CellDispatchError, CellDispatchResult}; use crate::microsvc::context::Context; @@ -597,9 +597,9 @@ where E: crate::domain_event::DomainEventBodyContract, S: crate::DomainState + crate::projection::lower::ProjectionBodyMetadata, { - let values = crate::graphql::__command_projection_state_known_values::(vec![( + let values = crate::command::__command_projection_state_known_values::(vec![( rust_field, - crate::graphql::CommandProjectionPreviewSource::trusted("x-user-id", "string"), + crate::command::CommandProjectionPreviewSource::trusted("x-user-id", "string"), )]); self.contract .projections @@ -611,7 +611,7 @@ where #[must_use] pub fn preview_reduce_known_record( mut self, - reduce: crate::graphql::CommandProjectionPureReduce, + reduce: crate::command::CommandProjectionPureReduce, ) -> Self { self.contract.projections.add_pure_reduce(reduce); self @@ -750,12 +750,12 @@ where } } -impl ThinCommandBuilder, ThinCommandInvoked> +impl ThinCommandBuilder, ThinCommandInvoked> where D: CausalRouteDependencies + Send + Sync + 'static, D::Aggregate: Aggregate + Send + Sync + 'static, I: serde::de::DeserializeOwned + Send + Sync + 'static, - T: crate::graphql::GraphqlOutputType + serde::Serialize + Send + Sync + 'static, + T: crate::command::CommandOutputType + serde::Serialize + Send + Sync + 'static, { /// Publish captured events, commit, and return an Eventual payload. /// @@ -782,12 +782,12 @@ where } } -impl ThinCommandBuilder, ThinCommandInvoked> +impl ThinCommandBuilder, ThinCommandInvoked> where D: CausalRouteDependencies + Send + Sync + 'static, D::Aggregate: Aggregate + Send + Sync + 'static, I: serde::de::DeserializeOwned + Send + Sync + 'static, - T: crate::graphql::GraphqlOutputType + serde::Serialize + Send + Sync + 'static, + T: crate::command::CommandOutputType + serde::Serialize + Send + Sync + 'static, { /// Commit and return a Succeeded payload. Used when the command is not Eventual. pub fn succeeded(self, payload: F) -> Routes @@ -826,18 +826,18 @@ where roles: Vec, } -impl<'a, A, I, T> PreparedCommandHandler<'a, A, I, crate::graphql::Eventual> +impl<'a, A, I, T> PreparedCommandHandler<'a, A, I, crate::command::Eventual> for ThinEventualHandler where A: Aggregate + Send + Sync + 'static, I: serde::de::DeserializeOwned + Send + Sync + 'static, - T: crate::graphql::GraphqlOutputType + serde::Serialize + Send + Sync + 'static, + T: crate::command::CommandOutputType + serde::Serialize + Send + Sync + 'static, { type Future = Pin< Box< dyn Future< Output = Result< - crate::graphql::PreparedCommand>, + crate::command::PreparedCommand>, HandlerError, >, > + Send @@ -887,18 +887,18 @@ where roles: Vec, } -impl<'a, A, I, T> PreparedCommandHandler<'a, A, I, crate::graphql::Succeeded> +impl<'a, A, I, T> PreparedCommandHandler<'a, A, I, crate::command::Succeeded> for ThinSucceededHandler where A: Aggregate + Send + Sync + 'static, I: serde::de::DeserializeOwned + Send + Sync + 'static, - T: crate::graphql::GraphqlOutputType + serde::Serialize + Send + Sync + 'static, + T: crate::command::CommandOutputType + serde::Serialize + Send + Sync + 'static, { type Future = Pin< Box< dyn Future< Output = Result< - crate::graphql::PreparedCommand>, + crate::command::PreparedCommand>, HandlerError, >, > + Send @@ -1097,7 +1097,7 @@ impl Routes { pub fn command_transition(self, name: &'static str) -> TypedRouteBuilder where S: CommandEventSet, - I: GraphqlInputType + serde::de::DeserializeOwned + Send + 'static, + I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, K: CommandOutcome, { self.typed_command(command_transition::(name)) diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 569d975af..bc680536f 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -25,9 +25,9 @@ use crate::application::{ use crate::bus::{ Message, MessageKind, OrderedDelivery, RunOptions, SubscriptionPlan, TransportError, }; +use crate::command::{TypedCommandContract, TypedServiceCommandBinding}; #[cfg(feature = "graphql")] use crate::command_ledger::{CommandId, CommandLookup, PrincipalPartitionId}; -use crate::graphql::command_contract::{TypedCommandContract, TypedServiceCommandBinding}; #[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; use crate::microsvc::error::HandlerError; diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 0bc0ac633..f96533621 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -6,6 +6,11 @@ use crate::aggregate::Aggregate; #[cfg(feature = "graphql")] use crate::bus::RunOptions; use crate::bus::{Message, MessageKind, SubscriptionPlan}; +#[cfg(all(feature = "graphql", feature = "sqlite"))] +use crate::command::Eventual; +use crate::command::{typed_command, PreparedCommand, Succeeded}; +#[cfg(feature = "graphql")] +use crate::command::{Atomic, CommandConsistency}; #[cfg(feature = "graphql")] use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, @@ -13,17 +18,10 @@ use crate::command_ledger::{ CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, }; #[cfg(feature = "graphql")] -use crate::graphql::command_contract::CommandConsistency; -#[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; -#[cfg(all(feature = "graphql", feature = "sqlite"))] -use crate::graphql::Eventual; -use crate::graphql::{ - typed_command, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, - PreparedCommand, Succeeded, -}; +use crate::graphql::{GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField}; #[cfg(feature = "graphql")] -use crate::graphql::{Atomic, SurfaceDirectProjection, SurfaceProjector}; +use crate::graphql::{SurfaceDirectProjection, SurfaceProjector}; #[cfg(feature = "graphql")] use crate::microsvc::HasOutboxStore; use crate::microsvc::{ @@ -1215,7 +1213,7 @@ async fn thin_complete_registers_without_a_handler_context_body() { let routes = Routes::new() .with_repo(repository.aggregate::()) .typed_command( - typed_command::>("todo.create") + typed_command::>("todo.create") .roles(["user"]), ) .create() @@ -1227,7 +1225,7 @@ async fn thin_complete_registers_without_a_handler_context_body() { id: aggregate.entity().id().to_string(), }) .typed_command( - typed_command::>( + typed_command::>( "todo.complete", ) .roles(["user"]), diff --git a/tests/core_command_contract.rs b/tests/core_command_contract.rs new file mode 100644 index 000000000..c8cb04907 --- /dev/null +++ b/tests/core_command_contract.rs @@ -0,0 +1,164 @@ +#![allow(dead_code)] + +// Derives in this package's integration targets resolve through the crate root. +pub use distributed::{command, graphql}; + +use distributed::application::{CommandDefinition, Module}; +use distributed::command::{typed_command, CommandInputType, CommandOutputType, Succeeded}; +use distributed::graphql::{build_surface, graphql_sdl_from_surface, SurfaceOptions}; +use serde::{Deserialize, Serialize}; + +mod neutral { + use super::*; + use distributed::{CommandInput, CommandOutput}; + + #[derive(Deserialize, CommandInput)] + #[serde(rename_all = "camelCase")] + pub struct ContractInput { + record_id: String, + count: i64, + nested: Option>>, + } + #[derive(Deserialize, CommandInput)] + pub struct NestedInput { + enabled: bool, + } + #[derive(Serialize, CommandOutput)] + pub struct ContractOutput { + record_id: String, + value: f64, + } +} + +mod legacy { + use super::*; + use distributed::{GraphqlInput, GraphqlOutput}; + + #[derive(Deserialize, GraphqlInput)] + #[serde(rename_all = "camelCase")] + pub struct ContractInput { + record_id: String, + count: i64, + nested: Option>>, + } + #[derive(Deserialize, GraphqlInput)] + pub struct NestedInput { + enabled: bool, + } + #[derive(Serialize, GraphqlOutput)] + pub struct ContractOutput { + record_id: String, + value: f64, + } +} + +fn artifact() -> serde_json::Value +where + I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, + O: CommandOutputType + Serialize + Send + Sync + 'static, +{ + let command = typed_command::>("contract.test") + .roles(["user"]) + .field_name("run_contract"); + let spec = command.spec().unwrap(); + let module = Module::new("contract") + .command_definition(CommandDefinition::from_typed_command(command, None).unwrap()) + .build() + .unwrap(); + let surface = build_surface(&[], &SurfaceOptions::sqlite()) + .unwrap() + .with_module(&module) + .unwrap(); + serde_json::json!({ "spec": spec, "sdl": graphql_sdl_from_surface(&surface).unwrap() }) +} + +#[test] +fn neutral_declarations_preserve_the_pre_extraction_artifact() { + // Captured from d188010d before changing the command implementation. + let expected: serde_json::Value = + serde_json::from_str(include_str!("fixtures/core-command-contract-v1.json")).unwrap(); + assert_eq!( + artifact::(), + expected + ); +} + +#[test] +fn legacy_graphql_derives_remain_compatible() { + assert_eq!( + artifact::(), + artifact::() + ); +} + +#[derive(Deserialize, distributed::CommandInput)] +#[serde(rename_all(deserialize = "kebab-case", serialize = "camelCase"))] +struct NonGraphqlInput { + record_id: String, +} + +#[test] +fn graphql_representability_is_checked_only_when_exposing_the_command() { + let command = typed_command::>("core.only"); + assert_eq!(command.spec().unwrap().input.fields[0].name, "record-id"); + let module = Module::new("core-only") + .command_definition(CommandDefinition::from_typed_command(command, None).unwrap()) + .build() + .unwrap(); + let result = build_surface(&[], &SurfaceOptions::sqlite()) + .unwrap() + .with_module(&module); + assert!(result.unwrap_err().contains("record-id")); +} + +#[derive(Deserialize, distributed::CommandInput)] +#[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] +struct DirectionalInput { + record_id: String, + #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] + alternate_id: String, + values: Option>>, +} + +#[derive(Serialize, distributed::CommandOutput)] +#[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] +struct DirectionalOutput { + record_id: String, + #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] + alternate_id: String, + values: Option>>, +} + +#[test] +fn neutral_shapes_follow_serde_direction_and_preserve_item_nullability() { + for (definition, names) in [ + ( + DirectionalInput::command_type(), + ["recordId", "inputID", "values"], + ), + ( + DirectionalOutput::command_type(), + ["RECORD_ID", "OUTPUT_ID", "VALUES"], + ), + ] { + assert_eq!( + definition + .fields + .iter() + .map(|f| f.name.as_str()) + .collect::>(), + names + ); + let list = &definition.fields[2]; + assert!(list.list && list.nullable && list.item_nullable); + } +} + +#[test] +fn graphql_metadata_can_be_derived_from_neutral_shapes() { + let neutral = neutral::ContractInput::command_type(); + let graph = graphql::GraphqlTypeDef::from(neutral.clone()); + assert_eq!(graph.name, neutral.name); + assert_eq!(graph.transitive_nested()[0].name, "NestedInput"); + assert_eq!(command::CommandTypeDef::from(graph), neutral); +} diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs b/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs index 08e80658d..16d72272d 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/archive.rs @@ -1,11 +1,11 @@ -use distributed::graphql::Eventual; +use distributed::command::Eventual; use distributed::portable_command; use serde::Deserialize; use super::TodoStatusPayload; use crate::{domain_commands, Todo}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoArchiveInput { pub todo_id: String, } diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs b/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs index 70e420dda..a722a45c0 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/complete.rs @@ -1,16 +1,16 @@ -use distributed::graphql::Eventual; +use distributed::command::Eventual; use distributed::portable_command; use serde::{Deserialize, Serialize}; use crate::{domain_commands, Todo, TodoState}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoCompleteInput { pub todo_id: String, } /// Shared complete / archive / reopen payload. -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct TodoStatusPayload { pub todo_id: String, pub status: String, diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/create.rs b/tests/e2e-ui/crates/todo-domain/src/commands/create.rs index 31ee6da4d..fea665347 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/create.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/create.rs @@ -1,5 +1,5 @@ +use distributed::command::{Eventual, PreparedCommand}; use distributed::command_input_defaults; -use distributed::graphql::{Eventual, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use serde::{Deserialize, Serialize}; @@ -7,13 +7,13 @@ use serde::{Deserialize, Serialize}; use super::support::{authenticated_user, principal, rejected}; use crate::{domain_commands, Todo, TodoState}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoCreateInput { pub todo_id: String, pub title: String, } -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct TodoCreatePayload { pub todo_id: String, pub owner_id: String, diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs b/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs index b8229618e..490daccdb 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/force_archive.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{Eventual, PreparedCommand}; +use distributed::command::{Eventual, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use serde::{Deserialize, Serialize}; @@ -6,12 +6,12 @@ use serde::{Deserialize, Serialize}; use super::support::{admin_user, principal, rejected}; use crate::{domain_commands, Todo, TodoState}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoForceArchiveInput { pub todo_id: String, } -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct TodoForceArchivePayload { pub todo_id: String, pub owner_id: String, diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs b/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs index 03b8efb9b..aef92e171 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/purge.rs @@ -1,15 +1,15 @@ -use distributed::graphql::Eventual; +use distributed::command::Eventual; use distributed::portable_command; use serde::{Deserialize, Serialize}; use crate::{domain_commands, Todo}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoPurgeInput { pub todo_id: String, } -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct TodoPurgePayload { pub todo_id: String, pub purged: bool, diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs b/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs index aee608247..be8d462a2 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/rename.rs @@ -1,16 +1,16 @@ -use distributed::graphql::Eventual; +use distributed::command::Eventual; use distributed::portable_command; use serde::{Deserialize, Serialize}; use crate::{domain_commands, Todo, TodoState}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoRenameInput { pub todo_id: String, pub title: String, } -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct TodoRenamePayload { pub todo_id: String, pub title: String, diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs b/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs index 3ce683c85..5b5ac9b62 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/reopen.rs @@ -1,11 +1,11 @@ -use distributed::graphql::Eventual; +use distributed::command::Eventual; use distributed::portable_command; use serde::Deserialize; use super::TodoStatusPayload; use crate::{domain_commands, Todo}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoReopenInput { pub todo_id: String, } diff --git a/tests/e2e-ui/crates/todo-domain/src/models/todo.rs b/tests/e2e-ui/crates/todo-domain/src/models/todo.rs index 89d67e926..60f6a9d09 100644 --- a/tests/e2e-ui/crates/todo-domain/src/models/todo.rs +++ b/tests/e2e-ui/crates/todo-domain/src/models/todo.rs @@ -255,8 +255,8 @@ mod tests { #[test] fn domain_commands_create_matches_created_event_contract() { + use distributed::command::CommandEventSet; use distributed::domain_event::DomainEventContract; - use distributed::graphql::CommandEventSet; let from_transition = domain_commands::Create::command_event_set(); let from_event = distributed::events![TodoCreatedDomainEvent]; diff --git a/tests/fixtures/core-command-contract-v1.json b/tests/fixtures/core-command-contract-v1.json new file mode 100644 index 000000000..4a715a4b4 --- /dev/null +++ b/tests/fixtures/core-command-contract-v1.json @@ -0,0 +1,83 @@ +{ + "sdl": "scalar BigInt\nscalar Bytea\nscalar JSON\nscalar Timestamptz\n\nenum order_by {\n asc\n asc_nulls_first\n asc_nulls_last\n desc\n desc_nulls_first\n desc_nulls_last\n}\n\ninput ContractInput {\n count: BigInt!\n nested: [NestedInput]\n recordId: String!\n}\n\ninput NestedInput {\n enabled: Boolean!\n}\n\ntype ContractOutput {\n record_id: String!\n value: Float!\n}\n\nenum DistributedCommandState {\n in_progress\n succeeded\n succeeded_pending_projection\n atomic\n rejected\n projection_failed\n expired\n unknown\n}\n\ntype DistributedCommandStatus {\n state: DistributedCommandState!\n}\n\ntype Query {\n commandStatus(commandId: ID!): DistributedCommandStatus!\n}\n\ntype Mutation {\n run_contract(commandId: ID!, input: ContractInput!): ContractOutput!\n}\n", + "spec": { + "applies": [], + "confirmations": [], + "consistency": "succeeded", + "defaults": [], + "effects": { + "fallback": "revalidate", + "operations": [] + }, + "emits": [], + "field_name": "run_contract", + "fingerprint": "sha256:ed43f086c62a1878472679415e0155e78a707921aa248a67416a49d5c97a39eb", + "id": "contract.test", + "input": { + "fields": [ + { + "item_nullable": false, + "list": false, + "name": "recordId", + "nullable": false, + "type_name": "String" + }, + { + "item_nullable": false, + "list": false, + "name": "count", + "nullable": false, + "type_name": "BigInt" + }, + { + "item_nullable": true, + "list": true, + "name": "nested", + "nested": { + "fields": [ + { + "item_nullable": false, + "list": false, + "name": "enabled", + "nullable": false, + "type_name": "Boolean" + } + ], + "name": "NestedInput" + }, + "nullable": true, + "type_name": "NestedInput" + } + ], + "name": "ContractInput" + }, + "output": { + "fields": [ + { + "item_nullable": false, + "list": false, + "name": "record_id", + "nullable": false, + "type_name": "String" + }, + { + "item_nullable": false, + "list": false, + "name": "value", + "nullable": false, + "type_name": "Float" + } + ], + "name": "ContractOutput" + }, + "projection_contract": { + "declaration_errors": [], + "previews": [], + "pure_reduces": [], + "selectors": [] + }, + "roles": [ + "user" + ] + } +} diff --git a/tests/fixtures/renamed-dependency-trybuild/tests/fixtures/renamed_dependency.rs b/tests/fixtures/renamed-dependency-trybuild/tests/fixtures/renamed_dependency.rs index 1c34c7bee..9f3b56dab 100644 --- a/tests/fixtures/renamed-dependency-trybuild/tests/fixtures/renamed_dependency.rs +++ b/tests/fixtures/renamed-dependency-trybuild/tests/fixtures/renamed_dependency.rs @@ -26,12 +26,12 @@ impl Aggregate for RenamedAggregate { } } -#[derive(Clone, serde::Deserialize, framework::GraphqlInput)] +#[derive(Clone, serde::Deserialize, framework::CommandInput)] struct RenamedInput { id: String, } -#[derive(Clone, serde::Serialize, framework::GraphqlOutput)] +#[derive(Clone, serde::Serialize, framework::CommandOutput)] struct RenamedOutput { id: String, } @@ -47,13 +47,13 @@ struct RenamedCreated { roles(user), emits(RenamedCreated), input = RenamedInput, - outcome = framework::graphql::Succeeded + outcome = framework::command::Succeeded )] async fn renamed_handler( _context: &framework::microsvc::CausalCommandContext<'_, RenamedAggregate>, _input: RenamedInput, ) -> Result< - framework::graphql::PreparedCommand>, + framework::command::PreparedCommand>, framework::microsvc::HandlerError, > { unreachable!() diff --git a/tests/legacy_authoring_absence.rs b/tests/legacy_authoring_absence.rs index 4e23bfef9..47f573879 100644 --- a/tests/legacy_authoring_absence.rs +++ b/tests/legacy_authoring_absence.rs @@ -100,6 +100,7 @@ fn projection_read_model_workspace_is_gone() { #[test] fn dead_effects_authoring_types_are_not_publicly_reexported() { let graphql_mod = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/graphql/mod.rs")); + let command_mod = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/command/mod.rs")); for forbidden in [ "CompiledCommandEffects", "CompiledConfirmationPlan", @@ -109,8 +110,8 @@ fn dead_effects_authoring_types_are_not_publicly_reexported() { "__effect_patch", ] { assert!( - !graphql_mod.contains(forbidden), - "{forbidden} must not be re-exported from graphql::" + !graphql_mod.contains(forbidden) && !command_mod.contains(forbidden), + "{forbidden} must not be re-exported from command:: or graphql::" ); } } @@ -119,7 +120,7 @@ fn dead_effects_authoring_types_are_not_publicly_reexported() { fn typed_command_has_no_public_effects_or_confirmations_builder() { let typed = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), - "/src/graphql/command_contract/typed_command.rs" + "/src/command/typed_command.rs" )); assert!( !typed.contains("pub fn effects("), From f4bb231d38f0817993f0394a5306f4c197b01f3e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 14:49:40 -0500 Subject: [PATCH 016/484] refactor!: remove GraphQL command compatibility APIs Use command-owned derives, metadata, and outcomes throughout library tests, e2e-ui domains, fixtures, and generated services. Remove legacy GraphQL traits, conversions, derives, and re-exports. BREAKING CHANGE: command authors must use distributed::command and the CommandInput/CommandOutput derives. GraphqlInput/GraphqlOutput and GraphQL command exports are removed. Implements [[tasks/core-command-contract-1]] --- README.md | 23 +-- distributed_cli/src/generate/service_crate.rs | 6 +- distributed_cli/tests/cli_scaffold_compile.rs | 10 +- .../tests/fixtures/orders-service/src/lib.rs | 27 ++-- distributed_macros/src/command_types.rs | 136 +++------------- distributed_macros/src/lib.rs | 20 --- distributed_macros/tests/application.rs | 10 +- .../tests/command_input_defaults.rs | 8 +- .../duplicate_input_default.rs | 4 +- .../input_default_list.rs | 4 +- .../input_default_nullable.rs | 4 +- .../input_default_wrong_type.rs | 4 +- .../tests/command_types_compile_fail.rs | 7 + .../nested_lists.rs | 4 +- .../nested_lists.stderr | 5 + .../serde_container_default.rs | 4 +- .../serde_container_default.stderr | 5 + .../serde_default.rs | 4 +- .../serde_default.stderr | 5 + .../serde_skip.rs | 4 +- .../serde_skip.stderr | 5 + .../serde_transparent.rs | 4 +- .../serde_transparent.stderr | 5 + .../serde_with.rs | 4 +- .../serde_with.stderr | 5 + ...lication_command_declared_type_mismatch.rs | 4 +- .../application_command_duplicate_id.rs | 2 +- .../application_command_duplicate_option.rs | 4 +- .../application_command_duplicate_role.rs | 4 +- .../application_command_empty_roles.rs | 4 +- .../application_command_invalid_id.rs | 4 +- .../application_command_missing_roles.rs | 4 +- .../application_command_wrong_handler.rs | 2 +- .../tests/graphql_compile_fail.rs | 7 - .../graphql_compile_fail/nested_lists.stderr | 5 - .../serde_container_default.stderr | 5 - .../graphql_compile_fail/serde_default.stderr | 5 - .../graphql_compile_fail/serde_kebab_case.rs | 9 -- .../serde_kebab_case.stderr | 5 - .../graphql_compile_fail/serde_skip.stderr | 5 - .../serde_transparent.stderr | 5 - .../graphql_compile_fail/serde_with.stderr | 5 - src/graphql/client_manifest/mod.rs | 2 +- src/graphql/client_manifest/tests.rs | 26 +-- src/graphql/commands.rs | 6 +- src/graphql/engine/mod.rs | 2 +- src/graphql/engine/tests.rs | 34 ++-- src/graphql/mod.rs | 27 +--- src/graphql/projection_delta/tests.rs | 4 +- src/graphql/surface/mod.rs | 4 +- src/graphql/surface/tests.rs | 33 ++-- src/graphql/types.rs | 150 ------------------ src/lib.rs | 2 +- src/microsvc/causal.rs | 8 +- src/microsvc/cell_host/tests.rs | 8 +- src/microsvc/service/tests.rs | 46 +++--- tests/application_composition.rs | 13 +- tests/application_plans.rs | 2 +- tests/causal_public_invoke/main.rs | 22 +-- tests/causal_wait_path/main.rs | 22 +-- tests/core_command_contract.rs | 39 ----- .../blob-domain/src/commands/move_dir.rs | 4 +- .../crates/blob-domain/src/commands/start.rs | 4 +- .../blob-domain/src/commands/start_level.rs | 4 +- .../crates/chat-domain/src/commands/post.rs | 6 +- tests/e2e_ui_celld_nats_profile/main.rs | 27 ++-- .../application-contract-only/src/lib.rs | 42 ++--- tests/graphql_causal_transport/main.rs | 11 +- tests/graphql_commands/main.rs | 36 ++--- tests/graphql_harden/transport.rs | 10 +- tests/typed_commands/main.rs | 98 ++++++------ 71 files changed, 385 insertions(+), 703 deletions(-) create mode 100644 distributed_macros/tests/command_types_compile_fail.rs rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/nested_lists.rs (60%) create mode 100644 distributed_macros/tests/command_types_compile_fail/nested_lists.stderr rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/serde_container_default.rs (65%) create mode 100644 distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/serde_default.rs (59%) create mode 100644 distributed_macros/tests/command_types_compile_fail/serde_default.stderr rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/serde_skip.rs (67%) create mode 100644 distributed_macros/tests/command_types_compile_fail/serde_skip.stderr rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/serde_transparent.rs (60%) create mode 100644 distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr rename distributed_macros/tests/{graphql_compile_fail => command_types_compile_fail}/serde_with.rs (61%) create mode 100644 distributed_macros/tests/command_types_compile_fail/serde_with.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail.rs delete mode 100644 distributed_macros/tests/graphql_compile_fail/nested_lists.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_default.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_skip.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr delete mode 100644 distributed_macros/tests/graphql_compile_fail/serde_with.stderr delete mode 100644 src/graphql/types.rs diff --git a/README.md b/README.md index 559749f88..7b2ad1c49 100644 --- a/README.md +++ b/README.md @@ -1421,14 +1421,16 @@ let declaration = typed_command::>("todo.re # } ``` -To migrate existing command DTOs, replace `GraphqlInput`/`GraphqlOutput` with -`CommandInput`/`CommandOutput` throughout the DTO's nested types and import -command APIs from `distributed::command`. Manual metadata implementations use -`CommandInputType`/`CommandOutputType`, `command_type()`, and -`CommandTypeDef`/`CommandTypeField`. Existing GraphQL derives, manual GraphQL -trait implementations, and command re-exports remain compatible through the -GraphQL adapter. Choose one metadata implementation per direction on each DTO. -Equivalent declarations retain their wire shapes and command fingerprints. +This is a breaking Rust API change. Replace `GraphqlInput`/`GraphqlOutput` +with `CommandInput`/`CommandOutput` throughout the DTO's nested types and +move command imports from `distributed::graphql` to `distributed::command`. +Manual metadata implementations now use `CommandInputType`/`CommandOutputType`, +`command_type()`, and `CommandTypeDef`/`CommandTypeField`. The old GraphQL +command re-exports, metadata types, and derives have been removed. + +GraphQL remains the application's UI gateway: it exposes the command contract +alongside queries and subscriptions. Command handlers describe their data and +consistency through the core API, independently of where that gateway runs. `Atomic` continues to obtain its response shape from the relational read model and requires the existing transaction proof. Moving command ownership @@ -1826,9 +1828,8 @@ distributed = { version = "0.1", features = ["graphql", "postgres"] } ### Mount on a service ```rust,ignore -use distributed::graphql::{ - claim, col, read, typed_command, Eventual, GraphqlEngine, -}; +use distributed::command::{typed_command, Eventual}; +use distributed::graphql::{claim, col, read, GraphqlEngine}; use distributed::microsvc::{Routes, Service}; let routes = Routes::new() diff --git a/distributed_cli/src/generate/service_crate.rs b/distributed_cli/src/generate/service_crate.rs index 922db3183..759fbcd1b 100644 --- a/distributed_cli/src/generate/service_crate.rs +++ b/distributed_cli/src/generate/service_crate.rs @@ -519,13 +519,13 @@ impl CommandAggregate { }; let command_types = if self.query_api { - r#"#[derive(Clone, Debug, Deserialize, distributed::GraphqlInput)] + r#"#[derive(Clone, Debug, Deserialize, distributed::CommandInput)] pub struct CommandInput { pub id: String, pub name: Option, } -#[derive(Clone, Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Clone, Debug, Serialize, distributed::CommandOutput)] pub struct CommandOutput { pub command: String, pub id: String, @@ -597,7 +597,7 @@ impl {model_struct} {{ .map(|model| (model.type_ident.as_str(), model.name.as_str())) .unwrap_or(("CommandAggregate", "CommandAggregate")); return format!( - r#"use distributed::graphql::{{typed_command, Succeeded, PreparedCommand, TypedCommand}}; + r#"use distributed::command::{{typed_command, Succeeded, PreparedCommand, TypedCommand}}; use distributed::microsvc::{{CausalCommandContext, HandlerError}}; use crate::models::{{CommandInput, CommandOutput, {model_type}}}; diff --git a/distributed_cli/tests/cli_scaffold_compile.rs b/distributed_cli/tests/cli_scaffold_compile.rs index 9811ed7a7..5afbb10dd 100644 --- a/distributed_cli/tests/cli_scaffold_compile.rs +++ b/distributed_cli/tests/cli_scaffold_compile.rs @@ -100,7 +100,15 @@ fn scaffolded_http_tracing_service_compiles() { fn scaffolded_query_api_service_compiles() { let out_dir = scaffold( "compile-query-api-sqlite", - &["--query-api", "--store", "sqlite", "--model", "order"], + &[ + "--query-api", + "--store", + "sqlite", + "--model", + "order", + "--command", + "orders.place", + ], ); cargo_check(&out_dir); } diff --git a/distributed_cli/tests/fixtures/orders-service/src/lib.rs b/distributed_cli/tests/fixtures/orders-service/src/lib.rs index 8e81ee8e9..bd1305c94 100644 --- a/distributed_cli/tests/fixtures/orders-service/src/lib.rs +++ b/distributed_cli/tests/fixtures/orders-service/src/lib.rs @@ -3,10 +3,13 @@ use std::any::TypeId; +use distributed::command::{ + typed_command, Atomic, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, + PreparedCommand, +}; use distributed::graphql::{ - build_surface, surface_for_role, typed_command, DistributedClientSurfaceExport, - Atomic, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, PreparedCommand, - RoleGrant, SurfaceOptions, SurfaceProjector, + build_surface, surface_for_role, DistributedClientSurfaceExport, RoleGrant, SurfaceOptions, + SurfaceProjector, }; use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use distributed::{ @@ -23,12 +26,12 @@ pub struct OrderView { pub status: String, } -impl GraphqlOutputType for OrderView { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for OrderView { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "OrderView", vec![ - GraphqlTypeField { + CommandTypeField { name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -36,7 +39,7 @@ impl GraphqlOutputType for OrderView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "status".into(), type_name: "String".into(), nullable: false, @@ -55,11 +58,11 @@ struct ProjectOrderInput { order_id: String, } -impl GraphqlInputType for ProjectOrderInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for ProjectOrderInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "ProjectOrderInput", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "order_id".into(), type_name: "String".into(), nullable: false, diff --git a/distributed_macros/src/command_types.rs b/distributed_macros/src/command_types.rs index a989328be..c67077002 100644 --- a/distributed_macros/src/command_types.rs +++ b/distributed_macros/src/command_types.rs @@ -1,4 +1,4 @@ -//! Command data-shape derives and legacy GraphQL adapters. +//! Transport-neutral command data-shape derives. use proc_macro2::TokenStream; use quote::{format_ident, quote}; @@ -23,8 +23,8 @@ impl SerdeDirection { fn derive_name(self) -> &'static str { match self { - Self::Deserialize => "GraphqlInput", - Self::Serialize => "GraphqlOutput", + Self::Deserialize => "CommandInput", + Self::Serialize => "CommandOutput", } } } @@ -59,7 +59,7 @@ impl RenameRule { other => Err(syn::Error::new_spanned( value, format!( - "unsupported serde rename_all rule `{other}` for GraphqlInput/GraphqlOutput" + "unsupported serde rename_all rule `{other}` for CommandInput/CommandOutput" ), )), } @@ -98,31 +98,6 @@ impl RenameRule { } } -pub fn expand_graphql_input(input: DeriveInput) -> syn::Result { - let framework = crate::shared::framework_path()?; - expand( - input, - quote! { #framework::graphql::GraphqlInputType }, - quote! { #framework::graphql::GraphqlInputType }, - framework, - SerdeDirection::Deserialize, - false, - ) -} - -pub fn expand_graphql_output(input: DeriveInput) -> syn::Result { - let framework = crate::shared::framework_path()?; - expand( - input, - quote! { #framework::graphql::GraphqlOutputType }, - quote! { #framework::graphql::GraphqlOutputType }, - framework, - SerdeDirection::Serialize, - false, - ) -} - -/// Neutral derives share serialization analysis with the legacy GraphQL derives. pub fn expand_command_input(input: DeriveInput) -> syn::Result { let framework = crate::shared::framework_path()?; expand( @@ -131,9 +106,7 @@ pub fn expand_command_input(input: DeriveInput) -> syn::Result { quote! { #framework::command::CommandInputType }, framework, SerdeDirection::Deserialize, - true, ) - .map_err(command_error) } pub fn expand_command_output(input: DeriveInput) -> syn::Result { @@ -144,19 +117,6 @@ pub fn expand_command_output(input: DeriveInput) -> syn::Result { quote! { #framework::command::CommandOutputType }, framework, SerdeDirection::Serialize, - true, - ) - .map_err(command_error) -} - -fn command_error(error: syn::Error) -> syn::Error { - syn::Error::new( - error.span(), - error - .to_string() - .replace("GraphqlInput", "CommandInput") - .replace("GraphqlOutput", "CommandOutput") - .replace("GraphQL", "command"), ) } @@ -166,49 +126,24 @@ fn expand( nested_trait: TokenStream, framework: TokenStream, serde_direction: SerdeDirection, - neutral: bool, ) -> syn::Result { - let method = if neutral { - quote! { command_type } - } else { - quote! { graphql_type } - }; - let (type_def, type_field) = if neutral { - ( - quote! { #framework::command::CommandTypeDef }, - quote! { #framework::command::CommandTypeField }, - ) - } else { - ( - quote! { #framework::graphql::GraphqlTypeDef }, - quote! { #framework::graphql::GraphqlTypeField }, - ) - }; + let method = quote! { command_type }; + let type_def = quote! { #framework::command::CommandTypeDef }; + let type_field = quote! { #framework::command::CommandTypeField }; let name = &input.ident; let visibility = &input.vis; validate_serde_container_shape(&input.attrs, serde_direction)?; let rename_all = serde_rename_all(&input.attrs, serde_direction)?; - if !neutral - && matches!( - rename_all, - Some(RenameRule::KebabCase | RenameRule::ScreamingKebabCase) - ) - { - if let Some(value) = serde_name_value(&input.attrs, "rename_all", serde_direction)? { - return Err(syn::Error::new_spanned(value, - "serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case")); - } - } let Data::Struct(data) = &input.data else { return Err(syn::Error::new_spanned( &input, - "GraphqlInput/GraphqlOutput only support structs with named fields", + "CommandInput/CommandOutput only support structs with named fields", )); }; let Fields::Named(fields) = &data.fields else { return Err(syn::Error::new_spanned( &input, - "GraphqlInput/GraphqlOutput require named fields", + "CommandInput/CommandOutput require named fields", )); }; @@ -230,9 +165,6 @@ fn expand( .map(|rule| rule.apply(rust_field_name)) .unwrap_or_else(|| rust_field_name.to_string()) }); - if !neutral { - validate_graphql_field_name(&field_name_str, field)?; - } let (type_name, nullable, list, item_nullable, nested) = map_type(&field.ty, field, &nested_trait, &method)?; let effect_path_kind = if !list && nested.is_some() { @@ -370,7 +302,7 @@ fn map_type( if extract_path_arg(current, "Vec").is_some() { return Err(syn::Error::new_spanned( ty, - "nested lists are not supported for GraphqlInput/GraphqlOutput fields", + "nested lists are not supported for CommandInput/CommandOutput fields", )); } } @@ -380,7 +312,7 @@ fn map_type( _ => { return Err(syn::Error::new_spanned( span, - "unsupported field type for GraphqlInput/GraphqlOutput", + "unsupported field type for CommandInput/CommandOutput", )); } }; @@ -497,7 +429,7 @@ fn validate_serde_field_shape(attrs: &[Attribute], direction: SerdeDirection) -> return Err(syn::Error::new_spanned( meta, format!( - "#[serde({attribute})] is not supported by {} because it changes the declared GraphQL field shape; define a separate wire type", + "#[serde({attribute})] is not supported by {} because it changes the declared command field shape; define a separate wire type", direction.derive_name(), ), )); @@ -561,7 +493,7 @@ fn validate_serde_container_shape( return Err(syn::Error::new_spanned( meta, format!( - "#[serde({attribute})] is not supported by {} because it changes the declared GraphQL object shape; define a separate wire type", + "#[serde({attribute})] is not supported by {} because it changes the declared command object shape; define a separate wire type", direction.derive_name(), ), )); @@ -617,7 +549,7 @@ fn set_serde_name(found: &mut Option, value: LitStr, key: &str) -> syn:: if found.is_some() { return Err(syn::Error::new_spanned( value, - format!("duplicate serde `{key}` rule for GraphqlInput/GraphqlOutput"), + format!("duplicate serde `{key}` rule for CommandInput/CommandOutput"), )); } *found = Some(value); @@ -640,30 +572,12 @@ fn string_literal(value: &Expr, key: &str) -> syn::Result { } } -fn validate_graphql_field_name(name: &str, span: &syn::Field) -> syn::Result<()> { - let mut chars = name.chars(); - let first_valid = match chars.next() { - Some('_') => !name.starts_with("__"), - Some(first) => first.is_ascii_alphabetic(), - None => false, - }; - if first_valid && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_') { - return Ok(()); - } - Err(syn::Error::new_spanned( - span, - format!( - "serde field name `{name}` is not a valid GraphQL name; use #[serde(rename = \"valid_name\")]" - ), - )) -} - #[cfg(test)] mod tests { use super::*; #[test] - fn graphql_safe_rename_all_rules_match_serde_field_rules() { + fn rename_all_rules_match_serde_field_rules() { let field = "long_field_name"; let cases = [ ("lowercase", "long_field_name"), @@ -672,6 +586,8 @@ mod tests { ("camelCase", "longFieldName"), ("snake_case", "long_field_name"), ("SCREAMING_SNAKE_CASE", "LONG_FIELD_NAME"), + ("kebab-case", "long-field-name"), + ("SCREAMING-KEBAB-CASE", "LONG-FIELD-NAME"), ]; for (rule, expected) in cases { let literal = LitStr::new(rule, proc_macro2::Span::call_site()); @@ -689,7 +605,7 @@ mod tests { custom_id: String, } }; - let input_tokens = expand_graphql_input(input).unwrap().to_string(); + let input_tokens = expand_command_input(input).unwrap().to_string(); assert!(input_tokens.contains("\"regularField\"")); assert!(input_tokens.contains("\"inputID\"")); @@ -701,7 +617,7 @@ mod tests { custom_id: String, } }; - let output_tokens = expand_graphql_output(output).unwrap().to_string(); + let output_tokens = expand_command_output(output).unwrap().to_string(); assert!(output_tokens.contains("\"REGULAR_FIELD\"")); assert!(output_tokens.contains("\"OUTPUT_ID\"")); } @@ -711,7 +627,7 @@ mod tests { let nested: DeriveInput = syn::parse_quote! { struct Nested { values: Option>>> } }; - let error = expand_graphql_input(nested).unwrap_err().to_string(); + let error = expand_command_input(nested).unwrap_err().to_string(); assert!(error.contains("nested lists are not supported"), "{error}"); let skipped: DeriveInput = syn::parse_quote! { @@ -720,9 +636,9 @@ mod tests { value: String, } }; - let error = expand_graphql_input(skipped).unwrap_err().to_string(); + let error = expand_command_input(skipped).unwrap_err().to_string(); assert!( - error.contains("changes the declared GraphQL field shape"), + error.contains("changes the declared command field shape"), "{error}" ); @@ -732,7 +648,7 @@ mod tests { value: String, } }; - let error = expand_graphql_input(defaulted).unwrap_err().to_string(); + let error = expand_command_input(defaulted).unwrap_err().to_string(); assert!(error.contains("#[serde(default)]"), "{error}"); let custom: DeriveInput = syn::parse_quote! { @@ -741,21 +657,21 @@ mod tests { value: String, } }; - let error = expand_graphql_input(custom).unwrap_err().to_string(); + let error = expand_command_input(custom).unwrap_err().to_string(); assert!(error.contains("#[serde(deserialize_with)]"), "{error}"); let transparent: DeriveInput = syn::parse_quote! { #[serde(transparent)] struct Transparent { value: String } }; - let error = expand_graphql_output(transparent).unwrap_err().to_string(); + let error = expand_command_output(transparent).unwrap_err().to_string(); assert!(error.contains("#[serde(transparent)]"), "{error}"); let container_default: DeriveInput = syn::parse_quote! { #[serde(default = "default_input")] struct ContainerDefault { value: String } }; - let error = expand_graphql_input(container_default) + let error = expand_command_input(container_default) .unwrap_err() .to_string(); assert!(error.contains("#[serde(default)]"), "{error}"); diff --git a/distributed_macros/src/lib.rs b/distributed_macros/src/lib.rs index bdde44f47..bd24f3f4a 100644 --- a/distributed_macros/src/lib.rs +++ b/distributed_macros/src/lib.rs @@ -202,25 +202,5 @@ pub fn derive_command_output(input: TokenStream) -> TokenStream { } } -/// Derive `GraphqlInputType` for command mutation input structs. -#[proc_macro_derive(GraphqlInput, attributes(serde))] -pub fn derive_graphql_input(input: TokenStream) -> TokenStream { - let input = syn::parse_macro_input!(input as DeriveInput); - match command_types::expand_graphql_input(input) { - Ok(tokens) => tokens.into(), - Err(err) => err.to_compile_error().into(), - } -} - -/// Derive `GraphqlOutputType` for command mutation output structs. -#[proc_macro_derive(GraphqlOutput, attributes(serde))] -pub fn derive_graphql_output(input: TokenStream) -> TokenStream { - let input = syn::parse_macro_input!(input as DeriveInput); - match command_types::expand_graphql_output(input) { - Ok(tokens) => tokens.into(), - Err(err) => err.to_compile_error().into(), - } -} - #[cfg(test)] mod entry_tests; diff --git a/distributed_macros/tests/application.rs b/distributed_macros/tests/application.rs index a3d29efb5..23a4447d1 100644 --- a/distributed_macros/tests/application.rs +++ b/distributed_macros/tests/application.rs @@ -2,9 +2,9 @@ #![allow(dead_code)] #![allow(unused_imports)] -use distributed::graphql::Succeeded; +use distributed::command::Succeeded; use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::{Aggregate, DomainEvent, Entity, EventRecord, GraphqlInput, GraphqlOutput}; +use distributed::{Aggregate, CommandInput, CommandOutput, DomainEvent, Entity, EventRecord}; use serde::{Deserialize, Serialize}; #[derive(Default)] @@ -32,13 +32,13 @@ impl Aggregate for FixtureAggregate { } } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] pub struct CreateInput { id: String, title: String, } -#[derive(Clone, Serialize, GraphqlOutput)] +#[derive(Clone, Serialize, CommandOutput)] pub struct CreateOutput { id: String, } @@ -66,7 +66,7 @@ pub struct TodoCreated { pub async fn handle( _context: &CausalCommandContext<'_, FixtureAggregate>, _input: CreateInput, -) -> Result>, HandlerError> { +) -> Result>, HandlerError> { unimplemented!() } diff --git a/distributed_macros/tests/command_input_defaults.rs b/distributed_macros/tests/command_input_defaults.rs index c115d1e04..a6104fa3c 100644 --- a/distributed_macros/tests/command_input_defaults.rs +++ b/distributed_macros/tests/command_input_defaults.rs @@ -1,17 +1,17 @@ //! Compile-pass checks for command_input_defaults!. -use distributed::graphql::{typed_command, Succeeded}; -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::command::{typed_command, Succeeded}; +use distributed::{command_input_defaults, CommandInput}; use serde::Deserialize; -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] #[allow(dead_code)] struct PlanInput { id: String, title: String, } -#[derive(Clone, serde::Serialize, distributed::GraphqlOutput)] +#[derive(Clone, serde::Serialize, distributed::CommandOutput)] struct PlanOutput { id: String, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs b/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs index e5d08c435..0fe6841ba 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs +++ b/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs @@ -1,6 +1,6 @@ -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::{command_input_defaults, CommandInput}; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct Input { id: String, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs index 407564fbd..71e0cd81f 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs @@ -1,6 +1,6 @@ -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::{command_input_defaults, CommandInput}; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct Input { ids: Vec, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs index 85b8563d7..39e407d28 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs @@ -1,7 +1,7 @@ -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::{command_input_defaults, CommandInput}; use serde::Deserialize; -#[derive(Deserialize, GraphqlInput)] +#[derive(Deserialize, CommandInput)] struct Input { id: Option, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs index 79e278999..baef4e689 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs @@ -1,6 +1,6 @@ -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::{command_input_defaults, CommandInput}; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct Input { count: i64, } diff --git a/distributed_macros/tests/command_types_compile_fail.rs b/distributed_macros/tests/command_types_compile_fail.rs new file mode 100644 index 000000000..44321cdf7 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail.rs @@ -0,0 +1,7 @@ +//! Compile-time diagnostics specific to CommandInput / CommandOutput. + +#[test] +fn command_types_compile_fail() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/command_types_compile_fail/*.rs"); +} diff --git a/distributed_macros/tests/graphql_compile_fail/nested_lists.rs b/distributed_macros/tests/command_types_compile_fail/nested_lists.rs similarity index 60% rename from distributed_macros/tests/graphql_compile_fail/nested_lists.rs rename to distributed_macros/tests/command_types_compile_fail/nested_lists.rs index 79e900306..60e698d4f 100644 --- a/distributed_macros/tests/graphql_compile_fail/nested_lists.rs +++ b/distributed_macros/tests/command_types_compile_fail/nested_lists.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlInput; +use distributed::CommandInput; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct NestedLists { values: Option>>>, } diff --git a/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr b/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr new file mode 100644 index 000000000..5a7498fbf --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr @@ -0,0 +1,5 @@ +error: nested lists are not supported for CommandInput/CommandOutput fields + --> tests/command_types_compile_fail/nested_lists.rs:5:13 + | +5 | values: Option>>>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_container_default.rs b/distributed_macros/tests/command_types_compile_fail/serde_container_default.rs similarity index 65% rename from distributed_macros/tests/graphql_compile_fail/serde_container_default.rs rename to distributed_macros/tests/command_types_compile_fail/serde_container_default.rs index deb0cb832..43b73b2fe 100644 --- a/distributed_macros/tests/graphql_compile_fail/serde_container_default.rs +++ b/distributed_macros/tests/command_types_compile_fail/serde_container_default.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlInput; +use distributed::CommandInput; -#[derive(GraphqlInput)] +#[derive(CommandInput)] #[serde(default = "default_input")] struct ContainerDefaultInput { value: String, diff --git a/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr b/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr new file mode 100644 index 000000000..6a418939b --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr @@ -0,0 +1,5 @@ +error: #[serde(default)] is not supported by CommandInput because it changes the declared command object shape; define a separate wire type + --> tests/command_types_compile_fail/serde_container_default.rs:4:9 + | +4 | #[serde(default = "default_input")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_default.rs b/distributed_macros/tests/command_types_compile_fail/serde_default.rs similarity index 59% rename from distributed_macros/tests/graphql_compile_fail/serde_default.rs rename to distributed_macros/tests/command_types_compile_fail/serde_default.rs index ca4633108..2ccfbcfd5 100644 --- a/distributed_macros/tests/graphql_compile_fail/serde_default.rs +++ b/distributed_macros/tests/command_types_compile_fail/serde_default.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlInput; +use distributed::CommandInput; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct DefaultedInput { #[serde(default)] value: String, diff --git a/distributed_macros/tests/command_types_compile_fail/serde_default.stderr b/distributed_macros/tests/command_types_compile_fail/serde_default.stderr new file mode 100644 index 000000000..7c3c9e18d --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_default.stderr @@ -0,0 +1,5 @@ +error: #[serde(default)] is not supported by CommandInput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_default.rs:5:13 + | +5 | #[serde(default)] + | ^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_skip.rs b/distributed_macros/tests/command_types_compile_fail/serde_skip.rs similarity index 67% rename from distributed_macros/tests/graphql_compile_fail/serde_skip.rs rename to distributed_macros/tests/command_types_compile_fail/serde_skip.rs index e7f761f58..26ff6f4fe 100644 --- a/distributed_macros/tests/graphql_compile_fail/serde_skip.rs +++ b/distributed_macros/tests/command_types_compile_fail/serde_skip.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlOutput; +use distributed::CommandOutput; -#[derive(GraphqlOutput)] +#[derive(CommandOutput)] struct SkippedOutput { #[serde(skip_serializing_if = "Option::is_none")] value: Option, diff --git a/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr b/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr new file mode 100644 index 000000000..6c2a582b3 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr @@ -0,0 +1,5 @@ +error: #[serde(skip_serializing_if)] is not supported by CommandOutput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_skip.rs:5:13 + | +5 | #[serde(skip_serializing_if = "Option::is_none")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_transparent.rs b/distributed_macros/tests/command_types_compile_fail/serde_transparent.rs similarity index 60% rename from distributed_macros/tests/graphql_compile_fail/serde_transparent.rs rename to distributed_macros/tests/command_types_compile_fail/serde_transparent.rs index 238801538..10d99439c 100644 --- a/distributed_macros/tests/graphql_compile_fail/serde_transparent.rs +++ b/distributed_macros/tests/command_types_compile_fail/serde_transparent.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlInput; +use distributed::CommandInput; -#[derive(GraphqlInput)] +#[derive(CommandInput)] #[serde(transparent)] struct TransparentInput { value: String, diff --git a/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr b/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr new file mode 100644 index 000000000..9bcd53272 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr @@ -0,0 +1,5 @@ +error: #[serde(transparent)] is not supported by CommandInput because it changes the declared command object shape; define a separate wire type + --> tests/command_types_compile_fail/serde_transparent.rs:4:9 + | +4 | #[serde(transparent)] + | ^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_with.rs b/distributed_macros/tests/command_types_compile_fail/serde_with.rs similarity index 61% rename from distributed_macros/tests/graphql_compile_fail/serde_with.rs rename to distributed_macros/tests/command_types_compile_fail/serde_with.rs index a921590e1..29cd62f26 100644 --- a/distributed_macros/tests/graphql_compile_fail/serde_with.rs +++ b/distributed_macros/tests/command_types_compile_fail/serde_with.rs @@ -1,6 +1,6 @@ -use distributed::GraphqlOutput; +use distributed::CommandOutput; -#[derive(GraphqlOutput)] +#[derive(CommandOutput)] struct CustomOutput { #[serde(with = "wire_value")] value: String, diff --git a/distributed_macros/tests/command_types_compile_fail/serde_with.stderr b/distributed_macros/tests/command_types_compile_fail/serde_with.stderr new file mode 100644 index 000000000..eb0e9587a --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_with.stderr @@ -0,0 +1,5 @@ +error: #[serde(with)] is not supported by CommandOutput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_with.rs:5:13 + | +5 | #[serde(with = "wire_value")] + | ^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs b/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs index 8c097363e..a61a18d5e 100644 --- a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs +++ b/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs @@ -6,13 +6,13 @@ struct ActualInput; id = "todo.mismatch", roles(user), input = ExpectedInput, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn declared_type_mismatch( _context: &distributed::microsvc::CausalCommandContext<'_, MismatchAggregate>, _input: ActualInput, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs index 38c11ade6..e173a3023 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs @@ -1,7 +1,7 @@ use std::sync::LazyLock; use distributed::application::{CommandDefinition, CommandSpec, CommandTypeField, CommandTypeSpec}; -use distributed::graphql::CommandConsistency; +use distributed::command::CommandConsistency; fn spec() -> CommandSpec { CommandSpec::try_new( diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs index bde61a0fe..bc12b78f4 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs @@ -6,13 +6,13 @@ struct Input; id = "todo.rename", roles(user), input = Input, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn duplicate_option( _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, _input: Input, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs index d498453c3..b6c08949f 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs @@ -5,13 +5,13 @@ struct Input; id = "todo.create", roles(user, user), input = Input, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn duplicate_role( _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, _input: Input, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_empty_roles.rs b/distributed_macros/tests/compile_fail/application_command_empty_roles.rs index 6846e99ac..207884b43 100644 --- a/distributed_macros/tests/compile_fail/application_command_empty_roles.rs +++ b/distributed_macros/tests/compile_fail/application_command_empty_roles.rs @@ -5,13 +5,13 @@ struct Input; id = "todo.create", roles(), input = Input, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn empty_roles( _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, _input: Input, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_invalid_id.rs b/distributed_macros/tests/compile_fail/application_command_invalid_id.rs index 722f23943..02a3fc5b2 100644 --- a/distributed_macros/tests/compile_fail/application_command_invalid_id.rs +++ b/distributed_macros/tests/compile_fail/application_command_invalid_id.rs @@ -5,13 +5,13 @@ struct Input; id = "../Admin", roles(admin), input = Input, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn invalid_id( _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, _input: Input, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_missing_roles.rs b/distributed_macros/tests/compile_fail/application_command_missing_roles.rs index d1aa37d18..46fcc0046 100644 --- a/distributed_macros/tests/compile_fail/application_command_missing_roles.rs +++ b/distributed_macros/tests/compile_fail/application_command_missing_roles.rs @@ -4,13 +4,13 @@ struct Input; #[distributed::command( id = "todo.create", input = Input, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn missing_roles( _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, _input: Input, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, distributed::microsvc::HandlerError, > { unreachable!() diff --git a/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs b/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs index f022ebcc3..b744a6296 100644 --- a/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs +++ b/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs @@ -5,7 +5,7 @@ struct WrongInput; id = "todo.create", roles(user), input = WrongInput, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] async fn wrong_handler( _context: &distributed::microsvc::CausalCommandContext<'_, WrongAggregate>, diff --git a/distributed_macros/tests/graphql_compile_fail.rs b/distributed_macros/tests/graphql_compile_fail.rs deleted file mode 100644 index 2cbead39d..000000000 --- a/distributed_macros/tests/graphql_compile_fail.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Compile-time diagnostics specific to GraphqlInput / GraphqlOutput. - -#[test] -fn graphql_compile_fail() { - let t = trybuild::TestCases::new(); - t.compile_fail("tests/graphql_compile_fail/*.rs"); -} diff --git a/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr b/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr deleted file mode 100644 index b3159e93f..000000000 --- a/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: nested lists are not supported for GraphqlInput/GraphqlOutput fields - --> tests/graphql_compile_fail/nested_lists.rs:5:13 - | -5 | values: Option>>>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr b/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr deleted file mode 100644 index 6ad3ec642..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(default)] is not supported by GraphqlInput because it changes the declared GraphQL object shape; define a separate wire type - --> tests/graphql_compile_fail/serde_container_default.rs:4:9 - | -4 | #[serde(default = "default_input")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_default.stderr b/distributed_macros/tests/graphql_compile_fail/serde_default.stderr deleted file mode 100644 index a2fc841e6..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_default.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(default)] is not supported by GraphqlInput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_default.rs:5:13 - | -5 | #[serde(default)] - | ^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs b/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs deleted file mode 100644 index 375917b7e..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlOutput; - -#[derive(GraphqlOutput)] -#[serde(rename_all = "kebab-case")] -struct KebabCase { - field_name: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr b/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr deleted file mode 100644 index 1197d3830..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case - --> tests/graphql_compile_fail/serde_kebab_case.rs:4:22 - | -4 | #[serde(rename_all = "kebab-case")] - | ^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr b/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr deleted file mode 100644 index dde249172..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(skip_serializing_if)] is not supported by GraphqlOutput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_skip.rs:5:13 - | -5 | #[serde(skip_serializing_if = "Option::is_none")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr b/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr deleted file mode 100644 index c8d1159dc..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(transparent)] is not supported by GraphqlInput because it changes the declared GraphQL object shape; define a separate wire type - --> tests/graphql_compile_fail/serde_transparent.rs:4:9 - | -4 | #[serde(transparent)] - | ^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_with.stderr b/distributed_macros/tests/graphql_compile_fail/serde_with.stderr deleted file mode 100644 index 0707da8a9..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_with.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(with)] is not supported by GraphqlOutput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_with.rs:5:13 - | -5 | #[serde(with = "wire_value")] - | ^^^^^^^^^^^^^^^^^^^ diff --git a/src/graphql/client_manifest/mod.rs b/src/graphql/client_manifest/mod.rs index 022c6b580..9a5f8db20 100644 --- a/src/graphql/client_manifest/mod.rs +++ b/src/graphql/client_manifest/mod.rs @@ -27,7 +27,6 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use super::command_contract::{CommandConsistency, EffectExpression}; use super::complexity_contract::{default_weights, DEFAULT_MAX_COMPLEXITY, DEFAULT_MAX_DEPTH}; use super::filter::{FilterExpr, Operand}; use super::naming::{aggregate_fields_type_name, aggregate_type_name}; @@ -36,6 +35,7 @@ use super::surface::{ SurfaceCommand, SurfaceCommandShape, SurfaceRelationshipKeys, SurfaceRowPolicy, SurfaceSelection, SurfaceTypeDef, }; +use crate::command::{CommandConsistency, EffectExpression}; use crate::table::RelationshipKind; use build::client_manifest_from_surface_with_execution; diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 3df26c721..94fb6c0a8 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -1,9 +1,9 @@ use super::*; use crate::command::{typed_command, Eventual, PreparedCommand, Succeeded}; +use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; use crate::graphql::{ - build_surface, claim, col, rel, surface_for_application, surface_for_role, GraphqlInputType, - GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, RoleGrant, SurfaceCommand, SurfaceOptions, - SurfaceProjector, SurfaceTypeField, + build_surface, claim, col, rel, surface_for_application, surface_for_role, RoleGrant, + SurfaceCommand, SurfaceOptions, SurfaceProjector, SurfaceTypeField, }; use crate::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use crate::table::{ @@ -184,11 +184,11 @@ fn team_members() -> TableSchema { #[derive(Deserialize)] struct CompleteInput; -impl GraphqlInputType for CompleteInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for CompleteInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CompleteTodoInput", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "todo_id".into(), type_name: "String".into(), nullable: false, @@ -203,11 +203,11 @@ impl GraphqlInputType for CompleteInput { #[derive(Serialize)] struct CompletePayload; -impl GraphqlOutputType for CompletePayload { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for CompletePayload { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CompleteTodoPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "todo_id".into(), type_name: "String".into(), nullable: false, @@ -479,7 +479,7 @@ fn modeled_surface_with_base( } fn projected_surface() -> Surface { - use super::super::command_contract::{CommandEffects, CommandProjectedModel, EffectExpression}; + use crate::command::{CommandEffects, CommandProjectedModel, EffectExpression}; let todo_schema: &'static TableSchema = Box::leak(Box::new(todos())); let mut surface = build_surface(&[todo_schema.clone(), users()], &SurfaceOptions::sqlite()) @@ -601,7 +601,7 @@ fn projected_command_exports_opaque_role_safe_direct_target() { #[test] fn legacy_effect_presets_are_not_v2_client_authority() { - use super::super::command_contract::{ + use crate::command::{ CommandEffect, CommandEffects, EffectExpression, EffectFieldValue, EffectKey, }; diff --git a/src/graphql/commands.rs b/src/graphql/commands.rs index 2e59b30f9..18d2ab970 100644 --- a/src/graphql/commands.rs +++ b/src/graphql/commands.rs @@ -8,16 +8,16 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; -#[cfg(feature = "graphql")] -use super::command_contract::CommandConsistency; -use super::command_contract::TypedCommandContract; #[cfg(feature = "graphql")] use super::surface::{ compile_projection_owner_topology, validate_direct_modeled_owner_compatibility, SurfaceProjectionOwner, }; use super::surface::{SurfaceCommand, SurfaceCommandShape, SurfaceTypeDef, SurfaceTypeField}; +#[cfg(feature = "graphql")] +use crate::command::CommandConsistency; use crate::command::CommandTypeDef; +use crate::command::TypedCommandContract; #[derive(Clone, Debug, Default)] pub(crate) struct TypedCommandInventory { diff --git a/src/graphql/engine/mod.rs b/src/graphql/engine/mod.rs index ce85b1cc1..991cf016f 100644 --- a/src/graphql/engine/mod.rs +++ b/src/graphql/engine/mod.rs @@ -24,7 +24,6 @@ use super::client_manifest::{ trusted_preset_descriptors, ClientExecutionLimits, ClientManifestError, ClientSurfaceIdentity, ClientTrustedPresetDescriptor, DistributedClientManifest, DistributedClientSurfaceExport, }; -use super::command_contract::TypedServiceCommandBinding; use super::commands::TypedCommandInventory; use super::compile::{SqlDialect, SqlPlan}; use super::execute; @@ -48,6 +47,7 @@ use super::surface::{ build_surface, surface_for_application_contract, surface_for_role, Surface, SurfaceDialect, SurfaceOptions, SurfaceProjectionOwner, SurfaceProjector, SurfaceSelection, }; +use crate::command::TypedServiceCommandBinding; const GRAPHIQL_INTROSPECTION_MAX_DEPTH_FLOOR: usize = 15; const GRAPHIQL_INTROSPECTION_MAX_COMPLEXITY_FLOOR: usize = 10_000; diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index 6c5b93b0a..fa4e51645 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -11,12 +11,12 @@ mod client_surface_parity_tests { use super::*; use crate::command::CommandConsistency; use crate::command::{CommandEffects, TypedCommandContract}; + use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; use crate::graphql::commands::TypedCommandInventory; #[cfg(feature = "sqlite")] use crate::graphql::ModelNormalization; use crate::graphql::{ - claim, col, ClientRootOperation, DistributedClientSurfaceExport, GraphqlInputType, - GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, RoleGrant, + claim, col, ClientRootOperation, DistributedClientSurfaceExport, RoleGrant, }; use crate::table::{ColumnType, PrimaryKey, TableColumn, TableKind, TableSchema}; #[cfg(feature = "sqlite")] @@ -65,15 +65,15 @@ mod client_surface_parity_tests { roles: &[&str], ) -> TypedCommandContract where - I: GraphqlInputType + 'static, - O: GraphqlOutputType + 'static, + I: CommandInputType + 'static, + O: CommandOutputType + 'static, { TypedCommandContract { name: command_name.into(), field_name: field_name.into(), roles: roles.iter().map(|role| (*role).into()).collect(), - input: I::graphql_type().with_type_id(TypeId::of::()).into(), - output: O::graphql_type().with_type_id(TypeId::of::()).into(), + input: I::command_type().with_type_id(TypeId::of::()), + output: O::command_type().with_type_id(TypeId::of::()), input_type_id: TypeId::of::(), output_type_id: TypeId::of::(), consistency: CommandConsistency::Succeeded, @@ -1405,9 +1405,9 @@ mod client_surface_parity_tests { type_name: &str, nullable: bool, list: bool, - nested: Option, - ) -> GraphqlTypeField { - GraphqlTypeField { + nested: Option, + ) -> CommandTypeField { + CommandTypeField { name: name.into(), type_name: type_name.into(), nullable, @@ -1419,16 +1419,16 @@ mod client_surface_parity_tests { struct ChangeOrderInput; - impl GraphqlInputType for ChangeOrderInput { - fn graphql_type() -> GraphqlTypeDef { - let patch = GraphqlTypeDef::new( + impl CommandInputType for ChangeOrderInput { + fn command_type() -> CommandTypeDef { + let patch = CommandTypeDef::new( "OrderPatchInput", vec![ type_field("status", "String", false, false, None), type_field("metadata", "JSON", true, false, None), ], ); - GraphqlTypeDef::new( + CommandTypeDef::new( "ChangeOrderInput", vec![ type_field("patch", "OrderPatchInput", false, false, Some(patch)), @@ -1440,16 +1440,16 @@ mod client_surface_parity_tests { struct ChangeOrderPayload; - impl GraphqlOutputType for ChangeOrderPayload { - fn graphql_type() -> GraphqlTypeDef { - let changed_order = GraphqlTypeDef::new( + impl CommandOutputType for ChangeOrderPayload { + fn command_type() -> CommandTypeDef { + let changed_order = CommandTypeDef::new( "ChangedOrder", vec![ type_field("status", "String", false, false, None), type_field("order_id", "String", false, false, None), ], ); - GraphqlTypeDef::new( + CommandTypeDef::new( "ChangeOrderPayload", vec![ type_field("warnings", "String", true, true, None), diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index a546d46a2..9c676cf09 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -1,4 +1,4 @@ -//! Auto-generated read-only GraphQL over relational read models. +//! GraphQL gateway for read-model queries, subscriptions, and core commands. //! //! `naming` and `sdl` always compile (zero deps beyond the rest of the crate) //! so `distributed schema --format graphql` works without enabling the `graphql` @@ -6,7 +6,6 @@ //! `feature = "graphql"`. pub mod client_manifest; -pub(crate) use crate::command as command_contract; pub mod naming; pub mod projection_delta; pub mod sdl; @@ -19,31 +18,8 @@ mod commands; mod complexity_contract; mod filter; mod permissions; -mod types; pub use client_manifest::*; -#[doc(hidden)] -pub use command_contract::{ - __command_input_defaults, __effect_key, __effect_key_assignment, __effect_key_field, - __effect_relationship, __input_default_ulid, __input_default_uuid_v7, CombineEffectNullability, - CompiledEffectKeyField, CompiledInputDefault, EffectInputDescendableKind, - EffectInputFieldMarker, EffectInputObjectKind, EffectInputPath, EffectInputPathKind, - EffectInputTerminalKind, EffectModelFieldMarker, EffectNullable, EffectPathNullability, - EffectRelationshipMarker, EffectRequired, EffectWireBigInt, EffectWireBoolean, EffectWireBytea, - EffectWireChecked, EffectWireCompatible, EffectWireFloat, EffectWireJson, EffectWireList, - EffectWireLiteral, EffectWireObject, EffectWireString, EffectWireTimestamp, - EffectWireUnsupported, -}; -pub use command_contract::{ - __command_projection_event_descriptor, __command_projection_event_preview, - __command_projection_events, __command_projection_preview_constant, - __command_projection_state_known_values, __command_projection_state_preview, - command_transition, typed_command, Atomic, CommandConsistency, CommandEventSet, CommandOutcome, - CommandProjectionEventSet, CommandProjectionPreview, CommandProjectionPreviewSource, - CommandProjectionPureArg, CommandProjectionPureReduce, CompiledDirectProjectionTarget, - CompiledInputDefaults, Eventual, PrepareCommandError, PreparedCommand, Succeeded, TypedCommand, - TypedEffectExpression, TypedEffectKey, TypedEffectRelationship, -}; pub use naming::{ aggregate_field, by_pk_field, comparison_op_fields, include_postgres_json_comparison_ops, is_valid_graphql_name, mutation_delete_by_pk_field, mutation_insert_one_field, @@ -68,7 +44,6 @@ pub use permissions::{ read, role_grant_from_read_permission, role_grants_from_model_role_perms, ModelPermissions, ReadPermission, }; -pub use types::{GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField}; #[cfg(feature = "graphql")] mod compile; diff --git a/src/graphql/projection_delta/tests.rs b/src/graphql/projection_delta/tests.rs index 906bbb401..770b252b5 100644 --- a/src/graphql/projection_delta/tests.rs +++ b/src/graphql/projection_delta/tests.rs @@ -51,12 +51,12 @@ const FOREIGN_CAUSATION_ID: &str = "0190a000-0000-7000-8000-000000000018"; const TEST_COMMAND_NAME: &str = "todo.modeled"; #[allow(dead_code)] -#[derive(Deserialize, crate::GraphqlInput)] +#[derive(Deserialize, crate::CommandInput)] struct ModeledCommandInput { todo_id: String, } -#[derive(Serialize, crate::GraphqlOutput)] +#[derive(Serialize, crate::CommandOutput)] struct ModeledCommandOutput { accepted: bool, } diff --git a/src/graphql/surface/mod.rs b/src/graphql/surface/mod.rs index 63a0e94d0..2bc19501a 100644 --- a/src/graphql/surface/mod.rs +++ b/src/graphql/surface/mod.rs @@ -12,14 +12,14 @@ use std::ops::Deref; use sha2::{Digest, Sha256}; -use super::command_contract::{ +use super::filter::{validate_row_policy_operand_literal, FilterExpr, Operand}; +use crate::command::{ compiled_direct_projection_target, validate_projection_confirmation_count, CommandConsistency, CommandDirectProjectionTarget, CommandEffect, CommandEffects, CommandInputDefault, CommandProjectedModel, CommandProjectionConfirmation, CommandProjectionEvents, CommandProjectionPreviewSource, CompiledDirectProjectionTarget, EffectExpression, EffectFieldValue, EffectKey, EffectRelationship, }; -use super::filter::{validate_row_policy_operand_literal, FilterExpr, Operand}; use crate::projection_protocol::ProjectionModelOwnership; use crate::projection_protocol::ProjectionPartitionSpec; use crate::table::{ diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index 3e4048fdd..db54af2f7 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -4,7 +4,7 @@ use super::*; use crate::command::{CommandEffects, TypedCommandContract}; use crate::graphql::commands::TypedCommandInventory; -use crate::graphql::{GraphqlTypeDef, GraphqlTypeField}; +use crate::command::{CommandTypeDef, CommandTypeField}; use crate::table::{ ColumnType, PrimaryKey, RelationshipDef, RelationshipKind, TableColumn, TableKind, }; @@ -225,7 +225,7 @@ fn modeled_direct_projection( fn test_command( command_name: &str, field_name: &str, - output: GraphqlTypeDef, + output: CommandTypeDef, ) -> TypedCommandContract { let input_type_id = TypeId::of::(); let output_type_id = TypeId::of::<()>(); @@ -233,9 +233,9 @@ fn test_command( name: command_name.into(), field_name: field_name.into(), roles: Vec::new(), - input: GraphqlTypeDef::new( + input: CommandTypeDef::new( "TestCommandInput", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -244,9 +244,8 @@ fn test_command( nested: None, }], ) - .with_type_id(input_type_id) - .into(), - output: output.with_type_id(output_type_id).into(), + .with_type_id(input_type_id), + output: output.with_type_id(output_type_id), input_type_id, output_type_id, consistency: CommandConsistency::Succeeded, @@ -268,9 +267,9 @@ fn test_inventory( #[test] fn causal_surface_commands_accept_modeled_event_selectors_but_not_empty_authority() { let output = || { - GraphqlTypeDef::new( + CommandTypeDef::new( "CausalPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -833,9 +832,9 @@ fn role_policy_rejects_non_finite_and_hides_js_unsafe_integers() { #[test] fn command_surface_rejects_duplicate_mutation_field_ids() { - let output = GraphqlTypeDef::new( + let output = CommandTypeDef::new( "TestCommandPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -860,7 +859,7 @@ fn command_surface_rejects_empty_nested_and_surface_colliding_types() { let empty = test_inventory([test_command( "order.empty", "order_empty", - GraphqlTypeDef::new("EmptyPayload", Vec::new()), + CommandTypeDef::new("EmptyPayload", Vec::new()), )]); let error = build_surface(&[orders()], &SurfaceOptions::sqlite()) .unwrap() @@ -871,15 +870,15 @@ fn command_surface_rejects_empty_nested_and_surface_colliding_types() { let nested = test_inventory([test_command( "order.nested_empty", "order_nested_empty", - GraphqlTypeDef::new( + CommandTypeDef::new( "OuterPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "inner".into(), type_name: "InnerPayload".into(), nullable: false, list: false, item_nullable: false, - nested: Some(Box::new(GraphqlTypeDef::new("InnerPayload", Vec::new()))), + nested: Some(Box::new(CommandTypeDef::new("InnerPayload", Vec::new()))), }], ), )]); @@ -892,9 +891,9 @@ fn command_surface_rejects_empty_nested_and_surface_colliding_types() { let collision = test_inventory([test_command( "order.collision", "order_collision", - GraphqlTypeDef::new( + CommandTypeDef::new( "OrderView", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "order_id".into(), type_name: "String".into(), nullable: false, diff --git a/src/graphql/types.rs b/src/graphql/types.rs deleted file mode 100644 index 1be5da675..000000000 --- a/src/graphql/types.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Command-mutation GraphQL type metadata (input/output derives). - -use std::any::TypeId; - -use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; - -/// One field on a GraphQL input or output object. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GraphqlTypeField { - pub name: String, - pub type_name: String, - pub nullable: bool, - pub list: bool, - /// Whether list elements are nullable. Always `false` for non-list fields. - pub item_nullable: bool, - /// Nested object type definition when `type_name` is not a scalar. - pub nested: Option>, -} - -/// Full type definition for a derive-emitted input or output object. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GraphqlTypeDef { - pub name: String, - pub fields: Vec, - pub type_id: Option, -} - -impl GraphqlTypeDef { - pub fn new(name: impl Into, fields: Vec) -> Self { - Self { - name: name.into(), - fields, - type_id: None, - } - } - - pub fn with_type_id(mut self, id: TypeId) -> Self { - self.type_id = Some(id); - self - } - - /// Transitive nested type defs (depth-first, deduped by name). - pub fn transitive_nested(&self) -> Vec { - let mut out = Vec::new(); - let mut seen = std::collections::BTreeSet::new(); - self.collect_nested(&mut out, &mut seen); - out - } - - fn collect_nested( - &self, - out: &mut Vec, - seen: &mut std::collections::BTreeSet, - ) { - for field in &self.fields { - if let Some(nested) = &field.nested { - if seen.insert(nested.name.clone()) { - out.push((**nested).clone()); - nested.collect_nested(out, seen); - } - } - } - } -} - -pub trait GraphqlInputType { - fn graphql_type() -> GraphqlTypeDef; -} - -pub trait GraphqlOutputType { - fn graphql_type() -> GraphqlTypeDef; -} - -// Builtin scalar mappings for free-standing helpers used by derives. -#[allow(dead_code)] -pub fn scalar_for_rust_type(ty: &str) -> Option<&'static str> { - match ty { - "String" | "str" => Some("String"), - "bool" => Some("Boolean"), - "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "isize" | "usize" => { - Some("BigInt") - } - "f32" | "f64" => Some("Float"), - "Value" | "serde_json::Value" => Some("JSON"), - _ => None, - } -} - -// Legacy GraphQL authors can keep their derives/manual implementations. The core -// depends only on command traits; the adapter translates legacy metadata here. -impl CommandInputType for T { - fn command_type() -> CommandTypeDef { - T::graphql_type().into() - } -} -impl CommandOutputType for T { - fn command_type() -> CommandTypeDef { - T::graphql_type().into() - } -} - -impl From for CommandTypeDef { - fn from(value: GraphqlTypeDef) -> Self { - Self { - name: value.name, - type_id: value.type_id, - fields: value - .fields - .into_iter() - .map(|field| CommandTypeField { - name: field.name, - type_name: field.type_name, - nullable: field.nullable, - list: field.list, - item_nullable: field.item_nullable, - nested: field.nested.map(|nested| Box::new((*nested).into())), - }) - .collect(), - } - } -} - -/// Derive GraphQL metadata from a transport-neutral command descriptor. -impl From for GraphqlTypeDef { - fn from(value: CommandTypeDef) -> Self { - Self { - name: value.name, - type_id: value.type_id, - fields: value - .fields - .into_iter() - .map(|field| GraphqlTypeField { - name: field.name, - type_name: field.type_name, - nullable: field.nullable, - list: field.list, - item_nullable: field.item_nullable, - nested: field.nested.map(|nested| Box::new((*nested).into())), - }) - .collect(), - } - } -} - -// Preserve the existing public conversion at the compatibility boundary. -impl From<&GraphqlTypeDef> for crate::application::CommandTypeSpec { - fn from(value: &GraphqlTypeDef) -> Self { - Self::from(&CommandTypeDef::from(value.clone())) - } -} diff --git a/src/lib.rs b/src/lib.rs index 118aa27fc..865d5abfc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -470,7 +470,7 @@ pub use microsvc::{ pub use distributed_macros::{ aggregate, application, command, command_input_defaults, digest, module, mutation, mutation_file, portable_command, sourced, CommandInput, CommandOutput, DomainEvent, - DomainState, GraphqlInput, GraphqlOutput, ReadModel, Snapshot, + DomainState, ReadModel, Snapshot, }; // Re-export enqueue macro (requires "emitter" feature) diff --git a/src/microsvc/causal.rs b/src/microsvc/causal.rs index 3eb650802..267925999 100644 --- a/src/microsvc/causal.rs +++ b/src/microsvc/causal.rs @@ -816,8 +816,8 @@ mod tests { use super::*; use std::sync::Arc; + use crate::command::CommandTypeDef; use crate::entity::{Entity, EventRecord}; - use crate::graphql::GraphqlTypeDef; use crate::table::{ ColumnType, PrimaryKey, RowKey, RowValue, RowValues, TableColumn, TableKind, TableMutation, TableSchema, @@ -1067,9 +1067,9 @@ mod tests { #[derive(serde::Deserialize)] struct TestInput {} - impl crate::graphql::GraphqlInputType for TestInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new("TestInput", Vec::new()) + impl crate::command::CommandInputType for TestInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new("TestInput", Vec::new()) .with_type_id(std::any::TypeId::of::()) } } diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index 97fe536c1..fca410105 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -39,23 +39,23 @@ impl CellItem { } } -#[derive(Debug, Deserialize, crate::GraphqlInput)] +#[derive(Debug, Deserialize, crate::CommandInput)] struct CreateInput { id: String, title: String, } -#[derive(Debug, Serialize, crate::GraphqlOutput)] +#[derive(Debug, Serialize, crate::CommandOutput)] struct CreatePayload { id: String, } -#[derive(Debug, Deserialize, crate::GraphqlInput)] +#[derive(Debug, Deserialize, crate::CommandInput)] struct CompleteInput { id: String, } -#[derive(Debug, Serialize, crate::GraphqlOutput)] +#[derive(Debug, Serialize, crate::CommandOutput)] struct CompletePayload { id: String, done: bool, diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index f96533621..8520e75d0 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -11,6 +11,7 @@ use crate::command::Eventual; use crate::command::{typed_command, PreparedCommand, Succeeded}; #[cfg(feature = "graphql")] use crate::command::{Atomic, CommandConsistency}; +use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; #[cfg(feature = "graphql")] use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, @@ -19,7 +20,6 @@ use crate::command_ledger::{ }; #[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; -use crate::graphql::{GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField}; #[cfg(feature = "graphql")] use crate::graphql::{SurfaceDirectProjection, SurfaceProjector}; #[cfg(feature = "graphql")] @@ -73,10 +73,10 @@ struct TypedOutput { id: String, } -fn one_string_field(name: &str, field: &str) -> GraphqlTypeDef { - GraphqlTypeDef::new( +fn one_string_field(name: &str, field: &str) -> CommandTypeDef { + CommandTypeDef::new( name, - vec![GraphqlTypeField { + vec![CommandTypeField { name: field.into(), type_name: "String".into(), nullable: false, @@ -87,14 +87,14 @@ fn one_string_field(name: &str, field: &str) -> GraphqlTypeDef { ) } -impl GraphqlInputType for TypedInput { - fn graphql_type() -> GraphqlTypeDef { +impl CommandInputType for TypedInput { + fn command_type() -> CommandTypeDef { one_string_field("TypedInput", "id").with_type_id(std::any::TypeId::of::()) } } -impl GraphqlOutputType for TypedOutput { - fn graphql_type() -> GraphqlTypeDef { +impl CommandOutputType for TypedOutput { + fn command_type() -> CommandTypeDef { one_string_field("TypedOutput", "id").with_type_id(std::any::TypeId::of::()) } } @@ -107,12 +107,12 @@ struct CausalTestInput { } #[cfg(feature = "graphql")] -impl GraphqlInputType for CausalTestInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for CausalTestInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CausalTestInput", vec![ - GraphqlTypeField { + CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -120,7 +120,7 @@ impl GraphqlInputType for CausalTestInput { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "label".into(), type_name: "String".into(), nullable: false, @@ -135,7 +135,7 @@ impl GraphqlInputType for CausalTestInput { } #[cfg(feature = "graphql")] -#[derive(Clone, Deserialize, crate::GraphqlInput)] +#[derive(Clone, Deserialize, crate::CommandInput)] struct CausalProjectionInput { #[serde(rename = "todoId")] id: String, @@ -587,28 +587,28 @@ fn modeled_lifecycle_projector( } #[cfg(feature = "graphql")] -impl GraphqlOutputType for CausalProjectionObligationView { - fn graphql_type() -> GraphqlTypeDef { +impl CommandOutputType for CausalProjectionObligationView { + fn command_type() -> CommandTypeDef { one_string_field("CausalProjectionObligationView", "id") .with_type_id(std::any::TypeId::of::()) } } #[cfg(feature = "graphql")] -impl GraphqlOutputType for CausalProjectionSiblingView { - fn graphql_type() -> GraphqlTypeDef { +impl CommandOutputType for CausalProjectionSiblingView { + fn command_type() -> CommandTypeDef { one_string_field("CausalProjectionSiblingView", "id") .with_type_id(std::any::TypeId::of::()) } } #[cfg(feature = "graphql")] -impl GraphqlOutputType for CausalLifecycleView { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for CausalLifecycleView { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CausalLifecycleView", vec![ - GraphqlTypeField { + CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -616,7 +616,7 @@ impl GraphqlOutputType for CausalLifecycleView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "label".into(), type_name: "String".into(), nullable: false, diff --git a/tests/application_composition.rs b/tests/application_composition.rs index d5b6f0029..2e3e06b38 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -6,19 +6,20 @@ use distributed::application::{ CommandDefinition, CommandMount, CommandSpec, CommandTypeField, CommandTypeSpec, ContractCompiler, Module, ProjectionSpec, Runtime, RuntimeDialect, SurfaceSpec, }; +use distributed::command::{typed_command, CommandConsistency, Succeeded}; use distributed::graphql::{ build_surface, col, prune_client_manifest, surface_for_application_contract, surface_for_role, - typed_command, ClientCommandPureReduce, ClientProjectionArm, ClientProjectionEventRef, + ClientCommandPureReduce, ClientProjectionArm, ClientProjectionEventRef, ClientProjectionFallback, ClientProjectionMutationKind, ClientProjectionOperation, - ClientProjectionPartition, ClientProjectionProgram, ClientSurfaceIdentity, CommandConsistency, + ClientProjectionPartition, ClientProjectionProgram, ClientSurfaceIdentity, CommandProjectionArmRef, CommandProjectionExtension, CommandProjectionPreviewOccurrence, - DistributedClientSurfaceExport, RoleGrant, Succeeded, Surface, SurfaceOptions, + DistributedClientSurfaceExport, RoleGrant, Surface, SurfaceOptions, }; use distributed::projection::{ PROJECTION_OPERATION_SEMANTICS_VERSION, PROJECTION_PROGRAM_IR_VERSION, }; use distributed::{ - ApplicationManifest, GraphqlInput, GraphqlOutput, ReadModel, RelationalReadModel, + ApplicationManifest, CommandInput, CommandOutput, ReadModel, RelationalReadModel, }; use serde::{Deserialize, Serialize}; @@ -40,12 +41,12 @@ struct ChatView { } #[allow(dead_code)] -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct ContractCommandInput { title: String, } -#[derive(Clone, Serialize, GraphqlOutput)] +#[derive(Clone, Serialize, CommandOutput)] struct ContractCommandOutput { id: String, } diff --git a/tests/application_plans.rs b/tests/application_plans.rs index 6a72c1eeb..704f9f8c9 100644 --- a/tests/application_plans.rs +++ b/tests/application_plans.rs @@ -5,7 +5,7 @@ use distributed::application::{ CommandTypeSpec, DeploymentPlan, ModelFieldSpec, ModelSpec, Module, MountSelector, ProcessIntent, ProcessPreset, ProjectionSpec, }; -use distributed::graphql::CommandConsistency; +use distributed::command::CommandConsistency; fn portable_command(id: &str, consistency: CommandConsistency) -> CommandSpec { let command = CommandSpec::try_new( diff --git a/tests/causal_public_invoke/main.rs b/tests/causal_public_invoke/main.rs index d58980ca3..671ca8399 100644 --- a/tests/causal_public_invoke/main.rs +++ b/tests/causal_public_invoke/main.rs @@ -5,10 +5,10 @@ #![cfg(feature = "graphql")] -use distributed::graphql::{ - typed_command, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, - Succeeded, VerifiedPrincipal, +use distributed::command::{ + typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, Succeeded, }; +use distributed::graphql::VerifiedPrincipal; use distributed::microsvc::{Routes, Service, Session, USER_ID_KEY}; use distributed::{Aggregate, AggregateBuilder, Entity, InMemoryRepository, Snapshot}; use serde::{Deserialize, Serialize}; @@ -51,11 +51,11 @@ struct CompleteInput { id: String, } -impl GraphqlInputType for CompleteInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for CompleteInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CompleteInput", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -73,11 +73,11 @@ struct CompletePayload { id: String, } -impl GraphqlOutputType for CompletePayload { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for CompletePayload { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CompletePayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index 90b09650d..80875069a 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -5,11 +5,11 @@ use std::sync::Arc; use distributed::bus::{Bus, BusConsumer, InMemoryBus, TransportError}; use distributed::cell_host::InternalHttpSecret; +use distributed::command::{ + typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, Succeeded, +}; use distributed::command_dispatch::{CommandHost, HttpCommandHost, SharedCommandHost}; use distributed::graphql::VerifiedPrincipal; -use distributed::graphql::{ - typed_command, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, Succeeded, -}; use distributed::microsvc::{router, Routes, Service, ROLE_KEY, USER_ID_KEY}; use distributed::{Aggregate, AggregateBuilder, Entity, InMemoryRepository, Snapshot}; use serde::{Deserialize, Serialize}; @@ -52,11 +52,11 @@ struct IdInput { id: String, } -impl GraphqlInputType for IdInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for IdInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "IdInput", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -74,11 +74,11 @@ struct IdPayload { id: String, } -impl GraphqlOutputType for IdPayload { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for IdPayload { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "IdPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/core_command_contract.rs b/tests/core_command_contract.rs index c8cb04907..d62c0c63a 100644 --- a/tests/core_command_contract.rs +++ b/tests/core_command_contract.rs @@ -30,28 +30,6 @@ mod neutral { } } -mod legacy { - use super::*; - use distributed::{GraphqlInput, GraphqlOutput}; - - #[derive(Deserialize, GraphqlInput)] - #[serde(rename_all = "camelCase")] - pub struct ContractInput { - record_id: String, - count: i64, - nested: Option>>, - } - #[derive(Deserialize, GraphqlInput)] - pub struct NestedInput { - enabled: bool, - } - #[derive(Serialize, GraphqlOutput)] - pub struct ContractOutput { - record_id: String, - value: f64, - } -} - fn artifact() -> serde_json::Value where I: CommandInputType + serde::de::DeserializeOwned + Send + 'static, @@ -83,14 +61,6 @@ fn neutral_declarations_preserve_the_pre_extraction_artifact() { ); } -#[test] -fn legacy_graphql_derives_remain_compatible() { - assert_eq!( - artifact::(), - artifact::() - ); -} - #[derive(Deserialize, distributed::CommandInput)] #[serde(rename_all(deserialize = "kebab-case", serialize = "camelCase"))] struct NonGraphqlInput { @@ -153,12 +123,3 @@ fn neutral_shapes_follow_serde_direction_and_preserve_item_nullability() { assert!(list.list && list.nullable && list.item_nullable); } } - -#[test] -fn graphql_metadata_can_be_derived_from_neutral_shapes() { - let neutral = neutral::ContractInput::command_type(); - let graph = graphql::GraphqlTypeDef::from(neutral.clone()); - assert_eq!(graph.name, neutral.name); - assert_eq!(graph.transitive_nested()[0].name, "NestedInput"); - assert_eq!(command::CommandTypeDef::from(graph), neutral); -} diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs b/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs index 947ad45d2..5faf5a815 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{Atomic, CommandProjectionPureReduce, PreparedCommand}; +use distributed::command::{Atomic, CommandProjectionPureReduce, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use e2e_readmodels::BlobGames; @@ -7,7 +7,7 @@ use serde::Deserialize; use super::support::{authenticated_user, principal, rejected, sealed_row}; use crate::{domain_commands, BlobGame, Direction}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct BlobMoveInput { pub game_id: String, pub direction: String, diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/start.rs b/tests/e2e-ui/crates/blob-domain/src/commands/start.rs index 5409b4203..de17a6983 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/start.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/start.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{Atomic, PreparedCommand}; +use distributed::command::{Atomic, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use e2e_readmodels::BlobGames; @@ -7,7 +7,7 @@ use serde::Deserialize; use super::support::{authenticated_user, principal, rejected, sealed_row}; use crate::{domain_commands, BlobGame}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct BlobStartInput { pub game_id: String, } diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs b/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs index 77f6e9ce6..7472d310f 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/start_level.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{Atomic, PreparedCommand}; +use distributed::command::{Atomic, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use e2e_readmodels::BlobGames; @@ -7,7 +7,7 @@ use serde::Deserialize; use super::support::{authenticated_user, principal, rejected, sealed_row}; use crate::{domain_commands, BlobGame}; -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct BlobStartLevelInput { pub game_id: String, } diff --git a/tests/e2e-ui/crates/chat-domain/src/commands/post.rs b/tests/e2e-ui/crates/chat-domain/src/commands/post.rs index 1b0bb5251..cf65fa5b1 100644 --- a/tests/e2e-ui/crates/chat-domain/src/commands/post.rs +++ b/tests/e2e-ui/crates/chat-domain/src/commands/post.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{Eventual, PreparedCommand}; +use distributed::command::{Eventual, PreparedCommand}; use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::portable_command; use serde::{Deserialize, Serialize}; @@ -17,7 +17,7 @@ fn authenticated_user(ctx: &CausalCommandContext<'_, ChatMessage>) -> bool { ctx.session().user_id().is_some_and(|id| !id.is_empty()) } -#[derive(Debug, Deserialize, distributed::GraphqlInput)] +#[derive(Debug, Deserialize, distributed::CommandInput)] pub struct ChatPostInput { pub message_id: String, pub body: String, @@ -27,7 +27,7 @@ pub struct ChatPostInput { pub created_at: String, } -#[derive(Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Debug, Serialize, distributed::CommandOutput)] pub struct ChatPostPayload { pub message_id: String, pub room_id: String, diff --git a/tests/e2e_ui_celld_nats_profile/main.rs b/tests/e2e_ui_celld_nats_profile/main.rs index 1be55cb69..d06f30526 100644 --- a/tests/e2e_ui_celld_nats_profile/main.rs +++ b/tests/e2e_ui_celld_nats_profile/main.rs @@ -77,11 +77,12 @@ mod live { CelldCommandHost, CelldRoute, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, }; - use distributed::command_dispatch::SharedCommandHost; - use distributed::graphql::{ - read, typed_command, GraphqlEngine, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, - GraphqlTypeField, ModelPermissions, Succeeded, VerifiedPrincipal, + use distributed::command::{ + typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, + Succeeded, }; + use distributed::command_dispatch::SharedCommandHost; + use distributed::graphql::{read, GraphqlEngine, ModelPermissions, VerifiedPrincipal}; use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; use distributed::{ Aggregate, AggregateBuilder, Entity, InMemoryRepository, ReadModel, Snapshot, @@ -156,12 +157,12 @@ mod live { title: String, } - impl GraphqlInputType for CreateInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( + impl CommandInputType for CreateInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "CreateInput", vec![ - GraphqlTypeField { + CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -169,7 +170,7 @@ mod live { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "title".into(), type_name: "String".into(), nullable: false, @@ -188,11 +189,11 @@ mod live { id: String, } - impl GraphqlOutputType for IdPayload { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( + impl CommandOutputType for IdPayload { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "IdPayload", - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/fixtures/application-contract-only/src/lib.rs b/tests/fixtures/application-contract-only/src/lib.rs index 68e6b992c..7823483f5 100644 --- a/tests/fixtures/application-contract-only/src/lib.rs +++ b/tests/fixtures/application-contract-only/src/lib.rs @@ -12,9 +12,9 @@ use distributed::microsvc::{CausalCommandContext, HandlerError}; use distributed::table::{ ColumnType, PrimaryKey, TableColumn, TableKind, TableSchema, DEFAULT_TABLE_VERSION_COLUMN, }; -use distributed::{Aggregate, Entity, EventRecord, GraphqlInput, GraphqlOutput}; #[cfg(feature = "application-runtime")] use distributed::AggregateBuilder; +use distributed::{Aggregate, CommandInput, CommandOutput, Entity, EventRecord}; use serde::{Deserialize, Serialize}; #[derive(Default)] @@ -42,13 +42,13 @@ impl Aggregate for ContractAggregate { } } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] pub struct CreateTodoInput { pub id: String, pub title: String, } -#[derive(Clone, Serialize, GraphqlOutput)] +#[derive(Clone, Serialize, CommandOutput)] pub struct CreateTodoOutput { pub id: String, } @@ -61,17 +61,19 @@ pub struct CreateTodoOutput { roles(user, admin), default(title = uuid_v7), input = CreateTodoInput, - outcome = distributed::graphql::Succeeded + outcome = distributed::command::Succeeded )] pub async fn create_todo( _context: &CausalCommandContext<'_, ContractAggregate>, input: CreateTodoInput, ) -> Result< - distributed::graphql::PreparedCommand>, + distributed::command::PreparedCommand>, HandlerError, > { - Ok(distributed::graphql::PreparedCommand::prepare(CreateTodoOutput { id: input.id }) - .expect("generated output is valid")) + Ok( + distributed::command::PreparedCommand::prepare(CreateTodoOutput { id: input.id }) + .expect("generated output is valid"), + ) } distributed::module! { @@ -113,14 +115,8 @@ fn todo_surface() -> Surface { .rows(col("status").eq("open")), )]), )]); - surface_for_application_contract( - &catalog, - "web", - &["user".into()], - &["user".into()], - &grants, - ) - .expect("contract fixture role surface should compile") + surface_for_application_contract(&catalog, "web", &["user".into()], &["user".into()], &grants) + .expect("contract fixture role surface should compile") } static WEB_SURFACE: LazyLock = LazyLock::new(|| { @@ -176,8 +172,12 @@ pub fn surface_sdl() -> String { } pub fn client_manifest_bytes() -> Vec { - serde_json::to_vec(&compiler().client_manifest().expect("client artifact should compile")) - .expect("client artifact should serialize") + serde_json::to_vec( + &compiler() + .client_manifest() + .expect("client artifact should compile"), + ) + .expect("client artifact should serialize") } pub fn selected_surface_fingerprint() -> String { @@ -196,8 +196,7 @@ pub fn runtime_service() -> distributed::microsvc::Service { let _catalog = ReadModelCatalog::new("todo-contract-only"); let repository = InMemoryRepository::new(); let routes = create_todo_register( - distributed::microsvc::Routes::new() - .with_repo(repository.aggregate::()), + distributed::microsvc::Routes::new().with_repo(repository.aggregate::()), ); distributed::microsvc::Service::new() .named("todo-contract-only") @@ -261,6 +260,9 @@ mod tests { #[test] fn no_default_contract_definition_has_no_executable_mount() { assert_eq!(TODO_MODULE.mounts().len(), 0); - assert!(TODO_MODULE.definitions().iter().all(|definition| definition.mount().is_none())); + assert!(TODO_MODULE + .definitions() + .iter() + .all(|definition| definition.mount().is_none())); } } diff --git a/tests/graphql_causal_transport/main.rs b/tests/graphql_causal_transport/main.rs index 44daccf31..aa4724fd5 100644 --- a/tests/graphql_causal_transport/main.rs +++ b/tests/graphql_causal_transport/main.rs @@ -4,12 +4,11 @@ use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use base64::Engine as _; -use distributed::graphql::{ - typed_command, GraphqlEngine, IdentityConfig, OidcConfig, PreparedCommand, Succeeded, -}; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::graphql::{GraphqlEngine, IdentityConfig, OidcConfig}; use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use distributed::{ - Aggregate, AggregateRepository, Entity, EventRecord, GraphqlInput, GraphqlOutput, + Aggregate, AggregateRepository, CommandInput, CommandOutput, Entity, EventRecord, InMemoryRepository, }; use futures_util::{SinkExt, StreamExt}; @@ -76,12 +75,12 @@ impl Aggregate for TransportAggregate { } } -#[derive(Deserialize, GraphqlInput)] +#[derive(Deserialize, CommandInput)] struct TransportCommandInput { id: String, } -#[derive(Serialize, GraphqlOutput)] +#[derive(Serialize, CommandOutput)] struct TransportCommandOutput { id: String, } diff --git a/tests/graphql_commands/main.rs b/tests/graphql_commands/main.rs index aa478b9db..fac88121a 100644 --- a/tests/graphql_commands/main.rs +++ b/tests/graphql_commands/main.rs @@ -2,14 +2,14 @@ #![cfg(feature = "graphql")] -use distributed::graphql::{GraphqlTypeDef, GraphqlTypeField}; +use distributed::command::{CommandTypeDef, CommandTypeField}; #[test] fn graphql_type_def_mapping_golden() { - let input = GraphqlTypeDef::new( + let input = CommandTypeDef::new( "CreateItemInput", vec![ - GraphqlTypeField { + CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -17,7 +17,7 @@ fn graphql_type_def_mapping_golden() { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "tags".into(), type_name: "String".into(), nullable: true, @@ -33,7 +33,7 @@ fn graphql_type_def_mapping_golden() { assert!(input.fields[1].list); } -#[derive(distributed::GraphqlInput)] +#[derive(distributed::CommandInput)] #[allow(dead_code)] struct DerivedInput { id: String, @@ -41,14 +41,14 @@ struct DerivedInput { tags: Option>, } -#[derive(distributed::GraphqlOutput)] +#[derive(distributed::CommandOutput)] #[allow(dead_code)] struct DerivedOutput { ok: bool, id: String, } -#[derive(distributed::GraphqlInput, serde::Deserialize)] +#[derive(distributed::CommandInput, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[allow(dead_code)] struct ScalarMatrixInput { @@ -61,7 +61,7 @@ struct ScalarMatrixInput { optional_nullable_items: Option>>, } -#[derive(distributed::GraphqlOutput, serde::Serialize)] +#[derive(distributed::CommandOutput, serde::Serialize)] #[serde(rename_all = "camelCase")] #[allow(dead_code)] struct ScalarMatrixOutput { @@ -74,7 +74,7 @@ struct ScalarMatrixOutput { optional_nullable_items: Option>>, } -#[derive(distributed::GraphqlInput)] +#[derive(distributed::CommandInput)] #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] #[allow(dead_code)] struct DirectionalInputNames { @@ -83,7 +83,7 @@ struct DirectionalInputNames { custom_id: String, } -#[derive(distributed::GraphqlOutput)] +#[derive(distributed::CommandOutput)] #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] #[allow(dead_code)] struct DirectionalOutputNames { @@ -94,9 +94,9 @@ struct DirectionalOutputNames { #[test] fn derive_mapping_golden() { - use distributed::graphql::{GraphqlInputType, GraphqlOutputType}; + use distributed::command::{CommandInputType, CommandOutputType}; - let input = DerivedInput::graphql_type(); + let input = DerivedInput::command_type(); assert_eq!(input.name, "DerivedInput"); assert_eq!(input.fields.len(), 3); assert_eq!(input.fields[0].type_name, "String"); @@ -105,7 +105,7 @@ fn derive_mapping_golden() { assert!(input.fields[2].list); assert!(input.fields[2].nullable); - let output = DerivedOutput::graphql_type(); + let output = DerivedOutput::command_type(); assert_eq!(output.name, "DerivedOutput"); assert_eq!(output.fields[0].type_name, "Boolean"); assert_eq!(output.fields[1].type_name, "String"); @@ -113,7 +113,7 @@ fn derive_mapping_golden() { #[test] fn derive_preserves_outer_and_item_nullability_and_serde_names() { - use distributed::graphql::{GraphqlInputType, GraphqlOutputType}; + use distributed::command::{CommandInputType, CommandOutputType}; let expected = [ ("wireRequired", false, false, false), @@ -124,8 +124,8 @@ fn derive_preserves_outer_and_item_nullability_and_serde_names() { ("optionalNullableItems", true, true, true), ]; for definition in [ - ScalarMatrixInput::graphql_type(), - ScalarMatrixOutput::graphql_type(), + ScalarMatrixInput::command_type(), + ScalarMatrixOutput::command_type(), ] { for (name, nullable, list, item_nullable) in expected { let field = definition @@ -140,14 +140,14 @@ fn derive_preserves_outer_and_item_nullability_and_serde_names() { } } - let input_names: Vec<_> = DirectionalInputNames::graphql_type() + let input_names: Vec<_> = DirectionalInputNames::command_type() .fields .into_iter() .map(|field| field.name) .collect(); assert_eq!(input_names, ["regularField", "inputID"]); - let output_names: Vec<_> = DirectionalOutputNames::graphql_type() + let output_names: Vec<_> = DirectionalOutputNames::command_type() .fields .into_iter() .map(|field| field.name) diff --git a/tests/graphql_harden/transport.rs b/tests/graphql_harden/transport.rs index 1fd758d6d..341215042 100644 --- a/tests/graphql_harden/transport.rs +++ b/tests/graphql_harden/transport.rs @@ -3,10 +3,8 @@ use std::sync::Arc; use async_graphql::Request; -use distributed::graphql::{ - graphiql_enabled_from_env_vars, read, typed_command, GraphqlEngine, ModelPermissions, - PreparedCommand, Succeeded, -}; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::graphql::{graphiql_enabled_from_env_vars, read, GraphqlEngine, ModelPermissions}; use distributed::microsvc::{router, CausalCommandContext, HandlerError, Routes, Service, Session}; use distributed::{ Aggregate, AggregateRepository, Entity, EventRecord, InMemoryRepository, ReadModel, @@ -42,13 +40,13 @@ impl Aggregate for T4Aggregate { } } -#[derive(Deserialize, distributed::GraphqlInput)] +#[derive(Deserialize, distributed::CommandInput)] struct T4CommandInput { id: String, name: String, } -#[derive(Serialize, distributed::GraphqlOutput)] +#[derive(Serialize, distributed::CommandOutput)] struct T4CommandOutput { id: String, name: String, diff --git a/tests/typed_commands/main.rs b/tests/typed_commands/main.rs index c868a0ad7..626da1b27 100644 --- a/tests/typed_commands/main.rs +++ b/tests/typed_commands/main.rs @@ -9,14 +9,16 @@ use async_graphql::futures_util::StreamExt; use async_graphql::Request; use axum::body::Body; use axum::http::Request as HttpRequest; +use distributed::command::{ + typed_command, Atomic, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, + EffectInputFieldMarker, EffectModelFieldMarker, Eventual, PreparedCommand, Succeeded, +}; use distributed::graphql::{ - build_surface, graphql_router_with_service, read, surface_for_role, typed_command, Atomic, - ClientProjectionAssignment, ClientProjectionExecutionClass, ClientProjectionExpression, - ClientProjectionFallback, ClientProjectionInvalidation, ClientProjectionMutationKind, - ClientProjectionPartition, ClientProjectionPreviewSource, ClientProjectionValue, - ClientProjectionValueType, DistributedClientSurfaceExport, EffectInputFieldMarker, - EffectModelFieldMarker, Eventual, GraphqlEngine, GraphqlInputType, GraphqlOutputType, - GraphqlTypeDef, GraphqlTypeField, ModelPermissions, PreparedCommand, RoleGrant, Succeeded, + build_surface, graphql_router_with_service, read, surface_for_role, ClientProjectionAssignment, + ClientProjectionExecutionClass, ClientProjectionExpression, ClientProjectionFallback, + ClientProjectionInvalidation, ClientProjectionMutationKind, ClientProjectionPartition, + ClientProjectionPreviewSource, ClientProjectionValue, ClientProjectionValueType, + DistributedClientSurfaceExport, GraphqlEngine, ModelPermissions, RoleGrant, SurfaceDirectProjection, SurfaceModeledProjection, SurfaceOptions, SurfaceProjector, }; use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; @@ -37,7 +39,7 @@ use distributed::{ body_bindings_for_model, body_field_binding, command_input_defaults, compile_projection, descriptor_from_factories, inventory_single_model, lower_single_model, resolve_mutation_program, state_upsert_program_for_model, Aggregate, AggregateRepository, - DomainEventDescriptor, DomainEventOccurrence, Entity, EventRecord, GraphqlInput, GraphqlOutput, + CommandInput, CommandOutput, DomainEventDescriptor, DomainEventOccurrence, Entity, EventRecord, InMemoryRepository, MutationAssignment, MutationEventBinding, MutationExpression, MutationField, MutationKeyField, MutationKind, MutationOperation, MutationProgram, MutationProgramError, ProjectionExpression, ProjectionHandler, ProjectionPartition, @@ -100,19 +102,19 @@ struct OutputB { id: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct PlanInput { id: String, title: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct RenamedDefaultInput { #[serde(rename = "todoId")] id: String, } -#[derive(Serialize, GraphqlOutput)] +#[derive(Serialize, CommandOutput)] struct PlanOutput { id: String, } @@ -134,12 +136,12 @@ enum PlanStatus { Closed, } -impl GraphqlOutputType for PlanView { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for PlanView { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "PlanView", vec![ - GraphqlTypeField { + CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -147,7 +149,7 @@ impl GraphqlOutputType for PlanView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "title".into(), type_name: "String".into(), nullable: false, @@ -155,7 +157,7 @@ impl GraphqlOutputType for PlanView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "count".into(), type_name: "BigInt".into(), nullable: false, @@ -163,7 +165,7 @@ impl GraphqlOutputType for PlanView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { name: "status".into(), type_name: "String".into(), nullable: false, @@ -177,7 +179,7 @@ impl GraphqlOutputType for PlanView { } } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct ForgedInput { id: String, title: String, @@ -190,12 +192,12 @@ struct ForgedView { count: i64, } -#[derive(Clone, Serialize, Deserialize, GraphqlInput)] +#[derive(Clone, Serialize, Deserialize, CommandInput)] struct JsonDocument { label: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct JsonPatchInput { id: String, tags: Vec, @@ -213,7 +215,7 @@ struct JsonView { details: JsonDocument, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct BigIntKeyInput { key: i64, title: String, @@ -228,7 +230,7 @@ struct BigIntKeyView { title: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct BigIntRelationshipInput { source_key: i64, target_id: String, @@ -254,7 +256,7 @@ struct BigIntRelationshipSource { targets: Vec, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct NullableKeyInput { key: Option, } @@ -267,7 +269,7 @@ struct NullableKeyView { title: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct CompositeKeyInput { tenant_id: String, id: String, @@ -286,7 +288,7 @@ struct CompositeKeyView { title: String, } -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] struct FloatEffectInput { id: String, } @@ -971,9 +973,9 @@ impl EffectInputFieldMarker for ForgedTitleMarker { type Input = ForgedInput; type Value = String; type NonNullValue = String; - type Nullability = distributed::graphql::EffectRequired; - type PathKind = distributed::graphql::EffectInputTerminalKind; - type Wire = distributed::graphql::EffectWireString; + type Nullability = distributed::command::EffectRequired; + type PathKind = distributed::command::EffectInputTerminalKind; + type Wire = distributed::command::EffectWireString; type Nested = String; fn path() -> Vec<&'static str> { @@ -987,7 +989,7 @@ impl EffectModelFieldMarker for ForgedCountMarker { type Model = ForgedView; // Deliberately lies about the independently-derived SQL/GraphQL field. type Value = String; - type Wire = distributed::graphql::EffectWireString; + type Wire = distributed::command::EffectWireString; const FIELD: &'static str = "count"; } @@ -997,9 +999,9 @@ impl EffectInputFieldMarker for ForgedDefaultMarker { type Input = PlanInput; type Value = String; type NonNullValue = String; - type Nullability = distributed::graphql::EffectRequired; - type PathKind = distributed::graphql::EffectInputTerminalKind; - type Wire = distributed::graphql::EffectWireString; + type Nullability = distributed::command::EffectRequired; + type PathKind = distributed::command::EffectInputTerminalKind; + type Wire = distributed::command::EffectWireString; type Nested = String; fn path() -> Vec<&'static str> { @@ -1007,10 +1009,10 @@ impl EffectInputFieldMarker for ForgedDefaultMarker { } } -fn object_type(name: &str) -> GraphqlTypeDef { - GraphqlTypeDef::new( +fn object_type(name: &str) -> CommandTypeDef { + CommandTypeDef::new( name, - vec![GraphqlTypeField { + vec![CommandTypeField { name: "id".into(), type_name: "String".into(), nullable: false, @@ -1022,26 +1024,26 @@ fn object_type(name: &str) -> GraphqlTypeDef { .with_type_id(TypeId::of::()) } -impl GraphqlInputType for InputA { - fn graphql_type() -> GraphqlTypeDef { +impl CommandInputType for InputA { + fn command_type() -> CommandTypeDef { object_type::("CommandInput") } } -impl GraphqlOutputType for OutputA { - fn graphql_type() -> GraphqlTypeDef { +impl CommandOutputType for OutputA { + fn command_type() -> CommandTypeDef { object_type::("CommandOutput") } } -impl GraphqlInputType for InputB { - fn graphql_type() -> GraphqlTypeDef { +impl CommandInputType for InputB { + fn command_type() -> CommandTypeDef { object_type::("CommandInput") } } -impl GraphqlOutputType for OutputB { - fn graphql_type() -> GraphqlTypeDef { +impl CommandOutputType for OutputB { + fn command_type() -> CommandTypeDef { object_type::("CommandOutput") } } @@ -1216,16 +1218,16 @@ fn direct_plan_projection() -> SurfaceDirectProjection { .change_epoch("plan-direct-v1") } -fn plan_input_defaults() -> distributed::graphql::CompiledInputDefaults { +fn plan_input_defaults() -> distributed::command::CompiledInputDefaults { command_input_defaults! { input: PlanInput; default input.id = uuid_v7(); } } -fn forged_input_defaults() -> distributed::graphql::CompiledInputDefaults { - distributed::graphql::__command_input_defaults::([ - distributed::graphql::__input_default_uuid_v7::(), +fn forged_input_defaults() -> distributed::command::CompiledInputDefaults { + distributed::command::__command_input_defaults::([ + distributed::command::__input_default_uuid_v7::(), ]) } From fff00d13f0b9e625519c408a284364ed34c0cfd1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 18:02:09 -0500 Subject: [PATCH 017/484] test: restore duplicate-command diagnostic source span Keep the full rust-src diagnostic used in CI; document the regeneration prerequisite. All 35 compile-fail fixtures pass with rust-src installed. Refs: tasks/distributed-v5-pr-stack --- distributed_macros/tests/compile_fail.rs | 2 ++ .../tests/compile_fail/application_command_duplicate_id.stderr | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/distributed_macros/tests/compile_fail.rs b/distributed_macros/tests/compile_fail.rs index ea5111b5a..a585d2a7a 100644 --- a/distributed_macros/tests/compile_fail.rs +++ b/distributed_macros/tests/compile_fail.rs @@ -5,6 +5,8 @@ //! regressions in diagnostic quality are caught. //! //! Regenerate `.stderr` snapshots with: +//! `rustup component add rust-src` (keeps standard-library source spans aligned +//! with CI), then: //! `TRYBUILD=overwrite cargo test -p distributed_macros` #[test] diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr index ed8715148..5377eae50 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr @@ -12,7 +12,8 @@ error[E0080]: evaluation panicked: duplicate command identity in module declarat note: inside `assert_unique_command_ids` --> $RUST/core/src/panic.rs | - = note: the failure occurred here + | $crate::panicking::panic_fmt($crate::const_format_args!($($t)+)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here | ::: $WORKSPACE/src/application/mod.rs | From e99e666cf4c3d2a590d9b3fae4093b2ce69ffe24 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 03:42:59 -0500 Subject: [PATCH 018/484] refactor: share SQL event and ledger operations across runtimes WIP foundation for cell-local SQLite persistence. Native SQLx repositories use the shared event append, snapshot, tail-load, and fenced command-ledger operations. Add a synchronous Worker SQL execution boundary without switching aggregate cells to it yet. Validation: 787 SQLite-feature library tests; 21 repository conformance tests; 4 snapshot hardening tests; SQLite/PostgreSQL compilation; celld Worker wasm compilation. Pending: cell repository wiring, row-based outbox drain, migration and live restart/crash coverage. --- src/microsvc/cell_host/mod.rs | 2 + src/microsvc/cell_host/sql_executor.rs | 258 ++++++++ src/repository/mod.rs | 4 +- src/repository/sql.rs | 457 ++++++++++++++ src/repository/sql/ledger.rs | 408 +++++++++++++ src/repository/sqlite_codec.rs | 76 +++ src/sqlite_repo/mod.rs | 51 +- src/sqlx_repo/repo/backend.rs | 3 - src/sqlx_repo/repo/commit.rs | 799 ++++--------------------- src/sqlx_repo/repo/events.rs | 48 +- src/sqlx_repo/repo/executor.rs | 134 +++++ src/sqlx_repo/repo/mod.rs | 20 +- src/sqlx_repo/repo/snapshots.rs | 151 +---- src/sqlx_repo/repo/streams.rs | 94 +-- 14 files changed, 1512 insertions(+), 993 deletions(-) create mode 100644 src/microsvc/cell_host/sql_executor.rs create mode 100644 src/repository/sql.rs create mode 100644 src/repository/sql/ledger.rs create mode 100644 src/repository/sqlite_codec.rs create mode 100644 src/sqlx_repo/repo/executor.rs diff --git a/src/microsvc/cell_host/mod.rs b/src/microsvc/cell_host/mod.rs index f906f3186..537abd243 100644 --- a/src/microsvc/cell_host/mod.rs +++ b/src/microsvc/cell_host/mod.rs @@ -20,6 +20,8 @@ mod celld_outbox; #[cfg(feature = "graphql")] mod command; mod internal_auth; +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +mod sql_executor; mod store; mod wire; diff --git a/src/microsvc/cell_host/sql_executor.rs b/src/microsvc/cell_host/sql_executor.rs new file mode 100644 index 000000000..18d374614 --- /dev/null +++ b/src/microsvc/cell_host/sql_executor.rs @@ -0,0 +1,258 @@ +//! Durable Object execution of the shared SQL repository operations. +//! +//! No event serialization, replay, or snapshot policy lives in this adapter. +//! The callback is synchronous and bounded by storage.transactionSync, so a +//! commit cannot yield between its domain and delivery/receipt participants. + +use std::collections::HashMap; +use std::future::Future; +use std::task::{Context, Poll, Waker}; +use std::time::SystemTime; + +use worker::js_sys::{Function, Reflect}; +use worker::send::SendWrapper; +use worker::wasm_bindgen::{closure::ScopedClosure, JsCast, JsValue}; +use worker::{SqlStorage, SqlStorageValue, State}; + +use crate::repository::sql::{SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; +use crate::repository::{sqlite_codec, RepositoryError}; + +#[derive(Clone)] +pub(crate) struct CellSqlConnection { + sql: SqlStorage, + storage: SendWrapper, + transaction_sync: SendWrapper, +} + +impl CellSqlConnection { + /// Takes the runtime-owned state, not a caller-supplied database URL. + pub fn from_state(state: State) -> Result { + let sql = state.storage().sql(); + let storage: JsValue = state._inner().storage().map_err(js_error)?.into(); + let transaction_sync = Reflect::get(&storage, &JsValue::from_str("transactionSync")) + .map_err(js_error)? + .dyn_into::() + .map_err(|_| { + RepositoryError::Model("cell storage.transactionSync is required".into()) + })?; + Ok(Self { + sql, + storage: SendWrapper::new(storage), + transaction_sync: SendWrapper::new(transaction_sync), + }) + } + + pub fn executor(&self) -> CellSqlExecutor { + CellSqlExecutor(self.sql.clone()) + } + + pub fn transaction>( + &self, + operation: impl FnOnce(&mut CellSqlExecutor) -> Result, + ) -> Result { + let mut operation = Some(operation); + let mut result = None; + let mut callback = || -> Result<(), JsValue> { + let Some(operation) = operation.take() else { + return Err(JsValue::from_str("cell transaction callback invoked twice")); + }; + result = Some(operation(&mut self.executor())); + match result.as_ref() { + Some(Ok(_)) => Ok(()), + _ => Err(JsValue::from_str("cell SQL transaction failed")), + } + }; + // Any Rust error is thrown through the JS callback, causing rollback. + // Nothing outside this callback is marked committed before call1 returns. + let closure = + ScopedClosure:: Result<(), JsValue>>::borrow_mut_assert_unwind_safe( + &mut callback, + ); + let committed = self.transaction_sync.call1(&self.storage, closure.as_ref()); + drop(closure); + match (committed, result) { + (_, Some(Err(error))) => Err(error), + (Err(error), _) => Err(js_error(error).into()), + (Ok(_), Some(Ok(value))) => Ok(value), + (Ok(_), None) => { + Err(RepositoryError::Model("cell transaction callback did not run".into()).into()) + } + } + } +} + +/// Shared SQL operations are async for SQLx, but every call through the cell +/// executor completes synchronously. Refuse accidental async work; never spin +/// or let a pending future outlive the transaction callback. +pub(crate) fn finish_sql>( + future: impl Future>, +) -> Result { + let mut future = std::pin::pin!(future); + match future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + Poll::Ready(result) => result, + Poll::Pending => Err(RepositoryError::Model( + "cell SQL transaction attempted to await asynchronous work".into(), + ) + .into()), + } +} + +#[derive(Clone)] +pub(crate) struct CellSqlExecutor(SqlStorage); +pub(crate) struct CellSqlRow(HashMap); + +impl CellSqlRow { + fn value(&self, column: &str) -> Result<&SqlStorageValue, RepositoryError> { + self.0 + .get(column) + .ok_or_else(|| RepositoryError::Model(format!("cell SQL row is missing {column}"))) + } + fn invalid(column: &str) -> RepositoryError { + RepositoryError::Model(format!( + "cell SQL column {column} has the wrong storage type" + )) + } +} + +impl SqlRow for CellSqlRow { + fn text(&self, column: &'static str) -> Result { + match self.value(column)? { + SqlStorageValue::String(value) => Ok(value.clone()), + _ => Err(Self::invalid(column)), + } + } + fn integer(&self, column: &'static str) -> Result { + match self.value(column)? { + SqlStorageValue::Integer(value) => Ok(*value), + _ => Err(Self::invalid(column)), + } + } + fn optional_text(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + SqlStorageValue::Null => Ok(None), + _ => self.text(column).map(Some), + } + } + fn optional_timestamp( + &self, + column: &'static str, + ) -> Result, RepositoryError> { + match self.value(column)? { + SqlStorageValue::Null => Ok(None), + _ => self.timestamp(column).map(Some), + } + } + fn optional_integer(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + SqlStorageValue::Null => Ok(None), + _ => self.integer(column).map(Some), + } + } + fn bytes(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + SqlStorageValue::Blob(value) => Ok(value.clone()), + _ => Err(Self::invalid(column)), + } + } + fn timestamp(&self, column: &'static str) -> Result { + match self.value(column)? { + SqlStorageValue::String(value) => sqlite_codec::decode(value), + SqlStorageValue::Float(value) => sqlite_codec::decode_epoch(*value), + SqlStorageValue::Integer(value) => sqlite_codec::decode_epoch(*value as f64), + _ => Err(Self::invalid(column)), + } + } +} + +impl CellSqlExecutor { + fn run(&self, statement: Statement<'_>) -> Result { + let mut sql = String::new(); + let mut bindings = Vec::new(); + for part in statement.0 { + match part { + SqlPart::LedgerNow | SqlPart::LedgerNowEpoch => { + sql.push_str("unixepoch('now','subsec')") + } + SqlPart::LedgerDeadline(duration) => { + sql.push_str("(unixepoch('now','subsec') + ?)"); + bindings.push(SqlStorageValue::Float(duration.as_secs_f64())); + } + SqlPart::LedgerDeadlineIsLive(deadline) => { + sql.push_str("CAST(? AS REAL) > unixepoch('now','subsec')"); + bindings.push(SqlStorageValue::String(sqlite_codec::encode(deadline)?)); + } + SqlPart::LedgerJson(json) => { + sql.push('?'); + bindings.push(SqlStorageValue::String(json)); + } + SqlPart::Sql(text) => sql.push_str(&text), + SqlPart::Bind(value) => { + sql.push('?'); + bindings.push(match value { + SqlBind::Text(value) | SqlBind::Metadata(value) => { + SqlStorageValue::String(value) + } + SqlBind::Bytes(value) => SqlStorageValue::Blob(value.into_owned()), + // Reject values outside JS's exact range, never round a + // sequence/fence silently while crossing the binding. + SqlBind::Integer(value) => { + SqlStorageValue::try_from_i64(value).map_err(|error| { + RepositoryError::Model(format!( + "cell SQL integer is not exactly representable: {error}" + )) + })? + } + SqlBind::Timestamp(value) => { + SqlStorageValue::String(sqlite_codec::encode(value)?) + } + }); + } + } + } + self.0.exec(&sql, Some(bindings)).map_err(worker_error) + } +} + +impl SqlExecutor for CellSqlExecutor { + type Row = CellSqlRow; + const EVENT_SELECT: &'static str = sqlite_codec::EVENT_SELECT; + const SNAPSHOT_SELECT: &'static str = sqlite_codec::SNAPSHOT_SELECT; + const NOW: &'static str = "CURRENT_TIMESTAMP"; + const COMMAND_LEDGER_SELECT: &'static str = sqlite_codec::COMMAND_LEDGER_SELECT; + const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = ""; + const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = ""; + + async fn query(&mut self, statement: Statement<'_>) -> Result, RepositoryError> { + let cursor = self.run(statement)?; + let names = cursor.column_names(); + cursor + .raw() + .map(|row| { + let values = row.map_err(worker_error)?; + if values.len() != names.len() { + return Err(RepositoryError::Model( + "cell SQL row width differs from its columns".into(), + )); + } + Ok(CellSqlRow(names.iter().cloned().zip(values).collect())) + }) + .collect() + } + + async fn execute(&mut self, statement: Statement<'_>) -> Result { + Ok(self.run(statement)?.rows_written() as u64) + } +} + +fn js_error(error: JsValue) -> RepositoryError { + worker_error(worker::Error::from(error)) +} +fn worker_error(error: worker::Error) -> RepositoryError { + // The SDK does not expose structured SQLite error codes. Unknown runtime + // failures must not permanently discard a command or pending delivery. + // Deterministic binding/row validation errors are classified above instead. + RepositoryError::retryable_storage("cell SQL", error) +} diff --git a/src/repository/mod.rs b/src/repository/mod.rs index 7ed5d177d..34477f906 100644 --- a/src/repository/mod.rs +++ b/src/repository/mod.rs @@ -1,6 +1,8 @@ mod error; mod identity; mod inbox; +pub(crate) mod sql; +pub(crate) mod sqlite_codec; mod traits; mod validation; @@ -12,6 +14,4 @@ pub use traits::{ RelationalReadModelQueryStore, Repository, SnapshotStore, SnapshotWrite, StreamWrite, TransactionalCommit, }; -#[cfg(any(feature = "postgres", feature = "sqlite"))] -pub(crate) use validation::validate_supported_event_codec; pub(crate) use validation::{validate_commit_batch, validate_snapshot_identity}; diff --git a/src/repository/sql.rs b/src/repository/sql.rs new file mode 100644 index 000000000..391628ae7 --- /dev/null +++ b/src/repository/sql.rs @@ -0,0 +1,457 @@ +//! SQL event-store operations independent of the connection runtime. +//! +//! SQLx and Durable Object SQL execute the same statements and decode the same +//! event/snapshot records. Only binding, row access, and transaction ownership +//! belong to the execution adapter. This module never opens a transaction: a +//! command's events, snapshots, ledger, and outbox must use the caller's one +//! transaction, not an independent transaction per participant. + +use std::borrow::Cow; +use std::future::Future; +use std::time::{Duration, SystemTime}; + +pub(crate) mod ledger; + +use crate::entity::{Entity, EventRecord, BITCODE_PAYLOAD_CODEC}; +use crate::snapshot::SnapshotRecord; + +use super::{validate_snapshot_identity, PreparedEventAppend, RepositoryError, StreamIdentity}; + +#[derive(Clone, Debug)] +pub(crate) enum SqlBind<'a> { + Text(String), + Integer(i64), + Bytes(Cow<'a, [u8]>), + Metadata(String), + Timestamp(SystemTime), +} + +impl From<&str> for SqlBind<'_> { + fn from(value: &str) -> Self { + Self::Text(value.into()) + } +} +impl From for SqlBind<'_> { + fn from(value: i64) -> Self { + Self::Integer(value) + } +} +impl<'a> From<&'a [u8]> for SqlBind<'a> { + fn from(value: &'a [u8]) -> Self { + Self::Bytes(Cow::Borrowed(value)) + } +} + +#[derive(Clone, Debug)] +pub(crate) enum SqlPart<'a> { + Sql(String), + Bind(SqlBind<'a>), + LedgerNow, + LedgerNowEpoch, + LedgerDeadline(Duration), + LedgerDeadlineIsLive(SystemTime), + LedgerJson(String), +} + +/// Structural statements: values are never interpolated into SQL text. The +/// executor renders placeholders for its dialect; it never splits SQL on `?`. +#[derive(Clone, Debug)] +pub(crate) struct Statement<'a>(pub Vec>); + +impl<'a> Statement<'a> { + pub fn push(&mut self, sql: impl Into) { + self.0.push(SqlPart::Sql(sql.into())); + } + + pub fn push_bind(&mut self, value: impl Into>) { + self.0.push(SqlPart::Bind(value.into())); + } + + pub fn part(&mut self, part: SqlPart<'a>) { + self.0.push(part); + } + pub fn new(sql: impl Into) -> Self { + Self(vec![SqlPart::Sql(sql.into())]) + } + + pub fn sql(mut self, sql: impl Into) -> Self { + self.0.push(SqlPart::Sql(sql.into())); + self + } + + pub fn bind(mut self, value: SqlBind<'a>) -> Self { + self.0.push(SqlPart::Bind(value)); + self + } + + fn identity(self, identity: &StreamIdentity) -> Self { + self.bind(SqlBind::Text(identity.aggregate_type().into())) + .sql(" AND aggregate_id = ") + .bind(SqlBind::Text(identity.aggregate_id().into())) + } +} + +pub(crate) trait SqlRow: Send { + fn text(&self, column: &'static str) -> Result; + fn optional_text(&self, column: &'static str) -> Result, RepositoryError>; + fn integer(&self, column: &'static str) -> Result; + fn optional_integer(&self, column: &'static str) -> Result, RepositoryError>; + fn bytes(&self, column: &'static str) -> Result, RepositoryError>; + fn timestamp(&self, column: &'static str) -> Result; + fn optional_timestamp( + &self, + column: &'static str, + ) -> Result, RepositoryError>; +} + +pub(crate) trait SqlExecutor: Send { + type Row: SqlRow; + const EVENT_SELECT: &'static str; + const SNAPSHOT_SELECT: &'static str; + const NOW: &'static str; + const COMMAND_LEDGER_SELECT: &'static str; + const COMMAND_LEDGER_LOCK_SUFFIX: &'static str; + const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str; + + fn query( + &mut self, + statement: Statement<'_>, + ) -> impl Future, RepositoryError>> + Send; + fn execute( + &mut self, + statement: Statement<'_>, + ) -> impl Future> + Send; +} + +pub(crate) struct EventInsert<'a> { + pub statement: Statement<'a>, + pub candidates: Vec<(StreamIdentity, u64)>, +} + +/// Prepare only new events, preserving the existing ten-column schema and +/// bound-parameter chunking. Conflict candidates are scoped to each statement: +/// earlier chunks in the same transaction must not skew conflict diagnostics. +pub(crate) fn event_inserts<'a>( + appends: &[PreparedEventAppend<'a>], + max_bind_params: usize, +) -> Result>, RepositoryError> { + const COLUMNS: usize = 10; + if max_bind_params < COLUMNS { + return Err(RepositoryError::Model( + "SQL executor cannot bind one event row".into(), + )); + } + let mut inserts = Vec::new(); + let mut current: Option> = None; + let mut count = 0; + for append in appends { + for event in append.events { + let insert = current.get_or_insert_with(|| EventInsert { + statement: Statement::new("INSERT INTO aggregate_events (aggregate_type, aggregate_id, sequence, event_name, event_version, payload, payload_codec, payload_codec_version, metadata, recorded_at) VALUES "), + candidates: Vec::new(), + }); + if count != 0 { + insert.statement.0.push(SqlPart::Sql(", ".into())); + } + insert.statement.0.push(SqlPart::Sql("(".into())); + let values = [ + SqlBind::Text(append.identity.aggregate_type().into()), + SqlBind::Text(append.identity.aggregate_id().into()), + SqlBind::Integer(signed(event.sequence, "sequence")?), + SqlBind::Text(event.event_name.clone()), + SqlBind::Integer(signed(event.event_version, "event version")?), + SqlBind::Bytes(Cow::Borrowed(&event.payload)), + SqlBind::Text(event.payload_codec.to_string()), + SqlBind::Integer(i64::from(event.payload_codec_version)), + SqlBind::Metadata(serde_json::to_string(&event.metadata).map_err(json_error)?), + SqlBind::Timestamp(event.timestamp), + ]; + for (index, value) in values.into_iter().enumerate() { + if index != 0 { + insert.statement.0.push(SqlPart::Sql(", ".into())); + } + insert.statement.0.push(SqlPart::Bind(value)); + } + insert.statement.0.push(SqlPart::Sql(")".into())); + if !insert + .candidates + .iter() + .any(|(id, _)| id == &append.identity) + { + insert + .candidates + .push((append.identity.clone(), append.expected_version)); + } + count += 1; + if count == max_bind_params / COLUMNS { + inserts.push(current.take().expect("event insert initialized")); + count = 0; + } + } + } + if let Some(insert) = current { + inserts.push(insert); + } + Ok(inserts) +} + +fn signed(value: u64, field: &str) -> Result { + i64::try_from(value) + .map_err(|_| RepositoryError::Model(format!("{field} exceeds SQL signed integer storage"))) +} + +fn unsigned(value: i64, field: &str) -> Result { + u64::try_from(value).map_err(|_| RepositoryError::Model(format!("stored {field} is negative"))) +} + +fn codec_version(value: i64) -> Result { + u16::try_from(value) + .map_err(|_| RepositoryError::Model("stored payload codec version is invalid".into())) +} + +fn json_error(error: serde_json::Error) -> RepositoryError { + RepositoryError::Model(format!("SQL metadata: {error}")) +} + +pub(crate) fn event_from_row(row: &impl SqlRow) -> Result { + let codec = row.text("payload_codec")?; + let event = EventRecord { + event_name: row.text("event_name")?, + event_version: unsigned(row.integer("event_version")?, "event version")?, + sequence: unsigned(row.integer("sequence")?, "event sequence")?, + payload: row.bytes("payload")?, + payload_codec: if codec == BITCODE_PAYLOAD_CODEC { + Cow::Borrowed(BITCODE_PAYLOAD_CODEC) + } else { + Cow::Owned(codec) + }, + payload_codec_version: codec_version(row.integer("payload_codec_version")?)?, + metadata: serde_json::from_str(&row.text("metadata")?).map_err(json_error)?, + timestamp: row.timestamp("recorded_at")?, + }; + super::validation::validate_supported_event_codec(&event)?; + Ok(event) +} + +pub(crate) fn snapshot_from_row(row: &impl SqlRow) -> Result { + Ok(SnapshotRecord { + aggregate_type: row.text("aggregate_type")?, + aggregate_id: row.text("aggregate_id")?, + version: unsigned(row.integer("version")?, "snapshot version")?, + snapshot_version: unsigned(row.integer("snapshot_version")?, "snapshot payload version")?, + payload: row.bytes("payload")?, + payload_codec: row.text("payload_codec")?, + payload_codec_version: codec_version(row.integer("payload_codec_version")?)?, + metadata: serde_json::from_str(&row.text("metadata")?).map_err(json_error)?, + recorded_at: row.timestamp("recorded_at")?, + }) +} + +pub(crate) async fn stream_version( + executor: &mut impl SqlExecutor, + identity: &StreamIdentity, +) -> Result { + let rows = executor + .query( + Statement::new( + "SELECT MAX(sequence) AS version FROM aggregate_events WHERE aggregate_type = ", + ) + .identity(identity), + ) + .await?; + let row = rows + .first() + .ok_or_else(|| RepositoryError::Model("missing stream version row".into()))?; + unsigned( + row.optional_integer("version")?.unwrap_or(0), + "event sequence", + ) +} + +pub(crate) async fn load_stream( + executor: &mut E, + identity: &StreamIdentity, + after_version: Option, +) -> Result, RepositoryError> { + let mut statement = Statement::new("SELECT ") + .sql(E::EVENT_SELECT) + .sql(" FROM aggregate_events WHERE aggregate_type = ") + .identity(identity); + if let Some(after) = after_version { + statement = statement + .sql(" AND sequence > ") + .bind(SqlBind::Integer(signed( + after, + "snapshot tail lower bound", + )?)); + } + let rows = executor + .query(statement.sql(" ORDER BY sequence ASC")) + .await?; + let events = rows + .iter() + .map(event_from_row) + .collect::, _>>()?; + let mut entity = Entity::with_id(identity.aggregate_id()); + match after_version { + None if events.is_empty() => return Ok(None), + None => entity.load_from_history(events), + Some(after) => { + // Keep the existing SQL snapshot-only restore contract. A future + // snapshot above a non-empty durable stream is clamped, not trusted. + let prefix = if events.is_empty() { + match stream_version(executor, identity).await? { + 0 => after, + version => after.min(version), + } + } else { + after + }; + entity.load_tail_from_history(events, prefix); + } + } + Ok(Some(entity)) +} + +pub(crate) async fn load_snapshot( + executor: &mut E, + identity: &StreamIdentity, +) -> Result, RepositoryError> { + let rows = executor + .query( + Statement::new("SELECT ") + .sql(E::SNAPSHOT_SELECT) + .sql(" FROM aggregate_snapshots WHERE aggregate_type = ") + .identity(identity), + ) + .await?; + rows.first().map(snapshot_from_row).transpose() +} + +/// The same upsert is used by standalone cache writes and command commits. +pub(crate) async fn save_snapshot( + executor: &mut E, + identity: &StreamIdentity, + record: &SnapshotRecord, +) -> Result<(), RepositoryError> { + validate_snapshot_identity(identity, record)?; + let values = [ + SqlBind::Text(identity.aggregate_type().into()), + SqlBind::Text(identity.aggregate_id().into()), + SqlBind::Integer(signed(record.version, "snapshot version")?), + SqlBind::Integer(signed(record.snapshot_version, "snapshot payload version")?), + SqlBind::Bytes(Cow::Borrowed(&record.payload)), + SqlBind::Text(record.payload_codec.clone()), + SqlBind::Integer(i64::from(record.payload_codec_version)), + SqlBind::Metadata(serde_json::to_string(&record.metadata).map_err(json_error)?), + SqlBind::Timestamp(record.recorded_at), + ]; + let mut statement = Statement::new("INSERT INTO aggregate_snapshots (aggregate_type, aggregate_id, version, snapshot_version, payload, payload_codec, payload_codec_version, metadata, recorded_at) VALUES ("); + for (index, value) in values.into_iter().enumerate() { + if index != 0 { + statement = statement.sql(", "); + } + statement = statement.bind(value); + } + executor.execute(statement.sql(") ON CONFLICT(aggregate_type, aggregate_id) DO UPDATE SET version = excluded.version, snapshot_version = excluded.snapshot_version, payload = excluded.payload, payload_codec = excluded.payload_codec, payload_codec_version = excluded.payload_codec_version, metadata = excluded.metadata, recorded_at = excluded.recorded_at, updated_at = ").sql(E::NOW)).await?; + Ok(()) +} + +pub(crate) async fn delete_snapshot( + executor: &mut impl SqlExecutor, + identity: &StreamIdentity, +) -> Result { + Ok(executor + .execute( + Statement::new("DELETE FROM aggregate_snapshots WHERE aggregate_type = ") + .identity(identity), + ) + .await? + > 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn event_plan_borrows_only_new_payloads_and_respects_bind_limit() { + let mut entity = Entity::with_id("large-history"); + for _ in 0..1000 { + entity.digest("created", &vec![7_u8; 4096]).unwrap(); + } + entity.mark_committed(); + for _ in 0..3 { + entity.digest("changed", &vec![9_u8; 4096]).unwrap(); + } + let identity = StreamIdentity::new("Item", "large-history").unwrap(); + let append = PreparedEventAppend { + identity: identity.clone(), + expected_version: 1000, + events: entity.new_events(), + }; + let plans = event_inserts(&[append], 20).unwrap(); + assert_eq!(plans.len(), 2); + assert_eq!( + plans[0] + .statement + .0 + .iter() + .filter(|part| matches!(part, SqlPart::Bind(_))) + .count(), + 20 + ); + assert_eq!( + plans[1] + .statement + .0 + .iter() + .filter(|part| matches!(part, SqlPart::Bind(_))) + .count(), + 10 + ); + let payloads = plans + .iter() + .flat_map(|plan| &plan.statement.0) + .filter_map(|part| match part { + SqlPart::Bind(SqlBind::Bytes(Cow::Borrowed(bytes))) => Some(*bytes), + SqlPart::Bind(SqlBind::Bytes(Cow::Owned(_))) => { + panic!("event plan cloned a payload") + } + _ => None, + }) + .collect::>(); + assert_eq!( + payloads.len(), + 3, + "old history must not enter the insert plan" + ); + for (payload, event) in payloads.iter().zip(entity.new_events()) { + assert_eq!(payload.as_ptr(), event.payload.as_ptr()); + } + for plan in plans { + assert_eq!(plan.candidates, vec![(identity.clone(), 1000)]); + } + } + + #[test] + fn event_plan_rejects_unrepresentable_sequence_and_too_few_binds() { + let mut entity = Entity::with_id("one"); + entity.digest_empty("created").unwrap(); + let mut events = entity.new_events().to_vec(); + let identity = StreamIdentity::new("Item", "one").unwrap(); + let append = PreparedEventAppend { + identity: identity.clone(), + expected_version: 0, + events: &events, + }; + assert!(event_inserts(&[append], 9).is_err()); + events[0].sequence = u64::MAX; + let append = PreparedEventAppend { + identity, + expected_version: 0, + events: &events, + }; + assert!(event_inserts(&[append], 900).is_err()); + } +} diff --git a/src/repository/sql/ledger.rs b/src/repository/sql/ledger.rs new file mode 100644 index 000000000..2e1ed41bd --- /dev/null +++ b/src/repository/sql/ledger.rs @@ -0,0 +1,408 @@ +//! Shared fenced command-ledger operations. The caller owns the transaction. +//! Both SQLx and cell SQL use these statements and the same record state machine. +use super::{signed, unsigned, SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; +use crate::command_ledger::{ + AttemptFence, AttemptToken, CanonicalInputHash, CausationId, CommandCompletion, + CommandContractFingerprint, CommandId, CommandLedgerError, CommandLedgerKey, + CommandLedgerRecord, CommandLedgerState, CommandLookup, CommandLookupScope, CommandReservation, + PrincipalPartitionId, ReservationDecision, ReservationOutcome, +}; +use std::time::SystemTime; + +fn corrupt(error: CommandLedgerError) -> CommandLedgerError { + CommandLedgerError::Corrupt(error.to_string()) +} + +pub(crate) fn key_from_row(row: &impl SqlRow) -> Result { + CommandLedgerKey::new( + row.text("service_id")?, + PrincipalPartitionId::new(row.text("principal_partition")?).map_err(corrupt)?, + CommandId::parse(row.text("command_id")?).map_err(corrupt)?, + ) + .map_err(corrupt) +} + +fn record_from_row( + row: &impl SqlRow, + key: CommandLedgerKey, +) -> Result { + let record = CommandLedgerRecord { + key, + command_name: row.text("command_name")?, + contract_fingerprint: CommandContractFingerprint::try_from_slice( + &row.bytes("command_contract_hash")?, + ) + .map_err(corrupt)?, + input_hash: CanonicalInputHash::try_from_slice(&row.bytes("input_hash")?) + .map_err(corrupt)?, + state: CommandLedgerState::parse(&row.text("state")?)?, + causation_id: CausationId::parse_stored(row.text("causation_id")?)?, + attempt_token: row + .optional_text("attempt_token")? + .map(AttemptToken::parse_stored) + .transpose()?, + attempt_number: unsigned( + row.integer("attempt_number")?, + "command ledger attempt number", + )?, + lease_expires_at: row.optional_timestamp("lease_expires_at")?, + outcome_json: row.optional_text("outcome")?, + created_at: row.timestamp("created_at")?, + updated_at: row.timestamp("updated_at")?, + completed_at: row.optional_timestamp("completed_at")?, + retention_expires_at: row.timestamp("retention_expires_at")?, + compacted_at: row.optional_timestamp("compacted_at")?, + }; + record.validate_stored_shape()?; + Ok(record) +} + +pub(crate) async fn now(executor: &mut impl SqlExecutor) -> Result { + let mut statement = Statement::new("SELECT "); + statement.part(SqlPart::LedgerNowEpoch); + statement.push(" AS ledger_now"); + let rows = executor.query(statement).await?; + let row = rows + .first() + .ok_or_else(|| CommandLedgerError::Corrupt("database clock returned no row".into()))?; + Ok(row.timestamp("ledger_now")?) +} + +fn key_filter<'a>(mut statement: Statement<'a>, key: &CommandLedgerKey) -> Statement<'a> { + statement.push_bind(key.service_id()); + statement.push(" AND principal_partition = "); + statement.push_bind(key.principal_partition()); + statement.push(" AND command_id = "); + statement.push_bind(key.command_id()); + statement +} + +async fn select( + executor: &mut E, + key: &CommandLedgerKey, + expected_command_name: Option<&str>, +) -> Result, CommandLedgerError> { + let mut statement = Statement::new("SELECT "); + statement.push(E::COMMAND_LEDGER_SELECT); + statement.push(" FROM command_ledger WHERE service_id = "); + statement = key_filter(statement, key); + if let Some(name) = expected_command_name { + statement.push(" AND command_name = "); + statement.push_bind(name); + } + statement.push(E::COMMAND_LEDGER_LOCK_SUFFIX); + let rows = executor.query(statement).await?; + rows.first() + .map(|row| record_from_row(row, key.clone())) + .transpose() +} + +pub(crate) async fn preflight( + executor: &mut E, + completion: &CommandCompletion, +) -> Result<(), CommandLedgerError> { + let fence = completion.attempt_fence(); + + // SQLite needs a write statement to reserve the database writer before + // the read; PostgreSQL's subsequent SELECT also carries FOR UPDATE. This + // establishes one portable lock order before any domain participant is + // mutated. + let mut lock = + Statement::new("UPDATE command_ledger SET updated_at = updated_at WHERE service_id = "); + lock.push_bind(fence.key().service_id()); + lock.push(" AND principal_partition = "); + lock.push_bind(fence.key().principal_partition()); + lock.push(" AND command_id = "); + lock.push_bind(fence.key().command_id()); + let result = executor.execute(lock).await?; + if result != 1 { + return Err(CommandLedgerError::AttemptFenced { + command_id: fence.key().command_id().to_string(), + }); + } + + let record = select(executor, fence.key(), None).await?.ok_or_else(|| { + CommandLedgerError::AttemptFenced { + command_id: fence.key().command_id().to_string(), + } + })?; + let now = now(executor).await?; + record.validate_live_attempt(&fence, now) +} + +pub(crate) async fn insert_reservation( + executor: &mut E, + reservation: &CommandReservation, +) -> Result { + let mut builder = Statement::new( + "INSERT INTO command_ledger (service_id, principal_partition, command_id, \ + command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, \ + attempt_number, lease_expires_at, outcome, created_at, updated_at, completed_at, \ + retention_expires_at, compacted_at) VALUES (", + ); + builder.push_bind(reservation.key().service_id()); + builder.push(", "); + builder.push_bind(reservation.key().principal_partition()); + builder.push(", "); + builder.push_bind(reservation.key().command_id()); + builder.push(", "); + builder.push_bind(reservation.command_name()); + builder.push(", "); + builder.push_bind(reservation.contract_fingerprint_bytes().as_slice()); + builder.push(", "); + builder.push_bind(reservation.input_hash_bytes().as_slice()); + builder.push(", "); + builder.push_bind(CommandLedgerState::InProgress.as_str()); + builder.push(", "); + builder.push_bind(reservation.candidate_causation().as_str()); + builder.push(", "); + builder.push_bind(reservation.candidate_attempt().as_str()); + builder.push(", "); + builder.push_bind(1_i64); + builder.push(", "); + builder.part(SqlPart::LedgerDeadline(reservation.lease())); + builder.push(", NULL, "); + builder.part(SqlPart::LedgerNow); + builder.push(", "); + builder.part(SqlPart::LedgerNow); + builder.push(", NULL, "); + builder.part(SqlPart::LedgerDeadline(reservation.retention())); + builder.push(", NULL"); + builder.push(") ON CONFLICT (service_id, principal_partition, command_id) DO NOTHING"); + let result = executor.execute(builder).await?; + Ok(result == 1) +} + +pub(crate) async fn expire( + executor: &mut E, + key: &CommandLedgerKey, + require_retention_due: bool, +) -> Result { + let mut builder = Statement::new( + "UPDATE command_ledger SET state = 'expired', attempt_token = NULL, \ + lease_expires_at = NULL, outcome = NULL, updated_at = ", + ); + builder.part(SqlPart::LedgerNow); + builder.push(", compacted_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(" WHERE service_id = "); + builder.push_bind(key.service_id()); + builder.push(" AND principal_partition = "); + builder.push_bind(key.principal_partition()); + builder.push(" AND command_id = "); + builder.push_bind(key.command_id()); + builder.push(" AND state <> 'expired'"); + if require_retention_due { + builder.push(" AND retention_expires_at <= "); + builder.part(SqlPart::LedgerNow); + } + let result = executor.execute(builder).await?; + Ok(result) +} + +pub(crate) async fn reclaim( + executor: &mut E, + record: &mut CommandLedgerRecord, + reservation: &CommandReservation, + now: SystemTime, +) -> Result<(), CommandLedgerError> { + record.reclaim(reservation, now)?; + let attempt_number = signed(record.attempt_number, "command ledger attempt number")?; + let mut builder = + Statement::new("UPDATE command_ledger SET state = 'in_progress', attempt_token = "); + builder.push_bind(reservation.candidate_attempt().as_str()); + builder.push(", attempt_number = "); + builder.push_bind(attempt_number); + builder.push(", lease_expires_at = "); + builder.part(SqlPart::LedgerDeadline(reservation.lease())); + builder.push(", outcome = NULL, updated_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(", completed_at = NULL, retention_expires_at = "); + builder.part(SqlPart::LedgerDeadline(reservation.retention())); + builder.push(", compacted_at = NULL WHERE service_id = "); + builder.push_bind(record.key.service_id()); + builder.push(" AND principal_partition = "); + builder.push_bind(record.key.principal_partition()); + builder.push(" AND command_id = "); + builder.push_bind(record.key.command_id()); + let result = executor.execute(builder).await?; + if result != 1 { + return Err(CommandLedgerError::AttemptFenced { + command_id: record.key.command_id().to_string(), + }); + } + Ok(()) +} + +pub(crate) async fn complete( + executor: &mut E, + completion: &CommandCompletion, +) -> Result<(), CommandLedgerError> { + let fence = completion.attempt_fence(); + let attempt_number = signed(fence.attempt_number(), "command ledger attempt number")?; + let terminal_state = CommandLedgerState::from(completion.state()).as_str(); + let retention_expires_at = completion.retention_expires_at(); + let mut builder = Statement::new("UPDATE command_ledger SET state = "); + builder.push_bind(terminal_state); + builder.push(", attempt_token = NULL, lease_expires_at = NULL, outcome = "); + builder.part(SqlPart::LedgerJson(completion.replay_json().into())); + builder.push(", updated_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(", completed_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(", retention_expires_at = "); + match retention_expires_at.as_ref() { + Some(deadline) => builder.push_bind(SqlBind::Timestamp(*deadline)), + None => builder.part(SqlPart::LedgerDeadline(completion.retention())), + } + builder.push(", compacted_at = NULL WHERE service_id = "); + builder.push_bind(fence.key().service_id()); + builder.push(" AND principal_partition = "); + builder.push_bind(fence.key().principal_partition()); + builder.push(" AND command_id = "); + builder.push_bind(fence.key().command_id()); + builder.push(" AND command_contract_hash = "); + builder.push_bind(fence.contract_fingerprint_bytes().as_slice()); + builder.push(" AND input_hash = "); + builder.push_bind(fence.input_hash_bytes().as_slice()); + builder.push(" AND state = 'in_progress' AND causation_id = "); + builder.push_bind(fence.causation_id().as_str()); + builder.push(" AND attempt_token = "); + builder.push_bind(fence.attempt_token().as_str()); + builder.push(" AND attempt_number = "); + builder.push_bind(attempt_number); + builder.push(" AND lease_expires_at > "); + builder.part(SqlPart::LedgerNow); + if let Some(deadline) = retention_expires_at.as_ref() { + builder.push(" AND "); + builder.part(SqlPart::LedgerDeadlineIsLive(*deadline)); + } + let result = executor.execute(builder).await?; + if result != 1 { + return Err(CommandLedgerError::AttemptFenced { + command_id: fence.key().command_id().to_string(), + }); + } + Ok(()) +} + +pub(crate) async fn reserve( + executor: &mut impl SqlExecutor, + reservation: &CommandReservation, +) -> Result { + if insert_reservation(executor, reservation).await? { + return Ok(ReservationOutcome::Acquired( + reservation.acquired_candidate_attempt(), + )); + } + let mut record = select(executor, reservation.key(), None) + .await? + .ok_or_else(|| { + CommandLedgerError::Corrupt("conflicting command disappeared during reservation".into()) + })?; + let now = now(executor).await?; + match record.classify_reservation(reservation, now)? { + ReservationDecision::Expire => { + expire(executor, reservation.key(), false).await?; + Ok(ReservationOutcome::Expired) + } + ReservationDecision::Reclaim => { + reclaim(executor, &mut record, reservation, now).await?; + Ok(ReservationOutcome::Acquired(record.acquired_attempt()?)) + } + other => record.reservation_outcome(other), + } +} + +pub(crate) async fn lookup( + executor: &mut impl SqlExecutor, + key: &CommandLedgerKey, + scope: CommandLookupScope<'_>, +) -> Result { + let expected_name = match scope { + CommandLookupScope::CommandName(name) + | CommandLookupScope::CommandContract { + command_name: name, .. + } => Some(name), + CommandLookupScope::Attempt(_) => None, + }; + // Reserve SQLite's writer before reading; PostgreSQL also locks the selected row. + let mut lock = key_filter( + Statement::new("UPDATE command_ledger SET updated_at = updated_at WHERE service_id = "), + key, + ); + if let Some(name) = expected_name { + lock.push(" AND command_name = "); + lock.push_bind(name); + } + executor.execute(lock).await?; + let Some(mut record) = select(executor, key, expected_name).await? else { + return Ok(CommandLookup::Unknown); + }; + if !record.matches_lookup_scope(scope) { + return Ok(CommandLookup::Unknown); + } + let now = now(executor).await?; + if record.state != CommandLedgerState::Expired && record.retention_expires_at <= now { + expire(executor, key, true).await?; + record.expire(now); + } + record.lookup() +} + +pub(crate) async fn mark_retryable( + executor: &mut impl SqlExecutor, + attempt: &AttemptFence, +) -> Result<(), CommandLedgerError> { + let mut builder = Statement::new("UPDATE command_ledger SET state = 'retryable_unknown', attempt_token = NULL, lease_expires_at = NULL, updated_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(" WHERE service_id = "); + builder = key_filter(builder, attempt.key()); + builder.push(" AND command_contract_hash = "); + builder.push_bind(attempt.contract_fingerprint_bytes().as_slice()); + builder.push(" AND input_hash = "); + builder.push_bind(attempt.input_hash_bytes().as_slice()); + builder.push(" AND state = 'in_progress' AND causation_id = "); + builder.push_bind(attempt.causation_id().as_str()); + builder.push(" AND attempt_token = "); + builder.push_bind(attempt.attempt_token().as_str()); + builder.push(" AND attempt_number = "); + builder.push_bind(signed( + attempt.attempt_number(), + "command ledger attempt number", + )?); + if executor.execute(builder).await? != 1 { + return Err(CommandLedgerError::AttemptFenced { + command_id: attempt.key().command_id().to_string(), + }); + } + Ok(()) +} + +pub(crate) async fn compact( + executor: &mut E, + limit: usize, +) -> Result { + if limit == 0 { + return Ok(0); + } + let limit = i64::try_from(limit) + .map_err(|_| CommandLedgerError::Invalid("command compaction limit exceeds i64".into()))?; + executor + .execute(Statement::new( + "UPDATE command_ledger SET updated_at = updated_at WHERE 1 = 0", + )) + .await?; + let mut select = Statement::new("SELECT service_id, principal_partition, command_id FROM command_ledger WHERE state <> 'expired' AND retention_expires_at <= "); + select.part(SqlPart::LedgerNow); + select + .push(" ORDER BY retention_expires_at, service_id, principal_partition, command_id LIMIT "); + select.push_bind(limit); + select.push(E::COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX); + let rows = executor.query(select).await?; + let mut count = 0; + for row in rows { + count += expire(executor, &key_from_row(&row)?, true).await?; + } + Ok(count) +} diff --git a/src/repository/sqlite_codec.rs b/src/repository/sqlite_codec.rs new file mode 100644 index 000000000..9440b4c4b --- /dev/null +++ b/src/repository/sqlite_codec.rs @@ -0,0 +1,76 @@ +//! SQLite timestamp representation shared by SQLx and Durable Object SQL. + +use super::RepositoryError; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +pub(crate) const EVENT_SELECT: &str = "event_name, event_version, payload, payload_codec, payload_codec_version, metadata, sequence, recorded_at"; +pub(crate) const SNAPSHOT_SELECT: &str = "aggregate_type, aggregate_id, version, snapshot_version, payload, payload_codec, payload_codec_version, metadata, recorded_at"; + +pub(crate) fn encode(timestamp: SystemTime) -> Result { + let duration = timestamp.duration_since(UNIX_EPOCH).map_err(|error| { + RepositoryError::Model(format!( + "event timestamp before UNIX epoch cannot be stored in sqlite: {error}" + )) + })?; + Ok(format!( + "{}.{:09}", + duration.as_secs(), + duration.subsec_nanos() + )) +} + +pub(crate) fn decode(value: &str) -> Result { + let invalid = + || RepositoryError::Model(format!("sqlite stored timestamp `{value}` is invalid")); + let (secs, nanos) = value.split_once('.').ok_or_else(invalid)?; + let secs = secs.parse::().map_err(|_| invalid())?; + let nanos = nanos.parse::().map_err(|_| invalid())?; + if nanos >= 1_000_000_000 { + return Err(invalid()); + } + UNIX_EPOCH + .checked_add(Duration::new(secs, nanos)) + .ok_or_else(invalid) +} + +pub(crate) fn decode_epoch(value: f64) -> Result { + let invalid = + || RepositoryError::Model(format!("sqlite timestamp epoch value {value} is invalid")); + let duration = Duration::try_from_secs_f64(value).map_err(|_| invalid())?; + UNIX_EPOCH.checked_add(duration).ok_or_else(invalid) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timestamp_round_trip_preserves_nanoseconds() { + let value = UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_789); + assert_eq!(encode(value).unwrap(), "1700000000.123456789"); + assert_eq!(decode(&encode(value).unwrap()).unwrap(), value); + assert_eq!( + decode_epoch(42.25).unwrap(), + UNIX_EPOCH + Duration::new(42, 250_000_000) + ); + } + + #[test] + fn invalid_timestamps_return_errors_without_panicking() { + for value in [ + "", + "not-a-time", + "-1.000000000", + "1.1000000000", + "1.2.3", + "18446744073709551615.000000000", + ] { + assert!(decode(value).is_err(), "accepted {value}"); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, f64::MAX] { + assert!(decode_epoch(value).is_err(), "accepted {value}"); + } + assert!(encode(UNIX_EPOCH - Duration::from_secs(1)).is_err()); + } +} +pub(crate) const COMMAND_LEDGER_SELECT: &str = "command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, attempt_number, lease_expires_at, outcome, created_at, updated_at, completed_at, retention_expires_at, compacted_at"; diff --git a/src/sqlite_repo/mod.rs b/src/sqlite_repo/mod.rs index 0f4621d3c..aa83376d4 100644 --- a/src/sqlite_repo/mod.rs +++ b/src/sqlite_repo/mod.rs @@ -7,8 +7,12 @@ //! candidate-scan outbox claim (SQLite has no row locks). It is feature-gated //! behind `sqlite` and async-only. +use crate::repository::sqlite_codec::{ + decode as system_time_from_storage, decode_epoch as system_time_from_epoch_secs, + encode as system_time_to_storage, +}; use std::sync::LazyLock; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime}; use sqlx::migrate::Migrator; use sqlx::query_builder::Separated; @@ -54,15 +58,12 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Sqlite { // recovery re-reads stream versions in the same transaction. const CONFLICT_REREAD_IN_TX: bool = true; const NOW: &'static str = "CURRENT_TIMESTAMP"; - const COMMAND_LEDGER_SELECT: &'static str = "command_name, command_contract_hash, \ - input_hash, state, causation_id, attempt_token, attempt_number, lease_expires_at, \ - outcome, created_at, updated_at, completed_at, retention_expires_at, compacted_at"; + const COMMAND_LEDGER_SELECT: &'static str = + crate::repository::sqlite_codec::COMMAND_LEDGER_SELECT; const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = ""; const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = ""; - const EVENT_SELECT: &'static str = "event_name, event_version, payload, payload_codec, \ - payload_codec_version, metadata, sequence, recorded_at"; - const SNAPSHOT_SELECT: &'static str = "aggregate_type, aggregate_id, version, \ - snapshot_version, payload, payload_codec, payload_codec_version, metadata, recorded_at"; + const EVENT_SELECT: &'static str = crate::repository::sqlite_codec::EVENT_SELECT; + const SNAPSHOT_SELECT: &'static str = crate::repository::sqlite_codec::SNAPSHOT_SELECT; const OUTBOX_SELECT: &'static str = "message_id, event_type, payload, payload_codec, \ payload_codec_version, metadata, status, created_at, claimed_by, claimed_until, \ attempts, last_error, destination, source_aggregate_type, source_aggregate_id, \ @@ -465,40 +466,6 @@ impl crate::sqlx_repo::read_model::SqlxReadModelBackend for Sqlite { } } -fn system_time_to_storage(timestamp: SystemTime) -> Result { - let duration = timestamp.duration_since(UNIX_EPOCH).map_err(|err| { - RepositoryError::Model(format!( - "event timestamp before UNIX epoch cannot be stored in sqlite: {err}" - )) - })?; - Ok(format!( - "{}.{:09}", - duration.as_secs(), - duration.subsec_nanos() - )) -} - -fn system_time_from_storage(value: &str) -> Result { - let invalid = - || RepositoryError::Model(format!("sqlite stored timestamp `{value}` is invalid")); - let (secs, nanos) = value.split_once('.').ok_or_else(invalid)?; - let secs = secs.parse::().map_err(|_| invalid())?; - let nanos = nanos.parse::().map_err(|_| invalid())?; - if nanos >= 1_000_000_000 { - return Err(invalid()); - } - Ok(UNIX_EPOCH + Duration::new(secs, nanos)) -} - -fn system_time_from_epoch_secs(value: f64) -> Result { - if !value.is_finite() || value < 0.0 { - return Err(RepositoryError::Model(format!( - "sqlite timestamp epoch value {value} is invalid" - ))); - } - Ok(UNIX_EPOCH + Duration::from_secs_f64(value)) -} - fn repository_storage_error(operation: &str, err: sqlx::Error) -> RepositoryError { sqlx_repo::repository_storage_error(SQLITE_BACKEND, operation, err) } diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index f93a034e5..d44b5ba9b 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -158,9 +158,6 @@ pub(super) fn ids_by_type(identities: &[StreamIdentity]) -> BTreeMap<&str, Vec<& groups } -/// Bound parameters per `aggregate_events` row. -pub(super) const EVENT_BIND_COLUMNS: usize = 10; - /// Bound parameters per `outbox_messages` row. pub(super) const OUTBOX_BIND_COLUMNS: usize = 19; diff --git a/src/sqlx_repo/repo/commit.rs b/src/sqlx_repo/repo/commit.rs index d7841aec7..c42cc7736 100644 --- a/src/sqlx_repo/repo/commit.rs +++ b/src/sqlx_repo/repo/commit.rs @@ -9,42 +9,17 @@ where for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, + for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { - let fence = completion.attempt_fence(); - - // SQLite needs a write statement to reserve the database writer before - // the read; PostgreSQL's subsequent SELECT also carries FOR UPDATE. This - // establishes one portable lock order before any domain participant is - // mutated. - let mut lock = QueryBuilder::::new( - "UPDATE command_ledger SET updated_at = updated_at WHERE service_id = ", - ); - lock.push_bind(fence.key().service_id()); - lock.push(" AND principal_partition = "); - lock.push_bind(fence.key().principal_partition()); - lock.push(" AND command_id = "); - lock.push_bind(fence.key().command_id()); - let result = - lock.build().execute(&mut **tx).await.map_err(|error| { - repository_storage_error::("lock command attempt preflight", error) - })?; - if DB::rows_affected(&result) != 1 { - return Err(CommandLedgerError::AttemptFenced { - command_id: fence.key().command_id().to_string(), - }); - } - - let record = select_command_ledger_record_in_tx(tx, fence.key(), None) - .await? - .ok_or_else(|| CommandLedgerError::AttemptFenced { - command_id: fence.key().command_id().to_string(), - })?; - let now = command_ledger_now_in_tx(tx).await?; - record.validate_live_attempt(&fence, now) + crate::repository::sql::ledger::preflight( + &mut executor::ConnectionExecutor::(&mut **tx), + completion, + ) + .await } async fn commit_sqlx_batch<'a, DB>( @@ -254,301 +229,6 @@ where } } -fn corrupt_ledger_value(error: CommandLedgerError) -> CommandLedgerError { - CommandLedgerError::Corrupt(error.to_string()) -} - -#[allow(dead_code)] -fn command_ledger_key_from_row(row: &DB::Row) -> Result -where - DB: SqlxRepoBackend, - for<'q> String: Type + sqlx::Decode<'q, DB>, - for<'r> &'r str: sqlx::ColumnIndex, -{ - let service_id: String = row.try_get("service_id").map_err(|error| { - repository_storage_error::("decode command ledger service ID", error) - })?; - let principal: String = row.try_get("principal_partition").map_err(|error| { - repository_storage_error::("decode command ledger principal partition", error) - })?; - let command_id: String = row.try_get("command_id").map_err(|error| { - repository_storage_error::("decode command ledger command ID", error) - })?; - CommandLedgerKey::new( - service_id, - PrincipalPartitionId::new(principal).map_err(corrupt_ledger_value)?, - CommandId::parse(command_id).map_err(corrupt_ledger_value)?, - ) - .map_err(corrupt_ledger_value) -} - -fn command_ledger_record_from_row( - row: &DB::Row, - key: CommandLedgerKey, -) -> Result -where - DB: SqlxRepoBackend, - for<'q> i64: Type + sqlx::Decode<'q, DB>, - for<'q> String: Type + sqlx::Decode<'q, DB>, - for<'q> Vec: Type + sqlx::Decode<'q, DB>, - for<'r> &'r str: sqlx::ColumnIndex, -{ - let decode = |operation: &'static str, error| repository_storage_error::(operation, error); - let command_name: String = row - .try_get("command_name") - .map_err(|error| decode("decode command ledger name", error))?; - let contract: Vec = row - .try_get("command_contract_hash") - .map_err(|error| decode("decode command contract hash", error))?; - let input: Vec = row - .try_get("input_hash") - .map_err(|error| decode("decode canonical command input hash", error))?; - let state: String = row - .try_get("state") - .map_err(|error| decode("decode command ledger state", error))?; - let causation_id: String = row - .try_get("causation_id") - .map_err(|error| decode("decode command ledger causation ID", error))?; - let attempt_token: Option = row - .try_get("attempt_token") - .map_err(|error| decode("decode command ledger attempt token", error))?; - let attempt_number: i64 = row - .try_get("attempt_number") - .map_err(|error| decode("decode command ledger attempt number", error))?; - let outcome_json: Option = row - .try_get("outcome") - .map_err(|error| decode("decode command ledger outcome", error))?; - - let record = CommandLedgerRecord { - key, - command_name, - contract_fingerprint: CommandContractFingerprint::try_from_slice(&contract) - .map_err(corrupt_ledger_value)?, - input_hash: CanonicalInputHash::try_from_slice(&input).map_err(corrupt_ledger_value)?, - state: CommandLedgerState::parse(&state)?, - causation_id: CausationId::parse_stored(causation_id)?, - attempt_token: attempt_token.map(AttemptToken::parse_stored).transpose()?, - attempt_number: repository_u64_from_i64( - DB::BACKEND, - attempt_number, - "command ledger attempt number", - )?, - lease_expires_at: DB::decode_optional_timestamp(row, "lease_expires_at")?, - outcome_json, - created_at: DB::decode_timestamp(row, "created_at")?, - updated_at: DB::decode_timestamp(row, "updated_at")?, - completed_at: DB::decode_optional_timestamp(row, "completed_at")?, - retention_expires_at: DB::decode_timestamp(row, "retention_expires_at")?, - compacted_at: DB::decode_optional_timestamp(row, "compacted_at")?, - }; - record.validate_stored_shape()?; - Ok(record) -} - -async fn command_ledger_now_in_tx( - tx: &mut Transaction<'_, DB>, -) -> Result -where - DB: SqlxRepoBackend, - for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'r> &'r str: sqlx::ColumnIndex, -{ - let mut builder = QueryBuilder::::new("SELECT "); - DB::push_command_ledger_now_epoch(&mut builder); - builder.push(" AS ledger_now"); - let row = builder - .build() - .fetch_one(&mut **tx) - .await - .map_err(|error| repository_storage_error::("read command ledger clock", error))?; - Ok(DB::decode_timestamp(&row, "ledger_now")?) -} - -async fn select_command_ledger_record_in_tx( - tx: &mut Transaction<'_, DB>, - key: &CommandLedgerKey, - expected_command_name: Option<&str>, -) -> Result, CommandLedgerError> -where - DB: SqlxRepoBackend, - for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> i64: Type + sqlx::Decode<'q, DB>, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> Vec: Type + sqlx::Decode<'q, DB>, - for<'q> &'q str: Encode<'q, DB> + Type, - for<'r> &'r str: sqlx::ColumnIndex, -{ - let mut builder = QueryBuilder::::new("SELECT "); - builder.push(DB::COMMAND_LEDGER_SELECT); - builder.push(" FROM command_ledger WHERE service_id = "); - builder.push_bind(key.service_id()); - builder.push(" AND principal_partition = "); - builder.push_bind(key.principal_partition()); - builder.push(" AND command_id = "); - builder.push_bind(key.command_id()); - if let Some(expected_command_name) = expected_command_name { - builder.push(" AND command_name = "); - builder.push_bind(expected_command_name); - } - builder.push(DB::COMMAND_LEDGER_LOCK_SUFFIX); - let row = builder - .build() - .fetch_optional(&mut **tx) - .await - .map_err(|error| repository_storage_error::("select command ledger row", error))?; - row.map(|row| command_ledger_record_from_row::(&row, key.clone())) - .transpose() -} - -async fn insert_command_reservation_in_tx( - tx: &mut Transaction<'_, DB>, - reservation: &CommandReservation, -) -> Result -where - DB: SqlxRepoBackend, - for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type, - for<'q> f64: Encode<'q, DB> + Type, - for<'q> &'q str: Encode<'q, DB> + Type, - for<'q> &'q [u8]: Encode<'q, DB> + Type, -{ - let mut builder = QueryBuilder::::new( - "INSERT INTO command_ledger (service_id, principal_partition, command_id, \ - command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, \ - attempt_number, lease_expires_at, outcome, created_at, updated_at, completed_at, \ - retention_expires_at, compacted_at) VALUES (", - ); - builder.push_bind(reservation.key().service_id()); - builder.push(", "); - builder.push_bind(reservation.key().principal_partition()); - builder.push(", "); - builder.push_bind(reservation.key().command_id()); - builder.push(", "); - builder.push_bind(reservation.command_name()); - builder.push(", "); - builder.push_bind(reservation.contract_fingerprint_bytes().as_slice()); - builder.push(", "); - builder.push_bind(reservation.input_hash_bytes().as_slice()); - builder.push(", "); - builder.push_bind(CommandLedgerState::InProgress.as_str()); - builder.push(", "); - builder.push_bind(reservation.candidate_causation().as_str()); - builder.push(", "); - builder.push_bind(reservation.candidate_attempt().as_str()); - builder.push(", "); - builder.push_bind(1_i64); - builder.push(", "); - DB::push_command_ledger_deadline(&mut builder, reservation.lease()); - builder.push(", NULL, "); - DB::push_command_ledger_now(&mut builder); - builder.push(", "); - DB::push_command_ledger_now(&mut builder); - builder.push(", NULL, "); - DB::push_command_ledger_deadline(&mut builder, reservation.retention()); - builder.push(", NULL"); - builder.push(") ON CONFLICT (service_id, principal_partition, command_id) DO NOTHING"); - let result = builder - .build() - .execute(&mut **tx) - .await - .map_err(|error| repository_storage_error::("insert command reservation", error))?; - Ok(DB::rows_affected(&result) == 1) -} - -async fn expire_command_in_tx( - tx: &mut Transaction<'_, DB>, - key: &CommandLedgerKey, - require_retention_due: bool, -) -> Result -where - DB: SqlxRepoBackend, - for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> String: Encode<'q, DB> + Type, - for<'q> &'q str: Encode<'q, DB> + Type, -{ - let mut builder = QueryBuilder::::new( - "UPDATE command_ledger SET state = 'expired', attempt_token = NULL, \ - lease_expires_at = NULL, outcome = NULL, updated_at = ", - ); - DB::push_command_ledger_now(&mut builder); - builder.push(", compacted_at = "); - DB::push_command_ledger_now(&mut builder); - builder.push(" WHERE service_id = "); - builder.push_bind(key.service_id()); - builder.push(" AND principal_partition = "); - builder.push_bind(key.principal_partition()); - builder.push(" AND command_id = "); - builder.push_bind(key.command_id()); - builder.push(" AND state <> 'expired'"); - if require_retention_due { - builder.push(" AND retention_expires_at <= "); - DB::push_command_ledger_now(&mut builder); - } - let result = builder - .build() - .execute(&mut **tx) - .await - .map_err(|error| repository_storage_error::("expire command ledger row", error))?; - Ok(DB::rows_affected(&result)) -} - -async fn reclaim_command_in_tx( - tx: &mut Transaction<'_, DB>, - record: &mut CommandLedgerRecord, - reservation: &CommandReservation, - now: SystemTime, -) -> Result<(), CommandLedgerError> -where - DB: SqlxRepoBackend, - for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type, - for<'q> f64: Encode<'q, DB> + Type, - for<'q> String: Encode<'q, DB> + Type, - for<'q> &'q str: Encode<'q, DB> + Type, -{ - record.reclaim(reservation, now)?; - let attempt_number = repository_i64_from_u64( - DB::BACKEND, - record.attempt_number, - "command ledger attempt number", - DB::INTEGER_STORAGE, - )?; - let mut builder = QueryBuilder::::new( - "UPDATE command_ledger SET state = 'in_progress', attempt_token = ", - ); - builder.push_bind(reservation.candidate_attempt().as_str()); - builder.push(", attempt_number = "); - builder.push_bind(attempt_number); - builder.push(", lease_expires_at = "); - DB::push_command_ledger_deadline(&mut builder, reservation.lease()); - builder.push(", outcome = NULL, updated_at = "); - DB::push_command_ledger_now(&mut builder); - builder.push(", completed_at = NULL, retention_expires_at = "); - DB::push_command_ledger_deadline(&mut builder, reservation.retention()); - builder.push(", compacted_at = NULL WHERE service_id = "); - builder.push_bind(record.key.service_id()); - builder.push(" AND principal_partition = "); - builder.push_bind(record.key.principal_partition()); - builder.push(" AND command_id = "); - builder.push_bind(record.key.command_id()); - let result = builder - .build() - .execute(&mut **tx) - .await - .map_err(|error| repository_storage_error::("reclaim command attempt", error))?; - if DB::rows_affected(&result) != 1 { - return Err(CommandLedgerError::AttemptFenced { - command_id: record.key.command_id().to_string(), - }); - } - Ok(()) -} - async fn complete_command_in_tx( tx: &mut Transaction<'_, DB>, completion: &CommandCompletion, @@ -557,292 +237,104 @@ where DB: SqlxRepoBackend, for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type, - for<'q> f64: Encode<'q, DB> + Type, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, for<'q> &'q [u8]: Encode<'q, DB> + Type, + for<'r> &'r str: sqlx::ColumnIndex, { - let fence = completion.attempt_fence(); - let attempt_number = repository_i64_from_u64( - DB::BACKEND, - fence.attempt_number(), - "command ledger attempt number", - DB::INTEGER_STORAGE, - )?; - let terminal_state = CommandLedgerState::from(completion.state()).as_str(); - let retention_expires_at = completion - .retention_expires_at() - .map(DB::timestamp_value) - .transpose() - .map_err(CommandLedgerError::Storage)?; - let mut builder = QueryBuilder::::new("UPDATE command_ledger SET state = "); - builder.push_bind(terminal_state); - builder.push(", attempt_token = NULL, lease_expires_at = NULL, outcome = "); - DB::push_command_ledger_json(&mut builder, completion.replay_json()); - builder.push(", updated_at = "); - DB::push_command_ledger_now(&mut builder); - builder.push(", completed_at = "); - DB::push_command_ledger_now(&mut builder); - builder.push(", retention_expires_at = "); - match retention_expires_at.as_ref() { - Some(deadline) => DB::push_timestamp_assign(&mut builder, deadline), - None => DB::push_command_ledger_deadline(&mut builder, completion.retention()), - } - builder.push(", compacted_at = NULL WHERE service_id = "); - builder.push_bind(fence.key().service_id()); - builder.push(" AND principal_partition = "); - builder.push_bind(fence.key().principal_partition()); - builder.push(" AND command_id = "); - builder.push_bind(fence.key().command_id()); - builder.push(" AND command_contract_hash = "); - builder.push_bind(fence.contract_fingerprint_bytes().as_slice()); - builder.push(" AND input_hash = "); - builder.push_bind(fence.input_hash_bytes().as_slice()); - builder.push(" AND state = 'in_progress' AND causation_id = "); - builder.push_bind(fence.causation_id().as_str()); - builder.push(" AND attempt_token = "); - builder.push_bind(fence.attempt_token().as_str()); - builder.push(" AND attempt_number = "); - builder.push_bind(attempt_number); - builder.push(" AND lease_expires_at > "); - DB::push_command_ledger_now(&mut builder); - if let Some(deadline) = retention_expires_at.as_ref() { - builder.push(" AND "); - DB::push_command_ledger_deadline_is_live(&mut builder, deadline); - } - let result = - builder.build().execute(&mut **tx).await.map_err(|error| { - repository_storage_error::("complete command ledger row", error) - })?; - if DB::rows_affected(&result) != 1 { - return Err(CommandLedgerError::AttemptFenced { - command_id: fence.key().command_id().to_string(), - }); - } - Ok(()) + crate::repository::sql::ledger::complete( + &mut executor::ConnectionExecutor::(&mut **tx), + completion, + ) + .await } impl CommandLedgerStore for SqlxRepository where DB: SqlxRepoBackend, for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, - for<'c> &'c Pool: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> f64: Encode<'q, DB> + Type, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { - fn reserve_command( + async fn reserve_command( &self, reservation: CommandReservation, - ) -> impl Future> + Send + '_ { - async move { - let mut tx = self.pool.begin().await.map_err(|error| { + ) -> Result { + let mut tx = + self.pool.begin().await.map_err(|error| { repository_storage_error::("begin command reservation", error) })?; - if insert_command_reservation_in_tx(&mut tx, &reservation).await? { - tx.commit().await.map_err(|error| { - repository_storage_error::("commit command reservation", error) - })?; - return Ok(ReservationOutcome::Acquired( - reservation.acquired_candidate_attempt(), - )); - } - - let mut record = select_command_ledger_record_in_tx(&mut tx, reservation.key(), None) - .await? - .ok_or_else(|| { - CommandLedgerError::Corrupt(format!( - "conflicting command `{}` disappeared during reservation", - reservation.key().command_id() - )) - })?; - let now = command_ledger_now_in_tx(&mut tx).await?; - let decision = record.classify_reservation(&reservation, now)?; - let outcome = match decision { - ReservationDecision::Expire => { - expire_command_in_tx(&mut tx, reservation.key(), false).await?; - ReservationOutcome::Expired - } - ReservationDecision::Reclaim => { - reclaim_command_in_tx(&mut tx, &mut record, &reservation, now).await?; - ReservationOutcome::Acquired(record.acquired_attempt()?) - } - other => record.reservation_outcome(other)?, - }; - tx.commit().await.map_err(|error| { - repository_storage_error::("commit command reservation decision", error) - })?; - Ok(outcome) - } + let outcome = crate::repository::sql::ledger::reserve( + &mut executor::ConnectionExecutor::(&mut *tx), + &reservation, + ) + .await?; + tx.commit() + .await + .map_err(|error| repository_storage_error::("commit command reservation", error))?; + Ok(outcome) } - fn lookup_command<'a>( + async fn lookup_command<'a>( &'a self, key: &'a CommandLedgerKey, scope: CommandLookupScope<'a>, - ) -> impl Future> + Send + 'a { - async move { - let mut tx = self.pool.begin().await.map_err(|error| { - repository_storage_error::("begin command ledger lookup", error) - })?; - - // Establish SQLite's single-writer reservation before selecting; - // PostgreSQL additionally takes the row lock through its suffix. - let mut lock = QueryBuilder::::new( - "UPDATE command_ledger SET updated_at = updated_at WHERE service_id = ", - ); - lock.push_bind(key.service_id()); - lock.push(" AND principal_partition = "); - lock.push_bind(key.principal_partition()); - lock.push(" AND command_id = "); - lock.push_bind(key.command_id()); - match scope { - CommandLookupScope::CommandName(expected_command_name) - | CommandLookupScope::CommandContract { - command_name: expected_command_name, - .. - } => { - lock.push(" AND command_name = "); - lock.push_bind(expected_command_name); - } - CommandLookupScope::Attempt(_) => {} - } - lock.build().execute(&mut *tx).await.map_err(|error| { - repository_storage_error::("lock command ledger lookup", error) - })?; - - let expected_command_name = match scope { - CommandLookupScope::CommandName(expected) => Some(expected), - CommandLookupScope::CommandContract { - command_name: expected, - .. - } => Some(expected), - CommandLookupScope::Attempt(_) => None, - }; - let Some(mut record) = - select_command_ledger_record_in_tx(&mut tx, key, expected_command_name).await? - else { - tx.commit().await.map_err(|error| { - repository_storage_error::("commit empty command ledger lookup", error) - })?; - return Ok(CommandLookup::Unknown); - }; - if !record.matches_lookup_scope(scope) { - tx.commit().await.map_err(|error| { - repository_storage_error::("commit mismatched command ledger lookup", error) - })?; - return Ok(CommandLookup::Unknown); - } - let now = command_ledger_now_in_tx(&mut tx).await?; - if record.state != CommandLedgerState::Expired && record.retention_expires_at <= now { - expire_command_in_tx(&mut tx, key, true).await?; - record.expire(now); - } - let lookup = record.lookup()?; - tx.commit().await.map_err(|error| { - repository_storage_error::("commit command ledger lookup", error) - })?; - Ok(lookup) - } + ) -> Result { + let mut tx = self + .pool + .begin() + .await + .map_err(|error| repository_storage_error::("begin command lookup", error))?; + let outcome = crate::repository::sql::ledger::lookup( + &mut executor::ConnectionExecutor::(&mut *tx), + key, + scope, + ) + .await?; + tx.commit() + .await + .map_err(|error| repository_storage_error::("commit command lookup", error))?; + Ok(outcome) } - fn mark_retryable_unknown( + async fn mark_retryable_unknown( &self, attempt: AttemptFence, - ) -> impl Future> + Send + '_ { - async move { - let attempt_number = repository_i64_from_u64( - DB::BACKEND, - attempt.attempt_number(), - "command ledger attempt number", - DB::INTEGER_STORAGE, - )?; - let mut builder = QueryBuilder::::new( - "UPDATE command_ledger SET state = 'retryable_unknown', attempt_token = NULL, \ - lease_expires_at = NULL, updated_at = ", - ); - DB::push_command_ledger_now(&mut builder); - builder.push(" WHERE service_id = "); - builder.push_bind(attempt.key().service_id()); - builder.push(" AND principal_partition = "); - builder.push_bind(attempt.key().principal_partition()); - builder.push(" AND command_id = "); - builder.push_bind(attempt.key().command_id()); - builder.push(" AND command_contract_hash = "); - builder.push_bind(attempt.contract_fingerprint_bytes().as_slice()); - builder.push(" AND input_hash = "); - builder.push_bind(attempt.input_hash_bytes().as_slice()); - builder.push(" AND state = 'in_progress' AND causation_id = "); - builder.push_bind(attempt.causation_id().as_str()); - builder.push(" AND attempt_token = "); - builder.push_bind(attempt.attempt_token().as_str()); - builder.push(" AND attempt_number = "); - builder.push_bind(attempt_number); - let result = builder.build().execute(&self.pool).await.map_err(|error| { - repository_storage_error::("mark command retryable unknown", error) - })?; - if DB::rows_affected(&result) != 1 { - return Err(CommandLedgerError::AttemptFenced { - command_id: attempt.key().command_id().to_string(), - }); - } - Ok(()) - } + ) -> Result<(), CommandLedgerError> { + let mut connection = self.pool.acquire().await.map_err(|error| { + repository_storage_error::("acquire command ledger connection", error) + })?; + crate::repository::sql::ledger::mark_retryable( + &mut executor::ConnectionExecutor::(&mut *connection), + &attempt, + ) + .await } - fn compact_expired_commands( - &self, - limit: usize, - ) -> impl Future> + Send + '_ { - async move { - if limit == 0 { - return Ok(0); - } - let limit = i64::try_from(limit).map_err(|_| { - CommandLedgerError::Invalid("command compaction limit exceeds i64".into()) - })?; - let mut tx = self.pool.begin().await.map_err(|error| { - repository_storage_error::("begin command ledger compaction", error) + async fn compact_expired_commands(&self, limit: usize) -> Result { + if limit == 0 { + return Ok(0); + } + let mut tx = + self.pool.begin().await.map_err(|error| { + repository_storage_error::("begin command compaction", error) })?; - - // A no-op write obtains SQLite's transaction-wide writer lock. - // PostgreSQL relies on the per-row SKIP LOCKED suffix below. - QueryBuilder::::new( - "UPDATE command_ledger SET updated_at = updated_at WHERE 1 = 0", - ) - .build() - .execute(&mut *tx) + let count = crate::repository::sql::ledger::compact( + &mut executor::ConnectionExecutor::(&mut *tx), + limit, + ) + .await?; + tx.commit() .await - .map_err(|error| { - repository_storage_error::("lock command ledger compaction", error) - })?; - - let mut select = QueryBuilder::::new( - "SELECT service_id, principal_partition, command_id FROM command_ledger \ - WHERE state <> 'expired' AND retention_expires_at <= ", - ); - DB::push_command_ledger_now(&mut select); - select.push(" ORDER BY retention_expires_at, service_id, principal_partition, command_id LIMIT "); - select.push_bind(limit); - select.push(DB::COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX); - let rows = select.build().fetch_all(&mut *tx).await.map_err(|error| { - repository_storage_error::("select command ledger compaction rows", error) - })?; - let mut compacted = 0; - for row in rows { - let key = command_ledger_key_from_row::(&row)?; - compacted += expire_command_in_tx(&mut tx, &key, true).await?; - } - tx.commit().await.map_err(|error| { - repository_storage_error::("commit command ledger compaction", error) - })?; - Ok(compacted) - } + .map_err(|error| repository_storage_error::("commit command compaction", error))?; + Ok(count) } } /// Record a consumer inbox receipt in the commit transaction. The @@ -880,31 +372,7 @@ where } } -/// One `aggregate_events` row with pre-validated bind values, built before the -/// query so any conversion error surfaces before we touch the database. The -/// stream identity and expected version ride along for conflict recovery. -struct EventRow<'a, DB: SqlxRepoBackend> { - identity: &'a StreamIdentity, - expected_version: u64, - sequence: i64, - event_name: &'a str, - event_version: i64, - payload: &'a [u8], - payload_codec: &'a str, - payload_codec_version: i64, - metadata: String, - recorded_at: DB::TimestampValue, -} - -/// Insert every event across all prepared appends with multi-row INSERTs, -/// chunked to respect the backend's bound-parameter limit (Postgres is -/// effectively unlimited, so its chunking collapses to one statement). -/// -/// Conflict detection is unchanged from the per-row path: the `(aggregate_type, -/// aggregate_id, sequence)` primary key is the contiguity gate, and a unique -/// violation still surfaces as `ConcurrentWrite`. Recovery re-reads stream -/// versions in-tx or over the pool depending on -/// [`SqlxRepoBackend::CONFLICT_REREAD_IN_TX`]. +/// Execute the shared event insert plan in the command's existing transaction. async fn insert_events_in_tx( pool: &Pool, tx: &mut Transaction<'_, DB>, @@ -916,96 +384,51 @@ where for<'c> &'c Pool: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { - let mut rows = Vec::new(); - for append in prepared { - for event in append.events { - rows.push(EventRow:: { - identity: &append.identity, - expected_version: append.expected_version, - sequence: repository_i64_from_u64( - DB::BACKEND, - event.sequence, - "sequence", - DB::INTEGER_STORAGE, - )?, - event_name: &event.event_name, - event_version: repository_i64_from_u64( - DB::BACKEND, - event.event_version, - "event_version", - DB::INTEGER_STORAGE, - )?, - payload: &event.payload, - payload_codec: &event.payload_codec, - payload_codec_version: i64::from(event.payload_codec_version), - metadata: serialize_event_metadata(&event.metadata)?, - recorded_at: DB::timestamp_value(event.timestamp)?, - }); - } - } - - for chunk in rows.chunks(DB::MAX_BIND_PARAMS / EVENT_BIND_COLUMNS) { - let mut builder = QueryBuilder::::new( - "INSERT INTO aggregate_events (\ - aggregate_type, aggregate_id, sequence, event_name, event_version, \ - payload, payload_codec, payload_codec_version, metadata, recorded_at) ", - ); - builder.push_values(chunk, |mut row, event| { - row.push_bind(event.identity.aggregate_type()) - .push_bind(event.identity.aggregate_id()) - .push_bind(event.sequence) - .push_bind(event.event_name) - .push_bind(event.event_version) - .push_bind(event.payload) - .push_bind(event.payload_codec) - .push_bind(event.payload_codec_version); - DB::push_metadata(&mut row, event.metadata.as_str()); - DB::push_timestamp(&mut row, &event.recorded_at); - }); - - let result = builder.build().execute(&mut **tx).await; - match result { - Ok(_) => {} - Err(err) if DB::is_unique_violation(&err) => { - return Err(if DB::CONFLICT_REREAD_IN_TX { - // The transaction survives the constraint error: re-read in - // the same tx, scoped to this chunk (earlier chunks were - // already inserted in this tx and would skew the versions - // of their streams). - let mut seen = std::collections::HashSet::new(); - let candidates: Vec<_> = chunk - .iter() - .filter(|event| seen.insert(event.identity.storage_key())) - .map(|event| (event.identity, event.expected_version)) - .collect(); - concurrent_write_from_conflict(&mut **tx, &candidates).await - } else { - // The failed statement aborted the transaction: re-read the - // conflicting streams' actual versions on a separate - // connection, across the whole batch. - let candidates: Vec<_> = prepared - .iter() - .map(|append| (&append.identity, append.expected_version)) - .collect(); - match pool.acquire().await { - Ok(mut conn) => { - concurrent_write_from_conflict(&mut conn, &candidates).await - } - Err(err) => repository_storage_error::( - "acquire conflict re-read connection", - err, - ), - } - }); + use crate::repository::sql::SqlExecutor; + for insert in crate::repository::sql::event_inserts(prepared, DB::MAX_BIND_PARAMS)? { + let result = super::executor::ConnectionExecutor::(&mut **tx) + .execute(insert.statement) + .await; + if let Err(error) = result { + let unique = match &error { + RepositoryError::Storage { + source: Some(source), + .. + } => source + .downcast_ref::() + .is_some_and(DB::is_unique_violation), + _ => false, + }; + if !unique { + return Err(error); } - Err(err) => return Err(repository_storage_error::("insert events", err)), + return Err(if DB::CONFLICT_REREAD_IN_TX { + let candidates: Vec<_> = insert + .candidates + .iter() + .map(|(identity, version)| (identity, *version)) + .collect(); + concurrent_write_from_conflict(&mut **tx, &candidates).await + } else { + let candidates: Vec<_> = prepared + .iter() + .map(|append| (&append.identity, append.expected_version)) + .collect(); + match pool.acquire().await { + Ok(mut conn) => concurrent_write_from_conflict(&mut conn, &candidates).await, + Err(error) => { + repository_storage_error::("acquire conflict re-read connection", error) + } + } + }); } } - Ok(()) } diff --git a/src/sqlx_repo/repo/events.rs b/src/sqlx_repo/repo/events.rs index 351ca17b8..174543b6f 100644 --- a/src/sqlx_repo/repo/events.rs +++ b/src/sqlx_repo/repo/events.rs @@ -8,51 +8,5 @@ where for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'r> &'r str: sqlx::ColumnIndex, { - let payload_codec: String = row - .try_get("payload_codec") - .map_err(|err| repository_storage_error::("decode payload codec row", err))?; - // Nearly every row carries the crate's own codec constant; borrow it - // instead of keeping a per-event allocation. - let payload_codec = if payload_codec == BITCODE_PAYLOAD_CODEC { - Cow::Borrowed(BITCODE_PAYLOAD_CODEC) - } else { - Cow::Owned(payload_codec) - }; - let payload_codec_version = repository_u16_from_i64( - DB::BACKEND, - row.try_get("payload_codec_version").map_err(|err| { - repository_storage_error::("decode payload codec version row", err) - })?, - "payload_codec_version", - )?; - let metadata_json: String = row - .try_get("metadata") - .map_err(|err| repository_storage_error::("decode metadata row", err))?; - let metadata = deserialize_event_metadata(&metadata_json)?; - let event = EventRecord { - event_name: row - .try_get("event_name") - .map_err(|err| repository_storage_error::("decode event name row", err))?, - payload_codec, - payload_codec_version, - payload: row - .try_get("payload") - .map_err(|err| repository_storage_error::("decode payload row", err))?, - event_version: repository_u64_from_i64( - DB::BACKEND, - row.try_get("event_version") - .map_err(|err| repository_storage_error::("decode event version row", err))?, - "event_version", - )?, - sequence: repository_u64_from_i64( - DB::BACKEND, - row.try_get("sequence") - .map_err(|err| repository_storage_error::("decode sequence row", err))?, - "sequence", - )?, - timestamp: DB::decode_timestamp(&row, "recorded_at")?, - metadata, - }; - validate_supported_event_codec(&event)?; - Ok(event) + crate::repository::sql::event_from_row(&super::executor::EventRow::(row)) } diff --git a/src/sqlx_repo/repo/executor.rs b/src/sqlx_repo/repo/executor.rs new file mode 100644 index 000000000..cb1477f16 --- /dev/null +++ b/src/sqlx_repo/repo/executor.rs @@ -0,0 +1,134 @@ +//! SQLx execution adapter for the runtime-independent SQL event store. + +use super::*; +use crate::repository::sql::{SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; + +pub(super) struct ConnectionExecutor<'a, DB: SqlxRepoBackend>(pub &'a mut DB::Connection); +pub(super) struct EventRow(pub DB::Row); + +impl SqlRow for EventRow +where + DB: SqlxRepoBackend, + for<'q> i64: Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, + for<'r> &'r str: sqlx::ColumnIndex, +{ + fn text(&self, column: &'static str) -> Result { + self.0 + .try_get(column) + .map_err(|error| repository_storage_error::(column, error)) + } + fn optional_text(&self, column: &'static str) -> Result, RepositoryError> { + self.0 + .try_get(column) + .map_err(|error| repository_storage_error::(column, error)) + } + fn integer(&self, column: &'static str) -> Result { + self.0 + .try_get(column) + .map_err(|error| repository_storage_error::(column, error)) + } + fn optional_integer(&self, column: &'static str) -> Result, RepositoryError> { + self.0 + .try_get(column) + .map_err(|error| repository_storage_error::(column, error)) + } + fn bytes(&self, column: &'static str) -> Result, RepositoryError> { + self.0 + .try_get(column) + .map_err(|error| repository_storage_error::(column, error)) + } + fn timestamp(&self, column: &'static str) -> Result { + DB::decode_timestamp(&self.0, column) + } + fn optional_timestamp( + &self, + column: &'static str, + ) -> Result, RepositoryError> { + DB::decode_optional_timestamp(&self.0, column) + } +} + +fn build(statement: &Statement<'_>) -> Result, RepositoryError> +where + DB: SqlxRepoBackend, + for<'q> i64: Encode<'q, DB> + Type, + for<'q> &'q str: Encode<'q, DB> + Type, + for<'q> &'q [u8]: Encode<'q, DB> + Type, +{ + let mut builder = QueryBuilder::::new(""); + for part in &statement.0 { + match part { + SqlPart::LedgerNow => DB::push_command_ledger_now(&mut builder), + SqlPart::LedgerNowEpoch => DB::push_command_ledger_now_epoch(&mut builder), + SqlPart::LedgerDeadline(value) => { + DB::push_command_ledger_deadline(&mut builder, *value) + } + SqlPart::LedgerDeadlineIsLive(value) => DB::push_command_ledger_deadline_is_live( + &mut builder, + &DB::timestamp_value(*value)?, + ), + SqlPart::LedgerJson(value) => DB::push_command_ledger_json(&mut builder, value), + SqlPart::Sql(sql) => { + builder.push(sql); + } + SqlPart::Bind(SqlBind::Text(value)) => { + builder.push_bind(value.as_str()); + } + SqlPart::Bind(SqlBind::Integer(value)) => { + builder.push_bind(*value); + } + SqlPart::Bind(SqlBind::Bytes(value)) => { + builder.push_bind(value.as_ref()); + } + SqlPart::Bind(SqlBind::Metadata(value)) => { + DB::push_metadata(&mut builder.separated(""), value); + } + SqlPart::Bind(SqlBind::Timestamp(value)) => { + DB::push_timestamp(&mut builder.separated(""), &DB::timestamp_value(*value)?); + } + } + } + Ok(builder) +} + +impl SqlExecutor for ConnectionExecutor<'_, DB> +where + DB: SqlxRepoBackend, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + DB::Arguments: IntoArguments, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, + for<'q> &'q str: Encode<'q, DB> + Type, + for<'q> &'q [u8]: Encode<'q, DB> + Type, + for<'r> &'r str: sqlx::ColumnIndex, +{ + type Row = EventRow; + const EVENT_SELECT: &'static str = DB::EVENT_SELECT; + const SNAPSHOT_SELECT: &'static str = DB::SNAPSHOT_SELECT; + const NOW: &'static str = DB::NOW; + const COMMAND_LEDGER_SELECT: &'static str = DB::COMMAND_LEDGER_SELECT; + const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = DB::COMMAND_LEDGER_LOCK_SUFFIX; + const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = + DB::COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX; + + async fn query(&mut self, statement: Statement<'_>) -> Result, RepositoryError> { + build::(&statement)? + .build() + .fetch_all(&mut *self.0) + .await + .map(|rows| rows.into_iter().map(EventRow).collect()) + .map_err(|error| repository_storage_error::("query event store", error)) + } + + async fn execute(&mut self, statement: Statement<'_>) -> Result { + build::(&statement)? + .build() + .execute(&mut *self.0) + .await + .map(|result| DB::rows_affected(&result)) + .map_err(|error| repository_storage_error::("write event store", error)) + } +} diff --git a/src/sqlx_repo/repo/mod.rs b/src/sqlx_repo/repo/mod.rs index 716b1e161..bfb431d99 100644 --- a/src/sqlx_repo/repo/mod.rs +++ b/src/sqlx_repo/repo/mod.rs @@ -16,7 +16,6 @@ reason = "async trait impls return impl Future + Send to preserve public Send bounds" )] -use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; use std::future::Future; use std::sync::{Arc, RwLock}; @@ -28,13 +27,12 @@ use sqlx::query_builder::Separated; use sqlx::{Encode, Executor, IntoArguments, Pool, QueryBuilder, Row, Transaction, Type}; use crate::command_ledger::{ - AttemptFence, AttemptToken, CanonicalInputHash, CausalCommitBatch, CausalGetStream, - CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CausationId, - CommandCompletion, CommandContractFingerprint, CommandId, CommandLedgerError, CommandLedgerKey, - CommandLedgerRecord, CommandLedgerState, CommandLedgerStore, CommandLookup, CommandLookupScope, - CommandReservation, PrincipalPartitionId, ReservationDecision, ReservationOutcome, + AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, + CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, + CommandLedgerKey, CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ReservationOutcome, }; -use crate::entity::{Entity, EventRecord, BITCODE_PAYLOAD_CODEC}; +use crate::entity::{Entity, EventRecord}; use crate::outbox::{OutboxMessage, OutboxMessageStatus}; use crate::outbox_worker::{ ensure_active_claim, ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxStore, @@ -42,10 +40,9 @@ use crate::outbox_worker::{ use crate::projection_protocol::{ProjectionChangeRetention, SameTransactionProjectionBatch}; use crate::read_model::{ReadModelLoadGraph, ReadModelLoadRequest, ReadModelQueryCapabilities}; use crate::repository::{ - validate_commit_batch, validate_snapshot_identity, validate_supported_event_codec, CommitBatch, - GetStream, InboxReceipt, InboxStore, PreparedEventAppend, ReadModelWritePlanStore, - RelationalReadModelQueryStore, RepositoryError, SnapshotStore, SnapshotWrite, StreamIdentity, - TransactionalCommit, + validate_commit_batch, CommitBatch, GetStream, InboxReceipt, InboxStore, PreparedEventAppend, + ReadModelWritePlanStore, RelationalReadModelQueryStore, RepositoryError, SnapshotStore, + SnapshotWrite, StreamIdentity, TransactionalCommit, }; use crate::snapshot::SnapshotRecord; use crate::sqlx_repo::projection_protocol::{ @@ -76,6 +73,7 @@ mod backend; mod commit; mod errors; mod events; +mod executor; mod inbox; mod outbox; mod read_models; diff --git a/src/sqlx_repo/repo/snapshots.rs b/src/sqlx_repo/repo/snapshots.rs index 5c62c218f..dea549d57 100644 --- a/src/sqlx_repo/repo/snapshots.rs +++ b/src/sqlx_repo/repo/snapshots.rs @@ -18,23 +18,14 @@ where identity: &'a StreamIdentity, ) -> impl Future, RepositoryError>> + Send + 'a { async move { - let mut builder = QueryBuilder::::new("SELECT "); - builder.push(DB::SNAPSHOT_SELECT); - builder.push(" FROM aggregate_snapshots WHERE aggregate_type = "); - builder.push_bind(identity.aggregate_type()); - builder.push(" AND aggregate_id = "); - builder.push_bind(identity.aggregate_id()); - let row = builder - .build() - .fetch_optional(&self.pool) - .await - .map_err(|err| repository_storage_error::("load snapshot", err))?; - - let Some(row) = row else { - return Ok(None); - }; - - Ok(Some(snapshot_from_row::(row)?)) + let mut connection = self.pool.acquire().await.map_err(|error| { + repository_storage_error::("acquire snapshot connection", error) + })?; + crate::repository::sql::load_snapshot( + &mut super::executor::ConnectionExecutor::(&mut connection), + identity, + ) + .await } } @@ -91,18 +82,14 @@ where identity: &'a StreamIdentity, ) -> impl Future> + Send + 'a { async move { - let mut builder = - QueryBuilder::::new("DELETE FROM aggregate_snapshots WHERE aggregate_type = "); - builder.push_bind(identity.aggregate_type()); - builder.push(" AND aggregate_id = "); - builder.push_bind(identity.aggregate_id()); - let result = builder - .build() - .execute(&self.pool) - .await - .map_err(|err| repository_storage_error::("delete snapshot", err))?; - - Ok(DB::rows_affected(&result) > 0) + let mut connection = self.pool.acquire().await.map_err(|error| { + repository_storage_error::("acquire snapshot connection", error) + })?; + crate::repository::sql::delete_snapshot( + &mut super::executor::ConnectionExecutor::(&mut connection), + identity, + ) + .await } } } @@ -115,64 +102,19 @@ where DB: SqlxRepoBackend, for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, + for<'r> &'r str: sqlx::ColumnIndex, for<'q> &'q str: Encode<'q, DB> + Type, for<'q> &'q [u8]: Encode<'q, DB> + Type, { - validate_snapshot_identity(identity, &record)?; - - let metadata = serialize_event_metadata(&record.metadata)?; - let recorded_at = DB::timestamp_value(record.recorded_at)?; - let version = repository_i64_from_u64( - DB::BACKEND, - record.version, - "snapshot version", - DB::INTEGER_STORAGE, - )?; - let snapshot_version = repository_i64_from_u64( - DB::BACKEND, - record.snapshot_version, - "snapshot payload version", - DB::INTEGER_STORAGE, - )?; - - let mut builder = QueryBuilder::::new( - "INSERT INTO aggregate_snapshots (\ - aggregate_type, aggregate_id, version, snapshot_version, payload, \ - payload_codec, payload_codec_version, metadata, recorded_at) VALUES (", - ); - { - let mut row = builder.separated(", "); - row.push_bind(identity.aggregate_type()) - .push_bind(identity.aggregate_id()) - .push_bind(version) - .push_bind(snapshot_version) - .push_bind(record.payload.as_slice()) - .push_bind(record.payload_codec.as_str()) - .push_bind(i64::from(record.payload_codec_version)); - DB::push_metadata(&mut row, metadata.as_str()); - DB::push_timestamp(&mut row, &recorded_at); - } - builder.push( - ") ON CONFLICT(aggregate_type, aggregate_id) DO UPDATE SET \ - version = excluded.version, \ - snapshot_version = excluded.snapshot_version, \ - payload = excluded.payload, \ - payload_codec = excluded.payload_codec, \ - payload_codec_version = excluded.payload_codec_version, \ - metadata = excluded.metadata, \ - recorded_at = excluded.recorded_at, \ - updated_at = ", - ); - builder.push(DB::NOW); - - builder - .build() - .execute(&mut **tx) - .await - .map_err(|err| repository_storage_error::("save snapshot", err))?; - - Ok(()) + crate::repository::sql::save_snapshot( + &mut super::executor::ConnectionExecutor::(&mut **tx), + identity, + &record, + ) + .await } pub(super) fn snapshot_from_row(row: DB::Row) -> Result where @@ -182,44 +124,5 @@ where for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'r> &'r str: sqlx::ColumnIndex, { - let metadata_json: String = row - .try_get("metadata") - .map_err(|err| repository_storage_error::("decode snapshot metadata row", err))?; - Ok(SnapshotRecord { - aggregate_type: row.try_get("aggregate_type").map_err(|err| { - repository_storage_error::("decode snapshot aggregate type row", err) - })?, - aggregate_id: row.try_get("aggregate_id").map_err(|err| { - repository_storage_error::("decode snapshot aggregate id row", err) - })?, - version: repository_u64_from_i64( - DB::BACKEND, - row.try_get("version").map_err(|err| { - repository_storage_error::("decode snapshot version row", err) - })?, - "snapshot version", - )?, - snapshot_version: repository_u64_from_i64( - DB::BACKEND, - row.try_get("snapshot_version").map_err(|err| { - repository_storage_error::("decode snapshot payload version row", err) - })?, - "snapshot payload version", - )?, - payload_codec: row.try_get("payload_codec").map_err(|err| { - repository_storage_error::("decode snapshot payload codec row", err) - })?, - payload_codec_version: repository_u16_from_i64( - DB::BACKEND, - row.try_get("payload_codec_version").map_err(|err| { - repository_storage_error::("decode snapshot payload codec version row", err) - })?, - "snapshot payload codec version", - )?, - payload: row - .try_get("payload") - .map_err(|err| repository_storage_error::("decode snapshot payload row", err))?, - metadata: deserialize_event_metadata(&metadata_json)?, - recorded_at: DB::decode_timestamp(&row, "recorded_at")?, - }) + crate::repository::sql::snapshot_from_row(&super::executor::EventRow::(row)) } diff --git a/src/sqlx_repo/repo/streams.rs b/src/sqlx_repo/repo/streams.rs index 7dfd9c70f..89b2ff515 100644 --- a/src/sqlx_repo/repo/streams.rs +++ b/src/sqlx_repo/repo/streams.rs @@ -19,32 +19,15 @@ where identity: &'a StreamIdentity, ) -> impl Future, RepositoryError>> + Send + 'a { async move { - let mut builder = QueryBuilder::::new("SELECT "); - builder.push(DB::EVENT_SELECT); - builder.push(" FROM aggregate_events WHERE aggregate_type = "); - builder.push_bind(identity.aggregate_type()); - builder.push(" AND aggregate_id = "); - builder.push_bind(identity.aggregate_id()); - builder.push(" ORDER BY sequence ASC"); - let rows = builder - .build() - .fetch_all(&self.pool) - .await - .map_err(|err| repository_storage_error::("load stream", err))?; - - if rows.is_empty() { - return Ok(None); - } - - let mut events = Vec::with_capacity(rows.len()); - for row in rows { - events.push(event_from_row::(row)?); - } - - let mut entity = Entity::new(); - entity.set_id(identity.aggregate_id()); - entity.load_from_history(events); - Ok(Some(entity)) + let mut connection = self.pool.acquire().await.map_err(|error| { + repository_storage_error::("acquire stream connection", error) + })?; + crate::repository::sql::load_stream( + &mut super::executor::ConnectionExecutor::(&mut connection), + identity, + None, + ) + .await } } @@ -112,56 +95,15 @@ where after_version: u64, ) -> impl Future, RepositoryError>> + Send + 'a { async move { - // Fetch only the post-snapshot tail. `after_version` is the snapshot - // version (an event sequence); `sequence > ?` skips already-folded - // rows so a fresh snapshot over a long stream no longer reads and - // decodes the entire history. - let after = repository_i64_from_u64( - DB::BACKEND, - after_version, - "snapshot tail lower bound", - DB::INTEGER_STORAGE, - )?; - let mut builder = QueryBuilder::::new("SELECT "); - builder.push(DB::EVENT_SELECT); - builder.push(" FROM aggregate_events WHERE aggregate_type = "); - builder.push_bind(identity.aggregate_type()); - builder.push(" AND aggregate_id = "); - builder.push_bind(identity.aggregate_id()); - builder.push(" AND sequence > "); - builder.push_bind(after); - builder.push(" ORDER BY sequence ASC"); - let rows = builder - .build() - .fetch_all(&self.pool) - .await - .map_err(|err| repository_storage_error::("load stream tail", err))?; - - let mut events = Vec::with_capacity(rows.len()); - for row in rows { - events.push(event_from_row::(row)?); - } - - // Empty tail is "snapshot current", "snapshot ahead of the stream", - // or "no event rows" (sqlite hardening deletes pre-snapshot rows). - // MAX(sequence) distinguishes a planted future snapshot (clamp) from - // a snapshot-only load (no rows → keep after_version). - let prefix = if events.is_empty() { - let stream_version = - super::commit::stream_version::(&self.pool, identity).await?; - if stream_version == 0 { - after_version - } else { - after_version.min(stream_version) - } - } else { - after_version - }; - - let mut entity = Entity::new(); - entity.set_id(identity.aggregate_id()); - entity.load_tail_from_history(events, prefix); - Ok(Some(entity)) + let mut connection = self.pool.acquire().await.map_err(|error| { + repository_storage_error::("acquire stream tail connection", error) + })?; + crate::repository::sql::load_stream( + &mut super::executor::ConnectionExecutor::(&mut connection), + identity, + Some(after_version), + ) + .await } } } From 5c3a2e0d1f4b17edfe95500abe135047738c1d5c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 03:43:57 -0500 Subject: [PATCH 019/484] fix!: retain cell replay evidence in command receipts Capture bounded projection inputs with the terminal command receipt in the domain commit. Return them from CellDispatchResult and stop the Worker response path scanning retained outbox messages. BREAKING CHANGE: successful cell command replay payloads now contain the result and projection inputs. Old stored successful receipts require explicit handling; no legacy replay fallback is provided. The public HTTP envelope is unchanged. Regression: restart with events and receipts but no outbox history; replay the same result and nonempty evidence without new events or publication. All 787 SQLite-feature library tests pass; celld Worker wasm check passes. Physical outbox deletion and SQL cell activation remain pending. --- src/microsvc/cell_host/causal.rs | 42 ++++++++++--- src/microsvc/cell_host/tests.rs | 100 ++++++++++++++++++++++++++++++- src/microsvc/cell_host/wire.rs | 6 +- src/microsvc/service/routes.rs | 15 ++++- tests/celld/README.md | 13 ++++ tests/celld/worker/src/lib.rs | 26 ++------ 6 files changed, 170 insertions(+), 32 deletions(-) diff --git a/src/microsvc/cell_host/causal.rs b/src/microsvc/cell_host/causal.rs index a27a3ecd4..df11ae6f7 100644 --- a/src/microsvc/cell_host/causal.rs +++ b/src/microsvc/cell_host/causal.rs @@ -7,8 +7,20 @@ use std::time::Duration; +use serde::{Deserialize, Serialize}; use serde_json::Value; +use super::CellProjectionEventWireItem; + +/// Bounded retry material, owned by the command ledger and expired with its +/// replay retention. It is not an outbox record or an event history archive. +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct CellCommandReplay { + pub payload: Value, + pub events: Vec, +} + use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalTransactionalCommit, CommandAttempt, CommandId, CommandLedgerError, CommandLedgerKey, CommandLedgerState, CommandLedgerStore, CommandLookup, @@ -68,6 +80,7 @@ impl CellCommandIdentity { #[derive(Clone, Debug, PartialEq)] pub struct CellDispatchResult { payload: Value, + events: Vec, command_id: String, causation_id: String, state: String, @@ -75,6 +88,11 @@ pub struct CellDispatchResult { } impl CellDispatchResult { + /// Exact confirmation evidence retained with this command's retry receipt. + /// Delivery may have already removed all of the command's outbox rows. + pub fn projection_events(&self) -> &[CellProjectionEventWireItem] { + &self.events + } pub fn payload(&self) -> &Value { &self.payload } @@ -189,13 +207,23 @@ pub(crate) fn replay_result( CommandLedgerState::Succeeded | CommandLedgerState::SucceededPendingProjection | CommandLedgerState::Atomic - | CommandLedgerState::ProjectionFailed => Ok(CellDispatchResult { - payload: replay.outcome, - command_id: replay.command_id.as_str().to_string(), - causation_id: replay.causation_id.as_str().to_string(), - state: replay.state.as_str().to_string(), - replayed, - }), + | CommandLedgerState::ProjectionFailed => { + let receipt: CellCommandReplay = + serde_json::from_value(replay.outcome).map_err(|error| { + CellDispatchError::Internal(format!("invalid cell command replay: {error}")) + })?; + // Validate persisted data just as strictly as the initial response. + super::parse_cell_projection_events(&serde_json::json!({ "events": receipt.events })) + .map_err(CellDispatchError::Internal)?; + Ok(CellDispatchResult { + payload: receipt.payload, + events: receipt.events, + command_id: replay.command_id.as_str().to_string(), + causation_id: replay.causation_id.as_str().to_string(), + state: replay.state.as_str().to_string(), + replayed, + }) + } CommandLedgerState::Rejected => replay_rejection(replay.outcome), CommandLedgerState::InProgress | CommandLedgerState::RetryableUnknown diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index fca410105..f93c682f4 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -24,7 +24,7 @@ struct CellItem { done: bool, } -#[sourced(entity, aggregate_type = "CellItem")] +#[sourced(entity, aggregate_type = "CellItem", events = "CellItemEvent")] impl CellItem { #[event("cell_item.created", version = 1)] fn create(&mut self, id: String, title: String) { @@ -37,6 +37,12 @@ impl CellItem { fn complete(&mut self) { self.done = true; } + + #[event("cell_item.published", version = 1, domain = event)] + fn publish(&mut self, id: String, title: String) { + self.entity.set_id(id); + self.title = title; + } } #[derive(Debug, Deserialize, crate::CommandInput)] @@ -134,6 +140,91 @@ fn owner_session() -> Session { session } +struct Publish; + +impl PortableCommand for Publish +where + D: crate::microsvc::CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + "cell_item.publish", + )) + .guarded( + |ctx: &CausalCommandContext<'_, CellItem>| ctx.session().user_id().is_some(), + handle_publish, + ) + } +} + +async fn handle_publish( + ctx: &CausalCommandContext<'_, CellItem>, + input: CreateInput, +) -> Result>, HandlerError> { + let repo = ctx.repo(); + let mut item = repo.create(); + item.publish(input.id.clone(), input.title) + .map_err(|error| HandlerError::Rejected(error.to_string()))?; + repo.publish_events() + .commit(item)? + .succeeded(CreatePayload { id: input.id }) +} + +#[tokio::test] +async fn command_replay_retains_confirmation_evidence_without_outbox_history() { + let cell = AggregateCell::::new("published-item") + .unwrap() + .mount(Publish); + let identity = CellCommandIdentity::new( + "cell-test-service", + "principal-alice", + "0190a000-0000-7000-8000-000000000405", + ) + .unwrap(); + let input = json!({ "id": "published-item", "title": "once" }); + let first = cell + .dispatch_idempotent( + "cell_item.publish", + &identity, + input.clone(), + owner_session(), + ) + .await + .unwrap(); + assert_eq!(first.projection_events().len(), 1); + assert_eq!( + first.projection_events()[0].event_type, + "cell_item.published" + ); + assert_eq!(cell.durable_outbox().unwrap().len(), 1); + + // Restore only domain history and the receipt, as after a completed drain. + // The retry must not require a single delivery record to be retained. + let reopened = AggregateCell::::new("published-item") + .unwrap() + .mount(Publish); + reopened + .restore_durable_events(cell.durable_events().unwrap()) + .unwrap(); + reopened + .restore_durable_commands(cell.durable_commands().unwrap()) + .unwrap(); + assert!(reopened.durable_outbox().unwrap().is_empty()); + let replay = reopened + .dispatch_idempotent("cell_item.publish", &identity, input, owner_session()) + .await + .unwrap(); + assert!(replay.replayed()); + assert_eq!(replay.payload(), first.payload()); + assert_eq!(replay.projection_events(), first.projection_events()); + assert!( + reopened.durable_outbox().unwrap().is_empty(), + "replay must not republish" + ); + assert_eq!(reopened.durable_events().unwrap()[0].events.len(), 1); +} + fn fn_send_sync(_: &T) {} #[tokio::test] @@ -304,6 +395,7 @@ async fn cell_wait_path_replays_the_same_command_without_new_domain_effects() { assert!(replay.replayed()); assert_eq!(replay.payload(), first.payload()); assert_eq!(replay.causation_id(), first.causation_id()); + assert_eq!(replay.projection_events(), first.projection_events()); let events = cell.durable_events().unwrap(); assert_eq!( events @@ -341,6 +433,12 @@ async fn cell_wait_path_replays_the_same_command_without_new_domain_effects() { .expect("durable replay after restart"); assert!(replay_after_restart.replayed()); assert_eq!(replay_after_restart.causation_id(), first.causation_id()); + assert!(restored.durable_outbox().unwrap().is_empty()); + assert_eq!( + replay_after_restart.projection_events(), + first.projection_events(), + "confirmation evidence must survive restart with no outbox history" + ); assert_eq!( restored .durable_events() diff --git a/src/microsvc/cell_host/wire.rs b/src/microsvc/cell_host/wire.rs index 59d55c2c3..a81bb4f38 100644 --- a/src/microsvc/cell_host/wire.rs +++ b/src/microsvc/cell_host/wire.rs @@ -18,7 +18,7 @@ const MAX_METADATA_VALUE_BYTES: usize = 1024; /// /// This is not a delivery record. Delivery status, leases, attempts, and /// settlement belong exclusively to the cell's durable outbox and Queue. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CellProjectionEventWireItem { pub id: String, @@ -149,8 +149,8 @@ pub fn parse_cell_projection_events( } /// Select the exact events committed by one causal command and encode them as -/// delivery-neutral projection evidence. Published rows remain valid evidence; -/// Queue settlement must not erase the data needed by optimistic replicas. +/// delivery-neutral projection evidence before commit. Store the result with +/// the command receipt; never recover it by retaining delivered outbox rows. pub fn cell_projection_event_evidence( messages: &[OutboxMessage], causation_id: &str, diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 2f610443b..8f190deac 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -1722,10 +1722,23 @@ where } let fence = attempt.fence(); + let replay = crate::microsvc::cell_host::causal::CellCommandReplay { + payload: replay_payload.clone(), + events: batch + .outbox_messages + .iter() + .map(crate::microsvc::cell_host::CellProjectionEventWireItem::from_message) + .collect(), + }; + let replay = serde_json::to_value(replay).map_err(|error| { + CellDispatchError::Internal(format!( + "cell command replay could not be encoded: {error}" + )) + })?; let completion = attempt .complete( TerminalCommandState::Succeeded, - replay_payload.clone(), + replay, policy.replay_retention, ) .map_err(crate::microsvc::cell_host::causal::internal_ledger_error)?; diff --git a/tests/celld/README.md b/tests/celld/README.md index 06b54c4cf..8ef92f2a6 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -52,6 +52,19 @@ The e2e-celld host wires that one route to `BusPublisher`. Kafka, RabbitMQ, and Knative use the same Queue consumer and relay contract; only the native `BusPublisher` changes. +## Command retry receipts + +The wait-path response gets its projection inputs from +`CellDispatchResult::projection_events()`, stored atomically with the command's +terminal retry receipt. It does not scan the outbox. A retry therefore returns +the same result and projection inputs even when delivery has removed the outbox +rows. Receipt evidence follows the existing command replay retention; event +history belongs in the event store, not in delivery records. + +This changes the internal successful cell replay payload. Previously persisted +successful receipts are not silently accepted as the new format. The public +HTTP response shape is unchanged. + ## Queue naming and sharding The producer binding name is local to the Worker and may be any valid binding diff --git a/tests/celld/worker/src/lib.rs b/tests/celld/worker/src/lib.rs index d1cb36f47..ce9360f6d 100644 --- a/tests/celld/worker/src/lib.rs +++ b/tests/celld/worker/src/lib.rs @@ -7,10 +7,9 @@ use chat_domain::{post, ChatMessage, ChatMessageState}; use distributed::cell_host::{ - cell_projection_event_evidence, AggregateCell, CellCommandIdentity, CellDispatchError, - CellDispatchResult, CellWaitPathRequest, CelldOutbox, DurableAggregateCellState, - InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, - CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, + AggregateCell, CellCommandIdentity, CellDispatchError, CellDispatchResult, CellWaitPathRequest, + CelldOutbox, DurableAggregateCellState, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, + CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, }; use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; use serde::de::DeserializeOwned; @@ -361,7 +360,7 @@ async fn post_chat( Ok(dispatch) => { seal_chat_from_load(cell).await; persist_and_drain_cell(sql, storage, env, cell).await?; - let events = projection_events_wire(cell, dispatch.causation_id())?; + let events = serde_json::to_value(dispatch.projection_events())?; wait_path_ok(dispatch.payload().clone(), &dispatch, 201, events) } Err(error) => { @@ -462,19 +461,6 @@ fn wait_path_ok( ) } -fn projection_events_wire(cell: &AggregateCell, causation_id: &str) -> Result -where - A: distributed::Aggregate + Send + Sync + 'static, -{ - let rows = cell - .durable_outbox() - .map_err(|error| Error::RustError(error.to_string()))?; - serde_json::to_value( - cell_projection_event_evidence(&rows, causation_id).map_err(Error::RustError)?, - ) - .map_err(|error| Error::RustError(error.to_string())) -} - async fn create_todo( sql: &SqlStorage, storage: &Storage, @@ -512,7 +498,7 @@ async fn create_todo( Ok(dispatch) => { seal_from_load(cell).await; persist_and_drain_cell(sql, storage, env, cell).await?; - let events = projection_events_wire(cell, dispatch.causation_id())?; + let events = serde_json::to_value(dispatch.projection_events())?; wait_path_ok( http_from_command(id, dispatch.payload(), &title), &dispatch, @@ -564,7 +550,7 @@ async fn transition_todo( Ok(dispatch) => { seal_from_load(cell).await; persist_and_drain_cell(sql, storage, env, cell).await?; - let events = projection_events_wire(cell, dispatch.causation_id())?; + let events = serde_json::to_value(dispatch.projection_events())?; let title = cell .load() .await From 76437893afec88eea24cf3e2434116f9c64beadb Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 04:20:57 -0500 Subject: [PATCH 020/484] fix!: delete delivered outbox rows through shared SQL operations Keep event history and command replay receipts separate from delivery work. Preserve lease/attempt fencing and verify actual bus delivery in runtime tests. Implements [[tasks/distributed-cell-sqlite-persistence-1]] --- README.md | 13 +- src/bus/in_memory_bus.rs | 11 + src/microsvc/cell_host/celld_outbox.rs | 2 +- src/microsvc/cell_host/sql_executor.rs | 11 + src/microsvc/runtime.rs | 118 ++--- src/outbox_worker/drain.rs | 20 +- src/outbox_worker/mod.rs | 1 - src/outbox_worker/outbox_dispatch.rs | 10 +- src/outbox_worker/outbox_source.rs | 8 +- src/outbox_worker/store/api.rs | 2 + src/outbox_worker/store/in_memory.rs | 10 +- src/outbox_worker/store/tests.rs | 8 +- src/repository/sql.rs | 7 + src/repository/sql/outbox.rs | 446 ++++++++++++++++++ src/repository/sqlite_codec.rs | 1 + src/sqlite_repo/mod.rs | 141 +----- src/sqlx_repo/mod.rs | 27 +- src/sqlx_repo/read_model/mod.rs | 9 +- src/sqlx_repo/read_model/validation.rs | 8 - src/sqlx_repo/repo/backend.rs | 3 - src/sqlx_repo/repo/executor.rs | 17 +- src/sqlx_repo/repo/mod.rs | 16 +- src/sqlx_repo/repo/outbox.rs | 372 ++------------- tests/durable_enqueue_sqlite/main.rs | 54 ++- .../outbox.rs | 34 +- tests/postgres_transport/main.rs | 15 +- tests/todos/main.rs | 14 +- tests/transport_conformance/mod.rs | 12 +- 28 files changed, 671 insertions(+), 719 deletions(-) create mode 100644 src/repository/sql/outbox.rs diff --git a/README.md b/README.md index 7b2ad1c49..574a91454 100644 --- a/README.md +++ b/README.md @@ -728,6 +728,17 @@ CQRS is the architectural split between write-side aggregates and query-side rea Published messages are a separate boundary. An aggregate event record is not automatically a domain event. When other services, projections, or transports need a fact or command, create an `OutboxMessage` and commit it with the aggregate. The outbox payload can represent a domain event, integration event, command, or any other transport message. +The outbox stores delivery work, not publication history. Successful delivery +deletes the row under its active lease. Failed or ambiguous sends retain the row +for retry or inspection. A crash after transport acceptance but before deletion +can deliver the same event ID again; consumers must remain idempotent. Event +history belongs in the event store, and command retry results belong in command +receipts. Neither depends on retaining delivered outbox rows. + +In v5, `OutboxStore::complete` and `complete_many` remove delivered rows instead +of retaining `Published` records. Repeating settlement of a removed row returns +`NotFound`; stale claims on existing rows still return `InvalidState`. + The existing names and serialized fields such as `EventRecord::event_name` remain part of the compatibility contract. Terminology cleanup should clarify usage without renaming stored event records unless a migration path is explicitly designed. ## Pluggable by Default @@ -1384,7 +1395,7 @@ in `bus` (no concrete broker dependency). **Two confirmation thresholds** (do not collapse them): -1. **Producer publish** — when an outbox row may be marked published (SQL commit, +1. **Producer publish** — when an outbox row may be deleted (SQL commit, broker confirm/ack, Knative 2xx, in-memory accept). Unknown outcomes stay retryable. 2. **Consumer ack** — only after the handler (and optional inbox receipt) committed. Never silently ack a handler error. diff --git a/src/bus/in_memory_bus.rs b/src/bus/in_memory_bus.rs index 2a76f974e..db517d1aa 100644 --- a/src/bus/in_memory_bus.rs +++ b/src/bus/in_memory_bus.rs @@ -82,6 +82,17 @@ impl InMemoryBus { Ok(()) } + #[cfg(test)] + pub(crate) fn published_ids(&self) -> Vec { + self.topics + .lock() + .expect("test topic lock") + .values() + .flat_map(|messages| messages.iter()) + .filter_map(|message| message.id().map(str::to_owned)) + .collect() + } + #[cfg(test)] pub(crate) fn ordered_topic_evidence(&self, name: &str, position: u64) -> OrderedDelivery { OrderedDelivery::new( diff --git a/src/microsvc/cell_host/celld_outbox.rs b/src/microsvc/cell_host/celld_outbox.rs index 06a5bb90d..63672695e 100644 --- a/src/microsvc/cell_host/celld_outbox.rs +++ b/src/microsvc/cell_host/celld_outbox.rs @@ -488,7 +488,7 @@ mod tests { ); let states = states.lock().unwrap(); assert_eq!(states[0].outbox[0].status, OutboxMessageStatus::Pending); - assert_eq!(states[1].outbox[0].status, OutboxMessageStatus::Published); + assert!(states[1].outbox.is_empty()); }); } diff --git a/src/microsvc/cell_host/sql_executor.rs b/src/microsvc/cell_host/sql_executor.rs index 18d374614..9c394e7a5 100644 --- a/src/microsvc/cell_host/sql_executor.rs +++ b/src/microsvc/cell_host/sql_executor.rs @@ -173,6 +173,16 @@ impl CellSqlExecutor { let mut bindings = Vec::new(); for part in statement.0 { match part { + SqlPart::TimestampCompare { + column, + operator, + value, + } => { + sql.push_str(&format!( + "CAST({column} AS REAL) {operator} CAST(? AS REAL)" + )); + bindings.push(SqlStorageValue::String(sqlite_codec::encode(value)?)); + } SqlPart::LedgerNow | SqlPart::LedgerNowEpoch => { sql.push_str("unixepoch('now','subsec')") } @@ -220,6 +230,7 @@ impl SqlExecutor for CellSqlExecutor { type Row = CellSqlRow; const EVENT_SELECT: &'static str = sqlite_codec::EVENT_SELECT; const SNAPSHOT_SELECT: &'static str = sqlite_codec::SNAPSHOT_SELECT; + const OUTBOX_SELECT: &'static str = sqlite_codec::OUTBOX_SELECT; const NOW: &'static str = "CURRENT_TIMESTAMP"; const COMMAND_LEDGER_SELECT: &'static str = sqlite_codec::COMMAND_LEDGER_SELECT; const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = ""; diff --git a/src/microsvc/runtime.rs b/src/microsvc/runtime.rs index 25b77d9d3..330e778f9 100644 --- a/src/microsvc/runtime.rs +++ b/src/microsvc/runtime.rs @@ -166,23 +166,29 @@ mod tests { use crate::microsvc::{Context, HandlerError, Routes, Service, Session}; use crate::outbox_worker::OutboxStore; - async fn wait_until_published(store: &impl OutboxStore, count: usize) { + async fn assert_published_and_drained(store: &impl OutboxStore, bus: &InMemoryBus, id: &str) { tokio::time::timeout(std::time::Duration::from_secs(1), async { loop { - if store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap() - .len() - >= count - { + // Delivery evidence is in the bus, not in deleted outbox rows. + let delivered = bus.published_ids().iter().any(|actual| actual == id); + let mut remaining = 0; + for status in [ + OutboxMessageStatus::Pending, + OutboxMessageStatus::InFlight, + OutboxMessageStatus::Failed, + OutboxMessageStatus::Published, + ] { + remaining += store.messages_by_status(status, 8).await.unwrap().len(); + } + if delivered && remaining == 0 { break; } tokio::task::yield_now().await; } }) .await - .expect("immediate publish should settle outbox rows"); + .expect("bus must receive the event and outbox must remove its row"); + assert_eq!(bus.published_ids(), vec![id.to_string()]); } use crate::{ sourced, AggregateBuilder, AggregateRepository, Entity, InMemoryRepository, OutboxMessage, @@ -221,6 +227,7 @@ mod tests { #[tokio::test] async fn with_bus_configures_outbox_for_all_eligible_route_bundles() { + let bus = InMemoryBus::new(); let repo_a = InMemoryRepository::new(); let store_a = repo_a.outbox_store(); let repo_b = InMemoryRepository::new(); @@ -238,7 +245,7 @@ mod tests { .command("dummy.touch.b") .handle(touch_and_publish), ) - .with_bus(InMemoryBus::new()); + .with_bus(bus.clone()); service .dispatch("dummy.touch.a", json!({}), Session::new()) @@ -249,32 +256,8 @@ mod tests { .await .unwrap(); - wait_until_published(&store_a, 1).await; - wait_until_published(&store_b, 1).await; - - let published_a = store_a - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!( - published_a.len(), - 1, - "first route bundle should publish at commit time" - ); - assert_eq!(published_a[0].id(), "evt-1"); - assert!(store_a.pending(usize::MAX).await.unwrap().is_empty()); - - let published_b = store_b - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!( - published_b.len(), - 1, - "second route bundle should publish at commit time" - ); - assert_eq!(published_b[0].id(), "evt-1"); - assert!(store_b.pending(usize::MAX).await.unwrap().is_empty()); + assert_published_and_drained(&store_a, &bus, "evt-1").await; + assert_published_and_drained(&store_b, &bus, "evt-1").await; } #[tokio::test] @@ -313,6 +296,7 @@ mod tests { #[tokio::test] async fn dispatch_through_a_handler_publishes_immediately() { + let bus = InMemoryBus::new(); let repo = InMemoryRepository::new(); let store = repo.outbox_store(); let service = Service::new() @@ -322,7 +306,7 @@ mod tests { .command("dummy.touch") .handle(touch_and_publish), ) - .with_bus(InMemoryBus::new()); + .with_bus(bus.clone()); // The handler runs `outbox().commit()`: pending row, then the // bounded worker publishes through the attached bus. @@ -331,14 +315,7 @@ mod tests { .await .unwrap(); - wait_until_published(&store, 1).await; - let published = store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!(published.len(), 1, "row should be published immediately"); - assert_eq!(published[0].id(), "evt-1"); - assert!(store.pending(usize::MAX).await.unwrap().is_empty()); + assert_published_and_drained(&store, &bus, "evt-1").await; } #[tokio::test] @@ -360,17 +337,7 @@ mod tests { // `run` returns once the queue is empty (InMemoryBus yields `None`). bus.send("dummy.touch", b"{}".to_vec()).await.unwrap(); service.run(RunOptions::idempotent()).await.unwrap(); - wait_until_published(&store, 1).await; - - let published = store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!( - published.len(), - 1, - "run() should consume the command and publish its outbox row" - ); + assert_published_and_drained(&store, &bus, "evt-1").await; } #[tokio::test] @@ -383,30 +350,15 @@ mod tests { .push(OutboxMessage::create("evt-left", "dummy.touched", b"{}".to_vec()).unwrap()); repo.commit_batch(batch).await.unwrap(); + let bus = InMemoryBus::new(); let handle = Service::outbox_drain( - store, - crate::BusPublisher::new(std::sync::Arc::new(InMemoryBus::new())), + store.clone(), + crate::BusPublisher::new(std::sync::Arc::new(bus.clone())), 5, ) .with_poll_interval(std::time::Duration::from_millis(5)) .spawn(); - tokio::time::timeout(std::time::Duration::from_secs(1), async { - loop { - if repo - .outbox_store() - .messages_by_status(OutboxMessageStatus::Published, 8) - .await - .unwrap() - .len() - == 1 - { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(5)).await; - } - }) - .await - .expect("Service::outbox_drain should publish leftover rows"); + assert_published_and_drained(&store, &bus, "evt-left").await; handle.stop().await.unwrap(); } @@ -438,6 +390,7 @@ mod tests { #[tokio::test] async fn outbox_commit_publishes_with_snapshot_backed_repo() { + let bus = InMemoryBus::new(); // `outbox().commit()` must work for a snapshot-backed repository too: the // outbox row and the snapshot commit together in one transaction, then // the row publishes immediately. @@ -450,23 +403,12 @@ mod tests { .command("snap.touch") .handle(touch_snap), ) - .with_bus(InMemoryBus::new()); + .with_bus(bus.clone()); service .dispatch("snap.touch", json!({}), Session::new()) .await .unwrap(); - wait_until_published(&store, 1).await; - - let published = store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!( - published.len(), - 1, - "snapshot-backed outbox commit should publish immediately" - ); - assert_eq!(published[0].id(), "evt-s1"); + assert_published_and_drained(&store, &bus, "evt-s1").await; } } diff --git a/src/outbox_worker/drain.rs b/src/outbox_worker/drain.rs index c2b025049..253c61168 100644 --- a/src/outbox_worker/drain.rs +++ b/src/outbox_worker/drain.rs @@ -358,15 +358,6 @@ mod tests { crate::outbox_worker::testing::block_on(future) } - fn load(repo: &InMemoryRepository, id: &str) -> OutboxMessage { - repo.outbox_storage() - .read() - .unwrap() - .get(id) - .unwrap() - .clone() - } - #[tokio::test] async fn immediate_publish_leaves_nothing_for_the_drainer() { let repo = InMemoryRepository::new(); @@ -384,7 +375,7 @@ mod tests { .await .unwrap(); assert_eq!(outcome.published, 1); - assert_eq!(load(&repo, &id).status, OutboxMessageStatus::Published); + assert!(!repo.outbox_storage().read().unwrap().contains_key(&id)); let drain = OutboxDrainRunner::new(OutboxDispatcher::new( repo.outbox_store(), @@ -423,10 +414,11 @@ mod tests { .await .expect("drain should publish the unclaimed row"); handle.stop().await.unwrap(); - assert_eq!( - load(&repo, "evt-crash").status, - OutboxMessageStatus::Published - ); + assert!(!repo + .outbox_storage() + .read() + .unwrap() + .contains_key("evt-crash")); } #[tokio::test] diff --git a/src/outbox_worker/mod.rs b/src/outbox_worker/mod.rs index 3abd9520c..6bd02d011 100644 --- a/src/outbox_worker/mod.rs +++ b/src/outbox_worker/mod.rs @@ -45,7 +45,6 @@ mod store; pub(crate) mod testing; // Repository helpers -#[cfg(any(feature = "postgres", feature = "sqlite"))] pub(crate) use store::ensure_active_claim; pub use store::{ ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxPublishFailureAction, diff --git a/src/outbox_worker/outbox_dispatch.rs b/src/outbox_worker/outbox_dispatch.rs index 34d6b78f2..166f7e23f 100644 --- a/src/outbox_worker/outbox_dispatch.rs +++ b/src/outbox_worker/outbox_dispatch.rs @@ -596,7 +596,7 @@ mod tests { ); // The publisher saw the message id, and the row is completed only after. assert_eq!(dispatcher.publisher.ids(), vec!["evt-1".to_string()]); - assert!(load(&repo, &id).is_published()); + assert!(!repo.outbox_storage().read().unwrap().contains_key(&id)); } #[test] @@ -640,7 +640,7 @@ mod tests { assert_eq!(outcome.claimed, 1); assert_eq!(outcome.published, 1); - assert!(load(&repo, &wanted).is_published()); + assert!(!repo.outbox_storage().read().unwrap().contains_key(&wanted)); // The unrequested row is untouched. assert!(load(&repo, &other).is_pending()); } @@ -723,8 +723,8 @@ mod tests { assert_eq!(outcome.claimed, 3); assert_eq!(outcome.published, 2); assert_eq!(outcome.released, 1); - assert!(load(&repo, "evt-1").is_published()); - assert!(load(&repo, "evt-3").is_published()); + assert!(!repo.outbox_storage().read().unwrap().contains_key("evt-1")); + assert!(!repo.outbox_storage().read().unwrap().contains_key("evt-3")); // The failed row is released for retry, untouched by the batched complete. let failed = load(&repo, "evt-2"); assert!(failed.is_pending()); @@ -745,7 +745,7 @@ mod tests { assert_eq!(outcome.claimed, 3); assert_eq!(outcome.published, 3); for id in ["evt-1", "evt-2", "evt-3"] { - assert!(load(&repo, id).is_published()); + assert!(!repo.outbox_storage().read().unwrap().contains_key(id)); } assert_eq!(dispatcher.publisher.ids().len(), 3); } diff --git a/src/outbox_worker/outbox_source.rs b/src/outbox_worker/outbox_source.rs index 361120a91..33a5527f3 100644 --- a/src/outbox_worker/outbox_source.rs +++ b/src/outbox_worker/outbox_source.rs @@ -256,7 +256,7 @@ mod tests { let mut src = source(&repo); let received = block_on(src.recv()).unwrap().unwrap(); block_on(received.ack()).unwrap(); - assert_eq!(status(&repo, "m1"), Some(OutboxMessageStatus::Published)); + assert_eq!(status(&repo, "m1"), None); } #[test] @@ -308,8 +308,8 @@ mod tests { let mut ids = handled.lock().unwrap().clone(); ids.sort(); assert_eq!(ids, vec!["m1".to_string(), "m2".to_string()]); - assert_eq!(status(&repo, "m1"), Some(OutboxMessageStatus::Published)); - assert_eq!(status(&repo, "m2"), Some(OutboxMessageStatus::Published)); + assert_eq!(status(&repo, "m1"), None); + assert_eq!(status(&repo, "m2"), None); } #[test] @@ -327,6 +327,6 @@ mod tests { ), ); block_on(run_source(service, source(&repo), RunOptions::idempotent())).unwrap(); - assert_eq!(status(&repo, "m1"), Some(OutboxMessageStatus::Published)); + assert_eq!(status(&repo, "m1"), None); } } diff --git a/src/outbox_worker/store/api.rs b/src/outbox_worker/store/api.rs index 75e21b608..4229f8874 100644 --- a/src/outbox_worker/store/api.rs +++ b/src/outbox_worker/store/api.rs @@ -156,6 +156,8 @@ pub trait OutboxStore: Send + Sync { request: ClaimOutboxMessages, ) -> impl Future, RepositoryError>> + Send + 'a; + /// Delete a delivered row while holding its active claim. The outbox is + /// pending delivery work, not a publication-history or replay store. fn complete<'a>( &'a self, claim: &'a OutboxClaimRef, diff --git a/src/outbox_worker/store/in_memory.rs b/src/outbox_worker/store/in_memory.rs index 13a2c718a..b58aedcee 100644 --- a/src/outbox_worker/store/in_memory.rs +++ b/src/outbox_worker/store/in_memory.rs @@ -127,13 +127,7 @@ impl OutboxStore for InMemoryOutboxStore { &'a self, claim: &'a OutboxClaimRef, ) -> impl Future> + Send + 'a { - async move { - self.update_outbox_message(&claim.message_id, |message| { - ensure_active_claim(message, Some(claim), crate::time::now())?; - message.complete()?; - Ok(()) - }) - } + async move { self.complete_many(std::slice::from_ref(claim)).await } } /// Batched complete under a single write lock instead of one lock @@ -161,7 +155,7 @@ impl OutboxStore for InMemoryOutboxStore { } })?; ensure_active_claim(message, Some(claim), now)?; - message.complete()?; + storage.remove(&claim.message_id); } Ok(()) } diff --git a/src/outbox_worker/store/tests.rs b/src/outbox_worker/store/tests.rs index 51f5be0cd..fbd42a7e2 100644 --- a/src/outbox_worker/store/tests.rs +++ b/src/outbox_worker/store/tests.rs @@ -471,7 +471,7 @@ async fn complete_many_completes_the_whole_batch() { store.complete_many(&claims).await.unwrap(); for id in ["msg-1", "msg-2", "msg-3"] { - assert!(load_message(&repo, id).is_published()); + assert!(!repo.outbox_storage().read().unwrap().contains_key(id)); } } @@ -496,9 +496,9 @@ async fn complete_many_rejects_stale_and_missing_claims() { let claims = vec![OutboxClaimRef::from_message(&claimed[0]).unwrap()]; store.complete_many(&claims).await.unwrap(); - // Re-settling the now-published row is a stale claim, same as `complete`. + // Re-settling a deleted delivery row is NotFound, same as `complete`. let err = store.complete_many(&claims).await.unwrap_err(); - assert!(matches!(err, RepositoryError::InvalidState { .. })); + assert!(matches!(err, RepositoryError::NotFound { .. })); let missing = vec![OutboxClaimRef { message_id: "missing".into(), @@ -529,5 +529,5 @@ async fn already_published_message_is_not_completed_again() { store.complete(&claim).await.unwrap(); let err = store.complete(&claim).await.unwrap_err(); - assert!(matches!(err, RepositoryError::InvalidState { .. })); + assert!(matches!(err, RepositoryError::NotFound { .. })); } diff --git a/src/repository/sql.rs b/src/repository/sql.rs index 391628ae7..e6482c910 100644 --- a/src/repository/sql.rs +++ b/src/repository/sql.rs @@ -11,6 +11,7 @@ use std::future::Future; use std::time::{Duration, SystemTime}; pub(crate) mod ledger; +pub(crate) mod outbox; use crate::entity::{Entity, EventRecord, BITCODE_PAYLOAD_CODEC}; use crate::snapshot::SnapshotRecord; @@ -51,6 +52,11 @@ pub(crate) enum SqlPart<'a> { LedgerDeadline(Duration), LedgerDeadlineIsLive(SystemTime), LedgerJson(String), + TimestampCompare { + column: &'static str, + operator: &'static str, + value: SystemTime, + }, } /// Structural statements: values are never interpolated into SQL text. The @@ -108,6 +114,7 @@ pub(crate) trait SqlExecutor: Send { type Row: SqlRow; const EVENT_SELECT: &'static str; const SNAPSHOT_SELECT: &'static str; + const OUTBOX_SELECT: &'static str; const NOW: &'static str; const COMMAND_LEDGER_SELECT: &'static str; const COMMAND_LEDGER_LOCK_SUFFIX: &'static str; diff --git a/src/repository/sql/outbox.rs b/src/repository/sql/outbox.rs new file mode 100644 index 000000000..438a04d84 --- /dev/null +++ b/src/repository/sql/outbox.rs @@ -0,0 +1,446 @@ +//! Delivery rows shared by native SQL and cell-local SQL. Transactions belong +//! to the caller, so these inserts join the command's event and receipt writes. + +use super::{json_error, signed, unsigned, SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; +use crate::outbox::{OutboxMessage, OutboxMessageStatus}; +use crate::outbox_worker::{ensure_active_claim, ClaimOutboxMessages, OutboxClaimRef}; +use crate::repository::{sqlite_codec, RepositoryError}; +use std::borrow::Cow; +use std::time::SystemTime; + +pub(crate) struct OutboxInsert<'a> { + pub statement: Statement<'a>, + pub first_id: &'a str, +} + +fn optional(value: Option>) -> SqlPart<'_> { + value + .map(SqlPart::Bind) + .unwrap_or_else(|| SqlPart::Sql("NULL".into())) +} + +/// Borrow payloads and emit at most nineteen bindings per row. Optional NULLs +/// are SQL literals, never stringified values or untyped driver bindings. +pub(crate) fn inserts( + messages: &[OutboxMessage], + max_bind_params: usize, +) -> Result>, RepositoryError> { + const COLUMNS: usize = 19; + if max_bind_params < COLUMNS { + return Err(RepositoryError::Model( + "SQL executor cannot bind one outbox row".into(), + )); + } + let mut result = Vec::new(); + for chunk in messages.chunks(max_bind_params / COLUMNS) { + let mut statement = Statement::new("INSERT INTO outbox_messages (message_id, event_type, payload, payload_codec, payload_codec_version, destination, metadata, status, created_at, next_available_at, claimed_by, claimed_until, attempts, last_error, source_aggregate_type, source_aggregate_id, source_sequence, correlation_id, causation_id) VALUES "); + for (index, message) in chunk.iter().enumerate() { + if index != 0 { + statement.push(", "); + } + statement.push("("); + let values = [ + Some(SqlBind::from(message.id())), + Some(SqlBind::from(message.event_type.as_str())), + Some(SqlBind::Bytes(Cow::Borrowed(&message.payload))), + Some(SqlBind::from(message.payload_codec.as_str())), + Some(SqlBind::Integer(i64::from(message.payload_codec_version))), + message.destination.as_deref().map(SqlBind::from), + Some(SqlBind::Metadata( + serde_json::to_string(&message.metadata).map_err(json_error)?, + )), + Some(SqlBind::from(message.status.as_str())), + Some(SqlBind::Timestamp(message.created_at)), + Some(SqlBind::Timestamp(message.created_at)), + message.worker_id.as_deref().map(SqlBind::from), + message.leased_until.map(SqlBind::Timestamp), + Some(SqlBind::Integer(i64::from(message.attempts))), + message.last_error.as_deref().map(SqlBind::from), + message.source_aggregate_type.as_deref().map(SqlBind::from), + message.source_aggregate_id.as_deref().map(SqlBind::from), + message + .source_sequence + .map(|value| signed(value, "outbox source sequence").map(SqlBind::Integer)) + .transpose()?, + message.correlation_id().map(SqlBind::from), + message.causation_id().map(SqlBind::from), + ]; + for (column, value) in values.into_iter().enumerate() { + if column != 0 { + statement.push(", "); + } + statement.part(optional(value)); + } + statement.push(")"); + } + result.push(OutboxInsert { + statement, + first_id: chunk[0].id(), + }); + } + Ok(result) +} + +pub(crate) fn from_row(row: impl SqlRow) -> Result { + let status_text = row.text("status")?; + let status = status_text + .parse::() + .map_err(|_| RepositoryError::Model(format!("outbox status `{status_text}` is invalid")))?; + let mut metadata: std::collections::HashMap = + serde_json::from_str(&row.text("metadata")?).map_err(json_error)?; + for column in ["correlation_id", "causation_id"] { + if let Some(value) = row.optional_text(column)? { + metadata.insert(column.into(), value); + } + } + Ok(OutboxMessage { + id: row.text("message_id")?, + event_type: row.text("event_type")?, + payload: row.bytes("payload")?, + payload_codec: row.text("payload_codec")?, + payload_codec_version: u16::try_from(row.integer("payload_codec_version")?) + .map_err(|_| RepositoryError::Model("invalid outbox payload codec version".into()))?, + status, + metadata, + created_at: row.timestamp("created_at")?, + worker_id: row.optional_text("claimed_by")?, + leased_until: row.optional_timestamp("claimed_until")?, + attempts: u32::try_from(row.integer("attempts")?) + .map_err(|_| RepositoryError::Model("invalid outbox attempts".into()))?, + last_error: row.optional_text("last_error")?, + destination: row.optional_text("destination")?, + source_aggregate_type: row.optional_text("source_aggregate_type")?, + source_aggregate_id: row.optional_text("source_aggregate_id")?, + source_sequence: row + .optional_integer("source_sequence")? + .map(|value| unsigned(value, "outbox source sequence")) + .transpose()?, + }) +} + +fn sqlite_claimable(statement: &mut Statement<'_>, now: SystemTime) { + statement.push("((status = 'pending' AND CAST(next_available_at AS REAL) <= CAST("); + statement.push_bind(SqlBind::Timestamp(now)); + statement.push(" AS REAL)) OR (status = 'in_flight' AND (claimed_until IS NULL OR CAST(claimed_until AS REAL) <= CAST("); + statement.push_bind(SqlBind::Timestamp(now)); + statement.push(" AS REAL))))"); +} + +fn destination(statement: &mut Statement<'_>, request: &ClaimOutboxMessages) { + if let Some(destination) = request.destination.as_deref() { + statement.push(" AND destination = "); + statement.push_bind(destination); + } +} + +/// SQLite has no row-lock/SKIP LOCKED claim. Both SQLx SQLite and cells use +/// this candidate scan plus conditional update in a caller-owned transaction. +pub(crate) async fn claim_sqlite( + executor: &mut impl SqlExecutor, + request: ClaimOutboxMessages, + now: SystemTime, +) -> Result, RepositoryError> { + if request.batch_size == 0 { + return Ok(Vec::new()); + } + let deadline = now + .checked_add(request.lease) + .ok_or_else(|| RepositoryError::Model("failed to compute outbox lease deadline".into()))?; + let ids = if let Some(ids) = request.message_ids.clone() { + ids + } else { + let mut query = Statement::new("SELECT message_id FROM outbox_messages WHERE "); + sqlite_claimable(&mut query, now); + destination(&mut query, &request); + query.push(" ORDER BY CAST(created_at AS REAL) ASC, message_id ASC LIMIT "); + query.push_bind(signed(request.batch_size as u64, "outbox claim limit")?); + executor + .query(query) + .await? + .into_iter() + .map(|row| row.text("message_id")) + .collect::, _>>()? + }; + let mut claimed = Vec::new(); + for id in ids { + if claimed.len() >= request.batch_size { + break; + } + let mut update = + Statement::new("UPDATE outbox_messages SET status = 'in_flight', claimed_by = ") + .bind(request.worker_id.as_str().into()) + .sql(", claimed_until = ") + .bind(SqlBind::Timestamp(deadline)) + .sql( + ", attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE message_id = ", + ) + .bind(id.as_str().into()) + .sql(" AND "); + sqlite_claimable(&mut update, now); + destination(&mut update, &request); + if executor.execute(update).await? == 0 { + continue; + } + let rows = executor + .query( + Statement::new("SELECT ") + .sql(sqlite_codec::OUTBOX_SELECT) + .sql(" FROM outbox_messages WHERE message_id = ") + .bind(id.as_str().into()), + ) + .await?; + let row = rows + .into_iter() + .next() + .ok_or_else(|| RepositoryError::NotFound { id })?; + claimed.push(from_row(row)?); + } + Ok(claimed) +} + +pub(crate) enum Transition<'a> { + Complete, + Release(&'a str), + Fail(&'a str), +} + +/// Acknowledgement removes delivery work. Event history and command-replay +/// evidence are separate records and are never reconstructed from this table. +pub(crate) async fn transition( + executor: &mut E, + claim: &OutboxClaimRef, + transition: Transition<'_>, + now: SystemTime, +) -> Result<(), RepositoryError> { + let mut statement = match transition { + Transition::Complete => Statement::new("DELETE FROM outbox_messages"), + Transition::Release(error) | Transition::Fail(error) => { + let released = matches!(transition, Transition::Release(_)); + let mut statement = Statement::new("UPDATE outbox_messages SET status = ") + .bind(if released { "pending" } else { "failed" }.into()) + .sql(", claimed_by = NULL, claimed_until = NULL, last_error = "); + statement.part(optional((!error.is_empty()).then(|| error.into()))); + statement.push(if released { + ", next_available_at = " + } else { + ", failed_at = " + }); + statement.push_bind(SqlBind::Timestamp(now)); + statement.push(", updated_at = "); + statement.push(E::NOW); + statement + } + }; + statement.push(" WHERE message_id = "); + statement.push_bind(claim.message_id.as_str()); + statement.push(" AND status = 'in_flight' AND claimed_by = "); + statement.push_bind(claim.worker_id.as_str()); + statement.push(" AND attempts = "); + statement.push_bind(i64::from(claim.attempt)); + statement.push(" AND claimed_until IS NOT NULL AND "); + statement.part(SqlPart::TimestampCompare { + column: "claimed_until", + operator: ">", + value: now, + }); + if executor.execute(statement).await? > 0 { + return Ok(()); + } + let row = executor + .query( + Statement::new("SELECT ") + .sql(E::OUTBOX_SELECT) + .sql(" FROM outbox_messages WHERE message_id = ") + .bind(claim.message_id.as_str().into()), + ) + .await? + .into_iter() + .next() + .ok_or_else(|| RepositoryError::NotFound { + id: claim.message_id.clone(), + })?; + let message = from_row(row)?; + ensure_active_claim(&message, Some(claim), now)?; + Err(RepositoryError::InvalidState { + id: claim.message_id.clone(), + expected: "settled outbox claim", + actual: "conditional settlement changed no row".into(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn insert_plans_bound_rows_and_borrow_payloads() { + let messages = (0..3) + .map(|n| { + OutboxMessage::create(format!("message-{n}"), "Changed", vec![7; 4096]).unwrap() + }) + .collect::>(); + let plans = inserts(&messages, 38).unwrap(); + assert_eq!(plans.len(), 2); + let payloads = plans + .iter() + .flat_map(|plan| &plan.statement.0) + .filter_map(|part| match part { + SqlPart::Bind(SqlBind::Bytes(Cow::Borrowed(bytes))) => Some(*bytes), + SqlPart::Bind(SqlBind::Bytes(Cow::Owned(_))) => panic!("payload was copied"), + _ => None, + }) + .collect::>(); + assert_eq!(payloads.len(), messages.len()); + for (payload, message) in payloads.iter().zip(&messages) { + assert_eq!(payload.as_ptr(), message.payload.as_ptr()); + } + for plan in &plans { + assert!( + plan.statement + .0 + .iter() + .filter(|part| matches!(part, SqlPart::Bind(_))) + .count() + <= 38 + ); + } + assert!(inserts(&messages, 18).is_err()); + let mut overflow = messages; + overflow[0].source_sequence = Some(u64::MAX); + assert!(inserts(&overflow, 38).is_err()); + } + + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn stale_ack_cannot_delete_reclaimed_work_and_delivery_keeps_event_history() { + use crate::sqlx_repo::repo::ConnectionExecutor; + use crate::{ + CommitBatch, Entity, GetStream, SqliteRepository, StreamIdentity, StreamWrite, + TransactionalCommit, + }; + use std::time::{Duration, UNIX_EPOCH}; + + let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let identity = StreamIdentity::new("Item", "one").unwrap(); + let mut entity = Entity::with_id("one"); + entity.digest_empty("created").unwrap(); + let mut message = OutboxMessage::create("event-1", "Created", b"payload".to_vec()).unwrap(); + let now = UNIX_EPOCH + Duration::from_secs(100); + message.created_at = now; + let mut batch = CommitBatch::new(vec![StreamWrite::new(identity.clone(), &mut entity)]); + batch.outbox_messages.push(message); + repo.commit_batch(batch).await.unwrap(); + + let mut tx = repo.pool().begin().await.unwrap(); + let first = claim_sqlite( + &mut ConnectionExecutor::(&mut tx), + ClaimOutboxMessages::new("same-worker", 1, Duration::from_secs(1)), + now, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + let first = OutboxClaimRef::from_message(&first[0]).unwrap(); + let expired = now + Duration::from_secs(1); + let mut tx = repo.pool().begin().await.unwrap(); + let second = claim_sqlite( + &mut ConnectionExecutor::(&mut tx), + ClaimOutboxMessages::new("same-worker", 1, Duration::from_secs(60)), + expired, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + assert_eq!(second[0].id(), first.message_id); + assert_eq!(second[0].attempts, first.attempt + 1); + assert_eq!(second[0].payload, b"payload"); + let second = OutboxClaimRef::from_message(&second[0]).unwrap(); + + let mut connection = repo.pool().acquire().await.unwrap(); + let mut executor = ConnectionExecutor::(&mut connection); + for action in [ + Transition::Complete, + Transition::Release("late"), + Transition::Fail("late"), + ] { + assert!(matches!( + transition(&mut executor, &first, action, expired).await, + Err(RepositoryError::InvalidState { .. }) + )); + } + assert_eq!( + executor + .query(Statement::new("SELECT message_id FROM outbox_messages")) + .await + .unwrap() + .len(), + 1 + ); + transition(&mut executor, &second, Transition::Complete, expired) + .await + .unwrap(); + assert!(executor + .query(Statement::new("SELECT message_id FROM outbox_messages")) + .await + .unwrap() + .is_empty()); + assert!(matches!( + transition(&mut executor, &second, Transition::Complete, expired).await, + Err(RepositoryError::NotFound { .. }) + )); + drop(connection); + let restored = repo.get_stream(&identity).await.unwrap().unwrap(); + assert_eq!(restored.version(), 1); + assert_eq!(restored.committed_version(), 1); + } + + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn delivery_settlement_rolls_back_with_its_transaction() { + use crate::sqlx_repo::repo::ConnectionExecutor; + use crate::{CommitBatch, OutboxStore, SqliteRepository, TransactionalCommit}; + use std::time::Duration; + let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let mut batch = CommitBatch::empty(); + batch + .outbox_messages + .push(OutboxMessage::create("event-1", "Changed", vec![]).unwrap()); + repo.commit_batch(batch).await.unwrap(); + let store = repo.outbox_store(); + let claimed = store + .claim(ClaimOutboxMessages::new( + "worker", + 1, + Duration::from_secs(60), + )) + .await + .unwrap(); + let claim = OutboxClaimRef::from_message(&claimed[0]).unwrap(); + let mut tx = repo.pool().begin().await.unwrap(); + transition( + &mut ConnectionExecutor::(&mut tx), + &claim, + Transition::Complete, + SystemTime::now(), + ) + .await + .unwrap(); + tx.rollback().await.unwrap(); + let remaining = store + .messages_by_status(OutboxMessageStatus::InFlight, 1) + .await + .unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(OutboxClaimRef::from_message(&remaining[0]).unwrap(), claim); + store.complete(&claim).await.unwrap(); + let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM outbox_messages") + .fetch_one(repo.pool()) + .await + .unwrap(); + assert_eq!(count, 0); + } +} diff --git a/src/repository/sqlite_codec.rs b/src/repository/sqlite_codec.rs index 9440b4c4b..34dd1257d 100644 --- a/src/repository/sqlite_codec.rs +++ b/src/repository/sqlite_codec.rs @@ -5,6 +5,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub(crate) const EVENT_SELECT: &str = "event_name, event_version, payload, payload_codec, payload_codec_version, metadata, sequence, recorded_at"; pub(crate) const SNAPSHOT_SELECT: &str = "aggregate_type, aggregate_id, version, snapshot_version, payload, payload_codec, payload_codec_version, metadata, recorded_at"; +pub(crate) const OUTBOX_SELECT: &str = "message_id, event_type, payload, payload_codec, payload_codec_version, metadata, status, created_at, claimed_by, claimed_until, attempts, last_error, destination, source_aggregate_type, source_aggregate_id, source_sequence, correlation_id, causation_id"; pub(crate) fn encode(timestamp: SystemTime) -> Result { let duration = timestamp.duration_since(UNIX_EPOCH).map_err(|error| { diff --git a/src/sqlite_repo/mod.rs b/src/sqlite_repo/mod.rs index aa83376d4..47f442246 100644 --- a/src/sqlite_repo/mod.rs +++ b/src/sqlite_repo/mod.rs @@ -19,18 +19,16 @@ use sqlx::query_builder::Separated; use sqlx::sqlite::SqliteRow; use sqlx::{QueryBuilder, Row, Sqlite, SqlitePool}; -use crate::outbox::{OutboxMessage, OutboxMessageStatus}; +use crate::outbox::OutboxMessage; use crate::outbox_worker::ClaimOutboxMessages; use crate::repository::RepositoryError; use crate::sqlx_repo::read_model::quote_identifier; use crate::sqlx_repo::repo::{ - embedded_migrator, outbox_message_by_id, system_time_epoch_secs, SqlxOutboxStore, - SqlxRepository, SQLITE_MIGRATIONS, + embedded_migrator, SqlxOutboxStore, SqlxRepository, SQLITE_MIGRATIONS, }; use crate::sqlx_repo::{ self, is_sqlite_unique_constraint, read_model_i64_from_u64 as sqlx_read_model_i64_from_u64, read_model_u64_from_i64 as sqlx_read_model_u64_from_i64, - repository_i64_from_u64 as sqlx_repository_i64_from_u64, }; use crate::table::TableSqlDialect; use crate::table::{ @@ -64,10 +62,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Sqlite { const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = ""; const EVENT_SELECT: &'static str = crate::repository::sqlite_codec::EVENT_SELECT; const SNAPSHOT_SELECT: &'static str = crate::repository::sqlite_codec::SNAPSHOT_SELECT; - const OUTBOX_SELECT: &'static str = "message_id, event_type, payload, payload_codec, \ - payload_codec_version, metadata, status, created_at, claimed_by, claimed_until, \ - attempts, last_error, destination, source_aggregate_type, source_aggregate_id, \ - source_sequence, correlation_id, causation_id"; + const OUTBOX_SELECT: &'static str = crate::repository::sqlite_codec::OUTBOX_SELECT; const ORDER_BY_CREATED_AT: &'static str = "CAST(created_at AS REAL)"; const OUTBOX_OLDEST_CREATED_AT_SELECT: &'static str = "MIN(CAST(created_at AS REAL)) AS oldest_created_at"; @@ -212,121 +207,23 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Sqlite { pool: &SqlitePool, request: ClaimOutboxMessages, ) -> Result, RepositoryError> { - { - if request.batch_size == 0 { - return Ok(Vec::new()); - } - - let now = SystemTime::now(); - let now_epoch = system_time_epoch_secs::(now)?; - let claimed_until = now.checked_add(request.lease).ok_or_else(|| { - RepositoryError::Model("failed to compute outbox lease deadline".into()) - })?; - let claimed_until_storage = system_time_to_storage(claimed_until)?; - - let mut tx = pool - .begin() - .await - .map_err(|err| repository_storage_error("begin outbox claim transaction", err))?; - - // Explicit ids (after-commit immediate dispatch) bypass the ordered - // candidate scan; the per-id conditional UPDATE below still enforces - // claimability and destination, so raced/unclaimable ids are skipped. - let candidate_ids: Vec = if let Some(ids) = request.message_ids.clone() { - ids - } else { - let limit = sqlx_repository_i64_from_u64( - SQLITE_BACKEND, - request.batch_size as u64, - "outbox claim limit", - SIGNED_INTEGER_STORAGE, - )?; - let candidate_rows = sqlx::query( - r#" - SELECT message_id - FROM outbox_messages - WHERE ( - (status = ? AND CAST(next_available_at AS REAL) <= ?) - OR (status = ? AND (claimed_until IS NULL OR CAST(claimed_until AS REAL) <= ?)) - ) - AND (? IS NULL OR destination = ?) - ORDER BY CAST(created_at AS REAL) ASC, message_id ASC - LIMIT ? - "#, - ) - .bind(OutboxMessageStatus::Pending.as_str()) - .bind(now_epoch) - .bind(OutboxMessageStatus::InFlight.as_str()) - .bind(now_epoch) - .bind(request.destination.as_deref()) - .bind(request.destination.as_deref()) - .bind(limit) - .fetch_all(&mut *tx) - .await - .map_err(|err| { - repository_storage_error("select claimable outbox messages", err) - })?; - let mut ids = Vec::with_capacity(candidate_rows.len()); - for row in candidate_rows { - ids.push(row.try_get::("message_id").map_err(|err| { - repository_storage_error("decode outbox message id row", err) - })?); - } - ids - }; - - let mut claimed = Vec::new(); - for message_id in candidate_ids { - if claimed.len() >= request.batch_size { - break; - } - let result = sqlx::query( - r#" - UPDATE outbox_messages - SET status = ?, - claimed_by = ?, - claimed_until = ?, - attempts = attempts + 1, - updated_at = CURRENT_TIMESTAMP - WHERE message_id = ? - AND ( - (status = ? AND CAST(next_available_at AS REAL) <= ?) - OR ( - status = ? - AND (claimed_until IS NULL OR CAST(claimed_until AS REAL) <= ?) - ) - ) - AND (? IS NULL OR destination = ?) - "#, - ) - .bind(OutboxMessageStatus::InFlight.as_str()) - .bind(&request.worker_id) - .bind(&claimed_until_storage) - .bind(&message_id) - .bind(OutboxMessageStatus::Pending.as_str()) - .bind(now_epoch) - .bind(OutboxMessageStatus::InFlight.as_str()) - .bind(now_epoch) - .bind(request.destination.as_deref()) - .bind(request.destination.as_deref()) - .execute(&mut *tx) - .await - .map_err(|err| repository_storage_error("claim outbox message", err))?; - - if result.rows_affected() == 0 { - continue; - } - - if let Some(message) = outbox_message_by_id(&mut *tx, &message_id).await? { - claimed.push(message); - } - } - - tx.commit() - .await - .map_err(|err| repository_storage_error("commit outbox claim transaction", err))?; - Ok(claimed) + if request.batch_size == 0 { + return Ok(Vec::new()); } + let mut tx = pool + .begin() + .await + .map_err(|error| repository_storage_error("begin outbox claim transaction", error))?; + let claimed = crate::repository::sql::outbox::claim_sqlite( + &mut crate::sqlx_repo::repo::ConnectionExecutor::(&mut tx), + request, + SystemTime::now(), + ) + .await?; + tx.commit() + .await + .map_err(|error| repository_storage_error("commit outbox claim transaction", error))?; + Ok(claimed) } } diff --git a/src/sqlx_repo/mod.rs b/src/sqlx_repo/mod.rs index b6af4bcc1..56da2af9e 100644 --- a/src/sqlx_repo/mod.rs +++ b/src/sqlx_repo/mod.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use crate::repository::RepositoryError; #[cfg(any(feature = "postgres", feature = "sqlite"))] use crate::table::TableStoreError; @@ -11,20 +9,7 @@ pub(crate) mod read_model; #[cfg(any(feature = "postgres", feature = "sqlite"))] pub(crate) mod repo; -pub(crate) fn serialize_event_metadata( - metadata: &HashMap, -) -> Result { - serde_json::to_string(metadata) - .map_err(|err| RepositoryError::Model(format!("serialize event metadata: {err}"))) -} - -pub(crate) fn deserialize_event_metadata( - metadata_json: &str, -) -> Result, RepositoryError> { - serde_json::from_str(metadata_json) - .map_err(|err| RepositoryError::Model(format!("deserialize event metadata: {err}"))) -} - +#[cfg(feature = "postgres")] pub(crate) fn repository_i64_from_u64( backend: &str, value: u64, @@ -45,16 +30,6 @@ pub(crate) fn repository_u64_from_i64( .map_err(|_| RepositoryError::Model(format!("{backend} {field} value {value} is negative"))) } -#[cfg(any(feature = "postgres", feature = "sqlite"))] -pub(crate) fn repository_u16_from_i64( - backend: &str, - value: i64, - field: &str, -) -> Result { - u16::try_from(value) - .map_err(|_| RepositoryError::Model(format!("{backend} {field} value {value} is invalid"))) -} - #[cfg(any(feature = "postgres", feature = "sqlite"))] pub(crate) fn read_model_i64_from_u64( backend: &str, diff --git a/src/sqlx_repo/read_model/mod.rs b/src/sqlx_repo/read_model/mod.rs index 7c8b97795..011e35ea2 100644 --- a/src/sqlx_repo/read_model/mod.rs +++ b/src/sqlx_repo/read_model/mod.rs @@ -28,11 +28,10 @@ pub(crate) use schema_registry::{ remember_read_model_schemas, resolve_registered_read_model_schemas, IncludeSpec, }; pub(crate) use validation::{ - belongs_to_target_column, column_by_name, empty_string_as_none, initial_row_version, - patch_values_preserving_key, quote_identifier, row_concurrency_conflict, - row_values_from_key_and_patch, row_write_values, sql_read_model_capabilities, - validate_row_expected_version, validate_sql_write_plan, validate_values_match_key, - version_column, + belongs_to_target_column, column_by_name, initial_row_version, patch_values_preserving_key, + quote_identifier, row_concurrency_conflict, row_values_from_key_and_patch, row_write_values, + sql_read_model_capabilities, validate_row_expected_version, validate_sql_write_plan, + validate_values_match_key, version_column, }; pub(crate) use write_plan::{ apply_read_model_write_plan_in_tx, begin_read_model_tx, commit_read_model_tx, row_version_in_tx, diff --git a/src/sqlx_repo/read_model/validation.rs b/src/sqlx_repo/read_model/validation.rs index d4c6c95d0..4b65c54f3 100644 --- a/src/sqlx_repo/read_model/validation.rs +++ b/src/sqlx_repo/read_model/validation.rs @@ -162,14 +162,6 @@ pub(crate) fn belongs_to_target_column( Ok(target_schema.primary_key.columns[0].clone()) } -pub(crate) fn empty_string_as_none(value: &str) -> Option<&str> { - if value.is_empty() { - None - } else { - Some(value) - } -} - pub(crate) fn row_write_values<'schema>( schema: &'schema TableSchema, values: &RowValues, diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index d44b5ba9b..652c8b171 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -158,9 +158,6 @@ pub(super) fn ids_by_type(identities: &[StreamIdentity]) -> BTreeMap<&str, Vec<& groups } -/// Bound parameters per `outbox_messages` row. -pub(super) const OUTBOX_BIND_COLUMNS: usize = 19; - /// Dialect surface for the shared repository path (event store, snapshots, /// outbox lifecycle, consumer inbox, schema bootstrap). /// diff --git a/src/sqlx_repo/repo/executor.rs b/src/sqlx_repo/repo/executor.rs index cb1477f16..352f04d23 100644 --- a/src/sqlx_repo/repo/executor.rs +++ b/src/sqlx_repo/repo/executor.rs @@ -3,8 +3,8 @@ use super::*; use crate::repository::sql::{SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; -pub(super) struct ConnectionExecutor<'a, DB: SqlxRepoBackend>(pub &'a mut DB::Connection); -pub(super) struct EventRow(pub DB::Row); +pub(crate) struct ConnectionExecutor<'a, DB: SqlxRepoBackend>(pub &'a mut DB::Connection); +pub(crate) struct EventRow(pub DB::Row); impl SqlRow for EventRow where @@ -60,6 +60,18 @@ where let mut builder = QueryBuilder::::new(""); for part in &statement.0 { match part { + SqlPart::TimestampCompare { + column, + operator, + value, + } => { + DB::push_timestamp_cmp( + &mut builder, + column, + operator, + system_time_epoch_secs::(*value)?, + ); + } SqlPart::LedgerNow => DB::push_command_ledger_now(&mut builder), SqlPart::LedgerNowEpoch => DB::push_command_ledger_now_epoch(&mut builder), SqlPart::LedgerDeadline(value) => { @@ -108,6 +120,7 @@ where type Row = EventRow; const EVENT_SELECT: &'static str = DB::EVENT_SELECT; const SNAPSHOT_SELECT: &'static str = DB::SNAPSHOT_SELECT; + const OUTBOX_SELECT: &'static str = DB::OUTBOX_SELECT; const NOW: &'static str = DB::NOW; const COMMAND_LEDGER_SELECT: &'static str = DB::COMMAND_LEDGER_SELECT; const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = DB::COMMAND_LEDGER_LOCK_SUFFIX; diff --git a/src/sqlx_repo/repo/mod.rs b/src/sqlx_repo/repo/mod.rs index bfb431d99..194dd7556 100644 --- a/src/sqlx_repo/repo/mod.rs +++ b/src/sqlx_repo/repo/mod.rs @@ -34,9 +34,7 @@ use crate::command_ledger::{ }; use crate::entity::{Entity, EventRecord}; use crate::outbox::{OutboxMessage, OutboxMessageStatus}; -use crate::outbox_worker::{ - ensure_active_claim, ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxStore, -}; +use crate::outbox_worker::{ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxStore}; use crate::projection_protocol::{ProjectionChangeRetention, SameTransactionProjectionBatch}; use crate::read_model::{ReadModelLoadGraph, ReadModelLoadRequest, ReadModelQueryCapabilities}; use crate::repository::{ @@ -51,13 +49,10 @@ use crate::sqlx_repo::projection_protocol::{ }; use crate::sqlx_repo::read_model::{ apply_read_model_write_plan_in_tx, begin_read_model_tx, commit_read_model_tx, - empty_string_as_none, load_read_model_graph, remember_read_model_schemas, - sql_read_model_capabilities, validate_sql_write_plan, SqlxReadModelBackend, -}; -use crate::sqlx_repo::{ - audited_table_schema_sql, deserialize_event_metadata, repository_i64_from_u64, - repository_u16_from_i64, repository_u64_from_i64, serialize_event_metadata, + load_read_model_graph, remember_read_model_schemas, sql_read_model_capabilities, + validate_sql_write_plan, SqlxReadModelBackend, }; +use crate::sqlx_repo::{audited_table_schema_sql, repository_u64_from_i64}; use crate::table::{ generate_table_migration_artifacts, table_schema_bootstrap_result, table_schema_statements, TableMigrationArtifact, TableSchemaBootstrap, TableSchemaRegistry, TableSqlDialect, @@ -74,6 +69,7 @@ mod commit; mod errors; mod events; mod executor; +pub(crate) use executor::ConnectionExecutor; mod inbox; mod outbox; mod read_models; @@ -93,8 +89,6 @@ pub(crate) use backend::POSTGRES_MIGRATIONS; #[cfg(feature = "sqlite")] pub(crate) use backend::SQLITE_MIGRATIONS; pub(crate) use errors::{repository_storage_error, system_time_epoch_secs}; -#[cfg(feature = "sqlite")] -pub(crate) use outbox::outbox_message_by_id; #[cfg(feature = "postgres")] pub(crate) use outbox::outbox_message_from_row; pub use types::{SqlxOutboxStore, SqlxRepository}; diff --git a/src/sqlx_repo/repo/outbox.rs b/src/sqlx_repo/repo/outbox.rs index 952686878..67e3dfee3 100644 --- a/src/sqlx_repo/repo/outbox.rs +++ b/src/sqlx_repo/repo/outbox.rs @@ -1,30 +1,6 @@ use super::*; -/// One claimed-message lifecycle transition (the `UPDATE` shape is shared; only -/// the assignments differ). -enum OutboxTransition<'a> { - Complete, - Release { error: &'a str }, - Fail { error: &'a str }, -} - -impl OutboxTransition<'_> { - fn target_status(&self) -> OutboxMessageStatus { - match self { - OutboxTransition::Complete => OutboxMessageStatus::Published, - OutboxTransition::Release { .. } => OutboxMessageStatus::Pending, - OutboxTransition::Fail { .. } => OutboxMessageStatus::Failed, - } - } - - fn operation(&self) -> &'static str { - match self { - OutboxTransition::Complete => "complete outbox message", - OutboxTransition::Release { .. } => "release outbox message", - OutboxTransition::Fail { .. } => "fail outbox message", - } - } -} +use crate::repository::sql::outbox::Transition as OutboxTransition; impl OutboxStore for SqlxOutboxStore where @@ -122,7 +98,7 @@ where claim: &'a OutboxClaimRef, error: &'a str, ) -> impl Future> + Send + 'a { - transition_claimed_outbox_message(&self.pool, claim, OutboxTransition::Release { error }) + transition_claimed_outbox_message(&self.pool, claim, OutboxTransition::Release(error)) } fn fail<'a>( @@ -130,16 +106,11 @@ where claim: &'a OutboxClaimRef, error: &'a str, ) -> impl Future> + Send + 'a { - transition_claimed_outbox_message(&self.pool, claim, OutboxTransition::Fail { error }) + transition_claimed_outbox_message(&self.pool, claim, OutboxTransition::Fail(error)) } } -/// Apply one claimed-message lifecycle transition (complete / release / fail). -/// -/// The conditional `UPDATE` only applies while the caller still holds the -/// active claim (`status`, `claimed_by`, unexpired `claimed_until`, and -/// matching `attempts`); when no row is updated, the message is re-read to -/// produce the precise claim error. +/// Execute the shared, lease-fenced delivery transition on one connection. async fn transition_claimed_outbox_message<'a, DB>( pool: &'a Pool, claim: &'a OutboxClaimRef, @@ -147,154 +118,29 @@ async fn transition_claimed_outbox_message<'a, DB>( ) -> Result<(), RepositoryError> where DB: SqlxRepoBackend, - for<'c> &'c Pool: Executor<'c, Database = DB>, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> f64: Encode<'q, DB> + Type, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, - for<'q> Option: Encode<'q, DB> + Type, - for<'q> Option<&'q str>: Encode<'q, DB> + Type, + for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { - let now = SystemTime::now(); - let now_epoch = system_time_epoch_secs::(now)?; - let now_value = DB::timestamp_value(now)?; - - let mut builder = QueryBuilder::::new("UPDATE outbox_messages SET status = "); - builder.push_bind(transition.target_status().as_str()); - builder.push(", claimed_by = NULL, claimed_until = NULL, "); - match &transition { - OutboxTransition::Complete => { - builder.push("published_at = "); - DB::push_timestamp_assign(&mut builder, &now_value); - } - OutboxTransition::Release { error } => { - builder.push("next_available_at = "); - DB::push_timestamp_assign(&mut builder, &now_value); - builder.push(", last_error = "); - builder.push_bind(empty_string_as_none(error)); - } - OutboxTransition::Fail { error } => { - builder.push("last_error = "); - builder.push_bind(empty_string_as_none(error)); - builder.push(", failed_at = "); - DB::push_timestamp_assign(&mut builder, &now_value); - } - } - builder.push(", updated_at = "); - builder.push(DB::NOW); - builder.push(" WHERE message_id = "); - builder.push_bind(claim.message_id.as_str()); - builder.push(" AND status = "); - builder.push_bind(OutboxMessageStatus::InFlight.as_str()); - builder.push(" AND claimed_by = "); - builder.push_bind(claim.worker_id.as_str()); - builder.push(" AND claimed_until IS NOT NULL AND "); - DB::push_timestamp_cmp(&mut builder, "claimed_until", ">", now_epoch); - builder.push(" AND attempts = "); - builder.push_bind(repository_i64_from_u64( - DB::BACKEND, - u64::from(claim.attempt), - "outbox claim attempt", - DB::INTEGER_STORAGE, - )?); - - let result = builder - .build() - .execute(pool) + let mut connection = pool + .acquire() .await - .map_err(|err| repository_storage_error::(transition.operation(), err))?; - - ensure_outbox_update_applied( - pool, - DB::rows_affected(&result), - &claim.message_id, - |message| ensure_active_claim(message, Some(claim), now), + .map_err(|error| repository_storage_error::("acquire outbox connection", error))?; + crate::repository::sql::outbox::transition( + &mut executor::ConnectionExecutor::(&mut connection), + claim, + transition, + SystemTime::now(), ) .await } -/// Load an outbox message by id through any executor (pool or transaction). -pub(crate) async fn outbox_message_by_id<'e, DB, E>( - executor: E, - message_id: &str, -) -> Result, RepositoryError> -where - DB: SqlxRepoBackend, - E: Executor<'e, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> Vec: Type + sqlx::Decode<'q, DB>, - for<'q> &'q str: Encode<'q, DB> + Type, - for<'r> &'r str: sqlx::ColumnIndex, -{ - let mut builder = QueryBuilder::::new("SELECT "); - builder.push(DB::OUTBOX_SELECT); - builder.push(" FROM outbox_messages WHERE message_id = "); - builder.push_bind(message_id); - let row = builder - .build() - .fetch_optional(executor) - .await - .map_err(|err| repository_storage_error::("load outbox message", err))?; - row.map(outbox_message_from_row::).transpose() -} - -pub(crate) async fn ensure_outbox_update_applied( - pool: &Pool, - rows_affected: u64, - message_id: &str, - validate: impl FnOnce(&OutboxMessage) -> Result<(), RepositoryError>, -) -> Result<(), RepositoryError> -where - DB: SqlxRepoBackend, - for<'c> &'c Pool: Executor<'c, Database = DB>, - DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> String: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, - for<'q> Vec: Type + sqlx::Decode<'q, DB>, - for<'q> &'q str: Encode<'q, DB> + Type, - for<'r> &'r str: sqlx::ColumnIndex, -{ - if rows_affected > 0 { - return Ok(()); - } - - let message = outbox_message_by_id(pool, message_id) - .await? - .ok_or_else(|| RepositoryError::NotFound { - id: message_id.to_string(), - })?; - validate(&message) -} -/// One `outbox_messages` row with pre-validated bind values. -struct OutboxRow<'a, DB: SqlxRepoBackend> { - message_id: &'a str, - event_type: &'a str, - payload: &'a [u8], - payload_codec: &'a str, - payload_codec_version: i64, - destination: Option<&'a str>, - metadata: String, - status: &'a str, - created_at: DB::TimestampValue, - worker_id: Option<&'a str>, - leased_until: Option, - attempts: i64, - last_error: Option<&'a str>, - source_aggregate_type: Option<&'a str>, - source_aggregate_id: Option<&'a str>, - source_sequence: Option, - correlation_id: Option<&'a str>, - causation_id: Option<&'a str>, -} - -/// Insert every outbox message with multi-row INSERTs (chunked to respect the -/// backend's bound-parameter limit). A unique violation on `message_id` still -/// maps to `DuplicateOutboxMessageInBatch`. +/// Insert shared delivery-row plans in the command's existing transaction. pub(super) async fn insert_outbox_messages_in_tx( tx: &mut Transaction<'_, DB>, messages: &[OutboxMessage], @@ -303,101 +149,35 @@ where DB: SqlxRepoBackend, for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, DB::Arguments: IntoArguments, - for<'q> i64: Encode<'q, DB> + Type, - for<'q> Option: Encode<'q, DB> + Type, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'q> String: Type + sqlx::Decode<'q, DB>, + for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'q> &'q str: Encode<'q, DB> + Type, - for<'q> Option<&'q str>: Encode<'q, DB> + Type, for<'q> &'q [u8]: Encode<'q, DB> + Type, + for<'r> &'r str: sqlx::ColumnIndex, { - if messages.is_empty() { - return Ok(()); - } - - let mut rows = Vec::with_capacity(messages.len()); - for message in messages { - rows.push(OutboxRow:: { - message_id: message.id(), - event_type: &message.event_type, - payload: &message.payload, - payload_codec: &message.payload_codec, - payload_codec_version: i64::from(message.payload_codec_version), - destination: message.destination.as_deref(), - metadata: serialize_event_metadata(&message.metadata)?, - status: message.status.as_str(), - created_at: DB::timestamp_value(message.created_at)?, - worker_id: message.worker_id.as_deref(), - leased_until: message.leased_until.map(DB::timestamp_value).transpose()?, - attempts: i64::from(message.attempts), - last_error: message.last_error.as_deref(), - source_aggregate_type: message.source_aggregate_type.as_deref(), - source_aggregate_id: message.source_aggregate_id.as_deref(), - source_sequence: message - .source_sequence - .map(|value| { - repository_i64_from_u64( - DB::BACKEND, - value, - "outbox source sequence", - DB::INTEGER_STORAGE, - ) - }) - .transpose()?, - correlation_id: message.correlation_id(), - causation_id: message.causation_id(), - }); - } - - for chunk in rows.chunks(DB::MAX_BIND_PARAMS / OUTBOX_BIND_COLUMNS) { - let mut builder = QueryBuilder::::new( - "INSERT INTO outbox_messages (\ - message_id, event_type, payload, payload_codec, payload_codec_version, \ - destination, metadata, status, created_at, next_available_at, \ - claimed_by, claimed_until, attempts, last_error, source_aggregate_type, \ - source_aggregate_id, source_sequence, correlation_id, causation_id) ", - ); - builder.push_values(chunk, |mut row, message| { - row.push_bind(message.message_id) - .push_bind(message.event_type) - .push_bind(message.payload) - .push_bind(message.payload_codec) - .push_bind(message.payload_codec_version) - .push_bind(message.destination); - DB::push_metadata(&mut row, message.metadata.as_str()); - row.push_bind(message.status); - // created_at and next_available_at share the same value. - DB::push_timestamp(&mut row, &message.created_at); - DB::push_timestamp(&mut row, &message.created_at); - row.push_bind(message.worker_id); - DB::push_optional_timestamp(&mut row, message.leased_until.as_ref()); - row.push_bind(message.attempts) - .push_bind(message.last_error) - .push_bind(message.source_aggregate_type) - .push_bind(message.source_aggregate_id) - .push_bind(message.source_sequence) - .push_bind(message.correlation_id) - .push_bind(message.causation_id); - }); - - let result = builder.build().execute(&mut **tx).await; - if let Err(err) = result { - if DB::is_unique_violation(&err) { - // The batch was already deduped (validate_commit_batch), so a - // violation means the id collides with a previously committed - // row. Report the first id in the chunk, matching the per-row - // path's contract. + use crate::repository::sql::SqlExecutor; + use std::error::Error; + for insert in crate::repository::sql::outbox::inserts(messages, DB::MAX_BIND_PARAMS)? { + let result = executor::ConnectionExecutor::(&mut **tx) + .execute(insert.statement) + .await; + if let Err(error) = result { + if error + .source() + .and_then(|source| source.downcast_ref::()) + .is_some_and(DB::is_unique_violation) + { return Err(RepositoryError::DuplicateOutboxMessageInBatch { - id: chunk[0].message_id.to_string(), + id: insert.first_id.to_string(), }); } - return Err(repository_storage_error::( - "insert outbox messages", - err, - )); + return Err(error); } } - Ok(()) } + pub(crate) fn outbox_message_from_row(row: DB::Row) -> Result where DB: SqlxRepoBackend, @@ -406,85 +186,5 @@ where for<'q> Vec: Type + sqlx::Decode<'q, DB>, for<'r> &'r str: sqlx::ColumnIndex, { - let status_text: String = row - .try_get("status") - .map_err(|err| repository_storage_error::("decode outbox status row", err))?; - let status = status_text.parse::().map_err(|_| { - RepositoryError::Model(format!( - "{} outbox status `{status_text}` is invalid", - DB::BACKEND - )) - })?; - let metadata_json: String = row - .try_get("metadata") - .map_err(|err| repository_storage_error::("decode outbox metadata row", err))?; - let attempts: i64 = row - .try_get("attempts") - .map_err(|err| repository_storage_error::("decode outbox attempts row", err))?; - let source_sequence = row - .try_get::, _>("source_sequence") - .map_err(|err| repository_storage_error::("decode outbox source sequence row", err))? - .map(|value| repository_u64_from_i64(DB::BACKEND, value, "outbox source sequence")) - .transpose()?; - let mut metadata = deserialize_event_metadata(&metadata_json)?; - if let Some(correlation_id) = row - .try_get::, _>("correlation_id") - .map_err(|err| repository_storage_error::("decode outbox correlation_id row", err))? - { - metadata.insert("correlation_id".into(), correlation_id); - } - if let Some(causation_id) = row - .try_get::, _>("causation_id") - .map_err(|err| repository_storage_error::("decode outbox causation_id row", err))? - { - metadata.insert("causation_id".into(), causation_id); - } - - Ok(OutboxMessage { - id: row - .try_get("message_id") - .map_err(|err| repository_storage_error::("decode outbox message id row", err))?, - event_type: row - .try_get("event_type") - .map_err(|err| repository_storage_error::("decode outbox event type row", err))?, - payload: row - .try_get("payload") - .map_err(|err| repository_storage_error::("decode outbox payload row", err))?, - payload_codec: row.try_get("payload_codec").map_err(|err| { - repository_storage_error::("decode outbox payload codec row", err) - })?, - payload_codec_version: repository_u16_from_i64( - DB::BACKEND, - row.try_get("payload_codec_version").map_err(|err| { - repository_storage_error::("decode outbox payload codec version row", err) - })?, - "outbox payload codec version", - )?, - metadata, - status, - created_at: DB::decode_timestamp(&row, "created_at")?, - worker_id: row - .try_get("claimed_by") - .map_err(|err| repository_storage_error::("decode outbox claimed_by row", err))?, - leased_until: DB::decode_optional_timestamp(&row, "claimed_until")?, - attempts: u32::try_from(attempts).map_err(|_| { - RepositoryError::Model(format!( - "{} outbox attempts value {attempts} is invalid", - DB::BACKEND - )) - })?, - last_error: row - .try_get("last_error") - .map_err(|err| repository_storage_error::("decode outbox last_error row", err))?, - destination: row - .try_get("destination") - .map_err(|err| repository_storage_error::("decode outbox destination row", err))?, - source_aggregate_type: row.try_get("source_aggregate_type").map_err(|err| { - repository_storage_error::("decode outbox source aggregate type row", err) - })?, - source_aggregate_id: row.try_get("source_aggregate_id").map_err(|err| { - repository_storage_error::("decode outbox source aggregate id row", err) - })?, - source_sequence, - }) + crate::repository::sql::outbox::from_row(executor::EventRow::(row)) } diff --git a/tests/durable_enqueue_sqlite/main.rs b/tests/durable_enqueue_sqlite/main.rs index 3b3a49308..eb07fb074 100644 --- a/tests/durable_enqueue_sqlite/main.rs +++ b/tests/durable_enqueue_sqlite/main.rs @@ -8,12 +8,13 @@ use serde_json::{json, Value}; -use distributed::bus::{Bus, InMemoryBus, RunOptions}; +use distributed::bus::{Bus, BusConsumer, Handlers, InMemoryBus, Message, RunOptions}; use distributed::microsvc::{Context, HandlerError, HasOutboxStore, Routes, Service, Session}; use distributed::{ sourced, AggregateBuilder, AggregateRepository, Entity, OutboxMessage, OutboxMessageStatus, OutboxStore, Queueable, QueuedRepository, SqliteRepository, }; +use std::sync::{Arc, Mutex}; #[derive(Default)] struct Counter { @@ -49,16 +50,19 @@ async fn service() -> Repo { .aggregate::() } -async fn wait_until_published(store: &impl OutboxStore, count: usize) { +async fn assert_published_and_drained(store: &impl OutboxStore, bus: &InMemoryBus) { tokio::time::timeout(std::time::Duration::from_secs(1), async { loop { - if store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap() - .len() - >= count - { + let mut remaining = 0; + for status in [ + OutboxMessageStatus::Pending, + OutboxMessageStatus::InFlight, + OutboxMessageStatus::Failed, + OutboxMessageStatus::Published, + ] { + remaining += store.messages_by_status(status, 8).await.unwrap().len(); + } + if remaining == 0 { break; } tokio::task::yield_now().await; @@ -66,10 +70,24 @@ async fn wait_until_published(store: &impl OutboxStore, count: usize) { }) .await .expect("immediate publish should settle outbox rows"); + let delivered = Arc::new(Mutex::new(Vec::new())); + let record = delivered.clone(); + let handlers = Handlers::new().on_event("counter.touched", move |message: &Message| { + record + .lock() + .unwrap() + .push(message.id().unwrap().to_string()); + async { Ok(()) } + }); + bus.subscribe(Arc::new(handlers), RunOptions::idempotent()) + .await + .unwrap(); + assert_eq!(*delivered.lock().unwrap(), vec!["evt-c1".to_string()]); } #[tokio::test] async fn commit_publishes_immediately_over_sqlite() { + let bus = InMemoryBus::new(); let repo = service().await; let store = repo.outbox_store(); let service = Service::new() @@ -79,7 +97,7 @@ async fn commit_publishes_immediately_over_sqlite() { .command("counter.touch") .handle(handle_touch), ) - .with_bus(InMemoryBus::new()); + .with_bus(bus.clone()); // Command completion returns at durable commit; the bounded worker // claims the pending row and publishes it. @@ -88,13 +106,7 @@ async fn commit_publishes_immediately_over_sqlite() { .await .unwrap(); - wait_until_published(&store, 1).await; - let published = store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!(published.len(), 1, "row should be published immediately"); - assert_eq!(published[0].id(), "evt-c1"); + assert_published_and_drained(&store, &bus).await; assert!( store.pending(usize::MAX).await.unwrap().is_empty(), "nothing should be left for the poller" @@ -120,11 +132,5 @@ async fn run_consumes_command_and_publishes_over_sqlite() { bus.send("counter.touch", b"{}".to_vec()).await.unwrap(); service.run(RunOptions::idempotent()).await.unwrap(); - wait_until_published(&store, 1).await; - let published = store - .messages_by_status(OutboxMessageStatus::Published, usize::MAX) - .await - .unwrap(); - assert_eq!(published.len(), 1); - assert_eq!(published[0].id(), "evt-c1"); + assert_published_and_drained(&store, &bus).await; } diff --git a/tests/persistent_repository_conformance/outbox.rs b/tests/persistent_repository_conformance/outbox.rs index 593d0a635..b993cc8d9 100644 --- a/tests/persistent_repository_conformance/outbox.rs +++ b/tests/persistent_repository_conformance/outbox.rs @@ -223,10 +223,9 @@ where .complete(&claim) .await .expect("owning worker should complete the claim"); - let published = find_outbox_by_id(&outbox, &complete_message_id) + assert!(find_outbox_by_id(&outbox, &complete_message_id) .await - .expect("completed message should still be queryable"); - assert_eq!(published.status, OutboxMessageStatus::Published); + .is_none()); let retry_message_id = unique_id("retry-outbox"); commit_outbox_for_seat( @@ -375,20 +374,15 @@ where .await .expect("batched complete should settle every active claim"); for message_id in &message_ids { - let published = find_outbox_by_id(&outbox, message_id) - .await - .expect("completed message should still be queryable"); - assert_eq!(published.status, OutboxMessageStatus::Published); - assert_eq!(published.worker_id, None); + assert!(find_outbox_by_id(&outbox, message_id).await.is_none()); } - // Re-settling the now-published rows is a stale batch: same - // InvalidState surface as a serial `complete` of a settled row. + // Re-settling deleted delivery rows is NotFound, as with serial completion. let stale_err = outbox .complete_many(&claims) .await .expect_err("stale batch should not complete again"); - assert!(matches!(stale_err, RepositoryError::InvalidState { .. })); + assert!(matches!(stale_err, RepositoryError::NotFound { .. })); // An empty batch is a no-op, not an error. outbox @@ -461,14 +455,7 @@ where .complete(&claim_b) .await .expect("the reclaiming worker should complete the row"); - let published = find_outbox_by_id(&outbox, &message_id) - .await - .expect("reclaimed message should still be queryable"); - assert_eq!( - published.status, - OutboxMessageStatus::Published, - "row is published by the worker that reclaimed it, not by the crashed one" - ); + assert!(find_outbox_by_id(&outbox, &message_id).await.is_none()); } pub async fn publish_failure_after_commit_retains_outbox_row_until_delivered( @@ -526,14 +513,7 @@ pub async fn publish_failure_after_commit_retains_outbox_row_until_delivered OutboxMessage { +async fn load_outbox_message(repo: &InMemoryRepository, id: &str) -> Option { let store = repo.outbox_store(); for status in [ OutboxMessageStatus::Pending, @@ -83,10 +83,10 @@ async fn load_outbox_message(repo: &InMemoryRepository, id: &str) -> OutboxMessa .into_iter() .find(|message| message.id() == id) { - return message; + return Some(message); } } - panic!("outbox message `{id}` should exist") + None } #[tokio::test] @@ -263,9 +263,8 @@ async fn outbox_dispatch_publishes_and_completes_committed_row() { assert_eq!(sent.len(), 1); assert_eq!(sent[0].name(), "todo.initialized"); - // Check record is marked as published - let published = load_outbox_message(&repo, &message_id).await; - assert!(published.is_published()); + // Delivered work is removed; publication evidence belongs to the bus. + assert!(load_outbox_message(&repo, &message_id).await.is_none()); } #[tokio::test] @@ -519,8 +518,7 @@ async fn outbox_dispatch_drains_one_row_at_a_time() { assert_eq!(processed, 3); for id in &message_ids { - let message = load_outbox_message(&repo, id).await; - assert!(message.is_published()); + assert!(load_outbox_message(&repo, id).await.is_none()); } assert_eq!( repo.outbox_store().pending(usize::MAX).await.unwrap().len(), diff --git a/tests/transport_conformance/mod.rs b/tests/transport_conformance/mod.rs index 9762a5214..e030536d0 100644 --- a/tests/transport_conformance/mod.rs +++ b/tests/transport_conformance/mod.rs @@ -385,10 +385,7 @@ pub async fn dispatcher_completes_only_after_publish_success() { dispatcher.publisher().published_ids(), vec!["evt-1".to_string()] ); - assert_eq!( - outbox_status(&repo, &id).await, - Some(OutboxMessageStatus::Published) - ); + assert_eq!(outbox_status(&repo, &id).await, None); } pub async fn dispatcher_unknown_outcome_stays_retryable() { @@ -421,10 +418,7 @@ pub async fn dispatcher_claims_explicit_ids_before_publish() { .unwrap(); assert_eq!(outcome.claimed, 1); assert_eq!(outcome.published, 1); - assert_eq!( - outbox_status(&repo, &wanted).await, - Some(OutboxMessageStatus::Published) - ); + assert_eq!(outbox_status(&repo, &wanted).await, None); // The unrequested row is untouched (claimed before publish, by id). assert_eq!( outbox_status(&repo, &other).await, @@ -575,7 +569,7 @@ pub async fn publish_then_crash_republishes_and_consumer_inbox_dedupes() { assert_eq!(outcome.published, 1, "the reclaimed row is republished"); assert_eq!( outbox_status(&producer, &message_id).await, - Some(OutboxMessageStatus::Published), + None, "the row completes only after the successful pass" ); From 9c689a924f7a9b32d7814353a8590dba2a62a951 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 05:13:26 -0500 Subject: [PATCH 021/484] fix!: persist aggregate cells in transactional SQLite rows --- .github/workflows/integration-celld.yaml | 41 ++ build.rs | 7 +- src/aggregate/mod.rs | 2 +- src/aggregate/repository.rs | 58 +- src/command_ledger/traits.rs | 7 + src/in_memory_repo/repository.rs | 8 + src/microsvc/causal.rs | 16 +- src/microsvc/cell_host/cell.rs | 138 +++- src/microsvc/cell_host/celld_outbox.rs | 620 ++++++++---------- src/microsvc/cell_host/mod.rs | 8 +- src/microsvc/cell_host/sql_store.rs | 340 ++++++++++ src/microsvc/cell_host/store.rs | 282 +++----- src/microsvc/dependencies.rs | 96 ++- src/microsvc/service/causal.rs | 13 +- src/microsvc/service/routes.rs | 6 +- src/microsvc/service/tests.rs | 54 +- src/queued_repo/repository.rs | 8 + src/repository/migrations.rs | 20 + src/repository/mod.rs | 6 + src/snapshot/repository.rs | 118 +++- src/sqlx_repo/repo/backend.rs | 14 +- src/sqlx_repo/repo/streams.rs | 8 + tests/celld/README.md | 94 ++- tests/celld/main.rs | 19 +- tests/celld/storage-conformance.mjs | 219 +++++++ tests/celld/worker/Cargo.toml | 4 + tests/celld/worker/src/lib.rs | 212 ++---- tests/celld/worker/src/storage_conformance.rs | 79 +++ 28 files changed, 1685 insertions(+), 812 deletions(-) create mode 100644 src/microsvc/cell_host/sql_store.rs create mode 100644 src/repository/migrations.rs create mode 100644 tests/celld/storage-conformance.mjs create mode 100644 tests/celld/worker/src/storage_conformance.rs diff --git a/.github/workflows/integration-celld.yaml b/.github/workflows/integration-celld.yaml index f55f37481..6e340e983 100644 --- a/.github/workflows/integration-celld.yaml +++ b/.github/workflows/integration-celld.yaml @@ -25,6 +25,47 @@ env: DISTRIBUTED_INTERNAL_SECRET: test-only-internal-secret-change-me-2026 jobs: + storage: + name: celld SQL transactions and crash recovery + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + workspaces: tests/celld/worker -> tests/celld/worker/target + shared-key: celld-storage + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install test runtimes + run: | + sudo apt-get update && sudo apt-get install -y sqlite3 + npm install -g esbuild + cargo install worker-build --locked + curl -fsSL https://celld.dev/install.sh | sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Build isolated fault-probe Worker + working-directory: tests/celld/worker + run: worker-build --release --features storage-conformance + - name: Prove SQL atomicity, fencing, autonomous recovery and growth + run: node tests/celld/storage-conformance.mjs + - name: Retain storage proof results and logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: celld-storage-proof + path: | + /tmp/distributed-cell-storage-*/results.json + /tmp/distributed-cell-storage-*/celld-*.log + if-no-files-found: ignore + e2e-celld: name: e2e-celld workspace tests runs-on: ubuntu-latest diff --git a/build.rs b/build.rs index a0f3b91bb..c406446f3 100644 --- a/build.rs +++ b/build.rs @@ -161,9 +161,10 @@ fn emit_migration_inventory() { } fn emit_dialect(generated: &mut String, name: &str, dialect: Dialect, inventory: &Inventory) { - generated.push_str("#[cfg(feature = \""); - generated.push_str(dialect.name()); - generated.push_str("\")]\n"); + match dialect { + Dialect::Sqlite => generated.push_str("#[cfg(any(feature = \"sqlite\", all(feature = \"workers-rs\", target_arch = \"wasm32\")))]\n"), + Dialect::Postgres => generated.push_str("#[cfg(feature = \"postgres\")]\n"), + } generated.push_str("pub(crate) const "); generated.push_str(name); generated.push_str(": &[EmbeddedMigration] = &[\n"); diff --git a/src/aggregate/mod.rs b/src/aggregate/mod.rs index 8ee68cf1e..4c89b876b 100644 --- a/src/aggregate/mod.rs +++ b/src/aggregate/mod.rs @@ -2,5 +2,5 @@ mod aggregate; mod repository; pub use aggregate::{hydrate, Aggregate}; -pub(crate) use repository::SnapshotPolicy; pub use repository::{AggregateBuilder, AggregateRepository}; +pub(crate) use repository::{SnapshotPolicy, StreamReads}; diff --git a/src/aggregate/repository.rs b/src/aggregate/repository.rs index a2dc949dc..82aaf2f29 100644 --- a/src/aggregate/repository.rs +++ b/src/aggregate/repository.rs @@ -2,6 +2,7 @@ use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; +use crate::command_ledger::CausalGetStream; use crate::entity::Entity; use crate::outbox::OutboxPublisherConfig; use crate::queued_repo::{GetAllWithOpts, GetWithOpts, ReadOpts, UnlockableRepository}; @@ -69,10 +70,41 @@ type HydrateAllFn = type LoadFn = for<'a> fn( &'a R, &'a StreamIdentity, + StreamReads, ) -> Pin< Box, RepositoryError>> + Send + 'a>, >; +type StreamReadFuture<'a> = + Pin, RepositoryError>> + Send + 'a>>; + +/// The same snapshot algorithm uses ordinary or explicitly non-locking reads. +/// Capturing the functions keeps with_snapshots independent of causal bounds. +pub(crate) struct StreamReads { + pub full: for<'a> fn(&'a R, &'a StreamIdentity) -> StreamReadFuture<'a>, + pub tail: for<'a> fn(&'a R, &'a StreamIdentity, u64) -> StreamReadFuture<'a>, +} + +impl StreamReads { + fn ordinary() -> Self { + Self { + full: |repo, identity| Box::pin(repo.get_stream(identity)), + tail: |repo, identity, version| Box::pin(repo.get_stream_tail(identity, version)), + } + } +} + +impl StreamReads { + fn causal() -> Self { + Self { + full: |repo, identity| Box::pin(repo.get_causal_stream(identity)), + tail: |repo, identity, version| { + Box::pin(repo.get_causal_stream_tail(identity, version)) + }, + } + } +} + impl SnapshotPolicy { /// Construct a policy from its captured hooks. Called by `with_snapshots`, /// which carries the `Snapshottable`/`SnapshotStore`/`GetStream` bounds. @@ -192,6 +224,30 @@ where } } +impl AggregateRepository +where + A: Aggregate + Send, +{ + /// Causal handlers use the same snapshot policy, with non-locking reads. + pub(crate) async fn get_causal( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> + where + R: CausalGetStream, + { + match &self.snapshot { + Some(policy) => (policy.load)(&self.repo, identity, StreamReads::causal()).await, + None => self + .repo + .get_causal_stream(identity) + .await? + .map(hydrate::) + .transpose(), + } + } +} + impl AggregateRepository where R: GetStream, @@ -204,7 +260,7 @@ where // and decode of already-snapshotted events). Without one, a plain full // stream load. Same hydrated aggregate either way. match &self.snapshot { - Some(policy) => (policy.load)(&self.repo, &identity).await, + Some(policy) => (policy.load)(&self.repo, &identity, StreamReads::ordinary()).await, None => { let Some(entity) = self.repo.get_stream(&identity).await? else { return Ok(None); diff --git a/src/command_ledger/traits.rs b/src/command_ledger/traits.rs index bd678363a..76724d48a 100644 --- a/src/command_ledger/traits.rs +++ b/src/command_ledger/traits.rs @@ -16,6 +16,13 @@ pub(crate) trait CausalGetStream: Send + Sync { &'a self, identity: &'a StreamIdentity, ) -> impl Future, RepositoryError>> + Send + 'a; + + /// Fetch only the post-snapshot tail without retaining wrapper queue locks. + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl Future, RepositoryError>> + Send + 'a; } /// Proves that command reservation, stream loading, and causal commit are all diff --git a/src/in_memory_repo/repository.rs b/src/in_memory_repo/repository.rs index defa9a17f..69f90d742 100644 --- a/src/in_memory_repo/repository.rs +++ b/src/in_memory_repo/repository.rs @@ -588,6 +588,14 @@ impl GetStream for InMemoryRepository { } impl CausalGetStream for InMemoryRepository { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl std::future::Future, RepositoryError>> + Send + 'a + { + GetStream::get_stream_tail(self, identity, after_version) + } fn get_causal_stream<'a>( &'a self, identity: &'a StreamIdentity, diff --git a/src/microsvc/causal.rs b/src/microsvc/causal.rs index 267925999..966db41dd 100644 --- a/src/microsvc/causal.rs +++ b/src/microsvc/causal.rs @@ -16,7 +16,7 @@ use std::sync::Mutex; use serde::Serialize; -use crate::aggregate::{hydrate, Aggregate, AggregateRepository}; +use crate::aggregate::{Aggregate, AggregateRepository}; use crate::command::{ validate_resolved_direct_plan, Atomic, CommandCommitProofError, CommandOutcome, PrepareCommandError, PreparedCommand, ProjectionCommitProof, ResolvedDirectProjectionTarget, @@ -58,12 +58,7 @@ where A: Aggregate + Send + Sync + 'static, { fn load<'a>(&'a self, identity: &'a StreamIdentity) -> LoadAggregateFuture<'a, A> { - Box::pin(async move { - let Some(entity) = self.repository.repo().get_causal_stream(identity).await? else { - return Ok(None); - }; - hydrate::(entity).map(Some) - }) + Box::pin(async move { self.repository.get_causal(identity).await }) } fn snapshot_writes( @@ -1005,6 +1000,13 @@ mod tests { } impl CausalGetStream for TestRepo { + async fn get_causal_stream_tail( + &self, + _identity: &StreamIdentity, + _after_version: u64, + ) -> Result, RepositoryError> { + panic!("this fixture does not configure snapshots") + } async fn get_causal_stream<'a>( &'a self, identity: &'a StreamIdentity, diff --git a/src/microsvc/cell_host/cell.rs b/src/microsvc/cell_host/cell.rs index 687fc11f2..b74904a13 100644 --- a/src/microsvc/cell_host/cell.rs +++ b/src/microsvc/cell_host/cell.rs @@ -7,9 +7,10 @@ use std::time::Duration; use serde_json::Value; use super::causal::{CellCommandIdentity, CellDispatchError, CellDispatchResult}; +use super::store::CellStreamStore; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use super::store::{ - CellStreamStore, DurableAggregateCellState, DurableCellCommand, DurableCellEvents, - DurableCellSnapshot, + DurableAggregateCellState, DurableCellCommand, DurableCellEvents, DurableCellSnapshot, }; use crate::aggregate::{Aggregate, AggregateRepository}; use crate::microsvc::error::HandlerError; @@ -18,7 +19,7 @@ use crate::microsvc::session::Session; use crate::microsvc::HasOutboxStore; use crate::repository::{RepositoryError, SnapshotStore, StreamIdentity}; use crate::snapshot::{SnapshotRecord, Snapshottable}; -use crate::{InMemoryOutboxStore, OutboxDispatcher}; +use crate::OutboxDispatcher; /// Cell class for aggregate `A`. Equivalent to /// `#[distributed::cell(aggregate = A)]`: mount the same domain @@ -52,6 +53,10 @@ where routes: Routes>, #[cfg(feature = "workers-rs")] celld_outbox: Option, + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + activity: super::celld_outbox::CommandActivity, + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + storage: worker::send::SendWrapper, } impl AggregateCell @@ -59,6 +64,7 @@ where A: Aggregate + Send + Sync + 'static, { /// Open a cell instance addressed as `{aggregate_type}:{shard_id}`. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn new(shard_id: impl Into) -> Result { let shard = StreamIdentity::new(A::aggregate_type(), shard_id.into())?; let store = CellStreamStore::for_identity(shard.clone()); @@ -67,6 +73,27 @@ where routes: Routes::from_dependencies(AggregateRepository::new(store)), #[cfg(feature = "workers-rs")] celld_outbox: None, + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + activity: Default::default(), + }) + } + + /// Open the named runtime-owned SQLite cell. Mount commands and configure + /// its Queue binding before dispatch; no in-memory persistence path exists. + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + pub fn from_state(state: worker::State) -> Result { + let name = state.id().name().ok_or_else(|| { + RepositoryError::Model("aggregate cells require a named Durable Object".into()) + })?; + let shard = StreamIdentity::new(A::aggregate_type(), name)?; + let storage = worker::send::SendWrapper::new(state.storage()); + let store = CellStreamStore::from_state(state, shard.clone())?; + Ok(Self { + shard, + routes: Routes::from_dependencies(AggregateRepository::new(store)), + celld_outbox: None, + activity: Default::default(), + storage, }) } @@ -111,6 +138,11 @@ where input: Value, session: Session, ) -> Result { + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + let _command = self + .begin_command() + .await + .map_err(|error| HandlerError::Other(Box::new(error)))?; self.routes .dispatch_cell_command(command, input, session, &self.shard) .await @@ -128,6 +160,11 @@ where input: Value, session: Session, ) -> Result { + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + let _command = self + .begin_command() + .await + .map_err(|error| CellDispatchError::Internal(error.to_string()))?; self.routes .dispatch_cell_causal(command, identity, input, session, &self.shard) .await @@ -142,11 +179,13 @@ where } /// Event log for Durable Object SQLite persistence. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_events(&self) -> Result, RepositoryError> { self.routes.repo().repo().durable_events() } /// Restore the working event log from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_events( &self, events: Vec, @@ -155,6 +194,7 @@ where } /// Outbox rows committed with the aggregate (same cell SQLite). + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_outbox(&self) -> Result, RepositoryError> { self.routes.repo().repo().durable_outbox() } @@ -169,7 +209,7 @@ where worker_id: impl Into, lease: Duration, max_attempts: u32, - ) -> OutboxDispatcher + ) -> OutboxDispatcher<::OutboxStore, P> where P: crate::bus::MessagePublisher, { @@ -189,31 +229,52 @@ where self } - /// Persist this cell's complete state, durably arm its Queue watchdog, - /// dispatch pending outbox rows, persist settlements, and rearm or clear - /// the watchdog according to the remaining backlog. Once the initial state - /// and watchdog are durable, later failures are returned as deferred drain - /// diagnostics rather than as a rejection of the committed command. - #[cfg(feature = "workers-rs")] - pub async fn persist_and_drain_outbox( + /// Drain committed rows to the configured Queue. Call from the alarm handler + /// and optionally after dispatch for low latency. No persistence callback is + /// needed. A post-commit drain error must not reject an accepted command. + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + pub async fn drain_outbox( &self, env: &worker::Env, - storage: &worker::Storage, - persist: F, - ) -> Result - where - F: Fn(&DurableAggregateCellState) -> Result<(), E>, - E: std::fmt::Display, - { - let outbox = self.celld_outbox.as_ref().ok_or_else(|| { + ) -> Result { + self.outbox_config()?.drain(self, env, &self.storage).await + } + + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + fn outbox_config( + &self, + ) -> Result<&super::celld_outbox::CelldOutbox, crate::bus::TransportError> { + self.celld_outbox.as_ref().ok_or_else(|| { crate::bus::TransportError::permanent( "aggregate cell has no celld outbox binding configured", ) - })?; - outbox.persist_and_drain(self, env, storage, persist).await + }) + } + + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + async fn begin_command( + &self, + ) -> Result { + self.outbox_config()? + .begin_command( + &self.activity, + &super::celld_outbox::WorkerAlarm(&self.storage), + ) + .await + } + + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + pub(super) fn command_activity(&self) -> &super::celld_outbox::CommandActivity { + &self.activity + } + + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + pub(super) fn outbox_store(&self) -> ::OutboxStore { + self.routes.repo().repo().outbox_store() } /// Restore outbox rows from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_outbox( &self, messages: Vec, @@ -222,11 +283,13 @@ where } /// Snapshot cache for Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_snapshots(&self) -> Result, RepositoryError> { self.routes.repo().repo().durable_snapshots() } /// Restore the working snapshot cache from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_snapshots( &self, snapshots: Vec, @@ -238,11 +301,13 @@ where } /// Command-ledger rows for Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_commands(&self) -> Result, RepositoryError> { self.routes.repo().repo().durable_commands() } /// Restore command-ledger rows before accepting another wait-path request. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_commands( &self, commands: Vec, @@ -252,11 +317,13 @@ where /// Export events, snapshots, command ledger, outbox, and sealed row as one /// versioned value suitable for a single durable storage write. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_state(&self) -> Result { self.routes.repo().repo().durable_state() } /// Restore the complete working copy from one durable storage value. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_state( &self, state: DurableAggregateCellState, @@ -270,11 +337,13 @@ where } /// Sealed read-model JSON for GET on this instance. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn sealed_row(&self) -> Result, RepositoryError> { self.routes.repo().repo().sealed_row() } /// Persist the sealed read-model row next to events/snapshots. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn replace_sealed_row(&self, row: Value) -> Result<(), RepositoryError> { self.routes.repo().repo().replace_sealed_row(row) } @@ -284,7 +353,31 @@ impl AggregateCell where A: Aggregate + Snapshottable + Send + Sync + 'static, { + /// Open a SQL cell with the ordinary repository snapshot policy. + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + pub fn from_state_with_snapshots( + state: worker::State, + frequency: u64, + ) -> Result { + let name = state.id().name().ok_or_else(|| { + RepositoryError::Model("aggregate cells require a named Durable Object".into()) + })?; + let shard = StreamIdentity::new(A::aggregate_type(), name)?; + let storage = worker::send::SendWrapper::new(state.storage()); + let store = CellStreamStore::from_state(state, shard.clone())?; + Ok(Self { + shard, + routes: Routes::from_dependencies( + AggregateRepository::new(store).with_snapshots(frequency), + ), + celld_outbox: None, + activity: Default::default(), + storage, + }) + } + /// Open a cell with repository snapshot caching (`with_snapshots`). + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn new_with_snapshots( shard_id: impl Into, frequency: u64, @@ -298,6 +391,8 @@ where ), #[cfg(feature = "workers-rs")] celld_outbox: None, + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + activity: Default::default(), }) } } @@ -345,6 +440,7 @@ where } /// Create or return the cell for `shard_id`. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn get_or_create( &mut self, shard_id: &str, diff --git a/src/microsvc/cell_host/celld_outbox.rs b/src/microsvc/cell_host/celld_outbox.rs index 63672695e..691a7c674 100644 --- a/src/microsvc/cell_host/celld_outbox.rs +++ b/src/microsvc/cell_host/celld_outbox.rs @@ -1,15 +1,23 @@ //! High-level celld Queue drain lifecycle for aggregate-cell outboxes. -use std::fmt; +#[cfg(any(target_arch = "wasm32", test))] +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; use std::time::Duration; -use worker::{Env, Storage}; +use worker::Env; +#[cfg(target_arch = "wasm32")] +use worker::Storage; +#[cfg(any(target_arch = "wasm32", test))] use super::cell::AggregateCell; -use super::store::DurableAggregateCellState; +#[cfg(any(target_arch = "wasm32", test))] use crate::bus::MessagePublisher; use crate::bus::{CelldQueuePublisher, TransportError}; use crate::outbox_worker::OutboxDispatchOutcome; +#[cfg(any(target_arch = "wasm32", test))] use crate::Aggregate; /// Conventional celld Queue producer binding for aggregate outboxes. @@ -25,8 +33,7 @@ pub const CELLD_OUTBOX_DEFAULT_LEASE: Duration = Duration::from_secs(30); /// Default publish-failure ceiling before an outbox row is terminal. pub const CELLD_OUTBOX_DEFAULT_MAX_ATTEMPTS: u32 = 10_000; -/// Result of persisting an aggregate-cell commit and attempting its immediate -/// celld Queue drain. +/// Result of attempting the Queue drain after an aggregate-cell commit. /// /// Once the aggregate state, outbox rows, and watchdog alarm are durable, the /// command is accepted. Failures after that boundary are reported in @@ -52,8 +59,8 @@ impl CelldOutboxDrainOutcome { /// celld Queue binding and drain policy attached to an [`AggregateCell`]. /// /// Domain aggregates remain transport-independent. The infrastructure-facing -/// cell host selects this binding once, then [`AggregateCell::persist_and_drain_outbox`] -/// owns the persist → watchdog → publish → settle → persist lifecycle. +/// cell host selects this binding once. Dispatch arms the watchdog before +/// invoking a command; draining publishes and deletes leased SQLite rows. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CelldOutbox { binding: String, @@ -160,67 +167,70 @@ impl CelldOutbox { self.max_attempts } - pub(crate) async fn persist_and_drain( + #[cfg(target_arch = "wasm32")] + pub(crate) async fn drain( &self, cell: &AggregateCell, env: &Env, storage: &Storage, - persist: F, ) -> Result where A: Aggregate + Send + Sync + 'static, - F: Fn(&DurableAggregateCellState) -> Result<(), E>, - E: fmt::Display, { - let alarm = WorkerAlarm(storage); - self.persist_and_drain_with( + self.drain_with( cell, || CelldQueuePublisher::from_env(env, &self.binding), - &alarm, - persist, + &WorkerAlarm(storage), ) .await } - async fn persist_and_drain_with( + #[cfg(any(target_arch = "wasm32", test))] + pub(super) async fn begin_command( + &self, + activity: &CommandActivity, + alarm: &W, + ) -> Result { + // Count the command before yielding to setAlarm. An alarm firing while + // this command is suspended must keep the next wake scheduled. + let guard = activity.enter()?; + alarm.arm(self.drain_interval).await?; + Ok(guard) + } + + #[cfg(any(target_arch = "wasm32", test))] + async fn drain_with( &self, cell: &AggregateCell, publisher: PF, alarm: &W, - persist: F, ) -> Result where A: Aggregate + Send + Sync + 'static, P: MessagePublisher, PF: FnOnce() -> Result, - F: Fn(&DurableAggregateCellState) -> Result<(), E>, - E: fmt::Display, W: CelldOutboxAlarm, { - persist_current_state(cell, &persist)?; - - if !has_pending(cell)? { - let deferred = alarm.clear().await.err().into_iter().collect(); - return Ok(CelldOutboxDrainOutcome { - dispatch: OutboxDispatchOutcome::default(), - deferred, - }); + let pending = has_pending(cell).await?; + if !pending && !cell.command_activity().is_active() { + // Never delete an alarm: doing so can erase a concurrent command's + // prearmed wake. The last scheduled alarm simply finds no work. + return Ok(CelldOutboxDrainOutcome::default()); } - // The watchdog is durable before Queue egress. If Queue accepts but - // settlement persistence is interrupted, the stable id is retried. + // Arm before Queue I/O, including during an alarm invocation. A crash + // after Queue acceptance but before deletion retries the stable event ID. alarm.arm(self.drain_interval).await?; - - // Binding resolution is deliberately after the state commit and armed - // watchdog. A missing/misconfigured Queue cannot make the aggregate - // mutation disappear; the alarm retries after the deployment is fixed. + if !pending { + return Ok(CelldOutboxDrainOutcome::default()); + } let publisher = match publisher() { Ok(publisher) => publisher, Err(error) => { return Ok(CelldOutboxDrainOutcome { dispatch: OutboxDispatchOutcome::default(), deferred: vec![error], - }); + }) } }; let dispatcher = cell.outbox_dispatcher( @@ -229,47 +239,58 @@ impl CelldOutbox { self.lease, self.max_attempts, ); - let (dispatch, mut deferred) = match dispatcher.dispatch_batch(self.batch_size).await { - Ok(dispatch) => (dispatch, Vec::new()), - Err(error) => (OutboxDispatchOutcome::default(), vec![error]), - }; - - // Persist even when the dispatcher reports a store error: earlier rows - // in the pass may already have settled. The armed alarm remains the - // recovery path if exporting or persisting this state fails. - if let Err(error) = persist_current_state(cell, &persist) { - deferred.push(error); - return Ok(CelldOutboxDrainOutcome { dispatch, deferred }); + match dispatcher.dispatch_batch(self.batch_size).await { + Ok(dispatch) => Ok(CelldOutboxDrainOutcome { + dispatch, + deferred: Vec::new(), + }), + Err(error) => Ok(CelldOutboxDrainOutcome { + dispatch: OutboxDispatchOutcome::default(), + deferred: vec![error], + }), } + } +} - let pending = match has_pending(cell) { - Ok(pending) => pending, - Err(error) => { - deferred.push(error); - return Ok(CelldOutboxDrainOutcome { dispatch, deferred }); - } - }; - let watchdog = if pending { - alarm.arm(self.drain_interval).await - } else { - alarm.clear().await - }; - if let Err(error) = watchdog { - deferred.push(error); - } +/// Tracks only currently executing commands, not durable data. The prearmed +/// alarm and pending SQL rows carry recovery across process loss. +#[cfg(any(target_arch = "wasm32", test))] +#[derive(Default)] +pub(super) struct CommandActivity(Arc); + +#[cfg(any(target_arch = "wasm32", test))] +impl CommandActivity { + fn enter(&self) -> Result { + self.0 + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |count| { + count.checked_add(1) + }) + .map_err(|_| TransportError::retryable("cell command concurrency limit exceeded"))?; + Ok(CommandGuard(Arc::clone(&self.0))) + } + fn is_active(&self) -> bool { + self.0.load(Ordering::SeqCst) != 0 + } +} - Ok(CelldOutboxDrainOutcome { dispatch, deferred }) +#[cfg(any(target_arch = "wasm32", test))] +pub(super) struct CommandGuard(Arc); +#[cfg(any(target_arch = "wasm32", test))] +impl Drop for CommandGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); } } +#[cfg(any(target_arch = "wasm32", test))] #[async_trait::async_trait(?Send)] -trait CelldOutboxAlarm { +pub(super) trait CelldOutboxAlarm { async fn arm(&self, interval: Duration) -> Result<(), TransportError>; - async fn clear(&self) -> Result<(), TransportError>; } -struct WorkerAlarm<'a>(&'a Storage); - +#[cfg(target_arch = "wasm32")] +pub(super) struct WorkerAlarm<'a>(pub &'a Storage); +#[cfg(target_arch = "wasm32")] #[async_trait::async_trait(?Send)] impl CelldOutboxAlarm for WorkerAlarm<'_> { async fn arm(&self, interval: Duration) -> Result<(), TransportError> { @@ -277,151 +298,112 @@ impl CelldOutboxAlarm for WorkerAlarm<'_> { TransportError::retryable(format!("cannot arm celld outbox watchdog: {error}")) }) } - - async fn clear(&self) -> Result<(), TransportError> { - self.0.delete_alarm().await.map_err(|error| { - TransportError::retryable(format!("cannot clear celld outbox watchdog: {error}")) - }) - } } -fn persist_current_state( - cell: &AggregateCell, - persist: &F, -) -> Result<(), TransportError> +#[cfg(any(target_arch = "wasm32", test))] +async fn has_pending(cell: &AggregateCell) -> Result where A: Aggregate + Send + Sync + 'static, - F: Fn(&DurableAggregateCellState) -> Result<(), E>, - E: fmt::Display, { - let state = cell.durable_state().map_err(|error| { - TransportError::permanent(format!("cannot export aggregate cell state: {error}")) - })?; - persist(&state).map_err(|error| { - TransportError::retryable(format!("cannot persist aggregate cell state: {error}")) - }) -} - -fn has_pending(cell: &AggregateCell) -> Result -where - A: Aggregate + Send + Sync + 'static, -{ - cell.durable_outbox() - .map(|rows| { - rows.iter() - .any(|row| !row.is_published() && !row.is_failed()) - }) - .map_err(|error| { - TransportError::permanent(format!("cannot inspect aggregate cell outbox: {error}")) - }) + use crate::outbox_worker::OutboxStore; + use crate::OutboxMessageStatus; + let store = cell.outbox_store(); + for status in [OutboxMessageStatus::Pending, OutboxMessageStatus::InFlight] { + if !store + .messages_by_status(status, 1) + .await + .map_err(|error| { + TransportError::retryable(format!("cannot inspect aggregate cell outbox: {error}")) + })? + .is_empty() + { + return Ok(true); + } + } + Ok(false) } #[cfg(test)] mod tests { use super::*; use crate::entity::{Entity, EventRecord}; - use crate::outbox_worker::testing::block_on; + use crate::outbox_worker::{testing::block_on, OutboxStore}; use crate::{OutboxMessage, OutboxMessageStatus}; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, Mutex}; + use std::sync::Mutex; #[derive(Default)] struct TestAggregate { entity: Entity, } - impl Aggregate for TestAggregate { type ReplayError = String; - fn aggregate_type() -> &'static str { "celld_outbox_test" } - fn entity(&self) -> &Entity { &self.entity } - fn entity_mut(&mut self) -> &mut Entity { &mut self.entity } - - fn replay_event(&mut self, _event: &EventRecord) -> Result<(), Self::ReplayError> { + fn replay_event(&mut self, _: &EventRecord) -> Result<(), String> { Err("test aggregate has no replay events".into()) } } - #[derive(Clone)] struct RecordingPublisher { log: Arc>>, fail: bool, } - impl MessagePublisher for RecordingPublisher { - fn publish( - &self, - _message: crate::bus::Message, - ) -> impl std::future::Future> + Send + '_ { - let log = Arc::clone(&self.log); - let fail = self.fail; - async move { - log.lock().unwrap().push("publish"); - if fail { - Err(TransportError::retryable("Queue unavailable")) - } else { - Ok(()) - } + async fn publish(&self, _: crate::bus::Message) -> Result<(), TransportError> { + self.log.lock().unwrap().push("publish"); + if self.fail { + Err(TransportError::retryable("Queue unavailable")) + } else { + Ok(()) } } } - struct RecordingAlarm { log: Arc>>, + fail: bool, } - #[async_trait::async_trait(?Send)] impl CelldOutboxAlarm for RecordingAlarm { - async fn arm(&self, _interval: Duration) -> Result<(), TransportError> { + async fn arm(&self, _: Duration) -> Result<(), TransportError> { self.log.lock().unwrap().push("arm"); - Ok(()) - } - - async fn clear(&self) -> Result<(), TransportError> { - self.log.lock().unwrap().push("clear"); - Ok(()) + if self.fail { + Err(TransportError::retryable("alarm unavailable")) + } else { + Ok(()) + } } } - - struct FailingArmAlarm { - log: Arc>>, - } - - #[async_trait::async_trait(?Send)] - impl CelldOutboxAlarm for FailingArmAlarm { - async fn arm(&self, _interval: Duration) -> Result<(), TransportError> { - self.log.lock().unwrap().push("arm"); - Err(TransportError::retryable("alarm unavailable")) - } - - async fn clear(&self) -> Result<(), TransportError> { - self.log.lock().unwrap().push("clear"); - Ok(()) + fn cell(pending: bool) -> AggregateCell { + let cell = AggregateCell::new("aggregate-1").unwrap(); + if pending { + cell.restore_durable_outbox(vec![OutboxMessage::create( + "evt-1", + "test.created", + vec![1], + ) + .unwrap()]) + .unwrap(); } - } - - fn pending_cell() -> AggregateCell { - let cell = AggregateCell::::new("aggregate-1").unwrap(); - let message = OutboxMessage::create("evt-1", "test.created", vec![1]).unwrap(); - cell.restore_durable_state(DurableAggregateCellState { - version: super::super::store::DURABLE_AGGREGATE_CELL_STATE_VERSION, - events: Vec::new(), - snapshots: Vec::new(), - commands: Vec::new(), - outbox: vec![message], - sealed_row: None, - }) - .unwrap(); cell } + fn fixtures() -> (CelldOutbox, RecordingAlarm, RecordingPublisher) { + let log = Arc::new(Mutex::new(Vec::new())); + ( + CelldOutbox::new("OUTBOX").unwrap(), + RecordingAlarm { + log: log.clone(), + fail: false, + }, + RecordingPublisher { log, fail: false }, + ) + } #[test] fn defaults_are_safe_and_conventional() { @@ -435,7 +417,6 @@ mod tests { assert_eq!(outbox.batch_size(), CELLD_OUTBOX_DEFAULT_BATCH_SIZE); assert_eq!(outbox.max_attempts(), CELLD_OUTBOX_DEFAULT_MAX_ATTEMPTS); } - #[test] fn invalid_policy_values_are_rejected() { assert!(CelldOutbox::new(" ").is_err()); @@ -448,248 +429,161 @@ mod tests { assert!(base.clone().with_batch_size(0).is_err()); assert!(base.with_max_attempts(0).is_err()); } - #[test] - fn persists_and_arms_before_publish_then_persists_and_clears() { + fn arms_before_dispatch_and_publish_then_deletes_delivered_rows() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let states = Arc::new(Mutex::new(Vec::new())); - let publisher = RecordingPublisher { - log: Arc::clone(&log), - fail: false, - }; - let alarm = RecordingAlarm { - log: Arc::clone(&log), - }; - let persist_log = Arc::clone(&log); - let persisted_states = Arc::clone(&states); - - let outcome = outbox - .persist_and_drain_with( - &cell, - || Ok(publisher), - &alarm, - move |state| { - persist_log.lock().unwrap().push("persist"); - persisted_states.lock().unwrap().push(state.clone()); - Ok::<_, String>(()) - }, - ) + let cell = cell(true); + let (outbox, alarm, publisher) = fixtures(); + let guard = outbox + .begin_command(cell.command_activity(), &alarm) .await .unwrap(); - - assert_eq!(outcome.dispatch.published, 1); - assert!(!outcome.is_deferred()); + alarm.log.lock().unwrap().push("command"); + drop(guard); + let result = outbox + .drain_with(&cell, || Ok(publisher), &alarm) + .await + .unwrap(); + assert_eq!(result.dispatch.published, 1); + assert!(!result.is_deferred()); + assert!(cell.durable_outbox().unwrap().is_empty()); assert_eq!( - *log.lock().unwrap(), - ["persist", "arm", "publish", "persist", "clear"] + *alarm.log.lock().unwrap(), + ["arm", "command", "arm", "publish"] + ); + let (_, _, publisher) = fixtures(); + assert!(!outbox + .drain_with(&cell, || Ok(publisher), &alarm) + .await + .unwrap() + .is_deferred()); + assert_eq!( + alarm.log.lock().unwrap().len(), + 4, + "idle wake neither rearms nor deletes another wake" ); - let states = states.lock().unwrap(); - assert_eq!(states[0].outbox[0].status, OutboxMessageStatus::Pending); - assert!(states[1].outbox.is_empty()); }); } - #[test] - fn retryable_publish_stays_pending_and_rearms_without_error() { + fn retryable_publish_keeps_pending_work_and_already_armed_wake() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let states = Arc::new(Mutex::new(Vec::new())); - let publisher = RecordingPublisher { - log: Arc::clone(&log), - fail: true, - }; - let alarm = RecordingAlarm { - log: Arc::clone(&log), - }; - let persist_log = Arc::clone(&log); - let persisted_states = Arc::clone(&states); - - let outcome = outbox - .persist_and_drain_with( - &cell, - || Ok(publisher), - &alarm, - move |state| { - persist_log.lock().unwrap().push("persist"); - persisted_states.lock().unwrap().push(state.clone()); - Ok::<_, String>(()) - }, - ) + let cell = cell(true); + let (outbox, alarm, mut publisher) = fixtures(); + publisher.fail = true; + let result = outbox + .drain_with(&cell, || Ok(publisher), &alarm) .await .unwrap(); - - assert_eq!(outcome.dispatch.released, 1); - assert!(!outcome.is_deferred()); - assert_eq!( - *log.lock().unwrap(), - ["persist", "arm", "publish", "persist", "arm"] - ); - let states = states.lock().unwrap(); - assert_eq!(states[1].outbox[0].status, OutboxMessageStatus::Pending); - assert_eq!(states[1].outbox[0].attempts, 1); + assert_eq!(result.dispatch.released, 1); + let rows = cell.durable_outbox().unwrap(); + assert_eq!(rows[0].status, OutboxMessageStatus::Pending); + assert_eq!(rows[0].attempts, 1); + assert_eq!(*alarm.log.lock().unwrap(), ["arm", "publish"]); }); } - #[test] - fn persistence_failure_prevents_alarm_and_publish() { + fn failed_prearm_does_not_admit_command_and_releases_activity_guard() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let alarm = RecordingAlarm { - log: Arc::clone(&log), - }; - let resolve_log = Arc::clone(&log); - let persist_log = Arc::clone(&log); - - let error = outbox - .persist_and_drain_with( - &cell, - move || { - resolve_log.lock().unwrap().push("resolve"); - Ok(RecordingPublisher { - log: Arc::clone(&resolve_log), - fail: false, - }) - }, - &alarm, - move |_state| { - persist_log.lock().unwrap().push("persist"); - Err::<(), _>("storage unavailable") - }, - ) + let cell = cell(false); + let (outbox, mut alarm, _) = fixtures(); + alarm.fail = true; + assert!(outbox + .begin_command(cell.command_activity(), &alarm) .await - .unwrap_err(); - - assert!(error.is_retryable()); - assert_eq!(*log.lock().unwrap(), ["persist"]); + .is_err()); + assert!(!cell.command_activity().is_active()); + assert_eq!(*alarm.log.lock().unwrap(), ["arm"]); }); } - #[test] - fn watchdog_failure_before_durable_acceptance_prevents_publish() { + fn alarm_keeps_waking_while_a_command_is_suspended_before_commit() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let alarm = FailingArmAlarm { - log: Arc::clone(&log), - }; - let resolve_log = Arc::clone(&log); - let persist_log = Arc::clone(&log); - - let error = outbox - .persist_and_drain_with( - &cell, - move || { - resolve_log.lock().unwrap().push("resolve"); - Ok(RecordingPublisher { - log: Arc::clone(&resolve_log), - fail: false, - }) - }, - &alarm, - move |_state| { - persist_log.lock().unwrap().push("persist"); - Ok::<_, String>(()) - }, - ) + let cell = cell(false); + let (outbox, alarm, publisher) = fixtures(); + let first = outbox + .begin_command(cell.command_activity(), &alarm) .await - .unwrap_err(); - - assert!(error.is_retryable()); - assert_eq!(*log.lock().unwrap(), ["persist", "arm"]); + .unwrap(); + assert!(!outbox + .drain_with(&cell, || Ok(publisher.clone()), &alarm) + .await + .unwrap() + .is_deferred()); + let second = outbox + .begin_command(cell.command_activity(), &alarm) + .await + .unwrap(); + drop(first); + assert!(!outbox + .drain_with(&cell, || Ok(publisher.clone()), &alarm) + .await + .unwrap() + .is_deferred()); + assert_eq!(*alarm.log.lock().unwrap(), ["arm", "arm", "arm", "arm"]); + drop(second); + assert!(!outbox + .drain_with(&cell, || Ok(publisher), &alarm) + .await + .unwrap() + .is_deferred()); + assert_eq!(alarm.log.lock().unwrap().len(), 4); }); } - #[test] - fn binding_failure_is_deferred_after_persistence_and_watchdog() { + fn binding_failure_is_deferred_with_work_and_wake_retained() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let alarm = RecordingAlarm { - log: Arc::clone(&log), - }; - let resolve_log = Arc::clone(&log); - let persist_log = Arc::clone(&log); - - let outcome = outbox - .persist_and_drain_with( + let cell = cell(true); + let (outbox, alarm, _) = fixtures(); + let result = outbox + .drain_with( &cell, - move || { - resolve_log.lock().unwrap().push("resolve"); - Err::(TransportError::permanent( - "binding unavailable", - )) - }, + || Err::(TransportError::permanent("missing Queue")), &alarm, - move |_state| { - persist_log.lock().unwrap().push("persist"); - Ok::<_, String>(()) - }, ) .await .unwrap(); - - assert_eq!(outcome.deferred.len(), 1); - assert!(outcome.deferred[0].is_permanent()); - assert_eq!(*log.lock().unwrap(), ["persist", "arm", "resolve"]); + assert_eq!(result.deferred.len(), 1); + assert_eq!(cell.durable_outbox().unwrap().len(), 1); + assert_eq!(*alarm.log.lock().unwrap(), ["arm"]); }); } - #[test] - fn settlement_persistence_failure_is_deferred_after_durable_acceptance() { + fn alarm_failure_prevents_egress_without_losing_committed_rows() { block_on(async { - let cell = pending_cell(); - let outbox = CelldOutbox::new("OUTBOX").unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let persisted_states = Arc::new(Mutex::new(Vec::new())); - let persist_calls = Arc::new(AtomicUsize::new(0)); - let publisher = RecordingPublisher { - log: Arc::clone(&log), - fail: false, - }; - let alarm = RecordingAlarm { - log: Arc::clone(&log), - }; - let persist_log = Arc::clone(&log); - let states = Arc::clone(&persisted_states); - let calls = Arc::clone(&persist_calls); - - let outcome = outbox - .persist_and_drain_with( - &cell, - || Ok(publisher), - &alarm, - move |state| { - persist_log.lock().unwrap().push("persist"); - if calls.fetch_add(1, Ordering::SeqCst) == 0 { - states.lock().unwrap().push(state.clone()); - Ok(()) - } else { - Err("storage unavailable") - } - }, - ) + let cell = cell(true); + let (outbox, mut alarm, publisher) = fixtures(); + alarm.fail = true; + assert!(outbox + .drain_with(&cell, || Ok(publisher), &alarm) + .await + .is_err()); + assert_eq!(cell.durable_outbox().unwrap().len(), 1); + assert_eq!(*alarm.log.lock().unwrap(), ["arm"]); + }); + } + #[test] + fn live_claim_rearms_without_publishing_until_lease_expires() { + block_on(async { + let cell = cell(true); + let (outbox, alarm, publisher) = fixtures(); + cell.outbox_store() + .claim(crate::outbox_worker::ClaimOutboxMessages::new( + "busy", + 1, + Duration::from_secs(60), + )) .await .unwrap(); - - assert_eq!(outcome.dispatch.published, 1); - assert_eq!(outcome.deferred.len(), 1); - assert!(outcome.deferred[0].is_retryable()); + let result = outbox + .drain_with(&cell, || Ok(publisher), &alarm) + .await + .unwrap(); + assert_eq!(result.dispatch.published, 0); + assert_eq!(*alarm.log.lock().unwrap(), ["arm"]); assert_eq!( - *log.lock().unwrap(), - ["persist", "arm", "publish", "persist"] + cell.durable_outbox().unwrap()[0].status, + OutboxMessageStatus::InFlight ); - let states = persisted_states.lock().unwrap(); - assert_eq!(states.len(), 1); - assert_eq!(states[0].outbox[0].status, OutboxMessageStatus::Pending); }); } } diff --git a/src/microsvc/cell_host/mod.rs b/src/microsvc/cell_host/mod.rs index 537abd243..51f94eb70 100644 --- a/src/microsvc/cell_host/mod.rs +++ b/src/microsvc/cell_host/mod.rs @@ -22,6 +22,8 @@ mod command; mod internal_auth; #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] mod sql_executor; +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +mod sql_store; mod store; mod wire; @@ -41,9 +43,11 @@ pub use command::{CelldCommandHost, CelldRoute}; pub use internal_auth::{ InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, }; +pub use store::CellStreamStore; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub use store::{ - CellStreamStore, DurableAggregateCellState, DurableCellCommand, DurableCellEvents, - DurableCellSnapshot, DURABLE_AGGREGATE_CELL_STATE_VERSION, + DurableAggregateCellState, DurableCellCommand, DurableCellEvents, DurableCellSnapshot, + DURABLE_AGGREGATE_CELL_STATE_VERSION, }; pub(crate) use wire::validate_cell_projection_events; pub use wire::{ diff --git a/src/microsvc/cell_host/sql_store.rs b/src/microsvc/cell_host/sql_store.rs new file mode 100644 index 000000000..70233deca --- /dev/null +++ b/src/microsvc/cell_host/sql_store.rs @@ -0,0 +1,340 @@ +//! Cell-local execution of the ordinary SQL event/snapshot/receipt repository. +//! No in-memory working copy and no whole-cell export are used here. + +use sha2::{Digest, Sha256}; +use worker::State; + +use super::sql_executor::{finish_sql, CellSqlConnection}; +use crate::command_ledger::{ + AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, + CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, + CommandLedgerKey, CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ReservationOutcome, +}; +use crate::entity::Entity; +use crate::microsvc::HasOutboxStore; +use crate::outbox::{OutboxMessage, OutboxMessageStatus}; +use crate::outbox_worker::{ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxStore}; +use crate::repository::sql::{self, ledger, outbox, SqlExecutor, SqlRow, Statement}; +use crate::repository::{ + validate_commit_batch, CommitBatch, GetStream, RepositoryError, SnapshotStore, SnapshotWrite, + StreamIdentity, TransactionalCommit, +}; +use crate::snapshot::SnapshotRecord; + +#[derive(Clone)] +pub(super) struct CellSqlRepository { + connection: CellSqlConnection, + identity: CausalStorageIdentity, +} + +impl CellSqlRepository { + pub fn from_state(state: State) -> Result { + let connection = CellSqlConnection::from_state(state)?; + connection.transaction(|executor| finish_sql(async { + let tables = executor.query(Statement::new("SELECT name FROM sqlite_master WHERE type = 'table'")).await?; + let tables = tables.iter().map(|row| row.text("name")).collect::, _>>()?; + if tables.iter().any(|name| name == "cell_state") { + return Err(RepositoryError::Model("whole-state cell storage requires an explicit migration before opening this version".into())); + } + let registered = tables.iter().any(|name| name == "__distributed_cell_migrations"); + if !registered && tables.iter().any(|name| matches!(name.as_str(), "aggregate_events" | "aggregate_snapshots" | "command_ledger" | "outbox_messages")) { + return Err(RepositoryError::Model("unregistered cell SQL schema requires an explicit migration".into())); + } + executor.execute(Statement::new("CREATE TABLE IF NOT EXISTS __distributed_cell_migrations (version INTEGER PRIMARY KEY, checksum TEXT NOT NULL)")).await?; + let applied = executor.query(Statement::new("SELECT version, checksum FROM __distributed_cell_migrations ORDER BY version")).await?; + let migrations = crate::repository::migrations::cell_migrations().collect::>(); + if applied.len() > migrations.len() { + return Err(RepositoryError::Model("cell SQL schema is newer than this runtime".into())); + } + for (row, migration) in applied.iter().zip(&migrations) { + let checksum = format!("{:x}", Sha256::digest(migration.sql.as_bytes())); + if row.integer("version")? != migration.version || row.text("checksum")? != checksum { + return Err(RepositoryError::Model("cell SQL migration history differs from this runtime".into())); + } + } + for migration in migrations.iter().skip(applied.len()) { + // Execute the original validated migration as a whole; never + // split SQL on semicolons or maintain a parallel schema copy. + executor.execute(Statement::new(migration.sql)).await?; + let checksum = format!("{:x}", Sha256::digest(migration.sql.as_bytes())); + executor.execute(Statement::new("INSERT INTO __distributed_cell_migrations (version, checksum) VALUES (") + .bind(migration.version.into()).sql(", ").bind(checksum.as_str().into()).sql(")")).await?; + } + Ok::<_, RepositoryError>(()) + }))?; + Ok(Self { + connection, + identity: CausalStorageIdentity::new(), + }) + } + + fn commit( + &self, + batch: CommitBatch<'_>, + completion: Option, + ) -> Result<(), CommandLedgerError> { + if !batch.read_model_plans.is_empty() || !batch.inbox_receipts.is_empty() { + return Err(CommandLedgerError::Invalid( + "aggregate cells accept command effects, not projection or consumer-inbox writes" + .into(), + )); + } + let prepared = validate_commit_batch(&batch)?; + self.connection.transaction(|executor| { + finish_sql(async { + if let Some(completion) = &completion { + ledger::preflight(executor, completion).await?; + } + for append in &prepared { + let actual = sql::stream_version(executor, &append.identity).await?; + if actual != append.expected_version { + return Err(RepositoryError::ConcurrentWrite { + id: append.identity.to_string(), + expected: append.expected_version, + actual, + } + .into()); + } + } + for insert in sql::event_inserts(&prepared, 900)? { + executor.execute(insert.statement).await?; + } + // SQL binding errors in this runtime have no structured constraint + // code. Check identities within the same synchronous transaction, + // where another request cannot insert between this read and write. + for message in &batch.outbox_messages { + let existing = executor + .query( + Statement::new( + "SELECT message_id FROM outbox_messages WHERE message_id = ", + ) + .bind(message.id().into()), + ) + .await?; + if !existing.is_empty() { + return Err(RepositoryError::DuplicateOutboxMessageInBatch { + id: message.id().into(), + } + .into()); + } + } + for insert in outbox::inserts(&batch.outbox_messages, 900)? { + executor.execute(insert.statement).await?; + } + for snapshot in &batch.snapshots { + let SnapshotWrite::Save { identity, record } = snapshot; + sql::save_snapshot(executor, identity, record).await?; + } + // Same final fenced write as SQLx. A lost lease rolls back every + // participant, and entities are marked committed only afterwards. + if let Some(completion) = &completion { + ledger::complete(executor, completion).await?; + } + Ok::<_, CommandLedgerError>(()) + }) + })?; + for stream in batch.streams { + stream.entity.mark_committed(); + } + Ok(()) + } +} + +impl GetStream for CellSqlRepository { + async fn get_stream( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + finish_sql(sql::load_stream( + &mut self.connection.executor(), + identity, + None, + )) + } + async fn get_stream_tail( + &self, + identity: &StreamIdentity, + after_version: u64, + ) -> Result, RepositoryError> { + finish_sql(sql::load_stream( + &mut self.connection.executor(), + identity, + Some(after_version), + )) + } +} +impl CausalGetStream for CellSqlRepository { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl std::future::Future, RepositoryError>> + Send + 'a + { + GetStream::get_stream_tail(self, identity, after_version) + } + async fn get_causal_stream( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + self.get_stream(identity).await + } +} +impl SnapshotStore for CellSqlRepository { + async fn get_snapshot( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + finish_sql(sql::load_snapshot( + &mut self.connection.executor(), + identity, + )) + } + async fn save_snapshot( + &self, + identity: &StreamIdentity, + record: SnapshotRecord, + ) -> Result<(), RepositoryError> { + self.connection + .transaction(|executor| finish_sql(sql::save_snapshot(executor, identity, &record))) + } + async fn delete_snapshot(&self, identity: &StreamIdentity) -> Result { + self.connection + .transaction(|executor| finish_sql(sql::delete_snapshot(executor, identity))) + } +} +impl CausalRepositoryIdentity for CellSqlRepository { + fn causal_storage_identity(&self) -> CausalStorageIdentity { + self.identity + } +} +impl CommandLedgerStore for CellSqlRepository { + async fn reserve_command( + &self, + reservation: CommandReservation, + ) -> Result { + self.connection + .transaction(|executor| finish_sql(ledger::reserve(executor, &reservation))) + } + async fn lookup_command( + &self, + key: &CommandLedgerKey, + scope: CommandLookupScope<'_>, + ) -> Result { + self.connection + .transaction(|executor| finish_sql(ledger::lookup(executor, key, scope))) + } + async fn mark_retryable_unknown( + &self, + attempt: AttemptFence, + ) -> Result<(), CommandLedgerError> { + self.connection + .transaction(|executor| finish_sql(ledger::mark_retryable(executor, &attempt))) + } + async fn compact_expired_commands(&self, limit: usize) -> Result { + self.connection + .transaction(|executor| finish_sql(ledger::compact(executor, limit))) + } +} +impl TransactionalCommit for CellSqlRepository { + async fn commit_batch(&self, batch: CommitBatch<'_>) -> Result<(), RepositoryError> { + self.commit(batch, None).map_err(|error| match error { + CommandLedgerError::Storage(error) => error, + error => RepositoryError::Model(error.to_string()), + }) + } +} +impl CausalTransactionalCommit for CellSqlRepository { + async fn commit_causal_batch( + &self, + batch: CausalCommitBatch<'_>, + ) -> Result<(), CommandLedgerError> { + if batch.direct_projection.is_some() { + return Err(CommandLedgerError::Invalid( + "aggregate cells do not execute read-model projections".into(), + )); + } + self.commit(batch.domain, Some(batch.completion)) + } +} + +#[derive(Clone)] +pub struct CellSqlOutboxStore { + connection: CellSqlConnection, +} + +impl HasOutboxStore for CellSqlRepository { + type OutboxStore = CellSqlOutboxStore; + fn outbox_store(&self) -> Self::OutboxStore { + CellSqlOutboxStore { + connection: self.connection.clone(), + } + } +} + +impl OutboxStore for CellSqlOutboxStore { + async fn messages_by_status( + &self, + status: OutboxMessageStatus, + limit: usize, + ) -> Result, RepositoryError> { + // Match the native no-practical-bound convention within JS's exact + // integer range; never round a bound crossing the runtime binding. + let limit = (limit as u64).min(9_007_199_254_740_991) as i64; + let rows = finish_sql( + self.connection.executor().query( + Statement::new("SELECT ") + .sql(crate::repository::sqlite_codec::OUTBOX_SELECT) + .sql(" FROM outbox_messages WHERE status = ") + .bind(status.as_str().into()) + .sql(" ORDER BY CAST(created_at AS REAL), message_id LIMIT ") + .bind(limit.into()), + ), + )?; + rows.into_iter().map(outbox::from_row).collect() + } + async fn backlog_stats(&self) -> Result { + let rows = finish_sql(self.connection.executor().query(Statement::new("SELECT COUNT(*) AS pending, MIN(CAST(created_at AS REAL)) AS oldest FROM outbox_messages WHERE status = 'pending'")))?; + let row = rows + .first() + .ok_or_else(|| RepositoryError::Model("outbox count returned no row".into()))?; + Ok(OutboxBacklogStats { + pending: usize::try_from(row.integer("pending")?) + .map_err(|_| RepositoryError::Model("outbox count is not representable".into()))?, + oldest_created_at: row.optional_timestamp("oldest")?, + }) + } + async fn claim( + &self, + request: ClaimOutboxMessages, + ) -> Result, RepositoryError> { + self.connection.transaction(|executor| { + finish_sql(outbox::claim_sqlite(executor, request, crate::time::now())) + }) + } + async fn complete(&self, claim: &OutboxClaimRef) -> Result<(), RepositoryError> { + self.settle(claim, outbox::Transition::Complete) + } + async fn release(&self, claim: &OutboxClaimRef, error: &str) -> Result<(), RepositoryError> { + self.settle(claim, outbox::Transition::Release(error)) + } + async fn fail(&self, claim: &OutboxClaimRef, error: &str) -> Result<(), RepositoryError> { + self.settle(claim, outbox::Transition::Fail(error)) + } +} +impl CellSqlOutboxStore { + fn settle( + &self, + claim: &OutboxClaimRef, + transition: outbox::Transition<'_>, + ) -> Result<(), RepositoryError> { + self.connection.transaction(|executor| { + finish_sql(outbox::transition( + executor, + claim, + transition, + crate::time::now(), + )) + }) + } +} diff --git a/src/microsvc/cell_host/store.rs b/src/microsvc/cell_host/store.rs index 1c1237c7f..e8639ea69 100644 --- a/src/microsvc/cell_host/store.rs +++ b/src/microsvc/cell_host/store.rs @@ -1,40 +1,39 @@ -//! Per-shard stream store: in-process stand-in for one cell's private SQLite. -//! -//! Production celld wraps rusqlite (or workers-rs storage) the same way: sync -//! calls inside async fns. This is **not** `feature = "sqlite"` (sqlx pool) and -//! **not** a `celld` dialect. +//! One cell's private command-side repository, with enforced stream ownership. +//! Workers use runtime-owned SQLite; native tests use the in-process reference host. use std::future::Future; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +use std::sync::Mutex; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use serde_json::Value; +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +use super::sql_store::CellSqlRepository; use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandLedgerError, CommandLedgerKey, CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, }; -use crate::entity::{Entity, EventRecord}; +use crate::entity::Entity; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +use crate::entity::EventRecord; use crate::microsvc::HasOutboxStore; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use crate::outbox::OutboxMessage; -use crate::projection_protocol::{ - ProjectionChangeCursor, ProjectionChangeRead, ProjectionCheckpoint, ProjectionCommitBatch, - ProjectionCommitResult, ProjectionFailure, ProjectionFailureBatch, ProjectionFailureLocation, - ProjectionGeneration, ProjectionInputCursor, ProjectionInputDisposition, - ProjectionLiveRecordBatch, ProjectionLiveRecordBatchRequest, ProjectionModelOwnership, - ProjectionObligationEvidenceBatch, ProjectionObligationEvidenceBatchRequest, - ProjectionObservation, ProjectionObservationKind, ProjectionPartition, - ProjectionPartitionRuntimeState, ProjectionProtocolError, ProjectionProtocolStore, - ProjectionQuerySnapshot, ProjectionQuerySnapshotBatch, ProjectionQuerySnapshotBatchRequest, - ProjectionQuerySnapshotRequest, ProjectionRecordMetadata, ProjectionRecordScope, - ProjectorTopologyId, TrustedProjectionInput, -}; use crate::repository::{ CommitBatch, GetStream, RepositoryError, SnapshotStore, SnapshotWrite, StreamIdentity, TransactionalCommit, }; use crate::snapshot::SnapshotRecord; -use crate::{InMemoryOutboxStore, InMemoryRepository}; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +use crate::InMemoryRepository; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +type CellRepository = InMemoryRepository; +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +type CellRepository = CellSqlRepository; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use serde::{Deserialize, Serialize}; #[derive(Clone)] @@ -49,7 +48,7 @@ enum CellOwnership { }, } -/// Private SQLite stand-in for one cell instance (`{aggregate_type}:{shard}`). +/// Private command-side repository for one cell instance (`{aggregate_type}:{shard}`). /// /// Exclusive cells reject any stream that is not this cell's shard. Parent /// cells (`for_parent_shard`) hold sibling streams of one game and commit @@ -67,6 +66,7 @@ enum CellOwnership { /// One stream's event records for Durable Object SQLite persistence. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellEvents { pub stream: String, pub events: Vec, @@ -74,6 +74,7 @@ pub struct DurableCellEvents { /// Snapshot cache record for Durable Object SQLite persistence. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellSnapshot { pub stream: String, pub aggregate_type: String, @@ -87,22 +88,21 @@ pub struct DurableCellSnapshot { /// One versioned command-ledger row for Durable Object SQLite persistence. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellCommand { pub id: String, pub body: String, } /// Current persisted aggregate-cell state envelope version. +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub const DURABLE_AGGREGATE_CELL_STATE_VERSION: u16 = 1; -/// Complete durable working copy for one aggregate cell. -/// -/// Hosts should serialize this value and persist it with one storage write. -/// That makes the event log, snapshot cache, command ledger, outbox, and sealed -/// row one commit even when a Worker SDK does not expose celld's -/// `transactionSync` API. +/// Export of the native in-process reference host for restart conformance tests. +/// This is not a production cell persistence API; Workers use SQLite rows. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableAggregateCellState { pub version: u16, pub events: Vec, @@ -115,12 +115,44 @@ pub struct DurableAggregateCellState { #[derive(Clone)] pub struct CellStreamStore { ownership: CellOwnership, - inner: InMemoryRepository, + inner: CellRepository, + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] sealed_row: Arc>>, } impl CellStreamStore { + /// Open this runtime-owned SQLite database; no storage export callback exists. + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + pub fn from_state( + state: worker::State, + identity: StreamIdentity, + ) -> Result { + Ok(Self { + ownership: CellOwnership::Exclusive(identity), + inner: CellSqlRepository::from_state(state)?, + }) + } + + /// Open a parent-shard SQL cell. All owned sibling streams share this one + /// database; the predicate never grants access to another cell's storage. + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + pub fn from_parent_state( + state: worker::State, + parent_type: impl Into, + parent_id: impl Into, + owns: impl Fn(&StreamIdentity) -> bool + Send + Sync + 'static, + ) -> Result { + Ok(Self { + ownership: CellOwnership::Parent { + name: StreamIdentity::new(parent_type, parent_id)?, + owns: Arc::new(owns), + }, + inner: CellSqlRepository::from_state(state)?, + }) + } + /// Bind a store to one exact stream identity. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn for_identity(identity: StreamIdentity) -> Self { Self { ownership: CellOwnership::Exclusive(identity), @@ -133,6 +165,7 @@ impl CellStreamStore { /// /// Child streams of any aggregate type live in this cell's SQLite. A /// transaction across two parent cells does not exist. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn for_parent_shard( parent_type: impl Into, parent_id: impl Into, @@ -149,6 +182,7 @@ impl CellStreamStore { } /// Named exclusive-cell constructor used by [`super::AggregateCell`]. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn new( aggregate_type: impl Into, shard_id: impl Into, @@ -190,6 +224,7 @@ impl CellStreamStore { } /// Sealed read-model row for GET on this cell instance. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn sealed_row(&self) -> Result, RepositoryError> { self.sealed_row .lock() @@ -198,6 +233,7 @@ impl CellStreamStore { } /// Replace the sealed read-model row (Atomic board / Todo view). + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn replace_sealed_row(&self, row: Value) -> Result<(), RepositoryError> { let mut guard = self .sealed_row @@ -208,6 +244,7 @@ impl CellStreamStore { } /// Event log for Durable Object SQLite. Memory remains the working copy. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_events(&self) -> Result, RepositoryError> { Ok(self .inner @@ -218,11 +255,13 @@ impl CellStreamStore { } /// Outbox rows committed with this cell's events (same private SQLite). + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_outbox(&self) -> Result, RepositoryError> { self.inner.clone_outbox() } /// Restore outbox rows from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_outbox( &self, messages: Vec, @@ -231,6 +270,7 @@ impl CellStreamStore { } /// Replace the working event log from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_events( &self, events: Vec, @@ -244,6 +284,7 @@ impl CellStreamStore { } /// Snapshot cache for Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_snapshots(&self) -> Result, RepositoryError> { Ok(self .inner @@ -263,6 +304,7 @@ impl CellStreamStore { } /// Replace the working snapshot cache from Durable Object SQLite. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_snapshots( &self, snapshots: Vec, @@ -291,6 +333,7 @@ impl CellStreamStore { } /// Fenced command rows committed with this cell's domain effects. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_commands(&self) -> Result, RepositoryError> { self.inner .clone_command_ledger()? @@ -306,6 +349,7 @@ impl CellStreamStore { } /// Restore the complete command ledger before accepting another request. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_commands( &self, commands: Vec, @@ -326,6 +370,7 @@ impl CellStreamStore { } /// Export every durable concern as one versioned persistence envelope. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_state(&self) -> Result { Ok(DurableAggregateCellState { version: DURABLE_AGGREGATE_CELL_STATE_VERSION, @@ -338,6 +383,7 @@ impl CellStreamStore { } /// Replace the complete working copy from one persisted envelope. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn restore_durable_state( &self, state: DurableAggregateCellState, @@ -377,6 +423,19 @@ impl CellStreamStore { } impl CausalGetStream for CellStreamStore { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl std::future::Future, RepositoryError>> + Send + 'a + { + async move { + self.ensure_identity(identity)?; + self.inner + .get_causal_stream_tail(identity, after_version) + .await + } + } fn get_causal_stream<'a>( &'a self, identity: &'a StreamIdentity, @@ -519,164 +578,27 @@ impl CausalTransactionalCommit for CellStreamStore { } impl HasOutboxStore for CellStreamStore { - type OutboxStore = InMemoryOutboxStore; + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + type OutboxStore = crate::InMemoryOutboxStore; + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] + type OutboxStore = super::sql_store::CellSqlOutboxStore; fn outbox_store(&self) -> Self::OutboxStore { self.inner.outbox_store() } } -impl ProjectionProtocolStore for CellStreamStore { - fn register_projection_models<'a>( - &'a self, - topology: &'a ProjectorTopologyId, - ownership: &'a [ProjectionModelOwnership], - ) -> impl Future> + Send + 'a { - self.inner.register_projection_models(topology, ownership) - } - - fn commit_projection( - &self, - batch: ProjectionCommitBatch, - ) -> impl Future> + Send + '_ - { - self.inner.commit_projection(batch) - } - - fn record_projection_failure( +// A command-only cell cannot bootstrap same-transaction read-model projections. +impl crate::microsvc::dependencies::CausalHostProjections for CellStreamStore { + async fn __register_direct_projection_models( &self, - batch: ProjectionFailureBatch, - ) -> impl Future> + Send + '_ { - self.inner.record_projection_failure(batch) - } - - fn projection_checkpoint<'a>( - &'a self, - cursor_scope: &'a ProjectionInputCursor, - generation: ProjectionGeneration, - ) -> impl Future, ProjectionProtocolError>> + Send + 'a - { - self.inner.projection_checkpoint(cursor_scope, generation) - } - - fn projection_record<'a>( - &'a self, - scope: &'a ProjectionRecordScope, - ) -> impl Future, ProjectionProtocolError>> - + Send - + 'a { - self.inner.projection_record(scope) - } - - fn projection_input_disposition<'a>( - &'a self, - input: &'a TrustedProjectionInput, - ) -> impl Future> + Send + 'a - { - self.inner.projection_input_disposition(input) - } - - fn projection_query_snapshot<'a>( - &'a self, - request: &'a ProjectionQuerySnapshotRequest, - ) -> impl Future> + Send + 'a - { - self.inner.projection_query_snapshot(request) - } - - fn projection_query_snapshot_batch<'a>( - &'a self, - request: &'a ProjectionQuerySnapshotBatchRequest, - ) -> impl Future> + Send + 'a - { - self.inner.projection_query_snapshot_batch(request) - } - - fn projection_obligation_evidence_batch<'a>( - &'a self, - request: &'a ProjectionObligationEvidenceBatchRequest, - ) -> impl Future> - + Send - + 'a { - self.inner.projection_obligation_evidence_batch(request) - } - - fn projection_live_record_batch<'a>( - &'a self, - request: &'a ProjectionLiveRecordBatchRequest, - ) -> impl Future> + Send + 'a - { - self.inner.projection_live_record_batch(request) - } - - fn projection_partition_runtime_state<'a>( - &'a self, - topology: &'a ProjectorTopologyId, - partition: &'a ProjectionPartition, - ) -> impl Future, ProjectionProtocolError>> - + Send - + 'a { - self.inner - .projection_partition_runtime_state(topology, partition) - } - - fn projection_observation<'a>( - &'a self, - causation_id: &'a str, - scope: &'a ProjectionRecordScope, - kind: ProjectionObservationKind, - ) -> impl Future, ProjectionProtocolError>> + Send + 'a - { - self.inner.projection_observation(causation_id, scope, kind) - } - - fn projection_changes<'a>( - &'a self, - topology: &'a ProjectorTopologyId, - partition: &'a ProjectionPartition, - after: Option<&'a ProjectionChangeCursor>, - limit: usize, - ) -> impl Future> + Send + 'a - { - self.inner - .projection_changes(topology, partition, after, limit) - } - - fn repair_projection<'a>( - &'a self, - topology: &'a ProjectorTopologyId, - partition: &'a ProjectionPartition, - failure_id: &'a str, - ) -> impl Future> + Send + 'a - { - self.inner - .repair_projection(topology, partition, failure_id) - } - - fn compact_projection_changes<'a>( - &'a self, - through: &'a ProjectionChangeCursor, - ) -> impl Future> + Send + 'a { - self.inner.compact_projection_changes(through) - } - - fn projection_failure<'a>( - &'a self, - topology: &'a ProjectorTopologyId, - partition: &'a ProjectionPartition, - failure_id: &'a str, - ) -> impl Future, ProjectionProtocolError>> + Send + 'a - { - self.inner - .projection_failure(topology, partition, failure_id) - } - - fn projection_failure_location<'a>( - &'a self, - failure_id: &'a str, - ) -> impl Future, ProjectionProtocolError>> - + Send - + 'a { - self.inner.projection_failure_location(failure_id) + _topology: &crate::projection_protocol::ProjectorTopologyId, + _ownership: &[crate::projection_protocol::ProjectionModelOwnership], + ) -> Result<(), crate::projection_protocol::ProjectionProtocolError> { + Err( + crate::projection_protocol::ProjectionProtocolError::InvalidBatch( + "aggregate cells do not execute read-model projections".into(), + ), + ) } } diff --git a/src/microsvc/dependencies.rs b/src/microsvc/dependencies.rs index d618e2d2a..0b3e11d60 100644 --- a/src/microsvc/dependencies.rs +++ b/src/microsvc/dependencies.rs @@ -28,7 +28,7 @@ pub trait CausalRepositoryBackend: + CommandLedgerStore + CausalTransactionalCommit + CausalRepositoryIdentity - + ProjectionProtocolStore + + CausalHostProjections + TransactionalCommit + Send + Sync @@ -41,7 +41,7 @@ impl CausalRepositoryBackend for T where + CommandLedgerStore + CausalTransactionalCommit + CausalRepositoryIdentity - + ProjectionProtocolStore + + CausalHostProjections + TransactionalCommit + Send + Sync @@ -49,6 +49,98 @@ impl CausalRepositoryBackend for T where { } +pub(crate) trait CausalHostProjections: Send + Sync { + #[cfg(feature = "graphql")] + fn command_obligation_evidence<'a>( + &'a self, + _request: &'a crate::projection_protocol::ProjectionObligationEvidenceBatchRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionObligationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + async { + Err( + crate::projection_protocol::ProjectionProtocolError::InvalidBatch( + "command-only cells do not query projection evidence".into(), + ), + ) + } + } + + #[cfg(feature = "graphql")] + fn command_causation_evidence<'a>( + &'a self, + _request: &'a crate::projection_protocol::ProjectionCausationEvidenceRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionCausationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + async { + Err( + crate::projection_protocol::ProjectionProtocolError::InvalidBatch( + "command-only cells do not query projection evidence".into(), + ), + ) + } + } + /// Bootstrap direct projections only on hosts that own a projection store. + /// Command-only hosts reject this operation without inventing query storage. + fn __register_direct_projection_models<'a>( + &'a self, + topology: &'a crate::projection_protocol::ProjectorTopologyId, + ownership: &'a [crate::projection_protocol::ProjectionModelOwnership], + ) -> impl std::future::Future< + Output = Result<(), crate::projection_protocol::ProjectionProtocolError>, + > + Send + + 'a; +} + +impl CausalHostProjections for T { + #[cfg(feature = "graphql")] + fn command_obligation_evidence<'a>( + &'a self, + request: &'a crate::projection_protocol::ProjectionObligationEvidenceBatchRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionObligationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + self.projection_obligation_evidence_batch(request) + } + + #[cfg(feature = "graphql")] + fn command_causation_evidence<'a>( + &'a self, + request: &'a crate::projection_protocol::ProjectionCausationEvidenceRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionCausationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + self.projection_causation_evidence(request) + } + fn __register_direct_projection_models<'a>( + &'a self, + topology: &'a crate::projection_protocol::ProjectorTopologyId, + ownership: &'a [crate::projection_protocol::ProjectionModelOwnership], + ) -> impl std::future::Future< + Output = Result<(), crate::projection_protocol::ProjectionProtocolError>, + > + Send + + 'a { + self.register_projection_models(topology, ownership) + } +} + /// Compile-time extraction of the one aggregate repository owned by a typed /// causal route bundle. /// diff --git a/src/microsvc/service/causal.rs b/src/microsvc/service/causal.rs index 75abb65e2..fa4e3ec65 100644 --- a/src/microsvc/service/causal.rs +++ b/src/microsvc/service/causal.rs @@ -22,8 +22,7 @@ use crate::microsvc::session::Session; use crate::projection_protocol::{ ProjectionCausationEvidenceRequest, ProjectionObligationEvidence, ProjectionObligationEvidenceBatchRequest, ProjectionObligationEvidenceRequest, - ProjectionObservationKind, ProjectionProtocolStore, ProjectionRecordScope, - SameTransactionProjectionEvidence, + ProjectionObservationKind, ProjectionRecordScope, SameTransactionProjectionEvidence, }; #[cfg(feature = "graphql")] use crate::repository::CommitBatch; @@ -819,7 +818,7 @@ pub(super) async fn evaluate_causal_command_status( protocol: Option<&crate::graphql::protocol::ProtocolResponseAccumulator>, ) -> Result where - R: CommandLedgerStore + ProjectionProtocolStore + Send + Sync, + R: CommandLedgerStore + crate::microsvc::dependencies::CausalHostProjections + Send + Sync, { match lookup { CommandLookup::Unknown => Ok(CausalCommandPublicStatus::unknown(command_id.as_str())), @@ -953,7 +952,7 @@ pub(super) async fn evaluate_pending_projection_evidence( CausalDispatchError, > where - R: ProjectionProtocolStore + Send + Sync, + R: crate::microsvc::dependencies::CausalHostProjections + Send + Sync, { if let Some(metadata) = receipt.projection_metadata.as_ref() { return evaluate_pending_modeled_projection_evidence( @@ -996,7 +995,7 @@ where )) })?; let batch = repository - .projection_obligation_evidence_batch(&request) + .command_obligation_evidence(&request) .await .map_err(|error| { CausalDispatchError::Internal(format!( @@ -1089,7 +1088,7 @@ async fn evaluate_pending_modeled_projection_evidence( CausalDispatchError, > where - R: ProjectionProtocolStore + Send + Sync, + R: crate::microsvc::dependencies::CausalHostProjections + Send + Sync, { let request = ProjectionCausationEvidenceRequest::new( receipt.causation_id.clone(), @@ -1101,7 +1100,7 @@ where )) })?; let batch = repository - .projection_causation_evidence(&request) + .command_causation_evidence(&request) .await .map_err(|error| { CausalDispatchError::Internal(format!( diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 8f190deac..3dc6022c4 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -43,6 +43,8 @@ use crate::graphql::SurfaceProjector; use crate::microsvc::causal::CausalWorkspace; use crate::microsvc::cell_host::{CellCommandIdentity, CellDispatchError, CellDispatchResult}; use crate::microsvc::context::Context; +#[cfg(feature = "graphql")] +use crate::microsvc::dependencies::CausalHostProjections; use crate::microsvc::dependencies::{ CausalProjectionRouteDependencies, CausalRouteDependencies, ConfigurableOutboxPublisher, HasOutboxStore, HasReadModelStore, HasRepo, @@ -72,8 +74,6 @@ use crate::outbox_worker::{ DEFAULT_OUTBOX_HINT_CAPACITY, }; #[cfg(feature = "graphql")] -use crate::projection_protocol::ProjectionProtocolStore; -#[cfg(feature = "graphql")] use crate::projection_protocol::{CompiledProjectionTopology, ProjectorTopologyId}; use crate::repository::{StreamIdentity, TransactionalCommit}; use serde_json::Value; @@ -1842,7 +1842,7 @@ where self.direct_projection_bootstrap .get_or_try_init(|| async { repository - .register_projection_models(topology, ownership) + .__register_direct_projection_models(topology, ownership) .await .map_err(|error| { CausalDispatchError::Internal(format!( diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 8520e75d0..d359a31ce 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -810,6 +810,13 @@ impl AmbiguousCommitRepository { #[cfg(feature = "graphql")] impl CausalGetStream for AmbiguousCommitRepository { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a crate::StreamIdentity, + after_version: u64, + ) -> impl Future, crate::RepositoryError>> + Send + 'a { + self.inner.get_causal_stream_tail(identity, after_version) + } fn get_causal_stream<'a>( &'a self, identity: &'a crate::StreamIdentity, @@ -2006,8 +2013,9 @@ async fn causal_dispatch_overwrites_event_and_outbox_causation_with_ledger_ident #[tokio::test] async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { let repository = InMemoryRepository::new(); - let observed_broker_metadata = Arc::new(Mutex::new(None::<[String; 4]>)); + let observed_broker_metadata = Arc::new(Mutex::new(None::<[String; 6]>)); let route_observed_broker_metadata = Arc::clone(&observed_broker_metadata); + let bus = crate::bus::InMemoryBus::new(); let service = Service::new() .named("causal-tests") .routes( @@ -2045,6 +2053,8 @@ async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { >| { let message = context.message(); let metadata = [ + message.id().expect("published message ID").to_string(), + message.name().to_string(), message.causation_id().unwrap_or_default().to_string(), message .metadata("x-sourced-source-aggregate-type") @@ -2067,7 +2077,7 @@ async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { }, ), ) - .with_bus(crate::bus::InMemoryBus::new()); + .with_bus(bus.clone()); service .dispatch_causal( @@ -2087,11 +2097,14 @@ async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { tokio::task::yield_now().await; continue; } - if !outbox - .messages_by_status(crate::outbox::OutboxMessageStatus::Published, usize::MAX) + if outbox + .messages_by_status(crate::outbox::OutboxMessageStatus::InFlight, usize::MAX) .await .unwrap() .is_empty() + && bus + .published_ids() + .contains(&"todo-immediate:immediate-fact".to_string()) { break; } @@ -2105,22 +2118,25 @@ async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { .messages_by_status(crate::outbox::OutboxMessageStatus::Published, usize::MAX) .await .unwrap(); - assert_eq!(published.len(), 1); - assert_eq!(published[0].id(), "todo-immediate:immediate-fact"); - assert_eq!(published[0].event_type, "causal.immediate_fact"); - let causation = published[0] + assert!( + published.is_empty(), + "delivered messages are deleted, not retained as evidence" + ); + let stream = repository + .get_stream( + &crate::StreamIdentity::new( + CausalDispatcherAggregate::aggregate_type(), + "todo-immediate", + ) + .unwrap(), + ) + .await + .unwrap() + .unwrap(); + let causation = stream.events()[0] .causation_id() - .expect("persisted outbox row should retain ledger causation") + .expect("committed event carries ledger causation") .to_string(); - assert_eq!( - published[0].source_aggregate_type.as_deref(), - Some(CausalDispatcherAggregate::aggregate_type()) - ); - assert_eq!( - published[0].source_aggregate_id.as_deref(), - Some("todo-immediate") - ); - assert_eq!(published[0].source_sequence, Some(1)); service .run(RunOptions::idempotent()) @@ -2129,6 +2145,8 @@ async fn causal_dispatch_uses_the_configured_immediate_outbox_publisher() { assert_eq!( observed_broker_metadata.lock().unwrap().as_ref(), Some(&[ + "todo-immediate:immediate-fact".to_string(), + "causal.immediate_fact".to_string(), causation, CausalDispatcherAggregate::aggregate_type().to_string(), "todo-immediate".to_string(), diff --git a/src/queued_repo/repository.rs b/src/queued_repo/repository.rs index 3c19d3e67..9e4bcbd48 100644 --- a/src/queued_repo/repository.rs +++ b/src/queued_repo/repository.rs @@ -187,6 +187,14 @@ where R: CausalGetStream, L: LockManager, { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl Future, RepositoryError>> + Send + 'a { + self.inner.get_causal_stream_tail(identity, after_version) + } + fn get_causal_stream<'a>( &'a self, identity: &'a StreamIdentity, diff --git a/src/repository/migrations.rs b/src/repository/migrations.rs new file mode 100644 index 000000000..8a73455ef --- /dev/null +++ b/src/repository/migrations.rs @@ -0,0 +1,20 @@ +//! Validated SQL migration inventory shared by native and cell executors. + +#[derive(Clone, Copy)] +pub(crate) struct EmbeddedMigration { + pub(crate) version: i64, + pub(crate) description: &'static str, + pub(crate) sql: &'static str, +} + +include!(concat!(env!("OUT_DIR"), "/migration_inventory.rs")); + +/// Cells host commands, not read-model projectors. These are the event, +/// snapshot, delivery and command-ledger migrations from the native inventory. +/// Projection-owned tables are initialized by their separate query host. +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +pub(crate) fn cell_migrations() -> impl Iterator { + SQLITE_MIGRATIONS + .iter() + .filter(|migration| matches!(migration.version, 1 | 2 | 4)) +} diff --git a/src/repository/mod.rs b/src/repository/mod.rs index 34477f906..29c100c17 100644 --- a/src/repository/mod.rs +++ b/src/repository/mod.rs @@ -1,6 +1,12 @@ mod error; mod identity; mod inbox; +#[cfg(any( + feature = "sqlite", + feature = "postgres", + all(feature = "workers-rs", target_arch = "wasm32") +))] +pub(crate) mod migrations; pub(crate) mod sql; pub(crate) mod sqlite_codec; mod traits; diff --git a/src/snapshot/repository.rs b/src/snapshot/repository.rs index f26f82547..f8d5bd565 100644 --- a/src/snapshot/repository.rs +++ b/src/snapshot/repository.rs @@ -1,7 +1,7 @@ use std::future::Future; use std::pin::Pin; -use crate::aggregate::{hydrate, AggregateRepository, SnapshotPolicy}; +use crate::aggregate::{hydrate, AggregateRepository, SnapshotPolicy, StreamReads}; use crate::entity::{upcast_events_for_replay, Entity, EventRecord}; use crate::repository::{GetStream, RepositoryError, SnapshotStore, StreamIdentity}; @@ -319,6 +319,7 @@ where fn load_from_store<'a, R, A>( repo: &'a R, identity: &'a StreamIdentity, + reads: StreamReads, ) -> Pin, RepositoryError>> + Send + 'a>> where R: SnapshotStore + GetStream + Sync, @@ -327,8 +328,7 @@ where Box::pin(async move { let Some(snapshot) = repo.get_snapshot(identity).await? else { // No snapshot: a plain full load (same as a snapshotless repo). - return repo - .get_stream(identity) + return (reads.full)(repo, identity) .await? .map(hydrate::) .transpose(); @@ -336,7 +336,7 @@ where // Fetch only events after the snapshot. The returned entity records the // true stream version even though it holds only the tail. - let Some(entity) = repo.get_stream_tail(identity, snapshot.version).await? else { + let Some(entity) = (reads.tail)(repo, identity, snapshot.version).await? else { // The stream is gone but a snapshot lingers; nothing to hydrate. return Ok(None); }; @@ -354,8 +354,7 @@ where // rebuild the aggregate, so fall back to a full stream load. This is // the I/O we hoped to avoid, but it only happens when the snapshot is // unusable — the correct, safe outcome. - Err(SnapshotHydrationError::Cache(_)) => Ok(repo - .get_stream(identity) + Err(SnapshotHydrationError::Cache(_)) => Ok((reads.full)(repo, identity) .await? .map(hydrate::) .transpose()?), @@ -404,6 +403,113 @@ mod tests { saw_snapshot: std::sync::atomic::AtomicBool, } + struct CausalReadProbe { + inner: crate::InMemoryRepository, + reads: std::sync::Mutex>>, + } + impl GetStream for CausalReadProbe { + async fn get_stream(&self, _: &StreamIdentity) -> Result, RepositoryError> { + panic!("causal snapshot loading must not use ordinary locking reads") + } + } + impl crate::command_ledger::CausalGetStream for CausalReadProbe { + async fn get_causal_stream( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + self.reads.lock().unwrap().push(None); + self.inner.get_stream(identity).await + } + async fn get_causal_stream_tail( + &self, + identity: &StreamIdentity, + after: u64, + ) -> Result, RepositoryError> { + self.reads.lock().unwrap().push(Some(after)); + self.inner.get_stream_tail(identity, after).await + } + } + impl SnapshotStore for CausalReadProbe { + async fn get_snapshot( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + self.inner.get_snapshot(identity).await + } + async fn save_snapshot( + &self, + identity: &StreamIdentity, + record: SnapshotRecord, + ) -> Result<(), RepositoryError> { + self.inner.save_snapshot(identity, record).await + } + async fn delete_snapshot( + &self, + identity: &StreamIdentity, + ) -> Result { + self.inner.delete_snapshot(identity).await + } + } + + #[tokio::test] + async fn causal_snapshots_use_only_tail_through_queued_wrappers() { + let inner = crate::InMemoryRepository::new(); + let writer = AggregateRepository::new(inner.clone()).with_snapshots(2); + let mut aggregate = TestAggregate::default(); + for _ in 0..3 { + aggregate.touch().unwrap(); + writer.commit(&mut aggregate).await.unwrap(); + } + let identity = StreamIdentity::new(TestAggregate::aggregate_type(), "snap-1").unwrap(); + let reader = AggregateRepository::<_, TestAggregate>::new(crate::QueuedRepository::new( + CausalReadProbe { + inner, + reads: Default::default(), + }, + )) + .with_snapshots(2); + // Repeated loads prove no queue lock leaks across a handler await. + for _ in 0..2 { + let loaded = tokio::time::timeout( + std::time::Duration::from_secs(1), + reader.get_causal(&identity), + ) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(loaded.value, 3); + assert_eq!(loaded.entity.version(), 3); + assert_eq!(loaded.entity.snapshot_version(), 2); + assert_eq!(loaded.entity.events().len(), 1); + } + assert_eq!( + *reader.repo().inner().reads.lock().unwrap(), + [Some(2), Some(2)] + ); + + // Invalid cache bytes retain the ordinary safe full-replay behavior, + // while still bypassing locking reads on that recovery path. + let mut snapshot = reader + .repo() + .get_snapshot(&identity) + .await + .unwrap() + .unwrap(); + snapshot.payload = vec![255; 9]; + reader + .repo() + .save_snapshot(&identity, snapshot) + .await + .unwrap(); + let loaded = reader.get_causal(&identity).await.unwrap().unwrap(); + assert_eq!(loaded.value, 3); + assert_eq!( + *reader.repo().inner().reads.lock().unwrap(), + [Some(2), Some(2), Some(2), None] + ); + } + impl TransactionalCommit for FailingSnapshotRepo { async fn commit_batch<'a>(&'a self, batch: CommitBatch<'a>) -> Result<(), RepositoryError> { { diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 652c8b171..fed68f969 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -1,14 +1,10 @@ use super::*; -/// One migration registration emitted by the root build script. -#[derive(Clone, Copy)] -pub(crate) struct EmbeddedMigration { - pub(crate) version: i64, - pub(crate) description: &'static str, - pub(crate) sql: &'static str, -} - -include!(concat!(env!("OUT_DIR"), "/migration_inventory.rs")); +pub(crate) use crate::repository::migrations::EmbeddedMigration; +#[cfg(feature = "postgres")] +pub(crate) use crate::repository::migrations::POSTGRES_MIGRATIONS; +#[cfg(feature = "sqlite")] +pub(crate) use crate::repository::migrations::SQLITE_MIGRATIONS; /// Build an embedded migrator from the validated, generated migration inventory. pub(crate) fn embedded_migrator(files: &[EmbeddedMigration]) -> Migrator { diff --git a/src/sqlx_repo/repo/streams.rs b/src/sqlx_repo/repo/streams.rs index 89b2ff515..5079a217f 100644 --- a/src/sqlx_repo/repo/streams.rs +++ b/src/sqlx_repo/repo/streams.rs @@ -122,6 +122,14 @@ where for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { + fn get_causal_stream_tail<'a>( + &'a self, + identity: &'a StreamIdentity, + after_version: u64, + ) -> impl Future, RepositoryError>> + Send + 'a { + GetStream::get_stream_tail(self, identity, after_version) + } + fn get_causal_stream<'a>( &'a self, identity: &'a StreamIdentity, diff --git a/tests/celld/README.md b/tests/celld/README.md index 8ef92f2a6..4e6475899 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -8,41 +8,66 @@ command -> AggregateCell -> domain event -> same-cell outbox ``` The aggregate Worker owns one SQLite Durable Object per Todo or Chat shard. -`AggregateCell::durable_state` assembles the event log, command ledger, -snapshot/sealed state, and outbox into one versioned envelope. The Worker saves -that envelope with one SQLite upsert, so the aggregate mutation and its outbox -are one cell commit. The host attaches `CelldOutbox::from_env(&env, "OUTBOX")` -to the `AggregateCell`, then `persist_and_drain_outbox` owns the complete -persist, watchdog, Queue dispatch, settlement persistence, and alarm-rearming -lifecycle. celld's output gate holds Queue egress until the cell write is -durable. If settlement persistence is interrupted, the same stable event id may -be delivered again; consumers must deduplicate by that id. +The same SQL operations used by native repositories append event rows, maintain +snapshots, fence command receipts and enqueue pending delivery rows. Each +command commits those participants inside one `storage.transactionSync`. +There is no whole-cell JSON value, authoritative in-memory shadow, or host +persistence callback. ```rust,ignore -let cell = AggregateCell::::new_with_snapshots(shard, 1)? +let cell = AggregateCell::::from_state_with_snapshots(state, 100)? .mount(create()) .mount(complete()) .with_celld_outbox(CelldOutbox::from_env(&env, "OUTBOX")?); -let drain = cell.persist_and_drain_outbox(&env, &storage, |state| { - persist_cell_state(&sql, state) -}) -.await?; -for error in drain.deferred { - worker::console_error!("outbox drain deferred: {error}"); +// Dispatch arms the durable watchdog before invoking the command. +let result = cell.dispatch_idempotent(command, &identity, input, session).await?; + +// Optional immediate delivery after commit. A drain error is diagnostic here: +// it cannot turn an already committed command into a rejection. +match cell.drain_outbox(&env).await { + Ok(drain) => { + for error in drain.deferred { + worker::console_error!("outbox drain deferred: {error}"); + } + } + Err(error) => worker::console_error!("outbox drain deferred: {error}"), } + +// The Durable Object alarm handler also calls drain_outbox(&env). ``` -The same `persist_and_drain_outbox` call runs after a command and from the -Durable Object alarm. It persists the full state before Queue egress, arms the -watchdog before publishing, persists any settlements even when a later store -operation errors, and clears the alarm only when no retryable rows remain. -Failure to persist that first state or arm its watchdog rejects the request. -After both are established, the command is durably accepted: Queue, settlement, -or later alarm-operation failures are returned in -`CelldOutboxDrainOutcome::deferred` for diagnostics while the already-armed -watchdog owns retry. Released Queue outcomes likewise stay pending. Neither can -turn an already committed command into an HTTP error. +The Queue lives in another cell: its acceptance is **not** part of the +aggregate's SQLite transaction. celld's output gate orders Queue egress after +the aggregate write becomes durable. The prearmed alarm covers the gap between +that commit and Queue acceptance, including process loss without another request. + +A drain claims rows, sends them, and deletes each matching lease-fenced row +after acceptance. A crash after acceptance but before deletion can deliver the +same stable event ID again; consumers must deduplicate. Queue publication or +settlement failures retain pending/in-flight work for the watchdog. An alarm +keeps a wake scheduled while commands are running, including suspended commands. +An empty drain never deletes another command's alarm; the last scheduled wake +simply finds no work and stops. + +Snapshots use the ordinary repository cache validation, upcasting and tail +loader on both native and cell command paths. A valid snapshot avoids loading +old event payloads; an unusable cache rebuilds from the authoritative events. + +### Breaking storage and host API change + +Workers now open cells with `AggregateCell::from_state` or +`from_state_with_snapshots`, and use `drain_outbox` from their alarm handler. +The whole-state export/restore and `persist_and_drain_outbox` APIs are not +available on the Worker host. Native in-process conformance fixtures are not a +production persistence adapter. + +Existing `cell_state` databases are rejected with an explicit migration-required +error. They are not silently reset or opened through a legacy adapter. Back up +retained development data and migrate it explicitly before changing an existing +fleet; creating a fresh test namespace is appropriate only for disposable data. +The SQL migration inventory and checksums also reject incompatible or newer +schemas. Queue is intentionally not modeled as a full Distributed `Bus`: it has one consumer and no fanout. `CelldQueueRelay` is generic over `MessagePublisher`, @@ -133,6 +158,23 @@ and consumer deployments as separate scripts without changing the relay code. Without `CELLD_URL`, `cargo test --test celld` checks the fixtures and skips the live HTTP round trips. +The independent storage proof owns a temporary celld fleet and deliberately +kills only the processes it starts: + +```sh +(cd tests/celld/worker && worker-build --release --features storage-conformance) +node tests/celld/storage-conformance.mjs +``` + +It requires Node.js, sqlite3, esbuild and celld in addition to the Worker +toolchain. It tests final-write rollback, lease fencing during commit, +Queue-acceptance/delete crash redelivery with stable IDs, prearmed-alarm +recovery without another cell request, receipt replay after delivery, and more +than 8 MiB of event payload in a single snapshot-backed cell across restart. +It prints and retains its temporary artifact directory. Fault probes are +feature-gated out of ordinary Worker builds. CI runs this proof separately +from the full Queue/NATS/browser profile. + Every non-health aggregate route requires `DISTRIBUTED_INTERNAL_SECRET`. The checked-in value is loopback test data only; production requires a separately provisioned secret plus the normal network policy. diff --git a/tests/celld/main.rs b/tests/celld/main.rs index 4ef7abdc1..4f1af64dd 100644 --- a/tests/celld/main.rs +++ b/tests/celld/main.rs @@ -76,14 +76,15 @@ fn worker_declares_sqlite_todo_and_chat_cells() { assert!(!source.contains("outbox.release")); assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_outbox")); assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_commands")); - assert!(source.contains("CREATE TABLE IF NOT EXISTS cell_state")); - assert!(source.contains("durable_state")); - assert!(source.contains("restore_durable_state")); - assert!(source.contains("ON CONFLICT(id) DO UPDATE SET body = excluded.body")); + assert!(!source.contains("CREATE TABLE IF NOT EXISTS cell_state")); + assert!(!source.contains("durable_state")); + assert!(!source.contains("restore_durable_state")); + assert!(!source.contains("ON CONFLICT(id) DO UPDATE SET body = excluded.body")); assert!(source.contains("dispatch_idempotent")); assert!(source.contains("CelldOutbox::from_env(&env, \"OUTBOX\")")); assert!(source.contains("with_celld_outbox(outbox)")); - assert!(source.contains("persist_and_drain_outbox")); + assert!(source.contains(".drain_outbox(env)")); + assert!(!source.contains("persist_and_drain_outbox")); assert!(!source.contains("CelldQueuePublisher::from_env")); assert!(!source.contains("drain_outbox_to_queue")); assert!(!source.contains("arm_drain_alarm")); @@ -91,15 +92,15 @@ fn worker_declares_sqlite_todo_and_chat_cells() { !source.contains("outcome.released") && !source.contains("outcome.failed"), "retryable Queue outcomes must stay alarm-owned, not fail a committed command" ); - assert!(source.contains("cell_projection_event_evidence")); + assert!(source.contains("dispatch.projection_events()")); assert!(source.contains("\"events\": events")); assert!(!source.contains("CellOutboxWireItem")); assert!(!source.contains("restore_durable_commands")); - assert!(source.contains("sealed_row")); - assert!(source.contains("new_with_snapshots")); + assert!(!source.contains("sealed_row")); + assert!(source.contains("from_state_with_snapshots")); assert!(!source.contains("restore_durable_events")); assert!(!source.contains("restore_durable_snapshots")); - assert!(source.contains("restore_cell_state")); + assert!(!source.contains("restore_cell_state")); } #[test] diff --git a/tests/celld/storage-conformance.mjs b/tests/celld/storage-conformance.mjs new file mode 100644 index 000000000..5263197d4 --- /dev/null +++ b/tests/celld/storage-conformance.mjs @@ -0,0 +1,219 @@ +// Build the fixture with worker-build --release --features storage-conformance. +// Owns an isolated celld process group and temporary object store. It never +// restarts a caller's fleet or edits its data; artifacts are retained on failure. +import assert from "node:assert/strict"; +import { spawn, execFileSync } from "node:child_process"; +import { once } from "node:events"; +import { createWriteStream } from "node:fs"; +import { cp, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { createServer } from "node:net"; +import { fileURLToPath } from "node:url"; +import { setTimeout as delay } from "node:timers/promises"; + +const here = dirname(fileURLToPath(import.meta.url)); +const artifacts = await mkdtemp(join(tmpdir(), "distributed-cell-storage-")); +const project = join(artifacts, "worker"); +await mkdir(project); +await cp(join(here, "worker/build"), join(project, "build"), { recursive: true }); +const config = JSON.parse(await readFile(join(here, "worker/wrangler.jsonc"), "utf8")); +await writeFile(join(project, "wrangler.jsonc"), JSON.stringify(config, null, 2)); +const server = createServer(); +server.listen(0, "127.0.0.1"); +await once(server, "listening"); +const port = server.address().port; +await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); +const base = `http://127.0.0.1:${port}`; +const headers = { + "content-type": "application/json", + "x-distributed-internal-secret": config.vars.DISTRIBUTED_INTERNAL_SECRET, + "x-distributed-service-id": "cell-storage-conformance", + "x-distributed-principal-partition": "alice", + "x-user-id": "alice", + "x-roles": "user", +}; +let child; +let generation = 0; +let commandSequence = 0; +const results = []; +const commandId = () => `0190a000-0000-7000-8000-${String(++commandSequence).padStart(12, "0")}`; +async function until(description, predicate, timeout = 70_000) { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const value = await predicate(); + if (value) return value; + if (child?.exitCode !== null && child?.exitCode !== undefined) throw new Error("celld exited"); + await delay(200); + } + throw new Error(`timed out: ${description}; artifacts: ${project}`); +} +async function start() { + const log = createWriteStream(join(artifacts, `celld-${++generation}.log`)); + child = spawn("celld", ["dev", project, "--host", "127.0.0.1", "--port", String(port), "--logs"], { + detached: true, + env: { ...process.env, RUST_LOG: "warn" }, + stdio: ["ignore", "pipe", "pipe"], + }); + child.stdout.pipe(log, { end: false }); + child.stderr.pipe(log, { end: false }); + child.once("close", () => log.end()); + child.once("error", error => console.error(error)); + await until("isolated Worker readiness", async () => { + try { return (await fetch(base + "/health", { signal: AbortSignal.timeout(1000) })).ok; } + catch { return false; } + }); +} +async function crash() { + const owned = child; + child = undefined; + if (!owned || owned.exitCode !== null) return; + const exited = once(owned, "close"); + // celld dev creates a separate process group for its runtime child. Freeze + // our launcher while resolving its exact descendants so it cannot respawn. + process.kill(owned.pid, "SIGSTOP"); + const processes = execFileSync("ps", ["-axo", "pid=,ppid="], { encoding: "utf8" }) + .trim().split("\n").map(line => line.trim().split(/\s+/).map(Number)); + const descendants = []; + function visit(parent) { + for (const [pid, ppid] of processes) if (ppid === parent) { + visit(pid); + descendants.push(pid); + } + } + visit(owned.pid); + for (const pid of [...descendants, owned.pid]) { + try { process.kill(pid, "SIGKILL"); } + catch (error) { if (error.code !== "ESRCH") throw error; } + } + await exited; +} +async function post(id, path, body, extraHeaders = {}) { + return fetch(`${base}/todo/${id}/${path}`, { + method: "POST", headers: { ...headers, ...extraHeaders }, + body: JSON.stringify(body), signal: AbortSignal.timeout(20_000), + }); +} +async function probe(id, operation) { + const response = await post(id, "__storage_test", { operation }); + assert.equal(response.status, 200, `${operation}: ${await response.clone().text()}`); + return operation === "inspect" ? response.json() : response.text(); +} +async function command(id, name, input, command = commandId(), extraHeaders = {}) { + const response = await post(id, name, { commandId: command, input }, extraHeaders); + const body = await response.json(); + assert.equal(response.status, name === "todo.create" ? 201 : 200, JSON.stringify(body)); + return body; +} +async function queueRows() { + const runtime = join(project, ".celld/dev/runtime"); + try { + const queue = (await readdir(runtime)).find(name => name.startsWith("__Queue:")); + if (!queue) return []; + const ltx = join(runtime, queue, "ltx"); + const epochs = (await readdir(ltx)).filter(name => /^e[0-9]+$/.test(name)) + .sort((a, b) => Number(b.slice(1)) - Number(a.slice(1))); + if (!epochs.length) return []; + const rows = execFileSync("sqlite3", ["-readonly", "-json", join(ltx, epochs[0], "db.sqlite"), + "SELECT seq, hex(body) AS body FROM __queue_messages ORDER BY seq"], { encoding: "utf8", maxBuffer: 128 * 1024 * 1024 }); + return rows.trim() ? JSON.parse(rows) : []; + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } +} +async function record(name, evidence) { + results.push({ name, evidence }); + console.log(JSON.stringify({ name, evidence })); + await writeFile(join(artifacts, "results.json"), JSON.stringify(results, null, 2)); +} + +try { + console.log(`Storage proof artifacts: ${artifacts}`); + await start(); + for (const fault of ["fail-completion", "expire-at-commit"]) { + const id = fault; + await probe(id, fault); + const cid = commandId(); + const failed = await post(id, "todo.create", { commandId: cid, input: { title: fault } }); + assert.ok(failed.status >= 400, await failed.text()); + const rollback = (await probe(id, "inspect")).counts; + assert.equal(rollback.events, 0); + assert.equal(rollback.snapshots, 0); + assert.equal(rollback.completed, 0); + assert.equal(rollback.outbox, 0); + await probe(id, "clear-faults"); + await command(id, "todo.create", { title: fault }, cid); + const recovered = (await probe(id, "inspect")).counts; + assert.equal(recovered.events, 1); + assert.equal(recovered.snapshots, 1); + assert.equal(recovered.completed, 1); + await record(fault, { rollback, recovered }); + } + + // The acceptance/delete gap: the test Worker clears its fault on activation. + // Only the retained lease and alarm may cause the duplicate send. + const before = (await queueRows()).length; + await probe("settlement-crash", "fail-settlement"); + const cid = commandId(); + const original = await command("settlement-crash", "todo.create", { title: "delivery proof" }, cid); + const accepted = await queueRows(); + assert.equal(accepted.length, before + 1); + const claimed = await probe("settlement-crash", "inspect"); + assert.equal(claimed.outbox[0].status, "in_flight"); + await crash(); + await start(); + const retried = await until("alarm redelivers after acceptance/delete crash, without a cell request", async () => { + const rows = await queueRows(); + return rows.length >= before + 2 && rows; + }); + assert.equal(retried[before].body, retried[before + 1].body, "stable delivery envelope survives restart"); + const replay = await command("settlement-crash", "todo.create", { title: "delivery proof" }, cid); + assert.equal(replay.receipt.replayed, true); + assert.deepEqual(replay.payload, original.payload); + assert.deepEqual(replay.events, original.events); + const settled = (await probe("settlement-crash", "inspect")).counts; + assert.equal(settled.outbox, 0); + assert.equal(settled.events, 1); + await record("accepted-before-delete restart", settled); + + const beforeDeferred = (await queueRows()).length; + await command("commit-crash", "todo.create", { title: "watchdog proof" }, commandId(), { + "x-distributed-test-defer-drain": "1", + }); + await crash(); + await start(); + await until("prearmed alarm publishes a committed row without another cell request", async () => + (await queueRows()).length > beforeDeferred); + await record("committed-before-send restart", (await probe("commit-crash", "inspect")).counts); + + // More than 8 MiB of actual event payload in one cell, not padding a result. + const payload = "x".repeat(8192); + const firstId = commandId(); + const first = await command("growth", "todo.create", { title: "0 " + payload }, firstId); + for (let i = 1; i <= 1100; i++) { + await command("growth", "todo.rename", { title: i + " " + payload }); + if (i % 100 === 0) console.log(`Growth proof: ${i} appended commands`); + } + const grown = (await probe("growth", "inspect")).counts; + assert.equal(grown.events, 1101); + assert.ok(grown.eventBytes > 8 * 1024 * 1024); + assert.equal(grown.snapshotVersion, 1101); + assert.equal(grown.snapshots, 1); + assert.equal(grown.completed, 1101); + assert.equal(grown.outbox, 0); + assert.equal(grown.wholeStateTables, 0); + await crash(); + await start(); + const oldRetry = await command("growth", "todo.create", { title: "0 " + payload }, firstId); + assert.equal(oldRetry.receipt.replayed, true); + assert.deepEqual(oldRetry.events, first.events); + await command("growth", "todo.rename", { title: "after restart" }); + const afterRestart = (await probe("growth", "inspect")).counts; + assert.equal(afterRestart.events, 1102); + assert.equal(afterRestart.snapshotVersion, 1102); + await record("growth and snapshot-tail restart", { grown, afterRestart }); +} finally { + await crash(); + console.log(`Retained storage proof artifacts: ${artifacts}`); +} diff --git a/tests/celld/worker/Cargo.toml b/tests/celld/worker/Cargo.toml index c928ead9d..582f25024 100644 --- a/tests/celld/worker/Cargo.toml +++ b/tests/celld/worker/Cargo.toml @@ -12,6 +12,10 @@ description = "workers-rs Todo and Chat cells: AggregateCell + domain handles" [lib] crate-type = ["cdylib"] +[features] +# Only the isolated crash/rollback harness builds these authenticated probes. +storage-conformance = [] + [dependencies] console_error_panic_hook = "0.1" distributed = { path = "../../..", default-features = false, features = ["workers-rs"] } diff --git a/tests/celld/worker/src/lib.rs b/tests/celld/worker/src/lib.rs index ce9360f6d..cfac2e983 100644 --- a/tests/celld/worker/src/lib.rs +++ b/tests/celld/worker/src/lib.rs @@ -1,43 +1,35 @@ //! Todo and Chat Durable Object classes backed by `AggregateCell`. //! //! HTTP is command-named wait-path (`POST /{command}` with -//! `{ commandId, input }`) plus GET of the sealed row. GraphQL and +//! `{ commandId, input }`) plus GET of the aggregate state. GraphQL and //! projectors are not methods on this class (`PCH-REQ-005`). Chat `@live` //! stays on the GraphQL host. use chat_domain::{post, ChatMessage, ChatMessageState}; use distributed::cell_host::{ AggregateCell, CellCommandIdentity, CellDispatchError, CellDispatchResult, CellWaitPathRequest, - CelldOutbox, DurableAggregateCellState, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, - CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, + CelldOutbox, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, }; use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; use serde::de::DeserializeOwned; -use serde::Deserialize; use serde_json::{json, Value}; use todo_domain::{ archive, complete, create, force_archive, purge, rename, reopen, Todo, TodoState, }; use worker::*; -const MAX_CELL_REQUEST_BYTES: usize = 2 * 1024 * 1024; +#[cfg(feature = "storage-conformance")] +mod storage_conformance; -const STATE_DDL: &str = "CREATE TABLE IF NOT EXISTS cell_state ( - id INTEGER PRIMARY KEY CHECK (id = 1), - body TEXT NOT NULL -)"; +const MAX_CELL_REQUEST_BYTES: usize = 2 * 1024 * 1024; -async fn persist_and_drain_cell( - sql: &SqlStorage, - storage: &Storage, - env: &Env, - cell: &AggregateCell, -) -> Result<()> +async fn drain_cell(env: &Env, cell: &AggregateCell) -> Result<()> where A: distributed::Aggregate + Send + Sync + 'static, { let outcome = cell - .persist_and_drain_outbox(env, storage, |state| persist_cell_state(sql, state)) + .drain_outbox(env) .await .map_err(|error| Error::RustError(error.to_string()))?; for error in outcome.deferred { @@ -50,23 +42,43 @@ where Ok(()) } +async fn drain_after_command(env: &Env, cell: &AggregateCell, request: &Request) +where + A: distributed::Aggregate + Send + Sync + 'static, +{ + #[cfg(feature = "storage-conformance")] + if request + .headers() + .get("x-distributed-test-defer-drain") + .ok() + .flatten() + .as_deref() + == Some("1") + { + return; + } + #[cfg(not(feature = "storage-conformance"))] + let _ = request; + if let Err(error) = drain_cell(env, cell).await { + worker::console_error!("post-commit Queue drain deferred: {}", error); + } +} + #[durable_object] pub struct TodoCell { cell: AggregateCell, + #[cfg(feature = "storage-conformance")] sql: SqlStorage, - storage: Storage, env: Env, } impl DurableObject for TodoCell { fn new(state: State, env: Env) -> Self { console_error_panic_hook::set_once(); - let storage = state.storage(); - let sql = storage.sql(); - sql.exec(STATE_DDL, None).expect("create cell_state"); - let shard = state.id().name().unwrap_or_else(|| "todo".to_string()); + #[cfg(feature = "storage-conformance")] + let sql = state.storage().sql(); let outbox = CelldOutbox::from_env(&env, "OUTBOX").expect("OUTBOX Queue binding"); - let cell = AggregateCell::::new_with_snapshots(shard.clone(), 1) + let cell = AggregateCell::::from_state_with_snapshots(state, 1) .expect("todo cell identity") .mount(create()) .mount(rename()) @@ -76,11 +88,12 @@ impl DurableObject for TodoCell { .mount(force_archive()) .mount(purge()) .with_celld_outbox(outbox); - let _ = restore_cell_state(&sql, &cell); + #[cfg(feature = "storage-conformance")] + storage_conformance::reset_faults_on_activation(&sql).expect("reset test faults"); Self { cell, + #[cfg(feature = "storage-conformance")] sql, - storage, env, } } @@ -89,9 +102,6 @@ impl DurableObject for TodoCell { if let Err(error) = authenticate_internal_request(&req, &self.env) { return internal_auth_error(error); } - if let Err(error) = restore_cell_state(&self.sql, &self.cell) { - return json_status(json!({ "error": error }), 500); - } let url = req.url()?; let parts: Vec = url .path() @@ -104,18 +114,18 @@ impl DurableObject for TodoCell { _ => return json_status(json!({ "error": "missing todo id" }), 400), }; + #[cfg(feature = "storage-conformance")] + if parts.get(2).map(String::as_str) == Some("__storage_test") { + return match storage_conformance::handle(&self.sql, &mut req).await { + Ok(response) => Ok(response), + Err(error) => Response::error(error.to_string(), 500), + }; + } + match (req.method(), parts.get(2).map(String::as_str)) { (Method::Get, None) => get_todo(&self.cell, &id).await, (Method::Post, Some("todo.create")) => { - create_todo( - &self.sql, - &self.storage, - &self.env, - &self.cell, - &id, - &mut req, - ) - .await + create_todo(&self.env, &self.cell, &id, &mut req).await } (Method::Post, Some(command)) if matches!( @@ -128,26 +138,14 @@ impl DurableObject for TodoCell { | "todo.purge" ) => { - transition_todo( - &self.sql, - &self.storage, - &self.env, - &self.cell, - &id, - command, - &mut req, - ) - .await + transition_todo(&self.env, &self.cell, &id, command, &mut req).await } _ => json_status(json!({ "error": "not found" }), 404), } } async fn alarm(&self) -> Result { - if let Err(error) = restore_cell_state(&self.sql, &self.cell) { - return json_status(json!({ "error": error }), 500); - } - persist_and_drain_cell(&self.sql, &self.storage, &self.env, &self.cell).await?; + drain_cell(&self.env, &self.cell).await?; Response::ok("ok") } } @@ -155,39 +153,24 @@ impl DurableObject for TodoCell { #[durable_object] pub struct ChatCell { cell: AggregateCell, - sql: SqlStorage, - storage: Storage, env: Env, } impl DurableObject for ChatCell { fn new(state: State, env: Env) -> Self { console_error_panic_hook::set_once(); - let storage = state.storage(); - let sql = storage.sql(); - sql.exec(STATE_DDL, None).expect("create cell_state"); - let shard = state.id().name().unwrap_or_else(|| "chat".to_string()); let outbox = CelldOutbox::from_env(&env, "OUTBOX").expect("OUTBOX Queue binding"); - let cell = AggregateCell::::new(shard.clone()) + let cell = AggregateCell::::from_state(state) .expect("chat cell identity") .mount(post()) .with_celld_outbox(outbox); - let _ = restore_cell_state(&sql, &cell); - Self { - cell, - sql, - storage, - env, - } + Self { cell, env } } async fn fetch(&self, mut req: Request) -> Result { if let Err(error) = authenticate_internal_request(&req, &self.env) { return internal_auth_error(error); } - if let Err(error) = restore_cell_state(&self.sql, &self.cell) { - return json_status(json!({ "error": error }), 500); - } let url = req.url()?; let parts: Vec = url .path() @@ -203,25 +186,14 @@ impl DurableObject for ChatCell { match (req.method(), parts.get(2).map(String::as_str)) { (Method::Get, None) => get_chat(&self.cell, &id).await, (Method::Post, Some("chat.post")) => { - post_chat( - &self.sql, - &self.storage, - &self.env, - &self.cell, - &id, - &mut req, - ) - .await + post_chat(&self.env, &self.cell, &id, &mut req).await } _ => json_status(json!({ "error": "not found" }), 404), } } async fn alarm(&self) -> Result { - if let Err(error) = restore_cell_state(&self.sql, &self.cell) { - return json_status(json!({ "error": error }), 500); - } - persist_and_drain_cell(&self.sql, &self.storage, &self.env, &self.cell).await?; + drain_cell(&self.env, &self.cell).await?; Response::ok("ok") } } @@ -317,9 +289,6 @@ fn request_session(req: &Request) -> Session { } async fn get_chat(cell: &AggregateCell, id: &str) -> Result { - if let Ok(Some(row)) = cell.sealed_row() { - return json_status(row, 200); - } match cell.load().await { Ok(Some(message)) => json_status(http_chat(&ChatMessageState::from(&message)), 200), Ok(None) => json_status(json!({ "error": "not found", "id": id }), 404), @@ -328,8 +297,6 @@ async fn get_chat(cell: &AggregateCell, id: &str) -> Result, id: &str, @@ -358,13 +325,12 @@ async fn post_chat( .await { Ok(dispatch) => { - seal_chat_from_load(cell).await; - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; let events = serde_json::to_value(dispatch.projection_events())?; wait_path_ok(dispatch.payload().clone(), &dispatch, 201, events) } Err(error) => { - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; map_cell_error(error, cell) } } @@ -380,30 +346,7 @@ fn http_chat(state: &ChatMessageState) -> Value { }) } -fn restore_cell_state( - sql: &SqlStorage, - cell: &AggregateCell, -) -> std::result::Result<(), String> -where - A: distributed::Aggregate + Send + Sync + 'static, -{ - if let Some(state) = load_cell_state(sql).map_err(|error| error.to_string())? { - cell.restore_durable_state(state) - .map_err(|error| error.to_string())?; - } - Ok(()) -} - -async fn seal_chat_from_load(cell: &AggregateCell) { - if let Ok(Some(message)) = cell.load().await { - let _ = cell.replace_sealed_row(http_chat(&ChatMessageState::from(&message))); - } -} - async fn get_todo(cell: &AggregateCell, id: &str) -> Result { - if let Ok(Some(row)) = cell.sealed_row() { - return json_status(row, 200); - } match cell.load().await { Ok(Some(todo)) => json_status(http_todo(&TodoState::from(&todo)), 200), Ok(None) => json_status(json!({ "error": "not found", "id": id }), 404), @@ -462,8 +405,6 @@ fn wait_path_ok( } async fn create_todo( - sql: &SqlStorage, - storage: &Storage, env: &Env, cell: &AggregateCell, id: &str, @@ -496,8 +437,7 @@ async fn create_todo( .await { Ok(dispatch) => { - seal_from_load(cell).await; - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; let events = serde_json::to_value(dispatch.projection_events())?; wait_path_ok( http_from_command(id, dispatch.payload(), &title), @@ -507,15 +447,13 @@ async fn create_todo( ) } Err(error) => { - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; map_cell_error(error, cell) } } } async fn transition_todo( - sql: &SqlStorage, - storage: &Storage, env: &Env, cell: &AggregateCell, id: &str, @@ -548,8 +486,7 @@ async fn transition_todo( .await { Ok(dispatch) => { - seal_from_load(cell).await; - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; let events = serde_json::to_value(dispatch.projection_events())?; let title = cell .load() @@ -566,7 +503,7 @@ async fn transition_todo( ) } Err(error) => { - persist_and_drain_cell(sql, storage, env, cell).await?; + drain_after_command(env, cell, req).await; map_cell_error(error, cell) } } @@ -634,36 +571,3 @@ async fn bounded_json( } serde_json::from_slice(&bytes).map_err(|_| "invalid cell request JSON") } - -async fn seal_from_load(cell: &AggregateCell) { - if let Ok(Some(todo)) = cell.load().await { - let _ = cell.replace_sealed_row(http_todo(&TodoState::from(&todo))); - } -} - -fn persist_cell_state(sql: &SqlStorage, state: &DurableAggregateCellState) -> Result<()> { - let body = serde_json::to_string(state).map_err(|error| Error::RustError(error.to_string()))?; - sql.exec( - "INSERT INTO cell_state (id, body) VALUES (1, ?) \ - ON CONFLICT(id) DO UPDATE SET body = excluded.body", - Some(vec![body.into()]), - )?; - Ok(()) -} - -fn load_cell_state(sql: &SqlStorage) -> Result> { - let rows: Vec = sql - .exec("SELECT body FROM cell_state WHERE id = 1", None)? - .to_array()?; - rows.into_iter() - .next() - .map(|row| { - serde_json::from_str(&row.body).map_err(|error| Error::RustError(error.to_string())) - }) - .transpose() -} - -#[derive(Deserialize)] -struct StateRow { - body: String, -} diff --git a/tests/celld/worker/src/storage_conformance.rs b/tests/celld/worker/src/storage_conformance.rs new file mode 100644 index 000000000..8010acffd --- /dev/null +++ b/tests/celld/worker/src/storage_conformance.rs @@ -0,0 +1,79 @@ +//! Fault probes for the isolated test harness, absent from ordinary builds. +//! The Worker authenticates the internal request before reaching this module. +//! Operations are finite and fixed; this is not an arbitrary-SQL endpoint. + +use serde_json::{json, Value}; +use worker::*; + +pub async fn handle(sql: &SqlStorage, request: &mut Request) -> Result { + if request.method() != Method::Post { + return Response::error("method not allowed", 405); + } + let body: Value = request.json().await?; + match body.get("operation").and_then(Value::as_str) { + Some("inspect") => { + let rows: Vec = sql.exec( + "SELECT + (SELECT COUNT(*) FROM aggregate_events) AS events, + (SELECT COALESCE(SUM(length(payload)), 0) FROM aggregate_events) AS eventBytes, + (SELECT COALESCE(MAX(sequence), 0) FROM aggregate_events) AS version, + (SELECT COUNT(*) FROM aggregate_snapshots) AS snapshots, + (SELECT COALESCE(MAX(version), 0) FROM aggregate_snapshots) AS snapshotVersion, + (SELECT COUNT(*) FROM command_ledger) AS receipts, + (SELECT COUNT(*) FROM command_ledger WHERE completed_at IS NOT NULL) AS completed, + (SELECT COUNT(*) FROM outbox_messages) AS outbox, + (SELECT COUNT(*) FROM sqlite_master WHERE name = 'cell_state') AS wholeStateTables", + None, + )?.to_array()?; + let outbox: Vec = sql + .exec( + "SELECT message_id, status, attempts FROM outbox_messages ORDER BY message_id", + None, + )? + .to_array()?; + Response::from_json(&json!({ "counts": rows[0], "outbox": outbox })) + } + Some("fail-completion") => { + sql.exec( + "CREATE TRIGGER test_fail_completion BEFORE UPDATE ON command_ledger + WHEN NEW.state = 'succeeded' + BEGIN SELECT RAISE(ABORT, 'test receipt write failure'); END", + None, + )?; + Response::ok("armed") + } + Some("expire-at-commit") => { + sql.exec( + "CREATE TRIGGER test_expire_attempt AFTER INSERT ON aggregate_events + BEGIN UPDATE command_ledger SET lease_expires_at = 0 WHERE state = 'in_progress'; END", + None, + )?; + Response::ok("armed") + } + Some("fail-settlement") => { + sql.exec( + "CREATE TRIGGER test_fail_settlement BEFORE DELETE ON outbox_messages + BEGIN SELECT RAISE(ABORT, 'test settlement failure'); END", + None, + )?; + Response::ok("armed") + } + Some("clear-faults") => { + reset_faults_on_activation(sql)?; + Response::ok("cleared") + } + _ => Response::error("unknown probe", 400), + } +} + +// celld intentionally forbids TEMP schema objects. These fixed test triggers +// are activation-scoped by explicit cleanup on the next test Worker activation. +pub fn reset_faults_on_activation(sql: &SqlStorage) -> Result<()> { + sql.exec( + "DROP TRIGGER IF EXISTS test_fail_completion; + DROP TRIGGER IF EXISTS test_expire_attempt; + DROP TRIGGER IF EXISTS test_fail_settlement;", + None, + )?; + Ok(()) +} From d9e529da5f1523dc99a799ce94e2f8cdbe3c6565 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 05:32:09 -0500 Subject: [PATCH 022/484] fix: preserve causal capabilities through queued repositories --- src/microsvc/cell_host/store.rs | 38 ++++---- src/microsvc/dependencies.rs | 97 ++++++++++++------- src/microsvc/mod.rs | 1 + src/microsvc/service/tests.rs | 5 + src/queued_repo/repository.rs | 45 +++++++++ tests/celld/README.md | 7 +- tests/celld/storage-conformance.mjs | 31 ++++-- tests/celld/worker/src/storage_conformance.rs | 12 ++- 8 files changed, 174 insertions(+), 62 deletions(-) diff --git a/src/microsvc/cell_host/store.rs b/src/microsvc/cell_host/store.rs index e8639ea69..af4b3b199 100644 --- a/src/microsvc/cell_host/store.rs +++ b/src/microsvc/cell_host/store.rs @@ -48,23 +48,7 @@ enum CellOwnership { }, } -/// Private command-side repository for one cell instance (`{aggregate_type}:{shard}`). -/// -/// Exclusive cells reject any stream that is not this cell's shard. Parent -/// cells (`for_parent_shard`) hold sibling streams of one game and commit -/// them in one [`CommitBatch`]. -/// -/// ```compile_fail -/// fn two_cell_transaction_does_not_exist( -/// left: &distributed::cell_host::CellStreamStore, -/// right: &distributed::cell_host::CellStreamStore, -/// batch: distributed::CommitBatch<'_>, -/// ) { -/// let _ = left.commit_across(right, batch); -/// } -/// ``` - -/// One stream's event records for Durable Object SQLite persistence. +/// One stream's event records in a native restart-test export. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellEvents { @@ -72,7 +56,7 @@ pub struct DurableCellEvents { pub events: Vec, } -/// Snapshot cache record for Durable Object SQLite persistence. +/// Snapshot cache record in a native restart-test export. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellSnapshot { @@ -86,7 +70,7 @@ pub struct DurableCellSnapshot { pub payload: Vec, } -/// One versioned command-ledger row for Durable Object SQLite persistence. +/// One versioned command-ledger row in a native restart-test export. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub struct DurableCellCommand { @@ -94,7 +78,7 @@ pub struct DurableCellCommand { pub body: String, } -/// Current persisted aggregate-cell state envelope version. +/// Current native restart-test export version. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub const DURABLE_AGGREGATE_CELL_STATE_VERSION: u16 = 1; @@ -112,6 +96,20 @@ pub struct DurableAggregateCellState { pub sealed_row: Option, } +/// Private command-side repository for one cell instance (`{aggregate_type}:{shard}`). +/// +/// Exclusive cells reject any stream that is not this cell's shard. Parent +/// cells hold sibling streams and commit them in one [`CommitBatch`]. +/// +/// ```compile_fail +/// fn two_cell_transaction_does_not_exist( +/// left: &distributed::cell_host::CellStreamStore, +/// right: &distributed::cell_host::CellStreamStore, +/// batch: distributed::CommitBatch<'_>, +/// ) { +/// let _ = left.commit_across(right, batch); +/// } +/// ``` #[derive(Clone)] pub struct CellStreamStore { ownership: CellOwnership, diff --git a/src/microsvc/dependencies.rs b/src/microsvc/dependencies.rs index 0b3e11d60..e9870e831 100644 --- a/src/microsvc/dependencies.rs +++ b/src/microsvc/dependencies.rs @@ -101,44 +101,60 @@ pub(crate) trait CausalHostProjections: Send + Sync { + 'a; } -impl CausalHostProjections for T { - #[cfg(feature = "graphql")] - fn command_obligation_evidence<'a>( - &'a self, - request: &'a crate::projection_protocol::ProjectionObligationEvidenceBatchRequest, - ) -> impl std::future::Future< - Output = Result< +// Concrete query-owning adapters forward only the causal host operations. +// A queued command-only adapter forwards this smaller capability independently. +macro_rules! direct_causal_projection_methods { + () => { + #[cfg(feature = "graphql")] + async fn command_obligation_evidence( + &self, + request: &crate::projection_protocol::ProjectionObligationEvidenceBatchRequest, + ) -> Result< crate::projection_protocol::ProjectionObligationEvidenceBatch, crate::projection_protocol::ProjectionProtocolError, - >, - > + Send - + 'a { - self.projection_obligation_evidence_batch(request) - } + > { + crate::projection_protocol::ProjectionProtocolStore::projection_obligation_evidence_batch( + self, request, + ).await + } - #[cfg(feature = "graphql")] - fn command_causation_evidence<'a>( - &'a self, - request: &'a crate::projection_protocol::ProjectionCausationEvidenceRequest, - ) -> impl std::future::Future< - Output = Result< + #[cfg(feature = "graphql")] + async fn command_causation_evidence( + &self, + request: &crate::projection_protocol::ProjectionCausationEvidenceRequest, + ) -> Result< crate::projection_protocol::ProjectionCausationEvidenceBatch, crate::projection_protocol::ProjectionProtocolError, - >, - > + Send - + 'a { - self.projection_causation_evidence(request) - } - fn __register_direct_projection_models<'a>( - &'a self, - topology: &'a crate::projection_protocol::ProjectorTopologyId, - ownership: &'a [crate::projection_protocol::ProjectionModelOwnership], - ) -> impl std::future::Future< - Output = Result<(), crate::projection_protocol::ProjectionProtocolError>, - > + Send - + 'a { - self.register_projection_models(topology, ownership) - } + > { + crate::projection_protocol::ProjectionProtocolStore::projection_causation_evidence( + self, request, + ).await + } + + async fn __register_direct_projection_models( + &self, + topology: &crate::projection_protocol::ProjectorTopologyId, + ownership: &[crate::projection_protocol::ProjectionModelOwnership], + ) -> Result<(), crate::projection_protocol::ProjectionProtocolError> { + crate::projection_protocol::ProjectionProtocolStore::register_projection_models( + self, topology, ownership, + ).await + } + }; +} +#[cfg(all(test, feature = "graphql"))] +pub(crate) use direct_causal_projection_methods; + +impl CausalHostProjections for crate::InMemoryRepository { + direct_causal_projection_methods!(); +} + +#[cfg(any(feature = "sqlite", feature = "postgres"))] +impl CausalHostProjections for crate::sqlx_repo::repo::SqlxRepository +where + Self: ProjectionProtocolStore, +{ + direct_causal_projection_methods!(); } /// Compile-time extraction of the one aggregate repository owned by a typed @@ -438,6 +454,21 @@ mod tests { fn assert_has_outbox_store() {} + fn assert_causal_backend() {} + + // Keep this generic: a concrete SQL/memory instantiation would also satisfy + // ProjectionProtocolStore and conceal an accidental query-store bound. + fn assert_queued_causal_backend() { + assert_causal_backend::>(); + } + + #[test] + fn causal_capability_resolves_without_a_projection_store() { + assert_queued_causal_backend::( + ); + assert_queued_causal_backend::(); + } + #[test] fn has_outbox_store_resolves_through_repo_wrappers() { // The capability must resolve for the leaf repo and through the diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index 54c17d96c..2b38adc8f 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -59,6 +59,7 @@ mod causal; pub mod cell_host; mod context; mod dependencies; +pub(crate) use dependencies::CausalHostProjections; mod descriptor; mod error; pub(crate) mod lifecycle; diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index d359a31ce..089f86c79 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -832,6 +832,11 @@ impl CausalRepositoryIdentity for AmbiguousCommitRepository { } } +#[cfg(feature = "graphql")] +impl crate::microsvc::dependencies::CausalHostProjections for AmbiguousCommitRepository { + crate::microsvc::dependencies::direct_causal_projection_methods!(); +} + #[cfg(feature = "graphql")] impl ProjectionProtocolStore for AmbiguousCommitRepository { fn register_projection_models<'a>( diff --git a/src/queued_repo/repository.rs b/src/queued_repo/repository.rs index 9e4bcbd48..d4138054b 100644 --- a/src/queued_repo/repository.rs +++ b/src/queued_repo/repository.rs @@ -304,6 +304,51 @@ where } } +impl crate::microsvc::CausalHostProjections for QueuedRepository +where + R: crate::microsvc::CausalHostProjections, + L: LockManager, +{ + #[cfg(feature = "graphql")] + fn command_obligation_evidence<'a>( + &'a self, + request: &'a crate::projection_protocol::ProjectionObligationEvidenceBatchRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionObligationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + self.inner.command_obligation_evidence(request) + } + + #[cfg(feature = "graphql")] + fn command_causation_evidence<'a>( + &'a self, + request: &'a crate::projection_protocol::ProjectionCausationEvidenceRequest, + ) -> impl std::future::Future< + Output = Result< + crate::projection_protocol::ProjectionCausationEvidenceBatch, + crate::projection_protocol::ProjectionProtocolError, + >, + > + Send + + 'a { + self.inner.command_causation_evidence(request) + } + fn __register_direct_projection_models<'a>( + &'a self, + topology: &'a crate::projection_protocol::ProjectorTopologyId, + ownership: &'a [crate::projection_protocol::ProjectionModelOwnership], + ) -> impl std::future::Future< + Output = Result<(), crate::projection_protocol::ProjectionProtocolError>, + > + Send + + 'a { + self.inner + .__register_direct_projection_models(topology, ownership) + } +} + impl ProjectionProtocolStore for QueuedRepository where R: ProjectionProtocolStore, diff --git a/tests/celld/README.md b/tests/celld/README.md index 4e6475899..0f40190e5 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -169,8 +169,11 @@ node tests/celld/storage-conformance.mjs It requires Node.js, sqlite3, esbuild and celld in addition to the Worker toolchain. It tests final-write rollback, lease fencing during commit, Queue-acceptance/delete crash redelivery with stable IDs, prearmed-alarm -recovery without another cell request, receipt replay after delivery, and more -than 8 MiB of event payload in a single snapshot-backed cell across restart. +recovery without another cell request, and receipt replay after delivery. It +also retains 1,101 unsent messages and more than 8 MiB of event payload in one +snapshot-backed cell, restarts it, and verifies that alarms drain the backlog +without another aggregate request. Events and receipts remain; delivered +outbox rows do not. It prints and retains its temporary artifact directory. Fault probes are feature-gated out of ordinary Worker builds. CI runs this proof separately from the full Queue/NATS/browser profile. diff --git a/tests/celld/storage-conformance.mjs b/tests/celld/storage-conformance.mjs index 5263197d4..87ddf1334 100644 --- a/tests/celld/storage-conformance.mjs +++ b/tests/celld/storage-conformance.mjs @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { spawn, execFileSync } from "node:child_process"; import { once } from "node:events"; import { createWriteStream } from "node:fs"; -import { cp, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; +import { access, cp, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, dirname } from "node:path"; import { createServer } from "node:net"; @@ -105,7 +105,7 @@ async function command(id, name, input, command = commandId(), extraHeaders = {} assert.equal(response.status, name === "todo.create" ? 201 : 200, JSON.stringify(body)); return body; } -async function queueRows() { +async function queueRows(countOnly = false) { const runtime = join(project, ".celld/dev/runtime"); try { const queue = (await readdir(runtime)).find(name => name.startsWith("__Queue:")); @@ -114,8 +114,21 @@ async function queueRows() { const epochs = (await readdir(ltx)).filter(name => /^e[0-9]+$/.test(name)) .sort((a, b) => Number(b.slice(1)) - Number(a.slice(1))); if (!epochs.length) return []; - const rows = execFileSync("sqlite3", ["-readonly", "-json", join(ltx, epochs[0], "db.sqlite"), - "SELECT seq, hex(body) AS body FROM __queue_messages ORDER BY seq"], { encoding: "utf8", maxBuffer: 128 * 1024 * 1024 }); + const database = join(ltx, epochs[0], "db.sqlite"); + // Recovery creates the epoch directory before materializing its database. + // Observe only the newest epoch; never mistake a stale epoch for delivery. + await access(database); + let rows; + try { + rows = execFileSync("sqlite3", ["-readonly", "-json", database, + countOnly ? "SELECT COUNT(*) AS count FROM __queue_messages" : + "SELECT seq, hex(body) AS body FROM __queue_messages ORDER BY seq"], { encoding: "utf8", maxBuffer: 128 * 1024 * 1024 }); + } catch (error) { + // A retired epoch may disappear between discovery and the read. + // Missing files are retryable observations; SQL errors are not. + await access(database); + throw error; + } return rows.trim() ? JSON.parse(rows) : []; } catch (error) { if (error.code === "ENOENT") return []; @@ -187,7 +200,10 @@ try { (await queueRows()).length > beforeDeferred); await record("committed-before-send restart", (await probe("commit-crash", "inspect")).counts); - // More than 8 MiB of actual event payload in one cell, not padding a result. + // Grow event history AND an unsent outbox beyond the former single-value + // ceiling. Claim failures cannot reject an already committed command. + const beforeGrowth = (await queueRows(true))[0].count; + await probe("growth", "fail-claim"); const payload = "x".repeat(8192); const firstId = commandId(); const first = await command("growth", "todo.create", { title: "0 " + payload }, firstId); @@ -201,10 +217,12 @@ try { assert.equal(grown.snapshotVersion, 1101); assert.equal(grown.snapshots, 1); assert.equal(grown.completed, 1101); - assert.equal(grown.outbox, 0); + assert.equal(grown.outbox, 1101); assert.equal(grown.wholeStateTables, 0); await crash(); await start(); + await until("large pending outbox drains from alarms without a cell request", async () => + (await queueRows(true))[0]?.count >= beforeGrowth + 1101, 120_000); const oldRetry = await command("growth", "todo.create", { title: "0 " + payload }, firstId); assert.equal(oldRetry.receipt.replayed, true); assert.deepEqual(oldRetry.events, first.events); @@ -212,6 +230,7 @@ try { const afterRestart = (await probe("growth", "inspect")).counts; assert.equal(afterRestart.events, 1102); assert.equal(afterRestart.snapshotVersion, 1102); + assert.equal(afterRestart.outbox, 0); await record("growth and snapshot-tail restart", { grown, afterRestart }); } finally { await crash(); diff --git a/tests/celld/worker/src/storage_conformance.rs b/tests/celld/worker/src/storage_conformance.rs index 8010acffd..392f3075d 100644 --- a/tests/celld/worker/src/storage_conformance.rs +++ b/tests/celld/worker/src/storage_conformance.rs @@ -58,6 +58,15 @@ pub async fn handle(sql: &SqlStorage, request: &mut Request) -> Result )?; Response::ok("armed") } + Some("fail-claim") => { + sql.exec( + "CREATE TRIGGER test_fail_claim BEFORE UPDATE ON outbox_messages + WHEN NEW.status = 'in_flight' + BEGIN SELECT RAISE(ABORT, 'test claim failure'); END", + None, + )?; + Response::ok("armed") + } Some("clear-faults") => { reset_faults_on_activation(sql)?; Response::ok("cleared") @@ -72,7 +81,8 @@ pub fn reset_faults_on_activation(sql: &SqlStorage) -> Result<()> { sql.exec( "DROP TRIGGER IF EXISTS test_fail_completion; DROP TRIGGER IF EXISTS test_expire_attempt; - DROP TRIGGER IF EXISTS test_fail_settlement;", + DROP TRIGGER IF EXISTS test_fail_settlement; + DROP TRIGGER IF EXISTS test_fail_claim;", None, )?; Ok(()) From 4a81ac95ce74013f3427ffedae6901c695b4685a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 05:57:16 -0500 Subject: [PATCH 023/484] fix: bound cell SQL batches within atomic commands --- src/microsvc/cell_host/sql_store.rs | 8 +++- tests/celld/README.md | 3 +- tests/celld/storage-conformance.mjs | 23 +++++++++ tests/celld/worker/src/lib.rs | 6 +++ tests/celld/worker/src/storage_conformance.rs | 47 +++++++++++++++++++ 5 files changed, 84 insertions(+), 3 deletions(-) diff --git a/src/microsvc/cell_host/sql_store.rs b/src/microsvc/cell_host/sql_store.rs index 70233deca..11ac0a053 100644 --- a/src/microsvc/cell_host/sql_store.rs +++ b/src/microsvc/cell_host/sql_store.rs @@ -22,6 +22,10 @@ use crate::repository::{ }; use crate::snapshot::SnapshotRecord; +// Durable Object SQL limits bindings per statement, not per transaction. +// Both shared insert planners split large commands within the same transaction. +const MAX_SQL_BIND_PARAMS: usize = 100; + #[derive(Clone)] pub(super) struct CellSqlRepository { connection: CellSqlConnection, @@ -97,7 +101,7 @@ impl CellSqlRepository { .into()); } } - for insert in sql::event_inserts(&prepared, 900)? { + for insert in sql::event_inserts(&prepared, MAX_SQL_BIND_PARAMS)? { executor.execute(insert.statement).await?; } // SQL binding errors in this runtime have no structured constraint @@ -119,7 +123,7 @@ impl CellSqlRepository { .into()); } } - for insert in outbox::inserts(&batch.outbox_messages, 900)? { + for insert in outbox::inserts(&batch.outbox_messages, MAX_SQL_BIND_PARAMS)? { executor.execute(insert.statement).await?; } for snapshot in &batch.snapshots { diff --git a/tests/celld/README.md b/tests/celld/README.md index 0f40190e5..83cafaf8a 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -167,7 +167,8 @@ node tests/celld/storage-conformance.mjs ``` It requires Node.js, sqlite3, esbuild and celld in addition to the Worker -toolchain. It tests final-write rollback, lease fencing during commit, +toolchain. It tests final-write rollback across multi-chunk event/outbox inserts +(the Worker uses at most 100 bound parameters per SQL statement), lease fencing during commit, Queue-acceptance/delete crash redelivery with stable IDs, prearmed-alarm recovery without another cell request, and receipt replay after delivery. It also retains 1,101 unsent messages and more than 8 MiB of event payload in one diff --git a/tests/celld/storage-conformance.mjs b/tests/celld/storage-conformance.mjs index 87ddf1334..b13bbab38 100644 --- a/tests/celld/storage-conformance.mjs +++ b/tests/celld/storage-conformance.mjs @@ -164,6 +164,29 @@ try { await record(fault, { rollback, recovered }); } + // One command crosses both event and outbox SQL insert chunk boundaries. + await command("batch", "todo.create", { title: "batch" }); + const batchId = commandId(); + await probe("batch", "fail-completion"); + const failedBatch = await post("batch", "todo.test_batch", { + commandId: batchId, input: { title: "batch" }, + }); + assert.ok(failedBatch.status >= 400, await failedBatch.text()); + const batchRollback = (await probe("batch", "inspect")).counts; + assert.equal(batchRollback.events, 1); + assert.equal(batchRollback.snapshotVersion, 1); + assert.equal(batchRollback.completed, 1); + assert.equal(batchRollback.outbox, 0); + await probe("batch", "clear-faults"); + const batchResult = await command("batch", "todo.test_batch", { title: "batch" }, batchId); + assert.equal(batchResult.events.length, 32); + const batchCommit = (await probe("batch", "inspect")).counts; + assert.equal(batchCommit.events, 33); + assert.equal(batchCommit.snapshotVersion, 33); + assert.equal(batchCommit.completed, 2); + assert.equal(batchCommit.outbox, 0); + await record("multi-chunk atomic command", { batchRollback, batchCommit }); + // The acceptance/delete gap: the test Worker clears its fault on activation. // Only the retained lease and alarm may cause the duplicate send. const before = (await queueRows()).length; diff --git a/tests/celld/worker/src/lib.rs b/tests/celld/worker/src/lib.rs index cfac2e983..dd287ff38 100644 --- a/tests/celld/worker/src/lib.rs +++ b/tests/celld/worker/src/lib.rs @@ -90,6 +90,8 @@ impl DurableObject for TodoCell { .with_celld_outbox(outbox); #[cfg(feature = "storage-conformance")] storage_conformance::reset_faults_on_activation(&sql).expect("reset test faults"); + #[cfg(feature = "storage-conformance")] + let cell = cell.mount(storage_conformance::test_batch()); Self { cell, #[cfg(feature = "storage-conformance")] @@ -124,6 +126,10 @@ impl DurableObject for TodoCell { match (req.method(), parts.get(2).map(String::as_str)) { (Method::Get, None) => get_todo(&self.cell, &id).await, + #[cfg(feature = "storage-conformance")] + (Method::Post, Some("todo.test_batch")) => { + transition_todo(&self.env, &self.cell, &id, "todo.test_batch", &mut req).await + } (Method::Post, Some("todo.create")) => { create_todo(&self.env, &self.cell, &id, &mut req).await } diff --git a/tests/celld/worker/src/storage_conformance.rs b/tests/celld/worker/src/storage_conformance.rs index 392f3075d..4daaf8b5b 100644 --- a/tests/celld/worker/src/storage_conformance.rs +++ b/tests/celld/worker/src/storage_conformance.rs @@ -5,6 +5,53 @@ use serde_json::{json, Value}; use worker::*; +#[derive(serde::Deserialize, distributed::CommandInput)] +pub struct BatchInput { + pub todo_id: String, + pub title: String, +} + +#[derive(serde::Serialize, distributed::CommandOutput)] +pub struct BatchPayload { + pub title: String, +} + +async fn handle_batch( + ctx: &distributed::microsvc::CausalCommandContext<'_, todo_domain::Todo>, + input: BatchInput, +) -> std::result::Result< + distributed::command::PreparedCommand>, + distributed::microsvc::HandlerError, +> { + use distributed::microsvc::HandlerError; + let principal = ctx.user_id()?; + let repo = ctx.repo(); + let mut todo = repo + .get(&input.todo_id) + .await? + .ok_or_else(|| HandlerError::Rejected("missing batch fixture".into()))?; + for index in 0..32 { + todo.rename(principal, &format!("{} {index}", input.title)) + .map_err(|error| HandlerError::Rejected(error.to_string()))?; + } + let title = todo_domain::TodoState::from(&*todo).title; + repo.publish_events() + .commit(todo)? + .eventual(BatchPayload { title }) +} + +distributed::portable_command! { + name: "todo.test_batch", + transition: todo_domain::domain_commands::Rename, + aggregate: todo_domain::Todo, + input: BatchInput, + outcome: distributed::command::Eventual, + shard: |input| input.todo_id.clone(), + roles: ["user"], + field: "test_batch", + handle: handle_batch, +} + pub async fn handle(sql: &SqlStorage, request: &mut Request) -> Result { if request.method() != Method::Post { return Response::error("method not allowed", 405); From bd96942b863c721b418a5b06227f91a751fa0b75 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 12:00:18 -0500 Subject: [PATCH 024/484] fix: infer optimistic constants from flat domain events Implements [[tasks/distributed-flat-event-preview-1]] --- README.md | 40 ++++ distributed_macros/src/command.rs | 2 +- distributed_macros/src/sourced.rs | 176 ++++++++++++++-- tests/fixtures/flat_review_save.graphql | 3 + tests/sourced/flat_preview.rs | 264 ++++++++++++++++++++++++ tests/sourced/main.rs | 1 + 6 files changed, 473 insertions(+), 13 deletions(-) create mode 100644 tests/fixtures/flat_review_save.graphql create mode 100644 tests/sourced/flat_preview.rs diff --git a/README.md b/README.md index 574a91454..20ed410ca 100644 --- a/README.md +++ b/README.md @@ -812,6 +812,46 @@ impl TryFrom<&EventRecord> for TodoEvent { /* ... */ } impl Aggregate for Todo { /* ... */ } ``` +### Flat events and optimistic updates + +With `domain = event`, recorder parameters are the flat outward event body. +Literal arguments in public transitions also inform generated optimistic +projections—there is no second status mapping to maintain: + +```rust,ignore +#[sourced(entity, aggregate_type = "review")] +impl Review { + pub fn approve(&mut self, id: String) -> distributed::SourcedResult { + // Validate the decision here, before recording it. + self.record_status(id, "approved".into())?; + Ok(()) + } + + #[event("review.status_recorded", version = 1, domain = event)] + fn record_status(&mut self, id: String, status: String) { + self.entity.set_id(id); + self.status = status; + } +} +``` + +A portable command selecting `domain_commands::Approve` carries the known +`status = "approved"` into its projection preview. The projection still defines +which read-model fields it updates; permissions and confirmed events still +decide what the client can ultimately retain. + +Inference recognizes scalar literals, literal string ownership conversions, +and optional literals using fully qualified standard constructors (for example, +`::core::option::Option::Some(true)`). Bare `Some`/`None` remain unknown because +they can be shadowed. Inference preserves numeric types. Computed IDs, clocks, +variables, arbitrary calls, and unsupported expressions stay unknown. When +calls to the same recorder disagree, only their shared constants are retained. +This does not predict authorization or guarantee an event will occur. Snapshot +events continue to infer known values from recorder state assignments. + +See [the executable contract tests](tests/sourced/flat_preview.rs), including +the generated GraphQL client manifest and conflicting/dynamic-value cases. + ### Durable Stream Identity `Aggregate::aggregate_type()` provides the type component of a persistence stream's identity (the pair `(aggregate_type, aggregate_id)`). The default uses Rust's type name for development convenience, but **production persistence should set an explicit, stable durable name**: diff --git a/distributed_macros/src/command.rs b/distributed_macros/src/command.rs index f9975417a..46fd280b0 100644 --- a/distributed_macros/src/command.rs +++ b/distributed_macros/src/command.rs @@ -193,7 +193,7 @@ pub fn expand( })?; if !function.sig.asyncness.is_some() { return Err(syn::Error::new_spanned( - &function.sig.fn_token, + function.sig.fn_token, "typed command handlers must be async", )); } diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index 1b24b7a95..90caa3434 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -224,6 +224,8 @@ struct DomainCommandEvent { domain_event_type: Ident, domain_state: Option, known_state_values: Vec, + body_params: Vec<(Ident, Type)>, + known_body_values: Vec, } #[derive(Clone)] @@ -754,9 +756,11 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res } let state_domain = matches!(event_attr.domain.as_ref(), Some(DomainMode::State)); - let known_state_values = state_domain - .then(|| infer_unconditional_known_state_values(&method.block)) - .unwrap_or_default(); + let known_state_values = if state_domain { + infer_unconditional_known_state_values(&method.block) + } else { + Vec::new() + }; let signature_synthesized = ensure_sourced_result_signature(&mut method.sig, "event", &framework)?; @@ -817,6 +821,12 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res )?, domain_state: state_domain.then(|| args.domain_state.clone()).flatten(), known_state_values, + body_params: if matches!(event_attr.domain, Some(DomainMode::Event)) { + params.clone() + } else { + Vec::new() + }, + known_body_values: Vec::new(), }) } else { None @@ -1181,15 +1191,155 @@ impl<'ast> Visit<'ast> for DomainEventCallFinder<'_> { fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) { if is_self_receiver(&node.receiver) { if let Some(command_event) = self.recorders.get(&node.method.to_string()) { + let mut candidate = command_event.clone(); + candidate.known_body_values = candidate + .body_params + .iter() + .zip(&node.args) + .filter_map(|((field, ty), arg)| { + flat_literal(arg, ty).map(|source| KnownStateValue { + field: field.clone(), + source, + }) + }) + .collect(); self.found .entry(command_event.domain_event_type.to_string()) - .or_insert_with(|| command_event.clone()); + .and_modify(|existing| { + // A single event type can occur more than once, including + // through branches. Only values shared by every call are known. + existing.known_body_values.retain(|value| { + candidate.known_body_values.iter().any(|other| { + value.field == other.field + && same_known_value(&value.source, &other.source) + }) + }); + }) + .or_insert(candidate); } } syn::visit::visit_expr_method_call(self, node); } } +fn same_known_value(left: &KnownStateValueSource, right: &KnownStateValueSource) -> bool { + match (left, right) { + (KnownStateValueSource::Null, KnownStateValueSource::Null) => true, + (KnownStateValueSource::Constant(left), KnownStateValueSource::Constant(right)) => { + quote!(#left).to_string() == quote!(#right).to_string() + } + _ => false, + } +} + +/// Recognize data, not executable expressions. In particular, never hoist +/// arbitrary calls/paths or replay a user conversion while building metadata. +fn flat_literal(expression: &Expr, ty: &Type) -> Option { + let Type::Path(ty) = ty else { return None }; + let segment = ty.path.segments.last()?; + let name = segment.ident.to_string(); + let path = ty + .path + .segments + .iter() + .map(|part| part.ident.to_string()) + .collect::>() + .join("::"); + let standard = path == name + || match name.as_str() { + "String" => matches!( + path.as_str(), + "std::string::String" | "alloc::string::String" + ), + "Option" => matches!( + path.as_str(), + "std::option::Option" | "core::option::Option" + ), + _ => { + path == format!("core::primitive::{name}") + || path == format!("std::primitive::{name}") + } + }; + if !standard { + return None; + } + let expression = ungroup_expr(expression); + if name == "Option" { + let syn::PathArguments::AngleBracketed(args) = &segment.arguments else { + return None; + }; + let Some(syn::GenericArgument::Type(inner)) = args.args.first() else { + return None; + }; + if matches!(expression, Expr::Path(path) if standard_option_variant(&path.path, "None")) { + return Some(KnownStateValueSource::Null); + } + if let Expr::Call(call) = expression { + if call.args.len() == 1 + && matches!(&*call.func, Expr::Path(path) if standard_option_variant(&path.path, "Some")) + { + return flat_literal(call.args.first()?, inner); + } + } + return None; + } + let literal = match expression { + Expr::Lit(literal) => literal, + Expr::MethodCall(call) + if name == "String" + && call.args.is_empty() + && call.turbofish.is_none() + && matches!( + call.method.to_string().as_str(), + "into" | "to_owned" | "to_string" + ) => + { + let Expr::Lit(literal) = ungroup_expr(&call.receiver) else { + return None; + }; + literal + } + _ => return None, + }; + let supported = match &literal.lit { + syn::Lit::Str(_) => name == "String", + syn::Lit::Bool(_) => name == "bool", + syn::Lit::Char(_) => name == "char", + syn::Lit::Int(_) => matches!( + name.as_str(), + "u8" | "u16" | "u32" | "u64" | "usize" | "i8" | "i16" | "i32" | "i64" | "isize" + ), + syn::Lit::Float(_) => matches!(name.as_str(), "f32" | "f64"), + _ => false, + }; + supported.then(|| { + let expression = if matches!(&literal.lit, syn::Lit::Int(_) | syn::Lit::Float(_)) { + let primitive = &segment.ident; + // Preserve contextual numeric typing (notably unsuffixed f32 and + // large u64 literals) without evaluating a user-defined conversion. + syn::parse_quote!({ let value: ::core::primitive::#primitive = #literal; value }) + } else { + Expr::Lit(literal.clone()) + }; + KnownStateValueSource::Constant(expression) + }) +} + +fn standard_option_variant(path: &syn::Path, variant: &str) -> bool { + // Bare Some/None can be locally shadowed; do not execute or guess them. + let names = path + .segments + .iter() + .map(|part| part.ident.to_string()) + .collect::>(); + path.leading_colon.is_some() + && names.len() == 4 + && matches!(names[0].as_str(), "core" | "std") + && names[1] == "option" + && names[2] == "Option" + && names[3] == variant +} + fn is_self_receiver(expression: &Expr) -> bool { match expression { Expr::Path(path) => path.path.is_ident("self"), @@ -1233,12 +1383,17 @@ fn expand_domain_commands_module( .map(|event| &event.domain_event_type) .collect::>(); let known_value_items = transition.events.iter().filter_map(|event| { - let state = event.domain_state.as_ref()?; - if event.known_state_values.is_empty() { + let values = if event.domain_state.is_some() { &event.known_state_values } else { &event.known_body_values }; + if values.is_empty() { return None; } let event_type = &event.domain_event_type; - let fields = event.known_state_values.iter().map(|value| { + let helper = if let Some(state) = &event.domain_state { + quote!(distributed::command::__command_projection_state_known_values::) + } else { + quote!(distributed::command::__command_projection_event_preview::) + }; + let fields = values.iter().map(|value| { let field = value.field.to_string(); let source = match &value.source { KnownStateValueSource::Constant(expression) => quote! { @@ -1251,16 +1406,13 @@ fn expand_domain_commands_module( quote! { (#field, #source) } }); Some(quote! { - distributed::command::__command_projection_state_known_values::< - super::#event_type, - #state, - >(vec![#(#fields),*]) + #helper(vec![#(#fields),*]) }) }); let has_known_values = transition .events .iter() - .any(|event| event.domain_state.is_some() && !event.known_state_values.is_empty()); + .any(|event| !event.known_state_values.is_empty() || !event.known_body_values.is_empty()); let known_values_method = has_known_values.then(|| { quote! { fn command_event_known_values( diff --git a/tests/fixtures/flat_review_save.graphql b/tests/fixtures/flat_review_save.graphql new file mode 100644 index 000000000..eaa75c218 --- /dev/null +++ b/tests/fixtures/flat_review_save.graphql @@ -0,0 +1,3 @@ +mutation SaveFlatReview { + upsert_flat_reviews(object: $input.review) +} diff --git a/tests/sourced/flat_preview.rs b/tests/sourced/flat_preview.rs new file mode 100644 index 000000000..0dafe7cc9 --- /dev/null +++ b/tests/sourced/flat_preview.rs @@ -0,0 +1,264 @@ +use distributed::{command::CommandEventSet, Entity}; +use serde_json::{json, Value}; + +#[derive(Default)] +struct Review { + entity: Entity, + status: String, +} + +#[distributed::sourced(entity, events = "ReviewEvent", aggregate_type = "review")] +impl Review { + pub fn approve(&mut self, id: String) -> distributed::SourcedResult { + self.record_status( + id, + "approved".into(), + true, + 25, + ::core::option::Option::Some(0.1), + ::core::option::Option::None, + )?; + Ok(()) + } + + pub fn reject(&mut self, id: String) -> distributed::SourcedResult { + self.record_status( + id, + "rejected".to_owned(), + false, + 0, + ::std::option::Option::None, + ::std::option::Option::Some('x'), + )?; + Ok(()) + } + + pub fn conflicting(&mut self, id: String, approve: bool) -> distributed::SourcedResult { + if approve { + self.record_status(id, "approved".into(), true, 1, None, None)?; + } else { + self.record_status(id, "rejected".into(), false, 1, None, None)?; + } + Ok(()) + } + + pub fn dynamic(&mut self, id: String, status: String) -> distributed::SourcedResult { + self.record_status(id.clone(), "approved".into(), true, 1, None, None)?; + self.record_status(id, status, false, 1, None, None)?; + Ok(()) + } + + pub fn executable(&mut self, id: String) -> distributed::SourcedResult { + self.record_status(id, never_execute(), true, 1, None, None)?; + Ok(()) + } + + pub fn shadowed_constructor(&mut self, id: String) -> distributed::SourcedResult { + #[allow(non_snake_case)] + fn Some(_score: f32) -> Option { + panic!("not an Option constructor") + } + self.record_status(id, "approved".into(), true, 1, Some(0.1), None)?; + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + #[event("review.status_recorded", version = 1, domain = event)] + fn record_status( + &mut self, + id: String, + status: String, + approved: bool, + count: u64, + score: Option, + mark: Option, + ) { + self.entity.set_id(id); + self.status = status; + let _ = (approved, count, score, mark); + } +} + +fn never_execute() -> String { + panic!("building metadata must not execute transition expressions") +} + +fn fields() -> Value { + let previews = serde_json::to_value(T::command_event_known_values()).unwrap(); + let mut fields = serde_json::Map::new(); + for preview in previews.as_array().unwrap() { + for field in preview["fields"].as_array().unwrap() { + fields.insert( + field["body_path"][0].as_str().unwrap().into(), + field["source"].clone(), + ); + } + } + Value::Object(fields) +} + +#[test] +fn flat_constants_match_recorded_body_without_running_the_command() { + let values = fields::(); + assert_eq!( + values["status"], + json!({"kind":"constant", "value":{"type":"string","value":"approved"}}) + ); + assert_eq!(values["approved"]["value"]["value"], true); + assert_eq!(values["count"]["value"]["value"], "25"); + assert!( + values.get("id").is_none(), + "server-computed/input identity is not a constant" + ); + let mut review = Review::default(); + review.approve("r1".into()).unwrap(); + let body: Value = review.entity.pending_domain_events()[0] + .decode_body() + .unwrap(); + for (name, source) in values.as_object().unwrap() { + if source["kind"] == "constant" { + let typed = &source["value"]; + let value = if matches!(typed["type"].as_str(), Some("u64" | "i64" | "f64")) { + serde_json::from_str(typed["value"].as_str().unwrap()).unwrap() + } else { + typed["value"].clone() + }; + assert_eq!(body[name], value, "wire value for {name}"); + } else { + assert_eq!(source["kind"], "null"); + assert!(body[name].is_null()); + } + } + let rejected = fields::(); + assert_eq!(rejected["status"]["value"]["value"], "rejected"); + assert_eq!(rejected["mark"]["value"]["value"], "x"); +} + +#[test] +fn conflicting_dynamic_and_executable_values_are_not_constants() { + for values in [ + fields::(), + fields::(), + ] { + assert!(values.get("status").is_none()); + assert!(values.get("approved").is_none()); + assert_eq!(values["count"]["value"]["value"], "1"); + } + assert!(fields::() + .get("status") + .is_none()); + let _never_call: fn(&mut Review, String) -> distributed::SourcedResult = Review::executable; + assert!(fields::() + .get("score") + .is_none()); + let _shadowed: fn(&mut Review, String) -> distributed::SourcedResult = + Review::shadowed_constructor; + // Exercise the commands too: inference does not change their real behavior. + let mut review = Review::default(); + review.conflicting("r1".into(), false).unwrap(); + review.dynamic("r1".into(), "custom".into()).unwrap(); + review.reject("r1".into()).unwrap(); + assert_eq!(review.status, "rejected"); +} + +#[cfg(feature = "graphql")] +mod client_contract { + use super::*; + use distributed::command::{typed_command, Eventual, PreparedCommand}; + use distributed::graphql::{ + build_surface, surface_for_role, ClientProjectionPreviewSource, ClientProjectionValue, + DistributedClientSurfaceExport, RoleGrant, SurfaceOptions, + }; + use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; + use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; + use distributed::{ + AggregateRepository, InMemoryRepository, LocalProjectionMountsBuilder, Mutation, + RelationalReadModel, + }; + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Default, Serialize, Deserialize, distributed::ReadModel)] + #[readmodel(table = "flat_reviews", primary_key = ["id"])] + struct FlatReviews { + id: String, + status: String, + } + + #[derive(Deserialize, distributed::CommandInput)] + struct Input { + id: String, + } + #[derive(Serialize, distributed::CommandOutput)] + struct Output { + id: String, + } + + #[allow(non_snake_case)] + fn SaveFlatReview() -> Mutation<()> { + distributed::mutation_file!("tests/fixtures/flat_review_save.graphql") + } + distributed::projection! { + const REVIEWS: ProjectionDescriptor = { + name: "flat_reviews", version: 1, epoch: "flat-reviews-v1", + model: FlatReviews, source: aggregate_snapshot, + on { events: [ReviewStatusRecordedDomainEvent], mutation: SaveFlatReview, + input: {review: body}, }, + }; + } + + async fn metadata_only( + _ctx: &CausalCommandContext<'_, Review>, + _input: Input, + ) -> Result>, HandlerError> { + let _ = _input.id; + panic!("manifest compilation must not execute a command") + } + + #[test] + fn flat_domain_constant_reaches_generated_projection_slots() { + let mounts = LocalProjectionMountsBuilder::new("reviews", "events") + .unwrap() + .eventual_model::("flat_reviews", REVIEWS, REVIEWS.epoch()) + .unwrap() + .build() + .unwrap(); + let service = Service::new().named("reviews").routes( + Routes::new() + .with_repo(AggregateRepository::<_, Review>::new( + InMemoryRepository::new(), + )) + .typed_command( + typed_command::>("review.approve") + .emits_events::(), + ) + .handle(metadata_only), + ); + let surface = build_surface( + &[FlatReviews::schema().clone()], + &SurfaceOptions::postgres(), + ) + .unwrap() + .with_projectors([mounts.projector("flat_reviews").unwrap()]) + .unwrap() + .with_service(&service) + .unwrap(); + let selected = surface_for_role( + &surface, + "anonymous", + &std::collections::BTreeMap::from([("FlatReviews".into(), RoleGrant::all_columns())]), + ) + .unwrap(); + let manifest = DistributedClientSurfaceExport::from_selected("reviews", selected) + .unwrap() + .manifest() + .unwrap(); + let projection = manifest.commands[0].extensions.projection.as_ref().unwrap(); + assert_eq!(projection.preview_occurrences.len(), 1); + assert!(projection.preview_occurrences[0].values.iter().any( + |field| matches!(&field.source, ClientProjectionPreviewSource::Constant { + value: ClientProjectionValue::String(status) } if status == "approved") + )); + assert!(projection.preview_occurrences[0].values.iter().any(|field| + matches!(&field.source, ClientProjectionPreviewSource::Input { path } if path == &["id"]))); + } +} diff --git a/tests/sourced/main.rs b/tests/sourced/main.rs index 64be90736..81744562b 100644 --- a/tests/sourced/main.rs +++ b/tests/sourced/main.rs @@ -1,5 +1,6 @@ mod aggregate; mod domain_events; +mod flat_preview; use aggregate::{Todo, TodoEvent}; use distributed::{ From d0967f90dc1eda81c9710fc4d5c22985a90c884d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 00:53:58 -0500 Subject: [PATCH 025/484] feat: support boxed singular read model relationships Implements [[tasks/distributed-boxed-readmodel-relations]] --- README.md | 6 ++ distributed_macros/src/read_model/attrs.rs | 19 +++++- .../src/read_model/relational.rs | 8 ++- distributed_macros/src/read_model/tests.rs | 28 ++++++++ distributed_macros/src/read_model/types.rs | 18 +++++ tests/graphql_sqlite/main.rs | 65 +++++++++++++++++++ .../read_model_relationship_includes/main.rs | 59 +++++++++++++++++ 7 files changed, 197 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 20ed410ca..b3f9bd900 100644 --- a/README.md +++ b/README.md @@ -1804,6 +1804,12 @@ let loaded = repo PK (same-named columns, or `foreign_key` / `target_foreign_key` in PK order). A one-column `foreign_key` on a composite PK is an error, not a silent `.first()`. +- **Cyclic singular relationships:** use `Option>` for a `belongs_to` + field when two models refer to each other. For example, + `#[readmodel(belongs_to = "Profile", foreign_key = "id")]` + `profile: Option>`. The box only gives Rust a finite-sized type; + GraphQL still exposes one nullable `Profile`, not a list or embedded JSON + column. Ordinary `Option` remains the same singular relationship. - **Writes:** `ReadModelWritePlan` / workspace `upsert` + `commit` (same transaction as events when staged on `CommitBatch`). - **Internal loads:** PK-anchored includes — diff --git a/distributed_macros/src/read_model/attrs.rs b/distributed_macros/src/read_model/attrs.rs index a21bcb703..410c3f80d 100644 --- a/distributed_macros/src/read_model/attrs.rs +++ b/distributed_macros/src/read_model/attrs.rs @@ -2,7 +2,8 @@ use quote::quote; use syn::{Attribute, DeriveInput, Expr, ExprArray, ExprLit, Field, Lit, LitStr, Meta, Token}; use super::types::{ - option_inner_type, option_string_tokens, validate_relationship_target_type, vec_inner_type, + box_inner_type, option_inner_type, option_string_tokens, validate_relationship_target_type, + vec_inner_type, }; #[derive(Default)] @@ -412,17 +413,29 @@ impl FieldAttrs { ), ) })?; + let boxed = box_inner_type(inner); + let inner = boxed.unwrap_or(inner); validate_relationship_target_type( field, inner, &relationship.target_model, field_name, )?; + let hydrated_value = if boxed.is_some() { + quote! { ::std::boxed::Box::new(<#inner as distributed::RelationalReadModel>::from_row(row)?) } + } else { + quote! { <#inner as distributed::RelationalReadModel>::from_row(row)? } + }; + let included_value = if boxed.is_some() { + quote! { value.as_ref() } + } else { + quote! { value } + }; let hydrate = quote! { #field_name => { let mut rows = rows.into_iter(); self.#ident = match rows.next() { - Some(row) => Some(<#inner as distributed::RelationalReadModel>::from_row(row)?), + Some(row) => Some(#hydrated_value), None => None, }; if rows.next().is_some() { @@ -438,7 +451,7 @@ impl FieldAttrs { #field_name => { let mut rows = Vec::new(); if let Some(value) = &self.#ident { - rows.push(distributed::RelationalReadModel::to_row(value)?); + rows.push(distributed::RelationalReadModel::to_row(#included_value)?); } Ok(rows) } diff --git a/distributed_macros/src/read_model/relational.rs b/distributed_macros/src/read_model/relational.rs index 89472e67b..a3858d33e 100644 --- a/distributed_macros/src/read_model/relational.rs +++ b/distributed_macros/src/read_model/relational.rs @@ -8,8 +8,8 @@ use crate::shared::{ use super::attrs::{foreign_key_tokens, FieldAttrs, RelationshipKindAttr, StructAttrs}; use super::types::{ - bytes_row_value_tokens, column_type_tokens, default_storage_name, effect_model_wire_tokens, - option_inner_type, option_string_tokens, vec_inner_type, + box_inner_type, bytes_row_value_tokens, column_type_tokens, default_storage_name, + effect_model_wire_tokens, option_inner_type, option_string_tokens, vec_inner_type, }; pub(super) fn expand_relational_read_model( @@ -114,7 +114,9 @@ pub(super) fn expand_relational_read_model( vec_inner_type(&field.ty).expect("relationship shape was validated") } RelationshipKindAttr::BelongsTo => { - option_inner_type(&field.ty).expect("relationship shape was validated") + let inner = + option_inner_type(&field.ty).expect("relationship shape was validated"); + box_inner_type(inner).unwrap_or(inner) } }; let marker = format_ident!("__Distributed{}EffectRelationship_{}", name, ident); diff --git a/distributed_macros/src/read_model/tests.rs b/distributed_macros/src/read_model/tests.rs index 9cffb946d..7c7099b2f 100644 --- a/distributed_macros/src/read_model/tests.rs +++ b/distributed_macros/src/read_model/tests.rs @@ -2,6 +2,34 @@ use super::types::{default_storage_name, to_snake_case}; use super::*; use syn::DeriveInput; +#[test] +fn boxed_belongs_to_preserves_target_markers_and_checks_inner_type() { + let input: DeriveInput = syn::parse_quote! { + struct Parent { + id: String, + #[readmodel(belongs_to = "Child", foreign_key = "id")] + child: Option>, + } + }; + let expanded = expand_read_model(input).unwrap().to_string(); + assert!(expanded.contains("type Target = Child"), "{expanded}"); + assert!(!expanded.contains("type Target = std :: boxed :: Box")); + assert!(expanded.contains("Box :: new")); + assert!(expanded.contains("value . as_ref ()")); + for ty in [ + "Option>", + "Option>>", + "Option>", + "Box", + "Vec>", + ] { + let input: DeriveInput = syn::parse_str(&format!( + "struct Parent {{ id: String, #[readmodel(belongs_to = \"Child\", foreign_key = \"id\")] child: {ty} }}" + )).unwrap(); + assert!(expand_read_model(input).is_err(), "accepted {ty}"); + } +} + #[test] fn expand_read_model_accepts_named_id_field() { let input: DeriveInput = syn::parse_quote! { diff --git a/distributed_macros/src/read_model/types.rs b/distributed_macros/src/read_model/types.rs index 1bd2e2385..429becc4f 100644 --- a/distributed_macros/src/read_model/types.rs +++ b/distributed_macros/src/read_model/types.rs @@ -131,6 +131,24 @@ pub(super) fn vec_inner_type(ty: &Type) -> Option<&Type> { }) } +/// One allocation wrapper for a singular relationship, not a model or column. +pub(super) fn box_inner_type(ty: &Type) -> Option<&Type> { + let segment = last_type_segment(ty)?; + if segment.ident != "Box" { + return None; + } + let PathArguments::AngleBracketed(args) = &segment.arguments else { + return None; + }; + if args.args.len() != 1 { + return None; + } + match args.args.first()? { + GenericArgument::Type(ty) => Some(ty), + _ => None, + } +} + pub(super) fn validate_relationship_target_type( field: &Field, ty: &Type, diff --git a/tests/graphql_sqlite/main.rs b/tests/graphql_sqlite/main.rs index 0785b613f..c3eced167 100644 --- a/tests/graphql_sqlite/main.rs +++ b/tests/graphql_sqlite/main.rs @@ -12,6 +12,71 @@ use distributed::{ use serde::{Deserialize, Serialize}; use sqlx::sqlite::SqlitePoolOptions; +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ReadModel)] +#[table("boxed_accounts")] +struct BoxedAccount { + id: String, + #[readmodel(belongs_to = "BoxedProfile", foreign_key = "id")] + profile: Option>, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ReadModel)] +#[table("boxed_profiles")] +struct BoxedProfile { + id: String, + owner_id: String, + #[readmodel(belongs_to = "BoxedAccount", foreign_key = "id")] + account: Option, +} + +#[tokio::test] +async fn boxed_singular_cycles_preserve_nested_graphql_permissions() { + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); + for sql in [ + "CREATE TABLE boxed_accounts (id TEXT PRIMARY KEY)", + "CREATE TABLE boxed_profiles (id TEXT PRIMARY KEY, owner_id TEXT NOT NULL)", + "INSERT INTO boxed_accounts VALUES ('a'), ('b')", + "INSERT INTO boxed_profiles VALUES ('a', 'alice'), ('b', 'bob')", + ] { + sqlx::query(sql).execute(&pool).await.unwrap(); + } + let engine = GraphqlEngine::builder(pool) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .model::( + ModelPermissions::new().grant( + "user", + read() + .all_columns() + .rows(col("owner_id").eq(distributed::graphql::claim("x-user-id"))), + ), + ) + .roles(&["user"]) + .build() + .unwrap(); + let response = engine + .execute( + &session_role("user", "alice"), + Request::new( + "{ boxed_accounts(order_by: [{ id: asc }]) { id profile { id account { id } } } }", + ), + ) + .await; + assert!(!response.is_err(), "{:?}", response.errors); + assert_eq!( + serde_json::to_value(response.data).unwrap(), + serde_json::json!({ + "boxed_accounts": [ + {"id": "a", "profile": {"id": "a", "account": {"id": "a"}}}, + {"id": "b", "profile": null} + ] + }) + ); +} + fn orders_schema() -> TableSchema { TableSchema { model_name: "OrderView".into(), diff --git a/tests/read_model_relationship_includes/main.rs b/tests/read_model_relationship_includes/main.rs index a435d1a27..9cd095ba4 100644 --- a/tests/read_model_relationship_includes/main.rs +++ b/tests/read_model_relationship_includes/main.rs @@ -10,6 +10,65 @@ use distributed::{ }; use serde::{Deserialize, Serialize}; +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ReadModel)] +struct Account { + id: String, + #[readmodel(belongs_to = "Profile", foreign_key = "id")] + profile: Option>, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ReadModel)] +struct Profile { + id: String, + #[readmodel(belongs_to = "Account", foreign_key = "id")] + account: Option, +} + +#[test] +fn cyclic_singular_relationships_hydrate_and_serialize_without_box_metadata() { + use distributed::{RelationalReadModel, RelationalReadModelIncludes}; + let mut account = Account { + id: "a".into(), + profile: None, + }; + let profile = Profile { + id: "a".into(), + account: None, + }; + let row = profile.to_row().unwrap(); + account + .hydrate_include("profile", vec![row.clone()]) + .unwrap(); + assert_eq!(account.profile.as_deref(), Some(&profile)); + assert_eq!(account.include_rows("profile").unwrap(), vec![row.clone()]); + assert_eq!( + Account::include_target_schema("profile").unwrap(), + Profile::schema() + ); + assert!(!Account::schema() + .columns + .iter() + .any(|column| column.field_name == "profile")); + account.hydrate_include("profile", vec![]).unwrap(); + assert_eq!(account.profile, None); + assert!(account + .hydrate_include("profile", vec![row.clone(), row]) + .is_err()); + let mut profile = profile; + profile + .hydrate_include( + "account", + vec![Account { + id: "a".into(), + profile: None, + } + .to_row() + .unwrap()], + ) + .unwrap(); + assert_eq!(profile.account.as_ref().unwrap().id, "a"); +} + fn block_on(future: F) -> F::Output { use std::ptr; use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; From 4484e73424563f4b9cf392173e5179094b651573 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 01:03:23 -0500 Subject: [PATCH 026/484] fix: retain source edits during initial dev startup Implements [[tasks/distributed-dev-startup-watch]] --- distributed_cli/src/lifecycle/dev.rs | 4 ++- distributed_cli/tests/cli_lifecycle.rs | 47 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/distributed_cli/src/lifecycle/dev.rs b/distributed_cli/src/lifecycle/dev.rs index 63d6179f1..068a8212a 100644 --- a/distributed_cli/src/lifecycle/dev.rs +++ b/distributed_cli/src/lifecycle/dev.rs @@ -285,6 +285,9 @@ pub fn run_lifecycle_project_dev( validate_restart_nodes(&dev, &graph)?; // Initial coherent generation is an absolute serving barrier. + // Observe before building/starting children: edits during startup must not + // become a new baseline without ever being built. + let mut snapshot = lifecycle_input_snapshot(&root, catalog, &graph)?; let mut initial_options = options.build.clone(); initial_options.nodes = None; initial_options.activation_inputs = None; @@ -315,7 +318,6 @@ pub fn run_lifecycle_project_dev( dev.processes.keys().cloned().collect::>().join(",") ); } - let mut snapshot = lifecycle_input_snapshot(&root, catalog, &graph)?; let mut final_generation = initial.generation_id.clone(); let mut active = initial.clone(); let mut rebuilds = 0; diff --git a/distributed_cli/tests/cli_lifecycle.rs b/distributed_cli/tests/cli_lifecycle.rs index b1cc46428..eda70d1a4 100644 --- a/distributed_cli/tests/cli_lifecycle.rs +++ b/distributed_cli/tests/cli_lifecycle.rs @@ -774,6 +774,53 @@ fn dev_browser_prepare_timeout_preserves_active_pointer_and_processes() { ); } +#[test] +fn dev_rebuilds_source_edited_while_initial_process_readiness_is_held() { + let fixture = temporary_root("dev-startup-edit"); + let root = fixture.path().to_path_buf(); + write_fixture(&root); + enable_dev(&root); + let path = root.join("distributed.lifecycle.json"); + let mut config: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + config["dev"]["processes"]["api"]["ready"] = serde_json::json!({ + "program": "/bin/test", + "args": ["-f", "{root}/release-readiness"], + "interval_ms": 10, + "timeout_ms": 5000 + }); + fs::write(&path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); + let supervisor = DevSupervisor::start(root.clone()); + wait_until(Duration::from_secs(5), || { + root.join("dev-process.log").exists() + }); + let before = wait_for_stable_file( + &root.join("dist/distributed/active.json"), + Duration::from_secs(5), + ); + // The initial build is complete but the supervisor cannot finish startup. + fs::write(root.join("src/input.txt"), "edited-during-startup\n").unwrap(); + fs::write(root.join("release-readiness"), "release\n").unwrap(); + wait_until(Duration::from_secs(5), || { + fs::read(root.join("dist/distributed/active.json")).is_ok_and(|active| active != before) + }); + let report = supervisor.stop_and_join(); + assert_ne!(report.initial_generation, report.final_generation); + assert_eq!(report.rebuilds, 1); + assert_eq!(report.restarts["api"], 1); + assert_eq!(report.restarts["ui"], 0); + let active: Value = + serde_json::from_slice(&fs::read(root.join("dist/distributed/active.json")).unwrap()) + .unwrap(); + let artifact = root + .join("dist/distributed") + .join(active["path"].as_str().unwrap()) + .join("generated/application.json"); + assert_eq!( + fs::read_to_string(artifact).unwrap(), + "application:edited-during-startup\n" + ); +} + #[test] fn dev_cancels_a_superseded_executor_before_activation() { let fixture = temporary_root("dev-cancel"); From 56521b15774b65717bd6b873726b854f94b8ed9b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 01:59:10 -0500 Subject: [PATCH 027/484] fix: budget structured surfaces as application contracts Keep opaque JSON caps and complete artifact bounds intact. Cover generated large surfaces and nested validation. Implements [[tasks/distributed-structured-surface-budget]]. --- README.md | 5 ++- src/application/manifest.rs | 55 ++++++++++++++++++++++++++++++-- tests/application_composition.rs | 26 +++++++++++++++ 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b3f9bd900..3045894ef 100644 --- a/README.md +++ b/README.md @@ -2301,7 +2301,10 @@ second module list to maintain. Assembly rejects commands missing from the Surface or exposed by the Surface without a Service owner. Role-selected client exports remain authorization views of that full contract. Complete application manifests are bounded at 4 MiB; each opaque JSON contract remains bounded at -1 MiB, with the existing collection, string and nesting limits still enforced. +1 MiB. A generated Surface contract uses the complete-manifest budget rather +than the opaque-value cap; its typed contents and the existing collection, +string and nesting limits are still validated. The complete artifact, including +all surfaces and module inventories, must fit within 4 MiB. An event-driven policy that emits through another aggregate can explicitly carry the incoming command's causal identity before recording its events: diff --git a/src/application/manifest.rs b/src/application/manifest.rs index c0fdd09e0..69be8507a 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -979,7 +979,14 @@ fn validate_surface( .map(|projection| projection.id.clone()) .collect::>(), )?; - validate_json_contract("surface canonical contract", &surface.contract)?; + // This is the structured catalog of an entire Surface, not an opaque + // extension value. Its contents are checked below against the typed spec; + // the complete serialized application still owns the aggregate byte budget. + validate_json_contract_with_budget( + "surface canonical contract", + &surface.contract, + MAX_APPLICATION_MANIFEST_BYTES, + )?; validate_surface_selection(surface)?; validate_portable_text("surface dialect", &surface.dialect)?; if surface.max_limit == 0 || surface.default_limit > surface.max_limit { @@ -1855,10 +1862,18 @@ fn validate_sha256_text(kind: &'static str, value: &str) -> ApplicationResult<() } fn validate_json_contract(kind: &'static str, value: &serde_json::Value) -> ApplicationResult<()> { + validate_json_contract_with_budget(kind, value, MAX_MANIFEST_JSON_BYTES) +} + +fn validate_json_contract_with_budget( + kind: &'static str, + value: &serde_json::Value, + max_bytes: usize, +) -> ApplicationResult<()> { let bytes = serde_json::to_vec(value)?; - if bytes.len() > MAX_MANIFEST_JSON_BYTES { + if bytes.len() > max_bytes { return Err(ApplicationError::InvalidSpec(format!( - "{kind} exceeds {MAX_MANIFEST_JSON_BYTES} JSON bytes" + "{kind} exceeds {max_bytes} JSON bytes" ))); } fn walk(kind: &'static str, value: &serde_json::Value, depth: usize) -> ApplicationResult<()> { @@ -2013,6 +2028,37 @@ fn validate_sorted_unique(kind: &'static str, identities: &[String]) -> Applicat mod size_limit_tests { use super::*; + #[test] + fn structured_surface_budget_preserves_nested_validation() { + let validate = |value: &serde_json::Value| { + validate_json_contract_with_budget( + "surface canonical contract", + value, + MAX_APPLICATION_MANIFEST_BYTES, + ) + }; + assert!(validate(&serde_json::json!({"bad": "nul\u{0}value"})).is_err()); + assert!( + validate(&serde_json::json!({"bad": "x".repeat(MAX_MANIFEST_STRING_BYTES + 1)})) + .is_err() + ); + assert!(validate(&serde_json::json!(vec![ + 0; + MAX_MANIFEST_COLLECTION_ITEMS + 1 + ])) + .is_err()); + let mut deep = serde_json::Value::Null; + for _ in 0..=MAX_MANIFEST_JSON_DEPTH { + deep = serde_json::json!([deep]); + } + assert!(validate(&deep).is_err()); + let oversized = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 1024]); + assert!(validate(&oversized) + .unwrap_err() + .to_string() + .contains("exceeds 4194304 JSON bytes")); + } + #[test] fn json_contract_can_exceed_the_old_256_kib_limit() { let chunk = "x".repeat(MAX_MANIFEST_STRING_BYTES); @@ -2057,5 +2103,8 @@ mod size_limit_tests { let error = manifest.canonical_bytes().unwrap_err().to_string(); assert!(error.contains("application manifest exceeds 4194304 bytes")); + let oversized_bytes = serde_json::to_vec(&manifest).unwrap(); + assert!(oversized_bytes.len() > MAX_APPLICATION_MANIFEST_BYTES); + assert!(ApplicationManifest::from_canonical_bytes(&oversized_bytes).is_err()); } } diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 2e3e06b38..99e411097 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -141,6 +141,32 @@ fn full_surface() -> Surface { .expect("non-empty Surface should compile") } +#[test] +fn generated_surface_above_opaque_json_budget_round_trips() { + let tables = (0..500) + .map(|index| { + let mut table = TodoView::schema().clone(); + table.model_name = format!("CatalogView{index:03}"); + table.table_name = format!("catalog_view_{index:03}"); + table + }) + .collect::>(); + let surface = build_surface(&tables, &SurfaceOptions::sqlite()).unwrap(); + let spec = SurfaceSpec::from_surface("catalog", &surface).unwrap(); + let contract_bytes = serde_json::to_vec(&spec.contract).unwrap().len(); + assert!( + contract_bytes > distributed::application::MAX_MANIFEST_JSON_BYTES, + "fixture must exceed opaque JSON budget: {contract_bytes}" + ); + let application = Application::try_new("catalog-app", [], [spec]).unwrap(); + let bytes = application.manifest().canonical_bytes().unwrap(); + assert!(bytes.len() <= distributed::application::MAX_APPLICATION_MANIFEST_BYTES); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), + *application.manifest() + ); +} + fn selected_surface() -> Surface { let full = full_surface(); let grants = BTreeMap::from([( From 801e79d948def86a45243543ef64c09ab3e70e22 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 03:50:08 -0500 Subject: [PATCH 028/484] fix: derive command presets from compiled preview Implements [[tasks/distributed-preview-preset-inventory]] --- .../projection_delta/preview.rs | 133 ++++++++++++ .../src/client_compiler/render/commands.rs | 25 ++- distributed_cli/src/client_compiler/tests.rs | 56 +++++ .../generated-recovery-preset-command.json | 199 ++++++++++++++++++ js/tests/replica-command-artifacts.test.mjs | 17 ++ 5 files changed, 425 insertions(+), 5 deletions(-) create mode 100644 distributed_cli/tests/fixtures/generated-recovery-preset-command.json diff --git a/distributed_cli/src/client_compiler/projection_delta/preview.rs b/distributed_cli/src/client_compiler/projection_delta/preview.rs index 0245253eb..cdbb0747e 100644 --- a/distributed_cli/src/client_compiler/projection_delta/preview.rs +++ b/distributed_cli/src/client_compiler/projection_delta/preview.rs @@ -116,6 +116,16 @@ struct CompiledPureArg { } impl CompiledCommandProjection { + /// Only emitted mutations consume command presets. Authored occurrences + /// can lower to recovery without retaining any of their input expressions. + pub(crate) fn trusted_preset_names(&self) -> BTreeSet { + let mut names = BTreeSet::new(); + for operation in &self.preview.operations { + operation.mutation.collect_trusted_presets(&mut names); + } + names + } + pub(crate) fn affected_models(&self) -> BTreeSet { let mut models = BTreeSet::new(); for operation in &self.preview.operations { @@ -333,6 +343,31 @@ enum PreviewMutation { } impl PreviewMutation { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + match self { + Self::Upsert { scope, fields, .. } + | Self::Patch { + scope, set: fields, .. + } => { + scope.collect_trusted_presets(names); + for field in fields { + field.value.collect_trusted_presets(names); + } + } + Self::Delete { scope } => scope.collect_trusted_presets(names), + Self::Link { source, target, .. } | Self::Unlink { source, target, .. } => { + source.collect_trusted_presets(names); + target.collect_trusted_presets(names); + } + Self::InvalidateRelationship { source, .. } => source.collect_trusted_presets(names), + Self::InvalidateModel { partition, .. } => { + if let Some(partition) = partition { + partition.collect_trusted_presets(names); + } + } + } + } + fn canonical_scope(&self) -> Result { let scope_json = |scope: &PreviewScope| { serde_json::to_string(scope).map_err(|error| { @@ -430,6 +465,50 @@ impl PreviewMutation { } } +impl PreviewScope { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + self.partition.collect_trusted_presets(names); + for field in &self.key { + field.value.collect_trusted_presets(names); + } + } +} + +impl PreviewPartition { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + if let Self::Expression { expression, .. } = self { + expression.collect_trusted_presets(names); + } + } +} + +impl PreviewExpression { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + match self { + Self::TrustedPreset { name, .. } => { + names.insert(name.clone()); + } + Self::List { values } + | Self::Transform { + arguments: values, .. + } => { + for value in values { + value.collect_trusted_presets(names); + } + } + Self::Object { fields } => { + for field in fields { + field.value.collect_trusted_presets(names); + } + } + Self::Input { .. } + | Self::GeneratedDefault { .. } + | Self::Constant { .. } + | Self::Null => {} + } + } +} + /// The variant declaration order is the canonical operation-kind order shared /// with the authoritative ProjectionDelta wire. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -1957,6 +2036,60 @@ fn model_recovery( mod tests { use super::*; + #[test] + fn emitted_mutation_presets_include_nested_values_keys_and_partitions_only() { + let preset = |name: &str| PreviewExpression::TrustedPreset { + name: name.into(), + codec: "string".into(), + }; + let scope = PreviewScope { + model: "Todo".into(), + partition: PreviewPartition::Expression { + expression: preset("tenant"), + requires: PreviewPartitionRequirement::CurrentCachePartition, + }, + key: vec![PreviewKeyField { + ordinal: 0, + field: "id".into(), + value: preset("actor"), + }], + }; + let mutation = PreviewMutation::Upsert { + scope: scope.clone(), + fields: vec![PreviewField { + field: "title".into(), + value: PreviewExpression::Object { + fields: vec![PreviewObjectField { + name: "nested".into(), + value: PreviewExpression::List { + values: vec![ + preset("label"), + preset("actor"), + PreviewExpression::Constant { + value: ManifestProjectionValue::String("trusted_preset".into()), + }, + ], + }, + }], + }, + }], + replace: vec![], + }; + let mut names = BTreeSet::new(); + mutation.collect_trusted_presets(&mut names); + assert_eq!(names, ["actor", "label", "tenant"].map(String::from).into()); + names.clear(); + PreviewMutation::Delete { scope }.collect_trusted_presets(&mut names); + assert_eq!(names, ["actor", "tenant"].map(String::from).into()); + names.clear(); + PreviewMutation::InvalidateModel { + model: "Todo".into(), + partition: Some(PreviewPartition::Unit), + } + .collect_trusted_presets(&mut names); + assert!(names.is_empty()); + } + fn event() -> ManifestProjectionEventRef { ManifestProjectionEventRef { id: "event:test:v1".into(), diff --git a/distributed_cli/src/client_compiler/render/commands.rs b/distributed_cli/src/client_compiler/render/commands.rs index 7f44ddf78..2de3d690e 100644 --- a/distributed_cli/src/client_compiler/render/commands.rs +++ b/distributed_cli/src/client_compiler/render/commands.rs @@ -518,11 +518,26 @@ fn command_artifact_json( direct_projection_json(direct, manifest)?, ); } - if !command.extensions.trusted_presets.is_empty() { - artifact.insert( - "trustedPresets".into(), - serde_json::json!(command.extensions.trusted_presets), - ); + let mut referenced_presets = projection + .as_ref() + .map(CompiledCommandProjection::trusted_preset_names) + .unwrap_or_default(); + if let Some(ManifestEffectExpression::TrustedPreset { name }) = command + .extensions + .direct_projection + .as_ref() + .and_then(|direct| direct.partition.as_ref()) + { + referenced_presets.insert(name.clone()); + } + let trusted_presets = command + .extensions + .trusted_presets + .iter() + .filter(|descriptor| referenced_presets.contains(&descriptor.name)) + .collect::>(); + if !trusted_presets.is_empty() { + artifact.insert("trustedPresets".into(), serde_json::json!(trusted_presets)); } artifact.insert( "revalidation".into(), diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 865631687..52dd91697 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -3106,6 +3106,62 @@ fn command_protocol_and_extensions_are_preserved_exactly() { ["values"][2]["source"] = json!({"kind": "trusted_preset", "name": "priority", "codec": "int32"}); refresh_schema_fingerprint(&mut preset_i64_value); + // An unknown record identity drops the mutation, including its preset + // expression. The generated inventory must follow the compiled result, + // while the surface retains the complete trusted context contract. + let mut recovery_preset = preset_i64_value.clone(); + recovery_preset["commands"][0]["extensions"]["projection"]["preview_occurrences"][0] + ["values"][1]["source"] = json!({"kind": "unknown"}); + refresh_schema_fingerprint(&mut recovery_preset); + for (fixture, retained) in [(preset_i64_value.clone(), true), (recovery_preset, false)] { + let compiled = compile_client(input_with_manifest(fixture, "query Todos { todos { id } }")) + .expect("compile preset inventory after preview lowering"); + let source = file(&compiled, "commands.ts"); + let declaration = source + .split("export const Command_createTodo:") + .nth(1) + .unwrap(); + let body = declaration + .split_once(" = ") + .unwrap() + .1 + .split_once("\n};") + .unwrap() + .0; + let artifact: JsonValue = serde_json::from_str(&format!("{body}\n}}")).unwrap(); + assert_eq!( + artifact["protocol"]["trustedPresets"], + json!([{"name": "priority", "codec": "int32"}]) + ); + if retained { + assert_eq!( + artifact["trustedPresets"], + json!([{"name": "priority", "codec": "int32"}]) + ); + assert!(!artifact["projection"]["preview"]["operations"] + .as_array() + .unwrap() + .is_empty()); + } else { + let fixture: JsonValue = serde_json::from_str(include_str!( + "../../tests/fixtures/generated-recovery-preset-command.json" + )) + .unwrap(); + assert_eq!( + artifact, fixture, + "JS bridge fixture must match compiler output" + ); + assert!(artifact.get("trustedPresets").is_none()); + assert!(artifact["projection"]["preview"]["operations"] + .as_array() + .unwrap() + .is_empty()); + assert!(!artifact["projection"]["preview"]["recoveries"] + .as_array() + .unwrap() + .is_empty()); + } + } let mut invalid_u64_source = input_i64_value.clone(); invalid_u64_source["projection_programs"][0]["arms"][0]["operations"][0]["fields"][1] ["assignment"]["expression"]["value_type"] = json!({"type": "u64"}); diff --git a/distributed_cli/tests/fixtures/generated-recovery-preset-command.json b/distributed_cli/tests/fixtures/generated-recovery-preset-command.json new file mode 100644 index 000000000..001c1c9a4 --- /dev/null +++ b/distributed_cli/tests/fixtures/generated-recovery-preset-command.json @@ -0,0 +1,199 @@ +{ + "consistency": "eventual", + "document": "mutation Client_createTodo($commandId: ID!, $input: CreateTodoInput!) { createTodo(commandId: $commandId, input: $input) { id } }", + "input": { + "definition": { + "fields": [ + { + "codec": "string", + "itemNullable": false, + "list": false, + "name": "id", + "nullable": false, + "typeName": "ID" + }, + { + "codec": "string", + "itemNullable": false, + "list": false, + "name": "tenantId", + "nullable": false, + "typeName": "ID" + }, + { + "codec": "string", + "itemNullable": false, + "list": false, + "name": "title", + "nullable": false, + "typeName": "String" + } + ], + "name": "CreateTodoInput" + }, + "kind": "object" + }, + "inputDefaults": { + "defaults": [ + { + "generator": "uuid_v7", + "path": [ + "id" + ] + } + ], + "version": 1 + }, + "mutationField": "createTodo", + "name": "todo.create", + "operationHash": "sha256:9b2ba78faeaad3b384d74519aff78252c2f7f0305db1ac0dda9833ba25af58e5", + "output": { + "definition": { + "fields": [ + { + "codec": "string", + "itemNullable": false, + "list": false, + "name": "id", + "nullable": false, + "typeName": "ID" + } + ], + "name": "CreateTodoPayload" + }, + "kind": "object" + }, + "projection": { + "capabilities": { + "arms": [ + { + "arm": "todo-created", + "event": { + "id": "event:todo.created:v1", + "name": "todo.created", + "version": 1 + }, + "mutations": [ + { + "delete": false, + "fields": [ + "completed", + "priority", + "title" + ], + "key": [ + "tenantId", + "id" + ], + "kind": "record", + "model": "Todo", + "patch": true, + "replace": [ + "completed", + "priority", + "title" + ], + "upsert": true + }, + { + "kind": "model", + "model": "Todo" + } + ], + "partition": { + "expression_fingerprint": "sha256:129a821dac4ec2bb0a8a1dccacdcb62a87ad8cac25fc9933f341b0fc7a6169f3", + "kind": "opaque" + }, + "projection_ref": 0 + } + ], + "version": 1 + }, + "deltaWireVersion": 1, + "eventSet": [ + { + "id": "event:todo.created:v1", + "name": "todo.created", + "version": 1 + } + ], + "fallback": "revalidate", + "operationSemanticsVersion": 1, + "preview": { + "occurrences": [ + { + "event": { + "id": "event:todo.created:v1", + "name": "todo.created", + "version": 1 + }, + "ordinal": 0 + } + ], + "operations": [], + "recoveries": [ + { + "condition": "always", + "occurrence_ordinal": 0, + "projection_refs": [ + 0 + ], + "target": { + "kind": "model", + "model": "Todo", + "partition": { + "expression": { + "kind": "input", + "path": [ + "tenantId" + ] + }, + "kind": "expression", + "requires": "current_cache_partition" + } + } + } + ], + "version": 1 + }, + "projectionProgramVersion": 2, + "projections": [ + { + "bindingId": "pb1:sha256:2222222222222222222222222222222222222222222222222222222222222222", + "epoch": "todos-projection-v2", + "operationSemanticsVersion": 1, + "programId": "pp1:sha256:1111111111111111111111111111111111111111111111111111111111111111", + "programIrVersion": 1 + } + ], + "version": 2 + }, + "protocol": { + "operation": "sha256:9b2ba78faeaad3b384d74519aff78252c2f7f0305db1ac0dda9833ba25af58e5", + "protocolHash": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "schemaHash": "sha256:574ba7862d1814821cb9de30c2494f298031dd1d25ea615317aac1062af08b60", + "surface": { + "kind": "role", + "name": "user" + }, + "trustedPresets": [ + { + "codec": "int32", + "name": "priority" + } + ], + "version": 1 + }, + "revalidation": { + "dependencies": [ + "todo_rows" + ], + "models": [ + "Todo" + ], + "relationships": [], + "required": true, + "version": 1 + }, + "version": 2 +} diff --git a/js/tests/replica-command-artifacts.test.mjs b/js/tests/replica-command-artifacts.test.mjs index b4a0f0f6e..0b7abd29b 100644 --- a/js/tests/replica-command-artifacts.test.mjs +++ b/js/tests/replica-command-artifacts.test.mjs @@ -32,6 +32,23 @@ const GENERATED_DRAINING_COMMAND = JSON.parse( ) ); +test('compiled recovery-only command drops unused presets without weakening validation', () => { + const artifact = JSON.parse(readFileSync(new URL( + '../../distributed_cli/tests/fixtures/generated-recovery-preset-command.json', import.meta.url + ), 'utf8')); + assert.deepEqual(artifact.protocol.trustedPresets, [{ name: 'priority', codec: 'int32' }]); + assert.equal(artifact.trustedPresets, undefined); + assert.deepEqual(artifact.projection.preview.operations, []); + assert.ok(artifact.projection.preview.recoveries.length > 0); + const input = { id: GENERATED_UUID, tenantId: 'tenant-1', title: 'Prepare' }; + assert.doesNotThrow(() => prepareReplicaCommand(artifact, input, { commandId: COMMAND_ID })); + const invalid = { ...artifact, trustedPresets: artifact.protocol.trustedPresets }; + assert.throws( + () => prepareReplicaCommand(invalid, input, { commandId: COMMAND_ID }), + /artifact.trustedPresets\[0\]/ + ); +}); + const scalarField = ( name, typeName = 'String', From 23b14a59856f19a395586ec2c9a317ceb7961d2f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 11:25:38 -0500 Subject: [PATCH 029/484] feat: derive typed facts with explicit source provenance Add retry-stable canonical derived occurrences without synthetic aggregate transitions. Reject derived facts in source-snapshot projections and document at-least-once publication. --- README.md | 37 +++++ src/domain_event/derived_tests.rs | 185 +++++++++++++++++++++ src/domain_event/mod.rs | 4 +- src/domain_event/occurrence.rs | 104 +++++++++++- src/projection/error.rs | 5 + src/projection/plan.rs | 3 + src/projection_protocol/source_snapshot.rs | 5 + tests/fixtures/derived_event_save.graphql | 3 + 8 files changed, 344 insertions(+), 2 deletions(-) create mode 100644 src/domain_event/derived_tests.rs create mode 100644 tests/fixtures/derived_event_save.graphql diff --git a/README.md b/README.md index 3045894ef..d7769dbd6 100644 --- a/README.md +++ b/README.md @@ -1283,6 +1283,43 @@ let message = OutboxMessage::encode_for_entity( )?; ``` +### Facts derived by event handlers + +An event handler may verify an external result without making another aggregate +decision—for example, extracting document metadata after an upload. Derive a +typed fact from the incoming canonical occurrence: + +```rust,ignore +#[derive(serde::Serialize, distributed::DomainEvent)] +#[domain_event(name = "document.indexed", version = 1)] +struct DocumentIndexed { + document_id: String, + word_count: u64, +} + +let indexed = source.derive( + "document-indexer", + "metadata-v1", + &DocumentIndexed { document_id, word_count }, +)?; +``` + +The same source, producer, output key and body produce identical canonical bytes +and an identical event ID. Different outputs or changed bodies have different +IDs. `indexed.derivation()` identifies the immediate source and producer; the +aggregate fields retain the original transition's provenance, not an invented +commit. Timestamp, causation, correlation and trace metadata come from the source. +Ordinary typed projections can consume the derived fact. Aggregate-snapshot +projections reject it because it does not establish a new aggregate version. + +Publish the canonical bytes using the existing bus API and `indexed.id()` as +the message ID. Propagate its causal metadata. Acknowledge the incoming delivery +only after every output publish succeeds; a failure retries the source and may +republish an accepted prefix with the same IDs. This is at-least-once delivery, +not an atomic external effect plus publish. Aggregate decisions still use a +transactional outbox. Bound external reads and make effects idempotent before +using this pattern. + ### Publishing the Outbox How a committed row reaches the bus depends on whether a bus is attached to the diff --git a/src/domain_event/derived_tests.rs b/src/domain_event/derived_tests.rs new file mode 100644 index 000000000..fd71e4bd7 --- /dev/null +++ b/src/domain_event/derived_tests.rs @@ -0,0 +1,185 @@ +use super::*; +use serde::Serialize; + +#[derive(Clone, serde::Serialize, serde::Deserialize, crate::ReadModel)] +#[readmodel(table = "derived_rows", primary_key = ["bytes"])] +struct DerivedRows { + bytes: u64, +} +#[allow(non_snake_case)] +fn SaveDerived() -> crate::Mutation<()> { + crate::mutation_file!("tests/fixtures/derived_event_save.graphql") +} +use crate::projection::lower::{EventualOnly, ProjectionDescriptor}; +crate::projection! { + const DERIVED_ROWS: ProjectionDescriptor = { + name: "derived-rows", version: 1, epoch: "derived-v1", model: DerivedRows, + on { events: [Indexed], mutation: SaveDerived, input: { row: body }, }, + }; +} +crate::projection! { + const SNAPSHOT_ROWS: ProjectionDescriptor = { + name: "derived-snapshot-rejection", version: 1, epoch: "snapshot-v1", model: DerivedRows, + source: aggregate_snapshot, + on { events: [Indexed], mutation: SaveDerived, input: { row: body }, }, + }; +} + +#[derive(Serialize)] +struct Indexed { + bytes: u64, +} +impl DomainEventContract for Indexed { + const EVENT_NAME: &'static str = "document.indexed"; + const EVENT_VERSION: u64 = 1; + fn descriptor() -> DomainEventDescriptor { + ::DESCRIPTOR.clone() + } +} +impl DomainEvent for Indexed { + const DESCRIPTOR: DomainEventDescriptor = DomainEventDescriptor { + name: std::borrow::Cow::Borrowed("document.indexed"), + version: 1, + body: DomainEventBodyDescriptor::distributed_json( + DomainEventBodyKind::Event, + "Indexed", + 1, + "indexed-v1", + "sha256:1111111111111111111111111111111111111111111111111111111111111111", + ), + }; +} +fn source() -> DomainEventOccurrence { + let mut entity = crate::Entity::with_id("document-1"); + entity.set_causation_id("command-1"); + entity.set_correlation_id("request-1"); + entity.digest("document.changed", &()).unwrap(); + entity + .capture_domain_event("document", &Indexed { bytes: 1 }) + .unwrap(); + entity.pending_domain_events()[0].clone() +} + +#[test] +fn derived_retry_round_trip_preserves_source_provenance() { + let source = source(); + let derived = source + .derive("indexer", "summary", &Indexed { bytes: 10 }) + .unwrap(); + let repeated = source + .derive("indexer", "summary", &Indexed { bytes: 10 }) + .unwrap(); + assert_eq!(derived, repeated); + assert_eq!( + derived.canonical_bytes().unwrap(), + repeated.canonical_bytes().unwrap() + ); + assert_eq!(derived.aggregate_id(), source.aggregate_id()); + assert_eq!(derived.aggregate_sequence(), source.aggregate_sequence()); + assert_eq!(derived.occurred_at_unix_ms(), source.occurred_at_unix_ms()); + assert_eq!(derived.causation_id(), source.causation_id()); + assert_eq!(derived.correlation_id(), source.correlation_id()); + assert_eq!( + derived.derivation().unwrap().source_occurrence_id, + source.id() + ); + assert_eq!( + DomainEventOccurrence::from_canonical_bytes(&derived.canonical_bytes().unwrap()).unwrap(), + derived + ); + assert!(source.derivation().is_none()); + assert_eq!( + DomainEventOccurrence::from_canonical_bytes(&source.canonical_bytes().unwrap()).unwrap(), + source + ); + let nested = derived + .derive("renderer", "html", &Indexed { bytes: 20 }) + .unwrap(); + assert_eq!( + nested.derivation().unwrap().source_occurrence_id, + derived.id() + ); + assert_eq!(nested.aggregate_id(), source.aggregate_id()); +} + +#[test] +fn derived_identity_binds_producer_key_body_and_parent() { + let source = source(); + let first = source + .derive("indexer", "one", &Indexed { bytes: 10 }) + .unwrap(); + for other in [ + source + .derive("other", "one", &Indexed { bytes: 10 }) + .unwrap(), + source + .derive("indexer", "two", &Indexed { bytes: 10 }) + .unwrap(), + source + .derive("indexer", "one", &Indexed { bytes: 11 }) + .unwrap(), + first + .derive("indexer", "one", &Indexed { bytes: 10 }) + .unwrap(), + ] { + assert_ne!(first.id(), other.id()); + } +} + +#[test] +fn derived_keys_and_canonical_tampering_fail_closed() { + let source = source(); + for key in ["".into(), " ".into(), "a\nb".into(), "x".repeat(1025)] { + assert!(source + .derive("indexer", &key, &Indexed { bytes: 1 }) + .is_err()); + } + assert!(source.derive("", "key", &Indexed { bytes: 1 }).is_err()); + let derived = source + .derive("indexer", "one", &Indexed { bytes: 10 }) + .unwrap(); + for (pointer, value) in [ + ("/derivation/output_key", serde_json::json!("changed")), + ("/aggregate_sequence", serde_json::json!(10)), + ("/occurred_at_unix_ms", serde_json::json!(0)), + ("/body", serde_json::json!("e30=")), + ] { + let mut wire = serde_json::to_value(&derived).unwrap(); + *wire.pointer_mut(pointer).unwrap() = value; + assert!( + DomainEventOccurrence::from_canonical_bytes(&canonical_json_bytes(&wire).unwrap()) + .is_err() + ); + } +} + +#[test] +fn derived_facts_are_not_aggregate_snapshots() { + let source = source(); + let derived = source + .derive("indexer", "one", &Indexed { bytes: 10 }) + .unwrap(); + assert!(crate::projection_protocol::SourceSnapshotVersion::from_occurrence(&source).is_ok()); + assert!(crate::projection_protocol::SourceSnapshotVersion::from_occurrence(&derived).is_err()); + assert_eq!( + DERIVED_ROWS + .server_executor() + .unwrap() + .plan(&derived) + .unwrap() + .write_plan + .mutations + .len(), + 1 + ); + assert!(SNAPSHOT_ROWS + .server_executor() + .unwrap() + .plan(&derived) + .is_err()); + assert!(SNAPSHOT_ROWS + .server_executor() + .unwrap() + .plan(&source) + .is_ok()); +} diff --git a/src/domain_event/mod.rs b/src/domain_event/mod.rs index 86fa4b0bb..0843f9e62 100644 --- a/src/domain_event/mod.rs +++ b/src/domain_event/mod.rs @@ -5,6 +5,8 @@ //! untouched, and only explicit successful persistence clears them. mod canonical; +#[cfg(test)] +mod derived_tests; mod descriptor; mod occurrence; @@ -19,7 +21,7 @@ pub use descriptor::{ }; pub use occurrence::{ DomainEventCaptureError, DomainEventCaptureOutcome, DomainEventCapturePoison, - DomainEventCommitGuardError, DomainEventEnvelope, DomainEventOccurrence, + DomainEventCommitGuardError, DomainEventDerivation, DomainEventEnvelope, DomainEventOccurrence, DOMAIN_EVENT_OCCURRENCE_VERSION, }; diff --git a/src/domain_event/occurrence.rs b/src/domain_event/occurrence.rs index f9b584f6b..592bb11dd 100644 --- a/src/domain_event/occurrence.rs +++ b/src/domain_event/occurrence.rs @@ -22,6 +22,20 @@ use super::{ /// Version of the canonical [`DomainEventOccurrence`] envelope. pub const DOMAIN_EVENT_OCCURRENCE_VERSION: u16 = 1; +/// Provenance of a typed fact produced while handling an earlier occurrence. +/// The envelope's aggregate fields still describe the originating transition, +/// not a new aggregate commit by this producer. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DomainEventDerivation { + /// Immediate parent occurrence (which may itself be derived). + pub source_occurrence_id: String, + /// Stable effect-handler identity. + pub producer: String, + /// Stable output identity within this handler/source pair. + pub output_key: String, +} + /// Immutable framework metadata captured with one outward event transition. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DomainEventEnvelope { @@ -42,6 +56,8 @@ pub struct DomainEventEnvelope { /// One exact typed outward event captured at aggregate transition time. #[derive(Clone, PartialEq, Eq, Serialize)] pub struct DomainEventOccurrence { + #[serde(skip_serializing_if = "Option::is_none")] + derivation: Option, /// Canonical occurrence envelope version. occurrence_version: u16, /// Retry-stable occurrence identity. @@ -113,6 +129,7 @@ impl DomainEventOccurrence { validate_stable_message_id(Some(&id)).map_err(DomainEventCaptureError::OccurrenceId)?; let occurrence = Self { + derivation: None, occurrence_version: DOMAIN_EVENT_OCCURRENCE_VERSION, id, descriptor, @@ -133,6 +150,80 @@ impl DomainEventOccurrence { &self.body } + /// Derive a typed fact without inventing another aggregate transition. + /// + /// Repeat with the same source, producer, output key and body for identical + /// canonical bytes. Changed bodies have distinct identities. Publishing is + /// still at-least-once: acknowledge the source only after all outputs have + /// been accepted by the bus, and retry accepted prefixes with these IDs. + pub fn derive( + &self, + producer: &str, + output_key: &str, + body: &T, + ) -> Result { + self.validate()?; + let mut result = self.clone(); + result.descriptor = T::DESCRIPTOR.clone(); + if result.descriptor.body.kind != DomainEventBodyKind::Event { + return Err(DomainEventCaptureError::BodyKindMismatch { + expected: DomainEventBodyKind::Event, + actual: result.descriptor.body.kind, + }); + } + result.derivation = Some(DomainEventDerivation { + source_occurrence_id: self.id.clone(), + producer: producer.into(), + output_key: output_key.into(), + }); + result.body = canonical_json_bytes(body)?; + result.id = result.derived_identity()?; + result.canonical_bytes()?; + Ok(result) + } + + /// None for an aggregate's own captured transition facts. + pub fn derivation(&self) -> Option<&DomainEventDerivation> { + self.derivation.as_ref() + } + + fn derived_identity(&self) -> Result { + let derivation = self + .derivation + .as_ref() + .ok_or(DomainEventCaptureError::InvalidDerivation)?; + validate_message_name(&derivation.producer) + .map_err(|_| DomainEventCaptureError::InvalidDerivation)?; + validate_stable_message_id(Some(&derivation.source_occurrence_id)) + .map_err(|_| DomainEventCaptureError::InvalidDerivation)?; + if derivation.output_key.trim().is_empty() + || derivation.output_key.len() > 1024 + || derivation.output_key.chars().any(char::is_control) + { + return Err(DomainEventCaptureError::InvalidDerivation); + } + if self.descriptor.body.kind != DomainEventBodyKind::Event { + return Err(DomainEventCaptureError::InvalidDerivation); + } + let mut hash = Sha256::new(); + hash.update(b"distributed.domain-event.derived/v1\0"); + for value in [ + &derivation.source_occurrence_id, + &derivation.producer, + &derivation.output_key, + &self.aggregate_type, + &self.aggregate_id, + ] { + hash_component(&mut hash, value.as_bytes()); + } + hash.update(self.aggregate_sequence.to_be_bytes()); + hash.update(self.publication_ordinal.to_be_bytes()); + hash.update(self.occurred_at_unix_ms.to_be_bytes()); + hash_component(&mut hash, &canonical_json_bytes(&self.descriptor)?); + hash_component(&mut hash, &self.body); + Ok(format!("dd1:sha256:{:x}", hash.finalize())) + } + /// Return the canonical occurrence envelope version. pub fn occurrence_version(&self) -> u16 { self.occurrence_version @@ -241,6 +332,7 @@ impl DomainEventOccurrence { let wire: DomainEventOccurrenceWire = serde_json::from_slice(bytes) .map_err(|error| DomainEventCaptureError::OccurrenceDecoding(error.to_string()))?; let occurrence = Self { + derivation: wire.derivation, occurrence_version: wire.occurrence_version, id: wire.id, descriptor: wire.descriptor, @@ -294,7 +386,12 @@ impl DomainEventOccurrence { occurred_at: UNIX_EPOCH, metadata: BTreeMap::new(), }; - if occurrence_id(&self.descriptor, &envelope) != self.id { + let expected_id = if self.derivation.is_some() { + self.derived_identity()? + } else { + occurrence_id(&self.descriptor, &envelope) + }; + if expected_id != self.id { return Err(DomainEventCaptureError::OccurrenceIdentityMismatch); } Ok(()) @@ -310,6 +407,8 @@ impl DomainEventOccurrence { #[derive(Deserialize)] struct DomainEventOccurrenceWire { + #[serde(default)] + derivation: Option, occurrence_version: u16, id: String, descriptor: DomainEventDescriptor, @@ -390,6 +489,8 @@ fn validate_fingerprint(fingerprint: &str) -> Result<(), DomainEventCaptureError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum DomainEventCaptureError { + /// Derived provenance has an invalid producer, output key or source identity. + InvalidDerivation, /// Semantic event name violated transport naming rules. EventName(MessageNameError), /// Aggregate type violated transport naming rules. @@ -468,6 +569,7 @@ pub enum DomainEventCaptureError { impl fmt::Display for DomainEventCaptureError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::InvalidDerivation => formatter.write_str("invalid domain-event derivation"), Self::EventName(error) => write!(formatter, "invalid domain-event name: {error}"), Self::AggregateType(error) => write!(formatter, "invalid aggregate type: {error}"), Self::AggregateId(error) => write!(formatter, "invalid aggregate id: {error}"), diff --git a/src/projection/error.rs b/src/projection/error.rs index 75dae206d..fb05a2a73 100644 --- a/src/projection/error.rs +++ b/src/projection/error.rs @@ -4,6 +4,8 @@ use std::fmt; #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ProjectionProgramError { + /// Derived facts are not new authoritative aggregate snapshots. + DerivedSourceSnapshot, /// A stable name, identifier, field, or storage name was empty. EmptyName(&'static str), /// A declared version must be non-zero. @@ -118,6 +120,9 @@ pub enum ProjectionProgramError { impl fmt::Display for ProjectionProgramError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::DerivedSourceSnapshot => { + formatter.write_str("derived facts cannot establish an aggregate source snapshot") + } Self::EmptyName(kind) => write!(formatter, "{kind} must not be empty"), Self::ZeroVersion(kind) => write!(formatter, "{kind} must be non-zero"), Self::InvalidBodyFingerprint => formatter.write_str( diff --git a/src/projection/plan.rs b/src/projection/plan.rs index 18327a42e..82b704ece 100644 --- a/src/projection/plan.rs +++ b/src/projection/plan.rs @@ -387,6 +387,9 @@ impl ResolvedProjectionPlan { program: &ProjectionProgram, occurrence: &DomainEventOccurrence, ) -> Result { + if program.source_snapshots() && occurrence.derivation().is_some() { + return Err(ProjectionProgramError::DerivedSourceSnapshot); + } let matches = program .arms() .iter() diff --git a/src/projection_protocol/source_snapshot.rs b/src/projection_protocol/source_snapshot.rs index 7b676ecd4..fdf8d6542 100644 --- a/src/projection_protocol/source_snapshot.rs +++ b/src/projection_protocol/source_snapshot.rs @@ -38,6 +38,11 @@ impl SourceSnapshotVersion { pub(crate) fn from_occurrence( event: &DomainEventOccurrence, ) -> Result { + if event.derivation().is_some() { + return Err(ProjectionProtocolError::InvalidBatch( + "derived facts cannot establish an aggregate source snapshot".into(), + )); + } let canonical = event .canonical_bytes() .map_err(|error| ProjectionProtocolError::InvalidBatch(error.to_string()))?; diff --git a/tests/fixtures/derived_event_save.graphql b/tests/fixtures/derived_event_save.graphql new file mode 100644 index 000000000..fc1100fef --- /dev/null +++ b/tests/fixtures/derived_event_save.graphql @@ -0,0 +1,3 @@ +mutation SaveDerived { + upsert_derived_rows(object: $input.row) +} From 855a8ad050b85ecaef7b04c5d37c11ef86685a23 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 11:27:58 -0500 Subject: [PATCH 030/484] test: prove derived fact retry through NATS --- tests/nats_transport/main.rs | 97 ++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/tests/nats_transport/main.rs b/tests/nats_transport/main.rs index 4ba7d937a..9b6c293b5 100644 --- a/tests/nats_transport/main.rs +++ b/tests/nats_transport/main.rs @@ -28,6 +28,103 @@ fn nats_url() -> Option { env_support::broker_env("NATS_URL", "nats transport test") } +#[tokio::test] +async fn derived_facts_round_trip_after_interrupted_publish_prefix() { + let Some(url) = nats_url() else { return }; + #[derive(serde::Serialize, distributed::DomainEvent)] + #[domain_event(name = "document.indexed", version = 1)] + struct Indexed { + document_id: String, + words: u64, + } + let mut entity = distributed::Entity::with_id("document-1"); + entity.set_causation_id("0190a000-0000-7000-8000-000000000094"); + entity.digest("document.uploaded", &()).unwrap(); + entity + .capture_domain_event( + "document", + &Indexed { + document_id: "one".into(), + words: 0, + }, + ) + .unwrap(); + let parent = entity.pending_domain_events()[0].clone(); + let outputs = || { + ["one", "two"].map(|key| { + parent + .derive( + "indexer", + key, + &Indexed { + document_id: key.into(), + words: 10, + }, + ) + .unwrap() + }) + }; + let initial = outputs(); + let retry = outputs(); + assert_eq!(initial, retry); + let subject = unique("derived.document.indexed"); + let source = NatsJetStreamSource::connect( + &url, + &unique("STREAM"), + vec![subject.clone()], + &unique("consumer"), + ) + .await + .unwrap() + .with_fetch_timeout(Duration::from_millis(800)); + let publisher = NatsPublisher::connect(&url).await.unwrap(); + // Simulate stopping after one accepted output. A new attempt regenerates + // both facts; JetStream receives the repeated stable message ID. + for output in [&initial[0], &retry[0], &retry[1]] { + publisher + .publish( + Message::new( + &subject, + MessageKind::Event, + output.canonical_bytes().unwrap(), + ) + .with_id(output.id()) + .with_metadata( + distributed::trace_context::CAUSATION_ID, + output.causation_id().unwrap(), + ), + ) + .await + .unwrap(); + } + let seen = Arc::new(Mutex::new(Vec::new())); + let captured = seen.clone(); + let service = Arc::new( + Service::new().routes( + Routes::new() + .with_dependencies(()) + .event(Box::leak(subject.into_boxed_str())) + .handle(move |ctx: &Context<()>| { + let decoded = distributed::DomainEventOccurrence::from_canonical_bytes( + ctx.message().payload(), + ) + .unwrap(); + assert_eq!(ctx.message().id(), Some(decoded.id())); + assert_eq!(ctx.message().causation_id(), decoded.causation_id()); + captured.lock().unwrap().push(decoded); + async { Ok(json!({})) } + }), + ), + ); + run_source(service, source, RunOptions::idempotent()) + .await + .unwrap(); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "broker deduplicates the accepted prefix"); + assert_eq!(seen[0], initial[0]); + assert_eq!(seen[1], initial[1]); +} + #[tokio::test] async fn publish_then_consume_round_trips_through_jetstream() { let Some(url) = nats_url() else { return }; From a2275d8b0541b4968bcf2700c7eff0c7a59c0602 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 13:51:59 -0500 Subject: [PATCH 031/484] feat!: normalize portable application manifest inventories Implements tasks/distributed-manifest-capacity. Manifest wire v2 derives flattened inventories from explicit ownership and retains bounded canonical validation. --- README.md | 7 ++ src/application/manifest.rs | 135 ++++++++++++++++++++++++++++--- tests/application_composition.rs | 83 ++++++++++++++++++- 3 files changed, 214 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d7769dbd6..ec0ec547e 100644 --- a/README.md +++ b/README.md @@ -2375,6 +2375,13 @@ distributed describe # print the ApplicationManifest as JSON distributed schema --dialect postgres # render migration SQL from read models ``` +Application manifest wire version 2 stores module declarations and selected +Surface contracts without repeating top-level `commands`, `events`, `models`, +or `projections`. The Rust `ApplicationManifest` decoder reconstructs those +inventories and validates their ownership; its convenience fields are unchanged. +Portable artifacts remain bounded to 4 MiB. Version 1 artifacts must be +regenerated with the matching CLI; they are not accepted as version 2. + For a full application, run `distributed build` or `distributed dev` from its Cargo workspace root. The CLI discovers the typed application, runtime binary, conventional `ui/` SvelteKit app, and `@hops-ops/distributed` dependency. A diff --git a/src/application/manifest.rs b/src/application/manifest.rs index 69be8507a..51b931213 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -8,13 +8,12 @@ use super::identity::{canonical_json, sha256_fingerprint, LogicalId}; use super::module::{ModelSpec, Module, ModuleManifest, ProjectionSpec, SurfaceSpec}; /// Wire/schema version for the complete logical application manifest. -pub const APPLICATION_MANIFEST_SCHEMA_VERSION: u32 = 1; +pub const APPLICATION_MANIFEST_SCHEMA_VERSION: u32 = 2; /// Bounds applied before a portable application artifact is accepted. /// -/// A complete manifest intentionally carries authoritative module declarations, -/// their flattened application inventory, and selected Surface contracts. Keep -/// the total bounded while leaving room for a production-sized application. +/// A complete manifest carries authoritative module declarations and selected +/// Surface contracts. Flattened inventories are reconstructed, not serialized. pub const MAX_APPLICATION_MANIFEST_BYTES: usize = 4 * 1024 * 1024; pub const MAX_MANIFEST_COLLECTION_ITEMS: usize = 4096; pub const MAX_MANIFEST_STRING_BYTES: usize = 4096; @@ -107,8 +106,7 @@ impl ApplicationExtension { /// executable handlers are intentionally absent. Those belong to named /// schema/deployment/runtime layers and cannot become portable application /// identity by accident. -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] -#[serde(deny_unknown_fields)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ApplicationManifest { /// This field is required during decoding: canonical input may not omit /// the explicit schema version and receive a legacy default. @@ -116,13 +114,13 @@ pub struct ApplicationManifest { pub name: String, #[serde(default)] pub modules: Vec, - #[serde(default)] + #[serde(skip_serializing)] pub commands: Vec, - #[serde(default)] + #[serde(skip_serializing)] pub events: Vec, - #[serde(default)] + #[serde(skip_serializing)] pub projections: Vec, - #[serde(default)] + #[serde(skip_serializing)] pub models: Vec, #[serde(default)] pub surfaces: Vec, @@ -136,7 +134,123 @@ pub struct ApplicationManifest { pub provenance: ManifestProvenance, } +/// Versioned portable authority. Derived inventories are deliberately absent: +/// accepting them would introduce a second, potentially conflicting authority. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ManifestWire { + schema_version: u32, + name: String, + #[serde(default)] + modules: Vec, + #[serde(default)] + surfaces: Vec, + #[serde(default)] + required_capabilities: Vec, + #[serde(default)] + extensions: Vec, + #[serde(default)] + fingerprints: ManifestFingerprint, + #[serde(default)] + provenance: ManifestProvenance, +} + +impl<'de> Deserialize<'de> for ApplicationManifest { + fn deserialize>(deserializer: D) -> Result { + let wire = ManifestWire::deserialize(deserializer)?; + let mut manifest = Self { + schema_version: wire.schema_version, + name: wire.name, + modules: wire.modules, + surfaces: wire.surfaces, + required_capabilities: wire.required_capabilities, + extensions: wire.extensions, + fingerprints: wire.fingerprints, + provenance: wire.provenance, + commands: Vec::new(), + events: Vec::new(), + projections: Vec::new(), + models: Vec::new(), + }; + manifest + .reconstruct_inventories() + .map_err(serde::de::Error::custom)?; + Ok(manifest) + } +} + impl ApplicationManifest { + fn validate_inventory_expansion(&self) -> ApplicationResult<()> { + // Check expansion before cloning any nested declarations. Duplicate + // declarations still consume the reconstruction budget. + validate_collection_len("modules", self.modules.len())?; + validate_collection_len("surfaces", self.surfaces.len())?; + for (kind, count) in [ + ( + "derived commands", + self.modules.iter().map(|m| m.commands.len()).sum(), + ), + ( + "derived events", + self.modules.iter().map(|m| m.events.len()).sum(), + ), + ( + "derived projections", + self.modules + .iter() + .map(|m| m.projections.len()) + .chain(self.surfaces.iter().map(|s| s.projections.len())) + .sum(), + ), + ( + "derived models", + self.modules + .iter() + .map(|m| m.models.len()) + .chain(self.surfaces.iter().map(|s| s.models.len())) + .sum(), + ), + ] { + validate_collection_len(kind, count)?; + } + Ok(()) + } + + fn reconstruct_inventories(&mut self) -> ApplicationResult<()> { + self.validate_inventory_expansion()?; + self.commands = dedup_commands( + self.modules + .iter() + .flat_map(|m| m.commands.iter().cloned()) + .collect(), + )?; + self.events = dedup_events( + self.modules + .iter() + .flat_map(|m| m.events.iter().cloned()) + .collect(), + )?; + self.projections = dedup_projections( + self.modules + .iter() + .flat_map(|m| m.projections.iter().cloned()) + .chain( + self.surfaces + .iter() + .flat_map(|s| s.projections.iter().cloned()), + ) + .collect(), + )?; + self.models = dedup_models( + self.modules + .iter() + .flat_map(|m| m.models.iter().cloned()) + .chain(self.surfaces.iter().flat_map(|s| s.models.iter().cloned())) + .collect(), + )?; + Ok(()) + } + pub fn new(name: impl Into) -> Self { Self { schema_version: APPLICATION_MANIFEST_SCHEMA_VERSION, @@ -365,6 +479,7 @@ impl ApplicationManifest { }); } LogicalId::try_new("application", self.name.clone())?; + self.validate_inventory_expansion()?; validate_collection_len("modules", self.modules.len())?; validate_collection_len("commands", self.commands.len())?; validate_collection_len("events", self.events.len())?; diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 99e411097..3fc3e970d 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -351,6 +351,87 @@ fn module_identity_is_identical_across_full_and_split_selection() { ); } +#[test] +fn normalized_manifest_fits_without_serializing_duplicate_model_inventory() { + use distributed::application::{ModelFieldSpec, ModelSpec, MAX_APPLICATION_MANIFEST_BYTES}; + let models = (0..64).map(|index| { + ModelSpec::try_new( + format!("Catalog{index:03}"), + format!("catalog_{index:03}"), + (0..400).map(|field| ModelFieldSpec { + name: format!("field_{field:03}_with_a_descriptive_domain_attribute_name"), + scalar: "String".into(), + nullable: false, + }), + ["field_000_with_a_descriptive_domain_attribute_name"], + ) + .unwrap() + }); + let module = Module::new("catalog").models(models).build().unwrap(); + let manifest = ApplicationManifest::try_from_modules("catalog-app", [module], []).unwrap(); + let bytes = manifest.canonical_bytes().unwrap(); + assert!(bytes.len() < MAX_APPLICATION_MANIFEST_BYTES); + let mut redundant = serde_json::from_slice::(&bytes).unwrap(); + redundant["models"] = serde_json::to_value(&manifest.models).unwrap(); + let redundant_bytes = serde_json::to_vec(&redundant).unwrap(); + assert!(redundant_bytes.len() > MAX_APPLICATION_MANIFEST_BYTES); + assert!(ApplicationManifest::from_canonical_bytes(&redundant_bytes).is_err()); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), + manifest + ); +} + +#[test] +fn manifest_reconstruction_rejects_excessive_inventory_before_cloning() { + let mut manifest = + ApplicationManifest::try_from_modules("app", [command_module()], []).unwrap(); + let mut wire = serde_json::to_value(&manifest).unwrap(); + let command = wire["modules"][0]["commands"][0].clone(); + wire["modules"][0]["commands"] = serde_json::Value::Array(vec![ + command; + distributed::application::MAX_MANIFEST_COLLECTION_ITEMS + + 1 + ]); + let error = serde_json::from_value::(wire).unwrap_err(); + assert!(error.to_string().contains("derived commands"), "{error}"); + manifest.modules[0].commands = vec![ + manifest.commands[0].clone(); + distributed::application::MAX_MANIFEST_COLLECTION_ITEMS + 1 + ]; + let error = manifest.canonical_bytes().unwrap_err(); + assert!(error.to_string().contains("derived commands"), "{error}"); +} + +#[test] +fn manifest_wire_derives_inventories_without_accepting_a_second_authority() { + let manifest = + ApplicationManifest::try_from_modules("normalized-app", [command_module()], []).unwrap(); + let bytes = manifest.canonical_bytes().unwrap(); + let wire: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(wire["schema_version"], 2); + for field in ["commands", "events", "models", "projections"] { + assert!( + wire.get(field).is_none(), + "{field} is derived, not wire authority" + ); + let mut redundant = wire.clone(); + redundant[field] = serde_json::json!([]); + assert!(serde_json::from_value::(redundant).is_err()); + } + assert_eq!( + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), + manifest + ); + let mut inconsistent = manifest.clone(); + inconsistent.commands.clear(); + assert!(inconsistent.canonical_bytes().is_err()); + + let mut old = wire; + old["schema_version"] = serde_json::json!(1); + assert!(ApplicationManifest::from_canonical_bytes(&serde_json::to_vec(&old).unwrap()).is_err()); +} + #[test] fn application_manifest_is_byte_deterministic_and_contains_no_executable_data() { let spec = command("todo.create"); @@ -561,7 +642,7 @@ fn nested_fingerprints_and_projection_references_are_fail_closed() { let application = application_with_commands(&["todo.create"]); let bytes = application.manifest().canonical_bytes().unwrap(); let mut value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); - value["commands"][0]["fingerprint"] = serde_json::json!(""); + value["modules"][0]["commands"][0]["fingerprint"] = serde_json::json!(""); let malformed: ApplicationManifest = serde_json::from_value(value) .expect("the malformed value should still be structurally deserializable"); assert!(malformed.clone().refresh_fingerprints().is_err()); From 06723a7310872175690d563a34793b157f22e2d9 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 14:12:00 -0500 Subject: [PATCH 032/484] fix: accept normalized manifests in CLI introspection --- distributed_cli/src/cli.rs | 35 +++++++++++---------------- distributed_cli/tests/cli_manifest.rs | 9 +++++++ 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index 76b5ca628..0ca5b3757 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -44,7 +44,7 @@ use crate::{ MetricsTarget, PostCreateAction, ServiceScaffoldSpec, ServiceTransport, StoreTarget, }; -const DISTRIBUTED_MANIFEST_SCHEMA_VERSION: u64 = 1; +const DISTRIBUTED_MANIFEST_SCHEMA_VERSION: u64 = 2; const DISTRIBUTED_CLIENT_MANIFEST_VERSION: u64 = 2; /// Top-level standalone CLI arguments for the `distributed` binary. @@ -2515,36 +2515,22 @@ fn github_repo_create_args(slug: &str) -> Vec<&str> { } fn validate_manifest_json(envelope: &serde_json::Value) -> Result<(), Box> { - let Some(schema_version) = envelope + let schema_version = envelope .get("schema_version") .and_then(serde_json::Value::as_u64) - else { - return Err("manifest JSON is missing numeric schema_version".into()); - }; + .ok_or("manifest JSON is missing numeric schema_version")?; if schema_version != DISTRIBUTED_MANIFEST_SCHEMA_VERSION { - return Err(format!( - "unsupported Distributed manifest schema version {schema_version}; expected {DISTRIBUTED_MANIFEST_SCHEMA_VERSION}" - ) - .into()); + return Err(format!("unsupported Distributed manifest schema version {schema_version}; expected {DISTRIBUTED_MANIFEST_SCHEMA_VERSION}").into()); } - // `describe` emits ApplicationManifest JSON (logical composition artifact), - // not the retired DistributedManifestEnvelope { project: ... } shape. if envelope .get("name") .and_then(serde_json::Value::as_str) - .map(str::is_empty) - .unwrap_or(true) + .filter(|name| !name.is_empty()) + .is_none() { return Err("application manifest JSON is missing non-empty string name".into()); } - for field in [ - "modules", - "commands", - "events", - "projections", - "models", - "surfaces", - ] { + for field in ["modules", "surfaces"] { if envelope .get(field) .and_then(serde_json::Value::as_array) @@ -2553,6 +2539,13 @@ fn validate_manifest_json(envelope: &serde_json::Value) -> Result<(), Box String { fn describe_emits_manifest_json() { let json = distributed(&["describe"]); let manifest: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(manifest["schema_version"], 2); + for inventory in ["commands", "events", "models", "projections"] { + assert!(manifest.get(inventory).is_none(), "redundant {inventory}"); + } + // This read-model-only fixture owns models through its Surface, not modules. + assert!(!manifest["surfaces"][0]["models"] + .as_array() + .unwrap() + .is_empty()); assert!(json.contains("\"schema_version\""), "json: {json}"); assert!(json.contains("\"orders\""), "json: {json}"); let framework = manifest["extensions"] From 6bf9b5b35d35887505ab2fb7d9f4ec23e7b829f6 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 15:09:52 -0500 Subject: [PATCH 033/484] fix: classify missing GraphQL session presets as bad requests --- README.md | 6 ++++ src/graphql/engine/request.rs | 50 ++++++++++++++++++++++++--- src/graphql/engine/tests.rs | 64 +++++++++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ec0ec547e..bca217b04 100644 --- a/README.md +++ b/README.md @@ -1994,6 +1994,12 @@ ModelPermissions::new() Row predicates can bind session claims (`claim("x-user-id")`, …) so multi-tenant RLS lives in the engine, not ad-hoc handler SQL. +With the causal protocol enabled, required session presets must be present and +valid for their declared codecs before execution. Missing or malformed values +return `BAD_REQUEST` for both ordinary and streaming requests, without running +resolvers or issuing a partial protocol envelope. The error does not disclose +claim names or values; configure the identity mapping to supply those inputs. + ### Identity (first-class OIDC) Auth is a **built-in GraphQL concern**, not a separate product you wire after the diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index 7cd88b2a2..9b79fd6de 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -1,5 +1,32 @@ use super::*; +enum ProtocolPreparationError { + RequiredPreset, + Internal, +} + +impl From<()> for ProtocolPreparationError { + fn from(_: ()) -> Self { + Self::Internal + } +} + +impl ProtocolPreparationError { + fn into_response(self) -> Response { + match self { + Self::RequiredPreset => { + let mut error = + ServerError::new("required session input is missing or invalid", None); + let mut extensions = async_graphql::ErrorExtensionValues::default(); + extensions.set("code", "BAD_REQUEST"); + error.extensions = Some(extensions); + Response::from_errors(vec![error]) + } + Self::Internal => protocol_internal_error_response(), + } + } +} + impl GraphqlEngine { pub async fn execute(&self, session: &Session, mut request: Request) -> Response { if selected_operation_type(&mut request) @@ -39,7 +66,7 @@ impl GraphqlEngine { let accumulator = match self.protocol_accumulator(&authority, session, &request) { Ok(accumulator) => accumulator, - Err(()) => return protocol_internal_error_response(), + Err(error) => return error.into_response(), }; if introspection { // The relaxed schema is defense-in-depth restricted even if a @@ -113,8 +140,8 @@ impl GraphqlEngine { } let accumulator = match self.protocol_accumulator(&authority, session, &request) { Ok(accumulator) => accumulator, - Err(()) => { - return stream::once(async { protocol_internal_error_response() }).boxed(); + Err(error) => { + return stream::once(async move { error.into_response() }).boxed(); } }; if accumulator @@ -144,7 +171,7 @@ impl GraphqlEngine { authority: &ExecutionAuthority, session: &Session, request: &Request, - ) -> Result, ()> { + ) -> Result, ProtocolPreparationError> { let Some(runtime) = &self.inner.protocol else { return Ok(None); }; @@ -153,7 +180,10 @@ impl GraphqlEngine { let trusted_presets = surface_info .trusted_presets .iter() - .map(|descriptor| resolve_protocol_preset(session, descriptor).ok_or(())) + .map(|descriptor| { + resolve_protocol_preset(session, descriptor) + .ok_or(ProtocolPreparationError::RequiredPreset) + }) .collect::, _>>()?; let principal = request .data @@ -312,6 +342,16 @@ mod lifecycle_request_tests { use async_graphql::parser::types::OperationType; use async_graphql::Request; + #[test] + fn internal_protocol_preparation_errors_are_not_request_errors() { + let response = super::ProtocolPreparationError::from(()).into_response(); + let expected = super::protocol_internal_error_response(); + assert_eq!( + serde_json::to_value(response).unwrap(), + serde_json::to_value(expected).unwrap() + ); + } + #[test] fn selected_operation_type_fails_closed_for_ambiguous_documents() { let mut mutation = Request::new("mutation Write { __typename }"); diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index fa4e51645..d805c06e6 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -975,6 +975,70 @@ mod client_surface_parity_tests { ); } + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn required_presets_reject_query_and_stream_without_internal_errors() { + let mut engine = preset_protocol_engine(); + Arc::get_mut(&mut engine.inner) + .unwrap() + .protocol + .as_mut() + .unwrap() + .roles + .get_mut("user") + .unwrap() + .surface + .trusted_presets = vec![ClientTrustedPresetDescriptor { + name: "x-required-number".into(), + codec: "int32".into(), + }]; + for value in [None, Some("not-a-number"), Some("01"), Some("2147483648")] { + let mut session = Session::new(); + session.set("x-roles", "user"); + if let Some(value) = value { + session.set("x-required-number", value); + } + let query = engine + .execute(&session, Request::new("{ __typename }")) + .await; + let streamed = engine + .execute_stream(&session, Request::new("{ __typename }")) + .collect::>() + .await; + assert_eq!(streamed.len(), 1); + for response in std::iter::once(query).chain(streamed) { + assert_eq!(response.errors.len(), 1); + let error = serde_json::to_value(&response.errors[0]).unwrap(); + assert_eq!(error["extensions"]["code"], "BAD_REQUEST", "{error}"); + assert_eq!( + error["message"], + "required session input is missing or invalid" + ); + assert_eq!(response.data, Value::Null); + assert!(!response.extensions.contains_key("distributed")); + } + } + let mut valid = Session::new(); + valid.set("x-roles", "user"); + valid.set("x-required-number", "42"); + let response = engine.execute(&valid, Request::new("{ __typename }")).await; + assert!(!response.is_err(), "{:?}", response.errors); + assert_eq!( + distributed_extension(&response)["trustedPresets"][0]["value"], + 42 + ); + let responses = engine + .execute_stream(&valid, Request::new("{ __typename }")) + .collect::>() + .await; + assert_eq!(responses.len(), 1); + assert!(!responses[0].is_err()); + assert_eq!( + distributed_extension(&responses[0])["trustedPresets"][0]["value"], + 42 + ); + } + #[cfg(feature = "sqlite")] #[tokio::test] async fn cache_scope_tracks_only_relevant_claims_and_private_policy() { From 165e2a3fe7d3a74d6aaf4f44916bfb8631b6497b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:06:22 -0500 Subject: [PATCH 034/484] feat: define direct relationships to unique candidate keys WIP foundation: metadata, derive parsing and direct key resolution. Runtime, protocol and browser verification remain before adoption. --- distributed_macros/src/read_model/attrs.rs | 22 ++++++ distributed_macros/src/read_model/tests.rs | 24 ++++++ src/graphql/client_manifest/tests.rs | 3 + src/graphql/complexity.rs | 2 + .../engine/composite_relationship_tests.rs | 5 ++ src/graphql/engine/tests.rs | 1 + src/graphql/projection_delta/tests.rs | 1 + src/graphql/surface/projections.rs | 1 + src/graphql/surface/tests.rs | 8 ++ .../projection_protocol/tests.rs | 2 + src/projection/catalog.rs | 1 + .../projection_protocol/postgres_tests.rs | 2 + src/sqlx_repo/projection_protocol/tests.rs | 2 + src/table/metadata.rs | 6 ++ src/table/mutation.rs | 1 + src/table/registry.rs | 75 ++++++++++++++++++- tests/graphql_engine/main.rs | 2 + tests/graphql_harden/authz.rs | 2 + tests/graphql_harden/dos.rs | 4 + tests/graphql_harden/residual.rs | 2 + tests/graphql_sdl/main.rs | 3 + tests/graphql_sqlite/main.rs | 2 + 22 files changed, 170 insertions(+), 1 deletion(-) diff --git a/distributed_macros/src/read_model/attrs.rs b/distributed_macros/src/read_model/attrs.rs index 410c3f80d..fc0898a89 100644 --- a/distributed_macros/src/read_model/attrs.rs +++ b/distributed_macros/src/read_model/attrs.rs @@ -99,6 +99,7 @@ impl FieldAttrs { pub(super) fn from_field(field: &Field) -> syn::Result { let mut attrs = Self::default(); let mut pending_foreign_key: Option = None; + let mut pending_references: Option = None; let mut pending_through: Option = None; let mut pending_target_foreign_key: Option = None; for attr in &field.attrs { @@ -165,6 +166,11 @@ impl FieldAttrs { if meta.input.peek(Token![=]) { attrs.default = Some(meta.value()?.parse::()?.value()); } + } else if meta.path.is_ident("references") { + if pending_references.is_some() { + return Err(meta.error("relationship references declared more than once")); + } + pending_references = Some(meta.value()?.parse::()?.value()); } else if meta.path.is_ident("foreign_key") { let value = meta.value()?.parse::()?.value(); if attrs.relationship.is_some() { @@ -185,6 +191,7 @@ impl FieldAttrs { } else if meta.path.is_ident("has_many") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::HasMany, target_model: target, foreign_key: None, @@ -194,6 +201,7 @@ impl FieldAttrs { } else if meta.path.is_ident("belongs_to") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::BelongsTo, target_model: target, foreign_key: None, @@ -203,6 +211,7 @@ impl FieldAttrs { } else if meta.path.is_ident("many_to_many") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::ManyToMany, target_model: target, foreign_key: None, @@ -293,6 +302,16 @@ impl FieldAttrs { } } + if let Some(references) = pending_references { + let relationship = attrs.relationship.as_mut().ok_or_else(|| { + syn::Error::new_spanned(field, "`references` requires a direct relationship") + })?; + if matches!(relationship.kind, RelationshipKindAttr::ManyToMany) { + return Err(syn::Error::new_spanned(field, "`references` requires a direct relationship")); + } + relationship.references = Some(references); + } + if attrs.jsonb && attrs.text { return Err(syn::Error::new_spanned( field, @@ -331,6 +350,7 @@ impl FieldAttrs { )); }; let target_model = &relationship.target_model; + let references = option_string_tokens(relationship.references.as_deref()); let through = option_string_tokens(relationship.through.as_deref()); let target_foreign_key = option_string_tokens(relationship.target_foreign_key.as_deref()); let kind = match relationship.kind { @@ -342,6 +362,7 @@ impl FieldAttrs { }; Ok(Some(quote! { distributed::RelationshipDef { + references: #references, field_name: #field_name.to_string(), kind: #kind, target_model: #target_model.to_string(), @@ -485,6 +506,7 @@ pub(super) struct ForeignKeyParts { #[derive(Clone)] pub(super) struct RelationshipAttr { + pub(super) references: Option, pub(super) kind: RelationshipKindAttr, pub(super) target_model: String, pub(super) foreign_key: Option, diff --git a/distributed_macros/src/read_model/tests.rs b/distributed_macros/src/read_model/tests.rs index 7c7099b2f..94d0c3f9f 100644 --- a/distributed_macros/src/read_model/tests.rs +++ b/distributed_macros/src/read_model/tests.rs @@ -2,6 +2,30 @@ use super::types::{default_storage_name, to_snake_case}; use super::*; use syn::DeriveInput; +#[test] +fn direct_relationship_references_are_order_independent_and_emitted() { + for attributes in [ + "references = \"namespace,oid\", belongs_to = \"Object\", foreign_key = \"scope,oid\"", + "belongs_to = \"Object\", foreign_key = \"scope,oid\", references = \"namespace,oid\"", + ] { + let input = syn::parse_str(&format!( + "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" + )).unwrap(); + let expanded = expand_read_model(input).unwrap().to_string(); + assert!(expanded.contains("references : Some (\"namespace,oid\""), "{expanded}"); + } + for attributes in [ + "references = \"id\"", + "belongs_to = \"Object\", foreign_key = \"id\", references = \"id\", references = \"id\"", + "many_to_many = \"Object\", foreign_key = \"id\", through = \"links\", references = \"id\"", + ] { + let input = syn::parse_str(&format!( + "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" + )).unwrap(); + assert!(expand_read_model(input).is_err(), "accepted {attributes}"); + } +} + #[test] fn boxed_belongs_to_preserves_target_markers_and_checks_inner_type() { let input: DeriveInput = syn::parse_quote! { diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 94fb6c0a8..08a3efe6b 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -97,6 +97,7 @@ fn todos() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "owner".into(), kind: RelationshipKind::BelongsTo, target_model: "UserView".into(), @@ -148,6 +149,7 @@ fn teams() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "members".into(), kind: RelationshipKind::ManyToMany, target_model: "UserView".into(), @@ -1782,6 +1784,7 @@ fn bigint_keys_embed_until_decimal_string_identity_is_available() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "account".into(), kind: RelationshipKind::BelongsTo, target_model: "AccountView".into(), diff --git a/src/graphql/complexity.rs b/src/graphql/complexity.rs index 89ede855a..6e9ccbbd3 100644 --- a/src/graphql/complexity.rs +++ b/src/graphql/complexity.rs @@ -146,6 +146,7 @@ mod tests { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "Child".into(), @@ -175,6 +176,7 @@ mod tests { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "grandchildren".into(), kind: RelationshipKind::HasMany, target_model: "Grandchild".into(), diff --git a/src/graphql/engine/composite_relationship_tests.rs b/src/graphql/engine/composite_relationship_tests.rs index 71588fac3..e36bec367 100644 --- a/src/graphql/engine/composite_relationship_tests.rs +++ b/src/graphql/engine/composite_relationship_tests.rs @@ -69,6 +69,7 @@ fn workspaces() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "projects".into(), kind: RelationshipKind::HasMany, target_model: "ProjectView".into(), @@ -158,6 +159,7 @@ fn project_labels() -> TableSchema { fn projects_with_labels() -> TableSchema { let mut schema = projects(); schema.relationships.push(RelationshipDef { + references: None, field_name: "labels".into(), kind: RelationshipKind::ManyToMany, target_model: "LabelView".into(), @@ -175,6 +177,7 @@ fn simple_records_with_composite_fk() -> TableSchema { .columns .push(TableColumn::new("record_id", "record_id", ColumnType::Text)); schema.relationships.push(RelationshipDef { + references: None, field_name: "composite".into(), kind: RelationshipKind::BelongsTo, target_model: "CompositeRecord".into(), @@ -189,6 +192,7 @@ fn simple_records_with_composite_fk() -> TableSchema { fn projects_with_files() -> TableSchema { let mut schema = projects(); schema.relationships.push(RelationshipDef { + references: None, field_name: "files".into(), kind: RelationshipKind::HasMany, target_model: "ProjectFileView".into(), @@ -233,6 +237,7 @@ async fn belongs_to_with_a_partial_composite_foreign_key_is_rejected() { let composite = composite_records(); let mut simple = simple_records(); simple.relationships.push(RelationshipDef { + references: None, field_name: "composite".into(), kind: RelationshipKind::BelongsTo, target_model: "CompositeRecord".into(), diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index d805c06e6..6dcf06364 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -2146,6 +2146,7 @@ mod client_surface_parity_tests { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "PolicyChildView".into(), diff --git a/src/graphql/projection_delta/tests.rs b/src/graphql/projection_delta/tests.rs index 770b252b5..132ed426b 100644 --- a/src/graphql/projection_delta/tests.rs +++ b/src/graphql/projection_delta/tests.rs @@ -3675,6 +3675,7 @@ fn todos() -> TableSchema { foreign_keys: vec![], indexes: vec![], relationships: vec![RelationshipDef { + references: None, field_name: "owner".into(), kind: RelationshipKind::BelongsTo, target_model: "UserView".into(), diff --git a/src/graphql/surface/projections.rs b/src/graphql/surface/projections.rs index b1b53fd0e..0e2e96577 100644 --- a/src/graphql/surface/projections.rs +++ b/src/graphql/surface/projections.rs @@ -1075,6 +1075,7 @@ mod tests { "todos", &["todo_id", "owner_id", "title"], vec![RelationshipDef { + references: None, field_name: "owner".into(), kind: RelationshipKind::BelongsTo, target_model: "UserView".into(), diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index db54af2f7..5506b20c8 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -1310,6 +1310,7 @@ fn relationship_only_when_target_on_surface() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -1388,6 +1389,7 @@ fn surface_rejects_relationship_and_generated_aggregate_field_collisions() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "CollisionChild".into(), @@ -1432,6 +1434,7 @@ fn relationship_keys_canonicalize_rust_field_names_to_graphql_columns() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "account".into(), kind: RelationshipKind::BelongsTo, target_model: "AccountView".into(), @@ -1489,6 +1492,7 @@ fn pool_free_surface_rejects_a_partial_composite_belongs_to_key() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "composite".into(), kind: RelationshipKind::BelongsTo, target_model: "CompositeView".into(), @@ -1525,6 +1529,7 @@ fn row_policy_rejects_a_partial_composite_m2m_mapping() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "labels".into(), kind: RelationshipKind::ManyToMany, target_model: "OperationalLabel".into(), @@ -1629,6 +1634,7 @@ fn belongs_to_onto_composite_identity_is_selected_when_keys_are_paired() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "composite".into(), kind: RelationshipKind::BelongsTo, target_model: "CompositeView".into(), @@ -1680,6 +1686,7 @@ fn has_many_onto_composite_child_is_selected_on_the_parent() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "projects".into(), kind: RelationshipKind::HasMany, target_model: "ProjectView".into(), @@ -1755,6 +1762,7 @@ fn has_many_from_composite_parent_is_selected() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "files".into(), kind: RelationshipKind::HasMany, target_model: "ProjectFileView".into(), diff --git a/src/in_memory_repo/projection_protocol/tests.rs b/src/in_memory_repo/projection_protocol/tests.rs index 5546a105e..cbd3a4e04 100644 --- a/src/in_memory_repo/projection_protocol/tests.rs +++ b/src/in_memory_repo/projection_protocol/tests.rs @@ -116,6 +116,7 @@ fn graph_parent_schema() -> &'static TableSchema { indexes: Vec::new(), relationships: vec![ RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "GraphChildView".into(), @@ -124,6 +125,7 @@ fn graph_parent_schema() -> &'static TableSchema { target_foreign_key: None, }, RelationshipDef { + references: None, field_name: "featured_children".into(), kind: RelationshipKind::HasMany, target_model: "GraphChildView".into(), diff --git a/src/projection/catalog.rs b/src/projection/catalog.rs index 73b6471cb..a3ffa2487 100644 --- a/src/projection/catalog.rs +++ b/src/projection/catalog.rs @@ -2024,6 +2024,7 @@ mod tests { fn relationship_kind_is_part_of_the_output_schema_identity() { let mut schema = todo_schema("todos"); schema.relationships.push(RelationshipDef { + references: None, field_name: "owner".into(), kind: RelationshipKind::BelongsTo, target_model: "Owners".into(), diff --git a/src/sqlx_repo/projection_protocol/postgres_tests.rs b/src/sqlx_repo/projection_protocol/postgres_tests.rs index 9f2ff8353..07ae6f960 100644 --- a/src/sqlx_repo/projection_protocol/postgres_tests.rs +++ b/src/sqlx_repo/projection_protocol/postgres_tests.rs @@ -87,6 +87,7 @@ mod postgres_tests { indexes: Vec::new(), relationships: vec![ RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "PostgresGraphChildView".into(), @@ -95,6 +96,7 @@ mod postgres_tests { target_foreign_key: None, }, RelationshipDef { + references: None, field_name: "featured_children".into(), kind: RelationshipKind::HasMany, target_model: "PostgresGraphChildView".into(), diff --git a/src/sqlx_repo/projection_protocol/tests.rs b/src/sqlx_repo/projection_protocol/tests.rs index c45833ebf..a445b192f 100644 --- a/src/sqlx_repo/projection_protocol/tests.rs +++ b/src/sqlx_repo/projection_protocol/tests.rs @@ -162,6 +162,7 @@ mod tests { indexes: Vec::new(), relationships: vec![ RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "SqlGraphChildView".into(), @@ -170,6 +171,7 @@ mod tests { target_foreign_key: None, }, RelationshipDef { + references: None, field_name: "featured_children".into(), kind: RelationshipKind::HasMany, target_model: "SqlGraphChildView".into(), diff --git a/src/table/metadata.rs b/src/table/metadata.rs index c8e7fbb60..19c03c8e2 100644 --- a/src/table/metadata.rs +++ b/src/table/metadata.rs @@ -152,6 +152,10 @@ pub enum RelationshipKind { /// Relationship metadata for a relational table model. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RelationshipDef { + /// Ordered columns of the referenced primary or declared unique key. + /// Omission selects the primary key; row identity is never changed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub references: Option, pub field_name: String, pub kind: RelationshipKind, pub target_model: String, @@ -609,6 +613,7 @@ mod tests { let schema = valid_schema(); let mut with_relationship = schema.clone(); with_relationship.relationships.push(RelationshipDef { + references: None, field_name: "player".into(), kind: RelationshipKind::BelongsTo, target_model: "Player".into(), @@ -667,6 +672,7 @@ mod tests { fn validate_rejects_relationships_without_foreign_keys() { let mut schema = valid_schema(); schema.relationships.push(RelationshipDef { + references: None, field_name: "weapons".into(), kind: RelationshipKind::HasMany, target_model: "PlayerWeapon".into(), diff --git a/src/table/mutation.rs b/src/table/mutation.rs index adc3633ba..665bb28ac 100644 --- a/src/table/mutation.rs +++ b/src/table/mutation.rs @@ -491,6 +491,7 @@ mod tests { kind: TableKind::ReadModel, }; let relationship = RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "Child".into(), diff --git a/src/table/registry.rs b/src/table/registry.rs index 55113634b..1d53dac5a 100644 --- a/src/table/registry.rs +++ b/src/table/registry.rs @@ -158,6 +158,12 @@ impl TableSchemaRegistry { let _ = resolve_direct_join_keys(schema, relationship, target_schema)?; } RelationshipKind::ManyToMany => { + if relationship.references.is_some() { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` references requires a direct relationship", + schema.model_name, relationship.field_name, + ))); + } let through = relationship.through.as_deref().ok_or_else(|| { TableStoreError::Metadata(format!( "model `{}` relationship `{}` many-to-many must declare `through`", @@ -284,7 +290,31 @@ pub fn resolve_direct_join_keys( ))); } }; - let pk_columns = &pk_schema.primary_key.columns; + let explicit = parse_explicit_through_columns( + source, relationship, "references", relationship.references.as_deref(), + )?; + let referenced_columns = if let Some(names) = explicit { + let columns = names.iter().map(|name| { + column_name_on(pk_schema, name).map(str::to_owned).ok_or_else(|| TableStoreError::Metadata(format!( + "model `{}` relationship `{}` references unknown column `{name}` on `{}`", + source.model_name, relationship.field_name, pk_schema.model_name, + ))) + }).collect::, _>>()?; + let unique = columns == pk_schema.primary_key.columns || pk_schema.indexes.iter().any(|index| { + index.unique && index.columns.len() == columns.len() + && index.columns.iter().all(|column| columns.contains(column)) + }); + if !unique { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` references must name a declared unique key on `{}`", + source.model_name, relationship.field_name, pk_schema.model_name, + ))); + } + columns + } else { + pk_schema.primary_key.columns.clone() + }; + let pk_columns = &referenced_columns; if pk_columns.is_empty() { return Err(TableStoreError::Metadata(format!( "model `{}` relationship `{}` cannot join because `{}` has an empty primary key", @@ -714,6 +744,7 @@ mod m2m_join_key_tests { fn labels_rel(foreign_key: Option<&str>, target_foreign_key: Option<&str>) -> RelationshipDef { RelationshipDef { + references: None, field_name: "labels".into(), kind: RelationshipKind::ManyToMany, target_model: "LabelView".into(), @@ -842,6 +873,7 @@ mod m2m_join_key_tests { fn files_rel(foreign_key: &str) -> RelationshipDef { RelationshipDef { + references: None, field_name: "files".into(), kind: RelationshipKind::HasMany, target_model: "ProjectFileView".into(), @@ -892,6 +924,7 @@ mod m2m_join_key_tests { ], &["workspace_id", "path", "file_id"], vec![RelationshipDef { + references: None, field_name: "project".into(), kind: RelationshipKind::BelongsTo, target_model: "ProjectView".into(), @@ -941,4 +974,44 @@ mod m2m_join_key_tests { ] ); } + + #[test] + fn direct_join_can_reference_a_composite_candidate_key() { + let mut target = schema("Object", "objects", vec![pk_column("id"), column("namespace"), column("oid")], &["id"], vec![]); + target.indexes.push(crate::table::TableIndex { + name: None, columns: vec!["namespace".into(), "oid".into()], unique: true, + }); + let relation = RelationshipDef { + references: Some("namespace,oid".into()), + field_name: "object".into(), kind: RelationshipKind::BelongsTo, + target_model: "Object".into(), foreign_key: Some("scope,object_oid".into()), + through: None, target_foreign_key: None, + }; + let source = schema("Ref", "refs", vec![pk_column("ref_id"), column("scope"), column("object_oid")], &["ref_id"], vec![relation.clone()]); + assert_eq!(resolve_direct_join_keys(&source, &relation, &target).unwrap(), vec![ + DirectJoinPair::new("scope", "namespace"), + DirectJoinPair::new("object_oid", "oid"), + ]); + assert_eq!(target.primary_key.columns, vec!["id"]); + let reverse = RelationshipDef { + field_name: "refs".into(), kind: RelationshipKind::HasMany, + target_model: "Ref".into(), ..relation + }; + assert_eq!(resolve_direct_join_keys(&target, &reverse, &source).unwrap(), vec![ + DirectJoinPair::new("scope", "namespace"), + DirectJoinPair::new("object_oid", "oid"), + ]); + } + + #[test] + fn direct_join_rejects_non_unique_candidate_key() { + let source = projects(files_rel("workspace_id,path")); + let target = project_files(); + let mut relation = source.relationships[0].clone(); + relation.references = Some("kind".into()); + let error = resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string(); + assert!(error.contains("declared unique key"), "{error}"); + relation.references = Some("missing".into()); + assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("unknown column")); + } } diff --git a/tests/graphql_engine/main.rs b/tests/graphql_engine/main.rs index 1ab1808cf..25874e7da 100644 --- a/tests/graphql_engine/main.rs +++ b/tests/graphql_engine/main.rs @@ -44,6 +44,7 @@ fn bidirectional_parent_schema() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "Child".into(), @@ -72,6 +73,7 @@ fn bidirectional_child_schema() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "parent".into(), kind: RelationshipKind::BelongsTo, target_model: "Parent".into(), diff --git a/tests/graphql_harden/authz.rs b/tests/graphql_harden/authz.rs index c4164eaf1..0e442d7d7 100644 --- a/tests/graphql_harden/authz.rs +++ b/tests/graphql_harden/authz.rs @@ -187,6 +187,7 @@ async fn a5_nested_relationship_column_allowlist_denies() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -242,6 +243,7 @@ async fn a5_nested_relationship_column_allowlist_denies() { fn parent_child_engine(pool: sqlx::SqlitePool) -> GraphqlEngine { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), diff --git a/tests/graphql_harden/dos.rs b/tests/graphql_harden/dos.rs index 57cf39522..a49babf4e 100644 --- a/tests/graphql_harden/dos.rs +++ b/tests/graphql_harden/dos.rs @@ -298,6 +298,7 @@ async fn d8_nested_has_many_exceeds_complexity_budget() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -307,6 +308,7 @@ async fn d8_nested_has_many_exceeds_complexity_budget() { }]; let mut child = ChildView::schema().clone(); child.relationships = vec![RelationshipDef { + references: None, field_name: "grandchildren".into(), kind: RelationshipKind::HasMany, target_model: "GrandView".into(), @@ -401,6 +403,7 @@ async fn d8_shallow_nested_has_many_within_budget() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -476,6 +479,7 @@ async fn d8_low_max_complexity_rejects_single_nest() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), diff --git a/tests/graphql_harden/residual.rs b/tests/graphql_harden/residual.rs index ef41200e4..dcccce36c 100644 --- a/tests/graphql_harden/residual.rs +++ b/tests/graphql_harden/residual.rs @@ -32,6 +32,7 @@ async fn a8_nested_has_many_without_child_grant_is_unknown_field() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -102,6 +103,7 @@ async fn a12_rel_where_without_target_grant_is_unknown_field() { let mut parent = ParentView::schema().clone(); parent.relationships = vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), diff --git a/tests/graphql_sdl/main.rs b/tests/graphql_sdl/main.rs index b93e86000..e0fff7d71 100644 --- a/tests/graphql_sdl/main.rs +++ b/tests/graphql_sdl/main.rs @@ -26,6 +26,7 @@ fn players() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "weapons".into(), kind: RelationshipKind::HasMany, target_model: "PlayerWeaponView".into(), @@ -61,6 +62,7 @@ fn weapons() -> TableSchema { foreign_keys: vec![ForeignKey::new("players", "player_id")], indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "player".into(), kind: RelationshipKind::BelongsTo, target_model: "PlayerView".into(), @@ -150,6 +152,7 @@ fn m2m_requires_through_error() { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "tags".into(), kind: RelationshipKind::ManyToMany, target_model: "Tag".into(), diff --git a/tests/graphql_sqlite/main.rs b/tests/graphql_sqlite/main.rs index c3eced167..70da869f2 100644 --- a/tests/graphql_sqlite/main.rs +++ b/tests/graphql_sqlite/main.rs @@ -325,6 +325,7 @@ fn parent_schema() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "children".into(), kind: RelationshipKind::HasMany, target_model: "ChildView".into(), @@ -553,6 +554,7 @@ fn post_schema() -> TableSchema { foreign_keys: Vec::new(), indexes: Vec::new(), relationships: vec![RelationshipDef { + references: None, field_name: "author".into(), kind: RelationshipKind::BelongsTo, target_model: "AuthorView".into(), From 6318d970421f3e362c45c4c8d33378a57c5e441e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:12:44 -0500 Subject: [PATCH 035/484] test: verify unique-key joins and reject invalid mappings --- .../engine/composite_relationship_tests.rs | 58 +++++++++++++++++++ src/table/registry.rs | 57 +++++++++++++++++- 2 files changed, 113 insertions(+), 2 deletions(-) diff --git a/src/graphql/engine/composite_relationship_tests.rs b/src/graphql/engine/composite_relationship_tests.rs index e36bec367..18ba7c27f 100644 --- a/src/graphql/engine/composite_relationship_tests.rs +++ b/src/graphql/engine/composite_relationship_tests.rs @@ -265,6 +265,64 @@ async fn belongs_to_with_a_partial_composite_foreign_key_is_rejected() { ); } +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { + let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1) + .connect("sqlite::memory:").await.unwrap(); + for statement in [ + "CREATE TABLE composite_records (id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT NOT NULL, value TEXT NOT NULL, UNIQUE(tenant_id, record_id))", + "CREATE TABLE simple_records (simple_id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT)", + "INSERT INTO composite_records VALUES ('opaque-a','a','same','first'),('opaque-b','b','same','second')", + "INSERT INTO simple_records VALUES ('1','a','same'),('2','b','same'),('3','a',NULL),('4','missing','same')", + ] { + sqlx::query(statement).execute(&pool).await.unwrap(); + } + let mut target = composite_records(); + for column in &mut target.columns { column.primary_key = false; } + target.columns.push(TableColumn { primary_key: true, ..TableColumn::new("id", "id", ColumnType::Text) }); + target.primary_key = PrimaryKey::new(["id"]); + target.indexes.push(crate::table::TableIndex { name: None, columns: vec!["tenant_id".into(), "record_id".into()], unique: true }); + target.relationships.push(RelationshipDef { + references: Some("tenant_id,record_id".into()), + field_name: "refs".into(), kind: RelationshipKind::HasMany, + target_model: "SimpleRecord".into(), foreign_key: Some("tenant_id,record_id".into()), + through: None, target_foreign_key: None, + }); + let mut source = simple_records(); + source.columns.push(TableColumn { nullable: true, ..TableColumn::new("record_id", "record_id", ColumnType::Text) }); + source.relationships.push(RelationshipDef { + references: Some("tenant_id,record_id".into()), + field_name: "record".into(), kind: RelationshipKind::BelongsTo, + target_model: "CompositeRecord".into(), foreign_key: Some("tenant_id,record_id".into()), + through: None, target_foreign_key: None, + }); + let project = ReadModelCatalog::new("unique-key-test").table_schema(target).table_schema(source); + let engine = GraphqlEngine::from_schema_catalog(&project, pool).unwrap() + .roles(&["admin"]).grant_all("admin").build().unwrap(); + let mut session = Session::new(); + session.set(crate::microsvc::ROLE_KEY, "admin"); + let response = engine.execute(&session, Request::new( + "{ simple_records(order_by: [{simple_id: asc}]) { simple_id record { id value } } }" + )).await; + assert!(response.errors.is_empty(), "{:?}", response.errors); + let data = response.data.into_json().unwrap(); + assert_eq!(data["simple_records"], serde_json::json!([ + {"simple_id":"1","record":{"id":"opaque-a","value":"first"}}, + {"simple_id":"2","record":{"id":"opaque-b","value":"second"}}, + {"simple_id":"3","record":null}, + {"simple_id":"4","record":null}, + ])); + let reverse = engine.execute(&session, Request::new( + "{ composite_records(order_by: [{id: asc}]) { id refs { simple_id } } }" + )).await; + assert!(reverse.errors.is_empty(), "{:?}", reverse.errors); + assert_eq!(reverse.data.into_json().unwrap()["composite_records"], serde_json::json!([ + {"id":"opaque-a","refs":[{"simple_id":"1"}]}, + {"id":"opaque-b","refs":[{"simple_id":"2"}]}, + ])); +} + #[cfg(feature = "sqlite")] #[tokio::test] async fn belongs_to_loads_composite_target_rows() { diff --git a/src/table/registry.rs b/src/table/registry.rs index 1d53dac5a..a91596435 100644 --- a/src/table/registry.rs +++ b/src/table/registry.rs @@ -300,7 +300,14 @@ pub fn resolve_direct_join_keys( source.model_name, relationship.field_name, pk_schema.model_name, ))) }).collect::, _>>()?; - let unique = columns == pk_schema.primary_key.columns || pk_schema.indexes.iter().any(|index| { + if columns.iter().collect::>().len() != columns.len() { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` references repeats a physical column", + source.model_name, relationship.field_name, + ))); + } + let unique = (columns.len() == pk_schema.primary_key.columns.len() + && pk_schema.primary_key.columns.iter().all(|column| columns.contains(column))) || pk_schema.indexes.iter().any(|index| { index.unique && index.columns.len() == columns.len() && index.columns.iter().all(|column| columns.contains(column)) }); @@ -335,15 +342,17 @@ pub fn resolve_direct_join_keys( }; if fk_names.len() != pk_columns.len() { return Err(TableStoreError::Metadata(format!( - "model `{}` relationship `{}` foreign_key lists {} column(s) but `{}` primary key has {}", + "model `{}` relationship `{}` foreign_key lists {} column(s) but `{}` {} has {}", source.model_name, relationship.field_name, fk_names.len(), pk_schema.model_name, + if relationship.references.is_some() { "referenced key" } else { "primary key" }, pk_columns.len() ))); } let mut pairs = Vec::with_capacity(pk_columns.len()); + let mut seen_foreign_columns = BTreeSet::new(); for (fk_name, pk_column) in fk_names.iter().zip(pk_columns) { let foreign_key_column = column_name_on(fk_schema, fk_name).ok_or_else(|| { let side = match relationship.kind { @@ -355,6 +364,22 @@ pub fn resolve_direct_join_keys( source.model_name, relationship.field_name, fk_schema.model_name )) })?; + if !seen_foreign_columns.insert(foreign_key_column) { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` foreign_key repeats a physical column", + source.model_name, relationship.field_name, + ))); + } + let foreign = fk_schema.columns.iter().find(|column| column.column_name == foreign_key_column).unwrap(); + let referenced = pk_schema.columns.iter().find(|column| column.column_name == *pk_column).ok_or_else(|| { + TableStoreError::Metadata(format!("referenced key column `{pk_column}` is missing")) + })?; + if foreign.column_type != referenced.column_type || foreign.jsonb != referenced.jsonb { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` joins incompatible column types for `{foreign_key_column}` and `{pk_column}`", + source.model_name, relationship.field_name, + ))); + } pairs.push(DirectJoinPair::new(foreign_key_column, pk_column.clone())); } Ok(pairs) @@ -375,6 +400,12 @@ pub fn resolve_m2m_join_keys( through_schema: &TableSchema, target_schema: &TableSchema, ) -> Result { + if relationship.references.is_some() { + return Err(TableStoreError::Metadata(format!( + "model `{}` relationship `{}` references requires a direct relationship", + source.model_name, relationship.field_name, + ))); + } if !matches!(relationship.kind, RelationshipKind::ManyToMany) { return Err(TableStoreError::Metadata(format!( "model `{}` relationship `{}` must be many-to-many to resolve join keys", @@ -1014,4 +1045,26 @@ mod m2m_join_key_tests { relation.references = Some("missing".into()); assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("unknown column")); } + + #[test] + fn direct_join_rejects_alias_duplicates_and_incompatible_types() { + let mut source = projects(files_rel("workspace_id,path")); + let mut target = project_files(); + let mut relation = source.relationships[0].clone(); + source.columns[0].field_name = "workspace_alias".into(); + relation.references = Some("workspace_alias,workspace_id".into()); + assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("repeats a physical column")); + relation.references = Some("workspace_id,path".into()); + target.columns[0].column_type = ColumnType::Integer; + assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("incompatible column types")); + } + + #[test] + fn programmatic_many_to_many_cannot_silently_ignore_references() { + let source = projects(labels_rel(None, None)); + let mut relation = source.relationships[0].clone(); + relation.references = Some("path".into()); + let error = resolve_m2m_join_keys(&source, &relation, &source, &labels()).unwrap_err().to_string(); + assert!(error.contains("requires a direct relationship"), "{error}"); + } } From f2ae496045df82a7855c53de9844f3528ad49f11 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:22:03 -0500 Subject: [PATCH 036/484] test: prove unique-key authorization across SQL backends --- .github/workflows/integration-postgres.yaml | 6 ++ README.md | 10 +++ .../engine/composite_relationship_tests.rs | 75 +++++++++++++++++-- 3 files changed, 85 insertions(+), 6 deletions(-) diff --git a/.github/workflows/integration-postgres.yaml b/.github/workflows/integration-postgres.yaml index a7eb33c0f..e6d213f9b 100644 --- a/.github/workflows/integration-postgres.yaml +++ b/.github/workflows/integration-postgres.yaml @@ -53,3 +53,9 @@ jobs: docker exec ${{ job.services.postgres.id }} createdb -U postgres distributed_rebuild cargo test --lib --no-default-features --features graphql,postgres projection::source_snapshot_tests::source_snapshots_postgres_reordering_and_restart -- --exact cargo test --lib --no-default-features --features graphql,postgres projection::source_snapshot_tests::snapshot_rebuild_postgres -- --exact + - name: Verify unique-key GraphQL joins and authorization + env: + DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:5432/distributed_unique_key_test + run: | + docker exec ${{ job.services.postgres.id }} createdb -U postgres distributed_unique_key_test + cargo test --lib --no-default-features --features graphql,postgres graphql::engine::composite_relationship_tests::unique_key_join_postgres_authorization_and_manifest -- --ignored --exact diff --git a/README.md b/README.md index bca217b04..906cdcd10 100644 --- a/README.md +++ b/README.md @@ -1841,6 +1841,16 @@ let loaded = repo PK (same-named columns, or `foreign_key` / `target_foreign_key` in PK order). A one-column `foreign_key` on a composite PK is an error, not a silent `.first()`. +- **Unique-key joins:** direct relationships can set + `references = "namespace,revision"` alongside + `foreign_key = "object_namespace,object_revision"`. The referenced columns + must be a complete declared unique key, such as + `#[unique(columns = ["namespace", "revision"])]`, on the target of + `belongs_to` or the source of `has_many`. Foreign-key columns pair in the + declared reference order. This lets a model retain a surrogate primary key + for row identity while relating by a domain key. Missing/null foreign keys + produce no match; nested target permissions still apply. Omitting `references` + selects the primary key. `references` is not supported on `many_to_many`. - **Cyclic singular relationships:** use `Option>` for a `belongs_to` field when two models refer to each other. For example, `#[readmodel(belongs_to = "Profile", foreign_key = "id")]` diff --git a/src/graphql/engine/composite_relationship_tests.rs b/src/graphql/engine/composite_relationship_tests.rs index 18ba7c27f..bd099f3d4 100644 --- a/src/graphql/engine/composite_relationship_tests.rs +++ b/src/graphql/engine/composite_relationship_tests.rs @@ -9,7 +9,7 @@ use crate::table::{ TableKind, TableSchema, }; -#[cfg(feature = "sqlite")] +#[cfg(any(feature = "sqlite", feature = "postgres"))] fn composite_records() -> TableSchema { TableSchema { model_name: "CompositeRecord".into(), @@ -34,7 +34,7 @@ fn composite_records() -> TableSchema { } } -#[cfg(feature = "sqlite")] +#[cfg(any(feature = "sqlite", feature = "postgres"))] fn simple_records() -> TableSchema { TableSchema { model_name: "SimpleRecord".into(), @@ -270,13 +270,38 @@ async fn belongs_to_with_a_partial_composite_foreign_key_is_rejected() { async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1) .connect("sqlite::memory:").await.unwrap(); + unique_key_join_fixture(pool.into()).await; +} + +#[cfg(feature = "postgres")] +#[tokio::test] +#[ignore = "requires dedicated DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL; run explicitly in PostgreSQL CI"] +async fn unique_key_join_postgres_authorization_and_manifest() { + let url = std::env::var("DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL").expect("dedicated test database URL"); + let options: sqlx::postgres::PgConnectOptions = url.parse().unwrap(); + assert!(options.get_database().unwrap_or("").starts_with("distributed_unique_key_test")); + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(1) + .connect_with(options).await.unwrap(); + unique_key_join_fixture(pool.into()).await; +} + +async fn unique_key_sql(pool: &GraphqlPool, statement: &'static str) { + match pool { + #[cfg(feature = "sqlite")] + GraphqlPool::Sqlite(pool) => { sqlx::query(statement).execute(pool).await.unwrap(); } + #[cfg(feature = "postgres")] + GraphqlPool::Postgres(pool) => { sqlx::query(statement).execute(pool).await.unwrap(); } + } +} + +async fn unique_key_join_fixture(pool: GraphqlPool) { for statement in [ - "CREATE TABLE composite_records (id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT NOT NULL, value TEXT NOT NULL, UNIQUE(tenant_id, record_id))", - "CREATE TABLE simple_records (simple_id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT)", + "CREATE TEMP TABLE composite_records (id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT NOT NULL, value TEXT NOT NULL, UNIQUE(tenant_id, record_id))", + "CREATE TEMP TABLE simple_records (simple_id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT)", "INSERT INTO composite_records VALUES ('opaque-a','a','same','first'),('opaque-b','b','same','second')", "INSERT INTO simple_records VALUES ('1','a','same'),('2','b','same'),('3','a',NULL),('4','missing','same')", ] { - sqlx::query(statement).execute(&pool).await.unwrap(); + unique_key_sql(&pool, statement).await; } let mut target = composite_records(); for column in &mut target.columns { column.primary_key = false; } @@ -298,7 +323,7 @@ async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { through: None, target_foreign_key: None, }); let project = ReadModelCatalog::new("unique-key-test").table_schema(target).table_schema(source); - let engine = GraphqlEngine::from_schema_catalog(&project, pool).unwrap() + let engine = GraphqlEngine::from_schema_catalog(&project, pool.clone()).unwrap() .roles(&["admin"]).grant_all("admin").build().unwrap(); let mut session = Session::new(); session.set(crate::microsvc::ROLE_KEY, "admin"); @@ -321,6 +346,44 @@ async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { {"id":"opaque-a","refs":[{"simple_id":"1"}]}, {"id":"opaque-b","refs":[{"simple_id":"2"}]}, ])); + // Parent visibility must not confer visibility on the referenced object. + let mut builder = GraphqlEngine::from_schema_catalog(&project, pool.clone()).unwrap() + .roles(&["reader"]).grant_all("reader"); + builder.permissions.get_mut(&("CompositeRecord".into(), "reader".into())).unwrap() + .permission.row_filter = Some(crate::graphql::col("value").eq("first")); + let restricted = builder.build().unwrap(); + let manifest = restricted.client_manifest_for_role("reader").unwrap(); + let object_model = manifest.models.iter().find(|model| model.source_table == "composite_records").unwrap(); + let normalization = serde_json::to_value(&object_model.normalization).unwrap(); + assert_eq!(normalization["kind"], "normalized"); + assert_eq!(normalization["fields"].as_array().unwrap().len(), 1); + assert_eq!(normalization["fields"][0]["name"], "id"); + let ref_model = manifest.models.iter().find(|model| model.source_table == "simple_records").unwrap(); + let mapping = &ref_model.relationships.iter().find(|relation| relation.name == "record").unwrap().key_mapping; + assert_eq!(serde_json::to_value(mapping).unwrap(), serde_json::json!({ + "kind":"direct", "local":["tenant_id","record_id"], "remote":["tenant_id","record_id"] + })); + session.set(crate::microsvc::ROLE_KEY, "reader"); + let query = "{ simple_records(order_by: [{simple_id: asc}]) { simple_id record { id } } }"; + let response = restricted.execute(&session, Request::new(query)).await; + assert!(response.errors.is_empty(), "{:?}", response.errors); + assert_eq!(response.data.into_json().unwrap()["simple_records"], serde_json::json!([ + {"simple_id":"1","record":{"id":"opaque-a"}}, + {"simple_id":"2","record":null}, + {"simple_id":"3","record":null}, + {"simple_id":"4","record":null}, + ])); + let hidden_filter = restricted.execute(&session, Request::new( + "{ simple_records(where: {record: {value: {_eq: \"second\"}}}) { simple_id } }" + )).await; + assert!(hidden_filter.errors.is_empty(), "{:?}", hidden_filter.errors); + assert_eq!(hidden_filter.data.into_json().unwrap()["simple_records"], serde_json::json!([])); + unique_key_sql(&pool, "UPDATE composite_records SET value='revoked' WHERE id='opaque-a'").await; + let revoked = restricted.execute(&session, Request::new(query)).await; + assert!(revoked.errors.is_empty(), "{:?}", revoked.errors); + for row in revoked.data.into_json().unwrap()["simple_records"].as_array().unwrap() { + assert!(row["record"].is_null(), "revoked target leaked: {row}"); + } } #[cfg(feature = "sqlite")] From 2dad91581ee74a3b02d1feb5dedbe6f0febe9eb3 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:28:05 -0500 Subject: [PATCH 037/484] fix: resolve unique keys in internal relationship loaders --- src/read_model/in_memory.rs | 79 +++++++++++++------------- src/sqlx_repo/read_model/load.rs | 19 ++----- src/sqlx_repo/read_model/mod.rs | 2 +- src/sqlx_repo/read_model/validation.rs | 14 ----- src/table/mod.rs | 2 +- src/table/mutation.rs | 18 ++++++ 6 files changed, 64 insertions(+), 70 deletions(-) diff --git a/src/read_model/in_memory.rs b/src/read_model/in_memory.rs index 6b3ded6ef..309abc7fa 100644 --- a/src/read_model/in_memory.rs +++ b/src/read_model/in_memory.rs @@ -14,7 +14,7 @@ use super::{ }; use crate::repository::{ReadModelWritePlanStore, RelationalReadModelQueryStore}; use crate::table::{ - column_name_for, has_many_join_columns, key_fingerprint, validate_key, validate_row_values, + has_many_join_columns, key_fingerprint, validate_key, validate_row_values, }; use crate::table::{ ExpectedVersion, PatchMode, RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, @@ -493,50 +493,16 @@ fn load_belongs_to_rows( root_row: &RowValues, spec: &IncludeSpec, ) -> Result>, TableStoreError> { - let foreign_key = spec.relationship.foreign_key.as_deref().ok_or_else(|| { - TableStoreError::Metadata(format!( - "relationship `{}` must declare a foreign key", - spec.relationship.field_name - )) - })?; - let source_column = column_name_for(root_schema, foreign_key).ok_or_else(|| { - TableStoreError::Metadata(format!( - "relationship `{}` foreign key `{}` is not a source column", - spec.relationship.field_name, foreign_key - )) - })?; - let target_column = belongs_to_target_column(&spec.target_schema, &source_column)?; + let (source_column, target_column) = crate::table::belongs_to_join_columns( + root_schema, &spec.relationship, &spec.target_schema, + )?; let source_value = root_row.get(&source_column).ok_or_else(|| { TableStoreError::Metadata(format!( "read model `{}` root row is missing relationship key `{}`", root_schema.model_name, source_column )) })?; - let key = RowKey::new([(target_column, source_value.clone())]); - let storage_key = relational_storage_key(&spec.target_schema.table_name, &key); - Ok(rows - .get(&storage_key) - .map(|row| { - vec![Versioned { - data: row.values.clone(), - version: row.version, - }] - }) - .unwrap_or_default()) -} - -fn belongs_to_target_column( - target_schema: &TableSchema, - source_column: &str, -) -> Result { - if target_schema.primary_key.columns.len() != 1 { - return Err(TableStoreError::Metadata(format!( - "belongs_to target `{}` must have a single-column primary key to load from `{}`", - target_schema.model_name, source_column - ))); - } - - Ok(target_schema.primary_key.columns[0].clone()) + Ok(rows_matching_column(rows, &spec.target_schema.table_name, &target_column, source_value)) } fn rows_matching_column( @@ -545,6 +511,7 @@ fn rows_matching_column( column: &str, value: &RowValue, ) -> Vec> { + if matches!(value, RowValue::Null) { return Vec::new(); } let prefix = format!("{table_name}:"); let mut matches = rows .iter() @@ -623,6 +590,40 @@ mod tests { ); } + #[test] + fn belongs_to_unique_key_matches_values_not_primary_key_and_never_nulls() { + let mut target = test_row_schema().clone(); + target.columns.push(TableColumn { nullable: true, ..TableColumn::new("slug", "slug", ColumnType::Text) }); + target.indexes.push(crate::TableIndex { name: None, columns: vec!["slug".into()], unique: true }); + let mut source = test_row_schema().clone(); + source.columns.push(TableColumn { nullable: true, ..TableColumn::new("target_slug", "target_slug", ColumnType::Text) }); + let spec = IncludeSpec { + name: "target".into(), target_schema: target.clone(), + relationship: RelationshipDef { + field_name: "target".into(), kind: RelationshipKind::BelongsTo, + target_model: target.model_name.clone(), foreign_key: Some("target_slug".into()), + references: Some("slug".into()), through: None, target_foreign_key: None, + }, + }; + let mut rows = HashMap::new(); + for (id, slug) in [("opaque", RowValue::String("chosen".into())), ("chosen", RowValue::String("other".into())), ("null-target", RowValue::Null)] { + let key = RowKey::new([("id", RowValue::String(id.into()))]); + let mut values = RowValues::new(); + values.insert("id", RowValue::String(id.into())); + values.insert("slug", slug); + rows.insert(relational_storage_key(&target.table_name, &key), StoredRow { values, version: 1 }); + } + let mut root = RowValues::new(); + root.insert("target_slug", RowValue::String("chosen".into())); + let found = load_belongs_to_rows(&rows, &source, &root, &spec).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].data.get("id"), Some(&RowValue::String("opaque".into()))); + root.insert("target_slug", RowValue::Null); + assert!(load_belongs_to_rows(&rows, &source, &root, &spec).unwrap().is_empty()); + root.insert("target_slug", RowValue::String("missing".into())); + assert!(load_belongs_to_rows(&rows, &source, &root, &spec).unwrap().is_empty()); + } + #[tokio::test] async fn relational_write_plan_patches_and_deletes_rows() { let store = InMemoryReadModelStore::new(); diff --git a/src/sqlx_repo/read_model/load.rs b/src/sqlx_repo/read_model/load.rs index 5fb9cf067..31b7884c5 100644 --- a/src/sqlx_repo/read_model/load.rs +++ b/src/sqlx_repo/read_model/load.rs @@ -4,7 +4,7 @@ use std::sync::RwLock; use sqlx::{Database, Encode, Executor, IntoArguments, Type}; use super::{ - belongs_to_target_column, column_by_name, push_key_predicates, push_order_by_primary_key, + column_by_name, push_key_predicates, push_order_by_primary_key, quote_identifier, relational_row_select, resolve_registered_read_model_schemas, row_to_versioned_values, IncludeSpec, SqlxReadModelBackend, }; @@ -146,20 +146,9 @@ where for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, for<'r> &'r str: sqlx::ColumnIndex<::Row>, { - let foreign_key = spec.relationship.foreign_key.as_deref().ok_or_else(|| { - TableStoreError::Metadata(format!( - "relationship `{}` must declare a foreign key", - spec.relationship.field_name - )) - })?; - let source_column = - crate::table::column_name_for(root_schema, foreign_key).ok_or_else(|| { - TableStoreError::Metadata(format!( - "relationship `{}` foreign key `{}` is not a source column", - spec.relationship.field_name, foreign_key - )) - })?; - let target_column = belongs_to_target_column(&spec.target_schema, &source_column)?; + let (source_column, target_column) = crate::table::belongs_to_join_columns( + root_schema, &spec.relationship, &spec.target_schema, + )?; let source_value = root_row.get(&source_column).ok_or_else(|| { TableStoreError::Metadata(format!( "read model `{}` root row is missing relationship key `{}`", diff --git a/src/sqlx_repo/read_model/mod.rs b/src/sqlx_repo/read_model/mod.rs index 011e35ea2..4dabdd97a 100644 --- a/src/sqlx_repo/read_model/mod.rs +++ b/src/sqlx_repo/read_model/mod.rs @@ -28,7 +28,7 @@ pub(crate) use schema_registry::{ remember_read_model_schemas, resolve_registered_read_model_schemas, IncludeSpec, }; pub(crate) use validation::{ - belongs_to_target_column, column_by_name, initial_row_version, patch_values_preserving_key, + column_by_name, initial_row_version, patch_values_preserving_key, quote_identifier, row_concurrency_conflict, row_values_from_key_and_patch, row_write_values, sql_read_model_capabilities, validate_row_expected_version, validate_sql_write_plan, validate_values_match_key, version_column, diff --git a/src/sqlx_repo/read_model/validation.rs b/src/sqlx_repo/read_model/validation.rs index 4b65c54f3..69e889a5a 100644 --- a/src/sqlx_repo/read_model/validation.rs +++ b/src/sqlx_repo/read_model/validation.rs @@ -148,20 +148,6 @@ pub(crate) fn validate_values_match_key( Ok(()) } -pub(crate) fn belongs_to_target_column( - target_schema: &TableSchema, - source_column: &str, -) -> Result { - if target_schema.primary_key.columns.len() != 1 { - return Err(TableStoreError::Metadata(format!( - "belongs_to target `{}` must have a single-column primary key to load from `{}`", - target_schema.model_name, source_column - ))); - } - - Ok(target_schema.primary_key.columns[0].clone()) -} - pub(crate) fn row_write_values<'schema>( schema: &'schema TableSchema, values: &RowValues, diff --git a/src/table/mod.rs b/src/table/mod.rs index 5533b69ab..1c30ec672 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -21,7 +21,7 @@ pub use metadata::{ RowValues, TableColumn, TableIndex, TableKind, TableSchema, DEFAULT_TABLE_VERSION_COLUMN, }; pub(crate) use mutation::{ - column_name_for, has_many_join_columns, key_fingerprint, key_from_row, + belongs_to_join_columns, column_name_for, has_many_join_columns, key_fingerprint, key_from_row, validate_delete_mutation, validate_expected_version, validate_key, validate_patch_mutation, validate_row_mutation, validate_row_values, }; diff --git a/src/table/mutation.rs b/src/table/mutation.rs index 665bb28ac..b5ba125f7 100644 --- a/src/table/mutation.rs +++ b/src/table/mutation.rs @@ -391,6 +391,24 @@ pub(crate) fn has_many_join_columns( } } +pub(crate) fn belongs_to_join_columns( + source: &TableSchema, + relationship: &RelationshipDef, + target: &TableSchema, +) -> Result<(String, String), TableStoreError> { + if !matches!(relationship.kind, RelationshipKind::BelongsTo) { + return Err(TableStoreError::Metadata("expected a belongs_to relationship".into())); + } + let pairs = super::registry::resolve_direct_join_keys(source, relationship, target)?; + match pairs.as_slice() { + [pair] => Ok((pair.foreign_key_column.clone(), pair.primary_key_column.clone())), + _ => Err(TableStoreError::Metadata(format!( + "relationship `{}` has a composite direct join; single-column belongs_to helpers cannot load it", + relationship.field_name, + ))), + } +} + pub(crate) fn key_fingerprint(key: &RowKey) -> String { let mut fingerprint = String::new(); for (column, value) in key.iter() { From 896af2d68621bbbe3bf9e781678caff7115f3fc7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:34:10 -0500 Subject: [PATCH 038/484] fix: align replica candidate-key joins with SQL null semantics --- js/src/replica/index-maintenance/engine.ts | 7 +++++- js/tests/replica-index-maintenance.test.mjs | 26 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/js/src/replica/index-maintenance/engine.ts b/js/src/replica/index-maintenance/engine.ts index 5918f2840..a5757e1c7 100644 --- a/js/src/replica/index-maintenance/engine.ts +++ b/js/src/replica/index-maintenance/engine.ts @@ -894,7 +894,12 @@ export function relationshipMembership( ) }; } - if (!sameValue(parent.fields[local], target.fields[remote])) { + // Direct SQL joins use equality, not IS NOT DISTINCT FROM: null never joins. + if ( + parent.fields[local] === null || + target.fields[remote] === null || + !sameValue(parent.fields[local], target.fields[remote]) + ) { return { related: false }; } } diff --git a/js/tests/replica-index-maintenance.test.mjs b/js/tests/replica-index-maintenance.test.mjs index 7ddda9422..a2537b4ef 100644 --- a/js/tests/replica-index-maintenance.test.mjs +++ b/js/tests/replica-index-maintenance.test.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createCacheEngine } from '../dist/internal/cache-engine.js'; +import { relationshipMembership } from '../dist/replica/index-maintenance/engine.js'; import { replaceOptimisticLayerOn } from '../dist/replica/distributed-replica/impl-optimistic.js'; import { createReplicaIndexMaintenanceRegistry, @@ -14,6 +15,31 @@ const Todo = Object.freeze({ id: 'Todo', identityFields: Object.freeze(['id']) } const Board = Object.freeze({ id: 'Board', identityFields: Object.freeze(['id']) }); const Card = Object.freeze({ id: 'Card', identityFields: Object.freeze(['id']) }); +test('direct candidate-key membership preserves row identity and SQL null semantics', () => { + const plan = { path: ['object'], relationship: { + keyMapping: { kind: 'direct', local: ['namespace', 'revision'], remote: ['scope', 'version'] } + } }; + const parent = { fields: { id: 'parent-id', namespace: 'team-a', revision: 'v1' } }; + const records = new Map([['parent-key', parent]]); + const branch = { metadata: { parent: 'parent-key' } }; + const target = { fields: { id: 'opaque-object-id', scope: 'team-a', version: 'v1' } }; + const membership = () => relationshipMembership(plan, branch, target, records); + assert.deepEqual(membership(), { related: true }); + target.fields.scope = 'team-b'; + assert.deepEqual(membership(), { related: false }); + target.fields.scope = 'team-a'; + parent.fields.revision = 'v2'; + assert.deepEqual(membership(), { related: false }); + target.fields.version = 'v2'; + assert.deepEqual(membership(), { related: true }); + assert.equal(target.fields.id, 'opaque-object-id'); + parent.fields.revision = null; + target.fields.version = null; + assert.deepEqual(membership(), { related: false }); + delete target.fields.version; + assert.equal(membership().reason.code, 'missing_field'); +}); + const COMPLETE = Object.freeze({ kind: 'complete' }); const COMPLETE_PAGINATION = Object.freeze({ kind: 'complete', From 796675cc82218483f4c5fc001579ed935c4ebd53 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:55:16 -0500 Subject: [PATCH 039/484] test: verify candidate-key hydration and live updates Implements tasks/distributed-unique-key-relations. --- .../client_compiler/runtime_bridge_tests.rs | 30 ++ .../fixtures/unique-key-bridge-operation.json | 332 ++++++++++++++++++ js/tests/unique-key-artifact-bridge.test.mjs | 76 ++++ 3 files changed, 438 insertions(+) create mode 100644 distributed_cli/tests/fixtures/unique-key-bridge-operation.json create mode 100644 js/tests/unique-key-artifact-bridge.test.mjs diff --git a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs index d6055ec48..1fef8612f 100644 --- a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs +++ b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs @@ -4,6 +4,36 @@ use super::render::{render_operation_artifact_json, render_operation_module}; use super::tests::manifest; use super::{ClientDocument, ClientSurfaceSelector}; +#[test] +fn unique_key_runtime_bridge_artifact_is_byte_exact() { + let mut value = manifest(); + value["models"][0]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "ownerTitle", "scalar": "String", "codec": "string", "nullable": true + })); + value["models"][0]["filter_input"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "ownerTitle", "operators": ["_eq"] + })); + for root in value["roots"].as_array_mut().unwrap() { + if let Some(fields) = root.get_mut("filter").and_then(|filter| filter.get_mut("fields")).and_then(|fields| fields.as_array_mut()) { + fields.push(serde_json::json!({"name": "ownerTitle", "operators": ["_eq"]})); + } + if let Some(fields) = root.get_mut("order").and_then(|order| order.get_mut("fields")).and_then(|fields| fields.as_array_mut()) { + fields.push(serde_json::json!("ownerTitle")); + } + } + value["models"][0]["relationships"][0]["key_mapping"] = serde_json::json!({ + "kind": "direct", "local": ["tenantId", "ownerTitle"], "remote": ["tenantId", "title"] + }); + value["models"][0]["relationships"][0]["maintenance"] = serde_json::json!("local"); + super::manifest::refresh_schema_fingerprint(&mut value); + let manifest = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")).unwrap(); + let document = ClientDocument::new("src/routes/unique-key/+page.graphql", + "query UniqueKeyBridge @load @live { todos(limit: 25) { id title owner { id title } } }"); + let operation = compile_document(&document, &manifest).unwrap(); + let artifact = format!("{}\n", render_operation_artifact_json(&operation, &manifest).unwrap()); + assert_eq!(artifact, include_str!("../../tests/fixtures/unique-key-bridge-operation.json")); +} + const RUNTIME_BRIDGE_QUERY: &str = r#" query RustRuntimeBridge($id: ID!, $tenantId: ID!) { todo(id: $id, tenantId: $tenantId) { diff --git a/distributed_cli/tests/fixtures/unique-key-bridge-operation.json b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json new file mode 100644 index 000000000..a6d76f052 --- /dev/null +++ b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json @@ -0,0 +1,332 @@ +{ + "id": "sha256:64d793257325afec58385b9e2e5e3d55fa778bc4d01753a123bd6fab2b67b010", + "document": "query UniqueKeyBridge {\n todos(limit: 25) {\n id\n title\n owner {\n id\n title\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n }\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n _distributed_ownerTitle: ownerTitle\n }\n}\n", + "source": { + "path": "src/routes/unique-key/+page.graphql", + "line": 1, + "column": 1 + }, + "variableCodec": { + "version": 2, + "limits": { + "maxDepth": 8, + "maxBoolWidth": 256, + "maxInList": 1000 + }, + "variables": {}, + "defaults": {}, + "inputs": {} + }, + "roots": [ + { + "responseKey": "todos", + "field": "todos", + "cardinality": "many", + "nullable": false, + "arguments": { + "limit": { + "kind": "literal", + "value": 25 + } + }, + "dependencies": [ + "todo_rows" + ], + "coverage": { + "kind": "offset", + "offsetArgument": "offset", + "limitArgument": "limit", + "defaultLimit": 25, + "maxLimit": 100 + }, + "filter": { + "fields": [ + { + "field": "completed", + "scalar": "Boolean", + "codec": "boolean", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "ownerTitle", + "scalar": "String", + "codec": "string", + "nullable": true, + "operators": [ + "_eq" + ] + }, + { + "field": "priority", + "scalar": "Int", + "codec": "int32", + "nullable": false, + "operators": [ + "_eq", + "_in", + "_nin" + ] + }, + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "title", + "scalar": "String", + "codec": "string", + "nullable": true, + "operators": [ + "_eq" + ] + } + ], + "relationships": [ + { + "field": "owner", + "targetModel": "Todo", + "kind": "belongs_to", + "keyMapping": { + "kind": "direct", + "local": [ + "tenantId", + "ownerTitle" + ], + "remote": [ + "tenantId", + "title" + ] + }, + "maintenance": "local", + "dependencies": [ + "todo_rows" + ] + } + ], + "rowPolicy": { + "kind": "unrestricted" + } + }, + "order": { + "fields": [ + { + "field": "completed", + "scalar": "Boolean", + "codec": "boolean", + "nullable": false + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "ownerTitle", + "scalar": "String", + "codec": "string", + "nullable": true + }, + { + "field": "priority", + "scalar": "Int", + "codec": "int32", + "nullable": false + }, + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "title", + "scalar": "String", + "codec": "string", + "nullable": true + } + ], + "tieBreakers": [ + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false + } + ] + }, + "pagination": { + "kind": "offset", + "insert": "local", + "delete": "local", + "reorder": "local", + "stableUpdate": "local" + }, + "selection": { + "typename": "todo", + "storage": { + "kind": "normalized", + "model": "Todo", + "identityFields": [ + "tenantId", + "id" + ] + }, + "members": [ + { + "kind": "scalar", + "responseKey": "id", + "field": "id", + "codec": "string", + "nullable": false + }, + { + "kind": "scalar", + "responseKey": "title", + "field": "title", + "codec": "string", + "nullable": true + }, + { + "kind": "branch", + "semantic": "relationship", + "responseKey": "owner", + "field": "owner", + "cardinality": "one", + "nullable": true, + "dependencies": [ + "todo_rows" + ], + "coverage": { + "kind": "complete" + }, + "relationship": { + "field": "owner", + "targetModel": "Todo", + "kind": "belongs_to", + "keyMapping": { + "kind": "direct", + "local": [ + "tenantId", + "ownerTitle" + ], + "remote": [ + "tenantId", + "title" + ] + }, + "maintenance": "local", + "dependencies": [ + "todo_rows" + ] + }, + "selection": { + "typename": "todo", + "storage": { + "kind": "normalized", + "model": "Todo", + "identityFields": [ + "tenantId", + "id" + ] + }, + "members": [ + { + "kind": "scalar", + "responseKey": "id", + "field": "id", + "codec": "string", + "nullable": false + }, + { + "kind": "scalar", + "responseKey": "title", + "field": "title", + "codec": "string", + "nullable": true + }, + { + "kind": "scalar", + "responseKey": "_distributed_tenantId", + "field": "tenantId", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_typename", + "field": "__typename", + "codec": "string", + "nullable": false, + "expose": false + } + ] + } + }, + { + "kind": "scalar", + "responseKey": "_distributed_tenantId", + "field": "tenantId", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_typename", + "field": "__typename", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_ownerTitle", + "field": "ownerTitle", + "codec": "string", + "nullable": true, + "expose": false + } + ] + } + } + ], + "protocol": { + "version": 1, + "schemaHash": "sha256:d43d65b233d9839f28271b4bdee7326f03b660cac3002013d8f058204e188415", + "surface": { + "kind": "role", + "name": "user" + }, + "operation": "sha256:64d793257325afec58385b9e2e5e3d55fa778bc4d01753a123bd6fab2b67b010", + "trustedPresets": [] + }, + "live": { + "id": "sha256:5f1d6c2a80bd0417bfd53ba757436a319fc6d9801af10247cd91cd32a6ac48e9", + "document": "subscription UniqueKeyBridge_Live {\n todos(limit: 25) {\n id\n title\n owner {\n id\n title\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n }\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n _distributed_ownerTitle: ownerTitle\n }\n}\n" + } +} diff --git a/js/tests/unique-key-artifact-bridge.test.mjs b/js/tests/unique-key-artifact-bridge.test.mjs new file mode 100644 index 000000000..c6c108017 --- /dev/null +++ b/js/tests/unique-key-artifact-bridge.test.mjs @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import { createDistributedReplica } from '../dist/replica/index.js'; +import { ControlledReplicaTransport } from './fixtures/adapter-conformance.mjs'; + +const artifact = JSON.parse(readFileSync(new URL( + '../../distributed_cli/tests/fixtures/unique-key-bridge-operation.json', import.meta.url +), 'utf8')); +const root = artifact.roots[0]; +const owner = root.selection.members.find(member => member.field === 'owner'); + +function frame(position, targetId, targetTitle) { + const records = []; + function wire(selection, values, path) { + records.push({ path, model: selection.storage.model, + scopeToken: `record:${values.id}`, incarnation: '1', revision: position, tombstone: false }); + return Object.fromEntries(selection.members.map(member => { + if (member.kind === 'branch') return [member.responseKey, targetId === null ? null : + wire(member.selection, { id: targetId, title: targetTitle, tenantId: 'tenant-a', + __typename: 'todo' }, [...path, member.responseKey])]; + assert.ok(Object.hasOwn(values, member.field), member.field); + return [member.responseKey, values[member.field]]; + })); + } + const row = wire(root.selection, { id: 'source-id', title: 'source', + ownerTitle: targetTitle, tenantId: 'tenant-a', __typename: 'todo' }, ['todos', '0']); + return { data: { todos: [row] }, extensions: { distributed: { + protocolVersion: artifact.protocol.version, schemaHash: artifact.protocol.schemaHash, + authorizationGeneration: 'auth-1', cacheScope: 'unique-key-cache', + operation: position === '1' ? artifact.id : artifact.live.id, + ...(position === '1' ? {} : { live: { supported: true, reset: false, cursors: [ + { projection: 'unique-key-projector', position, token: `resume:${position}` } + ] } }), + snapshot: { scopeToken: 'unique-key-snapshot', recordsComplete: true, indexesComparable: true, + records, indexes: [{ projection: 'unique-key-projector', scopeToken: 'unique-key-index', position, + resume: { projection: 'unique-key-projector', position, token: `resume:${position}` } }], observations: [] } + } } }; +} + +test('Rust-generated candidate-key relationship survives hydration and live reference changes', async () => { + assert.deepEqual(owner.relationship.keyMapping, { + kind: 'direct', local: ['tenantId', 'ownerTitle'], remote: ['tenantId', 'title'] + }); + assert.deepEqual(owner.selection.storage.identityFields, ['tenantId', 'id']); + const transport = new ControlledReplicaTransport(); + const server = createDistributedReplica({ transport }); + const watch = server.watch(artifact, {}, { live: false }); + const pending = watch.refresh(); + await Promise.resolve(); + transport.fetches[0].response.resolve(frame('1', 'target-one', 'first')); + await pending; + assert.deepEqual(server.read(artifact, {}).data.todos[0], { + id: 'source-id', title: 'source', owner: { id: 'target-one', title: 'first' } + }); + watch.destroy(); + const seed = server.dehydrate(); + const browserTransport = new ControlledReplicaTransport(); + const browser = createDistributedReplica({ transport: browserTransport }); + assert.equal(browser.hydrate(seed, seed.scope), true); + assert.deepEqual(browser.read(artifact, {}).data, server.read(artifact, {}).data); + const live = browser.watch(artifact, {}, { live: true }); + const unsubscribe = live.subscribe(() => {}); + assert.equal(browserTransport.fetches.length, 0); + assert.equal(browserTransport.lives.length, 1); + browserTransport.lives[0].observer.next(frame('2', 'target-two', 'second')); + assert.deepEqual(live.get().data.todos[0], { + id: 'source-id', title: 'source', owner: { id: 'target-two', title: 'second' } + }); + browserTransport.lives[0].observer.next(frame('3', null, null)); + assert.equal(live.get().data.todos[0].owner, null); + assert.equal(live.get().data.todos[0].id, 'source-id'); + unsubscribe(); + live.destroy(); + assert.equal(browserTransport.lives[0].closed, true); +}); From 31c7df655e434afa73fb79d5ce29d910faa77617 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 17:58:18 -0500 Subject: [PATCH 040/484] style: format unique-key relationship implementation --- .../client_compiler/runtime_bridge_tests.rs | 46 +++- distributed_macros/src/read_model/attrs.rs | 5 +- distributed_macros/src/read_model/tests.rs | 11 +- .../engine/composite_relationship_tests.rs | 205 +++++++++++++----- src/read_model/in_memory.rs | 72 ++++-- src/sqlx_repo/read_model/load.rs | 10 +- src/sqlx_repo/read_model/mod.rs | 4 +- src/table/mutation.rs | 4 +- src/table/registry.rs | 136 +++++++++--- 9 files changed, 360 insertions(+), 133 deletions(-) diff --git a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs index 1fef8612f..29ad43386 100644 --- a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs +++ b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs @@ -7,17 +7,31 @@ use super::{ClientDocument, ClientSurfaceSelector}; #[test] fn unique_key_runtime_bridge_artifact_is_byte_exact() { let mut value = manifest(); - value["models"][0]["fields"].as_array_mut().unwrap().push(serde_json::json!({ - "name": "ownerTitle", "scalar": "String", "codec": "string", "nullable": true - })); - value["models"][0]["filter_input"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ - "name": "ownerTitle", "operators": ["_eq"] - })); + value["models"][0]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": "ownerTitle", "scalar": "String", "codec": "string", "nullable": true + })); + value["models"][0]["filter_input"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": "ownerTitle", "operators": ["_eq"] + })); for root in value["roots"].as_array_mut().unwrap() { - if let Some(fields) = root.get_mut("filter").and_then(|filter| filter.get_mut("fields")).and_then(|fields| fields.as_array_mut()) { + if let Some(fields) = root + .get_mut("filter") + .and_then(|filter| filter.get_mut("fields")) + .and_then(|fields| fields.as_array_mut()) + { fields.push(serde_json::json!({"name": "ownerTitle", "operators": ["_eq"]})); } - if let Some(fields) = root.get_mut("order").and_then(|order| order.get_mut("fields")).and_then(|fields| fields.as_array_mut()) { + if let Some(fields) = root + .get_mut("order") + .and_then(|order| order.get_mut("fields")) + .and_then(|fields| fields.as_array_mut()) + { fields.push(serde_json::json!("ownerTitle")); } } @@ -27,11 +41,19 @@ fn unique_key_runtime_bridge_artifact_is_byte_exact() { value["models"][0]["relationships"][0]["maintenance"] = serde_json::json!("local"); super::manifest::refresh_schema_fingerprint(&mut value); let manifest = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")).unwrap(); - let document = ClientDocument::new("src/routes/unique-key/+page.graphql", - "query UniqueKeyBridge @load @live { todos(limit: 25) { id title owner { id title } } }"); + let document = ClientDocument::new( + "src/routes/unique-key/+page.graphql", + "query UniqueKeyBridge @load @live { todos(limit: 25) { id title owner { id title } } }", + ); let operation = compile_document(&document, &manifest).unwrap(); - let artifact = format!("{}\n", render_operation_artifact_json(&operation, &manifest).unwrap()); - assert_eq!(artifact, include_str!("../../tests/fixtures/unique-key-bridge-operation.json")); + let artifact = format!( + "{}\n", + render_operation_artifact_json(&operation, &manifest).unwrap() + ); + assert_eq!( + artifact, + include_str!("../../tests/fixtures/unique-key-bridge-operation.json") + ); } const RUNTIME_BRIDGE_QUERY: &str = r#" diff --git a/distributed_macros/src/read_model/attrs.rs b/distributed_macros/src/read_model/attrs.rs index fc0898a89..86c10bc55 100644 --- a/distributed_macros/src/read_model/attrs.rs +++ b/distributed_macros/src/read_model/attrs.rs @@ -307,7 +307,10 @@ impl FieldAttrs { syn::Error::new_spanned(field, "`references` requires a direct relationship") })?; if matches!(relationship.kind, RelationshipKindAttr::ManyToMany) { - return Err(syn::Error::new_spanned(field, "`references` requires a direct relationship")); + return Err(syn::Error::new_spanned( + field, + "`references` requires a direct relationship", + )); } relationship.references = Some(references); } diff --git a/distributed_macros/src/read_model/tests.rs b/distributed_macros/src/read_model/tests.rs index 94d0c3f9f..48a8ba732 100644 --- a/distributed_macros/src/read_model/tests.rs +++ b/distributed_macros/src/read_model/tests.rs @@ -10,9 +10,13 @@ fn direct_relationship_references_are_order_independent_and_emitted() { ] { let input = syn::parse_str(&format!( "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" - )).unwrap(); + )) + .unwrap(); let expanded = expand_read_model(input).unwrap().to_string(); - assert!(expanded.contains("references : Some (\"namespace,oid\""), "{expanded}"); + assert!( + expanded.contains("references : Some (\"namespace,oid\""), + "{expanded}" + ); } for attributes in [ "references = \"id\"", @@ -21,7 +25,8 @@ fn direct_relationship_references_are_order_independent_and_emitted() { ] { let input = syn::parse_str(&format!( "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" - )).unwrap(); + )) + .unwrap(); assert!(expand_read_model(input).is_err(), "accepted {attributes}"); } } diff --git a/src/graphql/engine/composite_relationship_tests.rs b/src/graphql/engine/composite_relationship_tests.rs index bd099f3d4..2302bb442 100644 --- a/src/graphql/engine/composite_relationship_tests.rs +++ b/src/graphql/engine/composite_relationship_tests.rs @@ -268,8 +268,11 @@ async fn belongs_to_with_a_partial_composite_foreign_key_is_rejected() { #[cfg(feature = "sqlite")] #[tokio::test] async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { - let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1) - .connect("sqlite::memory:").await.unwrap(); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); unique_key_join_fixture(pool.into()).await; } @@ -277,20 +280,31 @@ async fn unique_key_join_preserves_namespace_nulls_and_surrogate_identity() { #[tokio::test] #[ignore = "requires dedicated DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL; run explicitly in PostgreSQL CI"] async fn unique_key_join_postgres_authorization_and_manifest() { - let url = std::env::var("DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL").expect("dedicated test database URL"); + let url = std::env::var("DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL") + .expect("dedicated test database URL"); let options: sqlx::postgres::PgConnectOptions = url.parse().unwrap(); - assert!(options.get_database().unwrap_or("").starts_with("distributed_unique_key_test")); - let pool = sqlx::postgres::PgPoolOptions::new().max_connections(1) - .connect_with(options).await.unwrap(); + assert!(options + .get_database() + .unwrap_or("") + .starts_with("distributed_unique_key_test")); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); unique_key_join_fixture(pool.into()).await; } async fn unique_key_sql(pool: &GraphqlPool, statement: &'static str) { match pool { #[cfg(feature = "sqlite")] - GraphqlPool::Sqlite(pool) => { sqlx::query(statement).execute(pool).await.unwrap(); } + GraphqlPool::Sqlite(pool) => { + sqlx::query(statement).execute(pool).await.unwrap(); + } #[cfg(feature = "postgres")] - GraphqlPool::Postgres(pool) => { sqlx::query(statement).execute(pool).await.unwrap(); } + GraphqlPool::Postgres(pool) => { + sqlx::query(statement).execute(pool).await.unwrap(); + } } } @@ -304,27 +318,51 @@ async fn unique_key_join_fixture(pool: GraphqlPool) { unique_key_sql(&pool, statement).await; } let mut target = composite_records(); - for column in &mut target.columns { column.primary_key = false; } - target.columns.push(TableColumn { primary_key: true, ..TableColumn::new("id", "id", ColumnType::Text) }); + for column in &mut target.columns { + column.primary_key = false; + } + target.columns.push(TableColumn { + primary_key: true, + ..TableColumn::new("id", "id", ColumnType::Text) + }); target.primary_key = PrimaryKey::new(["id"]); - target.indexes.push(crate::table::TableIndex { name: None, columns: vec!["tenant_id".into(), "record_id".into()], unique: true }); + target.indexes.push(crate::table::TableIndex { + name: None, + columns: vec!["tenant_id".into(), "record_id".into()], + unique: true, + }); target.relationships.push(RelationshipDef { references: Some("tenant_id,record_id".into()), - field_name: "refs".into(), kind: RelationshipKind::HasMany, - target_model: "SimpleRecord".into(), foreign_key: Some("tenant_id,record_id".into()), - through: None, target_foreign_key: None, + field_name: "refs".into(), + kind: RelationshipKind::HasMany, + target_model: "SimpleRecord".into(), + foreign_key: Some("tenant_id,record_id".into()), + through: None, + target_foreign_key: None, }); let mut source = simple_records(); - source.columns.push(TableColumn { nullable: true, ..TableColumn::new("record_id", "record_id", ColumnType::Text) }); + source.columns.push(TableColumn { + nullable: true, + ..TableColumn::new("record_id", "record_id", ColumnType::Text) + }); source.relationships.push(RelationshipDef { references: Some("tenant_id,record_id".into()), - field_name: "record".into(), kind: RelationshipKind::BelongsTo, - target_model: "CompositeRecord".into(), foreign_key: Some("tenant_id,record_id".into()), - through: None, target_foreign_key: None, + field_name: "record".into(), + kind: RelationshipKind::BelongsTo, + target_model: "CompositeRecord".into(), + foreign_key: Some("tenant_id,record_id".into()), + through: None, + target_foreign_key: None, }); - let project = ReadModelCatalog::new("unique-key-test").table_schema(target).table_schema(source); - let engine = GraphqlEngine::from_schema_catalog(&project, pool.clone()).unwrap() - .roles(&["admin"]).grant_all("admin").build().unwrap(); + let project = ReadModelCatalog::new("unique-key-test") + .table_schema(target) + .table_schema(source); + let engine = GraphqlEngine::from_schema_catalog(&project, pool.clone()) + .unwrap() + .roles(&["admin"]) + .grant_all("admin") + .build() + .unwrap(); let mut session = Session::new(); session.set(crate::microsvc::ROLE_KEY, "admin"); let response = engine.execute(&session, Request::new( @@ -332,56 +370,109 @@ async fn unique_key_join_fixture(pool: GraphqlPool) { )).await; assert!(response.errors.is_empty(), "{:?}", response.errors); let data = response.data.into_json().unwrap(); - assert_eq!(data["simple_records"], serde_json::json!([ - {"simple_id":"1","record":{"id":"opaque-a","value":"first"}}, - {"simple_id":"2","record":{"id":"opaque-b","value":"second"}}, - {"simple_id":"3","record":null}, - {"simple_id":"4","record":null}, - ])); - let reverse = engine.execute(&session, Request::new( - "{ composite_records(order_by: [{id: asc}]) { id refs { simple_id } } }" - )).await; + assert_eq!( + data["simple_records"], + serde_json::json!([ + {"simple_id":"1","record":{"id":"opaque-a","value":"first"}}, + {"simple_id":"2","record":{"id":"opaque-b","value":"second"}}, + {"simple_id":"3","record":null}, + {"simple_id":"4","record":null}, + ]) + ); + let reverse = engine + .execute( + &session, + Request::new("{ composite_records(order_by: [{id: asc}]) { id refs { simple_id } } }"), + ) + .await; assert!(reverse.errors.is_empty(), "{:?}", reverse.errors); - assert_eq!(reverse.data.into_json().unwrap()["composite_records"], serde_json::json!([ - {"id":"opaque-a","refs":[{"simple_id":"1"}]}, - {"id":"opaque-b","refs":[{"simple_id":"2"}]}, - ])); + assert_eq!( + reverse.data.into_json().unwrap()["composite_records"], + serde_json::json!([ + {"id":"opaque-a","refs":[{"simple_id":"1"}]}, + {"id":"opaque-b","refs":[{"simple_id":"2"}]}, + ]) + ); // Parent visibility must not confer visibility on the referenced object. - let mut builder = GraphqlEngine::from_schema_catalog(&project, pool.clone()).unwrap() - .roles(&["reader"]).grant_all("reader"); - builder.permissions.get_mut(&("CompositeRecord".into(), "reader".into())).unwrap() - .permission.row_filter = Some(crate::graphql::col("value").eq("first")); + let mut builder = GraphqlEngine::from_schema_catalog(&project, pool.clone()) + .unwrap() + .roles(&["reader"]) + .grant_all("reader"); + builder + .permissions + .get_mut(&("CompositeRecord".into(), "reader".into())) + .unwrap() + .permission + .row_filter = Some(crate::graphql::col("value").eq("first")); let restricted = builder.build().unwrap(); let manifest = restricted.client_manifest_for_role("reader").unwrap(); - let object_model = manifest.models.iter().find(|model| model.source_table == "composite_records").unwrap(); + let object_model = manifest + .models + .iter() + .find(|model| model.source_table == "composite_records") + .unwrap(); let normalization = serde_json::to_value(&object_model.normalization).unwrap(); assert_eq!(normalization["kind"], "normalized"); assert_eq!(normalization["fields"].as_array().unwrap().len(), 1); assert_eq!(normalization["fields"][0]["name"], "id"); - let ref_model = manifest.models.iter().find(|model| model.source_table == "simple_records").unwrap(); - let mapping = &ref_model.relationships.iter().find(|relation| relation.name == "record").unwrap().key_mapping; - assert_eq!(serde_json::to_value(mapping).unwrap(), serde_json::json!({ - "kind":"direct", "local":["tenant_id","record_id"], "remote":["tenant_id","record_id"] - })); + let ref_model = manifest + .models + .iter() + .find(|model| model.source_table == "simple_records") + .unwrap(); + let mapping = &ref_model + .relationships + .iter() + .find(|relation| relation.name == "record") + .unwrap() + .key_mapping; + assert_eq!( + serde_json::to_value(mapping).unwrap(), + serde_json::json!({ + "kind":"direct", "local":["tenant_id","record_id"], "remote":["tenant_id","record_id"] + }) + ); session.set(crate::microsvc::ROLE_KEY, "reader"); let query = "{ simple_records(order_by: [{simple_id: asc}]) { simple_id record { id } } }"; let response = restricted.execute(&session, Request::new(query)).await; assert!(response.errors.is_empty(), "{:?}", response.errors); - assert_eq!(response.data.into_json().unwrap()["simple_records"], serde_json::json!([ - {"simple_id":"1","record":{"id":"opaque-a"}}, - {"simple_id":"2","record":null}, - {"simple_id":"3","record":null}, - {"simple_id":"4","record":null}, - ])); - let hidden_filter = restricted.execute(&session, Request::new( - "{ simple_records(where: {record: {value: {_eq: \"second\"}}}) { simple_id } }" - )).await; - assert!(hidden_filter.errors.is_empty(), "{:?}", hidden_filter.errors); - assert_eq!(hidden_filter.data.into_json().unwrap()["simple_records"], serde_json::json!([])); - unique_key_sql(&pool, "UPDATE composite_records SET value='revoked' WHERE id='opaque-a'").await; + assert_eq!( + response.data.into_json().unwrap()["simple_records"], + serde_json::json!([ + {"simple_id":"1","record":{"id":"opaque-a"}}, + {"simple_id":"2","record":null}, + {"simple_id":"3","record":null}, + {"simple_id":"4","record":null}, + ]) + ); + let hidden_filter = restricted + .execute( + &session, + Request::new( + "{ simple_records(where: {record: {value: {_eq: \"second\"}}}) { simple_id } }", + ), + ) + .await; + assert!( + hidden_filter.errors.is_empty(), + "{:?}", + hidden_filter.errors + ); + assert_eq!( + hidden_filter.data.into_json().unwrap()["simple_records"], + serde_json::json!([]) + ); + unique_key_sql( + &pool, + "UPDATE composite_records SET value='revoked' WHERE id='opaque-a'", + ) + .await; let revoked = restricted.execute(&session, Request::new(query)).await; assert!(revoked.errors.is_empty(), "{:?}", revoked.errors); - for row in revoked.data.into_json().unwrap()["simple_records"].as_array().unwrap() { + for row in revoked.data.into_json().unwrap()["simple_records"] + .as_array() + .unwrap() + { assert!(row["record"].is_null(), "revoked target leaked: {row}"); } } diff --git a/src/read_model/in_memory.rs b/src/read_model/in_memory.rs index 309abc7fa..ce82fdac4 100644 --- a/src/read_model/in_memory.rs +++ b/src/read_model/in_memory.rs @@ -13,9 +13,7 @@ use super::{ RelationalReadModel, Versioned, }; use crate::repository::{ReadModelWritePlanStore, RelationalReadModelQueryStore}; -use crate::table::{ - has_many_join_columns, key_fingerprint, validate_key, validate_row_values, -}; +use crate::table::{has_many_join_columns, key_fingerprint, validate_key, validate_row_values}; use crate::table::{ ExpectedVersion, PatchMode, RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, RowWriteMode, TableAdapterCapabilities, TableCommitOutcome, TableMutation, TableSchema, @@ -494,7 +492,9 @@ fn load_belongs_to_rows( spec: &IncludeSpec, ) -> Result>, TableStoreError> { let (source_column, target_column) = crate::table::belongs_to_join_columns( - root_schema, &spec.relationship, &spec.target_schema, + root_schema, + &spec.relationship, + &spec.target_schema, )?; let source_value = root_row.get(&source_column).ok_or_else(|| { TableStoreError::Metadata(format!( @@ -502,7 +502,12 @@ fn load_belongs_to_rows( root_schema.model_name, source_column )) })?; - Ok(rows_matching_column(rows, &spec.target_schema.table_name, &target_column, source_value)) + Ok(rows_matching_column( + rows, + &spec.target_schema.table_name, + &target_column, + source_value, + )) } fn rows_matching_column( @@ -511,7 +516,9 @@ fn rows_matching_column( column: &str, value: &RowValue, ) -> Vec> { - if matches!(value, RowValue::Null) { return Vec::new(); } + if matches!(value, RowValue::Null) { + return Vec::new(); + } let prefix = format!("{table_name}:"); let mut matches = rows .iter() @@ -593,35 +600,64 @@ mod tests { #[test] fn belongs_to_unique_key_matches_values_not_primary_key_and_never_nulls() { let mut target = test_row_schema().clone(); - target.columns.push(TableColumn { nullable: true, ..TableColumn::new("slug", "slug", ColumnType::Text) }); - target.indexes.push(crate::TableIndex { name: None, columns: vec!["slug".into()], unique: true }); + target.columns.push(TableColumn { + nullable: true, + ..TableColumn::new("slug", "slug", ColumnType::Text) + }); + target.indexes.push(crate::TableIndex { + name: None, + columns: vec!["slug".into()], + unique: true, + }); let mut source = test_row_schema().clone(); - source.columns.push(TableColumn { nullable: true, ..TableColumn::new("target_slug", "target_slug", ColumnType::Text) }); + source.columns.push(TableColumn { + nullable: true, + ..TableColumn::new("target_slug", "target_slug", ColumnType::Text) + }); let spec = IncludeSpec { - name: "target".into(), target_schema: target.clone(), + name: "target".into(), + target_schema: target.clone(), relationship: RelationshipDef { - field_name: "target".into(), kind: RelationshipKind::BelongsTo, - target_model: target.model_name.clone(), foreign_key: Some("target_slug".into()), - references: Some("slug".into()), through: None, target_foreign_key: None, + field_name: "target".into(), + kind: RelationshipKind::BelongsTo, + target_model: target.model_name.clone(), + foreign_key: Some("target_slug".into()), + references: Some("slug".into()), + through: None, + target_foreign_key: None, }, }; let mut rows = HashMap::new(); - for (id, slug) in [("opaque", RowValue::String("chosen".into())), ("chosen", RowValue::String("other".into())), ("null-target", RowValue::Null)] { + for (id, slug) in [ + ("opaque", RowValue::String("chosen".into())), + ("chosen", RowValue::String("other".into())), + ("null-target", RowValue::Null), + ] { let key = RowKey::new([("id", RowValue::String(id.into()))]); let mut values = RowValues::new(); values.insert("id", RowValue::String(id.into())); values.insert("slug", slug); - rows.insert(relational_storage_key(&target.table_name, &key), StoredRow { values, version: 1 }); + rows.insert( + relational_storage_key(&target.table_name, &key), + StoredRow { values, version: 1 }, + ); } let mut root = RowValues::new(); root.insert("target_slug", RowValue::String("chosen".into())); let found = load_belongs_to_rows(&rows, &source, &root, &spec).unwrap(); assert_eq!(found.len(), 1); - assert_eq!(found[0].data.get("id"), Some(&RowValue::String("opaque".into()))); + assert_eq!( + found[0].data.get("id"), + Some(&RowValue::String("opaque".into())) + ); root.insert("target_slug", RowValue::Null); - assert!(load_belongs_to_rows(&rows, &source, &root, &spec).unwrap().is_empty()); + assert!(load_belongs_to_rows(&rows, &source, &root, &spec) + .unwrap() + .is_empty()); root.insert("target_slug", RowValue::String("missing".into())); - assert!(load_belongs_to_rows(&rows, &source, &root, &spec).unwrap().is_empty()); + assert!(load_belongs_to_rows(&rows, &source, &root, &spec) + .unwrap() + .is_empty()); } #[tokio::test] diff --git a/src/sqlx_repo/read_model/load.rs b/src/sqlx_repo/read_model/load.rs index 31b7884c5..128c014b9 100644 --- a/src/sqlx_repo/read_model/load.rs +++ b/src/sqlx_repo/read_model/load.rs @@ -4,9 +4,9 @@ use std::sync::RwLock; use sqlx::{Database, Encode, Executor, IntoArguments, Type}; use super::{ - column_by_name, push_key_predicates, push_order_by_primary_key, - quote_identifier, relational_row_select, resolve_registered_read_model_schemas, - row_to_versioned_values, IncludeSpec, SqlxReadModelBackend, + column_by_name, push_key_predicates, push_order_by_primary_key, quote_identifier, + relational_row_select, resolve_registered_read_model_schemas, row_to_versioned_values, + IncludeSpec, SqlxReadModelBackend, }; use crate::read_model::{ ReadModelIncludeRows, ReadModelLoadGraph, ReadModelLoadRequest, ReadModelQueryCapabilities, @@ -147,7 +147,9 @@ where for<'r> &'r str: sqlx::ColumnIndex<::Row>, { let (source_column, target_column) = crate::table::belongs_to_join_columns( - root_schema, &spec.relationship, &spec.target_schema, + root_schema, + &spec.relationship, + &spec.target_schema, )?; let source_value = root_row.get(&source_column).ok_or_else(|| { TableStoreError::Metadata(format!( diff --git a/src/sqlx_repo/read_model/mod.rs b/src/sqlx_repo/read_model/mod.rs index 4dabdd97a..08b611035 100644 --- a/src/sqlx_repo/read_model/mod.rs +++ b/src/sqlx_repo/read_model/mod.rs @@ -28,8 +28,8 @@ pub(crate) use schema_registry::{ remember_read_model_schemas, resolve_registered_read_model_schemas, IncludeSpec, }; pub(crate) use validation::{ - column_by_name, initial_row_version, patch_values_preserving_key, - quote_identifier, row_concurrency_conflict, row_values_from_key_and_patch, row_write_values, + column_by_name, initial_row_version, patch_values_preserving_key, quote_identifier, + row_concurrency_conflict, row_values_from_key_and_patch, row_write_values, sql_read_model_capabilities, validate_row_expected_version, validate_sql_write_plan, validate_values_match_key, version_column, }; diff --git a/src/table/mutation.rs b/src/table/mutation.rs index b5ba125f7..87192a922 100644 --- a/src/table/mutation.rs +++ b/src/table/mutation.rs @@ -397,7 +397,9 @@ pub(crate) fn belongs_to_join_columns( target: &TableSchema, ) -> Result<(String, String), TableStoreError> { if !matches!(relationship.kind, RelationshipKind::BelongsTo) { - return Err(TableStoreError::Metadata("expected a belongs_to relationship".into())); + return Err(TableStoreError::Metadata( + "expected a belongs_to relationship".into(), + )); } let pairs = super::registry::resolve_direct_join_keys(source, relationship, target)?; match pairs.as_slice() { diff --git a/src/table/registry.rs b/src/table/registry.rs index a91596435..9c7b48942 100644 --- a/src/table/registry.rs +++ b/src/table/registry.rs @@ -291,15 +291,25 @@ pub fn resolve_direct_join_keys( } }; let explicit = parse_explicit_through_columns( - source, relationship, "references", relationship.references.as_deref(), + source, + relationship, + "references", + relationship.references.as_deref(), )?; let referenced_columns = if let Some(names) = explicit { - let columns = names.iter().map(|name| { - column_name_on(pk_schema, name).map(str::to_owned).ok_or_else(|| TableStoreError::Metadata(format!( + let columns = names + .iter() + .map(|name| { + column_name_on(pk_schema, name) + .map(str::to_owned) + .ok_or_else(|| { + TableStoreError::Metadata(format!( "model `{}` relationship `{}` references unknown column `{name}` on `{}`", source.model_name, relationship.field_name, pk_schema.model_name, - ))) - }).collect::, _>>()?; + )) + }) + }) + .collect::, _>>()?; if columns.iter().collect::>().len() != columns.len() { return Err(TableStoreError::Metadata(format!( "model `{}` relationship `{}` references repeats a physical column", @@ -307,10 +317,16 @@ pub fn resolve_direct_join_keys( ))); } let unique = (columns.len() == pk_schema.primary_key.columns.len() - && pk_schema.primary_key.columns.iter().all(|column| columns.contains(column))) || pk_schema.indexes.iter().any(|index| { - index.unique && index.columns.len() == columns.len() - && index.columns.iter().all(|column| columns.contains(column)) - }); + && pk_schema + .primary_key + .columns + .iter() + .all(|column| columns.contains(column))) + || pk_schema.indexes.iter().any(|index| { + index.unique + && index.columns.len() == columns.len() + && index.columns.iter().all(|column| columns.contains(column)) + }); if !unique { return Err(TableStoreError::Metadata(format!( "model `{}` relationship `{}` references must name a declared unique key on `{}`", @@ -347,7 +363,11 @@ pub fn resolve_direct_join_keys( relationship.field_name, fk_names.len(), pk_schema.model_name, - if relationship.references.is_some() { "referenced key" } else { "primary key" }, + if relationship.references.is_some() { + "referenced key" + } else { + "primary key" + }, pk_columns.len() ))); } @@ -370,10 +390,18 @@ pub fn resolve_direct_join_keys( source.model_name, relationship.field_name, ))); } - let foreign = fk_schema.columns.iter().find(|column| column.column_name == foreign_key_column).unwrap(); - let referenced = pk_schema.columns.iter().find(|column| column.column_name == *pk_column).ok_or_else(|| { - TableStoreError::Metadata(format!("referenced key column `{pk_column}` is missing")) - })?; + let foreign = fk_schema + .columns + .iter() + .find(|column| column.column_name == foreign_key_column) + .unwrap(); + let referenced = pk_schema + .columns + .iter() + .find(|column| column.column_name == *pk_column) + .ok_or_else(|| { + TableStoreError::Metadata(format!("referenced key column `{pk_column}` is missing")) + })?; if foreign.column_type != referenced.column_type || foreign.jsonb != referenced.jsonb { return Err(TableStoreError::Metadata(format!( "model `{}` relationship `{}` joins incompatible column types for `{foreign_key_column}` and `{pk_column}`", @@ -1008,30 +1036,55 @@ mod m2m_join_key_tests { #[test] fn direct_join_can_reference_a_composite_candidate_key() { - let mut target = schema("Object", "objects", vec![pk_column("id"), column("namespace"), column("oid")], &["id"], vec![]); + let mut target = schema( + "Object", + "objects", + vec![pk_column("id"), column("namespace"), column("oid")], + &["id"], + vec![], + ); target.indexes.push(crate::table::TableIndex { - name: None, columns: vec!["namespace".into(), "oid".into()], unique: true, + name: None, + columns: vec!["namespace".into(), "oid".into()], + unique: true, }); let relation = RelationshipDef { references: Some("namespace,oid".into()), - field_name: "object".into(), kind: RelationshipKind::BelongsTo, - target_model: "Object".into(), foreign_key: Some("scope,object_oid".into()), - through: None, target_foreign_key: None, + field_name: "object".into(), + kind: RelationshipKind::BelongsTo, + target_model: "Object".into(), + foreign_key: Some("scope,object_oid".into()), + through: None, + target_foreign_key: None, }; - let source = schema("Ref", "refs", vec![pk_column("ref_id"), column("scope"), column("object_oid")], &["ref_id"], vec![relation.clone()]); - assert_eq!(resolve_direct_join_keys(&source, &relation, &target).unwrap(), vec![ - DirectJoinPair::new("scope", "namespace"), - DirectJoinPair::new("object_oid", "oid"), - ]); + let source = schema( + "Ref", + "refs", + vec![pk_column("ref_id"), column("scope"), column("object_oid")], + &["ref_id"], + vec![relation.clone()], + ); + assert_eq!( + resolve_direct_join_keys(&source, &relation, &target).unwrap(), + vec![ + DirectJoinPair::new("scope", "namespace"), + DirectJoinPair::new("object_oid", "oid"), + ] + ); assert_eq!(target.primary_key.columns, vec!["id"]); let reverse = RelationshipDef { - field_name: "refs".into(), kind: RelationshipKind::HasMany, - target_model: "Ref".into(), ..relation + field_name: "refs".into(), + kind: RelationshipKind::HasMany, + target_model: "Ref".into(), + ..relation }; - assert_eq!(resolve_direct_join_keys(&target, &reverse, &source).unwrap(), vec![ - DirectJoinPair::new("scope", "namespace"), - DirectJoinPair::new("object_oid", "oid"), - ]); + assert_eq!( + resolve_direct_join_keys(&target, &reverse, &source).unwrap(), + vec![ + DirectJoinPair::new("scope", "namespace"), + DirectJoinPair::new("object_oid", "oid"), + ] + ); } #[test] @@ -1040,10 +1093,15 @@ mod m2m_join_key_tests { let target = project_files(); let mut relation = source.relationships[0].clone(); relation.references = Some("kind".into()); - let error = resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string(); + let error = resolve_direct_join_keys(&source, &relation, &target) + .unwrap_err() + .to_string(); assert!(error.contains("declared unique key"), "{error}"); relation.references = Some("missing".into()); - assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("unknown column")); + assert!(resolve_direct_join_keys(&source, &relation, &target) + .unwrap_err() + .to_string() + .contains("unknown column")); } #[test] @@ -1053,10 +1111,16 @@ mod m2m_join_key_tests { let mut relation = source.relationships[0].clone(); source.columns[0].field_name = "workspace_alias".into(); relation.references = Some("workspace_alias,workspace_id".into()); - assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("repeats a physical column")); + assert!(resolve_direct_join_keys(&source, &relation, &target) + .unwrap_err() + .to_string() + .contains("repeats a physical column")); relation.references = Some("workspace_id,path".into()); target.columns[0].column_type = ColumnType::Integer; - assert!(resolve_direct_join_keys(&source, &relation, &target).unwrap_err().to_string().contains("incompatible column types")); + assert!(resolve_direct_join_keys(&source, &relation, &target) + .unwrap_err() + .to_string() + .contains("incompatible column types")); } #[test] @@ -1064,7 +1128,9 @@ mod m2m_join_key_tests { let source = projects(labels_rel(None, None)); let mut relation = source.relationships[0].clone(); relation.references = Some("path".into()); - let error = resolve_m2m_join_keys(&source, &relation, &source, &labels()).unwrap_err().to_string(); + let error = resolve_m2m_join_keys(&source, &relation, &source, &labels()) + .unwrap_err() + .to_string(); assert!(error.contains("requires a direct relationship"), "{error}"); } } From 966f5962ddc6ee2d3423d5117b820b6b8a1157a0 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:07:31 -0500 Subject: [PATCH 041/484] fix: report unsupported composite includes explicitly --- src/table/mutation.rs | 6 ++++++ src/table/registry.rs | 11 ++++++----- tests/read_model_metadata/main.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/table/mutation.rs b/src/table/mutation.rs index 87192a922..ecf989960 100644 --- a/src/table/mutation.rs +++ b/src/table/mutation.rs @@ -401,6 +401,12 @@ pub(crate) fn belongs_to_join_columns( "expected a belongs_to relationship".into(), )); } + if relationship.references.is_none() && target.primary_key.columns.len() != 1 { + return Err(TableStoreError::Metadata(format!( + "belongs_to include `{}` targeting `{}` through `{}` requires a single-column primary key", + relationship.field_name, target.model_name, relationship.foreign_key.as_deref().unwrap_or("unspecified foreign key"), + ))); + } let pairs = super::registry::resolve_direct_join_keys(source, relationship, target)?; match pairs.as_slice() { [pair] => Ok((pair.foreign_key_column.clone(), pair.primary_key_column.clone())), diff --git a/src/table/registry.rs b/src/table/registry.rs index 9c7b48942..afe817011 100644 --- a/src/table/registry.rs +++ b/src/table/registry.rs @@ -249,7 +249,8 @@ pub struct M2mJoinKeys { pub target: Vec, } -/// One foreign-key column paired with one primary-key column for a direct join. +/// One foreign-key column paired with a referenced key column for a direct join. +/// The referenced key defaults to the primary key, or is selected by `references`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DirectJoinPair { pub foreign_key_column: String, @@ -270,11 +271,11 @@ impl DirectJoinPair { /// Resolve `has_many` / `belongs_to` join equalities. /// -/// `foreign_key` lists the FK-holding table's columns in the other end's PK -/// order, same arity as that PK (comma-separated when more than one). +/// `foreign_key` lists the FK-holding table's columns in the order of `references`, +/// or the other end's primary key when references are omitted. Arity must match. /// -/// - **HasMany**: FK columns live on the target; PK is the source. -/// - **BelongsTo**: FK columns live on the source; PK is the target. +/// - **HasMany**: FK columns live on the target; referenced key is on the source. +/// - **BelongsTo**: FK columns live on the source; referenced key is on the target. pub fn resolve_direct_join_keys( source: &TableSchema, relationship: &RelationshipDef, diff --git a/tests/read_model_metadata/main.rs b/tests/read_model_metadata/main.rs index 460c0a159..c9067c408 100644 --- a/tests/read_model_metadata/main.rs +++ b/tests/read_model_metadata/main.rs @@ -67,6 +67,37 @@ struct DirectTableView { value: i32, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +struct DirectTableReference { + #[id] + reference_id: String, + target_tenant: String, + target_slug: Option, + #[readmodel( + belongs_to = "DirectTableView", + foreign_key = "target_tenant,target_slug", + references = "tenant_id,slug" + )] + target: Option, +} + +#[test] +fn authored_candidate_key_relationship_preserves_surrogate_identity() { + let source = DirectTableReference::schema(); + let target = DirectTableView::schema(); + let relation = &source.relationships[0]; + assert_eq!(relation.references.as_deref(), Some("tenant_id,slug")); + assert_eq!(target.primary_key.columns, ["direct_id"]); + let pairs = distributed::table::resolve_direct_join_keys(source, relation, target).unwrap(); + assert_eq!( + pairs, + vec![ + distributed::table::DirectJoinPair::new("target_tenant", "tenant_id"), + distributed::table::DirectJoinPair::new("target_slug", "slug"), + ] + ); +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] #[table("binary_assets")] struct BinaryAsset { From fa10e6a986bbce456e82503f84155f2b543f2c2b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:12:18 -0500 Subject: [PATCH 042/484] test: exercise unique-key hydration in Chromium --- js/tests/fixtures/unique-key-artifact.mjs | 36 +++++++++++ js/tests/unique-key-artifact-bridge.test.mjs | 35 +--------- .../e2e/unique-key-runtime.anon.spec.ts | 64 +++++++++++++++++++ 3 files changed, 101 insertions(+), 34 deletions(-) create mode 100644 js/tests/fixtures/unique-key-artifact.mjs create mode 100644 tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts diff --git a/js/tests/fixtures/unique-key-artifact.mjs b/js/tests/fixtures/unique-key-artifact.mjs new file mode 100644 index 000000000..b4fc191d7 --- /dev/null +++ b/js/tests/fixtures/unique-key-artifact.mjs @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +export const artifact = JSON.parse(readFileSync(new URL( + '../../../distributed_cli/tests/fixtures/unique-key-bridge-operation.json', import.meta.url +), 'utf8')); +export const root = artifact.roots[0]; +export const owner = root.selection.members.find(member => member.field === 'owner'); + +export function frame(position, targetId, targetTitle) { + const records = []; + function wire(selection, values, path) { + records.push({ path, model: selection.storage.model, + scopeToken: `record:${values.id}`, incarnation: '1', revision: position, tombstone: false }); + return Object.fromEntries(selection.members.map(member => { + if (member.kind === 'branch') return [member.responseKey, targetId === null ? null : + wire(member.selection, { id: targetId, title: targetTitle, tenantId: 'tenant-a', + __typename: 'todo' }, [...path, member.responseKey])]; + assert.ok(Object.hasOwn(values, member.field), member.field); + return [member.responseKey, values[member.field]]; + })); + } + const row = wire(root.selection, { id: 'source-id', title: 'source', + ownerTitle: targetTitle, tenantId: 'tenant-a', __typename: 'todo' }, ['todos', '0']); + return { data: { todos: [row] }, extensions: { distributed: { + protocolVersion: artifact.protocol.version, schemaHash: artifact.protocol.schemaHash, + authorizationGeneration: 'auth-1', cacheScope: 'unique-key-cache', + operation: position === '1' ? artifact.id : artifact.live.id, + ...(position === '1' ? {} : { live: { supported: true, reset: false, cursors: [ + { projection: 'unique-key-projector', position, token: `resume:${position}` } + ] } }), + snapshot: { scopeToken: 'unique-key-snapshot', recordsComplete: true, indexesComparable: true, + records, indexes: [{ projection: 'unique-key-projector', scopeToken: 'unique-key-index', position, + resume: { projection: 'unique-key-projector', position, token: `resume:${position}` } }], observations: [] } + } } }; +} diff --git a/js/tests/unique-key-artifact-bridge.test.mjs b/js/tests/unique-key-artifact-bridge.test.mjs index c6c108017..a3a9d1051 100644 --- a/js/tests/unique-key-artifact-bridge.test.mjs +++ b/js/tests/unique-key-artifact-bridge.test.mjs @@ -1,42 +1,9 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; import test from 'node:test'; import { createDistributedReplica } from '../dist/replica/index.js'; import { ControlledReplicaTransport } from './fixtures/adapter-conformance.mjs'; -const artifact = JSON.parse(readFileSync(new URL( - '../../distributed_cli/tests/fixtures/unique-key-bridge-operation.json', import.meta.url -), 'utf8')); -const root = artifact.roots[0]; -const owner = root.selection.members.find(member => member.field === 'owner'); - -function frame(position, targetId, targetTitle) { - const records = []; - function wire(selection, values, path) { - records.push({ path, model: selection.storage.model, - scopeToken: `record:${values.id}`, incarnation: '1', revision: position, tombstone: false }); - return Object.fromEntries(selection.members.map(member => { - if (member.kind === 'branch') return [member.responseKey, targetId === null ? null : - wire(member.selection, { id: targetId, title: targetTitle, tenantId: 'tenant-a', - __typename: 'todo' }, [...path, member.responseKey])]; - assert.ok(Object.hasOwn(values, member.field), member.field); - return [member.responseKey, values[member.field]]; - })); - } - const row = wire(root.selection, { id: 'source-id', title: 'source', - ownerTitle: targetTitle, tenantId: 'tenant-a', __typename: 'todo' }, ['todos', '0']); - return { data: { todos: [row] }, extensions: { distributed: { - protocolVersion: artifact.protocol.version, schemaHash: artifact.protocol.schemaHash, - authorizationGeneration: 'auth-1', cacheScope: 'unique-key-cache', - operation: position === '1' ? artifact.id : artifact.live.id, - ...(position === '1' ? {} : { live: { supported: true, reset: false, cursors: [ - { projection: 'unique-key-projector', position, token: `resume:${position}` } - ] } }), - snapshot: { scopeToken: 'unique-key-snapshot', recordsComplete: true, indexesComparable: true, - records, indexes: [{ projection: 'unique-key-projector', scopeToken: 'unique-key-index', position, - resume: { projection: 'unique-key-projector', position, token: `resume:${position}` } }], observations: [] } - } } }; -} +import { artifact, owner, frame } from './fixtures/unique-key-artifact.mjs'; test('Rust-generated candidate-key relationship survives hydration and live reference changes', async () => { assert.deepEqual(owner.relationship.keyMapping, { diff --git a/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts b/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts new file mode 100644 index 000000000..7f1bc4715 --- /dev/null +++ b/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts @@ -0,0 +1,64 @@ +import { test, expect } from '@playwright/test'; +import { build } from '../../../js/node_modules/esbuild/lib/main.js'; +import { createDistributedReplica } from '../../../js/dist/replica/index.js'; +import { artifact, frame } from '../../../js/tests/fixtures/unique-key-artifact.mjs'; +import { fileURLToPath } from 'node:url'; + +// Browser runtime contract proof. The transport is controlled; SQL joins and +// application SSR are covered separately, not simulated by this test. +test('candidate-key artifact hydrates and changes relationships in Chromium', async ({ page }) => { + const server = createDistributedReplica(); + server.writeResult(artifact, {}, frame('1', 'target-one', 'first'), 'network'); + const initial = server.read(artifact, {}); + const seed = server.dehydrate(); + const runtimePath = fileURLToPath(new URL('../../../js/dist/replica/index.js', import.meta.url)); + const bundle = await build({ + stdin: { contents: ` + import { createDistributedReplica } from ${JSON.stringify(runtimePath)}; + globalThis.startUniqueKeyProof = (artifact, seed) => { + let observer; + const state = { fetches: 0, subscriptions: 0, closed: false }; + const replica = createDistributedReplica({ transport: { + fetch() { state.fetches++; throw new Error('unexpected hydration fetch'); }, + subscribe(request, next) { + state.subscriptions++; observer = next; + return () => { state.closed = true; }; + } + } }); + if (!replica.hydrate(seed, seed.scope)) throw new Error('hydration rejected'); + const watch = replica.watch(artifact, {}, { live: true }); + const unsubscribe = watch.subscribe(snapshot => { + document.querySelector('output').textContent = JSON.stringify(snapshot.data); + }); + return { state, update(frame) { observer.next(frame); }, + close() { unsubscribe(); watch.destroy(); } }; + }; + `, resolveDir: process.cwd(), loader: 'js' }, + bundle: true, write: false, platform: 'browser', format: 'iife' + }); + await page.setContent(''); + await page.getByLabel('Query result').evaluate((element, data) => { + element.textContent = JSON.stringify(data); + }, initial.data); + await expect(page.getByLabel('Query result')).toContainText('target-one'); + await page.addScriptTag({ content: bundle.outputFiles[0].text }); + await page.evaluate(({ artifact, seed }) => { + (globalThis as any).proof = (globalThis as any).startUniqueKeyProof(artifact, seed); + }, { artifact, seed }); + await expect(page.getByLabel('Query result')).toHaveText(JSON.stringify(initial.data)); + expect(await page.evaluate(() => (globalThis as any).proof.state)).toEqual({ + fetches: 0, subscriptions: 1, closed: false + }); + await page.evaluate(value => (globalThis as any).proof.update(value), frame('2', 'target-two', 'second')); + await expect(page.getByLabel('Query result')).toHaveText(JSON.stringify({ todos: [ + { id: 'source-id', title: 'source', owner: { id: 'target-two', title: 'second' } } + ] })); + await page.evaluate(value => (globalThis as any).proof.update(value), frame('3', null, null)); + await expect(page.getByLabel('Query result')).toHaveText(JSON.stringify({ todos: [ + { id: 'source-id', title: 'source', owner: null } + ] })); + await page.evaluate(() => (globalThis as any).proof.close()); + expect(await page.evaluate(() => (globalThis as any).proof.state)).toEqual({ + fetches: 0, subscriptions: 1, closed: true + }); +}); From 4d7cc5352dd6c35cac7d602d366f45e011b283db Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:30:50 -0500 Subject: [PATCH 043/484] fix: resolve candidate keys in projection snapshots Use one direct-join mapping for SQL and memory snapshots while retaining primary-key record scopes. Add committed snapshot regressions and exercise SvelteKit loader hydration in Chromium. --- src/in_memory_repo/projection_protocol/mod.rs | 5 +- .../projection_protocol/read_helpers.rs | 59 ++----- .../projection_protocol/tests.rs | 140 +++++++++++++++ .../store/backend_helpers.rs | 40 ++++- src/projection_protocol/store/mod.rs | 2 +- src/sqlx_repo/projection_protocol/mod.rs | 6 +- src/sqlx_repo/projection_protocol/reads.rs | 161 ++++++++++++------ .../e2e/unique-key-runtime.anon.spec.ts | 36 +++- 8 files changed, 327 insertions(+), 122 deletions(-) diff --git a/src/in_memory_repo/projection_protocol/mod.rs b/src/in_memory_repo/projection_protocol/mod.rs index 0242f3462..a1a8c04cd 100644 --- a/src/in_memory_repo/projection_protocol/mod.rs +++ b/src/in_memory_repo/projection_protocol/mod.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use super::InMemoryRepository; use crate::projection_protocol::{ change_kind_for_mutation, checked_next, checked_projection_graph_materialization, - failure_matches_batch, projection_has_many_columns, table_model_name, + failure_matches_batch, projection_relationship_values, table_model_name, validate_projection_graph_snapshot_request, ProjectionCausationEvidenceBatch, ProjectionCausationEvidenceRequest, ProjectionChange, ProjectionChangeCursor, ProjectionChangeKind, ProjectionChangeRead, ProjectionChangeRetention, ProjectionCheckpoint, @@ -36,8 +36,7 @@ use crate::read_model::in_memory::{ }; use crate::repository::RepositoryError; use crate::table::{ - column_name_for, key_from_row, RelationshipKind, RowKey, RowValues, TableMutation, TableSchema, - TableStoreError, TableWritePlan, + key_from_row, RowKey, RowValues, TableMutation, TableSchema, TableStoreError, TableWritePlan, }; mod direct_projection; diff --git a/src/in_memory_repo/projection_protocol/read_helpers.rs b/src/in_memory_repo/projection_protocol/read_helpers.rs index e95f184e6..c1fb0339d 100644 --- a/src/in_memory_repo/projection_protocol/read_helpers.rs +++ b/src/in_memory_repo/projection_protocol/read_helpers.rs @@ -122,60 +122,23 @@ fn relationship_keys_from_state( target_schema: &TableSchema, max_unique: usize, ) -> Result, ProjectionProtocolError> { - let foreign_key = relationship.foreign_key.as_deref().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` has no foreign key", - relationship.field_name - )) - })?; - let (target_column, value) = match relationship.kind { - RelationshipKind::HasMany => { - let (target_column, root_column) = - projection_has_many_columns(root_schema, relationship, target_schema)?; - let value = root_row.get(&root_column).cloned().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph root `{}` is missing relationship key `{root_column}`", - root_schema.model_name - )) - })?; - (target_column, value) - } - RelationshipKind::BelongsTo => { - let source_column = column_name_for(root_schema, foreign_key).ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` foreign key `{foreign_key}` is not a source column", - relationship.field_name - )) - })?; - let [target_column] = target_schema.primary_key.columns.as_slice() else { - return Err(ProjectionProtocolError::InvalidBatch(format!( - "projection graph belongs-to target `{}` must have one primary-key column", - target_schema.model_name - ))); - }; - let value = root_row.get(&source_column).cloned().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph root `{}` is missing relationship key `{source_column}`", - root_schema.model_name - )) - })?; - (target_column.clone(), value) - } - RelationshipKind::ManyToMany => { - return Err(ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` is many-to-many; project an explicit join read model instead", - relationship.field_name - ))); - } - }; - if value == crate::table::RowValue::Null { + let values = + projection_relationship_values(root_schema, root_row, relationship, target_schema)?; + if values + .iter() + .any(|(_, value)| *value == crate::table::RowValue::Null) + { return Ok(Vec::new()); } let prefix = format!("{}:", target_schema.table_name); let mut keys = Vec::new(); for (storage_key, stored) in rows { - if storage_key.starts_with(&prefix) && stored.values.get(&target_column) == Some(&value) { + if storage_key.starts_with(&prefix) + && values + .iter() + .all(|(column, value)| stored.values.get(column) == Some(value)) + { if keys.len() == max_unique { return Err(graph_budget_error_from_parts( root_schema, diff --git a/src/in_memory_repo/projection_protocol/tests.rs b/src/in_memory_repo/projection_protocol/tests.rs index cbd3a4e04..e2f28c16b 100644 --- a/src/in_memory_repo/projection_protocol/tests.rs +++ b/src/in_memory_repo/projection_protocol/tests.rs @@ -257,6 +257,146 @@ fn graph_snapshot_request(max_unique: usize) -> ProjectionGraphSnapshotRequest { .unwrap() } +#[tokio::test] +async fn graph_snapshots_follow_composite_candidate_keys_and_keep_pk_scopes() { + let mut parent = graph_parent_schema().clone(); + parent.relationships.truncate(1); + parent.relationships[0].foreign_key = Some("tenant,key".into()); + parent.relationships[0].references = Some("tenant,key".into()); + let mut child = graph_child_schema().clone(); + child.relationships.push(RelationshipDef { + field_name: "parent".into(), + kind: RelationshipKind::BelongsTo, + target_model: parent.model_name.clone(), + foreign_key: Some("tenant,key".into()), + references: Some("tenant,key".into()), + through: None, + target_foreign_key: None, + }); + for schema in [&mut parent, &mut child] { + schema + .columns + .push(TableColumn::new("tenant", "tenant", ColumnType::Text)); + schema.columns.push(TableColumn { + nullable: true, + ..TableColumn::new("key", "key", ColumnType::Text) + }); + } + parent.indexes.push(crate::table::TableIndex { + name: None, + columns: vec!["tenant".into(), "key".into()], + unique: true, + }); + let parent: &'static TableSchema = Box::leak(Box::new(parent)); + let child: &'static TableSchema = Box::leak(Box::new(child)); + let codec = ProjectionScopeCodec::with_models( + topology(), + [ + (parent.model_name.as_str(), parent), + (child.model_name.as_str(), child), + ], + ) + .unwrap(); + let key = |id: &str| RowKey::new([("id", RowValue::String(id.into()))]); + let mutation = + |schema: &'static TableSchema, id: &str, tenant: &str, candidate: Option<&str>| { + let row_key = key(id); + let mut values = RowValues::new(); + values.insert("id", RowValue::String(id.into())); + values.insert("parent_id", RowValue::String("unused".into())); + values.insert("tenant", RowValue::String(tenant.into())); + values.insert( + "key", + candidate + .map(|v| RowValue::String(v.into())) + .unwrap_or(RowValue::Null), + ); + ProjectionRecordMutation::new( + codec + .encode_row_scope_in_partition(&schema.model_name, partition(), &row_key) + .unwrap(), + TableMutation::UpsertRow(TableRowMutation { + schema, + key: row_key, + values, + expected_version: ExpectedVersion::Any, + mode: RowWriteMode::Upsert, + }), + ProjectionRecordExpectation::Missing, + ProjectionMutationKind::Upsert, + ) + .unwrap() + }; + let repository = InMemoryRepository::new(); + repository + .register_projection_models(&topology(), &graph_ownership()) + .await + .unwrap(); + repository + .commit_projection(ProjectionCommitBatch { + input: input( + 1, + b"candidate-graph", + "candidate-message", + "candidate-cause", + ProjectionGeneration::initial(), + ), + change_epoch: change_epoch(), + ownership: graph_ownership(), + observations: vec![], + mutations: vec![ + mutation(parent, "opaque-a", "a", Some("same")), + mutation(parent, "opaque-b", "b", Some("same")), + mutation(parent, "null-target", "a", None), + mutation(child, "source", "a", Some("same")), + mutation(child, "null-source", "a", None), + ], + }) + .await + .unwrap(); + for (schema, id, field, target, expected) in [ + (child, "source", "parent", parent, Some("opaque-a")), + (parent, "opaque-a", "children", child, Some("source")), + (parent, "opaque-b", "children", child, None), + (child, "null-source", "parent", parent, None), + (parent, "null-target", "children", child, None), + ] { + let root = ProjectionQuerySnapshotRequest::new( + &codec, + Some(&serde_json::json!("tenant-a")), + &schema.model_name, + key(id), + vec![], + ) + .unwrap(); + let request = ProjectionGraphSnapshotRequest::new( + root, + [(field.into(), Arc::new(target.clone()))], + 2, + ) + .unwrap(); + let snapshot = repository + .projection_graph_snapshot(&request) + .await + .unwrap(); + let rows = &snapshot.includes[field].rows; + assert_eq!(rows.len(), usize::from(expected.is_some()), "{id}/{field}"); + if let Some(expected) = expected { + assert_eq!( + rows[0].row.as_ref().unwrap().get("id"), + Some(&RowValue::String(expected.into())) + ); + assert_eq!( + rows[0].scope, + codec + .encode_row_scope_in_partition(&target.model_name, partition(), &key(expected)) + .unwrap() + ); + assert!(rows[0].record.is_some()); + } + } +} + fn fanout_schemas() -> &'static [TableSchema] { static SCHEMAS: LazyLock> = LazyLock::new(|| { [ diff --git a/src/projection_protocol/store/backend_helpers.rs b/src/projection_protocol/store/backend_helpers.rs index 47feb32d4..6b6f62a2a 100644 --- a/src/projection_protocol/store/backend_helpers.rs +++ b/src/projection_protocol/store/backend_helpers.rs @@ -5,7 +5,8 @@ use super::{ }; use crate::projection_protocol::MAX_PROJECTION_POSITION; use crate::table::{ - has_many_join_columns, RelationshipDef, TableMutation, TableSchema, TableStoreError, + resolve_direct_join_keys, RelationshipDef, RelationshipKind, RowValue, RowValues, + TableMutation, TableSchema, TableStoreError, }; pub(crate) fn checked_next( @@ -101,15 +102,40 @@ pub(crate) fn validate_projection_graph_snapshot_request( Ok(()) } -pub(crate) fn projection_has_many_columns( +pub(crate) fn projection_relationship_values( root_schema: &TableSchema, + root_row: &RowValues, relationship: &RelationshipDef, target_schema: &TableSchema, -) -> Result<(String, String), ProjectionProtocolError> { - has_many_join_columns(root_schema, relationship, target_schema).map_err(|error| match error { - TableStoreError::Metadata(message) => ProjectionProtocolError::InvalidBatch(message), - other => ProjectionProtocolError::Table(other), - }) +) -> Result, ProjectionProtocolError> { + let pairs = + resolve_direct_join_keys(root_schema, relationship, target_schema).map_err(|error| { + match error { + TableStoreError::Metadata(message) => { + ProjectionProtocolError::InvalidBatch(message) + } + other => ProjectionProtocolError::Table(other), + } + })?; + pairs + .into_iter() + .map(|pair| { + let (source, target) = match relationship.kind { + RelationshipKind::HasMany => (pair.primary_key_column, pair.foreign_key_column), + RelationshipKind::BelongsTo => (pair.foreign_key_column, pair.primary_key_column), + RelationshipKind::ManyToMany => { + unreachable!("direct resolver rejects many-to-many") + } + }; + let value = root_row.get(&source).cloned().ok_or_else(|| { + ProjectionProtocolError::InvalidBatch(format!( + "projection graph root `{}` is missing relationship key `{source}`", + root_schema.model_name + )) + })?; + Ok((target, value)) + }) + .collect() } pub(crate) fn checked_projection_graph_materialization( diff --git a/src/projection_protocol/store/mod.rs b/src/projection_protocol/store/mod.rs index 6c54b57c3..0ab5d9fb3 100644 --- a/src/projection_protocol/store/mod.rs +++ b/src/projection_protocol/store/mod.rs @@ -56,7 +56,7 @@ use identity::{ pub(crate) use backend_helpers::{ change_kind_for_mutation, checked_next, checked_projection_graph_materialization, - failure_matches_batch, projection_has_many_columns, table_model_name, + failure_matches_batch, projection_relationship_values, table_model_name, validate_projection_graph_snapshot_request, }; pub(crate) use commit::{ diff --git a/src/sqlx_repo/projection_protocol/mod.rs b/src/sqlx_repo/projection_protocol/mod.rs index b26cf20d9..d27b7c6bf 100644 --- a/src/sqlx_repo/projection_protocol/mod.rs +++ b/src/sqlx_repo/projection_protocol/mod.rs @@ -20,7 +20,7 @@ use sqlx::{Encode, Executor, IntoArguments, Pool, QueryBuilder, Row, Transaction use crate::projection_protocol::{ change_kind_for_mutation, checked_next, checked_projection_graph_materialization, - projection_has_many_columns, table_model_name, validate_projection_graph_snapshot_request, + projection_relationship_values, table_model_name, validate_projection_graph_snapshot_request, ProjectionCausationEvidenceBatch, ProjectionCausationEvidenceRequest, ProjectionChange, ProjectionChangeCursor, ProjectionChangeKind, ProjectionChangeRead, ProjectionChangeRetention, ProjectionCheckpoint, ProjectionCommitBatch, ProjectionCommitOutcome, ProjectionCommitResult, @@ -48,8 +48,8 @@ use crate::sqlx_repo::read_model::{ }; use crate::sqlx_repo::repo::{repository_storage_error, SqlxRepoBackend, SqlxRepository}; use crate::table::{ - column_name_for, validate_row_values, RelationshipKind, RowKey, RowValue, RowValues, - TableMutation, TableSchema, TableStoreError, TableWritePlan, + validate_row_values, RowKey, RowValues, TableMutation, TableSchema, TableStoreError, + TableWritePlan, }; mod helpers; diff --git a/src/sqlx_repo/projection_protocol/reads.rs b/src/sqlx_repo/projection_protocol/reads.rs index fd163ffbc..8dbdb18d8 100644 --- a/src/sqlx_repo/projection_protocol/reads.rs +++ b/src/sqlx_repo/projection_protocol/reads.rs @@ -1,5 +1,94 @@ use super::*; +#[cfg(all(test, feature = "sqlite"))] +#[tokio::test] +async fn candidate_key_snapshot_lookup_selects_surrogate_keys_in_sql() { + use crate::table::{ + ColumnType, PrimaryKey, RelationshipDef, RelationshipKind, RowValue, TableColumn, + TableIndex, TableKind, + }; + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); + let mut connection = pool.acquire().await.unwrap(); + for statement in [ + "CREATE TABLE snapshot_targets (id TEXT PRIMARY KEY, tenant TEXT NOT NULL, candidate TEXT, UNIQUE(tenant,candidate))", + "INSERT INTO snapshot_targets VALUES ('opaque-a','a','same'),('opaque-b','b','same'),('null-target','a',NULL)", + ] { sqlx::query(statement).execute(&mut *connection).await.unwrap(); } + let target = TableSchema { + model_name: "SnapshotTarget".into(), + table_name: "snapshot_targets".into(), + columns: vec![ + TableColumn { + primary_key: true, + ..TableColumn::new("id", "id", ColumnType::Text) + }, + TableColumn::new("tenant", "tenant", ColumnType::Text), + TableColumn { + nullable: true, + ..TableColumn::new("candidate", "candidate", ColumnType::Text) + }, + ], + primary_key: PrimaryKey::new(["id"]), + version_column: None, + foreign_keys: vec![], + indexes: vec![TableIndex { + name: None, + columns: vec!["tenant".into(), "candidate".into()], + unique: true, + }], + relationships: vec![], + kind: TableKind::ReadModel, + }; + let mut source = target.clone(); + source.model_name = "SnapshotSource".into(); + source.table_name = "snapshot_sources".into(); + let relation = RelationshipDef { + field_name: "target".into(), + kind: RelationshipKind::BelongsTo, + target_model: target.model_name.clone(), + foreign_key: Some("tenant,candidate".into()), + references: Some("tenant,candidate".into()), + through: None, + target_foreign_key: None, + }; + for (tenant, candidate, expected) in [ + ("a", Some("same"), Some("opaque-a")), + ("b", Some("same"), Some("opaque-b")), + ("missing", Some("same"), None), + ("a", None, None), + ] { + let mut values = RowValues::new(); + values.insert("id", RowValue::String("source-id".into())); + values.insert("tenant", RowValue::String(tenant.into())); + values.insert( + "candidate", + candidate + .map(|v| RowValue::String(v.into())) + .unwrap_or(RowValue::Null), + ); + let keys = read_projection_relationship_keys_in_executor::( + &mut connection, + &source, + &values, + &relation, + &target, + 2, + ) + .await + .unwrap(); + assert_eq!( + keys, + expected + .into_iter() + .map(|id| RowKey::new([("id", RowValue::String(id.into()))])) + .collect::>() + ); + } +} + pub(super) fn decode_change_row( row: &DB::Row, topology: &ProjectorTopologyId, @@ -1086,53 +1175,12 @@ where for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, for<'r> &'r str: sqlx::ColumnIndex, { - let foreign_key = relationship.foreign_key.as_deref().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` has no foreign key", - relationship.field_name - )) - })?; - let (target_column, value) = match relationship.kind { - RelationshipKind::HasMany => { - let (target_column, root_column) = - projection_has_many_columns(root_schema, relationship, target_schema)?; - let value = root_row.get(&root_column).cloned().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph root `{}` is missing relationship key `{root_column}`", - root_schema.model_name - )) - })?; - (target_column, value) - } - RelationshipKind::BelongsTo => { - let source_column = column_name_for(root_schema, foreign_key).ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` foreign key `{foreign_key}` is not a source column", - relationship.field_name - )) - })?; - let [target_column] = target_schema.primary_key.columns.as_slice() else { - return Err(ProjectionProtocolError::InvalidBatch(format!( - "projection graph belongs-to target `{}` must have one primary-key column", - target_schema.model_name - ))); - }; - let value = root_row.get(&source_column).cloned().ok_or_else(|| { - ProjectionProtocolError::InvalidBatch(format!( - "projection graph root `{}` is missing relationship key `{source_column}`", - root_schema.model_name - )) - })?; - (target_column.clone(), value) - } - RelationshipKind::ManyToMany => { - return Err(ProjectionProtocolError::InvalidBatch(format!( - "projection graph relationship `{}` is many-to-many; project an explicit join read model instead", - relationship.field_name - ))); - } - }; - if value == RowValue::Null { + let values = + projection_relationship_values(root_schema, root_row, relationship, target_schema)?; + if values + .iter() + .any(|(_, value)| *value == crate::table::RowValue::Null) + { return Ok(Vec::new()); } @@ -1146,13 +1194,18 @@ where builder.push(" FROM "); builder.push(quote_identifier(&target_schema.table_name)); builder.push(" WHERE "); - builder.push(quote_identifier(&target_column)); - builder.push(" = "); - DB::push_row_value_bind( - &mut builder, - value, - column_by_name(target_schema, &target_column)?, - )?; + for (index, (target_column, value)) in values.into_iter().enumerate() { + if index > 0 { + builder.push(" AND "); + } + builder.push(quote_identifier(&target_column)); + builder.push(" = "); + DB::push_row_value_bind( + &mut builder, + value, + column_by_name(target_schema, &target_column)?, + )?; + } push_order_by_primary_key(&mut builder, target_schema); builder.push(" LIMIT "); builder.push(max_unique.saturating_add(1).to_string()); diff --git a/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts b/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts index 7f1bc4715..7c1f9ea78 100644 --- a/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts +++ b/tests/e2e-ui/e2e/unique-key-runtime.anon.spec.ts @@ -1,16 +1,40 @@ import { test, expect } from '@playwright/test'; import { build } from '../../../js/node_modules/esbuild/lib/main.js'; import { createDistributedReplica } from '../../../js/dist/replica/index.js'; +import { + createDistributedSvelteKitServer, + defineDistributedBoundaryBinding, + defineDistributedBoundaryOperation +} from '../../../js/dist/sveltekit/index.js'; import { artifact, frame } from '../../../js/tests/fixtures/unique-key-artifact.mjs'; import { fileURLToPath } from 'node:url'; -// Browser runtime contract proof. The transport is controlled; SQL joins and -// application SSR are covered separately, not simulated by this test. +// SvelteKit loader-to-browser contract proof. GraphQL transport is controlled; +// this does not claim to exercise database-backed live delivery. test('candidate-key artifact hydrates and changes relationships in Chromium', async ({ page }) => { - const server = createDistributedReplica(); - server.writeResult(artifact, {}, frame('1', 'target-one', 'first'), 'network'); - const initial = server.read(artifact, {}); - const seed = server.dehydrate(); + const boundary = defineDistributedBoundaryOperation({ + operation: 'UniqueKeyBridge', route: '/unique-key', kind: 'page', discovery: 'route_document' + }, artifact, defineDistributedBoundaryBinding(artifact, {})); + const server = createDistributedSvelteKitServer({ + boundaries: [boundary], getSession: async () => null, getRole: () => 'user' + }); + let serverFetches = 0; + const loaded = await server.load({ + locals: {}, route: { id: '/unique-key' }, url: new URL('https://example.test/unique-key'), + async fetch(_url, init) { + serverFetches++; + expect(JSON.parse(init.body).query).toBe(artifact.document); + return new Response(JSON.stringify(frame('1', 'target-one', 'first')), { + headers: { 'content-type': 'application/json' } + }); + } + }); + expect(loaded.gqlError).toBeNull(); + expect(serverFetches).toBe(1); + const seed = loaded.distributed.state; + const serverResult = createDistributedReplica(); + expect(serverResult.hydrate(seed, seed.scope)).toBe(true); + const initial = serverResult.read(artifact, {}); const runtimePath = fileURLToPath(new URL('../../../js/dist/replica/index.js', import.meta.url)); const bundle = await build({ stdin: { contents: ` From 73b3886d1a1ea22b0a635e2c05a09ac8f0f63b98 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:34:31 -0500 Subject: [PATCH 044/484] test: verify snapshot candidate keys on PostgreSQL --- .github/workflows/integration-postgres.yaml | 1 + src/sqlx_repo/projection_protocol/reads.rs | 47 +++++++++++++++++---- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/.github/workflows/integration-postgres.yaml b/.github/workflows/integration-postgres.yaml index e6d213f9b..1543702c5 100644 --- a/.github/workflows/integration-postgres.yaml +++ b/.github/workflows/integration-postgres.yaml @@ -59,3 +59,4 @@ jobs: run: | docker exec ${{ job.services.postgres.id }} createdb -U postgres distributed_unique_key_test cargo test --lib --no-default-features --features graphql,postgres graphql::engine::composite_relationship_tests::unique_key_join_postgres_authorization_and_manifest -- --ignored --exact + cargo test --lib --no-default-features --features postgres sqlx_repo::projection_protocol::reads::candidate_key_snapshot_lookup_postgres -- --ignored --exact diff --git a/src/sqlx_repo/projection_protocol/reads.rs b/src/sqlx_repo/projection_protocol/reads.rs index 8dbdb18d8..1dfac6dd0 100644 --- a/src/sqlx_repo/projection_protocol/reads.rs +++ b/src/sqlx_repo/projection_protocol/reads.rs @@ -3,20 +3,51 @@ use super::*; #[cfg(all(test, feature = "sqlite"))] #[tokio::test] async fn candidate_key_snapshot_lookup_selects_surrogate_keys_in_sql() { - use crate::table::{ - ColumnType, PrimaryKey, RelationshipDef, RelationshipKind, RowValue, TableColumn, - TableIndex, TableKind, - }; let pool = sqlx::sqlite::SqlitePoolOptions::new() .max_connections(1) .connect("sqlite::memory:") .await .unwrap(); let mut connection = pool.acquire().await.unwrap(); + candidate_key_snapshot_sql_fixture::(&mut connection).await; +} + +#[cfg(all(test, feature = "postgres"))] +#[tokio::test] +#[ignore = "requires dedicated DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL; explicitly run in CI"] +async fn candidate_key_snapshot_lookup_postgres() { + let url = std::env::var("DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL") + .expect("dedicated test database URL"); + let options: sqlx::postgres::PgConnectOptions = url.parse().unwrap(); + assert!(options + .get_database() + .unwrap_or("") + .starts_with("distributed_unique_key_test")); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + let mut connection = pool.acquire().await.unwrap(); + candidate_key_snapshot_sql_fixture::(&mut connection).await; +} + +#[cfg(test)] +async fn candidate_key_snapshot_sql_fixture(connection: &mut DB::Connection) +where + DB: SqlxRepoBackend, + DB::Arguments: IntoArguments, + for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, + for<'r> &'r str: sqlx::ColumnIndex, +{ + use crate::table::{ + ColumnType, PrimaryKey, RelationshipDef, RelationshipKind, RowValue, TableColumn, + TableIndex, TableKind, + }; for statement in [ - "CREATE TABLE snapshot_targets (id TEXT PRIMARY KEY, tenant TEXT NOT NULL, candidate TEXT, UNIQUE(tenant,candidate))", + "CREATE TEMP TABLE snapshot_targets (id TEXT PRIMARY KEY, tenant TEXT NOT NULL, candidate TEXT, UNIQUE(tenant,candidate))", "INSERT INTO snapshot_targets VALUES ('opaque-a','a','same'),('opaque-b','b','same'),('null-target','a',NULL)", - ] { sqlx::query(statement).execute(&mut *connection).await.unwrap(); } + ] { sqlx::query::(statement).execute(&mut *connection).await.unwrap(); } let target = TableSchema { model_name: "SnapshotTarget".into(), table_name: "snapshot_targets".into(), @@ -69,8 +100,8 @@ async fn candidate_key_snapshot_lookup_selects_surrogate_keys_in_sql() { .map(|v| RowValue::String(v.into())) .unwrap_or(RowValue::Null), ); - let keys = read_projection_relationship_keys_in_executor::( - &mut connection, + let keys = read_projection_relationship_keys_in_executor::( + &mut *connection, &source, &values, &relation, From 25a028dc721411401f785385a955f44aad18f869 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:39:33 -0500 Subject: [PATCH 045/484] test: verify live candidate-key authorization changes --- .../engine/composite_relationship_tests.rs | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/graphql/engine/composite_relationship_tests.rs b/src/graphql/engine/composite_relationship_tests.rs index 2302bb442..fedd878d7 100644 --- a/src/graphql/engine/composite_relationship_tests.rs +++ b/src/graphql/engine/composite_relationship_tests.rs @@ -309,6 +309,7 @@ async fn unique_key_sql(pool: &GraphqlPool, statement: &'static str) { } async fn unique_key_join_fixture(pool: GraphqlPool) { + use futures_util::StreamExt; for statement in [ "CREATE TEMP TABLE composite_records (id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT NOT NULL, value TEXT NOT NULL, UNIQUE(tenant_id, record_id))", "CREATE TEMP TABLE simple_records (simple_id TEXT PRIMARY KEY NOT NULL, tenant_id TEXT NOT NULL, record_id TEXT)", @@ -394,10 +395,12 @@ async fn unique_key_join_fixture(pool: GraphqlPool) { ]) ); // Parent visibility must not confer visibility on the referenced object. + let (changes, change_rx) = tokio::sync::broadcast::channel(8); let mut builder = GraphqlEngine::from_schema_catalog(&project, pool.clone()) .unwrap() .roles(&["reader"]) - .grant_all("reader"); + .grant_all("reader") + .change_stream(change_rx); builder .permissions .get_mut(&("CompositeRecord".into(), "reader".into())) @@ -434,6 +437,18 @@ async fn unique_key_join_fixture(pool: GraphqlPool) { ); session.set(crate::microsvc::ROLE_KEY, "reader"); let query = "{ simple_records(order_by: [{simple_id: asc}]) { simple_id record { id } } }"; + let mut live = Box::pin( + restricted.execute_stream(&session, Request::new(format!("subscription {query}"))), + ); + let initial_live = tokio::time::timeout(std::time::Duration::from_secs(3), live.next()) + .await + .expect("initial candidate-key subscription timed out") + .expect("subscription ended"); + assert!(initial_live.errors.is_empty(), "{:?}", initial_live.errors); + assert_eq!( + initial_live.data.into_json().unwrap()["simple_records"][0]["record"]["id"], + "opaque-a" + ); let response = restricted.execute(&session, Request::new(query)).await; assert!(response.errors.is_empty(), "{:?}", response.errors); assert_eq!( @@ -467,6 +482,25 @@ async fn unique_key_join_fixture(pool: GraphqlPool) { "UPDATE composite_records SET value='revoked' WHERE id='opaque-a'", ) .await; + changes + .send(crate::read_model::ReadModelChange::new([ + "composite_records", + ])) + .unwrap(); + let revoked_live = tokio::time::timeout(std::time::Duration::from_secs(3), live.next()) + .await + .expect("target-only change did not refresh candidate-key subscription") + .expect("subscription ended"); + assert!(revoked_live.errors.is_empty(), "{:?}", revoked_live.errors); + for row in revoked_live.data.into_json().unwrap()["simple_records"] + .as_array() + .unwrap() + { + assert!( + row["record"].is_null(), + "live result leaked revoked target: {row}" + ); + } let revoked = restricted.execute(&session, Request::new(query)).await; assert!(revoked.errors.is_empty(), "{:?}", revoked.errors); for row in revoked.data.into_json().unwrap()["simple_records"] From cdbe29ed324282226da87da5c879c45eae04820e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 18:47:24 -0500 Subject: [PATCH 046/484] test: connect candidate-key projections to live queries --- tests/graphql_unique_key_live/main.rs | 178 ++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 tests/graphql_unique_key_live/main.rs diff --git a/tests/graphql_unique_key_live/main.rs b/tests/graphql_unique_key_live/main.rs new file mode 100644 index 000000000..463bae2d9 --- /dev/null +++ b/tests/graphql_unique_key_live/main.rs @@ -0,0 +1,178 @@ +#![cfg(all(feature = "graphql", feature = "sqlite"))] + +use distributed::bus::{Bus, InMemoryBus, Message, MessageKind, RunOptions}; +use distributed::graphql::{read, GraphqlEngine, ModelPermissions, SurfaceProjector}; +use distributed::microsvc::{CausalProjectorContext, HandlerError, Routes, Service}; +use distributed::{ReadModel, ReadModelCatalog, SqliteRepository}; +use distributed_cli::{compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector}; +use futures_util::StreamExt; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[readmodel(table = "revision_views", primary_key = ["id"])] +#[unique(columns = ["namespace", "revision"])] +struct RevisionView { + id: String, + namespace: String, + revision: String, + body: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[readmodel(table = "reference_views", primary_key = ["id"])] +struct ReferenceView { + id: String, + namespace: String, + revision: String, + #[readmodel( + belongs_to = "RevisionView", + foreign_key = "namespace,revision", + references = "namespace,revision" + )] + target: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct RevisionPublished { + id: String, + namespace: String, + revision: String, + body: String, +} + +fn projector() -> SurfaceProjector { + SurfaceProjector::new("publish_revision") + .facts(["revision.published"]) + .models(["ReferenceView", "RevisionView"]) + .change_epoch("revision-test-v1") +} + +async fn publish(repository: &SqliteRepository, bus: &InMemoryBus, revision: &str) { + let routes = Routes::new() + .with_read_model_store(repository.clone()) + .causal_projector::(projector()) + .model::() + .model::() + .handle( + |context: CausalProjectorContext, fact: RevisionPublished| async move { + context + .project(&RevisionView { + id: fact.id, + namespace: fact.namespace.clone(), + revision: fact.revision.clone(), + body: fact.body, + }) + .await?; + context + .project(&ReferenceView { + id: "reference-stable".into(), + namespace: fact.namespace, + revision: fact.revision, + target: None, + }) + .await?; + Ok::<(), HandlerError>(()) + }, + ); + bus.publish_message( + Message::new( + "revision.published", + MessageKind::Event, + serde_json::to_vec(&RevisionPublished { + id: format!("opaque-{revision}"), + namespace: "team-a".into(), + revision: revision.into(), + body: format!("Content {revision}"), + }) + .unwrap(), + ) + .with_id(format!("published-{revision}")) + .with_metadata( + distributed::trace_context::CAUSATION_ID, + format!("publish-command-{revision}"), + ), + ) + .await + .unwrap(); + Service::new() + .named("unique-key-live") + .routes(routes) + .with_bus(bus.clone()) + .run(RunOptions::idempotent()) + .await + .unwrap(); +} + +#[tokio::test] +async fn projected_candidate_keys_generate_a_live_client() { + let repository = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let catalog = ReadModelCatalog::new("unique-key-live") + .read_model::() + .read_model::(); + repository + .bootstrap_table_schema_for_dev(&catalog.table_registry().unwrap()) + .await + .unwrap(); + let bus = InMemoryBus::new(); + publish(&repository, &bus, "one").await; + let engine = GraphqlEngine::builder(&repository) + .service_id("unique-key-live") + .protocol_token_key([0x37; 32]) + .roles(&["user"]) + .anonymous_role("user") + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .change_stream(repository.read_model_changes()) + .build() + .unwrap(); + let generated = compile_client(ClientCompileInput::new( + serde_json::to_value(engine.client_manifest_for_role("user").unwrap()).unwrap(), + ClientSurfaceSelector::role("user"), + vec![ClientDocument::new( + "src/routes/references/+page.graphql", + "query References @load @live { reference_views { id target { id body } } }", + )], + )) + .unwrap(); + assert_eq!(generated.operations.len(), 1); + assert!(generated.operations[0].live_operation_hash.is_some()); + let mut session = distributed::microsvc::Session::new(); + session.set(distributed::microsvc::ROLE_KEY, "user"); + let result = engine + .execute( + &session, + async_graphql::Request::new("{ reference_views { id target { id body } } }"), + ) + .await; + assert!(result.errors.is_empty(), "{:?}", result.errors); + assert_eq!( + result.data.into_json().unwrap(), + serde_json::json!({"reference_views": [ + {"id": "reference-stable", "target": {"id": "opaque-one", "body": "Content one"}} + ]}) + ); + let mut live = Box::pin(engine.execute_stream( + &session, + async_graphql::Request::new("subscription { reference_views { id target { id body } } }"), + )); + let first = tokio::time::timeout(std::time::Duration::from_secs(3), live.next()) + .await + .unwrap() + .unwrap(); + assert!(first.errors.is_empty(), "{:?}", first.errors); + publish(&repository, &bus, "two").await; + let next = tokio::time::timeout(std::time::Duration::from_secs(3), live.next()) + .await + .unwrap() + .unwrap(); + assert!(next.errors.is_empty(), "{:?}", next.errors); + assert_eq!( + next.data.into_json().unwrap(), + serde_json::json!({"reference_views": [ + {"id": "reference-stable", "target": {"id": "opaque-two", "body": "Content two"}} + ]}) + ); +} From c84c50ad28889cb6072987c94490c16e917148be Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 19:00:15 -0500 Subject: [PATCH 047/484] test: prove candidate-key SSR and live browser delivery --- .github/workflows/integration-e2e-ui.yaml | 3 + tests/e2e-ui/scripts/unique-key-connected.mjs | 63 +++++++++++++++ tests/graphql_unique_key_live/main.rs | 77 ++++++++++++++++++- 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 tests/e2e-ui/scripts/unique-key-connected.mjs diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index fb7899f19..eadd1526f 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -141,6 +141,9 @@ jobs: npm install npx playwright install chromium --with-deps + - name: Verify candidate-key SSR and live delivery end to end + run: cargo test --manifest-path ../../Cargo.toml --features graphql,sqlite --test graphql_unique_key_live projected_candidate_keys_reach_chromium_over_http_and_websocket -- --ignored --exact --nocapture + - name: Run browser e2e run: | npm run test:browser diff --git a/tests/e2e-ui/scripts/unique-key-connected.mjs b/tests/e2e-ui/scripts/unique-key-connected.mjs new file mode 100644 index 000000000..2d05eae6e --- /dev/null +++ b/tests/e2e-ui/scripts/unique-key-connected.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { build, transform } from '../../../js/node_modules/esbuild/lib/main.js'; +import { chromium, expect } from '../node_modules/@playwright/test/index.mjs'; +import { createDistributedSvelteKitServer, defineDistributedBoundaryBinding, defineDistributedBoundaryOperation } from '../../../js/dist/sveltekit/index.js'; +import { fileURLToPath } from 'node:url'; + +const origin = process.argv[2]; +assert.match(origin, /^http:\/\/127\.0\.0\.1:\d+$/); +const fixture = await (await fetch(`${origin}/fixture`)).json(); +const compiled = await transform(fixture.module, { loader: 'ts', format: 'esm' }); +const artifact = (await import(`data:text/javascript;base64,${Buffer.from(compiled.code).toString('base64')}`))[fixture.exportName]; +const boundary = defineDistributedBoundaryOperation({ operation: 'References', route: '/references', kind: 'page', discovery: 'route_document' }, artifact, defineDistributedBoundaryBinding(artifact, {})); +const server = createDistributedSvelteKitServer({ boundaries: [boundary], getSession: async () => null, getRole: () => 'user' }); +let ssrFetches = 0; +const loaded = await server.load({ locals: {}, route: { id: '/references' }, url: new URL(`${origin}/references`), + fetch(url, init) { ssrFetches++; return fetch(new URL(url, origin), init); } }); +assert.equal(loaded.gqlError, null); +assert.equal(ssrFetches, 1); +const runtime = fileURLToPath(new URL('../../../js/dist/sveltekit/index.js', import.meta.url)); +const bundle = await build({ stdin: { contents: `import { createDistributedSvelteKit, defineDistributedBoundaryOperation, defineDistributedBoundaryBinding } from ${JSON.stringify(runtime)}; +globalThis.mountProof = (artifact, loaded) => { + const boundary = defineDistributedBoundaryOperation({ operation: 'References', route: '/references', kind: 'page', discovery: 'route_document' }, artifact, defineDistributedBoundaryBinding(artifact, {})); + const client = createDistributedSvelteKit({ boundaries: [boundary], hydration: loaded.distributed, + authority: loaded.distributedAuthority, session: { getAuth: () => ({}) } }); + const view = client.operation(artifact).use(); + const unsubscribe = view.subscribe(snapshot => { document.querySelector('output').textContent = JSON.stringify(snapshot.data); }); + globalThis.closeProof = () => { unsubscribe(); client.destroy(); }; +};`, loader: 'js', resolveDir: process.cwd() }, bundle: true, write: false, platform: 'browser', format: 'iife' }); +const browser = await chromium.launch(); +try { + const page = await browser.newPage(); + const browserErrors = []; + page.on('pageerror', error => browserErrors.push(error.message)); + let graphqlFetches = 0; + const sockets = []; + let liveFrames = 0; + let closed = false; + page.on('request', request => { if (request.url() === `${origin}/graphql`) graphqlFetches++; }); + page.on('websocket', socket => { + sockets.push(socket); + socket.on('socketerror', error => browserErrors.push(String(error))); + socket.on('framereceived', event => { if (JSON.parse(String(event.payload)).type === 'next') liveFrames++; }); + socket.on('close', () => { closed = true; }); + }); + await page.goto(`${origin}/references`); + await page.addScriptTag({ content: bundle.outputFiles[0].text }); + await page.evaluate(({ artifact, loaded }) => globalThis.mountProof(artifact, loaded), { artifact, loaded }); + await page.waitForFunction(() => document.querySelector('output').textContent.includes('opaque-one')); + assert.equal(graphqlFetches, 0, 'SSR seed must avoid browser mount fetch'); + await expect.poll(() => liveFrames).toBeGreaterThan(0); + assert.equal(sockets.length, 1, 'real GraphQL WebSocket opened'); + const published = await fetch(`${origin}/publish`, { method: 'POST' }); + assert.equal(published.status, 200); + await page.waitForFunction(() => document.querySelector('output').textContent.includes('opaque-two')); + assert.deepEqual(JSON.parse(await page.locator('output').textContent()), { reference_views: [ + { id: 'reference-stable', target: { id: 'opaque-two', body: 'Content two' } } + ] }); + assert.equal(graphqlFetches, 0, 'live update must arrive via WebSocket'); + await page.evaluate(() => globalThis.closeProof()); + await expect.poll(() => closed).toBe(true); + assert.deepEqual(browserErrors, []); + console.log('Connected SQLite/projector → GraphQL HTTP SSR → Chromium → WebSocket update passed'); +} finally { await browser.close(); } diff --git a/tests/graphql_unique_key_live/main.rs b/tests/graphql_unique_key_live/main.rs index 463bae2d9..683548dd9 100644 --- a/tests/graphql_unique_key_live/main.rs +++ b/tests/graphql_unique_key_live/main.rs @@ -103,8 +103,12 @@ async fn publish(repository: &SqliteRepository, bus: &InMemoryBus, revision: &st .unwrap(); } -#[tokio::test] -async fn projected_candidate_keys_generate_a_live_client() { +async fn fixture() -> ( + SqliteRepository, + InMemoryBus, + GraphqlEngine, + distributed_cli::GeneratedClientProject, +) { let repository = SqliteRepository::connect_and_migrate("sqlite::memory:") .await .unwrap(); @@ -139,6 +143,12 @@ async fn projected_candidate_keys_generate_a_live_client() { .unwrap(); assert_eq!(generated.operations.len(), 1); assert!(generated.operations[0].live_operation_hash.is_some()); + (repository, bus, engine, generated) +} + +#[tokio::test] +async fn projected_candidate_keys_generate_a_live_client() { + let (repository, bus, engine, _) = fixture().await; let mut session = distributed::microsvc::Session::new(); session.set(distributed::microsvc::ROLE_KEY, "user"); let result = engine @@ -176,3 +186,66 @@ async fn projected_candidate_keys_generate_a_live_client() { ]}) ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires built JS and Playwright Chromium; explicitly run by browser CI"] +async fn projected_candidate_keys_reach_chromium_over_http_and_websocket() { + use axum::{ + routing::{get, post}, + Json, + }; + let (repository, bus, engine, generated) = fixture().await; + let operation = &generated.operations[0]; + let module = generated + .files + .iter() + .find(|file| file.path == operation.module_path) + .unwrap() + .contents + .clone(); + let export_name = operation.export_name.clone(); + let app = distributed::microsvc::router(std::sync::Arc::new( + Service::new() + .named("unique-key-live") + .try_with_graphql(engine) + .unwrap(), + )) + .route( + "/references", + get(|| async { axum::response::Html("") }), + ) + .route( + "/fixture", + get(move || { + let module = module.clone(); + let export_name = export_name.clone(); + async move { Json(serde_json::json!({"module": module, "exportName": export_name})) } + }), + ) + .route( + "/publish", + post(move || { + let repository = repository.clone(); + let bus = bus.clone(); + async move { + publish(&repository, &bus, "two").await; + Json(serde_json::json!({"ok": true})) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let status = tokio::task::spawn_blocking(move || { + std::process::Command::new("node") + .arg("tests/e2e-ui/scripts/unique-key-connected.mjs") + .arg(origin) + .status() + }) + .await + .unwrap(); + server.abort(); + assert!(status.unwrap().success(), "connected browser proof failed"); +} From e41acb3926472ea6857e28ba418425afc19d5291 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 19:28:17 -0500 Subject: [PATCH 048/484] ci: diagnose dev readiness failures without exposing arguments Implements [[tasks/distributed-unique-key-relations]] --- .github/workflows/integration-e2e-ui.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index eadd1526f..886b66f89 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -122,6 +122,7 @@ jobs: if ! kill -0 "$(cat .distributed-dev.pid)" 2>/dev/null; then echo "distributed dev exited before readiness" tail -200 .distributed-dev.log + ps -eo pid,ppid,etime,stat,comm exit 1 fi sleep 0.5 @@ -129,6 +130,9 @@ jobs: if [ "$ok" != "1" ]; then echo "distributed dev failed to become ready" tail -200 .distributed-dev.log + # Executable names identify quiet build children without exposing + # credentials from process arguments or environment variables. + ps -eo pid,ppid,etime,stat,comm exit 1 fi From 4cad0539daff3b82b5306cf6ca5d72da44017f2f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 20:04:42 -0500 Subject: [PATCH 049/484] feat: add portable gateway routing and adapter contracts --- .github/workflows/integration-gateway.yaml | 40 + Cargo.toml | 3 + src/gateway/config.rs | 326 ++++++++ src/gateway/extension.rs | 78 ++ src/gateway/mod.rs | 29 + src/gateway/route.rs | 220 +++++ src/lib.rs | 2 + tests/gateway-portable/.gitignore | 2 + tests/gateway-portable/Cargo.lock | 798 +++++++++++++++++++ tests/gateway-portable/Cargo.toml | 25 + tests/gateway-portable/README.md | 23 + tests/gateway-portable/check_dependencies.py | 17 + tests/gateway-portable/src/lib.rs | 19 + tests/gateway_extensions.rs | 164 ++++ tests/gateway_routing.rs | 317 ++++++++ tests/gateway_support/mod.rs | 138 ++++ 16 files changed, 2201 insertions(+) create mode 100644 .github/workflows/integration-gateway.yaml create mode 100644 src/gateway/config.rs create mode 100644 src/gateway/extension.rs create mode 100644 src/gateway/mod.rs create mode 100644 src/gateway/route.rs create mode 100644 tests/gateway-portable/.gitignore create mode 100644 tests/gateway-portable/Cargo.lock create mode 100644 tests/gateway-portable/Cargo.toml create mode 100644 tests/gateway-portable/README.md create mode 100644 tests/gateway-portable/check_dependencies.py create mode 100644 tests/gateway-portable/src/lib.rs create mode 100644 tests/gateway_extensions.rs create mode 100644 tests/gateway_routing.rs create mode 100644 tests/gateway_support/mod.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml new file mode 100644 index 000000000..3ba4b228b --- /dev/null +++ b/.github/workflows/integration-gateway.yaml @@ -0,0 +1,40 @@ +name: Portable gateway contracts + +on: + pull_request: + paths: + - 'src/**' + - 'distributed_macros/**' + - 'Cargo.toml' + - 'build.rs' + - 'tests/gateway*' + - 'tests/gateway*/**' + - '.github/workflows/integration-gateway.yaml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + contracts: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: rustfmt, clippy + - name: Format contract and fixture sources + run: rustfmt --edition 2021 --check src/gateway/mod.rs tests/gateway_routing.rs tests/gateway_extensions.rs tests/gateway-portable/src/lib.rs + - name: Test portable routing and adapter contracts + run: cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked + - name: Check fixture lints + run: cargo clippy --manifest-path tests/gateway-portable/Cargo.toml --locked --all-targets -- -D warnings + - name: Compile the UI/auth consumer to Wasm + run: cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown + - name: Verify native and Wasm dependency isolation + run: python3 tests/gateway-portable/check_dependencies.py diff --git a/Cargo.toml b/Cargo.toml index d187188c7..6981211d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,8 @@ required-features = ["graphql", "sqlite"] [features] default = [] application-runtime = [] +# Portable gateway declarations and dispatch only; runtime adapters are separate. +gateway = ["dep:url"] runtime = ["application-runtime"] emitter = ["dep:event-emitter-rs"] metrics = [] @@ -79,6 +81,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "net", "macros", "time", tracing = { version = "0.1", optional = true } tracing-opentelemetry = { version = "0.33", default-features = false, optional = true } uuid = { version = "1", features = ["v7"] } +url = { version = "2", optional = true } worker = { version = "0.8", features = ["queue"], optional = true } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] diff --git a/src/gateway/config.rs b/src/gateway/config.rs new file mode 100644 index 000000000..e5658e309 --- /dev/null +++ b/src/gateway/config.rs @@ -0,0 +1,326 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +use serde::{Deserialize, Serialize}; + +use super::route::{normalize_path, Route, RoutePath, SelectedRoute}; + +/// Maximum declared routes in one gateway configuration. +pub const MAX_ROUTES: usize = 256; +/// Maximum runtime bindings in one gateway configuration. +pub const MAX_BINDINGS: usize = 256; +/// Maximum bytes in route, binding, policy and schema-extension identifiers. +pub const MAX_ID_BYTES: usize = 256; + +/// Invalid gateway configuration or request metadata. Errors never echo URLs, +/// headers or credentials supplied by a caller. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct GatewayError(pub(crate) &'static str); + +impl fmt::Display for GatewayError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } +} + +impl std::error::Error for GatewayError {} + +pub(crate) fn validate_id(id: &str) -> Result<(), GatewayError> { + if id.len() > MAX_ID_BYTES { + return Err(GatewayError("gateway identifier exceeds size bound")); + } + crate::application::LogicalId::try_new("gateway identifier", id) + .map(|_| ()) + .map_err(|_| GatewayError("invalid gateway identifier")) +} + +/// Optional optimizations. These flags select adapter capabilities, never +/// authorize reuse. Origin-validated identity and freshness are still required. +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct DeliveryCapabilities { + /// Complete query snapshot reuse with origin validation. + pub snapshots: bool, + /// Equivalent concurrent query execution sharing. + pub coalescing: bool, + /// Equivalent upstream live subscription sharing. + pub live_sharing: bool, +} + +/// Explicit GraphQL surface selection at the bound executor. +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct GraphqlCapabilities { + /// Expose command mutations. + pub commands: bool, + /// Expose queries. + pub queries: bool, + /// Expose live operations. + pub live: bool, +} + +/// Location of the composed executor. Remote requests remain whole operations. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum GraphqlExecutor { + /// Adapter-owned executor in this process. + Embedded, + /// Complete remote executor at this configured HTTP(S) origin. The adapter + /// owns endpoint-path configuration and credential trust. + Remote { + /// Absolute origin without userinfo, path, query or fragment. + origin: String, + }, +} + +/// Kind of adapter resource explicitly selected by configuration. No handles, +/// secrets, native futures or database pools are part of this declaration. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum BindingKind { + /// Application HTTP handler or delegated auth lifecycle handler. + Handler, + /// Authentication/admission policy implemented by the selected adapter. + Admission, + /// Native or platform assets; route admission precedes serving. + Assets, + /// UI server at a configured origin; never a request-selected proxy URL. + UiProxy { + /// Absolute HTTP(S) origin without userinfo, path, query or fragment. + origin: String, + }, + /// GraphQL executor and its explicitly selected capabilities. + Graphql { + /// Local or complete remote execution. + executor: GraphqlExecutor, + /// Surface components implemented by the executor. + capabilities: GraphqlCapabilities, + /// Independent optional delivery mounts; all disabled by default. + delivery: DeliveryCapabilities, + /// Adapter registration identifiers for local schema extensions. + /// Remote schemas must install their own fields at the remote executor; + /// declaring local extensions with a remote binding is rejected. + schema_extensions: Vec, + }, +} + +/// Named adapter binding. Identifiers are shared with route targets/admission. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Binding { + /// Unique configuration identifier. + pub id: String, + /// Required adapter capability. + pub kind: BindingKind, +} + +impl Binding { + /// Declare a binding. [`GatewayConfig::build`] validates all declarations. + pub fn new(id: impl Into, kind: BindingKind) -> Self { + Self { + id: id.into(), + kind, + } + } +} + +/// Portable configuration, validated atomically before a gateway is usable. +/// Declaration order does not change routing. Deserialization alone does not +/// validate references or grant authority; always call [`Self::build`]. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct GatewayConfig { + /// Explicit resource declarations. Merely linking an adapter adds nothing. + pub bindings: Vec, + /// Explicit path ownership and admission chains. + pub routes: Vec, +} + +/// Validated immutable route and binding inventory. Creating this value performs +/// no I/O or runtime allocation other than its bounded configuration storage. +#[derive(Clone, Debug)] +pub struct Gateway { + routes: Vec, + bindings: BTreeMap, +} + +impl GatewayConfig { + /// Validate declarations, references, bounds and deterministic ownership. + /// + /// # Errors + /// Rejects duplicate/ambiguous paths or IDs, missing/wrong-kind bindings, + /// invalid origins, malformed paths and incompatible capability selections. + pub fn build(self) -> Result { + if self.routes.len() > MAX_ROUTES || self.bindings.len() > MAX_BINDINGS { + return Err(GatewayError( + "gateway configuration exceeds inventory bounds", + )); + } + let mut bindings = BTreeMap::new(); + for binding in self.bindings { + validate_id(&binding.id)?; + validate_binding(&binding.kind)?; + if bindings.insert(binding.id.clone(), binding).is_some() { + return Err(GatewayError("duplicate gateway binding identifier")); + } + } + let mut route_ids = BTreeSet::new(); + let mut paths = BTreeSet::new(); + let mut routes = self.routes; + for route in &mut routes { + route.validate()?; + if !route_ids.insert(route.id.clone()) { + return Err(GatewayError("duplicate gateway route identifier")); + } + if !paths.insert(route.path.clone()) { + return Err(GatewayError("duplicate gateway path owner")); + } + let target = bindings + .get(&route.target) + .ok_or(GatewayError("gateway route references a missing binding"))?; + if matches!(target.kind, BindingKind::Admission) { + return Err(GatewayError("admission binding cannot execute a route")); + } + for policy in &route.admission { + if !matches!( + bindings.get(policy).map(|b| &b.kind), + Some(BindingKind::Admission) + ) { + return Err(GatewayError( + "route admission requires an admission binding", + )); + } + } + } + // Stable declaration order aids adapters and diagnostics. Selection below + // ranks exact paths and prefix length rather than registration order. + routes.sort_by(|a, b| a.id.cmp(&b.id)); + Ok(Gateway { routes, bindings }) + } +} + +impl Gateway { + /// The validated route inventory, ordered by identifier. + pub fn routes(&self) -> &[Route] { + &self.routes + } + + /// Resolve a configured resource without accepting a caller-selected URL. + pub fn binding(&self, id: &str) -> Option<&Binding> { + self.bindings.get(id) + } + + /// Resolve path ownership before checking the HTTP method. An unsupported + /// method stays owned by its selected route; it never falls through to UI. + /// Prefixes match at segment boundaries. Percent-encoded path aliases are + /// decoded once; encoded separators and ambiguous traversal are rejected. + /// + /// # Errors + /// Rejects malformed methods/targets and bounded or ambiguous path input. + pub fn select( + &self, + method: &str, + target: &str, + ) -> Result>, GatewayError> { + super::route::validate_method(method)?; + if target.len() > 16 * 1024 + || target.contains('#') + || target.bytes().any(|b| b.is_ascii_control()) + { + return Err(GatewayError("invalid gateway request target")); + } + let path = normalize_path(target.split('?').next().unwrap_or_default())?; + let route = self + .routes + .iter() + .filter(|r| r.path.matches(&path)) + .max_by_key(|r| match &r.path { + RoutePath::Exact(p) => (true, p.len()), + RoutePath::Prefix(p) => (false, p.len()), + }); + Ok(route.map(|route| SelectedRoute { + route, + binding: &self.bindings[&route.target], + method_allowed: route.methods.allows(method), + })) + } +} + +fn validate_binding(kind: &BindingKind) -> Result<(), GatewayError> { + match kind { + BindingKind::UiProxy { origin } => validate_origin(origin)?, + BindingKind::Graphql { + executor, + capabilities, + delivery, + schema_extensions, + } => { + if !capabilities.commands && !capabilities.queries && !capabilities.live { + return Err(GatewayError( + "GraphQL binding must select a surface capability", + )); + } + if ((delivery.snapshots || delivery.coalescing) && !capabilities.queries) + || (delivery.live_sharing && !capabilities.live) + { + return Err(GatewayError( + "delivery mount requires its query or live capability", + )); + } + if let GraphqlExecutor::Remote { origin } = executor { + validate_origin(origin)?; + if !schema_extensions.is_empty() { + return Err(GatewayError( + "remote schema extensions must be registered at the remote executor", + )); + } + } + if schema_extensions.len() > MAX_BINDINGS { + return Err(GatewayError("too many schema extensions")); + } + let mut seen = BTreeSet::new(); + for extension in schema_extensions { + validate_id(extension)?; + if !seen.insert(extension) { + return Err(GatewayError("duplicate schema extension identifier")); + } + } + } + BindingKind::Handler | BindingKind::Admission | BindingKind::Assets => {} + } + Ok(()) +} + +fn validate_origin(origin: &str) -> Result<(), GatewayError> { + let invalid = GatewayError( + "binding requires an absolute HTTP(S) origin without credentials, path, query or fragment", + ); + if origin.len() > 2048 + || origin + .bytes() + .any(|b| b.is_ascii_whitespace() || b.is_ascii_control() || b == b'\\') + { + return Err(invalid); + } + let parsed = url::Url::parse(origin).map_err(|_| invalid.clone())?; + if !matches!(parsed.scheme(), "http" | "https") + || parsed.host_str().is_none() + || !parsed.username().is_empty() + || parsed.password().is_some() + || parsed.query().is_some() + || parsed.fragment().is_some() + || parsed.path() != "/" + { + return Err(invalid); + } + // Check the original authority/path as well: URL parsing can erase dot + // segments or repair missing slashes, neither is an origin declaration. + let authority = origin.split_once("://").ok_or(invalid.clone())?.1; + if authority.trim_end_matches('/').contains('/') + || authority.contains('@') + || authority.ends_with("//") + { + return Err(invalid); + } + Ok(()) +} diff --git a/src/gateway/extension.rs b/src/gateway/extension.rs new file mode 100644 index 000000000..a09158f36 --- /dev/null +++ b/src/gateway/extension.rs @@ -0,0 +1,78 @@ +use super::{Gateway, SelectedRoute}; +use std::future::Future; + +/// Protocol-neutral rejection for the host to render as an HTTP response. +#[derive(Clone, Copy, Debug)] +pub enum Rejection<'a> { + /// Invalid or oversized request metadata (400). + BadRequest, + /// No declared route owns the path (404). + NotFound, + /// The selected owner does not support this method (405). Its methods can + /// populate Allow; the adapter must not retry against a UI fallback. + MethodNotAllowed(SelectedRoute<'a>), +} + +/// Runtime execution seam. Implementations own bodies, headers, credentials, +/// streaming, cancellation and the selected binding/provider registry. +/// +/// Futures deliberately have no Send bound: a Worker may hold local handles. +/// Native adapters can implement these methods with Send futures. Gateway +/// admission does not replace authorization at a remote or embedded executor. +pub trait GatewayAdapter { + /// Complete runtime request, including the body and untrusted credentials. + type Request; + /// Authenticated/admitted context, defined by the adapter/provider contract. + type Context; + /// Complete runtime response, including streaming body and independent headers. + type Response; + + /// The actual method of this request; it must agree with the executed request. + fn method<'a>(&self, request: &'a Self::Request) -> &'a str; + /// Raw origin-form path/query from this request (before decoding). Worker + /// adapters extract this from the platform URL, never forwarded-host headers. + fn target<'a>(&self, request: &'a Self::Request) -> &'a str; + /// Authenticate and run every declared admission policy in order. Return a + /// terminal denial response on failure. Public routes may return anonymous + /// context, but must not treat an invalid credential as a valid principal. + fn admit( + &self, + selected: SelectedRoute<'_>, + request: &Self::Request, + ) -> impl Future>; + /// Execute exactly the selected binding with admitted context. Preserve all + /// data/errors/protocol evidence. Upstream failures are terminal responses; + /// do not retry mutations or re-route 404/405/5xx responses to UI. + fn execute( + &self, + selected: SelectedRoute<'_>, + context: Self::Context, + request: Self::Request, + ) -> impl Future; + /// Render a gateway rejection without resolving another route. + fn reject(&self, rejection: Rejection<'_>) -> Self::Response; +} + +impl Gateway { + /// Select once, admit before serving (including protected assets), then + /// execute once. The returned response/body is untouched and adapter-owned. + pub async fn dispatch( + &self, + adapter: &A, + request: A::Request, + ) -> A::Response { + let selected = match self.select(adapter.method(&request), adapter.target(&request)) { + Ok(Some(selected)) => selected, + Ok(None) => return adapter.reject(Rejection::NotFound), + Err(_) => return adapter.reject(Rejection::BadRequest), + }; + let context = match adapter.admit(selected, &request).await { + Ok(context) => context, + Err(response) => return response, + }; + if !selected.method_allowed() { + return adapter.reject(Rejection::MethodNotAllowed(selected)); + } + adapter.execute(selected, context, request).await + } +} diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs new file mode 100644 index 000000000..8001ae3e3 --- /dev/null +++ b/src/gateway/mod.rs @@ -0,0 +1,29 @@ +//! Portable application gateway contracts (`gateway` feature). +//! +//! Configuration selects capabilities; linking this module starts no listeners, +//! executors, projectors or delivery coordinators. [`Gateway::dispatch`] fixes +//! route ownership before admission and execution. Native/Worker adapters own +//! HTTP bodies, credentials, streams, cancellation and connection lifetimes. +//! +//! ``` +//! use distributed::gateway::*; +//! let gateway = GatewayConfig { +//! bindings: vec![Binding::new("assets", BindingKind::Assets)], +//! routes: vec![Route::new("ui", RoutePath::prefix("/"), "assets")], +//! }.build()?; +//! assert_eq!(gateway.select("GET", "/about")?.unwrap().route().id, "ui"); +//! # Ok::<(), GatewayError>(()) +//! ``` + +#![deny(missing_docs)] + +mod config; +mod extension; +mod route; + +pub use config::{ + Binding, BindingKind, DeliveryCapabilities, Gateway, GatewayConfig, GatewayError, + GraphqlCapabilities, GraphqlExecutor, MAX_BINDINGS, MAX_ID_BYTES, MAX_ROUTES, +}; +pub use extension::{GatewayAdapter, Rejection}; +pub use route::{Methods, Route, RoutePath, SelectedRoute, MAX_ADMISSIONS, MAX_PATH_BYTES}; diff --git a/src/gateway/route.rs b/src/gateway/route.rs new file mode 100644 index 000000000..a3d7c2d13 --- /dev/null +++ b/src/gateway/route.rs @@ -0,0 +1,220 @@ +use super::config::{validate_id, Binding, GatewayError}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Maximum UTF-8 bytes in a route or request path before decoding. +pub const MAX_PATH_BYTES: usize = 4096; +/// Maximum ordered admission policies on one route. +pub const MAX_ADMISSIONS: usize = 16; + +/// Explicit ownership of an exact path or a segment-delimited prefix. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde( + tag = "kind", + content = "path", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum RoutePath { + /// Matches just this path, before every prefix match. + Exact(String), + /// Matches this path and descendants; `/` is the explicit UI fallback. + Prefix(String), +} + +impl RoutePath { + /// Declare an exact route. Validation happens during configuration build. + pub fn exact(path: impl Into) -> Self { + Self::Exact(path.into()) + } + /// Declare a prefix. A trailing slash is normalized during build. + pub fn prefix(path: impl Into) -> Self { + Self::Prefix(path.into()) + } + pub(crate) fn matches(&self, path: &str) -> bool { + match self { + Self::Exact(value) => value == path, + Self::Prefix(value) => { + value == "/" + || value == path + || path + .strip_prefix(value) + .is_some_and(|tail| tail.starts_with('/')) + } + } + } +} + +/// HTTP method selection within one path owner. Disjoint method registrations +/// at the same path are rejected too: use one owner with an explicit list. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde( + tag = "kind", + content = "methods", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum Methods { + /// Delegate all valid HTTP methods, including HEAD/OPTIONS, to this owner. + #[default] + Any, + /// Exactly these case-sensitive methods. HEAD is not implicitly GET. + Only(Vec), +} + +impl Methods { + /// Whether this selection admits the supplied method. + pub fn allows(&self, method: &str) -> bool { + match self { + Self::Any => true, + Self::Only(methods) => methods.iter().any(|m| m == method), + } + } +} + +/// One route declaration. Public routes have an empty admission chain; protected +/// assets use the same ordered policies as API/custom routes. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Route { + /// Unique route identifier. + pub id: String, + /// Owned exact path or prefix. + pub path: RoutePath, + /// Configured execution binding identifier. + pub target: String, + /// Supported HTTP methods within this owner. + pub methods: Methods, + /// Ordered admission binding identifiers, all required before execution. + pub admission: Vec, +} + +impl Route { + /// Declare a public route accepting all methods. Add policies/methods + /// explicitly before building the configuration. + pub fn new(id: impl Into, path: RoutePath, target: impl Into) -> Self { + Self { + id: id.into(), + path, + target: target.into(), + methods: Methods::Any, + admission: Vec::new(), + } + } + + pub(crate) fn validate(&mut self) -> Result<(), GatewayError> { + validate_id(&self.id)?; + validate_id(&self.target)?; + match &mut self.path { + RoutePath::Exact(path) => *path = normalize_path(path)?, + RoutePath::Prefix(path) => { + *path = normalize_path(path)?; + if path.len() > 1 { + *path = path.trim_end_matches('/').to_owned(); + } + } + } + if let Methods::Only(methods) = &mut self.methods { + if methods.is_empty() || methods.len() > 32 { + return Err(GatewayError("method selection must contain 1..=32 methods")); + } + let mut seen = BTreeSet::new(); + for method in methods.iter() { + validate_method(method)?; + if !seen.insert(method) { + return Err(GatewayError("duplicate route method")); + } + } + methods.sort(); + } + if self.admission.len() > MAX_ADMISSIONS { + return Err(GatewayError("too many route admission policies")); + } + let mut seen = BTreeSet::new(); + for policy in &self.admission { + validate_id(policy)?; + if !seen.insert(policy) { + return Err(GatewayError("duplicate route admission policy")); + } + } + Ok(()) + } +} + +/// Validated selection borrowed from one gateway. No caller can construct a +/// selection that bypasses binding validation. An adapter response is terminal. +#[derive(Clone, Copy, Debug)] +pub struct SelectedRoute<'a> { + pub(crate) route: &'a Route, + pub(crate) binding: &'a Binding, + pub(crate) method_allowed: bool, +} + +impl<'a> SelectedRoute<'a> { + /// Fixed route owner, including its admission policy chain. + pub fn route(self) -> &'a Route { + self.route + } + /// Validated configured execution resource. + pub fn binding(self) -> &'a Binding { + self.binding + } + /// False means an owned 405, never a search for another matching route. + pub fn method_allowed(self) -> bool { + self.method_allowed + } +} + +pub(crate) fn validate_method(method: &str) -> Result<(), GatewayError> { + if method.is_empty() + || method.len() > 32 + || !method + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) + { + return Err(GatewayError("invalid HTTP method")); + } + Ok(()) +} + +pub(crate) fn normalize_path(path: &str) -> Result { + if path.len() > MAX_PATH_BYTES || !path.starts_with('/') { + return Err(GatewayError("gateway path must be a bounded absolute path")); + } + let mut decoded = Vec::with_capacity(path.len()); + let mut input = path.bytes(); + while let Some(byte) = input.next() { + let byte = if byte == b'%' { + let hi = input.next().and_then(hex); + let lo = input.next().and_then(hex); + let (Some(hi), Some(lo)) = (hi, lo) else { + return Err(GatewayError("invalid percent-encoded path")); + }; + let value = hi * 16 + lo; + if matches!(value, b'/' | b'\\' | b'%') { + return Err(GatewayError("ambiguous encoded path separator")); + } + value + } else { + byte + }; + if byte.is_ascii_control() || matches!(byte, b'\\' | b'?' | b'#') { + return Err(GatewayError("invalid gateway path character")); + } + decoded.push(byte); + } + let path = String::from_utf8(decoded).map_err(|_| GatewayError("gateway path is not UTF-8"))?; + if path.contains("//") || path.split('/').any(|s| matches!(s, "." | "..")) { + return Err(GatewayError("ambiguous gateway path segments")); + } + Ok(path) +} + +fn hex(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} diff --git a/src/lib.rs b/src/lib.rs index 865d5abfc..c2f4fcb21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,6 +34,8 @@ pub(crate) mod command_ledger; mod commit_builder; #[cfg(feature = "emitter")] pub mod emitter; +#[cfg(feature = "gateway")] +pub mod gateway; pub mod graphql; mod in_memory_repo; pub mod lock; diff --git a/tests/gateway-portable/.gitignore b/tests/gateway-portable/.gitignore new file mode 100644 index 000000000..556a76756 --- /dev/null +++ b/tests/gateway-portable/.gitignore @@ -0,0 +1,2 @@ +/target/ +!Cargo.lock diff --git a/tests/gateway-portable/Cargo.lock b/tests/gateway-portable/Cargo.lock new file mode 100644 index 000000000..d9b925ef5 --- /dev/null +++ b/tests/gateway-portable/Cargo.lock @@ -0,0 +1,798 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitcode" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6ed1b54d8dc333e7be604d00fa9262f4635485ffea923647b6521a5fff045d" +dependencies = [ + "arrayvec", + "bitcode_derive", + "bytemuck", + "glam", + "serde", +] + +[[package]] +name = "bitcode_derive" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238b90427dfad9da4a9abd60f3ec1cdee6b80454bde49ed37f1781dd8e9dc7f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "distributed" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64", + "bitcode", + "distributed_macros", + "futures-util", + "js-sys", + "serde", + "serde_json", + "sha2", + "tonic-build", + "url", + "uuid", +] + +[[package]] +name = "distributed_macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "sha2", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gateway-portable-fixture" +version = "0.0.0" +dependencies = [ + "distributed", + "serde_json", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "glam" +version = "0.33.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21fef0953c54fd3de2f44b743fbf77e044c81a25faee03636dfccc0d35135e23" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/gateway-portable/Cargo.toml b/tests/gateway-portable/Cargo.toml new file mode 100644 index 000000000..1c57af6a4 --- /dev/null +++ b/tests/gateway-portable/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "gateway-portable-fixture" +version = "0.0.0" +edition = "2021" +publish = false + +[workspace] + +[features] +default = ["gateway"] +gateway = ["distributed/gateway"] + +[dependencies] +distributed = { path = "../..", default-features = false } + +[dev-dependencies] +serde_json = "1" + +[[test]] +name = "gateway_routing" +path = "../gateway_routing.rs" + +[[test]] +name = "gateway_extensions" +path = "../gateway_extensions.rs" diff --git a/tests/gateway-portable/README.md b/tests/gateway-portable/README.md new file mode 100644 index 000000000..da77a1adc --- /dev/null +++ b/tests/gateway-portable/README.md @@ -0,0 +1,23 @@ +# Portable gateway contract fixture + +This separate consumer avoids the parent crate's native dev-dependency feature +unification. It builds the same UI/auth-only contract on native and Wasm and +runs the parent gateway contract tests with only portable dependencies. + +From the repository root: + +```sh +cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked +cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown +python3 tests/gateway-portable/check_dependencies.py +``` + +The runtime dependency tree must exclude async-graphql, axum, sqlx, tokio, +reqwest, tonic and worker. Build dependencies run on the host and are not runtime +imports. The single `gateway` feature selects contracts; no native/Worker server +adapter feature is advertised by this fixture. Route/admission tests use local +`Rc`-holding futures without an async I/O runtime. + +These tests prove portable decisions and adapter sequencing. They do not prove +real authentication, UI/network streaming, GraphQL execution or workerd/DO +behavior, which belong to the subsequent gateway implementation tasks. diff --git a/tests/gateway-portable/check_dependencies.py b/tests/gateway-portable/check_dependencies.py new file mode 100644 index 000000000..08777783a --- /dev/null +++ b/tests/gateway-portable/check_dependencies.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Fail if the UI/auth consumer starts depending on a native runtime or executor.""" +from pathlib import Path +import subprocess + +manifest = Path(__file__).resolve().with_name("Cargo.toml") +for target in (None, "wasm32-unknown-unknown"): + command = ["cargo", "tree", "--manifest-path", str(manifest), "--locked", "--edges", "normal", "--prefix", "none"] + if target: + command += ["--target", target] + output = subprocess.check_output(command, text=True) + packages = {line.split()[0] for line in output.splitlines() if line.strip()} + forbidden = {"async-graphql", "async-graphql-axum", "axum", "sqlx", "sqlx-core", "tokio", "reqwest", "tonic", "worker"} + leaked = sorted(packages & forbidden) + if leaked: + raise SystemExit(f"{target or 'native'}: forbidden runtime dependencies: {', '.join(leaked)}") + print(f"{target or 'native'}: portable dependency boundary passed") diff --git a/tests/gateway-portable/src/lib.rs b/tests/gateway-portable/src/lib.rs new file mode 100644 index 000000000..a3844fdbd --- /dev/null +++ b/tests/gateway-portable/src/lib.rs @@ -0,0 +1,19 @@ +//! UI/auth-only consumer: no GraphQL executor, SQL, listener or Worker SDK. +use distributed::gateway::*; + +pub fn ui_and_auth() -> Result { + let mut assets = Route::new("ui", RoutePath::prefix("/"), "assets"); + assets.admission = vec!["session".into()]; + GatewayConfig { + bindings: vec![ + Binding::new("session", BindingKind::Admission), + Binding::new("assets", BindingKind::Assets), + Binding::new("auth", BindingKind::Handler), + ], + routes: vec![ + assets, + Route::new("auth", RoutePath::prefix("/auth"), "auth"), + ], + } + .build() +} diff --git a/tests/gateway_extensions.rs b/tests/gateway_extensions.rs new file mode 100644 index 000000000..ee1949606 --- /dev/null +++ b/tests/gateway_extensions.rs @@ -0,0 +1,164 @@ +#![cfg(feature = "gateway")] +mod gateway_support; +use distributed::gateway::*; +use gateway_support::*; +use std::rc::Rc; + +fn graphql(executor: GraphqlExecutor, schema_extensions: Vec) -> BindingKind { + BindingKind::Graphql { + executor, + schema_extensions, + capabilities: GraphqlCapabilities { + commands: true, + queries: true, + live: true, + }, + delivery: DeliveryCapabilities::default(), + } +} + +#[test] +fn custom_route_provider_and_field() { + let mut c = config(); + c.bindings.push(Binding::new( + "schema", + graphql( + GraphqlExecutor::Embedded, + vec!["custom_health_field".into()], + ), + )); + let mut custom = Route::new("custom", RoutePath::exact("/custom"), "schema"); + custom.admission = vec!["identity".into()]; + c.routes.push(custom); + let gateway = c.build().unwrap(); + let mut adapter = Adapter::new(200); + adapter.provider = Rc::new("replacement-provider".into()); + let response = run(gateway.dispatch( + &adapter, + Request { + method: "GET", + target: "/custom", + authorized: true, + }, + )); + assert_eq!(response.body, "schema:replacement-provider"); + assert_eq!( + *adapter.calls.borrow(), + ["admit:identity", "execute:schema"] + ); + let BindingKind::Graphql { + schema_extensions, + delivery, + .. + } = &gateway.binding("schema").unwrap().kind + else { + panic!("wrong executor kind") + }; + assert_eq!(schema_extensions, &["custom_health_field"]); + assert_eq!(*delivery, DeliveryCapabilities::default()); +} + +#[test] +fn remote_binding_requires_extensions_at_its_executor() { + let remote = GraphqlExecutor::Remote { + origin: "https://api.example.test".into(), + }; + for extensions in [vec![], vec!["local_field".into()]] { + let mut c = config(); + c.bindings.push(Binding::new( + "schema", + graphql(remote.clone(), extensions.clone()), + )); + assert_eq!(c.build().is_ok(), extensions.is_empty()); + } + let mut c = config(); + c.bindings.push(Binding::new( + "schema", + graphql(GraphqlExecutor::Embedded, vec!["field".into(); 2]), + )); + assert!(c.build().is_err()); +} + +#[test] +fn delivery_mounts_are_independent_and_require_their_surface() { + for queries in [false, true] { + for live in [false, true] { + for snapshots in [false, true] { + for coalescing in [false, true] { + for live_sharing in [false, true] { + let c = GatewayConfig { + bindings: vec![Binding::new( + "schema", + BindingKind::Graphql { + executor: GraphqlExecutor::Embedded, + capabilities: GraphqlCapabilities { + commands: true, + queries, + live, + }, + delivery: DeliveryCapabilities { + snapshots, + coalescing, + live_sharing, + }, + schema_extensions: vec![], + }, + )], + routes: vec![], + }; + assert_eq!( + c.build().is_ok(), + (!(snapshots || coalescing) || queries) && (!live_sharing || live) + ); + } + } + } + } + } + let c = GatewayConfig { + bindings: vec![Binding::new( + "empty", + BindingKind::Graphql { + executor: GraphqlExecutor::Embedded, + capabilities: GraphqlCapabilities::default(), + delivery: DeliveryCapabilities::default(), + schema_extensions: vec![], + }, + )], + routes: vec![], + }; + assert!(c.build().is_err()); +} + +#[test] +fn native_adapter_can_return_a_send_dispatch_future() { + struct Native; + impl GatewayAdapter for Native { + type Request = String; + type Context = (); + type Response = u16; + fn method<'a>(&self, _: &'a String) -> &'a str { + "GET" + } + fn target<'a>(&self, request: &'a String) -> &'a str { + request + } + async fn admit(&self, _: SelectedRoute<'_>, _: &String) -> Result<(), u16> { + Ok(()) + } + async fn execute(&self, _: SelectedRoute<'_>, _: (), _: String) -> u16 { + 204 + } + fn reject(&self, _: Rejection<'_>) -> u16 { + 404 + } + } + fn require_send(value: T) -> T { + value + } + let gateway = config().build().unwrap(); + assert_eq!( + run(require_send(gateway.dispatch(&Native, "/".into()))), + 204 + ); +} diff --git a/tests/gateway_routing.rs b/tests/gateway_routing.rs new file mode 100644 index 000000000..0b73d3f5d --- /dev/null +++ b/tests/gateway_routing.rs @@ -0,0 +1,317 @@ +#![cfg(feature = "gateway")] +mod gateway_support; +use distributed::gateway::*; +use gateway_support::*; + +#[test] +fn route_ownership_matrix() { + let cases = [ + ("GET", "/", "ui", true), + ("POST", "/graphql?operationName=Write", "api", true), + ("DELETE", "/graphql", "api", false), + ("HEAD", "/graphql", "api", false), + ("GET", "/graphql/missing", "api", true), + ("DELETE", "/graphql/ws", "ws", true), + ("GET", "/graphql/ws/child", "api", true), + ("GET", "/graphqlish", "ui", true), + ("POST", "/api/auth/callback", "auth", true), + ("GET", "/api/%61uth/callback", "auth", true), + ("GET", "/private/a.css", "protected", true), + ("GET", "/privacy", "ui", true), + ]; + let original = config(); + for reverse in [false, true] { + let mut config = original.clone(); + if reverse { + config.routes.reverse(); + config.bindings.reverse(); + } + let gateway = config.build().unwrap(); + for (method, path, owner, allowed) in cases { + let selected = gateway.select(method, path).unwrap().unwrap(); + assert_eq!( + (selected.route().id.as_str(), selected.method_allowed()), + (owner, allowed), + "{method} {path}" + ); + } + } +} + +#[test] +fn exact_owner_precedes_even_a_longer_prefix_and_prefixes_use_segment_boundaries() { + let mut c = config(); + c.routes.push(Route::new( + "nested", + RoutePath::prefix("/private/images/"), + "assets", + )); + c.routes.push(Route::new( + "exact", + RoutePath::exact("/private/images/logo"), + "auth", + )); + let g = c.build().unwrap(); + for (path, owner) in [ + ("/private/images", "nested"), + ("/private/images/", "nested"), + ("/private/images/logo", "exact"), + ("/private/images2", "protected"), + ] { + assert_eq!(g.select("GET", path).unwrap().unwrap().route().id, owner); + } +} + +#[test] +fn duplicate_and_normalized_alias_owners_fail_before_serving_even_with_disjoint_methods() { + for path in [ + RoutePath::prefix("/graphql"), + RoutePath::prefix("/graphql/"), + RoutePath::prefix("/%67raphql"), + ] { + let mut c = config(); + let mut duplicate = Route::new("duplicate", path, "ui"); + duplicate.methods = Methods::Only(vec!["DELETE".into()]); + c.routes.push(duplicate); + assert!(c.build().is_err()); + } + let mut c = config(); + c.routes + .push(Route::new("api", RoutePath::exact("/elsewhere"), "ui")); + assert!(c.build().is_err()); +} + +#[test] +fn ambiguous_paths_and_malformed_methods_fail_closed() { + let g = config().build().unwrap(); + for path in [ + "", + "graphql", + "https://host/graphql", + "//host/graphql", + "/a//b", + "/../graphql", + "/a/./b", + "/a/%2e%2e/graphql", + "/%2fgraphql", + "/%5Cgraphql", + "/%252e", + "/a\\b", + "/%00", + "/%7f", + "/%ff", + "/%c0%af", + "/%", + "/%2", + "/%ZZ", + "/a#b", + "/a%3fb", + "/a%23b", + ] { + assert!(g.select("GET", path).is_err(), "accepted {path:?}"); + } + for method in ["", "G ET", "GET\r\n", "GÉT"] { + assert!(g.select(method, "/").is_err()); + } + assert!(g + .select("GET", &format!("/{}", "a".repeat(MAX_PATH_BYTES))) + .is_err()); + assert_eq!( + g.select("GET", "/caf%C3%A9").unwrap().unwrap().route().id, + "ui" + ); +} + +#[test] +fn protected_assets_admit_in_order_before_execution() { + let g = config().build().unwrap(); + for authorized in [false, true] { + let adapter = Adapter::new(200); + let result = run(g.dispatch( + &adapter, + Request { + method: "GET", + target: "/private/app.js", + authorized, + }, + )); + assert_eq!(result.status, if authorized { 200 } else { 401 }); + let expected = if authorized { + vec!["admit:identity", "admit:policy", "execute:assets"] + } else { + vec!["admit:identity"] + }; + assert_eq!(*adapter.calls.borrow(), expected); + } +} + +#[test] +fn owned_errors_never_retry_or_reach_ui_fallback() { + let g = config().build().unwrap(); + for target in ["/graphql/missing", "/api/auth/missing"] { + for status in [404, 405, 500, 503, 504] { + let adapter = Adapter::new(status); + let response = run(g.dispatch( + &adapter, + Request { + method: "GET", + target, + authorized: true, + }, + )); + assert_eq!(response.status, status); + assert_eq!(response.evidence, "opaque-causal-envelope"); + assert_eq!(adapter.calls.borrow().len(), 1); + assert!(!adapter + .calls + .borrow() + .iter() + .any(|call| call == "execute:ui")); + } + } + let adapter = Adapter::new(200); + assert_eq!( + run(g.dispatch( + &adapter, + Request { + method: "DELETE", + target: "/graphql", + authorized: true + } + )) + .status, + 405 + ); + assert!(adapter.calls.borrow().is_empty()); +} + +#[test] +fn absent_mounts_expose_nothing_and_invalid_requests_do_not_execute() { + let g = GatewayConfig::default().build().unwrap(); + let adapter = Adapter::new(200); + for (target, status) in [("/", 404), ("/graphql", 404), ("/%2fprivate", 400)] { + assert_eq!( + run(g.dispatch( + &adapter, + Request { + method: "GET", + target, + authorized: false + } + )) + .status, + status + ); + } + assert!(adapter.calls.borrow().is_empty()); +} + +#[test] +fn declarations_are_bounded_and_references_are_checked() { + let mut c = config(); + c.routes[0].target = "missing".into(); + assert!(c.build().is_err()); + let mut c = config(); + c.routes[0].target = "identity".into(); + assert!(c.build().is_err()); + for admission in [ + vec!["missing".into()], + vec!["ui".into()], + vec!["identity".into(); MAX_ADMISSIONS + 1], + vec!["identity".into(); 2], + ] { + let mut c = config(); + c.routes[0].admission = admission; + assert!(c.build().is_err()); + } + let mut c = config(); + c.routes[0].methods = Methods::Only(vec![]); + assert!(c.build().is_err()); + let mut c = config(); + c.routes[0].methods = Methods::Only(vec!["GET".into(); 2]); + assert!(c.build().is_err()); + let mut c = config(); + c.bindings.push(c.bindings[0].clone()); + assert!(c.build().is_err()); + let mut c = config(); + c.routes = vec![c.routes[0].clone(); MAX_ROUTES + 1]; + assert!(c.build().is_err()); + let mut c = config(); + c.bindings = vec![c.bindings[0].clone(); MAX_BINDINGS + 1]; + assert!(c.build().is_err()); +} + +#[test] +fn configured_origins_cannot_hide_paths_credentials_or_non_http_targets() { + for origin in [ + "https://site.test/path", + "https://site.test/..", + "https://site.test//", + "https:site.test", + "//site.test", + "file:///etc/passwd", + "ftp://site.test", + "https://user:pass@site.test", + "https://@site.test", + "https://site.test?url=elsewhere", + "https://site.test#x", + "https://site.test\\evil", + "https://site.test\n", + ] { + let mut c = config(); + c.bindings[5].kind = BindingKind::UiProxy { + origin: origin.into(), + }; + assert!(c.build().is_err(), "accepted {origin:?}"); + } + for origin in [ + "http://localhost:5180", + "https://site.test/", + "http://[::1]:5180", + ] { + let mut c = config(); + c.bindings[5].kind = BindingKind::UiProxy { + origin: origin.into(), + }; + assert!(c.build().is_ok()); + } +} + +#[test] +fn serialized_configuration_still_requires_validation() { + let c = config(); + let serialized = serde_json::to_vec(&c).unwrap(); + let roundtrip: GatewayConfig = serde_json::from_slice(&serialized).unwrap(); + assert_eq!(roundtrip, c); + assert!(roundtrip.build().is_ok()); + assert!(serde_json::from_str::( + r#"{"routes":[],"bindings":[],"implicit_ui":true}"# + ) + .is_err()); +} + +#[test] +fn identifiers_and_exact_inventory_limits_are_enforced() { + let mut c = GatewayConfig { + bindings: vec![Binding::new("assets", BindingKind::Assets)], + routes: (0..MAX_ROUTES) + .map(|i| { + Route::new( + format!("route-{i}"), + RoutePath::exact(format!("/route-{i}")), + "assets", + ) + }) + .collect(), + }; + assert!(c.clone().build().is_ok()); + c.routes[0].id = "a".repeat(MAX_ID_BYTES + 1); + assert!(c.build().is_err()); + let c = GatewayConfig { + bindings: (0..MAX_BINDINGS) + .map(|i| Binding::new(format!("binding-{i}"), BindingKind::Handler)) + .collect(), + routes: vec![], + }; + assert!(c.build().is_ok()); +} diff --git a/tests/gateway_support/mod.rs b/tests/gateway_support/mod.rs new file mode 100644 index 000000000..c70450058 --- /dev/null +++ b/tests/gateway_support/mod.rs @@ -0,0 +1,138 @@ +#![allow(dead_code)] +use distributed::gateway::*; +use std::{ + cell::RefCell, + future::Future, + pin::pin, + rc::Rc, + task::{Context, Poll, Waker}, +}; + +pub fn run(future: F) -> F::Output { + let mut future = pin!(future); + let mut cx = Context::from_waker(Waker::noop()); + match future.as_mut().poll(&mut cx) { + Poll::Ready(value) => value, + Poll::Pending => panic!("contract fixture unexpectedly requires an I/O runtime"), + } +} + +pub struct Request { + pub method: &'static str, + pub target: &'static str, + pub authorized: bool, +} + +#[derive(Debug, PartialEq)] +pub struct Response { + pub status: u16, + pub body: String, + pub evidence: &'static str, +} + +pub struct Adapter { + pub calls: RefCell>, + pub provider: Rc, + pub status: u16, +} + +impl Adapter { + pub fn new(status: u16) -> Self { + Self { + calls: RefCell::new(Vec::new()), + provider: Rc::new("default".into()), + status, + } + } +} + +impl GatewayAdapter for Adapter { + type Request = Request; + type Context = Rc; + type Response = Response; + fn method<'a>(&self, request: &'a Request) -> &'a str { + request.method + } + fn target<'a>(&self, request: &'a Request) -> &'a str { + request.target + } + async fn admit( + &self, + selected: SelectedRoute<'_>, + request: &Request, + ) -> Result, Response> { + for policy in &selected.route().admission { + self.calls.borrow_mut().push(format!("admit:{policy}")); + if !request.authorized { + return Err(Response { + status: 401, + body: "denied".into(), + evidence: "", + }); + } + } + // Holding Rc across await proves that neither the contract nor dispatcher + // forces Worker adapters into Send futures or a native async runtime. + let context = self.provider.clone(); + std::future::ready(()).await; + Ok(context) + } + async fn execute( + &self, + selected: SelectedRoute<'_>, + context: Rc, + _request: Request, + ) -> Response { + self.calls + .borrow_mut() + .push(format!("execute:{}", selected.binding().id)); + std::future::ready(()).await; + Response { + status: self.status, + body: format!("{}:{}", selected.binding().id, context), + evidence: "opaque-causal-envelope", + } + } + fn reject(&self, rejection: Rejection<'_>) -> Response { + let status = match rejection { + Rejection::BadRequest => 400, + Rejection::NotFound => 404, + Rejection::MethodNotAllowed(_) => 405, + }; + Response { + status, + body: "rejected".into(), + evidence: "", + } + } +} + +pub fn config() -> GatewayConfig { + let mut api = Route::new("api", RoutePath::prefix("/graphql"), "api"); + api.methods = Methods::Only(vec!["POST".into(), "GET".into()]); + let auth = Route::new("auth", RoutePath::prefix("/api/auth"), "auth"); + let mut protected = Route::new("protected", RoutePath::prefix("/private"), "assets"); + protected.admission = vec!["identity".into(), "policy".into()]; + GatewayConfig { + bindings: vec![ + Binding::new("api", BindingKind::Handler), + Binding::new("auth", BindingKind::Handler), + Binding::new("assets", BindingKind::Assets), + Binding::new("identity", BindingKind::Admission), + Binding::new("policy", BindingKind::Admission), + Binding::new( + "ui", + BindingKind::UiProxy { + origin: "http://localhost:5180".into(), + }, + ), + ], + routes: vec![ + api, + auth, + protected, + Route::new("ws", RoutePath::exact("/graphql/ws"), "api"), + Route::new("ui", RoutePath::prefix("/"), "ui"), + ], + } +} From d0d7c1cf45b6eab583b8b78c08a665f82ea9664a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 20:40:42 -0500 Subject: [PATCH 050/484] feat: share gateway identity and prove delegated auth Implements [[tasks/application-gateway-3]] in [[tasks/application-gateway-1]]. --- .github/workflows/integration-gateway.yaml | 31 +- src/gateway/README.md | 28 + src/gateway/auth.rs | 92 + src/gateway/context.rs | 146 ++ src/gateway/mod.rs | 5 + src/graphql/identity/gateway.rs | 68 + src/graphql/identity/mod.rs | 5 + tests/e2e-ui/ui/src/auth.ts | 42 +- .../e2e-ui/ui/src/lib/server/require-auth.ts | 11 +- .../ui/src/routes/api/auth/refresh/+server.ts | 5 +- tests/gateway-auth/.gitignore | 5 + tests/gateway-auth/README.md | 38 + tests/gateway-auth/package-lock.json | 2306 +++++++++++++++++ tests/gateway-auth/package.json | 21 + tests/gateway-auth/prepare.mjs | 9 + tests/gateway-auth/provider.mjs | 53 + tests/gateway-auth/run.mjs | 121 + tests/gateway-auth/src/app.html | 1 + tests/gateway-auth/src/hooks.server.ts | 1 + tests/gateway-auth/src/routes/+page.svelte | 1 + .../src/routes/api/auth/refresh/+server.ts | 1 + .../gateway-auth/src/routes/login/+server.ts | 2 + .../gateway-auth/src/routes/logout/+server.ts | 2 + .../src/routes/private/+server.ts | 6 + tests/gateway-auth/svelte.config.js | 2 + tests/gateway-auth/vite.config.js | 3 + tests/gateway-portable/Cargo.toml | 4 + tests/gateway_auth.rs | 115 + tests/graphql_identity/main.rs | 64 + 29 files changed, 3171 insertions(+), 17 deletions(-) create mode 100644 src/gateway/README.md create mode 100644 src/gateway/auth.rs create mode 100644 src/gateway/context.rs create mode 100644 src/graphql/identity/gateway.rs create mode 100644 tests/gateway-auth/.gitignore create mode 100644 tests/gateway-auth/README.md create mode 100644 tests/gateway-auth/package-lock.json create mode 100644 tests/gateway-auth/package.json create mode 100644 tests/gateway-auth/prepare.mjs create mode 100644 tests/gateway-auth/provider.mjs create mode 100644 tests/gateway-auth/run.mjs create mode 100644 tests/gateway-auth/src/app.html create mode 100644 tests/gateway-auth/src/hooks.server.ts create mode 100644 tests/gateway-auth/src/routes/+page.svelte create mode 100644 tests/gateway-auth/src/routes/api/auth/refresh/+server.ts create mode 100644 tests/gateway-auth/src/routes/login/+server.ts create mode 100644 tests/gateway-auth/src/routes/logout/+server.ts create mode 100644 tests/gateway-auth/src/routes/private/+server.ts create mode 100644 tests/gateway-auth/svelte.config.js create mode 100644 tests/gateway-auth/vite.config.js create mode 100644 tests/gateway_auth.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 3ba4b228b..e7d6f6e0d 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -1,4 +1,4 @@ -name: Portable gateway contracts +name: Application gateway on: pull_request: @@ -7,6 +7,10 @@ on: - 'distributed_macros/**' - 'Cargo.toml' - 'build.rs' + - 'tests/e2e-ui/ui/src/auth.ts' + - 'tests/e2e-ui/ui/src/lib/server/**' + - 'tests/e2e-ui/ui/src/routes/api/auth/**' + - 'tests/graphql_identity/**' - 'tests/gateway*' - 'tests/gateway*/**' - '.github/workflows/integration-gateway.yaml' @@ -38,3 +42,28 @@ jobs: run: cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown - name: Verify native and Wasm dependency isolation run: python3 tests/gateway-portable/check_dependencies.py + + auth: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - name: Verify gateway and backend identity + run: cargo test -p distributed --no-default-features --features gateway,graphql,sqlite --test graphql_identity + - name: Install pinned auth fixture dependencies + working-directory: tests/gateway-auth + run: npm ci + - name: Install Chromium + working-directory: tests/gateway-auth + run: npx playwright install --with-deps chromium + - name: Run production Auth.js lifecycle and browser security cases + working-directory: tests/gateway-auth + run: npm test diff --git a/src/gateway/README.md b/src/gateway/README.md new file mode 100644 index 000000000..b55dea8d9 --- /dev/null +++ b/src/gateway/README.md @@ -0,0 +1,28 @@ +# Gateway identity boundary + +`AuthProvider` validates current `Credentials` and supplies `RequestContext` for +UI, API, assets and custom routes. Run authentication before each consumer's +route admission or delivery reuse; an expired assertion fails even on a public +route. `provider_revision` changes when provider policy/configuration changes. +An application can replace the provider without changing route declarations. +Contexts are in-process assertions and have no client deserializer. + +`BackendCredential` is explicit: either none or a provider-supplied bearer. +The gateway does not translate a cookie or `x-user-id` into a credential. +A configured session provider may resolve an Auth.js session and supply its +access token; the backend must still validate that token and authorize the +operation. With `graphql` enabled, `graphql::identity::OidcGatewayProvider` +reuses the existing JWT validator, JWKS cache and role mapping. This optional +adapter does not make the portable gateway depend on GraphQL. + +Delegate login/callback/refresh/logout to existing auth handlers. Configure +`AUTH_URL` as the public origin. Strip incoming identity and forwarded headers, +including deployment-specific identity/secret names, before adding trusted +public-origin metadata. Preserve Origin for CSRF and every Set-Cookie header. +Credentials are redacted from Debug output and are not cache keys. + +The reusable production Auth.js/OIDC/browser fixture is in +`tests/gateway-auth`. Network adapters and application mounts own transport +plumbing; merely declaring routes or providers starts no service or identity +store. Removing a gateway mount restores the application's prior entrypoints; +backend authentication stays enabled. diff --git a/src/gateway/auth.rs b/src/gateway/auth.rs new file mode 100644 index 000000000..d24784459 --- /dev/null +++ b/src/gateway/auth.rs @@ -0,0 +1,92 @@ +use super::{Credentials, RequestContext}; +use std::future::Future; + +/// Authentication/admission failures carry no credentials or provider internals. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AuthError { + /// Missing, invalid, revoked or expired required credentials (401). + Unauthorized, + /// Authenticated but forbidden by the route policy (403). + Forbidden, + /// Provider cannot establish current identity (503); never serve stale data. + Unavailable, +} + +impl std::fmt::Display for AuthError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Unauthorized => "unauthorized", + Self::Forbidden => "forbidden", + Self::Unavailable => "identity provider unavailable", + }) + } +} +impl std::error::Error for AuthError {} + +/// Replaceable credential validator/session provider. Implementations may use +/// local Worker handles; native implementations may return Send futures. +/// Never trust caller identity or forwarded-host headers. Session providers +/// delegate refresh/callback/logout to their existing auth lifecycle handlers. +pub trait AuthProvider { + /// Validate current credentials, returning anonymous only when credentials + /// are absent (or the provider explicitly recognizes an anonymous session). + fn authenticate( + &self, + credentials: &Credentials, + ) -> impl Future>; +} + +/// Built-in route admission; applications can add policies in their adapter. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Admission { + /// Anonymous callers allowed; invalid credentials still fail authentication. + Public, + /// Any current authenticated subject. + Authenticated, + /// A provider-mapped role is required. + Role(String), +} + +impl Admission { + /// Apply after provider authentication with a host-supplied Unix clock. + /// Expiry is enforced on public routes too; it cannot downgrade to anonymous. + pub fn check(&self, context: &RequestContext, now: u64) -> Result<(), AuthError> { + let identity = context.identity(); + if identity.is_some_and(|identity| identity.expires_at() <= now) { + return Err(AuthError::Unauthorized); + } + match self { + Self::Public => Ok(()), + Self::Authenticated => identity.map(|_| ()).ok_or(AuthError::Unauthorized), + Self::Role(role) => { + let identity = identity.ok_or(AuthError::Unauthorized)?; + if identity.roles().contains(role) { + Ok(()) + } else { + Err(AuthError::Forbidden) + } + } + } + } +} + +/// Headers a public ingress must remove before delegating to a backend or auth +/// handler. Reconstruct public-origin headers from configured origin only. +/// Deployments must additionally strip their own custom identity/secret names. +pub fn is_untrusted_identity_header(name: &str) -> bool { + let name = name.to_ascii_lowercase(); + matches!( + name.as_str(), + "forwarded" + | "x-forwarded-host" + | "x-forwarded-proto" + | "x-forwarded-port" + | "x-forwarded-for" + | "x-real-ip" + | "cf-connecting-ip" + | "cf-access-jwt-assertion" + | "x-user-id" + | "x-role" + | "x-roles" + ) || name.starts_with("x-hasura-") +} diff --git a/src/gateway/context.rs b/src/gateway/context.rs new file mode 100644 index 000000000..ab3505877 --- /dev/null +++ b/src/gateway/context.rs @@ -0,0 +1,146 @@ +use super::GatewayError; +use std::fmt; + +/// Credentials received from a client. Possession is not authentication. +/// Providers must reject invalid credentials even on otherwise public routes. +#[derive(Clone, Default)] +pub struct Credentials { + /// Raw Authorization value; never populated from a cookie by the gateway. + pub authorization: Option, + /// Raw Cookie value, for a configured session provider only. + pub cookie: Option, +} + +impl fmt::Debug for Credentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Credentials") + .field("authorization_present", &self.authorization.is_some()) + .field("cookie_present", &self.cookie.is_some()) + .finish() + } +} + +/// A credential explicitly supplied by the configured provider for backend +/// validation. Gateway admission never grants backend authorization. +#[derive(Clone, Default)] +pub enum BackendCredential { + /// No backend credential. The backend applies its anonymous policy. + #[default] + None, + /// An access token validated or obtained by the provider. Backends still + /// validate issuer, audience, expiry and their own authorization policy. + Bearer(String), +} + +impl fmt::Debug for BackendCredential { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::None => "None", + Self::Bearer(_) => "Bearer([redacted])", + }) + } +} + +/// Provider-authenticated identity shared across UI, API and custom routes. +/// This is an in-process assertion, never a deserializable client proof. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Identity { + authority: String, + subject: String, + roles: Vec, + expires_at: u64, +} + +impl Identity { + /// Called by a trusted provider after validating credentials. `expires_at` + /// is Unix seconds, including the provider's session expiry ceiling. + pub fn verified( + authority: impl Into, + subject: impl Into, + roles: Vec, + expires_at: u64, + ) -> Result { + let authority = authority.into(); + let subject = subject.into(); + if [&authority, &subject] + .iter() + .any(|s| s.is_empty() || s.len() > 4096 || s.chars().any(char::is_control)) + || roles.len() > 128 + || roles + .iter() + .any(|s| s.is_empty() || s.len() > 256 || s.chars().any(char::is_control)) + { + return Err(GatewayError("invalid provider identity")); + } + let mut roles = roles; + roles.sort(); + roles.dedup(); + Ok(Self { + authority, + subject, + roles, + expires_at, + }) + } + /// Authority under which the subject is unique. + pub fn authority(&self) -> &str { + &self.authority + } + /// Authenticated subject, not a caller-supplied identity header. + pub fn subject(&self) -> &str { + &self.subject + } + /// Provider-mapped roles. The backend independently authorizes operations. + pub fn roles(&self) -> &[String] { + &self.roles + } + /// Unix second at which this assertion ceases to admit new work. + pub fn expires_at(&self) -> u64 { + self.expires_at + } +} + +/// Shared admission context. Re-authenticate every new consumer before any +/// cache/flight/live join; this value is not an authorization cache. +#[derive(Clone, Debug)] +pub struct RequestContext { + identity: Option, + provider_revision: String, + backend: BackendCredential, +} + +impl RequestContext { + /// Create an assertion from a trusted provider. Bump `provider_revision` + /// when replacing provider configuration/policy to prevent reuse across it. + pub fn from_provider( + identity: Option, + provider_revision: impl Into, + backend: BackendCredential, + ) -> Result { + let provider_revision = provider_revision.into(); + if provider_revision.is_empty() + || provider_revision.len() > 256 + || provider_revision.chars().any(char::is_control) + || (identity.is_none() && !matches!(backend, BackendCredential::None)) + { + return Err(GatewayError("invalid provider context")); + } + Ok(Self { + identity, + provider_revision, + backend, + }) + } + /// Authenticated identity, or anonymous. + pub fn identity(&self) -> Option<&Identity> { + self.identity.as_ref() + } + /// Provider/policy configuration generation; not a credential. + pub fn provider_revision(&self) -> &str { + &self.provider_revision + } + /// Explicit downstream credential, never derived from asserted headers. + pub fn backend_credential(&self) -> &BackendCredential { + &self.backend + } +} diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 8001ae3e3..7dbed2d18 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -17,7 +17,9 @@ #![deny(missing_docs)] +mod auth; mod config; +mod context; mod extension; mod route; @@ -27,3 +29,6 @@ pub use config::{ }; pub use extension::{GatewayAdapter, Rejection}; pub use route::{Methods, Route, RoutePath, SelectedRoute, MAX_ADMISSIONS, MAX_PATH_BYTES}; + +pub use auth::{is_untrusted_identity_header, Admission, AuthError, AuthProvider}; +pub use context::{BackendCredential, Credentials, Identity, RequestContext}; diff --git a/src/graphql/identity/gateway.rs b/src/graphql/identity/gateway.rs new file mode 100644 index 000000000..6e762214f --- /dev/null +++ b/src/graphql/identity/gateway.rs @@ -0,0 +1,68 @@ +//! Gateway provider using the existing OIDC validator and role mapping. +use super::{OidcConfig, OidcValidator}; +use crate::gateway::{ + AuthError, AuthProvider, BackendCredential, Credentials, Identity, RequestContext, +}; + +/// Strict bearer provider for public gateways. Ambient identity headers and +/// cookies cannot enter this adapter; use an explicit session provider for UI. +pub struct OidcGatewayProvider { + validator: OidcValidator, + revision: String, +} + +impl OidcGatewayProvider { + /// Reuse one validator/JWKS cache across all routes. The revision identifies + /// this provider configuration and must change when its policy changes. + pub fn new(config: OidcConfig, revision: impl Into) -> Self { + Self { + validator: OidcValidator::new(config), + revision: revision.into(), + } + } +} + +impl AuthProvider for OidcGatewayProvider { + async fn authenticate(&self, credentials: &Credentials) -> Result { + let Some(authorization) = &credentials.authorization else { + return RequestContext::from_provider(None, &self.revision, BackendCredential::None) + .map_err(|_| AuthError::Unavailable); + }; + let (scheme, token) = authorization + .trim() + .split_once(' ') + .ok_or(AuthError::Unauthorized)?; + let token = token.trim(); + if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() { + return Err(AuthError::Unauthorized); + } + let session = self + .validator + .validate_and_map_async(token) + .await + .map_err(|_| AuthError::Unauthorized)?; + // Use only verified claims for the lease; decoding an unverified JWT is + // never sufficient to certify subject, scope or expiry. The second + // validation reads the same cached keys, without another network fetch. + let claims = self + .validator + .validate_token(token) + .map_err(|_| AuthError::Unauthorized)?; + let issuer = claims["iss"].as_str().ok_or(AuthError::Unauthorized)?; + let subject = claims["sub"].as_str().ok_or(AuthError::Unauthorized)?; + let expires = claims["exp"].as_u64().ok_or(AuthError::Unauthorized)?; + let identity = Identity::verified( + issuer, + subject, + session.roles().into_iter().map(str::to_owned).collect(), + expires, + ) + .map_err(|_| AuthError::Unauthorized)?; + RequestContext::from_provider( + Some(identity), + &self.revision, + BackendCredential::Bearer(token.into()), + ) + .map_err(|_| AuthError::Unavailable) + } +} diff --git a/src/graphql/identity/mod.rs b/src/graphql/identity/mod.rs index 8d023a9ac..a53e18485 100644 --- a/src/graphql/identity/mod.rs +++ b/src/graphql/identity/mod.rs @@ -31,3 +31,8 @@ pub fn session_from_all_headers(headers: &HeaderMap) -> Session { } Session::from_map(vars) } + +#[cfg(feature = "gateway")] +mod gateway; +#[cfg(feature = "gateway")] +pub use gateway::OidcGatewayProvider; diff --git a/tests/e2e-ui/ui/src/auth.ts b/tests/e2e-ui/ui/src/auth.ts index 4ff763233..49e888ad0 100644 --- a/tests/e2e-ui/ui/src/auth.ts +++ b/tests/e2e-ui/ui/src/auth.ts @@ -1,4 +1,5 @@ import { SvelteKitAuth } from '@auth/sveltekit'; +import type { Handle } from '@sveltejs/kit'; import { env } from '$env/dynamic/private'; import { cleanEnvValue } from '$lib/clean-env'; import { oidcAudience, oidcScopes } from '$lib/server/oidc-scopes'; @@ -223,7 +224,7 @@ function userClaims(token: TokenRecord) { return decodeJwtPayload(token.idToken) ?? decodeJwtPayload(token.accessToken) ?? {}; } -export const { handle, signIn, signOut } = SvelteKitAuth({ +const { handle: authHandle, signIn, signOut } = SvelteKitAuth({ providers: [ { id: 'oidc', @@ -240,7 +241,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ scope: oidcScopes() } }, - checks: ['pkce', 'state'], + checks: ['pkce', 'state', 'nonce'], profile(profile: Record) { const groupClaims = envCsv('OIDC_GROUP_CLAIMS', DEFAULT_GROUP_CLAIMS); const name = @@ -262,7 +263,10 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ ], callbacks: { async jwt({ token, account, user, profile }) { + // Auth.js may assign an internal user UUID. UI and API identity must + // use the same OIDC subject established by the provider callback. if (account) { + token.sub = account.providerAccountId; token.accessToken = account.access_token; token.refreshToken = account.refresh_token; token.idToken = account.id_token; @@ -293,7 +297,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ if (groups.length) refreshed.groups = groups; return refreshed; } catch (error) { - console.error('Token refresh failed:', error); + console.error('Token refresh failed'); token.error = 'RefreshAccessTokenError'; return token; } @@ -347,10 +351,8 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ signIn: '/', error: '/' }, - // HARD false for this local fixture. Auth.js defaults secure from request - // protocol / AUTH_URL; on plain http://127.0.0.1 Secure cookies are dropped - // by the browser and every protected page looks broken (session never sticks). - // Production HTTPS deploys must set AUTH_USE_SECURE_COOKIES=true (or AUTH_URL=https…). + // Cookie overrides and Auth.js defaults share the configured public-origin + // policy. Local HTTP fixtures remain usable; HTTPS sets Secure throughout. useSecureCookies: useSecureCookies(), cookies: { sessionToken: { @@ -359,7 +361,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ httpOnly: true, sameSite: authSessionCookieSameSite(), path: '/', - secure: false + secure: useSecureCookies() } }, callbackUrl: { @@ -368,7 +370,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ httpOnly: true, sameSite: authSessionCookieSameSite(), path: '/', - secure: false + secure: useSecureCookies() } }, csrfToken: { @@ -377,7 +379,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ httpOnly: true, sameSite: authSessionCookieSameSite(), path: '/', - secure: false + secure: useSecureCookies() } }, pkceCodeVerifier: { @@ -386,7 +388,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ httpOnly: true, sameSite: authSessionCookieSameSite(), path: '/', - secure: false, + secure: useSecureCookies(), maxAge: 60 * 15 } }, @@ -396,7 +398,7 @@ export const { handle, signIn, signOut } = SvelteKitAuth({ httpOnly: true, sameSite: authSessionCookieSameSite(), path: '/', - secure: false, + secure: useSecureCookies(), maxAge: 60 * 15 } } @@ -474,3 +476,19 @@ async function oidcTokenEndpoint() { } export { engineRoleFromGroups } from './lib/roles'; + +// Auth.js session renewal parses Set-Cookie before calling event.cookies.set. +// An absent Secure attribute becomes undefined, which SvelteKit defaults to +// true on HTTP 127.0.0.1. Preserve our explicit policy during that delegation, +// including cookies renewed by locals.auth() on UI/API requests. +export const handle: Handle = ({ event, resolve }) => { + const setCookie = event.cookies.set.bind(event.cookies); + event.cookies.set = (name, value, options) => { + if (name.startsWith('authjs.')) { + return setCookie(name, value, { ...options, secure: useSecureCookies() }); + } + return setCookie(name, value, options); + }; + return authHandle({ event, resolve }); +}; +export { signIn, signOut }; diff --git a/tests/e2e-ui/ui/src/lib/server/require-auth.ts b/tests/e2e-ui/ui/src/lib/server/require-auth.ts index a6682d2b9..f3915576e 100644 --- a/tests/e2e-ui/ui/src/lib/server/require-auth.ts +++ b/tests/e2e-ui/ui/src/lib/server/require-auth.ts @@ -5,16 +5,23 @@ */ import { redirect } from '@sveltejs/kit'; +type AuthSession = { user?: unknown; error?: string; expiresAt?: number }; type AuthLocals = { - auth: () => Promise<{ user?: unknown } | null>; + auth: () => Promise; }; +/** Share the current-session check between protected UI and refresh/API routes. */ +export function isCurrentSession(session: AuthSession | null): session is AuthSession { + return !!session?.user && !session.error && + (session.expiresAt === undefined || session.expiresAt > Date.now() / 1000); +} + export async function requireAuth( event: { locals: AuthLocals; url: URL }, options?: { fallbackPath?: string } ): Promise>>> { const session = await event.locals.auth(); - if (session?.user) { + if (isCurrentSession(session)) { return session; } diff --git a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts index 33ef13f0f..8df2ffd75 100644 --- a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts +++ b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts @@ -1,11 +1,12 @@ import { json } from '@sveltejs/kit'; +import { isCurrentSession } from '$lib/server/require-auth'; import type { RequestHandler } from './$types'; export const POST: RequestHandler = async ({ locals }) => { const session = await locals.auth(); - if (!session?.user) { - return json({ authenticated: false }, { status: 401 }); + if (!isCurrentSession(session)) { + return json({ authenticated: false, error: session?.error }, { status: 401 }); } return json({ diff --git a/tests/gateway-auth/.gitignore b/tests/gateway-auth/.gitignore new file mode 100644 index 000000000..bbe82e0b0 --- /dev/null +++ b/tests/gateway-auth/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.svelte-kit/ +.generated/ +test-results/ +build/ diff --git a/tests/gateway-auth/README.md b/tests/gateway-auth/README.md new file mode 100644 index 000000000..4609129bc --- /dev/null +++ b/tests/gateway-auth/README.md @@ -0,0 +1,38 @@ +# Delegated auth fixture + +Run from this directory: + +```sh +npm ci +npx playwright install chromium +npm test +``` + +The runner builds and launches a production SvelteKit/adapter-node server and +an isolated, in-memory `oidc-provider`, then drives Chromium through actual +OIDC authorization-code, PKCE, state, nonce, refresh and logout flows. It checks +cross-origin CSRF rejection, failed refresh admission, missing state/nonce, +HTTP session renewal, and explicitly configured Secure cookies. Production +output matters: SvelteKit disables its origin check in the Vite development +server. Dependency versions and the complete npm lockfile are committed. + +`prepare.mjs` copies the application's current Auth.js configuration, claim +helpers, session admission and refresh handler from `tests/e2e-ui/ui/src` into +ignored `.generated/` files on every run. The fixture does not maintain an +independent auth implementation. A local fixture-only client secret and fresh +in-memory signing/session keys are used; no playground env file or remote IdP +is read or modified. Servers bind loopback on dynamically allocated ports and +are stopped on success or failure. Build output and node_modules are ignored. + +`startFixture()` and `exerciseAuth()` are reusable by native and Worker tests. +`GATEWAY_TEST_ORIGIN` names the public origin when another fixture owns ingress; +`uiOrigin` identifies the private Auth.js upstream. Configure the gateway to +delegate `/auth`, `/login`, `/logout` and `/api/auth` to that upstream. Preserve +independent Set-Cookie fields and reconstruct forwarded host/protocol from +configured public origin. Keep the browser's Origin header for CSRF validation. + +Application bindings use `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, +`AUTH_URL`, and `AUTH_SECRET`; values belong to the host secret/configuration +provider. The fixture supplies only local values through an explicit process +environment. Its memory-only provider and unconditional local consent policy +are test infrastructure, not a production identity service. diff --git a/tests/gateway-auth/package-lock.json b/tests/gateway-auth/package-lock.json new file mode 100644 index 000000000..e21c1d322 --- /dev/null +++ b/tests/gateway-auth/package-lock.json @@ -0,0 +1,2306 @@ +{ + "name": "gateway-auth-fixture", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "gateway-auth-fixture", + "dependencies": { + "@auth/core": "0.41.3", + "@auth/sveltekit": "1.11.3", + "@playwright/test": "1.61.1", + "@sveltejs/adapter-node": "5.2.12", + "@sveltejs/kit": "2.70.1", + "@sveltejs/vite-plugin-svelte": "5.1.1", + "oidc-provider": "9.12.2", + "svelte": "5.56.7", + "typescript": "5.8.3", + "vite": "6.4.3" + } + }, + "node_modules/@auth/core": { + "version": "0.41.3", + "resolved": "https://registry.npmjs.org/@auth/core/-/core-0.41.3.tgz", + "integrity": "sha512-sJ3JMHHkXMD3aOjopv7mOBTO1Ocw4b0fAEXJBz6k7YHLpYQI6C40jCUPc5fNvUKxXRXNE1/sRISA15UrwWJBTw==", + "license": "ISC", + "dependencies": { + "@panva/hkdf": "^1.2.1", + "jose": "^6.0.6", + "oauth4webapi": "^3.3.0", + "preact": "10.24.3", + "preact-render-to-string": "6.5.11" + }, + "peerDependencies": { + "@simplewebauthn/browser": "^9.0.1", + "@simplewebauthn/server": "^9.0.2", + "nodemailer": "^7.0.7 || ^8.0.5" + }, + "peerDependenciesMeta": { + "@simplewebauthn/browser": { + "optional": true + }, + "@simplewebauthn/server": { + "optional": true + }, + "nodemailer": { + "optional": true + } + } + }, + "node_modules/@auth/sveltekit": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@auth/sveltekit/-/sveltekit-1.11.3.tgz", + "integrity": "sha512-nfI/CFHD9hpJG4W+u+xtMrw9XSrA1k6kbgbGc9PvbiEf67oPMuzLAvLDj6/3yd98kFz+51Rq04JLBckKp8T5Kg==", + "license": "ISC", + "dependencies": { + "@auth/core": "0.41.3", + "set-cookie-parser": "^2.7.0" + }, + "peerDependencies": { + "@simplewebauthn/browser": "^9.0.1", + "@simplewebauthn/server": "^9.0.3", + "@sveltejs/kit": "^1.0.0 || ^2.0.0", + "nodemailer": "^7.0.7 || ^8.0.5", + "svelte": "^3.54.0 || ^4.0.0 || ^5.0.0-0" + }, + "peerDependenciesMeta": { + "@simplewebauthn/browser": { + "optional": true + }, + "@simplewebauthn/server": { + "optional": true + }, + "nodemailer": { + "optional": true + } + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@panva/hkdf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", + "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/@playwright/test": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.29", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", + "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==", + "license": "MIT" + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "28.0.9", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-28.0.9.tgz", + "integrity": "sha512-PIR4/OHZ79romx0BVVll/PkwWpJ7e5lsqFa3gFfcrFPWwLXLV39JVUzQV9RKjWerE7B845Hqjj9VYlQeieZ2dA==", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.1.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz", + "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz", + "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz", + "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz", + "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz", + "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz", + "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz", + "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz", + "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==", + "cpu": [ + "arm" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz", + "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz", + "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz", + "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==", + "cpu": [ + "loong64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz", + "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==", + "cpu": [ + "loong64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz", + "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz", + "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz", + "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz", + "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz", + "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz", + "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz", + "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz", + "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz", + "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz", + "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz", + "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz", + "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz", + "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/adapter-node": { + "version": "5.2.12", + "resolved": "https://registry.npmjs.org/@sveltejs/adapter-node/-/adapter-node-5.2.12.tgz", + "integrity": "sha512-0bp4Yb3jKIEcZWVcJC/L1xXp9zzJS4hDwfb4VITAkfT4OVdkspSHsx7YhqJDbb2hgLl6R9Vs7VQR+fqIVOxPUQ==", + "license": "MIT", + "dependencies": { + "@rollup/plugin-commonjs": "^28.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.0", + "rollup": "^4.9.5" + }, + "peerDependencies": { + "@sveltejs/kit": "^2.4.0" + } + }, + "node_modules/@sveltejs/kit": { + "version": "2.70.1", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.1.tgz", + "integrity": "sha512-nY9SPHGOZro3doud9vZXDBwl9tCZIouuJztjgSHs6PAIrv9M/z5O7eOhPV5xU7CgVHA976Jwu3BA1hIFvXztkA==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@sveltejs/acorn-typescript": "^1.0.9", + "@types/cookie": "^0.6.0", + "acorn": "^8.16.0", + "cookie": "^0.6.0", + "devalue": "^5.8.1", + "esm-env": "^1.2.2", + "kleur": "^4.1.5", + "magic-string": "^0.30.5", + "mrmime": "^2.0.0", + "set-cookie-parser": "^3.0.0", + "sirv": "^3.0.0" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "engines": { + "node": ">=18.13" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0", + "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.3.3 || ^6.0.0", + "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@sveltejs/kit/node_modules/set-cookie-parser": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz", + "integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==", + "license": "MIT" + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-5.1.1.tgz", + "integrity": "sha512-Y1Cs7hhTc+a5E9Va/xwKlAJoariQyHY+5zBgCZg4PFWNYQ1nMN9sjK1zhw1gK69DuqVP++sht/1GZg1aRwmAXQ==", + "license": "MIT", + "dependencies": { + "@sveltejs/vite-plugin-svelte-inspector": "^4.0.1", + "debug": "^4.4.1", + "deepmerge": "^4.3.1", + "kleur": "^4.1.5", + "magic-string": "^0.30.17", + "vitefu": "^1.0.6" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte-inspector": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-4.0.1.tgz", + "integrity": "sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.7" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.0", + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookies": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.9.1.tgz", + "integrity": "sha512-TG2hpqe4ELx54QER/S3HQ9SRVnQnGBtKUz5bLQWtYAQ+o6GpgMs6sYUvaiJjVxb+UXwhRhAEP3m7LbsIZ77Hmw==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==", + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT" + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/devalue": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.2.tgz", + "integrity": "sha512-po4PAY5c53tw5XMocSnf8A/5OHhbbUftpr93aEN6BBoAdntUmK7vu7wOATqvt7cXO7m1Cl4gMVn6p7n6n4mj0w==", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.7.tgz", + "integrity": "sha512-n2nf7fZR3c9yXf0BPEuHuXqT+KW0SJVj4cN5FMEkpCZ3scLjOQWpiccyCxVzCC2q1wubTghuEGzngJY/7Ah0Ow==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", + "license": "MIT", + "dependencies": { + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-assert/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "license": "MIT" + }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/koa": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/koa/-/koa-3.2.1.tgz", + "integrity": "sha512-e7IpWJrnanNUroVK2taAgMxoEZvHLXdQiNjeExSu/DEIWm83jaKGBgb7tLmu2rMYpA027qFB3iLR/k3AVpFRnA==", + "license": "MIT", + "dependencies": { + "accepts": "^1.3.8", + "content-disposition": "~1.0.1", + "content-type": "^1.0.5", + "cookies": "~0.9.1", + "delegates": "^1.0.0", + "destroy": "^1.2.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.5.0", + "http-errors": "^2.0.0", + "koa-compose": "^4.1.0", + "mime-types": "^3.0.1", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/koa-compose": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "license": "MIT" + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/oauth4webapi": { + "version": "3.8.8", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz", + "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/oidc-provider": { + "version": "9.12.2", + "resolved": "https://registry.npmjs.org/oidc-provider/-/oidc-provider-9.12.2.tgz", + "integrity": "sha512-UaqeVpeijTocxVbDowPqPKloGjb49bxRSzHfChyI86teR+6xxoiI1V5jv8CHL2AIUmA2rg0xTZcYaC9GguympA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "jose": "^6.2.10", + "koa": "^3.2.1" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "10.24.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz", + "integrity": "sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/preact-render-to-string": { + "version": "6.5.11", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.5.11.tgz", + "integrity": "sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==", + "license": "MIT", + "peerDependencies": { + "preact": ">=10" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", + "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.1", + "@rollup/rollup-android-arm64": "4.63.1", + "@rollup/rollup-darwin-arm64": "4.63.1", + "@rollup/rollup-darwin-x64": "4.63.1", + "@rollup/rollup-freebsd-arm64": "4.63.1", + "@rollup/rollup-freebsd-x64": "4.63.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.1", + "@rollup/rollup-linux-arm-musleabihf": "4.63.1", + "@rollup/rollup-linux-arm64-gnu": "4.63.1", + "@rollup/rollup-linux-arm64-musl": "4.63.1", + "@rollup/rollup-linux-loong64-gnu": "4.63.1", + "@rollup/rollup-linux-loong64-musl": "4.63.1", + "@rollup/rollup-linux-ppc64-gnu": "4.63.1", + "@rollup/rollup-linux-ppc64-musl": "4.63.1", + "@rollup/rollup-linux-riscv64-gnu": "4.63.1", + "@rollup/rollup-linux-riscv64-musl": "4.63.1", + "@rollup/rollup-linux-s390x-gnu": "4.63.1", + "@rollup/rollup-linux-x64-gnu": "4.63.1", + "@rollup/rollup-linux-x64-musl": "4.63.1", + "@rollup/rollup-openbsd-x64": "4.63.1", + "@rollup/rollup-openharmony-arm64": "4.63.1", + "@rollup/rollup-win32-arm64-msvc": "4.63.1", + "@rollup/rollup-win32-ia32-msvc": "4.63.1", + "@rollup/rollup-win32-x64-gnu": "4.63.1", + "@rollup/rollup-win32-x64-msvc": "4.63.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/sirv": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", + "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==", + "license": "MIT", + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svelte": { + "version": "5.56.7", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.7.tgz", + "integrity": "sha512-5qERUZX80oQj6XrDMUmD2Uhd/cIpCPDWWKBK3ZHmyRUC9apPyamWM8xMo31mbWsIQxwG2hVoSnOJ/EcnhVkkzQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.10", + "@types/estree": "^1.0.5", + "@types/trusted-types": "^2.0.7", + "acorn": "^8.12.1", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.8.1", + "esm-env": "^1.2.1", + "esrap": "^2.2.12", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "license": "MIT" + } + } +} diff --git a/tests/gateway-auth/package.json b/tests/gateway-auth/package.json new file mode 100644 index 000000000..f7fae0c8d --- /dev/null +++ b/tests/gateway-auth/package.json @@ -0,0 +1,21 @@ +{ + "name": "gateway-auth-fixture", + "private": true, + "type": "module", + "scripts": { + "prepare": "node prepare.mjs", + "test": "node run.mjs" + }, + "dependencies": { + "@auth/core": "0.41.3", + "@auth/sveltekit": "1.11.3", + "@playwright/test": "1.61.1", + "@sveltejs/adapter-node": "5.2.12", + "@sveltejs/kit": "2.70.1", + "@sveltejs/vite-plugin-svelte": "5.1.1", + "oidc-provider": "9.12.2", + "svelte": "5.56.7", + "typescript": "5.8.3", + "vite": "6.4.3" + } +} diff --git a/tests/gateway-auth/prepare.mjs b/tests/gateway-auth/prepare.mjs new file mode 100644 index 000000000..a333901b0 --- /dev/null +++ b/tests/gateway-auth/prepare.mjs @@ -0,0 +1,9 @@ +import { mkdir, copyFile } from 'node:fs/promises'; +// Exercise the app's actual Auth.js configuration and refresh handler. +for (const file of ['auth.ts', 'lib/clean-env.ts', 'lib/roles.ts', 'lib/server/oidc-scopes.ts', 'lib/server/oidc-start.ts', 'lib/server/require-auth.ts']) { + const target = `.generated/${file}`; + await mkdir(target.substring(0, target.lastIndexOf('/')), { recursive: true }); + await copyFile(`../e2e-ui/ui/src/${file}`, target); +} +await mkdir('src/routes/api/auth/refresh', { recursive: true }); +await copyFile('../e2e-ui/ui/src/routes/api/auth/refresh/+server.ts', '.generated/refresh.ts'); diff --git a/tests/gateway-auth/provider.mjs b/tests/gateway-auth/provider.mjs new file mode 100644 index 000000000..102b99847 --- /dev/null +++ b/tests/gateway-auth/provider.mjs @@ -0,0 +1,53 @@ +import { Provider } from 'oidc-provider'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { randomBytes } from 'node:crypto'; + +// An isolated, in-memory standards implementation. No external IdP or secrets. +export async function startProvider(issuer, publicOrigin) { + let refreshes = 0; + let failRefresh = false; + const provider = new Provider(issuer, { + clients: [{ client_id: 'gateway-fixture', client_secret: 'local-fixture-only', + redirect_uris: [`${publicOrigin}/auth/callback/oidc`], + response_types: ['code'], grant_types: ['authorization_code', 'refresh_token'], + token_endpoint_auth_method: 'client_secret_basic' }], + cookies: { keys: [randomBytes(32).toString('hex')] }, + features: { devInteractions: { enabled: false } }, + ttl: { AccessToken: 61 }, + async issueRefreshToken() { return true; }, + claims: { openid: ['sub'], profile: ['name'], email: ['email'] }, + async findAccount(_ctx, id) { + return { accountId: id, async claims() { return { sub: id, name: 'Alice', email: 'alice@example.invalid' }; } }; + }, + interactions: { url(_ctx, interaction) { return `/interaction/${interaction.uid}`; } }, + }); + provider.use(async (ctx, next) => { + if (ctx.path === '/token' && ctx.method === 'POST') { + // The grant event below counts actual successful refreshes. + if (failRefresh) { ctx.status = 400; ctx.body = { error: 'invalid_grant' }; return; } + } + await next(); + }); + provider.on('grant.success', ctx => { if (ctx.oidc.params.grant_type === 'refresh_token') refreshes++; }); + const server = createServer(async (req, res) => { + try { + if (req.url.startsWith('/interaction/')) { + const details = await provider.interactionDetails(req, res); + if (req.method === 'GET') { + res.setHeader('content-type', 'text/html'); + res.end('
'); return; + } + const grant = details.grantId ? await provider.Grant.find(details.grantId) : new provider.Grant({ accountId: 'alice', clientId: details.params.client_id }); + grant.addOIDCScope('openid profile email offline_access'); + const grantId = await grant.save(); + await provider.interactionFinished(req, res, { login: { accountId: 'alice' }, consent: { grantId } }, { mergeWithLastSubmission: true }); + return; + } + provider.callback()(req, res); + } catch { res.statusCode = 500; res.end('fixture provider failure'); } + }); + server.listen(Number(new URL(issuer).port), '127.0.0.1'); + await once(server, 'listening'); + return { server, refreshes: () => refreshes, failRefresh: () => { failRefresh = true; }, allowRefresh: () => { failRefresh = false; } }; +} diff --git a/tests/gateway-auth/run.mjs b/tests/gateway-auth/run.mjs new file mode 100644 index 000000000..ed4e211fe --- /dev/null +++ b/tests/gateway-auth/run.mjs @@ -0,0 +1,121 @@ +import './prepare.mjs'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { randomBytes } from 'node:crypto'; +import { pathToFileURL } from 'node:url'; +import { chromium } from '@playwright/test'; +import { startProvider } from './provider.mjs'; + +async function freePort() { + const server = createServer(); server.listen(0, '127.0.0.1'); await once(server, 'listening'); + const port = server.address().port; await new Promise(resolve => server.close(resolve)); return port; +} +export async function startFixture({ secureCookies = false } = {}) { + const uiPort = await freePort(); + const publicOrigin = process.env.GATEWAY_TEST_ORIGIN || `http://127.0.0.1:${uiPort}`; + const issuer = `http://127.0.0.1:${await freePort()}`; + const idp = await startProvider(issuer, publicOrigin); + // Explicit environment: do not load the playground's real credential files. + const build = spawn(process.execPath, ['node_modules/vite/bin/vite.js', 'build'], { env: { PATH: process.env.PATH, HOME: process.env.HOME, NODE_ENV: 'production' }, stdio: ['ignore', 'pipe', 'pipe'] }); + let buildLog = ''; + build.stdout.on('data', chunk => { buildLog = (buildLog + chunk).slice(-4000); }); + build.stderr.on('data', chunk => { buildLog = (buildLog + chunk).slice(-4000); }); + const [buildCode] = await once(build, 'exit'); + if (buildCode !== 0) { await new Promise(resolve => idp.server.close(resolve)); throw Error('Auth.js build failed: ' + buildLog); } + const ui = spawn(process.execPath, ['build/index.js'], { + env: { PATH: process.env.PATH, HOME: process.env.HOME, NODE_ENV: 'production', HOST: '127.0.0.1', PORT: String(uiPort), + OIDC_ISSUER: issuer, OIDC_CLIENT_ID: 'gateway-fixture', OIDC_CLIENT_SECRET: 'local-fixture-only', + AUTH_SECRET: randomBytes(32).toString('hex'), AUTH_URL: publicOrigin, ORIGIN: publicOrigin, + AUTH_USE_SECURE_COOKIES: String(secureCookies) }, stdio: ['ignore', 'pipe', 'pipe'] + }); + let log = ''; ui.stdout.on('data', chunk => { log = (log + chunk).slice(-6000); }); ui.stderr.on('data', chunk => { log = (log + chunk).slice(-6000); }); + const stop = async () => { + if (ui.exitCode === null) { ui.kill('SIGTERM'); await once(ui, 'exit'); } + await new Promise(resolve => idp.server.close(resolve)); + }; + try { + for (let i = 0; i < 100; i++) { + if (ui.exitCode !== null) throw Error('Auth.js process exited: ' + log); + try { if ((await fetch(`http://127.0.0.1:${uiPort}/`)).ok) return { publicOrigin, uiOrigin: `http://127.0.0.1:${uiPort}`, issuer, idp, stop, logs: () => log }; } catch {} + await new Promise(resolve => setTimeout(resolve, 200)); + } + throw Error('Auth.js readiness timed out: ' + log); + } catch (error) { await stop(); throw error; } +} + +export async function exerciseAuth(fixture) { + const { publicOrigin, idp } = fixture; + const browser = await chromium.launch(); + try { + const context = await browser.newContext(); + const page = await context.newPage(); + assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 401); + await page.goto(publicOrigin); + await page.getByRole('link', { name: 'Log in' }).click(); + await page.getByRole('button', { name: 'Continue as Alice' }).click(); + await page.waitForURL(publicOrigin + '/'); + assert.deepEqual(await (await context.request.get(`${publicOrigin}/private`)).json(), { subject: 'alice' }); + const cookies = await context.cookies(); + const sessionCookies = cookies.filter(c => c.name.startsWith('authjs.session-token')); + assert.ok(sessionCookies.length > 0); + assert.ok(sessionCookies.every(c => c.httpOnly && c.sameSite === 'Lax' && c.path === '/')); + assert.ok(cookies.every(c => !c.name.includes('code_verifier') && !c.name.includes('state') && !c.name.includes('nonce'))); + console.log('PASS callback, PKCE/state/nonce cleanup, session cookie, protected route'); + // The real provider issues a 61-second access token. Cross the app's existing + // 60-second refresh skew; no fake auth clock or forged session is involved. + await new Promise(resolve => setTimeout(resolve, 2200)); + const refreshed = await context.request.post(`${publicOrigin}/api/auth/refresh`, { headers: { origin: publicOrigin } }); + assert.equal(refreshed.status(), 200, JSON.stringify({ url: refreshed.url(), body: await refreshed.text(), cookies: (await context.cookies()).map(({name, expires, path}) => ({name, expires, path})), privateStatus: (await context.request.get(`${publicOrigin}/private`)).status() })); + const refreshBody = await refreshed.json(); + assert.equal(refreshBody.authenticated, true); + assert.equal(refreshBody.hasRefreshToken, true); + assert.equal(refreshBody.error, undefined); + assert.ok(idp.refreshes() > 0); + console.log('PASS delegated refresh against local OIDC token endpoint'); + const csrf = await context.request.post(`${publicOrigin}/logout`, { headers: { origin: 'https://attacker.invalid', 'content-type': 'application/x-www-form-urlencoded' }, data: '' }); + assert.equal(csrf.status(), 403); + assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 200); + idp.failRefresh(); + await new Promise(resolve => setTimeout(resolve, 2200)); + const failedRefresh = await context.request.post(`${publicOrigin}/api/auth/refresh`, { headers: { origin: publicOrigin } }); + assert.equal(failedRefresh.status(), 401); + assert.equal((await failedRefresh.json()).error, 'RefreshAccessTokenError'); + assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 401); + console.log('PASS failed refresh denies protected UI/API'); + await page.getByRole('button', { name: 'Log out' }).click(); + await page.waitForURL(publicOrigin + '/'); + assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 401); + console.log('PASS cross-origin CSRF rejection and delegated logout'); + await context.close(); + idp.allowRefresh(); + // Removing the state/nonce cookies before callback must never establish a session. + for (const removed of ['state', 'nonce']) { + const bad = await browser.newContext(); const badPage = await bad.newPage(); + await badPage.goto(`${publicOrigin}/login`); + await badPage.getByRole('button', { name: 'Continue as Alice' }).waitFor(); + await bad.clearCookies({ name: new RegExp(removed) }); + await badPage.getByRole('button', { name: 'Continue as Alice' }).click(); + await badPage.waitForURL(url => url.origin === publicOrigin); + assert.equal((await bad.request.get(`${publicOrigin}/private`)).status(), 401); + await bad.close(); + console.log(`PASS missing ${removed} rejects callback`); + } + } finally { await browser.close(); } +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const fixture = await startFixture(); + try { await exerciseAuth(fixture); } + catch (error) { console.error(fixture.logs()); throw error; } + finally { await fixture.stop(); } + const secure = await startFixture({ secureCookies: true }); + try { + const response = await fetch(`${secure.uiOrigin}/login`, { redirect: 'manual' }); + assert.equal(response.status, 302); + const cookies = response.headers.getSetCookie(); + assert.ok(cookies.length >= 3); + assert.ok(cookies.every(cookie => /; Secure(?:;|$)/i.test(cookie))); + console.log('PASS explicit secure-cookie policy survives Auth.js delegation'); + } finally { await secure.stop(); } +} diff --git a/tests/gateway-auth/src/app.html b/tests/gateway-auth/src/app.html new file mode 100644 index 000000000..b42f8d00d --- /dev/null +++ b/tests/gateway-auth/src/app.html @@ -0,0 +1 @@ +%sveltekit.head%
%sveltekit.body%
diff --git a/tests/gateway-auth/src/hooks.server.ts b/tests/gateway-auth/src/hooks.server.ts new file mode 100644 index 000000000..95ddcd38a --- /dev/null +++ b/tests/gateway-auth/src/hooks.server.ts @@ -0,0 +1 @@ +export { handle } from '../.generated/auth'; diff --git a/tests/gateway-auth/src/routes/+page.svelte b/tests/gateway-auth/src/routes/+page.svelte new file mode 100644 index 000000000..2214edd45 --- /dev/null +++ b/tests/gateway-auth/src/routes/+page.svelte @@ -0,0 +1 @@ +

Gateway auth fixture

Log in
diff --git a/tests/gateway-auth/src/routes/api/auth/refresh/+server.ts b/tests/gateway-auth/src/routes/api/auth/refresh/+server.ts new file mode 100644 index 000000000..9399b3f32 --- /dev/null +++ b/tests/gateway-auth/src/routes/api/auth/refresh/+server.ts @@ -0,0 +1 @@ +export { POST } from '../../../../../.generated/refresh'; diff --git a/tests/gateway-auth/src/routes/login/+server.ts b/tests/gateway-auth/src/routes/login/+server.ts new file mode 100644 index 000000000..85469e4cd --- /dev/null +++ b/tests/gateway-auth/src/routes/login/+server.ts @@ -0,0 +1,2 @@ +import { startOidcSignIn } from '$lib/server/oidc-start'; +export async function GET(event) { return startOidcSignIn(event); } diff --git a/tests/gateway-auth/src/routes/logout/+server.ts b/tests/gateway-auth/src/routes/logout/+server.ts new file mode 100644 index 000000000..127e6fba2 --- /dev/null +++ b/tests/gateway-auth/src/routes/logout/+server.ts @@ -0,0 +1,2 @@ +import { signOut } from '../../../.generated/auth'; +export async function POST(event) { return signOut(event); } diff --git a/tests/gateway-auth/src/routes/private/+server.ts b/tests/gateway-auth/src/routes/private/+server.ts new file mode 100644 index 000000000..39811f672 --- /dev/null +++ b/tests/gateway-auth/src/routes/private/+server.ts @@ -0,0 +1,6 @@ +import { json } from '@sveltejs/kit'; +import { isCurrentSession } from '$lib/server/require-auth'; +export async function GET({ locals }) { + const session = await locals.auth(); + return isCurrentSession(session) ? json({ subject: session.user.id }) : json({ error: 'unauthorized' }, { status: 401 }); +} diff --git a/tests/gateway-auth/svelte.config.js b/tests/gateway-auth/svelte.config.js new file mode 100644 index 000000000..7f0871745 --- /dev/null +++ b/tests/gateway-auth/svelte.config.js @@ -0,0 +1,2 @@ +import adapter from '@sveltejs/adapter-node'; +export default { kit: { adapter: adapter(), files: { lib: './.generated/lib' } } }; diff --git a/tests/gateway-auth/vite.config.js b/tests/gateway-auth/vite.config.js new file mode 100644 index 000000000..b13a59513 --- /dev/null +++ b/tests/gateway-auth/vite.config.js @@ -0,0 +1,3 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; +export default defineConfig({ plugins: [sveltekit()], server: { host: '127.0.0.1', strictPort: true } }); diff --git a/tests/gateway-portable/Cargo.toml b/tests/gateway-portable/Cargo.toml index 1c57af6a4..6a5554ce7 100644 --- a/tests/gateway-portable/Cargo.toml +++ b/tests/gateway-portable/Cargo.toml @@ -23,3 +23,7 @@ path = "../gateway_routing.rs" [[test]] name = "gateway_extensions" path = "../gateway_extensions.rs" + +[[test]] +name = "gateway_auth" +path = "../gateway_auth.rs" diff --git a/tests/gateway_auth.rs b/tests/gateway_auth.rs new file mode 100644 index 000000000..2f93be139 --- /dev/null +++ b/tests/gateway_auth.rs @@ -0,0 +1,115 @@ +#![cfg(feature = "gateway")] +mod gateway_support; +use distributed::gateway::*; +use gateway_support::run; + +struct Provider { + revision: &'static str, +} +impl AuthProvider for Provider { + async fn authenticate(&self, credentials: &Credentials) -> Result { + let (identity, backend) = match credentials.authorization.as_deref() { + None => (None, BackendCredential::None), + Some("valid") | Some("expired") => ( + Some( + Identity::verified( + "issuer", + "alice", + vec!["user".into()], + if credentials.authorization.as_deref() == Some("expired") { + 10 + } else { + 100 + }, + ) + .unwrap(), + ), + BackendCredential::Bearer("validated-token".into()), + ), + _ => return Err(AuthError::Unauthorized), + }; + Ok(RequestContext::from_provider(identity, self.revision, backend).unwrap()) + } +} + +#[test] +fn shared_context_and_delegated_handlers() { + let provider = Provider { revision: "v1" }; + let anonymous = run(provider.authenticate(&Credentials::default())).unwrap(); + assert_eq!(Admission::Public.check(&anonymous, 20), Ok(())); + assert_eq!( + Admission::Authenticated.check(&anonymous, 20), + Err(AuthError::Unauthorized) + ); + let credentials = Credentials { + authorization: Some("valid".into()), + cookie: None, + }; + let context = run(provider.authenticate(&credentials)).unwrap(); + for _route in ["UI", "API", "custom", "protected-assets"] { + assert_eq!(Admission::Authenticated.check(&context, 20), Ok(())); + assert_eq!(context.identity().unwrap().subject(), "alice"); + } + // Route admission is not backend authorization; a more privileged action + // still fails its own policy after successful gateway admission. + assert_eq!( + Admission::Role("admin".into()).check(&context, 20), + Err(AuthError::Forbidden) + ); + let replacement = run(Provider { revision: "v2" }.authenticate(&credentials)).unwrap(); + assert_ne!(context.provider_revision(), replacement.provider_revision()); + assert!(run(provider.authenticate(&Credentials { + authorization: Some("invalid".into()), + cookie: None + })) + .is_err()); + let expired = run(provider.authenticate(&Credentials { + authorization: Some("expired".into()), + cookie: None, + })) + .unwrap(); + assert_eq!( + Admission::Public.check(&expired, 20), + Err(AuthError::Unauthorized) + ); + assert_eq!( + Admission::Authenticated.check(&context, 100), + Err(AuthError::Unauthorized) + ); +} + +#[test] +fn credentials_and_assertions_cannot_leak_or_be_guessed() { + let credentials = Credentials { + authorization: Some("secret-token".into()), + cookie: Some("session-secret".into()), + }; + let debug = format!( + "{credentials:?} {:?}", + BackendCredential::Bearer("secret-token".into()) + ); + assert!(!debug.contains("secret-token")); + assert!(!debug.contains("session-secret")); + assert!( + RequestContext::from_provider(None, "v1", BackendCredential::Bearer("token".into())) + .is_err() + ); + for name in [ + "X-User-Id", + "X-Roles", + "X-Hasura-Allowed-Roles", + "Forwarded", + "X-Forwarded-Host", + "CF-Access-Jwt-Assertion", + ] { + assert!(is_untrusted_identity_header(name)); + } + assert!(!is_untrusted_identity_header("content-type")); + // A bearer-only provider cannot promote a session cookie into a token. + let context = run(Provider { revision: "v1" }.authenticate(&Credentials { + authorization: None, + cookie: Some("valid".into()), + })) + .unwrap(); + assert!(context.identity().is_none()); +} diff --git a/tests/graphql_identity/main.rs b/tests/graphql_identity/main.rs index c13c6c87b..1e2906f30 100644 --- a/tests/graphql_identity/main.rs +++ b/tests/graphql_identity/main.rs @@ -913,3 +913,67 @@ fn gateway_secret_wrong_is_401() { AuthError::Unauthorized ); } + +#[cfg(feature = "gateway")] +#[tokio::test] +async fn gateway_oidc_context_keeps_backend_authority() { + use distributed::gateway::{Admission, AuthProvider, BackendCredential, Credentials}; + use distributed::graphql::identity::OidcGatewayProvider; + let keys = mint_keys(); + let claims = json!({ "iss": "http://localhost:8080", "aud": "graphql-api", "sub": "user-a-001", "exp": now() + 3600, "iat": now(), "groups": ["customer", "unmapped"] }); + let token = sign_claims(&keys, claims.clone()); + let provider = OidcGatewayProvider::new(oidc_cfg(&keys), "oidc-v1"); + let credentials = Credentials { + authorization: Some(format!("Bearer {token}")), + cookie: Some("forged-session".into()), + }; + let context = provider.authenticate(&credentials).await.unwrap(); + assert_eq!(Admission::Authenticated.check(&context, now()), Ok(())); + assert_eq!(context.identity().unwrap().subject(), "user-a-001"); + assert_eq!(context.identity().unwrap().roles(), &["customer"]); + let BackendCredential::Bearer(forwarded) = context.backend_credential() else { + panic!("explicit bearer") + }; + assert_eq!(forwarded, &token); + + // A valid gateway assertion does not suppress backend credential checks. + let mut backend = oidc_cfg(&keys); + backend.audience = "another-api".into(); + let app = graphql_router(engine_with_identity(IdentityConfig::oidc_bearer(backend)).await); + let response = app + .oneshot( + axum::http::Request::builder() + .method("POST") + .uri("/graphql") + .header("content-type", "application/json") + .header("authorization", format!("Bearer {forwarded}")) + .header("x-user-id", "admin") + .body(axum::body::Body::from(r#"{"query":"{ id_items { id } }"}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), axum::http::StatusCode::UNAUTHORIZED); + + for replacement in [ + "invalid".to_string(), + sign_claims(&keys, { + let mut expired = claims; + expired["exp"] = json!(now() - 3600); + expired + }), + ] { + assert!(provider + .authenticate(&Credentials { + authorization: Some(format!("Bearer {replacement}")), + cookie: None + }) + .await + .is_err()); + } + let anon = provider + .authenticate(&Credentials::default()) + .await + .unwrap(); + assert!(anon.identity().is_none()); +} From b593d5d7262397df8faf038491dc6c7ea7256b7c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 20:56:48 -0500 Subject: [PATCH 051/484] feat: add native streaming application gateway Implements [[tasks/application-gateway-4]] in [[tasks/application-gateway-1]]. --- .github/workflows/integration-gateway.yaml | 18 + Cargo.toml | 7 +- src/gateway/README.md | 30 + src/gateway/config.rs | 2 +- src/gateway/mod.rs | 4 + src/gateway/native/assets.rs | 70 + src/gateway/native/mod.rs | 387 ++++ src/gateway/native/proxy.rs | 230 ++ tests/gateway-native/.gitignore | 2 + tests/gateway-native/Cargo.lock | 2352 ++++++++++++++++++++ tests/gateway-native/Cargo.toml | 27 + tests/gateway-native/README.md | 25 + tests/gateway-native/check_dependencies.py | 10 + tests/gateway-native/src/lib.rs | 2 + tests/gateway_ui.rs | 592 +++++ 15 files changed, 3756 insertions(+), 2 deletions(-) create mode 100644 src/gateway/native/assets.rs create mode 100644 src/gateway/native/mod.rs create mode 100644 src/gateway/native/proxy.rs create mode 100644 tests/gateway-native/.gitignore create mode 100644 tests/gateway-native/Cargo.lock create mode 100644 tests/gateway-native/Cargo.toml create mode 100644 tests/gateway-native/README.md create mode 100644 tests/gateway-native/check_dependencies.py create mode 100644 tests/gateway-native/src/lib.rs create mode 100644 tests/gateway_ui.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index e7d6f6e0d..85dfa2996 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -67,3 +67,21 @@ jobs: - name: Run production Auth.js lifecycle and browser security cases working-directory: tests/gateway-auth run: npm test + + native: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + components: clippy + - name: Test real native HTTP streams and upgrades + run: cargo test --manifest-path tests/gateway-native/Cargo.toml --locked + - name: Check native fixture lints + run: cargo clippy --manifest-path tests/gateway-native/Cargo.toml --locked --all-targets -- -D warnings + - name: Verify UI/auth executor dependency isolation + run: python3 tests/gateway-native/check_dependencies.py diff --git a/Cargo.toml b/Cargo.toml index 6981211d2..c1005cca1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,8 @@ default = [] application-runtime = [] # Portable gateway declarations and dispatch only; runtime adapters are separate. gateway = ["dep:url"] +# Native HTTP adapter remains independent of GraphQL and SQL. +gateway-native = ["gateway", "http", "reqwest/stream", "dep:hyper", "dep:hyper-util", "dep:tower", "tokio/io-util"] runtime = ["application-runtime"] emitter = ["dep:event-emitter-rs"] metrics = [] @@ -57,6 +59,9 @@ async-trait = "0.1" async-graphql = { version = "7", optional = true } async-graphql-axum = { version = "7", optional = true } axum = { version = "0.8", optional = true } +hyper = { version = "1", features = ["http1", "server"], optional = true } +hyper-util = { version = "0.1", features = ["tokio"], optional = true } +tower = { version = "0.5", features = ["util"], optional = true } base64 = "0.23.0" futures = { version = "0.3", optional = true } lapin = { version = "4", optional = true } @@ -95,7 +100,7 @@ sha2 = "0.10" tonic-build = { version = "0.14", default-features = false, features = ["transport"] } [dev-dependencies] -axum = "0.8" +axum = { version = "0.8", features = ["ws"] } distributed_cli = { path = "distributed_cli" } tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" diff --git a/src/gateway/README.md b/src/gateway/README.md index b55dea8d9..3592db387 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -26,3 +26,33 @@ The reusable production Auth.js/OIDC/browser fixture is in plumbing; merely declaring routes or providers starts no service or identity store. Removing a gateway mount restores the application's prior entrypoints; backend authentication stays enabled. + +## Native HTTP adapter + +Enable `gateway-native` and construct `NativeGateway` from a validated gateway, +`NativeOptions`, explicit named `NativeBinding` resources and `NativeAuth`. +Mount its `router()` on the application's existing listener. Local handlers +receive `RequestContext` through Axum request extensions. UI proxy targets come +from the portable declaration; callers cannot select upstream URLs. + +Use the real public origin in `NativeOptions::new`. Incoming identity and +forwarded headers are stripped; Host and forwarded host/protocol are rebuilt +from this value, while Origin is preserved for CSRF. Add deployment-specific +identity/secret header names to `strip_headers`. Upstream redirects are returned +to the browser, with private-origin locations mapped to public origin. The +proxy disables retries, automatic redirects, environment proxies and automatic +response decompression. Duplicate Set-Cookie values remain separate. + +`ProxyLimits` bounds request bytes, active proxy streams, connect/header wait, +read idle time and upgraded-connection lifetime. Known oversize requests return +413; over-limit streamed uploads terminate rather than being retried. Capacity +exhaustion returns 503. Response bytes stream without a whole-body buffer; +dropping the body releases capacity and cancels its upstream stream. WebSocket +upgrades require an explicit target opt-in and close on disconnect, identity +expiry or configured lifetime. Exact public-origin loops fail construction; +a bounded hop chain also detects loops through aliases at runtime. + +`StaticAssets` validates an immutable preloaded path/byte inventory and memory +budget. Protected assets run normal admission before lookup. It performs no +caller-selected filesystem access. Native construction starts no listener, +projector or event consumer. Disabling this mount restores previous entrypoints. diff --git a/src/gateway/config.rs b/src/gateway/config.rs index e5658e309..a0f761263 100644 --- a/src/gateway/config.rs +++ b/src/gateway/config.rs @@ -291,7 +291,7 @@ fn validate_binding(kind: &BindingKind) -> Result<(), GatewayError> { Ok(()) } -fn validate_origin(origin: &str) -> Result<(), GatewayError> { +pub(crate) fn validate_origin(origin: &str) -> Result<(), GatewayError> { let invalid = GatewayError( "binding requires an absolute HTTP(S) origin without credentials, path, query or fragment", ); diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 7dbed2d18..49e827066 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -32,3 +32,7 @@ pub use route::{Methods, Route, RoutePath, SelectedRoute, MAX_ADMISSIONS, MAX_PA pub use auth::{is_untrusted_identity_header, Admission, AuthError, AuthProvider}; pub use context::{BackendCredential, Credentials, Identity, RequestContext}; + +/// Native HTTP routing, streaming proxy and static asset adapter. +#[cfg(feature = "gateway-native")] +pub mod native; diff --git a/src/gateway/native/assets.rs b/src/gateway/native/assets.rs new file mode 100644 index 000000000..026f5dd72 --- /dev/null +++ b/src/gateway/native/assets.rs @@ -0,0 +1,70 @@ +use super::{response, Body, GatewayError, HeaderValue, Request, Response, StatusCode}; +use axum::http::header; +use std::{collections::BTreeMap, sync::Arc}; + +/// Preloaded asset with explicit response content type. +#[derive(Clone)] +pub struct Asset { + /// Bytes stored once and shared between responses. + pub bytes: axum::body::Bytes, + /// Trusted application-selected content type. + pub content_type: HeaderValue, +} +/// Immutable bounded static inventory. There is no fallback filesystem path, +/// symlink traversal or directory listing. Route policy runs before lookup. +#[derive(Clone)] +pub struct StaticAssets(Arc>); +impl StaticAssets { + /// Validate canonical paths, duplicate entries and a total memory budget. + pub fn new( + assets: impl IntoIterator, + max_bytes: usize, + ) -> Result { + let mut inventory = BTreeMap::new(); + let mut bytes = 0usize; + for (path, asset) in assets { + let normalized = super::super::route::normalize_path(&path)?; + if path != normalized || inventory.len() >= 16384 { + return Err(GatewayError("invalid static asset inventory")); + } + bytes = bytes + .checked_add(asset.bytes.len()) + .ok_or(GatewayError("asset inventory too large"))?; + if bytes > max_bytes || inventory.insert(path, asset).is_some() { + return Err(GatewayError("asset inventory budget or duplicate")); + } + } + Ok(Self(Arc::new(inventory))) + } + pub(super) fn serve(&self, request: Request) -> Response { + if request.method() != "GET" && request.method() != "HEAD" { + let mut result = response(StatusCode::METHOD_NOT_ALLOWED); + result + .headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("GET, HEAD")); + return result; + } + let Ok(path) = super::super::route::normalize_path(request.uri().path()) else { + return response(StatusCode::BAD_REQUEST); + }; + let Some(asset) = self.0.get(&path) else { + return response(StatusCode::NOT_FOUND); + }; + let mut result = response(StatusCode::OK); + result + .headers_mut() + .insert(header::CONTENT_TYPE, asset.content_type.clone()); + result.headers_mut().insert( + header::CONTENT_LENGTH, + HeaderValue::from_str(&asset.bytes.len().to_string()).expect("usize header"), + ); + result.headers_mut().insert( + "x-content-type-options", + HeaderValue::from_static("nosniff"), + ); + if request.method() != "HEAD" { + *result.body_mut() = Body::from(asset.bytes.clone()); + } + result + } +} diff --git a/src/gateway/native/mod.rs b/src/gateway/native/mod.rs new file mode 100644 index 000000000..4c3764a09 --- /dev/null +++ b/src/gateway/native/mod.rs @@ -0,0 +1,387 @@ +//! Opt-in native HTTP gateway. Construction starts no listener or projector. +mod assets; +mod proxy; + +use super::{ + Admission, AuthError, BackendCredential, BindingKind, Credentials, Gateway, GatewayAdapter, + GatewayError, Rejection, RequestContext, SelectedRoute, +}; +pub use assets::{Asset, StaticAssets}; +use axum::{ + body::Body, + extract::State, + http::{header, HeaderMap, HeaderName, HeaderValue, Request, StatusCode}, + response::Response, + Router, +}; +use std::{ + collections::BTreeMap, + future::Future, + pin::Pin, + sync::Arc, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::sync::Semaphore; +use tower::ServiceExt; +use url::Url; + +/// Boxed native provider result. Providers receive credentials, never identity +/// headers. Use one shared validator/session provider for all route owners. +type AuthFuture = Pin> + Send>>; + +/// Native provider registry entry. Worker adapters can use the local-future +/// portable AuthProvider trait without this Send/Sync runtime requirement. +#[derive(Clone)] +pub struct NativeAuth(Arc AuthFuture + Send + Sync>); +impl NativeAuth { + /// Adapt a configured native provider; the closure runs on every request. + pub fn new(provider: F) -> Self + where + F: Fn(Credentials) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + { + Self(Arc::new(move |credentials| Box::pin(provider(credentials)))) + } + /// Gateway without identity admission. Cookies remain opaque for delegated + /// UI/auth handlers; bearer credentials fail closed rather than being trusted. + pub fn anonymous() -> Self { + Self::new(|credentials| async move { + if credentials.authorization.is_some() { + return Err(AuthError::Unauthorized); + } + RequestContext::from_provider(None, "anonymous-v1", BackendCredential::None) + .map_err(|_| AuthError::Unavailable) + }) + } +} + +/// Explicit proxy resource limits, shared by all mounted targets. +#[derive(Clone, Debug)] +pub struct ProxyLimits { + /// Maximum incoming body size. Known oversize bodies fail before forwarding. + pub request_body_bytes: usize, + /// Maximum active HTTP streams and upgraded connections; overload gets 503. + pub concurrent_requests: usize, + /// Connect and response-header wait bound. + pub response_header_timeout: Duration, + /// Idle time between response reads; no whole-response buffering. + pub read_timeout: Duration, + /// Maximum upgraded-connection lifetime, also capped by identity expiry. + pub upgrade_lifetime: Duration, +} +impl Default for ProxyLimits { + fn default() -> Self { + Self { + request_body_bytes: 16 * 1024 * 1024, + concurrent_requests: 1024, + response_header_timeout: Duration::from_secs(30), + read_timeout: Duration::from_secs(60), + upgrade_lifetime: Duration::from_secs(3600), + } + } +} + +/// Host configuration. The public origin is trusted configuration, not Host or +/// forwarded headers from a request. Upstreams cannot point back to this origin. +#[derive(Clone, Debug)] +pub struct NativeOptions { + /// Absolute HTTP(S) public origin, without path or credentials. + pub public_origin: String, + /// Resource limits applied before/throughout forwarding. + pub limits: ProxyLimits, + /// Deployment-specific incoming identity/secret names to strip in addition + /// to the framework denylist. Values never appear in configuration errors. + pub strip_headers: Vec, +} +impl NativeOptions { + /// Default bounded proxy settings for this public origin. + pub fn new(public_origin: impl Into) -> Self { + Self { + public_origin: public_origin.into(), + limits: ProxyLimits::default(), + strip_headers: Vec::new(), + } + } +} + +/// Runtime resource for one portable binding. Duplicate or incompatible binding +/// entries are rejected before serving. Application handlers receive admitted +/// RequestContext in request extensions; backend authorization stays theirs. +#[derive(Clone)] +pub enum NativeBinding { + /// Complete application router; URI is preserved, without prefix stripping. + Handler(Router), + /// Configured UI proxy. Upgrades are disabled unless explicitly selected. + UiProxy { + /// Whether this target may negotiate a WebSocket upgrade. + websocket: bool, + }, + /// Bounded, preloaded static inventory; no request-selected filesystem I/O. + Assets(StaticAssets), + /// Named route admission policy. + Admission(Admission), +} + +/// Validated native adapter, shareable between explicit application mounts. +#[derive(Clone)] +pub struct NativeGateway(Arc); +struct NativeInner { + gateway: Gateway, + options: NativeOptions, + origin: Url, + bindings: BTreeMap, + auth: NativeAuth, + client: reqwest::Client, + permits: Arc, + hop_id: String, +} + +impl NativeGateway { + /// Validate runtime bindings and construct only the selected adapter. Caller + /// owns the listener/process lifecycle; this method opens no connections. + pub fn new( + gateway: Gateway, + options: NativeOptions, + bindings: impl IntoIterator, + auth: NativeAuth, + ) -> Result { + super::config::validate_origin(&options.public_origin)?; + let origin = Url::parse(&options.public_origin) + .map_err(|_| GatewayError("invalid public origin"))?; + let limits = &options.limits; + if limits.request_body_bytes == 0 + || limits.concurrent_requests == 0 + || limits.concurrent_requests > 65536 + || limits.response_header_timeout.is_zero() + || limits.read_timeout.is_zero() + || limits.upgrade_lifetime.is_zero() + { + return Err(GatewayError("invalid native proxy limits")); + } + if options.strip_headers.len() > 128 + || options + .strip_headers + .iter() + .any(|name| HeaderName::from_bytes(name.as_bytes()).is_err()) + { + return Err(GatewayError("invalid identity header strip list")); + } + let mut registry = BTreeMap::new(); + for (id, binding) in bindings { + let declaration = gateway + .binding(&id) + .ok_or(GatewayError("undeclared native binding"))?; + let compatible = matches!( + (&declaration.kind, &binding), + (BindingKind::Handler, NativeBinding::Handler(_)) + | (BindingKind::UiProxy { .. }, NativeBinding::UiProxy { .. }) + | (BindingKind::Assets, NativeBinding::Assets(_)) + | (BindingKind::Admission, NativeBinding::Admission(_)) + ); + if !compatible { + return Err(GatewayError("incompatible native binding")); + } + if let BindingKind::UiProxy { origin: upstream } = &declaration.kind { + let upstream = + Url::parse(upstream).map_err(|_| GatewayError("invalid upstream"))?; + if upstream.origin() == origin.origin() { + return Err(GatewayError("upstream points to public gateway")); + } + } + if registry.insert(id, binding).is_some() { + return Err(GatewayError("duplicate native binding")); + } + } + for route in gateway.routes() { + for id in std::iter::once(&route.target).chain(&route.admission) { + if !registry.contains_key(id) { + return Err(GatewayError("missing native runtime binding")); + } + } + } + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .no_proxy() + .no_gzip() + .no_brotli() + .no_deflate() + .no_zstd() + .connect_timeout(limits.response_header_timeout) + .read_timeout(limits.read_timeout) + .build() + .map_err(|_| GatewayError("cannot construct proxy client"))?; + let permits = Arc::new(Semaphore::new(limits.concurrent_requests)); + Ok(Self(Arc::new(NativeInner { + gateway, + options, + origin, + bindings: registry, + auth, + client, + permits, + hop_id: uuid::Uuid::now_v7().to_string(), + }))) + } + + /// Mount on the application's HTTP server. Every path goes through portable + /// selection/admission before an application handler or proxy executes. + pub fn router(self) -> Router { + Router::new().fallback(Self::handle).with_state(self) + } + + async fn handle(State(this): State, request: Request) -> Response { + if let Some(hops) = request.headers().get("x-distributed-gateway-hops") { + let Ok(hops) = hops.to_str() else { + return response(StatusCode::BAD_REQUEST); + }; + if hops.len() > 512 + || hops.split(',').count() >= 8 + || hops.split(',').any(|hop| hop.trim() == this.0.hop_id) + { + return response(StatusCode::LOOP_DETECTED); + } + } + this.0.gateway.dispatch(&this, request).await + } +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(u64::MAX, |d| d.as_secs()) +} +fn response(status: StatusCode) -> Response { + Response::builder() + .status(status) + .body(Body::empty()) + .expect("static response") +} +fn auth_response(error: AuthError) -> Response { + response(match error { + AuthError::Unauthorized => StatusCode::UNAUTHORIZED, + AuthError::Forbidden => StatusCode::FORBIDDEN, + AuthError::Unavailable => StatusCode::SERVICE_UNAVAILABLE, + }) +} + +fn credentials(headers: &HeaderMap) -> Result { + let mut authorization = headers.get_all(header::AUTHORIZATION).iter(); + let authorization_value = authorization + .next() + .map(|v| v.to_str().map(str::to_owned)) + .transpose() + .map_err(|_| AuthError::Unauthorized)?; + if authorization.next().is_some() { + return Err(AuthError::Unauthorized); + } + let cookies = headers + .get_all(header::COOKIE) + .iter() + .map(|v| v.to_str()) + .collect::, _>>() + .map_err(|_| AuthError::Unauthorized)?; + if authorization_value.as_ref().map_or(0, String::len) + + cookies.iter().map(|v| v.len()).sum::() + > 32768 + { + return Err(AuthError::Unauthorized); + } + Ok(Credentials { + authorization: authorization_value, + cookie: if cookies.is_empty() { + None + } else { + Some(cookies.join("; ")) + }, + }) +} + +impl GatewayAdapter for NativeGateway { + type Request = Request; + type Context = RequestContext; + type Response = Response; + fn method<'a>(&self, request: &'a Self::Request) -> &'a str { + request.method().as_str() + } + fn target<'a>(&self, request: &'a Self::Request) -> &'a str { + request.uri().path_and_query().map_or("/", |p| p.as_str()) + } + fn admit( + &self, + selected: SelectedRoute<'_>, + request: &Self::Request, + ) -> impl Future> { + // Own credential metadata before awaiting. A streaming HTTP Body is + // Send but not Sync, so never retain &Request across provider I/O. + let credentials = credentials(request.headers()); + let auth = self.0.auth.clone(); + let policies: Vec<_> = selected + .route() + .admission + .iter() + .filter_map(|name| match self.0.bindings.get(name) { + Some(NativeBinding::Admission(policy)) => Some(policy.clone()), + _ => None, + }) + .collect(); + async move { + let context = (auth.0)(credentials.map_err(auth_response)?) + .await + .map_err(auth_response)?; + Admission::Public + .check(&context, now()) + .map_err(auth_response)?; + for policy in policies { + policy.check(&context, now()).map_err(auth_response)?; + } + Ok(context) + } + } + async fn execute( + &self, + selected: SelectedRoute<'_>, + context: RequestContext, + mut request: Self::Request, + ) -> Response { + let Some(binding) = self.0.bindings.get(&selected.binding().id) else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; + match binding { + NativeBinding::Handler(handler) => { + if proxy::prepare_headers(request.headers_mut(), &self.0, &context, false).is_err() + { + return response(StatusCode::BAD_REQUEST); + } + request.extensions_mut().insert(context); + match handler.clone().oneshot(request).await { + Ok(response) => response, + Err(never) => match never {}, + } + } + NativeBinding::UiProxy { websocket } => { + let BindingKind::UiProxy { origin } = &selected.binding().kind else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; + proxy::forward(&self.0, origin, *websocket, context, request).await + } + NativeBinding::Assets(assets) => assets.serve(request), + NativeBinding::Admission(_) => response(StatusCode::SERVICE_UNAVAILABLE), + } + } + fn reject(&self, rejection: Rejection<'_>) -> Response { + match rejection { + Rejection::BadRequest => response(StatusCode::BAD_REQUEST), + Rejection::NotFound => response(StatusCode::NOT_FOUND), + Rejection::MethodNotAllowed(selected) => { + let mut response = response(StatusCode::METHOD_NOT_ALLOWED); + if let super::Methods::Only(methods) = &selected.route().methods { + if let Ok(allow) = HeaderValue::from_str(&methods.join(", ")) { + response.headers_mut().insert(header::ALLOW, allow); + } + } + response + } + } + } +} diff --git a/src/gateway/native/proxy.rs b/src/gateway/native/proxy.rs new file mode 100644 index 000000000..bc32816ff --- /dev/null +++ b/src/gateway/native/proxy.rs @@ -0,0 +1,230 @@ +use super::{ + response, BackendCredential, Body, HeaderMap, HeaderValue, NativeInner, Request, + RequestContext, Response, StatusCode, Url, +}; +use axum::http::header; +use futures_util::{Stream, StreamExt}; +use std::{io, time::Duration}; + +fn strip_hop_headers(headers: &mut HeaderMap) { + let named: Vec<_> = headers + .get_all(header::CONNECTION) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(',')) + .map(|v| v.trim().to_owned()) + .collect(); + for name in named { + headers.remove(name); + } + for name in [ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade", + ] { + headers.remove(name); + } +} + +pub(super) fn prepare_headers( + headers: &mut HeaderMap, + inner: &NativeInner, + context: &RequestContext, + upgrade: bool, +) -> Result<(), ()> { + strip_hop_headers(headers); + let remove: Vec<_> = headers + .keys() + .filter(|name| { + super::super::is_untrusted_identity_header(name.as_str()) + || inner + .options + .strip_headers + .iter() + .any(|s| s.eq_ignore_ascii_case(name.as_str())) + }) + .cloned() + .collect(); + for name in remove { + headers.remove(name); + } + headers.remove(header::AUTHORIZATION); + if let BackendCredential::Bearer(token) = context.backend_credential() { + headers.insert( + header::AUTHORIZATION, + HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| ())?, + ); + } + let authority = &inner.origin[url::Position::BeforeHost..url::Position::AfterPort]; + let host = HeaderValue::from_str(authority).map_err(|_| ())?; + headers.insert(header::HOST, host.clone()); + headers.insert("x-forwarded-host", host); + headers.insert( + "x-forwarded-proto", + HeaderValue::from_str(inner.origin.scheme()).map_err(|_| ())?, + ); + if upgrade { + headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade")); + headers.insert(header::UPGRADE, HeaderValue::from_static("websocket")); + } + Ok(()) +} + +pub(super) async fn forward( + inner: &NativeInner, + origin: &str, + allow_websocket: bool, + context: RequestContext, + mut request: Request, +) -> Response { + let permit = match inner.permits.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + }; + if request + .headers() + .get(header::CONTENT_LENGTH) + .is_some_and(|v| { + v.to_str() + .ok() + .and_then(|s| s.parse::().ok()) + .is_none_or(|n| n > inner.options.limits.request_body_bytes as u64) + }) + { + return response(StatusCode::PAYLOAD_TOO_LARGE); + } + let wants_upgrade = request.headers().contains_key(header::UPGRADE); + if wants_upgrade + && (!allow_websocket + || request.method() != "GET" + || !request.headers()[header::UPGRADE] + .as_bytes() + .eq_ignore_ascii_case(b"websocket")) + { + return response(StatusCode::BAD_REQUEST); + } + let on_upgrade = wants_upgrade.then(|| hyper::upgrade::on(&mut request)); + if prepare_headers(request.headers_mut(), inner, &context, wants_upgrade).is_err() { + return response(StatusCode::BAD_REQUEST); + } + let hops = request + .headers() + .get("x-distributed-gateway-hops") + .and_then(|v| v.to_str().ok()) + .map_or_else( + || inner.hop_id.clone(), + |previous| format!("{previous},{}", inner.hop_id), + ); + let Ok(hops) = HeaderValue::from_str(&hops) else { + return response(StatusCode::BAD_REQUEST); + }; + request + .headers_mut() + .insert("x-distributed-gateway-hops", hops); + let target = request.uri().path_and_query().map_or("/", |p| p.as_str()); + // Path ownership already rejected traversal/authority aliases. A configured + // origin is concatenated with origin-form target, never joined to a URL. + let url = format!("{}{target}", origin.trim_end_matches('/')); + let (parts, body) = request.into_parts(); + let max = inner.options.limits.request_body_bytes; + let mut read = 0usize; + let body = body.into_data_stream().map(move |chunk| { + let chunk = chunk.map_err(io::Error::other)?; + read = read + .checked_add(chunk.len()) + .ok_or_else(|| io::Error::other("request body limit"))?; + if read > max { + return Err(io::Error::other("request body limit")); + } + Ok(chunk) + }); + let pending = inner + .client + .request(parts.method, url) + .headers(parts.headers) + .body(reqwest::Body::wrap_stream(body)) + .send(); + let upstream = + match tokio::time::timeout(inner.options.limits.response_header_timeout, pending).await { + Ok(Ok(upstream)) => upstream, + Err(_) => return response(StatusCode::GATEWAY_TIMEOUT), + _ => return response(StatusCode::BAD_GATEWAY), + }; + let status = upstream.status(); + let mut headers = upstream.headers().clone(); + strip_hop_headers(&mut headers); + if let Some(location) = headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) { + if let (Ok(location), Ok(upstream_origin)) = ( + Url::parse(origin).and_then(|origin| origin.join(location)), + Url::parse(origin), + ) { + if location.origin() == upstream_origin.origin() { + let suffix = &location[url::Position::BeforePath..]; + if let Ok(location) = HeaderValue::from_str(&format!( + "{}{suffix}", + inner.options.public_origin.trim_end_matches('/') + )) { + headers.insert(header::LOCATION, location); + } + } + } + } + if status == StatusCode::SWITCHING_PROTOCOLS { + let Some(on_upgrade) = on_upgrade else { + return response(StatusCode::BAD_GATEWAY); + }; + if !upstream + .headers() + .get(header::UPGRADE) + .is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"websocket")) + { + return response(StatusCode::BAD_GATEWAY); + } + headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade")); + headers.insert(header::UPGRADE, HeaderValue::from_static("websocket")); + let lifetime = + context + .identity() + .map_or(inner.options.limits.upgrade_lifetime, |identity| { + inner + .options + .limits + .upgrade_lifetime + .min(Duration::from_secs( + identity.expires_at().saturating_sub(super::now()), + )) + }); + tokio::spawn(async move { + let _permit = permit; + let _ = tokio::time::timeout(lifetime, async move { + let (Ok(downstream), Ok(mut upstream)) = + tokio::join!(on_upgrade, upstream.upgrade()) + else { + return; + }; + let mut downstream = hyper_util::rt::TokioIo::new(downstream); + let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; + }) + .await; + }); + let mut result = response(status); + *result.headers_mut() = headers; + return result; + } + // Dropping the downstream body drops both upstream body and capacity permit. + // No detached response pump keeps reading after the client disconnects. + let mut stream = Box::pin(upstream.bytes_stream()); + let body = futures_util::stream::poll_fn(move |cx| { + let _permit = &permit; + stream.as_mut().poll_next(cx) + }); + let mut result = Response::new(Body::from_stream(body)); + *result.status_mut() = status; + *result.headers_mut() = headers; + result +} diff --git a/tests/gateway-native/.gitignore b/tests/gateway-native/.gitignore new file mode 100644 index 000000000..556a76756 --- /dev/null +++ b/tests/gateway-native/.gitignore @@ -0,0 +1,2 @@ +/target/ +!Cargo.lock diff --git a/tests/gateway-native/Cargo.lock b/tests/gateway-native/Cargo.lock new file mode 100644 index 000000000..c08398b9b --- /dev/null +++ b/tests/gateway-native/Cargo.lock @@ -0,0 +1,2352 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitcode" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6ed1b54d8dc333e7be604d00fa9262f4635485ffea923647b6521a5fff045d" +dependencies = [ + "arrayvec", + "bitcode_derive", + "bytemuck", + "glam", + "serde", +] + +[[package]] +name = "bitcode_derive" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238b90427dfad9da4a9abd60f3ec1cdee6b80454bde49ed37f1781dd8e9dc7f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "distributed" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "base64 0.23.1", + "bitcode", + "distributed_macros", + "futures-util", + "hyper", + "hyper-util", + "js-sys", + "reqwest", + "serde", + "serde_json", + "sha2", + "tokio", + "tonic-build", + "tower", + "url", + "uuid", +] + +[[package]] +name = "distributed_macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "sha2", + "syn 2.0.119", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gateway-native-fixture" +version = "0.0.0" +dependencies = [ + "axum", + "distributed", + "futures-util", + "reqwest", + "serde_json", + "tokio", + "tokio-tungstenite 0.30.0", + "tower", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "glam" +version = "0.33.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21fef0953c54fd3de2f44b743fbf77e044c81a25faee03636dfccc0d35135e23" + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "reqwest" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf0ded5c4e56918d8f8a339e1bb67d038d3bc6d144ac407904015ba2e4cde9b" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1 0.10.7", + "thiserror", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.2", + "sha1 0.11.0", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/gateway-native/Cargo.toml b/tests/gateway-native/Cargo.toml new file mode 100644 index 000000000..599f0944b --- /dev/null +++ b/tests/gateway-native/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "gateway-native-fixture" +version = "0.0.0" +edition = "2021" +publish = false + +[workspace] + +[features] +default = ["gateway-native"] +gateway-native = ["distributed/gateway-native"] + +[dependencies] +distributed = { path = "../..", default-features = false } + +[dev-dependencies] +axum = { version = "0.8", features = ["ws"] } +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = "0.30" +reqwest = { version = "0.13", features = ["json", "stream"] } +futures-util = "0.3" +tower = { version = "0.5", features = ["util"] } +serde_json = "1" + +[[test]] +name = "gateway_ui" +path = "../gateway_ui.rs" diff --git a/tests/gateway-native/README.md b/tests/gateway-native/README.md new file mode 100644 index 000000000..650103329 --- /dev/null +++ b/tests/gateway-native/README.md @@ -0,0 +1,25 @@ +# Native gateway fixture + +This isolated consumer enables `distributed/gateway-native` without GraphQL, +SQL, domain buses or Worker SDK dependencies. + +From the repository root: + +```sh +cargo test --manifest-path tests/gateway-native/Cargo.toml --locked +cargo clippy --manifest-path tests/gateway-native/Cargo.toml --locked --all-targets -- -D warnings +python3 tests/gateway-native/check_dependencies.py +``` + +The tests use real ephemeral loopback HTTP servers and WebSocket connections. +They prove incremental streaming before an explicit completion signal, response +body drop cancelling upstream work, independent cookies, public-origin headers +and redirects, method/body/query/HEAD semantics, upgrade echo and closure, +protected assets/custom routes, owned failures, request size and concurrency +limits, timeout, and proxy loops through origin aliases. Every server belongs +to the test and is aborted on teardown. No database or external service runs. + +A parent build cache can be reused with `--target-dir target` from the repository +root. The package lockfile is committed for reproducibility. Production +Auth.js browser tests are independently reusable from `tests/gateway-auth`; +the full application/Worker owners run them through their public ingress. diff --git a/tests/gateway-native/check_dependencies.py b/tests/gateway-native/check_dependencies.py new file mode 100644 index 000000000..367c2cd62 --- /dev/null +++ b/tests/gateway-native/check_dependencies.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +"""The native UI/auth adapter has no GraphQL/SQL or domain bus dependency.""" +from pathlib import Path +import subprocess +manifest = Path(__file__).resolve().with_name("Cargo.toml") +output = subprocess.check_output(["cargo", "tree", "--manifest-path", str(manifest), "--locked", "--edges", "normal", "--prefix", "none"], text=True) +packages = {line.split()[0] for line in output.splitlines() if line.strip()} +forbidden = {"async-graphql", "async-graphql-axum", "sqlx", "sqlx-core", "tonic", "worker", "async-nats", "lapin", "rdkafka"} +assert not packages & forbidden, sorted(packages & forbidden) +print("native UI/auth dependency boundary passed") diff --git a/tests/gateway-native/src/lib.rs b/tests/gateway-native/src/lib.rs new file mode 100644 index 000000000..459ffc314 --- /dev/null +++ b/tests/gateway-native/src/lib.rs @@ -0,0 +1,2 @@ +//! Native UI/auth gateway consumer, independent of GraphQL and SQL. +pub use distributed::gateway::native::*; diff --git a/tests/gateway_ui.rs b/tests/gateway_ui.rs new file mode 100644 index 000000000..ee85fea0e --- /dev/null +++ b/tests/gateway_ui.rs @@ -0,0 +1,592 @@ +#![cfg(feature = "gateway-native")] +use axum::{ + body::{Body, Bytes}, + extract::{ + ws::{Message, WebSocketUpgrade}, + State, + }, + http::{header, HeaderMap, HeaderValue, Request, StatusCode}, + response::{IntoResponse, Response}, + routing::{any, get}, + Router, +}; +use distributed::gateway::{native::*, *}; +use futures_util::{SinkExt, Stream, StreamExt}; +use std::{ + collections::BTreeMap, + convert::Infallible, + pin::Pin, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, + task::{Context, Poll}, + time::Duration, +}; +use tokio::{ + net::TcpListener, + sync::{mpsc, Notify}, + task::JoinHandle, +}; +use tower::ServiceExt; + +struct Server { + origin: String, + task: JoinHandle<()>, +} +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn serve(router: Router) -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + Server { origin, task } +} +fn auth() -> NativeAuth { + NativeAuth::new(|credentials| async move { + let identity = match credentials.authorization.as_deref() { + None => None, + Some("Bearer valid") => { + Some(Identity::verified("local", "alice", vec!["user".into()], u64::MAX).unwrap()) + } + _ => return Err(AuthError::Unauthorized), + }; + RequestContext::from_provider(identity, "test-v1", BackendCredential::None) + .map_err(|_| AuthError::Unavailable) + }) +} +fn gateway(origin: &str, upstream: &str, limits: ProxyLimits) -> NativeGateway { + let mut private = Route::new("private", RoutePath::prefix("/private"), "ui"); + private.admission = vec!["auth".into()]; + let config = GatewayConfig { + bindings: vec![ + Binding::new( + "ui", + BindingKind::UiProxy { + origin: upstream.into(), + }, + ), + Binding::new("auth", BindingKind::Admission), + ], + routes: vec![private, Route::new("ui", RoutePath::prefix("/"), "ui")], + } + .build() + .unwrap(); + let mut options = NativeOptions::new(origin); + options.limits = limits; + options.strip_headers = vec!["x-company-user".into(), "x-gateway-secret".into()]; + NativeGateway::new( + config, + options, + vec![ + ("ui".into(), NativeBinding::UiProxy { websocket: true }), + ( + "auth".into(), + NativeBinding::Admission(Admission::Authenticated), + ), + ], + auth(), + ) + .unwrap() +} + +struct TrackedStream { + receiver: mpsc::Receiver>, + dropped: Arc, +} +impl Stream for TrackedStream { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.receiver.poll_recv(cx) + } +} +impl Drop for TrackedStream { + fn drop(&mut self) { + self.dropped.fetch_add(1, Ordering::SeqCst); + } +} +#[derive(Clone)] +struct Upstream { + finish: Arc, + dropped: Arc, + ws_closed: Arc, +} +async fn stream(State(state): State) -> Response { + let (send, receiver) = mpsc::channel(1); + let dropped = state.dropped.clone(); + tokio::spawn(async move { + if send.send(Ok(Bytes::from_static(b"first"))).await.is_err() { + return; + } + tokio::select! { _ = state.finish.notified() => { let _ = send.send(Ok(Bytes::from_static(b"last"))).await; }, _ = send.closed() => {} } + }); + Response::new(Body::from_stream(TrackedStream { receiver, dropped })) +} +async fn echo(request: Request) -> Response { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, 1024).await.unwrap(); + let headers: BTreeMap<_, _> = parts + .headers + .iter() + .map(|(k, v)| (k.to_string(), v.to_str().unwrap().to_string())) + .collect(); + let mut result = axum::Json(serde_json::json!({ "method": parts.method.to_string(), "target": parts.uri.to_string(), "body": String::from_utf8(body.to_vec()).unwrap(), "headers": headers })).into_response(); + result.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_static("one=1; Path=/; HttpOnly; SameSite=Lax"), + ); + result.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_static("two=2; Path=/; HttpOnly; SameSite=Lax"), + ); + result.headers_mut().insert( + header::CONNECTION, + HeaderValue::from_static("x-hop-response"), + ); + result + .headers_mut() + .insert("x-hop-response", HeaderValue::from_static("remove")); + result +} +async fn websocket(State(state): State, ws: WebSocketUpgrade) -> Response { + ws.on_upgrade(move |mut ws| async move { + while let Some(Ok(message)) = ws.recv().await { + if matches!(message, Message::Close(_)) { + break; + } + if ws.send(message).await.is_err() { + break; + } + } + state.ws_closed.notify_one(); + }) +} + +#[tokio::test] +async fn stream_cookies_redirects_and_upgrades() { + let state = Upstream { + finish: Arc::new(Notify::new()), + dropped: Arc::new(AtomicUsize::new(0)), + ws_closed: Arc::new(Notify::new()), + }; + let upstream = serve( + Router::new() + .route("/stream", get(stream)) + .route("/ws", get(websocket)) + .route("/echo", any(echo)) + .route("/head", get(|| async { "head-body" })) + .with_state(state.clone()), + ) + .await; + let ingress_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let public = format!("http://{}", ingress_listener.local_addr().unwrap()); + let router = gateway(&public, &upstream.origin, ProxyLimits::default()).router(); + let ingress = Server { + origin: public.clone(), + task: tokio::spawn(async move { axum::serve(ingress_listener, router).await.unwrap() }), + }; + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let response = client + .post(format!("{public}/echo?x=a%2Fb")) + .header("x-user-id", "admin") + .header("x-hasura-role", "admin") + .header("x-forwarded-host", "attacker.invalid") + .header("forwarded", "host=attacker.invalid") + .header("x-company-user", "admin") + .header("x-gateway-secret", "spoofed") + .header("connection", "x-hop-request") + .header("x-hop-request", "remove") + .header("origin", &public) + .body("input") + .send() + .await + .unwrap(); + assert_eq!( + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .count(), + 2 + ); + assert!(!response.headers().contains_key("x-hop-response")); + let value: serde_json::Value = response.json().await.unwrap(); + assert_eq!(value["method"], "POST"); + assert_eq!(value["target"], "/echo?x=a%2Fb"); + assert_eq!(value["body"], "input"); + assert_eq!( + value["headers"]["host"], + public.trim_start_matches("http://") + ); + assert_eq!( + value["headers"]["x-forwarded-host"], + public.trim_start_matches("http://") + ); + assert_eq!(value["headers"]["origin"], public); + for name in [ + "x-user-id", + "x-hasura-role", + "forwarded", + "x-company-user", + "x-gateway-secret", + "x-hop-request", + ] { + assert!(value["headers"].get(name).is_none(), "{name}"); + } + let head = client.head(format!("{public}/head")).send().await.unwrap(); + assert_eq!(head.headers()[header::CONTENT_LENGTH], "9"); + assert!(head.bytes().await.unwrap().is_empty()); + let mut response = client.get(format!("{public}/stream")).send().await.unwrap(); + let first = tokio::time::timeout(Duration::from_secs(2), response.chunk()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(first, "first"); // Completion is impossible until this signal. + state.finish.notify_one(); + assert_eq!(response.bytes().await.unwrap(), "last"); + let mut response = client.get(format!("{public}/stream")).send().await.unwrap(); + assert_eq!(response.chunk().await.unwrap().unwrap(), "first"); + drop(response); + tokio::time::timeout(Duration::from_secs(2), async { + while state.dropped.load(Ordering::SeqCst) < 2 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let (mut ws, _) = + tokio_tungstenite::connect_async(format!("{}/ws", ingress.origin.replace("http:", "ws:"))) + .await + .unwrap(); + ws.send(tokio_tungstenite::tungstenite::Message::Text( + "hello".into(), + )) + .await + .unwrap(); + assert_eq!( + ws.next().await.unwrap().unwrap().into_text().unwrap(), + "hello" + ); + ws.close(None).await.unwrap(); + drop(ws); + tokio::time::timeout(Duration::from_secs(2), state.ws_closed.notified()) + .await + .unwrap(); +} + +#[tokio::test] +async fn redirect_ownership_assets_and_limits() { + let upstream = serve(Router::new().fallback(|headers: HeaderMap| async move { + let mut response = StatusCode::FOUND.into_response(); + // App emits a private absolute URL; it must be rewritten without following. + response + .headers_mut() + .insert(header::LOCATION, headers["x-redirect-to"].clone()); + response + })) + .await; + let ingress = serve( + gateway( + "https://site.test", + &upstream.origin, + ProxyLimits { + request_body_bytes: 4, + ..Default::default() + }, + ) + .router(), + ) + .await; + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let response = client + .get(&ingress.origin) + .header( + "x-redirect-to", + format!("{}/next?q=1#anchor", upstream.origin), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FOUND); + assert_eq!( + response.headers()[header::LOCATION], + "https://site.test/next?q=1#anchor" + ); + let response = client + .get(&ingress.origin) + .header("x-redirect-to", "https://idp.example.invalid/authorize") + .send() + .await + .unwrap(); + assert_eq!( + response.headers()[header::LOCATION], + "https://idp.example.invalid/authorize" + ); + let response = client + .get(&ingress.origin) + .header( + "x-redirect-to", + format!("//{}/next", upstream.origin.trim_start_matches("http://")), + ) + .send() + .await + .unwrap(); + assert_eq!( + response.headers()[header::LOCATION], + "https://site.test/next" + ); + assert_eq!( + client + .post(&ingress.origin) + .body("large") + .send() + .await + .unwrap() + .status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!( + client + .get(format!("{}/private/page", ingress.origin)) + .send() + .await + .unwrap() + .status(), + StatusCode::UNAUTHORIZED + ); + assert_eq!( + client + .get(&ingress.origin) + .header("authorization", "Bearer forged") + .send() + .await + .unwrap() + .status(), + StatusCode::UNAUTHORIZED + ); + + let assets = StaticAssets::new( + [( + "/private/file".into(), + Asset { + bytes: Bytes::from_static(b"secret"), + content_type: HeaderValue::from_static("text/plain"), + }, + )], + 6, + ) + .unwrap(); + let mut route = Route::new("asset", RoutePath::prefix("/private"), "asset"); + route.admission.push("auth".into()); + let mut api = Route::new("api", RoutePath::prefix("/api"), "api"); + api.methods = Methods::Only(vec!["POST".into()]); + let config = GatewayConfig { + bindings: vec![ + Binding::new("asset", BindingKind::Assets), + Binding::new("auth", BindingKind::Admission), + Binding::new("api", BindingKind::Handler), + ], + routes: vec![route, api, { + let mut custom = Route::new("custom", RoutePath::exact("/custom"), "api"); + custom.admission.push("auth".into()); + custom + }], + } + .build() + .unwrap(); + let router = NativeGateway::new( + config, + NativeOptions::new("https://site.test"), + vec![ + ("asset".into(), NativeBinding::Assets(assets)), + ( + "auth".into(), + NativeBinding::Admission(Admission::Authenticated), + ), + ( + "api".into(), + NativeBinding::Handler( + Router::new().route("/custom", get(|axum::Extension(context): axum::Extension| async move { context.identity().unwrap().subject().to_string() })).fallback(|| async { StatusCode::SERVICE_UNAVAILABLE }), + ), + ), + ], + auth(), + ) + .unwrap() + .router(); + for (method, path, token, expected) in [ + ("GET", "/private/file", None, 401), + ("GET", "/custom", None, 401), + ("GET", "/custom", Some("Bearer valid"), 200), + ("GET", "/private/file", Some("Bearer valid"), 200), + ("HEAD", "/private/file", Some("Bearer valid"), 200), + ("GET", "/private/%2e%2e/file", Some("Bearer valid"), 400), + ("GET", "/api/missing", None, 405), + ("POST", "/api/missing", None, 503), + ] { + let mut request = Request::builder().method(method).uri(path); + if let Some(token) = token { + request = request.header("authorization", token); + } + let response = router + .clone() + .oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status().as_u16(), expected, "{method} {path}"); + if path == "/custom" && expected == 200 { + assert_eq!( + axum::body::to_bytes(response.into_body(), 100) + .await + .unwrap(), + "alice" + ); + continue; + } + if method == "HEAD" { + assert_eq!(response.headers()[header::CONTENT_LENGTH], "6"); + assert!(axum::body::to_bytes(response.into_body(), 100) + .await + .unwrap() + .is_empty()); + } + } +} + +#[test] +fn native_bindings_reject_loops_and_duplicate_resources() { + let config = || { + GatewayConfig { + bindings: vec![Binding::new( + "ui", + BindingKind::UiProxy { + origin: "https://site.test".into(), + }, + )], + routes: vec![Route::new("ui", RoutePath::prefix("/"), "ui")], + } + .build() + .unwrap() + }; + assert!(NativeGateway::new( + config(), + NativeOptions::new("https://site.test"), + [("ui".into(), NativeBinding::UiProxy { websocket: false })], + NativeAuth::anonymous() + ) + .is_err()); + assert!(NativeGateway::new( + config(), + NativeOptions::new("https://other.test"), + [ + ("ui".into(), NativeBinding::UiProxy { websocket: false }), + ("ui".into(), NativeBinding::UiProxy { websocket: false }) + ], + NativeAuth::anonymous() + ) + .is_err()); + assert!(StaticAssets::new( + [( + "/../secret".into(), + Asset { + bytes: Bytes::new(), + content_type: HeaderValue::from_static("text/plain") + } + )], + 100 + ) + .is_err()); +} + +#[tokio::test] +async fn capacity_cancellation_timeout_and_alias_loop_are_bounded() { + let state = Upstream { + finish: Arc::new(Notify::new()), + dropped: Arc::new(AtomicUsize::new(0)), + ws_closed: Arc::new(Notify::new()), + }; + let upstream = serve( + Router::new() + .route("/stream", get(stream)) + .route( + "/slow", + get(|| async { + std::future::pending::<()>().await; + "unreachable" + }), + ) + .with_state(state.clone()), + ) + .await; + let ingress = serve( + gateway( + "https://site.test", + &upstream.origin, + ProxyLimits { + concurrent_requests: 1, + response_header_timeout: Duration::from_millis(100), + ..Default::default() + }, + ) + .router(), + ) + .await; + let client = reqwest::Client::new(); + let mut first = client + .get(format!("{}/stream", ingress.origin)) + .send() + .await + .unwrap(); + assert_eq!(first.chunk().await.unwrap().unwrap(), "first"); + assert_eq!( + client + .get(format!("{}/stream", ingress.origin)) + .send() + .await + .unwrap() + .status(), + StatusCode::SERVICE_UNAVAILABLE + ); + drop(first); + tokio::time::timeout(Duration::from_secs(2), async { + while state.dropped.load(Ordering::SeqCst) == 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!( + client + .get(format!("{}/slow", ingress.origin)) + .send() + .await + .unwrap() + .status(), + StatusCode::GATEWAY_TIMEOUT + ); + + // Two names can resolve to one listener. A bounded hop chain catches this + // even when origin string comparison at construction cannot detect it. + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let direct = format!("http://{}", listener.local_addr().unwrap()); + let router = gateway("https://alias.test", &direct, ProxyLimits::default()).router(); + let looped = Server { + origin: direct, + task: tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }), + }; + let response = tokio::time::timeout(Duration::from_secs(2), client.get(&looped.origin).send()) + .await + .unwrap() + .unwrap(); + assert_eq!(response.status(), StatusCode::LOOP_DETECTED); +} From 899634311cb8fd2f30a58beba81e324839bde746 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 21:35:05 -0500 Subject: [PATCH 052/484] feat(gateway): bind embedded and remote GraphQL execution Preserve selected-operation capabilities, causal receipts and live proofs across native HTTP and WebSocket gateways. Add portable operation parsing and real transport parity coverage. Refs: [[tasks/application-gateway-5]] [[tasks/application-gateway-1]] --- .github/workflows/integration-gateway.yaml | 20 + Cargo.toml | 5 + src/gateway/README.md | 18 + src/gateway/graphql/mod.rs | 181 +++++++ src/gateway/mod.rs | 4 + src/gateway/native/graphql.rs | 531 +++++++++++++++++++ src/gateway/native/mod.rs | 36 +- src/gateway/native/proxy.rs | 48 +- src/graphql/engine/builder.rs | 10 +- src/graphql/engine/core.rs | 1 + src/graphql/http.rs | 98 +++- src/graphql/mod.rs | 4 +- tests/gateway-portable/Cargo.lock | 52 ++ tests/gateway-portable/Cargo.toml | 5 + tests/gateway-portable/check_dependencies.py | 2 + tests/gateway_graphql.rs | 442 +++++++++++++++ tests/gateway_graphql_operation.rs | 65 +++ tests/graphql_causal_transport/main.rs | 109 +++- tests/graphql_query_protocol/main.rs | 211 +++++++- 19 files changed, 1811 insertions(+), 31 deletions(-) create mode 100644 src/gateway/graphql/mod.rs create mode 100644 src/gateway/native/graphql.rs create mode 100644 tests/gateway_graphql.rs create mode 100644 tests/gateway_graphql_operation.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 85dfa2996..4d7808a91 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -11,6 +11,8 @@ on: - 'tests/e2e-ui/ui/src/lib/server/**' - 'tests/e2e-ui/ui/src/routes/api/auth/**' - 'tests/graphql_identity/**' + - 'tests/graphql_causal_transport/**' + - 'tests/graphql_query_protocol/**' - 'tests/gateway*' - 'tests/gateway*/**' - '.github/workflows/integration-gateway.yaml' @@ -40,6 +42,11 @@ jobs: run: cargo clippy --manifest-path tests/gateway-portable/Cargo.toml --locked --all-targets -- -D warnings - name: Compile the UI/auth consumer to Wasm run: cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown + - name: Test and compile portable GraphQL operation policy + run: | + cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-graphql + cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-graphql --target wasm32-unknown-unknown + python3 tests/gateway-portable/check_dependencies.py --features gateway-graphql - name: Verify native and Wasm dependency isolation run: python3 tests/gateway-portable/check_dependencies.py @@ -85,3 +92,16 @@ jobs: run: cargo clippy --manifest-path tests/gateway-native/Cargo.toml --locked --all-targets -- -D warnings - name: Verify UI/auth executor dependency isolation run: python3 tests/gateway-native/check_dependencies.py + + graphql: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - name: Verify embedded and remote GraphQL protocols + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity diff --git a/Cargo.toml b/Cargo.toml index c1005cca1..0ce1a501d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,9 @@ application-runtime = [] gateway = ["dep:url"] # Native HTTP adapter remains independent of GraphQL and SQL. gateway-native = ["gateway", "http", "reqwest/stream", "dep:hyper", "dep:hyper-util", "dep:tower", "tokio/io-util"] +# Whole-operation selection is portable; execution adapters are separately gated. +gateway-graphql = ["gateway", "dep:async-graphql-parser"] +gateway-graphql-native = ["gateway-native", "gateway-graphql", "graphql", "dep:tokio-tungstenite"] runtime = ["application-runtime"] emitter = ["dep:event-emitter-rs"] metrics = [] @@ -57,6 +60,8 @@ graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:hmac", "dep:jsonw async-nats = { version = "0.50", optional = true } async-trait = "0.1" async-graphql = { version = "7", optional = true } +async-graphql-parser = { version = "7", optional = true } +tokio-tungstenite = { version = "0.30", optional = true } async-graphql-axum = { version = "7", optional = true } axum = { version = "0.8", optional = true } hyper = { version = "1", features = ["http1", "server"], optional = true } diff --git a/src/gateway/README.md b/src/gateway/README.md index 3592db387..e899b6c92 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -56,3 +56,21 @@ a bounded hop chain also detects loops through aliases at runtime. budget. Protected assets run normal admission before lookup. It performs no caller-selected filesystem access. Native construction starts no listener, projector or event consumer. Disabling this mount restores previous entrypoints. + +### GraphQL executors + +`gateway-graphql` adds a portable parser-based selected-operation policy; it +compiles to Wasm without an executor. `gateway-graphql-native` binds the existing +GraphQL HTTP/WS executor or a whole remote endpoint to `NativeBinding::Graphql`. +Build query-only engines without command inventory and with `subscriptions(false)` +when live is absent. Commands include status recovery; status queries are never +ordinary reusable reads. Configure custom fields on the selected executor and +register their extension IDs. Custom embedded executors must install the supplied +operation filter and retain/run `GraphqlConnectionGuard` for custom WS handlers. + +Remote transport preserves operation names, variables, errors, extensions and +GraphQL WS IDs. It never retries mutations or creates receipts on transport +failure. Configured body, concurrency and connection lifetime limits apply; +backend authorization remains authoritative. Optional delivery features are +rejected until their adapters are bound. Removing the GraphQL binding restores +the existing direct executor routes; no migration is required. diff --git a/src/gateway/graphql/mod.rs b/src/gateway/graphql/mod.rs new file mode 100644 index 000000000..59204bfbd --- /dev/null +++ b/src/gateway/graphql/mod.rs @@ -0,0 +1,181 @@ +//! Whole GraphQL operation admission, independent of an executor or SQL pool. +//! The caller retains the original request/envelope; admission never dispatches +//! commands itself, rewrites command IDs or manufactures commit evidence. +use super::GraphqlCapabilities; +use async_graphql_parser::{ + parse_query, + types::{ExecutableDocument, OperationDefinition, OperationType, Selection}, +}; +use serde_json::Value; + +/// Maximum portable operation document size accepted before parsing. +pub const MAX_DOCUMENT_BYTES: usize = 256 * 1024; + +/// Kind of the exact selected operation, obtained from the GraphQL parser. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OperationKind { + /// Read query. + Query, + /// Built-in command status recovery query, owned by the command mount and + /// excluded from query snapshot/coalescing eligibility. + CommandStatus, + /// Query combining ordinary reads and command status; requires both mounts + /// and remains ineligible for query delivery reuse. + MixedQuery, + /// Command mutation; never eligible for an automatic retry. + Mutation, + /// Live subscription. + Subscription, +} + +/// Admission failure before invoking the selected executor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OperationError { + /// Malformed transport request/variables/extensions. + InvalidRequest, + /// Invalid executable GraphQL document. + InvalidDocument, + /// Multiple operations require an explicit operationName. + AmbiguousOperation, + /// The requested operationName does not exist in the document. + UnknownOperation, + /// The selected operation's surface is not mounted. + NotMounted, +} +impl std::fmt::Display for OperationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::InvalidRequest => "invalid GraphQL request", + Self::InvalidDocument => "invalid GraphQL document", + Self::AmbiguousOperation => { + "GraphQL operation name is required for multi-operation documents" + } + Self::UnknownOperation => "GraphQL operation name was not found", + Self::NotMounted => "GraphQL operation surface is not mounted", + }) + } +} +impl std::error::Error for OperationError {} +impl OperationError { + /// GraphQL error envelope, without command receipts or response evidence. + pub fn envelope(self) -> Value { + serde_json::json!({ "errors": [{ "message": self.to_string(), "extensions": { "code": if self == Self::NotMounted { "OPERATION_NOT_MOUNTED" } else { "BAD_REQUEST" } } }] }) + } +} + +/// Resolve the exact operation. Reject ambiguous/unknown selection even when +/// another operation in the same document would be allowed. This is not full +/// schema validation; that remains the executor's responsibility. +pub fn operation_kind( + document: &str, + operation_name: Option<&str>, +) -> Result { + if document.len() > MAX_DOCUMENT_BYTES || operation_name.is_some_and(|name| name.len() > 256) { + return Err(OperationError::InvalidRequest); + } + let document = parse_query(document).map_err(|_| OperationError::InvalidDocument)?; + let mut operations = document.operations.iter(); + let operation = if let Some(name) = operation_name { + operations + .find(|(candidate, _)| candidate.is_some_and(|candidate| candidate.as_str() == name)) + .map(|(_, op)| op) + .ok_or(OperationError::UnknownOperation)? + } else { + let (_, operation) = operations.next().ok_or(OperationError::InvalidDocument)?; + if operations.next().is_some() { + return Err(OperationError::AmbiguousOperation); + } + operation + }; + Ok(match operation.node.ty { + OperationType::Query => query_kind(&document, &operation.node), + OperationType::Mutation => OperationKind::Mutation, + OperationType::Subscription => OperationKind::Subscription, + }) +} + +/// Check a selected operation against explicit command/query/live mounts. +pub fn admit_operation( + document: &str, + operation_name: Option<&str>, + capabilities: GraphqlCapabilities, +) -> Result { + let kind = operation_kind(document, operation_name)?; + let allowed = match kind { + OperationKind::Query => capabilities.queries, + OperationKind::Mutation | OperationKind::CommandStatus => capabilities.commands, + OperationKind::MixedQuery => capabilities.queries && capabilities.commands, + OperationKind::Subscription => capabilities.live, + }; + if allowed { + Ok(kind) + } else { + Err(OperationError::NotMounted) + } +} + +/// Validate and admit one JSON GraphQL request, preserving all original values +/// and extensions for forwarding. Request byte/depth limits belong to the host. +pub fn admit_request( + request: &Value, + capabilities: GraphqlCapabilities, +) -> Result { + let document = request + .get("query") + .and_then(Value::as_str) + .ok_or(OperationError::InvalidRequest)?; + let name = match request.get("operationName") { + None | Some(Value::Null) => None, + Some(Value::String(name)) => Some(name.as_str()), + _ => return Err(OperationError::InvalidRequest), + }; + for key in ["variables", "extensions"] { + if request + .get(key) + .is_some_and(|value| !value.is_null() && !value.is_object()) + { + return Err(OperationError::InvalidRequest); + } + } + admit_operation(document, name, capabilities) +} + +// Follow root fragments, not text/aliases. Every selected root must belong to +// status recovery; mixed read/status documents need the full query surface. +fn query_kind(document: &ExecutableDocument, operation: &OperationDefinition) -> OperationKind { + let mut pending: Vec<_> = operation.selection_set.node.items.iter().collect(); + let mut fragments = std::collections::BTreeSet::new(); + let mut status = false; + let mut query = false; + let mut count = 0; + while let Some(selection) = pending.pop() { + count += 1; + if count > 4096 { + return OperationKind::MixedQuery; + } + match &selection.node { + Selection::Field(field) => match field.node.name.node.as_str() { + "commandStatus" => status = true, + "__typename" => {} + _ => query = true, + }, + Selection::InlineFragment(fragment) => { + pending.extend(fragment.node.selection_set.node.items.iter()) + } + Selection::FragmentSpread(spread) => { + let name = spread.node.fragment_name.node.as_str(); + if fragments.insert(name) { + let Some(fragment) = document.fragments.get(name) else { + return OperationKind::MixedQuery; + }; + pending.extend(fragment.node.selection_set.node.items.iter()); + } + } + } + } + match (status, query) { + (true, false) => OperationKind::CommandStatus, + (true, true) => OperationKind::MixedQuery, + _ => OperationKind::Query, + } +} diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 49e827066..2df3110a3 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -36,3 +36,7 @@ pub use context::{BackendCredential, Credentials, Identity, RequestContext}; /// Native HTTP routing, streaming proxy and static asset adapter. #[cfg(feature = "gateway-native")] pub mod native; + +/// Portable GraphQL operation selection and capability admission. +#[cfg(feature = "gateway-graphql")] +pub mod graphql; diff --git a/src/gateway/native/graphql.rs b/src/gateway/native/graphql.rs new file mode 100644 index 000000000..a3114b5bd --- /dev/null +++ b/src/gateway/native/graphql.rs @@ -0,0 +1,531 @@ +use super::{ + proxy, response, Body, GatewayError, HeaderValue, NativeInner, Request, RequestContext, + Response, Router, StatusCode, Url, +}; +use crate::command_dispatch::SharedCommandHost; +use crate::gateway::{ + graphql::{admit_operation, admit_request, OperationError}, + BindingKind, DeliveryCapabilities, GraphqlCapabilities, GraphqlExecutor, +}; +use crate::graphql::{graphql_router_composed, GraphqlEngine, GraphqlOperationFilter}; +use axum::{ + extract::{ + ws::{Message, WebSocket, WebSocketUpgrade}, + FromRequestParts, + }, + http::header, + response::IntoResponse, +}; +use futures_util::{SinkExt, StreamExt}; +use std::{collections::BTreeSet, sync::Arc, time::Duration}; +use tokio_tungstenite::{ + tungstenite::{protocol::Role, Message as UpstreamMessage}, + WebSocketStream, +}; +use tower::ServiceExt; + +/// Complete embedded executor, with explicit capabilities and extension +/// registration. The executor owns the composed schema and authorization. +#[derive(Clone)] +pub struct EmbeddedGraphql { + router: Router, + capabilities: GraphqlCapabilities, + extensions: BTreeSet, +} +impl EmbeddedGraphql { + /// Mount the framework's existing HTTP/WS handlers. Build query-only schemas + /// without command inventory and with subscriptions(false). This validates + /// absent capabilities against the actual role surfaces before serving. + pub fn new( + engine: Arc, + host: Option, + capabilities: GraphqlCapabilities, + ) -> Result { + for surface in engine.inner.role_surfaces.values() { + if (!capabilities.commands && !surface.commands.is_empty()) + || (!capabilities.live && !surface.subscription_fields.is_empty()) + { + return Err(GatewayError( + "embedded schema exposes an unmounted capability", + )); + } + } + if capabilities.commands && host.is_none() { + return Err(GatewayError("command surface requires a command host")); + } + Ok(Self { + router: graphql_router_composed(engine, host, Some(operation_filter(capabilities))), + capabilities, + extensions: BTreeSet::new(), + }) + } + + /// Bind an application-composed executor (including custom GraphQL fields). + /// The factory must install the supplied filter in its HTTP and WS execution + /// paths, just as graphql_router_composed does. Custom WS handlers must also + /// retain the request extension `GraphqlConnectionGuard` through the socket + /// lifetime and run the connection with its `run` method. It is a trusted executor + /// extension seam, not arbitrary field federation. Register fields here at + /// this executor; declare their registration IDs in the gateway config. + pub fn custom( + factory: impl FnOnce(GraphqlOperationFilter) -> Router, + capabilities: GraphqlCapabilities, + extensions: impl IntoIterator, + ) -> Result { + let mut registered = BTreeSet::new(); + for name in extensions { + super::super::config::validate_id(&name)?; + if !registered.insert(name) { + return Err(GatewayError("duplicate schema extension registration")); + } + } + Ok(Self { + router: factory(operation_filter(capabilities)), + capabilities, + extensions: registered, + }) + } +} + +/// Paths at a complete remote GraphQL executor. Its origin comes from the +/// validated portable binding, never from a caller request or query variable. +#[derive(Clone, Debug)] +pub struct RemoteGraphql { + /// Remote HTTP operation path. + pub http_path: String, + /// Remote WebSocket operation path, required when live is mounted. + pub live_path: Option, +} +impl Default for RemoteGraphql { + fn default() -> Self { + Self { + http_path: "/graphql".into(), + live_path: Some("/graphql/ws".into()), + } + } +} + +/// One executor resource for a portable GraphQL binding. +#[derive(Clone)] +pub enum GraphqlBinding { + /// Executor in the same process, sharing its existing schema and command host. + Embedded(EmbeddedGraphql), + /// Whole-operation remote HTTP and WS transport. + Remote(RemoteGraphql), +} + +fn operation_filter(capabilities: GraphqlCapabilities) -> GraphqlOperationFilter { + Arc::new(move |request| { + admit_operation( + &request.query, + request.operation_name.as_deref(), + capabilities, + ) + .map(|_| ()) + .map_err(|error| { + let mut result = async_graphql::ServerError::new(error.to_string(), None); + let mut extensions = async_graphql::ErrorExtensionValues::default(); + extensions.set( + "code", + if error == OperationError::NotMounted { + "OPERATION_NOT_MOUNTED" + } else { + "BAD_REQUEST" + }, + ); + result.extensions = Some(extensions); + result + }) + }) +} +fn error_response(error: OperationError) -> Response { + axum::Json(error.envelope()).into_response() +} + +impl GraphqlBinding { + pub(super) fn validate( + &self, + executor: &GraphqlExecutor, + capabilities: GraphqlCapabilities, + delivery: DeliveryCapabilities, + extensions: &[String], + public: &Url, + ) -> Result<(), GatewayError> { + // Later delivery mounts provide these implementations. Reject enabling + // a mount until it is bound; a configuration flag cannot pretend to cache. + if delivery != DeliveryCapabilities::default() { + return Err(GatewayError("delivery adapter is not bound")); + } + match (self, executor) { + (Self::Embedded(embedded), GraphqlExecutor::Embedded) => { + if embedded.capabilities != capabilities + || embedded.extensions != extensions.iter().cloned().collect() + { + return Err(GatewayError( + "embedded schema registration does not match declaration", + )); + } + } + (Self::Remote(remote), GraphqlExecutor::Remote { origin }) => { + if Url::parse(origin) + .map_err(|_| GatewayError("invalid GraphQL origin"))? + .origin() + == public.origin() + { + return Err(GatewayError("GraphQL upstream points to gateway")); + } + for path in std::iter::once(&remote.http_path).chain(remote.live_path.as_ref()) { + if super::super::route::normalize_path(path)? != *path { + return Err(GatewayError("invalid remote GraphQL path")); + } + } + if capabilities.live && remote.live_path.is_none() { + return Err(GatewayError("live gateway needs a remote live endpoint")); + } + } + _ => return Err(GatewayError("GraphQL executor location mismatch")), + } + Ok(()) + } + + pub(super) async fn execute( + &self, + inner: &NativeInner, + declaration: &BindingKind, + context: RequestContext, + mut request: Request, + ) -> Response { + let BindingKind::Graphql { + capabilities, + executor, + .. + } = declaration + else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; + let upgrade = request.headers().contains_key(header::UPGRADE); + if upgrade { + if !capabilities.live { + return response(StatusCode::NOT_FOUND); + } + return match (self, executor) { + (Self::Embedded(embedded), _) => { + let permit = match inner.permits.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + }; + let lifetime = + context + .identity() + .map_or(inner.options.limits.upgrade_lifetime, |id| { + inner + .options + .limits + .upgrade_lifetime + .min(Duration::from_secs( + id.expires_at().saturating_sub(super::now()), + )) + }); + request.extensions_mut().insert(Arc::new( + crate::graphql::http::GraphqlConnectionGuard { + lifetime, + _permit: permit, + }, + )); + if proxy::prepare_headers(request.headers_mut(), inner, &context, true).is_err() + { + return response(StatusCode::BAD_REQUEST); + } + rewrite_path(&mut request, "/graphql/ws"); + request.extensions_mut().insert(context); + match embedded.router.clone().oneshot(request).await { + Ok(response) => response, + Err(never) => match never {}, + } + } + (Self::Remote(remote), GraphqlExecutor::Remote { origin }) => { + remote_websocket( + inner, + origin, + remote.live_path.as_deref().expect("validated live path"), + *capabilities, + context, + request, + ) + .await + } + _ => response(StatusCode::SERVICE_UNAVAILABLE), + }; + } + if request.method() != "POST" { + let mut result = response(StatusCode::METHOD_NOT_ALLOWED); + result + .headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("POST")); + return result; + } + let permit = match inner.permits.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + }; + let (parts, body) = request.into_parts(); + let body = match tokio::time::timeout( + inner.options.limits.response_header_timeout, + axum::body::to_bytes(body, inner.options.limits.request_body_bytes), + ) + .await + { + Ok(Ok(body)) => body, + Ok(Err(_)) => return response(StatusCode::PAYLOAD_TOO_LARGE), + Err(_) => return response(StatusCode::REQUEST_TIMEOUT), + }; + let value = match serde_json::from_slice(&body) { + Ok(value) => value, + Err(_) => return error_response(OperationError::InvalidRequest), + }; + if let Err(error) = admit_request(&value, *capabilities) { + return error_response(error); + } + let mut request = Request::from_parts(parts, Body::from(body)); + match (self, executor) { + (Self::Embedded(embedded), _) => { + if proxy::prepare_headers(request.headers_mut(), inner, &context, false).is_err() { + return response(StatusCode::BAD_REQUEST); + } + rewrite_path(&mut request, "/graphql"); + request.extensions_mut().insert(context); + match embedded.router.clone().oneshot(request).await { + Ok(response) => response, + Err(never) => match never {}, + } + } + (Self::Remote(remote), GraphqlExecutor::Remote { origin }) => { + rewrite_path(&mut request, &remote.http_path); + proxy::forward_with_permit(inner, origin, false, context, request, permit).await + } + _ => response(StatusCode::SERVICE_UNAVAILABLE), + } + } +} + +fn rewrite_path(request: &mut Request, path: &str) { + let target = request + .uri() + .query() + .map_or_else(|| path.to_owned(), |query| format!("{path}?{query}")); + *request.uri_mut() = target.parse().expect("validated path and request query"); +} + +async fn remote_websocket( + inner: &NativeInner, + origin: &str, + path: &str, + capabilities: GraphqlCapabilities, + context: RequestContext, + request: Request, +) -> Response { + let permit = match inner.permits.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + }; + let (mut parts, _) = request.into_parts(); + let offered = parts + .headers + .get(header::SEC_WEBSOCKET_PROTOCOL) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let protocol = if offered + .split(',') + .any(|p| p.trim() == "graphql-transport-ws") + { + "graphql-transport-ws" + } else if offered.split(',').any(|p| p.trim() == "graphql-ws") { + "graphql-ws" + } else { + return response(StatusCode::BAD_REQUEST); + }; + let upgrade = match WebSocketUpgrade::from_request_parts(&mut parts, &()).await { + Ok(upgrade) => upgrade, + Err(rejection) => return rejection.into_response(), + }; + if proxy::prepare_headers(&mut parts.headers, inner, &context, true).is_err() { + return response(StatusCode::BAD_REQUEST); + } + parts.headers.insert( + header::SEC_WEBSOCKET_PROTOCOL, + HeaderValue::from_static(protocol), + ); + let Some(key) = parts.headers.get(header::SEC_WEBSOCKET_KEY) else { + return response(StatusCode::BAD_REQUEST); + }; + let accept = tokio_tungstenite::tungstenite::handshake::derive_accept_key(key.as_bytes()); + if proxy::add_hop(&mut parts.headers, inner).is_err() { + return response(StatusCode::BAD_REQUEST); + } + let pending = inner + .client + .get(format!( + "{}{path}{}", + origin.trim_end_matches('/'), + parts + .uri + .query() + .map_or(String::new(), |query| format!("?{query}")) + )) + .headers(parts.headers) + .send(); + let upstream = + match tokio::time::timeout(inner.options.limits.response_header_timeout, pending).await { + Ok(Ok(upstream)) => upstream, + Err(_) => return response(StatusCode::GATEWAY_TIMEOUT), + _ => return response(StatusCode::BAD_GATEWAY), + }; + if upstream.status() != StatusCode::SWITCHING_PROTOCOLS { + let status = upstream.status(); + let mut headers = upstream.headers().clone(); + proxy::strip_hop_headers(&mut headers); + // The client already enforces idle read timeout. Retain capacity until + // the terminal upstream body finishes or the consumer disconnects. + let stream = upstream.bytes_stream().map(move |chunk| { + let _ = &permit; + chunk + }); + let mut result = Response::new(Body::from_stream(stream)); + *result.status_mut() = status; + *result.headers_mut() = headers; + return result; + } + if upstream + .headers() + .get(header::SEC_WEBSOCKET_ACCEPT) + .and_then(|v| v.to_str().ok()) + != Some(accept.as_str()) + || upstream + .headers() + .get(header::SEC_WEBSOCKET_PROTOCOL) + .and_then(|v| v.to_str().ok()) + != Some(protocol) + { + return response(StatusCode::BAD_GATEWAY); + } + let mut headers = upstream.headers().clone(); + for name in [ + header::SEC_WEBSOCKET_ACCEPT, + header::SEC_WEBSOCKET_PROTOCOL, + header::CONNECTION, + header::UPGRADE, + header::CONTENT_LENGTH, + ] { + headers.remove(name); + } + let lifetime = context + .identity() + .map_or(inner.options.limits.upgrade_lifetime, |id| { + inner + .options + .limits + .upgrade_lifetime + .min(Duration::from_secs( + id.expires_at().saturating_sub(super::now()), + )) + }); + let max_message = inner.options.limits.request_body_bytes; + let mut response = upgrade + .protocols([protocol]) + .max_message_size(max_message) + .on_upgrade(move |socket| async move { + let _permit = permit; + let _ = tokio::time::timeout(lifetime, async move { + let Ok(upstream) = upstream.upgrade().await else { + return; + }; + let upstream = WebSocketStream::from_raw_socket( + upstream, + Role::Client, + Some( + tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default() + .max_message_size(Some(max_message)), + ), + ) + .await; + bridge(socket, upstream, capabilities, protocol).await; + }) + .await; + }) + .into_response(); + for (name, value) in &headers { + response.headers_mut().append(name, value.clone()); + } + response +} + +async fn bridge( + mut client: WebSocket, + mut origin: WebSocketStream, + capabilities: GraphqlCapabilities, + protocol: &str, +) { + let mut admitted = false; + let mut active = BTreeSet::new(); + loop { + tokio::select! { + message = client.recv() => { + let Some(Ok(message)) = message else { break }; + match message { + Message::Text(text) => { + if let Ok(value) = serde_json::from_str::(&text) { + match value["type"].as_str() { + Some("subscribe" | "start") => { + let Some(id) = value["id"].as_str() else { break }; + if !admitted || id.len() > 256 || active.len() >= 128 || active.contains(id) { break; } + if let Err(error) = admit_request(&value["payload"], capabilities) { + let payload = serde_json::json!({ "id": id, "type": if protocol == "graphql-ws" { "data" } else { "next" }, "payload": error.envelope() }); + if client.send(Message::Text(payload.to_string().into())).await.is_err() { break; } + if client.send(Message::Text(serde_json::json!({ "id": id, "type": "complete" }).to_string().into())).await.is_err() { break; } + continue; + } + active.insert(id.to_owned()); + } + Some("complete" | "stop") => { if let Some(id) = value["id"].as_str() { active.remove(id); } } + _ => {} + } + } + if origin.send(UpstreamMessage::Text(text.to_string().into())).await.is_err() { break; } + } + Message::Binary(_) => break, // GraphQL WS uses JSON text; never bypass operation admission. + Message::Ping(bytes) => { if origin.send(UpstreamMessage::Ping(bytes)).await.is_err() { break; } } + Message::Pong(bytes) => { if origin.send(UpstreamMessage::Pong(bytes)).await.is_err() { break; } } + Message::Close(frame) => { + let frame = frame.map(|frame| tokio_tungstenite::tungstenite::protocol::CloseFrame { code: frame.code.into(), reason: frame.reason.to_string().into() }); + let _ = origin.send(UpstreamMessage::Close(frame)).await; + break; + }, + } + } + message = origin.next() => { + let Some(Ok(message)) = message else { break }; + let downstream = match message { + UpstreamMessage::Text(text) => { + if let Ok(value) = serde_json::from_str::(&text) { + if value["type"] == "connection_ack" { admitted = true; } + if matches!(value["type"].as_str(), Some("complete" | "error")) { if let Some(id) = value["id"].as_str() { active.remove(id); } } + } + Message::Text(text.to_string().into()) + } + UpstreamMessage::Binary(bytes) => Message::Binary(bytes), + UpstreamMessage::Ping(bytes) => Message::Ping(bytes), + UpstreamMessage::Pong(bytes) => Message::Pong(bytes), + UpstreamMessage::Close(frame) => { + let frame = frame.map(|frame| axum::extract::ws::CloseFrame { code: frame.code.into(), reason: frame.reason.to_string().into() }); + let _ = client.send(Message::Close(frame)).await; + break; + }, + UpstreamMessage::Frame(_) => continue, + }; + if client.send(downstream).await.is_err() { break; } + } + } + } + let _ = client.send(Message::Close(None)).await; + let _ = origin.close(None).await; +} diff --git a/src/gateway/native/mod.rs b/src/gateway/native/mod.rs index 4c3764a09..35676cf29 100644 --- a/src/gateway/native/mod.rs +++ b/src/gateway/native/mod.rs @@ -1,6 +1,10 @@ //! Opt-in native HTTP gateway. Construction starts no listener or projector. mod assets; +#[cfg(feature = "gateway-graphql-native")] +mod graphql; mod proxy; +#[cfg(feature = "gateway-graphql-native")] +pub use graphql::{EmbeddedGraphql, GraphqlBinding, RemoteGraphql}; use super::{ Admission, AuthError, BackendCredential, BindingKind, Credentials, Gateway, GatewayAdapter, @@ -111,6 +115,9 @@ impl NativeOptions { pub enum NativeBinding { /// Complete application router; URI is preserved, without prefix stripping. Handler(Router), + /// Embedded or complete remote GraphQL executor. + #[cfg(feature = "gateway-graphql-native")] + Graphql(GraphqlBinding), /// Configured UI proxy. Upgrades are disabled unless explicitly selected. UiProxy { /// Whether this target may negotiate a WebSocket upgrade. @@ -171,13 +178,34 @@ impl NativeGateway { let declaration = gateway .binding(&id) .ok_or(GatewayError("undeclared native binding"))?; - let compatible = matches!( + #[allow(unused_mut)] + let mut compatible = matches!( (&declaration.kind, &binding), (BindingKind::Handler, NativeBinding::Handler(_)) | (BindingKind::UiProxy { .. }, NativeBinding::UiProxy { .. }) | (BindingKind::Assets, NativeBinding::Assets(_)) | (BindingKind::Admission, NativeBinding::Admission(_)) ); + #[cfg(feature = "gateway-graphql-native")] + if let ( + BindingKind::Graphql { + executor, + capabilities, + delivery, + schema_extensions, + }, + NativeBinding::Graphql(binding), + ) = (&declaration.kind, &binding) + { + binding.validate( + executor, + *capabilities, + *delivery, + schema_extensions, + &origin, + )?; + compatible = true; + } if !compatible { return Err(GatewayError("incompatible native binding")); } @@ -365,6 +393,12 @@ impl GatewayAdapter for NativeGateway { }; proxy::forward(&self.0, origin, *websocket, context, request).await } + #[cfg(feature = "gateway-graphql-native")] + NativeBinding::Graphql(binding) => { + binding + .execute(&self.0, &selected.binding().kind, context, request) + .await + } NativeBinding::Assets(assets) => assets.serve(request), NativeBinding::Admission(_) => response(StatusCode::SERVICE_UNAVAILABLE), } diff --git a/src/gateway/native/proxy.rs b/src/gateway/native/proxy.rs index bc32816ff..07f2d0266 100644 --- a/src/gateway/native/proxy.rs +++ b/src/gateway/native/proxy.rs @@ -6,7 +6,7 @@ use axum::http::header; use futures_util::{Stream, StreamExt}; use std::{io, time::Duration}; -fn strip_hop_headers(headers: &mut HeaderMap) { +pub(super) fn strip_hop_headers(headers: &mut HeaderMap) { let named: Vec<_> = headers .get_all(header::CONNECTION) .iter() @@ -80,12 +80,23 @@ pub(super) async fn forward( origin: &str, allow_websocket: bool, context: RequestContext, - mut request: Request, + request: Request, ) -> Response { let permit = match inner.permits.clone().try_acquire_owned() { Ok(permit) => permit, Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), }; + forward_with_permit(inner, origin, allow_websocket, context, request, permit).await +} + +pub(super) async fn forward_with_permit( + inner: &NativeInner, + origin: &str, + allow_websocket: bool, + context: RequestContext, + mut request: Request, + permit: tokio::sync::OwnedSemaphorePermit, +) -> Response { if request .headers() .get(header::CONTENT_LENGTH) @@ -112,20 +123,9 @@ pub(super) async fn forward( if prepare_headers(request.headers_mut(), inner, &context, wants_upgrade).is_err() { return response(StatusCode::BAD_REQUEST); } - let hops = request - .headers() - .get("x-distributed-gateway-hops") - .and_then(|v| v.to_str().ok()) - .map_or_else( - || inner.hop_id.clone(), - |previous| format!("{previous},{}", inner.hop_id), - ); - let Ok(hops) = HeaderValue::from_str(&hops) else { + if add_hop(request.headers_mut(), inner).is_err() { return response(StatusCode::BAD_REQUEST); - }; - request - .headers_mut() - .insert("x-distributed-gateway-hops", hops); + } let target = request.uri().path_and_query().map_or("/", |p| p.as_str()); // Path ownership already rejected traversal/authority aliases. A configured // origin is concatenated with origin-form target, never joined to a URL. @@ -228,3 +228,21 @@ pub(super) async fn forward( *result.headers_mut() = headers; result } + +pub(super) fn add_hop(headers: &mut HeaderMap, inner: &NativeInner) -> Result<(), ()> { + let hops = headers + .get("x-distributed-gateway-hops") + .and_then(|v| v.to_str().ok()) + .map_or_else( + || inner.hop_id.clone(), + |previous| format!("{previous},{}", inner.hop_id), + ); + if hops.len() > 512 { + return Err(()); + } + headers.insert( + "x-distributed-gateway-hops", + HeaderValue::from_str(&hops).map_err(|_| ())?, + ); + Ok(()) +} diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 74e2a76b7..51ddf3cd2 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -27,6 +27,7 @@ impl GraphqlEngineBuilder { introspection_for_anonymous: true, statement_timeout: Duration::from_secs(5), graphiql: false, + subscriptions: true, typed_commands: TypedCommandInventory::empty(), projectors: Vec::new(), change_rx: None, @@ -37,6 +38,13 @@ impl GraphqlEngineBuilder { } } + /// Include live roots in the runtime schema and generated client surface. + /// Query-only gateway executors disable this before schema construction. + pub fn subscriptions(mut self, enabled: bool) -> Self { + self.subscriptions = enabled; + self + } + pub fn model(mut self, perms: ModelPermissions) -> Self { let schema = M::schema().clone(); if let Err(e) = self.insert_catalog(schema.clone(), true) { @@ -725,7 +733,7 @@ impl GraphqlEngineBuilder { SqlDialect::Postgres => SurfaceDialect::Postgres, }, aggregates: true, - subscriptions: true, + subscriptions: self.subscriptions, default_limit: self.default_limit, max_limit: self.max_limit, }; diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index 472db32d7..40b75d6fc 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -309,6 +309,7 @@ pub struct GraphqlEngineBuilder { pub(crate) introspection_for_anonymous: bool, pub(crate) statement_timeout: Duration, pub(crate) graphiql: bool, + pub(crate) subscriptions: bool, pub(crate) typed_commands: TypedCommandInventory, pub(crate) projectors: Vec, pub(crate) change_rx: Option>, diff --git a/src/graphql/http.rs b/src/graphql/http.rs index 8a738870d..602e9ff40 100644 --- a/src/graphql/http.rs +++ b/src/graphql/http.rs @@ -54,6 +54,30 @@ pub fn graphiql_page() -> Html { ) } +/// Per-operation execution admission for a composed GraphQL surface. The +/// filter runs for HTTP and each WS operation, after ordinary authentication. +/// It may restrict the surface but never supplies identity or commit evidence. +pub type GraphqlOperationFilter = Arc Result<(), ServerError> + Send + Sync>; + +/// Resource lease supplied only by the native gateway adapter. +pub struct GraphqlConnectionGuard { + pub(crate) lifetime: std::time::Duration, + pub(crate) _permit: tokio::sync::OwnedSemaphorePermit, +} +impl GraphqlConnectionGuard { + /// Run a custom executor connection within its admitted lifetime. Keep this + /// guard alive until completion to retain the gateway capacity permit. + pub async fn run(&self, connection: F) -> Option { + tokio::time::timeout(self.lifetime, connection).await.ok() + } +} + +#[derive(Default)] +struct GraphqlWsOptions { + filter: Option, + guard: Option>, +} + /// [`Executor`] for WebSocket subscriptions. /// /// Prefers a [`Session`] injected via `connection_init` / `session_data` (GraphiQL @@ -64,6 +88,7 @@ pub struct GraphqlSessionExecutor { session: Session, principal: Option, host: Option, + filter: Option, } impl GraphqlSessionExecutor { @@ -73,6 +98,7 @@ impl GraphqlSessionExecutor { session, principal: None, host: None, + filter: None, } } @@ -81,18 +107,23 @@ impl GraphqlSessionExecutor { session: Session, principal: Option, host: Option, + filter: Option, ) -> Self { Self { engine, session, principal, host, + filter, } } } impl Executor for GraphqlSessionExecutor { async fn execute(&self, request: Request) -> GqlResponse { + if let Some(Err(error)) = self.filter.as_ref().map(|filter| filter(&request)) { + return GqlResponse::from_errors(vec![error]); + } // Subscriptions must not go through execute() — that yields // "Subscription root not found". GraphiQL should use the WS path only. self.engine @@ -113,6 +144,11 @@ impl Executor for GraphqlSessionExecutor { session_data: Option>, ) -> BoxStream<'static, GqlResponse> { use std::any::TypeId; + if let Some(Err(error)) = self.filter.as_ref().map(|filter| filter(&request)) { + return Box::pin(futures_util::stream::once(async move { + GqlResponse::from_errors(vec![error]) + })); + } let session = session_data .as_ref() .and_then(|d| d.get(&TypeId::of::())) @@ -231,10 +267,22 @@ pub fn graphql_router_with_dispatcher( /// GraphQL router that wait-dispatches through an explicit command host. pub fn graphql_router_with_host(engine: Arc, host: SharedCommandHost) -> Router { + graphql_router_composed(engine, Some(host), None) +} + +/// Compose the existing HTTP and WS handlers with an operation filter. A +/// query-only executor can omit the command host entirely. Callers still own +/// schema construction; filters cannot hide fields from schema introspection. +pub fn graphql_router_composed( + engine: Arc, + host: Option, + filter: Option, +) -> Router { let graphiql = engine.graphiql_enabled(); let state = GraphqlHttpState { engine, - host: Some(host), + host, + filter, }; let mut router = Router::new() .route( @@ -256,6 +304,7 @@ pub fn graphql_router_with_host(engine: Arc, host: SharedCommandH struct GraphqlHttpState { engine: Arc, host: Option, + filter: Option, } fn unauthorized_response() -> Response { @@ -333,6 +382,9 @@ async fn graphql_handler_with_service( Err(AuthError::Unauthorized) => return unauthorized_response(), }; let (session, principal) = identity.into_parts(); + if let Some(Err(error)) = state.filter.as_ref().map(|filter| filter(&request)) { + return GraphQLResponse::from(GqlResponse::from_errors(vec![error])).into_response(); + } let mut request = request_with_principal(request, principal); if let Some(host) = &state.host { request = request.data(Arc::clone(host)); @@ -404,6 +456,7 @@ pub async fn microsvc_graphql_ws( headers: HeaderMap, uri: axum::http::Uri, protocol: GraphQLProtocol, + guard: Option>>, upgrade: WebSocketUpgrade, ) -> Response { let engine = match service.graphql_engine() { @@ -411,7 +464,19 @@ pub async fn microsvc_graphql_ws( None => return StatusCode::NOT_FOUND.into_response(), }; let host: SharedCommandHost = Arc::new(LocalCommandHost::new(Arc::clone(&service))); - graphql_ws_upgrade(engine, Some(host), headers, uri, protocol, upgrade).await + graphql_ws_upgrade( + engine, + Some(host), + GraphqlWsOptions { + filter: None, + guard: guard.map(|guard| guard.0), + }, + headers, + uri, + protocol, + upgrade, + ) + .await } async fn graphql_ws_with_host( @@ -419,14 +484,28 @@ async fn graphql_ws_with_host( headers: HeaderMap, uri: axum::http::Uri, protocol: GraphQLProtocol, + guard: Option>>, upgrade: WebSocketUpgrade, ) -> Response { - graphql_ws_upgrade(state.engine, state.host, headers, uri, protocol, upgrade).await + graphql_ws_upgrade( + state.engine, + state.host, + GraphqlWsOptions { + filter: state.filter, + guard: guard.map(|guard| guard.0), + }, + headers, + uri, + protocol, + upgrade, + ) + .await } async fn graphql_ws_upgrade( engine: Arc, host: Option, + options: GraphqlWsOptions, headers: HeaderMap, uri: axum::http::Uri, protocol: GraphQLProtocol, @@ -459,6 +538,7 @@ async fn graphql_ws_upgrade( upgrade_session.clone(), upgrade_principal, host, + options.filter, ); let engine_for_init = Arc::clone(&engine); upgrade @@ -466,7 +546,7 @@ async fn graphql_ws_upgrade( .on_upgrade(move |socket| { let base = upgrade_session; let upgrade_headers = upgrade_headers; - GraphQLWebSocket::new(socket, executor, protocol) + let serve = GraphQLWebSocket::new(socket, executor, protocol) .on_connection_init(move |payload| { let base = base.clone(); let engine = engine_for_init; @@ -490,7 +570,15 @@ async fn graphql_ws_upgrade( Ok(data) } }) - .serve() + .serve(); + async move { + if let Some(guard) = options.guard { + let _ = tokio::time::timeout(guard.lifetime, serve).await; + drop(guard); + } else { + serve.await; + } + } }) .into_response() } diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index 9c676cf09..a92ea8dab 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -74,8 +74,8 @@ pub use engine::{ }; #[cfg(feature = "graphql")] pub use http::{ - graphiql_page, graphql_router, graphql_router_with_dispatcher, graphql_router_with_host, - graphql_router_with_service, + graphiql_page, graphql_router, graphql_router_composed, graphql_router_with_dispatcher, + graphql_router_with_host, graphql_router_with_service, GraphqlOperationFilter, }; #[cfg(feature = "graphql")] pub use identity::{ diff --git a/tests/gateway-portable/Cargo.lock b/tests/gateway-portable/Cargo.lock index d9b925ef5..9577e8892 100644 --- a/tests/gateway-portable/Cargo.lock +++ b/tests/gateway-portable/Cargo.lock @@ -8,6 +8,30 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "async-graphql-parser" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64ef70f77a1c689111e52076da1cd18f91834bcb847de0a9171f83624b07fbf" +dependencies = [ + "async-graphql-value", + "pest", + "serde", + "serde_json", +] + +[[package]] +name = "async-graphql-value" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3ef112905abea9dea592fc868a6873b10ebd3f983e83308f995d6284e9ba41" +dependencies = [ + "bytes", + "indexmap", + "serde", + "serde_json", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -70,6 +94,15 @@ version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -120,6 +153,7 @@ dependencies = [ name = "distributed" version = "0.1.0" dependencies = [ + "async-graphql-parser", "async-trait", "base64", "bitcode", @@ -337,6 +371,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -386,6 +422,16 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pest" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d45aeb61b4bf818e12d4205f2466f8c4748f85f4fce0146d1c03d69d753f0ad" +dependencies = [ + "memchr", + "ucd-trie", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -613,6 +659,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/tests/gateway-portable/Cargo.toml b/tests/gateway-portable/Cargo.toml index 6a5554ce7..6cbb3f314 100644 --- a/tests/gateway-portable/Cargo.toml +++ b/tests/gateway-portable/Cargo.toml @@ -9,6 +9,7 @@ publish = false [features] default = ["gateway"] gateway = ["distributed/gateway"] +gateway-graphql = ["gateway", "distributed/gateway-graphql"] [dependencies] distributed = { path = "../..", default-features = false } @@ -27,3 +28,7 @@ path = "../gateway_extensions.rs" [[test]] name = "gateway_auth" path = "../gateway_auth.rs" + +[[test]] +name = "gateway_graphql_operation" +path = "../gateway_graphql_operation.rs" diff --git a/tests/gateway-portable/check_dependencies.py b/tests/gateway-portable/check_dependencies.py index 08777783a..a65e23309 100644 --- a/tests/gateway-portable/check_dependencies.py +++ b/tests/gateway-portable/check_dependencies.py @@ -2,10 +2,12 @@ """Fail if the UI/auth consumer starts depending on a native runtime or executor.""" from pathlib import Path import subprocess +import sys manifest = Path(__file__).resolve().with_name("Cargo.toml") for target in (None, "wasm32-unknown-unknown"): command = ["cargo", "tree", "--manifest-path", str(manifest), "--locked", "--edges", "normal", "--prefix", "none"] + command += sys.argv[1:] if target: command += ["--target", target] output = subprocess.check_output(command, text=True) diff --git a/tests/gateway_graphql.rs b/tests/gateway_graphql.rs new file mode 100644 index 000000000..0dcc28653 --- /dev/null +++ b/tests/gateway_graphql.rs @@ -0,0 +1,442 @@ +#![cfg(all(feature = "gateway-graphql-native", feature = "sqlite"))] +use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema, Subscription}; +use async_graphql_axum::{GraphQLProtocol, GraphQLRequest, GraphQLResponse, GraphQLWebSocket}; +use axum::{ + extract::ws::WebSocketUpgrade, + http::StatusCode, + response::IntoResponse, + routing::{get, post}, + Router, +}; +use distributed::gateway::{native::*, *}; +use distributed::graphql::{read, GraphqlEngine, ModelPermissions}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::{ + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, + time::Duration, +}; +use tokio::task::JoinHandle; +use tokio_tungstenite::{ + tungstenite::{client::IntoClientRequest, Message}, + MaybeTlsStream, WebSocketStream, +}; + +struct Server { + origin: String, + task: JoinHandle<()>, +} +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn serve(router: Router) -> Server { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + Server { + origin, + task: tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }), + } +} +fn mounted( + binding: GraphqlBinding, + executor: GraphqlExecutor, + caps: GraphqlCapabilities, + extensions: Vec, +) -> Router { + mounted_with_options( + binding, + executor, + caps, + extensions, + NativeOptions::new("https://public.example.invalid"), + ) +} +fn mounted_with_options( + binding: GraphqlBinding, + executor: GraphqlExecutor, + caps: GraphqlCapabilities, + extensions: Vec, + options: NativeOptions, +) -> Router { + let gateway = GatewayConfig { + bindings: vec![Binding::new( + "graphql", + BindingKind::Graphql { + executor, + capabilities: caps, + delivery: DeliveryCapabilities::default(), + schema_extensions: extensions, + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "graphql")], + } + .build() + .unwrap(); + NativeGateway::new( + gateway, + options, + [("graphql".into(), NativeBinding::Graphql(binding))], + NativeAuth::anonymous(), + ) + .unwrap() + .router() +} +struct CustomQuery; +#[Object] +impl CustomQuery { + async fn extension_value(&self, input: String) -> String { + input + } +} +fn custom_router(filter: distributed::graphql::GraphqlOperationFilter) -> Router { + let schema = Schema::build(CustomQuery, EmptyMutation, EmptySubscription).finish(); + Router::new().route( + "/graphql", + post(move |request: GraphQLRequest| { + let schema = schema.clone(); + let filter = filter.clone(); + async move { + let request = request.into_inner(); + let mut result = match filter(&request) { + Ok(()) => schema.execute(request).await, + Err(error) => async_graphql::Response::from_errors(vec![error]), + }; + result.extensions.insert( + "originProof".into(), + async_graphql::value!({"generation": "g7", "opaque": "unchanged"}), + ); + GraphQLResponse::from(result) + } + }), + ) +} + +#[tokio::test] +async fn embedded_remote_parity() { + let caps = GraphqlCapabilities { + queries: true, + ..Default::default() + }; + let embedded = EmbeddedGraphql::custom(custom_router, caps, ["extra-field".into()]).unwrap(); + let direct = serve(mounted( + GraphqlBinding::Embedded(embedded.clone()), + GraphqlExecutor::Embedded, + caps, + vec!["extra-field".into()], + )) + .await; + // Custom fields are registered at the complete origin executor. The remote + // binding has no local schema extensions or field federation. + let origin = serve(custom_router(Arc::new(|_| Ok(())))).await; + let remote = serve(mounted( + GraphqlBinding::Remote(RemoteGraphql { + live_path: None, + ..Default::default() + }), + GraphqlExecutor::Remote { + origin: origin.origin.clone(), + }, + caps, + vec![], + )) + .await; + let client = reqwest::Client::new(); + for request in [ + json!({ "query": "query First { extensionValue(input: \"wrong\") } query Selected($input: String!) { chosen: extensionValue(input: $input) }", "operationName": "Selected", "variables": { "input": "selected" }, "extensions": { "requestTag": "opaque" } }), + json!({ "query": "{ unknownField }" }), + json!({ "query": "query A { extensionValue(input: \"a\") } query B { extensionValue(input: \"b\") }" }), + json!({ "query": "mutation Forbidden { write }" }), + ] { + let left = client + .post(format!("{}/graphql", direct.origin)) + .json(&request) + .send() + .await + .unwrap(); + let right = client + .post(format!("{}/graphql", remote.origin)) + .json(&request) + .send() + .await + .unwrap(); + assert_eq!(left.status(), right.status()); + let left: Value = left.json().await.unwrap(); + let right: Value = right.json().await.unwrap(); + assert_eq!(left, right, "{request}"); + if request["operationName"] == "Selected" { + assert_eq!(left["data"], json!({"chosen": "selected"})); + assert_eq!(left["extensions"]["originProof"]["generation"], "g7"); + } + } + let mut ws_request = format!("{}/graphql/ws", remote.origin.replace("http:", "ws:")) + .into_client_request() + .unwrap(); + ws_request.headers_mut().insert( + "sec-websocket-protocol", + "graphql-transport-ws".parse().unwrap(), + ); + assert!(tokio_tungstenite::connect_async(ws_request).await.is_err()); +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, distributed::ReadModel)] +#[readmodel(table = "gateway_items", primary_key = ["id"])] +struct Item { + id: String, +} +#[tokio::test] +async fn query_only_schema_is_built_without_command_or_subscription_roots() { + let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap(); + let engine = Arc::new( + GraphqlEngine::builder(pool) + .roles(&["user"]) + .anonymous_role("user") + .subscriptions(false) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .build() + .unwrap(), + ); + let caps = GraphqlCapabilities { + queries: true, + ..Default::default() + }; + let schema = engine.sdl_for_role("user").unwrap(); + assert!(!schema.contains("type Mutation")); + assert!(!schema.contains("type Subscription")); + let embedded = EmbeddedGraphql::new(engine, None, caps).unwrap(); + let server = serve(mounted( + GraphqlBinding::Embedded(embedded), + GraphqlExecutor::Embedded, + caps, + vec![], + )) + .await; + let value: Value = reqwest::Client::new() + .post(format!("{}/graphql", server.origin)) + .json(&json!({"query":"{ __schema { mutationType { name } subscriptionType { name } } }"})) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + value["data"]["__schema"], + json!({"mutationType": null, "subscriptionType": null}) + ); +} + +struct Writes(Arc); +#[Object] +impl Writes { + async fn write(&self) -> i32 { + self.0.fetch_add(1, Ordering::SeqCst); + 1 + } +} +struct Ticks; +#[Subscription] +impl Ticks { + async fn ticks(&self) -> impl futures_util::Stream { + futures_util::stream::iter([1]) + } +} +type Socket = WebSocketStream>; +async fn ws_json(socket: &mut Socket) -> Value { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + match socket.next().await.unwrap().unwrap() { + Message::Text(text) => return serde_json::from_str(&text).unwrap(), + Message::Ping(bytes) => { + socket.send(Message::Pong(bytes)).await.unwrap(); + } + other => panic!("unexpected {other:?}"), + } + } + }) + .await + .unwrap() +} +async fn connect(origin: &str) -> Socket { + let mut request = format!("{}/graphql/ws", origin.replace("http:", "ws:")) + .into_client_request() + .unwrap(); + request.headers_mut().insert( + "sec-websocket-protocol", + "graphql-transport-ws".parse().unwrap(), + ); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + socket + .send(Message::Text( + json!({"type":"connection_init","payload":{}}) + .to_string() + .into(), + )) + .await + .unwrap(); + assert_eq!(ws_json(&mut socket).await, json!({"type":"connection_ack"})); + socket +} + +#[tokio::test] +async fn remote_ws_checks_selected_operations_and_preserves_ids() { + let writes = Arc::new(AtomicUsize::new(0)); + let schema = Schema::build(CustomQuery, Writes(writes.clone()), Ticks).finish(); + let origin = serve(Router::new().route( + "/graphql/ws", + get( + move |protocol: GraphQLProtocol, upgrade: WebSocketUpgrade| { + let schema = schema.clone(); + async move { + upgrade + .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS) + .on_upgrade(move |socket| { + GraphQLWebSocket::new(socket, schema, protocol).serve() + }) + .into_response() + } + }, + ), + )) + .await; + let caps = GraphqlCapabilities { + queries: true, + live: true, + commands: false, + }; + let remote = serve(mounted( + GraphqlBinding::Remote(RemoteGraphql::default()), + GraphqlExecutor::Remote { + origin: origin.origin.clone(), + }, + caps, + vec![], + )) + .await; + let mut socket = connect(&remote.origin).await; + socket.send(Message::Text(json!({"id":"query-id","type":"subscribe","payload":{"query":"query Wrong { extensionValue(input: \"wrong\") } query Right($value:String!) { extensionValue(input:$value) }", "operationName":"Right", "variables":{"value":"right"}}}).to_string().into())).await.unwrap(); + let next = ws_json(&mut socket).await; + assert_eq!(next["id"], "query-id"); + assert_eq!(next["payload"]["data"], json!({"extensionValue":"right"})); + assert_eq!(ws_json(&mut socket).await["type"], "complete"); + socket + .send(Message::Text( + json!({"id":"mutation-id","type":"subscribe","payload":{"query":"mutation { write }"}}) + .to_string() + .into(), + )) + .await + .unwrap(); + let denied = ws_json(&mut socket).await; + assert_eq!(denied["id"], "mutation-id"); + assert_eq!( + denied["payload"]["errors"][0]["extensions"]["code"], + "OPERATION_NOT_MOUNTED" + ); + assert_eq!(ws_json(&mut socket).await["type"], "complete"); + socket + .send(Message::Text( + json!({"id":"live-id","type":"subscribe","payload":{"query":"subscription { ticks }"}}) + .to_string() + .into(), + )) + .await + .unwrap(); + assert_eq!( + ws_json(&mut socket).await["payload"]["data"], + json!({"ticks":1}) + ); + assert_eq!(ws_json(&mut socket).await["type"], "complete"); + socket.close(None).await.unwrap(); + let mut binary = connect(&remote.origin).await; + binary + .send(Message::Binary( + json!({"id":"binary","type":"subscribe","payload":{"query":"mutation { write }"}}) + .to_string() + .into_bytes() + .into(), + )) + .await + .unwrap(); + let _ = tokio::time::timeout(Duration::from_secs(2), binary.next()) + .await + .unwrap(); + assert_eq!(writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn reloading_response_is_preserved_without_retry_or_receipt() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + let origin = serve(Router::new().fallback(move || { let calls = counted.clone(); async move { + calls.fetch_add(1, Ordering::SeqCst); + (StatusCode::SERVICE_UNAVAILABLE, axum::Json(json!({"errors":[{"message":"application generation is reloading", "extensions":{"code":"APPLICATION_RELOADING"}}]}))) + }})).await; + let caps = GraphqlCapabilities { + commands: true, + queries: true, + live: false, + }; + let remote = serve(mounted( + GraphqlBinding::Remote(RemoteGraphql::default()), + GraphqlExecutor::Remote { + origin: origin.origin.clone(), + }, + caps, + vec![], + )) + .await; + let response = reqwest::Client::new().post(format!("{}/graphql", remote.origin)).json(&json!({"query":"mutation Write($commandId: ID!) { write(commandId:$commandId) }", "variables":{"commandId":"exact-id"}})).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let body: Value = response.json().await.unwrap(); + assert_eq!( + body, + json!({"errors":[{"message":"application generation is reloading", "extensions":{"code":"APPLICATION_RELOADING"}}]}) + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn timed_out_mutation_executes_once_and_returns_no_receipt() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + let origin = serve(Router::new().fallback(move || { + let calls = counted.clone(); + async move { + calls.fetch_add(1, Ordering::SeqCst); + std::future::pending::<()>().await; + StatusCode::OK + } + })) + .await; + let caps = GraphqlCapabilities { + commands: true, + queries: true, + live: false, + }; + let mut options = NativeOptions::new("https://public.example.invalid"); + options.limits.response_header_timeout = Duration::from_millis(100); + let remote = serve(mounted_with_options( + GraphqlBinding::Remote(RemoteGraphql::default()), + GraphqlExecutor::Remote { + origin: origin.origin.clone(), + }, + caps, + vec![], + options, + )) + .await; + let response = reqwest::Client::new() + .post(format!("{}/graphql", remote.origin)) + .json(&json!({"query":"mutation { write }"})) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT); + assert!(response.bytes().await.unwrap().is_empty()); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} diff --git a/tests/gateway_graphql_operation.rs b/tests/gateway_graphql_operation.rs new file mode 100644 index 000000000..be6c1a96c --- /dev/null +++ b/tests/gateway_graphql_operation.rs @@ -0,0 +1,65 @@ +#![cfg(feature = "gateway-graphql")] +use distributed::gateway::{graphql::*, GraphqlCapabilities}; +use serde_json::json; + +#[test] +fn selected_operation_and_status_follow_the_parser() { + let query = GraphqlCapabilities { + queries: true, + ..Default::default() + }; + let command = GraphqlCapabilities { + commands: true, + ..Default::default() + }; + let document = + "query Allowed { message(text: \"mutation { write }\") } mutation Blocked { write }"; + assert_eq!( + admit_operation(document, Some("Allowed"), query), + Ok(OperationKind::Query) + ); + assert_eq!( + admit_operation(document, Some("Blocked"), query), + Err(OperationError::NotMounted) + ); + assert_eq!( + admit_operation(document, None, query), + Err(OperationError::AmbiguousOperation) + ); + assert_eq!( + admit_operation(document, Some("Missing"), query), + Err(OperationError::UnknownOperation) + ); + let status = "query Recover { ...Recovery } fragment Recovery on Query { renamed: commandStatus(commandId: \"same-id\") { state } }"; + assert_eq!( + admit_operation(status, None, command), + Ok(OperationKind::CommandStatus) + ); + assert_eq!( + admit_operation(status, None, query), + Err(OperationError::NotMounted) + ); + assert_eq!( + admit_operation( + "{ commandStatus(commandId: \"id\") { state } items { id } }", + None, + command + ), + Err(OperationError::NotMounted) + ); + assert_eq!( + admit_request(&json!({"query":"{ ok }", "variables":[1]}), query), + Err(OperationError::InvalidRequest) + ); + assert_eq!( + admit_request( + &json!({"query":"{ ok }", "variables":null, "extensions":{"opaque":"value"}}), + query + ), + Ok(OperationKind::Query) + ); + assert_eq!( + operation_kind(&" ".repeat(MAX_DOCUMENT_BYTES + 1), None), + Err(OperationError::InvalidRequest) + ); +} diff --git a/tests/graphql_causal_transport/main.rs b/tests/graphql_causal_transport/main.rs index aa4724fd5..048c3db29 100644 --- a/tests/graphql_causal_transport/main.rs +++ b/tests/graphql_causal_transport/main.rs @@ -185,20 +185,108 @@ struct TestServer { http_url: String, ws_url: String, task: JoinHandle<()>, + upstream: Option>, } impl Drop for TestServer { fn drop(&mut self) { self.task.abort(); + if let Some(upstream) = &self.upstream { + upstream.abort(); + } } } +enum GatewayMode { + Direct, + #[cfg(feature = "gateway-graphql-native")] + Embedded, + #[cfg(feature = "gateway-graphql-native")] + Remote, +} + async fn spawn_server(service: Arc) -> TestServer { + spawn_server_mode(service, GatewayMode::Direct).await +} + +async fn spawn_server_mode(service: Arc, mode: GatewayMode) -> TestServer { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind test server"); let address = listener.local_addr().expect("test server address"); - let app = distributed::microsvc::router(service); + let mut upstream = None; + let app = match mode { + GatewayMode::Direct => distributed::microsvc::router(service), + #[cfg(feature = "gateway-graphql-native")] + mode => { + use distributed::gateway::{native::*, *}; + let engine = service.graphql_engine().unwrap(); + let provider = Arc::new(distributed::graphql::identity::OidcGatewayProvider::new( + engine.identity_config().oidc.clone().unwrap(), + "causal-fixture-v1", + )); + let auth = NativeAuth::new(move |credentials| { + let provider = provider.clone(); + async move { provider.authenticate(&credentials).await } + }); + let caps = GraphqlCapabilities { + commands: true, + queries: true, + live: true, + }; + let (executor, binding) = match mode { + GatewayMode::Embedded => ( + GraphqlExecutor::Embedded, + GraphqlBinding::Embedded( + EmbeddedGraphql::new( + engine, + Some(Arc::new( + distributed::command_dispatch::LocalCommandHost::new(service), + )), + caps, + ) + .unwrap(), + ), + ), + GatewayMode::Remote => { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + upstream = Some(tokio::spawn(async move { + axum::serve(listener, distributed::microsvc::router(service)) + .await + .unwrap() + })); + ( + GraphqlExecutor::Remote { origin }, + GraphqlBinding::Remote(RemoteGraphql::default()), + ) + } + GatewayMode::Direct => unreachable!(), + }; + let gateway = GatewayConfig { + bindings: vec![Binding::new( + "graphql", + BindingKind::Graphql { + executor, + capabilities: caps, + delivery: DeliveryCapabilities::default(), + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "graphql")], + } + .build() + .unwrap(); + NativeGateway::new( + gateway, + NativeOptions::new(format!("http://{address}")), + [("graphql".into(), NativeBinding::Graphql(binding))], + auth, + ) + .unwrap() + .router() + } + }; let task = tokio::spawn(async move { axum::serve(listener, app) .await @@ -208,6 +296,7 @@ async fn spawn_server(service: Arc) -> TestServer { http_url: format!("http://{address}/graphql"), ws_url: format!("ws://{address}/graphql/ws"), task, + upstream, } } @@ -372,6 +461,22 @@ async fn assert_http_ws_status_pair( #[tokio::test] async fn causal_receipt_status_replay_and_nonenumeration_match_http_and_ws() { + exercise_causal_transport(GatewayMode::Direct).await; +} + +#[cfg(feature = "gateway-graphql-native")] +#[tokio::test] +async fn gateway_embedded_causal_receipt_status_parity() { + exercise_causal_transport(GatewayMode::Embedded).await; +} + +#[cfg(feature = "gateway-graphql-native")] +#[tokio::test] +async fn gateway_remote_causal_receipt_status_parity() { + exercise_causal_transport(GatewayMode::Remote).await; +} + +async fn exercise_causal_transport(mode: GatewayMode) { let keys = TestKeys::new(); let mut oidc = OidcConfig::new(ISSUER, AUDIENCE) .with_static_jwks(keys.jwks.clone()) @@ -395,7 +500,7 @@ async fn causal_receipt_status_replay_and_nonenumeration_match_http_and_ws() { .try_with_graphql(engine) .expect("causal transport GraphQL attachment"), ); - let server = spawn_server(service).await; + let server = spawn_server_mode(service, mode).await; let writer_a = keys.token("subject-a", "writer"); let writer_b = keys.token("subject-b", "writer"); diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 9c453cb5e..6310e7af3 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -1219,19 +1219,51 @@ async fn query_over_http_and_graphql_ws( (http, next["payload"].clone()) } +#[derive(Clone, Copy)] +enum QueryGatewayMode { + Direct, + #[cfg(feature = "gateway-graphql-native")] + Embedded, + #[cfg(feature = "gateway-graphql-native")] + Remote, +} + #[tokio::test] async fn http_and_graphql_ws_serialize_the_same_query_revision_envelope() { + exercise_query_transport(QueryGatewayMode::Direct).await; +} + +#[cfg(feature = "gateway-graphql-native")] +#[tokio::test] +async fn gateway_embedded_query_revision_parity() { + exercise_query_transport(QueryGatewayMode::Embedded).await; +} + +#[cfg(feature = "gateway-graphql-native")] +#[tokio::test] +async fn gateway_remote_query_revision_parity() { + exercise_query_transport(QueryGatewayMode::Remote).await; +} + +async fn exercise_query_transport(mode: QueryGatewayMode) { let fixture = protocol_fixture_with_retention(10).await; - let engine = GraphqlEngine::builder(&fixture.repository) + let builder = GraphqlEngine::builder(&fixture.repository) .service_id(SERVICE_ID) .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) .roles(&["user"]) .anonymous_role("user") .model::(ModelPermissions::new().grant("user", read().all_columns())) .client_projectors([projector()]) - .change_stream(fixture.repository.read_model_changes()) - .build() - .expect("query transport parity engine"); + .change_stream(fixture.repository.read_model_changes()); + #[cfg(feature = "gateway-graphql-native")] + let builder = match mode { + QueryGatewayMode::Direct => builder, + _ => builder.identity(distributed::graphql::IdentityConfig::oidc_bearer( + distributed::graphql::OidcConfig::new("http://local-fixture.invalid", "query-api") + .require_auth(false), + )), + }; + let engine = builder.build().expect("query transport parity engine"); let service = Arc::new( Service::new() .named(SERVICE_ID) @@ -1242,8 +1274,67 @@ async fn http_and_graphql_ws_serialize_the_same_query_revision_envelope() { .await .expect("query transport listener"); let address = listener.local_addr().expect("query transport address"); + #[allow(unused_mut)] + let mut upstream = None::>; + let router = match mode { + QueryGatewayMode::Direct => distributed::microsvc::router(service), + #[cfg(feature = "gateway-graphql-native")] + mode => { + use distributed::gateway::{native::*, *}; + let caps = GraphqlCapabilities { + commands: false, + queries: true, + live: true, + }; + let (executor, binding) = match mode { + QueryGatewayMode::Embedded => ( + GraphqlExecutor::Embedded, + GraphqlBinding::Embedded( + EmbeddedGraphql::new(service.graphql_engine().unwrap(), None, caps) + .unwrap(), + ), + ), + QueryGatewayMode::Remote => { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + upstream = Some(tokio::spawn(async move { + axum::serve(listener, distributed::microsvc::router(service)) + .await + .unwrap() + })); + ( + GraphqlExecutor::Remote { origin }, + GraphqlBinding::Remote(RemoteGraphql::default()), + ) + } + QueryGatewayMode::Direct => unreachable!(), + }; + let config = GatewayConfig { + bindings: vec![Binding::new( + "graphql", + BindingKind::Graphql { + executor, + capabilities: caps, + delivery: DeliveryCapabilities::default(), + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "graphql")], + } + .build() + .unwrap(); + NativeGateway::new( + config, + NativeOptions::new(format!("http://{address}")), + [("graphql".into(), NativeBinding::Graphql(binding))], + NativeAuth::anonymous(), + ) + .unwrap() + .router() + } + }; let server = tokio::spawn(async move { - axum::serve(listener, distributed::microsvc::router(service)) + axum::serve(listener, router) .await .expect("query transport server"); }); @@ -1261,7 +1352,117 @@ async fn http_and_graphql_ws_serialize_the_same_query_revision_envelope() { "{case}: HTTP and GraphQL-WS must preserve one canonical query/revision envelope" ); } + // Exercise committed projection changes through the actual socket path, + // including redundant invalidation and immutable per-frame causal metadata. + let mut request = format!("ws://{address}/graphql/ws") + .into_client_request() + .unwrap(); + request.headers_mut().insert( + SEC_WEBSOCKET_PROTOCOL, + "graphql-transport-ws".parse().unwrap(), + ); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + socket + .send(WsMessage::Text( + json!({"type":"connection_init"}).to_string().into(), + )) + .await + .unwrap(); + let ack = socket.next().await.unwrap().unwrap(); + assert_eq!( + serde_json::from_str::(ack.to_text().unwrap()).unwrap()["type"], + "connection_ack" + ); + socket + .send(WsMessage::Text( + json!({"id":"live-proof", "type":"subscribe", "payload":{"query":LIVE_SUBSCRIPTION}}) + .to_string() + .into(), + )) + .await + .unwrap(); + let mut frames = Vec::new(); + for position in 1..=3 { + if position > 1 { + project_item( + &fixture.repository, + &fixture.bus, + position, + &format!("causal row {position}"), + ) + .await; + } + let frame = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let frame: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!(frame["id"], "live-proof"); + assert_eq!(frame["type"], "next"); + let title = if position == 1 { + "causal row".into() + } else { + format!("causal row {position}") + }; + assert_live_frame( + &frame["payload"], + "causal_query_views", + &title, + &position.to_string(), + false, + ); + if position > 1 { + assert_eq!( + distributed_envelope(&frame["payload"])["snapshot"]["observations"][0] + ["causationId"], + format!("query-protocol-command-{position}") + ); + } + frames.push(frame["payload"].clone()); + fixture + .repository + .publish_read_model_change(distributed::ReadModelChange::new(["causal_query_views"])); + let redundant = tokio::time::timeout(Duration::from_millis(350), socket.next()).await; + if position == 1 { + assert!( + redundant.is_err(), + "identical data and metadata must be suppressed" + ); + } else { + // The origin emits a proof-only frame as its causation suffix moves + // to the new head. Preserve it even though domain data is identical. + let redundant = redundant.unwrap().unwrap().unwrap(); + let proof: Value = serde_json::from_str(redundant.to_text().unwrap()).unwrap(); + assert_eq!(proof["id"], "live-proof"); + assert_eq!(proof["payload"]["data"], frame["payload"]["data"]); + assert_eq!( + distributed_envelope(&proof["payload"])["snapshot"]["observations"], + json!([]) + ); + fixture + .repository + .publish_read_model_change(distributed::ReadModelChange::new([ + "causal_query_views", + ])); + assert!( + tokio::time::timeout(Duration::from_millis(350), socket.next()) + .await + .is_err() + ); + } + } + for (i, frame) in frames.iter().enumerate() { + assert_eq!( + distributed_envelope(frame)["snapshot"]["indexes"][0]["position"], + (i + 1).to_string() + ); + } + socket.close(None).await.unwrap(); server.abort(); + if let Some(upstream) = upstream { + upstream.abort(); + } } #[tokio::test] From 15382d78a6022ce61ae07b83306ab22cc451598b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 22:03:52 -0500 Subject: [PATCH 053/484] feat(gateway): enforce causal freshness and primary read policy Bind explicit client context to origin authority, preserve pending effects and confirmed floors, and opt selected stale-tolerant queries into replicas. Verify physical standby pause, primary outage, backend mismatch and replay recovery with an isolated PostgreSQL fixture. Refs: [[tasks/application-gateway-6]] [[tasks/application-gateway-1]] --- .github/workflows/integration-gateway.yaml | 34 ++- Cargo.toml | 2 + .../src/client_compiler/render/artifact.rs | 3 + .../tests/fixtures/generated-operation.ts | 1 + .../fixtures/generated-scalar-operation.ts | 1 + .../fixtures/runtime-bridge-operation.json | 1 + js/src/replica/command-runtime/create.ts | 3 + js/src/replica/command-runtime/symbols.ts | 3 + js/src/replica/command-runtime/types.ts | 2 + .../distributed-replica/impl-fetch-live.ts | 17 +- js/src/replica/distributed-replica/impl.ts | 53 +++- js/src/replica/types.ts | 2 + js/tests/replica-protocol.test.mjs | 47 +++ src/gateway/README.md | 32 ++ src/gateway/delivery/freshness.rs | 288 ++++++++++++++++++ src/gateway/delivery/identity.rs | 135 ++++++++ src/gateway/delivery/mod.rs | 27 ++ src/gateway/mod.rs | 4 + src/graphql/engine/builder.rs | 16 + src/graphql/engine/core.rs | 4 + src/graphql/engine/mod.rs | 5 + src/graphql/engine/read_routing.rs | 197 ++++++++++++ src/graphql/engine/request.rs | 27 +- src/graphql/execute.rs | 43 ++- src/graphql/mod.rs | 3 + src/graphql/query_protocol.rs | 8 +- src/graphql/schema.rs | 9 +- src/graphql/subscribe.rs | 2 + tests/edge_query_delivery.rs | 155 ++++++++++ tests/edge_query_delivery_postgres.rs | 189 ++++++++++++ tests/gateway-portable/Cargo.toml | 5 + tests/gateway-postgres/README.md | 13 + tests/gateway-postgres/run.py | 73 +++++ tests/graphql_query_protocol/main.rs | 93 ++++++ 34 files changed, 1482 insertions(+), 15 deletions(-) create mode 100644 src/gateway/delivery/freshness.rs create mode 100644 src/gateway/delivery/identity.rs create mode 100644 src/gateway/delivery/mod.rs create mode 100644 src/graphql/engine/read_routing.rs create mode 100644 tests/edge_query_delivery.rs create mode 100644 tests/edge_query_delivery_postgres.rs create mode 100644 tests/gateway-postgres/README.md create mode 100644 tests/gateway-postgres/run.py diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 4d7808a91..b6604d48a 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -13,6 +13,9 @@ on: - 'tests/graphql_identity/**' - 'tests/graphql_causal_transport/**' - 'tests/graphql_query_protocol/**' + - 'tests/edge_query_delivery*' + - 'js/src/replica/**' + - 'js/tests/replica*' - 'tests/gateway*' - 'tests/gateway*/**' - '.github/workflows/integration-gateway.yaml' @@ -44,9 +47,9 @@ jobs: run: cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown - name: Test and compile portable GraphQL operation policy run: | - cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-graphql - cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-graphql --target wasm32-unknown-unknown - python3 tests/gateway-portable/check_dependencies.py --features gateway-graphql + cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-delivery + cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --features gateway-delivery --target wasm32-unknown-unknown + python3 tests/gateway-portable/check_dependencies.py --features gateway-delivery - name: Verify native and Wasm dependency isolation run: python3 tests/gateway-portable/check_dependencies.py @@ -104,4 +107,27 @@ jobs: with: toolchain: stable - name: Verify embedded and remote GraphQL protocols - run: cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity + + freshness: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Prove primary routing with paused physical standby + run: python3 tests/gateway-postgres/run.py + - name: Verify client freshness and command protocol + run: | + npm ci --prefix js + npm --prefix js run build + node --test js/tests/replica-command-runtime.test.mjs js/tests/replica-protocol.test.mjs js/tests/replica-revalidation.test.mjs js/tests/replica-graphql-transport.test.mjs + - name: Verify generated delivery metadata + run: cargo test -p distributed_cli client_compiler diff --git a/Cargo.toml b/Cargo.toml index 0ce1a501d..44c5299ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,8 @@ gateway = ["dep:url"] gateway-native = ["gateway", "http", "reqwest/stream", "dep:hyper", "dep:hyper-util", "dep:tower", "tokio/io-util"] # Whole-operation selection is portable; execution adapters are separately gated. gateway-graphql = ["gateway", "dep:async-graphql-parser"] +# Shared portable identity, freshness and delivery contracts. +gateway-delivery = ["gateway-graphql"] gateway-graphql-native = ["gateway-native", "gateway-graphql", "graphql", "dep:tokio-tungstenite"] runtime = ["application-runtime"] emitter = ["dep:event-emitter-rs"] diff --git a/distributed_cli/src/client_compiler/render/artifact.rs b/distributed_cli/src/client_compiler/render/artifact.rs index a2f56f84b..dea841df2 100644 --- a/distributed_cli/src/client_compiler/render/artifact.rs +++ b/distributed_cli/src/client_compiler/render/artifact.rs @@ -41,6 +41,8 @@ struct ArtifactProtocol<'a> { version: u32, #[serde(rename = "schemaHash")] schema_hash: &'a str, + #[serde(rename = "protocolHash")] + protocol_hash: &'a str, surface: &'a super::super::manifest::ManifestSurface, operation: &'a str, #[serde(rename = "trustedPresets")] @@ -256,6 +258,7 @@ pub(super) fn render_operation_artifact_json( protocol: ArtifactProtocol { version: 1, schema_hash: &manifest.schema_fingerprint, + protocol_hash: &manifest.protocol_fingerprint, surface: &manifest.surface, operation: &operation.query_hash, trusted_presets: &manifest.trusted_presets, diff --git a/distributed_cli/tests/fixtures/generated-operation.ts b/distributed_cli/tests/fixtures/generated-operation.ts index 46a11817f..e533ebd92 100644 --- a/distributed_cli/tests/fixtures/generated-operation.ts +++ b/distributed_cli/tests/fixtures/generated-operation.ts @@ -828,6 +828,7 @@ export const Operation_ScalarInputs: ReplicaOperationArtifact diff --git a/js/src/replica/command-runtime/symbols.ts b/js/src/replica/command-runtime/symbols.ts index f3bbee6c9..c6705b5f4 100644 --- a/js/src/replica/command-runtime/symbols.ts +++ b/js/src/replica/command-runtime/symbols.ts @@ -47,3 +47,6 @@ export const replicaCommandProjectedLifecycle = Symbol( export const replicaCommandReadRecord = Symbol( 'distributed.replica.command-read-record' ); + +/** @internal Generated dependency registration before dispatch/optimism. */ +export const replicaCommandFreshness = Symbol('distributed.replica.command-freshness'); diff --git a/js/src/replica/command-runtime/types.ts b/js/src/replica/command-runtime/types.ts index 72f3e9af5..20d7900f2 100644 --- a/js/src/replica/command-runtime/types.ts +++ b/js/src/replica/command-runtime/types.ts @@ -26,6 +26,7 @@ import type { import type { ReplicaPureFunction } from '../projection-delta/index.js'; import { replicaCommandAuthority, + replicaCommandFreshness, replicaCommandDirectProjection, replicaCommandProjectionDelta, replicaCommandProjectedLifecycle, @@ -66,6 +67,7 @@ export type ReplicaCommandDirectProjection = Readonly<{ }>; export type ReplicaCommandAuthorityHost = DistributedReplica & { + readonly [replicaCommandFreshness]?: (commandId: string, plan: import('../types.js').ReplicaRevalidationPlan) => void; readonly [replicaCommandAuthority]?: ( contract: ReplicaCommandSurfaceContract ) => ReplicaCommandAuthorityRegistration; diff --git a/js/src/replica/distributed-replica/impl-fetch-live.ts b/js/src/replica/distributed-replica/impl-fetch-live.ts index ff178acbf..650c8182e 100644 --- a/js/src/replica/distributed-replica/impl-fetch-live.ts +++ b/js/src/replica/distributed-replica/impl-fetch-live.ts @@ -57,6 +57,7 @@ export type FetchLiveHost = { ): DistributedProtocolEnvelope; diagnosticEvent(event: ReplicaDiagnosticEventInput): void; resumeCursors(key: string): readonly DistributedLiveCursor[]; + freshness(artifact: ReplicaOperationArtifact, key: string): Readonly> | undefined; }; export function emitWatchState(host: FetchLiveHost, key: string, allowFetch: boolean): void { @@ -151,7 +152,7 @@ export function fetchWatch( document: watch.artifact.document, variables: watch.variables, artifact: watch.artifact, - ...replicaClientRequestExtensions(watch.artifact), + extensions: requestExtensions(host, watch.artifact, watch.key), signal: controller.signal }); let flight: Promise; @@ -251,7 +252,7 @@ export function retainLive( document: watch.artifact.live.document, variables: watch.variables, artifact: watch.artifact, - ...replicaClientRequestExtensions(watch.artifact), + extensions: requestExtensions(host, watch.artifact, watch.key), ...(resume === undefined || resume.length === 0 ? {} : { resume }) @@ -493,3 +494,15 @@ export function releaseLive(host: FetchLiveHost, key: string): void { host.queryState(key).live = 'off'; host.emitState(key, false); } + +function requestExtensions( + host: FetchLiveHost, + artifact: ReplicaOperationArtifact, + key: string +): Readonly> { + const freshness = host.freshness(artifact, key); + return Object.freeze({ + ...replicaClientRequestExtensions(artifact).extensions, + ...(freshness === undefined ? {} : { gatewayFreshness: freshness }) + }); +} diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index 8e5654967..7641babb2 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -1,3 +1,4 @@ +import { replicaCommandFreshness } from '../command-runtime/symbols.js'; import { CacheRevisionConflictError, createCacheEngine, @@ -127,6 +128,7 @@ import { latestCursors, protocolInvalid, recordKeyMatchesModel, + modelFromRecordKey, responsePathKey, sameRecordClock, sameRecordRevision @@ -228,6 +230,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { DistributedOpaqueString, AnonymousRecordProtocolClock >(); + readonly #freshnessPlans = new Map(); readonly #optimisticReceipts = new Map(); readonly #renderedOperations = new Map(); readonly #readOperationKeys = new Set(); @@ -344,7 +347,8 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { responseProjectionGeneration ), diagnosticEvent: (event) => self.#diagnosticEvent(event), - resumeCursors: (key) => self.#resumeCursors(key) + resumeCursors: (key) => self.#resumeCursors(key), + freshness: (artifact, key) => self.#freshness(artifact, key) }; return this.#fetchLiveHostCache; } @@ -659,6 +663,53 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { }); } + [replicaCommandFreshness](commandId: string, plan: ReplicaRevalidationPlan): void { + // Validate before dispatch, using the existing generated dependency matcher. + createReplicaRevalidationMatcher(plan); + for (const [id, entry] of this.#freshnessPlans) { + if (entry.generation !== this.#protocolGenerationSequence || this.#engine.optimisticLayerState(id) === undefined) this.#freshnessPlans.delete(id); + } + if (!this.#freshnessPlans.has(commandId) && this.#freshnessPlans.size >= 256) throw new Error('too many pending causal commands'); + this.#freshnessPlans.set(commandId, { generation: this.#protocolGenerationSequence, plan }); + } + + #freshness(artifact: ReplicaOperationArtifact, key: string): Readonly> | undefined { + const scope = this.#protocolGeneration; + const protocolHash = artifact.protocol.protocolHash ?? this.#commandAuthorityContract?.protocolHash; + if (scope === undefined || protocolHash === undefined) return undefined; + const pending: unknown[] = []; + for (const [id, entry] of this.#freshnessPlans) { + if (entry.generation !== this.#protocolGenerationSequence || this.#engine.optimisticLayerState(id) === undefined) { + this.#freshnessPlans.delete(id); + continue; + } + if (!createReplicaRevalidationMatcher(entry.plan)(artifact)) continue; + // Overlap already uses full generated list/filter/count/relationship + // dependencies. An overlapping request must use primary even when an + // incomplete producer only supplied an opaque dependency name. + pending.push({ complete: false, models: [...entry.plan.models], relationships: [] }); + } + const minimum: unknown[] = []; + // Retained clocks live independently of pending layer state. Index scopes + // belong to this query/live plan; never compare a different query's clock. + const group = this.#operationProtocols.get(key); + for (const state of [group?.query, group?.live]) { + for (const [projection, clock] of state?.indexClocks ?? []) { + minimum.push({ kind: 'index', projection, scopeToken: clock.scopeToken, position: clock.position }); + } + } + // Direct Atomic effects have not yet acquired a query index checkpoint. + // Once a proving query retires this fence, its retained index clock covers + // membership (including later deletion) without requiring an absent row. + for (const [recordKey, { clock }] of this.#projectedRecordFences) { + const model = modelFromRecordKey(recordKey); + if (model === undefined || !createReplicaRevalidationMatcher({ dependencies: [], models: [model], relationships: [] })(artifact)) continue; + minimum.push({ kind: 'record', model, scopeToken: clock.scopeToken, incarnation: clock.incarnation, revision: clock.revision }); + } + if (pending.length + minimum.length > 256) throw new Error('causal delivery context exceeds bounded evidence budget'); + return Object.freeze({ version: 1, schemaHash: scope.schemaHash, protocolHash, authorizationGeneration: scope.authorizationGeneration, cacheScope: scope.cacheScope, pending, minimum }); + } + [replicaResultObservation]( observer: (envelope: ReplicaResultEnvelope) => void ): ReplicaResultObservationRegistration { diff --git a/js/src/replica/types.ts b/js/src/replica/types.ts index 6ce1d0aba..ac2058b92 100644 --- a/js/src/replica/types.ts +++ b/js/src/replica/types.ts @@ -517,6 +517,8 @@ export type ReplicaOperationSourceLocation = { }; export type ReplicaOperationProtocol = { + /** Exact generated protocol generation for causal delivery context. */ + readonly protocolHash?: string; readonly version: 1; /** Opaque service schema fingerprint, compared byte-for-byte. */ readonly schemaHash: string; diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index d12f99010..92230bf7c 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -2761,3 +2761,50 @@ test('protocol record scopes remain opaque and never become replica identities', undefined ); }); + +test('issuing-user freshness keeps pending effects separate from confirmed floors', async () => { + const { replicaCommandFreshness } = await import('../dist/replica/command-runtime/symbols.js'); + const artifact = { ...Todos, protocol: { ...Todos.protocol, protocolHash: 'protocol-a' } }; + const requests = []; + let candidate = wireFrame({ position: '1', rows: [{ id: 'todo-1', title: 'base' }] }); + const replica = createDistributedReplica({ transport: { async fetch(request) { requests.push(request); return candidate; } } }); + write(replica, { position: '1', rows: [{ id: 'todo-1', title: 'base' }] }, 'network', artifact); + const watch = replica.watch(artifact, {}); + const plan = { dependencies: ['todos'], models: [Todo.id], relationships: [] }; + replica[replicaCommandFreshness]('cmd-1', plan); + replica.createOptimisticLayer('cmd-1', writer => writer.writeRecord(Todo, 'todo-1', { fields: { title: 'preview' } })); + replica.markOptimisticLayerAccepted('cmd-1', commandMetadata()); + await watch.refresh(); + assert.equal(requests.at(-1).extensions.gatewayFreshness.pending.length, 1); + assert.equal(replica.read(artifact, {}).data.todos[0].title, 'preview'); + candidate = wireFrame({ position: '2', revision: '2', rows: [{ id: 'todo-1', title: 'committed' }], observations: [{ causationId: 'cause-1', projection: 'todos-projector', model: Todo.id, scopeToken: 'expect:todo-1' }] }); + await watch.refresh(); + assert.equal(replica.read(artifact, {}).data.todos[0].title, 'committed'); + candidate = wireFrame({ position: '1', rows: [{ id: 'todo-1', title: 'lagging' }] }); + await watch.refresh(); + const context = requests.at(-1).extensions.gatewayFreshness; + assert.equal(context.pending.length, 0); + assert(context.minimum.some(floor => floor.kind === 'index' && floor.position === '2')); + assert.equal(replica.read(artifact, {}).data.todos[0].title, 'committed'); + watch.destroy(); +}); + +test('Atomic installs a retained outgoing floor without an automatic fetch', async () => { + const { replicaCommandFreshness } = await import('../dist/replica/command-runtime/symbols.js'); + const artifact = { ...Todos, protocol: { ...Todos.protocol, protocolHash: 'protocol-a' } }; + const requests = []; + const replica = createDistributedReplica({ transport: { async fetch(request) { requests.push(request); return wireFrame({ position: '1', rows: [{ id: 'todo-1', title: 'lagging' }] }); } } }); + write(replica, { position: '1', rows: [{ id: 'todo-1', title: 'base' }] }, 'network', artifact); + const watch = replica.watch(artifact, {}); + replica[replicaCommandFreshness]('atomic', { dependencies: ['todos'], models: [Todo.id], relationships: [] }); + replica.createOptimisticLayer('atomic', writer => writer.writeRecord(Todo, 'todo-1', { fields: { title: 'preview' } })); + replica[replicaCommandDirectProjection]('atomic', { model: Todo, identity: 'todo-1', evidence: { model: Todo.id, scopeToken: 'record:todo-1', incarnation: '1', revision: '2', tombstone: false }, fields: { id: 'todo-1', title: 'committed', __typename: Todo.id } }); + assert.equal(requests.length, 0); + assert.equal(replica.read(artifact, {}).data.todos[0].title, 'committed'); + await watch.refresh(); + const context = requests.at(-1).extensions.gatewayFreshness; + assert.equal(context.pending.length, 0); + assert(context.minimum.some(floor => floor.kind === 'record' && floor.revision === '2')); + assert.equal(replica.read(artifact, {}).data.todos[0].title, 'committed'); + watch.destroy(); +}); diff --git a/src/gateway/README.md b/src/gateway/README.md index e899b6c92..40cfbdbf4 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -74,3 +74,35 @@ failure. Configured body, concurrency and connection lifetime limits apply; backend authorization remains authoritative. Optional delivery features are rejected until their adapters are bound. Removing the GraphQL binding restores the existing direct executor routes; no migration is required. + +### Causal read routing + +`gateway-delivery` supplies bounded exact-scope identity, dependency overlap and +record/index minima contracts without a server or SQL dependency. With GraphQL, +`ReadRouting::new(replica).stale_tolerant(document, operation_name)` explicitly +registers stale-tolerant reads. Pass it to `GraphqlEngineBuilder::read_routing`; +the builder's original repository remains the authoritative primary. Schema and +SQL dialect must match. Unregistered queries, command recovery and live refreshes +use primary. SQLx pools do not certify replay progress. + +Generated query artifacts carry the protocol fingerprint. The client sends +`extensions.gatewayFreshness`, bound to its server-established schema, protocol, +policy and cache scope. Generated command dependencies select affected queries; +unknown effects broaden within the authorized surface. Pending effects force +primary without confirming projection. Confirmed query/live index clocks and +Atomic record fences survive optimistic layer retirement. An origin response +that cannot cover supplied minima returns `FRESHNESS_PENDING`, including +incomparable scopes. No stale fallback occurs on primary failure. Context limits +fail explicitly rather than discarding retained evidence. This initial router +has no replica-proof adapter; any retained floor uses primary. + +Applications must change the configured protocol namespace when activating a +new projection epoch/backend with incomparable evidence. Old contexts are +rejected and the existing replica scope/reset lifecycle handles rebootstrap. +Keep normal backend authentication on the executor: cacheScope and minima are +identifiers/hints, never bearer credentials. Snapshot-cache and shared-work +admission require a fresh origin identity for every consumer. + +No routing migration is required. Disable replica registration to route all reads +to primary; keep client revision fences active during a deployment rollback. +The isolated physical standby fixture is documented in tests/gateway-postgres. diff --git a/src/gateway/delivery/freshness.rs b/src/gateway/delivery/freshness.rs new file mode 100644 index 000000000..3d13a3659 --- /dev/null +++ b/src/gateway/delivery/freshness.rs @@ -0,0 +1,288 @@ +use super::{DeliveryError, OriginIdentity}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Maximum combined number of pending dependencies and retained floors. +pub const MAX_FRESHNESS_ITEMS: usize = 256; +/// Maximum serialized causal context size. +pub const MAX_FRESHNESS_BYTES: usize = 64 * 1024; + +/// Compiler-known dependency inventory. Unknown coverage overlaps everything +/// within the already authorized surface, including empty lists and counts. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Dependencies { + /// Whether the compiler accounts for every dependency. + pub complete: bool, + /// Model names including filter and join dependencies. + pub models: BTreeSet, + /// Relationship identities affecting membership. + pub relationships: BTreeSet, +} +impl Dependencies { + /// Conservatively test dependency overlap without inspecting result rows. + pub fn overlaps(&self, other: &Self) -> bool { + !self.complete + || !other.complete + || !self.models.is_disjoint(&other.models) + || !self.relationships.is_disjoint(&other.relationships) + } + /// Validate bounded contract values before accepting external data. + pub fn validate(&self) -> Result<(), DeliveryError> { + if self.models.len() + self.relationships.len() > MAX_FRESHNESS_ITEMS { + return Err(DeliveryError::InvalidContext); + } + for name in self.models.iter().chain(&self.relationships) { + bounded(name)?; + } + Ok(()) + } +} + +/// Opaque scope tokens keep incomparable record/index obligations separate. +/// This carries existing evidence, never a new public/global partition clock. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum Minimum { + /// Comparable evidence for one record. + Record { + /// Model owning this record evidence. + model: String, + #[serde(rename = "scopeToken")] + /// Opaque origin-issued comparison scope. + scope_token: String, + /// Decimal record incarnation. + incarnation: String, + /// Decimal revision within the incarnation. + revision: String, + }, + /// Comparable evidence for an index. + Index { + /// Projection owning this index evidence. + projection: String, + #[serde(rename = "scopeToken")] + /// Opaque origin-issued comparison scope. + scope_token: String, + /// Decimal checkpoint within this opaque scope. + position: String, + }, +} +impl Minimum { + /// Validate bounded contract values before accepting external data. + pub fn validate(&self) -> Result<(), DeliveryError> { + match self { + Self::Record { + model, + scope_token, + incarnation, + revision, + } => { + bounded(model)?; + bounded(scope_token)?; + decimal(incarnation)?; + decimal(revision)?; + } + Self::Index { + projection, + scope_token, + position, + } => { + bounded(projection)?; + bounded(scope_token)?; + decimal(position)?; + } + } + Ok(()) + } + /// Whether this same-scope evidence is at least the required revision. + pub fn covers(&self, required: &Self) -> bool { + match (self, required) { + ( + Self::Record { + model: a, + scope_token: sa, + incarnation: ia, + revision: ra, + }, + Self::Record { + model: b, + scope_token: sb, + incarnation: ib, + revision: rb, + }, + ) => { + a == b + && sa == sb + && (compare(ia, ib).is_gt() || (ia == ib && !compare(ra, rb).is_lt())) + } + ( + Self::Index { + projection: a, + scope_token: sa, + position: pa, + }, + Self::Index { + projection: b, + scope_token: sb, + position: pb, + }, + ) => a == b && sa == sb && !compare(pa, pb).is_lt(), + _ => false, + } + } +} + +/// An authenticated request binds these client hints to the origin identity. +/// Hints may force primary reads; they are never proof that a command committed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct FreshnessContext { + /// Wire contract version; must be one. + pub version: u32, + /// Exact schema generation. + pub schema_hash: String, + /// Exact protocol generation. + pub protocol_hash: String, + /// Origin policy generation. + pub authorization_generation: String, + /// Origin-issued subject and authorization scope. + pub cache_scope: String, + /// Unconfirmed effect dependencies, separate from minima. + pub pending: Vec, + /// Retained confirmed evidence, including incomparable scopes. + pub minimum: Vec, +} +impl FreshnessContext { + /// Decode a bounded context and reject malformed or unknown fields. + pub fn parse(value: &serde_json::Value) -> Result { + if serde_json::to_vec(value) + .map_err(|_| DeliveryError::InvalidContext)? + .len() + > MAX_FRESHNESS_BYTES + { + return Err(DeliveryError::InvalidContext); + } + let context: Self = + serde_json::from_value(value.clone()).map_err(|_| DeliveryError::InvalidContext)?; + if context.version != 1 + || context.pending.len() + context.minimum.len() > MAX_FRESHNESS_ITEMS + { + return Err(DeliveryError::InvalidContext); + } + for part in [ + &context.schema_hash, + &context.protocol_hash, + &context.authorization_generation, + &context.cache_scope, + ] { + bounded(part)?; + } + for dependencies in &context.pending { + dependencies.validate()?; + } + for minimum in &context.minimum { + minimum.validate()?; + } + Ok(context) + } + /// Compare client context with freshly authenticated origin authority. + pub fn bind(&self, identity: &OriginIdentity) -> Result<(), DeliveryError> { + identity.validate()?; + if self.schema_hash != identity.schema_hash + || self.protocol_hash != identity.protocol_hash + || self.authorization_generation != identity.authorization_generation + || self.cache_scope != identity.cache_scope + { + return Err(DeliveryError::ScopeChanged); + } + Ok(()) + } + /// Whether any unconfirmed effect can affect these dependencies. + pub fn pending_overlaps(&self, dependencies: &Dependencies) -> bool { + self.pending + .iter() + .any(|pending| pending.overlaps(dependencies)) + } + /// Require every retained floor to have comparable covering evidence. + pub fn satisfied_by(&self, evidence: &[Minimum]) -> bool { + self.minimum + .iter() + .all(|required| evidence.iter().any(|candidate| candidate.covers(required))) + } + /// Retain maximal comparable floors without discarding incomparable scopes. + pub fn observe( + &mut self, + evidence: impl IntoIterator, + ) -> Result<(), DeliveryError> { + let mut next = self.minimum.clone(); + for candidate in evidence { + candidate.validate()?; + if next.iter().any(|current| current.covers(&candidate)) { + continue; + } + next.retain(|current| !candidate.covers(current)); + next.push(candidate); + if next.len() + self.pending.len() > MAX_FRESHNESS_ITEMS { + return Err(DeliveryError::InvalidContext); + } + } + self.minimum = next; + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +/// Origin-owned operation consistency policy. +pub enum ReadConsistency { + #[default] + /// Require an authoritative current read. + Current, + /// Explicit opt-in to stale reads subject to causal requirements. + StaleTolerant, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Backend chosen without assuming replay freshness from a pool. +pub enum ReadTarget { + /// Authoritative read-model backend. + Primary, + /// Explicitly configured stale-tolerant read backend. + Replica, +} +/// No replica-proof adapter is installed by the initial framework router. +/// Even an unrelated retained floor conservatively uses primary; pending work +/// with known disjoint dependencies does not change an explicit stale policy. +pub fn read_target( + policy: ReadConsistency, + dependencies: &Dependencies, + freshness: Option<&FreshnessContext>, +) -> ReadTarget { + if policy == ReadConsistency::Current + || freshness.is_some_and(|f| f.pending_overlaps(dependencies) || !f.minimum.is_empty()) + { + ReadTarget::Primary + } else { + ReadTarget::Replica + } +} +fn bounded(value: &str) -> Result<(), DeliveryError> { + if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) { + Err(DeliveryError::InvalidContext) + } else { + Ok(()) + } +} +fn decimal(value: &str) -> Result<(), DeliveryError> { + if value.is_empty() + || value.len() > 20 + || !value.bytes().all(|b| b.is_ascii_digit()) + || (value.len() > 1 && value.starts_with('0')) + || value.parse::().is_err() + { + Err(DeliveryError::InvalidContext) + } else { + Ok(()) + } +} +fn compare(a: &str, b: &str) -> std::cmp::Ordering { + a.len().cmp(&b.len()).then_with(|| a.cmp(b)) +} diff --git a/src/gateway/delivery/identity.rs b/src/gateway/delivery/identity.rs new file mode 100644 index 000000000..507041aab --- /dev/null +++ b/src/gateway/delivery/identity.rs @@ -0,0 +1,135 @@ +use super::DeliveryError; +use crate::gateway::graphql::{operation_kind, OperationKind, MAX_DOCUMENT_BYTES}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Values established by the authenticated origin, never by a browser scope +/// claim. The cache scope includes subject and all result-affecting authority. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OriginIdentity { + /// Origin-selected application surface. + pub application: String, + /// Configured origin service identity. + pub endpoint: String, + /// Exact schema generation. + pub schema_hash: String, + /// Exact protocol generation. + pub protocol_hash: String, + /// Origin policy generation. + pub authorization_generation: String, + /// Origin-issued subject and authorization scope. + pub cache_scope: String, +} +impl OriginIdentity { + /// Validate bounded contract values before accepting external data. + pub fn validate(&self) -> Result<(), DeliveryError> { + for part in [ + &self.application, + &self.endpoint, + &self.schema_hash, + &self.protocol_hash, + &self.authorization_generation, + &self.cache_scope, + ] { + if part.is_empty() || part.len() > 1024 || part.chars().any(char::is_control) { + return Err(DeliveryError::InvalidContext); + } + } + Ok(()) + } +} + +/// Exact operation identity bound to an authenticated origin response. +/// Different HTTP/query and live documents intentionally have different keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct OperationKey(String); +impl OperationKey { + /// Call only after origin admission and trusted operation eligibility. + pub fn from_origin( + identity: &OriginIdentity, + request: &serde_json::Value, + ) -> Result { + identity.validate()?; + let document = request + .get("query") + .and_then(|v| v.as_str()) + .ok_or(DeliveryError::Ineligible)?; + let name = match request.get("operationName") { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(name)) => Some(name.as_str()), + _ => return Err(DeliveryError::Ineligible), + }; + if !matches!( + operation_kind(document, name), + Ok(OperationKind::Query | OperationKind::Subscription) + ) { + return Err(DeliveryError::Ineligible); + } + let variables = request + .get("variables") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + if !variables.is_object() { + return Err(DeliveryError::Ineligible); + } + let mut extensions = request + .get("extensions") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + // Freshness is checked separately for each consumer; it is not identity. + let object = extensions + .as_object_mut() + .ok_or(DeliveryError::Ineligible)?; + object.remove("gatewayFreshness"); + let bytes = canonical_json(&serde_json::json!([ + identity, document, name, variables, extensions + ]))?; + Ok(Self(format!("{:x}", Sha256::digest(bytes)))) + } + /// Stable digest used only after admission. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Bounded canonical JSON: objects sort by key, arrays preserve order. +/// Used for keys only, never a rewrite of the executed GraphQL request. +pub fn canonical_json(value: &serde_json::Value) -> Result, DeliveryError> { + fn ordered( + value: &serde_json::Value, + depth: usize, + budget: &mut usize, + ) -> Result { + if depth > 64 || *budget == 0 { + return Err(DeliveryError::InvalidContext); + } + *budget -= 1; + Ok(match value { + serde_json::Value::Object(map) => { + let sorted: std::collections::BTreeMap<_, _> = map.iter().collect(); + let mut result = serde_json::Map::new(); + for (key, value) in sorted { + result.insert(key.clone(), ordered(value, depth + 1, budget)?); + } + serde_json::Value::Object(result) + } + serde_json::Value::Array(values) => serde_json::Value::Array( + values + .iter() + .map(|v| ordered(v, depth + 1, budget)) + .collect::>()?, + ), + value => value.clone(), + }) + } + let bytes = serde_json::to_vec(&ordered(value, 0, &mut 16384)?) + .map_err(|_| DeliveryError::InvalidContext)?; + if bytes.len() > MAX_DOCUMENT_BYTES * 2 { + return Err(DeliveryError::InvalidContext); + } + Ok(bytes) +} diff --git a/src/gateway/delivery/mod.rs b/src/gateway/delivery/mod.rs new file mode 100644 index 000000000..0315c03d3 --- /dev/null +++ b/src/gateway/delivery/mod.rs @@ -0,0 +1,27 @@ +//! Portable delivery contracts. Origin authentication establishes identity; +//! client freshness hints can strengthen reads but never authorize reuse. +mod freshness; +mod identity; +pub use freshness::*; +pub use identity::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Fail-closed outcomes of admission, routing or proof checks. +pub enum DeliveryError { + /// Malformed or oversized client context. + InvalidContext, + /// Origin authority differs from the supplied context. + ScopeChanged, + /// Operation has no trusted reusable contract. + Ineligible, + /// Available snapshot cannot prove the required minimum. + Pending, + /// Authoritative origin is unavailable; stale fallback is forbidden. + Unavailable, +} +impl std::fmt::Display for DeliveryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for DeliveryError {} diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 2df3110a3..6a6ca6ff2 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -40,3 +40,7 @@ pub mod native; /// Portable GraphQL operation selection and capability admission. #[cfg(feature = "gateway-graphql")] pub mod graphql; + +/// Portable authenticated delivery identity and freshness contracts. +#[cfg(feature = "gateway-delivery")] +pub mod delivery; diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 51ddf3cd2..628bd9269 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -10,6 +10,8 @@ impl GraphqlEngineBuilder { command_binding: None, causal_storage_identity: source.causal_storage_identity, pool: source.pool, + #[cfg(feature = "gateway-delivery")] + read_routing: None, catalog: BTreeMap::new(), by_table: BTreeMap::new(), permissions: BTreeMap::new(), @@ -45,6 +47,18 @@ impl GraphqlEngineBuilder { self } + /// Opt in selected exact query documents to a read replica. The engine's + /// original repository remains the primary for current reads and evidence. + #[cfg(feature = "gateway-delivery")] + pub fn read_routing(mut self, routing: ReadRouting) -> Self { + if std::mem::discriminant(&self.pool) != std::mem::discriminant(&routing.replica) { + self.pending_errors + .push("read replica must use the primary SQL dialect".into()); + } + self.read_routing = Some(routing); + self + } + pub fn model(mut self, perms: ModelPermissions) -> Self { let schema = M::schema().clone(); if let Err(e) = self.insert_catalog(schema.clone(), true) { @@ -1011,6 +1025,8 @@ impl GraphqlEngineBuilder { command_binding: self.command_binding, causal_storage_identity: self.causal_storage_identity, pool: self.pool, + #[cfg(feature = "gateway-delivery")] + read_routing: self.read_routing, catalog: self.catalog, by_table: self.by_table, permissions: self.permissions, diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index 40b75d6fc..524747687 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -231,6 +231,8 @@ pub(crate) struct EngineInner { pub command_binding: Option, pub causal_storage_identity: Option, pub pool: GraphqlPool, + #[cfg(feature = "gateway-delivery")] + pub read_routing: Option, pub catalog: BTreeMap, pub by_table: BTreeMap, pub permissions: BTreeMap<(String, String), RoleModelPerm>, @@ -294,6 +296,8 @@ pub struct GraphqlEngineBuilder { pub(crate) command_binding: Option, pub(crate) causal_storage_identity: Option, pub(crate) pool: GraphqlPool, + #[cfg(feature = "gateway-delivery")] + pub(crate) read_routing: Option, pub(crate) catalog: BTreeMap, pub(crate) by_table: BTreeMap, pub(crate) permissions: BTreeMap<(String, String), RoleModelPerm>, diff --git a/src/graphql/engine/mod.rs b/src/graphql/engine/mod.rs index 991cf016f..599c2604a 100644 --- a/src/graphql/engine/mod.rs +++ b/src/graphql/engine/mod.rs @@ -102,3 +102,8 @@ pub(crate) use validation::{execute_plan, validate_filter, validate_generated_na pub fn core_sdl_for_catalog(tables: &[TableSchema]) -> Result { validation::core_sdl_for_catalog(tables) } + +#[cfg(feature = "gateway-delivery")] +pub(crate) mod read_routing; +#[cfg(feature = "gateway-delivery")] +pub use read_routing::ReadRouting; diff --git a/src/graphql/engine/read_routing.rs b/src/graphql/engine/read_routing.rs new file mode 100644 index 000000000..e339523cd --- /dev/null +++ b/src/graphql/engine/read_routing.rs @@ -0,0 +1,197 @@ +use super::*; +use crate::gateway::{ + delivery::*, + graphql::{operation_kind, OperationKind}, +}; + +/// Explicit stale-tolerant allowlist. No timeout/stickiness is treated as replay +/// proof. With any retained floor the initial router always uses primary. +#[derive(Clone)] +pub struct ReadRouting { + pub(crate) replica: GraphqlPool, + stale_tolerant: BTreeSet<(String, Option)>, +} +impl ReadRouting { + /// Bind an optional read replica; no query uses it until explicitly registered. + pub fn new(replica: impl Into) -> Self { + Self { + replica: replica.into(), + stale_tolerant: BTreeSet::new(), + } + } + /// Register one exact selected ordinary query as stale-tolerant. + pub fn stale_tolerant( + mut self, + document: impl Into, + operation_name: Option, + ) -> Result { + let document = document.into(); + if operation_kind(&document, operation_name.as_deref()) != Ok(OperationKind::Query) + || self.stale_tolerant.len() >= 4096 + { + return Err(GraphqlBuildError( + "stale-tolerant routing requires a bounded ordinary query inventory".into(), + )); + } + self.stale_tolerant.insert((document, operation_name)); + Ok(self) + } +} + +#[derive(Clone)] +pub(crate) struct ReadRequest { + policy: ReadConsistency, + pub(crate) freshness: Option, +} +impl ReadRequest { + pub(crate) fn pool<'a>( + &self, + inner: &'a EngineInner, + plan: &SqlPlan, + ) -> (&'a GraphqlPool, bool) { + let Some(routing) = &inner.read_routing else { + return (&inner.pool, true); + }; + // Physical compiler footprint covers filters, empty membership, joins + // and counts even when no result row contains a corresponding key. + let mut dependencies = Dependencies { + complete: true, + ..Default::default() + }; + for table in &plan.tables_touched { + if let Some(model) = inner.by_table.get(table) { + dependencies.models.insert(model.clone()); + } else { + dependencies.complete = false; + } + } + match read_target(self.policy, &dependencies, self.freshness.as_ref()) { + ReadTarget::Primary => (&inner.pool, true), + ReadTarget::Replica => (&routing.replica, false), + } + } +} + +impl GraphqlEngine { + /// Establish identity on the authenticated origin control path. Callers + /// must supply the same verified principal and surface request as execution. + /// The returned scope is an identifier, never authorization by itself. + pub fn delivery_identity( + &self, + session: &Session, + request: &Request, + ) -> Result { + let authority = resolve_execution_authority(&self.inner, session, request) + .map_err(|_| DeliveryError::Ineligible)?; + let runtime = self + .inner + .protocol + .as_ref() + .ok_or(DeliveryError::Ineligible)?; + let (_, surface, _, _) = + select_protocol_surface(runtime, &authority).map_err(|_| DeliveryError::Ineligible)?; + let envelope = self + .protocol_accumulator(&authority, session, request) + .map_err(|_| DeliveryError::Ineligible)? + .ok_or(DeliveryError::Ineligible)? + .snapshot() + .map_err(|_| DeliveryError::Ineligible)?; + let identity = OriginIdentity { + application: serde_json::to_string(&authority.surface) + .map_err(|_| DeliveryError::Ineligible)?, + endpoint: runtime.service_id.clone(), + schema_hash: envelope.schema_hash, + protocol_hash: surface.protocol_fingerprint.clone(), + authorization_generation: envelope.authorization_generation, + cache_scope: envelope.cache_scope.as_str().to_owned(), + }; + identity.validate()?; + Ok(identity) + } + pub(crate) fn prepare_read( + &self, + session: &Session, + request: &Request, + ) -> Result { + let kind = operation_kind(&request.query, request.operation_name.as_deref()); + let context = request.extensions.get("gatewayFreshness"); + let freshness = if let Some(context) = context { + if !matches!(kind, Ok(OperationKind::Query | OperationKind::Subscription)) { + return Err(DeliveryError::Ineligible); + } + let context = + serde_json::to_value(context).map_err(|_| DeliveryError::InvalidContext)?; + let context = FreshnessContext::parse(&context)?; + context.bind(&self.delivery_identity(session, request)?)?; + Some(context) + } else { + None + }; + let policy = if kind == Ok(OperationKind::Query) + && self.inner.read_routing.as_ref().is_some_and(|r| { + r.stale_tolerant + .contains(&(request.query.clone(), request.operation_name.clone())) + }) { + ReadConsistency::StaleTolerant + } else { + ReadConsistency::Current + }; + Ok(ReadRequest { policy, freshness }) + } +} + +pub(crate) fn enforce_minimum(response: Response, read: &ReadRequest) -> Response { + let Some(context) = &read.freshness else { + return response; + }; + if context.minimum.is_empty() || !response.errors.is_empty() { + return response; + } + let value = serde_json::to_value(&response).unwrap_or_default(); + let snapshot = &value["extensions"]["distributed"]["snapshot"]; + let mut evidence = Vec::new(); + for record in snapshot["records"].as_array().into_iter().flatten() { + let mut record = record.clone(); + if let Some(object) = record.as_object_mut() { + object.remove("path"); + object.remove("tombstone"); + object.insert("kind".into(), "record".into()); + } + if let Ok(minimum) = serde_json::from_value::(record) { + if minimum.validate().is_ok() { + evidence.push(minimum); + } + } + } + for index in snapshot["indexes"].as_array().into_iter().flatten() { + let mut index = index.clone(); + if let Some(object) = index.as_object_mut() { + object.remove("resume"); + object.insert("kind".into(), "index".into()); + } + if let Ok(minimum) = serde_json::from_value::(index) { + if minimum.validate().is_ok() { + evidence.push(minimum); + } + } + } + if context.satisfied_by(&evidence) { + response + } else { + delivery_error(DeliveryError::Pending) + } +} +pub(crate) fn delivery_error(error: DeliveryError) -> Response { + let mut result = ServerError::new(error.to_string(), None); + let mut extensions = async_graphql::ErrorExtensionValues::default(); + extensions.set( + "code", + match error { + DeliveryError::Pending => "FRESHNESS_PENDING", + DeliveryError::ScopeChanged => "FRESHNESS_SCOPE_CHANGED", + _ => "INVALID_FRESHNESS_CONTEXT", + }, + ); + result.extensions = Some(extensions); + Response::from_errors(vec![result]) +} diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index 9b79fd6de..f02f8473f 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -73,6 +73,13 @@ impl GraphqlEngine { // future classifier or request extension behaves unexpectedly. request = request.only_introspection(); } + #[cfg(feature = "gateway-delivery")] + let read = match self.prepare_read(session, &request) { + Ok(read) => read, + Err(error) => return read_routing::delivery_error(error), + }; + #[cfg(feature = "gateway-delivery")] + let request = request.data(read.clone()); let mut request = request .data(session.clone()) .data(authority) @@ -83,6 +90,8 @@ impl GraphqlEngine { let start = std::time::Instant::now(); let response = attach_protocol_response(schema.execute(request).await, accumulator.as_ref()); + #[cfg(feature = "gateway-delivery")] + let response = read_routing::enforce_minimum(response, &read); let status = metrics_status_for_response(&response); let root_field = match &response.data { Value::Object(map) => map.keys().next().map(|s| s.as_str()).unwrap_or("_"), @@ -153,6 +162,15 @@ impl GraphqlEngine { if introspection { request = request.only_introspection(); } + #[cfg(feature = "gateway-delivery")] + let read = match self.prepare_read(session, &request) { + Ok(read) => read, + Err(error) => { + return stream::once(async move { read_routing::delivery_error(error) }).boxed() + } + }; + #[cfg(feature = "gateway-delivery")] + let request = request.data(read.clone()); let mut request = request .data(session.clone()) .data(authority) @@ -162,11 +180,16 @@ impl GraphqlEngine { } schema .execute_stream(request) - .map(move |response| attach_protocol_response(response, accumulator.as_ref())) + .map(move |response| { + let response = attach_protocol_response(response, accumulator.as_ref()); + #[cfg(feature = "gateway-delivery")] + let response = read_routing::enforce_minimum(response, &read); + response + }) .boxed() } - fn protocol_accumulator( + pub(super) fn protocol_accumulator( &self, authority: &ExecutionAuthority, session: &Session, diff --git a/src/graphql/execute.rs b/src/graphql/execute.rs index d0a25186d..7d5bd8852 100644 --- a/src/graphql/execute.rs +++ b/src/graphql/execute.rs @@ -11,15 +11,27 @@ use super::compile::{BindValue, ExtractedQueryEvidence, SqlDialect, SqlPlan}; use super::engine::{EngineInner, GraphqlPool}; pub async fn execute_sql(inner: &EngineInner, plan: &SqlPlan) -> Result { - match &inner.pool { + execute_sql_on_pool(inner, &inner.pool, true, plan).await +} + +pub(crate) async fn execute_sql_on_pool( + inner: &EngineInner, + pool: &GraphqlPool, + primary: bool, + plan: &SqlPlan, +) -> Result { + let _ = primary; + match pool { #[cfg(feature = "sqlite")] GraphqlPool::Sqlite(pool) => execute_sqlite(pool, plan, inner.statement_timeout) .await .map(|executed| executed.value), #[cfg(feature = "postgres")] - GraphqlPool::Postgres(pool) => execute_postgres(pool, plan, inner.statement_timeout) - .await - .map(|executed| executed.value), + GraphqlPool::Postgres(pool) => { + execute_postgres(pool, plan, inner.statement_timeout, primary) + .await + .map(|executed| executed.value) + } #[allow(unreachable_patterns)] _ => Err("no database pool available for GraphQL execution".into()), } @@ -204,6 +216,7 @@ async fn execute_postgres( pool: &sqlx::PgPool, plan: &SqlPlan, timeout: std::time::Duration, + primary: bool, ) -> Result { let mut tx = pool .begin() @@ -217,6 +230,7 @@ async fn execute_postgres( .await .map_err(|e| format!("statement_timeout: {e}"))?; + ensure_primary_backend(&mut tx, primary).await?; let value = fetch_postgres_value(&mut *tx, plan).await?; tx.commit() .await @@ -331,3 +345,24 @@ pub fn dialect_name(d: SqlDialect) -> &'static str { SqlDialect::Sqlite => "sqlite", } } + +/// Check the actual transaction connection, not another pool checkout. This +/// detects a physical standby misbound/switched into the primary slot; it does +/// not claim a general timeline or WAL replay routing implementation. +#[cfg(feature = "postgres")] +pub(crate) async fn ensure_primary_backend( + connection: &mut sqlx::PgConnection, + primary: bool, +) -> Result<(), String> { + #[cfg(feature = "gateway-delivery")] + if primary + && sqlx::query_scalar::<_, bool>("SELECT pg_is_in_recovery()") + .fetch_one(&mut *connection) + .await + .map_err(|e| format!("primary validation: {e}"))? + { + return Err("authoritative primary is unavailable".into()); + } + let _ = (connection, primary); + Ok(()) +} diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index a92ea8dab..ce9e727a4 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -89,3 +89,6 @@ pub use identity::{ pub use read_store::{CellByKeyGetter, HttpCellByKey, MapCellByKey, ReadStore}; #[cfg(feature = "graphql")] pub use subscribe::ChangeHub; + +#[cfg(all(feature = "graphql", feature = "gateway-delivery"))] +pub use engine::ReadRouting; diff --git a/src/graphql/query_protocol.rs b/src/graphql/query_protocol.rs index 3b4412a30..945ed8031 100644 --- a/src/graphql/query_protocol.rs +++ b/src/graphql/query_protocol.rs @@ -535,6 +535,8 @@ struct PreparedLiveMetadata { #[cfg(any(feature = "sqlite", feature = "postgres"))] pub(crate) async fn execute_query_with_protocol( inner: &EngineInner, + pool: &GraphqlPool, + primary: bool, role_surface: Arc, accumulator: ProtocolResponseAccumulator, plan: &SqlPlan, @@ -566,10 +568,11 @@ pub(crate) async fn execute_query_with_protocol( // The snapshot helper accepts an HRTB closure whose returned future may // borrow only its connection. Keep every other input owned by the closure // so plan/runtime references cannot escape into that future. + let _ = primary; let plan = plan.clone(); let runtime = inner.query_protocol.clone(); let statement_timeout = inner.statement_timeout; - match &inner.pool { + match pool { #[cfg(feature = "sqlite")] GraphqlPool::Sqlite(pool) => { let run = with_projection_read_snapshot(pool, move |connection| { @@ -618,6 +621,9 @@ pub(crate) async fn execute_query_with_protocol( .map_err(|error| { query_execution_error(format!("statement_timeout: {error}")) })?; + execute::ensure_primary_backend(connection, primary) + .await + .map_err(query_execution_error)?; let executed = execute::execute_postgres_in_connection(connection, &plan) .await .map_err(query_execution_error)?; diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 49537fe11..579c37ccc 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -765,12 +765,19 @@ async fn resolve_root( .await .map_err(|_| client_error("INTERNAL", "cell read dependency failed"))?, QueryPlan::Sql(plan) => { + let (pool, primary) = (&inner.pool, true); + #[cfg(feature = "gateway-delivery")] + let (pool, primary) = ctx + .data_opt::() + .map_or((pool, primary), |read| read.pool(&inner, &plan)); if let Some(protocol) = ctx.data_opt::().cloned() { let role_surface = inner.role_surfaces.get(&role).cloned().ok_or_else(|| { client_error("INTERNAL", "authorized GraphQL role surface is unavailable") })?; let executed = super::query_protocol::execute_query_with_protocol( &inner, + pool, + primary, role_surface, protocol.clone(), &plan, @@ -783,7 +790,7 @@ async fn resolve_root( .map_err(|_| client_error("INTERNAL", "query evidence encoding failed"))?; executed.value } else { - super::engine::execute_plan(&inner, &plan) + super::execute::execute_sql_on_pool(&inner, pool, primary, &plan) .await .map_err(|e| client_error_for_execute_err(&e))? } diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index 4661084ab..39cf493ce 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -275,6 +275,8 @@ async fn execute_list( .ok_or_else(|| "authorized GraphQL role surface is unavailable".to_string())?; let executed = super::query_protocol::execute_query_with_protocol( inner, + &inner.pool, + true, role_surface, protocol.clone(), plan, diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs new file mode 100644 index 000000000..183f4cfb2 --- /dev/null +++ b/tests/edge_query_delivery.rs @@ -0,0 +1,155 @@ +#![cfg(feature = "gateway-delivery")] +use distributed::gateway::delivery::*; +use serde_json::json; +fn identity(subject: &str) -> OriginIdentity { + OriginIdentity { + application: "todo".into(), + endpoint: "api".into(), + schema_hash: "schema-1".into(), + protocol_hash: "protocol-1".into(), + authorization_generation: "policy-1".into(), + cache_scope: subject.into(), + } +} +fn context() -> FreshnessContext { + FreshnessContext::parse(&json!({"version":1,"schemaHash":"schema-1","protocolHash":"protocol-1","authorizationGeneration":"policy-1","cacheScope":"alice","pending":[],"minimum":[]})).unwrap() +} +fn models(names: &[&str]) -> Dependencies { + Dependencies { + complete: true, + models: names.iter().map(|v| v.to_string()).collect(), + relationships: Default::default(), + } +} +fn index(scope: &str, position: &str) -> Minimum { + Minimum::Index { + projection: "todos".into(), + scope_token: scope.into(), + position: position.into(), + } +} +#[test] +fn origin_identity_canonical_variables_and_selected_operation() { + let alice = identity("alice"); + let bob = identity("bob"); + let a = json!({"query":"query A($filter: Input) { todos(filter: $filter) { title } } query B { count }", "operationName":"A", "variables":{"filter":{"a":1,"b":[2,3]}}}); + let mut b = a.clone(); + b["variables"] = json!({"filter":{"b":[2,3],"a":1}}); + assert_eq!( + OperationKey::from_origin(&alice, &a), + OperationKey::from_origin(&alice, &b) + ); + assert_ne!( + OperationKey::from_origin(&alice, &a), + OperationKey::from_origin(&bob, &a) + ); + b["operationName"] = "B".into(); + assert_ne!( + OperationKey::from_origin(&alice, &a), + OperationKey::from_origin(&alice, &b) + ); + b["operationName"] = "Absent".into(); + assert!(OperationKey::from_origin(&alice, &b).is_err()); + for document in [ + "mutation { edit }", + "query { commandStatus(commandId: \"one\") { state } }", + "query { todos { id } commandStatus(commandId: \"one\") { state } }", + ] { + assert!(OperationKey::from_origin(&alice, &json!({"query":document})).is_err()); + } + let mut changed = alice.clone(); + changed.authorization_generation = "policy-2".into(); + assert_ne!( + OperationKey::from_origin(&alice, &a), + OperationKey::from_origin(&changed, &a) + ); + let mut order = a.clone(); + order["variables"]["filter"]["b"] = json!([3, 2]); + assert_ne!( + OperationKey::from_origin(&alice, &a), + OperationKey::from_origin(&alice, &order) + ); +} +#[test] +fn eventual_pending_and_confirmed_minimum() { + let mut request = context(); + request.pending.push(models(&["Todo"])); + for dependency in [ + models(&["Todo"]), + models(&["Count", "Todo"]), + models(&["Todo", "Owner"]), + Dependencies::default(), + ] { + assert_eq!( + read_target(ReadConsistency::StaleTolerant, &dependency, Some(&request)), + ReadTarget::Primary + ); + } + assert_eq!( + read_target( + ReadConsistency::StaleTolerant, + &models(&["Blob"]), + Some(&request) + ), + ReadTarget::Replica + ); + request.observe([index("scope-1", "2")]).unwrap(); + request.pending.clear(); + assert!(!request.satisfied_by(&[index("scope-1", "1")])); + assert!(request.satisfied_by(&[index("scope-1", "2")])); + assert_eq!( + read_target( + ReadConsistency::StaleTolerant, + &models(&["Todo"]), + Some(&request) + ), + ReadTarget::Primary + ); + request + .observe([index("scope-1", "3"), index("incomparable", "1")]) + .unwrap(); + assert_eq!(request.minimum.len(), 2); + assert!(!request.satisfied_by(&[index("scope-1", "999")])); +} +#[test] +fn atomic_minimum_survives_confirmation() { + let mut request = context(); + let record = |incarnation: &str, revision: &str| Minimum::Record { + model: "Blob".into(), + scope_token: "record-1".into(), + incarnation: incarnation.into(), + revision: revision.into(), + }; + request.observe([record("1", "9")]).unwrap(); + assert!(request.pending.is_empty()); + assert!(!request.satisfied_by(&[record("1", "8")])); + request.observe([record("2", "1")]).unwrap(); + assert_eq!(request.minimum, [record("2", "1")]); + assert!(!request.satisfied_by(&[record("1", "999")])); + assert!(request.satisfied_by(&[record("2", "1")])); + assert_eq!( + request.bind(&identity("bob")), + Err(DeliveryError::ScopeChanged) + ); +} +#[test] +fn invalid_context_never_weakens_routing() { + let value = serde_json::to_value(context()).unwrap(); + for field in ["version", "cacheScope", "minimum", "pending"] { + let mut forged = value.clone(); + forged[field] = json!(-1); + assert!(FreshnessContext::parse(&forged).is_err()); + } + let mut large = value.clone(); + large["minimum"] = json!(vec![ + serde_json::to_value(index("scope", "1")).unwrap(); + 257 + ]); + assert!(FreshnessContext::parse(&large).is_err()); + assert!(index("scope", "18446744073709551616").validate().is_err()); + assert!(index("scope", "01").validate().is_err()); + assert_eq!( + read_target(ReadConsistency::Current, &models(&[]), None), + ReadTarget::Primary + ); +} diff --git a/tests/edge_query_delivery_postgres.rs b/tests/edge_query_delivery_postgres.rs new file mode 100644 index 000000000..e971359d0 --- /dev/null +++ b/tests/edge_query_delivery_postgres.rs @@ -0,0 +1,189 @@ +#![cfg(all( + feature = "gateway-delivery", + feature = "graphql", + feature = "postgres" +))] +use async_graphql::Request; +use distributed::graphql::{read, GraphqlEngine, ModelPermissions, ReadRouting}; +use distributed::microsvc::Session; +use serde_json::{json, Value}; +use std::time::Duration; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, distributed::ReadModel)] +#[readmodel(table = "gateway_replica_views", primary_key = ["id"])] +struct ReplicaView { + id: String, + title: String, +} +const QUERY: &str = "query StaleAllowed { gateway_replica_views { id title } }"; +const CURRENT: &str = "query CurrentState { gateway_replica_views { id title } }"; +fn engine(primary: &sqlx::PgPool, replica: &sqlx::PgPool, namespace: &str) -> GraphqlEngine { + GraphqlEngine::builder(primary.clone()) + .service_id("replica-fixture") + .protocol_token_key([57; 32]) + .protocol_namespace(namespace) + .roles(&["user"]) + .anonymous_role("user") + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .read_routing( + ReadRouting::new(replica.clone()) + .stale_tolerant(QUERY, Some("StaleAllowed".into())) + .unwrap(), + ) + .build() + .unwrap() +} +async fn query(engine: &GraphqlEngine, document: &str, context: Option) -> Value { + let mut request = Request::new(document).operation_name(if document == QUERY { + "StaleAllowed" + } else { + "CurrentState" + }); + if let Some(context) = context { + request.extensions.insert( + "gatewayFreshness".into(), + async_graphql::Value::from_json(context).unwrap(), + ); + } + serde_json::to_value(engine.execute(&Session::new(), request).await).unwrap() +} +async fn wait_replayed(pool: &sqlx::PgPool, title: &str) { + tokio::time::timeout(Duration::from_secs(15), async { + loop { + if sqlx::query_scalar::<_, String>( + "SELECT title FROM gateway_replica_views WHERE id='one'", + ) + .fetch_optional(pool) + .await + .ok() + .flatten() + .as_deref() + == Some(title) + { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .expect("standby replayed fixture write"); +} + +#[tokio::test] +async fn paused_replica_never_certifies_freshness() { + let primary = sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(Duration::from_secs(3)) + .connect( + &std::env::var("GATEWAY_TEST_PRIMARY_URL").expect("run tests/gateway-postgres/run.py"), + ) + .await + .unwrap(); + let replica = sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(Duration::from_secs(3)) + .connect(&std::env::var("GATEWAY_TEST_REPLICA_URL").expect("owned standby URL")) + .await + .unwrap(); + sqlx::query("CREATE TABLE gateway_replica_views (id text PRIMARY KEY, title text NOT NULL)") + .execute(&primary) + .await + .unwrap(); + sqlx::query("INSERT INTO gateway_replica_views VALUES ('one','before')") + .execute(&primary) + .await + .unwrap(); + wait_replayed(&replica, "before").await; + assert!(sqlx::query_scalar::<_, bool>("SELECT pg_is_in_recovery()") + .fetch_one(&replica) + .await + .unwrap()); + sqlx::query("SELECT pg_wal_replay_pause()") + .execute(&replica) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if sqlx::query_scalar::<_, String>("SELECT pg_get_wal_replay_pause_state()") + .fetch_one(&replica) + .await + .unwrap() + == "paused" + { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .unwrap(); + sqlx::query("UPDATE gateway_replica_views SET title='committed' WHERE id='one'") + .execute(&primary) + .await + .unwrap(); + let engine = engine(&primary, &replica, "epoch-1"); + assert_eq!( + query(&engine, QUERY, None).await["data"]["gateway_replica_views"][0]["title"], + "before" + ); + assert_eq!( + query(&engine, CURRENT, None).await["data"]["gateway_replica_views"][0]["title"], + "committed" + ); + let identity = engine + .delivery_identity( + &Session::new(), + &Request::new(QUERY).operation_name("StaleAllowed"), + ) + .unwrap(); + let context = json!({"version":1,"schemaHash":identity.schema_hash,"protocolHash":identity.protocol_hash,"authorizationGeneration":identity.authorization_generation,"cacheScope":identity.cache_scope,"pending":[{"complete":true,"models":["ReplicaView"],"relationships":[]}],"minimum":[]}); + assert_eq!( + query(&engine, QUERY, Some(context.clone())).await["data"]["gateway_replica_views"][0] + ["title"], + "committed" + ); + let mut disjoint = context.clone(); + disjoint["pending"][0]["models"] = json!(["OtherView"]); + assert_eq!( + query(&engine, QUERY, Some(disjoint)).await["data"]["gateway_replica_views"][0]["title"], + "before" + ); + // A new backend generation cannot authenticate old-scope context. + let next = self::engine(&replica, &primary, "epoch-2"); + assert_eq!( + query(&next, QUERY, Some(context.clone())).await["errors"][0]["extensions"]["code"], + "FRESHNESS_SCOPE_CHANGED" + ); + let misbound = query(&next, CURRENT, None).await; + assert!( + misbound.get("errors").is_some() && misbound["data"].is_null(), + "a standby cannot certify a current read: {misbound}" + ); + let container = std::env::var("GATEWAY_TEST_PRIMARY_CONTAINER").unwrap(); + assert!(container.starts_with("gateway-replay-") && container.ends_with("-primary")); + assert!(std::process::Command::new("docker") + .args(["stop", "-t", "1", &container]) + .status() + .unwrap() + .success()); + let unavailable = query(&engine, QUERY, Some(context.clone())).await; + assert!(unavailable.get("errors").is_some(), "{unavailable}"); + assert!( + unavailable["data"].is_null(), + "must not retry the old standby: {unavailable}" + ); + assert!(std::process::Command::new("docker") + .args(["start", &container]) + .status() + .unwrap() + .success()); + sqlx::query("SELECT pg_wal_replay_resume()") + .execute(&replica) + .await + .unwrap(); + wait_replayed(&replica, "committed").await; + assert_eq!( + query(&engine, QUERY, None).await["data"]["gateway_replica_views"][0]["title"], + "committed" + ); + primary.close().await; + replica.close().await; +} diff --git a/tests/gateway-portable/Cargo.toml b/tests/gateway-portable/Cargo.toml index 6cbb3f314..80a1340c1 100644 --- a/tests/gateway-portable/Cargo.toml +++ b/tests/gateway-portable/Cargo.toml @@ -10,6 +10,7 @@ publish = false default = ["gateway"] gateway = ["distributed/gateway"] gateway-graphql = ["gateway", "distributed/gateway-graphql"] +gateway-delivery = ["gateway-graphql", "distributed/gateway-delivery"] [dependencies] distributed = { path = "../..", default-features = false } @@ -32,3 +33,7 @@ path = "../gateway_auth.rs" [[test]] name = "gateway_graphql_operation" path = "../gateway_graphql_operation.rs" + +[[test]] +name = "edge_query_delivery" +path = "../edge_query_delivery.rs" diff --git a/tests/gateway-postgres/README.md b/tests/gateway-postgres/README.md new file mode 100644 index 000000000..589679b41 --- /dev/null +++ b/tests/gateway-postgres/README.md @@ -0,0 +1,13 @@ +# Physical standby freshness fixture + +Run `python3 tests/gateway-postgres/run.py`. Requires Docker and Rust. The script +creates its own network and two digest-pinned PostgreSQL containers with empty +in-memory data directories, binds only loopback ephemeral ports, and removes only +those owned resources on exit. No application database or credentials are read. + +The test uses `pg_wal_replay_pause` and waits for the actual paused state before +writing the primary. It checks selected GraphQL responses and unavailable-primary +behavior, then resumes replay. PostgreSQL documents the distinction between +[replay pause and receive](https://www.postgresql.org/docs/16/functions-admin.html) +and the [`pg_basebackup -R` standby setup](https://www.postgresql.org/docs/16/app-pgbasebackup.html). +This is a test fixture, not a production WAL routing policy. diff --git a/tests/gateway-postgres/run.py b/tests/gateway-postgres/run.py new file mode 100644 index 000000000..4de64df10 --- /dev/null +++ b/tests/gateway-postgres/run.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Owned ephemeral primary/physical-standby fixture; no shared DB access.""" +from pathlib import Path +import json, os, socketserver, subprocess, sys, threading, time, uuid +ROOT = Path(__file__).resolve().parents[2] +IMAGE = "postgres@sha256:cf78e76683b9ca8c5733cbbdce6c9262b45b6767934dd0a95e671f9a0fc20685" +prefix = "gateway-replay-" + uuid.uuid4().hex[:10] +primary, standby = prefix + "-primary", prefix + "-standby" + +def docker(*args): + try: + return subprocess.check_output(["docker", *args], text=True, stderr=subprocess.STDOUT).strip() + except subprocess.CalledProcessError as error: + print(error.output[-3000:], file=sys.stderr) + raise + +def ready(container): + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + result = subprocess.run(["docker", "exec", container, "pg_isready", "-h", "127.0.0.1", "-U", "postgres"], capture_output=True) + if result.returncode == 0: return + time.sleep(.2) + raise RuntimeError("fixture database failed readiness: " + docker("logs", container)[-3000:]) + +bridges = [] +def url(container): + # Docker stdio avoids dependence on desktop VM published-port forwarding. + # Every connection still terminates at the actual PostgreSQL backend. + class Tunnel(socketserver.BaseRequestHandler): + def handle(self): + process = subprocess.Popen(["docker", "exec", "-i", container, "busybox", "nc", "127.0.0.1", "5432"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0) + def upload(): + try: + while chunk := self.request.recv(65536): process.stdin.write(chunk) + except (OSError, BrokenPipeError): pass + finally: + try: process.stdin.close() + except OSError: pass + sender = threading.Thread(target=upload, daemon=True); sender.start() + try: + while chunk := process.stdout.read(65536): self.request.sendall(chunk) + except OSError: pass + finally: + process.terminate() + try: process.wait(timeout=2) + except subprocess.TimeoutExpired: process.kill(); process.wait() + try: self.request.shutdown(2) + except OSError: pass + sender.join(timeout=2) + class Server(socketserver.ThreadingTCPServer): + daemon_threads = True + server = Server(("127.0.0.1", 0), Tunnel) + threading.Thread(target=server.serve_forever, daemon=True).start() + bridges.append(server) + return "postgres://postgres@127.0.0.1:" + str(server.server_address[1]) + "/postgres?sslmode=disable" + +try: + docker("network", "create", prefix) + docker("run", "-d", "--name", primary, "--network", prefix, "--network-alias", "primary", "--tmpfs", "/var/lib/postgresql/data", "-e", "POSTGRES_HOST_AUTH_METHOD=trust", IMAGE, "postgres", "-c", "wal_level=replica", "-c", "max_wal_senders=4") + ready(primary) + docker("exec", primary, "sh", "-c", "printf 'host replication postgres all trust\n' >> /var/lib/postgresql/data/pg_hba.conf") + docker("exec", primary, "psql", "-U", "postgres", "-c", "SELECT pg_reload_conf()") + docker("run", "-d", "--name", standby, "--network", prefix, "--user", "postgres", "--tmpfs", "/replica:uid=70,gid=70,mode=0700", "--entrypoint", "sh", IMAGE, "-c", "pg_basebackup -h primary -U postgres -D /replica -R -X stream && exec postgres -D /replica") + ready(standby) + print("Fixture PostgreSQL " + docker("exec", primary, "postgres", "--version"), flush=True) + env = {**os.environ, "GATEWAY_TEST_PRIMARY_URL": url(primary), "GATEWAY_TEST_REPLICA_URL": url(standby), "GATEWAY_TEST_PRIMARY_CONTAINER": primary} + subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--nocapture"], cwd=ROOT, env=env, check=True) +finally: + for bridge in bridges: + bridge.shutdown(); bridge.server_close() + for container in [standby, primary]: + subprocess.run(["docker", "rm", "-f", container], capture_output=True) + subprocess.run(["docker", "network", "rm", prefix], capture_output=True) diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 6310e7af3..2234d7d97 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -1496,3 +1496,96 @@ async fn unowned_legacy_query_is_explicitly_incomplete_and_still_strips_keys() { assert_eq!(snapshot["observations"], json!([])); assert_opaque_token(&snapshot["scopeToken"], "query-snapshot"); } + +#[cfg(feature = "gateway-delivery")] +#[tokio::test] +async fn freshness_context_binds_origin_and_rejects_unproven_minima() { + use distributed::gateway::delivery::{FreshnessContext, Minimum}; + let fixture = protocol_fixture_with_retention(10).await; + let document = "query ReadFreshness { causal_query_views { title } }"; + let request = || Request::new(document); + let identity = fixture + .engine + .delivery_identity(&user_session(), &request()) + .unwrap(); + let mut context = FreshnessContext::parse(&json!({ + "version":1, "schemaHash":identity.schema_hash, "protocolHash":identity.protocol_hash, + "authorizationGeneration":identity.authorization_generation, "cacheScope":identity.cache_scope, + "pending":[{"complete":true,"models":["CausalQueryView"],"relationships":[]}], "minimum":[] + })).unwrap(); + let with_context = |context: &FreshnessContext| { + let mut request = request(); + request.extensions.insert( + "gatewayFreshness".into(), + async_graphql::Value::from_json(serde_json::to_value(context).unwrap()).unwrap(), + ); + request + }; + let before = wire_response( + fixture + .engine + .execute(&user_session(), with_context(&context)) + .await, + ); + assert_eq!( + before["data"]["causal_query_views"][0]["title"], + "causal row" + ); + assert_eq!( + distributed_envelope(&before)["snapshot"]["observations"], + json!([]) + ); + project_item(&fixture.repository, &fixture.bus, 2, "committed").await; + let after = wire_response( + fixture + .engine + .execute(&user_session(), with_context(&context)) + .await, + ); + let index = &distributed_envelope(&after)["snapshot"]["indexes"][0]; + context + .observe([Minimum::Index { + projection: index["projection"].as_str().unwrap().into(), + scope_token: index["scopeToken"].as_str().unwrap().into(), + position: "2".into(), + }]) + .unwrap(); + context.pending.clear(); + assert_eq!( + wire_response( + fixture + .engine + .execute(&user_session(), with_context(&context)) + .await + )["data"]["causal_query_views"][0]["title"], + "committed" + ); + let mut future = context.clone(); + if let Minimum::Index { position, .. } = &mut future.minimum[0] { + *position = "999".into(); + } + let rejected = serde_json::to_value( + fixture + .engine + .execute(&user_session(), with_context(&future)) + .await, + ) + .unwrap(); + assert_eq!( + rejected["errors"][0]["extensions"]["code"], + "FRESHNESS_PENDING" + ); + assert!(rejected["data"].is_null()); + let mut forged = context; + forged.cache_scope = "another-subject".into(); + assert_eq!( + serde_json::to_value( + fixture + .engine + .execute(&user_session(), with_context(&forged)) + .await + ) + .unwrap()["errors"][0]["extensions"]["code"], + "FRESHNESS_SCOPE_CHANGED" + ); +} From d018dc00bccfc294e401304bf5f8a19d44c3ae8a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 22:48:32 -0500 Subject: [PATCH 054/484] feat(gateway): validate snapshot caches against transactional origin versions --- .github/workflows/integration-gateway.yaml | 9 +- docs/gateway/snapshot-cache.md | 65 +++ migrations/inventory.json | 12 + .../0006_gateway_dependency_versions.sql | 9 + .../0006_gateway_dependency_versions.sql | 9 + src/gateway/README.md | 6 + src/gateway/delivery/identity.rs | 1 + src/gateway/delivery/mod.rs | 3 + src/gateway/delivery/snapshot.rs | 351 ++++++++++++ src/gateway/native/delivery.rs | 300 ++++++++++ src/gateway/native/graphql.rs | 38 +- src/gateway/native/mod.rs | 38 ++ src/gateway/native/proxy.rs | 12 +- src/graphql/delivery/mod.rs | 39 ++ src/graphql/delivery/versions.rs | 535 ++++++++++++++++++ src/graphql/engine/builder.rs | 15 + src/graphql/engine/core.rs | 4 + src/graphql/engine/delivery.rs | 158 ++++++ src/graphql/engine/mod.rs | 3 + src/graphql/engine/request.rs | 13 + src/graphql/identity/oidc.rs | 9 + src/graphql/mod.rs | 3 + src/graphql/protocol/accumulator.rs | 56 ++ src/graphql/query_protocol.rs | 55 +- src/graphql/schema.rs | 14 + src/sqlx_repo/projection_protocol/tests.rs | 17 + tests/edge_query_delivery.rs | 135 +++++ tests/gateway-postgres/run.py | 2 + tests/graphql_query_protocol/main.rs | 314 ++++++++++ tests/graphql_sqlite/main.rs | 89 +++ tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 32 files changed, 2307 insertions(+), 11 deletions(-) create mode 100644 docs/gateway/snapshot-cache.md create mode 100644 migrations/postgres/0006_gateway_dependency_versions.sql create mode 100644 migrations/sqlite/0006_gateway_dependency_versions.sql create mode 100644 src/gateway/delivery/snapshot.rs create mode 100644 src/gateway/native/delivery.rs create mode 100644 src/graphql/delivery/mod.rs create mode 100644 src/graphql/delivery/versions.rs create mode 100644 src/graphql/engine/delivery.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index b6604d48a..570c9e5ae 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -7,6 +7,8 @@ on: - 'distributed_macros/**' - 'Cargo.toml' - 'build.rs' + - 'migrations/**' + - 'docs/gateway/**' - 'tests/e2e-ui/ui/src/auth.ts' - 'tests/e2e-ui/ui/src/lib/server/**' - 'tests/e2e-ui/ui/src/routes/api/auth/**' @@ -107,7 +109,12 @@ jobs: with: toolchain: stable - name: Verify embedded and remote GraphQL protocols - run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity --test graphql_sqlite --test sqlite_repository + + - name: Verify transactional cache coverage and Atomic rollback + run: | + cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib graphql::delivery::versions::tests + cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib sqlite_direct_projection_and_ledger_replay_commit_atomically freshness: runs-on: ubuntu-latest diff --git a/docs/gateway/snapshot-cache.md b/docs/gateway/snapshot-cache.md new file mode 100644 index 000000000..d00c6fa2a --- /dev/null +++ b/docs/gateway/snapshot-cache.md @@ -0,0 +1,65 @@ +# Origin-validated query snapshots + +Enable `gateway-graphql-native,gateway-delivery` and the origin's SQL adapter. +The portable `gateway-delivery` feature alone has no SQL or native runtime. +Caching is opt-in: mount `NativeBinding::GraphqlWithDelivery` with an explicit +`NativeDelivery::snapshots(SnapshotLimits)` resource and declare `snapshots` +on that binding. An unselected capability allocates no cache. + +On the origin, after framework and application migrations, install +`GatewayVersionStore::install(&pool, application_namespace, physical_tables)` +and pass the resulting store to `GraphqlEngine::builder(...).gateway_versions(store)`. +The inventory must cover every table touched by an eligible compiled query, +including relationship targets and intermediate join tables. Installed projection +proof tables are included automatically because even a no-op projection can +change the response's evidence. This is conservative across projection partitions. + +Each consumer sends an authenticated validation request to the configured origin +using the existing GraphQL endpoint with the reserved `gatewayDelivery` extension. +Origin authentication, schema validation and the compiler's row/field authorization +run for every request. Validation executes a single dependency-vector SQL statement +inside a primary read snapshot; it executes no result SQL. The gateway accepts the +identity and opaque validator only from that origin response. Public request metadata +cannot grant cache scope. The existing executor still owns commands and command status. + +A miss executes the query with its data, causal metadata and validator in the same +SQL snapshot. The gateway revalidates after the fill and installs only if its own +validator is still current. Every hit revalidates on the primary, so delayed or lost +invalidation notifications cannot certify old private data. Authentication/primary +failure never falls back to cached private data. Missing dependency hooks make the +operation bypass reuse; unknown/custom resolver dependencies, commands/status, +errors, partial results, cookie-setting responses, `no-store`, and `Vary: *` also +bypass storage. Required client freshness minima must be covered by the stored proof. + +Defaults are 1,024 entries, 16 MiB total response bytes and 1 MiB per response. +Oversized/streaming responses continue to the consumer without truncation or storage. +Native response-header/read deadlines bound validation and capture. Entries use LRU +eviction; `invalidate_all()` also fences fills that began before the reset. +`GatewayVersionStore::metrics()` reports origin validations separately from actual +result SQL executions; these counters do not contain subjects or query text. + +For explicitly public content, `store.public_snapshot(exact_document, operation_name, +max_age_seconds)` permits 1–86,400 seconds of content age. This applies to all variable +values of that exact operation. It still requires fresh origin admission and preserves +subject isolation. Age starts at the original origin validation and is never extended +by copying an entry, a new admission, or another cache layer. The default policy always +requires the current version vector. + +## Activation and rollback + +Migration `0006_gateway_dependency_versions` is additive and registered in the normal +SQLite/PostgreSQL migration inventory. No application data is backfilled or rewritten. +Activation installs transactional write hooks and starts a new random epoch. Normal +SQL producers, Eventual projectors, Atomic projection commits, deletes, and PostgreSQL +TRUNCATE all update versions in their data transaction. A failed transaction rolls +versions back with the data. Privileged writers that disable/drop hooks are unsupported +until coverage is restored; validation detects missing/disabled hooks and bypasses reuse. +Applications must not manually replace framework hooks with different implementations. + +Install after application migrations, before enabling cache bindings. Rebuild or change +writer coverage in a controlled migration window, reinstall hooks/start a new epoch, +then invalidate gateway stores before reopening traffic. `rotate_epoch` is available +for an explicit rebuild boundary. Epochs are random identities, not inferred wall clocks +or PostgreSQL WAL positions. Disable the cache binding on rollback; leave additive +metadata in place until a separately planned cleanup. Never apply cleanup to a live DB +as part of a gateway cache rollback. diff --git a/migrations/inventory.json b/migrations/inventory.json index f241a8742..ccea03955 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -60,6 +60,18 @@ "path": "migrations/postgres/0005_projection_source_snapshots.sql", "sha256": "2cb605be4ec190d9b3f156bdbbeb83a76e5f1f37287a8a7f3c2653dafbede442" } + }, + { + "version": 6, + "description": "gateway dependency versions", + "sqlite": { + "path": "migrations/sqlite/0006_gateway_dependency_versions.sql", + "sha256": "c156bc51dddecd49b1beef7bb4069557b024c19cb1271f0ec9cc0efe71939471" + }, + "postgres": { + "path": "migrations/postgres/0006_gateway_dependency_versions.sql", + "sha256": "c156bc51dddecd49b1beef7bb4069557b024c19cb1271f0ec9cc0efe71939471" + } } ] } diff --git a/migrations/postgres/0006_gateway_dependency_versions.sql b/migrations/postgres/0006_gateway_dependency_versions.sql new file mode 100644 index 000000000..287d427cc --- /dev/null +++ b/migrations/postgres/0006_gateway_dependency_versions.sql @@ -0,0 +1,9 @@ +-- Private gateway dependency versions. Runtime cache activation installs +-- per-table transactional hooks after application read-model migrations. +CREATE TABLE IF NOT EXISTS distributed_gateway_versions ( + namespace TEXT NOT NULL, + table_name TEXT NOT NULL, + epoch TEXT NOT NULL, + version BIGINT NOT NULL CHECK (version >= 0), + PRIMARY KEY (namespace, table_name) +); diff --git a/migrations/sqlite/0006_gateway_dependency_versions.sql b/migrations/sqlite/0006_gateway_dependency_versions.sql new file mode 100644 index 000000000..287d427cc --- /dev/null +++ b/migrations/sqlite/0006_gateway_dependency_versions.sql @@ -0,0 +1,9 @@ +-- Private gateway dependency versions. Runtime cache activation installs +-- per-table transactional hooks after application read-model migrations. +CREATE TABLE IF NOT EXISTS distributed_gateway_versions ( + namespace TEXT NOT NULL, + table_name TEXT NOT NULL, + epoch TEXT NOT NULL, + version BIGINT NOT NULL CHECK (version >= 0), + PRIMARY KEY (namespace, table_name) +); diff --git a/src/gateway/README.md b/src/gateway/README.md index 40cfbdbf4..ae253ac42 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -106,3 +106,9 @@ admission require a fresh origin identity for every consumer. No routing migration is required. Disable replica registration to route all reads to primary; keep client revision fences active during a deployment rollback. The isolated physical standby fixture is documented in tests/gateway-postgres. + +Snapshot caching is available through the explicit `NativeDelivery::snapshots` +resource (`gateway-graphql-native,gateway-delivery`). Origin-side +`GatewayVersionStore` supplies transactional data/proof dependency versions; +every hit authenticates and validates at the primary without result SQL. +See [activation, limits, public-age policy and rollback](../../docs/gateway/snapshot-cache.md). diff --git a/src/gateway/delivery/identity.rs b/src/gateway/delivery/identity.rs index 507041aab..3668e1b63 100644 --- a/src/gateway/delivery/identity.rs +++ b/src/gateway/delivery/identity.rs @@ -85,6 +85,7 @@ impl OperationKey { .as_object_mut() .ok_or(DeliveryError::Ineligible)?; object.remove("gatewayFreshness"); + object.remove("gatewayDelivery"); let bytes = canonical_json(&serde_json::json!([ identity, document, name, variables, extensions ]))?; diff --git a/src/gateway/delivery/mod.rs b/src/gateway/delivery/mod.rs index 0315c03d3..c8f589ad3 100644 --- a/src/gateway/delivery/mod.rs +++ b/src/gateway/delivery/mod.rs @@ -25,3 +25,6 @@ impl std::fmt::Display for DeliveryError { } } impl std::error::Error for DeliveryError {} + +mod snapshot; +pub use snapshot::*; diff --git a/src/gateway/delivery/snapshot.rs b/src/gateway/delivery/snapshot.rs new file mode 100644 index 000000000..5f4026c97 --- /dev/null +++ b/src/gateway/delivery/snapshot.rs @@ -0,0 +1,351 @@ +use super::{DeliveryError, FreshnessContext, Minimum, OperationKey, OriginIdentity}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Fresh authenticated origin control response. Deserialize only from the +/// configured origin, never from public request headers/body or a cached grant. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OriginAdmission { + /// Effective origin identity including subject and policy generation. + pub identity: OriginIdentity, + /// Exact admitted operation and variable identity. + pub key: OperationKey, + /// Exact transport document fingerprint in the response envelope. + pub operation: String, + /// Opaque version vector computed on the primary at this validation. + pub validator: String, + /// Origin validation time, seconds since Unix epoch. + pub validated_at: u64, + /// Credential/admission expiry; never extended by copying an entry. + pub expires_at: u64, + /// Origin-approved policy; private/current is the default. + pub policy: SnapshotPolicy, +} +impl OriginAdmission { + /// Ensure a configured origin answered this exact consumer operation. + pub fn bind(&self, request: &serde_json::Value, now: u64) -> Result<(), DeliveryError> { + self.validate(now)?; + if OperationKey::from_origin(&self.identity, request)? != self.key { + return Err(DeliveryError::ScopeChanged); + } + Ok(()) + } + /// Validate a fresh control response before lookup/join. + pub fn validate(&self, now: u64) -> Result<(), DeliveryError> { + self.identity.validate()?; + if self.key.as_str().len() != 64 + || !self + .key + .as_str() + .bytes() + .all(|byte| byte.is_ascii_hexdigit()) + { + return Err(DeliveryError::InvalidContext); + } + if self.validator.is_empty() + || self.validator.len() > 1024 + || self.operation.is_empty() + || self.operation.len() > 256 + || self.validated_at > now.saturating_add(5) + || self.expires_at <= now + || self.expires_at <= self.validated_at + { + return Err(DeliveryError::Unavailable); + } + if let SnapshotPolicy::Public { max_age_seconds } = self.policy { + if max_age_seconds == 0 || max_age_seconds > 86400 { + return Err(DeliveryError::InvalidContext); + } + } + Ok(()) + } +} + +/// Data staleness policy never relaxes per-consumer origin authentication. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum SnapshotPolicy { + /// Require the primary's current version vector on every hit. + #[default] + Current, + /// Explicit origin-approved public staleness, measured from validation. + Public { + /// Maximum age in seconds; copying cannot renew it. + max_age_seconds: u64, + }, +} + +/// Bounded storage limits. No cache exists unless explicitly constructed. +#[derive(Clone, Copy, Debug)] +pub struct SnapshotLimits { + /// Maximum resident entries. + pub entries: usize, + /// Maximum aggregate response bytes. + pub bytes: usize, + /// Maximum individual response size. + pub entry_bytes: usize, +} +impl Default for SnapshotLimits { + fn default() -> Self { + Self { + entries: 1024, + bytes: 16 * 1024 * 1024, + entry_bytes: 1024 * 1024, + } + } +} + +/// Complete HTTP envelope retained without reconstructing GraphQL data/proofs. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SnapshotResponse { + /// HTTP status; reusable responses must be successful. + pub status: u16, + /// End-to-end response headers, preserving duplicate values. + pub headers: Vec<(String, String)>, + /// Exact JSON response bytes from the executor. + pub body: Vec, +} +impl SnapshotResponse { + fn evidence(&self, admission: &OriginAdmission) -> Option> { + if self.status != 200 + || self.headers.iter().any(|(name, value)| { + name.eq_ignore_ascii_case("set-cookie") + || (name.eq_ignore_ascii_case("cache-control") + && value + .split(',') + .any(|directive| directive.trim().eq_ignore_ascii_case("no-store"))) + || (name.eq_ignore_ascii_case("vary") + && value.split(',').any(|field| field.trim() == "*")) + }) + { + return None; + } + let value: serde_json::Value = serde_json::from_slice(&self.body).ok()?; + if value.get("data").is_none() + || value["data"].is_null() + || value + .get("errors") + .is_some_and(|e| e.as_array().is_none_or(|e| !e.is_empty())) + { + return None; + } + let protocol = &value["extensions"]["distributed"]; + if protocol["protocolVersion"] != 1 + || protocol["schemaHash"] != admission.identity.schema_hash + || protocol["authorizationGeneration"] != admission.identity.authorization_generation + || protocol["cacheScope"] != admission.identity.cache_scope + || protocol["operation"] != admission.operation + || protocol.get("command").is_some() + || protocol.get("receipt").is_some() + || protocol.get("live").is_some() + { + return None; + } + let snapshot = &protocol["snapshot"]; + if snapshot["recordsComplete"] != true || snapshot["indexesComparable"] != true { + return None; + } + let mut evidence = Vec::new(); + for record in snapshot["records"].as_array()? { + let minimum = Minimum::Record { + model: record["model"].as_str()?.into(), + scope_token: record["scopeToken"].as_str()?.into(), + incarnation: record["incarnation"].as_str()?.into(), + revision: record["revision"].as_str()?.into(), + }; + minimum.validate().ok()?; + evidence.push(minimum); + } + for index in snapshot["indexes"].as_array()? { + let minimum = Minimum::Index { + projection: index["projection"].as_str()?.into(), + scope_token: index["scopeToken"].as_str()?.into(), + position: index["position"].as_str()?.into(), + }; + minimum.validate().ok()?; + evidence.push(minimum); + } + Some(evidence) + } + /// Candidate proof covers every required floor in the admitted scope. + pub fn satisfies( + &self, + admission: &OriginAdmission, + freshness: Option<&FreshnessContext>, + ) -> bool { + self.evidence(admission).is_some_and(|evidence| { + freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + }) + }) + } +} + +#[derive(Clone)] +struct Entry { + admission: OriginAdmission, + response: SnapshotResponse, + bytes: usize, + sequence: u64, +} +/// Opaque reservation fencing cache installation after invalidation/restart. +#[derive(Clone, Debug)] +pub struct FillTicket { + key: OperationKey, + generation: u64, +} + +/// Portable bounded snapshot store. Runtime adapters provide current origin +/// admission for every consumer and coordinate calls; this owns no task/socket. +pub struct SnapshotCache { + limits: SnapshotLimits, + entries: BTreeMap, + bytes: usize, + generation: u64, + sequence: u64, +} +impl SnapshotCache { + /// Allocate an empty cache with explicit resource bounds. + pub fn new(limits: SnapshotLimits) -> Result { + if limits.entries == 0 + || limits.entries > 65536 + || limits.bytes == 0 + || limits.bytes > 1024 * 1024 * 1024 + || limits.entry_bytes == 0 + || limits.entry_bytes > limits.bytes + { + return Err(DeliveryError::InvalidContext); + } + Ok(Self { + limits, + entries: BTreeMap::new(), + bytes: 0, + generation: 0, + sequence: 0, + }) + } + /// Reserve a fill after authentication. Invalidations fence old tickets. + pub fn begin_fill( + &self, + admission: &OriginAdmission, + now: u64, + ) -> Result { + admission.validate(now)?; + Ok(FillTicket { + key: admission.key.clone(), + generation: self.generation, + }) + } + /// Lookup against a fresh authenticated primary validation, never a stored + /// lease alone. Public age is anchored to the original validation time. + pub fn lookup( + &mut self, + admission: &OriginAdmission, + freshness: Option<&FreshnessContext>, + now: u64, + ) -> Result, DeliveryError> { + admission.validate(now)?; + if let Some(freshness) = freshness { + freshness.bind(&admission.identity)?; + } + let Some(entry) = self.entries.get_mut(&admission.key) else { + return Ok(None); + }; + let current = entry.admission.validator == admission.validator; + let public_age = match (entry.admission.policy, admission.policy) { + ( + SnapshotPolicy::Public { + max_age_seconds: first, + }, + SnapshotPolicy::Public { + max_age_seconds: next, + }, + ) => now.saturating_sub(entry.admission.validated_at) <= first.min(next), + _ => false, + }; + if (!current && !public_age) + || entry.admission.identity != admission.identity + || !entry.response.satisfies(admission, freshness) + { + return Ok(None); + } + self.sequence = self.sequence.saturating_add(1); + entry.sequence = self.sequence; + Ok(Some(entry.response.clone())) + } + /// Install only after revalidating the response's own snapshot validator at + /// the origin. A late old fill cannot acquire a newer result's validator. + pub fn install( + &mut self, + ticket: FillTicket, + admission: OriginAdmission, + response: SnapshotResponse, + now: u64, + ) -> Result { + admission.validate(now)?; + let bytes = response.body.len() + + response + .headers + .iter() + .map(|(a, b)| a.len() + b.len()) + .sum::(); + if bytes > self.limits.entry_bytes { + return Ok(false); + } + if self.generation == u64::MAX + || ticket.generation != self.generation + || ticket.key != admission.key + || !response.satisfies(&admission, None) + { + return Ok(false); + } + let value: serde_json::Value = + serde_json::from_slice(&response.body).map_err(|_| DeliveryError::Ineligible)?; + if value["extensions"]["gatewayDelivery"]["validator"] != admission.validator { + return Ok(false); + } + if let Some(previous) = self.entries.remove(&ticket.key) { + self.bytes -= previous.bytes; + } + while self.entries.len() >= self.limits.entries || self.bytes + bytes > self.limits.bytes { + let Some(key) = self + .entries + .iter() + .min_by_key(|(_, e)| e.sequence) + .map(|(k, _)| k.clone()) + else { + break; + }; + self.bytes -= self.entries.remove(&key).expect("resident key").bytes; + } + self.sequence = self.sequence.saturating_add(1); + self.bytes += bytes; + self.entries.insert( + ticket.key, + Entry { + admission, + response, + bytes, + sequence: self.sequence, + }, + ); + Ok(true) + } + /// Lost feed, rebuild or coordinator reset discards data and fences fills. + pub fn invalidate_all(&mut self) { + self.entries.clear(); + self.bytes = 0; + // Saturation cannot permit an old ticket to become current: at the + // terminal counter value installation is permanently disabled. + self.generation = self.generation.saturating_add(1); + } + /// Current resident entry count for diagnostics and boundedness checks. + pub fn len(&self) -> usize { + self.entries.len() + } + /// Whether the store is empty. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} diff --git a/src/gateway/native/delivery.rs b/src/gateway/native/delivery.rs new file mode 100644 index 000000000..f69724c89 --- /dev/null +++ b/src/gateway/native/delivery.rs @@ -0,0 +1,300 @@ +use super::{ + graphql::GraphqlBinding, response, Body, GatewayError, NativeInner, Request, RequestContext, + Response, StatusCode, +}; +use crate::gateway::{delivery::*, DeliveryCapabilities, GraphqlExecutor}; +use axum::{ + body::Bytes, + http::{header, request::Parts}, + response::IntoResponse, +}; +use futures_util::StreamExt; +use std::sync::Mutex; +use tokio::sync::OwnedSemaphorePermit; + +/// Bounded native coordinator. Snapshot storage is allocated only when this +/// explicit resource is mounted; every lookup first visits authenticated origin +/// validation. Query-flight and live-sharing mounts remain independent. +pub struct NativeDelivery { + snapshots: Mutex, + entry_bytes: usize, +} +impl NativeDelivery { + /// Allocate a bounded origin-validated snapshot cache. + pub fn snapshots(limits: SnapshotLimits) -> Result { + let snapshots = + SnapshotCache::new(limits).map_err(|_| GatewayError("invalid snapshot limits"))?; + Ok(Self { + snapshots: Mutex::new(snapshots), + entry_bytes: limits.entry_bytes, + }) + } + pub(super) fn capabilities(&self) -> DeliveryCapabilities { + DeliveryCapabilities { + snapshots: true, + coalescing: false, + live_sharing: false, + } + } + /// Invalidate on a known lost feed, rebuild or coordinator reset. Private + /// lookups still validate at primary even without a pushed invalidation. + pub fn invalidate_all(&self) { + if let Ok(mut cache) = self.snapshots.lock() { + cache.invalidate_all(); + } + } + #[allow(clippy::too_many_arguments)] + pub(super) async fn execute( + &self, + binding: &GraphqlBinding, + inner: &NativeInner, + executor: &GraphqlExecutor, + context: RequestContext, + parts: Parts, + value: serde_json::Value, + permit: OwnedSemaphorePermit, + ) -> Response { + let freshness = match value["extensions"].get("gatewayFreshness") { + Some(value) => match FreshnessContext::parse(value) { + Ok(value) => Some(value), + Err(_) => return response(StatusCode::BAD_REQUEST), + }, + None => None, + }; + let admission = match validate(binding, inner, executor, &context, &parts, &value).await { + AdmissionResult::Eligible(admission) => admission, + AdmissionResult::Bypass => { + return binding + .execute_http( + inner, + executor, + context, + request(&parts, value), + Some(permit), + ) + .await + } + AdmissionResult::Error(error) => return error, + }; + let ticket = { + let Ok(mut cache) = self.snapshots.lock() else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; + match cache.lookup(&admission, freshness.as_ref(), super::now()) { + Ok(Some(hit)) => return cached_response(hit), + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + Ok(None) => {} + } + match cache.begin_fill(&admission, super::now()) { + Ok(ticket) => ticket, + Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), + } + }; + let mut execution = value.clone(); + mark(&mut execution, "snapshot"); + let result = binding + .execute_http( + inner, + executor, + context.clone(), + request(&parts, execution), + None, + ) + .await; + let (response_parts, body) = result.into_parts(); + let captured = match tokio::time::timeout( + inner.options.limits.read_timeout, + capture(body, self.entry_bytes), + ) + .await + { + Ok(captured) => captured, + Err(_) => return response(StatusCode::GATEWAY_TIMEOUT), + }; + let body = match captured { + Captured::Bytes(body) => body, + Captured::Streaming(body) => { + // An oversized/streaming result bypasses cache without truncation. + let stream = body.into_data_stream().map(move |chunk| { + let _ = &permit; + chunk + }); + return Response::from_parts(response_parts, Body::from_stream(stream)); + } + }; + let headers = response_parts + .headers + .iter() + .map(|(name, value)| { + value + .to_str() + .map(|value| (name.to_string(), value.to_owned())) + }) + .collect::, _>>(); + let Ok(headers) = headers else { + return Response::from_parts(response_parts, Body::from(body)); + }; + let snapshot = SnapshotResponse { + status: response_parts.status.as_u16(), + headers, + body: body.to_vec(), + }; + if !snapshot.satisfies(&admission, freshness.as_ref()) { + return Response::from_parts(response_parts, Body::from(body)); + } + // Recheck the actual fill's vector and authorization after result SQL. + // A delayed fill cannot install behind a newer primary commit, even if + // the invalidation feed was delayed, dropped or never connected. + match validate(binding, inner, executor, &context, &parts, &value).await { + AdmissionResult::Eligible(current) => { + if let Ok(mut cache) = self.snapshots.lock() { + if cache + .install(ticket, current, snapshot, super::now()) + .is_err() + { + return response(StatusCode::SERVICE_UNAVAILABLE); + } + } + } + AdmissionResult::Error(error) => return error, + AdmissionResult::Bypass => {} + } + Response::from_parts(response_parts, Body::from(body)) + } +} + +enum AdmissionResult { + Eligible(OriginAdmission), + Bypass, + Error(Response), +} +async fn validate( + binding: &GraphqlBinding, + inner: &NativeInner, + executor: &GraphqlExecutor, + context: &RequestContext, + parts: &Parts, + value: &serde_json::Value, +) -> AdmissionResult { + let mut validation = value.clone(); + mark(&mut validation, "validate"); + let pending = binding.execute_http( + inner, + executor, + context.clone(), + request(parts, validation), + None, + ); + let result = + match tokio::time::timeout(inner.options.limits.response_header_timeout, pending).await { + Ok(result) => result, + Err(_) => return AdmissionResult::Error(response(StatusCode::GATEWAY_TIMEOUT)), + }; + let (parts, body) = result.into_parts(); + let body = match tokio::time::timeout( + inner.options.limits.read_timeout, + axum::body::to_bytes(body, 65536), + ) + .await + { + Ok(Ok(body)) => body, + Ok(Err(_)) => return AdmissionResult::Error(response(StatusCode::BAD_GATEWAY)), + Err(_) => return AdmissionResult::Error(response(StatusCode::GATEWAY_TIMEOUT)), + }; + if parts.status != StatusCode::OK { + return AdmissionResult::Error(Response::from_parts(parts, Body::from(body))); + } + let parsed: serde_json::Value = match serde_json::from_slice(&body) { + Ok(value) => value, + Err(_) => return AdmissionResult::Error(response(StatusCode::BAD_GATEWAY)), + }; + if parsed + .get("errors") + .is_some_and(|e| e.as_array().is_none_or(|e| !e.is_empty())) + { + return AdmissionResult::Error(Response::from_parts(parts, Body::from(body))); + } + let delivery = &parsed["extensions"]["gatewayDelivery"]; + if delivery["eligible"] != true { + return AdmissionResult::Bypass; + } + // Cookie-bearing validation is never a reusable authorization grant. + if parts.headers.contains_key(header::SET_COOKIE) { + return AdmissionResult::Bypass; + } + let admission: OriginAdmission = match serde_json::from_value(delivery["admission"].clone()) { + Ok(value) => value, + Err(_) => return AdmissionResult::Error(response(StatusCode::BAD_GATEWAY)), + }; + if admission.bind(value, super::now()).is_err() { + return AdmissionResult::Error(response(StatusCode::SERVICE_UNAVAILABLE)); + } + AdmissionResult::Eligible(admission) +} +fn mark(value: &mut serde_json::Value, action: &str) { + if !value["extensions"].is_object() { + value["extensions"] = serde_json::json!({}); + } + value["extensions"]["gatewayDelivery"] = serde_json::json!({"action":action}); +} +fn request(parts: &Parts, value: serde_json::Value) -> Request { + let mut request = Request::new(Body::from(value.to_string())); + *request.method_mut() = parts.method.clone(); + *request.uri_mut() = parts.uri.clone(); + *request.version_mut() = parts.version; + *request.headers_mut() = parts.headers.clone(); + *request.extensions_mut() = parts.extensions.clone(); + request.headers_mut().remove(header::CONTENT_LENGTH); + request.headers_mut().insert( + header::CONTENT_TYPE, + axum::http::HeaderValue::from_static("application/json"), + ); + request +} +fn cached_response(snapshot: SnapshotResponse) -> Response { + let mut result = snapshot.body.into_response(); + *result.status_mut() = StatusCode::from_u16(snapshot.status).expect("validated status"); + result.headers_mut().clear(); + for (name, value) in snapshot.headers { + if let (Ok(name), Ok(value)) = ( + name.parse::(), + value.parse::(), + ) { + result.headers_mut().append(name, value); + } + } + result +} +enum Captured { + Bytes(Bytes), + Streaming(Body), +} +async fn capture(body: Body, limit: usize) -> Captured { + let mut stream = body.into_data_stream(); + let mut chunks = Vec::new(); + let mut bytes = 0; + while let Some(chunk) = stream.next().await { + match chunk { + Ok(chunk) => { + bytes += chunk.len(); + chunks.push(Ok(chunk)); + } + Err(error) => { + chunks.push(Err(error)); + return Captured::Streaming(Body::from_stream( + futures_util::stream::iter(chunks).chain(stream), + )); + } + } + if bytes > limit { + return Captured::Streaming(Body::from_stream( + futures_util::stream::iter(chunks).chain(stream), + )); + } + } + let mut result = Vec::with_capacity(bytes); + for chunk in chunks { + result.extend_from_slice(&chunk.expect("successful captured chunks")); + } + Captured::Bytes(result.into()) +} diff --git a/src/gateway/native/graphql.rs b/src/gateway/native/graphql.rs index a3114b5bd..6b387ac9e 100644 --- a/src/gateway/native/graphql.rs +++ b/src/gateway/native/graphql.rs @@ -286,7 +286,43 @@ impl GraphqlBinding { if let Err(error) = admit_request(&value, *capabilities) { return error_response(error); } - let mut request = Request::from_parts(parts, Body::from(body)); + #[cfg(feature = "gateway-delivery")] + if let Some(coordinator) = parts + .extensions + .get::>() + .cloned() + { + if super::super::graphql::operation_kind( + value["query"].as_str().unwrap_or(""), + value["operationName"].as_str(), + ) == Ok(super::super::graphql::OperationKind::Query) + && value["extensions"].get("gatewayDelivery").is_none() + { + return coordinator + .execute(self, inner, executor, context, parts, value, permit) + .await; + } + } + self.execute_http( + inner, + executor, + context, + Request::from_parts(parts, Body::from(body)), + Some(permit), + ) + .await + } + + pub(super) async fn execute_http( + &self, + inner: &NativeInner, + executor: &GraphqlExecutor, + context: RequestContext, + mut request: Request, + permit: Option, + ) -> Response { + // Internal control/result calls share the outer admitted capacity slot. + // Plain remote streaming responses retain their own permit in the body. match (self, executor) { (Self::Embedded(embedded), _) => { if proxy::prepare_headers(request.headers_mut(), inner, &context, false).is_err() { diff --git a/src/gateway/native/mod.rs b/src/gateway/native/mod.rs index 35676cf29..af7956e23 100644 --- a/src/gateway/native/mod.rs +++ b/src/gateway/native/mod.rs @@ -118,6 +118,9 @@ pub enum NativeBinding { /// Embedded or complete remote GraphQL executor. #[cfg(feature = "gateway-graphql-native")] Graphql(GraphqlBinding), + /// GraphQL with an explicitly allocated bounded delivery coordinator. + #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] + GraphqlWithDelivery(GraphqlBinding, Arc), /// Configured UI proxy. Upgrades are disabled unless explicitly selected. UiProxy { /// Whether this target may negotiate a WebSocket upgrade. @@ -206,6 +209,29 @@ impl NativeGateway { )?; compatible = true; } + #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] + if let ( + BindingKind::Graphql { + executor, + capabilities, + delivery, + schema_extensions, + }, + NativeBinding::GraphqlWithDelivery(binding, coordinator), + ) = (&declaration.kind, &binding) + { + if *delivery != coordinator.capabilities() { + return Err(GatewayError("delivery resource does not match declaration")); + } + binding.validate( + executor, + *capabilities, + super::DeliveryCapabilities::default(), + schema_extensions, + &origin, + )?; + compatible = true; + } if !compatible { return Err(GatewayError("incompatible native binding")); } @@ -399,6 +425,13 @@ impl GatewayAdapter for NativeGateway { .execute(&self.0, &selected.binding().kind, context, request) .await } + #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] + NativeBinding::GraphqlWithDelivery(binding, coordinator) => { + request.extensions_mut().insert(Arc::clone(coordinator)); + binding + .execute(&self.0, &selected.binding().kind, context, request) + .await + } NativeBinding::Assets(assets) => assets.serve(request), NativeBinding::Admission(_) => response(StatusCode::SERVICE_UNAVAILABLE), } @@ -419,3 +452,8 @@ impl GatewayAdapter for NativeGateway { } } } + +#[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] +mod delivery; +#[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] +pub use delivery::NativeDelivery; diff --git a/src/gateway/native/proxy.rs b/src/gateway/native/proxy.rs index 07f2d0266..64e9a50f9 100644 --- a/src/gateway/native/proxy.rs +++ b/src/gateway/native/proxy.rs @@ -86,7 +86,15 @@ pub(super) async fn forward( Ok(permit) => permit, Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), }; - forward_with_permit(inner, origin, allow_websocket, context, request, permit).await + forward_with_permit( + inner, + origin, + allow_websocket, + context, + request, + Some(permit), + ) + .await } pub(super) async fn forward_with_permit( @@ -95,7 +103,7 @@ pub(super) async fn forward_with_permit( allow_websocket: bool, context: RequestContext, mut request: Request, - permit: tokio::sync::OwnedSemaphorePermit, + permit: Option, ) -> Response { if request .headers() diff --git a/src/graphql/delivery/mod.rs b/src/graphql/delivery/mod.rs new file mode 100644 index 000000000..56478823c --- /dev/null +++ b/src/graphql/delivery/mod.rs @@ -0,0 +1,39 @@ +//! Origin-side delivery validation. SQL dependency versions are private; +//! gateway responses carry only scope-bound opaque validators. +mod versions; +pub(crate) use versions::*; +pub use versions::{GatewayOriginMetrics, GatewayVersionStore}; + +use crate::gateway::delivery::{OperationKey, OriginIdentity}; +use crate::graphql::protocol::{ProtocolTokenCodec, ProtocolTokenPurpose}; + +#[derive(Clone, Debug)] +pub(crate) struct GatewayCapture { + pub(crate) identity: OriginIdentity, + pub(crate) key: OperationKey, + pub(crate) validator: Option, +} + +pub(crate) fn validator( + codec: &ProtocolTokenCodec, + identity: &OriginIdentity, + key: &OperationKey, + versions: &VersionVector, +) -> Result { + codec + .issue( + ProtocolTokenPurpose::QuerySnapshot, + &serde_json::json!({ + "domain":"distributed.gateway.snapshot-validator", "version":1, + "identity":identity, "operation":key, "versions":versions + }), + ) + .map(|token| token.as_str().to_owned()) + .map_err(|_| "validator encoding failed".into()) +} + +#[derive(Clone, Default)] +pub(crate) struct PlanCapture( + pub(crate) std::sync::Arc>>, +); +pub(crate) const CAPTURED: &str = "gateway query plan captured"; diff --git a/src/graphql/delivery/versions.rs b/src/graphql/delivery/versions.rs new file mode 100644 index 000000000..b101937b1 --- /dev/null +++ b/src/graphql/delivery/versions.rs @@ -0,0 +1,535 @@ +use crate::graphql::engine::GraphqlPool; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, +}; + +const MAX_TABLES: usize = 128; +// The cached envelope includes projection evidence as well as model data. +// Version all persisted evidence dependencies, including no-op/empty commits. +const PROOF_TABLES: &[&str] = &[ + "projection_partitions", + "projection_generations", + "projection_source_capabilities", + "projection_input_identities", + "projection_input_cursors", + "projection_input_receipts", + "projection_table_ownership_fences", + "projection_causal_tables", + "projection_registered_models", + "projection_model_ownership", + "projection_records", + "projection_observations", + "projection_failures", + "projection_changes", +]; + +/// Installed transactional dependency coverage for one origin database. Create +/// after application migrations, before enabling gateway caching. Every covered +/// table receives write triggers; unsupported/uncovered tables remain ineligible. +#[derive(Clone)] +pub struct GatewayVersionStore { + namespace: Arc, + tables: Arc>, + counters: Arc, + proof_tables: Arc>, + public_policies: BTreeMap<(String, Option), u64>, +} +#[derive(Default)] +struct Counters { + validations: AtomicU64, + result_executions: AtomicU64, +} +/// Origin work counters; result executions exclude dependency validation SQL. +#[derive(Clone, Copy, Debug)] +pub struct GatewayOriginMetrics { + /// Authenticated validation requests reaching the configured origin store. + pub validations: u64, + /// Actual compiled result SQL executions using the protocol snapshot path. + pub result_executions: u64, +} +#[derive(Clone, Debug, Serialize)] +pub(crate) struct DependencyVersion { + epoch: String, + version: String, +} +pub(crate) type VersionVector = BTreeMap; + +impl GatewayVersionStore { + /// Explicitly permit bounded content age for one exact ordinary operation + /// (all its variable values). Subject isolation and fresh origin admission + /// still apply. Omit this declaration for current/private reads. + pub fn public_snapshot( + mut self, + document: impl Into, + operation: Option, + max_age_seconds: u64, + ) -> Result { + let document = document.into(); + if self.public_policies.len() >= 512 + || !(1..=86400).contains(&max_age_seconds) + || crate::gateway::graphql::operation_kind(&document, operation.as_deref()) + != Ok(crate::gateway::graphql::OperationKind::Query) + { + return Err("invalid public snapshot policy".into()); + } + self.public_policies + .insert((document, operation), max_age_seconds); + Ok(self) + } + pub(crate) fn policy( + &self, + document: &str, + operation: Option<&str>, + ) -> crate::gateway::delivery::SnapshotPolicy { + self.public_policies + .get(&(document.to_owned(), operation.map(str::to_owned))) + .map_or( + crate::gateway::delivery::SnapshotPolicy::Current, + |seconds| crate::gateway::delivery::SnapshotPolicy::Public { + max_age_seconds: *seconds, + }, + ) + } + /// Snapshot origin work counters without resetting concurrent observations. + pub fn metrics(&self) -> GatewayOriginMetrics { + GatewayOriginMetrics { + validations: self.counters.validations.load(Ordering::Relaxed), + result_executions: self.counters.result_executions.load(Ordering::Relaxed), + } + } + pub(crate) fn record_validation(&self) { + self.counters.validations.fetch_add(1, Ordering::Relaxed); + } + pub(crate) fn record_result(&self) { + self.counters + .result_executions + .fetch_add(1, Ordering::Relaxed); + } + + /// Install additive version metadata and triggers in one transaction. Data + /// migration/cleanup is never implicit. Namespace is a configured app ID. + pub async fn install( + pool: &GraphqlPool, + namespace: &str, + tables: impl IntoIterator, + ) -> Result { + let tables: BTreeSet<_> = tables.into_iter().collect(); + if namespace.is_empty() + || namespace.len() > 128 + || tables.is_empty() + || tables.len() > MAX_TABLES + || tables + .iter() + .any(|t| t.is_empty() || t.len() > 128 || t.chars().any(char::is_control)) + { + return Err("invalid dependency version inventory".into()); + } + let epoch = uuid::Uuid::now_v7().to_string(); + let mut store = Self { + namespace: namespace.into(), + tables: Arc::new(tables), + counters: Arc::default(), + proof_tables: Arc::default(), + public_policies: BTreeMap::new(), + }; + match pool { + #[cfg(feature = "sqlite")] + GraphqlPool::Sqlite(pool) => { + let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + let existing: Vec = + sqlx::query_scalar("SELECT name FROM sqlite_master WHERE type='table'") + .fetch_all(&mut *tx) + .await + .map_err(|e| e.to_string())?; + store.proof_tables = Arc::new( + existing + .into_iter() + .filter(|table| PROOF_TABLES.contains(&table.as_str())) + .collect(), + ); + for sql in store.install_sql(&epoch, false) { + sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(&mut *tx) + .await + .map_err(|e| e.to_string())?; + } + tx.commit().await.map_err(|e| e.to_string())?; + } + #[cfg(feature = "postgres")] + GraphqlPool::Postgres(pool) => { + let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + super::super::execute::ensure_primary_backend(&mut tx, true).await?; + let existing: Vec = sqlx::query_scalar( + "SELECT tablename::text FROM pg_tables WHERE schemaname=current_schema()", + ) + .fetch_all(&mut *tx) + .await + .map_err(|e| e.to_string())?; + store.proof_tables = Arc::new( + existing + .into_iter() + .filter(|table| PROOF_TABLES.contains(&table.as_str())) + .collect(), + ); + for sql in store.install_sql(&epoch, true) { + sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(&mut *tx) + .await + .map_err(|e| e.to_string())?; + } + tx.commit().await.map_err(|e| e.to_string())?; + } + #[allow(unreachable_patterns)] + _ => return Err("dependency versions require a SQL adapter".into()), + } + Ok(store) + } + fn install_sql(&self, epoch: &str, postgres: bool) -> Vec { + let mut sql = + vec![ + include_str!("../../../migrations/postgres/0006_gateway_dependency_versions.sql") + .to_owned(), + ]; + for table in self.tables.union(&self.proof_tables) { + let ns = literal(&self.namespace); + let table_literal = literal(table); + let name = self.trigger_name(table); + sql.push(format!("INSERT INTO distributed_gateway_versions(namespace, table_name, epoch, version) VALUES ({ns},{table_literal},{},0) ON CONFLICT(namespace,table_name) DO UPDATE SET epoch=excluded.epoch,version=0",literal(epoch))); + let update = format!("UPDATE distributed_gateway_versions SET version=version+1 WHERE namespace={ns} AND table_name={table_literal};"); + if postgres { + sql.push(format!( + "CREATE OR REPLACE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS {}", + ident(&name), + literal(&format!("BEGIN {update} RETURN NULL; END")) + )); + sql.push(format!( + "DROP TRIGGER IF EXISTS {} ON {}", + ident(&name), + ident(table) + )); + sql.push(format!("CREATE TRIGGER {} AFTER INSERT OR UPDATE OR DELETE OR TRUNCATE ON {} FOR EACH STATEMENT EXECUTE FUNCTION {}()",ident(&name),ident(table),ident(&name))); + } else { + for event in ["INSERT", "UPDATE", "DELETE"] { + sql.push(format!( + "CREATE TRIGGER IF NOT EXISTS {} AFTER {event} ON {} BEGIN {update} END", + ident(&format!("{name}_{event}")), + ident(table) + )); + } + } + } + sql + } + fn trigger_name(&self, table: &str) -> String { + let digest = + Sha256::digest(format!("gateway-version-v1:{}:{table}", self.namespace).as_bytes()); + format!("dg_v_{digest:x}")[..55].into() + } + pub(crate) fn envelope_coverage(&self) -> bool { + self.proof_tables.len() == PROOF_TABLES.len() + } + pub(crate) fn covers(&self, tables: &[String]) -> bool { + !tables.is_empty() + && tables.len() <= MAX_TABLES + && tables.iter().all(|t| self.tables.contains(t)) + } + /// Read current validators on the authoritative primary only. Result fills + /// use the connection methods inside their data snapshot instead. + pub(crate) async fn current( + &self, + pool: &GraphqlPool, + tables: &[String], + ) -> Result { + match pool { + #[cfg(feature = "sqlite")] + GraphqlPool::Sqlite(pool) => { + let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + let result = self.sqlite(&mut tx, tables).await?; + tx.commit().await.map_err(|e| e.to_string())?; + Ok(result) + } + #[cfg(feature = "postgres")] + GraphqlPool::Postgres(pool) => { + let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY") + .execute(&mut *tx) + .await + .map_err(|e| e.to_string())?; + super::super::execute::ensure_primary_backend(&mut tx, true).await?; + let result = self.postgres(&mut tx, tables).await?; + tx.commit().await.map_err(|e| e.to_string())?; + Ok(result) + } + #[allow(unreachable_patterns)] + _ => Err("dependency versions require a SQL adapter".into()), + } + } + /// Activate a new explicit epoch after a rebuild or writer-coverage change. + /// Call in a controlled migration window; old validators become unusable. + pub async fn rotate_epoch(&self, pool: &GraphqlPool) -> Result<(), String> { + let epoch = uuid::Uuid::now_v7().to_string(); + let sql = format!( + "UPDATE distributed_gateway_versions SET epoch={},version=0 WHERE namespace={}", + literal(&epoch), + literal(&self.namespace) + ); + match pool { + #[cfg(feature = "sqlite")] + GraphqlPool::Sqlite(pool) => { + sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(pool) + .await + .map_err(|e| e.to_string())?; + } + #[cfg(feature = "postgres")] + GraphqlPool::Postgres(pool) => { + sqlx::query(sqlx::AssertSqlSafe(sql)) + .execute(pool) + .await + .map_err(|e| e.to_string())?; + } + #[allow(unreachable_patterns)] + _ => return Err("dependency versions require a SQL adapter".into()), + } + Ok(()) + } +} + +// SQLx database implementations keep trigger coverage checks and version reads +// in the caller's actual serving snapshot. Missing/disabled hooks fail closed. +macro_rules! version_reader { + ($method:ident, $connection:ty, $coverage:expr) => { + impl GatewayVersionStore { + pub(crate) async fn $method(&self, connection: &mut $connection, tables: &[String]) -> Result { + if !self.covers(tables) { return Err("query dependency coverage is incomplete".into()); } + let selected: BTreeSet<_> = tables.iter().chain(self.proof_tables.iter()).collect(); + let queries = selected.iter().map(|table| { + let coverage_sql: String = ($coverage)(self, table); + format!("SELECT table_name, epoch, version, ({coverage_sql}) AS covered FROM distributed_gateway_versions WHERE namespace={} AND table_name={}",literal(&self.namespace),literal(table)) + }).collect::>().join(" UNION ALL "); + let rows: Vec<(String,String,i64,i64)> = sqlx::query_as(sqlx::AssertSqlSafe(queries)).fetch_all(&mut *connection).await.map_err(|e| e.to_string())?; + if rows.len() != selected.len() { return Err("dependency version coverage is unavailable".into()); } + let mut result = BTreeMap::new(); + for (table, epoch, version, covered) in rows { + if covered != 1 || version < 0 { return Err("dependency invalidation coverage is unavailable".into()); } + result.insert(table, DependencyVersion { epoch, version: version.to_string() }); + } + Ok(result) + } + } + } +} +#[cfg(feature = "sqlite")] +version_reader!( + sqlite, + sqlx::SqliteConnection, + |store: &GatewayVersionStore, table: &str| { + let name = store.trigger_name(table); + format!("SELECT CASE WHEN COUNT(*)=3 THEN 1 ELSE 0 END FROM sqlite_master WHERE type='trigger' AND tbl_name={} AND name IN ({},{},{})",literal(table),literal(&format!("{name}_INSERT")),literal(&format!("{name}_UPDATE")),literal(&format!("{name}_DELETE"))) + } +); +#[cfg(feature = "postgres")] +version_reader!( + postgres, + sqlx::PgConnection, + |store: &GatewayVersionStore, table: &str| { + format!("SELECT COUNT(*)::bigint FROM pg_trigger WHERE tgrelid={}::regclass AND tgname={} AND tgenabled IN ('O','A')",literal(&ident(table)),literal(&store.trigger_name(table))) + } +); +fn literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} +fn ident(value: &str) -> String { + format!("\"{}\"", value.replace('"', "\"\"")) +} + +#[cfg(test)] +mod tests { + use super::*; + // The same behavioral matrix runs against both actual SQL adapters. It + // includes a concurrent data/version snapshot and supported external SQL. + macro_rules! exercise { + ($pool:ident, $adapter:ident, $method:ident, $begin:expr) => {{ + sqlx::query( + "CREATE TABLE gateway_version_test (id INTEGER PRIMARY KEY, title TEXT NOT NULL)", + ) + .execute(&$pool) + .await + .unwrap(); + let adapter = GraphqlPool::$adapter($pool.clone()); + let tables = vec!["gateway_version_test".to_owned()]; + let store = GatewayVersionStore::install(&adapter, "version-test", tables.clone()) + .await + .unwrap(); + let vector = |v: VersionVector| serde_json::to_value(v).unwrap(); + let empty = vector(store.current(&adapter, &tables).await.unwrap()); + sqlx::query("INSERT INTO gateway_version_test VALUES (1,'first')") + .execute(&$pool) + .await + .unwrap(); + let inserted = vector(store.current(&adapter, &tables).await.unwrap()); + assert_ne!( + inserted, empty, + "insert into an empty result invalidates membership" + ); + let mut failed = $pool.begin().await.unwrap(); + sqlx::query("UPDATE gateway_version_test SET title='rollback'") + .execute(&mut *failed) + .await + .unwrap(); + failed.rollback().await.unwrap(); + assert_eq!( + vector(store.current(&adapter, &tables).await.unwrap()), + inserted + ); + let mut serving = $pool.begin().await.unwrap(); + if let Some(begin) = $begin { + sqlx::query(sqlx::AssertSqlSafe(begin)) + .execute(&mut *serving) + .await + .unwrap(); + } + let data: String = + sqlx::query_scalar("SELECT title FROM gateway_version_test WHERE id=1") + .fetch_one(&mut *serving) + .await + .unwrap(); + assert_eq!(data, "first"); + sqlx::query("UPDATE gateway_version_test SET title='newer'") + .execute(&$pool) + .await + .unwrap(); + assert_eq!( + vector(store.$method(&mut serving, &tables).await.unwrap()), + inserted, + "an old result must carry its own old validator, even after concurrent commit" + ); + serving.commit().await.unwrap(); + let updated = vector(store.current(&adapter, &tables).await.unwrap()); + assert_ne!(updated, inserted); + sqlx::query("DELETE FROM gateway_version_test WHERE id=1") + .execute(&$pool) + .await + .unwrap(); + assert_ne!( + vector(store.current(&adapter, &tables).await.unwrap()), + updated + ); + assert!(store + .current(&adapter, &["unknown_dependency".into()]) + .await + .is_err()); + (adapter, store, tables) + }}; + } + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn sqlite_transactional_coverage_and_snapshot_race() { + use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; + let directory = + std::env::temp_dir().join(format!("gateway-cache-{}", uuid::Uuid::now_v7())); + std::fs::create_dir(&directory).unwrap(); + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(directory.clone()); + let pool = SqlitePoolOptions::new() + .max_connections(3) + .connect_with( + SqliteConnectOptions::new() + .filename(directory.join("cache.sqlite")) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal), + ) + .await + .unwrap(); + let (adapter, store, tables) = exercise!(pool, Sqlite, sqlite, None::); + let name = store.trigger_name(&tables[0]); + sqlx::query(sqlx::AssertSqlSafe(format!( + "DROP TRIGGER {}", + ident(&format!("{name}_UPDATE")) + ))) + .execute(&pool) + .await + .unwrap(); + assert!( + store.current(&adapter, &tables).await.is_err(), + "missing hook disables validation" + ); + sqlx::query("INSERT INTO gateway_version_test VALUES (2,'during missing coverage')") + .execute(&pool) + .await + .unwrap(); + let restored = GatewayVersionStore::install(&adapter, "version-test", tables.clone()) + .await + .unwrap(); + let before = + serde_json::to_value(restored.current(&adapter, &tables).await.unwrap()).unwrap(); + restored.rotate_epoch(&adapter).await.unwrap(); + assert_ne!( + serde_json::to_value(restored.current(&adapter, &tables).await.unwrap()).unwrap(), + before + ); + } + #[cfg(feature = "postgres")] + #[tokio::test] + async fn postgres_transactional_coverage_and_snapshot_race() { + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(3) + .connect( + &std::env::var("GATEWAY_TEST_PRIMARY_URL").expect("run gateway-postgres fixture"), + ) + .await + .unwrap(); + let (adapter, store, tables) = exercise!( + pool, + Postgres, + postgres, + Some("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY".to_owned()) + ); + let name = store.trigger_name(&tables[0]); + let before = serde_json::to_value(store.current(&adapter, &tables).await.unwrap()).unwrap(); + sqlx::query("TRUNCATE gateway_version_test") + .execute(&pool) + .await + .unwrap(); + assert_ne!( + serde_json::to_value(store.current(&adapter, &tables).await.unwrap()).unwrap(), + before + ); + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE gateway_version_test DISABLE TRIGGER {}", + ident(&name) + ))) + .execute(&pool) + .await + .unwrap(); + assert!( + store.current(&adapter, &tables).await.is_err(), + "disabled hooks cannot certify current data" + ); + let restored = GatewayVersionStore::install(&adapter, "version-test", tables.clone()) + .await + .unwrap(); + assert_ne!( + serde_json::to_value(restored.current(&adapter, &tables).await.unwrap()).unwrap(), + before + ); + let before = + serde_json::to_value(restored.current(&adapter, &tables).await.unwrap()).unwrap(); + restored.rotate_epoch(&adapter).await.unwrap(); + assert_ne!( + serde_json::to_value(restored.current(&adapter, &tables).await.unwrap()).unwrap(), + before + ); + } +} diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 628bd9269..4ccc46b86 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -12,6 +12,8 @@ impl GraphqlEngineBuilder { pool: source.pool, #[cfg(feature = "gateway-delivery")] read_routing: None, + #[cfg(feature = "gateway-delivery")] + gateway_versions: None, catalog: BTreeMap::new(), by_table: BTreeMap::new(), permissions: BTreeMap::new(), @@ -59,6 +61,17 @@ impl GraphqlEngineBuilder { self } + /// Enable origin dependency validation after installing version coverage + /// in the engine's database. This allocates no gateway cache or coordinator. + #[cfg(feature = "gateway-delivery")] + pub fn gateway_versions( + mut self, + store: crate::graphql::delivery::GatewayVersionStore, + ) -> Self { + self.gateway_versions = Some(store); + self + } + pub fn model(mut self, perms: ModelPermissions) -> Self { let schema = M::schema().clone(); if let Err(e) = self.insert_catalog(schema.clone(), true) { @@ -1027,6 +1040,8 @@ impl GraphqlEngineBuilder { pool: self.pool, #[cfg(feature = "gateway-delivery")] read_routing: self.read_routing, + #[cfg(feature = "gateway-delivery")] + gateway_versions: self.gateway_versions, catalog: self.catalog, by_table: self.by_table, permissions: self.permissions, diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index 524747687..b453f60ad 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -233,6 +233,8 @@ pub(crate) struct EngineInner { pub pool: GraphqlPool, #[cfg(feature = "gateway-delivery")] pub read_routing: Option, + #[cfg(feature = "gateway-delivery")] + pub gateway_versions: Option, pub catalog: BTreeMap, pub by_table: BTreeMap, pub permissions: BTreeMap<(String, String), RoleModelPerm>, @@ -298,6 +300,8 @@ pub struct GraphqlEngineBuilder { pub(crate) pool: GraphqlPool, #[cfg(feature = "gateway-delivery")] pub(crate) read_routing: Option, + #[cfg(feature = "gateway-delivery")] + pub(crate) gateway_versions: Option, pub(crate) catalog: BTreeMap, pub(crate) by_table: BTreeMap, pub(crate) permissions: BTreeMap<(String, String), RoleModelPerm>, diff --git a/src/graphql/engine/delivery.rs b/src/graphql/engine/delivery.rs new file mode 100644 index 000000000..63607f028 --- /dev/null +++ b/src/graphql/engine/delivery.rs @@ -0,0 +1,158 @@ +use super::*; +use crate::gateway::{ + delivery::{OperationKey, OriginAdmission}, + graphql::{operation_kind, OperationKind}, +}; +use crate::graphql::delivery::{self, GatewayCapture, PlanCapture}; + +pub(crate) fn request_value(request: &Request) -> serde_json::Value { + serde_json::json!({"query": request.query, "operationName":request.operation_name, "variables":request.variables, "extensions":request.extensions}) +} +pub(crate) fn action(request: &Request) -> Option { + request + .extensions + .get("gatewayDelivery") + .and_then(|value| serde_json::to_value(value).ok()) + .and_then(|value| value["action"].as_str().map(str::to_owned)) +} +fn unavailable() -> Response { + let mut error = ServerError::new("origin delivery validation unavailable", None); + let mut extensions = async_graphql::ErrorExtensionValues::default(); + extensions.set("code", "DELIVERY_UNAVAILABLE"); + error.extensions = Some(extensions); + Response::from_errors(vec![error]) +} +fn ineligible() -> Response { + Response::new(Value::Null).extension( + "gatewayDelivery", + Value::from_json(serde_json::json!({"eligible":false})).expect("static JSON"), + ) +} +impl GraphqlEngine { + pub(super) fn enable_delivery_capture( + &self, + session: &Session, + request: &Request, + accumulator: &ProtocolResponseAccumulator, + ) -> Result<(), ()> { + if action(request).as_deref() != Some("snapshot") + || self + .inner + .gateway_versions + .as_ref() + .is_none_or(|store| !store.envelope_coverage()) + { + return Ok(()); + } + if operation_kind(&request.query, request.operation_name.as_deref()) + != Ok(OperationKind::Query) + { + return Err(()); + } + let identity = self.delivery_identity(session, request).map_err(|_| ())?; + let key = OperationKey::from_origin(&identity, &request_value(request)).map_err(|_| ())?; + accumulator + .enable_gateway(GatewayCapture { + identity, + key, + validator: None, + }) + .map_err(|_| ()) + } + pub(super) async fn validate_delivery(&self, session: &Session, request: Request) -> Response { + if operation_kind(&request.query, request.operation_name.as_deref()) + != Ok(OperationKind::Query) + { + return ineligible(); + } + let Some(store) = &self.inner.gateway_versions else { + return ineligible(); + }; + store.record_validation(); + let Some(runtime) = &self.inner.protocol else { + return ineligible(); + }; + let identity = match self.delivery_identity(session, &request) { + Ok(identity) => identity, + Err(_) => return ineligible(), + }; + let key = match OperationKey::from_origin(&identity, &request_value(&request)) { + Ok(key) => key, + Err(_) => return ineligible(), + }; + if self.prepare_read(session, &request).is_err() { + return unavailable(); + } + let authority = match resolve_execution_authority(&self.inner, session, &request) { + Ok(authority) => authority, + Err(_) => return ineligible(), + }; + let Some(schema) = self.inner.schemas.get(&authority.privilege_role) else { + return ineligible(); + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |value| value.as_secs()); + let expiry = request + .data + .get(&TypeId::of::()) + .and_then(|p| p.downcast_ref::()) + .and_then(VerifiedPrincipal::expires_at) + .unwrap_or(now.saturating_add(30)); + if expiry <= now { + return unavailable(); + } + let operation = operation_fingerprint(&request.query); + let policy = store.policy(&request.query, request.operation_name.as_deref()); + let captured = PlanCapture::default(); + let response = schema + .execute( + request + .data(session.clone()) + .data(authority) + .data(Arc::clone(&self.inner)) + .data(captured.clone()), + ) + .await; + // Schema validation and normal compiler authorization still run. Only + // the private capture sentinel may replace SQL; unknown/custom fields, + // cell reads and multi-root documents never acquire cache eligibility. + if response.errors.len() != 1 || response.errors[0].message != delivery::CAPTURED { + return ineligible(); + } + let plan = match captured.0.lock() { + Ok(mut plans) if plans.len() == 1 => plans.pop().expect("captured plan"), + _ => return ineligible(), + }; + if !store.covers(&plan.tables_touched) { + return ineligible(); + } + let versions = match store.current(&self.inner.pool, &plan.tables_touched).await { + Ok(versions) => versions, + Err(error) + if error.starts_with("dependency ") || error.starts_with("query dependency ") => + { + return ineligible() + } + Err(_) => return unavailable(), + }; + let validator = match delivery::validator(&runtime.codec, &identity, &key, &versions) { + Ok(validator) => validator, + Err(_) => return unavailable(), + }; + let admission = OriginAdmission { + identity, + key, + operation, + validator, + validated_at: now, + expires_at: expiry, + policy, + }; + Response::new(Value::Null).extension( + "gatewayDelivery", + Value::from_json(serde_json::json!({"eligible":true,"admission":admission})) + .expect("serializable admission"), + ) + } +} diff --git a/src/graphql/engine/mod.rs b/src/graphql/engine/mod.rs index 599c2604a..24d2b6c5f 100644 --- a/src/graphql/engine/mod.rs +++ b/src/graphql/engine/mod.rs @@ -107,3 +107,6 @@ pub fn core_sdl_for_catalog(tables: &[TableSchema]) -> Result { pub(crate) mod read_routing; #[cfg(feature = "gateway-delivery")] pub use read_routing::ReadRouting; + +#[cfg(feature = "gateway-delivery")] +mod delivery; diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index f02f8473f..af9f34f0b 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -29,6 +29,10 @@ impl ProtocolPreparationError { impl GraphqlEngine { pub async fn execute(&self, session: &Session, mut request: Request) -> Response { + #[cfg(feature = "gateway-delivery")] + if delivery::action(&request).as_deref() == Some("validate") { + return self.validate_delivery(session, request).await; + } if selected_operation_type(&mut request) == Some(async_graphql::parser::types::OperationType::Mutation) && !crate::microsvc::lifecycle_mutations_open() @@ -68,6 +72,15 @@ impl GraphqlEngine { Ok(accumulator) => accumulator, Err(error) => return error.into_response(), }; + #[cfg(feature = "gateway-delivery")] + if let Some(accumulator) = &accumulator { + if self + .enable_delivery_capture(session, &request, accumulator) + .is_err() + { + return protocol_internal_error_response(); + } + } if introspection { // The relaxed schema is defense-in-depth restricted even if a // future classifier or request extension behaves unexpectedly. diff --git a/src/graphql/identity/oidc.rs b/src/graphql/identity/oidc.rs index 284567a2e..54a2bb02a 100644 --- a/src/graphql/identity/oidc.rs +++ b/src/graphql/identity/oidc.rs @@ -123,6 +123,7 @@ pub struct VerifiedPrincipal { subject: String, audiences: Vec, tenant_partitions: Vec<(String, Value)>, + expires_at: Option, } impl VerifiedPrincipal { @@ -162,6 +163,7 @@ impl VerifiedPrincipal { }) .collect(), tenant_partitions: Vec::new(), + expires_at: None, } } @@ -175,6 +177,12 @@ impl VerifiedPrincipal { &self.subject } + /// Credential expiry used to bound admitted delivery work. Trusted local + /// principals without an expiring credential return None. + pub fn expires_at(&self) -> Option { + self.expires_at + } + pub(crate) fn subject_matches(&self, subject: &str) -> bool { self.subject == subject } @@ -736,6 +744,7 @@ fn verified_principal( subject, audiences, tenant_partitions, + expires_at: claims.get("exp").and_then(Value::as_u64), }) } diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index ce9e727a4..46565a410 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -92,3 +92,6 @@ pub use subscribe::ChangeHub; #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] pub use engine::ReadRouting; + +#[cfg(all(feature = "graphql", feature = "gateway-delivery"))] +pub mod delivery; diff --git a/src/graphql/protocol/accumulator.rs b/src/graphql/protocol/accumulator.rs index b41a70301..d258f9a3e 100644 --- a/src/graphql/protocol/accumulator.rs +++ b/src/graphql/protocol/accumulator.rs @@ -95,6 +95,8 @@ struct ProtocolResponseState { stream_frames: Mutex>>, dispatch_claimed: Mutex, codec: ProtocolTokenCodec, + #[cfg(feature = "gateway-delivery")] + gateway: Mutex>, } impl ProtocolResponseAccumulator { @@ -108,6 +110,8 @@ impl ProtocolResponseAccumulator { stream_frames: Mutex::new(None), dispatch_claimed: Mutex::new(false), codec, + #[cfg(feature = "gateway-delivery")] + gateway: Mutex::new(None), }), } } @@ -974,6 +978,43 @@ impl ProtocolResponseAccumulator { .map_err(|_| ProtocolAccumulatorError::Poisoned) } + #[cfg(feature = "gateway-delivery")] + pub(crate) fn enable_gateway( + &self, + capture: crate::graphql::delivery::GatewayCapture, + ) -> Result<(), ProtocolAccumulatorError> { + *self + .inner + .gateway + .lock() + .map_err(|_| ProtocolAccumulatorError::Poisoned)? = Some(capture); + Ok(()) + } + #[cfg(feature = "gateway-delivery")] + pub(crate) fn gateway_enabled(&self) -> bool { + self.inner.gateway.lock().is_ok_and(|state| state.is_some()) + } + #[cfg(feature = "gateway-delivery")] + pub(crate) fn record_gateway_versions( + &self, + versions: &crate::graphql::delivery::VersionVector, + ) -> Result<(), String> { + let mut state = self + .inner + .gateway + .lock() + .map_err(|_| "gateway capture unavailable")?; + if let Some(state) = state.as_mut() { + state.validator = Some(crate::graphql::delivery::validator( + &self.inner.codec, + &state.identity, + &state.key, + versions, + )?); + } + Ok(()) + } + pub(crate) fn attach(&self, response: &mut Response) -> Result<(), ProtocolAccumulatorError> { if response.extensions.contains_key("distributed") { return Err(ProtocolAccumulatorError::ExtensionCollision); @@ -998,6 +1039,21 @@ impl ProtocolResponseAccumulator { serde_json::to_value(envelope).map_err(|_| ProtocolAccumulatorError::Encoding)?; let value = Value::from_json(json).map_err(|_| ProtocolAccumulatorError::Encoding)?; response.extensions.insert("distributed".into(), value); + #[cfg(feature = "gateway-delivery")] + if response.errors.is_empty() { + let state = self + .inner + .gateway + .lock() + .map_err(|_| ProtocolAccumulatorError::Poisoned)?; + if let Some(validator) = state.as_ref().and_then(|state| state.validator.as_ref()) { + response.extensions.insert( + "gatewayDelivery".into(), + Value::from_json(serde_json::json!({"validator":validator})) + .map_err(|_| ProtocolAccumulatorError::Encoding)?, + ); + } + } Ok(()) } } diff --git a/src/graphql/query_protocol.rs b/src/graphql/query_protocol.rs index 945ed8031..1ca252fd3 100644 --- a/src/graphql/query_protocol.rs +++ b/src/graphql/query_protocol.rs @@ -14,7 +14,6 @@ use sqlx::{Encode, Executor, IntoArguments, Type}; use super::compile::{ExtractedQueryEvidence, QueryResponsePathSegment, SqlPlan}; use super::engine::EngineInner; -#[cfg(any(feature = "sqlite", feature = "postgres"))] use super::engine::GraphqlPool; #[cfg(any(feature = "sqlite", feature = "postgres"))] use super::execute; @@ -572,6 +571,8 @@ pub(crate) async fn execute_query_with_protocol( let plan = plan.clone(); let runtime = inner.query_protocol.clone(); let statement_timeout = inner.statement_timeout; + #[cfg(feature = "gateway-delivery")] + let gateway_versions = inner.gateway_versions.clone(); match pool { #[cfg(feature = "sqlite")] GraphqlPool::Sqlite(pool) => { @@ -581,11 +582,17 @@ pub(crate) async fn execute_query_with_protocol( let plan = plan.clone(); let runtime = runtime.clone(); let live_resume = live_resume.clone(); + #[cfg(feature = "gateway-delivery")] + let gateway_versions = gateway_versions.clone(); Box::pin(async move { + #[cfg(feature = "gateway-delivery")] + if let Some(store) = &gateway_versions { + store.record_result(); + } let executed = execute::execute_sqlite_in_connection(connection, &plan) .await .map_err(query_execution_error)?; - finish_protocol_query::( + let result = finish_protocol_query::( connection, &runtime, &role_surface, @@ -594,7 +601,22 @@ pub(crate) async fn execute_query_with_protocol( executed, live_resume, ) - .await + .await?; + #[cfg(feature = "gateway-delivery")] + if accumulator.gateway_enabled() { + if let Some(store) = &gateway_versions { + if store.covers(&plan.tables_touched) { + let versions = store + .sqlite(connection, &plan.tables_touched) + .await + .map_err(query_execution_error)?; + accumulator + .record_gateway_versions(&versions) + .map_err(query_execution_error)?; + } + } + } + Ok(result) }) }); execute::apply_statement_timeout(statement_timeout, async { @@ -610,6 +632,8 @@ pub(crate) async fn execute_query_with_protocol( let plan = plan.clone(); let runtime = runtime.clone(); let live_resume = live_resume.clone(); + #[cfg(feature = "gateway-delivery")] + let gateway_versions = gateway_versions.clone(); Box::pin(async move { let timeout_ms = i64::try_from(statement_timeout.as_millis()).unwrap_or(i64::MAX); @@ -624,10 +648,14 @@ pub(crate) async fn execute_query_with_protocol( execute::ensure_primary_backend(connection, primary) .await .map_err(query_execution_error)?; + #[cfg(feature = "gateway-delivery")] + if let Some(store) = &gateway_versions { + store.record_result(); + } let executed = execute::execute_postgres_in_connection(connection, &plan) .await .map_err(query_execution_error)?; - finish_protocol_query::( + let result = finish_protocol_query::( connection, &runtime, &role_surface, @@ -636,7 +664,22 @@ pub(crate) async fn execute_query_with_protocol( executed, live_resume, ) - .await + .await?; + #[cfg(feature = "gateway-delivery")] + if accumulator.gateway_enabled() { + if let Some(store) = &gateway_versions { + if store.covers(&plan.tables_touched) { + let versions = store + .postgres(connection, &plan.tables_touched) + .await + .map_err(query_execution_error)?; + accumulator + .record_gateway_versions(&versions) + .map_err(query_execution_error)?; + } + } + } + Ok(result) }) }); execute::apply_statement_timeout(statement_timeout, async { @@ -652,6 +695,8 @@ pub(crate) async fn execute_query_with_protocol( #[cfg(not(any(feature = "sqlite", feature = "postgres")))] pub(crate) async fn execute_query_with_protocol( _inner: &EngineInner, + _pool: &GraphqlPool, + _primary: bool, _role_surface: Arc, _accumulator: ProtocolResponseAccumulator, _plan: &SqlPlan, diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 579c37ccc..680765448 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -756,6 +756,20 @@ async fn resolve_root( let selection = compile::selection_from_field(ctx.field()); let plan = compile::compile_query(&inner, &session, &role, model, kind, &selection) .map_err(|e| client_error("BAD_REQUEST", sanitize_compile_error(&e)))?; + #[cfg(feature = "gateway-delivery")] + if let Some(captured) = ctx.data_opt::() { + if let QueryPlan::Sql(plan) = plan { + let mut plans = captured + .0 + .lock() + .map_err(|_| client_error("INTERNAL", "plan capture unavailable"))?; + plans.push(plan); + return Err(async_graphql::Error::new(super::delivery::CAPTURED)); + } + return Err(async_graphql::Error::new( + "query is ineligible for delivery reuse", + )); + } let value = match plan { QueryPlan::CellByKey { model, diff --git a/src/sqlx_repo/projection_protocol/tests.rs b/src/sqlx_repo/projection_protocol/tests.rs index a445b192f..53b908b49 100644 --- a/src/sqlx_repo/projection_protocol/tests.rs +++ b/src/sqlx_repo/projection_protocol/tests.rs @@ -2815,6 +2815,14 @@ mod tests { #[tokio::test] async fn sqlite_direct_projection_and_ledger_replay_commit_atomically() { let repository = repository().await; + #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] + let (cache_store, cache_pool, cache_tables, cache_before) = { + let pool = crate::graphql::GraphqlPool::Sqlite(repository.pool().clone()); + let tables = vec!["sql_todo_views".to_owned()]; + let store = crate::graphql::delivery::GatewayVersionStore::install(&pool, "atomic-cache-test", tables.clone()).await.unwrap(); + let before = serde_json::to_value(store.current(&pool, &tables).await.unwrap()).unwrap(); + (store, pool, tables, before) + }; let command_id = uuid::Uuid::now_v7().hyphenated().to_string(); let key = CommandLedgerKey::new( "projection-runtime-test", @@ -2864,6 +2872,12 @@ mod tests { .await .unwrap(); + #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] + let cache_committed = { + let committed = serde_json::to_value(cache_store.current(&cache_pool, &cache_tables).await.unwrap()).unwrap(); + assert_ne!(committed, cache_before, "Atomic result and cache dependency versions commit together"); + committed + }; let metadata = repository .projection_record(&record_scope()) .await @@ -2958,6 +2972,9 @@ mod tests { .unwrap(), CommandLookup::InProgress { .. } )); + #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] + assert_eq!(serde_json::to_value(cache_store.current(&cache_pool, &cache_tables).await.unwrap()).unwrap(), cache_committed, + "failed Atomic ledger completion must roll back cache versions too"); sqlx::query("DROP TRIGGER fail_direct_ledger_completion") .execute(repository.pool()) .await diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs index 183f4cfb2..fb51df856 100644 --- a/tests/edge_query_delivery.rs +++ b/tests/edge_query_delivery.rs @@ -153,3 +153,138 @@ fn invalid_context_never_weakens_routing() { ReadTarget::Primary ); } + +fn admission(validator: &str) -> OriginAdmission { + let identity = identity("alice"); + OriginAdmission { + key: OperationKey::from_origin(&identity, &json!({"query":"{ todos { title } }"})).unwrap(), + identity, + operation: "document-fingerprint".into(), + validator: validator.into(), + validated_at: 100, + expires_at: 200, + policy: SnapshotPolicy::Current, + } +} +fn snapshot(admission: &OriginAdmission) -> SnapshotResponse { + SnapshotResponse { status: 200, headers: vec![("content-type".into(), "application/json".into())], body: serde_json::to_vec(&json!({ + "data":{"todos":[]}, "extensions": { + "gatewayDelivery":{"validator":admission.validator}, + "distributed": {"protocolVersion":1,"schemaHash":admission.identity.schema_hash, + "authorizationGeneration":admission.identity.authorization_generation,"cacheScope":admission.identity.cache_scope, + "operation":admission.operation,"snapshot":{"recordsComplete":true,"indexesComparable":true,"records":[], + "indexes":[{"projection":"todos","scopeToken":"scope","position":"2"}]}} + } + })).unwrap() } +} +#[test] +fn private_validation_public_age_and_late_fill_fence() { + let mut cache = SnapshotCache::new(SnapshotLimits::default()).unwrap(); + let first = admission("v1"); + let body = snapshot(&first); + let ticket = cache.begin_fill(&first, 100).unwrap(); + assert!(cache + .install(ticket, first.clone(), body.clone(), 100) + .unwrap()); + assert_eq!( + cache.lookup(&first, None, 101).unwrap().unwrap().body, + body.body + ); + let newer = admission("v2"); + assert!(cache.lookup(&newer, None, 101).unwrap().is_none()); + let ticket = cache.begin_fill(&first, 100).unwrap(); + assert!( + !cache + .install(ticket, newer.clone(), body.clone(), 101) + .unwrap(), + "old bytes cannot acquire new version" + ); + let late = cache.begin_fill(&first, 100).unwrap(); + cache.invalidate_all(); + assert!(!cache + .install(late, first.clone(), body.clone(), 101) + .unwrap()); + assert!(cache.is_empty()); + let mut public = first.clone(); + public.policy = SnapshotPolicy::Public { + max_age_seconds: 10, + }; + let ticket = cache.begin_fill(&public, 100).unwrap(); + assert!(cache + .install(ticket, public.clone(), body.clone(), 100) + .unwrap()); + let mut current = public.clone(); + current.validator = "v2".into(); + current.validated_at = 108; + assert!(cache.lookup(¤t, None, 108).unwrap().is_some()); + current.validated_at = 111; + assert!( + cache.lookup(¤t, None, 111).unwrap().is_none(), + "fresh admission cannot renew old public age" + ); + assert!( + cache.lookup(¤t, None, 200).is_err(), + "expired consumer cannot reuse public entry" + ); + current.policy = SnapshotPolicy::Current; + assert!(cache.lookup(¤t, None, 112).unwrap().is_none()); +} +#[test] +fn cache_envelope_eligibility_freshness_and_capacity() { + let admission = admission("v1"); + let valid = snapshot(&admission); + let mut floor = context(); + floor.observe([index("scope", "3")]).unwrap(); + assert!(!valid.satisfies(&admission, Some(&floor))); + let mut floor = context(); + floor.observe([index("scope", "2")]).unwrap(); + assert!(valid.satisfies(&admission, Some(&floor))); + for (name, value) in [ + ("Set-Cookie", "session=secret"), + ("Cache-Control", "private, no-store"), + ("Vary", "*"), + ] { + let mut response = valid.clone(); + response.headers.push((name.into(), value.into())); + assert!(!response.satisfies(&admission, None)); + } + for path in ["errors", "partial", "command", "protocol", "null"] { + let mut response = valid.clone(); + let mut value: serde_json::Value = serde_json::from_slice(&response.body).unwrap(); + match path { + "errors" => value["errors"] = json!([{"message":"denied"}]), + "partial" => { + value["extensions"]["distributed"]["snapshot"]["recordsComplete"] = false.into() + } + "command" => value["extensions"]["distributed"]["command"] = json!({}), + "protocol" => value["extensions"]["distributed"]["protocolVersion"] = 2.into(), + _ => value["data"] = serde_json::Value::Null, + } + response.body = serde_json::to_vec(&value).unwrap(); + assert!(!response.satisfies(&admission, None), "{path}"); + } + let mut cache = SnapshotCache::new(SnapshotLimits { + entries: 1, + bytes: 4096, + entry_bytes: 2048, + }) + .unwrap(); + let ticket = cache.begin_fill(&admission, 100).unwrap(); + assert!(cache + .install(ticket, admission.clone(), valid.clone(), 100) + .unwrap()); + let mut other = admission.clone(); + other.identity.cache_scope = "bob".into(); + other.key = OperationKey::from_origin(&other.identity, &json!({"query":"{ todos { title } }"})) + .unwrap(); + let ticket = cache.begin_fill(&other, 100).unwrap(); + assert!(cache + .install(ticket, other.clone(), snapshot(&other), 100) + .unwrap()); + assert_eq!(cache.len(), 1); + assert!(cache.lookup(&admission, None, 100).unwrap().is_none()); + let mut oversized = snapshot(&other); + oversized.body.resize(4096, b' '); + let ticket = cache.begin_fill(&other, 100).unwrap(); + assert!(!cache.install(ticket, other, oversized, 100).unwrap()); +} diff --git a/tests/gateway-postgres/run.py b/tests/gateway-postgres/run.py index 4de64df10..7a025a73e 100644 --- a/tests/gateway-postgres/run.py +++ b/tests/gateway-postgres/run.py @@ -65,6 +65,8 @@ class Server(socketserver.ThreadingTCPServer): print("Fixture PostgreSQL " + docker("exec", primary, "postgres", "--version"), flush=True) env = {**os.environ, "GATEWAY_TEST_PRIMARY_URL": url(primary), "GATEWAY_TEST_REPLICA_URL": url(standby), "GATEWAY_TEST_PRIMARY_CONTAINER": primary} subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--nocapture"], cwd=ROOT, env=env, check=True) + subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--lib", "graphql::delivery::versions::tests", "--", "--nocapture"], cwd=ROOT, env=env, check=True) + subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "postgres_repository", "projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks", "--", "--nocapture"], cwd=ROOT, env={**env, "DATABASE_URL": env["GATEWAY_TEST_PRIMARY_URL"]}, check=True) finally: for bridge in bridges: bridge.shutdown(); bridge.server_close() diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 2234d7d97..1e9bdd375 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -1589,3 +1589,317 @@ async fn freshness_context_binds_origin_and_rejects_unproven_minima() { "FRESHNESS_SCOPE_CHANGED" ); } + +#[cfg(feature = "gateway-delivery")] +#[tokio::test] +async fn gateway_validator_tracks_projection_commit_in_the_result_snapshot() { + use distributed::graphql::delivery::GatewayVersionStore; + let fixture = protocol_fixture_with_retention(10).await; + let pool = distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()); + let store = + GatewayVersionStore::install(&pool, "query-protocol-cache", ["causal_query_views".into()]) + .await + .unwrap(); + let engine = GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .anonymous_role("user") + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .gateway_versions(store.clone()) + .build() + .unwrap(); + let request = |action: &str| { + let mut request = Request::new("query CachedRows { causal_query_views { title } }"); + request.extensions.insert( + "gatewayDelivery".into(), + async_graphql::Value::from_json(json!({"action":action})).unwrap(), + ); + request + }; + let validate = wire_response(engine.execute(&user_session(), request("validate")).await); + assert_eq!( + validate["extensions"]["gatewayDelivery"]["eligible"], true, + "{validate}" + ); + let validator = validate["extensions"]["gatewayDelivery"]["admission"]["validator"].clone(); + let first = wire_response(engine.execute(&user_session(), request("snapshot")).await); + assert_eq!( + first["extensions"]["gatewayDelivery"]["validator"], validator, + "{first}" + ); + assert_eq!( + first["data"]["causal_query_views"][0]["title"], + "causal row" + ); + project_item(&fixture.repository, &fixture.bus, 2, "changed").await; + let validate = wire_response(engine.execute(&user_session(), request("validate")).await); + assert_ne!( + validate["extensions"]["gatewayDelivery"]["admission"]["validator"], + validator + ); + let second = wire_response(engine.execute(&user_session(), request("snapshot")).await); + assert_eq!( + second["extensions"]["gatewayDelivery"]["validator"], + validate["extensions"]["gatewayDelivery"]["admission"]["validator"] + ); + assert_eq!(second["data"]["causal_query_views"][0]["title"], "changed"); + assert_eq!( + distributed_envelope(&second)["snapshot"]["indexes"][0]["position"], + "2" + ); + store.rotate_epoch(&pool).await.unwrap(); + let next_epoch = wire_response(engine.execute(&user_session(), request("validate")).await); + assert_ne!( + next_epoch["extensions"]["gatewayDelivery"]["admission"]["validator"], + second["extensions"]["gatewayDelivery"]["validator"] + ); + // A failed write transaction cannot advance the cache dependency version. + let mut tx = fixture.repository.pool().begin().await.unwrap(); + sqlx::query("UPDATE causal_query_views SET title='rolled back'") + .execute(&mut *tx) + .await + .unwrap(); + tx.rollback().await.unwrap(); + let rolled_back = wire_response(engine.execute(&user_session(), request("validate")).await); + assert_eq!( + rolled_back["extensions"]["gatewayDelivery"]["admission"]["validator"], + next_epoch["extensions"]["gatewayDelivery"]["admission"]["validator"] + ); +} + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +#[tokio::test] +async fn native_snapshot_cache_revalidates_each_consumer_without_result_sql() { + use axum::{routing::post, Router}; + use distributed::gateway::{delivery::SnapshotLimits, native::*, *}; + use distributed::graphql::delivery::GatewayVersionStore; + use std::sync::atomic::{AtomicBool, Ordering}; + use tower::ServiceExt; + let fixture = protocol_fixture_with_retention(10).await; + let pool = distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()); + let store = GatewayVersionStore::install(&pool, "native-cache", ["causal_query_views".into()]) + .await + .unwrap(); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .anonymous_role("user") + .subscriptions(false) + .model::( + ModelPermissions::new().grant("user", read().all_columns().aggregations()), + ) + .client_projectors([projector()]) + .gateway_versions(store.clone()) + .build() + .unwrap(), + ); + let revoked = Arc::new(AtomicBool::new(false)); + let origin = { + let engine = engine.clone(); + let revoked = revoked.clone(); + Router::new().route( + "/graphql", + post(move |axum::Json(value): axum::Json| { + let engine = engine.clone(); + let revoked = revoked.clone(); + async move { + if revoked.load(Ordering::SeqCst) { + return ( + axum::http::StatusCode::UNAUTHORIZED, + axum::Json(json!({"error":"denied"})), + ); + } + let request: Request = serde_json::from_value(value).unwrap(); + ( + axum::http::StatusCode::OK, + axum::Json( + serde_json::to_value(engine.execute(&user_session(), request).await) + .unwrap(), + ), + ) + } + }), + ) + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin_url = format!("http://{}", listener.local_addr().unwrap()); + let origin_task = tokio::spawn(async move { axum::serve(listener, origin).await.unwrap() }); + struct Stop(tokio::task::JoinHandle<()>); + impl Drop for Stop { + fn drop(&mut self) { + self.0.abort(); + } + } + let _origin = Stop(origin_task); + for remote in [false, true] { + let caps = GraphqlCapabilities { + queries: true, + ..Default::default() + }; + let executor = if remote { + GraphqlExecutor::Remote { + origin: origin_url.clone(), + } + } else { + GraphqlExecutor::Embedded + }; + let binding = if remote { + GraphqlBinding::Remote(RemoteGraphql { + live_path: None, + ..Default::default() + }) + } else { + GraphqlBinding::Embedded(EmbeddedGraphql::new(engine.clone(), None, caps).unwrap()) + }; + let delivery = Arc::new(NativeDelivery::snapshots(SnapshotLimits::default()).unwrap()); + let config = GatewayConfig { + bindings: vec![Binding::new( + "api", + BindingKind::Graphql { + executor, + capabilities: caps, + delivery: DeliveryCapabilities { + snapshots: true, + ..Default::default() + }, + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "api")], + } + .build() + .unwrap(); + let gateway = NativeGateway::new( + config, + NativeOptions::new("http://public.invalid"), + [( + "api".into(), + NativeBinding::GraphqlWithDelivery(binding, delivery.clone()), + )], + NativeAuth::anonymous(), + ) + .unwrap() + .router(); + let run = |document: &str| { + let gateway = gateway.clone(); + let body = serde_json::to_vec(&json!({"query": document})).unwrap(); + async move { + let response = gateway + .oneshot( + axum::http::Request::post("/graphql") + .header("content-type", "application/json") + .body(axum::body::Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + ( + status, + serde_json::from_slice::(&bytes).unwrap(), + ) + } + }; + let document = "query Cache { causal_query_views { title } }"; + let before = store.metrics(); + let (status, first) = run(document).await; + assert_eq!(status, axum::http::StatusCode::OK); + assert!(first.get("errors").is_none(), "{first}"); + assert!( + first["extensions"]["gatewayDelivery"]["validator"].is_string(), + "{first}" + ); + let filled = store.metrics(); + assert_eq!(filled.result_executions, before.result_executions + 1); + assert_eq!(filled.validations, before.validations + 2); + for _ in 0..5 { + assert_eq!(run(document).await.1, first); + } + let hit = store.metrics(); + assert_eq!( + hit.result_executions, filled.result_executions, + "cache hit ran result SQL" + ); + assert_eq!( + hit.validations, + filled.validations + 5, + "each consumer needs fresh origin admission" + ); + // No invalidation feed is connected: transactional dependency validation + // must still discover a supported external SQL producer's update. + sqlx::query("UPDATE causal_query_views SET title=title || '-external'") + .execute(fixture.repository.pool()) + .await + .unwrap(); + let changed = run(document).await.1; + assert_ne!(changed["data"], first["data"]); + assert_eq!(store.metrics().result_executions, hit.result_executions + 1); + assert_eq!(run(document).await.1, changed); + delivery.invalidate_all(); + assert_eq!(run(document).await.1, changed); + assert_eq!(store.metrics().result_executions, hit.result_executions + 2); + if remote { + revoked.store(true, Ordering::SeqCst); + assert_eq!( + run(document).await.0, + axum::http::StatusCode::UNAUTHORIZED, + "no private stale-on-auth-error" + ); + assert_eq!(store.metrics().result_executions, hit.result_executions + 2); + revoked.store(false, Ordering::SeqCst); + } + // A projection can advance evidence while leaving selected data equal. + let title = changed["data"]["causal_query_views"][0]["title"] + .as_str() + .unwrap(); + project_item( + &fixture.repository, + &fixture.bus, + if remote { 3 } else { 2 }, + title, + ) + .await; + let proof_only = run(document).await.1; + assert_eq!(proof_only["data"], changed["data"]); + assert_ne!( + proof_only["extensions"]["gatewayDelivery"]["validator"], + changed["extensions"]["gatewayDelivery"]["validator"] + ); + let filtered = + "query Filtered { causal_query_views(where: {title: {_eq: \"matching\"}}) { title } }"; + let count = "query Count { causal_query_views_aggregate(where: {title: {_eq: \"matching\"}}) { aggregate { count } } }"; + assert_eq!( + run(filtered).await.1["data"]["causal_query_views"], + json!([]) + ); + let empty_count = run(count).await.1; + assert!(empty_count.get("errors").is_none(), "{empty_count}"); + assert_eq!( + empty_count["data"]["causal_query_views_aggregate"]["aggregate"]["count"], + 0 + ); + let filled = store.metrics(); + run(filtered).await; + run(count).await; + assert_eq!(store.metrics().result_executions, filled.result_executions); + sqlx::query("UPDATE causal_query_views SET title='matching'") + .execute(fixture.repository.pool()) + .await + .unwrap(); + assert_eq!( + run(filtered).await.1["data"]["causal_query_views"][0]["title"], + "matching" + ); + assert_eq!( + run(count).await.1["data"]["causal_query_views_aggregate"]["aggregate"]["count"], + 1 + ); + } +} diff --git a/tests/graphql_sqlite/main.rs b/tests/graphql_sqlite/main.rs index 70da869f2..0df7c68d1 100644 --- a/tests/graphql_sqlite/main.rs +++ b/tests/graphql_sqlite/main.rs @@ -705,3 +705,92 @@ async fn domain_service_shaped_fixture() { assert_eq!(data["users"][0]["name"], "ada"); assert_eq!(data["orders"][0]["name"], "widget"); } + +#[cfg(feature = "gateway-delivery")] +#[tokio::test] +async fn gateway_dependency_inventory_includes_empty_relationship_filters() { + use distributed::graphql::{delivery::GatewayVersionStore, GraphqlPool}; + use serde_json::{json, Value}; + let pool = SqlitePoolOptions::new() + .connect("sqlite::memory:") + .await + .unwrap(); + for sql in [ + "CREATE TABLE m2m_players (player_id TEXT PRIMARY KEY, name TEXT NOT NULL)", + "CREATE TABLE m2m_weapons (weapon_id TEXT PRIMARY KEY, name TEXT NOT NULL)", + "CREATE TABLE m2m_player_weapon_links (player_ref TEXT NOT NULL, weapon_ref TEXT NOT NULL)", + "INSERT INTO m2m_players VALUES ('p1', 'Ada')", + "INSERT INTO m2m_weapons VALUES ('w1', 'Compiler')", + ] { + sqlx::query(sql).execute(&pool).await.unwrap(); + } + let store = GatewayVersionStore::install( + &GraphqlPool::Sqlite(pool.clone()), + "relationship-test", + [ + "m2m_players".into(), + "m2m_weapons".into(), + "m2m_player_weapon_links".into(), + ], + ) + .await + .unwrap(); + let engine = GraphqlEngine::builder(pool.clone()) + .service_id("relationship-test") + .protocol_token_key([17; 32]) + .table_schema(m2m_link_schema()) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .roles(&["user"]) + .gateway_versions(store) + .build() + .unwrap(); + let document = r#"{ m2m_players(where: { weapons: { name: { _eq: "Compiler" } } }) { name } }"#; + let validate = || async { + let mut request = Request::new(document); + request.extensions.insert( + "gatewayDelivery".into(), + async_graphql::Value::from_json(json!({"action":"validate"})).unwrap(), + ); + let response: Value = + serde_json::to_value(engine.execute(&session_role("user", "u1"), request).await) + .unwrap(); + assert_eq!( + response["extensions"]["gatewayDelivery"]["eligible"], true, + "{response}" + ); + response["extensions"]["gatewayDelivery"]["admission"]["validator"].clone() + }; + let empty = validate().await; + sqlx::query("INSERT INTO m2m_player_weapon_links VALUES ('p1','w1')") + .execute(&pool) + .await + .unwrap(); + let linked = validate().await; + assert_ne!(linked, empty); + let rows = engine + .execute(&session_role("user", "u1"), Request::new(document)) + .await; + assert_eq!( + serde_json::to_value(rows.data).unwrap()["m2m_players"], + json!([{"name":"Ada"}]) + ); + sqlx::query("UPDATE m2m_weapons SET name='Debugger'") + .execute(&pool) + .await + .unwrap(); + let changed_target = validate().await; + assert_ne!(changed_target, linked); + sqlx::query("DELETE FROM m2m_player_weapon_links") + .execute(&pool) + .await + .unwrap(); + assert_ne!(validate().await, changed_target); + let response = engine + .execute(&session_role("user", "u1"), Request::new(document)) + .await; + assert_eq!( + serde_json::to_value(response.data).unwrap()["m2m_players"], + json!([]) + ); +} diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index 858dc1314..33bd83f5c 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 5); + assert_eq!(latest_version, 6); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index af0cb0e9d..55e7fd3c9 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 5); + assert_eq!(latest_version, 6); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From 6b2b4e9a1d0792b227decac2a650998bf22d6f9b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 6 Sep 2026 23:02:21 -0500 Subject: [PATCH 055/484] feat(gateway): coalesce admitted concurrent queries with cancellation leases --- .github/workflows/integration-gateway.yaml | 2 + docs/gateway/query-coalescing.md | 42 +++ src/gateway/README.md | 5 + src/gateway/delivery/flight.rs | 193 +++++++++++++ src/gateway/delivery/mod.rs | 3 + src/gateway/delivery/snapshot.rs | 39 ++- src/gateway/native/delivery.rs | 191 ++++++++++--- src/gateway/native/flight.rs | 312 +++++++++++++++++++++ src/gateway/native/graphql.rs | 4 +- src/gateway/native/mod.rs | 5 +- tests/edge_query_delivery.rs | 54 ++++ tests/graphql_query_protocol/main.rs | 198 +++++++++++++ 12 files changed, 999 insertions(+), 49 deletions(-) create mode 100644 docs/gateway/query-coalescing.md create mode 100644 src/gateway/delivery/flight.rs create mode 100644 src/gateway/native/flight.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 570c9e5ae..5c6d5f4eb 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -111,6 +111,8 @@ jobs: - name: Verify embedded and remote GraphQL protocols run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test gateway_graphql --test gateway_graphql_operation --test graphql_causal_transport --test graphql_query_protocol --test graphql_identity --test graphql_sqlite --test sqlite_repository + - name: Verify shared query cancellation, expiry and deadlines + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib gateway::native::flight::tests - name: Verify transactional cache coverage and Atomic rollback run: | cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib graphql::delivery::versions::tests diff --git a/docs/gateway/query-coalescing.md b/docs/gateway/query-coalescing.md new file mode 100644 index 000000000..89138c5a4 --- /dev/null +++ b/docs/gateway/query-coalescing.md @@ -0,0 +1,42 @@ +# Shared concurrent queries + +Mount `NativeDelivery::coalescing(FlightLimits)` with the GraphQL binding's +`coalescing` capability. This creates no snapshot cache. To select both, use +`NativeDelivery::new(NativeDeliveryOptions { snapshots: Some(...), coalescing: +Some(...) })`. All capabilities remain explicit and independently removable. +The origin uses the authenticated delivery control path and version store +described in [snapshot-cache.md](snapshot-cache.md). + +Every consumer authenticates and validates at the origin before joining. A group +key binds the exact origin subject/scope, operation/variables/extensions, current +dependency validator, and exact freshness requirements. Different or stronger +floors conservatively form different groups; no minimum is weakened to improve +sharing. Mutations, status operations and unknown origin eligibility never join. +The result retains its own complete data and protocol envelope. In-flight sharing +can serve an otherwise successful admitted query that lacks future cache eligibility; +any required minima must still be proven by that response. + +An operation owns one shared future. The registry retains a weak reference, and +each consumer holds a cancellation lease. Dropping one lease leaves the other +consumers' work running. Dropping the last lease immediately drops the upstream +future; no detached task remains as a hidden owner. Each response waits for its +consumer's own credential expiry deadline, and expiry is checked again before +delivery. The origin is also revalidated after result execution to detect a +changed scope/policy. A completed group is removed when its consumers finish; +with the cache disabled, a later nonoverlapping query executes normally. + +Default limits are 256 active groups, 1,024 consumers per group, a 30-second +operation deadline, and 1 MiB of complete response bytes per group. Native ingress +capacity also bounds all active requests. A full registry rejects additional +joins without evicting work needed by existing consumers. Expired generation +identities cannot release a newer same-key group. Oversized streams, errors, +cookie-setting and otherwise nonshareable responses go to one consumer; other +consumers execute normally with their own admission and freshness. They are never +stored as successful shared snapshots. + +`NativeDelivery::flight_counts()` exposes active groups/consumers without +identifiers. Origin metrics distinguish result SQL from per-consumer validation. +Portable `FlightKey`, `FlightLimits` and `FlightRegistry` provide the same bounded +identity, generation and refcount contracts for runtime adapters. They contain +no timers, network clients, SQL pools, or detached tasks. The Worker/DO adapter +owns its own runtime scheduling and cancellation. diff --git a/src/gateway/README.md b/src/gateway/README.md index ae253ac42..058ec24a1 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -112,3 +112,8 @@ resource (`gateway-graphql-native,gateway-delivery`). Origin-side `GatewayVersionStore` supplies transactional data/proof dependency versions; every hit authenticates and validates at the primary without result SQL. See [activation, limits, public-age policy and rollback](../../docs/gateway/snapshot-cache.md). + +Concurrent queries can share a bounded execution independently of caching via +`NativeDelivery::coalescing(FlightLimits)`. Each consumer still authenticates; +last-consumer cancellation drops the upstream future. See +[query coalescing](../../docs/gateway/query-coalescing.md). diff --git a/src/gateway/delivery/flight.rs b/src/gateway/delivery/flight.rs new file mode 100644 index 000000000..3c742f7d9 --- /dev/null +++ b/src/gateway/delivery/flight.rs @@ -0,0 +1,193 @@ +use super::{canonical_json, DeliveryError, FreshnessContext, OriginAdmission}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// Exact admitted operation, dependency version and freshness requirement. +/// Conservative equality prevents stronger late consumers joining older work. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct FlightKey(String); +impl FlightKey { + /// Authenticate at the origin before constructing a flight identity. + pub fn admitted( + admission: &OriginAdmission, + request: &serde_json::Value, + freshness: Option<&FreshnessContext>, + now: u64, + ) -> Result { + admission.bind(request, now)?; + if crate::gateway::graphql::operation_kind( + request["query"].as_str().ok_or(DeliveryError::Ineligible)?, + request["operationName"].as_str(), + ) != Ok(crate::gateway::graphql::OperationKind::Query) + { + return Err(DeliveryError::Ineligible); + } + if let Some(context) = freshness { + context.bind(&admission.identity)?; + } + let bytes = canonical_json(&serde_json::json!([ + "query-flight-v1", + admission.key, + admission.validator, + freshness + ]))?; + Ok(Self(format!("{:x}", Sha256::digest(bytes)))) + } +} +/// Explicit coordinator bounds, independent of snapshot cache activation. +#[derive(Clone, Copy, Debug)] +pub struct FlightLimits { + /// Maximum simultaneously active exact-scope groups. + pub groups: usize, + /// Maximum admitted consumers in one group. + pub consumers: usize, + /// Maximum operation duration in milliseconds. + pub deadline_ms: u64, + /// Maximum complete response bytes retained by one group. + pub response_bytes: usize, +} +impl Default for FlightLimits { + fn default() -> Self { + Self { + groups: 256, + consumers: 1024, + deadline_ms: 30000, + response_bytes: 1024 * 1024, + } + } +} +impl FlightLimits { + /// Validate resource bounds before allocating runtime coordination. + pub fn validate(&self) -> Result<(), DeliveryError> { + if self.groups == 0 + || self.groups > 4096 + || self.consumers == 0 + || self.consumers > 65536 + || self.deadline_ms == 0 + || self.deadline_ms > 300000 + || self.response_bytes == 0 + || self.response_bytes > 16 * 1024 * 1024 + { + Err(DeliveryError::InvalidContext) + } else { + Ok(()) + } + } +} +/// Adapter-owned consumer ticket. Release exactly once when that consumer +/// finishes/cancels. Stale tickets cannot release a newer same-key generation. +#[derive(Debug)] +pub struct FlightTicket { + key: FlightKey, + generation: u64, +} +impl FlightTicket { + /// Flight generation used to bind a runtime future to portable bookkeeping. + pub fn generation(&self) -> u64 { + self.generation + } +} +struct Group { + generation: u64, + consumers: usize, + deadline: u64, +} +/// Portable bounded refcount/deadline bookkeeping. Runtime futures, clocks, +/// sockets and cancellation guards belong to native/Worker adapters. +pub struct FlightRegistry { + limits: FlightLimits, + groups: BTreeMap, + next: u64, +} +impl FlightRegistry { + /// Allocate empty bookkeeping only when query coalescing is selected. + pub fn new(limits: FlightLimits) -> Result { + limits.validate()?; + Ok(Self { + limits, + groups: BTreeMap::new(), + next: 0, + }) + } + /// Join/create; the boolean identifies the one upstream execution owner. + /// `now_ms` is the adapter's monotonic clock, not a causal data clock. + pub fn join( + &mut self, + key: FlightKey, + now_ms: u64, + ) -> Result<(FlightTicket, bool), DeliveryError> { + self.expire(now_ms); + if let Some(group) = self.groups.get_mut(&key) { + if group.consumers >= self.limits.consumers { + return Err(DeliveryError::Unavailable); + } + group.consumers += 1; + return Ok(( + FlightTicket { + key, + generation: group.generation, + }, + false, + )); + } + if self.groups.len() >= self.limits.groups { + return Err(DeliveryError::Unavailable); + } + self.next = self.next.checked_add(1).ok_or(DeliveryError::Unavailable)?; + self.groups.insert( + key.clone(), + Group { + generation: self.next, + consumers: 1, + deadline: now_ms.saturating_add(self.limits.deadline_ms), + }, + ); + Ok(( + FlightTicket { + key, + generation: self.next, + }, + true, + )) + } + /// Release one consumer; true means the last consumer left that generation. + pub fn leave(&mut self, ticket: FlightTicket) -> bool { + let Some(group) = self.groups.get_mut(&ticket.key) else { + return false; + }; + if group.generation != ticket.generation { + return false; + } + group.consumers -= 1; + if group.consumers == 0 { + self.groups.remove(&ticket.key); + true + } else { + false + } + } + /// Forget expired groups; adapters enforce matching upstream deadlines. + pub fn expire(&mut self, now_ms: u64) { + self.groups.retain(|_, group| group.deadline > now_ms); + } + /// Active group count. + pub fn len(&self) -> usize { + self.groups.len() + } + /// Whether no group has an admitted consumer. + pub fn is_empty(&self) -> bool { + self.groups.is_empty() + } + /// Total current admitted consumers. + pub fn consumers(&self) -> usize { + self.groups.values().map(|group| group.consumers).sum() + } + /// Check whether a runtime future still belongs to an active generation. + pub fn contains_generation(&self, generation: u64) -> bool { + self.groups + .values() + .any(|group| group.generation == generation) + } +} diff --git a/src/gateway/delivery/mod.rs b/src/gateway/delivery/mod.rs index c8f589ad3..fb4510e15 100644 --- a/src/gateway/delivery/mod.rs +++ b/src/gateway/delivery/mod.rs @@ -28,3 +28,6 @@ impl std::error::Error for DeliveryError {} mod snapshot; pub use snapshot::*; + +mod flight; +pub use flight::*; diff --git a/src/gateway/delivery/snapshot.rs b/src/gateway/delivery/snapshot.rs index 5f4026c97..29d3c47c0 100644 --- a/src/gateway/delivery/snapshot.rs +++ b/src/gateway/delivery/snapshot.rs @@ -107,7 +107,7 @@ pub struct SnapshotResponse { pub body: Vec, } impl SnapshotResponse { - fn evidence(&self, admission: &OriginAdmission) -> Option> { + fn evidence(&self, admission: &OriginAdmission, complete: bool) -> Option> { if self.status != 200 || self.headers.iter().any(|(name, value)| { name.eq_ignore_ascii_case("set-cookie") @@ -143,11 +143,23 @@ impl SnapshotResponse { return None; } let snapshot = &protocol["snapshot"]; - if snapshot["recordsComplete"] != true || snapshot["indexesComparable"] != true { + if complete + && (snapshot["recordsComplete"] != true || snapshot["indexesComparable"] != true) + { + return None; + } + if complete + && (snapshot["records"].as_array().is_none() + || snapshot["indexes"].as_array().is_none()) + { return None; } let mut evidence = Vec::new(); - for record in snapshot["records"].as_array()? { + for record in snapshot["records"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]) + { let minimum = Minimum::Record { model: record["model"].as_str()?.into(), scope_token: record["scopeToken"].as_str()?.into(), @@ -157,7 +169,11 @@ impl SnapshotResponse { minimum.validate().ok()?; evidence.push(minimum); } - for index in snapshot["indexes"].as_array()? { + for index in snapshot["indexes"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]) + { let minimum = Minimum::Index { projection: index["projection"].as_str()?.into(), scope_token: index["scopeToken"].as_str()?.into(), @@ -168,13 +184,26 @@ impl SnapshotResponse { } Some(evidence) } + /// Complete admitted HTTP result may be shared in flight without requiring + /// future cache eligibility. Any supplied minima still require actual proof. + pub fn shareable( + &self, + admission: &OriginAdmission, + freshness: Option<&FreshnessContext>, + ) -> bool { + self.evidence(admission, false).is_some_and(|evidence| { + freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + }) + }) + } /// Candidate proof covers every required floor in the admitted scope. pub fn satisfies( &self, admission: &OriginAdmission, freshness: Option<&FreshnessContext>, ) -> bool { - self.evidence(admission).is_some_and(|evidence| { + self.evidence(admission, true).is_some_and(|evidence| { freshness.is_none_or(|context| { context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) }) diff --git a/src/gateway/native/delivery.rs b/src/gateway/native/delivery.rs index f69724c89..fca7ebdae 100644 --- a/src/gateway/native/delivery.rs +++ b/src/gateway/native/delivery.rs @@ -9,45 +9,100 @@ use axum::{ response::IntoResponse, }; use futures_util::StreamExt; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use tokio::sync::OwnedSemaphorePermit; -/// Bounded native coordinator. Snapshot storage is allocated only when this -/// explicit resource is mounted; every lookup first visits authenticated origin -/// validation. Query-flight and live-sharing mounts remain independent. +/// Independently selected native delivery capabilities. None allocates nothing. +#[derive(Default)] +pub struct NativeDeliveryOptions { + /// Optional complete snapshot storage. + pub snapshots: Option, + /// Optional concurrent query execution coordination. + pub coalescing: Option, +} +/// Bounded native delivery. Each consumer authenticates at the origin before +/// lookup/join; snapshot storage and shared query execution are independent. pub struct NativeDelivery { - snapshots: Mutex, + snapshots: Option>, + flights: Option>, entry_bytes: usize, } +struct Fill { + binding: GraphqlBinding, + inner: Arc, + executor: GraphqlExecutor, + context: RequestContext, + parts: Parts, + value: serde_json::Value, + admission: OriginAdmission, + freshness: Option, + ticket: Option, +} impl NativeDelivery { + /// Allocate only the explicitly selected capabilities and their bounds. + pub fn new(options: NativeDeliveryOptions) -> Result { + if options.snapshots.is_none() && options.coalescing.is_none() { + return Err(GatewayError("no delivery capability selected")); + } + let entry_bytes = options + .coalescing + .map(|limits| limits.response_bytes) + .or(options.snapshots.map(|limits| limits.entry_bytes)) + .expect("selected delivery"); + Ok(Self { + snapshots: options + .snapshots + .map(SnapshotCache::new) + .transpose() + .map_err(|_| GatewayError("invalid snapshot limits"))? + .map(Mutex::new), + flights: options + .coalescing + .map(super::flight::NativeFlights::new) + .transpose()?, + entry_bytes, + }) + } /// Allocate a bounded origin-validated snapshot cache. pub fn snapshots(limits: SnapshotLimits) -> Result { - let snapshots = - SnapshotCache::new(limits).map_err(|_| GatewayError("invalid snapshot limits"))?; - Ok(Self { - snapshots: Mutex::new(snapshots), - entry_bytes: limits.entry_bytes, + Self::new(NativeDeliveryOptions { + snapshots: Some(limits), + coalescing: None, + }) + } + /// Allocate bounded query coalescing without snapshot storage. + pub fn coalescing(limits: FlightLimits) -> Result { + Self::new(NativeDeliveryOptions { + snapshots: None, + coalescing: Some(limits), }) } pub(super) fn capabilities(&self) -> DeliveryCapabilities { DeliveryCapabilities { - snapshots: true, - coalescing: false, + snapshots: self.snapshots.is_some(), + coalescing: self.flights.is_some(), live_sharing: false, } } - /// Invalidate on a known lost feed, rebuild or coordinator reset. Private - /// lookups still validate at primary even without a pushed invalidation. + /// Current active query groups and admitted consumers, without identifiers. + pub fn flight_counts(&self) -> (usize, usize) { + self.flights + .as_ref() + .map_or((0, 0), |flights| flights.counts()) + } + /// Lost-feed/rebuild reset fences fills; primary hit validation still applies. pub fn invalidate_all(&self) { - if let Ok(mut cache) = self.snapshots.lock() { - cache.invalidate_all(); + if let Some(cache) = &self.snapshots { + if let Ok(mut cache) = cache.lock() { + cache.invalidate_all(); + } } } #[allow(clippy::too_many_arguments)] pub(super) async fn execute( - &self, + self: &Arc, binding: &GraphqlBinding, - inner: &NativeInner, + inner: &Arc, executor: &GraphqlExecutor, context: RequestContext, parts: Parts, @@ -76,8 +131,8 @@ impl NativeDelivery { } AdmissionResult::Error(error) => return error, }; - let ticket = { - let Ok(mut cache) = self.snapshots.lock() else { + let ticket = if let Some(cache) = &self.snapshots { + let Ok(mut cache) = cache.lock() else { return response(StatusCode::SERVICE_UNAVAILABLE); }; match cache.lookup(&admission, freshness.as_ref(), super::now()) { @@ -86,16 +141,72 @@ impl NativeDelivery { Ok(None) => {} } match cache.begin_fill(&admission, super::now()) { - Ok(ticket) => ticket, + Ok(ticket) => Some(ticket), Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), } + } else { + None + }; + let fill = Fill { + binding: binding.clone(), + inner: inner.clone(), + executor: executor.clone(), + context: context.clone(), + parts: request(&parts, value.clone()).into_parts().0, + value: value.clone(), + admission: admission.clone(), + freshness: freshness.clone(), + ticket, + }; + let result = if let Some(flights) = &self.flights { + let key = + match FlightKey::admitted(&admission, &value, freshness.as_ref(), super::now()) { + Ok(key) => key, + Err(_) => return response(StatusCode::BAD_REQUEST), + }; + let owner = self.clone(); + match flights + .execute(key, admission, freshness, move || async move { + owner.fill(fill).await + }) + .await + { + Some(result) => result, + None => { + return binding + .execute_http( + inner, + executor, + context, + request(&parts, value), + Some(permit), + ) + .await + } + } + } else { + self.fill(fill).await }; + super::flight::with_permit(result, permit) + } + async fn fill(&self, fill: Fill) -> Response { + let Fill { + binding, + inner, + executor, + context, + parts, + value, + admission, + freshness, + ticket, + } = fill; let mut execution = value.clone(); mark(&mut execution, "snapshot"); let result = binding .execute_http( - inner, - executor, + &inner, + &executor, context.clone(), request(&parts, execution), None, @@ -113,14 +224,7 @@ impl NativeDelivery { }; let body = match captured { Captured::Bytes(body) => body, - Captured::Streaming(body) => { - // An oversized/streaming result bypasses cache without truncation. - let stream = body.into_data_stream().map(move |chunk| { - let _ = &permit; - chunk - }); - return Response::from_parts(response_parts, Body::from_stream(stream)); - } + Captured::Streaming(body) => return Response::from_parts(response_parts, body), }; let headers = response_parts .headers @@ -139,15 +243,20 @@ impl NativeDelivery { headers, body: body.to_vec(), }; - if !snapshot.satisfies(&admission, freshness.as_ref()) { + if !snapshot.shareable(&admission, freshness.as_ref()) { return Response::from_parts(response_parts, Body::from(body)); } - // Recheck the actual fill's vector and authorization after result SQL. - // A delayed fill cannot install behind a newer primary commit, even if - // the invalidation feed was delayed, dropped or never connected. - match validate(binding, inner, executor, &context, &parts, &value).await { + // Scope/policy can change while result work is running. Authenticate + // after the result too, including when only coalescing is selected. + match validate(&binding, &inner, &executor, &context, &parts, &value).await { AdmissionResult::Eligible(current) => { - if let Ok(mut cache) = self.snapshots.lock() { + if current.identity != admission.identity || current.key != admission.key { + return response(StatusCode::CONFLICT); + } + if let (Some(ticket), Some(cache)) = (ticket, &self.snapshots) { + let Ok(mut cache) = cache.lock() else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; if cache .install(ticket, current, snapshot, super::now()) .is_err() @@ -170,7 +279,7 @@ enum AdmissionResult { } async fn validate( binding: &GraphqlBinding, - inner: &NativeInner, + inner: &std::sync::Arc, executor: &GraphqlExecutor, context: &RequestContext, parts: &Parts, @@ -251,7 +360,7 @@ fn request(parts: &Parts, value: serde_json::Value) -> Request { ); request } -fn cached_response(snapshot: SnapshotResponse) -> Response { +pub(super) fn cached_response(snapshot: SnapshotResponse) -> Response { let mut result = snapshot.body.into_response(); *result.status_mut() = StatusCode::from_u16(snapshot.status).expect("validated status"); result.headers_mut().clear(); @@ -265,11 +374,11 @@ fn cached_response(snapshot: SnapshotResponse) -> Response { } result } -enum Captured { +pub(super) enum Captured { Bytes(Bytes), Streaming(Body), } -async fn capture(body: Body, limit: usize) -> Captured { +pub(super) async fn capture(body: Body, limit: usize) -> Captured { let mut stream = body.into_data_stream(); let mut chunks = Vec::new(); let mut bytes = 0; diff --git a/src/gateway/native/flight.rs b/src/gateway/native/flight.rs new file mode 100644 index 000000000..1e3cb8448 --- /dev/null +++ b/src/gateway/native/flight.rs @@ -0,0 +1,312 @@ +use super::{response, Body, Response, StatusCode}; +use crate::gateway::delivery::{ + FlightKey, FlightLimits, FlightRegistry, FlightTicket, FreshnessContext, OriginAdmission, + SnapshotResponse, +}; +use futures_util::{ + future::{BoxFuture, Shared, WeakShared}, + FutureExt, StreamExt, +}; +use std::{ + collections::BTreeMap, + future::Future, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; + +#[derive(Clone)] +enum Outcome { + Shared(Arc), + Exclusive(Arc>>), +} +type Work = BoxFuture<'static, Outcome>; +struct State { + registry: FlightRegistry, + work: BTreeMap>, +} +pub(super) struct NativeFlights { + state: Mutex, + limits: FlightLimits, + started: Instant, +} +struct Lease { + owner: Arc, + ticket: Option, + work: Shared, +} +impl Drop for Lease { + fn drop(&mut self) { + if let Some(ticket) = self.ticket.take() { + let generation = ticket.generation(); + if let Ok(mut state) = self.owner.state.lock() { + if state.registry.leave(ticket) { + state.work.remove(&generation); + } + } + } + // The registry owns only WeakShared. Dropping the last lease cancels + // the upstream future immediately, without a detached background task. + } +} +impl NativeFlights { + pub(super) fn new(limits: FlightLimits) -> Result, super::GatewayError> { + Ok(Arc::new(Self { + state: Mutex::new(State { + registry: FlightRegistry::new(limits) + .map_err(|_| super::GatewayError("invalid flight limits"))?, + work: BTreeMap::new(), + }), + limits, + started: Instant::now(), + })) + } + pub(super) fn counts(&self) -> (usize, usize) { + self.state.lock().map_or((0, 0), |state| { + (state.registry.len(), state.registry.consumers()) + }) + } + fn join(self: &Arc, key: FlightKey, start: impl FnOnce() -> Work) -> Result { + let mut state = self.state.lock().map_err(|_| ())?; + let now = u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX); + state.registry.expire(now); + let expired = state + .work + .keys() + .filter(|generation| !state.registry.contains_generation(**generation)) + .copied() + .collect::>(); + for generation in expired { + state.work.remove(&generation); + } + let (ticket, owner) = state.registry.join(key, now).map_err(|_| ())?; + let generation = ticket.generation(); + let work = if owner { + let work = start().shared(); + state.work.insert(generation, work.downgrade().ok_or(())?); + work + } else { + match state.work.get(&generation).and_then(WeakShared::upgrade) { + Some(work) => work, + None => { + state.registry.leave(ticket); + return Err(()); + } + } + }; + Ok(Lease { + owner: self.clone(), + ticket: Some(ticket), + work, + }) + } + // None means a nonshareable (cookie/oversized/partial/error) result already + // went to another consumer. This consumer executes normally without joining. + pub(super) async fn execute( + self: &Arc, + key: FlightKey, + admission: OriginAdmission, + freshness: Option, + start: F, + ) -> Option + where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future + Send + 'static, + { + let limits = self.limits; + let expires = admission.expires_at; + let lease = match self.join(key, move || { + async move { + let result = + tokio::time::timeout(Duration::from_millis(limits.deadline_ms), async move { + let response = start().await; + let (parts, body) = response.into_parts(); + let body = match super::delivery::capture(body, limits.response_bytes).await + { + super::delivery::Captured::Bytes(bytes) => bytes, + super::delivery::Captured::Streaming(body) => { + return exclusive(Response::from_parts(parts, body)) + } + }; + let headers = parts + .headers + .iter() + .map(|(name, value)| { + value + .to_str() + .map(|value| (name.to_string(), value.to_owned())) + }) + .collect::, _>>(); + if let Ok(headers) = headers { + let snapshot = SnapshotResponse { + status: parts.status.as_u16(), + headers, + body: body.to_vec(), + }; + if snapshot.shareable(&admission, freshness.as_ref()) { + return Outcome::Shared(Arc::new(snapshot)); + } + } + exclusive(Response::from_parts(parts, Body::from(body))) + }) + .await; + result.unwrap_or_else(|_| exclusive(response(StatusCode::GATEWAY_TIMEOUT))) + } + .boxed() + }) { + Ok(lease) => lease, + Err(_) => return Some(response(StatusCode::SERVICE_UNAVAILABLE)), + }; + let remaining = Duration::from_secs(expires.saturating_sub(super::now())); + if remaining.is_zero() { + return Some(response(StatusCode::UNAUTHORIZED)); + } + let outcome = match tokio::time::timeout(remaining, lease.work.clone()).await { + Ok(outcome) => outcome, + Err(_) => return Some(response(StatusCode::UNAUTHORIZED)), + }; + if super::now() >= expires { + return Some(response(StatusCode::UNAUTHORIZED)); + } + match outcome { + Outcome::Shared(snapshot) => { + Some(super::delivery::cached_response((*snapshot).clone())) + } + Outcome::Exclusive(response) => response + .lock() + .ok() + .and_then(|mut response| response.take()), + } + } +} +fn exclusive(response: Response) -> Outcome { + Outcome::Exclusive(Arc::new(Mutex::new(Some(response)))) +} +pub(super) fn with_permit( + response: Response, + permit: tokio::sync::OwnedSemaphorePermit, +) -> Response { + let (parts, body) = response.into_parts(); + let stream = body.into_data_stream().map(move |chunk| { + let _ = &permit; + chunk + }); + Response::from_parts(parts, Body::from_stream(stream)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gateway::delivery::{OperationKey, OriginIdentity, SnapshotPolicy}; + use std::sync::atomic::{AtomicUsize, Ordering}; + fn admitted() -> (FlightKey, OriginAdmission) { + let request = serde_json::json!({"query":"{ rows { title } }"}); + let identity = OriginIdentity { + application: "test".into(), + endpoint: "origin".into(), + schema_hash: "schema".into(), + protocol_hash: "protocol".into(), + authorization_generation: "policy".into(), + cache_scope: "alice".into(), + }; + let admission = OriginAdmission { + key: OperationKey::from_origin(&identity, &request).unwrap(), + identity, + operation: "operation".into(), + validator: "v1".into(), + validated_at: super::super::now(), + expires_at: super::super::now() + 30, + policy: SnapshotPolicy::Current, + }; + ( + FlightKey::admitted(&admission, &request, None, super::super::now()).unwrap(), + admission, + ) + } + struct Dropped(Arc); + impl Drop for Dropped { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + #[tokio::test] + async fn last_consumer_cancels_upstream_without_detached_owner() { + let flights = NativeFlights::new(FlightLimits::default()).unwrap(); + let (key, admission) = admitted(); + let dropped = Arc::new(AtomicUsize::new(0)); + let counter = dropped.clone(); + let (started, ready) = tokio::sync::oneshot::channel(); + let owner = flights.clone(); + let first_key = key.clone(); + let first_admission = admission.clone(); + let first = tokio::spawn(async move { + owner + .execute(first_key, first_admission, None, move || async move { + let _guard = Dropped(counter); + let _ = started.send(()); + std::future::pending::().await + }) + .await + }); + ready.await.unwrap(); + let owner = flights.clone(); + let second = tokio::spawn(async move { + owner + .execute(key, admission, None, || async { + panic!("joined consumer must not start work") + }) + .await + }); + tokio::time::timeout(Duration::from_secs(2), async { + while flights.counts() != (1, 2) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + first.abort(); + let _ = first.await; + assert_eq!(flights.counts(), (1, 1)); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + second.abort(); + let _ = second.await; + assert_eq!(flights.counts(), (0, 0)); + assert_eq!(dropped.load(Ordering::SeqCst), 1); + } + #[tokio::test] + async fn deadline_expiry_and_failure_release_every_group() { + let flights = NativeFlights::new(FlightLimits { + deadline_ms: 20, + ..Default::default() + }) + .unwrap(); + let (key, admission) = admitted(); + let response = flights + .execute(key, admission, None, || std::future::pending::()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT); + assert_eq!(flights.counts(), (0, 0)); + let flights = NativeFlights::new(FlightLimits { + deadline_ms: 3000, + ..Default::default() + }) + .unwrap(); + let (key, mut admission) = admitted(); + admission.expires_at = super::super::now() + 1; + let response = flights + .execute(key, admission, None, || std::future::pending::()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(flights.counts(), (0, 0)); + let (key, admission) = admitted(); + let result = flights + .execute(key, admission, None, || async { + super::response(StatusCode::BAD_GATEWAY) + }) + .await + .unwrap(); + assert_eq!(result.status(), StatusCode::BAD_GATEWAY); + assert_eq!(flights.counts(), (0, 0)); + } +} diff --git a/src/gateway/native/graphql.rs b/src/gateway/native/graphql.rs index 6b387ac9e..b147ee9c9 100644 --- a/src/gateway/native/graphql.rs +++ b/src/gateway/native/graphql.rs @@ -190,7 +190,7 @@ impl GraphqlBinding { pub(super) async fn execute( &self, - inner: &NativeInner, + inner: &Arc, declaration: &BindingKind, context: RequestContext, mut request: Request, @@ -315,7 +315,7 @@ impl GraphqlBinding { pub(super) async fn execute_http( &self, - inner: &NativeInner, + inner: &Arc, executor: &GraphqlExecutor, context: RequestContext, mut request: Request, diff --git a/src/gateway/native/mod.rs b/src/gateway/native/mod.rs index af7956e23..f283ff5f4 100644 --- a/src/gateway/native/mod.rs +++ b/src/gateway/native/mod.rs @@ -456,4 +456,7 @@ impl GatewayAdapter for NativeGateway { #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] mod delivery; #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] -pub use delivery::NativeDelivery; +pub use delivery::{NativeDelivery, NativeDeliveryOptions}; + +#[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] +mod flight; diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs index fb51df856..073a3ba44 100644 --- a/tests/edge_query_delivery.rs +++ b/tests/edge_query_delivery.rs @@ -288,3 +288,57 @@ fn cache_envelope_eligibility_freshness_and_capacity() { let ticket = cache.begin_fill(&other, 100).unwrap(); assert!(!cache.install(ticket, other, oversized, 100).unwrap()); } + +#[test] +fn flight_admission_limits_freshness_and_generation_fences() { + let request = json!({"query":"{ todos { title } }"}); + let admission = admission("v1"); + let key = FlightKey::admitted(&admission, &request, None, 100).unwrap(); + let mut stronger = context(); + stronger.observe([index("scope", "3")]).unwrap(); + assert_ne!( + key, + FlightKey::admitted(&admission, &request, Some(&stronger), 100).unwrap() + ); + let mut later = admission.clone(); + later.validator = "v2".into(); + assert_ne!( + key, + FlightKey::admitted(&later, &request, None, 100).unwrap() + ); + assert!(FlightKey::admitted(&admission, &request, None, 200).is_err()); + let mut forged = context(); + forged.cache_scope = "bob".into(); + assert!(FlightKey::admitted(&admission, &request, Some(&forged), 100).is_err()); + let mut registry = FlightRegistry::new(FlightLimits { + groups: 1, + consumers: 100, + deadline_ms: 1000, + ..Default::default() + }) + .unwrap(); + let mut tickets = Vec::new(); + for index in 0..100 { + let (ticket, owner) = registry.join(key.clone(), 0).unwrap(); + assert_eq!(owner, index == 0); + tickets.push(ticket); + } + assert_eq!(registry.consumers(), 100); + assert!(registry.join(key.clone(), 1).is_err()); + assert!(!registry.leave(tickets.pop().unwrap())); + assert_eq!(registry.consumers(), 99); + for ticket in tickets { + registry.leave(ticket); + } + assert!(registry.is_empty()); + let (old, _) = registry.join(key.clone(), 100).unwrap(); + let (new, owner) = registry.join(key.clone(), 1100).unwrap(); + assert!(owner); + assert!( + !registry.leave(old), + "expired owner cannot release new generation" + ); + assert_eq!(registry.consumers(), 1); + assert!(registry.leave(new)); + assert!(registry.is_empty()); +} diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 1e9bdd375..830e9c9c3 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -1903,3 +1903,201 @@ async fn native_snapshot_cache_revalidates_each_consumer_without_result_sql() { ); } } + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +#[tokio::test] +async fn hundred_reads_one_execution_with_cache_disabled() { + use axum::{routing::post, Router}; + use distributed::gateway::{delivery::FlightLimits, native::*, *}; + use distributed::graphql::delivery::GatewayVersionStore; + use tower::ServiceExt; + let fixture = protocol_fixture_with_retention(10).await; + let store = GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()), + "flight-test", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .anonymous_role("user") + .subscriptions(false) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .gateway_versions(store.clone()) + .build() + .unwrap(), + ); + let protocol_hash = engine + .delivery_identity( + &user_session(), + &Request::new("query Coalesced { causal_query_views { title } }"), + ) + .unwrap() + .protocol_hash; + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + let handler_gate = gate.clone(); + let origin = Router::new().route( + "/graphql", + post(move |axum::Json(value): axum::Json| { + let engine = engine.clone(); + let gate = handler_gate.clone(); + async move { + if value["extensions"]["gatewayDelivery"]["action"] == "snapshot" { + gate.acquire().await.unwrap().forget(); + } + axum::Json( + serde_json::to_value( + engine + .execute( + &user_session(), + serde_json::from_value::(value).unwrap(), + ) + .await, + ) + .unwrap(), + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin_url = format!("http://{}", listener.local_addr().unwrap()); + struct Stop(tokio::task::JoinHandle<()>); + impl Drop for Stop { + fn drop(&mut self) { + self.0.abort(); + } + } + let _server = Stop(tokio::spawn(async move { + axum::serve(listener, origin).await.unwrap() + })); + let delivery = Arc::new(NativeDelivery::coalescing(FlightLimits::default()).unwrap()); + let config = GatewayConfig { + bindings: vec![Binding::new( + "api", + BindingKind::Graphql { + executor: GraphqlExecutor::Remote { origin: origin_url }, + capabilities: GraphqlCapabilities { + queries: true, + ..Default::default() + }, + delivery: DeliveryCapabilities { + coalescing: true, + ..Default::default() + }, + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "api")], + } + .build() + .unwrap(); + let router = NativeGateway::new( + config, + NativeOptions::new("http://public.invalid"), + [( + "api".into(), + NativeBinding::GraphqlWithDelivery( + GraphqlBinding::Remote(RemoteGraphql { + live_path: None, + ..Default::default() + }), + delivery.clone(), + ), + )], + NativeAuth::anonymous(), + ) + .unwrap() + .router(); + let document = "query Coalesced { causal_query_views { title } }"; + let spawn = |extension: Option| { + let router = router.clone(); + let mut request = json!({"query":document}); + if let Some(extension) = extension { + request["extensions"] = json!({"gatewayFreshness":extension}); + } + tokio::spawn(async move { + let response = router + .oneshot( + axum::http::Request::post("/graphql") + .header("content-type", "application/json") + .body(axum::body::Body::from(request.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), axum::http::StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + serde_json::from_slice::(&bytes).unwrap() + }) + }; + let wait = |groups, consumers| { + let delivery = delivery.clone(); + async move { + tokio::time::timeout(Duration::from_secs(10), async { + while delivery.flight_counts() != (groups, consumers) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("all consumers admitted and joined before releasing result execution"); + } + }; + let mut consumers = Vec::new(); + for _ in 0..100 { + consumers.push(spawn(None)); + } + wait(1, 100).await; + assert_eq!(store.metrics().validations, 100); + assert_eq!(store.metrics().result_executions, 0); + gate.add_permits(1); + let first = consumers.pop().unwrap().await.unwrap(); + assert!(first.get("errors").is_none(), "{first}"); + for consumer in consumers { + assert_eq!(consumer.await.unwrap(), first); + } + assert_eq!( + store.metrics().result_executions, + 1, + "100 overlapping consumers must execute result SQL exactly once" + ); + assert_eq!(delivery.flight_counts(), (0, 0)); + // Cache is disabled: a subsequent nonoverlapping request executes again. + let next = spawn(None); + wait(1, 1).await; + gate.add_permits(1); + assert_eq!(next.await.unwrap(), first); + assert_eq!(store.metrics().result_executions, 2); + // One consumer can cancel without aborting the other's execution. + let cancelled = spawn(None); + let survivor = spawn(None); + wait(1, 2).await; + cancelled.abort(); + let _ = cancelled.await; + wait(1, 1).await; + gate.add_permits(1); + assert_eq!(survivor.await.unwrap(), first); + assert_eq!(store.metrics().result_executions, 3); + // A stronger floor must not join a flight admitted without that floor. + let protocol = &first["extensions"]["distributed"]; + let index = &protocol["snapshot"]["indexes"][0]; + let context = json!({"version":1,"schemaHash":protocol["schemaHash"],"protocolHash":protocol_hash, + "authorizationGeneration":protocol["authorizationGeneration"],"cacheScope":protocol["cacheScope"],"pending":[], + "minimum":[{"kind":"index","projection":index["projection"],"scopeToken":index["scopeToken"],"position":"1"}]}); + let old = spawn(None); + wait(1, 1).await; + let stronger = spawn(Some(context)); + wait(2, 2).await; + gate.add_permits(2); + assert_eq!(old.await.unwrap(), first); + let strong = stronger.await.unwrap(); + assert!(strong.get("errors").is_none(), "{strong}"); + assert_eq!(store.metrics().result_executions, 5); + assert_eq!(delivery.flight_counts(), (0, 0)); +} From 1381850fc8231b223dbcf363d09b6e2995cba031 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 00:00:56 -0500 Subject: [PATCH 056/484] feat(gateway): share admitted live subscriptions with bounded recovery Implements [[tasks/application-gateway-9]]. --- .github/workflows/integration-gateway.yaml | 2 + docs/gateway/live-sharing.md | 53 ++ docs/gateway/query-coalescing.md | 2 +- src/gateway/README.md | 3 + src/gateway/delivery/coordinator.rs | 127 ++++ src/gateway/delivery/flight.rs | 121 +--- src/gateway/delivery/live.rs | 244 ++++++++ src/gateway/delivery/mod.rs | 6 + src/gateway/delivery/snapshot.rs | 40 +- src/gateway/native/delivery.rs | 38 +- src/gateway/native/graphql.rs | 96 ++- src/gateway/native/live.rs | 692 +++++++++++++++++++++ src/gateway/native/live_transport.rs | 676 ++++++++++++++++++++ src/gateway/native/mod.rs | 6 + src/graphql/engine/delivery.rs | 40 +- src/graphql/http.rs | 74 ++- src/graphql/schema.rs | 27 + src/graphql/subscribe.rs | 43 +- tests/edge_query_delivery.rs | 59 ++ tests/graphql_query_protocol/main.rs | 301 +++++++++ 20 files changed, 2462 insertions(+), 188 deletions(-) create mode 100644 docs/gateway/live-sharing.md create mode 100644 src/gateway/delivery/coordinator.rs create mode 100644 src/gateway/delivery/live.rs create mode 100644 src/gateway/native/live.rs create mode 100644 src/gateway/native/live_transport.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 5c6d5f4eb..5864b0108 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -113,6 +113,8 @@ jobs: - name: Verify shared query cancellation, expiry and deadlines run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib gateway::native::flight::tests + - name: Verify shared live replay, expiry, backpressure and teardown + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib gateway::native::live::tests - name: Verify transactional cache coverage and Atomic rollback run: | cargo test -p distributed --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --lib graphql::delivery::versions::tests diff --git a/docs/gateway/live-sharing.md b/docs/gateway/live-sharing.md new file mode 100644 index 000000000..1ef09998d --- /dev/null +++ b/docs/gateway/live-sharing.md @@ -0,0 +1,53 @@ +# Shared live GraphQL + +Enable `gateway-graphql-native,gateway-delivery`, select `live_sharing` on the +GraphQL declaration, and bind `NativeDelivery::live(LiveLimits::default())`. +Snapshot caching, concurrent queries and live sharing can be selected separately +with `NativeDeliveryOptions`. The origin needs the authenticated delivery control +path and version coverage described in [snapshot-cache.md](snapshot-cache.md). +Custom embedded executor routers conservatively keep independent subscriptions; +the canonical engine and eligible remote whole-operation executors support sharing. + +Every consumer is admitted by the origin, including credentials supplied through +GraphQL `connection_init`. The gateway passes these credentials to the backend's +existing validator; it does not derive a subject from cookies or unverified JWTs. +A remote client initially uses a temporary origin WebSocket for the real connection +acknowledgement. It owns no subscription and closes before operation coordination. +Thus 100 clients incur 100 admissions and handshake costs but can share one steady +upstream subscription and producer. HTTP control requests do not execute result SQL. + +Groups bind the exact document, variables, origin subject/cache scope, policy, +schema and protocol. Each consumer keeps its own transport ID, expiry, queue and +freshness requirements. Different resume cursors start independent replay. Handoff +requires the same operation plus an exact supported, comparable cursor vector and +matching data; the consumer's replay frames remain queued before future shared +frames. Unknown cursors keep independent streams. Equal data alone never proves +cursor equality. Duplicate suppression hashes the whole data and protocol envelope, +so new confirmation evidence is delivered even when values are unchanged. + +Defaults bound a coordinator to 256 groups, 1,024 consumers per group, 16 pending +frames per consumer, 1 MiB per full frame, eight retained history frames and a +one-hour group lifetime. Native ingress bounds socket/request counts and wire +message sizes as well. Frames share immutable storage across consumer queues. +If a slow consumer cannot preserve all evidence within its queue, it receives +`LIVE_RESET_REQUIRED`; a blocked socket is closed so it must reconnect. No +latest-value replacement silently discards confirmation proof. Group deadline, +upstream loss and incomplete/invalid origin envelopes also require recovery. + +Dropping a consumer releases only its lease. Last leave aborts the actual upstream +stream, socket and origin change-feed receiver, including a pending origin SQL +read. An expired credential cannot continue receiving shared frames or own other +consumers' upstream: the remaining valid consumer reconnects with its own origin +credential and the last proven resume cursor. Normal GraphQL completion drains +queued frames; unexpected transport loss requires reset. Reconnect authenticates +again. Shared outbound sockets do not hibernate for free. + +`NativeDelivery::live_counts()` reports active groups, consumers, cumulative source +attempts, resets, upstream frames, exact duplicate frames and safe handoffs. Source +attempts include credential reconnects; they are not a count of active producers. +`GraphqlEngine::live_subscriber_count()` separately reports actual origin producer +subscriptions. No credentials or subject identifiers appear in these counters. + +Disable `live_sharing` and remove the live delivery resource to restore independent +subscriptions. Existing client resume/reset and response-sealing behavior remains +in force. No migration or new credential is required by live coordination itself. diff --git a/docs/gateway/query-coalescing.md b/docs/gateway/query-coalescing.md index 89138c5a4..a120f4299 100644 --- a/docs/gateway/query-coalescing.md +++ b/docs/gateway/query-coalescing.md @@ -3,7 +3,7 @@ Mount `NativeDelivery::coalescing(FlightLimits)` with the GraphQL binding's `coalescing` capability. This creates no snapshot cache. To select both, use `NativeDelivery::new(NativeDeliveryOptions { snapshots: Some(...), coalescing: -Some(...) })`. All capabilities remain explicit and independently removable. +Some(...), ..Default::default() })`. All capabilities remain explicit and independently removable. The origin uses the authenticated delivery control path and version store described in [snapshot-cache.md](snapshot-cache.md). diff --git a/src/gateway/README.md b/src/gateway/README.md index 058ec24a1..1563be0bc 100644 --- a/src/gateway/README.md +++ b/src/gateway/README.md @@ -117,3 +117,6 @@ Concurrent queries can share a bounded execution independently of caching via `NativeDelivery::coalescing(FlightLimits)`. Each consumer still authenticates; last-consumer cancellation drops the upstream future. See [query coalescing](../../docs/gateway/query-coalescing.md). + +Shared live delivery is independently selected with `NativeDelivery::live(LiveLimits)`. +See [live sharing and recovery](../../docs/gateway/live-sharing.md). diff --git a/src/gateway/delivery/coordinator.rs b/src/gateway/delivery/coordinator.rs new file mode 100644 index 000000000..298034d71 --- /dev/null +++ b/src/gateway/delivery/coordinator.rs @@ -0,0 +1,127 @@ +use super::DeliveryError; +use std::collections::BTreeMap; + +/// Validated shared group bounds; construct through flight or live limits. +pub struct CoordinatorLimits { + pub(crate) groups: usize, + pub(crate) consumers: usize, + pub(crate) deadline_ms: u64, +} + +/// Adapter-owned consumer ticket. Release exactly once when that consumer +/// finishes/cancels. Stale tickets cannot release a newer same-key generation. +#[derive(Debug)] +pub struct CoordinatorTicket { + key: K, + generation: u64, +} +impl CoordinatorTicket { + /// Flight generation used to bind a runtime future to portable bookkeeping. + pub fn generation(&self) -> u64 { + self.generation + } +} +struct Group { + generation: u64, + consumers: usize, + deadline: u64, +} +/// Portable bounded refcount/deadline bookkeeping. Runtime futures, clocks, +/// sockets and cancellation guards belong to native/Worker adapters. +pub struct CoordinatorRegistry { + limits: CoordinatorLimits, + groups: BTreeMap, + next: u64, +} +impl CoordinatorRegistry { + /// Allocate empty bookkeeping only when query coalescing is selected. + pub fn new( + limits: impl TryInto, + ) -> Result { + let limits = limits.try_into()?; + Ok(Self { + limits, + groups: BTreeMap::new(), + next: 0, + }) + } + /// Join/create; the boolean identifies the one upstream execution owner. + /// `now_ms` is the adapter's monotonic clock, not a causal data clock. + pub fn join( + &mut self, + key: K, + now_ms: u64, + ) -> Result<(CoordinatorTicket, bool), DeliveryError> { + self.expire(now_ms); + if let Some(group) = self.groups.get_mut(&key) { + if group.consumers >= self.limits.consumers { + return Err(DeliveryError::Unavailable); + } + group.consumers += 1; + return Ok(( + CoordinatorTicket { + key, + generation: group.generation, + }, + false, + )); + } + if self.groups.len() >= self.limits.groups { + return Err(DeliveryError::Unavailable); + } + self.next = self.next.checked_add(1).ok_or(DeliveryError::Unavailable)?; + self.groups.insert( + key.clone(), + Group { + generation: self.next, + consumers: 1, + deadline: now_ms.saturating_add(self.limits.deadline_ms), + }, + ); + Ok(( + CoordinatorTicket { + key, + generation: self.next, + }, + true, + )) + } + /// Release one consumer; true means the last consumer left that generation. + pub fn leave(&mut self, ticket: CoordinatorTicket) -> bool { + let Some(group) = self.groups.get_mut(&ticket.key) else { + return false; + }; + if group.generation != ticket.generation { + return false; + } + group.consumers -= 1; + if group.consumers == 0 { + self.groups.remove(&ticket.key); + true + } else { + false + } + } + /// Forget expired groups; adapters enforce matching upstream deadlines. + pub fn expire(&mut self, now_ms: u64) { + self.groups.retain(|_, group| group.deadline > now_ms); + } + /// Active group count. + pub fn len(&self) -> usize { + self.groups.len() + } + /// Whether no group has an admitted consumer. + pub fn is_empty(&self) -> bool { + self.groups.is_empty() + } + /// Total current admitted consumers. + pub fn consumers(&self) -> usize { + self.groups.values().map(|group| group.consumers).sum() + } + /// Check whether a runtime future still belongs to an active generation. + pub fn contains_generation(&self, generation: u64) -> bool { + self.groups + .values() + .any(|group| group.generation == generation) + } +} diff --git a/src/gateway/delivery/flight.rs b/src/gateway/delivery/flight.rs index 3c742f7d9..68f8ef34f 100644 --- a/src/gateway/delivery/flight.rs +++ b/src/gateway/delivery/flight.rs @@ -1,7 +1,6 @@ use super::{canonical_json, DeliveryError, FreshnessContext, OriginAdmission}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; /// Exact admitted operation, dependency version and freshness requirement. /// Conservative equality prevents stronger late consumers joining older work. @@ -76,118 +75,18 @@ impl FlightLimits { } } } -/// Adapter-owned consumer ticket. Release exactly once when that consumer -/// finishes/cancels. Stale tickets cannot release a newer same-key generation. -#[derive(Debug)] -pub struct FlightTicket { - key: FlightKey, - generation: u64, -} -impl FlightTicket { - /// Flight generation used to bind a runtime future to portable bookkeeping. - pub fn generation(&self) -> u64 { - self.generation - } -} -struct Group { - generation: u64, - consumers: usize, - deadline: u64, -} -/// Portable bounded refcount/deadline bookkeeping. Runtime futures, clocks, -/// sockets and cancellation guards belong to native/Worker adapters. -pub struct FlightRegistry { - limits: FlightLimits, - groups: BTreeMap, - next: u64, -} -impl FlightRegistry { - /// Allocate empty bookkeeping only when query coalescing is selected. - pub fn new(limits: FlightLimits) -> Result { +/// Portable query registry using the common bounded coordinator. +pub type FlightRegistry = super::CoordinatorRegistry; +/// One admitted query consumer's cancellation/generation ticket. +pub type FlightTicket = super::CoordinatorTicket; +impl TryFrom for super::CoordinatorLimits { + type Error = DeliveryError; + fn try_from(limits: FlightLimits) -> Result { limits.validate()?; Ok(Self { - limits, - groups: BTreeMap::new(), - next: 0, + groups: limits.groups, + consumers: limits.consumers, + deadline_ms: limits.deadline_ms, }) } - /// Join/create; the boolean identifies the one upstream execution owner. - /// `now_ms` is the adapter's monotonic clock, not a causal data clock. - pub fn join( - &mut self, - key: FlightKey, - now_ms: u64, - ) -> Result<(FlightTicket, bool), DeliveryError> { - self.expire(now_ms); - if let Some(group) = self.groups.get_mut(&key) { - if group.consumers >= self.limits.consumers { - return Err(DeliveryError::Unavailable); - } - group.consumers += 1; - return Ok(( - FlightTicket { - key, - generation: group.generation, - }, - false, - )); - } - if self.groups.len() >= self.limits.groups { - return Err(DeliveryError::Unavailable); - } - self.next = self.next.checked_add(1).ok_or(DeliveryError::Unavailable)?; - self.groups.insert( - key.clone(), - Group { - generation: self.next, - consumers: 1, - deadline: now_ms.saturating_add(self.limits.deadline_ms), - }, - ); - Ok(( - FlightTicket { - key, - generation: self.next, - }, - true, - )) - } - /// Release one consumer; true means the last consumer left that generation. - pub fn leave(&mut self, ticket: FlightTicket) -> bool { - let Some(group) = self.groups.get_mut(&ticket.key) else { - return false; - }; - if group.generation != ticket.generation { - return false; - } - group.consumers -= 1; - if group.consumers == 0 { - self.groups.remove(&ticket.key); - true - } else { - false - } - } - /// Forget expired groups; adapters enforce matching upstream deadlines. - pub fn expire(&mut self, now_ms: u64) { - self.groups.retain(|_, group| group.deadline > now_ms); - } - /// Active group count. - pub fn len(&self) -> usize { - self.groups.len() - } - /// Whether no group has an admitted consumer. - pub fn is_empty(&self) -> bool { - self.groups.is_empty() - } - /// Total current admitted consumers. - pub fn consumers(&self) -> usize { - self.groups.values().map(|group| group.consumers).sum() - } - /// Check whether a runtime future still belongs to an active generation. - pub fn contains_generation(&self, generation: u64) -> bool { - self.groups - .values() - .any(|group| group.generation == generation) - } } diff --git a/src/gateway/delivery/live.rs b/src/gateway/delivery/live.rs new file mode 100644 index 000000000..9ada4bd5a --- /dev/null +++ b/src/gateway/delivery/live.rs @@ -0,0 +1,244 @@ +use super::{ + canonical_json, CoordinatorLimits, DeliveryError, FreshnessContext, OperationKey, + OriginAdmission, SnapshotResponse, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Authenticated live operation identity and initial replay requirements. +/// HTTP query documents can never construct this key. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct LiveKey { + base: String, + initial: String, + fork: u64, +} +impl LiveKey { + /// Construct only after fresh origin admission for this exact consumer. + pub fn admitted( + admission: &OriginAdmission, + request: &serde_json::Value, + freshness: Option<&FreshnessContext>, + now: u64, + ) -> Result { + admission.bind(request, now)?; + if crate::gateway::graphql::operation_kind( + request["query"].as_str().ok_or(DeliveryError::Ineligible)?, + request["operationName"].as_str(), + ) != Ok(crate::gateway::graphql::OperationKind::Subscription) + { + return Err(DeliveryError::Ineligible); + } + if let Some(freshness) = freshness { + freshness.bind(&admission.identity)?; + } + let mut base = request.clone(); + if let Some(extensions) = base + .get_mut("extensions") + .and_then(serde_json::Value::as_object_mut) + { + if let Some(distributed) = extensions + .get_mut("distributed") + .and_then(serde_json::Value::as_object_mut) + { + distributed.remove("resume"); + if distributed.is_empty() { + extensions.remove("distributed"); + } + } + } + let base = OperationKey::from_origin(&admission.identity, &base)? + .as_str() + .to_owned(); + let initial = canonical_json(&serde_json::json!([ + "live-join-v1", + admission.key, + admission.validator, + freshness + ]))?; + Ok(Self { + base, + initial: format!("{:x}", Sha256::digest(initial)), + fork: 0, + }) + } + /// Same exact operation/scope may hand off only after comparable cursor + /// equality. Different resume requests are not automatically initial joins. + pub fn same_operation(&self, other: &Self) -> bool { + self.base == other.base + } + /// Independent replay generation while waiting for a safe handoff. + pub fn fork(&self, nonce: u64) -> Self { + Self { + fork: nonce, + ..self.clone() + } + } + /// Exact initial request compatibility, ignoring runtime generation. + pub fn same_initial(&self, other: &Self) -> bool { + self.base == other.base && self.initial == other.initial + } +} +/// Bounded per-coordinator and per-consumer live resources. +#[derive(Clone, Copy, Debug)] +pub struct LiveLimits { + /// Maximum active upstream groups including independent replays. + pub groups: usize, + /// Maximum logical consumers sharing one group. + pub consumers: usize, + /// Maximum pending full frames for each consumer. + pub queue_frames: usize, + /// Maximum bytes in one full data/protocol frame. + pub frame_bytes: usize, + /// Maximum retained history frames for exact initial replay. + pub history_frames: usize, + /// Maximum upstream group lifetime; reconnect reauthenticates. + pub lifetime_ms: u64, +} +impl Default for LiveLimits { + fn default() -> Self { + Self { + groups: 256, + consumers: 1024, + queue_frames: 16, + frame_bytes: 1024 * 1024, + history_frames: 8, + lifetime_ms: 3600000, + } + } +} +impl LiveLimits { + /// Validate all bounds before mounting live coordination. + pub fn validate(&self) -> Result<(), DeliveryError> { + if self.groups == 0 + || self.groups > 4096 + || self.consumers == 0 + || self.consumers > 65536 + || self.queue_frames == 0 + || self.queue_frames > 1024 + || self.frame_bytes == 0 + || self.frame_bytes > 16 * 1024 * 1024 + || self.history_frames == 0 + || self.history_frames > self.queue_frames + || self.lifetime_ms == 0 + || self.lifetime_ms > 3600000 + { + Err(DeliveryError::InvalidContext) + } else { + Ok(()) + } + } +} +impl TryFrom for CoordinatorLimits { + type Error = DeliveryError; + fn try_from(limits: LiveLimits) -> Result { + limits.validate()?; + Ok(Self { + groups: limits.groups, + consumers: limits.consumers, + deadline_ms: limits.lifetime_ms, + }) + } +} +/// Live refcounts/deadlines use the same coordinator as query flights. +pub type LiveRegistry = super::CoordinatorRegistry; +/// One admitted live consumer's generation ticket. +pub type LiveTicket = super::CoordinatorTicket; + +/// Full origin frame, including every causal observation and checkpoint. +#[derive(Clone, Debug)] +pub struct LiveFrame { + payload: serde_json::Value, + hash: [u8; 32], + cursor: Option>, + identity: super::OriginIdentity, + operation: String, + evidence: Vec, +} +impl LiveFrame { + /// Validate exact origin authority and any supplied floors before fan-out. + pub fn from_origin( + admission: &OriginAdmission, + payload: serde_json::Value, + freshness: Option<&FreshnessContext>, + max_bytes: usize, + ) -> Result { + let bytes = serde_json::to_vec(&payload).map_err(|_| DeliveryError::Ineligible)?; + if bytes.len() > max_bytes { + return Err(DeliveryError::Unavailable); + } + let response = SnapshotResponse { + status: 200, + headers: Vec::new(), + body: bytes.clone(), + }; + if !response.live_shareable(admission, freshness) { + return Err(DeliveryError::Ineligible); + } + let evidence = response + .evidence(admission, false, true) + .ok_or(DeliveryError::Ineligible)?; + let canonical = canonical_json(&payload).unwrap_or(bytes); + let protocol = &payload["extensions"]["distributed"]; + let cursors = &protocol["live"]["cursors"]; + let cursor = if protocol["live"]["supported"] == true + && protocol["snapshot"]["indexesComparable"] == true + && cursors.as_array().is_some_and(|cursors| { + !cursors.is_empty() + && cursors.len() <= 256 + && cursors.iter().all(|cursor| { + cursor["projection"] + .as_str() + .is_some_and(|value| !value.is_empty() && value.len() <= 1024) + && cursor["position"].as_str().is_some_and(|value| { + !value.is_empty() + && value.bytes().all(|byte| byte.is_ascii_digit()) + && value.parse::().is_ok() + }) + && cursor["token"] + .as_str() + .is_some_and(|value| !value.is_empty() && value.len() <= 1024) + }) + }) { + Some(canonical_json(cursors)?) + } else { + None + }; + Ok(Self { + payload, + hash: Sha256::digest(canonical).into(), + cursor, + identity: admission.identity.clone(), + operation: admission.operation.clone(), + evidence, + }) + } + /// Check each consumer's independent authority and retained minima. + pub fn satisfies( + &self, + admission: &OriginAdmission, + freshness: Option<&FreshnessContext>, + ) -> bool { + self.identity == admission.identity + && self.operation == admission.operation + && freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&self.evidence) + }) + } + /// Full payload to serialize under each consumer's own transport ID. + pub fn payload(&self) -> &serde_json::Value { + &self.payload + } + /// Suppress only fully identical data plus protocol, never data alone. + pub fn same_frame(&self, other: &Self) -> bool { + self.hash == other.hash + } + /// Independent replay can hand off only at an exact proven cursor vector. + /// Adapters must also compare LiveKey::same_operation and preserve queued + /// frames before moving the consumer to the target's future stream. + pub fn same_cursor(&self, other: &Self) -> bool { + self.cursor.is_some() + && self.cursor == other.cursor + && self.payload["data"] == other.payload["data"] + } +} diff --git a/src/gateway/delivery/mod.rs b/src/gateway/delivery/mod.rs index fb4510e15..3aad997e3 100644 --- a/src/gateway/delivery/mod.rs +++ b/src/gateway/delivery/mod.rs @@ -31,3 +31,9 @@ pub use snapshot::*; mod flight; pub use flight::*; + +mod coordinator; +pub use coordinator::*; + +mod live; +pub use live::*; diff --git a/src/gateway/delivery/snapshot.rs b/src/gateway/delivery/snapshot.rs index 29d3c47c0..7b645a52c 100644 --- a/src/gateway/delivery/snapshot.rs +++ b/src/gateway/delivery/snapshot.rs @@ -107,7 +107,12 @@ pub struct SnapshotResponse { pub body: Vec, } impl SnapshotResponse { - fn evidence(&self, admission: &OriginAdmission, complete: bool) -> Option> { + pub(super) fn evidence( + &self, + admission: &OriginAdmission, + complete: bool, + live: bool, + ) -> Option> { if self.status != 200 || self.headers.iter().any(|(name, value)| { name.eq_ignore_ascii_case("set-cookie") @@ -138,7 +143,7 @@ impl SnapshotResponse { || protocol["operation"] != admission.operation || protocol.get("command").is_some() || protocol.get("receipt").is_some() - || protocol.get("live").is_some() + || (!live && protocol.get("live").is_some()) { return None; } @@ -191,11 +196,25 @@ impl SnapshotResponse { admission: &OriginAdmission, freshness: Option<&FreshnessContext>, ) -> bool { - self.evidence(admission, false).is_some_and(|evidence| { - freshness.is_none_or(|context| { - context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + self.evidence(admission, false, false) + .is_some_and(|evidence| { + freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + }) + }) + } + /// Validate live fan-out while retaining the origin's live envelope. + pub fn live_shareable( + &self, + admission: &OriginAdmission, + freshness: Option<&FreshnessContext>, + ) -> bool { + self.evidence(admission, false, true) + .is_some_and(|evidence| { + freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + }) }) - }) } /// Candidate proof covers every required floor in the admitted scope. pub fn satisfies( @@ -203,11 +222,12 @@ impl SnapshotResponse { admission: &OriginAdmission, freshness: Option<&FreshnessContext>, ) -> bool { - self.evidence(admission, true).is_some_and(|evidence| { - freshness.is_none_or(|context| { - context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + self.evidence(admission, true, false) + .is_some_and(|evidence| { + freshness.is_none_or(|context| { + context.bind(&admission.identity).is_ok() && context.satisfied_by(&evidence) + }) }) - }) } } diff --git a/src/gateway/native/delivery.rs b/src/gateway/native/delivery.rs index fca7ebdae..33aaf129e 100644 --- a/src/gateway/native/delivery.rs +++ b/src/gateway/native/delivery.rs @@ -19,12 +19,15 @@ pub struct NativeDeliveryOptions { pub snapshots: Option, /// Optional concurrent query execution coordination. pub coalescing: Option, + /// Optional shared live operation coordination. + pub live: Option, } /// Bounded native delivery. Each consumer authenticates at the origin before /// lookup/join; snapshot storage and shared query execution are independent. pub struct NativeDelivery { snapshots: Option>, flights: Option>, + pub(super) live: Option>, entry_bytes: usize, } struct Fill { @@ -41,14 +44,14 @@ struct Fill { impl NativeDelivery { /// Allocate only the explicitly selected capabilities and their bounds. pub fn new(options: NativeDeliveryOptions) -> Result { - if options.snapshots.is_none() && options.coalescing.is_none() { + if options.snapshots.is_none() && options.coalescing.is_none() && options.live.is_none() { return Err(GatewayError("no delivery capability selected")); } let entry_bytes = options .coalescing .map(|limits| limits.response_bytes) .or(options.snapshots.map(|limits| limits.entry_bytes)) - .expect("selected delivery"); + .unwrap_or(1024 * 1024); Ok(Self { snapshots: options .snapshots @@ -60,6 +63,7 @@ impl NativeDelivery { .coalescing .map(super::flight::NativeFlights::new) .transpose()?, + live: options.live.map(super::live::NativeLive::new).transpose()?, entry_bytes, }) } @@ -68,6 +72,7 @@ impl NativeDelivery { Self::new(NativeDeliveryOptions { snapshots: Some(limits), coalescing: None, + live: None, }) } /// Allocate bounded query coalescing without snapshot storage. @@ -75,13 +80,28 @@ impl NativeDelivery { Self::new(NativeDeliveryOptions { snapshots: None, coalescing: Some(limits), + live: None, }) } + /// Allocate shared live coordination without query caching/coalescing. + pub fn live(limits: LiveLimits) -> Result { + Self::new(NativeDeliveryOptions { + live: Some(limits), + ..Default::default() + }) + } + /// Active live groups/consumers and cumulative source attempts, resets, + /// upstream frames, duplicate frames and safe consumer handoffs. + pub fn live_counts(&self) -> (usize, usize, u64, u64, u64, u64, u64) { + self.live + .as_ref() + .map_or((0, 0, 0, 0, 0, 0, 0), |live| live.counts()) + } pub(super) fn capabilities(&self) -> DeliveryCapabilities { DeliveryCapabilities { snapshots: self.snapshots.is_some(), coalescing: self.flights.is_some(), - live_sharing: false, + live_sharing: self.live.is_some(), } } /// Current active query groups and admitted consumers, without identifiers. @@ -272,12 +292,12 @@ impl NativeDelivery { } } -enum AdmissionResult { +pub(super) enum AdmissionResult { Eligible(OriginAdmission), Bypass, Error(Response), } -async fn validate( +pub(super) async fn validate( binding: &GraphqlBinding, inner: &std::sync::Arc, executor: &GraphqlExecutor, @@ -344,9 +364,15 @@ fn mark(value: &mut serde_json::Value, action: &str) { if !value["extensions"].is_object() { value["extensions"] = serde_json::json!({}); } + let init = value["extensions"]["gatewayDelivery"] + .get("connectionInit") + .cloned(); value["extensions"]["gatewayDelivery"] = serde_json::json!({"action":action}); + if let Some(init) = init { + value["extensions"]["gatewayDelivery"]["connectionInit"] = init; + } } -fn request(parts: &Parts, value: serde_json::Value) -> Request { +pub(super) fn request(parts: &Parts, value: serde_json::Value) -> Request { let mut request = Request::new(Body::from(value.to_string())); *request.method_mut() = parts.method.clone(); *request.uri_mut() = parts.uri.clone(); diff --git a/src/gateway/native/graphql.rs b/src/gateway/native/graphql.rs index b147ee9c9..743a9793a 100644 --- a/src/gateway/native/graphql.rs +++ b/src/gateway/native/graphql.rs @@ -28,7 +28,9 @@ use tower::ServiceExt; /// registration. The executor owns the composed schema and authorization. #[derive(Clone)] pub struct EmbeddedGraphql { - router: Router, + pub(super) router: Router, + #[cfg(feature = "gateway-delivery")] + pub(super) engine: Option>, capabilities: GraphqlCapabilities, extensions: BTreeSet, } @@ -54,6 +56,8 @@ impl EmbeddedGraphql { return Err(GatewayError("command surface requires a command host")); } Ok(Self { + #[cfg(feature = "gateway-delivery")] + engine: Some(engine.clone()), router: graphql_router_composed(engine, host, Some(operation_filter(capabilities))), capabilities, extensions: BTreeSet::new(), @@ -81,6 +85,8 @@ impl EmbeddedGraphql { } Ok(Self { router: factory(operation_filter(capabilities)), + #[cfg(feature = "gateway-delivery")] + engine: None, capabilities, extensions: registered, }) @@ -205,11 +211,33 @@ impl GraphqlBinding { }; let upgrade = request.headers().contains_key(header::UPGRADE); if upgrade { + #[cfg(feature = "gateway-delivery")] + let shared = request + .extensions() + .get::>() + .cloned() + .filter(|delivery| delivery.live.is_some()); if !capabilities.live { return response(StatusCode::NOT_FOUND); } return match (self, executor) { (Self::Embedded(embedded), _) => { + #[cfg(feature = "gateway-delivery")] + if let Some(coordinator) = shared.filter(|_| embedded.engine.is_some()) { + let execution = super::live_transport::Execution { + binding: self.clone(), + inner: inner.clone(), + declaration: declaration.clone(), + context, + }; + return super::live_transport::upgrade_embedded( + execution, + request, + embedded.clone(), + coordinator, + ) + .await; + } let permit = match inner.permits.clone().try_acquire_owned() { Ok(permit) => permit, Err(_) => return response(StatusCode::SERVICE_UNAVAILABLE), @@ -249,14 +277,46 @@ impl GraphqlBinding { origin, remote.live_path.as_deref().expect("validated live path"), *capabilities, - context, + context.clone(), request, + #[cfg(feature = "gateway-delivery")] + shared.map(|coordinator| { + ( + super::live_transport::Execution { + binding: self.clone(), + inner: inner.clone(), + declaration: declaration.clone(), + context, + }, + coordinator, + ) + }), ) .await } _ => response(StatusCode::SERVICE_UNAVAILABLE), }; } + self.execute_operation(inner, declaration, context, request) + .await + } + + /// Execute an already-selected HTTP operation without an upgrade branch. + pub(super) async fn execute_operation( + &self, + inner: &Arc, + declaration: &BindingKind, + context: RequestContext, + request: Request, + ) -> Response { + let BindingKind::Graphql { + capabilities, + executor, + .. + } = declaration + else { + return response(StatusCode::SERVICE_UNAVAILABLE); + }; if request.method() != "POST" { let mut result = response(StatusCode::METHOD_NOT_ALLOWED); result @@ -296,7 +356,8 @@ impl GraphqlBinding { value["query"].as_str().unwrap_or(""), value["operationName"].as_str(), ) == Ok(super::super::graphql::OperationKind::Query) - && value["extensions"].get("gatewayDelivery").is_none() + && (value["extensions"].get("gatewayDelivery").is_none() + || value["extensions"]["gatewayDelivery"]["action"] == "execute") { return coordinator .execute(self, inner, executor, context, parts, value, permit) @@ -353,12 +414,16 @@ fn rewrite_path(request: &mut Request, path: &str) { } async fn remote_websocket( - inner: &NativeInner, + inner: &Arc, origin: &str, path: &str, capabilities: GraphqlCapabilities, context: RequestContext, request: Request, + #[cfg(feature = "gateway-delivery")] sharing: Option<( + super::live_transport::Execution, + Arc, + )>, ) -> Response { let permit = match inner.permits.clone().try_acquire_owned() { Ok(permit) => permit, @@ -387,6 +452,16 @@ async fn remote_websocket( if proxy::prepare_headers(&mut parts.headers, inner, &context, true).is_err() { return response(StatusCode::BAD_REQUEST); } + #[cfg(feature = "gateway-delivery")] + let sharing = sharing.map(|(execution, coordinator)| { + ( + execution, + coordinator, + super::delivery::request(&parts, serde_json::json!({})) + .into_parts() + .0, + ) + }); parts.headers.insert( header::SEC_WEBSOCKET_PROTOCOL, HeaderValue::from_static(protocol), @@ -484,6 +559,19 @@ async fn remote_websocket( ), ) .await; + #[cfg(feature = "gateway-delivery")] + if let Some((execution, coordinator, parts)) = sharing { + super::live_transport::remote( + socket, + upstream, + execution, + parts, + coordinator, + protocol, + ) + .await; + return; + } bridge(socket, upstream, capabilities, protocol).await; }) .await; diff --git a/src/gateway/native/live.rs b/src/gateway/native/live.rs new file mode 100644 index 000000000..b4e29f6e7 --- /dev/null +++ b/src/gateway/native/live.rs @@ -0,0 +1,692 @@ +use crate::gateway::delivery::*; +use futures_util::{future::BoxFuture, stream::BoxStream, StreamExt}; +use std::{ + collections::{BTreeMap, BTreeSet, VecDeque}, + sync::{Arc, Mutex, Weak}, + time::{Duration, Instant}, +}; +use tokio::sync::{mpsc, oneshot}; + +pub(super) type LiveSource = BoxStream<'static, Result>; +pub(super) type LiveSourceFactory = + Arc BoxFuture<'static, Result> + Send + Sync>; +#[derive(Clone)] +struct Input { + admission: OriginAdmission, + request: serde_json::Value, + freshness: Option, + source: LiveSourceFactory, +} +struct Consumer { + ticket: LiveTicket, + input: Input, + frames: mpsc::Sender>, + reset: oneshot::Sender<&'static str>, +} +struct Group { + key: LiveKey, + initial: LiveKey, + consumers: BTreeSet, + history: VecDeque>, + complete_history: bool, + driver: Option, +} +impl Drop for Group { + fn drop(&mut self) { + if let Some(driver) = &self.driver { + driver.abort(); + } + } +} +struct State { + registry: LiveRegistry, + groups: BTreeMap, + consumers: BTreeMap, + next: u64, + upstreams: u64, + resets: u64, + frames: u64, + deduplicated: u64, + handoffs: u64, +} +/// Native stream drivers are owned by these groups; removing the last consumer +/// aborts the upstream and releases its socket/stream, including on disconnect. +pub(super) struct NativeLive { + state: Mutex, + limits: LiveLimits, + started: Instant, +} +pub(super) struct LiveLease { + id: u64, + owner: Arc, + frames: mpsc::Receiver>, + reset: oneshot::Receiver<&'static str>, + expiry: u64, + terminal: Option<&'static str>, +} +impl Drop for LiveLease { + fn drop(&mut self) { + self.owner.remove(self.id, "consumer_left"); + } +} +impl LiveLease { + pub(super) async fn next(&mut self) -> Result>, &'static str> { + loop { + let remaining = Duration::from_secs(self.expiry.saturating_sub(super::now())); + if remaining.is_zero() { + return Err("AUTH_EXPIRED"); + } + if let Some(reason) = self.terminal { + if reason != "complete" { + return Err(reason); + } + let frame = self.frames.recv().await; + return if super::now() >= self.expiry { + Err("AUTH_EXPIRED") + } else { + Ok(frame) + }; + } + tokio::select! { biased; + reset = &mut self.reset => { self.terminal = Some(reset.unwrap_or("LIVE_RESET_REQUIRED")); }, + _ = tokio::time::sleep(remaining) => return Err("AUTH_EXPIRED"), + frame = self.frames.recv() => return if super::now() >= self.expiry { Err("AUTH_EXPIRED") } else { Ok(frame) }, + } + } + } + // A reset/expiry interrupts a blocked network queue. Normal completion + // preserves all already-queued frames before the terminal complete packet. + pub(super) async fn interrupted(&mut self) -> &'static str { + let remaining = Duration::from_secs(self.expiry.saturating_sub(super::now())); + if remaining.is_zero() { + return "AUTH_EXPIRED"; + } + if let Some(reason) = self.terminal { + if reason != "complete" { + return reason; + } + tokio::time::sleep(remaining).await; + return "AUTH_EXPIRED"; + } + tokio::select! { + reset = &mut self.reset => { + let reason = reset.unwrap_or("LIVE_RESET_REQUIRED"); self.terminal = Some(reason); + if reason == "complete" { tokio::time::sleep(remaining).await; "AUTH_EXPIRED" } else { reason } + }, + _ = tokio::time::sleep(remaining) => "AUTH_EXPIRED", + } + } +} + +impl NativeLive { + pub(super) fn new(limits: LiveLimits) -> Result, super::GatewayError> { + let registry = + LiveRegistry::new(limits).map_err(|_| super::GatewayError("invalid live limits"))?; + Ok(Arc::new(Self { + state: Mutex::new(State { + registry, + groups: BTreeMap::new(), + consumers: BTreeMap::new(), + next: 0, + upstreams: 0, + resets: 0, + frames: 0, + deduplicated: 0, + handoffs: 0, + }), + limits, + started: Instant::now(), + })) + } + pub(super) fn counts(&self) -> (usize, usize, u64, u64, u64, u64, u64) { + self.state.lock().map_or((0, 0, 0, 0, 0, 0, 0), |s| { + ( + s.groups.len(), + s.consumers.len(), + s.upstreams, + s.resets, + s.frames, + s.deduplicated, + s.handoffs, + ) + }) + } + pub(super) fn join( + self: &Arc, + admission: OriginAdmission, + request: serde_json::Value, + freshness: Option, + source: LiveSourceFactory, + ) -> Result { + let initial = LiveKey::admitted(&admission, &request, freshness.as_ref(), super::now())?; + let input = Input { + admission, + request, + freshness, + source, + }; + let (frames, receiver) = mpsc::channel(self.limits.queue_frames); + let (reset, reset_receiver) = oneshot::channel(); + let mut state = self.state.lock().map_err(|_| DeliveryError::Unavailable)?; + let now = u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX); + state.registry.expire(now); + let expired = state + .groups + .keys() + .filter(|generation| !state.registry.contains_generation(**generation)) + .copied() + .collect::>(); + for generation in expired { + end(&mut state, generation, "LIVE_RESET_REQUIRED"); + } + state.next = state + .next + .checked_add(1) + .ok_or(DeliveryError::Unavailable)?; + let id = state.next; + let existing = state + .groups + .iter() + .find(|(_, group)| { + group.initial.same_initial(&initial) + && group.complete_history + && group.consumers.len() < self.limits.consumers + }) + .map(|(generation, group)| (*generation, group.key.clone())); + let key = existing + .map(|(_, key)| key) + .unwrap_or_else(|| initial.fork(id)); + let (ticket, owner) = state.registry.join(key.clone(), now)?; + let generation = ticket.generation(); + if owner { + state.groups.insert( + generation, + Group { + key, + initial, + consumers: BTreeSet::new(), + history: VecDeque::new(), + complete_history: true, + driver: None, + }, + ); + } + let group = state + .groups + .get_mut(&generation) + .ok_or(DeliveryError::Unavailable)?; + for frame in &group.history { + if !frame.satisfies(&input.admission, input.freshness.as_ref()) { + state.registry.leave(ticket); + return Err(DeliveryError::Pending); + } + frames + .try_send(frame.clone()) + .map_err(|_| DeliveryError::Unavailable)?; + } + group.consumers.insert(id); + let expiry = input.admission.expires_at; + state.consumers.insert( + id, + Consumer { + ticket, + input, + frames, + reset, + }, + ); + drop(state); + if owner { + let weak = Arc::downgrade(self); + let lifetime = self.limits.lifetime_ms; + let driver = tokio::spawn(async move { + let reason = tokio::time::timeout( + Duration::from_millis(lifetime), + drive(weak.clone(), generation), + ) + .await + .unwrap_or("LIVE_RESET_REQUIRED"); + if let Some(owner) = weak.upgrade() { + if let Ok(mut state) = owner.state.lock() { + end(&mut state, generation, reason); + } + } + }); + let handle = driver.abort_handle(); + // No detached owner: Group owns the abort handle, and the driver + // retains only Weak so the coordinator can be dropped cleanly. + if let Ok(mut state) = self.state.lock() { + if let Some(group) = state.groups.get_mut(&generation) { + group.driver = Some(handle); + } else { + handle.abort(); + } + } else { + handle.abort(); + } + } + Ok(LiveLease { + id, + owner: self.clone(), + frames: receiver, + reset: reset_receiver, + expiry, + terminal: None, + }) + } + fn remove(&self, id: u64, reason: &'static str) { + if let Ok(mut state) = self.state.lock() { + remove(&mut state, id, reason); + } + } + fn input(&self, generation: u64) -> Option { + let mut state = self.state.lock().ok()?; + let group = state.groups.get(&generation)?; + let mut input = group + .consumers + .iter() + .filter_map(|id| state.consumers.get(id)) + .filter(|consumer| consumer.input.admission.expires_at > super::now()) + .max_by_key(|consumer| consumer.input.admission.expires_at)? + .input + .clone(); + // Reconnect under a remaining consumer's current credentials. The + // origin handles replay/reset at the last observed proven cursor. + if let Some(frame) = group.history.back() { + if !input.request["extensions"].is_object() { + input.request["extensions"] = serde_json::json!({}); + } + if !input.request["extensions"]["distributed"].is_object() { + input.request["extensions"]["distributed"] = serde_json::json!({}); + } + input.request["extensions"]["distributed"]["resume"] = serde_json::json!({"cursors":frame.payload()["extensions"]["distributed"]["live"]["cursors"]}); + } + state.upstreams = state.upstreams.saturating_add(1); + Some(input) + } + fn emit(&self, generation: u64, input: &Input, payload: serde_json::Value) -> bool { + let frame = match LiveFrame::from_origin( + &input.admission, + payload, + None, + self.limits.frame_bytes, + ) { + Ok(frame) => Arc::new(frame), + Err(_) => { + if let Ok(mut state) = self.state.lock() { + end(&mut state, generation, "LIVE_RESET_REQUIRED"); + } + return false; + } + }; + let Ok(mut state) = self.state.lock() else { + return false; + }; + state.frames = state.frames.saturating_add(1); + let Some(group) = state.groups.get_mut(&generation) else { + return false; + }; + if group + .history + .back() + .is_some_and(|last| last.same_frame(&frame)) + { + state.deduplicated = state.deduplicated.saturating_add(1); + return true; + } + group.history.push_back(frame.clone()); + if group.history.len() > self.limits.history_frames { + group.history.pop_front(); + group.complete_history = false; + } + let ids = group.consumers.iter().copied().collect::>(); + for id in ids { + let Some(consumer) = state.consumers.get(&id) else { + continue; + }; + let reason = if consumer.input.admission.expires_at <= super::now() { + Some("AUTH_EXPIRED") + } else if !frame.satisfies(&consumer.input.admission, consumer.input.freshness.as_ref()) + { + Some("FRESHNESS_PENDING") + } else if consumer.frames.try_send(frame.clone()).is_err() { + Some("LIVE_RESET_REQUIRED") + } else { + None + }; + if let Some(reason) = reason { + remove(&mut state, id, reason); + } + } + // Each replay's own frame is queued first. At equal proven cursor and + // data, future frames can move to an existing operation without a gap. + let Some(group) = state.groups.get(&generation) else { + return false; + }; + let target = state + .groups + .iter() + .find(|(other, target)| { + **other < generation + && target.key.same_operation(&group.key) + && target + .history + .back() + .is_some_and(|head| head.same_cursor(&frame)) + }) + .map(|(id, group)| (*id, group.key.clone())); + if let Some((target, key)) = target { + let ids = group.consumers.iter().copied().collect::>(); + let now = u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX); + for id in ids { + let Ok((ticket, new_owner)) = state.registry.join(key.clone(), now) else { + break; + }; + if new_owner { + state.registry.leave(ticket); + break; + } + let Some(consumer) = state.consumers.get_mut(&id) else { + state.registry.leave(ticket); + continue; + }; + let old = std::mem::replace(&mut consumer.ticket, ticket); + state.registry.leave(old); + if let Some(group) = state.groups.get_mut(&generation) { + group.consumers.remove(&id); + } + if let Some(group) = state.groups.get_mut(&target) { + group.consumers.insert(id); + } + state.handoffs = state.handoffs.saturating_add(1); + } + if state + .groups + .get(&generation) + .is_some_and(|group| group.consumers.is_empty()) + { + state.groups.remove(&generation); + return false; + } + } + true + } +} +fn remove(state: &mut State, id: u64, reason: &'static str) { + let Some(consumer) = state.consumers.remove(&id) else { + return; + }; + let generation = consumer.ticket.generation(); + if reason != "consumer_left" && reason != "complete" { + state.resets = state.resets.saturating_add(1); + } + let _ = consumer.reset.send(reason); + let last = state.registry.leave(consumer.ticket); + if let Some(group) = state.groups.get_mut(&generation) { + group.consumers.remove(&id); + } + if last { + state.groups.remove(&generation); + } +} +fn end(state: &mut State, generation: u64, reason: &'static str) { + let ids = state + .groups + .get(&generation) + .map(|group| group.consumers.iter().copied().collect::>()) + .unwrap_or_default(); + for id in ids { + remove(state, id, reason); + } + state.groups.remove(&generation); +} +async fn drive(owner: Weak, generation: u64) -> &'static str { + loop { + let input = match owner.upgrade().and_then(|owner| owner.input(generation)) { + Some(input) => input, + None => return "AUTH_EXPIRED", + }; + let expiry = Duration::from_secs(input.admission.expires_at.saturating_sub(super::now())); + let run = async { + let mut stream = (input.source)(input.request.clone()).await?; + while let Some(frame) = stream.next().await { + let frame = frame?; + if !owner + .upgrade() + .is_some_and(|owner| owner.emit(generation, &input, frame)) + { + return Err("upstream no longer owned".into()); + } + } + Ok::<(), String>(()) + }; + match tokio::time::timeout(expiry, run).await { + Ok(Ok(())) => return "complete", + Ok(Err(_)) => return "LIVE_RESET_REQUIRED", + Err(_) => continue, // Reauthenticate with a remaining unexpired consumer. + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use futures_util::{FutureExt, StreamExt}; + use std::sync::atomic::{AtomicUsize, Ordering}; + fn request() -> serde_json::Value { + serde_json::json!({"query":"subscription Watch { rows { title } }"}) + } + fn admission(request: &serde_json::Value) -> OriginAdmission { + let identity = OriginIdentity { + application: "app".into(), + endpoint: "origin".into(), + schema_hash: "schema".into(), + protocol_hash: "protocol".into(), + authorization_generation: "policy".into(), + cache_scope: "alice".into(), + }; + OriginAdmission { + key: OperationKey::from_origin(&identity, request).unwrap(), + identity, + operation: "operation".into(), + validator: "v1".into(), + validated_at: super::super::now(), + expires_at: super::super::now() + 30, + policy: SnapshotPolicy::Current, + } + } + fn frame(position: u64, proof: &str) -> serde_json::Value { + serde_json::json!({"data":{"rows":[{"title":"unchanged"}]},"extensions":{"distributed":{ + "protocolVersion":1,"schemaHash":"schema","authorizationGeneration":"policy","cacheScope":"alice","operation":"operation", + "snapshot":{"recordsComplete":true,"indexesComparable":true,"records":[],"indexes":[{"projection":"rows","scopeToken":"scope","position":position.to_string()}],"observations":[proof]}, + "live":{"supported":true,"reset":false,"cursors":[{"projection":"rows","position":position.to_string(),"token":format!("token-{position}")}]} + }}}) + } + struct DropCount(Arc); + impl Drop for DropCount { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + fn source() -> ( + LiveSourceFactory, + mpsc::UnboundedSender, + Arc, + Arc, + ) { + let (sender, receiver) = mpsc::unbounded_channel(); + let receiver = Arc::new(Mutex::new(Some(receiver))); + let calls = Arc::new(AtomicUsize::new(0)); + let dropped = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let drop_count = dropped.clone(); + let source: LiveSourceFactory = Arc::new(move |_| { + let receiver = receiver.lock().unwrap().take(); + let count = count.clone(); + let drop_count = drop_count.clone(); + async move { + let receiver = receiver.ok_or_else(|| "fixture source consumed".to_owned())?; + count.fetch_add(1, Ordering::SeqCst); + let guard = DropCount(drop_count); + Ok(futures_util::stream::unfold( + (receiver, guard), + |(mut receiver, guard)| async move { + receiver + .recv() + .await + .map(|frame| (Ok(frame), (receiver, guard))) + }, + ) + .boxed()) + } + .boxed() + }); + (source, sender, calls, dropped) + } + async fn wait(condition: impl Fn() -> bool) { + tokio::time::timeout(Duration::from_secs(3), async { + while !condition() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + } + #[tokio::test] + async fn hundred_live_leases_preserve_proof_and_last_leave() { + let live = NativeLive::new(LiveLimits::default()).unwrap(); + let request = request(); + let admission = admission(&request); + let (factory, sender, calls, dropped) = source(); + let mut leases = Vec::new(); + for _ in 0..100 { + leases.push( + live.join(admission.clone(), request.clone(), None, factory.clone()) + .unwrap(), + ); + } + assert_eq!((live.counts().0, live.counts().1), (1, 100)); + wait(|| calls.load(Ordering::SeqCst) == 1).await; + sender.send(frame(1, "first-proof")).unwrap(); + for lease in &mut leases { + assert_eq!( + lease.next().await.unwrap().unwrap().payload(), + &frame(1, "first-proof") + ); + } + sender.send(frame(1, "first-proof")).unwrap(); + sender.send(frame(1, "new-confirmation")).unwrap(); + for lease in &mut leases { + assert_eq!( + lease.next().await.unwrap().unwrap().payload(), + &frame(1, "new-confirmation") + ); + } + assert_eq!( + live.counts().5, + 1, + "only a full data-plus-proof duplicate is suppressed" + ); + while leases.len() > 1 { + leases.pop(); + } + assert_eq!((live.counts().0, live.counts().1), (1, 1)); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + leases.clear(); + wait(|| dropped.load(Ordering::SeqCst) == 1).await; + assert_eq!((live.counts().0, live.counts().1), (0, 0)); + } + #[tokio::test] + async fn independent_resume_handoff_keeps_prior_confirmation() { + let live = NativeLive::new(LiveLimits::default()).unwrap(); + let request = request(); + let (first, first_sender, _, first_dropped) = source(); + let mut existing = live + .join(admission(&request), request.clone(), None, first) + .unwrap(); + first_sender.send(frame(1, "existing")).unwrap(); + existing.next().await.unwrap().unwrap(); + let mut replay = request.clone(); + replay["extensions"] = serde_json::json!({"distributed":{"resume":{"cursors":[{"projection":"rows","position":"0","token":"old"}]}}}); + let (second, second_sender, _, second_dropped) = source(); + let mut replaying = live.join(admission(&replay), replay, None, second).unwrap(); + assert_eq!( + live.counts().0, + 2, + "different resume cursor initially replays independently" + ); + second_sender + .send(frame(1, "replayed-command-confirmation")) + .unwrap(); + assert_eq!( + replaying.next().await.unwrap().unwrap().payload(), + &frame(1, "replayed-command-confirmation") + ); + wait(|| live.counts().0 == 1).await; + assert_eq!(live.counts().6, 1); + wait(|| second_dropped.load(Ordering::SeqCst) == 1).await; + first_sender.send(frame(2, "next")).unwrap(); + assert_eq!( + existing.next().await.unwrap().unwrap().payload(), + &frame(2, "next") + ); + assert_eq!( + replaying.next().await.unwrap().unwrap().payload(), + &frame(2, "next") + ); + drop(existing); + assert_eq!(live.counts().1, 1); + assert_eq!(first_dropped.load(Ordering::SeqCst), 0); + drop(replaying); + wait(|| first_dropped.load(Ordering::SeqCst) == 1).await; + } + #[tokio::test] + async fn slow_consumer_gets_explicit_reset_and_releases_origin() { + let live = NativeLive::new(LiveLimits { + queue_frames: 1, + history_frames: 1, + ..Default::default() + }) + .unwrap(); + let request = request(); + let (factory, sender, _, dropped) = source(); + let mut lease = live + .join(admission(&request), request, None, factory) + .unwrap(); + sender.send(frame(1, "one")).unwrap(); + sender.send(frame(2, "two")).unwrap(); + wait(|| live.counts().0 == 0).await; + assert_eq!(lease.next().await.unwrap_err(), "LIVE_RESET_REQUIRED"); + assert_eq!(live.counts().3, 1); + wait(|| dropped.load(Ordering::SeqCst) == 1).await; + } + #[tokio::test] + async fn expired_consumer_does_not_own_remaining_consumers_upstream() { + let live = NativeLive::new(LiveLimits::default()).unwrap(); + let request = request(); + let mut early = admission(&request); + early.expires_at = super::super::now() + 1; + let (first, first_sender, first_calls, first_dropped) = source(); + let mut expires = live.join(early, request.clone(), None, first).unwrap(); + wait(|| first_calls.load(Ordering::SeqCst) == 1).await; + first_sender.send(frame(1, "before-renewal")).unwrap(); + expires.next().await.unwrap(); + let (second, second_sender, second_calls, second_dropped) = source(); + let mut remaining = live + .join(admission(&request), request, None, second) + .unwrap(); + remaining.next().await.unwrap(); + assert_eq!(expires.next().await.unwrap_err(), "AUTH_EXPIRED"); + drop(expires); + wait(|| second_calls.load(Ordering::SeqCst) == 1).await; + wait(|| first_dropped.load(Ordering::SeqCst) == 1).await; + second_sender.send(frame(2, "after-renewal")).unwrap(); + assert_eq!( + remaining.next().await.unwrap().unwrap().payload(), + &frame(2, "after-renewal") + ); + assert_eq!((live.counts().0, live.counts().1), (1, 1)); + drop(remaining); + wait(|| second_dropped.load(Ordering::SeqCst) == 1).await; + } +} diff --git a/src/gateway/native/live_transport.rs b/src/gateway/native/live_transport.rs new file mode 100644 index 000000000..02df27c03 --- /dev/null +++ b/src/gateway/native/live_transport.rs @@ -0,0 +1,676 @@ +use super::{ + graphql::{EmbeddedGraphql, GraphqlBinding, RemoteGraphql}, + live::{LiveSource, LiveSourceFactory}, + proxy, NativeDelivery, NativeInner, RequestContext, +}; +use crate::gateway::{BindingKind, GraphqlCapabilities, GraphqlExecutor}; +use axum::{ + body::Bytes, + extract::ws::{Message, WebSocket}, + http::{header, request::Parts, HeaderMap, HeaderValue, Method}, +}; +use futures_util::{FutureExt, SinkExt, StreamExt}; +use std::{collections::BTreeMap, sync::Arc, time::Duration}; +use tokio::sync::{mpsc, watch}; +use tokio_tungstenite::{ + tungstenite::{protocol::Role, Message as Upstream}, + WebSocketStream, +}; + +type OriginSocket = WebSocketStream; +#[derive(Clone)] +pub(super) struct Execution { + pub binding: GraphqlBinding, + pub inner: Arc, + pub declaration: BindingKind, + pub context: RequestContext, +} +impl Execution { + fn executor(&self) -> &GraphqlExecutor { + let BindingKind::Graphql { executor, .. } = &self.declaration else { + unreachable!() + }; + executor + } + fn capabilities(&self) -> GraphqlCapabilities { + let BindingKind::Graphql { capabilities, .. } = &self.declaration else { + unreachable!() + }; + *capabilities + } + fn source( + &self, + headers: HeaderMap, + query: Option, + init: serde_json::Value, + ) -> LiveSourceFactory { + let execution = self.clone(); + Arc::new(move |mut request: serde_json::Value| { + if let Some(extensions) = request + .get_mut("extensions") + .and_then(serde_json::Value::as_object_mut) + { + extensions.remove("gatewayDelivery"); + } + let execution = execution.clone(); + let headers = headers.clone(); + let init = init.clone(); + let query = query.clone(); + async move { + match &execution.binding { + GraphqlBinding::Embedded(embedded)=>{ + let engine=embedded.engine.as_ref().ok_or_else(||"custom embedded live source is not eligible".to_owned())?; + let (session,principal)=crate::graphql::http::resolve_gateway_ws_identity(engine,&headers,&init).await?.into_parts(); + let mut request:async_graphql::Request=serde_json::from_value(request).map_err(|_|"invalid live request".to_owned())?; + if let Some(principal)=principal {request=request.data(principal);} + Ok(engine.execute_stream(&session,request).map(|response|serde_json::to_value(response).map_err(|_|"invalid origin envelope".into())).boxed()) + } + GraphqlBinding::Remote(remote)=>{ + let GraphqlExecutor::Remote{origin}=execution.executor() else {return Err("invalid origin binding".into())}; + let mut socket=connect(&execution.inner,origin,remote,&execution.context,headers,query.as_deref(),&init).await?; + socket.send(Upstream::Text(serde_json::json!({"id":"upstream","type":"subscribe","payload":request}).to_string().into())).await.map_err(|_|"upstream subscribe failed")?; + Ok(origin_stream(socket)) + } + } + }.boxed() + }) + } +} +async fn connect( + inner: &Arc, + origin: &str, + remote: &RemoteGraphql, + context: &RequestContext, + mut headers: HeaderMap, + query: Option<&str>, + init: &serde_json::Value, +) -> Result { + let path = remote.live_path.as_deref().ok_or("live endpoint missing")?; + proxy::prepare_headers(&mut headers, inner, context, true) + .map_err(|_| "invalid live headers")?; + headers.remove(header::CONTENT_LENGTH); + headers.remove(header::CONTENT_TYPE); + let key = tokio_tungstenite::tungstenite::handshake::client::generate_key(); + headers.insert( + header::SEC_WEBSOCKET_KEY, + HeaderValue::from_str(&key).map_err(|_| "invalid websocket key")?, + ); + headers.insert( + header::SEC_WEBSOCKET_VERSION, + HeaderValue::from_static("13"), + ); + headers.insert( + header::SEC_WEBSOCKET_PROTOCOL, + HeaderValue::from_static("graphql-transport-ws"), + ); + proxy::add_hop(&mut headers, inner).map_err(|_| "gateway loop")?; + let url = format!( + "{}{path}{}", + origin.trim_end_matches('/'), + query.map(|q| format!("?{q}")).unwrap_or_default() + ); + let response = tokio::time::timeout( + inner.options.limits.response_header_timeout, + inner.client.get(url).headers(headers).send(), + ) + .await + .map_err(|_| "upstream handshake timed out")? + .map_err(|_| "upstream handshake failed")?; + if response.status() == axum::http::StatusCode::UNAUTHORIZED { + return Err("AUTH_EXPIRED".into()); + } + if response.status() != axum::http::StatusCode::SWITCHING_PROTOCOLS + || response + .headers() + .get(header::SEC_WEBSOCKET_ACCEPT) + .and_then(|v| v.to_str().ok()) + != Some( + tokio_tungstenite::tungstenite::handshake::derive_accept_key(key.as_bytes()) + .as_str(), + ) + || response + .headers() + .get(header::SEC_WEBSOCKET_PROTOCOL) + .and_then(|v| v.to_str().ok()) + != Some("graphql-transport-ws") + { + return Err("invalid upstream handshake".into()); + } + let socket = response + .upgrade() + .await + .map_err(|_| "upstream upgrade failed")?; + let mut socket = WebSocketStream::from_raw_socket( + socket, + Role::Client, + Some( + tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default() + .max_message_size(Some(inner.options.limits.request_body_bytes)), + ), + ) + .await; + socket + .send(Upstream::Text( + serde_json::json!({"type":"connection_init","payload":init}) + .to_string() + .into(), + )) + .await + .map_err(|_| "upstream init failed")?; + tokio::time::timeout(inner.options.limits.response_header_timeout, async { + loop { + match socket.next().await { + Some(Ok(Upstream::Text(text))) => { + let value: serde_json::Value = + serde_json::from_str(&text).map_err(|_| "invalid upstream init")?; + if value["type"] == "connection_ack" { + return Ok(()); + } + if value["type"] == "connection_error" { + return Err("AUTH_EXPIRED"); + } + } + Some(Ok(Upstream::Ping(data))) => { + socket + .send(Upstream::Pong(data)) + .await + .map_err(|_| "upstream ping failed")?; + } + _ => return Err("AUTH_EXPIRED"), + } + } + }) + .await + .map_err(|_| "upstream admission timed out")??; + Ok(socket) +} +fn origin_stream(socket: OriginSocket) -> LiveSource { + futures_util::stream::unfold(socket, |mut socket| async move { + loop { + match socket.next().await { + Some(Ok(Upstream::Text(text))) => { + let value = match serde_json::from_str::(&text) { + Ok(value) => value, + Err(_) => return Some((Err("invalid upstream frame".into()), socket)), + }; + match value["type"].as_str() { + Some("next") if value["id"] == "upstream" => { + return Some((Ok(value["payload"].clone()), socket)) + } + Some("complete") if value["id"] == "upstream" => return None, + Some("error") => { + return Some((Err("upstream operation failed".into()), socket)) + } + Some("ping") => { + let _ = socket + .send(Upstream::Text( + serde_json::json!({"type":"pong","payload":value["payload"]}) + .to_string() + .into(), + )) + .await; + } + _ => {} + } + } + Some(Ok(Upstream::Ping(data))) => { + let _ = socket.send(Upstream::Pong(data)).await; + } + Some(Ok(Upstream::Pong(_))) => {} + Some(Ok(Upstream::Close(_))) | None => { + return Some(( + Err("upstream disconnected before operation completion".into()), + socket, + )); + } + _ => return Some((Err("upstream stream failed".into()), socket)), + } + } + }) + .boxed() +} + +pub(super) async fn remote( + mut client: WebSocket, + mut origin: OriginSocket, + execution: Execution, + parts: Parts, + coordinator: Arc, + protocol: &'static str, +) { + let init = match initial_message( + &mut client, + execution.inner.options.limits.response_header_timeout, + ) + .await + { + Some(init) => init, + None => return, + }; + if origin + .send(Upstream::Text( + serde_json::json!({"type":"connection_init","payload":init}) + .to_string() + .into(), + )) + .await + .is_err() + { + return; + } + let ack = tokio::time::timeout( + execution.inner.options.limits.response_header_timeout, + async { + loop { + match origin.next().await { + Some(Ok(Upstream::Text(text))) => { + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + if value["type"] == "connection_ack" { + return Some(text.to_string()); + } + if value["type"] == "connection_error" { + let _ = client.send(Message::Text(text.to_string().into())).await; + return None; + } + } + Some(Ok(Upstream::Ping(data))) => { + let _ = origin.send(Upstream::Pong(data)).await; + } + Some(Ok(Upstream::Close(frame))) => { + let _ = client + .send(Message::Close(frame.map(|frame| { + axum::extract::ws::CloseFrame { + code: frame.code.into(), + reason: frame.reason.to_string().into(), + } + }))) + .await; + return None; + } + _ => return None, + } + } + }, + ) + .await + .ok() + .flatten(); + let Some(ack) = ack else { + return; + }; + if client.send(Message::Text(ack.into())).await.is_err() { + return; + } + // The temporary per-consumer origin connection authenticated connection_init. + // It owns no subscription and is closed before shared operation admission. + let _ = origin.close(None).await; + drop(origin); + client_loop(client, execution, parts, coordinator, protocol, init).await; +} +pub(super) async fn embedded( + mut client: WebSocket, + embedded: EmbeddedGraphql, + execution: Execution, + parts: Parts, + coordinator: Arc, + protocol: &'static str, +) { + let init = match initial_message( + &mut client, + execution.inner.options.limits.response_header_timeout, + ) + .await + { + Some(init) => init, + None => return, + }; + let Some(engine) = &embedded.engine else { + return; + }; + if crate::graphql::http::resolve_gateway_ws_identity(engine, &parts.headers, &init) + .await + .is_err() + { + let _ = client + .send(Message::Close(Some(axum::extract::ws::CloseFrame { + code: 4401, + reason: "unauthorized".into(), + }))) + .await; + return; + } + if client + .send(Message::Text( + serde_json::json!({"type":"connection_ack"}) + .to_string() + .into(), + )) + .await + .is_err() + { + return; + } + client_loop(client, execution, parts, coordinator, protocol, init).await; +} +async fn initial_message(client: &mut WebSocket, timeout: Duration) -> Option { + let message = tokio::time::timeout(timeout, client.recv()) + .await + .ok()?? + .ok()?; + let Message::Text(text) = message else { + return None; + }; + if text.len() > 65536 { + return None; + } + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + (value["type"] == "connection_init").then(|| { + value + .get("payload") + .cloned() + .unwrap_or_else(|| serde_json::json!({})) + }) +} +struct Operation(tokio::task::JoinHandle<()>); +impl Drop for Operation { + fn drop(&mut self) { + self.0.abort(); + } +} +fn packet(id: &str, kind: &str, payload: serde_json::Value) -> serde_json::Value { + serde_json::json!({"id":id,"type":kind,"payload":payload}) +} +fn failure(id: &str, code: &str) -> serde_json::Value { + packet( + id, + "error", + serde_json::json!([{"message":code,"extensions":{"code":code}}]), + ) +} +async fn client_loop( + client: WebSocket, + execution: Execution, + mut parts: Parts, + coordinator: Arc, + protocol: &'static str, + init: serde_json::Value, +) { + let source = execution.source( + parts.headers.clone(), + parts.uri.query().map(str::to_owned), + init.clone(), + ); + parts.method = Method::POST; + proxy::strip_hop_headers(&mut parts.headers); + let parts = Arc::new(parts); + let (mut sink, mut stream) = client.split(); + let (out, mut output) = mpsc::channel::(32); + let (close, mut closed) = watch::channel(false); + let mut operations = BTreeMap::::new(); + let mut close_frame = Some(axum::extract::ws::CloseFrame { + code: 1013, + reason: "LIVE_RESET_REQUIRED".into(), + }); + loop { + tokio::select! {biased; + _=closed.changed()=>break, + next=output.recv()=>{ + let Some(value)=next else {break;}; + let id=value["id"].as_str().map(str::to_owned); + let terminal=matches!(value["type"].as_str(),Some("complete"|"error")); + let sending=sink.send(Message::Text(value.to_string().into())); + tokio::select! { _=closed.changed()=>break, sent=tokio::time::timeout(execution.inner.options.limits.read_timeout,sending)=>{if !matches!(sent,Ok(Ok(()))){break;}} } + if terminal {if let Some(id)=id {operations.remove(&id);}} + } + next=stream.next()=>{ + let Some(Ok(message))=next else {break;}; + match message { + Message::Text(text)=>{ + let Ok(value)=serde_json::from_str::(&text) else {break;}; + match value["type"].as_str() { + Some(kind @ ("subscribe"|"start")) if kind == if protocol == "graphql-ws" {"start"} else {"subscribe"}=>{ + let Some(id)=value["id"].as_str() else {break;}; + if id.is_empty()||id.len()>256||operations.len()>=128||operations.contains_key(id){break;} + if let Err(error)=crate::gateway::graphql::admit_request(&value["payload"],execution.capabilities()) {let _=out.try_send(packet(id,if protocol=="graphql-ws"{"data"}else{"next"},error.envelope()));let _=out.try_send(serde_json::json!({"id":id,"type":"complete"}));continue;} + let id=id.to_owned();let payload=value["payload"].clone();let execution=execution.clone();let parts=parts.clone();let coordinator=coordinator.clone();let source=source.clone();let out=out.clone();let close=close.clone();let init=init.clone();let task_id=id.clone(); + operations.insert(id,Operation(tokio::spawn(async move {operation(task_id,payload,execution,parts,coordinator,source,out,close,protocol,init).await;}))); + } + Some(kind @ ("complete"|"stop")) if kind == if protocol == "graphql-ws" {"stop"} else {"complete"}=>{if let Some(id)=value["id"].as_str(){operations.remove(id);}} + Some("ping")=>{if !matches!(tokio::time::timeout(execution.inner.options.limits.read_timeout,sink.send(Message::Text(serde_json::json!({"type":"pong","payload":value["payload"]}).to_string().into()))).await,Ok(Ok(()))){break;}} + Some("pong")=>{}, + Some("connection_terminate") if protocol == "graphql-ws"=>{close_frame=Some(axum::extract::ws::CloseFrame{code:1000,reason:"".into()});break;}, + _=>break, + } + } + Message::Ping(data)=>{if !matches!(tokio::time::timeout(execution.inner.options.limits.read_timeout,sink.send(Message::Pong(data))).await,Ok(Ok(()))){break;}}, + Message::Pong(_)=>{},Message::Close(frame)=>{close_frame=frame;break;},_=>break, + } + } + } + } + drop(operations); + let _ = tokio::time::timeout( + Duration::from_millis(100), + sink.send(Message::Close(close_frame)), + ) + .await; +} +#[allow(clippy::too_many_arguments)] +async fn operation( + id: String, + mut payload: serde_json::Value, + execution: Execution, + parts: Arc, + coordinator: Arc, + source: LiveSourceFactory, + out: mpsc::Sender, + close: watch::Sender, + protocol: &str, + init: serde_json::Value, +) { + let next = if protocol == "graphql-ws" { + "data" + } else { + "next" + }; + if !payload["extensions"].is_object() { + payload["extensions"] = serde_json::json!({}); + } + payload["extensions"]["gatewayDelivery"] = + serde_json::json!({"action":"execute","connectionInit":init}); + let kind = crate::gateway::graphql::operation_kind( + payload["query"].as_str().unwrap_or(""), + payload["operationName"].as_str(), + ); + if kind != Ok(crate::gateway::graphql::OperationKind::Subscription) { + let request = super::delivery::request(&parts, payload); + let result = execution + .binding + .execute_operation( + &execution.inner, + &execution.declaration, + execution.context, + request, + ) + .await; + let value = match axum::body::to_bytes( + result.into_body(), + execution.inner.options.limits.request_body_bytes, + ) + .await + { + Ok(body) => serde_json::from_slice(&body).unwrap_or_else( + |_| serde_json::json!({"errors":[{"message":"origin unavailable"}]}), + ), + Err(_) => serde_json::json!({"errors":[{"message":"origin unavailable"}]}), + }; + if out.send(packet(&id, next, value)).await.is_ok() { + let _ = out + .send(serde_json::json!({"id":id,"type":"complete"})) + .await; + } + return; + } + let freshness = match payload["extensions"].get("gatewayFreshness") { + Some(value) => match crate::gateway::delivery::FreshnessContext::parse(value) { + Ok(value) => Some(value), + Err(_) => { + let _ = out.send(failure(&id, "FRESHNESS_SCOPE_CHANGED")).await; + return; + } + }, + None => None, + }; + let admission = super::delivery::validate( + &execution.binding, + &execution.inner, + execution.executor(), + &execution.context, + &parts, + &payload, + ) + .await; + match admission { + super::delivery::AdmissionResult::Eligible(admission) => { + let Some(live) = &coordinator.live else { + return; + }; + let mut lease = match live.join(admission, payload, freshness, source) { + Ok(lease) => lease, + Err(_) => { + let _ = out.send(failure(&id, "LIVE_RESET_REQUIRED")).await; + return; + } + }; + loop { + match lease.next().await { + Ok(Some(frame)) => { + let message = packet(&id, next, frame.payload().clone()); + tokio::select! { + sent=out.send(message)=>{if sent.is_err(){break;}}, + reason=lease.interrupted()=>{let _=out.try_send(failure(&id,reason));let _=close.send(true);break;} + } + } + Ok(None) => { + let _ = out + .send(serde_json::json!({"id":id,"type":"complete"})) + .await; + break; + } + Err(reason) => { + if out.try_send(failure(&id, reason)).is_err() { + let _ = close.send(true); + } + break; + } + } + } + } + super::delivery::AdmissionResult::Bypass => match source(payload).await { + Ok(mut stream) => { + while let Some(result) = stream.next().await { + match result { + Ok(payload) => { + if out.send(packet(&id, next, payload)).await.is_err() { + return; + } + } + Err(_) => { + let _ = out.send(failure(&id, "LIVE_RESET_REQUIRED")).await; + return; + } + } + } + let _ = out + .send(serde_json::json!({"id":id,"type":"complete"})) + .await; + } + Err(_) => { + let _ = out.send(failure(&id, "LIVE_RESET_REQUIRED")).await; + } + }, + super::delivery::AdmissionResult::Error(response) => { + let bytes = axum::body::to_bytes(response.into_body(), 65536) + .await + .unwrap_or_else(|_| Bytes::new()); + let value = serde_json::from_slice(&bytes).unwrap_or_else( + |_| serde_json::json!({"errors":[{"message":"origin unavailable"}]}), + ); + let _ = out.send(packet(&id, next, value)).await; + let _ = out + .send(serde_json::json!({"id":id,"type":"complete"})) + .await; + } + } +} + +pub(super) async fn upgrade_embedded( + execution: Execution, + request: axum::http::Request, + embedded: EmbeddedGraphql, + coordinator: Arc, +) -> axum::response::Response { + use axum::{ + extract::{ws::WebSocketUpgrade, FromRequestParts}, + response::IntoResponse, + }; + let permit = match execution.inner.permits.clone().try_acquire_owned() { + Ok(permit) => permit, + Err(_) => return super::response(axum::http::StatusCode::SERVICE_UNAVAILABLE), + }; + let (mut parts, _) = request.into_parts(); + let offered = parts + .headers + .get(header::SEC_WEBSOCKET_PROTOCOL) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let protocol = if offered + .split(',') + .any(|p| p.trim() == "graphql-transport-ws") + { + "graphql-transport-ws" + } else if offered.split(',').any(|p| p.trim() == "graphql-ws") { + "graphql-ws" + } else { + return super::response(axum::http::StatusCode::BAD_REQUEST); + }; + let upgrade = match WebSocketUpgrade::from_request_parts(&mut parts, &()).await { + Ok(upgrade) => upgrade, + Err(error) => return error.into_response(), + }; + if proxy::prepare_headers( + &mut parts.headers, + &execution.inner, + &execution.context, + false, + ) + .is_err() + { + return super::response(axum::http::StatusCode::BAD_REQUEST); + } + let lifetime = execution.context.identity().map_or( + execution.inner.options.limits.upgrade_lifetime, + |id| { + execution + .inner + .options + .limits + .upgrade_lifetime + .min(Duration::from_secs( + id.expires_at().saturating_sub(super::now()), + )) + }, + ); + upgrade + .protocols([protocol]) + .max_message_size(execution.inner.options.limits.request_body_bytes) + .on_upgrade(move |socket| async move { + let _permit = permit; + let _ = tokio::time::timeout( + lifetime, + self::embedded(socket, embedded, execution, parts, coordinator, protocol), + ) + .await; + }) + .into_response() +} diff --git a/src/gateway/native/mod.rs b/src/gateway/native/mod.rs index f283ff5f4..bbb0c7481 100644 --- a/src/gateway/native/mod.rs +++ b/src/gateway/native/mod.rs @@ -460,3 +460,9 @@ pub use delivery::{NativeDelivery, NativeDeliveryOptions}; #[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] mod flight; + +#[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] +mod live; + +#[cfg(all(feature = "gateway-graphql-native", feature = "gateway-delivery"))] +mod live_transport; diff --git a/src/graphql/engine/delivery.rs b/src/graphql/engine/delivery.rs index 63607f028..e70fcb24b 100644 --- a/src/graphql/engine/delivery.rs +++ b/src/graphql/engine/delivery.rs @@ -29,6 +29,11 @@ fn ineligible() -> Response { ) } impl GraphqlEngine { + /// Active origin live-query producers for delivery diagnostics. + pub fn live_subscriber_count(&self) -> usize { + self.inner.change_hub.subscriber_count() + } + pub(super) fn enable_delivery_capture( &self, session: &Session, @@ -60,11 +65,11 @@ impl GraphqlEngine { .map_err(|_| ()) } pub(super) async fn validate_delivery(&self, session: &Session, request: Request) -> Response { - if operation_kind(&request.query, request.operation_name.as_deref()) - != Ok(OperationKind::Query) - { - return ineligible(); - } + let live = match operation_kind(&request.query, request.operation_name.as_deref()) { + Ok(OperationKind::Query) => false, + Ok(OperationKind::Subscription) => true, + _ => return ineligible(), + }; let Some(store) = &self.inner.gateway_versions else { return ineligible(); }; @@ -98,22 +103,27 @@ impl GraphqlEngine { .get(&TypeId::of::()) .and_then(|p| p.downcast_ref::()) .and_then(VerifiedPrincipal::expires_at) - .unwrap_or(now.saturating_add(30)); + .unwrap_or(now.saturating_add(if live { 3600 } else { 30 })); if expiry <= now { return unavailable(); } let operation = operation_fingerprint(&request.query); let policy = store.policy(&request.query, request.operation_name.as_deref()); let captured = PlanCapture::default(); - let response = schema - .execute( - request - .data(session.clone()) - .data(authority) - .data(Arc::clone(&self.inner)) - .data(captured.clone()), - ) - .await; + let request = request + .data(session.clone()) + .data(authority) + .data(Arc::clone(&self.inner)) + .data(captured.clone()); + let response = if live { + schema + .execute_stream(request) + .next() + .await + .unwrap_or_else(ineligible) + } else { + schema.execute(request).await + }; // Schema validation and normal compiler authorization still run. Only // the private capture sentinel may replace SQL; unknown/custom fields, // cell reads and multi-root documents never acquire cache eligibility. diff --git a/src/graphql/http.rs b/src/graphql/http.rs index 602e9ff40..91eb0f583 100644 --- a/src/graphql/http.rs +++ b/src/graphql/http.rs @@ -325,6 +325,56 @@ fn lifecycle_reloading_response() -> Response { .into_response() } +// Gateway-delivered WS operations carry the original connection_init payload. +// Only the origin's existing credential parser/validator resolves authority; +// the gateway neither decodes roles nor fabricates a provider identity. +async fn resolve_http_identity( + engine: &GraphqlEngine, + headers: &HeaderMap, + request: &Request, +) -> Result { + #[cfg(feature = "gateway-delivery")] + if let Some(init) = request + .extensions + .get("gatewayDelivery") + .and_then(|value| serde_json::to_value(value).ok()) + .and_then(|value| value.get("connectionInit").cloned()) + { + return resolve_gateway_ws_identity(engine, headers, &init) + .await + .map_err(|_| AuthError::Unauthorized); + } + let _ = request; + resolve_identity_with_validator( + headers, + engine.identity_config(), + engine.identity_validator(), + ) + .await +} +#[cfg(feature = "gateway-delivery")] +pub(crate) async fn resolve_gateway_ws_identity( + engine: &GraphqlEngine, + headers: &HeaderMap, + init: &serde_json::Value, +) -> Result { + let base = match engine.identity_config().mode { + IdentityMode::OidcBearer | IdentityMode::Hybrid => Session::new(), + _ => { + resolve_identity_with_validator( + headers, + engine.identity_config(), + engine.identity_validator(), + ) + .await + .map_err(|_| "unauthorized".to_owned())? + .into_parts() + .0 + } + }; + resolve_ws_identity(engine, headers, base, init).await +} + async fn graphql_handler( State(engine): State>, headers: axum::http::HeaderMap, @@ -339,13 +389,7 @@ async fn graphql_handler( { return lifecycle_reloading_response(); } - let identity = match resolve_identity_with_validator( - &headers, - engine.identity_config(), - engine.identity_validator(), - ) - .await - { + let identity = match resolve_http_identity(&engine, &headers, &request).await { Ok(identity) => identity, Err(AuthError::Unauthorized) => return unauthorized_response(), }; @@ -371,13 +415,7 @@ async fn graphql_handler_with_service( { return lifecycle_reloading_response(); } - let identity = match resolve_identity_with_validator( - &headers, - state.engine.identity_config(), - state.engine.identity_validator(), - ) - .await - { + let identity = match resolve_http_identity(&state.engine, &headers, &request).await { Ok(identity) => identity, Err(AuthError::Unauthorized) => return unauthorized_response(), }; @@ -411,13 +449,7 @@ pub async fn microsvc_graphql_handler( let engine = service .graphql_engine() .expect("graphql route mounted without engine"); - let identity = match resolve_identity_with_validator( - &headers, - engine.identity_config(), - engine.identity_validator(), - ) - .await - { + let identity = match resolve_http_identity(&engine, &headers, &request).await { Ok(identity) => identity, Err(AuthError::Unauthorized) => return unauthorized_response(), }; diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 680765448..090bbd2e2 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -270,6 +270,8 @@ pub fn build_role_schema( .unwrap_or_else(Session::new); let authority = ctx.data_opt::().cloned(); let protocol = ctx.data_opt::().cloned(); + #[cfg(feature = "gateway-delivery")] + let captured = ctx.data_opt::().cloned(); let selection = compile::selection_from_field(ctx.field()); SubscriptionFieldFuture::new(async move { let inner = inner.ok_or_else(|| { @@ -280,6 +282,31 @@ pub fn build_role_schema( &session, &inner.anonymous_role, ); + #[cfg(feature = "gateway-delivery")] + if let Some(captured) = captured { + let plan = compile::compile_query( + &inner, + &session, + &role, + &model, + compile::RootKind::List, + &selection, + ) + .map_err(async_graphql::Error::new)?; + if let compile::QueryPlan::Sql(plan) = plan { + captured + .0 + .lock() + .map_err(|_| { + async_graphql::Error::new("plan capture unavailable") + })? + .push(plan); + return Err(async_graphql::Error::new(super::delivery::CAPTURED)); + } + return Err(async_graphql::Error::new( + "query is ineligible for delivery reuse", + )); + } let stream = super::subscribe::live_query_stream( inner, session, role, model, selection, protocol, ) diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index 39cf493ce..e87a71b20 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -35,6 +35,11 @@ impl ChangeHub { Self { tx } } + /// Active origin live readers, excluding the external invalidation forwarder. + pub fn subscriber_count(&self) -> usize { + self.tx.receiver_count() + } + pub fn subscribe(&self) -> broadcast::Receiver { self.tx.subscribe() } @@ -126,15 +131,11 @@ pub(crate) async fn live_query_stream( tokio::spawn(async move { // 1) Initial execution + yield - let mut initial = match execute_list( - &inner, - &role, - &plan, - protocol.as_ref(), - requested_live_resume, - ) - .await - { + let initial_result = tokio::select! { + _ = tx.closed() => return, + result = execute_list(&inner, &role, &plan, protocol.as_ref(), requested_live_resume) => result, + }; + let mut initial = match initial_result { Ok(executed) => executed, Err(e) => { let _ = tx.send(Err(async_graphql::Error::new(e))).await; @@ -153,7 +154,10 @@ pub(crate) async fn live_query_stream( // 2) Change loop: dirty → debounce → re-exec → hash-gate → yield loop { - let change = match change_rx.recv().await { + let change = match tokio::select! { + _ = tx.closed() => break, + change = change_rx.recv() => change, + } { Ok(c) => c, Err(broadcast::error::RecvError::Lagged(_)) => ReadModelChange { tables: BTreeSet::new(), @@ -166,7 +170,10 @@ pub(crate) async fn live_query_stream( } // Debounce / coalesce - tokio::time::sleep(debounce).await; + tokio::select! { + _ = tx.closed() => break, + _ = tokio::time::sleep(debounce) => {}, + } loop { match change_rx.try_recv() { Ok(more) => { @@ -179,15 +186,11 @@ pub(crate) async fn live_query_stream( } } - match execute_list( - &inner, - &role, - &plan, - protocol.as_ref(), - next_live_resume.clone(), - ) - .await - { + let refreshed = tokio::select! { + _ = tx.closed() => break, + result = execute_list(&inner, &role, &plan, protocol.as_ref(), next_live_resume.clone()) => result, + }; + match refreshed { Ok(mut executed) => { // Advance the private replay cursor even when a redundant // execution is hash-gated. Protocol frame metadata is diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs index 073a3ba44..be8363903 100644 --- a/tests/edge_query_delivery.rs +++ b/tests/edge_query_delivery.rs @@ -342,3 +342,62 @@ fn flight_admission_limits_freshness_and_generation_fences() { assert!(registry.leave(new)); assert!(registry.is_empty()); } + +#[test] +fn live_scope_replay_and_proof_sensitive_frames() { + let request = json!({"query":"subscription { todos { title } }"}); + let mut admitted = admission("v1"); + admitted.key = OperationKey::from_origin(&admitted.identity, &request).unwrap(); + let key = LiveKey::admitted(&admitted, &request, None, 100).unwrap(); + let mut resumed = request.clone(); + resumed["extensions"] = + json!({"distributed":{"resume":[{"projection":"todos","position":"1","token":"cursor"}]}}); + let mut replay = admitted.clone(); + replay.key = OperationKey::from_origin(&replay.identity, &resumed).unwrap(); + let replay_key = LiveKey::admitted(&replay, &resumed, None, 100).unwrap(); + assert!(key.same_operation(&replay_key)); + assert!(!key.same_initial(&replay_key)); + for changed in ["subject", "policy"] { + let mut other = admitted.clone(); + if changed == "subject" { + other.identity.cache_scope = "bob".into(); + } else { + other.identity.authorization_generation = "policy-2".into(); + } + other.key = OperationKey::from_origin(&other.identity, &request).unwrap(); + assert!(!key.same_operation(&LiveKey::admitted(&other, &request, None, 100).unwrap())); + } + assert!(LiveKey::admitted(&admitted, &request, None, 200).is_err()); + assert!(LiveKey::admitted( + &admission("v1"), + &json!({"query":"{ todos { title } }"}), + None, + 100 + ) + .is_err()); + let mut payload: serde_json::Value = serde_json::from_slice(&snapshot(&admitted).body).unwrap(); + payload["extensions"]["distributed"]["live"] = json!({"supported":true,"cursors":[{"projection":"todos","position":"2","token":"cursor"}]}); + let first = LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap(); + assert!( + first.same_frame(&LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap()) + ); + payload["extensions"]["distributed"]["observations"] = json!([{"commandId":"confirmed"}]); + let proof = LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap(); + assert!( + !first.same_frame(&proof), + "equal data with new evidence must be delivered" + ); + assert!(first.same_cursor(&proof)); + payload["data"] = json!({"todos":[{"title":"external write"}]}); + let changed = LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap(); + assert!( + !first.same_cursor(&changed), + "same projector cursor does not cover external writes" + ); + payload["extensions"]["distributed"]["live"]["supported"] = false.into(); + let unsupported = LiveFrame::from_origin(&admitted, payload, None, 4096).unwrap(); + assert!(!unsupported.same_cursor(&unsupported)); + let mut stronger = context(); + stronger.observe([index("scope", "3")]).unwrap(); + assert!(!first.satisfies(&admitted, Some(&stronger))); +} diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 830e9c9c3..fc0a16e23 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -2101,3 +2101,304 @@ async fn hundred_reads_one_execution_with_cache_disabled() { assert_eq!(store.metrics().result_executions, 5); assert_eq!(delivery.flight_counts(), (0, 0)); } + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +#[tokio::test] +async fn hundred_subscribers_one_upstream_over_embedded_and_remote_websockets() { + use axum::Router; + use distributed::gateway::{delivery::LiveLimits, native::*, *}; + use distributed::graphql::{delivery::GatewayVersionStore, IdentityConfig, OidcConfig}; + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + use rsa::{pkcs1::EncodeRsaPrivateKey, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey}; + let private = RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap(); + let public = RsaPublicKey::from(&private); + let encoding = EncodingKey::from_rsa_pem( + private + .to_pkcs1_pem(rsa::pkcs8::LineEnding::LF) + .unwrap() + .as_bytes(), + ) + .unwrap(); + let jwks=json!({"keys":[{"kty":"RSA","kid":"live-test","alg":"RS256","use":"sig", + "n":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.n().to_bytes_be()),"e":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.e().to_bytes_be())}]}).to_string(); + let token = |subject: &str| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("live-test".into()); + encode(&header,&json!({"iss":"https://live-fixture.invalid","aud":"live-fixture","sub":subject,"iat":now-1,"nbf":now-1,"exp":now+3600,"roles":["user"]}),&encoding).unwrap() + }; + struct Server { + origin: String, + task: tokio::task::JoinHandle<()>, + } + impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } + } + async fn serve(router: Router) -> Server { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + Server { + origin, + task: tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }), + } + } + type Socket = tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >; + async fn connect(origin: &str, token: &str, legacy: bool) -> Socket { + let mut request = format!("{}/graphql/ws", origin.replace("http:", "ws:")) + .into_client_request() + .unwrap(); + request.headers_mut().insert( + "sec-websocket-protocol", + if legacy { + "graphql-ws" + } else { + "graphql-transport-ws" + } + .parse() + .unwrap(), + ); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + socket.send(WsMessage::Text(json!({"type":"connection_init","payload":{"authorization":format!("Bearer {token}")}}).to_string().into())).await.unwrap(); + let ack = tokio::time::timeout(Duration::from_secs(10), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!( + matches!(ack,WsMessage::Text(ref text) if serde_json::from_str::(text).unwrap()["type"]=="connection_ack"), + "{ack:?}" + ); + socket + } + async fn next(socket: &mut Socket, id: &str, title: &str) -> Value { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let message = socket.next().await.unwrap().unwrap(); + if let WsMessage::Text(text) = message { + let value: Value = serde_json::from_str(&text).unwrap(); + if matches!(value["type"].as_str(), Some("next" | "data")) { + assert_eq!(value["id"], id); + assert!(value["payload"].get("errors").is_none(), "{value}"); + if value["payload"]["data"]["causal_query_views"][0]["title"] == title { + return value["payload"].clone(); + } + } + } + } + }) + .await + .expect("matching full live frame") + } + for remote in [false, true] { + eprintln!( + "shared live transport: {}", + if remote { "remote" } else { "embedded" } + ); + let fixture = protocol_fixture_with_retention(10).await; + let versions = GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()), + "live-fixture", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let oidc = OidcConfig::new("https://live-fixture.invalid", "live-fixture") + .with_static_jwks(jwks.clone()) + .engine_roles(&["user"]); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .anonymous_role("user") + .identity(IdentityConfig::oidc_bearer(oidc)) + .model::( + ModelPermissions::new().grant("user", read().all_columns()), + ) + .client_projectors([projector()]) + .change_stream(fixture.repository.read_model_changes()) + .gateway_versions(versions.clone()) + .build() + .unwrap(), + ); + let caps = GraphqlCapabilities { + queries: true, + live: true, + ..Default::default() + }; + let origin = serve(distributed::graphql::graphql_router_composed( + engine.clone(), + None, + None, + )) + .await; + let executor = if remote { + GraphqlExecutor::Remote { + origin: origin.origin.clone(), + } + } else { + GraphqlExecutor::Embedded + }; + let binding = if remote { + GraphqlBinding::Remote(RemoteGraphql::default()) + } else { + GraphqlBinding::Embedded(EmbeddedGraphql::new(engine.clone(), None, caps).unwrap()) + }; + let delivery = Arc::new(NativeDelivery::live(LiveLimits::default()).unwrap()); + let config = GatewayConfig { + bindings: vec![Binding::new( + "api", + BindingKind::Graphql { + executor, + capabilities: caps, + delivery: DeliveryCapabilities { + live_sharing: true, + ..Default::default() + }, + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "api")], + } + .build() + .unwrap(); + let gateway = serve( + NativeGateway::new( + config, + NativeOptions::new("http://public.invalid"), + [( + "api".into(), + NativeBinding::GraphqlWithDelivery(binding, delivery.clone()), + )], + NativeAuth::anonymous(), + ) + .unwrap() + .router(), + ) + .await; + let alice = token("alice"); + let bob = token("bob"); + let mut sockets = futures_util::future::join_all( + (0..100).map(|_| connect(&gateway.origin, &alice, false)), + ) + .await; + for (n, socket) in sockets.iter_mut().enumerate() { + socket.send(WsMessage::Text(json!({"id":format!("consumer-{n}"),"type":"subscribe","payload":{"query":LIVE_SUBSCRIPTION}}).to_string().into())).await.unwrap(); + } + let mut first = None; + for (n, socket) in sockets.iter_mut().enumerate() { + let payload = next(socket, &format!("consumer-{n}"), "causal row").await; + if let Some(first) = &first { + assert_eq!(&payload, first); + } else { + first = Some(payload); + } + } + assert_eq!( + (delivery.live_counts().0, delivery.live_counts().1), + (1, 100) + ); + assert_eq!(engine.live_subscriber_count(), 1); + assert_eq!(versions.metrics().validations, 100); + assert_eq!( + versions.metrics().result_executions, + 1, + "100 authenticated clients should own one origin live query" + ); + let first = first.unwrap(); + let mut bob_socket = connect(&gateway.origin, &bob, false).await; + bob_socket + .send(WsMessage::Text( + json!({"id":"consumer-0","type":"subscribe","payload":{"query":LIVE_SUBSCRIPTION}}) + .to_string() + .into(), + )) + .await + .unwrap(); + let bob_frame = next(&mut bob_socket, "consumer-0", "causal row").await; + assert_ne!( + first["extensions"]["distributed"]["cacheScope"], + bob_frame["extensions"]["distributed"]["cacheScope"] + ); + assert_eq!( + (delivery.live_counts().0, engine.live_subscriber_count()), + (2, 2), + "identical roles/data must not cross subject scopes" + ); + bob_socket + .send(WsMessage::Text( + json!({"id":"consumer-0","type":"complete"}) + .to_string() + .into(), + )) + .await + .unwrap(); + let _ = bob_socket.close(None).await; + project_item(&fixture.repository, &fixture.bus, 2, "committed-live").await; + for (n, socket) in sockets.iter_mut().enumerate() { + let frame = next(socket, &format!("consumer-{n}"), "committed-live").await; + assert_eq!( + frame["extensions"]["distributed"]["snapshot"]["indexes"][0]["position"], + "2" + ); + } + let mut resumed = connect(&gateway.origin, &alice, true).await; + resumed.send(WsMessage::Text(json!({"id":"legacy-resume","type":"start","payload":{"query":LIVE_SUBSCRIPTION,"extensions":{"distributed":{"resume":{"cursors":first["extensions"]["distributed"]["live"]["cursors"]}}}}}).to_string().into())).await.unwrap(); + let replay = next(&mut resumed, "legacy-resume", "committed-live").await; + assert_eq!(replay["extensions"]["distributed"]["live"]["reset"], false); + tokio::time::timeout(Duration::from_secs(5), async { + while delivery.live_counts().0 != 1 || engine.live_subscriber_count() != 1 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("independent replay handed off and released its origin producer"); + assert!(delivery.live_counts().6 >= 1); + for (n, socket) in sockets.iter_mut().enumerate() { + socket + .send(WsMessage::Text( + json!({"id":format!("consumer-{n}"),"type":"complete"}) + .to_string() + .into(), + )) + .await + .unwrap(); + let _ = socket.close(None).await; + } + tokio::time::timeout(Duration::from_secs(5), async { + while delivery.live_counts().1 != 1 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + assert_eq!( + engine.live_subscriber_count(), + 1, + "remaining resumed client retains upstream ownership" + ); + resumed + .send(WsMessage::Text( + json!({"id":"legacy-resume","type":"stop"}) + .to_string() + .into(), + )) + .await + .unwrap(); + let _ = resumed.close(None).await; + tokio::time::timeout(Duration::from_secs(5), async { + while delivery.live_counts().0 != 0 || engine.live_subscriber_count() != 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("last leave tears down gateway and origin live producers"); + } +} From b51f51cbdb99b70685043dc5a5e1fcabaf2e3112 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 01:32:42 -0500 Subject: [PATCH 057/484] feat: add Worker gateway and sharded delivery coordination --- .github/workflows/integration-gateway.yaml | 34 + Cargo.toml | 3 + docs/gateway/worker.md | 103 ++ js/src/websocket.ts | 5 +- js/tests/replica-graphql-transport.test.mjs | 5 + src/gateway/mod.rs | 4 + src/gateway/worker/cancellation.rs | 73 + src/gateway/worker/coordinator.rs | 781 +++++++++ src/gateway/worker/frontend.rs | 512 ++++++ src/gateway/worker/live.rs | 541 +++++++ src/gateway/worker/live_transport.rs | 122 ++ src/gateway/worker/mod.rs | 446 +++++ src/gateway/worker/proxy.rs | 297 ++++ src/gateway/worker/raw_socket.rs | 166 ++ src/gateway/worker/socket.rs | 99 ++ src/gateway/worker/timer.rs | 99 ++ tests/gateway-worker/.gitignore | 5 + tests/gateway-worker/Cargo.lock | 1119 +++++++++++++ tests/gateway-worker/Cargo.toml | 14 + tests/gateway-worker/README.md | 50 + tests/gateway-worker/check_dependencies.py | 17 + tests/gateway-worker/live-runtime.mjs | 83 + tests/gateway-worker/package-lock.json | 1609 +++++++++++++++++++ tests/gateway-worker/package.json | 1 + tests/gateway-worker/proxy-runtime.mjs | 79 + tests/gateway-worker/query-runtime.mjs | 55 + tests/gateway-worker/run.mjs | 28 + tests/gateway-worker/runtime.mjs | 22 + tests/gateway-worker/sharded-runtime.mjs | 14 + tests/gateway-worker/src/lib.rs | 179 +++ tests/gateway-worker/wrangler.jsonc | 15 + tests/graphql_query_protocol/main.rs | 171 ++ 32 files changed, 6750 insertions(+), 1 deletion(-) create mode 100644 docs/gateway/worker.md create mode 100644 src/gateway/worker/cancellation.rs create mode 100644 src/gateway/worker/coordinator.rs create mode 100644 src/gateway/worker/frontend.rs create mode 100644 src/gateway/worker/live.rs create mode 100644 src/gateway/worker/live_transport.rs create mode 100644 src/gateway/worker/mod.rs create mode 100644 src/gateway/worker/proxy.rs create mode 100644 src/gateway/worker/raw_socket.rs create mode 100644 src/gateway/worker/socket.rs create mode 100644 src/gateway/worker/timer.rs create mode 100644 tests/gateway-worker/.gitignore create mode 100644 tests/gateway-worker/Cargo.lock create mode 100644 tests/gateway-worker/Cargo.toml create mode 100644 tests/gateway-worker/README.md create mode 100644 tests/gateway-worker/check_dependencies.py create mode 100644 tests/gateway-worker/live-runtime.mjs create mode 100644 tests/gateway-worker/package-lock.json create mode 100644 tests/gateway-worker/package.json create mode 100644 tests/gateway-worker/proxy-runtime.mjs create mode 100644 tests/gateway-worker/query-runtime.mjs create mode 100644 tests/gateway-worker/run.mjs create mode 100644 tests/gateway-worker/runtime.mjs create mode 100644 tests/gateway-worker/sharded-runtime.mjs create mode 100644 tests/gateway-worker/src/lib.rs create mode 100644 tests/gateway-worker/wrangler.jsonc diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 5864b0108..49d8df7ae 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -142,3 +142,37 @@ jobs: node --test js/tests/replica-command-runtime.test.mjs js/tests/replica-protocol.test.mjs js/tests/replica-revalidation.test.mjs js/tests/replica-graphql-transport.test.mjs - name: Verify generated delivery metadata run: cargo test -p distributed_cli client_compiler + + worker: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: clippy + - name: Install pinned local Worker and auth fixtures + run: | + cargo install worker-build --version 0.8.5 --locked + npm ci --prefix tests/gateway-worker + npm ci --prefix tests/gateway-auth + cd tests/gateway-auth + npx playwright install --with-deps chromium + - name: Check Wasm build and dependency boundary + run: | + cargo check --manifest-path tests/gateway-worker/Cargo.toml --locked --target wasm32-unknown-unknown + cargo clippy --manifest-path tests/gateway-worker/Cargo.toml --locked --target wasm32-unknown-unknown -- -D warnings + python3 tests/gateway-worker/check_dependencies.py + - name: Exercise actual workerd HTTP, WebSockets and Auth.js lifecycle + run: | + node tests/gateway-worker/proxy-runtime.mjs + node tests/gateway-worker/run.mjs + - name: Prove actual DO coordination, SQL reduction, restart and cancellation + run: cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol worker_ -- --ignored --nocapture --test-threads=1 diff --git a/Cargo.toml b/Cargo.toml index 44c5299ea..fc02e1729 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,8 @@ gateway-native = ["gateway", "http", "reqwest/stream", "dep:hyper", "dep:hyper-u gateway-graphql = ["gateway", "dep:async-graphql-parser"] # Shared portable identity, freshness and delivery contracts. gateway-delivery = ["gateway-graphql"] +# workers-rs ingress and delivery contracts, without native executors. +gateway-worker = ["gateway-delivery", "dep:worker", "dep:futures-channel"] gateway-graphql-native = ["gateway-native", "gateway-graphql", "graphql", "dep:tokio-tungstenite"] runtime = ["application-runtime"] emitter = ["dep:event-emitter-rs"] @@ -77,6 +79,7 @@ reqwest = { version = "0.13", default-features = false, features = ["json", "rus jsonwebtoken = { version = "9", optional = true } bitcode = { version = "0.6.9", features = ["serde"] } event-emitter-rs = { version = "0.1.4", optional = true } +futures-channel = { version = "0.3", features = ["sink"], optional = true } futures-util = { version = "0.3", default-features = false, features = ["alloc"] } hmac = { version = "0.12", optional = true } opentelemetry = { version = "0.32", default-features = false, features = ["trace"], optional = true } diff --git a/docs/gateway/worker.md b/docs/gateway/worker.md new file mode 100644 index 000000000..e54826841 --- /dev/null +++ b/docs/gateway/worker.md @@ -0,0 +1,103 @@ +# Worker ingress and Durable Object delivery + +Enable `gateway-worker` to use `distributed::gateway::worker`. It compiles to +`wasm32-unknown-unknown` with workers-rs and the portable gateway/delivery +contracts. It links no Axum, Tokio runtime, SQLx, GraphQL server or domain bus. +workers-rs includes Tokio with no features for utility types. Commands +continue to execute at the configured backend; the Worker is ingress. + +An application constructs `WorkerGateway` with its portable `GatewayConfig`, +explicit `WorkerBinding` resources, `WorkerOptions` and `WorkerAuth`. Mount +`gateway.fetch(request, env)` from the Worker fetch entrypoint. Bind handlers, +an asset service, UI/auth reverse proxies, or a whole remote GraphQL endpoint. +Routes use the same exact/longest-segment ownership as native ingress. A selected +handler's error is terminal. The public origin is configured, never taken from +incoming forwarding headers. The adapter retains Origin and duplicate cookies, +rewrites private-origin redirects and rejects proxy loops. Fetch requires Host +to match the fetched URL; trusted public authority reaches delegated handlers +through configured origin and forwarded headers. + +`WorkerAuth::new` accepts an application-owned asynchronous session/provider +implementation returning the shared `RequestContext`. It must validate the +credential before constructing identity or a backend bearer credential. +`WorkerAuth::anonymous()` accepts opaque UI/auth cookies but rejects HTTP bearer +input. It does not turn a cookie or decoded JWT into identity. Auth.js remains +the session/callback/refresh/logout owner when delegated; no second identity +store is introduced. GraphQL connection_init credentials are forwarded to and +validated by the backend. WebSocket commands/status stay on that backend socket +identity path. HTTP query reuse for a WebSocket operation requires explicit +origin control-protocol recognition; older/custom origins remain independent. + +## Optional coordination + +A `WorkerDeliveryBinding` declares namespace, epoch, shard count and independent +snapshot/coalescing/live resources. With `delivery: None`, forwarding creates no +coordinator. It also works with a backend that has no delivery control protocol. +Declare a workers-rs Durable Object in application code and construct one +`Rc` in its `new`. Route its fetch method through +`gateway.fetch_coordinated(request, env, coordinator)`. This is an in-process +mount; public headers cannot assert that admission already happened. + +All ingress instances must use the same namespace, binding name, epoch and shard +count. Operation documents, selected operation and canonical variables select a +shard. This routing hash conveys no authorization. The DO repeats provider +admission and obtains a fresh origin validation for **every** consumer before +reuse. The actual cache/flight/live keys retain origin-resolved application, +endpoint, subject scope, schema/policy versions and freshness floors. Private +hits still cost origin validation; 100 eligible query consumers can share one +result SQL execution. WebSocket queries require a control capability check +before the HTTP reuse path and therefore have additional validation overhead. + +Use Worker-sized limits, for example the explicit limits in +[`tests/gateway-worker/src/lib.rs`](../../tests/gateway-worker/src/lib.rs). +Native defaults intentionally do not fit the Worker retained-payload budget. +The adapter rejects selected configurations exceeding 16 MiB of reserved cache, +flight and live payload. Live-frame charges follow actual shared ownership, +including consumer queues retained across handoff, and force explicit reset if +the budget is exhausted. This bounds wire payload, not the entire runtime heap: +parsed JSON, credentials, active requests, sockets and the application's own +allocations need additional memory headroom. Groups, consumers, frame sizes, +queue length, response sizes and operation lifetimes have independent limits. + +Modern GraphQL subscriptions use standard ping/pong payload echo as delivery +credits: the supplied JS transport echoes the payload. Full data and confirmation +proof stay unchanged. A client that does not acknowledge is reset instead of +silently accumulating data. Raw UI and legacy GraphQL sockets cannot assume that +protocol; they have bounded callback queues and cumulative delivery limits, +after which reconnect is required. `websocket_buffer_bytes` bounds a complete +frame and aggregate queued wire bytes per socket; arbitrary UI delivery is +limited to eight times this value per connection. Customize limits for the UI's +protocol. Outgoing origin sockets remain active and do not hibernate. One shared +steady-state producer does not mean one lifetime handshake: every consumer is +independently authenticated at the origin before grouping. + +## Recovery and cancellation + +Coordinator state is volatile. Restart starts empty and requires fresh origin +validation/replay. No invalidation feed is needed for correctness: validators +cover committed projection data and proof state, including external SQL writes. +An epoch or shard change abandons old cache/work; clients reconnect and present +origin-verifiable cursors. Cursor gaps, incompatible freshness and queue overflow +cause origin recovery or explicit reset. Last-leave drops the actual upstream +socket; one expired consumer cannot terminate another valid consumer's group. +The upstream can reconnect with a remaining consumer's current credential. + +Set the `enable_request_signal` compatibility flag. The adapter preserves +Request.signal through rebuilt requests, and cancellation drops the associated +Rust work and shared-flight ownership. Plain HTTP disconnects before headers +did not produce that signal in the pinned local workerd fixture; those requests +remain bounded by the configured deadline. Explicit ingress abort signals, +response-stream cancellation and live last-leave teardown have separate actual +runtime tests. A cancelled command is never retried by the gateway; cancellation +does not imply that backend effects were rolled back. + +The fixture's migration declares a new `DeliveryCoordinator` SQLite DO class; +the adapter stores no cache entries or identity grants in durable storage. For +local reset, stop the runner and change its epoch (or use fresh disposable local +state). Rollback disables delivery bindings while retaining independent remote +forwarding. Do not reuse aggregate-cell classes or namespaces. Nothing in this +fixture provisions or deploys Cloudflare resources. + +Platform references: [request cancellation](https://developers.cloudflare.com/changelog/post/2025-05-22-handle-request-cancellation/), +[WebSocket API](https://developers.cloudflare.com/workers/runtime-apis/websockets/), +[outgoing socket lifecycle](https://developers.cloudflare.com/durable-objects/best-practices/websockets/). diff --git a/js/src/websocket.ts b/js/src/websocket.ts index 65c8c0ed1..9e7bc048b 100644 --- a/js/src/websocket.ts +++ b/js/src/websocket.ts @@ -191,7 +191,10 @@ export function subscribe< handlers.onComplete?.(); break; case 'ping': - socket.send(JSON.stringify({ type: 'pong' })); + socket.send(JSON.stringify({ + type: 'pong', + ...(message.payload === undefined ? {} : { payload: message.payload }) + })); break; case 'connection_error': handlers.onError?.(message.payload ?? 'connection error'); diff --git a/js/tests/replica-graphql-transport.test.mjs b/js/tests/replica-graphql-transport.test.mjs index a4ad78e61..f5c8b355b 100644 --- a/js/tests/replica-graphql-transport.test.mjs +++ b/js/tests/replica-graphql-transport.test.mjs @@ -197,6 +197,11 @@ test('replica GraphQL live work merges surface binding with resume and closes on } } }); + const credit = { gatewayOperation: '1', gatewayDeliveryAck: 'opaque-credit' }; + socket.message({ type: 'ping', payload: credit }); + assert.deepEqual(socket.sent.at(-1), { type: 'pong', payload: credit }); + socket.message({ type: 'ping' }); + assert.deepEqual(socket.sent.at(-1), { type: 'pong' }); socket.message({ type: 'next', payload: { data: { todos: [{ id: '1' }] } } }); assert.deepEqual(next, [{ data: { todos: [{ id: '1' }] } }]); assert.deepEqual(errors, []); diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 6a6ca6ff2..09ac5ff47 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -44,3 +44,7 @@ pub mod graphql; /// Portable authenticated delivery identity and freshness contracts. #[cfg(feature = "gateway-delivery")] pub mod delivery; + +/// workers-rs ingress and sharded Durable Object delivery adapter. +#[cfg(feature = "gateway-worker")] +pub mod worker; diff --git a/src/gateway/worker/cancellation.rs b/src/gateway/worker/cancellation.rs new file mode 100644 index 000000000..fcc1c5846 --- /dev/null +++ b/src/gateway/worker/cancellation.rs @@ -0,0 +1,73 @@ +use futures_channel::oneshot; +use std::{ + future::Future, + pin::Pin, + task::{Context, Poll}, +}; +use worker::{ + wasm_bindgen::{closure::Closure, JsCast}, + web_sys::AbortSignal, + Request, Response, Result, +}; + +/// Own the event listener so cancellation drops the actual in-flight Rust work. +pub(super) struct Cancelled { + signal: AbortSignal, + callback: Closure, + receiver: oneshot::Receiver<()>, +} +impl Cancelled { + pub fn new(signal: AbortSignal) -> Result { + let (sender, receiver) = oneshot::channel(); + let mut sender = Some(sender); + let callback = Closure::wrap_assert_unwind_safe(Box::new(move || { + if let Some(sender) = sender.take() { + let _ = sender.send(()); + } + }) as Box); + signal.add_event_listener_with_callback("abort", callback.as_ref().unchecked_ref())?; + Ok(Self { + signal, + callback, + receiver, + }) + } +} +impl Future for Cancelled { + type Output = (); + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if self.signal.aborted() { + return Poll::Ready(()); + } + Pin::new(&mut self.receiver).poll(cx).map(|_| ()) + } +} +impl Drop for Cancelled { + fn drop(&mut self) { + let _ = self + .signal + .remove_event_listener_with_callback("abort", self.callback.as_ref().unchecked_ref()); + } +} +pub(super) async fn run( + signal: AbortSignal, + future: impl Future>, +) -> Result { + match futures_util::future::select(Box::pin(future), Box::pin(Cancelled::new(signal)?)).await { + futures_util::future::Either::Left((result, _)) => result, + futures_util::future::Either::Right(_) => Response::error("request cancelled", 499), + } +} +pub(super) fn preserve_signal(request: Request, signal: &AbortSignal) -> Result { + let init = worker::web_sys::RequestInit::new(); + init.set_signal(Some(signal)); + Ok(worker::web_sys::Request::new_with_request_and_init(request.inner(), &init)?.into()) +} + +/// Dropping a WebSocket operation also cancels its HTTP/DO fetch promise. +pub(super) struct AbortOnDrop(pub worker::web_sys::AbortController); +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} diff --git a/src/gateway/worker/coordinator.rs b/src/gateway/worker/coordinator.rs new file mode 100644 index 000000000..539207bbc --- /dev/null +++ b/src/gateway/worker/coordinator.rs @@ -0,0 +1,781 @@ +use super::{proxy, RequestContext, WorkerOptions}; +use crate::gateway::{delivery::*, DeliveryCapabilities, GatewayError}; +use futures_util::{ + future::{LocalBoxFuture, Shared, WeakShared}, + FutureExt, StreamExt, +}; +use std::{cell::RefCell, collections::BTreeMap, rc::Rc}; +use worker::{Headers, Request, RequestInit, RequestRedirect, Response, Result}; + +/// Optional delivery resources, allocated inside a Durable Object only. +#[derive(Clone, Copy, Debug, Default)] +pub struct WorkerDeliveryOptions { + /// Bounded complete response cache. + pub snapshots: Option, + /// Bounded concurrent query sharing. + pub coalescing: Option, + /// Bounded live sharing. + pub live: Option, +} +impl WorkerDeliveryOptions { + pub(super) fn capabilities(&self) -> DeliveryCapabilities { + DeliveryCapabilities { + snapshots: self.snapshots.is_some(), + coalescing: self.coalescing.is_some(), + live_sharing: self.live.is_some(), + } + } + pub(super) fn validate(&self) -> std::result::Result<(), GatewayError> { + if self.snapshots.is_none() && self.coalescing.is_none() && self.live.is_none() { + return Err(GatewayError("no Worker delivery capability selected")); + } + if let Some(limits) = self.snapshots { + SnapshotCache::new(limits).map_err(|_| GatewayError("invalid snapshot limits"))?; + } + if let Some(limits) = self.coalescing { + FlightRegistry::new(limits).map_err(|_| GatewayError("invalid flight limits"))?; + } + if let Some(limits) = self.live { + limits + .validate() + .map_err(|_| GatewayError("invalid live limits"))?; + } + // Bound retained wire payload independently of the native defaults. + // Parsed JSON, credentials and runtime socket overhead require additional + // headroom; this is a payload budget, not the platform heap limit. + let snapshots = self.snapshots.map_or(0, |l| l.bytes); + let flights = self + .coalescing + .map_or(0, |l| l.groups.saturating_mul(l.response_bytes)); + let live = self.live.map_or(0, |l| { + l.groups + .saturating_mul( + l.queue_frames + .saturating_add(l.history_frames) + .saturating_add(2), + ) + .saturating_mul(l.frame_bytes) + }); + if snapshots.saturating_add(flights).saturating_add(live) > 16 * 1024 * 1024 { + return Err(GatewayError( + "Worker coordinator retained payload budget exceeds 16 MiB", + )); + } + Ok(()) + } +} +/// Stable sharded namespace configuration, distinct from domain aggregate cells. +#[derive(Clone, Debug)] +pub struct WorkerDeliveryBinding { + /// Application-declared Durable Object namespace binding name. + pub namespace: String, + /// Stable deployment/application namespace. Change to abandon prior coordinator state. + pub epoch: String, + /// Number of operation shards, 1..=1024; every ingress uses the same configuration. + pub shards: u16, + /// Independent resources and limits for each selected Durable Object. + pub options: WorkerDeliveryOptions, +} +impl WorkerDeliveryBinding { + pub(super) fn validate(&self) -> std::result::Result<(), GatewayError> { + if self.namespace.is_empty() + || self.namespace.len() > 256 + || self.epoch.is_empty() + || self.epoch.len() > 256 + || self.shards == 0 + || self.shards > 1024 + { + return Err(GatewayError("invalid Worker coordinator binding")); + } + self.options.validate() + } + pub(super) fn shard(&self, binding: &str, value: &serde_json::Value) -> Result { + use sha2::{Digest, Sha256}; + // Routing uses no caller scope assertion or bearer material. The DO + // independently authenticates and derives exact scope before any reuse. + let bytes = canonical_json(&serde_json::json!([ + binding, + value["query"], + value["operationName"], + value["variables"] + ])) + .map_err(|_| worker::Error::RustError("invalid operation shard".into()))?; + let hash = Sha256::digest(bytes); + let shard = u16::from_be_bytes([hash[0], hash[1]]) % self.shards; + Ok(format!( + "gateway-delivery-v1:{}:{binding}:{shard}", + self.epoch + )) + } +} +/// Volatile cache/work state owned by one platform Durable Object instance. +/// A restart starts empty; every reuse still requires current origin validation. +/// Do not keep this in ordinary ingress isolate memory. +pub struct WorkerCoordinator { + options: WorkerDeliveryOptions, + cache: Option>, + flights: Option>, + live: Option>, +} +impl WorkerCoordinator { + /// Construct only in an application's DurableObject::new implementation. + pub fn new(options: WorkerDeliveryOptions) -> std::result::Result, GatewayError> { + options.validate()?; + Ok(Rc::new(Self { + options, + live: options + .live + .map(|limits| { + super::live::WorkerLive::new( + limits, + 16 * 1024 * 1024 + - options.snapshots.map_or(0, |l| l.bytes) + - options + .coalescing + .map_or(0, |l| l.groups * l.response_bytes), + ) + }) + .transpose()?, + cache: options + .snapshots + .map(SnapshotCache::new) + .transpose() + .map_err(|_| GatewayError("invalid snapshot limits"))? + .map(RefCell::new), + flights: options.coalescing.map(Flights::new).transpose()?, + })) + } + /// Forget cached data and fence in-progress fills after reset/lost feed. + pub fn invalidate_all(&self) { + if let Some(cache) = &self.cache { + cache.borrow_mut().invalidate_all(); + } + } + /// Current cache entries, active query groups and query consumers; no identity values. + pub fn counts(&self) -> (usize, usize, usize) { + let (groups, consumers) = self.flights.as_ref().map_or((0, 0), |flights| { + let state = flights.state.borrow(); + (state.registry.len(), state.registry.consumers()) + }); + ( + self.cache.as_ref().map_or(0, |cache| cache.borrow().len()), + groups, + consumers, + ) + } + /// Active live groups and consumers, followed by source/reset/frame counters. + pub fn live_counts(&self) -> (usize, usize, u64, u64, u64, u64, u64) { + self.live + .as_ref() + .map_or((0, 0, 0, 0, 0, 0, 0), |live| live.counts()) + } + pub(super) fn upgrade( + self: &Rc, + origin: OriginRequest, + live_path: String, + capabilities: crate::gateway::GraphqlCapabilities, + ) -> Result { + let pair = worker::WebSocketPair::new()?; + let mut socket = super::socket::Socket::new( + pair.server, + origin.options.limits.websocket_buffer_bytes, + 4, + )?; + let owner = self.clone(); + worker::wasm_bindgen_futures::spawn_local(async move { + let first = super::timer::deadline( + std::time::Duration::from_millis(origin.options.limits.header_timeout_ms), + socket.next(), + ) + .await; + let Ok(Ok(first)) = first else { + return; + }; + let value = first["payload"].clone(); + if first["type"] != "subscribe" + || crate::gateway::graphql::admit_request(&value, capabilities).is_err() + || crate::gateway::graphql::operation_kind( + value["query"].as_str().unwrap_or(""), + value["operationName"].as_str(), + ) != Ok(crate::gateway::graphql::OperationKind::Subscription) + { + return; + } + let _ = owner.subscribe(origin, live_path, value, socket).await; + }); + Response::from_websocket(pair.client) + } + pub(super) async fn subscribe( + self: &Rc, + origin: OriginRequest, + live_path: String, + value: serde_json::Value, + mut socket: super::socket::Socket, + ) -> Result<()> { + let freshness = value["extensions"] + .get("gatewayFreshness") + .map(FreshnessContext::parse) + .transpose() + .map_err(delivery_error)?; + let init = value["extensions"]["gatewayDelivery"] + .get("connectionInit") + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + let source = super::live_transport::source(origin.clone(), live_path, init); + let admission = origin.validate(&value).await?; + let lifetime = origin.options.limits.websocket_lifetime_ms; + let ack_timeout = origin.options.limits.read_timeout_ms; + match admission { + Admitted::Eligible(admission) => { + let live = self + .live + .as_ref() + .ok_or_else(|| worker::Error::RustError("live coordinator absent".into()))?; + let mut lease = live + .join(admission, value, freshness, source) + .map_err(delivery_error)?; + worker::wasm_bindgen_futures::spawn_local(async move { + let run = async { + loop { + enum Event { + Frame( + std::result::Result< + Option>, + &'static str, + >, + ), + Client(std::result::Result), + } + let event = match futures_util::future::select( + Box::pin(lease.next()), + Box::pin(socket.next()), + ) + .await + { + futures_util::future::Either::Left((frame, _)) => { + Event::Frame(frame) + } + futures_util::future::Either::Right((client, _)) => { + Event::Client(client) + } + }; + let frame = match event { + Event::Frame(frame) => frame, + Event::Client(Ok(value)) if value["type"] == "ping" => { + let _=socket.send(&serde_json::json!({"type":"pong","payload":value["payload"]})); + continue; + } + _ => return, + }; + let frame = match frame { + Ok(Some(frame)) => frame, + Ok(None) => { + let _ = socket.send(&serde_json::json!({"type":"complete"})); + return; + } + Err(reason) => { + let _ = socket.send( + &serde_json::json!({"type":"error","payload":reason}), + ); + return; + } + }; + if socket + .send(&serde_json::json!({"type":"next","payload":frame.payload()})) + .is_err() + { + return; + } + // Standard GraphQL ping/pong provides a delivery credit on + // workerd, whose WebSocket API has no bufferedAmount. + let nonce = uuid::Uuid::now_v7().to_string(); + if socket.send(&serde_json::json!({"type":"ping","payload":{"gatewayDeliveryAck":nonce}})).is_err(){return;} + let acknowledged = { + let ack = wait_ack(&mut socket, &nonce, ack_timeout); + matches!( + futures_util::future::select( + Box::pin(ack), + Box::pin(lease.interrupted()) + ) + .await, + futures_util::future::Either::Left((Ok(()), _)) + ) + }; + if !acknowledged { + let _ = socket.ws.close(Some(1013), Some("LIVE_RESET_REQUIRED")); + return; + } + } + }; + let _ = super::timer::deadline(std::time::Duration::from_millis(lifetime), run) + .await; + }); + } + Admitted::Bypass => { + worker::wasm_bindgen_futures::spawn_local(async move { + let run = async { + let Ok(mut stream) = source(value).await else { + return; + }; + loop { + let frame = { + let result = futures_util::future::select( + Box::pin(stream.next()), + Box::pin(socket.next()), + ) + .await; + match result { + futures_util::future::Either::Left((frame, _)) => frame, + _ => return, + } + }; + let Some(frame) = frame else { + break; + }; + let Ok(frame) = frame else { + let _ = socket.ws.close(Some(1013), Some("LIVE_RESET_REQUIRED")); + return; + }; + if socket + .send(&serde_json::json!({"type":"next","payload":frame})) + .is_err() + { + return; + } + let nonce = uuid::Uuid::now_v7().to_string(); + if socket.send(&serde_json::json!({"type":"ping","payload":{"gatewayDeliveryAck":nonce}})).is_err()||wait_ack(&mut socket,&nonce,ack_timeout).await.is_err(){return;} + } + let _ = socket.send(&serde_json::json!({"type":"complete"})); + }; + let _ = super::timer::deadline(std::time::Duration::from_millis(lifetime), run) + .await; + }); + } + Admitted::Error(mut response) => { + let bytes = read_response(&mut response, 65536).await?; + let payload = serde_json::from_slice::(&bytes).unwrap_or_else( + |_| serde_json::json!({"errors":[{"message":"origin admission failed"}]}), + ); + let _ = socket.send(&serde_json::json!({"type":"next","payload":payload})); + let _ = socket.send(&serde_json::json!({"type":"complete"})); + } + } + Ok(()) + } + pub(super) fn capabilities(&self) -> DeliveryCapabilities { + self.options.capabilities() + } + pub(super) async fn execute( + self: &Rc, + origin: OriginRequest, + value: serde_json::Value, + ) -> Result { + let freshness = value["extensions"] + .get("gatewayFreshness") + .map(FreshnessContext::parse) + .transpose() + .map_err(|_| worker::Error::RustError("invalid freshness".into()))?; + let admission = match origin.validate(&value).await? { + Admitted::Eligible(admission) => admission, + Admitted::Bypass => return origin.execute(value).await, + Admitted::Error(response) => return Ok(response), + }; + let ticket = if let Some(cache) = &self.cache { + let mut cache = cache.borrow_mut(); + match cache + .lookup(&admission, freshness.as_ref(), super::now()) + .map_err(delivery_error)? + { + Some(hit) => return render(hit), + None => Some( + cache + .begin_fill(&admission, super::now()) + .map_err(delivery_error)?, + ), + } + } else { + None + }; + if let Some(flights) = &self.flights { + let key = FlightKey::admitted(&admission, &value, freshness.as_ref(), super::now()) + .map_err(delivery_error)?; + let owner = self.clone(); + let input = origin.clone(); + let request = value.clone(); + let admitted = admission.clone(); + let floor = freshness.clone(); + let expires = admission.expires_at; + let limit = flights.limits; + let lease = flights + .join(key, move || { + async move { + let work = async { + let result = owner + .fill(input, request, admitted.clone(), floor.clone(), ticket) + .await?; + let captured = capture(result, limit.response_bytes).await?; + Ok(match captured { + Captured::Bytes(snapshot) + if snapshot.shareable(&admitted, floor.as_ref()) => + { + Outcome::Shared(Rc::new(snapshot)) + } + Captured::Bytes(snapshot) => exclusive(render(snapshot)?), + Captured::Streaming(response) => exclusive(response), + }) + }; + proxy::timeout(limit.deadline_ms, work) + .await + .unwrap_or_else(|_| { + exclusive( + Response::error("origin unavailable", 502) + .expect("fixed status"), + ) + }) + } + .boxed_local() + }) + .map_err(delivery_error)?; + let outcome = proxy::timeout(expires.saturating_sub(super::now()) * 1000, async { + Ok(lease.work.clone().await) + }) + .await; + if super::now() >= expires { + return Response::error("credential expired", 401); + } + match outcome? { + Outcome::Shared(snapshot) => return render((*snapshot).clone()), + Outcome::Exclusive(response) => { + if let Some(response) = response.borrow_mut().take() { + return Ok(response); + } + } + } + return origin.execute(value).await; + } + self.fill(origin, value, admission, freshness, ticket).await + } + async fn fill( + &self, + origin: OriginRequest, + value: serde_json::Value, + admission: OriginAdmission, + freshness: Option, + ticket: Option, + ) -> Result { + let mut marked = value.clone(); + mark(&mut marked, "snapshot"); + let limit = self + .options + .coalescing + .map(|l| l.response_bytes) + .or(self.options.snapshots.map(|l| l.entry_bytes)) + .unwrap_or(1024 * 1024); + let captured = capture(origin.execute(marked).await?, limit).await?; + let snapshot = match captured { + Captured::Bytes(snapshot) => snapshot, + Captured::Streaming(response) => return Ok(response), + }; + if snapshot.shareable(&admission, freshness.as_ref()) { + match origin.validate(&value).await? { + Admitted::Eligible(current) => { + if current.identity != admission.identity || current.key != admission.key { + return Response::error("origin scope changed", 409); + } + if let (Some(cache), Some(ticket)) = (&self.cache, ticket) { + cache + .borrow_mut() + .install(ticket, current, snapshot.clone(), super::now()) + .map_err(delivery_error)?; + } + } + Admitted::Error(response) => return Ok(response), + Admitted::Bypass => {} + } + } + render(snapshot) + } +} +#[derive(Clone)] +pub(super) struct OriginRequest { + pub origin: String, + pub path: String, + pub url: String, + pub headers: Vec<(String, String)>, + pub options: WorkerOptions, + pub context: RequestContext, +} +impl OriginRequest { + pub(super) async fn execute(&self, value: serde_json::Value) -> Result { + let mut init = RequestInit::new(); + init.method = worker::Method::Post; + init.redirect = RequestRedirect::Manual; + for (name, value) in &self.headers { + if !matches!( + name.to_ascii_lowercase().as_str(), + "content-length" + | "connection" + | "upgrade" + | "sec-websocket-key" + | "sec-websocket-protocol" + | "sec-websocket-version" + ) { + init.headers.append(name, value)?; + } + } + init.headers.set("content-type", "application/json")?; + init.body = Some(value.to_string().into()); + proxy::forward( + Request::new_with_init(&self.url, &init)?, + &self.origin, + Some(&self.path), + false, + &self.options, + &self.context, + ) + .await + } + pub(super) async fn validate(&self, value: &serde_json::Value) -> Result { + let mut marked = value.clone(); + mark(&mut marked, "validate"); + let result = self.execute(marked).await?; + let Captured::Bytes(snapshot) = capture(result, 65536).await? else { + return Err(worker::Error::RustError( + "oversized origin admission".into(), + )); + }; + if snapshot.status != 200 { + return Ok(Admitted::Error(render(snapshot)?)); + } + let parsed: serde_json::Value = serde_json::from_slice(&snapshot.body)?; + if parsed + .get("errors") + .is_some_and(|v| v.as_array().is_none_or(|v| !v.is_empty())) + { + return Ok(Admitted::Error(render(snapshot)?)); + } + let delivery = &parsed["extensions"]["gatewayDelivery"]; + if delivery["eligible"] != true + || snapshot + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("set-cookie")) + { + return Ok(Admitted::Bypass); + } + let admission: OriginAdmission = serde_json::from_value(delivery["admission"].clone())?; + admission + .bind(value, super::now()) + .map_err(delivery_error)?; + Ok(Admitted::Eligible(admission)) + } +} +pub(super) enum Admitted { + Eligible(OriginAdmission), + Bypass, + Error(Response), +} +pub(super) fn mark(value: &mut serde_json::Value, action: &str) { + if !value["extensions"].is_object() { + value["extensions"] = serde_json::json!({}); + } + let init = value["extensions"]["gatewayDelivery"] + .get("connectionInit") + .cloned(); + value["extensions"]["gatewayDelivery"] = serde_json::json!({"action":action}); + if let Some(init) = init { + value["extensions"]["gatewayDelivery"]["connectionInit"] = init; + } +} +fn delivery_error(_: DeliveryError) -> worker::Error { + worker::Error::RustError("delivery unavailable".into()) +} +fn render(snapshot: SnapshotResponse) -> Result { + let headers = Headers::new(); + for (name, value) in snapshot.headers { + headers.append(&name, &value)?; + } + Ok(Response::from_bytes(snapshot.body)? + .with_status(snapshot.status) + .with_headers(headers)) +} +enum Captured { + Bytes(SnapshotResponse), + Streaming(Response), +} +async fn capture(mut response: Response, limit: usize) -> Result { + let status = response.status_code(); + let headers = response.headers().entries().collect::>(); + match response.body() { + worker::ResponseBody::Empty => { + return Ok(Captured::Bytes(SnapshotResponse { + status, + headers, + body: Vec::new(), + })) + } + worker::ResponseBody::Body(body) if body.len() <= limit => { + return Ok(Captured::Bytes(SnapshotResponse { + status, + headers, + body: body.clone(), + })) + } + worker::ResponseBody::Body(_) => return Ok(Captured::Streaming(response)), + worker::ResponseBody::Stream(_) => {} + } + let stream = response.stream()?; + let mut stream = stream; + let mut chunks = Vec::new(); + let mut size = 0; + while let Some(chunk) = stream.next().await { + let failed = chunk.is_err(); + size += chunk.as_ref().map_or(0, Vec::len); + chunks.push(chunk); + if failed || size > limit { + let head = Headers::new(); + for (name, value) in headers { + head.append(&name, &value)?; + } + return Ok(Captured::Streaming( + Response::from_stream(futures_util::stream::iter(chunks).chain(stream))? + .with_status(status) + .with_headers(head), + )); + } + } + let mut body = Vec::with_capacity(size); + for chunk in chunks { + body.extend(chunk?); + } + Ok(Captured::Bytes(SnapshotResponse { + status, + headers, + body, + })) +} +#[derive(Clone)] +enum Outcome { + Shared(Rc), + Exclusive(Rc>>), +} +fn exclusive(response: Response) -> Outcome { + Outcome::Exclusive(Rc::new(RefCell::new(Some(response)))) +} +type Work = LocalBoxFuture<'static, Outcome>; +struct FlightState { + registry: FlightRegistry, + work: BTreeMap>, +} +struct Flights { + state: RefCell, + limits: FlightLimits, +} +struct Lease { + owner: Rc, + ticket: Option, + work: Shared, +} +impl Drop for Lease { + fn drop(&mut self) { + if let Some(ticket) = self.ticket.take() { + let generation = ticket.generation(); + let mut state = self.owner.state.borrow_mut(); + if state.registry.leave(ticket) { + state.work.remove(&generation); + } + } + } +} +impl Flights { + fn new(limits: FlightLimits) -> std::result::Result, GatewayError> { + Ok(Rc::new(Self { + state: RefCell::new(FlightState { + registry: FlightRegistry::new(limits) + .map_err(|_| GatewayError("invalid flight limits"))?, + work: BTreeMap::new(), + }), + limits, + })) + } + fn join( + self: &Rc, + key: FlightKey, + start: impl FnOnce() -> Work, + ) -> std::result::Result { + let mut state = self.state.borrow_mut(); + state.registry.expire(worker::Date::now().as_millis()); + let expired = state + .work + .keys() + .filter(|generation| !state.registry.contains_generation(**generation)) + .copied() + .collect::>(); + for generation in expired { + state.work.remove(&generation); + } + let (ticket, owner) = state.registry.join(key, worker::Date::now().as_millis())?; + let generation = ticket.generation(); + let work = if owner { + let work = start().shared(); + state.work.insert( + generation, + work.downgrade().ok_or(DeliveryError::Unavailable)?, + ); + work + } else { + state + .work + .get(&generation) + .and_then(WeakShared::upgrade) + .ok_or(DeliveryError::Unavailable)? + }; + Ok(Lease { + owner: self.clone(), + ticket: Some(ticket), + work, + }) + } +} + +async fn wait_ack( + socket: &mut super::socket::Socket, + nonce: &str, + milliseconds: u64, +) -> std::result::Result<(), String> { + super::timer::deadline(std::time::Duration::from_millis(milliseconds), async { + loop { + let value = socket.next().await?; + match value["type"].as_str() { + Some("pong") if value["payload"]["gatewayDeliveryAck"] == nonce => return Ok(()), + Some("ping") => { + socket.send(&serde_json::json!({"type":"pong","payload":value["payload"]}))? + } + _ => return Err("invalid delivery acknowledgement".into()), + } + } + }) + .await + .map_err(|_| "delivery acknowledgement timeout".to_owned())? +} + +pub(super) async fn read_response(response: &mut Response, max: usize) -> Result> { + match response.body() { + worker::ResponseBody::Empty => return Ok(Vec::new()), + worker::ResponseBody::Body(bytes) if bytes.len() <= max => return Ok(bytes.clone()), + worker::ResponseBody::Body(_) => { + return Err(worker::Error::RustError("response too large".into())) + } + _ => {} + } + let mut stream = response.stream()?; + let mut bytes = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + if bytes.len().saturating_add(chunk.len()) > max { + return Err(worker::Error::RustError("response too large".into())); + } + bytes.extend(chunk); + } + Ok(bytes) +} diff --git a/src/gateway/worker/frontend.rs b/src/gateway/worker/frontend.rs new file mode 100644 index 000000000..a4825542e --- /dev/null +++ b/src/gateway/worker/frontend.rs @@ -0,0 +1,512 @@ +use super::{ + coordinator::{OriginRequest, WorkerDeliveryBinding}, + live_transport, + socket::Socket, + WorkerGateway, +}; +use crate::gateway::{ + graphql::{admit_request, operation_kind, OperationKind}, + GraphqlCapabilities, +}; +use futures_channel::mpsc; +use futures_util::{ + future::{select, AbortHandle, Abortable, Either}, + SinkExt, StreamExt, +}; +use std::{collections::BTreeMap, time::Duration}; +use worker::{Env, Request, RequestInit, RequestRedirect, Response, Result, WebSocketPair}; + +#[allow(clippy::too_many_arguments)] +pub(super) async fn upgrade( + gateway: WorkerGateway, + env: Env, + request: Request, + input: OriginRequest, + live_path: String, + capabilities: GraphqlCapabilities, + delivery: Option, + binding: String, +) -> Result { + if request.method() != worker::Method::Get { + return Response::error("invalid websocket method", 400); + } + let offered = request + .headers() + .get("sec-websocket-protocol")? + .unwrap_or_default(); + let protocol = if offered + .split(',') + .any(|p| p.trim() == "graphql-transport-ws") + { + "graphql-transport-ws" + } else if offered.split(',').any(|p| p.trim() == "graphql-ws") { + "graphql-ws" + } else { + return Response::error("unsupported GraphQL protocol", 400); + }; + let mut origin = match live_transport::handshake(&input, &live_path, protocol).await { + Ok(socket) => socket, + Err(_) => return Response::error("origin unavailable", 502), + }; + let pair = WebSocketPair::new()?; + let mut client = Socket::new(pair.server, input.options.limits.websocket_buffer_bytes, 32)?; + let lifetime = + input + .context + .identity() + .map_or(input.options.limits.websocket_lifetime_ms, |identity| { + input + .options + .limits + .websocket_lifetime_ms + .min(identity.expires_at().saturating_sub(super::now()) * 1000) + }); + worker::wasm_bindgen_futures::spawn_local(async move { + let run = async { + let first = match super::timer::deadline( + Duration::from_millis(input.options.limits.header_timeout_ms), + client.next(), + ) + .await + { + Ok(Ok(value)) if value["type"] == "connection_init" => value, + _ => return, + }; + let init = first + .get("payload") + .cloned() + .unwrap_or_else(|| serde_json::json!({})); + let ack = match live_transport::initialize( + &mut origin, + init.clone(), + input.options.limits.header_timeout_ms, + ) + .await + { + Ok(ack) => ack, + Err(_) => { + let _ = client.ws.close(Some(4401), Some("unauthorized")); + return; + } + }; + if client.send(&ack).is_err() { + return; + } + if protocol == "graphql-ws" || delivery.is_none() { + independent( + &mut client, + &mut origin, + capabilities, + input.options.limits.websocket_buffer_bytes, + protocol, + ) + .await; + return; + } + drop(origin); + modern( + client, + gateway, + env, + input, + live_path, + capabilities, + delivery, + binding, + init, + ) + .await; + }; + let _ = super::timer::deadline(Duration::from_millis(lifetime), run).await; + }); + let response = Response::from_websocket(pair.client)?; + response.headers().set("sec-websocket-protocol", protocol)?; + Ok(response) +} +struct Operation { + abort: AbortHandle, + ack: mpsc::Sender, +} +impl Drop for Operation { + fn drop(&mut self) { + self.abort.abort(); + } +} +#[allow(clippy::too_many_arguments)] +async fn modern( + mut client: Socket, + gateway: WorkerGateway, + env: Env, + input: OriginRequest, + live_path: String, + capabilities: GraphqlCapabilities, + delivery: Option, + binding: String, + init: serde_json::Value, +) { + let (out, mut outgoing) = mpsc::channel::(32); + let mut operations = BTreeMap::::new(); + loop { + enum Event { + Client(std::result::Result), + Output(Option), + } + let event = match select(Box::pin(client.next()), Box::pin(outgoing.next())).await { + Either::Left((value, _)) => Event::Client(value), + Either::Right((value, _)) => Event::Output(value), + }; + match event { + Event::Client(Ok(value)) => { + match value["type"].as_str() { + Some("subscribe") => { + let Some(id) = value["id"] + .as_str() + .filter(|id| !id.is_empty() && id.len() <= 256) + else { + break; + }; + if operations.len() >= 128 || operations.contains_key(id) { + let _ = client + .ws + .close(Some(4409), Some("duplicate or excessive operation ID")); + break; + } + if let Err(error) = admit_request(&value["payload"], capabilities) { + let _=client.send(&serde_json::json!({"id":id,"type":"next","payload":error.envelope()})); + let _ = client.send(&serde_json::json!({"id":id,"type":"complete"})); + continue; + } + let (abort, registration) = AbortHandle::new_pair(); + let (ack, acks) = mpsc::channel(1); + operations.insert(id.to_owned(), Operation { abort, ack }); + let id = id.to_owned(); + let value = value["payload"].clone(); + let gateway = gateway.clone(); + let env = env.clone(); + let input = input.clone(); + let path = live_path.clone(); + let delivery = delivery.clone(); + let binding = binding.clone(); + let init = init.clone(); + let mut out = out.clone(); + worker::wasm_bindgen_futures::spawn_local(async move { + let task = async { + if let Err(reason) = operation( + &id, value, gateway, env, input, path, delivery, binding, init, + &mut out, acks, + ) + .await + { + let code = match reason.as_str() { + "AUTH_EXPIRED" => "AUTH_EXPIRED", + "FRESHNESS_PENDING" => "FRESHNESS_PENDING", + "FRESHNESS_SCOPE_CHANGED" => "FRESHNESS_SCOPE_CHANGED", + _ => "LIVE_RESET_REQUIRED", + }; + let _=out.send(serde_json::json!({"id":id,"type":"error","payload":[{"message":code,"extensions":{"code":code}}]})).await; + } + }; + let _ = Abortable::new(task, registration).await; + }); + } + Some("complete") => { + if let Some(id) = value["id"].as_str() { + operations.remove(id); + } + } + Some("ping") => { + if client + .send(&serde_json::json!({"type":"pong","payload":value["payload"]})) + .is_err() + { + break; + } + } + Some("pong") => { + if let Some(operation) = value["payload"]["gatewayOperation"] + .as_str() + .and_then(|id| operations.get_mut(id)) + { + let mut value = value; + value["payload"] + .as_object_mut() + .map(|payload| payload.remove("gatewayOperation")); + if operation.ack.try_send(value).is_err() { + break; + } + } + } + _ => break, + } + } + Event::Output(Some(value)) => { + if client.send(&value).is_err() { + break; + } + if matches!(value["type"].as_str(), Some("complete" | "error")) { + if let Some(id) = value["id"].as_str() { + operations.remove(id); + } + } + } + _ => break, + } + } +} +fn post_request( + input: &OriginRequest, + value: &serde_json::Value, + upgrade: bool, +) -> Result { + let mut init = RequestInit::new(); + init.method = if upgrade { + worker::Method::Get + } else { + worker::Method::Post + }; + init.redirect = RequestRedirect::Manual; + for (name, value) in &input.headers { + if !matches!( + name.as_str(), + "content-length" + | "content-type" + | "upgrade" + | "connection" + | "sec-websocket-key" + | "sec-websocket-protocol" + | "sec-websocket-version" + ) { + init.headers.append(name, value)?; + } + } + init.headers.set("content-type", "application/json")?; + if upgrade { + init.headers.set("upgrade", "websocket")?; + } + if !upgrade { + init.body = Some(value.to_string().into()); + } + Request::new_with_init(&input.url, &init) +} +#[allow(clippy::too_many_arguments)] +async fn operation( + id: &str, + mut value: serde_json::Value, + gateway: WorkerGateway, + env: Env, + input: OriginRequest, + live_path: String, + delivery: Option, + binding: String, + init: serde_json::Value, + out: &mut mpsc::Sender, + mut acks: mpsc::Receiver, +) -> std::result::Result<(), String> { + if !value["extensions"].is_object() { + value["extensions"] = serde_json::json!({}); + } + value["extensions"]["gatewayDelivery"] = + serde_json::json!({"action":"execute","connectionInit":init}); + let send = |payload| serde_json::json!({"id":id,"type":"next","payload":payload}); + let kind = operation_kind( + value["query"].as_str().unwrap_or(""), + value["operationName"].as_str(), + ); + // Command/status operations retain the origin's WebSocket identity path. + // A query may use HTTP reuse only after the origin explicitly recognizes + // its control protocol; older/custom origins remain independently executed. + let reuse_query = kind == Ok(OperationKind::Query) + && matches!( + input.validate(&value).await, + Ok(super::coordinator::Admitted::Eligible(_)) + ); + if kind != Ok(OperationKind::Subscription) && !reuse_query { + let mut stream = live_transport::source(input.clone(), live_path, init)(value).await?; + while let Some(frame) = stream.next().await { + out.send(send(frame?)).await.map_err(|_| "consumer left")?; + } + } else if reuse_query { + let request = post_request(&input, &value, false).map_err(|_| "invalid operation")?; + let abort = super::cancellation::AbortOnDrop( + worker::web_sys::AbortController::new().map_err(|_| "cancellation unavailable")?, + ); + let request = super::cancellation::preserve_signal(request, &abort.0.signal()) + .map_err(|_| "invalid operation")?; + let mut response = Box::pin(gateway.fetch(request, env)) + .await + .map_err(|_| "origin unavailable")?; + let bytes = super::coordinator::read_response( + &mut response, + input.options.limits.websocket_buffer_bytes, + ) + .await + .map_err(|_| "invalid origin response")?; + let value = serde_json::from_slice::(&bytes) + .map_err(|_| "invalid origin response")?; + out.send(send(value)).await.map_err(|_| "consumer left")?; + } else if let Some(delivery) = delivery.filter(|delivery| delivery.options.live.is_some()) { + let shard = delivery + .shard(&binding, &value) + .map_err(|_| "invalid shard")?; + let namespace = env + .durable_object(&delivery.namespace) + .map_err(|_| "coordinator unavailable")?; + let stub = namespace + .id_from_name(&shard) + .and_then(|id| id.get_stub()) + .map_err(|_| "coordinator unavailable")?; + let response = stub + .fetch_with_request( + post_request(&input, &value, true).map_err(|_| "invalid operation")?, + ) + .await + .map_err(|_| "coordinator unavailable")?; + if response.status_code() != 101 { + return Err("live admission failed".into()); + } + let mut socket = Socket::new( + response.websocket().ok_or("coordinator stream missing")?, + input.options.limits.websocket_buffer_bytes, + 32, + ) + .map_err(|_| "invalid coordinator socket")?; + socket.send(&serde_json::json!({"type":"subscribe","payload":value}))?; + loop { + enum Event { + Frame(std::result::Result), + Ack(Option), + } + let event = match select(Box::pin(socket.next()), Box::pin(acks.next())).await { + Either::Left((value, _)) => Event::Frame(value), + Either::Right((value, _)) => Event::Ack(value), + }; + match event { + Event::Frame(Ok(mut value)) => match value["type"].as_str() { + Some("next") => out + .send(send(value["payload"].take())) + .await + .map_err(|_| "consumer left")?, + Some("ping") => { + value["payload"]["gatewayOperation"] = id.into(); + out.send(value).await.map_err(|_| "consumer left")?; + } + Some("complete") => break, + Some("error") => { + return Err(value["payload"] + .as_str() + .unwrap_or("LIVE_RESET_REQUIRED") + .into()) + } + _ => return Err("LIVE_RESET_REQUIRED".into()), + }, + Event::Ack(Some(value)) => socket.send(&value)?, + _ => return Err("LIVE_RESET_REQUIRED".into()), + } + } + } else { + let mut stream = live_transport::source(input.clone(), live_path, init)(value).await?; + while let Some(frame) = stream.next().await { + out.send(send(frame?)).await.map_err(|_| "consumer left")?; + let nonce = uuid::Uuid::now_v7().to_string(); + out.send(serde_json::json!({"type":"ping","payload":{"gatewayOperation":id,"gatewayDeliveryAck":nonce}})).await.map_err(|_|"consumer left")?; + let ack = super::timer::deadline( + Duration::from_millis(input.options.limits.read_timeout_ms), + acks.next(), + ) + .await + .map_err(|_| "slow consumer")? + .ok_or("consumer left")?; + if ack["payload"]["gatewayDeliveryAck"] != nonce { + return Err("invalid acknowledgement".into()); + } + } + } + out.send(serde_json::json!({"id":id,"type":"complete"})) + .await + .map_err(|_| "consumer left".into()) +} +// Independent forwarding works with ordinary origins without delivery control. +// Bound cumulative output because workerd has no socket backpressure API; +// exhaustion explicitly requires recovery. Legacy has no ping/pong credits. +async fn independent( + client: &mut Socket, + origin: &mut Socket, + capabilities: GraphqlCapabilities, + max_bytes: usize, + protocol: &str, +) { + let mut ids = std::collections::BTreeSet::new(); + let mut bytes = 0usize; + loop { + let (value, from_client) = + match select(Box::pin(client.next()), Box::pin(origin.next())).await { + Either::Left((value, _)) => (value, true), + Either::Right((value, _)) => (value, false), + }; + let Ok(value) = value else { + return; + }; + if from_client { + match value["type"].as_str() { + Some(kind @ ("start" | "subscribe")) + if kind + == if protocol == "graphql-ws" { + "start" + } else { + "subscribe" + } => + { + let Some(id) = value["id"] + .as_str() + .filter(|id| !id.is_empty() && id.len() <= 256) + else { + return; + }; + if ids.len() >= 128 || !ids.insert(id.to_owned()) { + return; + } + if let Err(error) = admit_request(&value["payload"], capabilities) { + let _ = client.send( + &serde_json::json!({"id":id,"type":if protocol=="graphql-ws"{"data"}else{"next"},"payload":error.envelope()}), + ); + let _ = client.send(&serde_json::json!({"id":id,"type":"complete"})); + ids.remove(id); + continue; + } + } + Some(kind @ ("stop" | "complete")) + if kind + == if protocol == "graphql-ws" { + "stop" + } else { + "complete" + } => + { + if let Some(id) = value["id"].as_str() { + ids.remove(id); + } + } + Some("connection_terminate") if protocol == "graphql-ws" => return, + Some("ping" | "pong") if protocol == "graphql-transport-ws" => {} + _ => return, + } + if origin.send(&value).is_err() { + return; + } + } else { + bytes = bytes.saturating_add(value.to_string().len()); + if bytes > max_bytes { + let _ = client.ws.close(Some(1013), Some("LIVE_RESET_REQUIRED")); + return; + } + if matches!(value["type"].as_str(), Some("complete" | "error")) { + if let Some(id) = value["id"].as_str() { + ids.remove(id); + } + } + if client.send(&value).is_err() { + return; + } + } + } +} diff --git a/src/gateway/worker/live.rs b/src/gateway/worker/live.rs new file mode 100644 index 000000000..b575ce664 --- /dev/null +++ b/src/gateway/worker/live.rs @@ -0,0 +1,541 @@ +use crate::gateway::delivery::*; +use futures_channel::{mpsc, oneshot}; +use futures_util::future::{select, AbortHandle, Abortable, Either}; +use futures_util::{future::LocalBoxFuture, stream::LocalBoxStream, StreamExt}; +use std::{ + cell::{Cell, RefCell}, + collections::{BTreeMap, BTreeSet, VecDeque}, + rc::{Rc, Weak}, + time::Duration, +}; + +/// The charge follows the shared frame through queues, history and handoff. +pub(super) struct WorkerFrame { + frame: LiveFrame, + bytes: usize, + used: Rc>, +} +impl std::ops::Deref for WorkerFrame { + type Target = LiveFrame; + fn deref(&self) -> &LiveFrame { + &self.frame + } +} +impl Drop for WorkerFrame { + fn drop(&mut self) { + self.used.set(self.used.get().saturating_sub(self.bytes)); + } +} +pub(super) type LiveSource = LocalBoxStream<'static, Result>; +pub(super) type LiveSourceFactory = + Rc LocalBoxFuture<'static, Result>>; +#[derive(Clone)] +struct Input { + admission: OriginAdmission, + request: serde_json::Value, + freshness: Option, + source: LiveSourceFactory, +} +struct Consumer { + ticket: LiveTicket, + input: Input, + frames: mpsc::Sender>, + reset: oneshot::Sender<&'static str>, +} +struct Group { + key: LiveKey, + initial: LiveKey, + consumers: BTreeSet, + history: VecDeque>, + complete_history: bool, + driver: Option, +} +impl Drop for Group { + fn drop(&mut self) { + if let Some(driver) = &self.driver { + driver.abort(); + } + } +} +struct State { + registry: LiveRegistry, + groups: BTreeMap, + consumers: BTreeMap, + next: u64, + upstreams: u64, + resets: u64, + frames: u64, + deduplicated: u64, + handoffs: u64, +} +/// Local stream drivers are owned by these groups; removing the last consumer +/// aborts the upstream and releases its socket/stream, including on disconnect. +pub(super) struct WorkerLive { + state: RefCell, + limits: LiveLimits, + payload_limit: usize, + payload_used: Rc>, + started: u64, +} +pub(super) struct LiveLease { + id: u64, + owner: Rc, + frames: mpsc::Receiver>, + reset: oneshot::Receiver<&'static str>, + expiry: u64, + terminal: Option<&'static str>, +} +impl Drop for LiveLease { + fn drop(&mut self) { + self.owner.remove(self.id, "consumer_left"); + } +} +impl LiveLease { + pub(super) async fn next(&mut self) -> Result>, &'static str> { + loop { + let remaining = Duration::from_secs(self.expiry.saturating_sub(super::now())); + if remaining.is_zero() { + return Err("AUTH_EXPIRED"); + } + if let Some(reason) = self.terminal { + if reason != "complete" { + return Err(reason); + } + let frame = self.frames.next().await; + return if super::now() >= self.expiry { + Err("AUTH_EXPIRED") + } else { + Ok(frame) + }; + } + enum Event { + Reset(&'static str), + Frame(Option>), + } + let next = async { + match select(Box::pin(&mut self.reset), Box::pin(self.frames.next())).await { + Either::Left((reason, _)) => { + Event::Reset(reason.unwrap_or("LIVE_RESET_REQUIRED")) + } + Either::Right((frame, _)) => Event::Frame(frame), + } + }; + match super::timer::deadline(remaining, next).await { + Err(_) => return Err("AUTH_EXPIRED"), + Ok(Event::Reset(reason)) => self.terminal = Some(reason), + Ok(Event::Frame(frame)) => { + return if super::now() >= self.expiry { + Err("AUTH_EXPIRED") + } else { + Ok(frame) + } + } + } + } + } + pub(super) async fn interrupted(&mut self) -> &'static str { + let remaining = Duration::from_secs(self.expiry.saturating_sub(super::now())); + if remaining.is_zero() { + return "AUTH_EXPIRED"; + } + if let Some(reason) = self.terminal { + if reason != "complete" { + return reason; + } + let _ = super::timer::Timer::new(remaining.as_millis() as u64).await; + return "AUTH_EXPIRED"; + } + match super::timer::deadline(remaining, &mut self.reset).await { + Ok(reason) => { + let reason = reason.unwrap_or("LIVE_RESET_REQUIRED"); + self.terminal = Some(reason); + if reason == "complete" { + let _ = super::timer::Timer::new(remaining.as_millis() as u64).await; + "AUTH_EXPIRED" + } else { + reason + } + } + Err(_) => "AUTH_EXPIRED", + } + } +} + +impl WorkerLive { + pub(super) fn new( + limits: LiveLimits, + payload_limit: usize, + ) -> Result, crate::gateway::GatewayError> { + let registry = LiveRegistry::new(limits) + .map_err(|_| crate::gateway::GatewayError("invalid live limits"))?; + Ok(Rc::new(Self { + state: RefCell::new(State { + registry, + groups: BTreeMap::new(), + consumers: BTreeMap::new(), + next: 0, + upstreams: 0, + resets: 0, + frames: 0, + deduplicated: 0, + handoffs: 0, + }), + limits, + payload_limit, + payload_used: Rc::new(Cell::new(0)), + started: worker::Date::now().as_millis(), + })) + } + pub(super) fn counts(&self) -> (usize, usize, u64, u64, u64, u64, u64) { + self.state + .try_borrow_mut() + .map_or((0, 0, 0, 0, 0, 0, 0), |s| { + ( + s.groups.len(), + s.consumers.len(), + s.upstreams, + s.resets, + s.frames, + s.deduplicated, + s.handoffs, + ) + }) + } + pub(super) fn join( + self: &Rc, + admission: OriginAdmission, + request: serde_json::Value, + freshness: Option, + source: LiveSourceFactory, + ) -> Result { + let initial = LiveKey::admitted(&admission, &request, freshness.as_ref(), super::now())?; + let input = Input { + admission, + request, + freshness, + source, + }; + let (mut frames, receiver) = mpsc::channel(self.limits.queue_frames); + let (reset, reset_receiver) = oneshot::channel(); + let mut state = self + .state + .try_borrow_mut() + .map_err(|_| DeliveryError::Unavailable)?; + let now = worker::Date::now().as_millis().saturating_sub(self.started); + state.registry.expire(now); + let expired = state + .groups + .keys() + .filter(|generation| !state.registry.contains_generation(**generation)) + .copied() + .collect::>(); + for generation in expired { + end(&mut state, generation, "LIVE_RESET_REQUIRED"); + } + state.next = state + .next + .checked_add(1) + .ok_or(DeliveryError::Unavailable)?; + let id = state.next; + let existing = state + .groups + .iter() + .find(|(_, group)| { + group.initial.same_initial(&initial) + && group.complete_history + && group.consumers.len() < self.limits.consumers + }) + .map(|(generation, group)| (*generation, group.key.clone())); + let key = existing + .map(|(_, key)| key) + .unwrap_or_else(|| initial.fork(id)); + let (ticket, owner) = state.registry.join(key.clone(), now)?; + let generation = ticket.generation(); + if owner { + state.groups.insert( + generation, + Group { + key, + initial, + consumers: BTreeSet::new(), + history: VecDeque::new(), + complete_history: true, + driver: None, + }, + ); + } + let group = state + .groups + .get_mut(&generation) + .ok_or(DeliveryError::Unavailable)?; + for frame in &group.history { + if !frame.satisfies(&input.admission, input.freshness.as_ref()) { + state.registry.leave(ticket); + return Err(DeliveryError::Pending); + } + frames + .try_send(frame.clone()) + .map_err(|_| DeliveryError::Unavailable)?; + } + group.consumers.insert(id); + let expiry = input.admission.expires_at; + state.consumers.insert( + id, + Consumer { + ticket, + input, + frames, + reset, + }, + ); + drop(state); + if owner { + let weak = Rc::downgrade(self); + let lifetime = self.limits.lifetime_ms; + let (handle, registration) = AbortHandle::new_pair(); + worker::wasm_bindgen_futures::spawn_local(async move { + let task = async move { + let reason = super::timer::deadline( + Duration::from_millis(lifetime), + drive(weak.clone(), generation), + ) + .await + .unwrap_or("LIVE_RESET_REQUIRED"); + if let Some(owner) = weak.upgrade() { + if let Ok(mut state) = owner.state.try_borrow_mut() { + end(&mut state, generation, reason); + } + } + }; + let _ = Abortable::new(task, registration).await; + }); + // No detached owner: Group owns the abort handle, and the driver + // retains only Weak so the coordinator can be dropped cleanly. + if let Ok(mut state) = self.state.try_borrow_mut() { + if let Some(group) = state.groups.get_mut(&generation) { + group.driver = Some(handle); + } else { + handle.abort(); + } + } else { + handle.abort(); + } + } + Ok(LiveLease { + id, + owner: self.clone(), + frames: receiver, + reset: reset_receiver, + expiry, + terminal: None, + }) + } + fn remove(&self, id: u64, reason: &'static str) { + if let Ok(mut state) = self.state.try_borrow_mut() { + remove(&mut state, id, reason); + } + } + fn input(&self, generation: u64) -> Option { + let mut state = self.state.try_borrow_mut().ok()?; + let group = state.groups.get(&generation)?; + let mut input = group + .consumers + .iter() + .filter_map(|id| state.consumers.get(id)) + .filter(|consumer| consumer.input.admission.expires_at > super::now()) + .max_by_key(|consumer| consumer.input.admission.expires_at)? + .input + .clone(); + // Reconnect under a remaining consumer's current credentials. The + // origin handles replay/reset at the last observed proven cursor. + if let Some(frame) = group.history.back() { + if !input.request["extensions"].is_object() { + input.request["extensions"] = serde_json::json!({}); + } + if !input.request["extensions"]["distributed"].is_object() { + input.request["extensions"]["distributed"] = serde_json::json!({}); + } + input.request["extensions"]["distributed"]["resume"] = serde_json::json!({"cursors":frame.payload()["extensions"]["distributed"]["live"]["cursors"]}); + } + state.upstreams = state.upstreams.saturating_add(1); + Some(input) + } + fn emit(&self, generation: u64, input: &Input, payload: serde_json::Value) -> bool { + let frame = match LiveFrame::from_origin( + &input.admission, + payload, + None, + self.limits.frame_bytes, + ) { + Ok(frame) => { + let bytes = + serde_json::to_vec(frame.payload()).map_or(usize::MAX, |bytes| bytes.len()); + let used = self.payload_used.get().saturating_add(bytes); + if used > self.payload_limit { + if let Ok(mut state) = self.state.try_borrow_mut() { + end(&mut state, generation, "LIVE_RESET_REQUIRED"); + } + return false; + } + self.payload_used.set(used); + Rc::new(WorkerFrame { + frame, + bytes, + used: self.payload_used.clone(), + }) + } + Err(_) => { + if let Ok(mut state) = self.state.try_borrow_mut() { + end(&mut state, generation, "LIVE_RESET_REQUIRED"); + } + return false; + } + }; + let Ok(mut state) = self.state.try_borrow_mut() else { + return false; + }; + state.frames = state.frames.saturating_add(1); + let Some(group) = state.groups.get_mut(&generation) else { + return false; + }; + if group + .history + .back() + .is_some_and(|last| last.same_frame(&frame)) + { + state.deduplicated = state.deduplicated.saturating_add(1); + return true; + } + group.history.push_back(frame.clone()); + if group.history.len() > self.limits.history_frames { + group.history.pop_front(); + group.complete_history = false; + } + let ids = group.consumers.iter().copied().collect::>(); + for id in ids { + let Some(consumer) = state.consumers.get_mut(&id) else { + continue; + }; + let reason = if consumer.input.admission.expires_at <= super::now() { + Some("AUTH_EXPIRED") + } else if !frame.satisfies(&consumer.input.admission, consumer.input.freshness.as_ref()) + { + Some("FRESHNESS_PENDING") + } else if consumer.frames.try_send(frame.clone()).is_err() { + Some("LIVE_RESET_REQUIRED") + } else { + None + }; + if let Some(reason) = reason { + remove(&mut state, id, reason); + } + } + // Each replay's own frame is queued first. At equal proven cursor and + // data, future frames can move to an existing operation without a gap. + let Some(group) = state.groups.get(&generation) else { + return false; + }; + let target = state + .groups + .iter() + .find(|(other, target)| { + **other < generation + && target.key.same_operation(&group.key) + && target + .history + .back() + .is_some_and(|head| head.same_cursor(&frame)) + }) + .map(|(id, group)| (*id, group.key.clone())); + if let Some((target, key)) = target { + let ids = group.consumers.iter().copied().collect::>(); + let now = worker::Date::now().as_millis().saturating_sub(self.started); + for id in ids { + let Ok((ticket, new_owner)) = state.registry.join(key.clone(), now) else { + break; + }; + if new_owner { + state.registry.leave(ticket); + break; + } + let Some(consumer) = state.consumers.get_mut(&id) else { + state.registry.leave(ticket); + continue; + }; + let old = std::mem::replace(&mut consumer.ticket, ticket); + state.registry.leave(old); + if let Some(group) = state.groups.get_mut(&generation) { + group.consumers.remove(&id); + } + if let Some(group) = state.groups.get_mut(&target) { + group.consumers.insert(id); + } + state.handoffs = state.handoffs.saturating_add(1); + } + if state + .groups + .get(&generation) + .is_some_and(|group| group.consumers.is_empty()) + { + state.groups.remove(&generation); + return false; + } + } + true + } +} +fn remove(state: &mut State, id: u64, reason: &'static str) { + let Some(consumer) = state.consumers.remove(&id) else { + return; + }; + let generation = consumer.ticket.generation(); + if reason != "consumer_left" && reason != "complete" { + state.resets = state.resets.saturating_add(1); + } + let _ = consumer.reset.send(reason); + let last = state.registry.leave(consumer.ticket); + if let Some(group) = state.groups.get_mut(&generation) { + group.consumers.remove(&id); + } + if last { + state.groups.remove(&generation); + } +} +fn end(state: &mut State, generation: u64, reason: &'static str) { + let ids = state + .groups + .get(&generation) + .map(|group| group.consumers.iter().copied().collect::>()) + .unwrap_or_default(); + for id in ids { + remove(state, id, reason); + } + state.groups.remove(&generation); +} +async fn drive(owner: Weak, generation: u64) -> &'static str { + loop { + let input = match owner.upgrade().and_then(|owner| owner.input(generation)) { + Some(input) => input, + None => return "AUTH_EXPIRED", + }; + let expiry = Duration::from_secs(input.admission.expires_at.saturating_sub(super::now())); + let run = async { + let mut stream = (input.source)(input.request.clone()).await?; + while let Some(frame) = stream.next().await { + let frame = frame?; + if !owner + .upgrade() + .is_some_and(|owner| owner.emit(generation, &input, frame)) + { + return Err("upstream no longer owned".into()); + } + } + Ok::<(), String>(()) + }; + match super::timer::deadline(expiry, run).await { + Ok(Ok(())) => return "complete", + Ok(Err(_)) => return "LIVE_RESET_REQUIRED", + Err(_) => continue, // Reauthenticate with a remaining unexpired consumer. + } + } +} diff --git a/src/gateway/worker/live_transport.rs b/src/gateway/worker/live_transport.rs new file mode 100644 index 000000000..fb02b41f0 --- /dev/null +++ b/src/gateway/worker/live_transport.rs @@ -0,0 +1,122 @@ +use super::{coordinator::OriginRequest, live::LiveSourceFactory, proxy, socket::Socket}; +use futures_util::{FutureExt, StreamExt}; +use std::rc::Rc; +use worker::{Fetch, Headers, Request, RequestInit, RequestRedirect, Result}; + +pub(super) async fn handshake( + input: &OriginRequest, + live_path: &str, + protocol: &str, +) -> Result { + let headers = Headers::new(); + for (name, value) in &input.headers { + if !matches!( + name.as_str(), + "content-length" | "content-type" | "sec-websocket-key" + ) { + headers.append(name, value)?; + } + } + proxy::prepare_headers(&headers, &input.options, &input.context, true)?; + headers.set("sec-websocket-protocol", protocol)?; + let public = worker::Url::parse(&input.url)?; + let url = format!( + "{}{}{}", + input.origin.trim_end_matches('/'), + live_path, + public.query().map(|q| format!("?{q}")).unwrap_or_default() + ); + let mut init = RequestInit::new(); + init.headers = headers; + init.redirect = RequestRedirect::Manual; + let response = proxy::timeout( + input.options.limits.header_timeout_ms, + Fetch::Request(Request::new_with_init(&url, &init)?).send(), + ) + .await?; + if response.status_code() != 101 + || response.headers().get("sec-websocket-protocol")?.as_deref() != Some(protocol) + { + return Err(worker::Error::RustError("upstream upgrade denied".into())); + } + let socket = response + .websocket() + .ok_or_else(|| worker::Error::RustError("upstream upgrade missing".into()))?; + Socket::new(socket, input.options.limits.websocket_buffer_bytes, 32) +} +pub(super) async fn initialize( + socket: &mut Socket, + init: serde_json::Value, + milliseconds: u64, +) -> std::result::Result { + socket.send(&serde_json::json!({"type":"connection_init","payload":init}))?; + super::timer::deadline(std::time::Duration::from_millis(milliseconds), async { + loop { + let value = socket.next().await?; + match value["type"].as_str() { + Some("connection_ack") => return Ok(value), + Some("ping") => { + socket.send(&serde_json::json!({"type":"pong","payload":value["payload"]}))? + } + Some("connection_error" | "error") => return Err("origin admission denied".into()), + _ => return Err("invalid origin initialization".into()), + } + } + }) + .await + .map_err(|_| "origin admission timed out".to_owned())? +} +pub(super) fn source( + input: OriginRequest, + live_path: String, + init: serde_json::Value, +) -> LiveSourceFactory { + Rc::new(move |mut request| { + let input = input.clone(); + let live_path = live_path.clone(); + let init = init.clone(); + async move { + let mut socket = handshake(&input, &live_path, "graphql-transport-ws") + .await + .map_err(|_| "origin unavailable".to_owned())?; + initialize(&mut socket, init, input.options.limits.header_timeout_ms).await?; + if let Some(extensions) = request + .get_mut("extensions") + .and_then(serde_json::Value::as_object_mut) + { + extensions.remove("gatewayDelivery"); + } + socket + .send(&serde_json::json!({"id":"upstream","type":"subscribe","payload":request}))?; + Ok( + futures_util::stream::unfold(socket, |mut socket| async move { + loop { + let value = match socket.next().await { + Ok(value) => value, + Err(error) => return Some((Err(error), socket)), + }; + match value["type"].as_str() { + Some("next") if value["id"] == "upstream" => { + return Some((Ok(value["payload"].clone()), socket)) + } + Some("complete") if value["id"] == "upstream" => return None, + Some("error") => { + return Some((Err("upstream operation failed".into()), socket)) + } + Some("ping") => { + if let Err(error) = socket.send( + &serde_json::json!({"type":"pong","payload":value["payload"]}), + ) { + return Some((Err(error), socket)); + } + } + _ => {} + } + } + }) + .boxed_local(), + ) + } + .boxed_local() + }) +} diff --git a/src/gateway/worker/mod.rs b/src/gateway/worker/mod.rs new file mode 100644 index 000000000..ea3f0d9eb --- /dev/null +++ b/src/gateway/worker/mod.rs @@ -0,0 +1,446 @@ +//! Explicit workers-rs gateway mounting. No listener or domain projector is linked. +mod cancellation; +mod coordinator; +mod frontend; +mod live; +mod live_transport; +mod proxy; +mod raw_socket; +mod socket; +mod timer; +pub use coordinator::{WorkerCoordinator, WorkerDeliveryBinding, WorkerDeliveryOptions}; + +use super::{ + Admission, AuthError, BackendCredential, BindingKind, Credentials, Gateway, GatewayError, + GraphqlExecutor, RequestContext, +}; +use futures_util::future::LocalBoxFuture; +use std::{collections::BTreeMap, future::Future, rc::Rc}; +use worker::{Env, Request, Response, Result}; + +/// Local-future provider; every consumer authenticates before route admission. +#[derive(Clone)] +pub struct WorkerAuth( + Rc< + dyn Fn( + Credentials, + ) -> LocalBoxFuture<'static, std::result::Result>, + >, +); +impl WorkerAuth { + /// Bind a trusted application/session provider. Backend authorization remains mandatory. + pub fn new(provider: F) -> Self + where + F: Fn(Credentials) -> Fut + 'static, + Fut: Future> + 'static, + { + Self(Rc::new(move |credentials| Box::pin(provider(credentials)))) + } + /// Opaque cookies may reach delegated auth/UI handlers. Unvalidated bearer input fails closed. + pub fn anonymous() -> Self { + Self::new(|credentials| async move { + if credentials.authorization.is_some() { + return Err(AuthError::Unauthorized); + } + RequestContext::from_provider(None, "anonymous-v1", BackendCredential::None) + .map_err(|_| AuthError::Unavailable) + }) + } +} +/// Custom mounted handler, including application-owned auth lifecycle handlers. +#[derive(Clone)] +pub struct WorkerHandler( + Rc LocalBoxFuture<'static, Result>>, +); +impl WorkerHandler { + /// Adapt a local Worker handler without requiring Send or a native runtime. + pub fn new(handler: F) -> Self + where + F: Fn(Request, RequestContext, Env) -> Fut + 'static, + Fut: Future> + 'static, + { + Self(Rc::new(move |request, context, env| { + Box::pin(handler(request, context, env)) + })) + } +} +/// Explicit per-request and upgraded-connection bounds. +#[derive(Clone, Debug)] +pub struct WorkerLimits { + /// Maximum incoming request bytes. + pub request_bytes: usize, + /// Maximum aggregate queued wire bytes per WebSocket (also bounds one frame). + pub websocket_buffer_bytes: usize, + /// Maximum response header wait in milliseconds. + pub header_timeout_ms: u64, + /// Maximum response stream idle wait in milliseconds. + pub read_timeout_ms: u64, + /// Maximum upgraded connection lifetime in milliseconds. + pub websocket_lifetime_ms: u64, +} +impl Default for WorkerLimits { + fn default() -> Self { + Self { + request_bytes: 256 * 1024, + websocket_buffer_bytes: 256 * 1024, + header_timeout_ms: 30000, + read_timeout_ms: 60000, + websocket_lifetime_ms: 3600000, + } + } +} +/// Trusted ingress configuration; public origin is never inferred from forwarded headers. +#[derive(Clone, Debug)] +pub struct WorkerOptions { + /// Canonical public HTTP(S) origin. + pub public_origin: String, + /// Bounded transport settings. + pub limits: WorkerLimits, + /// Additional incoming identity/secret header names to remove. + pub strip_headers: Vec, + /// Stable deployment identity used to reject proxy loops, not a secret. + pub hop_id: String, +} +impl WorkerOptions { + /// Default bounded settings for the public origin. + pub fn new(public_origin: impl Into) -> Self { + Self { + public_origin: public_origin.into(), + limits: WorkerLimits::default(), + strip_headers: Vec::new(), + hop_id: "application-gateway-worker-v1".into(), + } + } +} +/// Resources allocated only for explicitly selected portable bindings. +#[derive(Clone)] +pub enum WorkerBinding { + /// Local application handler. + Handler(WorkerHandler), + /// Static asset service binding, fetched only after route admission. + Assets(String), + /// Whole UI/auth reverse proxy. + UiProxy { + /// Allow transparent WebSocket upgrades to this UI target. + websocket: bool, + }, + /// Named portable admission policy. + Admission(Admission), + /// Whole remote GraphQL endpoint; embedded executors are rejected. + Graphql { + /// Origin HTTP path, independent of the public mount path. + http_path: String, + /// Optional origin live endpoint path. + live_path: Option, + /// Optional sharded Durable Object delivery; never isolate-local state. + delivery: Option, + }, +} +/// A mounted Worker gateway. Construction starts no network work. +#[derive(Clone)] +pub struct WorkerGateway(Rc); +struct Inner { + gateway: Gateway, + options: WorkerOptions, + bindings: BTreeMap, + auth: WorkerAuth, +} +impl WorkerGateway { + /// Validate bindings and capabilities before handling requests. + pub fn new( + gateway: Gateway, + options: WorkerOptions, + bindings: impl IntoIterator, + auth: WorkerAuth, + ) -> std::result::Result { + super::config::validate_origin(&options.public_origin)?; + if options.hop_id.is_empty() + || options.hop_id.len() > 128 + || !options + .hop_id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) + || options.strip_headers.len() > 128 + || options + .strip_headers + .iter() + .any(|s| s.is_empty() || !s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')) + { + return Err(GatewayError("invalid Worker header configuration")); + } + let limits = &options.limits; + if limits.request_bytes == 0 + || limits.request_bytes > 16 * 1024 * 1024 + || limits.websocket_buffer_bytes == 0 + || limits.websocket_buffer_bytes > 1024 * 1024 + || limits.header_timeout_ms == 0 + || limits.header_timeout_ms > 300000 + || limits.read_timeout_ms == 0 + || limits.read_timeout_ms > 300000 + || limits.websocket_lifetime_ms == 0 + || limits.websocket_lifetime_ms > 3600000 + { + return Err(GatewayError("invalid Worker transport limits")); + } + let mut registry = BTreeMap::new(); + for (id, binding) in bindings { + let declaration = gateway + .binding(&id) + .ok_or(GatewayError("undeclared Worker binding"))?; + let compatible = match (&declaration.kind, &binding) { + (BindingKind::Handler, WorkerBinding::Handler(_)) + | (BindingKind::Admission, WorkerBinding::Admission(_)) + | (BindingKind::Assets, WorkerBinding::Assets(_)) => true, + (BindingKind::UiProxy { origin }, WorkerBinding::UiProxy { .. }) => { + origin.trim_end_matches('/') != options.public_origin.trim_end_matches('/') + } + ( + BindingKind::Graphql { + executor: GraphqlExecutor::Remote { origin }, + capabilities, + delivery, + .. + }, + WorkerBinding::Graphql { + http_path, + live_path, + delivery: resource, + }, + ) => { + origin.trim_end_matches('/') != options.public_origin.trim_end_matches('/') + && super::route::normalize_path(http_path).is_ok() + && live_path + .as_ref() + .is_none_or(|p| super::route::normalize_path(p).is_ok()) + && capabilities.live == live_path.is_some() + && resource.as_ref().map_or_else( + || { + !delivery.snapshots + && !delivery.coalescing + && !delivery.live_sharing + }, + |resource| { + resource.validate().is_ok() + && resource.options.capabilities() == *delivery + }, + ) + } + _ => false, + }; + if !compatible || registry.insert(id, binding).is_some() { + return Err(GatewayError("incompatible or duplicate Worker binding")); + } + } + if gateway.routes().iter().any(|route| { + !registry.contains_key(&route.target) + || route.admission.iter().any(|id| !registry.contains_key(id)) + }) { + return Err(GatewayError("missing Worker binding")); + } + Ok(Self(Rc::new(Inner { + gateway, + options, + bindings: registry, + auth, + }))) + } + /// Select one owner, authenticate, admit and execute exactly once. + pub async fn fetch(&self, request: Request, env: Env) -> Result { + cancellation::run(request.inner().signal(), self.dispatch(request, env, None)).await + } + /// Execute inside the selected Durable Object, repeating provider and origin admission. + /// This entrypoint is an in-process mount, never a client header or URL flag. + pub async fn fetch_coordinated( + &self, + request: Request, + env: Env, + coordinator: Rc, + ) -> Result { + cancellation::run( + request.inner().signal(), + self.dispatch(request, env, Some(coordinator)), + ) + .await + } + async fn dispatch( + &self, + mut request: Request, + env: Env, + coordinator: Option>, + ) -> Result { + let url = request.url()?; + let selected = match self.0.gateway.select(request.method().as_ref(), url.path()) { + Ok(Some(selected)) => selected, + Ok(None) => return Response::error("not found", 404), + Err(_) => return Response::error("invalid route", 400), + }; + let credentials = Credentials { + authorization: request.headers().get("authorization")?, + cookie: request.headers().get("cookie")?, + }; + let context = match (self.0.auth.0)(credentials).await { + Ok(context) => context, + Err(error) => return auth_error(error), + }; + if let Err(error) = Admission::Public.check(&context, now()) { + return auth_error(error); + } + for id in &selected.route().admission { + let Some(WorkerBinding::Admission(policy)) = self.0.bindings.get(id) else { + return Response::error("invalid admission", 503); + }; + if let Err(error) = policy.check(&context, now()) { + return auth_error(error); + } + } + if !selected.method_allowed() { + return Response::error("method not allowed", 405); + } + let binding = &self.0.bindings[&selected.binding().id]; + match (binding, &selected.binding().kind) { + (WorkerBinding::Handler(handler), _) => (handler.0)(request, context, env).await, + (WorkerBinding::Assets(binding), _) => { + if !matches!(request.method(), worker::Method::Get | worker::Method::Head) { + return Response::error("method not allowed", 405); + } + env.service(binding)?.fetch_request(request).await + } + (WorkerBinding::UiProxy { websocket }, BindingKind::UiProxy { origin }) => { + proxy::forward(request, origin, None, *websocket, &self.0.options, &context).await + } + ( + WorkerBinding::Graphql { + http_path, + live_path, + delivery, + }, + BindingKind::Graphql { + executor: GraphqlExecutor::Remote { origin }, + capabilities, + .. + }, + ) => { + if proxy::is_upgrade(&request)? { + if let (Some(coordinator), Some(delivery)) = (&coordinator, delivery) { + if coordinator.capabilities() != delivery.options.capabilities() { + return Response::error("coordinator configuration mismatch", 503); + } + let input = coordinator::OriginRequest { + origin: origin.clone(), + path: http_path.clone(), + url: request.url()?.to_string(), + headers: request.headers().entries().collect(), + options: self.0.options.clone(), + context, + }; + return coordinator.upgrade( + input, + live_path + .clone() + .ok_or_else(|| worker::Error::RustError("live disabled".into()))?, + *capabilities, + ); + } + } + if proxy::is_upgrade(&request)? && coordinator.is_none() { + if !capabilities.live { + return Response::error("live disabled", 405); + } + let input = coordinator::OriginRequest { + origin: origin.clone(), + path: http_path.clone(), + url: request.url()?.to_string(), + headers: request.headers().entries().collect(), + options: self.0.options.clone(), + context, + }; + return frontend::upgrade( + self.clone(), + env, + request, + input, + live_path.clone().expect("validated live path"), + *capabilities, + delivery.clone(), + selected.binding().id.clone(), + ) + .await; + } + if request.method() != worker::Method::Post { + return Response::error("method not allowed", 405); + } + let bytes = match proxy::timeout( + self.0.options.limits.header_timeout_ms, + proxy::read_request(&mut request, self.0.options.limits.request_bytes), + ) + .await + { + Ok(bytes) => bytes, + Err(worker::Error::RustError(message)) if message == "request too large" => { + return Response::error(message, 413) + } + Err(_) => return Response::error("invalid or timed out request body", 400), + }; + let value: serde_json::Value = match serde_json::from_slice(&bytes) { + Ok(value) => value, + Err(_) => return Response::error("invalid GraphQL request", 400), + }; + if let Err(error) = super::graphql::admit_request(&value, *capabilities) { + return Response::from_json(&error.envelope()); + } + if let Some(delivery) = delivery { + if super::graphql::operation_kind( + value["query"].as_str().unwrap_or(""), + value["operationName"].as_str(), + ) == Ok(super::graphql::OperationKind::Query) + { + if let Some(coordinator) = coordinator { + if coordinator.capabilities() != delivery.options.capabilities() { + return Response::error("coordinator configuration mismatch", 503); + } + let input = coordinator::OriginRequest { + origin: origin.clone(), + path: http_path.clone(), + url: request.url()?.to_string(), + headers: request.headers().entries().collect(), + options: self.0.options.clone(), + context, + }; + return coordinator.execute(input, value).await; + } + let shard = delivery.shard(&selected.binding().id, &value)?; + let namespace = env.durable_object(&delivery.namespace)?; + let stub = namespace.id_from_name(&shard)?.get_stub()?; + return stub + .fetch_with_request(proxy::with_body(&request, bytes)?) + .await; + } + } + let request = proxy::with_body(&request, bytes)?; + proxy::forward( + request, + origin, + Some(http_path), + false, + &self.0.options, + &context, + ) + .await + } + _ => Response::error("invalid execution binding", 503), + } + } +} +fn auth_error(error: AuthError) -> Result { + Response::error( + error.to_string(), + match error { + AuthError::Unauthorized => 401, + AuthError::Forbidden => 403, + AuthError::Unavailable => 503, + }, + ) +} +fn now() -> u64 { + worker::Date::now().as_millis() / 1000 +} diff --git a/src/gateway/worker/proxy.rs b/src/gateway/worker/proxy.rs new file mode 100644 index 000000000..6e2c693c7 --- /dev/null +++ b/src/gateway/worker/proxy.rs @@ -0,0 +1,297 @@ +use super::{RequestContext, WorkerOptions}; +use crate::gateway::{is_untrusted_identity_header, BackendCredential}; +use futures_util::{ + future::{select, Either}, + StreamExt, +}; +use std::{cell::Cell, future::Future, rc::Rc}; +use worker::{ + AbortController, Fetch, Headers, Request, RequestInit, RequestRedirect, Response, Result, + WebSocketPair, +}; + +pub(super) async fn timeout( + milliseconds: u64, + future: impl Future>, +) -> Result { + match select( + Box::pin(future), + Box::pin(super::timer::Timer::new(milliseconds)), + ) + .await + { + Either::Left((result, _)) => result, + Either::Right(_) => Err(worker::Error::RustError("gateway deadline exceeded".into())), + } +} +struct AbortOnDrop(Option); +impl Drop for AbortOnDrop { + fn drop(&mut self) { + if let Some(controller) = self.0.take() { + controller.abort(); + } + } +} +pub(super) fn is_upgrade(request: &Request) -> Result { + Ok(request + .headers() + .get("upgrade")? + .is_some_and(|value| value.eq_ignore_ascii_case("websocket"))) +} +pub(super) fn prepare_headers( + headers: &Headers, + options: &WorkerOptions, + context: &RequestContext, + upgrade: bool, +) -> Result<()> { + let nominated = headers.get("connection")?.unwrap_or_default(); + for name in nominated + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + { + headers.delete(name)?; + } + for name in headers.keys().collect::>() { + if is_untrusted_identity_header(&name) + || options + .strip_headers + .iter() + .any(|s| s.eq_ignore_ascii_case(&name)) + || matches!( + name.as_str(), + "connection" + | "keep-alive" + | "proxy-authenticate" + | "proxy-authorization" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + | "authorization" + | "host" + ) + { + headers.delete(&name)?; + } + } + if let BackendCredential::Bearer(token) = context.backend_credential() { + headers.set("authorization", &format!("Bearer {token}"))?; + } + let public = worker::Url::parse(&options.public_origin)?; + let authority = &public[url::Position::BeforeHost..url::Position::AfterPort]; + headers.set("x-forwarded-host", authority)?; + headers.set("x-forwarded-proto", public.scheme())?; + // Workers require Host to agree with the fetched URL. Trusted public origin + // is therefore carried in forwarded headers for delegated auth handlers. + if upgrade { + headers.set("upgrade", "websocket")?; + } + let hops = headers + .get("x-distributed-gateway-hops")? + .unwrap_or_default(); + if hops.len() > 1024 + || hops.split(',').count() > 8 + || hops.split(',').any(|s| s.trim() == options.hop_id) + { + return Err(worker::Error::RustError("gateway loop".into())); + } + headers.set( + "x-distributed-gateway-hops", + &if hops.is_empty() { + options.hop_id.clone() + } else { + format!("{hops},{}", options.hop_id) + }, + )?; + Ok(()) +} +pub(super) async fn read_request(request: &mut Request, max: usize) -> Result> { + if request + .headers() + .get("content-length")? + .and_then(|s| s.parse::().ok()) + .is_some_and(|n| n > max) + { + return Err(worker::Error::RustError("request too large".into())); + } + if request.inner().body().is_none() { + return Ok(Vec::new()); + } + let mut stream = request.stream()?; + let mut bytes = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + if bytes.len().saturating_add(chunk.len()) > max { + return Err(worker::Error::RustError("request too large".into())); + } + bytes.extend(chunk); + } + Ok(bytes) +} +pub(super) fn with_body(request: &Request, bytes: Vec) -> Result { + let mut init = RequestInit::new(); + init.method = request.method(); + init.headers = copy_headers(request.headers())?; + init.redirect = RequestRedirect::Manual; + init.body = Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()); + super::cancellation::preserve_signal( + Request::new_with_init(request.url()?.as_str(), &init)?, + &request.inner().signal(), + ) +} +pub(super) async fn forward( + mut request: Request, + origin: &str, + path: Option<&str>, + allow_upgrade: bool, + options: &WorkerOptions, + context: &RequestContext, +) -> Result { + let upgrade = is_upgrade(&request)?; + if upgrade && !allow_upgrade { + return Response::error("upgrade disabled", 400); + } + if request + .headers() + .get("content-length")? + .and_then(|s| s.parse::().ok()) + .is_some_and(|n| n > options.limits.request_bytes) + { + return Response::error("request too large", 413); + } + let source = request.url()?; + let url = format!( + "{}{}{}", + origin.trim_end_matches('/'), + path.unwrap_or(source.path()), + source.query().map(|q| format!("?{q}")).unwrap_or_default() + ); + let headers = copy_headers(request.headers())?; + if prepare_headers(&headers, options, context, upgrade).is_err() { + return Response::error("invalid proxy request", 400); + } + let mut init = RequestInit::new(); + init.method = request.method(); + init.headers = headers; + init.redirect = RequestRedirect::Manual; + init.cache = Some(worker::CacheMode::NoStore); + let oversized = Rc::new(Cell::new(false)); + if request.inner().body().is_some() { + let oversized = oversized.clone(); + let max = options.limits.request_bytes; + let stream = request.stream()?; + let bounded = + futures_util::stream::try_unfold((stream, 0usize), move |(mut stream, total)| { + let oversized = oversized.clone(); + async move { + match stream.next().await { + Some(chunk) => { + let chunk = chunk?; + let total = total.saturating_add(chunk.len()); + if total > max { + oversized.set(true); + return Err(worker::Error::RustError("request too large".into())); + } + Ok(Some((chunk, (stream, total)))) + } + None => Ok(None), + } + } + }); + let body: worker::web_sys::Response = Response::from_stream(bounded)?.into(); + init.body = body.body().map(Into::into); + } + let outbound = Request::new_with_init(&url, &init)?; + let controller = AbortController::default(); + let signal = controller.signal(); + let guard = AbortOnDrop(Some(controller)); + let mut response = match timeout( + options.limits.header_timeout_ms, + Fetch::Request(outbound).send_with_signal(&signal), + ) + .await + { + Ok(response) => response, + Err(_) if oversized.get() => return Response::error("request too large", 413), + Err(_) => return Response::error("origin unavailable", 502), + }; + if oversized.get() { + return Response::error("request too large", 413); + } + let mutable_headers = copy_headers(response.headers())?; + response = response.with_headers(mutable_headers); + rewrite_redirect(&mut response, origin, &options.public_origin)?; + if response.status_code() == 101 { + if !allow_upgrade { + return Response::error("unexpected upgrade", 502); + } + let headers = copy_headers(response.headers())?; + let Some(origin) = response.websocket() else { + return Response::error("invalid upgrade", 502); + }; + let pair = WebSocketPair::new()?; + let client = pair.client; + let lifetime = + context + .identity() + .map_or(options.limits.websocket_lifetime_ms, |identity| { + options + .limits + .websocket_lifetime_ms + .min(identity.expires_at().saturating_sub(super::now()) * 1000) + }); + let max = options.limits.websocket_buffer_bytes; + worker::wasm_bindgen_futures::spawn_local(async move { + let _guard = guard; + let _ = timeout( + lifetime, + super::raw_socket::bridge(pair.server, origin, max), + ) + .await; + }); + return Ok(Response::from_websocket(client)?.with_headers(headers)); + } + if request.method() == worker::Method::Head || matches!(response.status_code(), 204 | 304) { + return Ok(response); + } + let headers = copy_headers(response.headers())?; + let status = response.status_code(); + let encode = *response.encode_body(); + if !matches!(response.body(), worker::ResponseBody::Stream(_)) { + return Ok(response); + } + let stream = response.stream()?; + let idle = options.limits.read_timeout_ms; + let bounded = + futures_util::stream::try_unfold((stream, guard), move |(mut stream, guard)| async move { + let next = timeout(idle, async { stream.next().await.transpose() }).await?; + Ok::<_, worker::Error>(next.map(|chunk| (chunk, (stream, guard)))) + }); + Ok(Response::from_stream(bounded)? + .with_status(status) + .with_headers(headers) + .with_encode_body(encode)) +} +fn rewrite_redirect(response: &mut Response, origin: &str, public: &str) -> Result<()> { + if let Some(location) = response.headers().get("location")? { + if let Ok(url) = worker::Url::parse(&location) { + if url.origin() == worker::Url::parse(origin)?.origin() { + response.headers_mut().set( + "location", + &format!( + "{}{}", + public.trim_end_matches('/'), + &url[url::Position::BeforePath..] + ), + )?; + } + } + } + Ok(()) +} +pub(super) fn copy_headers(headers: &Headers) -> Result { + Ok(Headers(worker::web_sys::Headers::new_with_headers( + &headers.0, + )?)) +} diff --git a/src/gateway/worker/raw_socket.rs b/src/gateway/worker/raw_socket.rs new file mode 100644 index 000000000..df6430d7d --- /dev/null +++ b/src/gateway/worker/raw_socket.rs @@ -0,0 +1,166 @@ +use futures_channel::mpsc; +use futures_util::StreamExt; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; +use worker::{ + js_sys::{ArrayBuffer, Reflect, Uint8Array}, + wasm_bindgen::{closure::Closure, JsCast, JsValue}, + Result, WebSocket, +}; + +type SocketCallback = (&'static str, Closure); +pub(super) enum Frame { + Text(String), + Bytes(Vec), + Close(u16, String), +} +impl Frame { + fn size(&self) -> usize { + match self { + Self::Text(s) => s.len(), + Self::Bytes(b) => b.len(), + Self::Close(_, s) => s.len(), + } + } + pub fn send(&self, socket: &WebSocket) -> Result<()> { + match self { + Self::Text(s) => socket.send_with_str(s), + Self::Bytes(b) => socket.send_with_bytes(b), + Self::Close(code, reason) => socket.close(Some(*code), Some(reason)), + } + } +} +/// UI proxy callbacks have both frame-count and aggregate-byte bounds. +pub(super) struct RawSocket { + pub ws: WebSocket, + receiver: mpsc::Receiver>, + bytes: Rc>, + overflow: Rc>, + callbacks: Vec, +} +impl RawSocket { + pub fn new(ws: WebSocket, max: usize) -> Result { + Reflect::set(ws.as_ref(), &"binaryType".into(), &"arraybuffer".into())?; + let (sender, receiver) = mpsc::channel(16); + let sender = Rc::new(RefCell::new(sender)); + let bytes = Rc::new(Cell::new(0usize)); + let overflow = Rc::new(Cell::new(false)); + let mut callbacks = Vec::new(); + for kind in ["message", "close", "error"] { + let sender = sender.clone(); + let bytes = bytes.clone(); + let overflow = overflow.clone(); + let socket = ws.clone(); + let callback = Closure::wrap_assert_unwind_safe(Box::new(move |event: JsValue| { + let frame = match kind { + "message" => Reflect::get(&event, &"data".into()).ok().and_then(|data| { + if let Some(text) = data.as_string() { + Some(Frame::Text(text)) + } else if data.is_instance_of::() { + Some(Frame::Bytes(Uint8Array::new(&data).to_vec())) + } else { + None + } + }), + "close" => { + let code = Reflect::get(&event, &"code".into()) + .ok() + .and_then(|c| c.as_f64()) + .unwrap_or(1012.0) as u16; + let reason = Reflect::get(&event, &"reason".into()) + .ok() + .and_then(|c| c.as_string()) + .unwrap_or_default(); + Some(Frame::Close( + if matches!(code, 1005 | 1006 | 1015) { + 1012 + } else { + code + }, + reason, + )) + } + _ => None, + }; + let total = bytes + .get() + .saturating_add(frame.as_ref().map_or(0, Frame::size)); + let mut sender = sender.borrow_mut(); + if total > max || sender.try_send(frame).is_err() { + overflow.set(true); + sender.close_channel(); + let _ = socket.close(Some(1013), Some("proxy queue limit")); + } else { + bytes.set(total); + } + }) + as Box); + ws.as_ref() + .add_event_listener_with_callback(kind, callback.as_ref().unchecked_ref())?; + callbacks.push((kind, callback)); + } + ws.accept()?; + Ok(Self { + ws, + receiver, + bytes, + overflow, + callbacks, + }) + } + async fn next(&mut self) -> Option { + if self.overflow.get() { + return None; + } + let frame = self.receiver.next().await??; + self.bytes + .set(self.bytes.get().saturating_sub(frame.size())); + if self.overflow.get() { + None + } else { + Some(frame) + } + } +} +impl Drop for RawSocket { + fn drop(&mut self) { + for (kind, callback) in self.callbacks.drain(..) { + let _ = self + .ws + .as_ref() + .remove_event_listener_with_callback(kind, callback.as_ref().unchecked_ref()); + } + let _ = self.ws.close(Some(1012), Some("gateway connection ended")); + } +} +pub(super) async fn bridge(client: WebSocket, origin: WebSocket, max: usize) -> Result<()> { + let mut client = RawSocket::new(client, max)?; + let mut origin = RawSocket::new(origin, max)?; + let mut delivered = 0usize; + loop { + let (frame, from_client) = + match futures_util::future::select(Box::pin(client.next()), Box::pin(origin.next())) + .await + { + futures_util::future::Either::Left((frame, _)) => (frame, true), + futures_util::future::Either::Right((frame, _)) => (frame, false), + }; + let Some(frame) = frame else { + return Ok(()); + }; + delivered = delivered.saturating_add(frame.size()); + // workerd exposes no bufferedAmount or send backpressure for arbitrary + // UI protocols. Bound cumulative delivery, then require reconnect. + if delivered > max.saturating_mul(8) { + let _ = client.ws.close(Some(1013), Some("proxy delivery limit")); + let _ = origin.ws.close(Some(1013), Some("proxy delivery limit")); + return Ok(()); + } + frame.send(if from_client { &origin.ws } else { &client.ws })?; + if matches!(frame, Frame::Close(..)) { + return Ok(()); + } + } +} diff --git a/src/gateway/worker/socket.rs b/src/gateway/worker/socket.rs new file mode 100644 index 000000000..7226b0ca7 --- /dev/null +++ b/src/gateway/worker/socket.rs @@ -0,0 +1,99 @@ +use futures_channel::mpsc; +use futures_util::StreamExt; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; +use worker::{ + js_sys::Reflect, + wasm_bindgen::{closure::Closure, JsCast, JsValue}, + Result, WebSocket, +}; +/// Runtime callbacks feed a bounded queue. workers-rs EventStream is unbounded. +type SocketCallback = (&'static str, Closure); +pub(super) struct Socket { + pub ws: WebSocket, + receiver: mpsc::Receiver>, + overflow: Rc>, + queued_bytes: Rc>, + callbacks: Vec, +} +impl Socket { + pub fn new(ws: WebSocket, max_bytes: usize, queue: usize) -> Result { + let (sender, receiver) = mpsc::channel(queue); + let sender = Rc::new(RefCell::new(sender)); + let overflow = Rc::new(Cell::new(false)); + let queued_bytes = Rc::new(Cell::new(0usize)); + let mut callbacks = Vec::new(); + for kind in ["message", "close", "error"] { + let sender = sender.clone(); + let overflow = overflow.clone(); + let queued_bytes = queued_bytes.clone(); + let socket = ws.clone(); + let callback = Closure::wrap_assert_unwind_safe(Box::new(move |event: JsValue| { + let value = if kind == "message" { + Reflect::get(&event, &"data".into()) + .ok() + .and_then(|data| data.as_string()) + .filter(|text| text.len() <= max_bytes) + .ok_or_else(|| "invalid or oversized GraphQL frame".to_owned()) + } else { + Err("socket disconnected".to_owned()) + }; + let mut sender = sender.borrow_mut(); + let bytes = value.as_ref().map_or(0, String::len); + let total = queued_bytes.get().saturating_add(bytes); + if total > max_bytes || sender.try_send(value).is_err() { + overflow.set(true); + sender.close_channel(); + let _ = socket.close(Some(1013), Some("LIVE_RESET_REQUIRED")); + } else { + queued_bytes.set(total); + } + }) + as Box); + ws.as_ref() + .add_event_listener_with_callback(kind, callback.as_ref().unchecked_ref())?; + callbacks.push((kind, callback)); + } + ws.accept()?; + Ok(Self { + ws, + receiver, + overflow, + queued_bytes, + callbacks, + }) + } + pub async fn next(&mut self) -> std::result::Result { + if self.overflow.get() { + return Err("LIVE_RESET_REQUIRED".into()); + } + let value = self + .receiver + .next() + .await + .ok_or_else(|| "socket disconnected".to_owned())?; + if self.overflow.get() { + return Err("LIVE_RESET_REQUIRED".into()); + } + let text = value?; + self.queued_bytes + .set(self.queued_bytes.get().saturating_sub(text.len())); + serde_json::from_str(&text).map_err(|_| "invalid GraphQL frame".to_owned()) + } + pub fn send(&self, value: &serde_json::Value) -> std::result::Result<(), String> { + self.ws.send(value).map_err(|_| "socket send failed".into()) + } +} +impl Drop for Socket { + fn drop(&mut self) { + for (kind, callback) in self.callbacks.drain(..) { + let _ = self + .ws + .as_ref() + .remove_event_listener_with_callback(kind, callback.as_ref().unchecked_ref()); + } + let _ = self.ws.close(Some(1012), Some("gateway connection ended")); + } +} diff --git a/src/gateway/worker/timer.rs b/src/gateway/worker/timer.rs new file mode 100644 index 000000000..8954fba22 --- /dev/null +++ b/src/gateway/worker/timer.rs @@ -0,0 +1,99 @@ +use std::{ + cell::{Cell, RefCell}, + future::Future, + pin::Pin, + rc::Rc, + task::{Context, Poll, Waker}, +}; +use worker::{ + js_sys::{self, Function, Reflect}, + wasm_bindgen::{closure::Closure, JsCast, JsValue}, + Result, +}; +// workers-rs 0.8 Delay requires a numeric timer ID. Recent workerd can return +// a Timeout object; retain the opaque handle and pass it back unchanged. +pub(super) struct Timer { + millis: u64, + callback: Option>, + handle: Option, + ready: Rc>, + waker: Rc>>, +} +impl Timer { + pub(super) fn new(millis: u64) -> Self { + Self { + millis, + callback: None, + handle: None, + ready: Rc::new(Cell::new(false)), + waker: Rc::new(RefCell::new(None)), + } + } +} +impl Future for Timer { + type Output = Result<()>; + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = self.get_mut(); + if this.ready.get() { + return Poll::Ready(Ok(())); + } + *this.waker.borrow_mut() = Some(cx.waker().clone()); + if this.callback.is_none() { + let ready = this.ready.clone(); + let waker = this.waker.clone(); + let callback = Closure::wrap_assert_unwind_safe(Box::new(move || { + ready.set(true); + if let Some(waker) = waker.borrow_mut().take() { + waker.wake(); + } + }) as Box); + let global = js_sys::global(); + let result = (|| -> Result { + let function = Reflect::get(&global, &"setTimeout".into())? + .dyn_into::() + .map_err(worker::Error::from)?; + Ok(function.call2( + &global, + callback.as_ref(), + &JsValue::from_f64(this.millis as f64), + )?) + })(); + match result { + Ok(handle) => { + this.handle = Some(handle); + this.callback = Some(callback); + } + Err(error) => return Poll::Ready(Err(error)), + } + } + Poll::Pending + } +} +impl Drop for Timer { + fn drop(&mut self) { + if let Some(handle) = self.handle.take() { + let global = js_sys::global(); + if let Ok(function) = Reflect::get(&global, &"clearTimeout".into()) + .and_then(|value| value.dyn_into::()) + { + let _ = function.call1(&global, &handle); + } + } + } +} + +// Generic runtime deadline used by cancellation-owned stream drivers. +pub(super) async fn deadline( + duration: std::time::Duration, + future: impl Future, +) -> std::result::Result { + match futures_util::future::select( + Box::pin(future), + Box::pin(Timer::new(duration.as_millis().min(u64::MAX as u128) as u64)), + ) + .await + { + futures_util::future::Either::Left((value, _)) => Ok(value), + futures_util::future::Either::Right(_) => Err(()), + } +} diff --git a/tests/gateway-worker/.gitignore b/tests/gateway-worker/.gitignore new file mode 100644 index 000000000..8d3e5deed --- /dev/null +++ b/tests/gateway-worker/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +target/ +build/ +.wrangler/ +artifacts/ diff --git a/tests/gateway-worker/Cargo.lock b/tests/gateway-worker/Cargo.lock new file mode 100644 index 000000000..ea87acf34 --- /dev/null +++ b/tests/gateway-worker/Cargo.lock @@ -0,0 +1,1119 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "application-gateway-worker-fixture" +version = "0.0.0" +dependencies = [ + "distributed", + "serde_json", + "worker", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "async-graphql-parser" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64ef70f77a1c689111e52076da1cd18f91834bcb847de0a9171f83624b07fbf" +dependencies = [ + "async-graphql-value", + "pest", + "serde", + "serde_json", +] + +[[package]] +name = "async-graphql-value" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3ef112905abea9dea592fc868a6873b10ebd3f983e83308f995d6284e9ba41" +dependencies = [ + "bytes", + "indexmap", + "serde", + "serde_json", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitcode" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6ed1b54d8dc333e7be604d00fa9262f4635485ffea923647b6521a5fff045d" +dependencies = [ + "arrayvec", + "bitcode_derive", + "bytemuck", + "glam", + "serde", +] + +[[package]] +name = "bitcode_derive" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238b90427dfad9da4a9abd60f3ec1cdee6b80454bde49ed37f1781dd8e9dc7f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "js-sys", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "distributed" +version = "0.1.0" +dependencies = [ + "async-graphql-parser", + "async-trait", + "base64", + "bitcode", + "distributed_macros", + "futures-channel", + "futures-util", + "js-sys", + "serde", + "serde_json", + "sha2", + "tonic-build", + "url", + "uuid", + "worker", +] + +[[package]] +name = "distributed_macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "sha2", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "glam" +version = "0.33.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21fef0953c54fd3de2f44b743fbf77e044c81a25faee03636dfccc0d35135e23" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d45aeb61b4bf818e12d4205f2466f8c4748f85f4fce0146d1c03d69d753f0ad" +dependencies = [ + "memchr", + "ucd-trie", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7d3be8814f5ba5f074491a469eed3d73c273ffad955f25ed1635efac4b0d269" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "worker" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f8adbf6c9ae45b665dee995c5e3a342c2bd7d58a2e8ca5c75b50ce8b1b8bfd9" +dependencies = [ + "async-trait", + "bytes", + "chrono", + "futures-channel", + "futures-util", + "http", + "http-body", + "js-sys", + "matchit", + "pin-project", + "serde", + "serde-wasm-bindgen", + "serde_json", + "serde_urlencoded", + "strum", + "tokio", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "worker-macros", + "worker-sys", +] + +[[package]] +name = "worker-macros" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d908735d273dd7f9c325a842623f4e5a745e0686187ce465b34dc162ad348df" +dependencies = [ + "async-trait", + "proc-macro2", + "quote", + "strum", + "syn 2.0.119", + "wasm-bindgen", + "wasm-bindgen-macro-support", + "worker-sys", +] + +[[package]] +name = "worker-sys" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33faa1a8fa6c7eec67b196e008859c44d468a5ad4f991855cdc856f119e0e98f" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/gateway-worker/Cargo.toml b/tests/gateway-worker/Cargo.toml new file mode 100644 index 000000000..2216840f0 --- /dev/null +++ b/tests/gateway-worker/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] +[package] +name = "application-gateway-worker-fixture" +version = "0.0.0" +edition = "2021" +publish = false +[lib] +crate-type = ["cdylib"] +[dependencies] +distributed = { path = "../..", default-features = false, features = ["gateway-worker"] } +worker = "=0.8.5" +serde_json = "1" +[package.metadata.wasm-pack.profile.release] +wasm-opt = false diff --git a/tests/gateway-worker/README.md b/tests/gateway-worker/README.md new file mode 100644 index 000000000..4d15379a0 --- /dev/null +++ b/tests/gateway-worker/README.md @@ -0,0 +1,50 @@ +# Local application gateway Worker + +This isolated workers-rs fixture mounts the framework gateway and a **separate** +`DeliveryCoordinator` Durable Object. It does not host commands, projectors, SQL, +or aggregate cells. No Cloudflare account, deployment, or remote resources are +used by its tests. See [the adapter guide](../../docs/gateway/worker.md). + +Install Node 24, a current stable Rust toolchain with `wasm32-unknown-unknown`, +and `cargo install worker-build --version 0.8.5 --locked`. From the repository: + +```sh +npm ci --prefix tests/gateway-worker +npm ci --prefix tests/gateway-auth +npm exec --prefix tests/gateway-auth -- playwright install chromium +python3 tests/gateway-worker/check_dependencies.py +cargo check --manifest-path tests/gateway-worker/Cargo.toml --locked --target wasm32-unknown-unknown +node tests/gateway-worker/proxy-runtime.mjs +node tests/gateway-worker/run.mjs +cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol worker_ -- --ignored --nocapture --test-threads=1 +``` + +Run these runtime commands sequentially: worker-build writes one generated +bundle. `RUSTUP_TOOLCHAIN` is passed into the isolated build environment; real +application credential files are never loaded. Lockfiles pin workers-rs 0.8.5, +Wrangler 4.129.0, Miniflare 5.20260903.0-alpha, workerd 1.20260903.1, and ws 8.21.3. + +The Rust tests start actual GraphQL engines and SQLite projection stores, then +launch Node clients against workerd. They count origin validations, actual +projection SQL, and actual live producers. Query tests cover 100 consumers, +current private hits, external SQL without an invalidation feed, restart, two +separate ingress Wasm isolates using one selected DO, and explicit ingress +AbortSignal cancellation. Live tests cover 100 real JWT-authenticated sockets, +subject isolation, projection commit fanout, proof-only updates, bounded slow +consumers, old-cursor handoff, retention gaps, expiry/reconnect, last-leave +teardown, two ingress isolates and coordinator restart. + +The proxy runner uses actual HTTP streams and text/binary WebSockets. The auth +runner reuses the production SvelteKit/Auth.js browser lifecycle fixture and +checks secure cookie attributes separately. Artifacts under `artifacts/` are +ignored. Fixture-only `/__coordinators`, origin control routes and distributor +cancellation headers are test instrumentation; the framework mounts none of +them. + +The multi-isolate runner uses Miniflare's explicit module manifest and v4-option +converter for its pinned v5 API. A direct workerd listening socket avoids making +the Node development proxy part of the gateway contract. Plain HTTP disconnects +before response headers did not trigger Request.signal in this local runtime; +the configured operation deadline remains the cleanup bound. The explicit +AbortSignal test proves propagation through service bindings into the DO, and +response-stream cancellation and WebSocket teardown are tested separately. diff --git a/tests/gateway-worker/check_dependencies.py b/tests/gateway-worker/check_dependencies.py new file mode 100644 index 000000000..f1109cc65 --- /dev/null +++ b/tests/gateway-worker/check_dependencies.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""The Worker gateway links portable control contracts, never a native server.""" +from pathlib import Path +import subprocess +manifest = Path(__file__).resolve().with_name("Cargo.toml") +output = subprocess.check_output(["cargo", "tree", "--manifest-path", str(manifest), "--locked", "--target", "wasm32-unknown-unknown", "--edges", "normal", "--prefix", "none"], text=True) +packages = {line.split()[0] for line in output.splitlines() if line.strip()} +forbidden = {"async-graphql", "async-graphql-axum", "sqlx", "sqlx-core", "axum", "reqwest", "tonic", "async-nats", "lapin", "rdkafka"} +assert not packages & forbidden, sorted(packages & forbidden) +assert "worker" in packages +# workers-rs itself uses Tokio's feature-free utility types. A native runtime, +# networking or timer feature must never become enabled in the Wasm graph. +features = subprocess.check_output(["cargo", "tree", "--manifest-path", str(manifest), "--locked", "--target", "wasm32-unknown-unknown", "--edges", "normal", "--prefix", "none", "--format", "{p}|{f}"], text=True) +for line in features.splitlines(): + if line.startswith("tokio "): + assert not line.split("|", 1)[1].strip().replace("(*)", "").strip(), line +print("Worker gateway dependency boundary passed: no native server, SQL, or domain bus") diff --git a/tests/gateway-worker/live-runtime.mjs b/tests/gateway-worker/live-runtime.mjs new file mode 100644 index 000000000..006431aca --- /dev/null +++ b/tests/gateway-worker/live-runtime.mjs @@ -0,0 +1,83 @@ +import assert from 'node:assert/strict'; +import {once} from 'node:events'; +import WebSocket from 'ws'; +import {startRuntime} from './runtime.mjs'; +import {startShardedRuntime} from './sharded-runtime.mjs'; +const apiOrigin=process.env.GATEWAY_ORIGIN; +let runtime=await startRuntime({apiOrigin,artifact:'live-workerd.log'}); +const clients=[]; +async function until(predicate,label='condition'){for(let n=0;n<500;n++){if(await predicate())return;await new Promise(resolve=>setTimeout(resolve,20));}throw Error(label+' not reached');} +async function metrics(){return await(await fetch(apiOrigin+'/__metrics')).json();} +async function counts(){const all=await(await fetch(runtime.publicOrigin+'/__coordinators')).json();return all.reduce((a,c)=>a.map((n,i)=>n+c.live[i]),[0,0,0,0,0,0,0]);} +async function connect(id,token,{resume,ack=true,legacy=false,ingress=0}={}){ + const socket=new WebSocket((runtime.at?runtime.at(ingress,'/graphql/ws'):runtime.publicOrigin+'/graphql/ws').replace('http:','ws:'),legacy?'graphql-ws':'graphql-transport-ws'); + const frames=[];const errors=[];let initialized=false;let closed=false; + socket.on('message',data=>{const value=JSON.parse(data);if(value.type==='connection_ack')initialized=true;else if(value.type==='ping'&&ack)socket.send(JSON.stringify({type:'pong',payload:value.payload}));else if(value.type==='next'||value.type==='data'){assert.equal(value.id,id);frames.push(value.payload);}else if(value.type==='error')errors.push(value.payload);}); + socket.on('close',()=>{closed=true;});socket.on('error',error=>{errors.push(error.message);}); + clients.push(socket);await once(socket,'open');socket.send(JSON.stringify({type:'connection_init',payload:{authorization:`Bearer ${token}`}})); + await until(()=>initialized,`connection ${id} admission`); + const payload={query:'subscription WorkerWatch { causal_query_views { title } }',...(resume?{extensions:{distributed:{resume:{cursors:resume}}}}:{})}; + socket.send(JSON.stringify({id,type:legacy?'start':'subscribe',payload})); + await until(()=>frames.length||errors.length||closed,`connection ${id} first frame`); + assert.equal(errors.length,0,JSON.stringify(errors));assert.ok(frames.length,`connection ${id} closed without frame`); + return {socket,frames,errors,closed:()=>closed,cancel:()=>socket.send(JSON.stringify({id,type:legacy?'stop':'complete'}))}; +} +try{ + const alice=process.env.GATEWAY_TOKEN_ALICE,bob=process.env.GATEWAY_TOKEN_BOB; + const group=[];for(let i=0;i<100;i++)group.push(await connect(`consumer-${i}`,alice)); + await until(async()=>{const c=await counts();return c[0]===1&&c[1]===100;},'100 consumers sharing one group'); + assert.equal((await metrics()).producers,1);assert.equal((await metrics()).resultExecutions,1);assert.equal((await metrics()).validations,100); + const initial=group[0].frames[0];for(const consumer of group)assert.deepEqual(consumer.frames[0],initial); + const other=await connect('bob',bob);assert.notEqual(other.frames[0].extensions.distributed.cacheScope,initial.extensions.distributed.cacheScope);assert.equal((await metrics()).producers,2);other.cancel(); + await until(async()=>(await metrics()).producers===1,'Bob cancellation'); + await fetch(apiOrigin+'/__commit',{method:'POST'}); + await until(()=>group.every(c=>c.frames.some(f=>f.data?.causal_query_views?.[0]?.title==='worker committed')),'100 committed fanout'); + const resumed=await connect('resumed',alice,{resume:initial.extensions.distributed.live.cursors}); + await until(async()=>(await metrics()).producers===1,'safe replay handoff');assert.ok((await counts())[6]>0); + for(const consumer of group)consumer.cancel();await until(async()=>(await counts())[1]===1,'surviving resume consumer'); + assert.equal((await metrics()).producers,1);resumed.cancel();await until(async()=>(await metrics()).producers===0,'actual last-leave teardown'); + console.log('PASS actual workerd DO: 100 JWT-admitted WebSockets, one producer, subject isolation, commit fanout, safe resume and last-leave teardown'); + const legacy=await connect('legacy',alice,{legacy:true});legacy.cancel();await until(async()=>(await metrics()).producers===0,'legacy independent teardown'); + console.log('PASS legacy protocol remains independently admitted'); + const fast=await connect('fast',alice);const slow=await connect('slow',alice,{ack:false}); + for(let position=3;position<=23;position++){ + const previous=fast.frames.length;await fetch(apiOrigin+'/__next/'+position,{method:'POST'}); + await until(()=>fast.frames.length>previous,'proof-bearing frame '+position); + } + await until(()=>slow.closed()||slow.errors.length,'bounded slow consumer reset'); + assert.equal(slow.frames.length,1,'unacknowledged consumer cannot accumulate unbounded network frames'); + await until(async()=>(await counts())[1]===1,'slow consumer release'); + assert.equal((await metrics()).producers,1); + assert.deepEqual(fast.frames[1].data,fast.frames[2].data,'same values across projection commits'); + assert.notDeepEqual(fast.frames[1].extensions.distributed,fast.frames[2].extensions.distributed,'new confirmation proof is delivered'); + fast.cancel();await until(async()=>(await metrics()).producers===0,'fast teardown'); + console.log('PASS slow consumer explicit reset; proof-only updates reach healthy consumer'); + const gap=await connect('gap',alice,{resume:initial.extensions.distributed.live.cursors}); + assert.equal(gap.frames[0].extensions.distributed.live.reset,true,'expired replay retention requires origin reset'); + gap.cancel();await until(async()=>(await metrics()).producers===0,'gap teardown'); + const shortToken=(await(await fetch(apiOrigin+'/__short_token')).json()).token; + const expiring=await connect('expiring',shortToken);const survivor=await connect('survivor',alice); + const attempts=(await counts())[2]; + await until(()=>expiring.errors.length||expiring.closed(),'per-consumer expiry'); + await until(async()=>(await counts())[2]>attempts,'remaining credential reconnect'); + await until(async()=>(await metrics()).producers===1,'remaining live producer'); + const previous=survivor.frames.length;await fetch(apiOrigin+'/__next/24',{method:'POST'});await until(()=>survivor.frames.length>previous,'post-expiry survivor update'); + survivor.cancel();await until(async()=>(await metrics()).producers===0,'expiry teardown'); + console.log('PASS replay gap reset, per-consumer expiry and remaining-credential upstream reconnect'); + + await runtime.stop();runtime=await startShardedRuntime(apiOrigin); + const baseline=await metrics();const sharded=[]; + for(let i=0;i<100;i++)sharded.push(await connect('sharded-'+i,alice,{ingress:i})); + assert.equal((await metrics()).producers,1);assert.equal((await metrics()).resultExecutions,baseline.resultExecutions+1); + assert.equal((await metrics()).validations,baseline.validations+100); + await fetch(apiOrigin+'/__next/25',{method:'POST'}); + await until(()=>sharded.every(c=>c.frames.length>1),'cross-isolate fanout'); + const resume=sharded[0].frames.at(-1).extensions.distributed.live.cursors; + await runtime.stop();await until(async()=>(await metrics()).producers===0,'runtime restart releases origin producer'); + runtime=await startShardedRuntime(apiOrigin); + const recovered=await connect('recovered',alice,{resume,ingress:1}); + await fetch(apiOrigin+'/__next/26',{method:'POST'});await until(()=>recovered.frames.length>1,'fresh producer after restart'); + recovered.cancel();await until(async()=>(await metrics()).producers===0,'restarted producer teardown'); + console.log('PASS two ingress isolates share100live consumers; actual coordinator restart resumes from origin and tears down'); + +}finally{for(const socket of clients)socket.terminate();await runtime.stop();} diff --git a/tests/gateway-worker/package-lock.json b/tests/gateway-worker/package-lock.json new file mode 100644 index 000000000..e3af7b6a1 --- /dev/null +++ b/tests/gateway-worker/package-lock.json @@ -0,0 +1,1609 @@ +{ + "name": "application-gateway-worker-fixture", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "application-gateway-worker-fixture", + "devDependencies": { + "miniflare": "5.20260903.0-alpha", + "wrangler": "4.129.0", + "ws": "8.21.3" + } + }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz", + "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260903.1.tgz", + "integrity": "sha512-FG+4mGxAXhKiL/1temH42alevIkumtYXNidhTa//3yULpzux6APw5UNVocI/vCQ1yG1YOEZRfbVy8lyuipM9MQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260903.1.tgz", + "integrity": "sha512-o241VefnjG8eG+kGap5CjgV4zOT5UaAmS3OR1VZCpNj7vkXGxvp9KftKvtQgcCsIqJKaKx+7Xd7xq0L1DjkfPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260903.1.tgz", + "integrity": "sha512-/VEvvtQ/XKf6HlBbg6FbvpwcpfYUcx6Fv6RkASY8DyEmUyuJ8rc7Qxil83ClRFoBzz/GY0BV94UZ6F+wers/hg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260903.1.tgz", + "integrity": "sha512-OWhihGC6KoTXF4u2C1AonfpgXeM4/7p/1IXuALqXESmFUpLLP5gZhRzjSk/gWW+mrCZDfSrvnjifl+lRqselbA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260903.1.tgz", + "integrity": "sha512-soPMF9/aMHlHKK7M0vq5HrRRicPbnZO1F6ZZ7JWN8EltxWJU5L7CEq7CxjO878DzyPx7gYvqBFy3SVgdZKZjMQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", + "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", + "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", + "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", + "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", + "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", + "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", + "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", + "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", + "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", + "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", + "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", + "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", + "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", + "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", + "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", + "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", + "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", + "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", + "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", + "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", + "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", + "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", + "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", + "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", + "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", + "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/miniflare": { + "version": "5.20260903.0-alpha", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20260903.0-alpha.tgz", + "integrity": "sha512-VCZIFxOqFXeibRBJWwTlppqbv2lkeO10IX3QBRGK9j1QiMAfH/OSsCvbjp1MslBMhVZmy2VTRlVaVnsKnbDp6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.2", + "undici": "7.29.0", + "workerd": "1.20260903.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/miniflare/node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz", + "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.2", + "@img/sharp-darwin-x64": "0.35.2", + "@img/sharp-freebsd-wasm32": "0.35.2", + "@img/sharp-libvips-darwin-arm64": "1.3.1", + "@img/sharp-libvips-darwin-x64": "1.3.1", + "@img/sharp-libvips-linux-arm": "1.3.1", + "@img/sharp-libvips-linux-arm64": "1.3.1", + "@img/sharp-libvips-linux-ppc64": "1.3.1", + "@img/sharp-libvips-linux-riscv64": "1.3.1", + "@img/sharp-libvips-linux-s390x": "1.3.1", + "@img/sharp-libvips-linux-x64": "1.3.1", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", + "@img/sharp-libvips-linuxmusl-x64": "1.3.1", + "@img/sharp-linux-arm": "0.35.2", + "@img/sharp-linux-arm64": "0.35.2", + "@img/sharp-linux-ppc64": "0.35.2", + "@img/sharp-linux-riscv64": "0.35.2", + "@img/sharp-linux-s390x": "0.35.2", + "@img/sharp-linux-x64": "0.35.2", + "@img/sharp-linuxmusl-arm64": "0.35.2", + "@img/sharp-linuxmusl-x64": "0.35.2", + "@img/sharp-webcontainers-wasm32": "0.35.2", + "@img/sharp-win32-arm64": "0.35.2", + "@img/sharp-win32-ia32": "0.35.2", + "@img/sharp-win32-x64": "0.35.2" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/undici": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", + "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/workerd": { + "version": "1.20260903.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260903.1.tgz", + "integrity": "sha512-xJzt2RnCy7ulOULmZy/4JLbEPg1uisp9lVoOUsEz+UVhDsTmrSQ0rBXZMGcXuhr2HCGKs89bg8nnbbzvBSX1Ig==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260903.1", + "@cloudflare/workerd-darwin-arm64": "1.20260903.1", + "@cloudflare/workerd-linux-64": "1.20260903.1", + "@cloudflare/workerd-linux-arm64": "1.20260903.1", + "@cloudflare/workerd-windows-64": "1.20260903.1" + } + }, + "node_modules/wrangler": { + "version": "4.129.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.129.0.tgz", + "integrity": "sha512-PGPvs9UPoFrwxT0VogpESSZGvZIctAuTK3wGsLLPHtHsSgS85kNdvtpa2d14UzG8gwLWD64XUGFPGG9tOXG9VQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.1", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.1", + "miniflare": "5.20260903.0-alpha", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20260903.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20260903.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/tests/gateway-worker/package.json b/tests/gateway-worker/package.json new file mode 100644 index 000000000..b2dc58bf1 --- /dev/null +++ b/tests/gateway-worker/package.json @@ -0,0 +1 @@ +{"name":"application-gateway-worker-fixture","private":true,"type":"module","scripts":{"build":"worker-build --dev","dev":"wrangler dev --local","test":"node run.mjs"},"devDependencies":{"wrangler":"4.129.0","ws":"8.21.3","miniflare":"5.20260903.0-alpha"}} diff --git a/tests/gateway-worker/proxy-runtime.mjs b/tests/gateway-worker/proxy-runtime.mjs new file mode 100644 index 000000000..3c6e8855d --- /dev/null +++ b/tests/gateway-worker/proxy-runtime.mjs @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict'; +import {createServer} from 'node:http'; +import {once} from 'node:events'; +import WebSocket,{WebSocketServer} from 'ws'; +import {startRuntime} from './runtime.mjs'; +let streamClosed=false,upgrades=0,mutations=0; +const server=createServer(async(request,response)=>{ + if(request.url==='/redirect'){response.writeHead(302,{location:origin+'/target?one=1'});response.end();return;} + if(request.url==='/cookies'){response.writeHead(200,{'set-cookie':['first=1; HttpOnly; SameSite=Lax','second=2; Secure; SameSite=Strict']});response.end('cookies');return;} + if(request.url==='/stream'){ + response.writeHead(200,{'content-type':'application/octet-stream'});const interval=setInterval(()=>response.write(Buffer.alloc(4096,7)),10); + response.on('close',()=>{clearInterval(interval);streamClosed=true;});return; + } + if(request.url==='/failure'){response.writeHead(503);response.end('origin failure');return;} + let bytes=0,body='';try{for await(const chunk of request){bytes+=chunk.length;if(request.url==='/graphql')body+=chunk;}}catch{return;} + if(request.url==='/graphql'&&JSON.parse(body).query.startsWith('mutation'))mutations++; + response.writeHead(200,{'content-type':'application/json'});response.end(JSON.stringify({headers:request.headers,bytes,method:request.method,data:{accepted:true}})); +}); +const wsServer=new WebSocketServer({noServer:true}); +server.on('upgrade',(request,socket,head)=>wsServer.handleUpgrade(request,socket,head,ws=>{upgrades++;ws.on('message',(bytes,binary)=>{ + if(request.url==='/graphql/ws'){ + const message=JSON.parse(bytes); + if(message.type==='connection_init')ws.send(JSON.stringify({type:'connection_ack'})); + else if(message.type==='subscribe'||message.type==='start'){ + if(message.payload.query.startsWith('mutation'))mutations++; + ws.send(JSON.stringify({id:message.id,type:message.type==='start'?'data':'next',payload:{data:{accepted:true},extensions:{unchanged:'origin'}}})); + ws.send(JSON.stringify({id:message.id,type:'complete'})); + } + }else ws.send(bytes,{binary}); + });ws.on('close',()=>upgrades--);})); +server.listen(0,'127.0.0.1');await once(server,'listening');const origin=`http://127.0.0.1:${server.address().port}`; +let runtime; +async function until(predicate){for(let i=0;i<300;i++){if(await predicate())return;await new Promise(r=>setTimeout(r,20));}throw Error('proxy condition not reached');} +try{ + runtime=await startRuntime({apiOrigin:origin,requestBytes:65536,mode:'none',artifact:'proxy-workerd.log'});const base=runtime.publicOrigin; + const headers=(await(await fetch(base+'/echo',{headers:{origin:base,cookie:'opaque=session','x-user-id':'mallory','x-forwarded-host':'attacker.invalid','x-distributed-subject':'mallory'}})).json()).headers; + assert.equal(headers.origin,base);assert.equal(headers.cookie,'opaque=session');assert.equal(headers['x-forwarded-host'],new URL(base).host);assert.equal(headers['x-forwarded-proto'],'http');assert.equal(headers['x-user-id'],undefined);assert.equal(headers['x-distributed-subject'],undefined); + const redirect=await fetch(base+'/redirect',{redirect:'manual'});assert.equal(redirect.status,302);assert.equal(redirect.headers.get('location'),base+'/target?one=1'); + assert.equal((await fetch(base+'/cookies')).headers.getSetCookie().length,2); + assert.equal((await fetch(base+'/failure')).status,503);assert.equal((await fetch(base+'/__owned/missing')).status,404);assert.equal((await fetch(base+'/graphql')).status,405); + assert.equal((await fetch(base+'/graphql',{method:'POST',body:JSON.stringify({query:'mutation Change { change }'})})).status,200);assert.equal(mutations,1); + console.log('PASS workerd header trust, redirects, duplicate cookies, terminal errors and one command execution'); + const upload=new ReadableStream({start(controller){for(let i=0;i<4;i++)controller.enqueue(new Uint8Array(4096));controller.close();}}); + const result=await(await fetch(base+'/upload',{method:'POST',body:upload,duplex:'half'})).json();assert.equal(result.bytes,16384); + assert.equal((await fetch(base+'/graphql',{method:'POST',body:'x'.repeat(65537)})).status,413); + const tooBig=new ReadableStream({start(controller){controller.enqueue(new Uint8Array(65537));controller.close();}}); + assert.equal((await fetch(base+'/upload',{method:'POST',body:tooBig,duplex:'half'})).status,413); + const stream=await fetch(base+'/stream');const reader=stream.body.getReader();assert.ok((await reader.read()).value.length);await reader.cancel();await until(()=>streamClosed); + console.log('PASS actual streamed upload, body limits and response cancellation reaches origin'); + const ws=new WebSocket(base.replace('http:','ws:')+'/socket');await once(ws,'open'); + let next=once(ws,'message');ws.send('hello');let [data,binary]=await next;assert.equal(data.toString(),'hello');assert.equal(binary,false); + next=once(ws,'message');ws.send(Buffer.from([0,255,17]));[data,binary]=await next;assert.deepEqual([...data],[0,255,17]);assert.equal(binary,true); + const closed=once(ws,'close');ws.close(1000,'done');const [code,reason]=await closed;assert.equal(code,1000);assert.equal(reason.toString(),'done');await until(()=>upgrades===0); + console.log('PASS actual UI text/binary WebSocket relay and close teardown'); + for(const legacy of [false,true]){ + const socket=new WebSocket(base.replace('http:','ws:')+'/graphql/ws',legacy?'graphql-ws':'graphql-transport-ws');await once(socket,'open'); + const messages=[];socket.on('message',data=>messages.push(JSON.parse(data))); + socket.send(JSON.stringify({type:'connection_init',payload:{opaque:'origin-owned'}}));await until(()=>messages.some(m=>m.type==='connection_ack')); + for(const [id,query] of [['query','query Read { value }'],['command','mutation Change { change }']]){ + socket.send(JSON.stringify({id,type:legacy?'start':'subscribe',payload:{query}}));await until(()=>messages.some(m=>m.id===id&&m.type==='complete')); + const frame=messages.find(m=>m.id===id&&m.type===(legacy?'data':'next'));assert.deepEqual(frame.payload,{data:{accepted:true},extensions:{unchanged:'origin'}}); + } + socket.close();await once(socket,'close'); + } + assert.equal(mutations,3);await until(()=>upgrades===0); + console.log('PASS modern/legacy query and command envelopes with delivery entirely disabled'); + await runtime.stop();runtime=await startRuntime({apiOrigin:origin,requestBytes:65536,mode:'all',artifact:'proxy-coordinated-workerd.log'}); + const socket=new WebSocket(runtime.publicOrigin.replace('http:','ws:')+'/graphql/ws','graphql-transport-ws');await once(socket,'open'); + const messages=[];socket.on('message',data=>messages.push(JSON.parse(data))); + socket.send(JSON.stringify({type:'connection_init',payload:{opaque:'origin-owned'}}));await until(()=>messages.some(m=>m.type==='connection_ack')); + for(const [id,query] of [['read','query Read { value }'],['write','mutation Change { change }']]){ + socket.send(JSON.stringify({id,type:'subscribe',payload:{query}}));await until(()=>messages.some(m=>m.id===id&&m.type==='complete')); + assert.deepEqual(messages.find(m=>m.id===id&&m.type==='next').payload,{data:{accepted:true},extensions:{unchanged:'origin'}}); + } + socket.close();await once(socket,'close');await until(()=>upgrades===0);assert.equal(mutations,4); + console.log('PASS delivery-enabled command identity and query fallback for origins without control protocol'); + + +}finally{await runtime?.stop();for(const ws of wsServer.clients)ws.terminate();await new Promise(r=>wsServer.close(r));server.closeAllConnections();await new Promise(r=>server.close(r));} diff --git a/tests/gateway-worker/query-runtime.mjs b/tests/gateway-worker/query-runtime.mjs new file mode 100644 index 000000000..eacdd7512 --- /dev/null +++ b/tests/gateway-worker/query-runtime.mjs @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import {startRuntime} from './runtime.mjs'; +import {startShardedRuntime} from './sharded-runtime.mjs'; +const apiOrigin=process.env.GATEWAY_ORIGIN; +assert.ok(apiOrigin?.startsWith('http://127.0.0.1:'),'isolated origin required'); +let runtime=await startRuntime({apiOrigin}); +const body=JSON.stringify({query:'query WorkerShared { causal_query_views { title } }'}); +const query=async()=>{const response=await fetch(runtime.publicOrigin+'/graphql',{method:'POST',headers:{'content-type':'application/json'},body});assert.equal(response.status,200,await response.clone().text());const value=await response.json();assert.equal(value.errors,undefined,JSON.stringify(value));return value;}; +const metrics=async()=>await(await fetch(apiOrigin+'/__metrics')).json(); +async function until(predicate){for(let n=0;n<300;n++){if(await predicate())return;await new Promise(resolve=>setTimeout(resolve,20));}throw Error('coordinator condition not reached');} +try{ + const pending=Promise.all(Array.from({length:100},()=>query())); + pending.catch(()=>{}); + await until(async()=>{const counts=await(await fetch(runtime.publicOrigin+'/__coordinators')).json();return counts.reduce((n,c)=>n+c.query[2],0)===100;}); + assert.deepEqual(await metrics(),{validations:100,resultExecutions:0}); + await fetch(apiOrigin+'/__release',{method:'POST'}); + const responses=await pending;for(const response of responses)assert.deepEqual(response,responses[0]); + assert.equal((await metrics()).resultExecutions,1); + const before=await metrics();await query();const hit=await metrics();assert.equal(hit.resultExecutions,before.resultExecutions);assert.equal(hit.validations,before.validations+1); + console.log('PASS actual workerd DO: 100 admitted queries, one actual origin SQL execution, current private hit'); + await fetch(apiOrigin+'/__write',{method:'POST'}); + assert.equal((await query()).data.causal_query_views[0].title,'external write'); + assert.equal((await metrics()).resultExecutions,2); + console.log('PASS missed feed/external SQL write invalidates through current origin validation'); + await runtime.stop();runtime=await startRuntime({apiOrigin,artifact:'query-restarted-workerd.log'}); + assert.equal((await query()).data.causal_query_views[0].title,'external write'); + assert.equal((await metrics()).resultExecutions,3); + console.log('PASS actual workerd restart loses cache and revalidates/refills'); + await runtime.stop();runtime=await startShardedRuntime(apiOrigin); + assert.equal(await(await fetch(runtime.at(0,'/__gateway_health'))).text(),'ingress-a'); + assert.equal(await(await fetch(runtime.at(1,'/__gateway_health'))).text(),'ingress-b'); + await fetch(apiOrigin+'/__block',{method:'POST'});const beforeShard=await metrics(); + const shared=Promise.all(Array.from({length:100},async(_,index)=>{const response=await fetch(runtime.at(index,'/graphql'),{method:'POST',headers:{'content-type':'application/json'},body});assert.equal(response.status,200);return response.json();}));shared.catch(()=>{}); + await until(async()=>{const counts=await(await fetch(runtime.at(0,'/__coordinators'))).json();return counts.reduce((n,c)=>n+c.query[2],0)===100;}); + assert.equal((await metrics()).validations,beforeShard.validations+100); + await fetch(apiOrigin+'/__release',{method:'POST'});const shardResults=await shared;for(const result of shardResults)assert.deepEqual(result,shardResults[0]); + assert.equal((await metrics()).resultExecutions,beforeShard.resultExecutions+1); + console.log('PASS two distinct ingress Wasm isolates coordinate100queries in one selected Durable Object'); + + await fetch(runtime.at(0,'/__coordinators'),{method:'POST'}); + await fetch(apiOrigin+'/__block',{method:'POST'}); + const controllers=[new AbortController(),new AbortController()]; + const cancellable=controllers.map((controller,index)=>new Promise(resolve=>{const request=http.request(runtime.at(index,'/graphql'),{method:'POST',agent:false,headers:{'content-type':'application/json',...(index===0?{'x-fixture-cancel':'yes'}:{})},signal:controller.signal},response=>{let data='';response.on('data',chunk=>data+=chunk);response.on('end',()=>resolve(JSON.parse(data)));});request.on('error',error=>resolve(error.name));request.end(body);})); + const consumers=async()=>{const all=await(await fetch(runtime.at(0,'/__coordinators'))).json();return all.reduce((n,c)=>n+c.query[2],0);}; + await until(async()=>await consumers()===2);controllers[0].abort(); + await until(async()=>await consumers()===1); + await fetch(apiOrigin+'/__release',{method:'POST'});assert.equal(await cancellable[0],'AbortError');assert.ok((await cancellable[1]).data); + console.log('PASS ingress AbortSignal releases one DO consumer while another completes'); + await fetch(runtime.at(0,'/__coordinators'),{method:'POST'});await fetch(apiOrigin+'/__block',{method:'POST'}); + const last=fetch(runtime.at(0,'/graphql'),{method:'POST',headers:{'content-type':'application/json','x-fixture-cancel':'yes'},body}).catch(()=>null); + await until(async()=>await consumers()===1);await until(async()=>await consumers()===0);await last; + console.log('PASS last ingress cancellation releases the actual DO flight'); + +}finally{await runtime.stop();} diff --git a/tests/gateway-worker/run.mjs b/tests/gateway-worker/run.mjs new file mode 100644 index 000000000..dcc588959 --- /dev/null +++ b/tests/gateway-worker/run.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import {root,freePort,startRuntime} from './runtime.mjs'; +const port=await freePort(); +const publicOrigin=`http://127.0.0.1:${port}`; +process.env.GATEWAY_TEST_ORIGIN=publicOrigin; +process.chdir(path.join(root,'../gateway-auth')); +const {startFixture,exerciseAuth}=await import('../gateway-auth/run.mjs'); +for(const secureCookies of [false,true]){ + process.chdir(path.join(root,'../gateway-auth')); + const fixture=await startFixture({secureCookies}); + process.chdir(root); + let runtime; + try{ + runtime=await startRuntime({port,uiOrigin:fixture.uiOrigin,apiOrigin:fixture.uiOrigin,artifact:secureCookies?'secure-auth-workerd.log':'auth-workerd.log'}); + assert.equal((await fetch(publicOrigin+'/__owned/not-found')).status,404); + assert.equal((await fetch(publicOrigin+'/',{headers:{authorization:'Bearer invalid'}})).status,401); + if(secureCookies){ + const response=await fetch(publicOrigin+'/login',{redirect:'manual'}); + assert.equal(response.status,302);const cookies=response.headers.getSetCookie(); + assert.ok(cookies.length>=3);assert.ok(cookies.every(cookie=>/; Secure(?:;|$)/i.test(cookie))); + console.log('PASS explicit secure-cookie policy survives actual workerd delegation'); + }else{ + await exerciseAuth(fixture); + console.log('PASS real production Auth.js/OIDC through actual workerd ingress'); + } + }finally{await runtime?.stop();await fixture.stop();} +} diff --git a/tests/gateway-worker/runtime.mjs b/tests/gateway-worker/runtime.mjs new file mode 100644 index 000000000..fb6e0c8c9 --- /dev/null +++ b/tests/gateway-worker/runtime.mjs @@ -0,0 +1,22 @@ +import { spawn } from 'node:child_process'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { mkdir,writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +export const root=path.dirname(fileURLToPath(import.meta.url)); +export async function freePort(){const server=createServer();server.listen(0,'127.0.0.1');await once(server,'listening');const port=server.address().port;await new Promise(resolve=>server.close(resolve));return port;} +export async function startRuntime({apiOrigin,uiOrigin=apiOrigin,mode='all',port=0,artifact='query-workerd.log',requestBytes=16*1024*1024}={}){ + port ||= await freePort(); const publicOrigin=`http://127.0.0.1:${port}`;let log=''; + const runner=spawn(process.execPath,['node_modules/wrangler/bin/wrangler.js','dev','--local','--ip','127.0.0.1','--port',String(port),'--var',`PUBLIC_ORIGIN:${publicOrigin}`,'--var',`UI_ORIGIN:${uiOrigin}`,'--var',`API_ORIGIN:${apiOrigin}`,'--var',`DELIVERY_MODE:${mode}`,'--var',`REQUEST_BYTES:${requestBytes}`],{cwd:root,env:{PATH:process.env.PATH,HOME:process.env.HOME,RUSTUP_TOOLCHAIN:process.env.RUSTUP_TOOLCHAIN||'stable',WRANGLER_SEND_METRICS:'false',CI:'1'},stdio:['ignore','pipe','pipe']}); + runner.stdout.on('data',chunk=>{log+=chunk;});runner.stderr.on('data',chunk=>{log+=chunk;}); + const stop=async()=>{if(runner.exitCode===null){runner.kill('SIGTERM');await once(runner,'exit');}await mkdir(path.join(root,'artifacts'),{recursive:true});await writeFile(path.join(root,'artifacts',artifact),log);}; + try{ + for(let n=0;n<600;n++){ + if(runner.exitCode!==null)throw Error(`workerd exited: ${log.slice(-7000)}`); + try{if((await fetch(`${publicOrigin}/__gateway_health`)).ok)return {publicOrigin,port,stop,logs:()=>log};}catch{} + await new Promise(resolve=>setTimeout(resolve,200)); + } + throw Error(`workerd readiness timeout: ${log.slice(-7000)}`); + }catch(error){await stop();throw error;} +} diff --git a/tests/gateway-worker/sharded-runtime.mjs b/tests/gateway-worker/sharded-runtime.mjs new file mode 100644 index 000000000..e62a5b87d --- /dev/null +++ b/tests/gateway-worker/sharded-runtime.mjs @@ -0,0 +1,14 @@ +import {Miniflare,convertV4MiniflareOptions} from 'miniflare'; +import {root,freePort} from './runtime.mjs'; +import path from 'node:path'; +export async function startShardedRuntime(apiOrigin){ + const port=await freePort();const publicOrigin=`http://127.0.0.1:${port}`; + const common={modules:[{type:'ESModule',path:path.join(root,'build/index.js')},{type:'CompiledWasm',path:path.join(root,'build/index_bg.wasm')}],modulesRoot:path.join(root,'build'),compatibilityDate:'2026-09-03',compatibilityFlags:['enable_request_signal']}; + const worker=(name)=>({...common,name,bindings:{PUBLIC_ORIGIN:publicOrigin,UI_ORIGIN:apiOrigin,API_ORIGIN:apiOrigin,DELIVERY_MODE:'all',INGRESS_ID:name},durableObjects:{DELIVERY:{className:'DeliveryCoordinator',...(name==='coordinator'?{}:{scriptName:'coordinator'}),useSQLite:true}}}); + const mf=new Miniflare(convertV4MiniflareOptions({cf:false,host:'127.0.0.1',port:await freePort(),workers:[ + {name:'test-distributor',unsafeDirectSockets:[{host:'127.0.0.1',port,proxy:false}],modules:true,compatibilityDate:'2026-09-03',compatibilityFlags:['enable_request_signal'],serviceBindings:{A:'ingress-a',B:'ingress-b'},script:`export default {fetch(request,env){const url=new URL(request.url);const target=url.searchParams.get('__ingress')==='b'?env.B:env.A;url.searchParams.delete('__ingress');const outbound=new Request(url,request);if(request.headers.get('x-fixture-cancel')==='yes'){const controller=new AbortController();setTimeout(()=>controller.abort(),500);return target.fetch(new Request(outbound,{signal:controller.signal}));}return target.fetch(outbound);}}`}, + worker('ingress-a'),worker('ingress-b'),worker('coordinator'), + ]})); + try{await mf.ready;}catch(error){await mf.dispose();throw error;} + return {publicOrigin,stop:()=>mf.dispose(),at:(index,path)=>`${publicOrigin}${path}${path.includes('?')?'&':'?'}__ingress=${index%2?'b':'a'}`}; +} diff --git a/tests/gateway-worker/src/lib.rs b/tests/gateway-worker/src/lib.rs new file mode 100644 index 000000000..7b8389cca --- /dev/null +++ b/tests/gateway-worker/src/lib.rs @@ -0,0 +1,179 @@ +use ::worker::wasm_bindgen; +use ::worker::{ + durable_object, event, Context, DurableObject, Env, Request, Response, Result, State, +}; +use distributed::gateway::{delivery::*, worker::*, *}; +use std::rc::Rc; +fn delivery_options(env: &Env) -> WorkerDeliveryOptions { + let mode = env + .var("DELIVERY_MODE") + .map(|v| v.to_string()) + .unwrap_or_else(|_| "all".into()); + if mode == "none" { + return WorkerDeliveryOptions::default(); + } + WorkerDeliveryOptions { + snapshots: (mode != "flights").then_some(SnapshotLimits { + entries: 128, + bytes: 2 * 1024 * 1024, + entry_bytes: 256 * 1024, + }), + coalescing: Some(FlightLimits { + groups: 8, + consumers: 128, + response_bytes: 256 * 1024, + ..Default::default() + }), + live: (mode != "flights").then(|| LiveLimits { + groups: 4, + consumers: 128, + frame_bytes: 64 * 1024, + ..Default::default() + }), + } +} +fn gateway(env: &Env) -> Result { + let origin = env.var("UI_ORIGIN")?.to_string(); + let public = env.var("PUBLIC_ORIGIN")?.to_string(); + let api = env + .var("API_ORIGIN") + .map(|v| v.to_string()) + .unwrap_or_else(|_| origin.clone()); + let options = delivery_options(env); + let config = GatewayConfig { + bindings: vec![ + Binding::new("ui", BindingKind::UiProxy { origin }), + Binding::new("health", BindingKind::Handler), + Binding::new("owned", BindingKind::Handler), + Binding::new( + "api", + BindingKind::Graphql { + executor: GraphqlExecutor::Remote { origin: api }, + capabilities: GraphqlCapabilities { + queries: true, + commands: true, + live: true, + }, + delivery: DeliveryCapabilities { + snapshots: options.snapshots.is_some(), + coalescing: options.coalescing.is_some(), + live_sharing: options.live.is_some(), + }, + schema_extensions: vec![], + }, + ), + ], + routes: vec![ + Route::new("health", RoutePath::exact("/__gateway_health"), "health"), + Route::new("owned", RoutePath::prefix("/__owned"), "owned"), + Route::new("api", RoutePath::prefix("/graphql"), "api"), + Route::new("ui", RoutePath::prefix("/"), "ui"), + ], + } + .build() + .map_err(|error| ::worker::Error::RustError(error.to_string()))?; + let mut worker_options = WorkerOptions::new(public); + worker_options + .strip_headers + .push("x-distributed-subject".into()); + if let Ok(limit) = env.var("REQUEST_BYTES") { + worker_options.limits.request_bytes = + limit.to_string().parse().expect("fixture request limit"); + } + WorkerGateway::new( + config, + worker_options, + [ + ("ui".into(), WorkerBinding::UiProxy { websocket: true }), + ( + "health".into(), + WorkerBinding::Handler(WorkerHandler::new(|_, _, env| async move { + Response::ok( + env.var("INGRESS_ID") + .map(|v| v.to_string()) + .unwrap_or_else(|_| "ready".into()), + ) + })), + ), + ( + "owned".into(), + WorkerBinding::Handler(WorkerHandler::new(|_, _, _| async { + Response::error("owned error", 404) + })), + ), + ( + "api".into(), + WorkerBinding::Graphql { + http_path: "/graphql".into(), + live_path: Some("/graphql/ws".into()), + delivery: (options.snapshots.is_some() + || options.coalescing.is_some() + || options.live.is_some()) + .then_some(WorkerDeliveryBinding { + namespace: "DELIVERY".into(), + epoch: "fixture-v1".into(), + shards: 4, + options, + }), + }, + ), + ], + WorkerAuth::anonymous(), + ) + .map_err(|error| ::worker::Error::RustError(error.to_string())) +} +#[durable_object] +pub struct DeliveryCoordinator { + env: Env, + coordinator: Rc, +} +impl DurableObject for DeliveryCoordinator { + fn new(_state: State, env: Env) -> Self { + Self { + coordinator: WorkerCoordinator::new(delivery_options(&env)) + .expect("validated fixture limits"), + env, + } + } + async fn fetch(&self, request: Request) -> Result { + match request.path().as_str() { + "/__metrics" => { + return Response::from_json( + &serde_json::json!({"query":self.coordinator.counts(),"live":self.coordinator.live_counts()}), + ) + } + "/__reset" => { + self.coordinator.invalidate_all(); + return Response::ok("reset"); + } + _ => {} + } + gateway(&self.env)? + .fetch_coordinated(request, self.env.clone(), self.coordinator.clone()) + .await + } +} +#[event(fetch)] +async fn fetch(request: Request, env: Env, _ctx: Context) -> Result { + if request.path() == "/__coordinators" { + let reset = request.method() == ::worker::Method::Post; + let mut counts = Vec::new(); + for shard in 0..4 { + let namespace = env.durable_object("DELIVERY")?; + let stub = namespace + .id_from_name(&format!("gateway-delivery-v1:fixture-v1:api:{shard}"))? + .get_stub()?; + let mut response = stub + .fetch_with_str(&format!( + "http://internal.invalid/{}", + if reset { "__reset" } else { "__metrics" } + )) + .await?; + if !reset { + counts.push(response.json::().await?); + } + } + return Response::from_json(&counts); + } + gateway(&env)?.fetch(request, env).await +} diff --git a/tests/gateway-worker/wrangler.jsonc b/tests/gateway-worker/wrangler.jsonc new file mode 100644 index 000000000..d42ea3df5 --- /dev/null +++ b/tests/gateway-worker/wrangler.jsonc @@ -0,0 +1,15 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "application-gateway-local-fixture", + "main": "build/worker/shim.mjs", + "compatibility_flags": ["enable_request_signal"], + "compatibility_date": "2026-09-03", + "workers_dev": false, + "durable_objects": {"bindings":[{"name":"DELIVERY","class_name":"DeliveryCoordinator"}]}, + "migrations":[{"tag":"gateway-v1","new_sqlite_classes":["DeliveryCoordinator"]}], + "build": {"command":"worker-build --dev"}, + "vars": { + "PUBLIC_ORIGIN": "http://127.0.0.1:8787", + "UI_ORIGIN": "http://127.0.0.1:3000" + } +} diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index fc0a16e23..4a9b62d64 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -2402,3 +2402,174 @@ async fn hundred_subscribers_one_upstream_over_embedded_and_remote_websockets() .expect("last leave tears down gateway and origin live producers"); } } + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +#[tokio::test] +#[ignore = "requires pinned tests/gateway-worker npm installation and worker-build; run explicitly in Worker CI"] +async fn worker_coordinator_uses_actual_origin_projection_sql() { + use axum::{ + routing::{get, post}, + Router, + }; + use distributed::graphql::delivery::GatewayVersionStore; + let fixture = protocol_fixture_with_retention(10).await; + let store = GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()), + "worker-test", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .anonymous_role("user") + .subscriptions(false) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .gateway_versions(store.clone()) + .build() + .unwrap(), + ); + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + let handler_gate = gate.clone(); + let blocking_gate = gate.clone(); + let pool = fixture.repository.pool().clone(); + let origin=Router::new().route("/graphql",post(move |axum::Json(value):axum::Json|{let engine=engine.clone();let gate=handler_gate.clone();async move{ + if value["extensions"]["gatewayDelivery"]["action"]=="snapshot"{gate.acquire().await.unwrap().forget();} + axum::Json(serde_json::to_value(engine.execute(&user_session(),serde_json::from_value::(value).unwrap()).await).unwrap()) + }})).route("/__metrics",get(move ||{let store=store.clone();async move{let metrics=store.metrics();axum::Json(json!({"validations":metrics.validations,"resultExecutions":metrics.result_executions}))}})) + .route("/__release",post(move ||{let gate=gate.clone();async move{gate.add_permits(1000);"released"}})) + .route("/__write",post(move ||{let pool=pool.clone();async move{sqlx::query("UPDATE causal_query_views SET title='external write'").execute(&pool).await.unwrap();"written"}})); + let origin = origin.route( + "/__block", + post(move || { + let gate = blocking_gate.clone(); + async move { + gate.forget_permits(gate.available_permits()); + "blocked" + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin_url = format!("http://{}", listener.local_addr().unwrap()); + struct Stop(tokio::task::JoinHandle<()>); + impl Drop for Stop { + fn drop(&mut self) { + self.0.abort(); + } + } + let _server = Stop(tokio::spawn(async move { + axum::serve(listener, origin).await.unwrap() + })); + let result = tokio::process::Command::new("node") + .arg("tests/gateway-worker/query-runtime.mjs") + .env("GATEWAY_ORIGIN", origin_url) + .kill_on_drop(true) + .output() + .await + .unwrap(); + println!("{}", String::from_utf8_lossy(&result.stdout)); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); +} + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +#[tokio::test] +#[ignore = "requires pinned local workerd fixture; run explicitly in Worker CI"] +async fn worker_live_coordinator_uses_actual_oidc_origin() { + use axum::Router; + use distributed::graphql::{delivery::GatewayVersionStore, IdentityConfig, OidcConfig}; + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + use rsa::{pkcs1::EncodeRsaPrivateKey, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey}; + let private = RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap(); + let public = RsaPublicKey::from(&private); + let encoding = EncodingKey::from_rsa_pem( + private + .to_pkcs1_pem(rsa::pkcs8::LineEnding::LF) + .unwrap() + .as_bytes(), + ) + .unwrap(); + let jwks=json!({"keys":[{"kty":"RSA","kid":"live-test","alg":"RS256","use":"sig", + "n":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.n().to_bytes_be()),"e":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.e().to_bytes_be())}]}).to_string(); + let token = |subject: &str| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("live-test".into()); + encode(&header,&json!({"iss":"https://live-fixture.invalid","aud":"live-fixture","sub":subject,"iat":now-1,"nbf":now-1,"exp":now+3600,"roles":["user"]}),&encoding).unwrap() + }; + + let fixture = protocol_fixture_with_retention(5).await; + let versions = GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()), + "worker-live-fixture", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let oidc = OidcConfig::new("https://live-fixture.invalid", "live-fixture") + .with_static_jwks(jwks) + .engine_roles(&["user"]); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .identity(IdentityConfig::oidc_bearer(oidc)) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .change_stream(fixture.repository.read_model_changes()) + .gateway_versions(versions.clone()) + .build() + .unwrap(), + ); + let router = distributed::graphql::graphql_router_composed(engine.clone(), None, None); + let repository = fixture.repository.clone(); + let bus = fixture.bus.clone(); + let control=Router::new().route("/__metrics",axum::routing::get(move ||{let engine=engine.clone();let versions=versions.clone();async move{let metrics=versions.metrics();axum::Json(json!({"producers":engine.live_subscriber_count(),"validations":metrics.validations,"resultExecutions":metrics.result_executions}))}})) + .route("/__commit",axum::routing::post(move ||{let repository=repository.clone();let bus=bus.clone();async move{project_item(&repository,&bus,2,"worker committed").await;"committed"}})); + let next_repository = fixture.repository.clone(); + let next_bus = fixture.bus.clone(); + let short_encoding = encoding.clone(); + let control=control.route("/__next/{position}",axum::routing::post(move |axum::extract::Path(position):axum::extract::Path|{let repository=next_repository.clone();let bus=next_bus.clone();async move{project_item(&repository,&bus,position,if position==23{"worker-22"}else{"worker update"}).await;"committed"}})) + .route("/__short_token",axum::routing::get(move ||{let encoding=short_encoding.clone();async move{ + let now=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();let mut header=Header::new(Algorithm::RS256);header.kid=Some("live-test".into()); + axum::Json(json!({"token":encode(&header,&json!({"iss":"https://live-fixture.invalid","aud":"live-fixture","sub":"alice","iat":now-1,"nbf":now-1,"exp":now+3,"roles":["user"]}),&encoding).unwrap()})) + }})); + let router = router.merge(control); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin_url = format!("http://{}", listener.local_addr().unwrap()); + struct Stop(tokio::task::JoinHandle<()>); + impl Drop for Stop { + fn drop(&mut self) { + self.0.abort(); + } + } + let _server = Stop(tokio::spawn(async move { + axum::serve(listener, router).await.unwrap() + })); + let result = tokio::process::Command::new("node") + .arg("tests/gateway-worker/live-runtime.mjs") + .env("GATEWAY_ORIGIN", origin_url) + .env("GATEWAY_TOKEN_ALICE", token("alice")) + .env("GATEWAY_TOKEN_BOB", token("bob")) + .kill_on_drop(true) + .output() + .await + .unwrap(); + println!("{}", String::from_utf8_lossy(&result.stdout)); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); +} From 3a96d3987b8ff1faed42131e85e7405be540c9b6 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:09:18 -0500 Subject: [PATCH 058/484] feat: compose explicit public application gateway Implements tasks/application-gateway-11: opt-in mounts and public-origin browser parity. --- .github/workflows/integration-gateway.yaml | 32 ++++ distributed_cli/src/lifecycle/project.rs | 3 +- docs/gateway/application.md | 33 ++++ src/application/mount.rs | 6 + src/application/registration.rs | 15 ++ src/application/runtime.rs | 53 ++++++ src/gateway/application.rs | 28 ++++ src/gateway/config.rs | 5 + src/gateway/mod.rs | 2 + tests/e2e-ui/Cargo.toml | 2 +- tests/e2e-ui/Makefile | 7 +- tests/e2e-ui/README.md | 9 +- tests/e2e-ui/crates/runner/src/main.rs | 13 ++ tests/e2e-ui/crates/service/src/host.rs | 61 ++++++- tests/e2e-ui/crates/service/src/http.rs | 154 +++++++++++++++++- tests/e2e-ui/crates/service/src/lib.rs | 6 +- .../crates/service/src/modules/graphql.rs | 31 ++++ tests/e2e-ui/gateway/.gitignore | 1 + tests/e2e-ui/gateway/README.md | 20 +++ tests/e2e-ui/gateway/run.mjs | 147 +++++++++++++++++ tests/e2e-ui/playwright.config.ts | 2 +- tests/e2e-ui/scripts/up.sh | 28 ++-- .../e2e-ui/ui/src/lib/server/require-auth.ts | 2 +- tests/e2e-ui/ui/vite.config.ts | 12 +- tests/gateway-auth/provider.mjs | 20 ++- tests/gateway-portable/Cargo.toml | 4 + tests/gateway_mounts.rs | 97 +++++++++++ 27 files changed, 744 insertions(+), 49 deletions(-) create mode 100644 docs/gateway/application.md create mode 100644 src/gateway/application.rs create mode 100644 tests/e2e-ui/gateway/.gitignore create mode 100644 tests/e2e-ui/gateway/README.md create mode 100644 tests/e2e-ui/gateway/run.mjs create mode 100644 tests/gateway_mounts.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 49d8df7ae..843f72d25 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -9,6 +9,8 @@ on: - 'build.rs' - 'migrations/**' - 'docs/gateway/**' + - 'tests/e2e-ui/**' + - 'distributed_cli/src/lifecycle/**' - 'tests/e2e-ui/ui/src/auth.ts' - 'tests/e2e-ui/ui/src/lib/server/**' - 'tests/e2e-ui/ui/src/routes/api/auth/**' @@ -176,3 +178,33 @@ jobs: node tests/gateway-worker/run.mjs - name: Prove actual DO coordination, SQL reduction, restart and cancellation run: cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol worker_ -- --ignored --nocapture --test-threads=1 + + application: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + - name: Install isolated browser fixture + run: | + cargo install wasm-pack --locked + npm ci --prefix tests/gateway-auth + cd tests/gateway-auth + npx playwright install --with-deps chromium + - name: Verify explicit application mounts + run: cargo test --no-default-features --features graphql,sqlite,application-runtime,gateway --test application_composition --test application_plans --test gateway_mounts + - name: Build coherent application and run public-origin browser flows + run: node tests/e2e-ui/gateway/run.mjs + - uses: actions/upload-artifact@v4 + if: always() + with: + name: gateway-application + path: tests/e2e-ui/gateway/artifacts/ diff --git a/distributed_cli/src/lifecycle/project.rs b/distributed_cli/src/lifecycle/project.rs index 705e8cc75..71716d137 100644 --- a/distributed_cli/src/lifecycle/project.rs +++ b/distributed_cli/src/lifecycle/project.rs @@ -1009,7 +1009,8 @@ fn lifecycle_dev( let ui_host = std::env::var("UI_HOST").unwrap_or_else(|_| "localhost".to_string()); let ui_bind = std::env::var("UI_BIND").unwrap_or_else(|_| ui_host.clone()); let ui_port = std::env::var("UI_PORT").unwrap_or_else(|_| "5180".to_string()); - let ui_url = std::env::var("UI_URL") + let ui_url = std::env::var("PUBLIC_ORIGIN") + .or_else(|_| std::env::var("UI_URL")) .or_else(|_| std::env::var("AUTH_URL")) .unwrap_or_else(|_| format!("http://{ui_host}:{ui_port}")); let cargo_cwd = cargo_root diff --git a/docs/gateway/application.md b/docs/gateway/application.md new file mode 100644 index 000000000..e7455d466 --- /dev/null +++ b/docs/gateway/application.md @@ -0,0 +1,33 @@ +# Application composition + +Declare a gateway alongside the typed service application: + +```rust,ignore +let application = service.application("site", surface)?.with_gateway("public", &gateway)?; +let selector = MountSelector::gateway("public")?; +let runtime = Runtime::default().mount_gateway(&application, selector.clone(), gateway)?; +let adapter = runtime.bind_gateway(&selector, |gateway| build_adapter(gateway))?; +``` + +The manifest records logical binding IDs and capabilities as a versioned +application extension. Physical origins, route paths, secrets and host placement +are excluded. Deployment plans use the existing extension mount algebra. +Selection validates the declaration before a host factory runs. An unselected +factory is never invoked; a gateway mount does not select domain workers, +projectors, stores or an embedded GraphQL server. Native and Wasm UI/auth-only +consumers remain independent of GraphQL/SQL dependencies. + +The e2e-ui sample explicitly combines its existing domain host with the public +native gateway. `/graphql` owns API failures; `/auth` and `/api/auth` reach +SvelteKit, `/` serves UI, and service health/lifecycle/Zitadel ingress paths keep +explicit owners. SvelteKit is an internal upstream with no reverse API proxy. +`PUBLIC_ORIGIN` defaults to `http://localhost:8791`, `UI_INTERNAL_ORIGIN` to +`http://localhost:5180`. Configure OIDC callbacks for the public origin. +`GATEWAY_DELIVERY=none` (default) creates no delivery coordinator; `all` selects +bounded cache/flight/live resources and transactional dependency version hooks. +The logical application still uses the existing command sealing and lifecycle +protocols, including `APPLICATION_RELOADING`. + +Rollback consists of reverting the sample gateway mount and public-origin +configuration together. Disabling delivery independently preserves command and +query correctness and leaves persisted domain data intact. diff --git a/src/application/mount.rs b/src/application/mount.rs index 05c7afe67..9b3051ee6 100644 --- a/src/application/mount.rs +++ b/src/application/mount.rs @@ -49,6 +49,12 @@ impl MountSelector { }) } + /// Gateway capabilities use the existing explicit extension mount algebra. + #[cfg(feature = "gateway")] + pub fn gateway(id: impl Into) -> ApplicationResult { + Self::extension(id) + } + pub fn kind_label(&self) -> &'static str { match self { Self::Command { .. } => "command", diff --git a/src/application/registration.rs b/src/application/registration.rs index 92593a599..1fe95d300 100644 --- a/src/application/registration.rs +++ b/src/application/registration.rs @@ -64,6 +64,21 @@ impl Application { }) } + /// Declare a gateway's logical capabilities beside the typed Service surface. + /// Origins, routes, credentials and adapter resources remain host bindings. + #[cfg(feature = "gateway")] + pub fn with_gateway( + mut self, + id: impl Into, + gateway: &crate::gateway::Gateway, + ) -> ApplicationResult { + self.manifest + .extensions + .push(gateway.application_extension(id)?); + self.manifest.refresh_fingerprints()?; + Ok(self) + } + pub fn name(&self) -> &str { &self.name } diff --git a/src/application/runtime.rs b/src/application/runtime.rs index cad4d3be1..14fe0b150 100644 --- a/src/application/runtime.rs +++ b/src/application/runtime.rs @@ -21,6 +21,8 @@ pub struct Runtime { mounts: Vec, graphql: bool, dispatch_routes: BTreeMap, + #[cfg(feature = "gateway")] + gateways: BTreeMap, } impl Runtime { @@ -52,6 +54,8 @@ impl Runtime { mounts: Vec::new(), graphql: false, dispatch_routes: BTreeMap::new(), + #[cfg(feature = "gateway")] + gateways: BTreeMap::new(), }) } @@ -69,6 +73,55 @@ impl Runtime { self } + /// Select one declared gateway. This stores portable host configuration only; + /// the caller instantiates its native/Worker resources after selecting it. + #[cfg(feature = "gateway")] + pub fn mount_gateway( + mut self, + application: &super::Application, + selector: super::MountSelector, + gateway: crate::gateway::Gateway, + ) -> ApplicationResult { + let super::MountSelector::Extension { id } = &selector else { + return Err(ApplicationError::InvalidSpec( + "gateway requires an extension mount".into(), + )); + }; + let expected = gateway.application_extension(id.clone())?; + if !application.manifest().extensions.contains(&expected) { + return Err(ApplicationError::InvalidSpec( + "gateway capabilities do not match the application declaration".into(), + )); + } + if self.gateways.insert(selector, gateway).is_some() { + return Err(ApplicationError::InvalidSpec( + "duplicate gateway mount".into(), + )); + } + Ok(self) + } + + /// Only explicitly selected gateways can be bound to a network adapter. + #[cfg(feature = "gateway")] + pub fn gateway(&self, selector: &super::MountSelector) -> Option<&crate::gateway::Gateway> { + self.gateways.get(selector) + } + + /// Invoke an adapter/resource factory only when this gateway was selected. + #[cfg(feature = "gateway")] + pub fn bind_gateway( + &self, + selector: &super::MountSelector, + factory: impl FnOnce(&crate::gateway::Gateway) -> Result, + ) -> Result, E> { + self.gateway(selector).map(factory).transpose() + } + + #[cfg(feature = "gateway")] + pub fn starts_gateway(&self) -> bool { + !self.gateways.is_empty() + } + pub fn graphql(mut self) -> Self { self.graphql = true; self diff --git a/src/gateway/application.rs b/src/gateway/application.rs new file mode 100644 index 000000000..bbab1882f --- /dev/null +++ b/src/gateway/application.rs @@ -0,0 +1,28 @@ +use super::{BindingKind, Gateway}; +use crate::application::{ApplicationExtension, ApplicationResult}; + +impl Gateway { + /// Logical capability declaration for Application/Service composition. + /// Changing physical origins, paths or embedded/remote placement does not + /// change the portable application identity. + pub fn application_extension( + &self, + id: impl Into, + ) -> ApplicationResult { + let bindings = self.bindings().map(|binding| { + let capability = match &binding.kind { + BindingKind::Handler => serde_json::json!({"kind":"handler"}), + BindingKind::Admission => serde_json::json!({"kind":"admission"}), + BindingKind::Assets => serde_json::json!({"kind":"assets"}), + BindingKind::UiProxy { .. } => serde_json::json!({"kind":"ui"}), + BindingKind::Graphql { capabilities, delivery, schema_extensions, .. } => serde_json::json!({"kind":"graphql","operations":capabilities,"delivery":delivery,"schemaExtensions":schema_extensions}), + }; + serde_json::json!({"id":binding.id,"capability":capability}) + }).collect::>(); + ApplicationExtension::try_new( + id, + 1, + serde_json::json!({"kind":"application_gateway","bindings":bindings}), + ) + } +} diff --git a/src/gateway/config.rs b/src/gateway/config.rs index a0f761263..e1a016306 100644 --- a/src/gateway/config.rs +++ b/src/gateway/config.rs @@ -205,6 +205,11 @@ impl Gateway { &self.routes } + /// Deterministic logical binding inventory for explicit application mounts. + pub fn bindings(&self) -> impl ExactSizeIterator { + self.bindings.values() + } + /// Resolve a configured resource without accepting a caller-selected URL. pub fn binding(&self, id: &str) -> Option<&Binding> { self.bindings.get(id) diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 09ac5ff47..23cb2ed9f 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -48,3 +48,5 @@ pub mod delivery; /// workers-rs ingress and sharded Durable Object delivery adapter. #[cfg(feature = "gateway-worker")] pub mod worker; + +mod application; diff --git a/tests/e2e-ui/Cargo.toml b/tests/e2e-ui/Cargo.toml index cd0e2a16e..d1f979d48 100644 --- a/tests/e2e-ui/Cargo.toml +++ b/tests/e2e-ui/Cargo.toml @@ -22,7 +22,7 @@ license = "MIT" publish = false [workspace.dependencies] -distributed = { path = "../..", features = ["sqlite", "postgres", "http", "graphql", "metrics"] } +distributed = { path = "../..", features = ["sqlite", "postgres", "http", "graphql", "metrics", "gateway-graphql-native", "gateway-delivery"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync"] } diff --git a/tests/e2e-ui/Makefile b/tests/e2e-ui/Makefile index 3b672aee0..b8f53fb4b 100644 --- a/tests/e2e-ui/Makefile +++ b/tests/e2e-ui/Makefile @@ -19,7 +19,9 @@ API_PORT ?= 8791 BASE_URL ?= http://127.0.0.1:8791 UI_PORT ?= 5180 # localhost required for Auth.js cookies over HTTP (SvelteKit Secure default) -UI_URL ?= http://localhost:5180 +PUBLIC_ORIGIN ?= http://localhost:8791 +UI_INTERNAL_ORIGIN ?= http://localhost:$(UI_PORT) +UI_URL ?= $(PUBLIC_ORIGIN) UI_HOST ?= localhost ENV_FILE ?= e2e-ui.env NPM ?= npm @@ -56,7 +58,8 @@ down: ## Coherent application build + actual API/UI supervision. ## Vite still owns Svelte, CSS, and GraphQL hot updates. run: - cargo run --quiet --manifest-path ../../Cargo.toml -p distributed_cli --bin distributed -- dev . + @if [ -f $(ENV_FILE) ]; then set -a; . ./$(ENV_FILE); set +a; fi; \ + PUBLIC_ORIGIN="$${PUBLIC_ORIGIN:-$(PUBLIC_ORIGIN)}" UI_URL="$${PUBLIC_ORIGIN:-$(PUBLIC_ORIGIN)}" UI_INTERNAL_ORIGIN="$${UI_INTERNAL_ORIGIN:-$(UI_INTERNAL_ORIGIN)}" cargo run --quiet --manifest-path ../../Cargo.toml -p distributed_cli --bin distributed -- dev . run-api: @if [ -f $(ENV_FILE) ]; then set -a; . ./$(ENV_FILE); set +a; fi; \ diff --git a/tests/e2e-ui/README.md b/tests/e2e-ui/README.md index 0dba81318..a26891050 100644 --- a/tests/e2e-ui/README.md +++ b/tests/e2e-ui/README.md @@ -46,8 +46,13 @@ make up # once: writes e2e-ui.env distributed dev ``` -The UI is at `http://localhost:5180`; GraphQL is at -`http://127.0.0.1:8791/graphql`. The CLI loads `e2e-ui.env` when it exists. +The public UI is at `http://localhost:8791`; GraphQL is at +`http://localhost:8791/graphql`. The backend hosts the application gateway and +proxies UI/auth requests to internal SvelteKit on port 5180. `PUBLIC_ORIGIN` +selects the public URL and `UI_INTERNAL_ORIGIN` selects the UI upstream. Vite +does not proxy API requests back to the gateway. Set `GATEWAY_DELIVERY=all` to +opt into bounded query snapshots, coalescing and shared live delivery; the +default `none` allocates none of those coordinators. The CLI loads `e2e-ui.env` when it exists. Demo users are `alice`, `bob`, and `admin` with password `Password1!`. `make run` is a convenience alias for the same zero-config command. Before diff --git a/tests/e2e-ui/crates/runner/src/main.rs b/tests/e2e-ui/crates/runner/src/main.rs index 5fb400293..abb34c346 100644 --- a/tests/e2e-ui/crates/runner/src/main.rs +++ b/tests/e2e-ui/crates/runner/src/main.rs @@ -21,6 +21,19 @@ async fn main() -> Result<(), Box> { HostOptions { bind, identity: identity_from_env(), + public_origin: env::var("PUBLIC_ORIGIN") + .unwrap_or_else(|_| "http://localhost:8791".into()), + ui_origin: env::var("UI_INTERNAL_ORIGIN") + .unwrap_or_else(|_| "http://localhost:5180".into()), + delivery: match env::var("GATEWAY_DELIVERY").as_deref().unwrap_or("none") { + "none" => Default::default(), + "all" => distributed::gateway::DeliveryCapabilities { + snapshots: true, + coalescing: true, + live_sharing: true, + }, + _ => return Err("GATEWAY_DELIVERY must be none or all".into()), + }, }, ) .await diff --git a/tests/e2e-ui/crates/service/src/host.rs b/tests/e2e-ui/crates/service/src/host.rs index d16589d09..ff1e43bb3 100644 --- a/tests/e2e-ui/crates/service/src/host.rs +++ b/tests/e2e-ui/crates/service/src/host.rs @@ -19,8 +19,8 @@ use distributed::microsvc::{ use distributed::{PostgresLockManager, PostgresRepository, SqliteLockManager, SqliteRepository}; use crate::{ - build_graphql_engine, build_service, distributed_manifest, serve, spawn_scrape_loop, - ZitadelScrapeConfig, E2E_UI_APPLICATION, + build_service, distributed_manifest, serve, spawn_scrape_loop, ZitadelScrapeConfig, + E2E_UI_APPLICATION, }; const BUS_GROUP: &str = "e2e-ui"; @@ -29,6 +29,9 @@ const BUS_GROUP: &str = "e2e-ui"; pub struct HostOptions { pub bind: String, pub identity: IdentityConfig, + pub public_origin: String, + pub ui_origin: String, + pub delivery: distributed::gateway::DeliveryCapabilities, } /// Start the e2e-ui full-local process for SQLite or Postgres from `DATABASE_URL`. @@ -63,7 +66,30 @@ async fn run_sqlite( let change_rx = repo.read_model_changes(); let service = build_service(repo.clone(), locks.clone(), repo.clone()) .with_bus(SqliteBus::new(repo.pool().clone()).group(BUS_GROUP)); - let gql = build_graphql_engine(&repo, &service, options.identity.clone(), Some(change_rx))?; + let versions = if options.delivery != distributed::gateway::DeliveryCapabilities::default() { + Some( + distributed::graphql::delivery::GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(repo.pool().clone()), + "e2e-ui-gateway-v1", + [ + "todos".into(), + "chat_messages".into(), + "blob_games".into(), + "auth_users".into(), + ], + ) + .await?, + ) + } else { + None + }; + let gql = crate::modules::graphql::build_graphql_engine_with_delivery( + &repo, + &service, + options.identity.clone(), + Some(change_rx), + versions, + )?; let service = Arc::new(service.try_with_graphql(gql)?); let _dispatcher = Arc::new(LocalCommandDispatcher::new(Arc::clone(&service))); @@ -87,7 +113,7 @@ async fn run_sqlite( spawn_zitadel_scrape(repo.clone()); eprintln!("e2e-ui (sqlite) listening on http://{}", options.bind); - serve(service, &options.bind).await?; + serve(service, &options).await?; Ok(()) } @@ -107,7 +133,30 @@ async fn run_postgres( let change_rx = repo.read_model_changes(); let service = build_service(repo.clone(), locks.clone(), repo.clone()) .with_bus(PostgresBus::new(repo.pool().clone()).group(BUS_GROUP)); - let gql = build_graphql_engine(&repo, &service, options.identity.clone(), Some(change_rx))?; + let versions = if options.delivery != distributed::gateway::DeliveryCapabilities::default() { + Some( + distributed::graphql::delivery::GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(repo.pool().clone()), + "e2e-ui-gateway-v1", + [ + "todos".into(), + "chat_messages".into(), + "blob_games".into(), + "auth_users".into(), + ], + ) + .await?, + ) + } else { + None + }; + let gql = crate::modules::graphql::build_graphql_engine_with_delivery( + &repo, + &service, + options.identity.clone(), + Some(change_rx), + versions, + )?; let service = Arc::new(service.try_with_graphql(gql)?); let _dispatcher = Arc::new(LocalCommandDispatcher::new(Arc::clone(&service))); @@ -131,7 +180,7 @@ async fn run_postgres( spawn_zitadel_scrape(repo.clone()); eprintln!("e2e-ui (postgres) listening on http://{}", options.bind); - serve(service, &options.bind).await?; + serve(service, &options).await?; Ok(()) } diff --git a/tests/e2e-ui/crates/service/src/http.rs b/tests/e2e-ui/crates/service/src/http.rs index e47c00ec7..bd381daad 100644 --- a/tests/e2e-ui/crates/service/src/http.rs +++ b/tests/e2e-ui/crates/service/src/http.rs @@ -58,11 +58,130 @@ async fn dispatch_named( } } -/// Serve GraphQL (engine identity) plus Zitadel Action HTTP. -pub async fn serve(service: Arc, addr: &str) -> Result<(), std::io::Error> { - let ingress = service.clone(); - let scrape = service.clone(); - let app = distributed::microsvc::router(service) +/// Compose the application's explicit public gateway without opening a listener. +pub fn gateway_router( + service: Arc, + options: &crate::HostOptions, +) -> Result { + use distributed::application::{MountSelector, Runtime}; + use distributed::command_dispatch::LocalCommandHost; + use distributed::gateway::{delivery::*, native::*, *}; + use distributed::graphql::identity::OidcGatewayProvider; + let engine = service + .graphql_engine() + .ok_or_else(|| std::io::Error::other("application GraphQL engine missing"))?; + let capabilities = GraphqlCapabilities { + queries: true, + commands: true, + live: true, + }; + let mut routes = vec![ + Route::new("graphql", RoutePath::prefix("/graphql"), "graphql"), + Route::new("auth", RoutePath::prefix("/auth"), "ui"), + Route::new("auth-api", RoutePath::prefix("/api/auth"), "ui"), + Route::new("ui", RoutePath::prefix("/"), "ui"), + ]; + for path in [ + "/zitadel.ingress.v1", + "/zitadel.scrape.v1", + "/health", + "/healthz", + "/metrics", + "/graphiql", + "/__distributed", + ] { + routes.push(Route::new( + format!("http-{}", routes.len()), + RoutePath::prefix(path), + "service", + )); + } + // Old HTTP command URLs retain API ownership and cannot become UI HTML. + for command in service.command_specs().map_err(std::io::Error::other)? { + let path = format!("/{}", command.id); + if !routes + .iter() + .any(|route| route.path == RoutePath::prefix(&path)) + { + routes.push(Route::new( + format!("command-{}", routes.len()), + RoutePath::exact(path), + "closed", + )); + } + } + let gateway = GatewayConfig { + bindings: vec![ + Binding::new( + "graphql", + BindingKind::Graphql { + executor: GraphqlExecutor::Embedded, + capabilities, + delivery: options.delivery, + schema_extensions: vec![], + }, + ), + Binding::new( + "ui", + BindingKind::UiProxy { + origin: options.ui_origin.clone(), + }, + ), + Binding::new("service", BindingKind::Handler), + Binding::new("closed", BindingKind::Handler), + ], + routes, + } + .build() + .map_err(std::io::Error::other)?; + let surface = crate::application_manifest() + .surfaces + .into_iter() + .next() + .ok_or_else(|| std::io::Error::other("application surface missing"))?; + let application = service + .application(crate::E2E_UI_APPLICATION, surface) + .map_err(std::io::Error::other)? + .with_gateway("public", &gateway) + .map_err(std::io::Error::other)?; + let selector = MountSelector::gateway("public").map_err(std::io::Error::other)?; + let runtime = Runtime::default() + .mount_gateway(&application, selector.clone(), gateway) + .map_err(std::io::Error::other)?; + runtime + .bind_gateway(&selector, |gateway| { + let graphql = GraphqlBinding::Embedded( + EmbeddedGraphql::new( + engine.clone(), + Some(Arc::new(LocalCommandHost::new(service.clone()))), + capabilities, + ) + .map_err(std::io::Error::other)?, + ); + let graphql = if options.delivery == DeliveryCapabilities::default() { + NativeBinding::Graphql(graphql) + } else { + let delivery = NativeDelivery::new(NativeDeliveryOptions { + snapshots: options.delivery.snapshots.then(SnapshotLimits::default), + coalescing: options.delivery.coalescing.then(FlightLimits::default), + live: options.delivery.live_sharing.then(LiveLimits::default), + }) + .map_err(std::io::Error::other)?; + NativeBinding::GraphqlWithDelivery(graphql, Arc::new(delivery)) + }; + let auth = if let Some(config) = engine.identity_config().oidc.clone() { + let provider = Arc::new(OidcGatewayProvider::new(config, "e2e-ui-oidc-v1")); + NativeAuth::new(move |credentials| { + let provider = provider.clone(); + async move { provider.authenticate(&credentials).await } + }) + } else { + NativeAuth::anonymous() + }; + + let ingress = service.clone(); + let scrape = service.clone(); + let service_routes = distributed::microsvc::router(service) .route( "/zitadel.ingress.v1", post(move |headers: HeaderMap, Json(input): Json| { @@ -78,6 +197,29 @@ pub async fn serve(service: Arc, addr: &str) -> Result<(), std::io::Err }), ); - let listener = tokio::net::TcpListener::bind(addr).await?; + NativeGateway::new( + gateway.clone(), + NativeOptions::new(&options.public_origin), + [ + ("graphql".into(), graphql), + ("ui".into(), NativeBinding::UiProxy { websocket: true }), + ("service".into(), NativeBinding::Handler(service_routes)), + ("closed".into(), NativeBinding::Handler(axum::Router::new())), + ], + auth, + ) + .map(NativeGateway::router) + .map_err(std::io::Error::other) + }) + .map(|adapter| adapter.expect("explicitly selected gateway")) +} + +/// One backend owns the public listener; SvelteKit remains its UI/auth backend. +pub async fn serve( + service: Arc, + options: &crate::HostOptions, +) -> Result<(), std::io::Error> { + let app = gateway_router(service, options)?; + let listener = tokio::net::TcpListener::bind(&options.bind).await?; axum::serve(listener, app).await } diff --git a/tests/e2e-ui/crates/service/src/lib.rs b/tests/e2e-ui/crates/service/src/lib.rs index 9b3a0685c..5db126ac8 100644 --- a/tests/e2e-ui/crates/service/src/lib.rs +++ b/tests/e2e-ui/crates/service/src/lib.rs @@ -19,15 +19,15 @@ mod http; pub mod modules; pub use application::{ - DISTRIBUTED_ADMIN_CLIENT_SURFACE, DISTRIBUTED_CLIENT_SURFACE, DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - E2E_UI_APPLICATION, E2E_UI_MODULE_IDS, + DISTRIBUTED_ADMIN_CLIENT_SURFACE, DISTRIBUTED_CLIENT_SURFACE, + DISTRIBUTED_PUBLIC_CLIENT_SURFACE, E2E_UI_APPLICATION, E2E_UI_MODULE_IDS, }; pub use e2e_readmodels::distributed_manifest; pub use handlers::ingestors::zitadel::{ scrape_users_to_outbox, spawn_scrape_loop, ScrapeReport, ZitadelScrapeConfig, }; pub use host::{run, HostOptions}; -pub use http::serve; +pub use http::{gateway_router, serve}; pub use modules::compose::build_service; pub use modules::graphql::{ application_manifest, build_graphql_engine, dev_identity, distributed_admin_client_surface, diff --git a/tests/e2e-ui/crates/service/src/modules/graphql.rs b/tests/e2e-ui/crates/service/src/modules/graphql.rs index 46429157a..0956415fa 100644 --- a/tests/e2e-ui/crates/service/src/modules/graphql.rs +++ b/tests/e2e-ui/crates/service/src/modules/graphql.rs @@ -49,6 +49,34 @@ pub(crate) fn build_graphql_engine_with_graphiql( identity: IdentityConfig, change_rx: Option>, graphiql: bool, +) -> Result { + build_engine(pool, service, identity, change_rx, graphiql, None) +} + +pub(crate) fn build_graphql_engine_with_delivery( + pool: impl Into, + service: &Service, + identity: IdentityConfig, + change_rx: Option>, + versions: Option, +) -> Result { + build_engine( + pool, + service, + identity, + change_rx, + graphiql_enabled(), + versions, + ) +} + +fn build_engine( + pool: impl Into, + service: &Service, + identity: IdentityConfig, + change_rx: Option>, + graphiql: bool, + versions: Option, ) -> Result { let projections = projections::projection_owners(); let mut b = GraphqlEngine::builder(pool) @@ -80,6 +108,9 @@ pub(crate) fn build_graphql_engine_with_graphiql( if let Some(rx) = change_rx { b = b.change_stream(rx); } + if let Some(versions) = versions { + b = b.gateway_versions(versions); + } b.build().map_err(|e| e.to_string()) } diff --git a/tests/e2e-ui/gateway/.gitignore b/tests/e2e-ui/gateway/.gitignore new file mode 100644 index 000000000..d4f588edf --- /dev/null +++ b/tests/e2e-ui/gateway/.gitignore @@ -0,0 +1 @@ +artifacts/ diff --git a/tests/e2e-ui/gateway/README.md b/tests/e2e-ui/gateway/README.md new file mode 100644 index 000000000..41b7460e2 --- /dev/null +++ b/tests/e2e-ui/gateway/README.md @@ -0,0 +1,20 @@ +# Public application gateway browser fixture + +Run `npm ci --prefix tests/gateway-auth`, install that fixture's Playwright +Chromium, then `node tests/e2e-ui/gateway/run.mjs` from the repository root. +Rust stable, wasm32-unknown-unknown and wasm-pack are required. The runner uses +`distributed build` to generate a coherent application and production SvelteKit +bundle; `GATEWAY_SKIP_BUILD=1` reuses an already successful build for iteration. + +Each delivery mode (`none`, `all`) starts a disposable SQLite backend, production +SvelteKit and an isolated standards OIDC provider on free loopback ports. There +are no external users, secrets, databases or cluster resources. Only processes +and temporary data created by this runner are stopped/removed. + +Assertions cover public-origin callback, trusted UI/API identity, cookie flags, +real refresh and failed-refresh denial, logout, API ownership, Todo Eventual +optimism before its held receipt, Blob Atomic response painting without HTTP +refetch, an old HTTP/cache response arriving after another move, and a real old +live frame replayed after a confirmed Chat command. Mutation observers detect +transient regressions as well as the final state. Logs omit session payloads and +are saved under ignored `artifacts/`. diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs new file mode 100644 index 000000000..2c4292b9e --- /dev/null +++ b/tests/e2e-ui/gateway/run.mjs @@ -0,0 +1,147 @@ +import assert from 'node:assert/strict'; +import {spawn} from 'node:child_process'; +import {createServer} from 'node:http'; +import {once} from 'node:events'; +import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {randomBytes} from 'node:crypto'; +import {chromium,expect} from '../../gateway-auth/node_modules/@playwright/test/index.mjs'; +import {startProvider} from '../../gateway-auth/provider.mjs'; +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const environment={PATH:process.env.PATH,HOME:process.env.HOME,RUSTUP_TOOLCHAIN:process.env.RUSTUP_TOOLCHAIN||'stable',NODE_ENV:'production'}; +async function freePort(){const server=createServer();server.listen(0,'127.0.0.1');await once(server,'listening');const port=server.address().port;await new Promise(r=>server.close(r));return port;} +function launch(program,args,{cwd=root,env=environment}={}){ + let log='';const child=spawn(program,args,{cwd,env,stdio:['ignore','pipe','pipe']}); + child.on('error',error=>log+='process launch failed: '+error.code); + child.stdout.on('data',chunk=>log=(log+chunk).slice(-60000));child.stderr.on('data',chunk=>log=(log+chunk).slice(-60000)); + return {child,logs:()=>log,stop:async()=>{if(child.exitCode===null){child.kill('SIGTERM');await once(child,'exit');}}}; +} +async function ready(url,process){for(let i=0;i<300;i++){if(process.child.exitCode!==null)throw Error(process.logs());try{const response=await fetch(url);if(response.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('readiness timeout: '+process.logs());} +const artifacts=path.join(root,'gateway/artifacts');await mkdir(artifacts,{recursive:true}); +if(process.env.GATEWAY_SKIP_BUILD!=='1'){ + const {NODE_ENV,...buildEnvironment}=environment; + const build=launch('cargo',['run','--quiet','--manifest-path',path.resolve(root,'../../Cargo.toml'),'-p','distributed_cli','--bin','distributed','--','build',root],{env:buildEnvironment}); + const [code]=await once(build.child,'exit');await writeFile(path.join(artifacts,'ui-build.log'),build.logs());assert.equal(code,0,build.logs()); +} +const temporary=await mkdtemp(path.join(os.tmpdir(),'gateway-app-')); +try{ + for(const delivery of ['none','all']){ + const apiPort=await freePort(),uiPort=await freePort(),issuer=`http://127.0.0.1:${await freePort()}`; + const publicOrigin=`http://127.0.0.1:${apiPort}`; + const idp=await startProvider(issuer,publicOrigin,{jwtAudience:'gateway-fixture'}); + let api,ui,browser; + try{ + api=launch(path.join(root,'target/debug/e2e-ui'),[],{env:{...environment,DATABASE_URL:`sqlite:${temporary}/${delivery}.db?mode=rwc`,BIND:`127.0.0.1:${apiPort}`,PUBLIC_ORIGIN:publicOrigin,UI_INTERNAL_ORIGIN:`http://127.0.0.1:${uiPort}`,GATEWAY_DELIVERY:delivery,OIDC_ISSUER:issuer,OIDC_AUDIENCE:'gateway-fixture',OIDC_CLIENT_ID:'gateway-fixture',GRAPHIQL:'0'}}); + await ready(publicOrigin+'/health',api); + ui=launch(process.execPath,['build/index.js'],{cwd:path.join(root,'ui'),env:{...environment,HOST:'127.0.0.1',PORT:String(uiPort),PUBLIC_ORIGIN:publicOrigin,ORIGIN:publicOrigin,AUTH_URL:publicOrigin,AUTH_SECRET:randomBytes(32).toString('hex'),AUTH_USE_SECURE_COOKIES:'false',OIDC_ISSUER:issuer,OIDC_CLIENT_ID:'gateway-fixture',OIDC_CLIENT_SECRET:'local-fixture-only',OIDC_AUDIENCE:'gateway-fixture',E2E_API_ORIGIN:publicOrigin}}); + await ready(publicOrigin,ui); + browser=await chromium.launch();const context=await browser.newContext();const page=await context.newPage(); + const errors=[];page.on('pageerror',error=>errors.push(error.message)); + await page.goto(publicOrigin);await page.getByRole('link',{name:/log in|sign in/i}).first().click(); + await page.getByRole('button',{name:'Continue as Alice'}).click(); + await page.waitForURL(url=>url.origin===publicOrigin&&!url.pathname.startsWith('/auth')&&!url.pathname.startsWith('/login')); + const session=await(await context.request.get(publicOrigin+'/auth/session')).json();assert.equal(session.user.id,'alice'); + await page.goto(publicOrigin+'/todos');await expect(page.getByRole('heading',{name:/todos/i})).toBeVisible(); + const unauthenticated=await fetch(publicOrigin+'/graphql',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({query:'query { todos { todo_id } }'})}); + assert.match(unauthenticated.headers.get('content-type'),/json/); + assert.ok((await unauthenticated.json()).errors?.length); + assert.equal((await context.request.post(publicOrigin+'/todo.create',{data:{}})).status(),404); + let releaseCommand,commandReady; + const commandBarrier=new Promise(resolve=>releaseCommand=resolve),commandArrived=new Promise(resolve=>commandReady=resolve); + await page.route('**/graphql',async route=>{ + if(!(route.request().postData()||'').includes('todos_create'))return route.continue(); + const response=await route.fetch();commandReady();await commandBarrier;await route.fulfill({response}); + }); + const title='gateway todo '+delivery;await page.locator('input').first().fill(title);await page.getByRole('button',{name:/^add$/i}).click(); + const todo=page.locator('[data-todo-id]').filter({hasText:title});await expect(todo).toBeVisible();await commandArrived;await expect(todo.locator('.pending-state')).toHaveText('Saving…');releaseCommand();await expect(todo.locator('.pending-state')).toHaveCount(0,{timeout:20000}); + await page.unroute('**/graphql'); + await todo.getByRole('button',{name:/^done$/i}).click();await expect(page.locator('.panel').filter({has:page.getByRole('heading',{name:/^done$/i})}).getByText(title)).toBeVisible(); + await page.goto(publicOrigin+'/blob');await expect(page.getByTestId('blob-start-game')).toBeEnabled();await page.getByTestId('blob-start-game').click();await expect(page.locator('.blob-board')).toBeVisible({timeout:20000}); + await verifyBlobRace(page); + await verifyLiveRace(page,publicOrigin); + await verifyAuth(context,idp,publicOrigin); + assert.deepEqual(errors,[]);console.log('PASS actual public-origin application login, Todo Eventual and Blob Atomic with delivery '+delivery); + }catch(error){await writeFile(path.join(artifacts,delivery+'-failure.txt'),String(error));throw error;} + finally{await browser?.close();await ui?.stop();await api?.stop();await new Promise(r=>idp.server.close(r));if(api)await writeFile(path.join(artifacts,delivery+'-api.log'),api.logs());if(ui)await writeFile(path.join(artifacts,delivery+'-ui.log'),ui.logs());} + } +}finally{await rm(temporary,{recursive:true,force:true});} + +// Delay a real old HTTP envelope while an Atomic response advances the replica. +// Delivery-enabled requests exercise the cache path; the body/proof are unchanged. +async function verifyBlobRace(page){ + await expect(page.locator('[data-blob-hydrated="1"]')).toBeVisible(); + const player=page.locator('.blob-board .tile-player'); + let queries=0;const count=request=>{if((request.postData()||'').includes('query BlobGames'))queries++;}; + page.on('request',count); + const move=async(key,label)=>{ + const result=page.waitForResponse(response=>(response.request().postData()||'').includes('blob_games_move')); + await page.keyboard.press(key);assert.ok((await result).ok());await expect(player).toHaveAttribute('aria-label',label); + }; + await move('ArrowRight','r0 c1'); + assert.equal(queries,0,'Atomic direct response should paint without an HTTP refetch'); + let release,arrived;const barrier=new Promise(resolve=>release=resolve),ready=new Promise(resolve=>arrived=resolve); + let held=false; + await page.route('**/graphql',async route=>{ + if(held||!(route.request().postData()||'').includes('query BlobGames'))return route.continue(); + held=true;const response=await route.fetch();assert.ok((await response.json()).data?.blob_games?.length);arrived();await barrier;await route.fulfill({response}); + }); + const refetch=()=>page.evaluate(()=>globalThis.__distributedBlobRefetch()); + const oldRequest=refetch();await ready; + const hole=(await page.locator('.cell[aria-label="r0 c2"]').getAttribute('class')).includes('tile-hole'); + const label=hole?'r1 c1':'r0 c2';await move(hole?'ArrowDown':'ArrowRight',label); + await page.evaluate(()=>{ + globalThis.__gatewaySamples=[]; + globalThis.__gatewayObserver=new MutationObserver(()=>globalThis.__gatewaySamples.push(document.querySelector('.blob-board .tile-player')?.getAttribute('aria-label')??'missing')); + globalThis.__gatewayObserver.observe(document.querySelector('.blob-page'),{attributes:true,childList:true,subtree:true,characterData:true}); + }); + release();await oldRequest;await refetch();await expect(player).toHaveAttribute('aria-label',label); + const samples=await page.evaluate(()=>{globalThis.__gatewayObserver.disconnect();return globalThis.__gatewaySamples;}); + assert.ok(samples.every(sample=>sample===label),'late HTTP/cache observation regressed the Atomic board'); + page.off('request',count);await page.unroute('**/graphql'); + await page.reload();await expect(player).toHaveAttribute('aria-label',label); +} +async function verifyAuth(context,idp,origin){ + const cookies=(await context.cookies()).filter(cookie=>cookie.name.startsWith('authjs.session-token')); + assert.ok(cookies.length&&cookies.every(cookie=>cookie.httpOnly&&cookie.sameSite==='Lax'&&cookie.path==='/')); + await new Promise(resolve=>setTimeout(resolve,2200)); + const response=await context.request.post(origin+'/api/auth/refresh',{headers:{origin}}); + assert.equal(response.status(),200);assert.equal((await response.json()).authenticated,true);assert.ok(idp.refreshes()>0); + idp.failRefresh();await new Promise(resolve=>setTimeout(resolve,2200)); + const failed=await context.request.post(origin+'/api/auth/refresh',{headers:{origin}}); + assert.equal(failed.status(),401);assert.equal((await failed.json()).error,'RefreshAccessTokenError'); + const denied=await context.request.get(origin+'/todos',{maxRedirects:0});assert.equal(denied.status(),303); + const signedOut=await context.request.get(origin+'/signout',{maxRedirects:0});assert.equal(signedOut.status(),303); + assert.ok(!(await context.cookies()).some(cookie=>cookie.name.startsWith('authjs.session-token'))); +} + +async function verifyLiveRace(page,origin){ + let oldFrame,downstream,liveUpdates=0; + await page.routeWebSocket('**/graphql/ws',socket=>{ + const upstream=socket.connectToServer(); + upstream.onMessage(message=>{ + let frame;try{frame=JSON.parse(String(message));}catch{} + if(frame?.type==='next'&&Array.isArray(frame.payload?.data?.chat_messages)){ + liveUpdates++;if(!oldFrame){oldFrame=message;downstream=socket;} + } + socket.send(message); + }); + }); + await page.goto(origin+'/chat');await expect.poll(()=>liveUpdates,{timeout:20000}).toBeGreaterThan(0); + const body='gateway live nonregression'; + await page.locator('#chat-body').fill(body);await page.getByRole('button',{name:/send/i}).click(); + await expect(page.getByText(body,{exact:true})).toBeVisible(); + await expect.poll(()=>liveUpdates,{timeout:20000}).toBeGreaterThan(1); + await page.evaluate(text=>{ + globalThis.__gatewayLiveSamples=[]; + globalThis.__gatewayLiveObserver=new MutationObserver(()=>globalThis.__gatewayLiveSamples.push(document.body.innerText.includes(text))); + globalThis.__gatewayLiveObserver.observe(document.body,{childList:true,subtree:true,characterData:true}); + },body); + downstream.send(oldFrame); + // Give the transport and Svelte render queue an observation window. + await page.waitForTimeout(150); + await expect(page.getByText(body,{exact:true})).toBeVisible(); + const samples=await page.evaluate(()=>{globalThis.__gatewayLiveObserver.disconnect();return globalThis.__gatewayLiveSamples;}); + assert.ok(samples.every(Boolean),'late live observation removed the confirmed message'); +} diff --git a/tests/e2e-ui/playwright.config.ts b/tests/e2e-ui/playwright.config.ts index 4882bc601..1b3de976b 100644 --- a/tests/e2e-ui/playwright.config.ts +++ b/tests/e2e-ui/playwright.config.ts @@ -27,7 +27,7 @@ function loadEnvFile(file: string) { loadEnvFile(path.join(root, 'e2e-ui.env')); -const baseURL = process.env.E2E_UI_ORIGIN || process.env.UI_URL || 'http://localhost:5180'; +const baseURL = process.env.PUBLIC_ORIGIN || process.env.E2E_UI_ORIGIN || process.env.UI_URL || 'http://localhost:8791'; /** * Browser tests for e2e-ui. diff --git a/tests/e2e-ui/scripts/up.sh b/tests/e2e-ui/scripts/up.sh index 57097eed6..b3edaebcc 100755 --- a/tests/e2e-ui/scripts/up.sh +++ b/tests/e2e-ui/scripts/up.sh @@ -10,7 +10,7 @@ ZITADEL_HOST="${ZITADEL_HOST:-http://localhost:18080}" OUT="${E2E_UI_ENV:-$ROOT/e2e-ui.env}" # Prefer localhost (not 127.0.0.1): SvelteKit only skips Secure cookies for # hostname === "localhost" over http. 127.0.0.1 forces Secure and breaks OIDC. -UI_ORIGIN="${E2E_UI_ORIGIN:-http://localhost:5180}" +UI_ORIGIN="${PUBLIC_ORIGIN:-${E2E_UI_ORIGIN:-http://localhost:8791}}" API_ORIGIN="${E2E_API_ORIGIN:-http://127.0.0.1:8791}" PROJECT_NAME="${E2E_OIDC_PROJECT:-e2e-ui}" APP_NAME="${E2E_OIDC_APP:-e2e-ui-web}" @@ -298,8 +298,8 @@ if [[ -z "$APP_ID" ]]; then redirectUris: [ ($ui + "/auth/callback/oidc"), ($ui + "/auth/callback"), - "http://127.0.0.1:5180/auth/callback/oidc", - "http://localhost:5180/auth/callback/oidc" + "http://127.0.0.1:8791/auth/callback/oidc", + "http://localhost:8791/auth/callback/oidc" ], responseTypes: ["OIDC_RESPONSE_TYPE_CODE"], grantTypes: [ @@ -311,10 +311,10 @@ if [[ -z "$APP_ID" ]]; then postLogoutRedirectUris: [ ($ui + "/"), $ui, - "http://127.0.0.1:5180/", - "http://127.0.0.1:5180", - "http://localhost:5180/", - "http://localhost:5180" + "http://127.0.0.1:8791/", + "http://127.0.0.1:8791", + "http://localhost:8791/", + "http://localhost:8791" ], version: "OIDC_VERSION_1_0", devMode: true, @@ -341,8 +341,8 @@ else redirectUris: [ ($ui + "/auth/callback/oidc"), ($ui + "/auth/callback"), - "http://127.0.0.1:5180/auth/callback/oidc", - "http://localhost:5180/auth/callback/oidc" + "http://127.0.0.1:8791/auth/callback/oidc", + "http://localhost:8791/auth/callback/oidc" ], responseTypes: ["OIDC_RESPONSE_TYPE_CODE"], grantTypes: [ @@ -354,10 +354,10 @@ else postLogoutRedirectUris: [ ($ui + "/"), $ui, - "http://127.0.0.1:5180/", - "http://127.0.0.1:5180", - "http://localhost:5180/", - "http://localhost:5180" + "http://127.0.0.1:8791/", + "http://127.0.0.1:8791", + "http://localhost:8791/", + "http://localhost:8791" ], devMode: true, accessTokenType: "OIDC_TOKEN_TYPE_JWT", @@ -602,6 +602,8 @@ ZITADEL_PROJECT_ID="$(_dq "$PROJECT_ID")" # Server-only: custom /login uses Session API + CreateCallback (never expose to browser). ZITADEL_SERVICE_USER_TOKEN="$(_dq "$LOGIN_PAT")" LOGIN_V2_BASE_URI="$(_dq "$LOGIN_V2_BASE_URI")" +PUBLIC_ORIGIN="$(_dq "$UI_ORIGIN")" +UI_INTERNAL_ORIGIN="http://localhost:5180" E2E_UI_ORIGIN="$(_dq "$UI_ORIGIN")" E2E_API_ORIGIN="$(_dq "$API_ORIGIN")" E2E_MACHINE_USER_KEY="$(_dq "$USER_M_KEY")" diff --git a/tests/e2e-ui/ui/src/lib/server/require-auth.ts b/tests/e2e-ui/ui/src/lib/server/require-auth.ts index f3915576e..e2096c330 100644 --- a/tests/e2e-ui/ui/src/lib/server/require-auth.ts +++ b/tests/e2e-ui/ui/src/lib/server/require-auth.ts @@ -11,7 +11,7 @@ type AuthLocals = { }; /** Share the current-session check between protected UI and refresh/API routes. */ -export function isCurrentSession(session: AuthSession | null): session is AuthSession { +export function isCurrentSession(session: AuthSession | null): session is AuthSession & { user: NonNullable } { return !!session?.user && !session.error && (session.expiresAt === undefined || session.expiresAt > Date.now() / 1000); } diff --git a/tests/e2e-ui/ui/vite.config.ts b/tests/e2e-ui/ui/vite.config.ts index 885b77610..2cc0e23bb 100644 --- a/tests/e2e-ui/ui/vite.config.ts +++ b/tests/e2e-ui/ui/vite.config.ts @@ -1,13 +1,9 @@ import { sveltekit } from '@sveltejs/kit/vite'; -import { - distributedGraphqlProxy, - distributedSvelteKit -} from '@hops-ops/distributed/sveltekit/vite'; +import { distributedSvelteKit } from '@hops-ops/distributed/sveltekit/vite'; import { defineConfig } from 'vite'; import { distributedViteOptions } from './distributed.config.js'; -const api = process.env.E2E_API_ORIGIN || process.env.E2E_BASE_URL || 'http://127.0.0.1:8791'; const uiPort = Number(process.env.UI_PORT || '5180'); if (!Number.isSafeInteger(uiPort) || uiPort < 1 || uiPort > 65_535) { throw new TypeError('UI_PORT must be an integer from 1 through 65535'); @@ -25,9 +21,9 @@ export default defineConfig({ port: uiPort, // hops local cluster-DNS mode uses svc.ns.svc.cluster.local Host headers. host: true, - allowedHosts: true, - // GraphQL-only public API (commands are mutations, not POST /todo.*). - proxy: distributedGraphqlProxy(api) + allowedHosts: true + // Public UI/API traffic enters the backend gateway. This internal UI + // server has no reverse API proxy, so it cannot loop back into ingress. }, optimizeDeps: { exclude: ['$lib/blob/pkg/blob_wasm.js'] diff --git a/tests/gateway-auth/provider.mjs b/tests/gateway-auth/provider.mjs index 102b99847..0499fd77f 100644 --- a/tests/gateway-auth/provider.mjs +++ b/tests/gateway-auth/provider.mjs @@ -4,7 +4,7 @@ import { once } from 'node:events'; import { randomBytes } from 'node:crypto'; // An isolated, in-memory standards implementation. No external IdP or secrets. -export async function startProvider(issuer, publicOrigin) { +export async function startProvider(issuer, publicOrigin, { jwtAudience } = {}) { let refreshes = 0; let failRefresh = false; const provider = new Provider(issuer, { @@ -13,12 +13,21 @@ export async function startProvider(issuer, publicOrigin) { response_types: ['code'], grant_types: ['authorization_code', 'refresh_token'], token_endpoint_auth_method: 'client_secret_basic' }], cookies: { keys: [randomBytes(32).toString('hex')] }, - features: { devInteractions: { enabled: false } }, + features: { devInteractions: { enabled: false }, ...(jwtAudience ? { + resourceIndicators: { + enabled:true, defaultResource:()=>publicOrigin, useGrantedResource:()=>true, + getResourceServerInfo:()=>({scope:'openid profile email offline_access',audience:jwtAudience,accessTokenFormat:'jwt',jwt:{sign:{alg:'RS256'}}}), + }, + } : {}) }, + ...(jwtAudience ? { + extraTokenClaims:()=>({roles:['user']}), + scopes:['openid','profile','email','offline_access','urn:zitadel:iam:org:project:roles','urn:zitadel:iam:org:projects:roles',`urn:zitadel:iam:org:project:id:${jwtAudience}:aud`,`urn:zitadel:iam:org:project:id:${jwtAudience}:roles`], + } : {}), ttl: { AccessToken: 61 }, async issueRefreshToken() { return true; }, - claims: { openid: ['sub'], profile: ['name'], email: ['email'] }, + claims: { openid: ['sub'], profile: ['name', ...(jwtAudience?['roles']:[])], email: ['email'] }, async findAccount(_ctx, id) { - return { accountId: id, async claims() { return { sub: id, name: 'Alice', email: 'alice@example.invalid' }; } }; + return { accountId: id, async claims() { return { sub: id, name: 'Alice', email: 'alice@example.invalid',...(jwtAudience?{roles:['user']}:{}) }; } }; }, interactions: { url(_ctx, interaction) { return `/interaction/${interaction.uid}`; } }, }); @@ -39,7 +48,8 @@ export async function startProvider(issuer, publicOrigin) { res.end('
'); return; } const grant = details.grantId ? await provider.Grant.find(details.grantId) : new provider.Grant({ accountId: 'alice', clientId: details.params.client_id }); - grant.addOIDCScope('openid profile email offline_access'); + grant.addOIDCScope(jwtAudience?details.params.scope:'openid profile email offline_access'); + if(jwtAudience)grant.addResourceScope(publicOrigin,'openid profile email offline_access'); const grantId = await grant.save(); await provider.interactionFinished(req, res, { login: { accountId: 'alice' }, consent: { grantId } }, { mergeWithLastSubmission: true }); return; diff --git a/tests/gateway-portable/Cargo.toml b/tests/gateway-portable/Cargo.toml index 80a1340c1..af7f2ae9d 100644 --- a/tests/gateway-portable/Cargo.toml +++ b/tests/gateway-portable/Cargo.toml @@ -37,3 +37,7 @@ path = "../gateway_graphql_operation.rs" [[test]] name = "edge_query_delivery" path = "../edge_query_delivery.rs" + +[[test]] +name = "gateway_mounts" +path = "../gateway_mounts.rs" diff --git a/tests/gateway_mounts.rs b/tests/gateway_mounts.rs new file mode 100644 index 000000000..c114747f5 --- /dev/null +++ b/tests/gateway_mounts.rs @@ -0,0 +1,97 @@ +#![cfg(feature = "gateway")] +use distributed::application::{ + compile_deployment_plan, Application, MountSelector, ProcessIntent, Runtime, +}; +use distributed::gateway::*; +use std::cell::Cell; + +fn ui(origin: &str) -> Gateway { + GatewayConfig { + bindings: vec![Binding::new( + "ui", + BindingKind::UiProxy { + origin: origin.into(), + }, + )], + routes: vec![Route::new("ui", RoutePath::prefix("/"), "ui")], + } + .build() + .unwrap() +} +#[test] +fn selected_capabilities_only() { + let gateway = ui("http://ui.internal:3000"); + let app = Application::new("site") + .build() + .unwrap() + .with_gateway("public", &gateway) + .unwrap(); + let selected = MountSelector::gateway("public").unwrap(); + let unused = MountSelector::gateway("unused").unwrap(); + let runtime = Runtime::default() + .mount_gateway(&app, selected.clone(), gateway) + .unwrap(); + let allocated = Cell::new(0); + let construct = |_: &Gateway| { + allocated.set(allocated.get() + 1); + Ok::<_, ()>("adapter") + }; + assert_eq!(runtime.bind_gateway(&unused, construct), Ok(None)); + assert_eq!(allocated.get(), 0); + assert_eq!( + runtime.bind_gateway(&selected, construct), + Ok(Some("adapter")) + ); + assert_eq!(allocated.get(), 1); + assert!(runtime.starts_gateway()); + assert!(!runtime.starts_graphql()); + assert!(!runtime.starts_outbox()); + assert!(!runtime.starts_projector_consumer()); + let plan = compile_deployment_plan( + "edge", + app.manifest(), + [ProcessIntent::new("ingress").unwrap().mounts([selected])], + ) + .unwrap(); + assert!(plan.processes[0] + .mounts + .iter() + .all(|mount| matches!(mount, MountSelector::Extension { .. }))); + assert!(!plan.processes[0].capabilities.iter().any(|requirement| { + let name = requirement.capability.as_str(); + name.contains("store") || name.contains("project") || name.contains("dispatch") + })); +} +#[test] +fn physical_binding_changes_do_not_rewrite_application_identity() { + let a = Application::new("site") + .build() + .unwrap() + .with_gateway("public", &ui("http://a.internal:3000")) + .unwrap(); + let b = Application::new("site") + .build() + .unwrap() + .with_gateway("public", &ui("http://b.internal:4000")) + .unwrap(); + assert_eq!(a.canonical_bytes().unwrap(), b.canonical_bytes().unwrap()); + assert!(!String::from_utf8(a.canonical_bytes().unwrap()) + .unwrap() + .contains("internal")); + assert!(Runtime::default() + .mount_gateway( + &a, + MountSelector::command("public").unwrap(), + ui("http://a.internal:3000") + ) + .is_err()); + let other = GatewayConfig { + bindings: vec![Binding::new("ui", BindingKind::Handler)], + routes: vec![Route::new("ui", RoutePath::prefix("/"), "ui")], + } + .build() + .unwrap(); + assert!(Runtime::default() + .mount_gateway(&a, MountSelector::gateway("public").unwrap(), other) + .is_err()); +} From 8d32ca190c775dfd1649404c419f13289123682a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:24:09 -0500 Subject: [PATCH 059/484] test: update gateway migration inventory and isolate PostgreSQL fixture Corrects integrated CI evidence for tasks/application-gateway-7; dedicated runner still executes the real PostgreSQL proof. --- distributed_cli/src/contracts/tests.rs | 2 +- src/graphql/delivery/versions.rs | 1 + src/sqlx_repo/repo/backend.rs | 18 ++++++++++++++---- tests/gateway-postgres/run.py | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index d86419575..11b4bb372 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/src/graphql/delivery/versions.rs b/src/graphql/delivery/versions.rs index b101937b1..e4b4795ac 100644 --- a/src/graphql/delivery/versions.rs +++ b/src/graphql/delivery/versions.rs @@ -482,6 +482,7 @@ mod tests { } #[cfg(feature = "postgres")] #[tokio::test] + #[ignore = "requires owned gateway-postgres primary; run tests/gateway-postgres/run.py"] async fn postgres_transactional_coverage_and_snapshot_race() { let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(3) diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index fed68f969..79f9f1136 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -47,7 +47,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); assert_eq!( descriptions, vec![ @@ -55,7 +55,8 @@ mod tests { "command ledger", "projection protocol", "command ledger atomic state", - "projection source snapshots" + "projection source snapshots", + "gateway dependency versions" ] ); assert_eq!( @@ -81,6 +82,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0005_projection_source_snapshots.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0006_gateway_dependency_versions.sql" + )), ] ); } @@ -100,7 +105,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); assert_eq!( descriptions, vec![ @@ -108,7 +113,8 @@ mod tests { "command ledger", "projection protocol", "command ledger atomic state", - "projection source snapshots" + "projection source snapshots", + "gateway dependency versions" ] ); assert_eq!( @@ -134,6 +140,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0005_projection_source_snapshots.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0006_gateway_dependency_versions.sql" + )), ] ); } diff --git a/tests/gateway-postgres/run.py b/tests/gateway-postgres/run.py index 7a025a73e..6e9a3fbe7 100644 --- a/tests/gateway-postgres/run.py +++ b/tests/gateway-postgres/run.py @@ -65,7 +65,7 @@ class Server(socketserver.ThreadingTCPServer): print("Fixture PostgreSQL " + docker("exec", primary, "postgres", "--version"), flush=True) env = {**os.environ, "GATEWAY_TEST_PRIMARY_URL": url(primary), "GATEWAY_TEST_REPLICA_URL": url(standby), "GATEWAY_TEST_PRIMARY_CONTAINER": primary} subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--nocapture"], cwd=ROOT, env=env, check=True) - subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--lib", "graphql::delivery::versions::tests", "--", "--nocapture"], cwd=ROOT, env=env, check=True) + subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--lib", "graphql::delivery::versions::tests::postgres_transactional_coverage_and_snapshot_race", "--", "--ignored", "--nocapture"], cwd=ROOT, env=env, check=True) subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "postgres_repository", "projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks", "--", "--nocapture"], cwd=ROOT, env={**env, "DATABASE_URL": env["GATEWAY_TEST_PRIMARY_URL"]}, check=True) finally: for bridge in bridges: From e55be3b2e8e091bfcfa442e935df7c47af20a965 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:24:46 -0500 Subject: [PATCH 060/484] feat: measure bounded gateway delivery work and traffic Implements tasks/application-gateway-12 with real native/workerd 100-query and 100-live comparisons, isolation and recovery costs. --- .github/workflows/integration-gateway.yaml | 7 + docs/gateway/metrics.md | 45 +++++ src/gateway/delivery/metrics.rs | 20 ++ src/gateway/delivery/mod.rs | 3 + src/gateway/delivery/snapshot.rs | 14 ++ src/gateway/native/delivery.rs | 16 +- src/gateway/native/graphql.rs | 4 + src/gateway/worker/coordinator.rs | 14 +- src/gateway/worker/mod.rs | 4 +- tests/edge_query_delivery.rs | 12 ++ tests/gateway-worker/load-runtime.mjs | 159 ++++++++++++++++ tests/gateway-worker/src/lib.rs | 12 +- tests/graphql_query_protocol/load.rs | 212 +++++++++++++++++++++ tests/graphql_query_protocol/main.rs | 3 + 14 files changed, 518 insertions(+), 7 deletions(-) create mode 100644 docs/gateway/metrics.md create mode 100644 src/gateway/delivery/metrics.rs create mode 100644 tests/gateway-worker/load-runtime.mjs create mode 100644 tests/graphql_query_protocol/load.rs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 843f72d25..58ee75f6a 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -176,6 +176,13 @@ jobs: run: | node tests/gateway-worker/proxy-runtime.mjs node tests/gateway-worker/run.mjs + - name: Measure actual native and workerd origin/client savings + run: cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol separate_origin_and_client_savings -- --ignored --nocapture + - uses: actions/upload-artifact@v4 + if: always() + with: + name: gateway-delivery-load + path: tests/gateway-worker/artifacts/load-report.json - name: Prove actual DO coordination, SQL reduction, restart and cancellation run: cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol worker_ -- --ignored --nocapture --test-threads=1 diff --git a/docs/gateway/metrics.md b/docs/gateway/metrics.md new file mode 100644 index 000000000..6fac87025 --- /dev/null +++ b/docs/gateway/metrics.md @@ -0,0 +1,45 @@ +# Delivery measurements + +`GatewayVersionStore::metrics()` counts actual compiled result SQL separately +from authenticated origin validation requests. `NativeDelivery::metrics()` and +`WorkerCoordinator::metrics()` expose optional `SnapshotMetrics` plus query +admission bypass counts. Cache decisions include hits, misses, resident stale +rejections, fill bypasses and explicit invalidations. These are cumulative, +identifier-free observations within a coordinator lifetime. Live counts expose +active groups/consumers, upstream source attempts, resets, received frames, +duplicates and handoffs; query counts expose active flights/consumers. Export +these through application-owned telemetry, with deployment/host/mode labels only. +No subject, token, document, variables or scope hashes are metric labels. + +Run the actual load fixture after installing `tests/gateway-worker` and +worker-build as described in [worker.md](worker.md): + +```sh +cargo test --no-default-features --features gateway-graphql-native,gateway-delivery,sqlite --test graphql_query_protocol separate_origin_and_client_savings -- --ignored --nocapture +``` + +`tests/gateway-worker/artifacts/load-report.json` records the source revision and +whether it was dirty, runtime/platform, repetitions, payload size and resource +limits. Native and workerd each run disabled, coalescing-only, snapshot-only and +live-only modes. A barrier holds actual SQL until100 coalesced consumers join. +Snapshots report warmup separately before100 hits. Every mode holds100 live +consumers during a real projection commit; result SQL, origin validation, steady +producers and all ongoing/temporary origin WebSocket connections are measured. +Different-subject controls prove private isolation. External writes, explicit +cache invalidation, cursor-gap resets and a slow Worker consumer expose recovery +costs. Native bounded-queue behavior is additionally covered by native live tests. + +The metering proxy counts actual HTTP request/response bodies and WebSocket +application frames, including origin authentication/validation control traffic. +Browser/client response bytes are counted independently. Header, TLS and frame +encoding overhead are explicitly excluded. No per-browser byte savings are +inferred from producer savings. Latency distributions and full fanout completion +are reported without universal thresholds. The deterministic correctness gates +are SQL/producer counts, causal data equality, isolation and teardown. + +With only live sharing selected, ordinary HTTP queries do not incur query +validation. The Worker modern WebSocket adapter may perform temporary origin +authentication handshakes even when query-only delivery is selected; those +connections and bytes are included, not hidden as steady-state producers. +Outgoing live sockets do not hibernate. Disable metric export independently of +resource bounds/correctness; coordinator restart starts a new counter series. diff --git a/src/gateway/delivery/metrics.rs b/src/gateway/delivery/metrics.rs new file mode 100644 index 000000000..6faf15a53 --- /dev/null +++ b/src/gateway/delivery/metrics.rs @@ -0,0 +1,20 @@ +//! Bounded, identifier-free coordinator observations. Exporters choose their own +//! transport; these counters never retain subjects, documents or variables. +use serde::Serialize; + +/// Cumulative cache decisions within one coordinator lifetime. Saturating +/// counters are monotonic; restarting a coordinator starts a new series. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SnapshotMetrics { + /// A freshly origin-admitted consumer reused a complete envelope. + pub hits: u64, + /// Admitted lookups with no reusable complete envelope. + pub misses: u64, + /// Resident/filling envelopes rejected by current version, proof or generation. + pub stale_rejections: u64, + /// Fills bypassed storage, including oversized or unshareable responses. + pub fill_bypasses: u64, + /// Explicit lost-feed/rebuild invalidations, not individual SQL writes. + pub invalidations: u64, +} diff --git a/src/gateway/delivery/mod.rs b/src/gateway/delivery/mod.rs index 3aad997e3..13f57b240 100644 --- a/src/gateway/delivery/mod.rs +++ b/src/gateway/delivery/mod.rs @@ -37,3 +37,6 @@ pub use coordinator::*; mod live; pub use live::*; + +mod metrics; +pub use metrics::*; diff --git a/src/gateway/delivery/snapshot.rs b/src/gateway/delivery/snapshot.rs index 7b645a52c..3faac1360 100644 --- a/src/gateway/delivery/snapshot.rs +++ b/src/gateway/delivery/snapshot.rs @@ -248,6 +248,7 @@ pub struct FillTicket { /// Portable bounded snapshot store. Runtime adapters provide current origin /// admission for every consumer and coordinate calls; this owns no task/socket. pub struct SnapshotCache { + metrics: super::SnapshotMetrics, limits: SnapshotLimits, entries: BTreeMap, bytes: usize, @@ -267,6 +268,7 @@ impl SnapshotCache { return Err(DeliveryError::InvalidContext); } Ok(Self { + metrics: super::SnapshotMetrics::default(), limits, entries: BTreeMap::new(), bytes: 0, @@ -299,6 +301,7 @@ impl SnapshotCache { freshness.bind(&admission.identity)?; } let Some(entry) = self.entries.get_mut(&admission.key) else { + self.metrics.misses = self.metrics.misses.saturating_add(1); return Ok(None); }; let current = entry.admission.validator == admission.validator; @@ -317,8 +320,11 @@ impl SnapshotCache { || entry.admission.identity != admission.identity || !entry.response.satisfies(admission, freshness) { + self.metrics.misses = self.metrics.misses.saturating_add(1); + self.metrics.stale_rejections = self.metrics.stale_rejections.saturating_add(1); return Ok(None); } + self.metrics.hits = self.metrics.hits.saturating_add(1); self.sequence = self.sequence.saturating_add(1); entry.sequence = self.sequence; Ok(Some(entry.response.clone())) @@ -340,6 +346,7 @@ impl SnapshotCache { .map(|(a, b)| a.len() + b.len()) .sum::(); if bytes > self.limits.entry_bytes { + self.metrics.fill_bypasses = self.metrics.fill_bypasses.saturating_add(1); return Ok(false); } if self.generation == u64::MAX @@ -347,11 +354,13 @@ impl SnapshotCache { || ticket.key != admission.key || !response.satisfies(&admission, None) { + self.metrics.fill_bypasses = self.metrics.fill_bypasses.saturating_add(1); return Ok(false); } let value: serde_json::Value = serde_json::from_slice(&response.body).map_err(|_| DeliveryError::Ineligible)?; if value["extensions"]["gatewayDelivery"]["validator"] != admission.validator { + self.metrics.fill_bypasses = self.metrics.fill_bypasses.saturating_add(1); return Ok(false); } if let Some(previous) = self.entries.remove(&ticket.key) { @@ -383,12 +392,17 @@ impl SnapshotCache { } /// Lost feed, rebuild or coordinator reset discards data and fences fills. pub fn invalidate_all(&mut self) { + self.metrics.invalidations = self.metrics.invalidations.saturating_add(1); self.entries.clear(); self.bytes = 0; // Saturation cannot permit an old ticket to become current: at the // terminal counter value installation is permanently disabled. self.generation = self.generation.saturating_add(1); } + /// Snapshot decisions without any identity-bearing labels. + pub fn metrics(&self) -> super::SnapshotMetrics { + self.metrics + } /// Current resident entry count for diagnostics and boundedness checks. pub fn len(&self) -> usize { self.entries.len() diff --git a/src/gateway/native/delivery.rs b/src/gateway/native/delivery.rs index 33aaf129e..ef7c9f5e1 100644 --- a/src/gateway/native/delivery.rs +++ b/src/gateway/native/delivery.rs @@ -25,6 +25,7 @@ pub struct NativeDeliveryOptions { /// Bounded native delivery. Each consumer authenticates at the origin before /// lookup/join; snapshot storage and shared query execution are independent. pub struct NativeDelivery { + bypasses: std::sync::atomic::AtomicU64, snapshots: Option>, flights: Option>, pub(super) live: Option>, @@ -53,6 +54,7 @@ impl NativeDelivery { .or(options.snapshots.map(|limits| limits.entry_bytes)) .unwrap_or(1024 * 1024); Ok(Self { + bypasses: std::sync::atomic::AtomicU64::new(0), snapshots: options .snapshots .map(SnapshotCache::new) @@ -67,6 +69,16 @@ impl NativeDelivery { entry_bytes, }) } + /// Cache decisions and origin-ineligible query bypasses. Labels contain no + /// request identity. None indicates snapshot storage was not selected. + pub fn metrics(&self) -> (Option, u64) { + ( + self.snapshots + .as_ref() + .and_then(|cache| cache.lock().ok().map(|cache| cache.metrics())), + self.bypasses.load(std::sync::atomic::Ordering::Relaxed), + ) + } /// Allocate a bounded origin-validated snapshot cache. pub fn snapshots(limits: SnapshotLimits) -> Result { Self::new(NativeDeliveryOptions { @@ -139,6 +151,8 @@ impl NativeDelivery { let admission = match validate(binding, inner, executor, &context, &parts, &value).await { AdmissionResult::Eligible(admission) => admission, AdmissionResult::Bypass => { + self.bypasses + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); return binding .execute_http( inner, @@ -147,7 +161,7 @@ impl NativeDelivery { request(&parts, value), Some(permit), ) - .await + .await; } AdmissionResult::Error(error) => return error, }; diff --git a/src/gateway/native/graphql.rs b/src/gateway/native/graphql.rs index 743a9793a..8eea1aba2 100644 --- a/src/gateway/native/graphql.rs +++ b/src/gateway/native/graphql.rs @@ -350,6 +350,10 @@ impl GraphqlBinding { if let Some(coordinator) = parts .extensions .get::>() + .filter(|delivery| { + let caps = delivery.capabilities(); + caps.snapshots || caps.coalescing + }) .cloned() { if super::super::graphql::operation_kind( diff --git a/src/gateway/worker/coordinator.rs b/src/gateway/worker/coordinator.rs index 539207bbc..4b3979328 100644 --- a/src/gateway/worker/coordinator.rs +++ b/src/gateway/worker/coordinator.rs @@ -112,6 +112,7 @@ impl WorkerDeliveryBinding { /// A restart starts empty; every reuse still requires current origin validation. /// Do not keep this in ordinary ingress isolate memory. pub struct WorkerCoordinator { + bypasses: std::cell::Cell, options: WorkerDeliveryOptions, cache: Option>, flights: Option>, @@ -122,6 +123,7 @@ impl WorkerCoordinator { pub fn new(options: WorkerDeliveryOptions) -> std::result::Result, GatewayError> { options.validate()?; Ok(Rc::new(Self { + bypasses: std::cell::Cell::new(0), options, live: options .live @@ -145,6 +147,13 @@ impl WorkerCoordinator { flights: options.coalescing.map(Flights::new).transpose()?, })) } + /// Identifier-free cache decisions and origin-ineligible query bypasses. + pub fn metrics(&self) -> (Option, u64) { + ( + self.cache.as_ref().map(|cache| cache.borrow().metrics()), + self.bypasses.get(), + ) + } /// Forget cached data and fence in-progress fills after reset/lost feed. pub fn invalidate_all(&self) { if let Some(cache) = &self.cache { @@ -377,7 +386,10 @@ impl WorkerCoordinator { .map_err(|_| worker::Error::RustError("invalid freshness".into()))?; let admission = match origin.validate(&value).await? { Admitted::Eligible(admission) => admission, - Admitted::Bypass => return origin.execute(value).await, + Admitted::Bypass => { + self.bypasses.set(self.bypasses.get().saturating_add(1)); + return origin.execute(value).await; + } Admitted::Error(response) => return Ok(response), }; let ticket = if let Some(cache) = &self.cache { diff --git a/src/gateway/worker/mod.rs b/src/gateway/worker/mod.rs index ea3f0d9eb..45627dcf2 100644 --- a/src/gateway/worker/mod.rs +++ b/src/gateway/worker/mod.rs @@ -388,7 +388,9 @@ impl WorkerGateway { if let Err(error) = super::graphql::admit_request(&value, *capabilities) { return Response::from_json(&error.envelope()); } - if let Some(delivery) = delivery { + if let Some(delivery) = delivery.as_ref().filter(|delivery| { + delivery.options.snapshots.is_some() || delivery.options.coalescing.is_some() + }) { if super::graphql::operation_kind( value["query"].as_str().unwrap_or(""), value["operationName"].as_str(), diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs index be8363903..697d3cd3a 100644 --- a/tests/edge_query_delivery.rs +++ b/tests/edge_query_delivery.rs @@ -192,6 +192,9 @@ fn private_validation_public_age_and_late_fill_fence() { ); let newer = admission("v2"); assert!(cache.lookup(&newer, None, 101).unwrap().is_none()); + assert_eq!(cache.metrics().hits, 1); + assert_eq!(cache.metrics().misses, 1); + assert_eq!(cache.metrics().stale_rejections, 1); let ticket = cache.begin_fill(&first, 100).unwrap(); assert!( !cache @@ -205,6 +208,15 @@ fn private_validation_public_age_and_late_fill_fence() { .install(late, first.clone(), body.clone(), 101) .unwrap()); assert!(cache.is_empty()); + assert_eq!(cache.metrics().invalidations, 1); + assert_eq!(cache.metrics().fill_bypasses, 2); + let labels = serde_json::to_value(cache.metrics()).unwrap(); + assert_eq!(labels.as_object().unwrap().len(), 5); + assert!(labels + .as_object() + .unwrap() + .values() + .all(serde_json::Value::is_u64)); let mut public = first.clone(); public.policy = SnapshotPolicy::Public { max_age_seconds: 10, diff --git a/tests/gateway-worker/load-runtime.mjs b/tests/gateway-worker/load-runtime.mjs new file mode 100644 index 000000000..02c2e3d80 --- /dev/null +++ b/tests/gateway-worker/load-runtime.mjs @@ -0,0 +1,159 @@ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import {once} from 'node:events'; +import {mkdir,writeFile} from 'node:fs/promises'; +import {execFileSync} from 'node:child_process'; +import WebSocket,{WebSocketServer} from 'ws'; +import {startRuntime,root} from './runtime.mjs'; + +const origin=process.env.GATEWAY_ORIGIN; +const tokens={alice:process.env.GATEWAY_TOKEN_ALICE,bob:process.env.GATEWAY_TOKEN_BOB}; +const native=JSON.parse(process.env.GATEWAY_NATIVE_MODES); +const meterOrigin=`http://127.0.0.1:${process.env.GATEWAY_METER_PORT}`; +// Count actual application bytes at the origin boundary, including control +// responses. HTTP/TLS framing and kernel/socket memory are not estimated here. +const wire={httpRequestBytes:0,httpResponseBytes:0,wsRequestBytes:0,wsResponseBytes:0,wsConnections:0}; +const meter=http.createServer((request,response)=>{ + const upstream=http.request(origin+request.url,{method:request.method,headers:{...request.headers,host:new URL(origin).host}},reply=>{ + response.writeHead(reply.statusCode,reply.headers); + reply.on('data',chunk=>wire.httpResponseBytes+=chunk.length);reply.pipe(response); + }); + upstream.on('error',()=>{response.writeHead(502);response.end();}); + request.on('data',chunk=>wire.httpRequestBytes+=chunk.length);request.pipe(upstream); + response.on('close',()=>{if(!response.writableFinished)upstream.destroy();}); +}); +const wss=new WebSocketServer({noServer:true}); +meter.on('upgrade',(request,socket,head)=>{ + const protocol=request.headers['sec-websocket-protocol']; + const upstream=new WebSocket((origin+request.url).replace('http:','ws:'),protocol,{headers:{origin:request.headers.origin??meterOrigin}}); + upstream.on('error',()=>socket.destroy()); + upstream.once('open',()=>wss.handleUpgrade(request,socket,head,downstream=>{ + wire.wsConnections++; + downstream.on('message',(data,binary)=>{wire.wsRequestBytes+=data.length;if(upstream.readyState===WebSocket.OPEN)upstream.send(data,{binary});}); + upstream.on('message',(data,binary)=>{wire.wsResponseBytes+=data.length;if(downstream.readyState===WebSocket.OPEN)downstream.send(data,{binary});}); + downstream.on('close',()=>upstream.close());upstream.on('close',()=>downstream.close()); + downstream.on('error',()=>upstream.close()); + })); +}); +meter.listen(Number(process.env.GATEWAY_METER_PORT),'127.0.0.1');await once(meter,'listening'); +const report={version:1,revision:execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim(),candidateChanges:execFileSync('git',['status','--porcelain'],{encoding:'utf8'}).trim().length>0,node:process.version,platform:process.platform,participants:100,repetitions:1,payloadCharacters:4096,measurement:'actual HTTP bodies and WebSocket application frames; excludes headers/TLS/framing',limits:{snapshotEntries:128,snapshotBytes:2097152,entryBytes:262144,flightGroups:8,consumers:128,flightBytes:262144,liveGroups:4,liveFrameBytes:65536},rows:[]}; +let position=2; +const snapshots=()=>({...wire}); +const difference=(after,before)=>Object.fromEntries(Object.keys(after).map(key=>[key,after[key]-before[key]])); +async function metrics(){return (await fetch(origin+'/__metrics')).json();} +async function until(predicate,label){for(let n=0;n<1000;n++){if(await predicate())return;await new Promise(resolve=>setTimeout(resolve,10));}throw Error(label+' timed out');} +const latency=values=>{const sorted=[...values].sort((a,b)=>a-b);return {min:sorted[0],p50:sorted[Math.floor(sorted.length/2)],p95:sorted[Math.floor(sorted.length*.95)],max:sorted.at(-1)};}; +async function advance(){position++;await fetch(origin+'/__next/'+position,{method:'POST'});return 'load-'+position+'-';} +async function modeRun(host,mode,runtime){ + console.log('START '+host+'/'+mode); + const url=runtime.publicOrigin; + const counts=async()=> (await fetch(url+'/__coordinators')).json(); + let downstreamBytes=0; + const query=async(subject='alice',document='query Load { causal_query_views { title } }')=>{ + const started=performance.now(); + const body=JSON.stringify({query:document,extensions:{gatewayDelivery:{action:'execute',connectionInit:{authorization:'Bearer '+tokens[subject]}}}}); + const response=await fetch(url+'/graphql',{method:'POST',headers:{'content-type':'application/json'},body}); + const text=await response.text();downstreamBytes+=Buffer.byteLength(text); + assert.equal(response.status,200,'query status');const value=JSON.parse(text);assert.equal(value.errors,undefined,'query errors'); + return {value,ms:performance.now()-started}; + }; + await advance(); + let warmup; + if(mode==='snapshots'){ + const before=await metrics(),bytes=snapshots();await query();warmup={origin:difference(await metrics(),before),wire:difference(snapshots(),bytes),clientBytes:downstreamBytes}; + } + const before=await metrics(),bytes=snapshots(),clientBefore=downstreamBytes; + if(mode==='flights')await fetch(origin+'/__block',{method:'POST'}); + const pending=Promise.all(Array.from({length:100},()=>query()));pending.catch(()=>{}); + if(mode==='flights'){ + await until(async()=> (await counts()).reduce((sum,row)=>sum+row.query[2],0)===100,'100 flight consumers'); + assert.equal((await metrics()).resultExecutions,before.resultExecutions,'barrier holds actual SQL'); + await fetch(origin+'/__release',{method:'POST'}); + } + const result=await pending; + for(const item of result)assert.deepEqual(item.value,result[0].value); + const queryWork=difference(await metrics(),before); + assert.equal(queryWork.resultExecutions,mode==='snapshots'?0:mode==='flights'?1:100); + assert.equal(queryWork.validations,mode==='snapshots'?100:mode==='flights'?101:0,'unselected query optimizations perform no validation work'); + const queryReport={origin:queryWork,wire:difference(snapshots(),bytes),clientResponseBytes:downstreamBytes-clientBefore,latencyMs:latency(result.map(item=>item.ms)),warmup}; + const alice=result[0].value.extensions.distributed.cacheScope; + const control=await query('bob');assert.notEqual(control.value.extensions.distributed.cacheScope,alice,'subjects stay separate'); + const title=await advance();assert.ok((await query()).value.data.causal_query_views[0].title.startsWith(title),'external projection invalidates cache'); + const decisions=await counts(); + if(mode==='snapshots'){ + assert.ok(decisions.reduce((sum,row)=>sum+(row.metrics[0]?.hits??0),0)>=100); + assert.ok(decisions.reduce((sum,row)=>sum+(row.metrics[0]?.staleRejections??0),0)>0); + } + // Unsupported protocol introspection follows the ordinary origin path and + // remains distinct from a reusable query hit. + const bypassBefore=decisions.reduce((sum,row)=>sum+row.metrics[1],0); + if(mode==='snapshots'||mode==='flights'){ + await query('alice','query Introspection { __typename }'); + assert.ok((await counts()).reduce((sum,row)=>sum+row.metrics[1],0)>bypassBefore); + } + await fetch(url+'/__coordinators',{method:'POST'}); + const liveBefore=await metrics(),liveBytes=snapshots();let receivedBytes=0; + const clients=[]; + async function connect(id,subject='alice',resume){ + const start=performance.now();const socket=new WebSocket(url.replace('http:','ws:')+'/graphql/ws','graphql-transport-ws'); + const frames=[];let initialized=false,closed=false;const errors=[];socket.on('close',()=>closed=true); + socket.on('message',data=>{ + receivedBytes+=data.length;const frame=JSON.parse(data); + if(frame.type==='connection_ack')initialized=true; + if(frame.type==='ping'&&id!=='slow')socket.send(JSON.stringify({type:'pong',payload:frame.payload})); + if(frame.type==='next'){assert.equal(frame.id,id);frames.push(frame.payload);} + if(frame.type==='error')errors.push(frame.payload); + }); + socket.on('error',()=>errors.push('socket failure'));clients.push(socket); + await once(socket,'open');socket.send(JSON.stringify({type:'connection_init',payload:{authorization:'Bearer '+tokens[subject]}})); + await until(()=>initialized||errors.length,'socket admission');assert.equal(errors.length,0); + socket.send(JSON.stringify({id,type:'subscribe',payload:{query:'subscription LoadLive { causal_query_views { title } }',...(resume?{extensions:{distributed:{resume:{cursors:resume}}}}:{})}})); + await until(()=>frames.length||errors.length,'live first frame');assert.equal(errors.length,0);assert.equal(frames[0].errors,undefined); + return {frames,errors,closed:()=>closed,ms:performance.now()-start,cancel:()=>socket.send(JSON.stringify({id,type:'complete'}))}; + } + try{ + const consumers=[]; + // Sequential admission makes steady-state producer count deterministic; + // all100 remain concurrently subscribed during the measured commit fanout. + for(let index=0;index<100;index++)consumers.push(await connect(String(index))); + const producerCount=(await metrics()).producers; + assert.equal(producerCount,mode==='live'?1:100); + const initial=consumers[0].frames[0];for(const consumer of consumers)assert.deepEqual(consumer.frames[0],initial); + const commitStart=performance.now(),title=await advance(); + await until(()=>consumers.every(consumer=>consumer.frames.some(frame=>frame.data?.causal_query_views?.[0]?.title.startsWith(title))),'100 commit deliveries'); + const fanoutMs=performance.now()-commitStart; + const liveReport={logicalSubscriptions:100,upstreamProducers:producerCount,origin:difference(await metrics(),liveBefore),wire:difference(snapshots(),liveBytes),clientFrameBytes:receivedBytes,initialLatencyMs:latency(consumers.map(consumer=>consumer.ms)),commitFanoutMs:fanoutMs}; + const bob=await connect('bob','bob');assert.notEqual(bob.frames[0].extensions.distributed.cacheScope,initial.extensions.distributed.cacheScope); + assert.equal((await metrics()).producers,producerCount+1);bob.cancel(); + await until(async()=>(await metrics()).producers===producerCount,'subject control teardown'); + for(const consumer of consumers)consumer.cancel(); + await until(async()=>(await metrics()).producers===0,'last subscriber teardown'); + const recoveryBefore=await metrics(),recoveryBytes=snapshots(),recoveryClientBytes=receivedBytes; + let recovery; + if(mode==='live'){ + for(let index=0;index<7;index++)await advance(); + const gap=await connect('gap','alice',initial.extensions.distributed.live.cursors); + assert.equal(gap.frames[0].extensions.distributed.live.reset,true,'old cursor gets an explicit origin reset'); + gap.cancel();await until(async()=>(await metrics()).producers===0,'gap teardown'); + if(host==='workerd'){ + const fast=await connect('fast'),slow=await connect('slow'); + for(let index=0;index<20;index++){ + const before=fast.frames.length;await advance();await until(()=>fast.frames.length>before,'healthy consumer receives update'); + } + await until(()=>slow.closed()||slow.errors.length,'slow consumer reset'); + assert.equal(slow.frames.length,1,'unacknowledged client has bounded network delivery'); + fast.cancel();await until(async()=>(await metrics()).producers===0,'slow scenario teardown'); + } + recovery={origin:difference(await metrics(),recoveryBefore),wire:difference(snapshots(),recoveryBytes),clientFrameBytes:receivedBytes-recoveryClientBytes,cursorResets:1,slowClientResets:host==='workerd'?1:0}; + } + report.rows.push({host,mode,recovery,query:queryReport,live:liveReport,decisions:await counts(),subjectControls:'query and live scope differ; separate producer',invalidation:'new projection returned; old cache envelope rejected'}); + console.log(`PASS ${host}/${mode}: 100 queries -> ${queryWork.resultExecutions} result SQL; 100 live -> ${producerCount} producers; measured origin and client bytes`); + }finally{for(const socket of clients)socket.terminate();} +} +try{ + for(const host of ['native','workerd'])for(const mode of ['none','flights','snapshots','live']){ + const runtime=host==='native'?{publicOrigin:native[mode],stop:async()=>{}}:await startRuntime({apiOrigin:meterOrigin,mode,artifact:'load-'+mode+'-workerd.log'}); + try{await modeRun(host,mode,runtime);}finally{await runtime.stop();} + } + await mkdir(root+'/artifacts',{recursive:true});await writeFile(root+'/artifacts/load-report.json',JSON.stringify(report,null,2)+'\n'); +}finally{for(const client of wss.clients)client.terminate();wss.close();meter.closeAllConnections();meter.close();} diff --git a/tests/gateway-worker/src/lib.rs b/tests/gateway-worker/src/lib.rs index 7b8389cca..ad5af9a2a 100644 --- a/tests/gateway-worker/src/lib.rs +++ b/tests/gateway-worker/src/lib.rs @@ -13,18 +13,18 @@ fn delivery_options(env: &Env) -> WorkerDeliveryOptions { return WorkerDeliveryOptions::default(); } WorkerDeliveryOptions { - snapshots: (mode != "flights").then_some(SnapshotLimits { + snapshots: (mode == "all" || mode == "snapshots").then_some(SnapshotLimits { entries: 128, bytes: 2 * 1024 * 1024, entry_bytes: 256 * 1024, }), - coalescing: Some(FlightLimits { + coalescing: (mode == "all" || mode == "flights").then_some(FlightLimits { groups: 8, consumers: 128, response_bytes: 256 * 1024, ..Default::default() }), - live: (mode != "flights").then(|| LiveLimits { + live: (mode == "all" || mode == "live").then(|| LiveLimits { groups: 4, consumers: 128, frame_bytes: 64 * 1024, @@ -139,7 +139,7 @@ impl DurableObject for DeliveryCoordinator { match request.path().as_str() { "/__metrics" => { return Response::from_json( - &serde_json::json!({"query":self.coordinator.counts(),"live":self.coordinator.live_counts()}), + &serde_json::json!({"query":self.coordinator.counts(),"live":self.coordinator.live_counts(),"metrics":self.coordinator.metrics()}), ) } "/__reset" => { @@ -156,6 +156,10 @@ impl DurableObject for DeliveryCoordinator { #[event(fetch)] async fn fetch(request: Request, env: Env, _ctx: Context) -> Result { if request.path() == "/__coordinators" { + let options = delivery_options(&env); + if options.snapshots.is_none() && options.coalescing.is_none() && options.live.is_none() { + return Response::from_json(&Vec::::new()); + } let reset = request.method() == ::worker::Method::Post; let mut counts = Vec::new(); for shard in 0..4 { diff --git a/tests/graphql_query_protocol/load.rs b/tests/graphql_query_protocol/load.rs new file mode 100644 index 000000000..721c5e186 --- /dev/null +++ b/tests/graphql_query_protocol/load.rs @@ -0,0 +1,212 @@ +use super::*; + +#[tokio::test] +#[ignore = "runs actual 100-query/100-live native and workerd load matrix; requires pinned Worker fixture"] +async fn separate_origin_and_client_savings() { + use axum::Router; + use distributed::graphql::{delivery::GatewayVersionStore, IdentityConfig, OidcConfig}; + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + use rsa::{pkcs1::EncodeRsaPrivateKey, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey}; + let private = RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap(); + let public = RsaPublicKey::from(&private); + let encoding = EncodingKey::from_rsa_pem( + private + .to_pkcs1_pem(rsa::pkcs8::LineEnding::LF) + .unwrap() + .as_bytes(), + ) + .unwrap(); + let jwks=json!({"keys":[{"kty":"RSA","kid":"live-test","alg":"RS256","use":"sig", + "n":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.n().to_bytes_be()),"e":base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public.e().to_bytes_be())}]}).to_string(); + let token = |subject: &str| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some("live-test".into()); + encode(&header,&json!({"iss":"https://live-fixture.invalid","aud":"live-fixture","sub":subject,"iat":now-1,"nbf":now-1,"exp":now+3600,"roles":["user"]}),&encoding).unwrap() + }; + + let fixture = protocol_fixture_with_retention(5).await; + let versions = GatewayVersionStore::install( + &distributed::graphql::GraphqlPool::from(fixture.repository.pool().clone()), + "load-fixture", + ["causal_query_views".into()], + ) + .await + .unwrap(); + let oidc = OidcConfig::new("https://live-fixture.invalid", "live-fixture") + .with_static_jwks(jwks) + .engine_roles(&["user"]); + let engine = Arc::new( + GraphqlEngine::builder(&fixture.repository) + .service_id(SERVICE_ID) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .roles(&["user"]) + .identity(IdentityConfig::oidc_bearer(oidc)) + .model::(ModelPermissions::new().grant("user", read().all_columns())) + .client_projectors([projector()]) + .change_stream(fixture.repository.read_model_changes()) + .gateway_versions(versions.clone()) + .build() + .unwrap(), + ); + + use axum::{ + body::Body, + extract::Request as HttpRequest, + middleware::{self, Next}, + routing::{get, post}, + }; + use distributed::gateway::{delivery::*, native::*, *}; + use std::collections::BTreeMap; + let gate = Arc::new(tokio::sync::Semaphore::new(10000)); + let gate_layer = gate.clone(); + let gql = distributed::graphql::graphql_router_composed(engine.clone(), None, None).layer( + middleware::from_fn(move |request: HttpRequest, next: Next| { + let gate = gate_layer.clone(); + async move { + if request.method() != axum::http::Method::POST { + return next.run(request).await; + } + let (parts, body) = request.into_parts(); + let bytes = axum::body::to_bytes(body, 1024 * 1024).await.unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + if value["extensions"]["gatewayDelivery"]["action"] != "validate" { + gate.acquire().await.unwrap().forget(); + } + next.run(HttpRequest::from_parts(parts, Body::from(bytes))) + .await + } + }), + ); + let observed = engine.clone(); + let counters = versions.clone(); + let release = gate.clone(); + let repository = fixture.repository.clone(); + let bus = fixture.bus.clone(); + let control = Router::new() + .route("/__metrics", get(move || {let engine=observed.clone();let versions=counters.clone();async move {let m=versions.metrics();axum::Json(json!({"producers":engine.live_subscriber_count(),"validations":m.validations,"resultExecutions":m.result_executions}))}})) + .route("/__block", post(move || {let gate=gate.clone();async move {gate.forget_permits(gate.available_permits());"blocked"}})) + .route("/__release", post(move || {let gate=release.clone();async move {gate.add_permits(10000);"released"}})) + .route("/__next/{position}",post(move |axum::extract::Path(position):axum::extract::Path| {let repository=repository.clone();let bus=bus.clone();async move {project_item(&repository,&bus,position,&format!("load-{position}-{}","x".repeat(4096))).await;"committed"}})); + struct Server { + origin: String, + task: tokio::task::JoinHandle<()>, + } + impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } + } + async fn serve(router: Router) -> Server { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + Server { + origin, + task: tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }), + } + } + let origin = serve(gql.merge(control)).await; + // Reserve an ephemeral metering proxy port for the owned Node runner. + let meter = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let meter_port = meter.local_addr().unwrap().port(); + drop(meter); + let mut servers = Vec::new(); + let mut native = BTreeMap::new(); + for mode in ["none", "flights", "snapshots", "live"] { + let caps = GraphqlCapabilities { + queries: true, + commands: true, + live: true, + }; + let delivery = if mode == "none" { + None + } else { + Some(Arc::new( + NativeDelivery::new(NativeDeliveryOptions { + snapshots: (mode == "snapshots").then_some(SnapshotLimits { + entries: 128, + bytes: 2 * 1024 * 1024, + entry_bytes: 256 * 1024, + }), + coalescing: (mode == "flights").then_some(FlightLimits { + groups: 8, + consumers: 128, + response_bytes: 256 * 1024, + ..Default::default() + }), + live: (mode == "live").then_some(LiveLimits { + groups: 4, + consumers: 128, + frame_bytes: 64 * 1024, + ..Default::default() + }), + }) + .unwrap(), + )) + }; + let selected = DeliveryCapabilities { + snapshots: mode == "snapshots", + coalescing: mode == "flights", + live_sharing: mode == "live", + }; + let config = GatewayConfig { + bindings: vec![Binding::new( + "api", + BindingKind::Graphql { + executor: GraphqlExecutor::Remote { + origin: format!("http://127.0.0.1:{meter_port}"), + }, + capabilities: caps, + delivery: selected, + schema_extensions: vec![], + }, + )], + routes: vec![Route::new("api", RoutePath::prefix("/graphql"), "api")], + } + .build() + .unwrap(); + let binding = GraphqlBinding::Remote(RemoteGraphql::default()); + let resource = delivery.clone().map_or_else( + || NativeBinding::Graphql(binding.clone()), + |d| NativeBinding::GraphqlWithDelivery(binding.clone(), d), + ); + let gateway = NativeGateway::new( + config, + NativeOptions::new("http://load-gateway.invalid"), + [("api".into(), resource)], + NativeAuth::anonymous(), + ) + .unwrap(); + let counts = delivery.clone(); + let reset = delivery; + let router=gateway.router().route("/__coordinators",get(move || {let delivery=counts.clone();async move {axum::Json(delivery.map_or_else(||json!([]),|d|json!([{ "query":[0,d.flight_counts().0,d.flight_counts().1],"live":d.live_counts(),"metrics":d.metrics()}])))}}).post(move || {let delivery=reset.clone();async move {if let Some(d)=delivery{d.invalidate_all();}"reset"}})); + let server = serve(router).await; + native.insert(mode, server.origin.clone()); + servers.push(server); + } + let result = tokio::process::Command::new("node") + .arg("tests/gateway-worker/load-runtime.mjs") + .env("GATEWAY_ORIGIN", &origin.origin) + .env("GATEWAY_METER_PORT", meter_port.to_string()) + .env( + "GATEWAY_NATIVE_MODES", + serde_json::to_string(&native).unwrap(), + ) + .env("GATEWAY_TOKEN_ALICE", token("alice")) + .env("GATEWAY_TOKEN_BOB", token("bob")) + .stdout(std::process::Stdio::inherit()) + .stderr(std::process::Stdio::inherit()) + .kill_on_drop(true) + .output() + .await + .unwrap(); + println!("{}", String::from_utf8_lossy(&result.stdout)); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); +} diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 4a9b62d64..325e4a294 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -2573,3 +2573,6 @@ async fn worker_live_coordinator_uses_actual_oidc_origin() { String::from_utf8_lossy(&result.stderr) ); } + +#[cfg(all(feature = "gateway-delivery", feature = "gateway-graphql-native"))] +mod load; From 88505b1780b363778f80d2775f425899e7c9cb75 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:26:23 -0500 Subject: [PATCH 061/484] docs: record measured native and workerd delivery results Evidence for tasks/application-gateway-12 at clean eaa2d5d2; actual body/frame bytes and measured latency. --- docs/gateway/load-report.json | 839 ++++++++++++++++++++++++++++++++++ 1 file changed, 839 insertions(+) create mode 100644 docs/gateway/load-report.json diff --git a/docs/gateway/load-report.json b/docs/gateway/load-report.json new file mode 100644 index 000000000..57c9c38c0 --- /dev/null +++ b/docs/gateway/load-report.json @@ -0,0 +1,839 @@ +{ + "version": 1, + "revision": "eaa2d5d2bc6b104b89d6ccee12fd4fca11791a3e", + "candidateChanges": false, + "node": "v24.20.0", + "platform": "darwin", + "participants": 100, + "repetitions": 1, + "payloadCharacters": 4096, + "measurement": "actual HTTP bodies and WebSocket application frames; excludes headers/TLS/framing", + "limits": { + "snapshotEntries": 128, + "snapshotBytes": 2097152, + "entryBytes": 262144, + "flightGroups": 8, + "consumers": 128, + "flightBytes": 262144, + "liveGroups": 4, + "liveFrameBytes": 65536 + }, + "rows": [ + { + "host": "native", + "mode": "none", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519200, + "latencyMs": { + "min": 147.129375, + "p50": 198.30575000000002, + "p95": 250.39304199999998, + "max": 257.099875 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104080, + "wsConnections": 100 + }, + "clientFrameBytes": 1104080, + "initialLatencyMs": { + "min": 21.134625000000142, + "p50": 23.260374999999954, + "p95": 24.767499999999927, + "max": 26.905917000000045 + }, + "commitFanoutMs": 299.9157919999998 + }, + "decisions": [], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "flights", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 101 + }, + "wire": { + "httpRequestBytes": 76194, + "httpResponseBytes": 90330, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 528800, + "latencyMs": { + "min": 339.3542910000001, + "p50": 340.51858300000004, + "p95": 342.00416700000005, + "max": 342.293416 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104080, + "wsConnections": 100 + }, + "clientFrameBytes": 1104080, + "initialLatencyMs": { + "min": 20.867291999999907, + "p50": 23.03570899999977, + "p95": 24.76141699999971, + "max": 26.264917000000423 + }, + "commitFanoutMs": 306.95758300000034 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "snapshots", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 0, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 74700, + "httpResponseBytes": 84200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 528800, + "latencyMs": { + "min": 116.18020800000068, + "p50": 200.55029100000047, + "p95": 250.50162499999988, + "max": 255.24691600000006 + }, + "warmup": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 2 + }, + "wire": { + "httpRequestBytes": 2241, + "httpResponseBytes": 6972, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientBytes": 5288 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104780, + "wsConnections": 100 + }, + "clientFrameBytes": 1104780, + "initialLatencyMs": { + "min": 20.942458000000443, + "p50": 22.93787499999962, + "p95": 24.133708000000297, + "max": 25.488624999999956 + }, + "commitFanoutMs": 301.81533299999865 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 100, + "invalidations": 1, + "misses": 3, + "staleRejections": 1 + }, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "live", + "recovery": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 1 + }, + "wire": { + "httpRequestBytes": 928, + "httpResponseBytes": 842, + "wsRequestBytes": 1610, + "wsResponseBytes": 5470, + "wsConnections": 2 + }, + "clientFrameBytes": 5440, + "cursorResets": 1, + "slowClientResets": 0 + }, + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 140.48958400000083, + "p50": 213.07474999999977, + "p95": 254.67654200000106, + "max": 262.21537499999977 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 1, + "origin": { + "producers": 1, + "resultExecutions": 2, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 75800, + "httpResponseBytes": 84200, + "wsRequestBytes": 66385, + "wsResponseBytes": 13564, + "wsConnections": 101 + }, + "clientFrameBytes": 1105180, + "initialLatencyMs": { + "min": 20.779709000000366, + "p50": 22.705541999999696, + "p95": 24.23895900000025, + "max": 25.080291999998735 + }, + "commitFanoutMs": 170.7697500000013 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 3, + 0, + 4, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "none", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 225.62924999999996, + "p50": 400.4289169999993, + "p95": 453.3817910000016, + "max": 461.52195799999936 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1105180, + "wsConnections": 100 + }, + "clientFrameBytes": 1105180, + "initialLatencyMs": { + "min": 23.570792000000438, + "p50": 25.99616700000115, + "p95": 28.189124999997148, + "max": 29.651667000001908 + }, + "commitFanoutMs": 346.484375 + }, + "decisions": [], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "flights", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 101 + }, + "wire": { + "httpRequestBytes": 76194, + "httpResponseBytes": 90334, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 529200, + "latencyMs": { + "min": 744.4551250000004, + "p50": 755.8567079999993, + "p95": 767.9520410000005, + "max": 769.9147080000002 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 144100, + "wsResponseBytes": 1108900, + "wsConnections": 200 + }, + "clientFrameBytes": 1127360, + "initialLatencyMs": { + "min": 22.836959000000206, + "p50": 25.345250000002125, + "p95": 28.244916999999987, + "max": 38.16112500000236 + }, + "commitFanoutMs": 335.93595800000185 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "snapshots", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 0, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 74700, + "httpResponseBytes": 84200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 529200, + "latencyMs": { + "min": 40.5157500000023, + "p50": 526.3143750000017, + "p95": 632.445499999998, + "max": 632.5337080000027 + }, + "warmup": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 2 + }, + "wire": { + "httpRequestBytes": 2241, + "httpResponseBytes": 6976, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientBytes": 5292 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 144100, + "wsResponseBytes": 1108900, + "wsConnections": 200 + }, + "clientFrameBytes": 1127360, + "initialLatencyMs": { + "min": 22.649750000000495, + "p50": 25.527957999998762, + "p95": 28.2020420000008, + "max": 40.410916000000725 + }, + "commitFanoutMs": 369.64583400000265 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 100, + "invalidations": 1, + "misses": 3, + "staleRejections": 1 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "live", + "recovery": { + "origin": { + "producers": 0, + "resultExecutions": 22, + "validations": 3 + }, + "wire": { + "httpRequestBytes": 2444, + "httpResponseBytes": 2526, + "wsRequestBytes": 3707, + "wsResponseBytes": 123326, + "wsConnections": 5 + }, + "clientFrameBytes": 131320, + "cursorResets": 1, + "slowClientResets": 1 + }, + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 143.1261669999949, + "p50": 374.0097079999978, + "p95": 432.9804170000061, + "max": 435.25541599999997 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 1, + "origin": { + "producers": 1, + "resultExecutions": 2, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 75800, + "httpResponseBytes": 84200, + "wsRequestBytes": 66385, + "wsResponseBytes": 13564, + "wsConnections": 101 + }, + "clientFrameBytes": 1120811, + "initialLatencyMs": { + "min": 22.425999999999476, + "p50": 34.62895800000115, + "p95": 37.213792000002286, + "max": 69.46099999999569 + }, + "commitFanoutMs": 241.35470899999927 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 4, + 1, + 25, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + } + ] +} From 29a5b1a139ff785354fc6cd39bfeed2791fdc517 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:29:21 -0500 Subject: [PATCH 062/484] fix: route existing e2e runners through the public gateway Completes task11 configuration audit: host CI uses8791 and local GitOps public UI Service targets the gateway with an explicit internal UI origin. --- .github/workflows/integration-e2e-ui.yaml | 7 ++++--- tests/e2e-ui/api/.gitops/local/README.md | 7 +++++-- tests/e2e-ui/api/.gitops/local/templates/deployment.yaml | 6 +++--- tests/e2e-ui/api/.gitops/local/values.yaml | 4 +++- tests/e2e-ui/scripts/lifecycle-reload.mjs | 2 +- 5 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index 886b66f89..16145e828 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -106,7 +106,8 @@ jobs: - name: Start application with Distributed dev run: | set -euo pipefail - export AUTH_URL="${E2E_UI_ORIGIN:-http://localhost:5180}" + export PUBLIC_ORIGIN="${E2E_UI_ORIGIN:-http://localhost:8791}" + export AUTH_URL="$PUBLIC_ORIGIN" export AUTH_USE_SECURE_COOKIES=false export AUTH_TRUST_HOST=true @@ -137,7 +138,7 @@ jobs: fi grep -F 'lifecycle dev: process api ready http://127.0.0.1:8791' .distributed-dev.log - grep -F 'lifecycle dev: process ui ready http://localhost:5180' .distributed-dev.log + grep -F 'lifecycle dev: process ui ready http://localhost:8791' .distributed-dev.log tail -40 .distributed-dev.log - name: Install Playwright + Chromium @@ -153,7 +154,7 @@ jobs: npm run test:browser npm run test:lifecycle-reload env: - E2E_UI_ORIGIN: http://localhost:5180 + E2E_UI_ORIGIN: http://localhost:8791 E2E_API_ORIGIN: http://127.0.0.1:8791 CI: true diff --git a/tests/e2e-ui/api/.gitops/local/README.md b/tests/e2e-ui/api/.gitops/local/README.md index e3c7ef903..32c2ec5ca 100644 --- a/tests/e2e-ui/api/.gitops/local/README.md +++ b/tests/e2e-ui/api/.gitops/local/README.md @@ -3,8 +3,11 @@ This cluster-development chart renders one Deployment running `distributed dev` for the complete editable application. The lifecycle owns the Rust API, SvelteKit UI, generated clients, linked framework JavaScript, -and generation activation. Two Services expose ports 8791 and 5180 from that -one lifecycle participant set. +and generation activation. Both Services enter the backend gateway on 8791: +the public UI Service retains port 5180 and the API Service uses 8791. The +gateway forwards UI/auth to same-pod SvelteKit at 127.0.0.1:5180; it never +uses the public UI Service as its upstream. PUBLIC_ORIGIN and Auth.js use +the public UI Service URL, so existing OIDC callbacks stay on that origin. Hops supplies the source mount or sync delivery. A Node init container places the pinned Node/npm toolchain beside the Rust toolchain without a custom local diff --git a/tests/e2e-ui/api/.gitops/local/templates/deployment.yaml b/tests/e2e-ui/api/.gitops/local/templates/deployment.yaml index 1b9126c15..aac3a2c06 100644 --- a/tests/e2e-ui/api/.gitops/local/templates/deployment.yaml +++ b/tests/e2e-ui/api/.gitops/local/templates/deployment.yaml @@ -69,7 +69,7 @@ spec: ports: - containerPort: {{ .Values.service.targetPort }} name: api - - containerPort: {{ .Values.uiService.targetPort }} + - containerPort: {{ .Values.env.UI_PORT | int }} name: ui env: {{- include "e2e-ui-api.oidcClientEnv" . | nindent 12 }} @@ -77,8 +77,8 @@ spec: {{- if eq $k "AUTH_URL" }} - name: AUTH_URL value: {{ printf "http://e2e-ui-ui.%s.svc.cluster.local:5180" (include "e2e-ui-api.releaseNamespace" $) | quote }} - {{- else if eq $k "UI_URL" }} - - name: UI_URL + {{- else if or (eq $k "UI_URL") (eq $k "PUBLIC_ORIGIN") }} + - name: {{ $k }} value: {{ printf "http://e2e-ui-ui.%s.svc.cluster.local:5180" (include "e2e-ui-api.releaseNamespace" $) | quote }} {{- else if and $v (ne $v "") }} - name: {{ $k }} diff --git a/tests/e2e-ui/api/.gitops/local/values.yaml b/tests/e2e-ui/api/.gitops/local/values.yaml index 06d2f28a7..1340c77f8 100644 --- a/tests/e2e-ui/api/.gitops/local/values.yaml +++ b/tests/e2e-ui/api/.gitops/local/values.yaml @@ -27,13 +27,15 @@ service: uiService: name: e2e-ui-ui port: 5180 - targetPort: 5180 + targetPort: 8791 env: CARGO_TARGET_DIR: "/workspace/tests/e2e-ui/target" BIND: "0.0.0.0:8791" UI_BIND: "0.0.0.0" UI_PORT: "5180" + UI_INTERNAL_ORIGIN: "http://127.0.0.1:5180" + PUBLIC_ORIGIN: "http://e2e-ui-ui.default.svc.cluster.local:5180" UI_URL: "http://e2e-ui-ui.default.svc.cluster.local:5180" AUTH_URL: "http://e2e-ui-ui.default.svc.cluster.local:5180" AUTH_TRUST_HOST: "true" diff --git a/tests/e2e-ui/scripts/lifecycle-reload.mjs b/tests/e2e-ui/scripts/lifecycle-reload.mjs index 78f01799c..5f880f902 100644 --- a/tests/e2e-ui/scripts/lifecycle-reload.mjs +++ b/tests/e2e-ui/scripts/lifecycle-reload.mjs @@ -12,7 +12,7 @@ const application = resolve(root, 'crates/todo-domain/src/commands/force_archive const clientPage = resolve(root, 'ui/src/routes/todos/+page.svelte'); const framework = resolve(frameworkRoot, 'src/sveltekit/lifecycle.ts'); const lifecycleFile = resolve(root, '.distributed/lifecycle/dev.json'); -const baseURL = process.env.E2E_UI_ORIGIN || 'http://127.0.0.1:5180'; +const baseURL = process.env.PUBLIC_ORIGIN || process.env.E2E_UI_ORIGIN || 'http://localhost:8791'; const apiURL = process.env.E2E_API_ORIGIN || 'http://127.0.0.1:8791'; const timeoutMs = 120_000; const lifecycleBuildTimeoutMs = 300_000; From ac321321c7b6ebc4c080706d4dc894f583de9388 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 02:42:59 -0500 Subject: [PATCH 063/484] test: isolate and stabilize the physical standby fixture Completes task6 CI correction: explicit invocation, owned primary data retained across restart, readiness and fresh primary read verified before subsequent fixtures. --- tests/edge_query_delivery_postgres.rs | 7 +++++++ tests/gateway-postgres/run.py | 7 +++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/edge_query_delivery_postgres.rs b/tests/edge_query_delivery_postgres.rs index e971359d0..3eb00bd6d 100644 --- a/tests/edge_query_delivery_postgres.rs +++ b/tests/edge_query_delivery_postgres.rs @@ -70,6 +70,7 @@ async fn wait_replayed(pool: &sqlx::PgPool, title: &str) { } #[tokio::test] +#[ignore = "requires owned primary and paused standby; run tests/gateway-postgres/run.py"] async fn paused_replica_never_certifies_freshness() { let primary = sqlx::postgres::PgPoolOptions::new() .acquire_timeout(Duration::from_secs(3)) @@ -175,6 +176,12 @@ async fn paused_replica_never_certifies_freshness() { .status() .unwrap() .success()); + wait_replayed(&primary, "committed").await; + assert_eq!( + query(&engine, CURRENT, Some(context)).await["data"]["gateway_replica_views"][0]["title"], + "committed", + "restarted primary retains its committed data and serves a current read" + ); sqlx::query("SELECT pg_wal_replay_resume()") .execute(&replica) .await diff --git a/tests/gateway-postgres/run.py b/tests/gateway-postgres/run.py index 6e9a3fbe7..148eee6a8 100644 --- a/tests/gateway-postgres/run.py +++ b/tests/gateway-postgres/run.py @@ -6,6 +6,7 @@ IMAGE = "postgres@sha256:cf78e76683b9ca8c5733cbbdce6c9262b45b6767934dd0a95e671f9a0fc20685" prefix = "gateway-replay-" + uuid.uuid4().hex[:10] primary, standby = prefix + "-primary", prefix + "-standby" +primary_data = prefix + "-data" def docker(*args): try: @@ -56,7 +57,7 @@ class Server(socketserver.ThreadingTCPServer): try: docker("network", "create", prefix) - docker("run", "-d", "--name", primary, "--network", prefix, "--network-alias", "primary", "--tmpfs", "/var/lib/postgresql/data", "-e", "POSTGRES_HOST_AUTH_METHOD=trust", IMAGE, "postgres", "-c", "wal_level=replica", "-c", "max_wal_senders=4") + docker("run", "-d", "--name", primary, "--network", prefix, "--network-alias", "primary", "--mount", "type=volume,source=" + primary_data + ",target=/var/lib/postgresql/data", "-e", "POSTGRES_HOST_AUTH_METHOD=trust", IMAGE, "postgres", "-c", "wal_level=replica", "-c", "max_wal_senders=4") ready(primary) docker("exec", primary, "sh", "-c", "printf 'host replication postgres all trust\n' >> /var/lib/postgresql/data/pg_hba.conf") docker("exec", primary, "psql", "-U", "postgres", "-c", "SELECT pg_reload_conf()") @@ -64,7 +65,8 @@ class Server(socketserver.ThreadingTCPServer): ready(standby) print("Fixture PostgreSQL " + docker("exec", primary, "postgres", "--version"), flush=True) env = {**os.environ, "GATEWAY_TEST_PRIMARY_URL": url(primary), "GATEWAY_TEST_REPLICA_URL": url(standby), "GATEWAY_TEST_PRIMARY_CONTAINER": primary} - subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--nocapture"], cwd=ROOT, env=env, check=True) + subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "edge_query_delivery_postgres", "--", "--ignored", "--nocapture"], cwd=ROOT, env=env, check=True) + ready(primary) # The standby proof deliberately stops and restarts the primary. subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--lib", "graphql::delivery::versions::tests::postgres_transactional_coverage_and_snapshot_race", "--", "--ignored", "--nocapture"], cwd=ROOT, env=env, check=True) subprocess.run(["cargo", "test", "-p", "distributed", "--no-default-features", "--features", "gateway-delivery,graphql,postgres", "--test", "postgres_repository", "projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks", "--", "--nocapture"], cwd=ROOT, env={**env, "DATABASE_URL": env["GATEWAY_TEST_PRIMARY_URL"]}, check=True) finally: @@ -72,4 +74,5 @@ class Server(socketserver.ThreadingTCPServer): bridge.shutdown(); bridge.server_close() for container in [standby, primary]: subprocess.run(["docker", "rm", "-f", container], capture_output=True) + subprocess.run(["docker", "volume", "rm", primary_data], capture_output=True) subprocess.run(["docker", "network", "rm", prefix], capture_output=True) From 4dd9f2ea595f38f49ef1f0b682f7bd547300da84 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 03:22:52 -0500 Subject: [PATCH 064/484] fix: route dev lifecycle and celld UI through the gateway Resolves tasks/application-gateway-ci-1: preserve remote command dispatch and internal relay ownership, update public origins, and verify actual dev browser flows. --- .github/workflows/integration-celld.yaml | 13 ++- .github/workflows/integration-e2e-ui.yaml | 3 +- .github/workflows/integration-gateway.yaml | 2 + tests/e2e-celld/Cargo.toml | 2 +- tests/e2e-celld/Makefile | 6 +- tests/e2e-celld/README.md | 4 +- .../crates/graphql-service/src/host.rs | 4 + .../crates/graphql-service/src/http.rs | 106 ++++++++++++++++-- tests/e2e-celld/crates/runner/src/main.rs | 4 + tests/e2e-ui/crates/service/src/http.rs | 1 - tests/e2e-ui/gateway/run.mjs | 25 ++++- 11 files changed, 144 insertions(+), 26 deletions(-) diff --git a/.github/workflows/integration-celld.yaml b/.github/workflows/integration-celld.yaml index 6e340e983..2d4f00953 100644 --- a/.github/workflows/integration-celld.yaml +++ b/.github/workflows/integration-celld.yaml @@ -7,7 +7,7 @@ name: celld (live + e2e-celld) # make -C tests/e2e-celld test # make -C tests/e2e-ui up && make -C tests/e2e-ui up-celld-nats # WATCH=0 WATCH_WORKER=0 make -C tests/e2e-celld run -# E2E_UI_ORIGIN=http://localhost:5180 npx --prefix tests/e2e-ui playwright test \ +# E2E_UI_ORIGIN=http://localhost:8791 npx --prefix tests/e2e-ui playwright test \ # todos.user.spec.ts chat.user.spec.ts --project chromium-user # # Default `cargo test` (quality) still runs fixture-only celld checks and @@ -174,12 +174,13 @@ jobs: export BIND=127.0.0.1:8791 export CELLD_URL=http://127.0.0.1:18880 export NATS_URL=nats://127.0.0.1:14222 - export AUTH_URL=http://localhost:5180 + export PUBLIC_ORIGIN=http://localhost:8791 + export AUTH_URL="$PUBLIC_ORIGIN" export AUTH_USE_SECURE_COOKIES=false export AUTH_TRUST_HOST=true export PUBLIC_E2E_PROFILE=celld-nats export UI_BIND=localhost - export UI_URL=http://localhost:5180 + export UI_URL=http://localhost:8791 target/debug/distributed dev tests/e2e-celld \ > tests/e2e-celld/.ci-distributed-dev.log 2>&1 & @@ -206,13 +207,13 @@ jobs: fi grep -F 'lifecycle dev: process api ready http://127.0.0.1:8791' \ tests/e2e-celld/.ci-distributed-dev.log - grep -F 'lifecycle dev: process ui ready http://localhost:5180' \ + grep -F 'lifecycle dev: process ui ready http://localhost:8791' \ tests/e2e-celld/.ci-distributed-dev.log ok=0 for i in $(seq 1 60); do code=$(curl -s -o /dev/null -w '%{http_code}' \ - "http://localhost:5180/" 2>/dev/null || echo 000) + "http://localhost:8791/" 2>/dev/null || echo 000) if [ "$code" = "200" ] || [ "$code" = "302" ] || [ "$code" = "303" ]; then ok=1 break @@ -271,7 +272,7 @@ jobs: npx playwright test todos.user.spec.ts chat.user.spec.ts --project chromium-user env: - E2E_UI_ORIGIN: http://localhost:5180 + E2E_UI_ORIGIN: http://localhost:8791 E2E_API_ORIGIN: http://127.0.0.1:8791 CI: true diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index 16145e828..16db9d94a 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -115,7 +115,8 @@ jobs: echo $! > .distributed-dev.pid ok=0 - for i in $(seq 1 240); do + # Match the CLI's bounded cold-runtime + UI readiness budget. + for i in $(seq 1 720); do if grep -Fq 'lifecycle dev: ready generation=' .distributed-dev.log; then ok=1 break diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 58ee75f6a..6ba3177ac 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -210,6 +210,8 @@ jobs: run: cargo test --no-default-features --features graphql,sqlite,application-runtime,gateway --test application_composition --test application_plans --test gateway_mounts - name: Build coherent application and run public-origin browser flows run: node tests/e2e-ui/gateway/run.mjs + - name: Verify dev lifecycle and browser flows through the gateway + run: GATEWAY_SKIP_BUILD=1 GATEWAY_DEV=1 node tests/e2e-ui/gateway/run.mjs - uses: actions/upload-artifact@v4 if: always() with: diff --git a/tests/e2e-celld/Cargo.toml b/tests/e2e-celld/Cargo.toml index 4f6f78f6c..5e63dc5b5 100644 --- a/tests/e2e-celld/Cargo.toml +++ b/tests/e2e-celld/Cargo.toml @@ -32,7 +32,7 @@ license = "MIT" publish = false [workspace.dependencies] -distributed = { path = "../..", features = ["sqlite", "postgres", "http", "graphql", "metrics", "nats"] } +distributed = { path = "../..", features = ["sqlite", "postgres", "http", "graphql", "gateway-graphql-native", "metrics", "nats"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync"] } diff --git a/tests/e2e-celld/Makefile b/tests/e2e-celld/Makefile index c2360603e..a49d1564e 100644 --- a/tests/e2e-celld/Makefile +++ b/tests/e2e-celld/Makefile @@ -12,7 +12,9 @@ BIND ?= 127.0.0.1:8791 API_PORT ?= 8791 UI_PORT ?= 5180 UI_HOST ?= localhost -UI_URL ?= http://localhost:5180 +PUBLIC_ORIGIN ?= http://localhost:8791 +UI_INTERNAL_ORIGIN ?= http://localhost:$(UI_PORT) +UI_URL ?= $(PUBLIC_ORIGIN) ENV_FILE ?= ../e2e-ui/e2e-ui.env CELLD_HTTP_PORT ?= 18080 CELLD_URL ?= http://127.0.0.1:$(CELLD_HTTP_PORT) @@ -64,6 +66,8 @@ run: $(if $(filter 1,$(WATCH_WORKER)),ensure-watch) export BIND="$${BIND:-127.0.0.1:8791}"; \ export UI_BIND="$${UI_BIND:-$(UI_HOST)}"; \ export UI_PORT="$${UI_PORT:-$(UI_PORT)}"; \ + export PUBLIC_ORIGIN="$${PUBLIC_ORIGIN:-$(PUBLIC_ORIGIN)}"; \ + export UI_INTERNAL_ORIGIN="$${UI_INTERNAL_ORIGIN:-$(UI_INTERNAL_ORIGIN)}"; \ export UI_URL="$${UI_URL:-$(UI_URL)}"; \ export AUTH_URL="$${AUTH_URL:-$$UI_URL}"; \ export AUTH_USE_SECURE_COOKIES="false"; \ diff --git a/tests/e2e-celld/README.md b/tests/e2e-celld/README.md index 565f46591..e49637200 100644 --- a/tests/e2e-celld/README.md +++ b/tests/e2e-celld/README.md @@ -54,7 +54,7 @@ make up # Zitadel + Postgres (read models + login) make up-celld-nats # celld 0.4 local store + NATS cd ../e2e-celld -make run # GraphQL :8791 + UI :5180 (watches sources) +make run # public gateway :8791 + internal UI :5180 (watches sources) ``` Eventual projectors and `@live` use **Postgres** from `e2e-ui.env` @@ -78,7 +78,7 @@ The Cargo workspace declares `../e2e-ui/ui` as its UI component. Both `distributed build` and `distributed dev` resolve it within the repository; CI and users do not launch a second unmanaged `npm run dev` process. -Open `http://localhost:5180`. The navbar shows a **celld** badge. Sign in +Open `http://localhost:8791`. The navbar shows a **celld** badge. Sign in (`alice` / `Password1!` when Zitadel is up). Todos create/complete and lobby posts go to cells; open Chat in two tabs to see `@live` still fire. diff --git a/tests/e2e-celld/crates/graphql-service/src/host.rs b/tests/e2e-celld/crates/graphql-service/src/host.rs index 38644def3..8e328d149 100644 --- a/tests/e2e-celld/crates/graphql-service/src/host.rs +++ b/tests/e2e-celld/crates/graphql-service/src/host.rs @@ -27,6 +27,8 @@ const BUS_GROUP: &str = "e2e-celld"; pub struct HostOptions { pub bind: String, + pub public_origin: String, + pub ui_origin: String, pub identity: IdentityConfig, pub celld_url: String, pub nats_url: String, @@ -100,6 +102,8 @@ async fn run_postgres( service, host, &options.bind, + &options.public_origin, + &options.ui_origin, queue_relay, options.internal_secret, ) diff --git a/tests/e2e-celld/crates/graphql-service/src/http.rs b/tests/e2e-celld/crates/graphql-service/src/http.rs index a52a171f7..cf4923579 100644 --- a/tests/e2e-celld/crates/graphql-service/src/http.rs +++ b/tests/e2e-celld/crates/graphql-service/src/http.rs @@ -16,7 +16,8 @@ use axum::{Json, Router}; use distributed::bus::{CelldQueueEnvelope, CelldQueueRelayHandler, CELLD_QUEUE_RELAY_PATH}; use distributed::cell_host::{InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER}; use distributed::command_dispatch::SharedCommandHost; -use distributed::graphql::graphql_router_with_host; +use distributed::gateway::{native::*, *}; +use distributed::graphql::identity::OidcGatewayProvider; use distributed::microsvc::{HandlerError, Service, Session}; use serde_json::{json, Value}; @@ -91,6 +92,8 @@ pub async fn serve( service: Arc, host: SharedCommandHost, addr: &str, + public_origin: &str, + ui_origin: &str, queue_relay: CelldQueueRelayHandler, internal_secret: InternalHttpSecret, ) -> Result<(), std::io::Error> { @@ -110,15 +113,13 @@ pub async fn serve( "graphql": true, "commands": commands, }); - let mut app = Router::new() - .route( - "/health", - get(move || { - let body = health_body.clone(); - async move { Json(body) } - }), - ) - .merge(graphql_router_with_host(engine, host)); + let mut app = Router::new().route( + "/health", + get(move || { + let body = health_body.clone(); + async move { Json(body) } + }), + ); let mut internal = Router::new() .route( "/zitadel.ingress.v1", @@ -158,6 +159,91 @@ pub async fn serve( require_internal, ))); + let capabilities = GraphqlCapabilities { + queries: true, + commands: true, + live: true, + }; + let mut routes = vec![ + Route::new("graphql", RoutePath::prefix("/graphql"), "graphql"), + Route::new("ui", RoutePath::prefix("/"), "ui"), + ]; + for path in [ + "/health", + "/zitadel.ingress.v1", + "/zitadel.scrape.v1", + CELLD_QUEUE_RELAY_PATH, + ] { + routes.push(Route::new( + format!("service-{}", routes.len()), + RoutePath::exact(path), + "service", + )); + } + for command in service.command_names() { + let path = RoutePath::exact(format!("/{command}")); + if !routes.iter().any(|route| route.path == path) { + routes.push(Route::new( + format!("closed-{}", routes.len()), + path, + "closed", + )); + } + } + let gateway = GatewayConfig { + bindings: vec![ + Binding::new( + "graphql", + BindingKind::Graphql { + executor: GraphqlExecutor::Embedded, + capabilities, + delivery: DeliveryCapabilities::default(), + schema_extensions: vec![], + }, + ), + Binding::new( + "ui", + BindingKind::UiProxy { + origin: ui_origin.into(), + }, + ), + Binding::new("service", BindingKind::Handler), + Binding::new("closed", BindingKind::Handler), + ], + routes, + } + .build() + .map_err(std::io::Error::other)?; + let auth = if let Some(config) = engine.identity_config().oidc.clone() { + let provider = Arc::new(OidcGatewayProvider::new(config, "e2e-celld-oidc-v1")); + NativeAuth::new(move |credentials| { + let provider = provider.clone(); + async move { provider.authenticate(&credentials).await } + }) + } else { + NativeAuth::anonymous() + }; + // The remote command host and secret-protected Queue relay keep their + // existing owners. UI, auth, HMR and lifecycle requests use this public edge. + let app = NativeGateway::new( + gateway, + NativeOptions::new(public_origin), + [ + ( + "graphql".into(), + NativeBinding::Graphql(GraphqlBinding::Embedded( + EmbeddedGraphql::new(engine, Some(host), capabilities) + .map_err(std::io::Error::other)?, + )), + ), + ("ui".into(), NativeBinding::UiProxy { websocket: true }), + ("service".into(), NativeBinding::Handler(app)), + ("closed".into(), NativeBinding::Handler(Router::new())), + ], + auth, + ) + .map_err(std::io::Error::other)? + .router(); let listener = tokio::net::TcpListener::bind(addr).await?; axum::serve(listener, app).await } diff --git a/tests/e2e-celld/crates/runner/src/main.rs b/tests/e2e-celld/crates/runner/src/main.rs index 2ee27e7b4..e4697db77 100644 --- a/tests/e2e-celld/crates/runner/src/main.rs +++ b/tests/e2e-celld/crates/runner/src/main.rs @@ -33,6 +33,10 @@ async fn main() -> Result<(), Box> { &database_url, HostOptions { bind, + public_origin: env::var("PUBLIC_ORIGIN") + .unwrap_or_else(|_| "http://localhost:8791".into()), + ui_origin: env::var("UI_INTERNAL_ORIGIN") + .unwrap_or_else(|_| "http://localhost:5180".into()), identity: identity_from_env(), celld_url, nats_url, diff --git a/tests/e2e-ui/crates/service/src/http.rs b/tests/e2e-ui/crates/service/src/http.rs index bd381daad..c0afafec1 100644 --- a/tests/e2e-ui/crates/service/src/http.rs +++ b/tests/e2e-ui/crates/service/src/http.rs @@ -88,7 +88,6 @@ pub fn gateway_router( "/healthz", "/metrics", "/graphiql", - "/__distributed", ] { routes.push(Route::new( format!("http-{}", routes.len()), diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 2c4292b9e..5f27ffe38 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import {spawn} from 'node:child_process'; import {createServer} from 'node:http'; import {once} from 'node:events'; -import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises'; +import {mkdtemp,mkdir,readFile,writeFile,rm} from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; @@ -10,15 +10,16 @@ import {randomBytes} from 'node:crypto'; import {chromium,expect} from '../../gateway-auth/node_modules/@playwright/test/index.mjs'; import {startProvider} from '../../gateway-auth/provider.mjs'; const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const devMode=process.env.GATEWAY_DEV==='1'; const environment={PATH:process.env.PATH,HOME:process.env.HOME,RUSTUP_TOOLCHAIN:process.env.RUSTUP_TOOLCHAIN||'stable',NODE_ENV:'production'}; async function freePort(){const server=createServer();server.listen(0,'127.0.0.1');await once(server,'listening');const port=server.address().port;await new Promise(r=>server.close(r));return port;} function launch(program,args,{cwd=root,env=environment}={}){ let log='';const child=spawn(program,args,{cwd,env,stdio:['ignore','pipe','pipe']}); child.on('error',error=>log+='process launch failed: '+error.code); child.stdout.on('data',chunk=>log=(log+chunk).slice(-60000));child.stderr.on('data',chunk=>log=(log+chunk).slice(-60000)); - return {child,logs:()=>log,stop:async()=>{if(child.exitCode===null){child.kill('SIGTERM');await once(child,'exit');}}}; + return {child,logs:()=>log,stop:async()=>{if(child.exitCode===null){child.kill('SIGINT');await once(child,'exit');}}}; } -async function ready(url,process){for(let i=0;i<300;i++){if(process.child.exitCode!==null)throw Error(process.logs());try{const response=await fetch(url);if(response.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('readiness timeout: '+process.logs());} +async function ready(url,process){for(let i=0;i<3600;i++){if(process.child.exitCode!==null)throw Error(process.logs());try{const response=await fetch(url);if(response.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('readiness timeout: '+process.logs());} const artifacts=path.join(root,'gateway/artifacts');await mkdir(artifacts,{recursive:true}); if(process.env.GATEWAY_SKIP_BUILD!=='1'){ const {NODE_ENV,...buildEnvironment}=environment; @@ -33,10 +34,26 @@ try{ const idp=await startProvider(issuer,publicOrigin,{jwtAudience:'gateway-fixture'}); let api,ui,browser; try{ + if(devMode){ + const {NODE_ENV,...devEnvironment}=environment; + api=launch(path.resolve(root,'../../target/debug/distributed'),['dev',root],{env:{...devEnvironment,DATABASE_URL:`sqlite:${temporary}/${delivery}.db?mode=rwc`,BIND:`127.0.0.1:${apiPort}`,PUBLIC_ORIGIN:publicOrigin,UI_INTERNAL_ORIGIN:`http://127.0.0.1:${uiPort}`,UI_PORT:String(uiPort),UI_BIND:'127.0.0.1',GATEWAY_DELIVERY:delivery,OIDC_ISSUER:issuer,OIDC_AUDIENCE:'gateway-fixture',OIDC_CLIENT_ID:'gateway-fixture',OIDC_CLIENT_SECRET:'local-fixture-only',AUTH_URL:publicOrigin,AUTH_SECRET:randomBytes(32).toString('hex'),AUTH_USE_SECURE_COOKIES:'false',GRAPHIQL:'0'}}); + ui={logs:api.logs,stop:async()=>{}}; + }else{ api=launch(path.join(root,'target/debug/e2e-ui'),[],{env:{...environment,DATABASE_URL:`sqlite:${temporary}/${delivery}.db?mode=rwc`,BIND:`127.0.0.1:${apiPort}`,PUBLIC_ORIGIN:publicOrigin,UI_INTERNAL_ORIGIN:`http://127.0.0.1:${uiPort}`,GATEWAY_DELIVERY:delivery,OIDC_ISSUER:issuer,OIDC_AUDIENCE:'gateway-fixture',OIDC_CLIENT_ID:'gateway-fixture',GRAPHIQL:'0'}}); await ready(publicOrigin+'/health',api); ui=launch(process.execPath,['build/index.js'],{cwd:path.join(root,'ui'),env:{...environment,HOST:'127.0.0.1',PORT:String(uiPort),PUBLIC_ORIGIN:publicOrigin,ORIGIN:publicOrigin,AUTH_URL:publicOrigin,AUTH_SECRET:randomBytes(32).toString('hex'),AUTH_USE_SECURE_COOKIES:'false',OIDC_ISSUER:issuer,OIDC_CLIENT_ID:'gateway-fixture',OIDC_CLIENT_SECRET:'local-fixture-only',OIDC_AUDIENCE:'gateway-fixture',E2E_API_ORIGIN:publicOrigin}}); - await ready(publicOrigin,ui); + } + await ready(publicOrigin,api); + if(devMode){ + const participant='gateway_ci_lifecycle_probe'; + const response=await fetch(publicOrigin+'/__distributed/lifecycle',{headers:{'x-distributed-participant':participant}}); + assert.equal(response.status,200,'gateway must route lifecycle to the UI'); + assert.equal((await response.json()).phase,'active'); + const heartbeat=JSON.parse(await readFile(path.join(root,'.distributed/lifecycle/dev-control/participants',participant+'.json'),'utf8')); + assert.ok(Date.now()-heartbeat.seenAtUnixMs<5000); + const ack=await fetch(publicOrigin+'/__distributed/lifecycle',{method:'POST',headers:{origin:publicOrigin,'content-type':'application/json'},body:JSON.stringify({participantId:participant,transitionId:'gateway_ci_no_transition',ok:true})}); + assert.equal(ack.status,409,'same-origin acknowledgement reaches lifecycle state validation'); + } browser=await chromium.launch();const context=await browser.newContext();const page=await context.newPage(); const errors=[];page.on('pageerror',error=>errors.push(error.message)); await page.goto(publicOrigin);await page.getByRole('link',{name:/log in|sign in/i}).first().click(); From 83813f4c73a1c22ac784ed05c29c15ef9ae4bc54 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 03:42:27 -0500 Subject: [PATCH 065/484] test: wait for chat delivery before asserting reload persistence Resolves tasks/application-gateway-ci-1. Optimistic paint remains asserted; reload now follows the command receipt and projection rather than cancelling a pending request. --- tests/e2e-ui/e2e/chat.user.spec.ts | 6 +++++- tests/e2e-ui/gateway/run.mjs | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/e2e-ui/e2e/chat.user.spec.ts b/tests/e2e-ui/e2e/chat.user.spec.ts index cabbb349c..f1103f313 100644 --- a/tests/e2e-ui/e2e/chat.user.spec.ts +++ b/tests/e2e-ui/e2e/chat.user.spec.ts @@ -88,7 +88,11 @@ test.describe('chat (alice)', () => { await expect(msg).toBeVisible({ timeout: 20_000 }); await expect(msg.locator('.ch-body')).toHaveText(body); - // Reload — message should still be there (RM + SSR) + // The first row is optimistic. Wait for the command receipt and + // projection before navigation can cancel the pending HTTP request. + await expect(page.locator('.ch-msg-block', { has: msg }).locator('.ch-status-footer')).toHaveText('Delivered'); + + // Reload — the confirmed message should still be there (RM + SSR) await page.reload(); await expect(page.locator('.ch-msg', { hasText: body })).toBeVisible({ timeout: 20_000 diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 5f27ffe38..eaa219d92 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -161,4 +161,8 @@ async function verifyLiveRace(page,origin){ await expect(page.getByText(body,{exact:true})).toBeVisible(); const samples=await page.evaluate(()=>{globalThis.__gatewayLiveObserver.disconnect();return globalThis.__gatewayLiveSamples;}); assert.ok(samples.every(Boolean),'late live observation removed the confirmed message'); + const message=page.locator('.ch-msg',{hasText:body}); + await expect(page.locator('.ch-msg-block',{has:message}).locator('.ch-status-footer')).toHaveText('Delivered'); + await page.reload(); + await expect(page.locator('.ch-msg',{hasText:body})).toBeVisible(); } From 4ed64c3c6384f930264e69b175f2dba6c49fce1c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 04:13:22 -0500 Subject: [PATCH 066/484] fix: coordinate dev socket recovery with application reloads Resolves tasks/application-gateway-ci-1. Let the coherent lifecycle own navigation after gateway restarts, retain prepared state through activation or rollback, and exercise the complete browser reload fixture through public ingress. --- .github/workflows/integration-gateway.yaml | 3 + js/src/sveltekit/lifecycle.ts | 30 ++++++-- js/src/sveltekit/vite.ts | 8 +++ js/tests/reload-dev-transport.test.mjs | 84 ++++++++++++++++++++++ tests/e2e-ui/gateway/run.mjs | 15 +++- tests/e2e-ui/scripts/lifecycle-reload.mjs | 15 +++- 6 files changed, 147 insertions(+), 8 deletions(-) create mode 100644 js/tests/reload-dev-transport.test.mjs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 6ba3177ac..059896222 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -204,6 +204,7 @@ jobs: run: | cargo install wasm-pack --locked npm ci --prefix tests/gateway-auth + npm ci --prefix tests/e2e-ui cd tests/gateway-auth npx playwright install --with-deps chromium - name: Verify explicit application mounts @@ -212,6 +213,8 @@ jobs: run: node tests/e2e-ui/gateway/run.mjs - name: Verify dev lifecycle and browser flows through the gateway run: GATEWAY_SKIP_BUILD=1 GATEWAY_DEV=1 node tests/e2e-ui/gateway/run.mjs + - name: Verify controlled reloads across gateway and application restarts + run: GATEWAY_SKIP_BUILD=1 GATEWAY_DEV=1 GATEWAY_LIFECYCLE=1 node tests/e2e-ui/gateway/run.mjs - uses: actions/upload-artifact@v4 if: always() with: diff --git a/js/src/sveltekit/lifecycle.ts b/js/src/sveltekit/lifecycle.ts index 674b3b09c..facb63c35 100644 --- a/js/src/sveltekit/lifecycle.ts +++ b/js/src/sveltekit/lifecycle.ts @@ -92,6 +92,8 @@ type ReloadCapsule = Readonly<{ }>; export interface DistributedReloadLifecycle { + /** Let a prepared coherent transition own reload after a dev socket reconnect. */ + deferDevTransportReload(): Promise; assertDispatchOpen(): void; register(participant: ReloadParticipant): () => void; destroy(): void; @@ -224,6 +226,8 @@ function createDistributedReloadLifecycle(): DistributedReloadLifecycle { let destroyed = false; let preparing: string | undefined; let reloadRequested = false; + let devTransportDisconnected = false; + const deferredTransports = new Set<() => void>(); let loadedGenerationId = documentGenerationId(); let timer: ReturnType | undefined; let restoration = Promise.resolve(); @@ -272,11 +276,18 @@ function createDistributedReloadLifecycle(): DistributedReloadLifecycle { } return; } - if (state.active.generationId !== loadedGenerationId) { + if ( + state.active.generationId !== loadedGenerationId || + (preparing !== undefined && devTransportDisconnected) + ) { blocked = true; if (!reloadRequested) { reloadRequested = true; - markCapsuleRestoring(); + // A rejected replacement can restart the previous API too. Restore + // the prepared state into that verified rollback generation. + markCapsuleRestoring( + state.active.generationId === loadedGenerationId ? state.active : undefined + ); window.location.reload(); } return; @@ -295,6 +306,14 @@ function createDistributedReloadLifecycle(): DistributedReloadLifecycle { void poll(); return Object.freeze({ + deferDevTransportReload(): Promise { + if (preparing === undefined && !reloadRequested) return Promise.resolve(); + devTransportDisconnected = true; + // Vite awaits its disconnect listeners before its automatic reload. + // The lifecycle poll keeps running and owns the one navigation after + // activation (or verified rollback); page teardown releases this wait. + return new Promise((resolve) => deferredTransports.add(resolve)); + }, assertDispatchOpen(): void { if (blocked) throw new Error('coherent application reload is in progress'); }, @@ -311,6 +330,8 @@ function createDistributedReloadLifecycle(): DistributedReloadLifecycle { destroyed = true; if (timer !== undefined) clearTimeout(timer); participants.clear(); + for (const resolve of deferredTransports) resolve(); + deferredTransports.clear(); } }); } @@ -446,9 +467,9 @@ function readCapsule(): ReloadCapsule | undefined { } } -function markCapsuleRestoring(): void { +function markCapsuleRestoring(rollback?: LifecycleGeneration): void { const capsule = readCapsule(); - if (capsule !== undefined) storeCapsule(Object.freeze({ ...capsule, phase: 'restoring' })); + if (capsule !== undefined) storeCapsule(Object.freeze({ ...capsule, to: rollback ?? capsule.to, phase: 'restoring' })); } function parseLifecycleState(value: unknown): LifecycleDevState { @@ -521,6 +542,7 @@ function documentGenerationId(): string | undefined { function inertLifecycle(): DistributedReloadLifecycle { return Object.freeze({ + async deferDevTransportReload(): Promise {}, assertDispatchOpen(): void {}, register(): () => void { return () => undefined; diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 3e722c1cf..73d4fdf50 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -235,6 +235,7 @@ export type DistributedSvelteKitVitePlugin = Readonly<{ buildStart(this: RollupWatchContextLike): void; resolveId(source: string, importer?: string): string | undefined; load(id: string): string | undefined; + transform(code: string, id: string, options?: Readonly<{ ssr?: boolean }>): string | undefined; transformIndexHtml(): LifecycleHtmlTag[]; handleHotUpdate(context: ViteHotContextLike): Promise; watchChange(id: string): Promise; @@ -500,6 +501,13 @@ export function distributedSvelteKit( : client.entry; return `export * from ${JSON.stringify(portablePath(entry))};\n`; }, + transform(code, id, options): string | undefined { + if (!lifecycleOwnsCompile || options?.ssr || frameworkDist === undefined) return; + if (id.split('?', 1)[0] !== join(frameworkDist, 'sveltekit', 'lifecycle.js')) return; + // SvelteKit aliases can resolve generated clients before the virtual + // module hook. Attach once to the actual shared browser lifecycle. + return code + `\nif (import.meta.hot) import.meta.hot.on('vite:ws:disconnect', () => distributedReloadLifecycle().deferDevTransportReload());\n`; + }, transformIndexHtml: lifecycleGenerationMeta, async handleHotUpdate(context): Promise { const suppressed = suppressFrameworkHotUpdate(context, frameworkDist); diff --git a/js/tests/reload-dev-transport.test.mjs b/js/tests/reload-dev-transport.test.mjs new file mode 100644 index 000000000..1dd1e8562 --- /dev/null +++ b/js/tests/reload-dev-transport.test.mjs @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +for (const outcome of ['activation', 'rollback', 'unplanned disconnect']) { + test(`dev reconnect ownership during ${outcome}`, async () => { + // Each case models a fresh browser page with its own lifecycle singleton. + const { distributedReloadLifecycle, registerDistributedReloadClient } = + await import(`../dist/sveltekit/lifecycle.js?${outcome}`); + const previous = Object.fromEntries( + ['window', 'document', 'sessionStorage', 'CustomEvent', 'fetch'] + .map((key) => [key, globalThis[key]]) + ); + const values = new Map(); + const capsuleKey = '@hops-ops/distributed/reload-capsule/v1'; + const generation = (generationId) => ({ + generationId, releaseId: `release-${generationId}`, + topologyId: 'topology', compatibilityId: 'compatible' + }); + let state = { + schemaVersion: 1, phase: 'preparing', active: generation('old'), + pending: generation('next'), transitionId: 'transition-reconnect', + deadlineUnixMs: Date.now() + 10_000 + }; + if (outcome === 'unplanned disconnect') state = { schemaVersion: 1, phase: 'active', active: generation('old') }; + let reloads = 0; + globalThis.sessionStorage = { + getItem: (key) => values.get(key) ?? null, + setItem: (key, value) => values.set(key, String(value)), + removeItem: (key) => values.delete(key) + }; + globalThis.document = { querySelector: () => ({ getAttribute: () => 'old' }) }; + globalThis.window = { + location: { href: 'http://localhost:8791/todos', reload() { reloads++; } }, + dispatchEvent() {} + }; + globalThis.CustomEvent = class { constructor(type, options) { this.type = type; this.detail = options?.detail; } }; + globalThis.fetch = async (_url, options) => options?.method === 'POST' + ? { status: 204, ok: true } + : { status: 200, ok: true, json: async () => state }; + const waitFor = async (condition) => { + const deadline = Date.now() + 3_000; + while (!condition()) { + assert.ok(Date.now() < deadline, 'lifecycle did not reach expected state'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + }; + const unregister = registerDistributedReloadClient( + { scope: undefined, dehydrate: () => ({}), hydrate: () => false }, + undefined, { key: 'surface' } + ); + const lifecycle = distributedReloadLifecycle(); + try { + if (outcome === 'unplanned disconnect') { + await lifecycle.deferDevTransportReload(); + lifecycle.assertDispatchOpen(); + assert.equal(reloads, 0); + assert.equal(values.has(capsuleKey), false); + return; + } + await waitFor(() => values.has(capsuleKey)); + let viteResumed = false; + const deferred = lifecycle.deferDevTransportReload().then(() => { viteResumed = true; }); + await Promise.resolve(); + assert.equal(viteResumed, false); + assert.throws(() => lifecycle.assertDispatchOpen(), /reload/); + const target = outcome === 'activation' ? 'next' : 'old'; + state = { schemaVersion: 1, phase: 'active', active: generation(target) }; + await waitFor(() => reloads === 1); + const capsule = JSON.parse(values.get(capsuleKey)); + assert.equal(capsule.phase, 'restoring'); + assert.equal(capsule.to.generationId, target); + assert.equal(viteResumed, false, 'Vite must not race the controlled navigation'); + lifecycle.destroy(); + await deferred; + } finally { + unregister(); + lifecycle.destroy(); + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete globalThis[key]; + else globalThis[key] = value; + } + } + }); +} diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index eaa219d92..7d57c1a6f 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -28,7 +28,7 @@ if(process.env.GATEWAY_SKIP_BUILD!=='1'){ } const temporary=await mkdtemp(path.join(os.tmpdir(),'gateway-app-')); try{ - for(const delivery of ['none','all']){ + for(const delivery of (process.env.GATEWAY_LIFECYCLE==='1'?['none']:['none','all'])){ const apiPort=await freePort(),uiPort=await freePort(),issuer=`http://127.0.0.1:${await freePort()}`; const publicOrigin=`http://127.0.0.1:${apiPort}`; const idp=await startProvider(issuer,publicOrigin,{jwtAudience:'gateway-fixture'}); @@ -78,7 +78,18 @@ try{ await page.goto(publicOrigin+'/blob');await expect(page.getByTestId('blob-start-game')).toBeEnabled();await page.getByTestId('blob-start-game').click();await expect(page.locator('.blob-board')).toBeVisible({timeout:20000}); await verifyBlobRace(page); await verifyLiveRace(page,publicOrigin); - await verifyAuth(context,idp,publicOrigin); + if(process.env.GATEWAY_LIFECYCLE==='1'){ + assert.ok(devMode,'full reload proof requires the CLI dev host'); + const storage=path.join(temporary,'reload-auth.json');await context.storageState({path:storage}); + // The lifecycle fixture owns the browser participants during source edits. + await browser.close();browser=undefined; + const reload=launch(process.execPath,['scripts/lifecycle-reload.mjs'],{env:{...environment,E2E_UI_ORIGIN:publicOrigin,E2E_API_ORIGIN:publicOrigin,E2E_RELOAD_STORAGE_STATE:storage}}); + reload.child.stdout.on('data',chunk=>process.stdout.write(chunk)); + const [code]=await once(reload.child,'exit'); + await writeFile(path.join(artifacts,'lifecycle-reload.log'),reload.logs()); + assert.equal(code,0,reload.logs()); + console.log('PASS complete controlled browser lifecycle through the public gateway'); + }else await verifyAuth(context,idp,publicOrigin); assert.deepEqual(errors,[]);console.log('PASS actual public-origin application login, Todo Eventual and Blob Atomic with delivery '+delivery); }catch(error){await writeFile(path.join(artifacts,delivery+'-failure.txt'),String(error));throw error;} finally{await browser?.close();await ui?.stop();await api?.stop();await new Promise(r=>idp.server.close(r));if(api)await writeFile(path.join(artifacts,delivery+'-api.log'),api.logs());if(ui)await writeFile(path.join(artifacts,delivery+'-ui.log'),ui.logs());} diff --git a/tests/e2e-ui/scripts/lifecycle-reload.mjs b/tests/e2e-ui/scripts/lifecycle-reload.mjs index 5f880f902..77c823738 100644 --- a/tests/e2e-ui/scripts/lifecycle-reload.mjs +++ b/tests/e2e-ui/scripts/lifecycle-reload.mjs @@ -209,7 +209,18 @@ async function transition(page, path, source, expectedReplicaRestore, assertGate }, 'controlled browser reload restoration', lifecycleBuildTimeoutMs - ); + ).catch(async (error) => { + const browserState = await page.evaluate(() => { + const capsule = JSON.parse(sessionStorage.getItem('@hops-ops/distributed/reload-capsule/v1') || 'null'); + return { + generation: document.querySelector('meta[name="distributed-generation"]')?.getAttribute('content'), + capsulePhase: capsule?.phase, + capsuleTarget: capsule?.to?.generationId, + restoredEvents: globalThis.__distributedReloadEvents?.length + }; + }).catch(() => undefined); + throw new Error(`${error.message}; browser=${JSON.stringify(browserState)}`, { cause: error }); + }); assert.equal(restored.replicaCaptured, true, 'authenticated replica must participate'); assert.equal(restored.replicaRestored, expectedReplicaRestore); assert.equal( @@ -284,7 +295,7 @@ async function transition(page, path, source, expectedReplicaRestore, assertGate const browser = await chromium.launch({ headless: true }); const context = await browser.newContext({ - storageState: resolve(root, 'e2e/.auth/alice.json') + storageState: process.env.E2E_RELOAD_STORAGE_STATE || resolve(root, 'e2e/.auth/alice.json') }); await context.addInitScript(() => { globalThis.__distributedReloadEvents = []; From 14988d4569c5c2aea61bc401fa3aefd2039f3735 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 11:04:41 -0500 Subject: [PATCH 067/484] fix: preserve replica state across authorized session refresh Use fresh independent same-scope evidence to restart query transports without clearing the replica or applying an older auth snapshot. Supply route authority during auth refresh and cover token rotation, stale seeds, and rejected authority. Implements [[tasks/gateway-demo-auth-refresh-1]]; resolves [[incidents/gateway-demo-confirmation-flash]]. --- js/README.md | 16 +++- .../impl-hydration-orchestrate.ts | 19 ++++- js/src/replica/distributed-replica/impl.ts | 10 +++ js/src/replica/types.ts | 10 +++ js/src/sveltekit/replica.ts | 58 ++++++++++++-- js/tests/sveltekit-ssr.test.mjs | 75 +++++++++++++++++++ tests/e2e-ui/gateway/refresh.mjs | 69 +++++++++++++++++ tests/e2e-ui/gateway/run.mjs | 8 +- .../lib/components/shared/AuthRefresh.svelte | 18 ++++- tests/e2e-ui/ui/src/lib/server/distributed.ts | 25 +++++++ tests/e2e-ui/ui/src/routes/+layout.server.ts | 24 +----- tests/e2e-ui/ui/src/routes/+layout.svelte | 24 +++--- .../ui/src/routes/api/auth/refresh/+server.ts | 46 +++++++++++- tests/gateway-auth/provider.mjs | 4 +- 14 files changed, 356 insertions(+), 50 deletions(-) create mode 100644 tests/e2e-ui/gateway/refresh.mjs create mode 100644 tests/e2e-ui/ui/src/lib/server/distributed.ts diff --git a/js/README.md b/js/README.md index ba10e2f35..ff30b5e97 100644 --- a/js/README.md +++ b/js/README.md @@ -355,8 +355,20 @@ once. Components do not generate IDs or maintain optimistic/cache recipes. `@load` results are normalized on the server, dehydrated, and restored in the browser without a duplicate first request. Hydration cannot authorize itself: the server sends a separate authority value, and the adapter requires both -values to match. Session, token, tenant, or role changes abort HTTP and live -work, discard the old generation, and reconnect under server-issued scope. +values to match. Credential changes abort old HTTP and live work. Without fresh +server evidence, they also discard the old generation. A refreshed credential +received together with a new authorized seed for the exact active scope can +keep the warm replica and pending optimism. The seed proves authorization; +its data does not overwrite newer local command results or freshness floors. +`createPageDataSessionSource` +provides that transfer automatically; custom session sources can supply +`getHydration()` alongside `getAuth()`. Never derive this authority from a JWT +or reuse an old transfer. Logout, changed scopes, and invalid hydration still +purge the generation. + +The sample auth refresh endpoint returns an authorized seed for the current +route before invalidating SvelteKit page data. Ordinary SPA navigation still +skips server GraphQL work. Confirmed records and indexes under an active scope stay until auth/scope change, stale+revalidate, or a newer authoritative write. Same-scope soft diff --git a/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts b/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts index c8801b432..e21655d36 100644 --- a/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts +++ b/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts @@ -84,6 +84,7 @@ export type HydrationHost = { closeActiveTransports(): void; closeAuthorizationGeneration(): void; resumeLiveWatches(): void; + refreshWatches(): void; syncDiagnostics(): void; diagnosticEvent(event: ReplicaDiagnosticEventInput): void; refreshIndexMaintenance(): void; @@ -315,7 +316,8 @@ export function dehydrateReplica(host: HydrationHost): ReplicaDehydratedState { export function hydrateReplica( host: HydrationHost, state: ReplicaDehydratedState, - authoritativeScope: ReplicaAuthoritativeScope + authoritativeScope: ReplicaAuthoritativeScope, + mode: 'merge' | 'reauthorize' = 'merge' ): boolean { const rejected = ( reason: @@ -366,6 +368,9 @@ export function hydrateReplica( ) { return rejected('active-scope-mismatch'); } + if (mode === 'reauthorize' && current === undefined) { + return rejected('active-scope-mismatch'); + } const preserveLocalCommandState = current !== undefined; // Validate the private engine payload before closing transports or changing @@ -398,6 +403,18 @@ export function hydrateReplica( return rejected('metadata-mismatch'); } + if (mode === 'reauthorize') { + // The independent scope authorizes continued use of the current replica. + // The accompanying snapshot may predate an intervening command: do not + // merge its records, clocks, indexes, or freshness evidence into that state. + host.closeActiveTransports(); + host.queryStates.clear(); + host.resumeLiveWatches(); + host.refreshWatches(); + host.syncDiagnostics(); + return true; + } + if (preserveLocalCommandState) { // Warm same-scope re-hydrate (soft nav / second SSR seed): keep confirmed // records and indexes the route seed omitted. Seed keys upsert; purge only diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index 7641babb2..83024fefa 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -556,6 +556,9 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { closeActiveTransports: () => self.#closeActiveTransports(), closeAuthorizationGeneration: () => self.#closeAuthorizationGeneration(), resumeLiveWatches: () => self.#resumeLiveWatches(), + refreshWatches: () => { + for (const key of self.#watches.keys()) self.#emitState(key, true); + }, syncDiagnostics: () => self.#syncDiagnostics(), diagnosticEvent: (event) => self.#diagnosticEvent(event), refreshIndexMaintenance: () => self.#refreshIndexMaintenance(), @@ -1010,6 +1013,13 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { return hydrateReplica(this.#hydrationHost(), state, authoritativeScope); } + reauthorize( + state: ReplicaDehydratedState, + authoritativeScope: ReplicaAuthoritativeScope + ): boolean { + return hydrateReplica(this.#hydrationHost(), state, authoritativeScope, 'reauthorize'); + } + #bindArtifact( artifact: ReplicaOperationArtifact ): void { diff --git a/js/src/replica/types.ts b/js/src/replica/types.ts index ac2058b92..b39705c44 100644 --- a/js/src/replica/types.ts +++ b/js/src/replica/types.ts @@ -898,6 +898,16 @@ export interface DistributedReplica { state: ReplicaDehydratedState, authoritativeScope: ReplicaAuthoritativeScope ): boolean; + /** + * Validate a fresh transfer against independent server authority and the + * exact active scope, then restart query/live transports without applying + * the transfer's potentially older data. Preserves command/freshness state. + * Returns false without mutating state when validation fails. + */ + reauthorize( + state: ReplicaDehydratedState, + authoritativeScope: ReplicaAuthoritativeScope + ): boolean; createOptimisticLayer( id: string, update: (writer: ReplicaOptimisticWriter) => void, diff --git a/js/src/sveltekit/replica.ts b/js/src/sveltekit/replica.ts index cdc51bbcd..caf785cb4 100644 --- a/js/src/sveltekit/replica.ts +++ b/js/src/sveltekit/replica.ts @@ -46,9 +46,20 @@ import { type UnknownCommandEntries = Readonly>; +type SessionHydration = Readonly<{ + hydration: SveltekitReplicaHydration; + authority: SveltekitReplicaAuthority; +}>; + export type SveltekitSessionSource = Readonly<{ /** Current credential. HTTP, WS, and commands all call this exact source. */ getAuth(): GqlAuth | Promise; + /** + * Fresh server page data received together with the current credential. + * Only independently authorized, same-scope hydration permits reuse during + * credential rotation. Never synthesize this from a token or cached state. + */ + getHydration?(): SessionHydration | undefined; /** * Notify on token, logout, role, tenant, or session changes. * @@ -317,7 +328,21 @@ export function createDistributedSvelteKit { + const active = replica?.scope; + if ( + active === undefined || + !sameReplicaScope(active, validatedHydrationAuthority(transfer.authority)) + ) return false; + if ((transfer.hydration.bindings ?? []).some(value => !boundaryIds.includes(value))) { + return false; + } + return transfer.hydration.version === 1 && replica!.reauthorize( + transfer.hydration.state, + validatedHydrationAuthority(transfer.authority) + ); + } ); const configuredUrl = options.url; const transport = createReplicaGraphqlTransport({ @@ -565,6 +590,12 @@ export function sessionSourceFromPageData( } return Object.freeze({ getAuth: () => authFromPageData(source.get()), + getHydration: () => { + const data: SveltekitDistributedPageData = source.get(); + return data.distributed === undefined || data.distributedAuthority === undefined + ? undefined + : { hydration: data.distributed, authority: data.distributedAuthority }; + }, ...(source.subscribe === undefined ? {} : { subscribe: source.subscribe.bind(source) }) @@ -998,23 +1029,40 @@ function sameQuerySnapshot( function createAuthorizationFence( source: SveltekitSessionSource, invalidate: () => void, - onError: ((error: unknown) => void) | undefined + onError: ((error: unknown) => void) | undefined, + refresh: (transfer: SessionHydration) => boolean ): Readonly<{ read(): Promise; dispose(): void }> { let current: Readonly | undefined; + const seenHydrations = new WeakSet(); + const seenAuthorities = new WeakSet(); let queue = Promise.resolve(); let disposed = false; const read = (): Promise => { - const candidate = Promise.resolve().then(() => source.getAuth()); + const candidate = Promise.resolve().then(() => { + // Capture the credential and its independent server transfer together, + // before another source notification can replace either value. + const credential = source.getAuth(); + const transfer = source.getHydration?.(); + return Promise.resolve(credential).then((auth) => ({ auth, transfer })); + }); const transition = queue.then(async () => { try { - const next = snapshotAuthCredential(await candidate); + const { auth, transfer } = await candidate; + const next = snapshotAuthCredential(auth); if ( current !== undefined && !sameAuthCredential(current, next) ) { - invalidate(); + const freshTransfer = transfer !== undefined && + !seenHydrations.has(transfer.hydration) && + !seenAuthorities.has(transfer.authority); + if (!freshTransfer || !refresh(transfer)) invalidate(); } current = next; + if (transfer !== undefined) { + seenHydrations.add(transfer.hydration); + seenAuthorities.add(transfer.authority); + } return next; } catch (error) { current = undefined; diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index d98316f42..2bde3a62e 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -4,6 +4,7 @@ import test from 'node:test'; import { createDistributedSvelteKit, + createPageDataSessionSource, createDistributedSvelteKitServer, defineDistributedBoundaryBinding, defineDistributedBoundaryOperation @@ -11,6 +12,7 @@ import { import { REACT_FIXTURE_SCHEMA, TodosArtifact, + TodoModel, todoFrame } from './fixtures/adapter-conformance.mjs'; @@ -507,3 +509,76 @@ test('lazy command authority preserves isolated SSR hydration and query prefetch clients.forEach(client=>client.destroy()); await assert.rejects(clients[0].preloadCommands(),/destroyed/); }); + + +test('fresh same-scope SSR authority rotates credentials without emptying the visible replica', async () => { + const harness = serverHarness(); + const first = await harness.server.load(harness.event('alice', '1')); + const second = await harness.server.load(harness.event('alice', '2')); + const pageData = createPageDataSessionSource(first); + const requests = []; + SsrWebSocket.instances.length = 0; + const client = createDistributedSvelteKit({ + boundaries: [todosBoundary], session: pageData.session, + hydration: first.distributed, authority: first.distributedAuthority, + fetch: (url, init) => new Promise(resolve => requests.push({init, resolve})), + webSocket: SsrWebSocket + }); + const todos = client.operation(TodosArtifact).use(); + const values = []; + const unsubscribe = todos.subscribe(snapshot => values.push(snapshot.data.todos?.[0]?.title)); + await flushMicrotasks(); + const oldSocket = SsrWebSocket.instances[0]; + const oldRequest = todos.refetch(); + await flushMicrotasks(); + assert.equal(requests.length, 1); + client.replica.writeResult(TodosArtifact, {}, todoFrame(TodosArtifact, [{id:'todo-alice', title:'confirmed ahead', status:'open'}], {cacheScope:'cache:alice', position:'3'}), 'network'); + client.replica.createOptimisticLayer('pending-edit', writer => writer.writeRecord(TodoModel, 'todo-alice', {fields:{title:'optimistic edit'}})); + pageData.set({...second, accessToken: 'rotated-alice'}); + await flushMicrotasks(); + assert.ok(values.every(value => value === 'alice:1' || value === 'confirmed ahead' || value === 'optimistic edit'), JSON.stringify(values)); + assert.equal(todos.get().data.todos[0].title, 'optimistic edit'); + assert.equal(requests[0].init.signal.aborted, true); + assert.equal(oldSocket.closed, true); + assert.equal(requests.length, 1, 'fresh SSR data needs no replacement browser query'); + const nextSocket = SsrWebSocket.instances.at(-1); + assert.notEqual(nextSocket, oldSocket); + nextSocket.open(); + await flushMicrotasks(); + assert.equal(nextSocket.sent[0].payload.authorization, 'Bearer rotated-alice'); + requests[0].resolve(jsonResponse(todoFrame(TodosArtifact, [{id:'todo-alice',title:'late old credential',status:'open'}], {cacheScope:'cache:alice',position:'3'}))); + await oldRequest; + assert.equal(todos.get().data.todos[0].title, 'optimistic edit', 'closed credential work cannot overwrite the new seed'); + client.replica.rejectOptimisticLayer('pending-edit'); + assert.equal(todos.get().data.todos[0].title, 'confirmed ahead', 'the refresh seed cannot overwrite a newer confirmed command result'); + unsubscribe(); client.destroy(); +}); + +for (const kind of ['missing', 'replayed', 'historical', 'tampered', 'different-scope', 'logout']) { + test(`credential change with ${kind} hydration still purges the old replica`, async () => { + const harness = serverHarness(); + const first = await harness.server.load(harness.event('alice')); + const second = await harness.server.load(harness.event(kind === 'different-scope' ? 'bob' : 'alice', '2')); + const pageData = createPageDataSessionSource(first); + const client = createDistributedSvelteKit({ + boundaries: [todosBoundary], session: pageData.session, + hydration: first.distributed, authority: first.distributedAuthority, + fetch: () => new Promise(() => {}), webSocket: SsrWebSocket + }); + const todos = client.operation(TodosArtifact).use({}, {live:false}); + const unsubscribe = todos.subscribe(() => {}); + await flushMicrotasks(); + let next = {...second, accessToken:'new-credential'}; + if(kind === 'missing') {delete next.distributed;delete next.distributedAuthority;} + if(kind === 'historical') {pageData.set({...first, distributed:undefined, distributedAuthority:undefined});await flushMicrotasks();} + if(kind === 'replayed' || kind === 'historical') next = {...first, accessToken:'new-credential'}; + if(kind === 'tampered') {next.distributed = structuredClone(next.distributed);next.distributed.state.scope.cacheScope = 'cache:forged';} + if(kind === 'logout') next = {session:null}; + pageData.set(next); + await flushMicrotasks(); + assert.equal(todos.get().complete, false); + assert.deepEqual(todos.get().data, {}); + assert.equal(client.replica.scope, undefined); + unsubscribe(); client.destroy(); + }); +} diff --git a/tests/e2e-ui/gateway/refresh.mjs b/tests/e2e-ui/gateway/refresh.mjs new file mode 100644 index 000000000..ca778b6c8 --- /dev/null +++ b/tests/e2e-ui/gateway/refresh.mjs @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import {expect} from '../../gateway-auth/node_modules/@playwright/test/index.mjs'; + +// Exercise actual background OIDC rotation, including the route seed and the +// follow-up SvelteKit invalidation. A final DOM assertion alone misses a flash. +export async function verifySessionRefreshContinuity(page, origin) { + for (const [route, selector] of [['todos', '[data-todo-id]'], ['chat', '.ch-msg-block']]) { + await page.goto(origin+'/'+route); + await expect(page.locator(selector).first()).toBeVisible(); + await page.waitForFunction(()=>globalThis.__distributedReloadState!==undefined); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); + const navigations=[]; + const request=r=>{if(r.isNavigationRequest())navigations.push(r.url());}; + page.on('request',request); + await page.evaluate(selector=>{ + const rows=[...document.querySelectorAll(selector)]; + globalThis.__refreshContinuity={lost:false,events:[],rows,observer:new MutationObserver(records=>{ + if(rows.some(row=>!row.isConnected)||records.some(record=>[...record.removedNodes].some(node=>rows.some(row=>node===row||node.contains(row))))){globalThis.__refreshContinuity.lost=true;globalThis.__refreshContinuity.events.push({time:performance.now(),remaining:rows.filter(row=>row.isConnected).length});} + })}; + globalThis.__refreshContinuity.observer.observe(document.body,{childList:true,subtree:true}); + },selector); + let releaseRefresh, seedArrived; + const release = new Promise(resolve=>releaseRefresh=resolve); + const seed = new Promise(resolve=>seedArrived=resolve); + let hold = route==='todos'; + const refreshRoute = async request=>{ + if(!hold)return request.continue(); + hold=false; + const response=await request.fetch(); + seedArrived();await release;await request.fulfill({response}); + }; + await page.route('**/api/auth/refresh',refreshRoute); + try { + for(let rotation=0;rotation<2;rotation++) { + const responses = Promise.all([ + page.waitForResponse(r=>r.url()===origin+'/api/auth/refresh'&&r.request().method()==='POST',{timeout:20000}), + page.waitForResponse(r=>r.url().includes('/'+route+'/__data.json'),{timeout:20000}) + ]); + if(route==='todos'&&rotation===0) { + await seed; + // The auth snapshot is now old: confirm a command before delivering it. + const title='confirmed after auth snapshot '+Date.now(); + await page.locator('#todo-title').fill(title); + await page.getByRole('button',{name:/^add$/i}).click(); + const todo=page.locator('[data-todo-id]').filter({hasText:title}); + await expect(todo).toBeVisible(); + await expect(todo.locator('.pending-state')).toHaveCount(0); + await todo.evaluate(row=>globalThis.__refreshContinuity.rows.push(row)); + releaseRefresh(); + } + const [refresh, data] = await responses; + assert.equal(refresh.status(),200); + const refreshed = await refresh.json(); + assert.ok(refreshed.pageData?.distributedAuthority); + assert.ok((await data.text()).includes(refreshed.pageData.accessToken), 'the follow-up page request unexpectedly rotated the credential a second time'); + assert.equal(data.status(),200); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); + } + assert.deepEqual(navigations,[],'session refresh must not navigate the document'); + assert.equal(await page.evaluate(()=>globalThis.__refreshContinuity.lost),false,route+' rows were removed during token refresh: '+JSON.stringify(await page.evaluate(()=>globalThis.__refreshContinuity.events))); + } finally { + releaseRefresh(); + await page.unroute('**/api/auth/refresh',refreshRoute); + page.off('request',request); + await page.evaluate(()=>globalThis.__refreshContinuity?.observer.disconnect()); + } + } + console.log('PASS Todo and Chat retain DOM rows through OIDC rotation and a late auth snapshot'); +} diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 7d57c1a6f..92b693963 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -9,6 +9,7 @@ import {fileURLToPath} from 'node:url'; import {randomBytes} from 'node:crypto'; import {chromium,expect} from '../../gateway-auth/node_modules/@playwright/test/index.mjs'; import {startProvider} from '../../gateway-auth/provider.mjs'; +import {verifySessionRefreshContinuity} from './refresh.mjs'; const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); const devMode=process.env.GATEWAY_DEV==='1'; const environment={PATH:process.env.PATH,HOME:process.env.HOME,RUSTUP_TOOLCHAIN:process.env.RUSTUP_TOOLCHAIN||'stable',NODE_ENV:'production'}; @@ -31,7 +32,7 @@ try{ for(const delivery of (process.env.GATEWAY_LIFECYCLE==='1'?['none']:['none','all'])){ const apiPort=await freePort(),uiPort=await freePort(),issuer=`http://127.0.0.1:${await freePort()}`; const publicOrigin=`http://127.0.0.1:${apiPort}`; - const idp=await startProvider(issuer,publicOrigin,{jwtAudience:'gateway-fixture'}); + const idp=await startProvider(issuer,publicOrigin,{jwtAudience:'gateway-fixture',accessTokenTtl:65}); let api,ui,browser; try{ if(devMode){ @@ -78,6 +79,7 @@ try{ await page.goto(publicOrigin+'/blob');await expect(page.getByTestId('blob-start-game')).toBeEnabled();await page.getByTestId('blob-start-game').click();await expect(page.locator('.blob-board')).toBeVisible({timeout:20000}); await verifyBlobRace(page); await verifyLiveRace(page,publicOrigin); + await verifySessionRefreshContinuity(page,publicOrigin); if(process.env.GATEWAY_LIFECYCLE==='1'){ assert.ok(devMode,'full reload proof requires the CLI dev host'); const storage=path.join(temporary,'reload-auth.json');await context.storageState({path:storage}); @@ -133,10 +135,10 @@ async function verifyBlobRace(page){ async function verifyAuth(context,idp,origin){ const cookies=(await context.cookies()).filter(cookie=>cookie.name.startsWith('authjs.session-token')); assert.ok(cookies.length&&cookies.every(cookie=>cookie.httpOnly&&cookie.sameSite==='Lax'&&cookie.path==='/')); - await new Promise(resolve=>setTimeout(resolve,2200)); + await new Promise(resolve=>setTimeout(resolve,6000)); const response=await context.request.post(origin+'/api/auth/refresh',{headers:{origin}}); assert.equal(response.status(),200);assert.equal((await response.json()).authenticated,true);assert.ok(idp.refreshes()>0); - idp.failRefresh();await new Promise(resolve=>setTimeout(resolve,2200)); + idp.failRefresh();await new Promise(resolve=>setTimeout(resolve,6000)); const failed=await context.request.post(origin+'/api/auth/refresh',{headers:{origin}}); assert.equal(failed.status(),401);assert.equal((await failed.json()).error,'RefreshAccessTokenError'); const denied=await context.request.get(origin+'/todos',{maxRedirects:0});assert.equal(denied.status(),303); diff --git a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte index 274b05be8..0f32da8b8 100644 --- a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte +++ b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte @@ -2,6 +2,9 @@ import { browser } from '$app/environment'; import { invalidateAll } from '$app/navigation'; import { page } from '$app/state'; + import type { SveltekitDistributedPageData } from '@hops-ops/distributed/sveltekit'; + + let { onRefresh }: { onRefresh: (data: SveltekitDistributedPageData) => void } = $props(); const MIN_REFRESH_DELAY_MS = 5_000; const RETRY_DELAY_MS = 30_000; @@ -23,10 +26,21 @@ method: 'POST', credentials: 'same-origin', headers: { - accept: 'application/json' - } + accept: 'application/json', + 'content-type': 'application/json' + }, + body: JSON.stringify({ + id: page.route.id, + path: page.url.pathname + page.url.search, + params: page.params + }) }); + if (response.ok) { + const result = await response.json(); + if (result.pageData) onRefresh(result.pageData); + } + if (response.ok || response.status === 401) { await invalidateAll(); return; diff --git a/tests/e2e-ui/ui/src/lib/server/distributed.ts b/tests/e2e-ui/ui/src/lib/server/distributed.ts new file mode 100644 index 000000000..a29285b6c --- /dev/null +++ b/tests/e2e-ui/ui/src/lib/server/distributed.ts @@ -0,0 +1,25 @@ +import { + createDistributedSvelteKitServer, + type SveltekitServerLoadEventLike +} from '@hops-ops/distributed/sveltekit'; + +import { DISTRIBUTED_BOUNDARY_OPERATIONS } from '$distributed'; +import { engineRoleFromGroups } from '$lib/roles'; +import { graphqlHttpUrl } from '$lib/server/graphql'; + +type LoadEvent = SveltekitServerLoadEventLike; +type Session = NonNullable< + Awaited> +>; + +/** + * One root loader owns every compiler-discovered user-safe `@load` operation. + * A fresh replica is created per request and no GraphQL work runs for routes + * absent from the generated registry. + */ +export const distributed = createDistributedSvelteKitServer({ + boundaries: DISTRIBUTED_BOUNDARY_OPERATIONS, + getSession: (event) => event.locals.auth(), + getRole: (session) => engineRoleFromGroups(session?.user?.groups), + getUrl: graphqlHttpUrl +}); diff --git a/tests/e2e-ui/ui/src/routes/+layout.server.ts b/tests/e2e-ui/ui/src/routes/+layout.server.ts index 524e8d8ed..12995514b 100644 --- a/tests/e2e-ui/ui/src/routes/+layout.server.ts +++ b/tests/e2e-ui/ui/src/routes/+layout.server.ts @@ -1,28 +1,6 @@ -import { createDistributedSvelteKitServer } from '@hops-ops/distributed/sveltekit'; - -import { DISTRIBUTED_BOUNDARY_OPERATIONS } from '$distributed'; -import { engineRoleFromGroups } from '$lib/roles'; -import { graphqlHttpUrl } from '$lib/server/graphql'; - +import { distributed } from '$lib/server/distributed'; import type { LayoutServerLoad } from './$types'; -type LoadEvent = Parameters[0]; -type Session = NonNullable< - Awaited> ->; - -/** - * One root loader owns every compiler-discovered user-safe `@load` operation. - * A fresh replica is created per request and no GraphQL work runs for routes - * absent from the generated registry. - */ -const distributed = createDistributedSvelteKitServer({ - boundaries: DISTRIBUTED_BOUNDARY_OPERATIONS, - getSession: (event) => event.locals.auth(), - getRole: (session) => engineRoleFromGroups(session?.user?.groups), - getUrl: graphqlHttpUrl -}); - /** * Unauthenticated traffic skips the portable user GraphQL surface (no Bearer / * empty identity cannot open e2e-ui). Lobby chat SSR uses the nested public diff --git a/tests/e2e-ui/ui/src/routes/+layout.svelte b/tests/e2e-ui/ui/src/routes/+layout.svelte index bcb6ce59d..e8425bb0a 100644 --- a/tests/e2e-ui/ui/src/routes/+layout.svelte +++ b/tests/e2e-ui/ui/src/routes/+layout.svelte @@ -7,6 +7,7 @@ import type { Snippet } from 'svelte'; import { createPageDataSessionSource, + type SveltekitDistributedPageData, type SveltekitReplicaHydration } from '@hops-ops/distributed/sveltekit'; import { DISTRIBUTED_BOUNDARY_OPERATIONS, provideDistributed } from '$distributed'; @@ -19,7 +20,7 @@ let { data, children }: { data: LayoutData; children: Snippet } = $props(); const initialData = untrack(() => data); - const pageData = createPageDataSessionSource(initialData); + const pageData = createPageDataSessionSource(initialData); let appliedHydration: SveltekitReplicaHydration | undefined = initialData.distributed; let hydrationTimer: ReturnType | undefined; @@ -59,17 +60,17 @@ : {}) }); - $effect(() => { - pageData.set(data); + function applyPageData(next: SveltekitDistributedPageData) { + pageData.set(next); if ( - data.distributed === undefined || - data.distributedAuthority === undefined || - data.distributed === appliedHydration + next.distributed === undefined || + next.distributedAuthority === undefined || + next.distributed === appliedHydration ) { return; } - appliedHydration = data.distributed; + appliedHydration = next.distributed; if (hydrationTimer !== undefined) clearTimeout(hydrationTimer); // Session listeners fence an old credential in the microtask queue. // Apply the separately-authorized navigation seed after that fence. @@ -77,9 +78,11 @@ // confirmed keys omitted from this route seed are retained. hydrationTimer = setTimeout(() => { hydrationTimer = undefined; - client.hydrate(data.distributed!, data.distributedAuthority!); + client.hydrate(next.distributed!, next.distributedAuthority!); }, 0); - }); + } + + $effect(() => applyPageData(data)); $effect(() => { if (!browser || !data.session?.user) return; @@ -121,7 +124,8 @@ - + + pageData.set(next)} />
{@render children()} diff --git a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts index 8df2ffd75..a9c0f9d29 100644 --- a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts +++ b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts @@ -1,15 +1,57 @@ import { json } from '@sveltejs/kit'; +import { distributed } from '$lib/server/distributed'; import { isCurrentSession } from '$lib/server/require-auth'; import type { RequestHandler } from './$types'; -export const POST: RequestHandler = async ({ locals }) => { +export const POST: RequestHandler = async (event) => { + const { locals } = event; const session = await locals.auth(); if (!isCurrentSession(session)) { return json({ authenticated: false, error: session?.error }, { status: 401 }); } + // A refresh may change the bearer credential without changing effective + // permissions. Supply a new, independently authorized route seed so the + // browser can prove same-scope reuse before fencing the old credential. + // Route selection is input, never authority: the generated user surface + // and GraphQL executor still authorize every selected operation. + let pageData; + if (event.request.headers.get('content-type')?.includes('application/json')) { + let route; + try { + route = await event.request.json(); + } catch { + return json({ error: 'Invalid route' }, { status: 400 }); + } + if ( + typeof route?.id !== 'string' || + typeof route?.path !== 'string' || + !route.path.startsWith('/') || + route.path.startsWith('//') || + route.params === null || + typeof route.params !== 'object' || + Array.isArray(route.params) || + Object.values(route.params).some(value => typeof value !== 'string') + ) { + return json({ error: 'Invalid route' }, { status: 400 }); + } + const url = new URL(route.path, event.url.origin); + if (url.origin !== event.url.origin) { + return json({ error: 'Invalid route' }, { status: 400 }); + } + pageData = await distributed.load({ + ...event, + locals: { ...locals, auth: async () => session }, + isDataRequest: false, + url, + route: { id: route.id }, + params: route.params + }); + } + return json({ + pageData, authenticated: true, expires: session.expires, expiresAt: session.expiresAt, @@ -18,5 +60,5 @@ export const POST: RequestHandler = async ({ locals }) => { hasRefreshToken: session.hasRefreshToken, hasIdToken: session.hasIdToken, error: session.error - }); + }, { headers: { 'cache-control': 'no-store' } }); }; diff --git a/tests/gateway-auth/provider.mjs b/tests/gateway-auth/provider.mjs index 0499fd77f..fbde813f7 100644 --- a/tests/gateway-auth/provider.mjs +++ b/tests/gateway-auth/provider.mjs @@ -4,7 +4,7 @@ import { once } from 'node:events'; import { randomBytes } from 'node:crypto'; // An isolated, in-memory standards implementation. No external IdP or secrets. -export async function startProvider(issuer, publicOrigin, { jwtAudience } = {}) { +export async function startProvider(issuer, publicOrigin, { jwtAudience, accessTokenTtl = 61 } = {}) { let refreshes = 0; let failRefresh = false; const provider = new Provider(issuer, { @@ -23,7 +23,7 @@ export async function startProvider(issuer, publicOrigin, { jwtAudience } = {}) extraTokenClaims:()=>({roles:['user']}), scopes:['openid','profile','email','offline_access','urn:zitadel:iam:org:project:roles','urn:zitadel:iam:org:projects:roles',`urn:zitadel:iam:org:project:id:${jwtAudience}:aud`,`urn:zitadel:iam:org:project:id:${jwtAudience}:roles`], } : {}), - ttl: { AccessToken: 61 }, + ttl: { AccessToken: accessTokenTtl }, async issueRefreshToken() { return true; }, claims: { openid: ['sub'], profile: ['name', ...(jwtAudience?['roles']:[])], email: ['email'] }, async findAccount(_ctx, id) { From ff63c1cebaf8a1ccdb2a2207834667552921e7d8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 7 Sep 2026 11:25:56 -0500 Subject: [PATCH 068/484] fix: decouple auth fixtures from application route loaders Share the real session refresh handler with an optional page-data loader so native and Worker auth fixtures build without generated GraphQL clients. Keep browser continuity and stale-snapshot assertions without reading a discarded Chromium response body. Implements [[tasks/gateway-auth-refresh-ci-1]]; resolves [[incidents/pr-228-auth-refresh-ci]]. --- tests/e2e-ui/gateway/refresh.mjs | 1 - .../e2e-ui/ui/src/lib/server/auth-refresh.ts | 28 ++++++++++++++ .../ui/src/routes/api/auth/refresh/+server.ts | 37 +++++-------------- tests/gateway-auth/prepare.mjs | 11 ++++-- 4 files changed, 44 insertions(+), 33 deletions(-) create mode 100644 tests/e2e-ui/ui/src/lib/server/auth-refresh.ts diff --git a/tests/e2e-ui/gateway/refresh.mjs b/tests/e2e-ui/gateway/refresh.mjs index ca778b6c8..cdab9ca85 100644 --- a/tests/e2e-ui/gateway/refresh.mjs +++ b/tests/e2e-ui/gateway/refresh.mjs @@ -52,7 +52,6 @@ export async function verifySessionRefreshContinuity(page, origin) { assert.equal(refresh.status(),200); const refreshed = await refresh.json(); assert.ok(refreshed.pageData?.distributedAuthority); - assert.ok((await data.text()).includes(refreshed.pageData.accessToken), 'the follow-up page request unexpectedly rotated the credential a second time'); assert.equal(data.status(),200); await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); } diff --git a/tests/e2e-ui/ui/src/lib/server/auth-refresh.ts b/tests/e2e-ui/ui/src/lib/server/auth-refresh.ts new file mode 100644 index 000000000..e0e393a32 --- /dev/null +++ b/tests/e2e-ui/ui/src/lib/server/auth-refresh.ts @@ -0,0 +1,28 @@ +import { json, type RequestEvent, type RequestHandler } from '@sveltejs/kit'; +import { isCurrentSession } from '$lib/server/require-auth'; + +type CurrentSession = NonNullable>>; +type PageDataLoader = (event: RequestEvent, session: CurrentSession) => Promise; + +/** Share auth refresh independently of an application's optional GraphQL loader. */ +export function createAuthRefreshHandler(loadPageData?: PageDataLoader): RequestHandler { + return async (event) => { + const session = await event.locals.auth(); + if (!isCurrentSession(session)) { + return json({ authenticated: false, error: session?.error }, { status: 401 }); + } + + const pageData = await loadPageData?.(event, session); + return json({ + pageData, + authenticated: true, + expires: session.expires, + expiresAt: session.expiresAt, + refreshAfter: session.refreshAfter, + hasAccessToken: session.hasAccessToken, + hasRefreshToken: session.hasRefreshToken, + hasIdToken: session.hasIdToken, + error: session.error + }, { headers: { 'cache-control': 'no-store' } }); + }; +} diff --git a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts index a9c0f9d29..539993895 100644 --- a/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts +++ b/tests/e2e-ui/ui/src/routes/api/auth/refresh/+server.ts @@ -1,28 +1,21 @@ -import { json } from '@sveltejs/kit'; +import { error } from '@sveltejs/kit'; import { distributed } from '$lib/server/distributed'; -import { isCurrentSession } from '$lib/server/require-auth'; -import type { RequestHandler } from './$types'; +import { createAuthRefreshHandler } from '$lib/server/auth-refresh'; -export const POST: RequestHandler = async (event) => { +export const POST = createAuthRefreshHandler(async (event, session) => { const { locals } = event; - const session = await locals.auth(); - - if (!isCurrentSession(session)) { - return json({ authenticated: false, error: session?.error }, { status: 401 }); - } - // A refresh may change the bearer credential without changing effective // permissions. Supply a new, independently authorized route seed so the // browser can prove same-scope reuse before fencing the old credential. // Route selection is input, never authority: the generated user surface // and GraphQL executor still authorize every selected operation. - let pageData; + if (event.request.headers.get('content-type')?.includes('application/json')) { let route; try { route = await event.request.json(); } catch { - return json({ error: 'Invalid route' }, { status: 400 }); + error(400, 'Invalid route'); } if ( typeof route?.id !== 'string' || @@ -34,13 +27,13 @@ export const POST: RequestHandler = async (event) => { Array.isArray(route.params) || Object.values(route.params).some(value => typeof value !== 'string') ) { - return json({ error: 'Invalid route' }, { status: 400 }); + error(400, 'Invalid route'); } const url = new URL(route.path, event.url.origin); if (url.origin !== event.url.origin) { - return json({ error: 'Invalid route' }, { status: 400 }); + error(400, 'Invalid route'); } - pageData = await distributed.load({ + return distributed.load({ ...event, locals: { ...locals, auth: async () => session }, isDataRequest: false, @@ -49,16 +42,4 @@ export const POST: RequestHandler = async (event) => { params: route.params }); } - - return json({ - pageData, - authenticated: true, - expires: session.expires, - expiresAt: session.expiresAt, - refreshAfter: session.refreshAfter, - hasAccessToken: session.hasAccessToken, - hasRefreshToken: session.hasRefreshToken, - hasIdToken: session.hasIdToken, - error: session.error - }, { headers: { 'cache-control': 'no-store' } }); -}; +}); diff --git a/tests/gateway-auth/prepare.mjs b/tests/gateway-auth/prepare.mjs index a333901b0..0ae773a59 100644 --- a/tests/gateway-auth/prepare.mjs +++ b/tests/gateway-auth/prepare.mjs @@ -1,9 +1,12 @@ -import { mkdir, copyFile } from 'node:fs/promises'; -// Exercise the app's actual Auth.js configuration and refresh handler. -for (const file of ['auth.ts', 'lib/clean-env.ts', 'lib/roles.ts', 'lib/server/oidc-scopes.ts', 'lib/server/oidc-start.ts', 'lib/server/require-auth.ts']) { +import { mkdir, copyFile, writeFile } from 'node:fs/promises'; +// Exercise the app's actual Auth.js configuration and shared refresh handler. +// This auth-only composition does not bind an application GraphQL route loader. +for (const file of ['auth.ts', 'lib/clean-env.ts', 'lib/roles.ts', 'lib/server/oidc-scopes.ts', 'lib/server/oidc-start.ts', 'lib/server/require-auth.ts', 'lib/server/auth-refresh.ts']) { const target = `.generated/${file}`; await mkdir(target.substring(0, target.lastIndexOf('/')), { recursive: true }); await copyFile(`../e2e-ui/ui/src/${file}`, target); } await mkdir('src/routes/api/auth/refresh', { recursive: true }); -await copyFile('../e2e-ui/ui/src/routes/api/auth/refresh/+server.ts', '.generated/refresh.ts'); +await writeFile('.generated/refresh.ts', `import { createAuthRefreshHandler } from '$lib/server/auth-refresh'; +export const POST = createAuthRefreshHandler(); +`); From fdc0a795c3d1066c9abf59022136c5a11f2fb65a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 8 Sep 2026 23:25:20 -0500 Subject: [PATCH 069/484] fix: reconcile gateway with v5 protocol changes Keep protocol preparation errors visible within the engine and update the byte-exact unique-key artifact with its emitted protocol hash. No assertions or authorization checks are relaxed. --- distributed_cli/tests/fixtures/unique-key-bridge-operation.json | 1 + src/graphql/engine/request.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/distributed_cli/tests/fixtures/unique-key-bridge-operation.json b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json index a6d76f052..9de33c538 100644 --- a/distributed_cli/tests/fixtures/unique-key-bridge-operation.json +++ b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json @@ -318,6 +318,7 @@ "protocol": { "version": 1, "schemaHash": "sha256:d43d65b233d9839f28271b4bdee7326f03b660cac3002013d8f058204e188415", + "protocolHash": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", "surface": { "kind": "role", "name": "user" diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index af9f34f0b..e8d3c2e77 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -1,6 +1,6 @@ use super::*; -enum ProtocolPreparationError { +pub(super) enum ProtocolPreparationError { RequiredPreset, Internal, } From d2135c735434b631587fc1991c807285d1d87531 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 02:55:38 -0500 Subject: [PATCH 070/484] fix!: keep authorized snapshot live queries subscribed Separate snapshot delivery from resumable projection evidence. Preserve authorization, source fencing, and SSR hydration invariants. BREAKING CHANGE: live.mode replaces live.supported; upgrade server and client together. Implements [[tasks/distributed-private-live-snapshots]] --- README.md | 4 + docs/gateway/live-sharing.md | 6 +- docs/live-query-delivery.md | 28 ++++ js/README.md | 6 + js/src/protocol.ts | 16 +- js/src/replica/distributed-replica/clocks.ts | 2 +- .../distributed-replica/impl-fetch-live.ts | 34 +--- js/src/replica/distributed-replica/impl.ts | 57 +++---- js/tests/fixtures/adapter-conformance.mjs | 11 +- js/tests/fixtures/unique-key-artifact.mjs | 2 +- js/tests/protocol-transport.test.mjs | 34 +++- js/tests/replica-protocol.test.mjs | 155 +++++++++++++----- js/tests/replica-result-observation.test.mjs | 2 +- js/tests/sveltekit-ssr.test.mjs | 11 +- src/gateway/delivery/live.rs | 2 +- src/gateway/native/live.rs | 2 +- src/graphql/protocol/mod.rs | 6 +- src/graphql/protocol/tests.rs | 4 +- src/graphql/protocol/types.rs | 12 +- src/graphql/query_protocol.rs | 24 ++- src/graphql/subscribe.rs | 2 +- tests/e2e-ui/crates/projections/src/chat.rs | 18 +- tests/edge_query_delivery.rs | 4 +- tests/graphql_query_protocol/main.rs | 61 ++++++- tests/graphql_query_protocol_postgres/main.rs | 4 +- 25 files changed, 353 insertions(+), 154 deletions(-) create mode 100644 docs/live-query-delivery.md diff --git a/README.md b/README.md index 906cdcd10..c555924c2 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ ## How it works +Live queries stream authorized results even when row-level permissions prevent +safe resume cursors. [Snapshot and resumable delivery](docs/live-query-delivery.md) +describe the two modes and their consistency guarantees. + Write the domain once, compose it into one `Service` or several, then generate the client. Each stage below uses real code from [`tests/e2e-ui`](tests/e2e-ui). diff --git a/docs/gateway/live-sharing.md b/docs/gateway/live-sharing.md index 1ef09998d..404f7bf58 100644 --- a/docs/gateway/live-sharing.md +++ b/docs/gateway/live-sharing.md @@ -19,12 +19,16 @@ upstream subscription and producer. HTTP control requests do not execute result Groups bind the exact document, variables, origin subject/cache scope, policy, schema and protocol. Each consumer keeps its own transport ID, expiry, queue and freshness requirements. Different resume cursors start independent replay. Handoff -requires the same operation plus an exact supported, comparable cursor vector and +requires the same operation plus an exact resumable, comparable cursor vector and matching data; the consumer's replay frames remain queued before future shared frames. Unknown cursors keep independent streams. Equal data alone never proves cursor equality. Duplicate suppression hashes the whole data and protocol envelope, so new confirmation evidence is delivered even when values are unchanged. +Cursorless `live.mode = "snapshot"` responses cannot prove shared replay handoff; +they retain independent authorized subscriptions and reconnect with fresh queries. +See [live query delivery](../live-query-delivery.md) for the wire contract. + Defaults bound a coordinator to 256 groups, 1,024 consumers per group, 16 pending frames per consumer, 1 MiB per full frame, eight retained history frames and a one-hour group lifetime. Native ingress bounds socket/request counts and wire diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md new file mode 100644 index 000000000..970b4a4c5 --- /dev/null +++ b/docs/live-query-delivery.md @@ -0,0 +1,28 @@ +# Live queries and authorization + +`@live` keeps an authorized query current. Resuming missed projection changes is +a separate capability: a partition-wide cursor can reveal activity outside a +row-filtered result, even when the rows themselves are protected. + +Every live response declares `extensions.distributed.live.mode`: + +- `snapshot`: a fresh authorized replacement result, with `reset: true` and + `cursors: []`. It carries no comparable index vector or projection observations. + The client keeps listening and reconnects with a fresh query, not a resume token. +- `resumable`: a result with matching, nonempty index and cursor vectors. Existing + resume validation, reset, replay and causal reconciliation rules apply. + +Snapshot delivery does not relax read permissions or invent causal evidence. +Changes affecting only denied rows must not produce activity frames. A row +leaving the authorized result disappears from that operation's membership; +absence is not a globally authoritative deletion or tombstone. + +Within one current subscription, snapshot frames are ordered. The client fences +older HTTP requests when a live result takes ownership, and fences callbacks +from disposed subscriptions and previous authorization generations. Local cache +membership revisions are not server projection positions and cannot confirm +optimistic commands. + +This is a breaking v5 protocol change: `mode` replaces the ambiguous `supported` +boolean. Upgrade server and generated-client runtime together. Old or unknown +wire forms fail closed; applications do not need a polling or reload workaround. diff --git a/js/README.md b/js/README.md index ff30b5e97..e0669ad52 100644 --- a/js/README.md +++ b/js/README.md @@ -51,6 +51,12 @@ to validate that committed artifacts are current without rewriting them. A co-located route document can opt into SSR and live continuation: +Row-filtered `@live` queries remain subscribed using authorized replacement +snapshots; cursor-capable queries retain resumable delivery. Neither requires +application polling. The v5 wire protocol uses `live.mode` (`snapshot` or +`resumable`), replacing `live.supported`; upgrade client and server together. +See [live query delivery](../docs/live-query-delivery.md). + ```graphql query Todos @load @live { todos(order_by: [{ status: asc }, { todo_id: asc }]) { diff --git a/js/src/protocol.ts b/js/src/protocol.ts index e99c285c8..d6b3dd457 100644 --- a/js/src/protocol.ts +++ b/js/src/protocol.ts @@ -149,10 +149,10 @@ export type DistributedQuerySnapshot = Readonly< } >; -/** Per-frame decision about live support, reset, and resumable cursors. */ +/** Per-frame delivery mode, reset decision, and resumable cursors. */ export type DistributedLiveMetadata = Readonly< Record & { - supported: boolean; + mode: 'snapshot' | 'resumable'; reset: boolean; cursors: readonly DistributedLiveCursor[]; } @@ -596,7 +596,8 @@ function parseSnapshot(value: unknown): DistributedQuerySnapshot { function parseLive(value: unknown): DistributedLiveMetadata { const path = 'extensions.distributed.live'; const live = record(value, path); - if (typeof live.supported !== 'boolean') invalid(`${path}.supported`); + if (live.mode !== 'snapshot' && live.mode !== 'resumable') invalid(`${path}.mode`); + if ('supported' in live) invalid(`${path}.supported`); if (typeof live.reset !== 'boolean') invalid(`${path}.reset`); if ( !Array.isArray(live.cursors) || @@ -613,12 +614,12 @@ function parseLive(value: unknown): DistributedLiveMetadata { cursors.map((cursor) => cursor.projection), `${path}.cursors` ); - if (!live.supported && (!live.reset || cursors.length !== 0)) { + if (live.mode === 'snapshot' && (!live.reset || cursors.length !== 0)) { invalid(path); } return Object.freeze({ ...live, - supported: live.supported, + mode: live.mode, reset: live.reset, cursors }) as DistributedLiveMetadata; @@ -630,7 +631,10 @@ function validateLiveSnapshot( ): void { if (live === undefined) return; if (snapshot === undefined) invalid('extensions.distributed.snapshot'); - if (!live.supported) return; + if (live.mode === 'snapshot') { + if (snapshot.indexesComparable) invalid('extensions.distributed.snapshot.indexesComparable'); + return; + } if (!snapshot.indexesComparable) { invalid('extensions.distributed.snapshot.indexesComparable'); } diff --git a/js/src/replica/distributed-replica/clocks.ts b/js/src/replica/distributed-replica/clocks.ts index ff20bc6db..44eafb9ab 100644 --- a/js/src/replica/distributed-replica/clocks.ts +++ b/js/src/replica/distributed-replica/clocks.ts @@ -122,7 +122,7 @@ export function latestCursors( live: DistributedProtocolEnvelope['live'] ): readonly DistributedLiveCursor[] { if (live !== undefined) { - return live.supported ? live.cursors : Object.freeze([]); + return live.mode === 'resumable' ? live.cursors : Object.freeze([]); } return Object.freeze( snapshot.indexes.flatMap((index) => diff --git a/js/src/replica/distributed-replica/impl-fetch-live.ts b/js/src/replica/distributed-replica/impl-fetch-live.ts index 650c8182e..72f55dbaf 100644 --- a/js/src/replica/distributed-replica/impl-fetch-live.ts +++ b/js/src/replica/distributed-replica/impl-fetch-live.ts @@ -1,7 +1,5 @@ -import { CacheRevisionConflictError } from '../../internal/cache-engine.js'; import type { GraphqlVariables } from '../../types.js'; import { - parseGraphqlResponseExtensions, type DistributedLiveCursor, type DistributedProtocolEnvelope } from '../../protocol.js'; @@ -309,13 +307,8 @@ export function retainLive( } return; } - let unsupportedLive = false; try { - unsupportedLive = - parseGraphqlResponseExtensions(result.extensions) - ?.distributed?.live?.supported === false; - if (unsupportedLive) state.live = 'off'; - const distributed = host.writeCanonicalResult( + host.writeCanonicalResult( watch.artifact, watch.variables, result, @@ -323,26 +316,10 @@ export function retainLive( undefined, projectionGeneration ); - if (distributed.live?.supported === false) { - fallbackFromLive(host, watch, entry); - return; - } state.live = 'active'; entry.operationGeneration = host.operationGeneration(watch.key); } catch (error) { - if ( - unsupportedLive && - error instanceof CacheRevisionConflictError - ) { - /* - * Revision zero is shared by provisional fallbacks. - * Another operation may already have filled the same - * semantic index differently; HTTP remains authoritative. - */ - fallbackFromLive(host, watch, entry); - return; - } state.live = 'error'; state.errors = stableErrors(state.errors, [graphqlError(error)]); host.emitState(watch.key, false); @@ -429,14 +406,13 @@ export function fallbackFromLive( /* * Keep the inactive entry as an authorization-generation-scoped * sentinel. Query ingestion calls resumeLiveWatches(); deleting this - * entry would otherwise reopen an unsupported or completed stream + * entry would otherwise reopen a completed stream * immediately. Authorization invalidation clears it and may retry. * - * A supported live frame advances the operation generation. Any HTTP + * An accepted live frame advances the operation generation. Any HTTP * request that was already running is therefore doomed by its response - * fence; drain it before starting the authoritative fallback. A first - * unsupported frame never advances the generation, so its overlapping - * HTTP request remains valid and can be reused directly. + * fence; drain it before starting the authoritative fallback. A stream + * that completed before its first frame can reuse the in-flight query. */ if (supersededFlight === undefined) { refresh(); diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index 83024fefa..e3eea0813 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -1184,21 +1184,9 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { } this.#validateLiveSnapshot(snapshot, live); - const unsupportedLive = - source === 'live' && live?.supported === false; + const snapshotLive = source === 'live' && live?.mode === 'snapshot'; const reset = live?.reset === true; const group = this.#operationProtocols.get(key)!; - /* - * An unsupported subscription response is an authorized fallback - * snapshot, not a live source. In particular, a row-filtered snapshot - * has no comparable index vector, so retaining live ownership here - * would reject every later query handoff. Relinquish any prior live - * ownership without advancing the generation; the forced HTTP fallback - * starts against the generation that remains after this frame. - */ - if (unsupportedLive && group.active === 'live') { - group.active = undefined; - } const previousActiveSource = group.active; const handoff = previousActiveSource !== undefined && @@ -1226,8 +1214,22 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { requestRevision, source ); + // A non-resumable stream has no causal vector to compare. An HTTP + // refresh may replace it only if the request began after its last + // accepted membership. fetchWatch also fences intervening live frames. + // Taking query ownership restarts the stream, fencing queued callbacks. + const snapshotRefresh = + source === 'network' && + previousActiveSource === 'live' && + !snapshot.indexesComparable && + activeState?.snapshotScope === undefined && + activeState?.indexRevision !== undefined && + requestRevision !== undefined && + compareCanonicalDecimalStrings(requestRevision, activeState.indexRevision) > 0; const handoffBlocked = handoff && + !snapshotLive && + !snapshotRefresh && ( !snapshot.indexesComparable || !isComparableHandoffDisposition(ownDisposition) || @@ -1251,7 +1253,6 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { : sharedDisposition.disposition ?? disposition; } const sourceSwitched = - !unsupportedLive && !handoffBlocked && isComparableHandoffDisposition(disposition) && this.#activateOperationSource( @@ -1316,24 +1317,16 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { !rejectedHandoff && disposition !== 'lower' && disposition !== 'incomparable'; - /* - * Revision zero is the cache engine's lowest legal checkpoint. It lets - * an unsupported live response fill an empty cache immediately while - * guaranteeing that any HTTP request revision can replace it. - */ + // Snapshot frames receive local membership revisions, not fabricated + // projection clocks. Live ownership fences older overlapping HTTP work. const indexRevision = - unsupportedLive - ? '0' + writeIndexes && + (sourceSwitched || sharedDisposition.disposition === 'higher') + ? this.#allocateIndexRevision() : writeIndexes && - ( - sourceSwitched || - sharedDisposition.disposition === 'higher' - ) - ? this.#allocateIndexRevision() - : writeIndexes && - sharedDisposition.disposition === 'equal' && - sharedDisposition.indexRevision !== undefined - ? sharedDisposition.indexRevision + sharedDisposition.disposition === 'equal' && + sharedDisposition.indexRevision !== undefined + ? sharedDisposition.indexRevision : snapshot.indexesComparable && disposition === 'equal' && operationState.indexRevision !== undefined @@ -1615,7 +1608,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { } else if (live?.reset === true || !snapshot.indexesComparable) { operationState.cursors = Object.freeze([]); } - if (source === 'live' && !unsupportedLive) { + if (source === 'live') { this.#advanceOperationGeneration(key); } if (source !== 'live' && sourceSwitched) { @@ -2838,7 +2831,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { snapshot: DistributedQuerySnapshot, live: DistributedProtocolEnvelope['live'] ): void { - if (live === undefined || !live.supported) return; + if (live === undefined || live.mode === 'snapshot') return; if (!snapshot.indexesComparable) { protocolInvalid( 'extensions.distributed.snapshot.indexesComparable' diff --git a/js/tests/fixtures/adapter-conformance.mjs b/js/tests/fixtures/adapter-conformance.mjs index fb200614a..c39ab1305 100644 --- a/js/tests/fixtures/adapter-conformance.mjs +++ b/js/tests/fixtures/adapter-conformance.mjs @@ -302,6 +302,7 @@ export function todoFrame( authorizationGeneration = 'auth-1', position = '1', source = 'query', + mode = 'resumable', reset = false, errors } = {} @@ -343,9 +344,9 @@ export function todoFrame( snapshot: { scopeToken: `snapshot:${root.field}`, recordsComplete: true, - indexesComparable: true, + indexesComparable: mode === 'resumable', records, - indexes: [ + indexes: mode === 'snapshot' ? [] : [ { projection: 'todos-projector', scopeToken: `index:${root.field}`, @@ -358,9 +359,9 @@ export function todoFrame( ...(source === 'live' ? { live: { - supported: true, - reset, - cursors: [resume] + mode, + reset: mode === 'snapshot' || reset, + cursors: mode === 'snapshot' ? [] : [resume] } } : {}) diff --git a/js/tests/fixtures/unique-key-artifact.mjs b/js/tests/fixtures/unique-key-artifact.mjs index b4fc191d7..ba4c5edad 100644 --- a/js/tests/fixtures/unique-key-artifact.mjs +++ b/js/tests/fixtures/unique-key-artifact.mjs @@ -26,7 +26,7 @@ export function frame(position, targetId, targetTitle) { protocolVersion: artifact.protocol.version, schemaHash: artifact.protocol.schemaHash, authorizationGeneration: 'auth-1', cacheScope: 'unique-key-cache', operation: position === '1' ? artifact.id : artifact.live.id, - ...(position === '1' ? {} : { live: { supported: true, reset: false, cursors: [ + ...(position === '1' ? {} : { live: { mode: "resumable", reset: false, cursors: [ { projection: 'unique-key-projector', position, token: `resume:${position}` } ] } }), snapshot: { scopeToken: 'unique-key-snapshot', recordsComplete: true, indexesComparable: true, diff --git a/js/tests/protocol-transport.test.mjs b/js/tests/protocol-transport.test.mjs index 9d067a8be..35542556d 100644 --- a/js/tests/protocol-transport.test.mjs +++ b/js/tests/protocol-transport.test.mjs @@ -81,7 +81,7 @@ function distributedEnvelope() { observations: [] }, live: { - supported: true, + mode: "resumable", reset: false, cursors: [ { @@ -237,7 +237,7 @@ test('protocol parser requires exact live snapshot alignment', () => { parseDistributedProtocolEnvelope({ ...envelope, snapshot: undefined, - live: { supported: false, reset: true, cursors: [] } + live: { mode: "snapshot", reset: true, cursors: [] } }), (error) => error instanceof DistributedProtocolError && @@ -253,7 +253,7 @@ test('protocol parser requires exact live snapshot alignment', () => { indexes: [], observations: [] }, - live: { supported: true, reset: true, cursors: [] } + live: { mode: "resumable", reset: true, cursors: [] } }), (error) => error instanceof DistributedProtocolError && @@ -333,6 +333,28 @@ test('protocol parser requires exact live snapshot alignment', () => { } }); +test('snapshot delivery requires an explicit cursorless reset and fails closed on old modes', () => { + const base = distributedEnvelope(); + const envelope = { + ...base, + snapshot: { ...base.snapshot, indexesComparable: false, indexes: [], observations: [] }, + live: { mode: 'snapshot', reset: true, cursors: [] } + }; + assert.equal(parseDistributedProtocolEnvelope(envelope).live.mode, 'snapshot'); + for (const live of [ + { supported: false, reset: true, cursors: [] }, + { ...envelope.live, supported: false }, + { ...envelope.live, mode: 'unknown' }, + { ...envelope.live, reset: false }, + { ...envelope.live, cursors: base.live.cursors } + ]) { + assert.throws(() => parseDistributedProtocolEnvelope({ ...envelope, live }), DistributedProtocolError); + } + assert.throws(() => parseDistributedProtocolEnvelope({ + ...envelope, snapshot: base.snapshot + }), DistributedProtocolError); +}); + test('protocol parser accepts 64 resume cursors and rejects 65', () => { const cursors = Array.from({ length: 65 }, (_, index) => ({ projection: `projection-${index}`, @@ -349,7 +371,7 @@ test('protocol parser accepts 64 resume cursors and rejects 65', () => { const accepted = parseDistributedProtocolEnvelope({ ...envelope, snapshot: { ...envelope.snapshot, indexes: indexes.slice(0, 64) }, - live: { supported: true, reset: false, cursors: cursors.slice(0, 64) } + live: { mode: "resumable", reset: false, cursors: cursors.slice(0, 64) } }); assert.equal(accepted.live.cursors.length, 64); assert.equal(accepted.snapshot.indexes.length, 64); @@ -358,7 +380,7 @@ test('protocol parser accepts 64 resume cursors and rejects 65', () => { () => parseDistributedProtocolEnvelope({ ...envelope, - live: { supported: true, reset: false, cursors } + live: { mode: "resumable", reset: false, cursors } }), (error) => error instanceof DistributedProtocolError && @@ -369,7 +391,7 @@ test('protocol parser accepts 64 resume cursors and rejects 65', () => { parseDistributedProtocolEnvelope({ ...envelope, snapshot: { ...envelope.snapshot, indexes }, - live: { supported: false, reset: true, cursors: [] } + live: { mode: "snapshot", reset: true, cursors: [] } }), (error) => error instanceof DistributedProtocolError && diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index 92230bf7c..20f70258a 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -416,11 +416,11 @@ function wireFrame(options = {}) { options.live === undefined ? undefined : { - supported: options.live.supported ?? true, + mode: options.live.mode ?? 'resumable', reset: options.live.reset ?? false, cursors: options.live.cursors ?? - (options.live.supported === false ? [] : [resume]) + (options.live.mode === 'snapshot' ? [] : [resume]) }; return { data: { todos: rows }, @@ -725,7 +725,7 @@ test('comparable live snapshot cannot drop an Eventual list row after confirmati position: '2', operation: Todos.live.id, rows: [{ id: 'todo-1', title: 'first' }], - live: { supported: true } + live: { mode: "resumable" } }, 'live' ); @@ -750,7 +750,7 @@ test('comparable live snapshot cannot drop an Eventual list row after confirmati { id: 'todo-1', title: 'first' }, { id: 'todo-2', title: 'posted' } ], - live: { supported: true }, + live: { mode: "resumable" }, records: [ { path: ['todos', '0'], @@ -832,7 +832,7 @@ test('Eventual membership fences are independent per index', () => { { id: 'todo-1', title: 'first' }, { id: 'todo-2', title: 'posted' } ], - live: { supported: true } + live: { mode: "resumable" } }, 'live' ); @@ -845,7 +845,7 @@ test('Eventual membership fences are independent per index', () => { indexScope: 'index:todos-open', snapshotScope: 'snapshot:todos-open', rows: [{ id: 'todo-1', title: 'first' }], - live: { supported: true } + live: { mode: "resumable" } }, 'live', TodosOpen @@ -867,7 +867,7 @@ test('Eventual membership fences are independent per index', () => { { id: 'todo-1', title: 'first' }, { id: 'todo-2', title: 'posted' } ], - live: { supported: true } + live: { mode: "resumable" } }, 'live', TodosOpen @@ -915,7 +915,7 @@ test('overlapping Eventual commands retain every membership-fence owner', () => position: '2', operation: Todos.live.id, rows: [{ id: 'todo-1', title: 'first' }], - live: { supported: true } + live: { mode: "resumable" } }, 'live' ); @@ -1438,7 +1438,7 @@ test('a comparable shared root cannot promote an incomparable nested sibling', a ownerName: 'unfenced live frame', operation: GamesWithOwnerLiveOperation.live.id, live: { - supported: true, + mode: "resumable", reset: false, cursors: [ { @@ -1469,7 +1469,7 @@ test('an older operation reset cannot erase a shared index owned by a newer arti operation: Todos.live.id, position: '5', rows: [{ id: 'todo-live', title: 'old live owner' }], - live: { supported: true } + live: { mode: "resumable" } }, 'live' ); @@ -1490,7 +1490,7 @@ test('an older operation reset cannot erase a shared index owned by a newer arti operation: Todos.live.id, position: '8', rows: [{ id: 'todo-reset', title: 'older reset' }], - live: { supported: true, reset: true } + live: { mode: "resumable", reset: true } }, 'live' ); @@ -1508,7 +1508,7 @@ test('reset preserves an equal-vector index with another operation co-owner', () operation: Todos.live.id, position: '5', rows: [{ id: 'todo-shared', title: 'shared snapshot' }], - live: { supported: true } + live: { mode: "resumable" } }, 'live' ); @@ -1529,7 +1529,7 @@ test('reset preserves an equal-vector index with another operation co-owner', () operation: Todos.live.id, position: '4', rows: [{ id: 'todo-reset', title: 'older reset' }], - live: { supported: true, reset: true } + live: { mode: "resumable", reset: true } }, 'live' ); @@ -1785,7 +1785,7 @@ test('a live handoff fences an HTTP response launched in the prior generation', watch.destroy(); }); -test('unsupported live fallback cannot fence HTTP membership or later revalidation', async () => { +test('snapshot live stays attached and fences overlapping HTTP membership', async () => { const fetches = []; const subscriptions = []; let unsubscribeCount = 0; @@ -1819,14 +1819,14 @@ test('unsupported live fallback cannot fence HTTP membership or later revalidati rows: [{ id: 'todo-live', title: 'provisional live fallback' }], recordScope: 'record:live', indexesComparable: false, - live: { supported: false, reset: true } + live: { mode: "snapshot", reset: true } }) ); assert.deepEqual(replica.read(Todos, {}).data.todos, [ { id: 'todo-live', title: 'provisional live fallback' } ]); - assert.equal(watch.get().live, 'off'); - assert.equal(unsubscribeCount, 1); + assert.equal(watch.get().live, 'active'); + assert.equal(unsubscribeCount, 0); await Promise.resolve(); fetches[0].resolve( @@ -1839,12 +1839,12 @@ test('unsupported live fallback cannot fence HTTP membership or later revalidati ); await new Promise((resolve) => setImmediate(resolve)); assert.deepEqual(replica.read(Todos, {}).data.todos, [ - { id: 'todo-http', title: 'newer HTTP membership' } + { id: 'todo-live', title: 'provisional live fallback' } ]); assert.equal( subscriptions.length, 1, - 'query fallback must not immediately reopen an unsupported stream' + 'snapshot delivery must keep the original subscription attached' ); const revalidation = replica.revalidate({ @@ -1866,13 +1866,19 @@ test('unsupported live fallback cannot fence HTTP membership or later revalidati assert.deepEqual(replica.read(Todos, {}).data.todos, [ { id: 'todo-revalidated', title: 'revalidated membership' } ]); - assert.equal(subscriptions.length, 1); + assert.equal(subscriptions.length, 2, 'refresh restarts the snapshot stream'); + assert.equal(subscriptions[1].request.resume, undefined); + subscriptions[0].observer.next(wireFrame({ + operation: 'live:todos', rows: [], indexesComparable: false, + live: { mode: 'snapshot', reset: true } + })); + assert.equal(replica.read(Todos, {}).data.todos[0].id, 'todo-revalidated'); watch.destroy(); - assert.equal(unsubscribeCount, 1); + assert.equal(unsubscribeCount, 2); }); -test('conflicting provisional live fallbacks still close and yield to HTTP', async () => { +test('snapshot live cannot supersede an incomparable sibling index owner', async () => { const fetches = []; let liveObserver; let unsubscribeCount = 0; @@ -1902,7 +1908,7 @@ test('conflicting provisional live fallbacks still close and yield to HTTP', asy rows: [{ id: 'todo-other', title: 'other provisional membership' }], recordScope: 'record:other', indexesComparable: false, - live: { supported: false, reset: true } + live: { mode: "snapshot", reset: true } }), 'live' ); @@ -1915,30 +1921,103 @@ test('conflicting provisional live fallbacks still close and yield to HTTP', asy rows: [{ id: 'todo-live', title: 'conflicting provisional membership' }], recordScope: 'record:live', indexesComparable: false, - live: { supported: false, reset: true } + live: { mode: "snapshot", reset: true } }) ); - assert.equal(watch.get().live, 'off'); - assert.equal(unsubscribeCount, 1); + assert.equal(watch.get().live, 'active'); + assert.equal(unsubscribeCount, 0); - await Promise.resolve(); - fetches[0].resolve( - wireFrame({ - rows: [{ id: 'todo-http', title: 'authoritative HTTP membership' }], - recordScope: 'record:http', - indexesComparable: false - }) - ); - await new Promise((resolve) => setImmediate(resolve)); + assert.equal(fetches.length, 0, 'a complete live result needs no HTTP fallback'); + assert.deepEqual(replica.read(Todos, {}).data.todos, [ + { id: 'todo-other', title: 'other provisional membership' } + ]); + liveObserver.next(wireFrame({ + operation: 'live:todos', rows: [], indexesComparable: false, + live: { mode: 'snapshot', reset: true } + })); assert.deepEqual(replica.read(Todos, {}).data.todos, [ - { id: 'todo-http', title: 'authoritative HTTP membership' } + { id: 'todo-other', title: 'other provisional membership' } ]); + assert.equal(watch.get().live, 'active'); + assert.equal(unsubscribeCount, 0); watch.destroy(); assert.equal(unsubscribeCount, 1); }); -test('completed supported live streams relinquish ownership and fall back to HTTP', async () => { +test('snapshot live replaces SSR membership, updates and removes rows, and fences disposal', () => { + let observer; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, next) { observer = next; return () => {}; } + } }); + replica.writeResult(Todos, {}, wireFrame({ + rows: [{ id: 'todo-1', title: 'SSR title' }], indexesComparable: false + }), 'ssr'); + const watch = replica.watch(Todos, {}, { live: true }); + observer.next(wireFrame({ + operation: 'live:todos', rows: [{ id: 'todo-1', title: 'updated title' }], + revision: '2', indexesComparable: false, + live: { mode: 'snapshot', reset: true } + })); + assert.equal(replica.read(Todos, {}).data.todos[0].title, 'updated title'); + observer.next(wireFrame({ + operation: 'live:todos', rows: [], indexesComparable: false, + live: { mode: 'snapshot', reset: true } + })); + assert.deepEqual(replica.read(Todos, {}).data.todos, []); + assert.equal(watch.get().live, 'active'); + watch.destroy(); + observer.next(wireFrame({ + operation: 'live:todos', rows: [{ id: 'late', title: 'disposed callback' }], + indexesComparable: false, live: { mode: 'snapshot', reset: true } + })); + assert.deepEqual(replica.read(Todos, {}).data.todos, []); +}); + +test('snapshot authorization changes discard the old stream and reconnect without cursors', async () => { + const subscriptions = []; + const requests = []; + const replica = createDistributedReplica({ transport: { + fetch(request) { + return new Promise((resolve) => requests.push({ request, resolve })); + }, + subscribe(request, observer) { + subscriptions.push({ request, observer }); + return () => {}; + } + } }); + write(replica, { rows: [{ id: 'alice', title: 'private alice' }], indexesComparable: false }, 'ssr'); + const watch = replica.watch(Todos, {}, { live: true }); + subscriptions[0].observer.next(wireFrame({ + operation: 'live:todos', rows: [{ id: 'alice', title: 'private alice' }], + indexesComparable: false, live: { mode: 'snapshot', reset: true } + })); + replica.invalidateAuthorization(); + await Promise.resolve(); + assert.equal(requests.length, 1); + subscriptions[0].observer.next(wireFrame({ + operation: 'live:todos', rows: [{ id: 'alice', title: 'late private alice' }], + indexesComparable: false, live: { mode: 'snapshot', reset: true } + })); + assert.equal(watch.get().complete, false); + requests[0].resolve(wireFrame({ + cacheScope: 'cache:b', rows: [{ id: 'bob', title: 'private bob' }], + recordScope: 'record:b', indexesComparable: false + })); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(subscriptions.length, 2); + assert.equal(subscriptions[1].request.resume, undefined); + assert.equal(watch.get().data.todos[0].id, 'bob'); + subscriptions[1].observer.next(wireFrame({ + operation: 'live:todos', cacheScope: 'cache:b', rows: [], + indexesComparable: false, live: { mode: 'snapshot', reset: true } + })); + assert.deepEqual(watch.get().data.todos, []); + watch.destroy(); +}); + +test('completed resumable live streams relinquish ownership and fall back to HTTP', async () => { const fetches = []; const subscriptions = []; let unsubscribeCount = 0; @@ -1971,7 +2050,7 @@ test('completed supported live streams relinquish ownership and fall back to HTT position: '2', rows: [{ id: 'todo-live', title: 'supported live membership' }], recordScope: 'record:live', - live: { supported: true, reset: true } + live: { mode: "resumable", reset: true } }) ); assert.deepEqual(replica.read(Todos, {}).data.todos, [ diff --git a/js/tests/replica-result-observation.test.mjs b/js/tests/replica-result-observation.test.mjs index 35e515d1a..40a8030fa 100644 --- a/js/tests/replica-result-observation.test.mjs +++ b/js/tests/replica-result-observation.test.mjs @@ -116,7 +116,7 @@ function frame(revision, value, operation = Query.id) { ...(operation === Query.live.id ? { live: { - supported: true, + mode: 'resumable', reset: false, cursors: [ { diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index 2bde3a62e..baeef371c 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -113,7 +113,7 @@ const forwardedTodosBoundary = defineDistributedBoundaryOperation( }) ); -function serverHarness() { +function serverHarness(mode = 'resumable') { const calls = []; const server = createDistributedSvelteKitServer({ boundaries: [todosBoundary], @@ -150,6 +150,7 @@ function serverHarness() { ], { cacheScope: `cache:${token}`, + mode, position } ) @@ -163,8 +164,9 @@ function serverHarness() { }; } -test('static @load SSR is request-isolated and hydration avoids a duplicate first fetch', async () => { - const harness = serverHarness(); +for (const mode of ['resumable', 'snapshot']) { +test(`static @load SSR is isolated and hydration avoids a duplicate fetch (${mode})`, async () => { + const harness = serverHarness(mode); const [alice, bob] = await Promise.all([ harness.server.load(harness.event('alice')), harness.server.load(harness.event('bob')) @@ -212,7 +214,7 @@ test('static @load SSR is request-isolated and hydration avoids a duplicate firs payload: todoFrame( TodosArtifact, [{ id: 'todo-alice', title: 'alice:live', status: 'open' }], - { cacheScope: 'cache:alice', position: '2', source: 'live' } + { cacheScope: 'cache:alice', position: '2', source: 'live', mode } ) }); await flushMicrotasks(); @@ -230,6 +232,7 @@ test('static @load SSR is request-isolated and hydration avoids a duplicate firs assert.equal(socket.closed, true); client.destroy(); }); +} test('SSR only awaits parent data for forwarded-prop bindings', async () => { const harness = serverHarness(); diff --git a/src/gateway/delivery/live.rs b/src/gateway/delivery/live.rs index 9ada4bd5a..f1ed4b196 100644 --- a/src/gateway/delivery/live.rs +++ b/src/gateway/delivery/live.rs @@ -181,7 +181,7 @@ impl LiveFrame { let canonical = canonical_json(&payload).unwrap_or(bytes); let protocol = &payload["extensions"]["distributed"]; let cursors = &protocol["live"]["cursors"]; - let cursor = if protocol["live"]["supported"] == true + let cursor = if protocol["live"]["mode"] == "resumable" && protocol["snapshot"]["indexesComparable"] == true && cursors.as_array().is_some_and(|cursors| { !cursors.is_empty() diff --git a/src/gateway/native/live.rs b/src/gateway/native/live.rs index b4e29f6e7..34ab796a7 100644 --- a/src/gateway/native/live.rs +++ b/src/gateway/native/live.rs @@ -499,7 +499,7 @@ mod tests { serde_json::json!({"data":{"rows":[{"title":"unchanged"}]},"extensions":{"distributed":{ "protocolVersion":1,"schemaHash":"schema","authorizationGeneration":"policy","cacheScope":"alice","operation":"operation", "snapshot":{"recordsComplete":true,"indexesComparable":true,"records":[],"indexes":[{"projection":"rows","scopeToken":"scope","position":position.to_string()}],"observations":[proof]}, - "live":{"supported":true,"reset":false,"cursors":[{"projection":"rows","position":position.to_string(),"token":format!("token-{position}")}]} + "live":{"mode":"resumable","reset":false,"cursors":[{"projection":"rows","position":position.to_string(),"token":format!("token-{position}")}]} }}}) } struct DropCount(Arc); diff --git a/src/graphql/protocol/mod.rs b/src/graphql/protocol/mod.rs index 21d99c9e0..03f27d159 100644 --- a/src/graphql/protocol/mod.rs +++ b/src/graphql/protocol/mod.rs @@ -25,7 +25,7 @@ pub(crate) use token::{ pub(crate) use types::{ DistributedCommandConsistency, DistributedCommandMetadata, DistributedCommandState, DistributedEnvelopeV1, DistributedIndexRevision, DistributedLiveCursor, - DistributedLiveMetadata, DistributedProjectionDisposition, DistributedProjectionExpectation, - DistributedProjectionObservation, DistributedQuerySnapshot, DistributedRecordRevision, - DistributedTrustedPreset, RequestedLiveResume, + DistributedLiveMetadata, DistributedLiveMode, DistributedProjectionDisposition, + DistributedProjectionExpectation, DistributedProjectionObservation, DistributedQuerySnapshot, + DistributedRecordRevision, DistributedTrustedPreset, RequestedLiveResume, }; diff --git a/src/graphql/protocol/tests.rs b/src/graphql/protocol/tests.rs index abef4469f..7ad481d63 100644 --- a/src/graphql/protocol/tests.rs +++ b/src/graphql/protocol/tests.rs @@ -519,7 +519,7 @@ fn stream_frames_are_immutable_fifo_and_do_not_bleed_forward() { .record_query_metadata( first.clone(), Some(DistributedLiveMetadata { - supported: true, + mode: DistributedLiveMode::Resumable, reset: true, cursors: vec![first.indexes[0].resume.clone().unwrap()], }), @@ -529,7 +529,7 @@ fn stream_frames_are_immutable_fifo_and_do_not_bleed_forward() { .record_query_metadata( second.clone(), Some(DistributedLiveMetadata { - supported: true, + mode: DistributedLiveMode::Resumable, reset: false, cursors: vec![second.indexes[0].resume.clone().unwrap()], }), diff --git a/src/graphql/protocol/types.rs b/src/graphql/protocol/types.rs index 64f4b7291..63f7c6293 100644 --- a/src/graphql/protocol/types.rs +++ b/src/graphql/protocol/types.rs @@ -170,11 +170,19 @@ impl DistributedQuerySnapshot { } } -/// Per-frame resumability decision for a live operation. +/// Authorized snapshot delivery does not imply partition-wide resumability. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum DistributedLiveMode { + Snapshot, + Resumable, +} + +/// Per-frame delivery mode for a live operation. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct DistributedLiveMetadata { - pub(crate) supported: bool, + pub(crate) mode: DistributedLiveMode, pub(crate) reset: bool, pub(crate) cursors: Vec, } diff --git a/src/graphql/query_protocol.rs b/src/graphql/query_protocol.rs index 1ca252fd3..bb31a5e46 100644 --- a/src/graphql/query_protocol.rs +++ b/src/graphql/query_protocol.rs @@ -18,9 +18,9 @@ use super::engine::GraphqlPool; #[cfg(any(feature = "sqlite", feature = "postgres"))] use super::execute; use super::protocol::{ - DistributedIndexRevision, DistributedLiveMetadata, DistributedQuerySnapshot, - DistributedRecordRevision, ProtocolResponseAccumulator, RequestedLiveResume, - MAX_LIVE_RESUME_CURSORS, + DistributedIndexRevision, DistributedLiveMetadata, DistributedLiveMode, + DistributedQuerySnapshot, DistributedRecordRevision, ProtocolResponseAccumulator, + RequestedLiveResume, MAX_LIVE_RESUME_CURSORS, }; use super::surface::{Surface, SurfaceProjectionOwner, SurfaceRowPolicy}; use crate::projection::placement::ProjectionBindingState; @@ -167,7 +167,7 @@ impl QueryProtocolRuntime { /// the plan. Join targets such as `auth_users` are often populated by /// integration handlers without a unit-resume owner; they still participate /// in dirty matching via `tables_touched`, but must not force - /// `live.supported = false` for an otherwise resumable root model (e.g. + /// snapshot-only live delivery for an otherwise resumable root model (e.g. /// `chat_messages` with a nested `author` selection). pub(crate) fn index_plan(&self, role_surface: &Surface, tables: &[String]) -> QueryIndexPlan { if tables.is_empty() { @@ -787,13 +787,23 @@ where } None => (None, Vec::new()), }; - let snapshot = wire_query_snapshot( + let mut snapshot = wire_query_snapshot( accumulator, prepared, record_metadata, partitions, live_changes, )?; + if live + .as_ref() + .is_some_and(|metadata| metadata.mode == DistributedLiveMode::Snapshot) + { + // A safe query vector can still exceed the live cursor budget. Snapshot + // delivery has one contract regardless of why resumability is unavailable. + snapshot.indexes_comparable = false; + snapshot.indexes.clear(); + snapshot.observations.clear(); + } Ok(ProtocolQueryExecution { value: executed.value, snapshot, @@ -894,7 +904,7 @@ where { return Ok(PreparedLiveMetadata { metadata: DistributedLiveMetadata { - supported: false, + mode: DistributedLiveMode::Snapshot, reset: true, cursors: Vec::new(), }, @@ -1094,7 +1104,7 @@ where Ok(PreparedLiveMetadata { metadata: DistributedLiveMetadata { - supported: true, + mode: DistributedLiveMode::Resumable, reset, cursors: current, }, diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index e87a71b20..c4a9c9f0b 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -290,7 +290,7 @@ async fn execute_list( let next_live_resume = executed .live .as_ref() - .filter(|live| live.supported) + .filter(|live| live.mode == super::protocol::DistributedLiveMode::Resumable) .map(|live| RequestedLiveResume::Cursors(live.cursors.clone())) .unwrap_or(RequestedLiveResume::Absent); Ok(ExecutedLiveQuery { diff --git a/tests/e2e-ui/crates/projections/src/chat.rs b/tests/e2e-ui/crates/projections/src/chat.rs index 97198e94c..0ea8d6582 100644 --- a/tests/e2e-ui/crates/projections/src/chat.rs +++ b/tests/e2e-ui/crates/projections/src/chat.rs @@ -1,15 +1,16 @@ //! Chat: mutation + projection. //! //! Unit partition so the lobby `@live` subscription can advertise resumable -//! index evidence (`live.supported = true`). Room isolation stays on the +//! index evidence (`live.mode = "resumable"`). Room isolation stays on the //! GraphQL document (`where: { room_id: { _eq: "lobby" } }`). Expression //! partitions are correct for multi-room worker sharding, but they make live -//! indexes incomparable and the client falls back to Idle. +//! indexes incomparable, so live delivery uses authorized snapshots without +//! partition-wide resume cursors. +use chat_domain::ChatMessagePostedDomainEvent; use distributed::mutation_file; use distributed::projection::lower::{DirectCandidate, ProjectionDescriptor}; use distributed::Mutation; -use chat_domain::ChatMessagePostedDomainEvent; use e2e_readmodels::ChatMessages; /// Mutation: complete-row upsert for chat messages. @@ -53,11 +54,18 @@ mod tests { occurrence.descriptor(), &ChatMessagePostedDomainEvent::descriptor() ); - let lowered = CHAT_MESSAGES.server_executor().unwrap().plan(occurrence).unwrap(); + let lowered = CHAT_MESSAGES + .server_executor() + .unwrap() + .plan(occurrence) + .unwrap(); let TableMutation::UpsertRow(row) = &lowered.write_plan.mutations[0] else { panic!("expected upsert"); }; - assert_eq!(row.values.get("body"), Some(&RowValue::String("hello".into()))); + assert_eq!( + row.values.get("body"), + Some(&RowValue::String("hello".into())) + ); assert_eq!( SaveChatMessage().program().operations()[0].kind(), MutationKind::Upsert diff --git a/tests/edge_query_delivery.rs b/tests/edge_query_delivery.rs index 697d3cd3a..91ea24131 100644 --- a/tests/edge_query_delivery.rs +++ b/tests/edge_query_delivery.rs @@ -388,7 +388,7 @@ fn live_scope_replay_and_proof_sensitive_frames() { ) .is_err()); let mut payload: serde_json::Value = serde_json::from_slice(&snapshot(&admitted).body).unwrap(); - payload["extensions"]["distributed"]["live"] = json!({"supported":true,"cursors":[{"projection":"todos","position":"2","token":"cursor"}]}); + payload["extensions"]["distributed"]["live"] = json!({"mode":"resumable","cursors":[{"projection":"todos","position":"2","token":"cursor"}]}); let first = LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap(); assert!( first.same_frame(&LiveFrame::from_origin(&admitted, payload.clone(), None, 4096).unwrap()) @@ -406,7 +406,7 @@ fn live_scope_replay_and_proof_sensitive_frames() { !first.same_cursor(&changed), "same projector cursor does not cover external writes" ); - payload["extensions"]["distributed"]["live"]["supported"] = false.into(); + payload["extensions"]["distributed"]["live"]["mode"] = "snapshot".into(); let unsupported = LiveFrame::from_origin(&admitted, payload, None, 4096).unwrap(); assert!(!unsupported.same_cursor(&unsupported)); let mut stronger = context(); diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 325e4a294..85378dafc 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -206,12 +206,21 @@ async fn project_item_with_id( } async fn delete_item(repository: &SqliteRepository, bus: &InMemoryBus, sequence: u64) { + delete_item_with_id(repository, bus, sequence, ROW_ID).await; +} + +async fn delete_item_with_id( + repository: &SqliteRepository, + bus: &InMemoryBus, + sequence: u64, + id: &str, +) { bus.publish_message( Message::new( FACT_NAME, MessageKind::Event, serde_json::to_vec(&json!({ - "id": ROW_ID, + "id": id, "title": "deleted row", "delete": true })) @@ -404,7 +413,7 @@ fn assert_live_frame( assert_eq!(snapshot["indexes"][0]["position"], expected_position); let live = &distributed["live"]; - assert_eq!(live["supported"], true, "{response}"); + assert_eq!(live["mode"], "resumable", "{response}"); assert_eq!(live["reset"], expected_reset, "{response}"); assert_eq!(live["cursors"].as_array().map(Vec::len), Some(1)); assert_eq!(live["cursors"][0]["projection"], PROJECTOR_NAME); @@ -957,7 +966,7 @@ async fn live_subscription_replays_delete_tombstone_and_observation() { "{deleted}" ); let distributed = distributed_envelope(&deleted); - assert_eq!(distributed["live"]["supported"], true); + assert_eq!(distributed["live"]["mode"], "resumable"); assert_eq!(distributed["live"]["reset"], false); assert_eq!(distributed["live"]["cursors"][0]["position"], "2"); assert_eq!(distributed["snapshot"]["indexes"][0]["position"], "2"); @@ -1124,7 +1133,7 @@ async fn row_filtered_surface_never_exposes_partition_wide_live_activity() { assert_eq!(records[0]["model"], "CausalQueryView"); assert_eq!(records[0]["tombstone"], false); assert_opaque_token(&records[0]["scopeToken"], "record-revision"); - assert_eq!(envelope["live"]["supported"], false, "{initial}"); + assert_eq!(envelope["live"]["mode"], "snapshot", "{initial}"); assert_eq!(envelope["live"]["reset"], true, "{initial}"); assert_eq!(envelope["live"]["cursors"], json!([]), "{initial}"); @@ -1142,6 +1151,50 @@ async fn row_filtered_surface_never_exposes_partition_wide_live_activity() { .is_err(), "a denied-row commit must not leak a cursor, causation, tombstone, or activity frame" ); + + delete_item_with_id( + &fixture.repository, + &fixture.bus, + 3, + "other-principal-private-row", + ) + .await; + assert!( + tokio::time::timeout(Duration::from_millis(350), stream.next()) + .await + .is_err(), + "a denied-row deletion must not leak activity or a tombstone" + ); + project_item(&fixture.repository, &fixture.bus, 4, "visible change").await; + let changed = next_wire_frame(&mut stream).await; + assert_eq!( + changed["data"]["causal_query_views"], + json!([{ "title": "visible change" }]) + ); + let metadata = distributed_envelope(&changed); + assert_eq!( + metadata["live"], + json!({"mode":"snapshot","reset":true,"cursors":[]}) + ); + assert_eq!(metadata["snapshot"]["indexes"], json!([])); + assert_eq!(metadata["snapshot"]["observations"], json!([])); + + drop(stream); + let mut stream = engine.execute_stream(&user_session(), Request::new(LIVE_SUBSCRIPTION)); + let reconnected = next_wire_frame(&mut stream).await; + assert_eq!(reconnected["data"], changed["data"]); + assert_eq!(distributed_envelope(&reconnected)["live"], metadata["live"]); + + delete_item(&fixture.repository, &fixture.bus, 5).await; + let deleted = next_wire_frame(&mut stream).await; + assert_eq!(deleted["data"]["causal_query_views"], json!([])); + let metadata = distributed_envelope(&deleted); + assert_eq!( + metadata["live"], + json!({"mode":"snapshot","reset":true,"cursors":[]}) + ); + assert_eq!(metadata["snapshot"]["records"], json!([])); + assert_eq!(metadata["snapshot"]["observations"], json!([])); } async fn query_over_http_and_graphql_ws( diff --git a/tests/graphql_query_protocol_postgres/main.rs b/tests/graphql_query_protocol_postgres/main.rs index 8b76bda23..da9def676 100644 --- a/tests/graphql_query_protocol_postgres/main.rs +++ b/tests/graphql_query_protocol_postgres/main.rs @@ -236,7 +236,7 @@ async fn postgres_emits_exact_revisions_and_accepts_an_exact_live_resume() { engine.execute_stream(&user_session(), Request::new(LIVE_SUBSCRIPTION)); let initial = next_wire_frame(&mut initial_stream).await; let initial_live = &distributed_envelope(&initial)["live"]; - assert_eq!(initial_live["supported"], true, "{initial}"); + assert_eq!(initial_live["mode"], "resumable", "{initial}"); assert_eq!(initial_live["reset"], false, "{initial}"); let cursors = initial_live["cursors"].clone(); assert_eq!(cursors[0]["projection"], PROJECTOR_NAME); @@ -247,7 +247,7 @@ async fn postgres_emits_exact_revisions_and_accepts_an_exact_live_resume() { let mut resumed_stream = engine.execute_stream(&user_session(), request_with_resume(cursors)); let resumed = next_wire_frame(&mut resumed_stream).await; let resumed_live = &distributed_envelope(&resumed)["live"]; - assert_eq!(resumed_live["supported"], true, "{resumed}"); + assert_eq!(resumed_live["mode"], "resumable", "{resumed}"); assert_eq!(resumed_live["reset"], false, "{resumed}"); assert_eq!(resumed_live["cursors"][0]["position"], "1"); } From c83252fcaba132b17e0291578de93afa69187a0f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 04:14:47 -0500 Subject: [PATCH 071/484] feat(graphql): add literal case-insensitive text filters --- .github/workflows/integration-postgres.yaml | 1 + README.md | 25 +++ .../manifest/model_validation.rs | 1 + distributed_cli/tests/cli_client.rs | 47 +++++ js/src/replica/identity/codec.ts | 4 +- js/src/replica/identity/constants.ts | 2 +- js/src/replica/query-plan/filter.ts | 4 +- js/src/replica/types.ts | 1 + js/tests/replica-query-plan.test.mjs | 7 +- js/tests/replica-variable-codec.test.mjs | 17 +- src/graphql/compile/filter.rs | 19 ++ src/graphql/naming.rs | 4 +- src/graphql/sdl.rs | 2 +- tests/graphql_literal_text/main.rs | 162 ++++++++++++++++++ 14 files changed, 288 insertions(+), 8 deletions(-) create mode 100644 tests/graphql_literal_text/main.rs diff --git a/.github/workflows/integration-postgres.yaml b/.github/workflows/integration-postgres.yaml index 1543702c5..465eac066 100644 --- a/.github/workflows/integration-postgres.yaml +++ b/.github/workflows/integration-postgres.yaml @@ -44,6 +44,7 @@ jobs: cargo test --test postgres_transport --no-default-features --features postgres --verbose cargo test --test distributed_read_model --no-default-features --features postgres --verbose cargo test --test sql_lock_manager --no-default-features --features postgres --verbose + cargo test --test graphql_literal_text --no-default-features --features graphql,postgres --verbose - name: Verify source fencing and snapshot rebuild against PostgreSQL env: DISTRIBUTED_SNAPSHOT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:5432/distributed_snapshots diff --git a/README.md b/README.md index c555924c2..bbb492149 100644 --- a/README.md +++ b/README.md @@ -1921,6 +1921,31 @@ distributed = { version = "0.1", features = ["graphql", "postgres"] } `distributed::graphql::{naming,sdl}` compile without the feature so `distributed schema --format graphql` works in tooling crates. +### Literal text search + +Use `_icontains` for a case-insensitive substring search on a String column: + +```graphql +query SearchTodos($q: String! = "") @load @live { + todos(where: { title: { _icontains: $q } }, limit: 20) { + todo_id + title + } +} +``` + +A colocated binding can pass `q: searchParam('q')` directly. Callers do not +construct `%patterns%`: `%`, `_`, backslash, quotes and the escape character +are literal text. The query engine binds an escaped pattern on both PostgreSQL +and SQLite. An empty string matches every non-null string; use a bounded query +and show results only after a submitted search when building a search form. + +Case matching follows the database: PostgreSQL uses its configured ILIKE +behavior; SQLite's default LIKE folds ASCII, not arbitrary Unicode. The browser +replica therefore leaves local match evaluation uncertain and relies on the +authorized server result. `_ilike` still accepts deliberate wildcard patterns; +`_contains` remains the PostgreSQL JSON containment operator. + ### Scope | In | Out | diff --git a/distributed_cli/src/client_compiler/manifest/model_validation.rs b/distributed_cli/src/client_compiler/manifest/model_validation.rs index dcf9db697..7c5a58f97 100644 --- a/distributed_cli/src/client_compiler/manifest/model_validation.rs +++ b/distributed_cli/src/client_compiler/manifest/model_validation.rs @@ -1134,6 +1134,7 @@ pub(crate) fn validate_filter_fields( | "_is_null" | "_like" | "_ilike" + | "_icontains" | "_contains" | "_contained_in" | "_has_key" diff --git a/distributed_cli/tests/cli_client.rs b/distributed_cli/tests/cli_client.rs index 1d814a2a2..53d29d906 100644 --- a/distributed_cli/tests/cli_client.rs +++ b/distributed_cli/tests/cli_client.rs @@ -382,6 +382,53 @@ fn snapshot_tree(root: &Path) -> BTreeMap> { snapshot } +#[test] +fn literal_text_search_generates_a_typed_load_island() { + let project = project_dir("client-literal-text"); + fs::write( + project.join("client-manifest.json"), + ROLE_MANIFEST + .replace("\"_ilike\"", "\"_ilike\", \"_icontains\"") + // Adding a filter changes the selected schema contract. + .replace( + "sha256:758a97e4f7e1e538e8be86d24abd3d50a8da2d5813d29abd7a04bfa092d05189", + "sha256:9143345e62737d38ed28e997fd76f434b18ae6b9c794b2c06477d1879fcfc136", + ), + ) + .unwrap(); + write_document( + &project, + "queries/search.graphql", + r#" + query SearchTodos($q: String! = "") @load { + todos(where: {title: {_icontains: $q}}, limit: 20) { id title } + } + "#, + ); + assert_success( + &generate(&project, "queries/*.graphql", &[]), + "literal search generation", + ); + assert_success( + &generate(&project, "queries/*.graphql", &["--check"]), + "literal search drift check", + ); + let inventory = fs::read_to_string(project.join("generated/islands.json")).unwrap(); + assert!(inventory.contains("SearchTodos")); + assert!(inventory.contains("\"load\": true")); + assert!(inventory.contains("String!")); + write_document( + &project, + "queries/search.graphql", + r#" + query SearchTodos { todos(where: {title: {_icontains: 1}}) { id } } + "#, + ); + assert!(!generate(&project, "queries/*.graphql", &[]) + .status + .success()); +} + #[test] fn generate_then_check_accepts_the_exact_artifact_tree() { let project = project_dir("client-generate-check"); diff --git a/js/src/replica/identity/codec.ts b/js/src/replica/identity/codec.ts index 24f81b25a..b8649be2c 100644 --- a/js/src/replica/identity/codec.ts +++ b/js/src/replica/identity/codec.ts @@ -756,7 +756,7 @@ export function canonicalizeFilterComparison( canonical.push([operator, operand]); continue; } - if (operator === '_like' || operator === '_ilike' || operator === '_has_key') { + if (operator === '_like' || operator === '_ilike' || operator === '_icontains' || operator === '_has_key') { if (typeof operand !== 'string') { variableValueInvalid(operatorPath, 'expected string or null'); } @@ -972,7 +972,7 @@ export function validateFilterOperatorContract( path: string ): void { if ( - (operator === '_like' || operator === '_ilike') && + (operator === '_like' || operator === '_ilike' || operator === '_icontains') && scalar !== 'String' ) { variableCodecInvalid(path); diff --git a/js/src/replica/identity/constants.ts b/js/src/replica/identity/constants.ts index e4e26ef44..a2356384c 100644 --- a/js/src/replica/identity/constants.ts +++ b/js/src/replica/identity/constants.ts @@ -12,8 +12,8 @@ export const FILTER_OPERATORS = new Set([ '_is_null', '_like', '_ilike', + '_icontains', '_contains', '_contained_in', '_has_key' ]); - diff --git a/js/src/replica/query-plan/filter.ts b/js/src/replica/query-plan/filter.ts index d040f3a53..5307da7cc 100644 --- a/js/src/replica/query-plan/filter.ts +++ b/js/src/replica/query-plan/filter.ts @@ -484,6 +484,7 @@ export function evaluateComparison( if ( operator === '_like' || operator === '_ilike' || + operator === '_icontains' || operator === '_contains' || operator === '_contained_in' || operator === '_has_key' @@ -961,6 +962,7 @@ export function isFilterOperator(value: string): value is ReplicaFilterOperator value === '_is_null' || value === '_like' || value === '_ilike' || + value === '_icontains' || value === '_contains' || value === '_contained_in' || value === '_has_key' @@ -971,7 +973,7 @@ export function isOperatorScalarCompatible( scalar: string, operator: ReplicaFilterOperator ): boolean { - if (operator === '_like' || operator === '_ilike') { + if (operator === '_like' || operator === '_ilike' || operator === '_icontains') { return scalar === 'String'; } if ( diff --git a/js/src/replica/types.ts b/js/src/replica/types.ts index b39705c44..384cb2f81 100644 --- a/js/src/replica/types.ts +++ b/js/src/replica/types.ts @@ -217,6 +217,7 @@ export type ReplicaFilterOperator = | '_is_null' | '_like' | '_ilike' + | '_icontains' | '_contains' | '_contained_in' | '_has_key'; diff --git a/js/tests/replica-query-plan.test.mjs b/js/tests/replica-query-plan.test.mjs index 043b3247f..c4c4a5ccb 100644 --- a/js/tests/replica-query-plan.test.mjs +++ b/js/tests/replica-query-plan.test.mjs @@ -52,7 +52,8 @@ const FILTER_FIELDS = Object.freeze([ '_in', '_nin', '_like', - '_ilike' + '_ilike', + '_icontains' ]) }), Object.freeze({ @@ -387,6 +388,10 @@ test('query-plan artifacts require exact scalar-codec pairs', () => { test('unsafe operators, codecs, and absent canonical fields explain why evaluation is unknown', () => { const record = { id: 'todo-1', priority: 3, active: true, title: 'one', payload: null }; + assert.equal( + evaluateReplicaFilter(filterArtifact(literal({ title: { _icontains: 'ONE' } })), record).reason.code, + 'unsupported_operator' + ); assert.equal( evaluateReplicaFilter( filterArtifact(literal({ title: { _like: 'o%' } })), diff --git a/js/tests/replica-variable-codec.test.mjs b/js/tests/replica-variable-codec.test.mjs index ea02fce66..f180ef95f 100644 --- a/js/tests/replica-variable-codec.test.mjs +++ b/js/tests/replica-variable-codec.test.mjs @@ -104,7 +104,7 @@ const variableCodec = Object.freeze({ scalar: 'String', codec: 'string', nullable: false, - operators: Object.freeze(['_eq', '_like', '_ilike']) + operators: Object.freeze(['_eq', '_like', '_ilike', '_icontains']) }) ]), relationships: Object.freeze([ @@ -319,6 +319,21 @@ test('compiler variable codec canonicalizes ID, lists, filters, order, and key o assert.equal(JSON.stringify(singleton), JSON.stringify(expanded)); }); +test('literal text filters preserve operands and reject non-string values', () => { + for (const q of ['', '%_!\\\'OR 1=1', 'Älice']) { + const variables = { id: '1', where: { title: { _icontains: q } } }; + assert.deepEqual(canonicalizeOperationVariables(CodecArtifact, variables), variables); + } + for (const q of [12, true, {}, []]) { + assert.throws(() => canonicalizeOperationVariables(CodecArtifact, { + id: '1', where: { title: { _icontains: q } } + }), /expected string/); + } + assert.throws(() => canonicalizeOperationVariables(CodecArtifact, { + id: '1', where: { priority: { _icontains: '1' } } + })); +}); + test('scalar canonicalization is deterministic and preserves omission versus null', () => { const canonical = canonicalizeOperationVariables(CodecArtifact, { id: -0, diff --git a/src/graphql/compile/filter.rs b/src/graphql/compile/filter.rs index 077740703..c05342818 100644 --- a/src/graphql/compile/filter.rs +++ b/src/graphql/compile/filter.rs @@ -481,6 +481,25 @@ fn compile_client_op( ) -> Result { let col_ref = format!("{alias}.\"{column}\""); match op { + "_icontains" => { + let Value::String(text) = rhs else { + return Err("_icontains requires a string".into()); + }; + // Use an explicit escape character on both dialects. The operand + // stays a bind parameter; user text never becomes SQL or a wildcard. + let mut pattern = String::from("%"); + for ch in text.chars() { + if matches!(ch, '!' | '%' | '_') { + pattern.push('!'); + } + pattern.push(ch); + } + pattern.push('%'); + binds.push(value_to_bind(&Value::String(pattern), column_type)?); + let ph = placeholder(inner.dialect, binds.len()); + let sql_op = inner.dialect.ops().ilike_op; + Ok(format!("{col_ref} {sql_op} {ph} ESCAPE '!'")) + } "_is_null" => { let yes = matches!(rhs, Value::Boolean(true)); Ok(if yes { diff --git a/src/graphql/naming.rs b/src/graphql/naming.rs index 834f7f1a1..9742bedf7 100644 --- a/src/graphql/naming.rs +++ b/src/graphql/naming.rs @@ -104,7 +104,7 @@ pub const PORTABLE_COMPARISON_OPS: &[&str] = &[ ]; /// String-only comparison operators (portable; SQLite maps `_ilike` → `LIKE`). -pub const STRING_COMPARISON_OPS: &[&str] = &["_like", "_ilike"]; +pub const STRING_COMPARISON_OPS: &[&str] = &["_like", "_ilike", "_icontains"]; /// Postgres `jsonb` operators — only on `JSON_comparison_exp` when the engine /// dialect is Postgres. **Must not** appear on SQLite schema or SDL. @@ -254,6 +254,8 @@ mod tests { let string_ops = comparison_op_fields("String", false); assert!(string_ops.contains(&"_like")); assert!(string_ops.contains(&"_ilike")); + assert!(string_ops.contains(&"_icontains")); + assert!(!comparison_op_fields("Int", false).contains(&"_icontains")); assert!(!string_ops.contains(&"_contains")); } diff --git a/src/graphql/sdl.rs b/src/graphql/sdl.rs index 8af2e41fd..9c7dbda27 100644 --- a/src/graphql/sdl.rs +++ b/src/graphql/sdl.rs @@ -456,7 +456,7 @@ fn emit_comparison_exp(out: &mut String, scalar: &str, operators: &[String]) { let operand = match operator.as_str() { "_in" | "_nin" => format!("[{scalar}!]"), "_is_null" => "Boolean".into(), - "_like" | "_ilike" | "_has_key" => "String".into(), + "_like" | "_ilike" | "_icontains" | "_has_key" => "String".into(), _ => scalar.to_string(), }; out.push_str(&format!(" {operator}: {operand}\n")); diff --git a/tests/graphql_literal_text/main.rs b/tests/graphql_literal_text/main.rs new file mode 100644 index 000000000..9ee9f4a0b --- /dev/null +++ b/tests/graphql_literal_text/main.rs @@ -0,0 +1,162 @@ +//! Real-database coverage for literal search through the generated GraphQL API. +#![cfg(all(feature = "graphql", any(feature = "sqlite", feature = "postgres")))] + +use async_graphql::{Request, Variables}; +use distributed::{ + graphql::{claim, col, read, GraphqlEngine, ModelPermissions}, + microsvc::Session, + ReadModel, ROLE_KEY, USER_ID_KEY, +}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[table("gql_literal_text")] +struct SearchRow { + #[id("id")] + id: String, + label: Option, + owner: String, + number: i64, +} + +const DDL: &str = "CREATE TEMP TABLE gql_literal_text (id TEXT PRIMARY KEY, label TEXT, owner TEXT NOT NULL, number BIGINT NOT NULL)"; +const ROWS: &[(&str, Option<&str>, &str)] = &[ + ("01", Some("A%_!\\'BC"), "alice"), + ("02", Some("aZQ!\\'bc"), "alice"), + ("03", None, "alice"), + ("04", Some(""), "alice"), + ("05", Some("A%_!\\'BC"), "bob"), +]; + +fn permissions() -> ModelPermissions { + ModelPermissions::new().grant( + "user", + read() + .all_columns() + .rows(col("owner").eq(claim("x-user-id"))), + ) +} + +async fn verify(engine: GraphqlEngine) { + let mut session = Session::new(); + session.set(ROLE_KEY, "user"); + session.set(USER_ID_KEY, "alice"); + for (text, expected) in [ + ("%", vec!["01"]), + ("_", vec!["01"]), + ("%_", vec!["01"]), + ("!", vec!["01", "02"]), + ("\\", vec!["01", "02"]), + ("'", vec!["01", "02"]), + ("bc", vec!["01", "02"]), + ("a%_!\\'bc", vec!["01"]), + ("' OR 1=1 --", vec![]), + ("", vec!["01", "02", "04"]), + ] { + let response = engine.execute(&session, Request::new( + "query($q: String!) { gql_literal_text(where: {label: {_icontains: $q}}, order_by: [{id: asc}], limit: 20) {id} }" + ).variables(Variables::from_json(json!({"q": text})))).await; + assert!( + response.errors.is_empty(), + "{text:?}: {:?}", + response.errors + ); + let data = response.data.into_json().unwrap(); + let ids: Vec<_> = data["gql_literal_text"] + .as_array() + .unwrap() + .iter() + .map(|row| row["id"].as_str().unwrap()) + .collect(); + assert_eq!(ids, expected, "operand {text:?}"); + } + let page = engine.execute(&session, Request::new( + "{ gql_literal_text(where: {label: {_icontains: \"bc\"}}, order_by: [{id: asc}], limit: 1, offset: 1) {id} }" + )).await; + assert!(page.errors.is_empty(), "{:?}", page.errors); + assert_eq!( + page.data.into_json().unwrap(), + json!({"gql_literal_text":[{"id":"02"}]}) + ); + for query in [ + "{ gql_literal_text(where: {number: {_icontains: \"1\"}}) {id} }", + "{ gql_literal_text(where: {label: {_icontains: 1}}) {id} }", + ] { + assert!(!engine + .execute(&session, Request::new(query)) + .await + .errors + .is_empty()); + } + // Existing wildcard semantics remain intentionally different. + let pattern = engine.execute(&session, Request::new( + "{ gql_literal_text(where: {label: {_ilike: \"a%bc\"}}, order_by: [{id: asc}]) {id} }" + )).await; + assert!(pattern.errors.is_empty(), "{:?}", pattern.errors); + assert_eq!( + pattern.data.into_json().unwrap(), + json!({"gql_literal_text":[{"id":"01"},{"id":"02"}]}) + ); +} + +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn sqlite_literal_text() { + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); + sqlx::query(DDL).execute(&pool).await.unwrap(); + for (id, label, owner) in ROWS { + sqlx::query("INSERT INTO gql_literal_text VALUES (?, ?, ?, 1)") + .bind(id) + .bind(label) + .bind(owner) + .execute(&pool) + .await + .unwrap(); + } + verify( + GraphqlEngine::builder(pool) + .roles(&["user"]) + .model::(permissions()) + .build() + .unwrap(), + ) + .await; +} + +#[cfg(feature = "postgres")] +#[tokio::test] +async fn postgres_literal_text() { + let Ok(url) = std::env::var("DATABASE_URL") else { + eprintln!("skip: DATABASE_URL unset"); + return; + }; + // Session-local table and a single connection: no retained tables changed. + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&url) + .await + .unwrap(); + sqlx::query(DDL).execute(&pool).await.unwrap(); + for (id, label, owner) in ROWS { + sqlx::query("INSERT INTO gql_literal_text VALUES ($1, $2, $3, 1)") + .bind(id) + .bind(label) + .bind(owner) + .execute(&pool) + .await + .unwrap(); + } + verify( + GraphqlEngine::builder(pool) + .roles(&["user"]) + .model::(permissions()) + .build() + .unwrap(), + ) + .await; +} From 94bf8f3f8021a5b1141102e4e5aaf5cded94a583 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 04:34:59 -0500 Subject: [PATCH 072/484] test(graphql): refresh literal filter schema fingerprints --- distributed_cli/tests/cli_manifest.rs | 2 +- src/graphql/client_manifest/tests.rs | 2 +- src/graphql/engine/tests.rs | 37 ++++++++++--------- .../generated-draining-command-v2.json | 2 +- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/distributed_cli/tests/cli_manifest.rs b/distributed_cli/tests/cli_manifest.rs index 9e53f197d..86106da2d 100644 --- a/distributed_cli/tests/cli_manifest.rs +++ b/distributed_cli/tests/cli_manifest.rs @@ -74,7 +74,7 @@ fn client_manifest_uses_service_surface_export() { assert_eq!(manifest["surface"]["name"], "user"); assert_eq!( manifest["schema_fingerprint"], - "sha256:8f91d3fc7b6d916241b959f6bacd6228eeb06586e9681739ba3e986b4092e134" + "sha256:64007d9696cdd73fdbd3b12133155c53b709970ef2411631d9f66189c3c8fc90" ); assert_eq!( manifest["protocol_fingerprint"], diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 08a3efe6b..c0cb568ba 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -763,7 +763,7 @@ fn role_manifest_is_deterministic_and_hides_denied_identity_and_commands() { assert_eq!(first.schema_fingerprint, second.schema_fingerprint); assert_eq!( first.schema_fingerprint, - "sha256:d170cb2de47ed71c0127206a5a42970abff278cec2bcb494551da554053f3a83" + "sha256:d0e8509749ca7a9a4a1b48a785e448bb5e798e6376f920bc15ec9c07ac314d7c" ); assert_eq!( first.protocol_fingerprint, diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index 6dcf06364..ea2b2d2d9 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -1304,7 +1304,7 @@ mod client_surface_parity_tests { } assert_eq!( manifest.schema_fingerprint, - "sha256:7a456dac4fce3e4ccba7255baccad3e70e891f71ea476c1560631c9b2e5cf1da" + "sha256:cce38712ab7d84a934fa10bf1272d292d20f746aea5bf2e485fe15b2527517c0" ); } @@ -1439,7 +1439,7 @@ mod client_surface_parity_tests { assert_eq!(manifest.service_id, "orders-service"); assert_eq!( manifest.schema_fingerprint, - "sha256:7a599939c85d2f444428431675655d371929234965bdcfb6c81eba244694e6d0" + "sha256:9c0150e725493dc1e5ddbb3fdfc8b651cad399f099908cbcac326e514389c48a" ); } @@ -1845,10 +1845,13 @@ mod client_surface_parity_tests { let actual_manifest = sha256(&manifest_json); let actual_static_sdl = sha256(static_sdl.as_bytes()); let actual_runtime_sdl = sha256(runtime_sdl.as_bytes()); - assert_eq!(actual_manifest, expected.manifest, "{dialect:?}/{role}"); - assert_eq!(actual_static_sdl, expected.static_sdl, "{dialect:?}/{role}"); assert_eq!( - actual_runtime_sdl, expected.runtime_sdl, + ( + actual_manifest.as_str(), + actual_static_sdl.as_str(), + actual_runtime_sdl.as_str() + ), + (expected.manifest, expected.static_sdl, expected.runtime_sdl), "{dialect:?}/{role}" ); } @@ -1882,30 +1885,30 @@ mod client_surface_parity_tests { #[cfg(feature = "sqlite")] const SQLITE_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:a2b97c4156fd9e6c99c3ad516af5cf2c57781fa4f13757902685989a691b2515", - static_sdl: "sha256:6ac07aaa60a726bdde7c1632125a3ab933766931187654dacc2dd4ab19ffece1", - runtime_sdl: "sha256:fb41d43fa1b58fec7224d768124abc8bb0b30407e1ee56b44f620ddc8d8c0007", + manifest: "sha256:c1c3dd3f242f82225b486542b1737976f791e019f50e015f8755f48d70685f9a", + static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", + runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", }; #[cfg(feature = "sqlite")] const SQLITE_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:4619fb257bd0b3b0155ebdff5f34a8d15f6c23bc0fc8a99459e7d56aad444932", - static_sdl: "sha256:4d7ba7651ff632d32e538a083165ff718e094858c6c5bdb2705d38d9f0665e2f", - runtime_sdl: "sha256:be0f13249ec0cb394457572097a1d201649deeec1eba9c980f48b1751a13062b", + manifest: "sha256:94345b9e29bccaa77aa5083eb73014a1a102db7ce1f03f022a2f0e242b5c84d2", + static_sdl: "sha256:128b85bcd6485d14de62b0976e9f12e8b35ad9e7d96a5627d1edcfcabdb591b3", + runtime_sdl: "sha256:c0b6d600d353357ab4f393897fb6b7ee51f69546f7a4cc4b6786e42abe621f5c", }; #[cfg(feature = "postgres")] const POSTGRES_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:a2b97c4156fd9e6c99c3ad516af5cf2c57781fa4f13757902685989a691b2515", - static_sdl: "sha256:6ac07aaa60a726bdde7c1632125a3ab933766931187654dacc2dd4ab19ffece1", - runtime_sdl: "sha256:fb41d43fa1b58fec7224d768124abc8bb0b30407e1ee56b44f620ddc8d8c0007", + manifest: "sha256:c1c3dd3f242f82225b486542b1737976f791e019f50e015f8755f48d70685f9a", + static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", + runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", }; #[cfg(feature = "postgres")] const POSTGRES_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:66cddbcf76eac385f94de011497fe4752f7fb6102de28c14c24d83c67367788b", - static_sdl: "sha256:d128621aea3ffa6c38abc44a9b7f3b2716aada4af4b579b10e7c415040281751", - runtime_sdl: "sha256:ae58e2ed718955a6d400197a4cfa2f363d3057c80c6f4e528d10615a3df804cb", + manifest: "sha256:8ff2691f33789c8267b1338603b2ee3544841f8b17cc5b90ea2e851381dd36de", + static_sdl: "sha256:afe92660c1700845ed5f3e0ddaacc4b481799c39f86b8eacecb46d1b8f99d421", + runtime_sdl: "sha256:de4885736fdf22a57ccc55160d63b6d1a7fdb33728dec399e8a81d54ce7e8c09", }; #[cfg(feature = "sqlite")] diff --git a/tests/fixtures/generated-draining-command-v2.json b/tests/fixtures/generated-draining-command-v2.json index 6cb960291..17ccf0ae8 100644 --- a/tests/fixtures/generated-draining-command-v2.json +++ b/tests/fixtures/generated-draining-command-v2.json @@ -39,7 +39,7 @@ "protocol": { "operation": "sha256:bb3a777dd32f7d40cccc173fafdbc7464f5dc50a3d17587909689a880fb0205a", "protocolHash": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", - "schemaHash": "sha256:2a4fd759519caaa13088228accd4fad4df3a0bc1bd19d1a9be323ad58cab29c1", + "schemaHash": "sha256:7e4d542ce141b2a9f350433b03603ae0ebfecd38c15b2e9d436fe8d0bca2662b", "surface": { "kind": "role", "name": "admin" From 95945aeaa3a1668563b89d43828761ad05b88438 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 10:32:23 -0500 Subject: [PATCH 073/484] fix: hand off older query graphs to live subscriptions --- docs/live-query-delivery.md | 7 ++ .../distributed-replica/impl-fetch-live.ts | 3 +- js/src/replica/distributed-replica/impl.ts | 10 +++ js/src/replica/distributed-replica/types.ts | 2 + js/tests/replica-protocol.test.mjs | 80 +++++++++++++++++++ 5 files changed, 101 insertions(+), 1 deletion(-) diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md index 970b4a4c5..ce58e8238 100644 --- a/docs/live-query-delivery.md +++ b/docs/live-query-delivery.md @@ -23,6 +23,13 @@ from disposed subscriptions and previous authorization generations. Local cache membership revisions are not server projection positions and cannot confirm optimistic commands. +A subscription also records its local start order. Snapshot delivery can take +over shared relationships owned by queries that preceded that subscription, +including SSR seeds from a layout or another island. This lets an initially +empty result acquire rows without waiting for another page load. It does not +override an independently active live stream or query ownership acquired after +the subscription started; those results have no safe cross-stream ordering. + This is a breaking v5 protocol change: `mode` replaces the ambiguous `supported` boolean. Upgrade server and generated-client runtime together. Old or unknown wire forms fail closed; applications do not need a polling or reload workaround. diff --git a/js/src/replica/distributed-replica/impl-fetch-live.ts b/js/src/replica/distributed-replica/impl-fetch-live.ts index 72f55dbaf..0882d5fbb 100644 --- a/js/src/replica/distributed-replica/impl-fetch-live.ts +++ b/js/src/replica/distributed-replica/impl-fetch-live.ts @@ -238,7 +238,8 @@ export function retainLive( count: 1, unsubscribe: () => undefined, active: true, - protocolGeneration: host.protocolGenerationSequence() + protocolGeneration: host.protocolGenerationSequence(), + startRevision: host.allocateIndexRevision() }; host.lives.set(watch.key, entry); const resume = host.resumeCursors(watch.key); diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index e3eea0813..4d8fbb33f 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -2320,6 +2320,9 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { if (incomingIndexKeys.size === 0) return { compared: false }; const confirmedRevisions = this.#confirmedIndexFences(incomingIndexKeys); + const liveStart = source === 'live' && !snapshot.indexesComparable + ? this.#lives.get(currentKey)?.startRevision + : undefined; let compared = false; let lower = false; let higher = false; @@ -2370,6 +2373,13 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { disposition === 'fresh' || disposition === 'incomparable' ) { + // A registered stream starts after the query seeds already in + // this replica. It can take over those seeds, but not another + // live stream or query ownership acquired after it started. + if ( + liveStart !== undefined && state === group.query && + compareCanonicalDecimalStrings(liveStart, state.indexRevision) > 0 + ) continue; incomparable = true; continue; } diff --git a/js/src/replica/distributed-replica/types.ts b/js/src/replica/distributed-replica/types.ts index 8dee80163..5d8761e79 100644 --- a/js/src/replica/distributed-replica/types.ts +++ b/js/src/replica/distributed-replica/types.ts @@ -30,6 +30,8 @@ export type LiveEntry = { unsubscribe: () => void; active: boolean; protocolGeneration: number; + /** Local fence for taking over query snapshots that preceded this stream. */ + startRevision: string; operationGeneration?: number; }; diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index 20f70258a..006203ef7 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -1975,6 +1975,86 @@ test('snapshot live replaces SSR membership, updates and removes rows, and fence assert.deepEqual(replica.read(Todos, {}).data.todos, []); }); +test('snapshot live adds a row with an unchanged SSR-owned nested relationship', () => { + let observer; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, next) { observer = next; return () => {}; } + } }); + replica.writeResult(FeaturedGamesWithOwner, {}, gamesFrame({ + artifact: FeaturedGamesWithOwner, responseKey: 'featuredGames', + position: '1', ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }), 'ssr'); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + position: '1', ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const watch = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observer.next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, + position: '2', ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(watch.get().errors, []); + assert.equal(watch.get().complete, true); + assert.equal(watch.get().data.games.length, 1, 'unchanged sibling relationship must not freeze an empty root'); + assert.equal(watch.get().data.games[0].owner.name, 'Owner'); + assert.equal(replica.read(FeaturedGamesWithOwner, {}).data.featuredGames[0].owner.name, 'Owner'); + observer.next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, + position: '3', ownerId: 'user-2', ownerName: 'Changed', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.equal(watch.get().data.games[0].owner.name, 'Changed'); + const removed = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, + position: '4', ownerId: 'user-2', ownerName: 'Changed', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + removed.data.games = []; + removed.extensions.distributed.snapshot.records = []; + observer.next(removed); + assert.deepEqual(watch.get().data.games, []); + assert.equal(watch.get().live, 'active'); + watch.destroy(); +}); + +test('snapshot live cannot take over query ownership acquired after stream start', () => { + let observer; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, next) { observer = next; return () => {}; } + } }); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + position: '1', ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const watch = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + replica.writeResult(FeaturedGamesWithOwner, {}, gamesFrame({ + artifact: FeaturedGamesWithOwner, responseKey: 'featuredGames', + position: '2', ownerId: 'user-2', ownerName: 'New query', indexesComparable: false + }), 'network'); + observer.next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, + position: '1', ownerId: 'user-1', ownerName: 'Old stream', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(watch.get().errors, []); + assert.deepEqual(watch.get().data.games, []); + assert.equal(replica.read(FeaturedGamesWithOwner, {}).data.featuredGames[0].owner.name, 'New query'); + watch.destroy(); +}); + test('snapshot authorization changes discard the old stream and reconnect without cursors', async () => { const subscriptions = []; const requests = []; From 66e911124dd2c377caff89f890c3f28a64aad73f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 11:13:31 -0500 Subject: [PATCH 074/484] test: capture redacted replica state on refresh failures --- tests/e2e-ui/gateway/refresh.mjs | 6 +++++- tests/e2e-ui/gateway/run.mjs | 4 +++- tests/e2e-ui/ui/src/routes/+layout.svelte | 7 +++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/tests/e2e-ui/gateway/refresh.mjs b/tests/e2e-ui/gateway/refresh.mjs index cdab9ca85..c5895a35f 100644 --- a/tests/e2e-ui/gateway/refresh.mjs +++ b/tests/e2e-ui/gateway/refresh.mjs @@ -56,7 +56,11 @@ export async function verifySessionRefreshContinuity(page, origin) { await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))); } assert.deepEqual(navigations,[],'session refresh must not navigate the document'); - assert.equal(await page.evaluate(()=>globalThis.__refreshContinuity.lost),false,route+' rows were removed during token refresh: '+JSON.stringify(await page.evaluate(()=>globalThis.__refreshContinuity.events))); + const lost = await page.evaluate(()=>globalThis.__refreshContinuity.lost); + if (lost) { + console.error('Redacted refresh replica diagnostics:', JSON.stringify(await page.evaluate(()=>globalThis.__replicaDiagnosticSnapshot?.()))); + } + assert.equal(lost,false,route+' rows were removed during token refresh: '+JSON.stringify(await page.evaluate(()=>globalThis.__refreshContinuity.events))); } finally { releaseRefresh(); await page.unroute('**/api/auth/refresh',refreshRoute); diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 92b693963..1282a02d9 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -55,7 +55,9 @@ try{ const ack=await fetch(publicOrigin+'/__distributed/lifecycle',{method:'POST',headers:{origin:publicOrigin,'content-type':'application/json'},body:JSON.stringify({participantId:participant,transitionId:'gateway_ci_no_transition',ok:true})}); assert.equal(ack.status,409,'same-origin acknowledgement reaches lifecycle state validation'); } - browser=await chromium.launch();const context=await browser.newContext();const page=await context.newPage(); + browser=await chromium.launch();const context=await browser.newContext(); + await context.addInitScript(()=>{globalThis.__captureReplicaDiagnostics=true;}); + const page=await context.newPage(); const errors=[];page.on('pageerror',error=>errors.push(error.message)); await page.goto(publicOrigin);await page.getByRole('link',{name:/log in|sign in/i}).first().click(); await page.getByRole('button',{name:'Continue as Alice'}).click(); diff --git a/tests/e2e-ui/ui/src/routes/+layout.svelte b/tests/e2e-ui/ui/src/routes/+layout.svelte index e8425bb0a..cd8bb97f4 100644 --- a/tests/e2e-ui/ui/src/routes/+layout.svelte +++ b/tests/e2e-ui/ui/src/routes/+layout.svelte @@ -2,6 +2,7 @@ import '../app.css'; import '$lib/styles/chrome.css'; import { browser } from '$app/environment'; + import { createReplicaDiagnostics } from '@hops-ops/distributed/replica'; import { page } from '$app/state'; import { onDestroy, untrack } from 'svelte'; import type { Snippet } from 'svelte'; @@ -35,7 +36,13 @@ diagnostics.__distributedReloadState = lifecycleDemoState; } + const replicaDiagnostics = browser && (globalThis as typeof globalThis & Record).__captureReplicaDiagnostics === true + ? createReplicaDiagnostics() : undefined; + if (replicaDiagnostics) { + (globalThis as typeof globalThis & Record).__replicaDiagnosticSnapshot = () => replicaDiagnostics.snapshot(); + } const client = provideDistributed({ + ...(replicaDiagnostics ? { replica: { diagnostics: replicaDiagnostics } } : {}), boundaries: DISTRIBUTED_BOUNDARY_OPERATIONS, session: pageData.session, browser, From 856e3bec9b31ba03b469dc3932266a44aaa7b280 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 12:53:29 -0500 Subject: [PATCH 075/484] fix: retire disposed live ownership --- docs/live-query-delivery.md | 10 + .../replica/distributed-replica/hydration.ts | 21 ++ .../distributed-replica/impl-fetch-live.ts | 26 +- js/src/replica/distributed-replica/impl.ts | 15 + js/src/replica/distributed-replica/types.ts | 4 + js/tests/replica-protocol.test.mjs | 350 ++++++++++++++++++ 6 files changed, 425 insertions(+), 1 deletion(-) diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md index ce58e8238..78931e7af 100644 --- a/docs/live-query-delivery.md +++ b/docs/live-query-delivery.md @@ -30,6 +30,16 @@ empty result acquire rows without waiting for another page load. It does not override an independently active live stream or query ownership acquired after the subscription started; those results have no safe cross-stream ordering. +When the last watch for a live operation is disposed, its local ownership is +retired at a monotonically increasing local boundary. A later live subscription +may take over an incomparable shared index only when that subscription started +after the retirement boundary. A subscription that started while the previous +stream was still active remains fenced against late frames from that stream. +Reopening the retired operation clears its retirement marker before transport +callbacks can arrive, so the reopened stream becomes an active owner again. +Retirement is local replica metadata; it does not claim that the server's +projection stopped or provide a server ordering signal. + This is a breaking v5 protocol change: `mode` replaces the ambiguous `supported` boolean. Upgrade server and generated-client runtime together. Old or unknown wire forms fail closed; applications do not need a polling or reload workaround. diff --git a/js/src/replica/distributed-replica/hydration.ts b/js/src/replica/distributed-replica/hydration.ts index 113cce337..6b5f8cac5 100644 --- a/js/src/replica/distributed-replica/hydration.ts +++ b/js/src/replica/distributed-replica/hydration.ts @@ -64,6 +64,9 @@ export function serializeOperationProtocolState( ...(state.indexRevision === undefined ? {} : { indexRevision: state.indexRevision }), + ...(state.retiredAtRevision === undefined + ? {} + : { retiredAtRevision: state.retiredAtRevision }), indexKeys: Object.freeze([...state.indexKeys].sort()), pathRecords: Object.freeze( [...state.pathRecords] @@ -375,6 +378,15 @@ export function parseReplicaHydration( ) { hydrationInvalid('state.payload.nextIndexRevision'); } + if ( + operation?.retiredAtRevision !== undefined && + compareDistributedDecimal( + operation.retiredAtRevision as DistributedDecimalString, + nextIndexRevision + ) > 0 + ) { + hydrationInvalid('state.payload.nextIndexRevision'); + } } } return { @@ -405,6 +417,7 @@ export function parseOperationProtocolState( 'snapshotScope', 'indexClocks', 'indexRevision', + 'retiredAtRevision', 'indexKeys', 'pathRecords', 'cursors' @@ -502,6 +515,14 @@ export function parseOperationProtocolState( `${path}.indexRevision` ) }), + ...(raw.retiredAtRevision === undefined + ? {} + : { + retiredAtRevision: hydrationDecimal( + raw.retiredAtRevision, + `${path}.retiredAtRevision` + ) + }), indexKeys, pathRecords, cursors: Object.freeze(cursors) diff --git a/js/src/replica/distributed-replica/impl-fetch-live.ts b/js/src/replica/distributed-replica/impl-fetch-live.ts index 0882d5fbb..5211aeee4 100644 --- a/js/src/replica/distributed-replica/impl-fetch-live.ts +++ b/js/src/replica/distributed-replica/impl-fetch-live.ts @@ -65,7 +65,8 @@ export function emitWatchState(host: FetchLiveHost, key: string, allowFetch: boo export function closeActiveTransports(host: FetchLiveHost): void { for (const controller of host.inFlightAborts.values()) controller.abort(); host.inFlightAborts.clear(); - for (const entry of host.lives.values()) { + for (const [key, entry] of host.lives) { + retireLiveProtocol(host, key); entry.active = false; try { entry.unsubscribe(); @@ -232,6 +233,7 @@ export function retainLive( existing.count += 1; return; } + clearRetiredLiveProtocol(host, watch.key); const state = host.queryState(watch.key); state.live = 'connecting'; const entry: LiveEntry = { @@ -328,6 +330,7 @@ export function retainLive( }, error: (error) => { if (!entry.active || host.lives.get(watch.key) !== entry) return; + retireLiveProtocol(host, watch.key); entry.active = false; host.lives.delete(watch.key); const unsub = entry.unsubscribe; @@ -359,6 +362,7 @@ export function retainLive( } state.live = 'active'; } catch (error) { + retireLiveProtocol(host, watch.key); entry.active = false; host.lives.delete(watch.key); state.live = 'error'; @@ -376,6 +380,7 @@ export function fallbackFromLive( void fetchWatch(host, watch, true); return; } + retireLiveProtocol(host, watch.key); const protocol = host.operationProtocols.get(watch.key); if (protocol?.active === 'live') protocol.active = undefined; entry.active = false; @@ -426,6 +431,7 @@ export function restartLive(host: FetchLiveHost, key: string): void { const previous = host.lives.get(key); if (previous === undefined) return; const count = previous.count; + retireLiveProtocol(host, key); previous.active = false; host.lives.delete(key); try { @@ -465,6 +471,7 @@ export function releaseLive(host: FetchLiveHost, key: string): void { if (!entry) return; entry.count -= 1; if (entry.count > 0) return; + retireLiveProtocol(host, key); entry.active = false; host.lives.delete(key); entry.unsubscribe(); @@ -472,6 +479,23 @@ export function releaseLive(host: FetchLiveHost, key: string): void { host.emitState(key, false); } +/** + * Mark protocol state as no longer backed by a live transport. The state is + * retained for cache and hydration bookkeeping, but a later live stream may + * replace its incomparable membership only when that stream started after + * this boundary. + */ +function retireLiveProtocol(host: FetchLiveHost, key: string): void { + const state = host.operationProtocols.get(key)?.live; + if (state === undefined) return; + state.retiredAtRevision = host.allocateIndexRevision(); +} + +function clearRetiredLiveProtocol(host: FetchLiveHost, key: string): void { + const state = host.operationProtocols.get(key)?.live; + if (state !== undefined) state.retiredAtRevision = undefined; +} + function requestExtensions( host: FetchLiveHost, artifact: ReplicaOperationArtifact, diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index 4d8fbb33f..a18077834 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -2344,6 +2344,21 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { } } if (!ownsIncomingIndex) continue; + if ( + !snapshot.indexesComparable && + state === group.live && + state.retiredAtRevision !== undefined && + liveStart !== undefined && + compareCanonicalDecimalStrings( + liveStart, + state.retiredAtRevision + ) > 0 + ) { + // A disposed stream is no longer an owner. Its boundary is + // still retained so a stream that started before disposal + // cannot win merely because the old transport later closed. + continue; + } latestOwnerRevision = latestOwnerRevision === undefined || compareCanonicalDecimalStrings( diff --git a/js/src/replica/distributed-replica/types.ts b/js/src/replica/distributed-replica/types.ts index 5d8761e79..4ae8faade 100644 --- a/js/src/replica/distributed-replica/types.ts +++ b/js/src/replica/distributed-replica/types.ts @@ -55,6 +55,8 @@ export type SerializedOperationProtocolState = { Readonly<{ scopeToken: string; position: string }> ])[]; readonly indexRevision?: string; + /** Local boundary after which a disposed live owner may be handed off. */ + readonly retiredAtRevision?: string; readonly indexKeys: readonly string[]; readonly pathRecords: readonly (readonly [string, string])[]; readonly cursors: readonly DistributedLiveCursor[]; @@ -140,6 +142,8 @@ export type OperationProtocolState = { snapshotScope?: DistributedOpaqueString; indexClocks: Map; indexRevision?: string; + /** Local boundary after which a disposed live owner may be handed off. */ + retiredAtRevision?: string; indexKeys: Set; pathRecords: Map; cursors: readonly DistributedLiveCursor[]; diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index 006203ef7..b76de6401 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -1975,6 +1975,356 @@ test('snapshot live replaces SSR membership, updates and removes rows, and fence assert.deepEqual(replica.read(Todos, {}).data.todos, []); }); +test('snapshot live takes over a nested graph from a disposed page subscription', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner', document: 'subscription FeaturedOwner { featuredGames { id owner { id name } } }' } + }; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + } }); + const oldFrame = (position, ownerName = 'Owner') => gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', + operation: previousPage.live.id, position, + ownerId: 'user-1', ownerName, indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + replica.writeResult(previousPage, {}, gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }), 'ssr'); + const oldWatch = replica.watch(previousPage, {}, { live: true }); + observers[0].next(oldFrame('2')); + oldWatch.destroy(); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const current = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '3', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(current.get().errors, []); + assert.equal(current.get().complete, true); + assert.equal(current.get().data.games.length, 1, 'disposed page must not permanently own the shared relationship'); + observers[0].next(oldFrame('4', 'Late disposed callback')); + assert.equal(current.get().data.games[0].owner.name, 'Owner'); + current.destroy(); +}); + +test('snapshot live keeps a stream started before disposal behind the retired owner', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner-before-disposal', document: 'subscription FeaturedOwnerBeforeDisposal { featuredGames { id owner { id name } } }' } + }; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + } }); + const oldFrame = (ownerName) => gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', operation: previousPage.live.id, + position: '2', ownerId: 'user-1', ownerName, indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + const oldWatch = replica.watch(previousPage, {}, { live: true }); + observers[0].next(oldFrame('active owner')); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const current = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '3', + ownerId: 'user-1', ownerName: 'started before disposal', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(current.get().data.games, []); + oldWatch.destroy(); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '4', + ownerId: 'user-1', ownerName: 'still started before disposal', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(current.get().data.games, []); + current.destroy(); +}); + +test('reopening a retired live owner restores its ownership fence', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner-reopened', document: 'subscription FeaturedOwnerReopened { featuredGames { id owner { id name } } }' } + }; + const frame = (artifact, responseKey, operation, position, ownerName) => gamesFrame({ + artifact, responseKey, operation, position, ownerId: 'user-1', ownerName, + indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } + }); + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { + observers.push(observer); + if (observers.length === 2) { + observer.next(frame(previousPage, 'featuredGames', previousPage.live.id, '3', 'reopened owner')); + } + return () => {}; + } } }); + const first = replica.watch(previousPage, {}, { live: true }); + observers[0].next(frame(previousPage, 'featuredGames', previousPage.live.id, '2', 'first owner')); + first.destroy(); + const reopened = replica.watch(previousPage, {}, { live: true }); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const current = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observers[2].next(frame( + GamesWithOwnerLiveOperation, + 'games', + GamesWithOwnerLiveOperation.live.id, + '4', + 'current contender' + )); + assert.deepEqual(current.get().data.games, []); + reopened.destroy(); + current.destroy(); +}); + +test('reopening a retired live owner clears the marker before its first frame', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner-reopened-empty', document: 'subscription FeaturedOwnerReopenedEmpty { featuredGames { id owner { id name } } }' } + }; + const frame = (artifact, responseKey, operation, position, ownerName) => gamesFrame({ + artifact, responseKey, operation, position, ownerId: 'user-1', ownerName, + indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } + }); + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + } }); + const first = replica.watch(previousPage, {}, { live: true }); + observers[0].next(frame(previousPage, 'featuredGames', previousPage.live.id, '2', 'first owner')); + first.destroy(); + // Reopen the operation, but do not deliver a frame yet. The replacement + // stream must still be treated as an active owner immediately. + const reopened = replica.watch(previousPage, {}, { live: true }); + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const contender = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observers[1].next(frame( + GamesWithOwnerLiveOperation, + 'games', + GamesWithOwnerLiveOperation.live.id, + '3', + 'contender before reopened frame' + )); + assert.deepEqual(contender.get().data.games, []); + reopened.destroy(); + contender.destroy(); +}); + +test('two watches retire shared live ownership only after final disposal', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner-refcount', document: 'subscription FeaturedOwnerRefcount { featuredGames { id owner { id name } } }' } + }; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + } }); + const oldFrame = (ownerName) => gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', operation: previousPage.live.id, + position: '2', ownerId: 'user-1', ownerName, indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + const first = replica.watch(previousPage, {}, { live: true }); + const second = replica.watch(previousPage, {}, { live: true }); + assert.equal(observers.length, 1, 'same operation shares one live transport'); + observers[0].next(oldFrame('active owner')); + first.destroy(); + + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const startedBeforeFinalRelease = replica.watch( + GamesWithOwnerLiveOperation, + {}, + { live: true } + ); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '3', + ownerId: 'user-1', ownerName: 'before final release', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(startedBeforeFinalRelease.get().data.games, []); + second.destroy(); + observers[0].next(oldFrame('late disposed callback')); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '4', + ownerId: 'user-1', ownerName: 'still before final release', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(startedBeforeFinalRelease.get().data.games, []); + startedBeforeFinalRelease.destroy(); + + const afterFinalRelease = replica.watch( + GamesWithOwnerLiveOperation, + {}, + { live: true } + ); + observers[2].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '5', + ownerId: 'user-1', ownerName: 'after final release', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.equal(afterFinalRelease.get().data.games[0].owner.name, 'after final release'); + afterFinalRelease.destroy(); +}); + +test('terminal live retirement permits a later snapshot handoff', () => { + for (const terminal of ['error', 'complete']) { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: `live:featured-owner-${terminal}`, document: `subscription FeaturedOwner${terminal} { featuredGames { id owner { id name } } }` } + }; + const replica = createDistributedReplica({ transport: { + fetch() { throw new Error('terminal stream test does not need HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + } }); + const oldFrame = gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', operation: previousPage.live.id, + position: '2', ownerId: 'user-1', ownerName: `${terminal} owner`, indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + replica.writeResult(previousPage, {}, gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', position: '1', + ownerId: 'user-1', ownerName: `${terminal} owner`, indexesComparable: false + }), 'ssr'); + const oldWatch = replica.watch(previousPage, {}, { live: true }); + observers[0].next(oldFrame); + if (terminal === 'error') observers[0].error(new Error('terminal test error')); + else observers[0].complete(); + // A terminal transport is no longer the page's live request. Dispose the + // watcher before another page seeds the same shared index; an error may + // otherwise be intentionally resumed by the replica on the next write. + oldWatch.destroy(); + + const empty = gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', position: '1', + ownerId: 'user-1', ownerName: 'Owner', indexesComparable: false + }); + empty.data.games = []; + empty.extensions.distributed.snapshot.records = []; + replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); + const current = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '3', + ownerId: 'user-1', ownerName: `${terminal} handoff`, indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.equal(current.get().data.games.length, 1, `${terminal} handoff should replace the retired owner`); + assert.equal(current.get().data.games[0].owner.name, `${terminal} handoff`); + observers[0].next(oldFrame); + assert.equal(current.get().data.games[0].owner.name, `${terminal} handoff`); + current.destroy(); + } +}); + +test('retired live ownership survives dehydration before a later handoff', () => { + const observers = []; + const previousPage = { + ...FeaturedGamesWithOwner, + live: { id: 'live:featured-owner-hydrated', document: 'subscription FeaturedOwnerHydrated { featuredGames { id owner { id name } } }' } + }; + const transport = { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { observers.push(observer); return () => {}; } + }; + const replica = createDistributedReplica({ transport }); + const oldFrame = gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', + operation: previousPage.live.id, position: '2', ownerId: 'user-1', + ownerName: 'retired owner', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + }); + replica.writeResult(previousPage, {}, gamesFrame({ + artifact: previousPage, responseKey: 'featuredGames', position: '1', + ownerId: 'user-1', ownerName: 'retired owner', indexesComparable: false + }), 'ssr'); + replica.read(previousPage, {}); + const oldWatch = replica.watch(previousPage, {}, { live: true }); + observers[0].next(oldFrame); + oldWatch.destroy(); + const dehydrated = replica.dehydrate(); + const oldProtocol = dehydrated.payload.operations.find((entry) => + entry.live?.retiredAtRevision !== undefined + ); + assert.ok(oldProtocol?.live?.retiredAtRevision !== undefined); + + const restoredObservers = []; + const restored = createDistributedReplica({ + transport: { + fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, + subscribe(_request, observer) { restoredObservers.push(observer); return () => {}; } + } + }); + assert.equal(restored.hydrate(dehydrated, dehydrated.scope), true); + const current = restored.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + restoredObservers[0].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '3', + ownerId: 'user-1', ownerName: 'hydrated handoff', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.equal(current.get().data.games.length, 1); + assert.equal(restored.hydrate(dehydrated, dehydrated.scope), true); + assert.equal(restoredObservers.length, 2); + restoredObservers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '4', + ownerId: 'user-1', ownerName: 'active receiver after hydrate', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + const contender = restored.watch(previousPage, {}, { live: true }); + restoredObservers[2].next(oldFrame); + assert.equal(current.get().data.games[0].owner.name, 'active receiver after hydrate'); + contender.destroy(); + current.destroy(); +}); + test('snapshot live adds a row with an unchanged SSR-owned nested relationship', () => { let observer; const replica = createDistributedReplica({ transport: { From 7834594f7dfafd90fe4ba8dd84165eb20d41593d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 16:37:44 -0500 Subject: [PATCH 076/484] fix: retain modeled wait-path obligations --- js/tests/replica-command-runtime.test.mjs | 319 +++++++++++++++++++--- src/graphql/projection_delta/tests.rs | 169 ++++++++++++ src/microsvc/service/causal.rs | 52 +--- 3 files changed, 457 insertions(+), 83 deletions(-) diff --git a/js/tests/replica-command-runtime.test.mjs b/js/tests/replica-command-runtime.test.mjs index 74e11de41..a17865ff6 100644 --- a/js/tests/replica-command-runtime.test.mjs +++ b/js/tests/replica-command-runtime.test.mjs @@ -12,6 +12,7 @@ import { ReplicaCommandRuntimeError } from '../dist/replica/command-runtime.js'; import { + createDistributedReplica, prepareReplicaCommand, replicaRecordKey, ReplicaCommandContractError @@ -21,6 +22,11 @@ import { COMMAND_STATE, commandReceipt } from './fixtures/command-protocol.mjs'; +import { + TodosArtifact, + TodoModel, + todoFrame +} from './fixtures/adapter-conformance.mjs'; const HASH_A = `sha256:${'a'.repeat(64)}`; const HASH_B = `sha256:${'b'.repeat(64)}`; @@ -46,6 +52,24 @@ const Todo = Object.freeze({ id: 'Todos', identityFields: Object.freeze(['id']) }); + +// Reuse the generated query/live selection while matching the command +// runtime's authoritative protocol scope. This keeps the regression on the +// public replica and generated-command paths rather than a hand-built cache. +const CommandTodos = Object.freeze({ + ...TodosArtifact, + id: 'query:command-runtime-todos', + protocol: Object.freeze({ + ...TodosArtifact.protocol, + schemaHash: HASH_B, + surface: SURFACE, + operation: 'query:command-runtime-todos' + }), + live: Object.freeze({ + ...TodosArtifact.live, + id: 'live:command-runtime-todos' + }) +}); const Audit = Object.freeze({ id: 'Audits', identityFields: Object.freeze(['id']) @@ -88,14 +112,15 @@ function scope(value, model = Todo.id) { }); } -function projection(operation = 'upsert') { +function projection(operation = 'upsert', model = Todo) { const event = Object.freeze({ id: 'event-1', name: 'todo.changed', version: 1 }); - const previewScope = scope(input(['id'])); + const previewScope = scope(input(['id']), model.id); const targetScope = scope( Object.freeze({ kind: 'constant', value: Object.freeze({ type: 'string', value: 'target' }) - }) + }), + model.id ); let mutation; if (operation === 'upsert') { @@ -130,7 +155,7 @@ function projection(operation = 'upsert') { mutation = Object.freeze({ op: 'invalidate_model', partition: unit, - model: Todo.id + model: model.id }); } else { mutation = Object.freeze({ @@ -144,40 +169,40 @@ function projection(operation = 'upsert') { ? Object.freeze({ kind: 'relationship', relationship: 'related', - source_model: Todo.id, + source_model: model.id, source_key: Object.freeze(['id']), - target_model: Todo.id, + target_model: model.id, target_key: Object.freeze(['id']), link: operation === 'link', unlink: operation === 'unlink' }) - : operation === 'invalidate_model' - ? Object.freeze({ kind: 'model', model: Todo.id }) - : operation === 'invalidate_relationship' - ? Object.freeze({ - kind: 'relationship', - relationship: 'related', - source_model: Todo.id, - source_key: Object.freeze(['id']), - target_model: Todo.id, - target_key: Object.freeze(['id']), - link: false, - unlink: false - }) - : Object.freeze({ - kind: 'record', - model: Todo.id, - key: Object.freeze(['id']), - fields: Object.freeze( - operation === 'delete' ? [] : ['title'] - ), - replace: Object.freeze( - operation === 'upsert' ? ['title'] : [] - ), - upsert: operation === 'upsert', - patch: operation === 'patch', - delete: operation === 'delete' - }); + : operation === 'invalidate_model' + ? Object.freeze({ kind: 'model', model: model.id }) + : operation === 'invalidate_relationship' + ? Object.freeze({ + kind: 'relationship', + relationship: 'related', + source_model: model.id, + source_key: Object.freeze(['id']), + target_model: model.id, + target_key: Object.freeze(['id']), + link: false, + unlink: false + }) + : Object.freeze({ + kind: 'record', + model: model.id, + key: Object.freeze(['id']), + fields: Object.freeze( + operation === 'delete' ? [] : ['title'] + ), + replace: Object.freeze( + operation === 'upsert' ? ['title'] : [] + ), + upsert: operation === 'upsert', + patch: operation === 'patch', + delete: operation === 'delete' + }); return Object.freeze({ version: 2, deltaWireVersion: 1, @@ -225,6 +250,7 @@ function projection(operation = 'upsert') { function artifact(options = {}) { const operation = options.operation ?? 'upsert'; + const model = options.model ?? Todo; return Object.freeze({ version: 2, name: options.name ?? `todo.${operation}`, @@ -243,7 +269,9 @@ function artifact(options = {}) { input: Object.freeze({ kind: 'object', definition: TodoInput }), output: Object.freeze({ kind: 'object', definition: ResultOutput }), consistency: options.consistency ?? COMMAND_CONSISTENCY.EVENTUAL, - ...(options.modeled === false ? {} : { projection: projection(operation) }), + ...(options.modeled === false + ? {} + : { projection: projection(operation, model) }), ...(options.directProjection === undefined ? {} : { directProjection: options.directProjection }), @@ -251,16 +279,16 @@ function artifact(options = {}) { version: 1, required: options.revalidate ?? false, dependencies: Object.freeze(['todos']), - models: Object.freeze([Todo.id]), + models: Object.freeze([model.id]), relationships: Object.freeze( operation === 'link' || operation === 'unlink' || operation === 'invalidate_relationship' ? [ Object.freeze({ - sourceModel: Todo.id, + sourceModel: model.id, field: 'related', - targetModel: Todo.id + targetModel: model.id }) ] : [] @@ -323,10 +351,11 @@ function modeledArtifactWithAuditArm() { function deltaMutation(request, options = {}) { const operation = options.operation ?? 'upsert'; + const model = options.model ?? Todo; const actualScope = scope({ type: 'string', value: request.variables.input.id - }); + }, model.id); if (operation === 'upsert') { return { op: 'upsert', @@ -366,11 +395,11 @@ function deltaMutation(request, options = {}) { op: operation, relationship: 'related', source: actualScope, - target: scope({ type: 'string', value: 'target' }) + target: scope({ type: 'string', value: 'target' }, model.id) }; } if (operation === 'invalidate_model') { - return { op: 'invalidate_model', partition: unit, model: Todo.id }; + return { op: 'invalidate_model', partition: unit, model: model.id }; } return { op: 'invalidate_relationship', @@ -397,7 +426,7 @@ function commandMetadata(request, options = {}) { { length: options.obligations ?? 1 }, (_, index) => ({ projectionRef: 0, - model: options.obligationModel ?? Todo.id, + model: options.obligationModel ?? options.model?.id ?? Todo.id, scopeToken: token('projection-obligation', index + 3) }) ); @@ -659,6 +688,214 @@ function tick() { return new Promise((resolve) => setTimeout(resolve, 0)); } +function commandFrame(artifactValue, rows, options = {}) { + const frame = todoFrame(artifactValue, rows, { + cacheScope: CACHE_SCOPE, + authorizationGeneration: 'auth-1', + position: options.position ?? '1', + source: options.source ?? 'query', + mode: options.mode ?? 'resumable', + reset: options.reset ?? false, + errors: options.errors + }); + const snapshot = frame.extensions.distributed.snapshot; + snapshot.observations = options.observations ?? []; + if (options.recordRevision !== undefined || options.incarnation !== undefined) { + snapshot.records = snapshot.records.map((record) => ({ + ...record, + ...(options.recordRevision === undefined + ? {} + : { revision: options.recordRevision }), + ...(options.incarnation === undefined + ? {} + : { incarnation: options.incarnation }) + })); + } + return frame; +} + +function obligationObservation(receipt, overrides = {}) { + const expectation = receipt.metadata.expects[0]; + assert.ok(expectation); + return { + causationId: receipt.metadata.causationId, + projection: expectation.projection, + model: expectation.model, + scopeToken: expectation.scopeToken, + ...overrides + }; +} + +test('generated command runtime retains an accepted projection until a matching live observation', async () => { + let liveObserver; + const replica = createDistributedReplica({ + transport: { + fetch() { + return Promise.reject(new Error('unexpected query fetch')); + }, + subscribe(_request, observer) { + liveObserver = observer; + return () => undefined; + } + } + }); + replica.writeResult( + CommandTodos, + {}, + commandFrame(CommandTodos, [ + { id: 'todo-1', title: 'base', status: 'open' } + ]), + 'network' + ); + const watch = replica.watch(CommandTodos, {}, { live: true }); + assert.ok(liveObserver); + const runtime = createReplicaCommandRuntime( + replica, + { + dispatch(request) { + return Promise.resolve( + envelope(request, { + model: TodoModel, + actualTitle: 'server projection' + }) + ); + } + }, + { change: artifact({ model: TodoModel }) } + ); + const receipt = await runtime.commands.change( + { id: 'todo-1', title: 'optimistic' }, + { commandId: COMMAND_A } + ); + assert.equal(receipt.metadata.expects[0].model, TodoModel.id); + assert.equal(watch.get().data.todos[0].title, 'server projection'); + const assertOverlayRetained = () => { + assert.equal(watch.get().data.todos[0].title, 'server projection'); + assert.throws(() => replica.createOptimisticLayer(COMMAND_A, () => undefined)); + }; + + // A complete base frame without causal evidence must not retire the layer; + // the accepted projection remains the visible overlay. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'base update', status: 'open' }], + { source: 'live', position: '2' } + ) + ); + assertOverlayRetained(); + + // Wrong-scope evidence is ignored even though the frame is otherwise fresh. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'wrong observation', status: 'open' }], + { + source: 'live', + position: '3', + observations: [ + obligationObservation(receipt, { + scopeToken: token('projection-obligation', 99) + }) + ] + } + ) + ); + assertOverlayRetained(); + + // Causation identity is part of the proof; a different command cannot + // retire this command's accepted projection. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'wrong causation', status: 'open' }], + { + source: 'live', + position: '4', + observations: [ + obligationObservation(receipt, { + causationId: 'cause:other-command' + }) + ] + } + ) + ); + assertOverlayRetained(); + + // Projection identity is equally strict; evidence from another projector + // is not an observation of this obligation. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'wrong projection', status: 'open' }], + { + source: 'live', + position: '5', + observations: [ + obligationObservation(receipt, { + projection: 'other-projector' + }) + ] + } + ) + ); + assertOverlayRetained(); + + // A frame with a lower record revision but no causal observation remains + // unable to retire the layer. This intentionally tests only missing proof; + // it does not establish whether a matching observation is subject to record + // revision gating. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'insufficient revision', status: 'open' }], + { + source: 'live', + position: '4', + recordRevision: '1' + } + ) + ); + assertOverlayRetained(); + + // Likewise, an incarnation marker without a causal observation is not proof. + // This does not assert a revision or incarnation fence on a matching proof. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'stale incarnation', status: 'open' }], + { + source: 'live', + position: '5', + recordRevision: '5', + incarnation: '0' + } + ) + ); + assertOverlayRetained(); + + // Exact causal observation from the active comparable live frame retires the + // accepted layer. Its proof is the protocol identity tuple; record-clock + // reconciliation is a separate cache concern. + liveObserver.next( + commandFrame( + CommandTodos, + [{ id: 'todo-1', title: 'confirmed', status: 'open' }], + { + source: 'live', + position: '6', + recordRevision: '6', + observations: [obligationObservation(receipt)] + } + ) + ); + assert.equal(watch.get().data.todos[0].title, 'confirmed'); + assert.equal(replica.inspectRecord(TodoModel, 'todo-1').revision, '6'); + assert.equal((await receipt.projected).state, 'atomic'); + runtime.dispose(); + watch.destroy(); +}); + test('artifact v1 is rejected at the public boundary', () => { assert.throws( () => diff --git a/src/graphql/projection_delta/tests.rs b/src/graphql/projection_delta/tests.rs index 132ed426b..c55253b80 100644 --- a/src/graphql/projection_delta/tests.rs +++ b/src/graphql/projection_delta/tests.rs @@ -1030,6 +1030,175 @@ fn zero_occurrence_metadata_is_classified_from_the_current_causal_command_contra assert_eq!(draining_command["expects"], serde_json::json!([])); } +#[cfg(feature = "graphql")] +fn wait_path_fixture() -> ( + crate::graphql::protocol::ProtocolResponseAccumulator, + crate::command::TypedCommandContract, + crate::OutboxMessage, +) { + use std::sync::Arc; + + use super::runtime::{ProtocolProjectionProgramRegistry, ProtocolProjectionRequestSeed}; + use crate::graphql::protocol::{ + DistributedEnvelopeV1, ProtocolResponseAccumulator, ProtocolTokenCodec, + ProtocolTokenPurpose, + }; + + let fixture = modeled_fixture( + ProjectionBindingState::Active, + ProjectionExecutionClass::Causal, + ); + let registry = + Arc::new(ProtocolProjectionProgramRegistry::try_from_surface(&fixture.surface).unwrap()); + let now_unix_ms = std::time::SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + let seed = ProtocolProjectionRequestSeed::new( + selected_export(&fixture.surface), + registry, + crate::command_ledger::PrincipalPartitionId::new("wait-path-principal").unwrap(), + "wait-path-generation", + Vec::new(), + now_unix_ms, + ) + .unwrap(); + let codec = ProtocolTokenCodec::new([0x70; 32]); + let cache_scope = codec + .issue(ProtocolTokenPurpose::CacheScope, &("wait-path", "cache")) + .unwrap(); + let accumulator = ProtocolResponseAccumulator::new( + DistributedEnvelopeV1::new("sha256:wait-path", "wait-path-auth", cache_scope, None), + codec, + ); + accumulator.bind_projection_request(seed).unwrap(); + let occurrence = state_occurrence(13, "todo-wait-path", "wait-path"); + let event = crate::OutboxMessage::from_domain_event_occurrence(&occurrence).unwrap(); + let contract = crate::command::typed_command::< + ModeledCommandInput, + crate::command::Eventual, + >(TEST_COMMAND_NAME) + .roles(["delta-user"]) + .emits(crate::command::__command_projection_events([Ok( + event_descriptor(), + )])) + .into_contract(); + (accumulator, contract, event) +} + +#[test] +#[cfg(feature = "graphql")] +fn wait_path_sealing_retains_event_obligations_and_status_stays_pending_without_observation() { + use crate::command::CommandConsistency; + use crate::command_ledger::CommandLedgerState; + use crate::microsvc::{ + CausalCommandPublicState, CausalCommandReceiptSource, CausalDispatchResult, + }; + + let (protocol, contract, event) = wait_path_fixture(); + let result = CausalDispatchResult { + payload: json!({"accepted": true}), + receipt: CausalCommandReceiptSource { + command_id: "wait-path-command".into(), + command_name: String::new(), + causation_id: String::new(), + consistency: CommandConsistency::Eventual, + state: CommandLedgerState::Succeeded, + outcome: json!({"accepted": true}), + obligations: Vec::new(), + projection_metadata: None, + direct_projection: None, + }, + projection_events: vec![event], + }; + + let result = result + .seal_wait_path_protocol(&protocol, &contract, Duration::from_secs(60)) + .unwrap(); + let metadata = result + .receipt + .projection_metadata + .as_ref() + .expect("an emitted modeled event must retain its exact metadata"); + assert_eq!(metadata.obligations.len(), 1); + assert_eq!(metadata.obligations[0].projection_ref, 0); + assert_eq!(metadata.obligations[0].model, "TodoView"); + assert!(metadata.obligations[0] + .scope_token + .as_str() + .starts_with("v1.projection-obligation.")); + assert_eq!(result.receipt.state, CommandLedgerState::Succeeded); + + let status = result.public_status(); + assert_eq!(status.state, CausalCommandPublicState::Succeeded); + assert!(status.evidence.is_empty()); + assert_eq!( + status + .projection_metadata + .as_ref() + .expect("status must carry modeled metadata") + .obligations + .len(), + 1 + ); + + protocol.record_status(&status).unwrap(); + let command = serde_json::to_value(protocol.snapshot().unwrap()).unwrap()["command"].clone(); + assert_eq!(command["state"], "succeeded"); + assert_eq!(command["expects"].as_array().unwrap().len(), 1); + assert!(command.get("observations").is_none()); +} + +#[test] +#[cfg(feature = "graphql")] +fn wait_path_sealing_keeps_atomic_and_unselected_commands_without_metadata() { + use crate::command::CommandConsistency; + use crate::command_ledger::CommandLedgerState; + use crate::microsvc::{CausalCommandReceiptSource, CausalDispatchResult}; + + let (protocol, contract, event) = wait_path_fixture(); + let result_for = |contract: crate::command::TypedCommandContract, + events: Vec| + -> CausalDispatchResult { + CausalDispatchResult { + payload: json!({"accepted": true}), + receipt: CausalCommandReceiptSource { + command_id: "wait-path-bypass".into(), + command_name: String::new(), + causation_id: String::new(), + consistency: CommandConsistency::Eventual, + state: CommandLedgerState::Succeeded, + outcome: json!({"accepted": true}), + obligations: Vec::new(), + projection_metadata: None, + direct_projection: None, + }, + projection_events: events, + } + .seal_wait_path_protocol(&protocol, &contract, Duration::from_secs(60)) + .unwrap() + }; + + let mut atomic_contract = contract.clone(); + atomic_contract.consistency = CommandConsistency::Atomic; + let atomic = result_for(atomic_contract, vec![event.clone()]); + assert_eq!(atomic.receipt.consistency, CommandConsistency::Atomic); + assert!(atomic.receipt.projection_metadata.is_none()); + assert_eq!(atomic.receipt.state, CommandLedgerState::Succeeded); + + let mut unselected_contract = contract.clone(); + unselected_contract.projections.selectors.clear(); + let unselected = result_for(unselected_contract, vec![event.clone()]); + assert_eq!(unselected.receipt.consistency, CommandConsistency::Eventual); + assert!(unselected.receipt.projection_metadata.is_none()); + assert_eq!(unselected.receipt.state, CommandLedgerState::Succeeded); + + let no_events = result_for(contract, Vec::new()); + assert_eq!(no_events.receipt.consistency, CommandConsistency::Eventual); + assert!(no_events.receipt.projection_metadata.is_none()); + assert_eq!(no_events.receipt.state, CommandLedgerState::Succeeded); +} + #[test] #[cfg(feature = "graphql")] fn opaque_fallback_hint_does_not_hide_empty_draining_modeled_work() { diff --git a/src/microsvc/service/causal.rs b/src/microsvc/service/causal.rs index fa4e3ec65..2cefd280a 100644 --- a/src/microsvc/service/causal.rs +++ b/src/microsvc/service/causal.rs @@ -311,30 +311,12 @@ impl CausalDispatchResult { .map_err(|error| { CausalDispatchError::Internal(format!("wait-path projection metadata: {error}")) })?; - // Cell wait-path has no GraphQL command-ledger observations. Keep the - // modeled delta so the replica can apply it, but drop expects so - // `projected` does not wait on live/status observations this process - // cannot emit. Preserve the delta's own recovery disposition: a fully - // resolved actual delta is sufficient local authority and must not turn - // every successful cell command into a full-query revalidation. - let metadata = if metadata.obligations.is_empty() { - metadata - } else { - let revalidate = metadata.revalidate; - crate::graphql::protocol::CommandProjectionMetadataV1::try_new( - metadata.issued_at_unix_ms, - metadata.expires_at_unix_ms, - metadata.delta, - metadata.lifecycle_proofs, - Vec::new(), - revalidate, - ) - .map_err(|error| { - CausalDispatchError::Internal(format!( - "wait-path projection metadata without ledger observations: {error}" - )) - })? - }; + // The cell has durably committed the domain event, but the modeled + // read-model projector is still asynchronous. Preserve the exact + // event-derived obligations so the client can retire its accepted + // optimistic layer only after a matching live/read observation. The + // wait-path has no command-ledger observation rows of its own; that + // affects status evidence below, not the modeled obligation contract. self.receipt.state = CommandLedgerState::Succeeded; self.receipt.projection_metadata = Some(metadata); Ok(self) @@ -356,24 +338,10 @@ impl CausalDispatchResult { CommandLedgerState::ProjectionFailed => CausalCommandPublicState::ProjectionFailed, CommandLedgerState::Expired => CausalCommandPublicState::Expired, }; - let evidence = self - .receipt - .projection_metadata - .as_ref() - .map(|metadata| { - metadata - .obligations - .iter() - .enumerate() - .map(|(index, _)| CausalCommandProjectionEvidence { - obligation_index: index, - state: CausalProjectionEvidenceState::Observed, - incarnation: None, - revision: None, - }) - .collect() - }) - .unwrap_or_default(); + // A wait-path receipt proves the cell command commit, not asynchronous + // projector application. Keep modeled obligations in the metadata, but + // never claim them observed without a read/live proof. + let evidence = Vec::new(); CausalCommandPublicStatus { state, command_id: self.receipt.command_id.clone(), From 1515691a0ebeb890955cf8a0eb858e38cf6ee9cb Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 19:19:20 -0500 Subject: [PATCH 077/484] fix: bind causal observations to authored program --- migrations/inventory.json | 12 + .../0007_projection_program_identity.sql | 5 + .../0007_projection_program_identity.sql | 5 + src/command/direct_projection.rs | 4 + src/command_ledger/tests.rs | 2 + src/graphql/projection_delta/runtime.rs | 8 + src/graphql/projection_delta/tests.rs | 287 +++++++++++ src/graphql/protocol/tests.rs | 2 + src/graphql/query_protocol.rs | 477 ++++++++++++++++-- src/graphql/surface/tests.rs | 99 +++- .../projection_protocol/direct_projection.rs | 6 + .../projection_protocol/rebuild.rs | 1 + .../projection_protocol/state.rs | 1 + .../projection_protocol/state_impl.rs | 1 + .../projection_protocol/store_impl.rs | 14 + .../projection_protocol/tests.rs | 1 + src/microsvc/projector/runtime.rs | 3 +- src/projection/catalog.rs | 87 ++++ src/projection_protocol/store/identity.rs | 13 + src/projection_protocol/store/mod.rs | 1 + src/projection_protocol/store/query.rs | 7 + src/projection_protocol/store/replay.rs | 26 + src/projection_protocol/store/tests.rs | 2 + src/projection_protocol/workspace.rs | 21 +- src/sqlx_repo/projection_protocol/helpers.rs | 14 + src/sqlx_repo/projection_protocol/mod.rs | 1 + src/sqlx_repo/projection_protocol/reads.rs | 22 +- src/sqlx_repo/projection_protocol/rebuild.rs | 1 + .../projection_protocol/store_impl.rs | 6 + src/sqlx_repo/projection_protocol/tests.rs | 138 ++++- src/sqlx_repo/projection_protocol/writes.rs | 38 +- src/sqlx_repo/repo/backend.rs | 18 +- 32 files changed, 1254 insertions(+), 69 deletions(-) create mode 100644 migrations/postgres/0007_projection_program_identity.sql create mode 100644 migrations/sqlite/0007_projection_program_identity.sql diff --git a/migrations/inventory.json b/migrations/inventory.json index ccea03955..9e2e9add7 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -72,6 +72,18 @@ "path": "migrations/postgres/0006_gateway_dependency_versions.sql", "sha256": "c156bc51dddecd49b1beef7bb4069557b024c19cb1271f0ec9cc0efe71939471" } + }, + { + "version": 7, + "description": "projection program identity", + "sqlite": { + "path": "migrations/sqlite/0007_projection_program_identity.sql", + "sha256": "cb247b632ce6b1dbab2bf3d15a25532334432ef58d20755c5491b009bd31a320" + }, + "postgres": { + "path": "migrations/postgres/0007_projection_program_identity.sql", + "sha256": "ad7da74a11637a522279a6bc061d2c79db1f807f869368cf31735a089dfe0204" + } } ] } diff --git a/migrations/postgres/0007_projection_program_identity.sql b/migrations/postgres/0007_projection_program_identity.sql new file mode 100644 index 000000000..e730271e7 --- /dev/null +++ b/migrations/postgres/0007_projection_program_identity.sql @@ -0,0 +1,5 @@ +-- Preserve the semantic program that authored each causal proof row. +-- NULL is intentional for history written before program identities existed; +-- readers must treat it as unversioned rather than infer the active program. +ALTER TABLE projection_changes ADD COLUMN program_id text; +ALTER TABLE projection_observations ADD COLUMN program_id text; diff --git a/migrations/sqlite/0007_projection_program_identity.sql b/migrations/sqlite/0007_projection_program_identity.sql new file mode 100644 index 000000000..27d53972c --- /dev/null +++ b/migrations/sqlite/0007_projection_program_identity.sql @@ -0,0 +1,5 @@ +-- Preserve the semantic program that authored each causal proof row. +-- NULL is intentional for history written before program identities existed; +-- readers must treat it as unversioned rather than infer the active program. +ALTER TABLE projection_changes ADD COLUMN program_id TEXT; +ALTER TABLE projection_observations ADD COLUMN program_id TEXT; diff --git a/src/command/direct_projection.rs b/src/command/direct_projection.rs index e454b66ff..ddc18f55f 100644 --- a/src/command/direct_projection.rs +++ b/src/command/direct_projection.rs @@ -392,6 +392,10 @@ impl ResolvedDirectProjectionTarget { ) .map_err(|error| ProjectionProtocolError::InvalidBatch(error.to_string()))?; let ownership = ProjectionModelOwnership::new(self.model, self.table)?; + let ownership = self + .modeled_program_id + .map(|program_id| ownership.clone().with_program_id(program_id)) + .unwrap_or(ownership); SameTransactionProjectionBatch::single_upsert( self.codec.topology().clone(), self.partition, diff --git a/src/command_ledger/tests.rs b/src/command_ledger/tests.rs index a3ccd1bd8..8bbb11511 100644 --- a/src/command_ledger/tests.rs +++ b/src/command_ledger/tests.rs @@ -136,6 +136,7 @@ fn direct_projection_evidence(marker: &str) -> SameTransactionProjectionEvidence scope: Some(scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: None, }; let observation = ProjectionObservation { causation_id: format!("cause:{marker}"), @@ -143,6 +144,7 @@ fn direct_projection_evidence(marker: &str) -> SameTransactionProjectionEvidence revision: Some(revision), scope, change: cursor, + program_id: None, }; SameTransactionProjectionEvidence { records: vec![record], diff --git a/src/graphql/projection_delta/runtime.rs b/src/graphql/projection_delta/runtime.rs index 3c271f7b7..c8001d3bb 100644 --- a/src/graphql/projection_delta/runtime.rs +++ b/src/graphql/projection_delta/runtime.rs @@ -259,6 +259,14 @@ impl ProtocolProjectionRequestSeed { if candidate.causation_id != causation_id || candidate.scope.topology() != entry.codec.topology() || candidate.scope.model() != obligation.model + // A modeled observation is proof for the exact semantic + // program that authored it. Physical projector names are + // shared across deployments and cannot establish this + // identity after an upgrade or cold restart. Legacy + // observations have no program ID and remain readable, + // but cannot satisfy a modeled obligation. + || candidate.program_id.map(|id| id.to_string()) + != Some(identity.program_id.clone()) || !entry .binding .outputs() diff --git a/src/graphql/projection_delta/tests.rs b/src/graphql/projection_delta/tests.rs index c55253b80..bfd49d0f3 100644 --- a/src/graphql/projection_delta/tests.rs +++ b/src/graphql/projection_delta/tests.rs @@ -1149,6 +1149,293 @@ fn wait_path_sealing_retains_event_obligations_and_status_stays_pending_without_ assert!(command.get("observations").is_none()); } +#[test] +#[cfg(feature = "graphql")] +fn wait_path_observation_proof_requires_the_persisted_semantic_program_identity() { + use std::sync::Arc; + + use crate::command::CommandConsistency; + use crate::command_ledger::CommandLedgerState; + use crate::graphql::protocol::{ProtocolTokenCodec, ProtocolTokenPurpose}; + use crate::microsvc::{ + CausalCommandProjectionEvidence, CausalCommandPublicState, CausalCommandPublicStatus, + CausalCommandReceiptSource, CausalDispatchResult, CausalProjectionEvidenceState, + }; + use crate::projection_protocol::{ + ProjectionCausationEvidenceBatch, ProjectionChangeCursor, ProjectionEpoch, + ProjectionObservation, ProjectionObservationKind, ProjectionScopeCodec, + ProjectorTopologyId, RecordRevision, + }; + use crate::ProjectionProgramId; + + let (protocol, contract, event) = wait_path_fixture(); + let result = CausalDispatchResult { + payload: json!({"accepted": true}), + receipt: CausalCommandReceiptSource { + command_id: "wait-path-identity-command".into(), + command_name: String::new(), + causation_id: String::new(), + consistency: CommandConsistency::Eventual, + state: CommandLedgerState::Succeeded, + outcome: json!({"accepted": true}), + obligations: Vec::new(), + projection_metadata: None, + direct_projection: None, + }, + projection_events: vec![event], + } + .seal_wait_path_protocol(&protocol, &contract, Duration::from_secs(60)) + .unwrap(); + let metadata = result + .receipt + .projection_metadata + .clone() + .expect("the real wait-path event produces modeled metadata"); + let semantic_program = ProjectionProgramId::parse(&metadata.delta.projections[0].program_id) + .expect("metadata carries the canonical semantic program identity"); + let wrong_program = ProjectionProgramId::parse( + "pp1:sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ) + .unwrap(); + let topology = ProjectorTopologyId::new(1, "projection-delta-test", [0x44; 32]).unwrap(); + let todo_schema = todos(); + let user_schema = users(); + let observation_codec = ProjectionScopeCodec::with_models( + topology.clone(), + [("TodoView", &todo_schema), ("UserView", &user_schema)], + ) + .unwrap(); + let scope = observation_codec + .encode_row_scope( + "projection-delta-test", + "TodoView", + Some(&json!("tenant-a")), + &crate::table::RowKey::new([( + "todo_id", + crate::table::RowValue::String("todo-wait-path".into()), + )]), + ) + .unwrap(); + let revision = RecordRevision::new(scope.clone(), 1, 1).unwrap(); + let change = ProjectionChangeCursor::new( + topology, + scope.projection_partition().clone(), + ProjectionEpoch::new("projection-delta-v1").unwrap(), + 1, + ) + .unwrap(); + let candidate = ProjectionObservation { + causation_id: result.causation_id().into(), + kind: ProjectionObservationKind::Record, + revision: Some(revision), + scope: scope.clone(), + change, + program_id: Some(semantic_program), + }; + let disposition = protocol + .modeled_projection_evidence_topologies(TEST_COMMAND_NAME, result.causation_id(), &metadata) + .unwrap() + .disposition; + let evidence = protocol + .modeled_projection_evidence( + TEST_COMMAND_NAME, + result.causation_id(), + &metadata, + &ProjectionCausationEvidenceBatch { + observations: vec![candidate.clone()], + terminal_failure_topologies: Vec::new(), + }, + disposition, + ) + .unwrap(); + assert!(matches!( + evidence.as_slice(), + [super::runtime::ModeledProjectionEvidence::Observed(observation)] + if observation.program_id == Some(semantic_program) + )); + assert_ne!( + candidate.scope.topology().name(), + semantic_program.to_string(), + "the physical projector name and semantic author identity are distinct" + ); + + let mut mismatched_program = candidate.clone(); + mismatched_program.program_id = Some(wrong_program); + let pending_for = |observation: ProjectionObservation| { + protocol + .modeled_projection_evidence( + TEST_COMMAND_NAME, + result.causation_id(), + &metadata, + &ProjectionCausationEvidenceBatch { + observations: vec![observation], + terminal_failure_topologies: Vec::new(), + }, + disposition, + ) + .unwrap() + }; + assert!(matches!( + pending_for(mismatched_program).as_slice(), + [super::runtime::ModeledProjectionEvidence::Pending] + )); + let mut unversioned = candidate.clone(); + unversioned.program_id = None; + assert!(matches!( + pending_for(unversioned).as_slice(), + [super::runtime::ModeledProjectionEvidence::Pending] + )); + let mut wrong_causation = candidate.clone(); + wrong_causation.causation_id = FOREIGN_CAUSATION_ID.into(); + assert!(matches!( + pending_for(wrong_causation).as_slice(), + [super::runtime::ModeledProjectionEvidence::Pending] + )); + let wrong_scope = observation_codec + .encode_row_scope( + "projection-delta-test", + "UserView", + Some(&json!("tenant-a")), + &crate::table::RowKey::new([( + "user_id", + crate::table::RowValue::String("owner-secret".into()), + )]), + ) + .unwrap(); + let mut wrong_model = candidate.clone(); + wrong_model.scope = wrong_scope; + wrong_model.revision = None; + assert!(matches!( + pending_for(wrong_model).as_slice(), + [super::runtime::ModeledProjectionEvidence::Pending] + )); + + // A cold restart with the same mounted program can still prove the + // persisted observation. Replacing only the program behavior while keeping + // the physical projector name/topology does not: the semantic ID is the + // durable authoring boundary, not a current-name lookup. + let restarted_fixture = modeled_fixture_deployment( + ProjectionBindingState::Active, + ProjectionExecutionClass::Causal, + ProjectionMutationKind::Upsert, + false, + "delta-service", + "projection-delta-test", + [0x44; 32], + ); + let restart_codec = ProtocolTokenCodec::new([0x70; 32]); + let restart_cache = restart_codec + .issue(ProtocolTokenPurpose::CacheScope, &("wait-path", "cache")) + .unwrap(); + let restart_seed = super::runtime::ProtocolProjectionRequestSeed::new( + selected_export(&restarted_fixture.surface), + Arc::new( + super::runtime::ProtocolProjectionProgramRegistry::try_from_surface( + &restarted_fixture.surface, + ) + .unwrap(), + ), + crate::command_ledger::PrincipalPartitionId::new("wait-path-principal").unwrap(), + "wait-path-generation", + Vec::new(), + 1, + ) + .unwrap(); + let restart_disposition = restart_seed + .modeled_evidence_topologies( + &restart_codec, + &restart_cache, + TEST_COMMAND_NAME, + result.causation_id(), + &metadata, + ) + .unwrap() + .disposition; + assert!(matches!( + restart_seed + .modeled_evidence( + &restart_codec, + &restart_cache, + TEST_COMMAND_NAME, + result.causation_id(), + &metadata, + &ProjectionCausationEvidenceBatch { + observations: vec![candidate.clone()], + terminal_failure_topologies: Vec::new(), + }, + restart_disposition, + ) + .unwrap() + .as_slice(), + [super::runtime::ModeledProjectionEvidence::Observed(_)] + )); + let changed_fixture = modeled_fixture_deployment( + ProjectionBindingState::Active, + ProjectionExecutionClass::Causal, + ProjectionMutationKind::Patch, + false, + "delta-service", + "projection-delta-test", + [0x44; 32], + ); + assert_ne!( + restarted_fixture.program.id().unwrap(), + changed_fixture.program.id().unwrap(), + "the cold-restarted replacement must have a distinct semantic identity" + ); + let changed_seed = super::runtime::ProtocolProjectionRequestSeed::new( + selected_export(&changed_fixture.surface), + Arc::new( + super::runtime::ProtocolProjectionProgramRegistry::try_from_surface( + &changed_fixture.surface, + ) + .unwrap(), + ), + crate::command_ledger::PrincipalPartitionId::new("wait-path-principal").unwrap(), + "wait-path-generation", + Vec::new(), + 1, + ) + .unwrap(); + let changed_result = changed_seed.modeled_evidence_topologies( + &restart_codec, + &restart_cache, + TEST_COMMAND_NAME, + result.causation_id(), + &metadata, + ); + assert!( + changed_result.is_err(), + "changed program identity cannot reuse old metadata" + ); + + let status = CausalCommandPublicStatus { + state: CausalCommandPublicState::Succeeded, + command_id: result.command_id().into(), + command_name: Some(TEST_COMMAND_NAME.into()), + causation_id: Some(result.causation_id().into()), + consistency: Some(CommandConsistency::Eventual), + outcome: Some(json!({"accepted": true})), + obligations: Vec::new(), + projection_metadata: Some(metadata), + projection_revalidate: false, + evidence: vec![CausalCommandProjectionEvidence { + obligation_index: 0, + state: CausalProjectionEvidenceState::Observed, + incarnation: Some(1), + revision: Some(1), + }], + direct_projection: None, + }; + protocol.record_status(&status).unwrap(); + let command = serde_json::to_value(protocol.snapshot().unwrap()).unwrap()["command"].clone(); + assert_eq!(command["observations"].as_array().unwrap().len(), 1); + assert_eq!( + command["observations"][0]["causationId"], + result.causation_id() + ); +} + #[test] #[cfg(feature = "graphql")] fn wait_path_sealing_keeps_atomic_and_unselected_commands_without_metadata() { diff --git a/src/graphql/protocol/tests.rs b/src/graphql/protocol/tests.rs index 7ad481d63..6888bb3e6 100644 --- a/src/graphql/protocol/tests.rs +++ b/src/graphql/protocol/tests.rs @@ -159,6 +159,7 @@ fn direct_projected_receipt() -> CausalCommandReceiptSource { scope: Some(scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: None, }], observations: vec![ProjectionObservation { causation_id: receipt.causation_id.clone(), @@ -166,6 +167,7 @@ fn direct_projected_receipt() -> CausalCommandReceiptSource { revision: Some(revision), scope, change, + program_id: None, }], }); receipt diff --git a/src/graphql/query_protocol.rs b/src/graphql/query_protocol.rs index bb31a5e46..a07b49df8 100644 --- a/src/graphql/query_protocol.rs +++ b/src/graphql/query_protocol.rs @@ -46,6 +46,13 @@ pub(crate) struct QueryProjectorRuntime { pub(crate) change_epoch: Option, models: BTreeSet, dependencies: BTreeSet, + /// Public causal-observation identity for each output model. Modeled + /// projections use their versioned program ID; legacy projections retain + /// the physical owner name as their public identity. + public_projection_by_model: BTreeMap, + /// Modeled changes must carry their authoring identity on the durable + /// change row. Legacy rows may derive the historical physical identity. + requires_semantic_identity: bool, } impl QueryProjectorRuntime { @@ -53,6 +60,12 @@ impl QueryProjectorRuntime { self.static_partition.is_some() && self.change_epoch.is_some() } + pub(crate) fn public_projection_for_model(&self, model: &str) -> Option<&str> { + self.public_projection_by_model + .get(model) + .map(String::as_str) + } + /// A partition-wide change cursor is safe to expose only when every model /// sharing that projector partition is visible without row filtering on /// this exact authorization surface. Otherwise positions, causations, and @@ -247,6 +260,13 @@ impl QueryProtocolRuntime { .get(model) .map(|owner| owner.static_partition.is_some()) } + + #[cfg(test)] + pub(crate) fn public_projection_for_model(&self, model: &str) -> Option<&str> { + self.model_owners + .get(model) + .and_then(|owner| owner.public_projection_for_model(model)) + } } fn compile_legacy_query_projector( @@ -324,6 +344,12 @@ fn compile_legacy_query_projector( change_epoch, models: projector.models.iter().cloned().collect(), dependencies: projector.dependencies.iter().cloned().collect(), + public_projection_by_model: projector + .models + .iter() + .map(|model| (model.clone(), projector.name.clone())) + .collect(), + requires_semantic_identity: false, })) } @@ -368,6 +394,7 @@ fn compile_modeled_query_projector( validate_modeled_partition_binding(projector, first_program, first_binding)?; let mut models = BTreeSet::new(); + let mut public_projection_by_model = BTreeMap::new(); for modeled in &active { let (program, binding) = modeled.raw().ok_or_else(|| { format!( @@ -405,7 +432,18 @@ fn compile_modeled_query_projector( projector.name )); } - models.extend(modeled.output_models().iter().cloned()); + for model in modeled.output_models() { + models.insert(model.clone()); + if public_projection_by_model + .insert(model.clone(), modeled.program_id().to_string()) + .is_some() + { + return Err(format!( + "query protocol modeled owner `{}` has ambiguous active program identity for model `{model}`", + projector.name + )); + } + } } if models.is_empty() { return Err(format!( @@ -475,6 +513,8 @@ fn compile_modeled_query_projector( change_epoch: Some(change_epoch), models, dependencies, + public_projection_by_model, + requires_semantic_identity: true, }))) } @@ -519,7 +559,10 @@ struct PreparedQueryEvidence { const MAX_PROTOCOL_EVIDENCE_ITEMS: usize = 4_096; struct PreparedLiveChange { + /// Physical owner used for change-log routing and opaque scope tokens. projection: String, + /// Versioned semantic identity used in public causal observations. + public_projection: Option, change: crate::projection_protocol::ProjectionChange, } @@ -1084,8 +1127,28 @@ where break; } replayed_changes.extend(changes.into_iter().map(|change| { + // Modeled identity is part of the persisted change + // evidence. Never relabel an old/null row from the + // currently active program after a cold restart. + let public_projection = change + .program_id + .map(|program_id| program_id.to_string()) + .or_else(|| { + if projector.requires_semantic_identity { + None + } else { + change + .scope + .as_ref() + .and_then(|scope| { + projector.public_projection_for_model(scope.model()) + }) + .map(str::to_owned) + } + }); PreparedLiveChange { projection: projector.name.clone(), + public_projection, change, } })); @@ -1269,24 +1332,33 @@ fn wire_query_snapshot( live_record_fences.insert(scope_key, (clock, wire_record)); } } - let observation = super::protocol::DistributedProjectionObservation { - causation_id: change.causation_id.clone(), - projection: live.projection.clone(), - model: scope.model().to_string(), - scope_token: accumulator - .issue_projection_obligation_scope( - &change.causation_id, - &live.projection, - scope.model(), - crate::projection_protocol::ProjectionObservationKind::Record, - scope, - ) - .map_err(|error| { - ProjectionProtocolError::InvalidBatch(error.to_string()) - })?, - }; - if observation_tokens.insert(observation.scope_token.as_str().to_string()) { - observations.push(observation); + // A retained pre-identity change still contributes its + // authoritative row/revision. It cannot, however, mint a + // modeled causal observation because its authoring program is + // unknown. Keep the readable data and omit only that proof. + if let Some(projection) = live.public_projection.clone() { + let observation = super::protocol::DistributedProjectionObservation { + causation_id: change.causation_id.clone(), + projection, + model: scope.model().to_string(), + scope_token: accumulator + .issue_projection_obligation_scope( + &change.causation_id, + &live.projection, + scope.model(), + crate::projection_protocol::ProjectionObservationKind::Record, + scope, + ) + .map_err(|error| { + ProjectionProtocolError::InvalidBatch(error.to_string()) + })?, + }; + if observation_tokens.insert(( + observation.projection.clone(), + observation.scope_token.as_str().to_string(), + )) { + observations.push(observation); + } } } crate::projection_protocol::ProjectionChangeKind::Observation => { @@ -1300,24 +1372,31 @@ fn wire_query_snapshot( "live projection observation omitted its kind".into(), ) })?; - let observation = super::protocol::DistributedProjectionObservation { - causation_id: change.causation_id.clone(), - projection: live.projection.clone(), - model: scope.model().to_string(), - scope_token: accumulator - .issue_projection_obligation_scope( - &change.causation_id, - &live.projection, - scope.model(), - kind, - scope, - ) - .map_err(|error| { - ProjectionProtocolError::InvalidBatch(error.to_string()) - })?, - }; - if observation_tokens.insert(observation.scope_token.as_str().to_string()) { - observations.push(observation); + // As with record changes, legacy/unversioned modeled history + // remains queryable but cannot be advertised as causal proof. + if let Some(projection) = live.public_projection.clone() { + let observation = super::protocol::DistributedProjectionObservation { + causation_id: change.causation_id.clone(), + projection, + model: scope.model().to_string(), + scope_token: accumulator + .issue_projection_obligation_scope( + &change.causation_id, + &live.projection, + scope.model(), + kind, + scope, + ) + .map_err(|error| { + ProjectionProtocolError::InvalidBatch(error.to_string()) + })?, + }; + if observation_tokens.insert(( + observation.projection.clone(), + observation.scope_token.as_str().to_string(), + )) { + observations.push(observation); + } } } crate::projection_protocol::ProjectionChangeKind::Checkpoint @@ -1375,4 +1454,328 @@ mod tests { assert!(query_index_budget_allows(MAX_PROTOCOL_EVIDENCE_ITEMS)); assert!(!query_index_budget_allows(MAX_PROTOCOL_EVIDENCE_ITEMS + 1)); } + + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn wire_snapshot_preserves_persisted_modeled_identity_and_receipt_scope() { + use std::collections::{BTreeMap, BTreeSet}; + + use crate::graphql::protocol::{ProtocolTokenCodec, ProtocolTokenPurpose}; + use crate::projection_protocol::{ + ProjectionChangeRead, ProjectionCommitBatch, ProjectionEpoch, ProjectionInputCursor, + ProjectionInputFingerprint, ProjectionModelOwnership, ProjectionMutationKind, + ProjectionObservationKind, ProjectionObservationRequest, ProjectionObservationTarget, + ProjectionProtocolStore, ProjectionRecordExpectation, ProjectionRecordMutation, + ProjectionSource, TrustedProjectionInput, + }; + use crate::sqlite_repo::SqliteRepository; + use crate::table::{ + ColumnType, ExpectedVersion, PrimaryKey, RowKey, RowValue, RowValues, RowWriteMode, + TableColumn, TableKind, TableMutation, TableRowMutation, TableSchema, + TableSchemaRegistry, + }; + + let topology = ProjectorTopologyId::new(1, "query-wire-modeled", [0x4a; 32]).unwrap(); + static SCHEMA: std::sync::LazyLock = + std::sync::LazyLock::new(|| TableSchema { + model_name: "WireView".into(), + table_name: "wire_views".into(), + columns: vec![ + TableColumn { + primary_key: true, + ..TableColumn::new("id", "id", ColumnType::Text) + }, + TableColumn::new("title", "title", ColumnType::Text), + ], + primary_key: PrimaryKey::new(["id"]), + version_column: Some(crate::table::DEFAULT_TABLE_VERSION_COLUMN.into()), + foreign_keys: Vec::new(), + indexes: Vec::new(), + relationships: Vec::new(), + kind: TableKind::ReadModel, + }); + let schema = &*SCHEMA; + let mut table_registry = TableSchemaRegistry::new(); + table_registry.register_schema(schema.clone()).unwrap(); + let repository = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + repository + .bootstrap_table_schema_for_dev(&table_registry) + .await + .unwrap(); + let program_id = + crate::ProjectionProgramId::parse(&format!("pp1:sha256:{}", "4".repeat(64))).unwrap(); + let ownership = ProjectionModelOwnership::new("WireView", "wire_views") + .unwrap() + .with_program_id(program_id); + repository + .register_projection_models(&topology, std::slice::from_ref(&ownership)) + .await + .unwrap(); + + let codec = Arc::new( + ProjectionScopeCodec::with_models(topology.clone(), [("WireView", schema)]).unwrap(), + ); + let partition = codec.encode_partition(None).unwrap(); + let key = RowKey::new([("id", RowValue::String("wire-1".into()))]); + let scope = codec + .encode_row_scope_in_partition("WireView", partition.clone(), &key) + .unwrap(); + let mut values = RowValues::new(); + values.insert("id", RowValue::String("wire-1".into())); + values.insert("title", RowValue::String("persisted".into())); + let mutation = TableMutation::UpsertRow(TableRowMutation { + schema: &schema, + key: key.clone(), + values, + expected_version: ExpectedVersion::Any, + mode: RowWriteMode::Upsert, + }); + let change_epoch = ProjectionEpoch::new("query-wire-modeled-v1").unwrap(); + let input = TrustedProjectionInput::mint( + ProjectionInputCursor::new( + topology.clone(), + partition.clone(), + ProjectionSource::new("wire-source", b"wire-partition".to_vec()).unwrap(), + ProjectionEpoch::new("wire-source-v1").unwrap(), + 1, + ) + .unwrap(), + ProjectionInputFingerprint::from_canonical_bytes(b"wire-input"), + "wire-message-1", + "wire-cause-1", + crate::projection_protocol::ProjectionGeneration::initial(), + true, + ) + .unwrap(); + let commit = repository + .commit_projection(ProjectionCommitBatch { + input, + change_epoch: change_epoch.clone(), + ownership: vec![ownership], + mutations: vec![ProjectionRecordMutation::new( + scope.clone(), + mutation, + ProjectionRecordExpectation::Missing, + ProjectionMutationKind::Upsert, + ) + .unwrap()], + observations: vec![ProjectionObservationRequest { + kind: ProjectionObservationKind::Record, + target: ProjectionObservationTarget::StagedRecord(scope.clone()), + }], + }) + .await + .unwrap(); + let stored_change = match repository + .projection_changes(&topology, &partition, None, 16) + .await + .unwrap() + { + ProjectionChangeRead::Changes { changes, .. } => changes + .into_iter() + .find(|change| { + change.kind == crate::projection_protocol::ProjectionChangeKind::RecordUpsert + }) + .expect("stored record change"), + other => panic!("unexpected projection change read: {other:?}"), + }; + assert_eq!(stored_change.program_id, Some(program_id)); + assert!(commit + .changes + .iter() + .any(|change| change.program_id == Some(program_id))); + + let cache_scope = ProtocolTokenCodec::new([0x4b; 32]) + .issue(ProtocolTokenPurpose::CacheScope, &("wire", "cache")) + .unwrap(); + let token_codec = ProtocolTokenCodec::new([0x4b; 32]); + let accumulator = ProtocolResponseAccumulator::new( + super::super::protocol::DistributedEnvelopeV1::new( + "sha256:wire-schema", + "wire-auth", + cache_scope, + None, + ), + token_codec, + ); + accumulator + .bind_query_snapshot_scope(&serde_json::json!({ + "sql": "SELECT wire_views", + "tables": ["wire_views"] + })) + .unwrap(); + + let runtime = Arc::new(QueryProjectorRuntime { + name: "wire-physical-projector".into(), + codec: Arc::clone(&codec), + static_partition: Some(partition.clone()), + change_epoch: Some(change_epoch.clone()), + models: BTreeSet::from(["WireView".into()]), + dependencies: BTreeSet::from(["wire_views".into()]), + public_projection_by_model: BTreeMap::from([( + "WireView".into(), + program_id.to_string(), + )]), + requires_semantic_identity: true, + }); + let snapshot_scope = accumulator.query_snapshot_scope().unwrap(); + let initial_cursor = accumulator + .issue_live_resume_position( + &runtime.name, + &snapshot_scope, + runtime.codec.topology(), + &partition, + &change_epoch, + 0, + ) + .unwrap(); + let partition_snapshot = ProjectionPartitionSnapshot { + head: Some(stored_change.cursor.clone()), + compacted_through: 0, + }; + let prepared_live = PreparedQueryEvidence { + records_complete: true, + records: Vec::new(), + indexes: QueryIndexPlan { + comparable: true, + projectors: vec![Arc::clone(&runtime)], + }, + }; + let mut connection = repository.pool().acquire().await.unwrap(); + let live_metadata = wire_live_metadata::( + &mut *connection, + &accumulator, + &prepared_live, + std::slice::from_ref(&partition_snapshot), + RequestedLiveResume::Cursors(vec![initial_cursor.clone()]), + ) + .await + .unwrap(); + assert_eq!(live_metadata.metadata.mode, DistributedLiveMode::Resumable); + assert!(!live_metadata.metadata.reset); + assert_eq!(live_metadata.changes.len(), 1); + assert_eq!( + live_metadata.changes[0].public_projection.as_deref(), + Some(program_id.to_string().as_str()) + ); + let live_changes = live_metadata.changes; + drop(connection); + let record = repository + .projection_record(&scope) + .await + .unwrap() + .expect("stored record metadata"); + let prepared = PreparedQueryEvidence { + records_complete: true, + records: vec![PreparedRecordProbe { + request: ProjectionLiveRecordRequest::new(&codec, "WireView", key).unwrap(), + paths: vec![vec!["wire_views".into(), "0".into()]], + }], + indexes: QueryIndexPlan { + comparable: true, + projectors: vec![Arc::clone(&runtime)], + }, + }; + let snapshot = wire_query_snapshot( + &accumulator, + prepared, + vec![Some(record)], + vec![partition_snapshot.clone()], + live_changes, + ) + .unwrap(); + assert_eq!( + snapshot.observations.len(), + 1, + "modeled proof is on the wire" + ); + let observation = &snapshot.observations[0]; + assert_eq!(observation.causation_id, "wire-cause-1"); + assert_eq!(observation.projection, program_id.to_string()); + assert_eq!(observation.model, "WireView"); + + // A sealed command receipt uses the same physical scope material and + // semantic public label. The opaque token must be byte-for-byte equal + // to the live observation, while the physical owner stays private. + let receipt_scope = accumulator + .issue_projection_obligation_scope( + "wire-cause-1", + &runtime.name, + "WireView", + ProjectionObservationKind::Record, + &scope, + ) + .unwrap(); + assert_eq!(observation.scope_token, receipt_scope); + + // Nulling the durable identity models pre-migration history: the row + // and record fence remain readable, but the wire must not relabel it + // as the currently active semantic program. + sqlx::query("UPDATE projection_changes SET program_id = NULL WHERE change_position = ?") + .bind(stored_change.cursor.position() as i64) + .execute(repository.pool()) + .await + .unwrap(); + let legacy_change = match repository + .projection_changes(&topology, &partition, None, 16) + .await + .unwrap() + { + ProjectionChangeRead::Changes { changes, .. } => changes + .into_iter() + .find(|change| { + change.kind == crate::projection_protocol::ProjectionChangeKind::RecordUpsert + }) + .expect("stored legacy record change"), + other => panic!("unexpected legacy projection change read: {other:?}"), + }; + assert!(legacy_change.program_id.is_none()); + let mut connection = repository.pool().acquire().await.unwrap(); + let legacy_live = wire_live_metadata::( + &mut *connection, + &accumulator, + &prepared_live, + std::slice::from_ref(&partition_snapshot), + RequestedLiveResume::Cursors(vec![initial_cursor]), + ) + .await + .unwrap(); + assert_eq!(legacy_live.changes.len(), 1); + assert!(legacy_live.changes[0].public_projection.is_none()); + let legacy_changes = legacy_live.changes; + drop(connection); + let legacy_snapshot = wire_query_snapshot( + &accumulator, + PreparedQueryEvidence { + records_complete: true, + records: vec![PreparedRecordProbe { + request: ProjectionLiveRecordRequest::new( + &codec, + "WireView", + RowKey::new([("id", RowValue::String("wire-1".into()))]), + ) + .unwrap(), + paths: vec![vec!["wire_views".into(), "0".into()]], + }], + indexes: QueryIndexPlan { + comparable: true, + projectors: vec![runtime], + }, + }, + vec![Some( + repository + .projection_record(&scope) + .await + .unwrap() + .expect("legacy row metadata remains readable"), + )], + vec![partition_snapshot], + legacy_changes, + ) + .unwrap(); + assert_eq!(legacy_snapshot.observations, Vec::new()); + assert_eq!(legacy_snapshot.records.len(), 1); + } } diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index 5506b20c8..1fa560d3f 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -109,6 +109,16 @@ fn modeled_direct_projection( epoch: &str, schema: TableSchema, options: DirectModeledBinding<'_>, +) -> SurfaceModeledProjection { + modeled_projection_with_outputs(owner, program_name, epoch, vec![schema], options) +} + +fn modeled_projection_with_outputs( + owner: &str, + program_name: &str, + epoch: &str, + schemas: Vec, + options: DirectModeledBinding<'_>, ) -> SurfaceModeledProjection { use crate::projection::catalog::{ProjectionBindingActivation, ProjectionCatalog}; use crate::projection::placement::{ @@ -126,8 +136,6 @@ fn modeled_direct_projection( DOMAIN_EVENT_BODY_CODEC, DOMAIN_EVENT_BODY_CODEC_VERSION, }; - let model_name = schema.model_name.clone(); - let table_name = schema.table_name.clone(); let selector = ProjectionEventSelector::try_new( 1, format!("{program_name}.changed"), @@ -141,18 +149,26 @@ fn modeled_direct_projection( DOMAIN_EVENT_BODY_CODEC_VERSION, ) .unwrap(); - let value = ProjectionExpression::constant(ProjectionValue::string("row-1")); - let operation = ProjectionOperation::try_new( - format!("{program_name}-upsert"), - 0, - ProjectionMutationKind::Upsert, - ProjectionTarget::try_new(&model_name, &table_name).unwrap(), - vec![ProjectionKeyField::try_new(0, "id", value.clone()).unwrap()], - vec![ProjectionField::try_new(0, "id", ProjectionAssignment::Set(value)).unwrap()], - Vec::new(), - Vec::new(), - ) - .unwrap(); + assert!(!schemas.is_empty(), "modeled projection requires an output"); + let operations = schemas + .iter() + .enumerate() + .map(|(index, schema)| { + let value = + ProjectionExpression::constant(ProjectionValue::string(format!("row-{index}"))); + ProjectionOperation::try_new( + format!("{program_name}-upsert-{index}"), + index.try_into().unwrap(), + ProjectionMutationKind::Upsert, + ProjectionTarget::try_new(&schema.model_name, &schema.table_name).unwrap(), + vec![ProjectionKeyField::try_new(0, "id", value.clone()).unwrap()], + vec![ProjectionField::try_new(0, "id", ProjectionAssignment::Set(value)).unwrap()], + Vec::new(), + Vec::new(), + ) + .unwrap() + }) + .collect::>(); let partition = if options.dynamic_partition { ProjectionPartition::Expression(ProjectionExpression::constant(ProjectionValue::string( "tenant-1", @@ -164,10 +180,7 @@ fn modeled_direct_projection( program_name, 1, partition, - vec![ - ProjectionArm::try_new(format!("{program_name}-arm"), selector, vec![operation]) - .unwrap(), - ], + vec![ProjectionArm::try_new(format!("{program_name}-arm"), selector, operations).unwrap()], ) .unwrap(); let descriptor = TestProjectionDescriptor(program.clone()); @@ -180,7 +193,13 @@ fn modeled_direct_projection( let source = ProjectionSourceBinding::try_new("test-domain", "ordered-domain-events", 1).unwrap(); let owner = ProjectionOwner::try_new(owner).unwrap(); - let outputs = vec![ProjectionOutput::try_new(model_name, table_name, schema).unwrap()]; + let outputs = schemas + .into_iter() + .map(|schema| { + ProjectionOutput::try_new(schema.model_name.clone(), schema.table_name.clone(), schema) + .unwrap() + }) + .collect::>(); let binding = if options.eventual { ProjectionBinding::from_eventual_program( &program, @@ -636,6 +655,7 @@ fn query_protocol_uses_exact_modeled_physical_topology() { ..DirectModeledBinding::active("exact-physical-topology") }, ); + let semantic_program_id = modeled.program_id().to_string(); let surface = build_surface(&[model], &SurfaceOptions::sqlite()) .unwrap() .with_projection_owners([SurfaceDirectProjection::new("exact-modeled-owner") @@ -653,6 +673,11 @@ fn query_protocol_uses_exact_modeled_physical_topology() { runtime.model_has_static_partition("ExactTopology"), Some(true) ); + assert_eq!( + runtime.public_projection_for_model("ExactTopology"), + Some(semantic_program_id.as_str()), + "causal observations use the active semantic program identity" + ); } #[cfg(feature = "graphql")] @@ -764,6 +789,42 @@ fn query_protocol_merges_compatible_active_models_without_inventing_static_parti } } +#[cfg(feature = "graphql")] +#[test] +fn query_protocol_preserves_one_semantic_identity_for_each_fanout_model() { + let first = direct_model("FirstFanout", "first_fanout"); + let second = direct_model("SecondFanout", "second_fanout"); + let modeled = modeled_projection_with_outputs( + "fanout-owner", + "fanout-program", + "fanout-v1", + vec![first.clone(), second.clone()], + DirectModeledBinding { + eventual: true, + ..DirectModeledBinding::active("fanout-physical-owner") + }, + ); + let semantic_program_id = modeled.program_id().to_string(); + let surface = build_surface(&[first, second], &SurfaceOptions::sqlite()) + .unwrap() + .with_projectors([SurfaceProjector::new("fanout-owner").modeled(modeled)]) + .unwrap(); + + let runtime = crate::graphql::query_protocol::QueryProtocolRuntime::compile(&surface).unwrap(); + for model in ["FirstFanout", "SecondFanout"] { + assert_eq!( + runtime.public_projection_for_model(model), + Some(semantic_program_id.as_str()), + "each fan-out model must retain the program identity that authored it" + ); + } + assert_eq!( + runtime.public_projection_for_model("UnknownModel"), + None, + "unknown models cannot mint a causal proof identity" + ); +} + #[test] fn selected_surfaces_reject_command_and_projector_reattachment() { let full = build_surface(&[orders()], &SurfaceOptions::sqlite()).unwrap(); diff --git a/src/in_memory_repo/projection_protocol/direct_projection.rs b/src/in_memory_repo/projection_protocol/direct_projection.rs index da90e0e8c..2293d4618 100644 --- a/src/in_memory_repo/projection_protocol/direct_projection.rs +++ b/src/in_memory_repo/projection_protocol/direct_projection.rs @@ -70,6 +70,11 @@ pub(in crate::in_memory_repo) fn stage_same_transaction_projection( scope: Some(mutation.scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: batch + .ownership + .iter() + .find(|ownership| ownership.model == mutation.scope.model()) + .and_then(|ownership| ownership.program_id), }, )?; let metadata = ProjectionRecordMetadata { @@ -111,6 +116,7 @@ pub(in crate::in_memory_repo) fn stage_same_transaction_projection( revision: Some(revision), scope: mutation.scope.clone(), change: change.cursor.clone(), + program_id: change.program_id, }; protocol .observations diff --git a/src/in_memory_repo/projection_protocol/rebuild.rs b/src/in_memory_repo/projection_protocol/rebuild.rs index cde839eab..f7795e1e8 100644 --- a/src/in_memory_repo/projection_protocol/rebuild.rs +++ b/src/in_memory_repo/projection_protocol/rebuild.rs @@ -91,6 +91,7 @@ impl InMemoryRepository { scope: Some(row.scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: None, }, )?; let record = ProjectionRecordMetadata { diff --git a/src/in_memory_repo/projection_protocol/state.rs b/src/in_memory_repo/projection_protocol/state.rs index 2bf0f5cbd..2ce23b504 100644 --- a/src/in_memory_repo/projection_protocol/state.rs +++ b/src/in_memory_repo/projection_protocol/state.rs @@ -228,6 +228,7 @@ pub(super) struct PendingChange { pub(super) scope: Option, pub(super) revision: Option, pub(super) failure_id: Option, + pub(super) program_id: Option, } impl PartitionState { diff --git a/src/in_memory_repo/projection_protocol/state_impl.rs b/src/in_memory_repo/projection_protocol/state_impl.rs index fbd37abcf..383e80464 100644 --- a/src/in_memory_repo/projection_protocol/state_impl.rs +++ b/src/in_memory_repo/projection_protocol/state_impl.rs @@ -683,6 +683,7 @@ impl InMemoryProjectionProtocolState { scope: pending.scope, revision: pending.revision, failure_id: pending.failure_id, + program_id: pending.program_id, }; partition.change_head = position; partition.changes.insert(position, change.clone()); diff --git a/src/in_memory_repo/projection_protocol/store_impl.rs b/src/in_memory_repo/projection_protocol/store_impl.rs index 655ef9bff..be530e460 100644 --- a/src/in_memory_repo/projection_protocol/store_impl.rs +++ b/src/in_memory_repo/projection_protocol/store_impl.rs @@ -216,6 +216,11 @@ impl ProjectionProtocolStore for InMemoryRepository { scope: Some(mutation.scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: batch + .ownership + .iter() + .find(|ownership| ownership.model == mutation.scope.model()) + .and_then(|ownership| ownership.program_id), }, )?; let metadata = ProjectionRecordMetadata { @@ -298,6 +303,11 @@ impl ProjectionProtocolStore for InMemoryRepository { if staged_protocol.observations.contains_key(&observation_key) { continue; } + let program_id = batch + .ownership + .iter() + .find(|ownership| ownership.model == scope.model()) + .and_then(|ownership| ownership.program_id); let change_cursor = match staged_change { Some(cursor) => cursor, None => { @@ -310,6 +320,7 @@ impl ProjectionProtocolStore for InMemoryRepository { scope: Some(scope.clone()), revision: revision.clone(), failure_id: None, + program_id, }, )?; let cursor = change.cursor.clone(); @@ -323,6 +334,7 @@ impl ProjectionProtocolStore for InMemoryRepository { revision, scope, change: change_cursor, + program_id, }; staged_protocol .observations @@ -339,6 +351,7 @@ impl ProjectionProtocolStore for InMemoryRepository { scope: None, revision: None, failure_id: None, + program_id: None, }, )?); } @@ -514,6 +527,7 @@ impl ProjectionProtocolStore for InMemoryRepository { scope: None, revision: None, failure_id: Some(batch.failure_id.clone()), + program_id: None, }, )?; let failure = ProjectionFailure { diff --git a/src/in_memory_repo/projection_protocol/tests.rs b/src/in_memory_repo/projection_protocol/tests.rs index e2f28c16b..017549216 100644 --- a/src/in_memory_repo/projection_protocol/tests.rs +++ b/src/in_memory_repo/projection_protocol/tests.rs @@ -1794,6 +1794,7 @@ async fn lengthening_retention_never_restores_a_compacted_prefix() { scope: None, revision: None, failure_id: None, + program_id: None, }], } ); diff --git a/src/microsvc/projector/runtime.rs b/src/microsvc/projector/runtime.rs index c0b3f67f5..26b391241 100644 --- a/src/microsvc/projector/runtime.rs +++ b/src/microsvc/projector/runtime.rs @@ -297,11 +297,12 @@ where } } let failure_input = trusted.clone(); - let workspace = ProjectionWorkspace::new( + let workspace = ProjectionWorkspace::new_with_program_id( self.compiled.codec(), partition_value, trusted, self.change_epoch.clone(), + Some(self.executor.program_id), )?; let (context, workspace) = CausalProjectorContext::new(message, D::Store::clone(store), workspace); diff --git a/src/projection/catalog.rs b/src/projection/catalog.rs index a3ffa2487..e47437be5 100644 --- a/src/projection/catalog.rs +++ b/src/projection/catalog.rs @@ -1808,6 +1808,93 @@ mod tests { )); } + #[test] + fn semantic_program_replacement_requires_epoch_rotation_before_replay() { + let previous_program = program_with_kind_and_partition( + "project_todos", + FINGERPRINT_A, + "Todos", + "todos", + ProjectionMutationKind::Upsert, + ProjectionPartition::Unit, + ); + let replacement_program = program_with_kind_and_partition( + "project_todos", + FINGERPRINT_A, + "Todos", + "todos", + ProjectionMutationKind::Patch, + ProjectionPartition::Unit, + ); + assert_ne!( + previous_program.id().unwrap(), + replacement_program.id().unwrap(), + "different projection behavior must have different semantic identities" + ); + let previous_binding = eventual( + &previous_program, + "todo-reads-v1", + ProjectionExecutionClass::Causal, + ); + let replacement_binding = eventual( + &replacement_program, + "todo-reads-v2", + ProjectionExecutionClass::Causal, + ); + assert_eq!( + previous_binding.physical_topology(), + replacement_binding.physical_topology(), + "the physical owner may remain stable while the program changes" + ); + + let previous_catalog = ProjectionCatalog::try_new(vec![previous_binding.clone()]).unwrap(); + let previous_active = previous_catalog + .activate( + vec![activation( + &previous_binding, + "todos-rebuild-1", + ProjectionBindingState::Active, + Some(ProjectionExecutorRoute::remote("projector-v1").unwrap()), + )], + None, + ) + .unwrap(); + let replacement_catalog = + ProjectionCatalog::try_new(vec![replacement_binding.clone()]).unwrap(); + let same_epoch = replacement_catalog + .activate( + vec![activation( + &replacement_binding, + "todos-rebuild-1", + ProjectionBindingState::Active, + Some(ProjectionExecutorRoute::remote("projector-v2").unwrap()), + )], + Some((&previous_catalog, &previous_active)), + ) + .unwrap_err(); + assert!(matches!( + same_epoch, + ProjectionCatalogError::SameEpochTakeover { .. } + )); + + let rotated = replacement_catalog + .activate( + vec![activation( + &replacement_binding, + "todos-rebuild-2", + ProjectionBindingState::Active, + Some(ProjectionExecutorRoute::remote("projector-v2").unwrap()), + )], + Some((&previous_catalog, &previous_active)), + ) + .unwrap(); + assert_eq!( + rotated.bindings()[0].program_id(), + replacement_program.id().unwrap() + ); + assert_eq!(rotated.bindings()[0].epoch().as_str(), "todos-rebuild-2"); + } + #[test] fn new_epoch_allows_rollout_then_draining_stops_new_obligations() { let program = program("project_todos", FINGERPRINT_A); diff --git a/src/projection_protocol/store/identity.rs b/src/projection_protocol/store/identity.rs index 14d55028d..4f2aef328 100644 --- a/src/projection_protocol/store/identity.rs +++ b/src/projection_protocol/store/identity.rs @@ -191,6 +191,13 @@ pub(crate) enum ProjectionInputDisposition { pub(crate) struct ProjectionModelOwnership { pub(crate) model: String, pub(crate) table: String, + /// Semantic author identity for a commit carrying this ownership. + /// + /// Bootstrap declarations leave this unset. A modeled projector attaches + /// its immutable program identity when sealing a commit; the adapter + /// persists that identity on each change/observation rather than changing + /// an existing ownership row retroactively. + pub(crate) program_id: Option, } impl ProjectionModelOwnership { @@ -201,8 +208,14 @@ impl ProjectionModelOwnership { Ok(Self { model: bounded_name("projection model", model, 255)?, table: bounded_name("projection table", table, 255)?, + program_id: None, }) } + + pub(crate) fn with_program_id(mut self, program_id: ProjectionProgramId) -> Self { + self.program_id = Some(program_id); + self + } } /// Record state required before a staged mutation may apply. diff --git a/src/projection_protocol/store/mod.rs b/src/projection_protocol/store/mod.rs index 0ab5d9fb3..f99901a1c 100644 --- a/src/projection_protocol/store/mod.rs +++ b/src/projection_protocol/store/mod.rs @@ -31,6 +31,7 @@ use crate::repository::{InboxReceipt, RepositoryError}; use crate::table::{ RowKey, RowValues, TableMutation, TableSchema, TableStoreError, TableWritePlan, }; +use crate::ProjectionProgramId; mod backend_helpers; mod commit; diff --git a/src/projection_protocol/store/query.rs b/src/projection_protocol/store/query.rs index 035207498..86132e37f 100644 --- a/src/projection_protocol/store/query.rs +++ b/src/projection_protocol/store/query.rs @@ -686,6 +686,10 @@ pub struct ProjectionObservation { /// Canonical dependency scope when no record revision exists. pub scope: ProjectionRecordScope, pub change: ProjectionChangeCursor, + /// Semantic program identity recorded by the projector that authored this + /// observation. `None` is legacy/unversioned evidence and cannot satisfy a + /// modeled causal obligation. + pub program_id: Option, } /// Durable terminal failure for one exact input and repair generation. @@ -753,6 +757,9 @@ pub struct ProjectionChange { pub scope: Option, pub revision: Option, pub failure_id: Option, + /// Semantic program identity recorded at commit time. It is deliberately + /// independent from the currently active projector binding. + pub program_id: Option, } /// Result and exact evidence produced by an asynchronous projection commit. diff --git a/src/projection_protocol/store/replay.rs b/src/projection_protocol/store/replay.rs index df6a257e0..e04a8d17c 100644 --- a/src/projection_protocol/store/replay.rs +++ b/src/projection_protocol/store/replay.rs @@ -162,6 +162,8 @@ struct ReplayChange { scope: Option, revision: Option, failure_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + program_id: Option, } impl From<&ProjectionChange> for ReplayChange { @@ -176,6 +178,7 @@ impl From<&ProjectionChange> for ReplayChange { scope: change.scope.as_ref().map(ReplayScope::from), revision: change.revision.as_ref().map(ReplayRevision::from), failure_id: change.failure_id.clone(), + program_id: change.program_id.map(|program_id| program_id.to_string()), } } } @@ -188,6 +191,8 @@ struct ReplayObservation { revision: Option, scope: ReplayScope, change: ReplayCursor, + #[serde(default, skip_serializing_if = "Option::is_none")] + program_id: Option, } impl From<&ProjectionObservation> for ReplayObservation { @@ -198,6 +203,9 @@ impl From<&ProjectionObservation> for ReplayObservation { revision: observation.revision.as_ref().map(ReplayRevision::from), scope: ReplayScope::from(&observation.scope), change: ReplayCursor::from(&observation.change), + program_id: observation + .program_id + .map(|program_id| program_id.to_string()), } } } @@ -316,6 +324,12 @@ impl ReplayChange { .map_err(|error| replay_validation_error("change failure ID", error)) }) .transpose()?, + program_id: self + .program_id + .as_deref() + .map(ProjectionProgramId::parse) + .transpose() + .map_err(|error| replay_validation_error("change program ID", error))?, }) } } @@ -336,6 +350,12 @@ impl ReplayObservation { .transpose()?, scope: self.scope.into_scope()?, change: self.change.into_cursor()?, + program_id: self + .program_id + .as_deref() + .map(ProjectionProgramId::parse) + .transpose() + .map_err(|error| replay_validation_error("observation program ID", error))?, }) } } @@ -468,6 +488,12 @@ fn validate_same_transaction_replay_evidence( "direct projection evidence observation does not match its record change".into(), ); } + if observation.program_id != change.program_id { + return Err( + "direct projection evidence observation and change program identities do not match" + .into(), + ); + } Ok(()) } diff --git a/src/projection_protocol/store/tests.rs b/src/projection_protocol/store/tests.rs index 0c7d6685c..5ba7b1f20 100644 --- a/src/projection_protocol/store/tests.rs +++ b/src/projection_protocol/store/tests.rs @@ -55,6 +55,7 @@ fn same_transaction_evidence() -> SameTransactionProjectionEvidence { scope: Some(scope.clone()), revision: Some(revision.clone()), failure_id: None, + program_id: None, }], observations: vec![ProjectionObservation { causation_id: "cause-1".into(), @@ -62,6 +63,7 @@ fn same_transaction_evidence() -> SameTransactionProjectionEvidence { revision: Some(revision), scope, change, + program_id: None, }], } } diff --git a/src/projection_protocol/workspace.rs b/src/projection_protocol/workspace.rs index e6bdb9c21..fe7645af7 100644 --- a/src/projection_protocol/workspace.rs +++ b/src/projection_protocol/workspace.rs @@ -21,6 +21,7 @@ use crate::table::{ DeleteTableRowMutation, ExpectedVersion, PatchMode, PatchTableRowMutation, RowKey, RowPatch, RowWriteMode, TableMutation, TableRowMutation, TableSchema, }; +use crate::ProjectionProgramId; /// Typed, commit-less workspace passed to a causal projector handler. /// @@ -33,6 +34,7 @@ pub struct ProjectionWorkspace { partition_value: Option, input: TrustedProjectionInput, change_epoch: ProjectionEpoch, + program_id: Option, ownership: BTreeMap, mutations: Vec, observations: Vec, @@ -45,6 +47,16 @@ impl ProjectionWorkspace { partition_value: Option, input: TrustedProjectionInput, change_epoch: ProjectionEpoch, + ) -> Result { + Self::new_with_program_id(codec, partition_value, input, change_epoch, None) + } + + pub(crate) fn new_with_program_id( + codec: Arc, + partition_value: Option, + input: TrustedProjectionInput, + change_epoch: ProjectionEpoch, + program_id: Option, ) -> Result { if codec.topology() != input.cursor.topology() { return Err(ProjectionProtocolError::ScopeMismatch { @@ -64,6 +76,7 @@ impl ProjectionWorkspace { partition_value, input, change_epoch, + program_id, ownership: BTreeMap::new(), mutations: Vec::new(), observations: Vec::new(), @@ -367,7 +380,13 @@ impl ProjectionWorkspace { ) -> Result, ProjectionProtocolError> { self.ownership .iter() - .map(|(model, table)| ProjectionModelOwnership::new(model.clone(), table.clone())) + .map(|(model, table)| { + let ownership = ProjectionModelOwnership::new(model.clone(), table.clone())?; + Ok(self + .program_id + .map(|program_id| ownership.clone().with_program_id(program_id)) + .unwrap_or(ownership)) + }) .collect() } diff --git a/src/sqlx_repo/projection_protocol/helpers.rs b/src/sqlx_repo/projection_protocol/helpers.rs index 175aafde9..bfd7d1e0f 100644 --- a/src/sqlx_repo/projection_protocol/helpers.rs +++ b/src/sqlx_repo/projection_protocol/helpers.rs @@ -104,3 +104,17 @@ pub(super) fn decode_observation_kind( ProjectionObservationKind::from_storage_str(value) .ok_or_else(|| corrupt_storage(format!("unknown projection observation kind `{value}`"))) } + +pub(super) fn decode_program_id( + value: Option, +) -> Result, ProjectionProtocolError> { + value + .map(|value| { + crate::ProjectionProgramId::parse(&value).map_err(|error| { + corrupt_storage(format!( + "invalid stored projection program identity: {error}" + )) + }) + }) + .transpose() +} diff --git a/src/sqlx_repo/projection_protocol/mod.rs b/src/sqlx_repo/projection_protocol/mod.rs index d27b7c6bf..cf125660e 100644 --- a/src/sqlx_repo/projection_protocol/mod.rs +++ b/src/sqlx_repo/projection_protocol/mod.rs @@ -51,6 +51,7 @@ use crate::table::{ validate_row_values, RowKey, RowValues, TableMutation, TableSchema, TableStoreError, TableWritePlan, }; +use crate::ProjectionProgramId; mod helpers; mod identity; diff --git a/src/sqlx_repo/projection_protocol/reads.rs b/src/sqlx_repo/projection_protocol/reads.rs index 1dfac6dd0..7b31bfd05 100644 --- a/src/sqlx_repo/projection_protocol/reads.rs +++ b/src/sqlx_repo/projection_protocol/reads.rs @@ -176,6 +176,10 @@ where let failure_id: Option = row .try_get("failure_id") .map_err(|error| protocol_storage_error::("decode change failure ID", error))?; + let program_id = + decode_program_id(row.try_get("program_id").map_err(|error| { + protocol_storage_error::("decode change program identity", error) + })?)?; let scope = match (model_name, key_bytes, key_hash) { (Some(model), Some(bytes), Some(hash)) => { @@ -253,6 +257,7 @@ where scope, revision, failure_id, + program_id, }) } @@ -365,6 +370,11 @@ where Some(staged.scope.clone()), Some(revision.clone()), None, + batch + .ownership + .iter() + .find(|ownership| ownership.model == staged.scope.model()) + .and_then(|ownership| ownership.program_id), )?; let metadata = ProjectionRecordMetadata { source_snapshot: None, @@ -398,6 +408,11 @@ where scope: staged.scope.clone(), revision: Some(revision), change: change.cursor.clone(), + program_id: batch + .ownership + .iter() + .find(|ownership| ownership.model == staged.scope.model()) + .and_then(|ownership| ownership.program_id), }; apply_read_model_write_plan_in_tx(tx, write_plan).await?; @@ -1317,7 +1332,8 @@ where observation.scope_kind AS evidence_scope_kind, \ observation.canonical_key_bytes, observation.canonical_key_hash, \ observation.incarnation, observation.revision, observation.change_epoch, \ - observation.change_position, partition.topology_bytes AS evidence_topology_bytes, \ + observation.change_position, observation.program_id, \ + partition.topology_bytes AS evidence_topology_bytes, \ partition.partition_bytes AS evidence_partition_bytes, \ partition.change_epoch AS evidence_partition_epoch, \ partition.change_head AS evidence_partition_head \ @@ -1624,7 +1640,7 @@ where observation.causation_id, observation.model_name, observation.scope_kind, \ observation.canonical_key_bytes, observation.canonical_key_hash, \ observation.incarnation, observation.revision, observation.change_epoch, \ - observation.change_position, partition.topology_bytes, \ + observation.change_position, observation.program_id, partition.topology_bytes, \ partition.partition_bytes, partition.change_epoch AS partition_change_epoch, \ partition.change_head AS partition_change_head \ FROM projection_observations observation \ @@ -2258,7 +2274,7 @@ where let mut builder = QueryBuilder::::new( "SELECT change_epoch, change_position, change_kind, causation_id, model_name, \ scope_kind, canonical_key_bytes, canonical_key_hash, incarnation, revision, \ - failure_id FROM projection_changes WHERE topology_hash = ", + failure_id, program_id FROM projection_changes WHERE topology_hash = ", ); builder.push_bind(topology_hash.as_slice()); builder.push(" AND partition_hash = "); diff --git a/src/sqlx_repo/projection_protocol/rebuild.rs b/src/sqlx_repo/projection_protocol/rebuild.rs index 1f48a7ade..0c82dca37 100644 --- a/src/sqlx_repo/projection_protocol/rebuild.rs +++ b/src/sqlx_repo/projection_protocol/rebuild.rs @@ -135,6 +135,7 @@ where Some(row.scope.clone()), Some(revision.clone()), None, + None, )?; let record = ProjectionRecordMetadata { revision, diff --git a/src/sqlx_repo/projection_protocol/store_impl.rs b/src/sqlx_repo/projection_protocol/store_impl.rs index 5e60a00ff..353378e58 100644 --- a/src/sqlx_repo/projection_protocol/store_impl.rs +++ b/src/sqlx_repo/projection_protocol/store_impl.rs @@ -442,6 +442,7 @@ where Some(mutation.scope.clone()), Some(revision.clone()), None, + program_id_for_model(&batch.ownership, mutation.scope.model()), )?; let metadata = ProjectionRecordMetadata { revision, @@ -530,17 +531,20 @@ where Some(scope.clone()), revision.clone(), None, + program_id_for_model(&batch.ownership, scope.model()), )?; let cursor = change.cursor.clone(); changes.push(change); cursor }; + let program_id = program_id_for_model(&batch.ownership, scope.model()); observations.push(ProjectionObservation { causation_id: batch.input.causation_id.clone(), kind: request.kind, revision, scope, change: change_cursor, + program_id, }); } @@ -555,6 +559,7 @@ where None, None, None, + None, )?); } let final_change = changes @@ -722,6 +727,7 @@ where None, None, Some(batch.failure_id.clone()), + None, )?; insert_change_in_tx(&mut tx, &change).await?; insert_failure_in_tx(&mut tx, &batch, &change.cursor).await?; diff --git a/src/sqlx_repo/projection_protocol/tests.rs b/src/sqlx_repo/projection_protocol/tests.rs index 53b908b49..f91a3a8b7 100644 --- a/src/sqlx_repo/projection_protocol/tests.rs +++ b/src/sqlx_repo/projection_protocol/tests.rs @@ -17,7 +17,8 @@ mod tests { use crate::projection_protocol::{ ProjectionCheckpointProbe, ProjectionExecutionSnapshotBatchRequest, ProjectionGraphSnapshotRequest, ProjectionObservationRequest, - ProjectionQuerySnapshotRequest, ProjectionRecordMutation, ProjectionScopeCodec, + ProjectionLiveRecordRequest, ProjectionQuerySnapshotRequest, ProjectionRecordMutation, + ProjectionScopeCodec, }; use crate::repository::{CommitBatch, ReadModelWritePlanStore, TransactionalCommit}; use crate::table::{ @@ -364,6 +365,12 @@ mod tests { ProjectionModelOwnership::new("SqlTodoView", "sql_todo_views").unwrap() } + fn semantic_program_id(fill: char) -> crate::ProjectionProgramId { + let hex = std::iter::repeat_n(fill, 64).collect::(); + crate::ProjectionProgramId::parse(&format!("pp1:sha256:{hex}")) + .expect("test semantic program ID is canonical") + } + #[derive(Clone, Copy)] struct ProjectionScenario; @@ -467,6 +474,33 @@ mod tests { (repository, database_path) } + async fn reopen_wal_repository(path: &Path) -> SqlxRepository { + let pool = SqlitePoolOptions::new() + .max_connections(5) + .connect_with( + SqliteConnectOptions::new() + .filename(path) + .create_if_missing(false) + .journal_mode(SqliteJournalMode::Wal), + ) + .await + .unwrap(); + let repository = SqlxRepository::::new(pool) + .with_projection_change_retention(ProjectionChangeRetention::new(16).unwrap()); + repository.migrate().await.unwrap(); + let mut registry = TableSchemaRegistry::new(); + registry.register_schema(schema().clone()).unwrap(); + repository + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + repository + .register_projection_models(&topology(), &[ownership()]) + .await + .unwrap(); + repository + } + async fn remove_wal_database(repository: SqlxRepository, path: &Path) { repository.pool().close().await; for candidate in [ @@ -1017,6 +1051,108 @@ mod tests { assert_ne!(old_scope, new_scope); } + #[tokio::test] + async fn sqlite_modeled_projection_identity_is_durable_across_restart_and_null_history_stays_readable() + { + let (repository, database_path) = wal_repository_with_retention(16).await; + let program_a = semantic_program_id('a'); + let scope = record_scope(); + let result = repository + .commit_projection(ProjectionCommitBatch { + input: input( + 1, + b"semantic-identity-a", + "semantic-identity-message-a", + "semantic-identity-cause-a", + ProjectionGeneration::initial(), + ), + change_epoch: change_epoch(), + ownership: vec![ownership().with_program_id(program_a)], + mutations: vec![mutation( + ProjectionRecordExpectation::Missing, + ProjectionMutationKind::Upsert, + )], + observations: vec![ProjectionObservationRequest { + kind: ProjectionObservationKind::Record, + target: ProjectionObservationTarget::StagedRecord(scope.clone()), + }], + }) + .await + .unwrap(); + assert!(result + .changes + .iter() + .all(|change| change.program_id == Some(program_a))); + + let selected = + ProjectionCausationEvidenceRequest::new("semantic-identity-cause-a", vec![topology()]) + .unwrap(); + let evidence = repository + .projection_causation_evidence(&selected) + .await + .unwrap(); + assert_eq!(evidence.observations.len(), 1); + assert_eq!(evidence.observations[0].program_id, Some(program_a)); + + repository.pool().close().await; + let reopened = reopen_wal_repository(&database_path).await; + let changes = match reopened + .projection_changes(&topology(), &partition(), None, 100) + .await + .unwrap() + { + ProjectionChangeRead::Changes { changes, .. } => changes, + other => panic!("restarted repository must retain projection changes: {other:?}"), + }; + assert_eq!(changes.len(), 1, "the staged observation shares the record change"); + assert!(changes + .iter() + .all(|change| change.program_id == Some(program_a))); + let evidence = reopened + .projection_causation_evidence(&selected) + .await + .unwrap(); + assert_eq!(evidence.observations.len(), 1); + assert_eq!(evidence.observations[0].program_id, Some(program_a)); + + // Rows written before semantic identities existed remain useful after + // migration, but their null identity cannot mint modeled proof. + sqlx::query( + "UPDATE projection_changes SET program_id = NULL WHERE causation_id = ?", + ) + .bind("semantic-identity-cause-a") + .execute(reopened.pool()) + .await + .unwrap(); + sqlx::query( + "UPDATE projection_observations SET program_id = NULL WHERE causation_id = ?", + ) + .bind("semantic-identity-cause-a") + .execute(reopened.pool()) + .await + .unwrap(); + let null_history = reopened + .projection_causation_evidence(&selected) + .await + .unwrap(); + assert_eq!(null_history.observations.len(), 1); + assert_eq!(null_history.observations[0].program_id, None); + let readable = reopened + .projection_live_record_batch( + &ProjectionLiveRecordBatchRequest::new(vec![ + ProjectionLiveRecordRequest::new(&scope_codec(), "SqlTodoView", record_key()) + .unwrap(), + ]) + .unwrap(), + ) + .await + .unwrap(); + assert!(readable.records[0].is_some(), "unversioned rows remain readable"); + assert_eq!(readable.records[0].as_ref().unwrap().revision.scope(), &scope); + + remove_wal_database(reopened, &database_path).await; + } + #[tokio::test] async fn sqlite_receipts_source_fences_and_raw_write_fence_are_exact() { let repository = repository().await; diff --git a/src/sqlx_repo/projection_protocol/writes.rs b/src/sqlx_repo/projection_protocol/writes.rs index 1711222c4..fd5472a61 100644 --- a/src/sqlx_repo/projection_protocol/writes.rs +++ b/src/sqlx_repo/projection_protocol/writes.rs @@ -1,5 +1,15 @@ use super::*; +pub(super) fn program_id_for_model( + ownership: &[ProjectionModelOwnership], + model: &str, +) -> Option { + ownership + .iter() + .find(|declaration| declaration.model == model) + .and_then(|declaration| declaration.program_id) +} + pub(super) async fn ensure_partition_ownership_in_tx( tx: &mut Transaction<'_, DB>, topology: &ProjectorTopologyId, @@ -387,6 +397,7 @@ pub(super) fn allocate_change( scope: Option, revision: Option, failure_id: Option, + program_id: Option, ) -> Result { state.change_head = checked_next(state.change_head, "projection change")?; Ok(ProjectionChange { @@ -402,6 +413,7 @@ pub(super) fn allocate_change( scope, revision, failure_id, + program_id, }) } @@ -425,7 +437,7 @@ where "INSERT INTO projection_changes \ (topology_hash, partition_hash, change_epoch, change_position, change_kind, \ causation_id, model_name, scope_kind, canonical_key_bytes, canonical_key_hash, \ - incarnation, revision, failure_id) VALUES (", + incarnation, revision, failure_id, program_id) VALUES (", ); builder.push_bind(topology_hash.as_slice()); builder.push(", "); @@ -487,6 +499,13 @@ where } else { builder.push("NULL"); } + builder.push(", "); + let program_id_value = change.program_id.map(|program_id| program_id.to_string()); + if let Some(program_id) = program_id_value.as_deref() { + builder.push_bind(program_id); + } else { + builder.push("NULL"); + } builder.push(")"); builder .build() @@ -659,6 +678,9 @@ where })?, "observation change position", )?; + let program_id = decode_program_id(row.try_get("program_id").map_err(|error| { + protocol_storage_error::("decode observation program identity", error) + })?)?; Ok(ProjectionObservation { causation_id: causation_id.to_string(), kind, @@ -670,6 +692,7 @@ where change_epoch, change_position, )?, + program_id, }) } @@ -696,7 +719,7 @@ where let key_hash = scope.key_digest(); let mut builder = QueryBuilder::::new( "SELECT canonical_key_bytes, canonical_key_hash, incarnation, revision, \ - change_epoch, change_position FROM projection_observations WHERE topology_hash = ", + change_epoch, change_position, program_id FROM projection_observations WHERE topology_hash = ", ); builder.push_bind(topology_hash.as_slice()); builder.push(" AND partition_hash = "); @@ -740,7 +763,7 @@ where "INSERT INTO projection_observations \ (topology_hash, partition_hash, causation_id, model_name, scope_kind, \ canonical_key_bytes, canonical_key_hash, incarnation, revision, \ - change_epoch, change_position) VALUES (", + change_epoch, change_position, program_id) VALUES (", ); builder.push_bind(topology_hash.as_slice()); builder.push(", "); @@ -780,6 +803,15 @@ where observation.change.position(), "observation change position", )?); + builder.push(", "); + let program_id_value = observation + .program_id + .map(|program_id| program_id.to_string()); + if let Some(program_id) = program_id_value.as_deref() { + builder.push_bind(program_id); + } else { + builder.push("NULL"); + } builder.push(")"); builder .build() diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 79f9f1136..3bb2ce531 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -47,7 +47,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); assert_eq!( descriptions, vec![ @@ -56,7 +56,8 @@ mod tests { "projection protocol", "command ledger atomic state", "projection source snapshots", - "gateway dependency versions" + "gateway dependency versions", + "projection program identity" ] ); assert_eq!( @@ -86,6 +87,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0006_gateway_dependency_versions.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0007_projection_program_identity.sql" + )), ] ); } @@ -105,7 +110,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); assert_eq!( descriptions, vec![ @@ -114,7 +119,8 @@ mod tests { "projection protocol", "command ledger atomic state", "projection source snapshots", - "gateway dependency versions" + "gateway dependency versions", + "projection program identity" ] ); assert_eq!( @@ -144,6 +150,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0006_gateway_dependency_versions.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0007_projection_program_identity.sql" + )), ] ); } From 4a796001097e0daad2b03670c43cb7c635b23ea3 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 19:24:42 -0500 Subject: [PATCH 078/484] test: track projection identity migration --- tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index 33bd83f5c..db25e06b8 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 6); + assert_eq!(latest_version, 7); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 55e7fd3c9..2a98aff4b 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 6); + assert_eq!(latest_version, 7); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From 4d08f12730eddf09b3052a203841edd286bcc7fd Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 19:26:25 -0500 Subject: [PATCH 079/484] test: include projection identity migration --- distributed_cli/src/contracts/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 11b4bb372..0f0052be0 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory From 0b511bb8d0f02ec9d0c1026e32eed3fe67f28ed1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 20:44:14 -0500 Subject: [PATCH 080/484] fix: evaluate proofs for succeeded causal receipts --- src/microsvc/service/causal.rs | 20 +++ src/microsvc/service/tests.rs | 237 +++++++++++++++++++++++++++++++++ 2 files changed, 257 insertions(+) diff --git a/src/microsvc/service/causal.rs b/src/microsvc/service/causal.rs index 2cefd280a..aa5a705ab 100644 --- a/src/microsvc/service/causal.rs +++ b/src/microsvc/service/causal.rs @@ -846,6 +846,26 @@ where == crate::graphql::projection_delta::runtime::ModeledProjectionStatusDisposition::Revalidate }); let (state, evidence) = match receipt.state { + CommandLedgerState::Succeeded + if receipt + .projection_metadata + .as_ref() + .is_some_and(|metadata| !metadata.obligations.is_empty()) + || !receipt.obligations.is_empty() => + { + let (_, evidence) = evaluate_pending_projection_evidence( + repository, + &receipt, + protocol, + modeled_plan.as_ref(), + ) + .await?; + // A succeeded ledger receipt proves the command commit. + // Retained projection obligations are only evidence detail; + // their asynchronous proof must not rewrite that public + // command state. + (CausalCommandPublicState::Succeeded, evidence) + } CommandLedgerState::Succeeded => (CausalCommandPublicState::Succeeded, Vec::new()), CommandLedgerState::Atomic => ( CausalCommandPublicState::Atomic, diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 089f86c79..dc2671b9f 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -2680,6 +2680,243 @@ async fn graphql_terminal_replay_revalidates_after_active_projection_starts_drai assert_eq!(handler_calls.load(Ordering::SeqCst), 2); } +#[cfg(all(feature = "graphql", feature = "sqlite"))] +#[tokio::test] +async fn graphql_succeeded_status_evaluates_retained_projection_evidence() { + let repository = crate::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .expect("framework migrations should apply"); + let mut table_registry = crate::table::TableSchemaRegistry::new(); + table_registry + .register_schema( + ::schema().clone(), + ) + .unwrap(); + repository + .bootstrap_table_schema_for_dev(&table_registry) + .await + .unwrap(); + let projector = modeled_lifecycle_projector( + crate::projection::placement::ProjectionBindingState::Active, + "causal-succeeded-status", + "causal-succeeded-status-topology", + 0x7a, + ); + let service = Service::new().named("causal-succeeded-status").routes( + Routes::new() + .with_repo(repository.clone().aggregate::()) + .with_read_model_store(repository.clone()) + .typed_command( + typed_command::>("causal.lifecycle") + .roles(["user"]) + .emits(crate::events![CausalLifecycleRecorded]), + ) + .handle( + |context: &CausalCommandContext<'_, CausalDispatcherAggregate>, + input: CausalTestInput| { + let result = (|| { + let mut checkout = context.create(); + checkout.record_lifecycle(input.id.clone(), input.label)?; + context + .publish_events() + .commit(checkout)? + .eventual(TypedOutput { id: input.id }) + })(); + async move { result } + }, + ) + .consume_projection(projector.clone()), + ); + let engine = crate::graphql::GraphqlEngine::builder(&repository) + .protocol_token_key(TEST_PROTOCOL_TOKEN_KEY) + .model::( + crate::graphql::ModelPermissions::new() + .grant("user", crate::graphql::read().all_columns()), + ) + .service(&service) + .client_projectors([projector]) + .build() + .expect("active modeled projection should compile"); + let service = Arc::new( + service + .try_with_graphql(engine) + .expect("compiled service should bind"), + ); + let command_id = causal_test_command_id(); + let mutation = format!( + "mutation {{ causal_lifecycle(commandId: \"{command_id}\", input: {{ id: \"todo-succeeded-status\", label: \"active\" }}) {{ id }} }}" + ); + let session = session_with_role("user"); + let principal = causal_test_principal(); + let response = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&mutation) + .data(command_host(&service)) + .data(principal.clone()), + ) + .await; + assert!(response.errors.is_empty(), "{response:?}"); + let envelope = serde_json::to_value( + response + .extensions + .get("distributed") + .expect("modeled command should carry the protocol envelope"), + ) + .unwrap(); + assert_eq!(envelope["command"]["state"], "succeeded_pending_projection"); + assert_eq!(envelope["command"]["expects"].as_array().unwrap().len(), 1); + let causation_id = envelope["command"]["causationId"] + .as_str() + .expect("command envelope should carry its causation") + .to_string(); + + // The wait-path cell commits a terminal succeeded receipt while retaining + // modeled obligations. Before the projector writes proof, status remains + // publicly succeeded but cannot claim an observation. + let changed = sqlx::query( + "UPDATE command_ledger SET state = 'succeeded' \ + WHERE service_id = ? AND command_id = ?", + ) + .bind("causal-succeeded-status") + .bind(&command_id) + .execute(repository.pool()) + .await + .unwrap(); + assert_eq!(changed.rows_affected(), 1); + + let status_query = + format!("query {{ commandStatus(commandId: \"{command_id}\") {{ state }} }}"); + let before_projection = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&status_query) + .data(command_host(&service)) + .data(principal.clone()), + ) + .await; + assert!(before_projection.errors.is_empty(), "{before_projection:?}"); + assert_eq!( + before_projection.data.into_json().unwrap(), + json!({"commandStatus": {"state": "succeeded"}}) + ); + let before_envelope = serde_json::to_value( + before_projection + .extensions + .get("distributed") + .expect("status should carry its protocol envelope"), + ) + .unwrap(); + assert_eq!(before_envelope["command"]["state"], "succeeded"); + assert_eq!( + before_envelope["command"]["expects"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert!(before_envelope["command"].get("observations").is_none()); + + let pending = repository + .outbox_store() + .pending(10) + .await + .expect("the committed domain event should be pending"); + assert_eq!(pending.len(), 1); + let ordered = crate::bus::OrderedDelivery::new( + crate::projection_protocol::ProjectionSource::new( + "test-ordered-events", + b"causal-succeeded-status".to_vec(), + ) + .unwrap(), + crate::projection_protocol::ProjectionEpoch::new("test-ordered-events-v1").unwrap(), + 1, + true, + ) + .unwrap(); + service + .dispatch_ordered_message(&Message::from(pending[0].clone()), Some(&ordered)) + .await + .expect("the real modeled projector should commit its evidence"); + + let after_projection = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&status_query) + .data(command_host(&service)) + .data(principal.clone()), + ) + .await; + assert!(after_projection.errors.is_empty(), "{after_projection:?}"); + let after_envelope = serde_json::to_value( + after_projection + .extensions + .get("distributed") + .expect("status should carry its protocol envelope"), + ) + .unwrap(); + assert_eq!(after_envelope["command"]["state"], "succeeded"); + assert_eq!( + after_envelope["command"]["observations"] + .as_array() + .expect("matching durable proof should be exposed") + .len(), + 1 + ); + assert_eq!( + after_envelope["command"]["observations"][0]["causationId"], + causation_id + ); + + // A proof authored by a different semantic program is not an observation + // for this command, even when its physical topology and scope are equal. + let wrong_program = + "pp1:sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let changed = + sqlx::query("UPDATE projection_observations SET program_id = ? WHERE causation_id = ?") + .bind(wrong_program) + .bind(&causation_id) + .execute(repository.pool()) + .await + .unwrap(); + assert_eq!(changed.rows_affected(), 1); + + let wrong_projection = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&status_query) + .data(command_host(&service)) + .data(principal), + ) + .await; + assert!(wrong_projection.errors.is_empty(), "{wrong_projection:?}"); + let wrong_envelope = serde_json::to_value( + wrong_projection + .extensions + .get("distributed") + .expect("status should carry its protocol envelope"), + ) + .unwrap(); + assert_eq!(wrong_envelope["command"]["state"], "succeeded"); + assert!(wrong_envelope["command"].get("observations").is_none()); + assert_eq!( + wrong_envelope["command"]["expects"] + .as_array() + .unwrap() + .len(), + 1, + "mismatched proof must leave the exact obligation pending" + ); +} + #[cfg(all(feature = "graphql", feature = "sqlite"))] #[tokio::test] async fn engine_rejects_incompatible_direct_owner_before_typed_command_binding() { From a1176e4ce3dbfaa8bc73f3117e00640efb5dcfca Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 23:15:51 -0500 Subject: [PATCH 081/484] feat: add external command ledger bindings --- README.md | 13 + distributed_cli/src/contracts/tests.rs | 2 +- migrations/inventory.json | 12 + .../0008_external_command_binding.sql | 4 + .../sqlite/0008_external_command_binding.sql | 4 + src/command_ledger/mod.rs | 3 +- src/command_ledger/record.rs | 62 ++- src/command_ledger/reservation.rs | 240 ++++++++++ src/command_ledger/tests.rs | 440 ++++++++++++++++++ src/command_ledger/traits.rs | 11 +- src/in_memory_repo/repository.rs | 27 +- src/microsvc/cell_host/sql_store.rs | 10 +- src/microsvc/cell_host/store.rs | 10 +- src/microsvc/service/tests.rs | 10 +- src/postgres_repo/mod.rs | 2 +- src/queued_repo/repository.rs | 10 +- src/repository/migrations.rs | 2 +- src/repository/sql/ledger.rs | 79 +++- src/repository/sqlite_codec.rs | 2 +- src/sqlx_repo/repo/backend.rs | 18 +- src/sqlx_repo/repo/commit.rs | 18 + src/sqlx_repo/repo/mod.rs | 2 +- tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 24 files changed, 964 insertions(+), 21 deletions(-) create mode 100644 migrations/postgres/0008_external_command_binding.sql create mode 100644 migrations/sqlite/0008_external_command_binding.sql diff --git a/README.md b/README.md index bbb492149..9ea07ee88 100644 --- a/README.md +++ b/README.md @@ -739,6 +739,19 @@ can deliver the same event ID again; consumers must remain idempotent. Event history belongs in the event store, and command retry results belong in command receipts. Neither depends on retaining delivered outbox rows. +Commands dispatched to another aggregate cell use the same command ledger, but +with an explicit external dispatch binding. The binding records the logical +route kind and shard alongside the command identity; it is immutable for that +reservation and survives lease reclaim and terminal replay. External completion +updates only the ledger after the returned attempt fence and binding match. It +does not append local events, write the outbox, or treat the cell's commit as +proof that an asynchronous read-model projection has completed. A local causal +commit cannot complete an externally bound reservation, and an external +completion cannot complete a local reservation. Retained cell-only receipts +without a gateway binding remain explicit unknowns until a matching gateway +reservation and trusted completion protocol can be established; they are never +retrofitted into a different route or silently replayed. + In v5, `OutboxStore::complete` and `complete_many` remove delivered rows instead of retaining `Published` records. Repeating settlement of a removed row returns `NotFound`; stale claims on existing rows still return `InvalidState`. diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 0f0052be0..1c05512d7 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/migrations/inventory.json b/migrations/inventory.json index 9e2e9add7..25b8cc134 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -84,6 +84,18 @@ "path": "migrations/postgres/0007_projection_program_identity.sql", "sha256": "ad7da74a11637a522279a6bc061d2c79db1f807f869368cf31735a089dfe0204" } + }, + { + "version": 8, + "description": "external command binding", + "sqlite": { + "path": "migrations/sqlite/0008_external_command_binding.sql", + "sha256": "4be4e5583d7f37a4f2820bf7777a750246ff574d43f4b9fbd15324d6712a6240" + }, + "postgres": { + "path": "migrations/postgres/0008_external_command_binding.sql", + "sha256": "2f93c5685cde1d5cafd444d3a28dbcbf01f16cd44a566c7af61a7bd2a793a163" + } } ] } diff --git a/migrations/postgres/0008_external_command_binding.sql b/migrations/postgres/0008_external_command_binding.sql new file mode 100644 index 000000000..0664b3d5e --- /dev/null +++ b/migrations/postgres/0008_external_command_binding.sql @@ -0,0 +1,4 @@ +-- Bind externally dispatched command reservations to their logical route. +-- NULL retains the pre-external-dispatch meaning for local reservations and +-- old cell-only rows; non-NULL values are canonical versioned JSON. +ALTER TABLE command_ledger ADD COLUMN external_binding text; diff --git a/migrations/sqlite/0008_external_command_binding.sql b/migrations/sqlite/0008_external_command_binding.sql new file mode 100644 index 000000000..4ae46667c --- /dev/null +++ b/migrations/sqlite/0008_external_command_binding.sql @@ -0,0 +1,4 @@ +-- Bind externally dispatched command reservations to their logical route. +-- NULL retains the pre-external-dispatch meaning for local reservations and +-- old cell-only rows; non-NULL values are canonical versioned JSON. +ALTER TABLE command_ledger ADD COLUMN external_binding TEXT; diff --git a/src/command_ledger/mod.rs b/src/command_ledger/mod.rs index 0c89ed847..5b069850d 100644 --- a/src/command_ledger/mod.rs +++ b/src/command_ledger/mod.rs @@ -32,7 +32,8 @@ pub(crate) use ids::{ pub(crate) use record::{CommandLedgerRecord, ReservationDecision}; pub(crate) use reservation::{ AttemptFence, CausalCommitBatch, CommandAttempt, CommandCompletion, CommandLookup, - CommandLookupScope, CommandReplay, CommandReservation, ReservationOutcome, + CommandLookupScope, CommandReplay, CommandReservation, ExternalCommandCompletion, + ExternalDispatchBinding, ReservationOutcome, }; pub(crate) use state::{CommandLedgerState, TerminalCommandState}; pub(crate) use traits::{ diff --git a/src/command_ledger/record.rs b/src/command_ledger/record.rs index 8ccc9629c..115df796b 100644 --- a/src/command_ledger/record.rs +++ b/src/command_ledger/record.rs @@ -11,7 +11,8 @@ use super::{ ids::COMMAND_REPLAY_VERSION, state::validate_projection_obligation_semantics, AttemptFence, AttemptToken, CanonicalInputHash, CausationId, CommandAttempt, CommandCompletion, CommandContractFingerprint, CommandLedgerError, CommandLedgerKey, CommandLedgerState, - CommandLookup, CommandLookupScope, CommandReplay, CommandReservation, ReservationOutcome, + CommandLookup, CommandLookupScope, CommandReplay, CommandReservation, + ExternalCommandCompletion, ExternalDispatchBinding, ReservationOutcome, }; /// Storage-neutral row representation shared by built-in adapters. @@ -25,6 +26,7 @@ pub(crate) struct CommandLedgerRecord { pub(crate) causation_id: CausationId, pub(crate) attempt_token: Option, pub(crate) attempt_number: u64, + pub(crate) external_binding: Option, pub(crate) lease_expires_at: Option, pub(crate) outcome_json: Option, #[allow(dead_code)] @@ -49,6 +51,7 @@ impl CommandLedgerRecord { causation_id: reservation.candidate_causation.clone(), attempt_token: Some(reservation.candidate_attempt.clone()), attempt_number: 1, + external_binding: reservation.external_binding.clone(), lease_expires_at: Some(checked_deadline(now, reservation.lease, "attempt lease")?), outcome_json: None, created_at: now, @@ -84,6 +87,11 @@ impl CommandLedgerRecord { principal_partition: self.key.principal_partition().to_string(), command_id: self.key.command_id().to_string(), command_name: self.command_name.clone(), + external_binding: self + .external_binding + .as_ref() + .map(ExternalDispatchBinding::to_storage) + .transpose()?, contract_fingerprint: self.contract_fingerprint.as_bytes().to_vec(), input_hash: self.input_hash.as_bytes().to_vec(), state: self.state.as_str().to_string(), @@ -135,6 +143,11 @@ impl CommandLedgerRecord { let record = Self { key, command_name: wire.command_name, + external_binding: wire + .external_binding + .as_deref() + .map(ExternalDispatchBinding::from_storage) + .transpose()?, contract_fingerprint: CommandContractFingerprint::try_from_slice( &wire.contract_fingerprint, )?, @@ -184,6 +197,7 @@ impl CommandLedgerRecord { causation_id: self.causation_id.clone(), attempt_token: token.clone(), attempt_number: self.attempt_number, + external_binding: self.external_binding.clone(), }) } @@ -198,6 +212,7 @@ impl CommandLedgerRecord { if self.command_name != reservation.command_name || self.contract_fingerprint != reservation.contract_fingerprint || self.input_hash != reservation.input_hash + || self.external_binding != reservation.external_binding { return Ok(ReservationDecision::Conflict); } @@ -385,6 +400,11 @@ impl CommandLedgerRecord { completion: &CommandCompletion, now: SystemTime, ) -> Result<(), CommandLedgerError> { + if self.external_binding.is_some() { + return Err(CommandLedgerError::Invalid( + "local causal completion cannot complete an externally bound reservation".into(), + )); + } completion.validate_direct_projection()?; self.validate_live_attempt(&completion.attempt.fence(), now)?; let retention_expires_at = match completion.retention_expires_at() { @@ -406,6 +426,44 @@ impl CommandLedgerRecord { Ok(()) } + pub(crate) fn complete_external( + &mut self, + completion: &ExternalCommandCompletion, + now: SystemTime, + ) -> Result<(), CommandLedgerError> { + if self.external_binding.as_ref() != Some(completion.binding()) { + return Err(CommandLedgerError::Invalid( + "external completion binding does not match the reserved route".into(), + )); + } + if completion.attempt().external_binding() != Some(completion.binding()) { + return Err(CommandLedgerError::Invalid( + "external completion attempt does not carry the reserved route".into(), + )); + } + // Check the complete attempt fence before any other mutable-row + // invariant. A late completion must report the generation race even + // when its retention deadline has also elapsed. + self.validate_live_attempt(&completion.attempt_fence(), now)?; + let retention_expires_at = match completion.retention_expires_at() { + Some(deadline) if deadline > now => deadline, + Some(_) => { + return Err(CommandLedgerError::Invalid( + "command retention deadline must remain live at commit".into(), + )); + } + None => checked_deadline(now, completion.retention(), "command retention")?, + }; + self.state = completion.state().into(); + self.attempt_token = None; + self.lease_expires_at = None; + self.outcome_json = Some(completion.replay_json().to_string()); + self.updated_at = now; + self.completed_at = Some(now); + self.retention_expires_at = retention_expires_at; + Ok(()) + } + pub(crate) fn replay(&self) -> Result { if !self.state.is_replayable() { return Err(CommandLedgerError::Corrupt(format!( @@ -615,6 +673,8 @@ struct DurableCellCommandRecordV1 { principal_partition: String, command_id: String, command_name: String, + #[serde(default)] + external_binding: Option, contract_fingerprint: Vec, input_hash: Vec, state: String, diff --git a/src/command_ledger/reservation.rs b/src/command_ledger/reservation.rs index a22d273a8..e22cc8544 100644 --- a/src/command_ledger/reservation.rs +++ b/src/command_ledger/reservation.rs @@ -3,6 +3,7 @@ use std::time::{Duration, SystemTime}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; +use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::projection_protocol::{ @@ -16,6 +17,97 @@ use super::{ CommandLedgerKey, CommandLedgerState, TerminalCommandState, SHA256_BYTES, }; +const EXTERNAL_BINDING_VERSION: u16 = 1; + +/// Immutable logical route ownership for a command dispatched outside the +/// repository that owns its ledger row. Transport addresses and retry leases +/// are intentionally not part of this identity. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ExternalDispatchBinding { + version: u16, + route_kind: String, + shard: String, +} + +impl ExternalDispatchBinding { + pub(crate) fn new( + route_kind: impl Into, + shard: impl Into, + ) -> Result { + let route_kind = route_kind.into(); + let shard = shard.into(); + validate_binding_part("external route kind", &route_kind)?; + validate_binding_part("external shard", &shard)?; + Ok(Self { + version: EXTERNAL_BINDING_VERSION, + route_kind, + shard, + }) + } + + pub(crate) fn route_kind(&self) -> &str { + &self.route_kind + } + + pub(crate) fn shard(&self) -> &str { + &self.shard + } + + /// Stable storage spelling. Parsing requires this exact canonical form so + /// equivalent-looking bindings cannot bypass the immutable row value. + pub(crate) fn to_storage(&self) -> Result { + serde_json::to_string(self).map_err(|error| { + CommandLedgerError::Invalid(format!( + "external dispatch binding could not be serialized: {error}" + )) + }) + } + + pub(crate) fn from_storage(value: &str) -> Result { + let binding: Self = serde_json::from_str(value).map_err(|error| { + CommandLedgerError::Corrupt(format!( + "stored external dispatch binding is invalid: {error}" + )) + })?; + if binding.version != EXTERNAL_BINDING_VERSION { + return Err(CommandLedgerError::Corrupt(format!( + "stored external dispatch binding version `{}` is unsupported", + binding.version + ))); + } + validate_binding_part("external route kind", &binding.route_kind) + .map_err(|error| CommandLedgerError::Corrupt(error.to_string()))?; + validate_binding_part("external shard", &binding.shard) + .map_err(|error| CommandLedgerError::Corrupt(error.to_string()))?; + let canonical = binding.to_storage().map_err(|error| { + CommandLedgerError::Corrupt(format!( + "stored external dispatch binding cannot be canonicalized: {error}" + )) + })?; + if canonical != value { + return Err(CommandLedgerError::Corrupt( + "stored external dispatch binding is not canonical JSON".into(), + )); + } + Ok(binding) + } +} + +fn validate_binding_part(label: &str, value: &str) -> Result<(), CommandLedgerError> { + if value.trim().is_empty() { + return Err(CommandLedgerError::Invalid(format!( + "{label} must not be empty" + ))); + } + if value.len() > 256 || value.chars().any(char::is_control) { + return Err(CommandLedgerError::Invalid(format!( + "{label} must be at most 256 bytes and contain no control characters" + ))); + } + Ok(()) +} + /// One validated reservation request. Fresh candidate IDs lose a race safely: /// only the inserted row keeps them; every retry reads the winner's causation. pub(crate) struct CommandReservation { @@ -27,6 +119,7 @@ pub(crate) struct CommandReservation { pub(super) retention: Duration, pub(super) candidate_causation: CausationId, pub(super) candidate_attempt: AttemptToken, + pub(super) external_binding: Option, } impl CommandReservation { @@ -60,9 +153,18 @@ impl CommandReservation { retention, candidate_causation: CausationId::new(), candidate_attempt: AttemptToken::new(), + external_binding: None, }) } + /// Mark this reservation as owned by an external logical route. The + /// binding is persisted with the reservation and cannot be changed by a + /// reclaim or completion. + pub(crate) fn with_external_binding(mut self, binding: ExternalDispatchBinding) -> Self { + self.external_binding = Some(binding); + self + } + pub(crate) fn key(&self) -> &CommandLedgerKey { &self.key } @@ -95,6 +197,10 @@ impl CommandReservation { &self.candidate_attempt } + pub(crate) fn external_binding(&self) -> Option<&ExternalDispatchBinding> { + self.external_binding.as_ref() + } + pub(crate) fn acquired_candidate_attempt(&self) -> CommandAttempt { CommandAttempt { key: self.key.clone(), @@ -103,6 +209,7 @@ impl CommandReservation { causation_id: self.candidate_causation.clone(), attempt_token: self.candidate_attempt.clone(), attempt_number: 1, + external_binding: self.external_binding.clone(), } } } @@ -126,6 +233,7 @@ pub(crate) struct CommandAttempt { pub(super) causation_id: CausationId, pub(super) attempt_token: AttemptToken, pub(super) attempt_number: u64, + pub(super) external_binding: Option, } impl CommandAttempt { @@ -137,6 +245,10 @@ impl CommandAttempt { &self.causation_id } + pub(crate) fn external_binding(&self) -> Option<&ExternalDispatchBinding> { + self.external_binding.as_ref() + } + #[cfg(test)] pub(crate) fn attempt_token(&self) -> &AttemptToken { &self.attempt_token @@ -189,6 +301,92 @@ impl CommandAttempt { ) } + /// Complete an externally dispatched command without appending local + /// events or outbox messages. The reservation binding is checked before a + /// replay payload is constructed; the ledger repeats the check at its + /// fenced write boundary. + pub(crate) fn complete_external( + self, + binding: ExternalDispatchBinding, + state: TerminalCommandState, + outcome: Value, + projection_obligations: Vec, + retention: Duration, + ) -> Result { + self.complete_external_with_replay_metadata( + binding, + state, + outcome, + projection_obligations, + None, + retention, + None, + ) + } + + /// Complete a remote command while retaining the exact sealed projection + /// metadata and absolute deadline returned by the remote command host. + /// Metadata is validated by the same versioned protocol checks used by a + /// local causal completion; it is never inferred from the active projector + /// registry. + pub(crate) fn complete_external_with_projection_metadata_until( + self, + binding: ExternalDispatchBinding, + state: TerminalCommandState, + outcome: Value, + projection_metadata: Vec, + retention: Duration, + retention_expires_at: SystemTime, + ) -> Result { + self.complete_external_with_replay_metadata( + binding, + state, + outcome, + Vec::new(), + Some(projection_metadata), + retention, + Some(retention_expires_at), + ) + } + + fn complete_external_with_replay_metadata( + self, + binding: ExternalDispatchBinding, + state: TerminalCommandState, + outcome: Value, + projection_obligations: Vec, + projection_metadata: Option>, + retention: Duration, + retention_expires_at: Option, + ) -> Result { + if state == TerminalCommandState::Atomic { + return Err(CommandLedgerError::Invalid( + "external command completion cannot be atomic".into(), + )); + } + if self.external_binding.as_ref() != Some(&binding) { + return Err(CommandLedgerError::Invalid( + "external command completion binding does not match its reservation".into(), + )); + } + let completion = self.complete_with_replay_metadata( + state, + outcome, + projection_obligations, + projection_metadata, + retention, + retention_expires_at, + )?; + Ok(ExternalCommandCompletion { + attempt: completion.attempt, + binding, + state: completion.state, + replay: completion.replay, + retention: completion.retention, + retention_expires_at: completion.retention_expires_at, + }) + } + /// Complete a command with exact already-canonical role-safe projection /// metadata. /// @@ -451,6 +649,48 @@ pub(crate) struct CommandCompletion { retention_expires_at: Option, } +/// Terminal receipt for a command whose domain effects were committed by a +/// different aggregate cell. It intentionally has no local domain batch +/// companion; storing the receipt never republishes the remote cell's events. +pub(crate) struct ExternalCommandCompletion { + pub(super) attempt: CommandAttempt, + pub(super) binding: ExternalDispatchBinding, + pub(super) state: TerminalCommandState, + pub(super) replay: String, + pub(super) retention: Duration, + retention_expires_at: Option, +} + +impl ExternalCommandCompletion { + pub(crate) fn attempt(&self) -> &CommandAttempt { + &self.attempt + } + + pub(crate) fn binding(&self) -> &ExternalDispatchBinding { + &self.binding + } + + pub(crate) fn state(&self) -> TerminalCommandState { + self.state + } + + pub(crate) fn replay_json(&self) -> &str { + &self.replay + } + + pub(crate) fn retention(&self) -> Duration { + self.retention + } + + pub(crate) fn retention_expires_at(&self) -> Option { + self.retention_expires_at + } + + pub(crate) fn attempt_fence(&self) -> AttemptFence { + self.attempt.fence() + } +} + impl CommandCompletion { pub(crate) fn attempt(&self) -> &CommandAttempt { &self.attempt diff --git a/src/command_ledger/tests.rs b/src/command_ledger/tests.rs index 8bbb11511..5fb03699c 100644 --- a/src/command_ledger/tests.rs +++ b/src/command_ledger/tests.rs @@ -249,6 +249,39 @@ fn reservation( ) } +fn external_binding(shard: &str) -> ExternalDispatchBinding { + ExternalDispatchBinding::new("aggregate-cell", shard).unwrap() +} + +fn external_reservation( + command_id: &str, + contract: u8, + input: u8, + shard: &str, +) -> Result { + Ok(reservation(command_id, contract, input)?.with_external_binding(external_binding(shard))) +} + +fn external_reservation_with_policy( + command_id: &str, + contract: u8, + input: u8, + shard: &str, + lease: Duration, + retention: Duration, +) -> Result { + Ok(reservation_for_partition_with_policy( + command_id, + "v1:sha256:principal", + "order.create", + contract, + input, + lease, + retention, + )? + .with_external_binding(external_binding(shard))) +} + trait CommandLedgerAdapterConformance: CommandLedgerStore + CausalTransactionalCommit @@ -281,6 +314,277 @@ where } } +async fn external_completion_is_ledger_only_and_replayable(repo: &R) +where + R: CommandLedgerAdapterConformance, +{ + let id = Uuid::now_v7().to_string(); + let binding = external_binding("orders-1"); + let request = external_reservation(&id, 101, 102, "orders-1").unwrap(); + let key = request.key().clone(); + let attempt = acquire(repo, request).await; + let completion = attempt + .complete_external( + binding, + TerminalCommandState::Succeeded, + serde_json::json!({"remote": true}), + Vec::new(), + Duration::from_secs(300), + ) + .unwrap(); + repo.complete_external_command(completion).await.unwrap(); + + let replay = match repo + .lookup_command(&key, CommandLookupScope::CommandName("order.create")) + .await + .unwrap() + { + CommandLookup::Replay(replay) => replay, + other => panic!("external completion should be replayable, got {other:?}"), + }; + assert_eq!(replay.state, CommandLedgerState::Succeeded); + assert_eq!(replay.outcome, serde_json::json!({"remote": true})); + assert!(repo + .get_stream(&StreamIdentity::new("remote-order", &id).unwrap()) + .await + .unwrap() + .is_none()); + let outbox = repo + .outbox_store() + .messages_by_status(OutboxMessageStatus::Pending, 1_000) + .await + .unwrap(); + assert!(outbox.iter().all(|message| message.id() != id)); + + assert!(matches!( + repo.reserve_command(external_reservation(&id, 101, 102, "orders-1").unwrap()) + .await + .unwrap(), + ReservationOutcome::Replay(_) + )); +} + +#[cfg(feature = "graphql")] +async fn external_completion_retains_the_sealed_projection_metadata(repo: &R) +where + R: CommandLedgerAdapterConformance, +{ + use std::time::UNIX_EPOCH; + + let fixture = include_bytes!("../../tests/fixtures/command-projection-metadata-v1.json"); + let fixture = fixture.strip_suffix(b"\n").unwrap_or(fixture); + let mut metadata = + crate::graphql::protocol::CommandProjectionMetadataV1::from_json(fixture).unwrap(); + let issued_at_unix_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + metadata.issued_at_unix_ms = issued_at_unix_ms; + metadata.expires_at_unix_ms = issued_at_unix_ms + 600_000; + let metadata_bytes = metadata.canonical_bytes().unwrap(); + let retention_expires_at = UNIX_EPOCH + .checked_add(Duration::from_millis(metadata.expires_at_unix_ms)) + .unwrap(); + + let id = Uuid::now_v7().to_string(); + let binding = external_binding("orders-sealed-metadata"); + let request = external_reservation(&id, 103, 104, "orders-sealed-metadata").unwrap(); + let key = request.key().clone(); + let attempt = acquire(repo, request).await; + let completion = attempt + .complete_external_with_projection_metadata_until( + binding, + TerminalCommandState::SucceededPendingProjection, + serde_json::json!({"remote": "sealed"}), + metadata_bytes.clone(), + Duration::from_secs(300), + retention_expires_at, + ) + .unwrap(); + repo.complete_external_command(completion).await.unwrap(); + + let replay = match repo + .lookup_command(&key, CommandLookupScope::CommandName("order.create")) + .await + .unwrap() + { + CommandLookup::Replay(replay) => replay, + other => panic!("sealed external completion should replay, got {other:?}"), + }; + assert_eq!(replay.state, CommandLedgerState::SucceededPendingProjection); + assert_eq!(replay.projection_obligations, Vec::new()); + assert_eq!( + replay.projection_metadata.as_deref(), + Some(metadata_bytes.as_slice()) + ); + assert_eq!( + crate::graphql::protocol::CommandProjectionMetadataV1::from_json( + replay.projection_metadata.as_deref().unwrap(), + ) + .unwrap(), + metadata + ); +} + +async fn external_binding_and_attempt_fences_are_strict(repo: &R) +where + R: CommandLedgerAdapterConformance, +{ + let id = Uuid::now_v7().to_string(); + let attempt = acquire( + repo, + external_reservation(&id, 111, 112, "orders-2").unwrap(), + ) + .await; + let wrong_binding = attempt.complete_external( + external_binding("orders-3"), + TerminalCommandState::Succeeded, + serde_json::json!({"wrong": true}), + Vec::new(), + Duration::from_secs(300), + ); + assert!(matches!(wrong_binding, Err(CommandLedgerError::Invalid(_)))); + assert!(matches!( + repo.reserve_command(external_reservation(&id, 111, 112, "orders-3").unwrap()) + .await + .unwrap(), + ReservationOutcome::Conflict + )); + + let first = acquire( + repo, + external_reservation(&Uuid::now_v7().to_string(), 113, 114, "orders-4").unwrap(), + ) + .await; + let first_fence = first.fence(); + let key = first.key().clone(); + repo.mark_retryable_unknown(first_fence).await.unwrap(); + let second = acquire( + repo, + external_reservation(key.command_id(), 113, 114, "orders-4").unwrap(), + ) + .await; + let stale = first + .complete_external( + external_binding("orders-4"), + TerminalCommandState::Succeeded, + serde_json::json!({"winner": false}), + Vec::new(), + Duration::from_secs(300), + ) + .unwrap(); + assert!(matches!( + repo.complete_external_command(stale).await, + Err(CommandLedgerError::AttemptFenced { .. }) + )); + let live = second + .complete_external( + external_binding("orders-4"), + TerminalCommandState::Succeeded, + serde_json::json!({"winner": true}), + Vec::new(), + Duration::from_secs(300), + ) + .unwrap(); + repo.complete_external_command(live).await.unwrap(); +} + +async fn external_and_local_reservations_cannot_mix(repo: &R) +where + R: CommandLedgerAdapterConformance, +{ + let external_id = Uuid::now_v7().to_string(); + let external_attempt = acquire( + repo, + external_reservation(&external_id, 121, 122, "orders-5").unwrap(), + ) + .await; + let local_completion = external_attempt + .complete( + TerminalCommandState::Succeeded, + serde_json::json!({"local": true}), + Duration::from_secs(300), + ) + .unwrap(); + let local_result = repo + .commit_causal_batch(CausalCommitBatch::new( + CommitBatch::empty(), + local_completion, + )) + .await; + assert!(matches!(local_result, Err(CommandLedgerError::Invalid(_)))); + + let local_id = Uuid::now_v7().to_string(); + let local_attempt = acquire(repo, reservation(&local_id, 123, 124).unwrap()).await; + let external_result = local_attempt.complete_external( + external_binding("orders-5"), + TerminalCommandState::Succeeded, + serde_json::json!({"external": true}), + Vec::new(), + Duration::from_secs(300), + ); + assert!(matches!( + external_result, + Err(CommandLedgerError::Invalid(_)) + )); + + assert!(matches!( + repo.reserve_command(reservation(&external_id, 121, 122).unwrap()) + .await + .unwrap(), + ReservationOutcome::Conflict + )); +} + +async fn external_reclaims_keep_causation_and_binding(repo: &R) +where + R: CommandLedgerAdapterConformance, +{ + let id = Uuid::now_v7().to_string(); + let first = acquire( + repo, + external_reservation_with_policy( + &id, + 131, + 132, + "orders-6", + Duration::from_millis(100), + Duration::from_secs(300), + ) + .unwrap(), + ) + .await; + let causation = first.causation_id().clone(); + tokio::time::sleep(Duration::from_millis(300)).await; + let second = acquire( + repo, + external_reservation_with_policy( + &id, + 131, + 132, + "orders-6", + Duration::from_secs(30), + Duration::from_secs(300), + ) + .unwrap(), + ) + .await; + assert_eq!(second.causation_id(), &causation); + assert_eq!(second.attempt_number(), 2); + let expected_binding = external_binding("orders-6"); + assert_eq!(second.external_binding(), Some(&expected_binding)); + let completion = second + .complete_external( + external_binding("orders-6"), + TerminalCommandState::Succeeded, + serde_json::json!({"reclaimed": true}), + Vec::new(), + Duration::from_secs(300), + ) + .unwrap(); + repo.complete_external_command(completion).await.unwrap(); +} + async fn same_input_retries_and_identity_conflicts_conform(repo: &R) where R: CommandLedgerAdapterConformance, @@ -945,6 +1249,12 @@ where stale_fence_rolls_back_every_commit_participant(repo).await; compacted_expiry_is_a_permanent_tombstone(repo).await; expired_modeled_metadata_deadline_cannot_commit(repo).await; + external_completion_is_ledger_only_and_replayable(repo).await; + #[cfg(feature = "graphql")] + external_completion_retains_the_sealed_projection_metadata(repo).await; + external_binding_and_attempt_fences_are_strict(repo).await; + external_and_local_reservations_cannot_mix(repo).await; + external_reclaims_keep_causation_and_binding(repo).await; } #[test] @@ -1354,6 +1664,88 @@ fn modeled_projection_metadata_bounds_fail_before_completion() { )); } +#[test] +fn cell_ledger_external_binding_round_trips_and_legacy_rows_stay_unbound() { + let id = Uuid::now_v7().to_string(); + let request = external_reservation(&id, 141, 142, "orders-cell").unwrap(); + let started = SystemTime::UNIX_EPOCH + Duration::from_secs(100); + let row = CommandLedgerRecord::initial(&request, started).unwrap(); + let encoded = row.durable_cell_json().unwrap(); + let restored = CommandLedgerRecord::from_durable_cell_json(&encoded).unwrap(); + assert_eq!(restored.external_binding, row.external_binding); + assert_eq!(restored.durable_cell_key(), row.durable_cell_key()); + + // Cell rows written before external dispatch existed omit the optional + // field. They remain readable, but cannot be treated as externally bound + // evidence after a process restart. + let mut legacy: serde_json::Value = serde_json::from_str(&encoded).unwrap(); + legacy.as_object_mut().unwrap().remove("external_binding"); + let legacy = serde_json::to_string(&legacy).unwrap(); + let restored_legacy = CommandLedgerRecord::from_durable_cell_json(&legacy).unwrap(); + assert!(restored_legacy.external_binding.is_none()); + + let completed_id = Uuid::now_v7().to_string(); + let completed_request = + external_reservation(&completed_id, 143, 144, "orders-cell-completed").unwrap(); + let mut completed = CommandLedgerRecord::initial(&completed_request, started).unwrap(); + let metadata = br#"{"sealed":"projection"}"#.to_vec(); + let completion = completed + .acquired_attempt() + .unwrap() + .complete_external_with_projection_metadata_until( + external_binding("orders-cell-completed"), + TerminalCommandState::SucceededPendingProjection, + serde_json::json!({"remote": true}), + metadata.clone(), + Duration::from_secs(300), + started + Duration::from_secs(301), + ) + .unwrap(); + completed + .complete_external(&completion, started + Duration::from_secs(1)) + .unwrap(); + let restored_completed = + CommandLedgerRecord::from_durable_cell_json(&completed.durable_cell_json().unwrap()) + .unwrap(); + let replay = restored_completed.replay().unwrap(); + assert_eq!(replay.projection_metadata, Some(metadata)); + assert_eq!(replay.outcome, serde_json::json!({"remote": true})); +} + +#[test] +fn external_dispatch_binding_storage_is_versioned_and_canonical() { + let binding = ExternalDispatchBinding::new("aggregate-cell", "orders-1").unwrap(); + let encoded = binding.to_storage().unwrap(); + assert_eq!( + ExternalDispatchBinding::from_storage(&encoded).unwrap(), + binding + ); + assert!(matches!( + ExternalDispatchBinding::from_storage( + r#"{"version":1,"route_kind":"aggregate-cell","shard":"orders-1","extra":true}"#, + ), + Err(CommandLedgerError::Corrupt(_)) + )); + assert!(matches!( + ExternalDispatchBinding::from_storage( + r#"{"version":2,"route_kind":"aggregate-cell","shard":"orders-1"}"#, + ), + Err(CommandLedgerError::Corrupt(_)) + )); + assert!(matches!( + ExternalDispatchBinding::new("", "orders-1"), + Err(CommandLedgerError::Invalid(_)) + )); + assert!(matches!( + ExternalDispatchBinding::new("aggregate-cell", "orders\n1"), + Err(CommandLedgerError::Invalid(_)) + )); + assert!(matches!( + ExternalDispatchBinding::new("é".repeat(129), "orders-1"), + Err(CommandLedgerError::Invalid(_)) + )); +} + #[test] fn causal_batch_applies_the_authoritative_stamp_at_the_final_boundary() { use crate::outbox::OutboxMessage; @@ -1503,6 +1895,30 @@ async fn sqlite_terminal_replay_survives_pool_drop_and_reopen() { .await .unwrap(); + let external_id = Uuid::now_v7().to_string(); + let external_request = + external_reservation(&external_id, 83, 84, "orders-restart-external").unwrap(); + let external_key = external_request.key().clone(); + let external_binding = external_binding("orders-restart-external"); + let external_attempt = acquire(&repo, external_request).await; + let external_completion = external_attempt + .complete_external( + external_binding, + TerminalCommandState::Succeeded, + serde_json::json!({"remote": "restart"}), + Vec::new(), + Duration::from_secs(300), + ) + .unwrap(); + repo.complete_external_command(external_completion) + .await + .unwrap(); + assert!(repo + .get_stream(&StreamIdentity::new("remote-order", &external_id).unwrap()) + .await + .unwrap() + .is_none()); + repo.pool().close().await; drop(repo); @@ -1545,6 +1961,30 @@ async fn sqlite_terminal_replay_survives_pool_drop_and_reopen() { Some(expected_causation.as_str()) ); + let external_replay = match reopened + .lookup_command( + &external_key, + CommandLookupScope::CommandName("order.create"), + ) + .await + .unwrap() + { + CommandLookup::Replay(replay) => replay, + other => panic!("reopened external ledger row should replay, got {other:?}"), + }; + assert_eq!(external_replay.state, CommandLedgerState::Succeeded); + assert_eq!( + external_replay.outcome, + serde_json::json!({"remote": "restart"}) + ); + assert!(matches!( + reopened + .reserve_command(reservation(&external_id, 83, 84).unwrap()) + .await + .unwrap(), + ReservationOutcome::Conflict + )); + reopened.pool().close().await; drop(reopened); } diff --git a/src/command_ledger/traits.rs b/src/command_ledger/traits.rs index 76724d48a..0c82dfd3f 100644 --- a/src/command_ledger/traits.rs +++ b/src/command_ledger/traits.rs @@ -5,7 +5,8 @@ use crate::repository::{RepositoryError, StreamIdentity}; use super::{ AttemptFence, CausalCommitBatch, CausalStorageIdentity, CommandLedgerError, CommandLedgerKey, - CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, + CommandLookup, CommandLookupScope, CommandReservation, ExternalCommandCompletion, + ReservationOutcome, }; /// Read capability used by the causal workspace. Unlike ordinary @@ -51,6 +52,14 @@ pub(crate) trait CommandLedgerStore: Send + Sync { attempt: AttemptFence, ) -> impl Future> + Send + '_; + /// Record a terminal receipt for a remote aggregate-cell command. This + /// updates only the ledger row and is never a substitute for a local + /// domain commit. + fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> impl Future> + Send + '_; + #[allow(dead_code)] fn compact_expired_commands( &self, diff --git a/src/in_memory_repo/repository.rs b/src/in_memory_repo/repository.rs index 69f90d742..55db22277 100644 --- a/src/in_memory_repo/repository.rs +++ b/src/in_memory_repo/repository.rs @@ -14,7 +14,7 @@ use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, CommandLedgerKey, CommandLedgerRecord, CommandLedgerStore, CommandLookup, CommandLookupScope, - CommandReservation, ReservationDecision, ReservationOutcome, + CommandReservation, ExternalCommandCompletion, ReservationDecision, ReservationOutcome, }; use crate::entity::{Entity, EventRecord}; use crate::outbox::OutboxMessage; @@ -384,6 +384,13 @@ impl InMemoryRepository { .ok_or_else(|| CommandLedgerError::AttemptFenced { command_id: completion.attempt().key().command_id().to_string(), })?; + if completion.attempt().external_binding().is_some() { + return Err(CommandLedgerError::Invalid( + "local causal completion cannot complete an externally bound reservation" + .into(), + ) + .into()); + } record.validate_live_attempt(&completion.attempt_fence(), crate::time::now())?; } @@ -692,6 +699,24 @@ impl CommandLedgerStore for InMemoryRepository { } } + fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> impl Future> + Send + '_ { + async move { + let mut ledger = self + .command_ledger + .write() + .map_err(|_| RepositoryError::LockPoisoned("external command completion"))?; + let record = ledger.get_mut(completion.attempt().key()).ok_or_else(|| { + CommandLedgerError::AttemptFenced { + command_id: completion.attempt().key().command_id().to_string(), + } + })?; + record.complete_external(&completion, crate::time::now()) + } + } + fn compact_expired_commands( &self, limit: usize, diff --git a/src/microsvc/cell_host/sql_store.rs b/src/microsvc/cell_host/sql_store.rs index 11ac0a053..b39e00efd 100644 --- a/src/microsvc/cell_host/sql_store.rs +++ b/src/microsvc/cell_host/sql_store.rs @@ -9,7 +9,7 @@ use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, CommandLedgerKey, CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, - ReservationOutcome, + ExternalCommandCompletion, ReservationOutcome, }; use crate::entity::Entity; use crate::microsvc::HasOutboxStore; @@ -235,6 +235,14 @@ impl CommandLedgerStore for CellSqlRepository { self.connection .transaction(|executor| finish_sql(ledger::mark_retryable(executor, &attempt))) } + + async fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> Result<(), CommandLedgerError> { + self.connection + .transaction(|executor| finish_sql(ledger::complete_external(executor, &completion))) + } async fn compact_expired_commands(&self, limit: usize) -> Result { self.connection .transaction(|executor| finish_sql(ledger::compact(executor, limit))) diff --git a/src/microsvc/cell_host/store.rs b/src/microsvc/cell_host/store.rs index af4b3b199..23d263941 100644 --- a/src/microsvc/cell_host/store.rs +++ b/src/microsvc/cell_host/store.rs @@ -14,7 +14,8 @@ use super::sql_store::CellSqlRepository; use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandLedgerError, CommandLedgerKey, - CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, + CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ExternalCommandCompletion, ReservationOutcome, }; use crate::entity::Entity; #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] @@ -542,6 +543,13 @@ impl CommandLedgerStore for CellStreamStore { CommandLedgerStore::mark_retryable_unknown(&self.inner, attempt) } + fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> impl Future> + Send + '_ { + CommandLedgerStore::complete_external_command(&self.inner, completion) + } + fn compact_expired_commands( &self, limit: usize, diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index dc2671b9f..e9450f889 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -16,7 +16,8 @@ use crate::command::{CommandInputType, CommandOutputType, CommandTypeDef, Comman use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalTransactionalCommit, CommandLedgerError, CommandLedgerKey, CommandLedgerState, - CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, + CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ExternalCommandCompletion, ReservationOutcome, }; #[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; @@ -1017,6 +1018,13 @@ impl CommandLedgerStore for AmbiguousCommitRepository { CommandLedgerStore::mark_retryable_unknown(&self.inner, attempt) } + fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> impl Future> + Send + '_ { + CommandLedgerStore::complete_external_command(&self.inner, completion) + } + fn compact_expired_commands( &self, limit: usize, diff --git a/src/postgres_repo/mod.rs b/src/postgres_repo/mod.rs index 041ba1f91..f58cab009 100644 --- a/src/postgres_repo/mod.rs +++ b/src/postgres_repo/mod.rs @@ -57,7 +57,7 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { const CONFLICT_REREAD_IN_TX: bool = false; const NOW: &'static str = "now()"; const COMMAND_LEDGER_SELECT: &'static str = "command_name, command_contract_hash, \ - input_hash, state, causation_id, attempt_token, attempt_number, \ + input_hash, state, causation_id, attempt_token, attempt_number, external_binding, \ EXTRACT(EPOCH FROM lease_expires_at)::double precision AS lease_expires_at, \ outcome::text AS outcome, \ EXTRACT(EPOCH FROM created_at)::double precision AS created_at, \ diff --git a/src/queued_repo/repository.rs b/src/queued_repo/repository.rs index d4138054b..58e4125dc 100644 --- a/src/queued_repo/repository.rs +++ b/src/queued_repo/repository.rs @@ -9,7 +9,8 @@ use std::sync::Arc; use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandLedgerError, CommandLedgerKey, - CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, ReservationOutcome, + CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ExternalCommandCompletion, ReservationOutcome, }; use crate::entity::Entity; use crate::lock::{InMemoryLockManager, Lock, LockManager}; @@ -243,6 +244,13 @@ where self.inner.mark_retryable_unknown(attempt) } + fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> impl Future> + Send + '_ { + self.inner.complete_external_command(completion) + } + fn compact_expired_commands( &self, limit: usize, diff --git a/src/repository/migrations.rs b/src/repository/migrations.rs index 8a73455ef..5d0a10b1b 100644 --- a/src/repository/migrations.rs +++ b/src/repository/migrations.rs @@ -16,5 +16,5 @@ include!(concat!(env!("OUT_DIR"), "/migration_inventory.rs")); pub(crate) fn cell_migrations() -> impl Iterator { SQLITE_MIGRATIONS .iter() - .filter(|migration| matches!(migration.version, 1 | 2 | 4)) + .filter(|migration| matches!(migration.version, 1 | 2 | 4 | 8)) } diff --git a/src/repository/sql/ledger.rs b/src/repository/sql/ledger.rs index 2e1ed41bd..1b494f3bd 100644 --- a/src/repository/sql/ledger.rs +++ b/src/repository/sql/ledger.rs @@ -5,7 +5,8 @@ use crate::command_ledger::{ AttemptFence, AttemptToken, CanonicalInputHash, CausationId, CommandCompletion, CommandContractFingerprint, CommandId, CommandLedgerError, CommandLedgerKey, CommandLedgerRecord, CommandLedgerState, CommandLookup, CommandLookupScope, CommandReservation, - PrincipalPartitionId, ReservationDecision, ReservationOutcome, + ExternalCommandCompletion, ExternalDispatchBinding, PrincipalPartitionId, ReservationDecision, + ReservationOutcome, }; use std::time::SystemTime; @@ -29,6 +30,11 @@ fn record_from_row( let record = CommandLedgerRecord { key, command_name: row.text("command_name")?, + external_binding: row + .optional_text("external_binding")? + .as_deref() + .map(ExternalDispatchBinding::from_storage) + .transpose()?, contract_fingerprint: CommandContractFingerprint::try_from_slice( &row.bytes("command_contract_hash")?, ) @@ -126,6 +132,11 @@ pub(crate) async fn preflight( command_id: fence.key().command_id().to_string(), } })?; + if completion.attempt().external_binding().is_some() { + return Err(CommandLedgerError::Invalid( + "local causal completion cannot complete an externally bound reservation".into(), + )); + } let now = now(executor).await?; record.validate_live_attempt(&fence, now) } @@ -137,7 +148,7 @@ pub(crate) async fn insert_reservation( let mut builder = Statement::new( "INSERT INTO command_ledger (service_id, principal_partition, command_id, \ command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, \ - attempt_number, lease_expires_at, outcome, created_at, updated_at, completed_at, \ + attempt_number, external_binding, lease_expires_at, outcome, created_at, updated_at, completed_at, \ retention_expires_at, compacted_at) VALUES (", ); builder.push_bind(reservation.key().service_id()); @@ -160,6 +171,15 @@ pub(crate) async fn insert_reservation( builder.push(", "); builder.push_bind(1_i64); builder.push(", "); + let external_binding = reservation + .external_binding() + .map(ExternalDispatchBinding::to_storage) + .transpose()?; + match external_binding.as_deref() { + Some(binding) => builder.push_bind(binding), + None => builder.push("NULL"), + } + builder.push(", "); builder.part(SqlPart::LedgerDeadline(reservation.lease())); builder.push(", NULL, "); builder.part(SqlPart::LedgerNow); @@ -265,6 +285,7 @@ pub(crate) async fn complete( builder.push_bind(fence.contract_fingerprint_bytes().as_slice()); builder.push(" AND input_hash = "); builder.push_bind(fence.input_hash_bytes().as_slice()); + builder.push(" AND external_binding IS NULL"); builder.push(" AND state = 'in_progress' AND causation_id = "); builder.push_bind(fence.causation_id().as_str()); builder.push(" AND attempt_token = "); @@ -286,6 +307,60 @@ pub(crate) async fn complete( Ok(()) } +pub(crate) async fn complete_external( + executor: &mut E, + completion: &ExternalCommandCompletion, +) -> Result<(), CommandLedgerError> { + let fence = completion.attempt_fence(); + let attempt_number = signed(fence.attempt_number(), "command ledger attempt number")?; + let terminal_state = CommandLedgerState::from(completion.state()).as_str(); + let retention_expires_at = completion.retention_expires_at(); + let binding = completion.binding().to_storage()?; + let mut builder = Statement::new("UPDATE command_ledger SET state = "); + builder.push_bind(terminal_state); + builder.push(", attempt_token = NULL, lease_expires_at = NULL, outcome = "); + builder.part(SqlPart::LedgerJson(completion.replay_json().into())); + builder.push(", updated_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(", completed_at = "); + builder.part(SqlPart::LedgerNow); + builder.push(", retention_expires_at = "); + match retention_expires_at.as_ref() { + Some(deadline) => builder.push_bind(SqlBind::Timestamp(*deadline)), + None => builder.part(SqlPart::LedgerDeadline(completion.retention())), + } + builder.push(", compacted_at = NULL WHERE service_id = "); + builder.push_bind(fence.key().service_id()); + builder.push(" AND principal_partition = "); + builder.push_bind(fence.key().principal_partition()); + builder.push(" AND command_id = "); + builder.push_bind(fence.key().command_id()); + builder.push(" AND command_contract_hash = "); + builder.push_bind(fence.contract_fingerprint_bytes().as_slice()); + builder.push(" AND input_hash = "); + builder.push_bind(fence.input_hash_bytes().as_slice()); + builder.push(" AND external_binding = "); + builder.push_bind(binding.as_str()); + builder.push(" AND state = 'in_progress' AND causation_id = "); + builder.push_bind(fence.causation_id().as_str()); + builder.push(" AND attempt_token = "); + builder.push_bind(fence.attempt_token().as_str()); + builder.push(" AND attempt_number = "); + builder.push_bind(attempt_number); + builder.push(" AND lease_expires_at > "); + builder.part(SqlPart::LedgerNow); + if let Some(deadline) = retention_expires_at.as_ref() { + builder.push(" AND "); + builder.part(SqlPart::LedgerDeadlineIsLive(*deadline)); + } + if executor.execute(builder).await? != 1 { + return Err(CommandLedgerError::AttemptFenced { + command_id: fence.key().command_id().to_string(), + }); + } + Ok(()) +} + pub(crate) async fn reserve( executor: &mut impl SqlExecutor, reservation: &CommandReservation, diff --git a/src/repository/sqlite_codec.rs b/src/repository/sqlite_codec.rs index 34dd1257d..ed40fedd7 100644 --- a/src/repository/sqlite_codec.rs +++ b/src/repository/sqlite_codec.rs @@ -74,4 +74,4 @@ mod tests { assert!(encode(UNIX_EPOCH - Duration::from_secs(1)).is_err()); } } -pub(crate) const COMMAND_LEDGER_SELECT: &str = "command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, attempt_number, lease_expires_at, outcome, created_at, updated_at, completed_at, retention_expires_at, compacted_at"; +pub(crate) const COMMAND_LEDGER_SELECT: &str = "command_name, command_contract_hash, input_hash, state, causation_id, attempt_token, attempt_number, external_binding, lease_expires_at, outcome, created_at, updated_at, completed_at, retention_expires_at, compacted_at"; diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 3bb2ce531..71eeac174 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -47,7 +47,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); assert_eq!( descriptions, vec![ @@ -57,7 +57,8 @@ mod tests { "command ledger atomic state", "projection source snapshots", "gateway dependency versions", - "projection program identity" + "projection program identity", + "external command binding" ] ); assert_eq!( @@ -91,6 +92,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0007_projection_program_identity.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0008_external_command_binding.sql" + )), ] ); } @@ -110,7 +115,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); assert_eq!( descriptions, vec![ @@ -120,7 +125,8 @@ mod tests { "command ledger atomic state", "projection source snapshots", "gateway dependency versions", - "projection program identity" + "projection program identity", + "external command binding" ] ); assert_eq!( @@ -154,6 +160,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0007_projection_program_identity.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0008_external_command_binding.sql" + )), ] ); } diff --git a/src/sqlx_repo/repo/commit.rs b/src/sqlx_repo/repo/commit.rs index c42cc7736..4e7fd6c97 100644 --- a/src/sqlx_repo/repo/commit.rs +++ b/src/sqlx_repo/repo/commit.rs @@ -318,6 +318,24 @@ where .await } + async fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> Result<(), CommandLedgerError> { + let mut tx = self.pool.begin().await.map_err(|error| { + repository_storage_error::("begin external command completion", error) + })?; + crate::repository::sql::ledger::complete_external( + &mut executor::ConnectionExecutor::(&mut *tx), + &completion, + ) + .await?; + tx.commit().await.map_err(|error| { + repository_storage_error::("commit external command completion", error) + })?; + Ok(()) + } + async fn compact_expired_commands(&self, limit: usize) -> Result { if limit == 0 { return Ok(0); diff --git a/src/sqlx_repo/repo/mod.rs b/src/sqlx_repo/repo/mod.rs index 194dd7556..9b3047266 100644 --- a/src/sqlx_repo/repo/mod.rs +++ b/src/sqlx_repo/repo/mod.rs @@ -30,7 +30,7 @@ use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, CommandLedgerKey, CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, - ReservationOutcome, + ExternalCommandCompletion, ReservationOutcome, }; use crate::entity::{Entity, EventRecord}; use crate::outbox::{OutboxMessage, OutboxMessageStatus}; diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index db25e06b8..f5dd02de3 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 7); + assert_eq!(latest_version, 8); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 2a98aff4b..8f62df91f 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 7); + assert_eq!(latest_version, 8); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From 34aa3881bf2551801b70895fe22b9dcfc41a9c92 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 9 Sep 2026 23:53:31 -0500 Subject: [PATCH 082/484] feat: persist external cell command completions --- README.md | 11 + src/command_dispatch/host.rs | 36 ++- src/command_ledger/reservation.rs | 8 + src/microsvc/cell_host/causal.rs | 30 ++- src/microsvc/cell_host/command.rs | 178 +++++++------ src/microsvc/cell_host/mod.rs | 4 +- src/microsvc/mod.rs | 2 + src/microsvc/service/causal.rs | 149 +++++++++++ src/microsvc/service/mod.rs | 2 +- src/microsvc/service/routes.rs | 288 ++++++++++++++++++++- src/microsvc/service/runtime.rs | 83 +++++- src/microsvc/service/tests.rs | 75 ++++++ tests/causal_wait_path/main.rs | 411 +++++++++++++++++++++++++++++- tests/celld/worker/src/lib.rs | 20 +- 14 files changed, 1195 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 9ea07ee88..3840938e1 100644 --- a/README.md +++ b/README.md @@ -752,6 +752,17 @@ without a gateway binding remain explicit unknowns until a matching gateway reservation and trusted completion protocol can be established; they are never retrofitted into a different route or silently replayed. +The celld command host reserves that gateway intent before making the cell +request. The reservation's causation ID and logical route binding must be +echoed by the trusted cell receipt; a changed command ID, input, causation, or +route is rejected before it can complete the gateway row. A terminal cell +receipt is durably recorded in the gateway ledger before the response is +returned. Status checks current authorization and re-evaluates the durable +receipt's projection evidence, so an in-memory completed-status cache is never +the source of truth. An ambiguous transport result remains retryable against +the same reservation and cell; it does not invoke the local domain handler or +re-publish the cell's events and outbox. + In v5, `OutboxStore::complete` and `complete_many` remove delivered rows instead of retaining `Published` records. Repeating settlement of a removed row returns `NotFound`; stale claims on existing rows still return `InvalidState`. diff --git a/src/command_dispatch/host.rs b/src/command_dispatch/host.rs index 7e44708c8..c7f14b3c5 100644 --- a/src/command_dispatch/host.rs +++ b/src/command_dispatch/host.rs @@ -9,8 +9,8 @@ use std::time::Duration; use crate::graphql::identity::VerifiedPrincipal; use crate::graphql::protocol::ProtocolResponseAccumulator; use crate::microsvc::cell_host::{ - InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, - CELL_SERVICE_ID_HEADER, + InternalHttpSecret, CELL_CAUSATION_ID_HEADER, CELL_INTERNAL_SECRET_HEADER, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, }; use crate::microsvc::{ CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult, Service, Session, @@ -340,7 +340,7 @@ impl HttpCommandHost { input: Value, session: &Session, ) -> Result<(u16, Value), CausalDispatchError> { - self.post_wait_path_inner(command, command_id, input, session, None) + self.post_wait_path_inner(command, command_id, input, session, None, None) .await } @@ -355,6 +355,30 @@ impl HttpCommandHost { session: &Session, service_id: &str, principal_partition: &str, + ) -> Result<(u16, Value), CausalDispatchError> { + self.post_cell_wait_path_with_causation( + command, + command_id, + input, + session, + service_id, + principal_partition, + None, + ) + .await + } + + /// POST a cell wait-path command while carrying the gateway's durable + /// causation through the authenticated internal boundary. + pub async fn post_cell_wait_path_with_causation( + &self, + command: &str, + command_id: &str, + input: Value, + session: &Session, + service_id: &str, + principal_partition: &str, + causation_id: Option<&str>, ) -> Result<(u16, Value), CausalDispatchError> { let first = self .post_wait_path_inner( @@ -363,6 +387,7 @@ impl HttpCommandHost { input.clone(), session, Some((service_id, principal_partition)), + causation_id, ) .await; if !matches!(&first, Ok((status, _)) if *status >= 500) { @@ -380,6 +405,7 @@ impl HttpCommandHost { input, session, Some((service_id, principal_partition)), + causation_id, ) .await } @@ -391,6 +417,7 @@ impl HttpCommandHost { input: Value, session: &Session, cell_identity: Option<(&str, &str)>, + causation_id: Option<&str>, ) -> Result<(u16, Value), CausalDispatchError> { let mut request = self.request_json( command, @@ -414,6 +441,9 @@ impl HttpCommandHost { request = request .header(CELL_SERVICE_ID_HEADER, service_id) .header(CELL_PRINCIPAL_PARTITION_HEADER, principal_partition); + if let Some(causation_id) = causation_id { + request = request.header(CELL_CAUSATION_ID_HEADER, causation_id); + } } let response = request.send().await.map_err(|err| { CausalDispatchError::Internal(format!("wait-path HTTP failed: {err}")) diff --git a/src/command_ledger/reservation.rs b/src/command_ledger/reservation.rs index e22cc8544..53afef713 100644 --- a/src/command_ledger/reservation.rs +++ b/src/command_ledger/reservation.rs @@ -165,6 +165,14 @@ impl CommandReservation { self } + /// Reuse the causation allocated by a trusted external gateway. The + /// command ID and canonical input still fence the cell row; this field + /// makes the remote receipt prove the same logical command attempt. + pub(crate) fn with_causation_id(mut self, causation_id: CausationId) -> Self { + self.candidate_causation = causation_id; + self + } + pub(crate) fn key(&self) -> &CommandLedgerKey { &self.key } diff --git a/src/microsvc/cell_host/causal.rs b/src/microsvc/cell_host/causal.rs index df11ae6f7..532f85b10 100644 --- a/src/microsvc/cell_host/causal.rs +++ b/src/microsvc/cell_host/causal.rs @@ -40,6 +40,11 @@ pub const CELL_SERVICE_ID_HEADER: &str = "x-distributed-service-id"; /// This is an opaque server-derived value, never a public command argument. pub const CELL_PRINCIPAL_PARTITION_HEADER: &str = "x-distributed-principal-partition"; +/// Internal wait-path header carrying the gateway's durable causation ID. +/// The shared internal secret authenticates this value; public clients cannot +/// select it. +pub const CELL_CAUSATION_ID_HEADER: &str = "x-distributed-causation-id"; + /// Trusted command-ledger identity supplied by the cell's authenticated host. /// /// `principal_partition` is the opaque, server-derived partition produced by @@ -47,6 +52,7 @@ pub const CELL_PRINCIPAL_PARTITION_HEADER: &str = "x-distributed-principal-parti #[derive(Clone, Debug)] pub struct CellCommandIdentity { key: CommandLedgerKey, + causation_id: Option, } impl CellCommandIdentity { @@ -60,7 +66,10 @@ impl CellCommandIdentity { PrincipalPartitionId::new(principal_partition).map_err(internal_ledger_error)?; let key = CommandLedgerKey::new(service_id, principal_partition, command_id) .map_err(internal_ledger_error)?; - Ok(Self { key }) + Ok(Self { + key, + causation_id: None, + }) } pub fn service_id(&self) -> &str { @@ -71,6 +80,25 @@ impl CellCommandIdentity { self.key.command_id() } + /// Bind a trusted gateway causation ID to the cell reservation. This is + /// used only across the authenticated internal wait-path boundary; a cell + /// identity without it retains the standalone cell-command behavior. + pub fn with_causation_id( + mut self, + causation_id: impl AsRef, + ) -> Result { + let causation_id = crate::command_ledger::CausationId::parse_stored( + causation_id.as_ref().to_string(), + ) + .map_err(internal_ledger_error)?; + self.causation_id = Some(causation_id); + Ok(self) + } + + pub(crate) fn causation_id(&self) -> Option<&crate::command_ledger::CausationId> { + self.causation_id.as_ref() + } + pub(crate) fn key(&self) -> &CommandLedgerKey { &self.key } diff --git a/src/microsvc/cell_host/command.rs b/src/microsvc/cell_host/command.rs index da7e59cd5..9c7b44df3 100644 --- a/src/microsvc/cell_host/command.rs +++ b/src/microsvc/cell_host/command.rs @@ -4,9 +4,7 @@ //! aggregate Worker owns outbox delivery through celld Queue; this host only //! invokes commands and seals the returned projection evidence. -use std::collections::{HashMap, VecDeque}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::sync::Arc; use async_trait::async_trait; use serde_json::Value; @@ -19,57 +17,10 @@ use crate::command_dispatch::{ use crate::graphql::identity::VerifiedPrincipal; use crate::graphql::protocol::ProtocolResponseAccumulator; use crate::microsvc::{ - CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult, Service, Session, + CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult, ExternalCausalReservation, + Service, Session, }; - -const COMPLETED_STATUS_CACHE_LIMIT: usize = 4_096; -const COMPLETED_STATUS_CACHE_TTL: Duration = Duration::from_secs(15 * 60); - -type CompletedStatusKey = (String, String); - -#[derive(Default)] -struct CompletedStatusCache { - entries: HashMap, - order: VecDeque, -} - -impl CompletedStatusCache { - fn insert(&mut self, key: CompletedStatusKey, status: CausalCommandPublicStatus) { - self.purge_expired(); - if self.entries.contains_key(&key) { - self.order.retain(|existing| existing != &key); - self.order.push_back(key.clone()); - self.entries.insert(key, (Instant::now(), status)); - return; - } - while self.entries.len() >= COMPLETED_STATUS_CACHE_LIMIT { - let Some(evicted) = self.order.pop_front() else { - break; - }; - self.entries.remove(&evicted); - } - self.order.push_back(key.clone()); - self.entries.insert(key, (Instant::now(), status)); - } - - fn get(&mut self, key: &CompletedStatusKey) -> Option { - self.purge_expired(); - self.entries.get(key).map(|(_, status)| status.clone()) - } - - fn purge_expired(&mut self) { - let now = Instant::now(); - while self.order.front().is_some_and(|key| { - self.entries.get(key).is_none_or(|(inserted, _)| { - now.duration_since(*inserted) >= COMPLETED_STATUS_CACHE_TTL - }) - }) { - if let Some(expired) = self.order.pop_front() { - self.entries.remove(&expired); - } - } - } -} +use crate::command_ledger::ExternalDispatchBinding; /// One aggregate's cell wait-path: command names, URL kind, shard id, payload. #[derive(Clone, Copy)] @@ -102,7 +53,6 @@ pub struct CelldCommandHost { http: HttpCommandHost, local: LocalCommandHost, routes: Vec, - completed: Arc>, } impl CelldCommandHost { @@ -117,7 +67,6 @@ impl CelldCommandHost { http, local: LocalCommandHost::new(service), routes: Vec::new(), - completed: Arc::new(Mutex::new(CompletedStatusCache::default())), }) } @@ -140,12 +89,6 @@ impl CelldCommandHost { }) } - fn remember_completed(&self, key: (String, String), status: CausalCommandPublicStatus) { - let Ok(mut completed) = self.completed.lock() else { - return; - }; - completed.insert(key, status); - } } fn remote_dispatch_error(status: u16, body: &Value) -> CausalDispatchError { @@ -209,34 +152,110 @@ impl CommandHost for CelldCommandHost { })?; let service_id = self.service_id()?.to_string(); let principal_partition = principal.partition_for_service(&service_id); - let http = self.http.retarget_segments(&[route.kind, &shard])?; - let (status, body) = http - .post_cell_wait_path( + let binding = ExternalDispatchBinding::new(route.kind, &shard) + .map_err(|error| CausalDispatchError::BadRequest(error.to_string()))?; + let reservation = self + .local + .service() + .reserve_external_causal( + command, + command_id, + input.clone(), + session.clone(), + principal, + binding, + ) + .await?; + let attempt = match reservation { + ExternalCausalReservation::Acquired(attempt) => attempt, + ExternalCausalReservation::Replay(replay) => return Ok(replay), + }; + let http = match self.http.retarget_segments(&[route.kind, &shard]) { + Ok(http) => http, + Err(error) => { + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(error); + } + }; + let (status, body) = match http + .post_cell_wait_path_with_causation( command, command_id, input.clone(), &session, &service_id, &principal_partition, + Some(attempt.causation_id()), ) - .await?; + .await + { + Ok(response) => response, + Err(error) => { + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(error); + } + }; if status >= 400 { - return Err(remote_dispatch_error(status, &body)); + let error = remote_dispatch_error(status, &body); + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(error); + } + let remote = match CausalDispatchResult::from_wait_path_wire(body) { + Ok(remote) => remote, + Err(error) => { + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(CausalDispatchError::Internal(format!( + "wait-path decode: {error}" + ))); + } + }; + if let Err(error) = attempt.validate_remote(&remote) { + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(error); } - let remote = CausalDispatchResult::from_wait_path_wire(body) - .map_err(|error| CausalDispatchError::Internal(format!("wait-path decode: {error}")))?; let payload = (route.payload)(command, &input, remote.payload(), &session); let mut remote = remote.with_payload(payload); if let Some(protocol) = protocol { - remote = self + remote = match self .local .service() - .seal_wait_path_dispatch(command, &protocol, remote)?; + .seal_wait_path_dispatch(command, &protocol, remote) + { + Ok(remote) => remote, + Err(error) => { + let _ = self + .local + .service() + .abandon_external_causal(command, attempt) + .await; + return Err(error); + } + }; } - self.remember_completed( - (principal_partition, command_id.to_string()), - remote.public_status(), - ); + self.local + .service() + .complete_external_causal(command, attempt, &remote) + .await?; Ok(remote) } @@ -248,17 +267,6 @@ impl CommandHost for CelldCommandHost { protocol: Option, ) -> Result { validate_principal_session_if_present(session, &principal)?; - let service_id = self.service_id()?; - let principal_partition = principal.partition_for_service(service_id); - let key = (principal_partition, command_id.to_string()); - if let Some(status) = self - .completed - .lock() - .ok() - .and_then(|mut guard| guard.get(&key)) - { - return Ok(status); - } self.local .status(command_id, session, principal, protocol) .await diff --git a/src/microsvc/cell_host/mod.rs b/src/microsvc/cell_host/mod.rs index 51f94eb70..8209bd249 100644 --- a/src/microsvc/cell_host/mod.rs +++ b/src/microsvc/cell_host/mod.rs @@ -28,8 +28,8 @@ mod store; mod wire; pub use causal::{ - CellCommandIdentity, CellDispatchError, CellDispatchResult, CELL_PRINCIPAL_PARTITION_HEADER, - CELL_SERVICE_ID_HEADER, + CellCommandIdentity, CellDispatchError, CellDispatchResult, CELL_CAUSATION_ID_HEADER, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, }; pub use cell::{instance_name, parent_cell_name, AggregateCell, CellNamespace}; #[cfg(feature = "workers-rs")] diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index 2b38adc8f..3ea157bb0 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -106,6 +106,8 @@ pub use runtime::{DEFAULT_MAX_PUBLISH_ATTEMPTS, DEFAULT_PUBLISH_LEASE}; pub(crate) use service::CausalCommandProjectionEvidence; #[cfg(feature = "graphql")] pub use service::GraphqlServiceBindError; +#[cfg(feature = "graphql")] +pub(crate) use service::ExternalCausalReservation; pub use service::{ direct_read_model, invoke_transition, require_loaded, CausalCommandContext, CausalCommitBuilder, CausalRepository, CommandRequest, CommandResponse, DeliveryKind, diff --git a/src/microsvc/service/causal.rs b/src/microsvc/service/causal.rs index aa5a705ab..7c70703bc 100644 --- a/src/microsvc/service/causal.rs +++ b/src/microsvc/service/causal.rs @@ -221,6 +221,121 @@ pub struct CausalDispatchResult { pub(crate) projection_events: Vec, } +/// Gateway-side capability for one externally dispatched command. The attempt +/// owns the durable reservation and is consumed only by terminal completion or +/// retryable-unknown recovery; it is never reconstructed from the wire. +#[cfg(feature = "graphql")] +pub(crate) struct ExternalCausalAttempt { + pub(crate) command_name: String, + pub(crate) attempt: CommandAttempt, + pub(crate) retention: Duration, +} + +#[cfg(feature = "graphql")] +pub(crate) enum ExternalCausalReservation { + Acquired(ExternalCausalAttempt), + Replay(CausalDispatchResult), +} + +#[cfg(feature = "graphql")] +impl ExternalCausalAttempt { + pub(crate) fn command_id(&self) -> &str { + self.attempt.key().command_id() + } + + pub(crate) fn causation_id(&self) -> &str { + self.attempt.causation_id().as_str() + } + + pub(crate) fn fence(&self) -> AttemptFence { + self.attempt.fence() + } + + pub(crate) fn validate_remote( + &self, + result: &CausalDispatchResult, + ) -> Result<(), CausalDispatchError> { + if result.command_id() != self.command_id() { + return Err(CausalDispatchError::Internal( + "cell wait-path returned a different command ID".into(), + )); + } + if result.causation_id() != self.causation_id() { + return Err(CausalDispatchError::Internal( + "cell wait-path returned a different causation ID".into(), + )); + } + Ok(()) + } + + pub(crate) fn into_external_completion( + self, + result: &CausalDispatchResult, + ) -> Result { + self.validate_remote(result)?; + let state = match result.receipt.state { + CommandLedgerState::Succeeded => TerminalCommandState::Succeeded, + CommandLedgerState::SucceededPendingProjection => { + TerminalCommandState::SucceededPendingProjection + } + CommandLedgerState::Atomic => { + return Err(CausalDispatchError::BadRequest( + "atomic commands cannot be dispatched to an aggregate cell".into(), + )); + } + other => { + return Err(CausalDispatchError::Internal(format!( + "cell wait-path returned non-terminal state `{}`", + other.as_str() + ))); + } + }; + if !result.receipt.obligations.is_empty() && result.receipt.projection_metadata.is_none() { + return Err(CausalDispatchError::Internal( + "cell wait-path returned legacy projection obligations without their canonical key identity" + .into(), + )); + } + let binding = self.attempt.external_binding().cloned().ok_or_else(|| { + CausalDispatchError::Internal( + "external command attempt lost its immutable route binding".into(), + ) + })?; + if let Some(metadata) = result.receipt.projection_metadata.as_ref() { + let bytes = metadata.canonical_bytes().map_err(|error| { + CausalDispatchError::Internal(format!( + "cell projection metadata could not be canonicalized: {error}" + )) + })?; + let expires_at = metadata.expires_at().map_err(|error| { + CausalDispatchError::Internal(format!( + "cell projection metadata retention deadline is invalid: {error}" + )) + })?; + self.attempt + .complete_external_with_projection_metadata_until( + binding, + state, + result.payload().clone(), + bytes, + self.retention, + expires_at, + ) + .map_err(internal_ledger_error) + } else { + self.attempt + .complete_external( + binding, + state, + result.payload().clone(), + Vec::new(), + self.retention, + ) + .map_err(internal_ledger_error) + } + } +} + #[cfg(feature = "graphql")] impl CausalDispatchResult { /// Handler payload returned to the wait-path caller. @@ -576,6 +691,40 @@ pub(super) fn internal_ledger_error(error: CommandLedgerError) -> CausalDispatch CausalDispatchError::Internal(error.to_string()) } +#[cfg(feature = "graphql")] +pub(super) async fn abandon_external_attempt( + repository: &R, + attempt: ExternalCausalAttempt, + detail: String, +) -> Result<(), CausalDispatchError> +where + R: CommandLedgerStore + Send + Sync, +{ + let fence = attempt.fence(); + match repository.mark_retryable_unknown(fence.clone()).await { + Ok(()) => Err(CausalDispatchError::Internal(detail)), + Err(CommandLedgerError::AttemptFenced { .. }) => match repository + .lookup_command(fence.key(), CommandLookupScope::Attempt(&fence)) + .await + { + Ok(CommandLookup::Replay(_)) => Ok(()), + Ok(CommandLookup::Expired) => Err(CausalDispatchError::Expired), + Ok(CommandLookup::RetryableUnknown { .. }) => { + Err(CausalDispatchError::Internal(detail)) + } + Ok(CommandLookup::InProgress { .. }) | Ok(CommandLookup::Unknown) => { + Err(CausalDispatchError::Internal(detail)) + } + Err(error) => Err(CausalDispatchError::Internal(format!( + "{detail}; external command recovery failed: {error}" + ))), + }, + Err(error) => Err(CausalDispatchError::Internal(format!( + "{detail}; failed to mark external command retryable: {error}" + ))), + } +} + #[cfg(feature = "graphql")] pub(super) fn replay_result( consistency: CommandConsistency, diff --git a/src/microsvc/service/mod.rs b/src/microsvc/service/mod.rs index c5cb368c8..a9592c7d5 100644 --- a/src/microsvc/service/mod.rs +++ b/src/microsvc/service/mod.rs @@ -43,7 +43,7 @@ pub use causal::GraphqlServiceBindError; #[cfg(feature = "graphql")] pub(crate) use causal::{ CausalCommandProjectionObligation, CausalCommandPublicState, CausalCommandReceiptSource, - CausalProjectionEvidenceState, + CausalProjectionEvidenceState, ExternalCausalReservation, }; #[cfg(feature = "graphql")] pub use causal::{CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult}; diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 3dc6022c4..2f61bbcc0 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -5,15 +5,13 @@ use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; -#[cfg(feature = "graphql")] -use std::time::SystemTime; - #[cfg(feature = "graphql")] use super::causal::{ abandon_causal_attempt, causal_handler_error_code, commit_causal_rejection, ensure_causal_grant, evaluate_causal_command_status, internal_ledger_error, load_committed_dispatch_result, recover_causal_commit_error, replay_result, CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult, + ExternalCausalAttempt, ExternalCausalReservation, }; use super::handlers::{ boxed_causal_guard, boxed_handler, boxed_prepared_handler, CausalCommandContext, CausalGuardFn, @@ -35,7 +33,7 @@ use crate::command_ledger::{ #[cfg(feature = "graphql")] use crate::command_ledger::{ CausalRepositoryIdentity, CommandId, CommandLedgerKey, CommandLookup, CommandLookupScope, - PrincipalPartitionId, + ExternalDispatchBinding, PrincipalPartitionId, }; #[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; @@ -189,6 +187,16 @@ pub(super) type CausalHandlerFuture<'a> = pub(super) type CausalStatusFuture<'a> = Pin< Box> + Send + 'a>, >; +#[cfg(feature = "graphql")] +pub(super) type ExternalReservationFuture<'a> = Pin< + Box> + Send + 'a>, +>; +#[cfg(feature = "graphql")] +pub(super) type ExternalCompletionFuture<'a> = + Pin> + Send + 'a>>; +#[cfg(feature = "graphql")] +pub(super) type ExternalAbandonFuture<'a> = + Pin> + Send + 'a>>; pub(super) type CellCausalHandlerFuture<'a> = Pin> + Send + 'a>>; @@ -246,6 +254,34 @@ pub(super) trait ErasedCausalHandler: Send + Sync { protocol: Option, ) -> CausalStatusFuture<'a>; + #[cfg(feature = "graphql")] + fn reserve_external<'a>( + &'a self, + dependencies: &'a D, + service_id: &'a str, + command_id: &'a str, + input: Value, + session: Session, + principal: VerifiedPrincipal, + policy: CausalCommandPolicy, + binding: ExternalDispatchBinding, + ) -> ExternalReservationFuture<'a>; + + #[cfg(feature = "graphql")] + fn complete_external<'a>( + &'a self, + dependencies: &'a D, + attempt: ExternalCausalAttempt, + result: &'a CausalDispatchResult, + ) -> ExternalCompletionFuture<'a>; + + #[cfg(feature = "graphql")] + fn abandon_external<'a>( + &'a self, + dependencies: &'a D, + attempt: ExternalCausalAttempt, + ) -> ExternalAbandonFuture<'a>; + /// Run the same typed `handle` inside one cell, without GraphQL receipts. fn invoke_cell<'a>( &'a self, @@ -368,6 +404,34 @@ pub(super) trait ErasedRoutes: Send + Sync { protocol: Option, ) -> CausalStatusFuture<'a>; + #[cfg(feature = "graphql")] + fn reserve_external<'a>( + &'a self, + command: &'a str, + service_id: &'a str, + command_id: &'a str, + input: Value, + session: Session, + principal: VerifiedPrincipal, + policy: CausalCommandPolicy, + binding: ExternalDispatchBinding, + ) -> ExternalReservationFuture<'a>; + + #[cfg(feature = "graphql")] + fn complete_external<'a>( + &'a self, + command: &'a str, + attempt: ExternalCausalAttempt, + result: &'a CausalDispatchResult, + ) -> ExternalCompletionFuture<'a>; + + #[cfg(feature = "graphql")] + fn abandon_external<'a>( + &'a self, + command: &'a str, + attempt: ExternalCausalAttempt, + ) -> ExternalAbandonFuture<'a>; + #[cfg(feature = "graphql")] fn projected_storage_identities(&self) -> Vec; @@ -1575,6 +1639,10 @@ where policy.replay_retention, ) .map_err(crate::microsvc::cell_host::causal::internal_ledger_error)?; + let reservation = match identity.causation_id() { + Some(causation_id) => reservation.with_causation_id(causation_id.clone()), + None => reservation, + }; let aggregate_repository = dependencies.__causal_aggregate_repository(); let repository = aggregate_repository.repo(); @@ -2263,6 +2331,132 @@ where }) } + #[cfg(feature = "graphql")] + fn reserve_external<'a>( + &'a self, + dependencies: &'a D, + service_id: &'a str, + command_id: &'a str, + input: Value, + session: Session, + principal: VerifiedPrincipal, + policy: CausalCommandPolicy, + binding: ExternalDispatchBinding, + ) -> ExternalReservationFuture<'a> { + Box::pin(async move { + ensure_causal_grant(&self.contract, &session)?; + if self.contract.consistency == CommandConsistency::Atomic { + return Err(CausalDispatchError::BadRequest( + "atomic typed commands cannot be dispatched to an aggregate cell".into(), + )); + } + let canonical = canonicalize_command_input(&self.contract.input, input) + .map_err(|error| CausalDispatchError::BadRequest(error.to_string()))?; + let typed = canonical + .decode::() + .map_err(|error| CausalDispatchError::BadRequest(error.to_string()))?; + let (_, _, input_digest) = typed.into_parts(); + let command_id = CommandId::parse(command_id) + .map_err(|error| CausalDispatchError::BadRequest(error.to_string()))?; + let partition = PrincipalPartitionId::new(principal.partition_for_service(service_id)) + .map_err(internal_ledger_error)?; + let key = CommandLedgerKey::new(service_id, partition, command_id) + .map_err(internal_ledger_error)?; + let reservation = CommandReservation::new( + key, + self.contract.name.clone(), + CommandContractFingerprint::new(self.contract.fingerprint_bytes()), + CanonicalInputHash::new(input_digest), + policy.attempt_lease, + policy.replay_retention, + ) + .map_err(internal_ledger_error)? + .with_external_binding(binding); + let repository = dependencies.__causal_aggregate_repository().repo(); + match repository + .reserve_command(reservation) + .await + .map_err(internal_ledger_error)? + { + ReservationOutcome::Acquired(attempt) => { + Ok(ExternalCausalReservation::Acquired(ExternalCausalAttempt { + command_name: self.contract.name.clone(), + attempt, + retention: policy.replay_retention, + })) + } + ReservationOutcome::Replay(replay) => Ok(ExternalCausalReservation::Replay( + replay_result(self.contract.consistency, replay)?, + )), + ReservationOutcome::InProgress { .. } => Err(CausalDispatchError::InProgress), + ReservationOutcome::Conflict => Err(CausalDispatchError::CommandIdReuse), + ReservationOutcome::Expired => Err(CausalDispatchError::Expired), + } + }) + } + + #[cfg(feature = "graphql")] + fn complete_external<'a>( + &'a self, + dependencies: &'a D, + attempt: ExternalCausalAttempt, + result: &'a CausalDispatchResult, + ) -> ExternalCompletionFuture<'a> { + Box::pin(async move { + if attempt.command_name != self.contract.name { + return Err(CausalDispatchError::Internal( + "external command completion route does not match its reservation".into(), + )); + } + let fence = attempt.fence(); + let completion = attempt.into_external_completion(result)?; + let repository = dependencies.__causal_aggregate_repository().repo(); + match repository.complete_external_command(completion).await { + Ok(()) => Ok(()), + Err(error) => match repository + .lookup_command(&fence.key(), CommandLookupScope::Attempt(&fence)) + .await + { + Ok(CommandLookup::Replay(_)) => Ok(()), + Ok(CommandLookup::InProgress { .. }) => { + match repository.mark_retryable_unknown(fence).await { + Ok(()) => Err(CausalDispatchError::Internal(error.to_string())), + Err(recovery) => Err(CausalDispatchError::Internal(format!( + "{error}; external completion recovery failed: {recovery}" + ))), + } + } + Ok(CommandLookup::RetryableUnknown { .. }) => { + Err(CausalDispatchError::Internal(error.to_string())) + } + Ok(CommandLookup::Expired) => Err(CausalDispatchError::Expired), + Ok(CommandLookup::Unknown) => Err(CausalDispatchError::Internal(format!( + "{error}; external command ledger row disappeared" + ))), + Err(recovery) => Err(CausalDispatchError::Internal(format!( + "{error}; external completion lookup failed: {recovery}" + ))), + }, + } + }) + } + + #[cfg(feature = "graphql")] + fn abandon_external<'a>( + &'a self, + dependencies: &'a D, + attempt: ExternalCausalAttempt, + ) -> ExternalAbandonFuture<'a> { + Box::pin(async move { + crate::microsvc::service::causal::abandon_external_attempt( + dependencies.__causal_aggregate_repository().repo(), + attempt, + "external cell dispatch did not produce a durable terminal receipt".into(), + ) + .await + }) + } + fn invoke_cell<'a>( &'a self, dependencies: &'a D, @@ -2585,6 +2779,92 @@ where }) } + #[cfg(feature = "graphql")] + fn reserve_external<'a>( + &'a self, + command: &'a str, + service_id: &'a str, + command_id: &'a str, + input: Value, + session: Session, + principal: VerifiedPrincipal, + policy: CausalCommandPolicy, + binding: ExternalDispatchBinding, + ) -> ExternalReservationFuture<'a> { + let handler = self + .handlers + .get(&MessageKind::Command) + .and_then(|handlers| handlers.get(command)); + match handler { + Some(RegisteredHandler::Causal(handler)) => handler.reserve_external( + &self.dependencies, + service_id, + command_id, + input, + session, + principal, + policy, + binding, + ), + Some(RegisteredHandler::Legacy { .. }) + | Some(RegisteredHandler::Projector(_)) + | None => Box::pin(async move { + Err(CausalDispatchError::BadRequest(format!( + "`{command}` is not a typed causal command" + ))) + }), + } + } + + #[cfg(feature = "graphql")] + fn complete_external<'a>( + &'a self, + command: &'a str, + attempt: ExternalCausalAttempt, + result: &'a CausalDispatchResult, + ) -> ExternalCompletionFuture<'a> { + let handler = self + .handlers + .get(&MessageKind::Command) + .and_then(|handlers| handlers.get(command)); + match handler { + Some(RegisteredHandler::Causal(handler)) => { + handler.complete_external(&self.dependencies, attempt, result) + } + Some(RegisteredHandler::Legacy { .. }) + | Some(RegisteredHandler::Projector(_)) + | None => Box::pin(async move { + Err(CausalDispatchError::BadRequest(format!( + "`{command}` is not a typed causal command" + ))) + }), + } + } + + #[cfg(feature = "graphql")] + fn abandon_external<'a>( + &'a self, + command: &'a str, + attempt: ExternalCausalAttempt, + ) -> ExternalAbandonFuture<'a> { + let handler = self + .handlers + .get(&MessageKind::Command) + .and_then(|handlers| handlers.get(command)); + match handler { + Some(RegisteredHandler::Causal(handler)) => { + handler.abandon_external(&self.dependencies, attempt) + } + Some(RegisteredHandler::Legacy { .. }) + | Some(RegisteredHandler::Projector(_)) + | None => Box::pin(async move { + Err(CausalDispatchError::BadRequest(format!( + "`{command}` is not a typed causal command" + ))) + }), + } + } + #[cfg(feature = "graphql")] fn projected_storage_identities(&self) -> Vec { self.handlers diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index bc680536f..688b5a46d 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -9,7 +9,7 @@ use serde_json::Value; #[cfg(feature = "graphql")] use super::causal::{ internal_ledger_error, CausalCommandPublicStatus, CausalDispatchError, CausalDispatchResult, - GraphqlServiceBindError, + ExternalCausalAttempt, ExternalCausalReservation, GraphqlServiceBindError, }; use super::helpers::{ is_json_content_type, message_to_json_input, message_to_session, names_by_kind, @@ -29,6 +29,8 @@ use crate::command::{TypedCommandContract, TypedServiceCommandBinding}; #[cfg(feature = "graphql")] use crate::command_ledger::{CommandId, CommandLookup, PrincipalPartitionId}; #[cfg(feature = "graphql")] +use crate::command_ledger::ExternalDispatchBinding; +#[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; use crate::microsvc::error::HandlerError; use crate::microsvc::projector::{ProjectionRepairHandle, ProjectorRegistration}; @@ -668,6 +670,85 @@ impl Service { ) } + /// Reserve the gateway ledger row for a command that will be committed by + /// an aggregate cell. The route performs canonical input and grant checks + /// before any remote request is made. + #[cfg(feature = "graphql")] + pub(crate) async fn reserve_external_causal( + &self, + command: &str, + command_id: &str, + input: Value, + session: Session, + principal: VerifiedPrincipal, + binding: ExternalDispatchBinding, + ) -> Result { + ensure_lifecycle_mutations_open().map_err(CausalDispatchError::Handler)?; + let service_id = self.name().ok_or_else(|| { + CausalDispatchError::Internal( + "external typed causal dispatch requires Service::named identity".into(), + ) + })?; + let route_index = self + .index + .get(&MessageKind::Command) + .and_then(|commands| commands.get(command)) + .and_then(|indices| (indices.len() == 1).then_some(indices[0])) + .ok_or_else(|| CausalDispatchError::BadRequest("unknown typed command".into()))?; + self.routes[route_index] + .reserve_external( + command, + service_id, + command_id, + input, + session, + principal, + self.causal_command_policy, + binding, + ) + .await + } + + /// Persist a sealed terminal receipt for a command committed by a cell. + /// This path only updates the gateway ledger and never invokes a local + /// handler or appends a local event batch. + #[cfg(feature = "graphql")] + pub(crate) async fn complete_external_causal( + &self, + command: &str, + attempt: ExternalCausalAttempt, + result: &CausalDispatchResult, + ) -> Result<(), CausalDispatchError> { + let route_index = self + .index + .get(&MessageKind::Command) + .and_then(|commands| commands.get(command)) + .and_then(|indices| (indices.len() == 1).then_some(indices[0])) + .ok_or_else(|| CausalDispatchError::BadRequest("unknown typed command".into()))?; + self.routes[route_index] + .complete_external(command, attempt, result) + .await + } + + /// Mark a remote attempt retryable after a transport/protocol failure. + /// The durable fence remains the authority for later replay or reclaim. + #[cfg(feature = "graphql")] + pub(crate) async fn abandon_external_causal( + &self, + command: &str, + attempt: ExternalCausalAttempt, + ) -> Result<(), CausalDispatchError> { + let route_index = self + .index + .get(&MessageKind::Command) + .and_then(|commands| commands.get(command)) + .and_then(|indices| (indices.len() == 1).then_some(indices[0])) + .ok_or_else(|| CausalDispatchError::BadRequest("unknown typed command".into()))?; + self.routes[route_index] + .abandon_external(command, attempt) + .await + } + pub(crate) fn typed_command_binding(&self) -> Result { let service_id = self .name() diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index e9450f889..0e99d74e9 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -20,11 +20,15 @@ use crate::command_ledger::{ ExternalCommandCompletion, ReservationOutcome, }; #[cfg(feature = "graphql")] +use crate::command_dispatch::SharedCommandHost; +#[cfg(feature = "graphql")] use crate::graphql::identity::VerifiedPrincipal; #[cfg(feature = "graphql")] use crate::graphql::{SurfaceDirectProjection, SurfaceProjector}; #[cfg(feature = "graphql")] use crate::microsvc::HasOutboxStore; +#[cfg(feature = "graphql")] +use crate::microsvc::cell_host::{CelldCommandHost, InternalHttpSecret}; use crate::microsvc::{ CommandRequest, Context, HandlerError, RepoReadModelDependencies, Routes, Service, Session, }; @@ -774,6 +778,19 @@ fn command_host(service: &Arc) -> crate::command_dispatch::SharedComman ))) } +#[cfg(feature = "graphql")] +fn celld_status_host(service: &Arc) -> SharedCommandHost { + Arc::new( + CelldCommandHost::new( + "http://127.0.0.1:1", + Arc::clone(service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes") + .expect("test internal secret should be valid"), + ) + .expect("status-only celld host should accept a local URL"), + ) +} + #[cfg(feature = "graphql")] #[derive(Clone, Copy)] enum InjectedCommitBehavior { @@ -2829,6 +2846,37 @@ async fn graphql_succeeded_status_evaluates_retained_projection_evidence() { ); assert!(before_envelope["command"].get("observations").is_none()); + // The celld host must use the same durable status evaluator. In + // particular, a terminal cell receipt cannot make the gateway claim a + // projection observation before the modeled projector has supplied proof. + let before_celld = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&status_query) + .data(celld_status_host(&service)) + .data(principal.clone()), + ) + .await; + assert!(before_celld.errors.is_empty(), "{before_celld:?}"); + let before_celld_envelope = serde_json::to_value( + before_celld + .extensions + .get("distributed") + .expect("celld status should carry its protocol envelope"), + ) + .unwrap(); + assert_eq!(before_celld_envelope["command"]["state"], "succeeded"); + assert_eq!( + before_celld_envelope["command"]["expects"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert!(before_celld_envelope["command"].get("observations").is_none()); + let pending = repository .outbox_store() .pending(10) @@ -2882,6 +2930,33 @@ async fn graphql_succeeded_status_evaluates_retained_projection_evidence() { causation_id ); + let after_celld = service + .graphql_engine() + .unwrap() + .execute( + &session, + async_graphql::Request::new(&status_query) + .data(celld_status_host(&service)) + .data(principal.clone()), + ) + .await; + assert!(after_celld.errors.is_empty(), "{after_celld:?}"); + let after_celld_envelope = serde_json::to_value( + after_celld + .extensions + .get("distributed") + .expect("celld status should carry its protocol envelope"), + ) + .unwrap(); + assert_eq!(after_celld_envelope["command"]["state"], "succeeded"); + assert_eq!( + after_celld_envelope["command"]["observations"] + .as_array() + .expect("celld status should expose matching durable proof") + .len(), + 1 + ); + // A proof authored by a different semantic program is not an observation // for this command, even when its physical topology and scope are equal. let wrong_program = diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index 80875069a..ab96b78ff 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -4,7 +4,9 @@ use std::sync::Arc; use distributed::bus::{Bus, BusConsumer, InMemoryBus, TransportError}; -use distributed::cell_host::InternalHttpSecret; +use distributed::cell_host::{ + CelldCommandHost, CelldRoute, InternalHttpSecret, CELL_CAUSATION_ID_HEADER, +}; use distributed::command::{ typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, Succeeded, }; @@ -12,8 +14,11 @@ use distributed::command_dispatch::{CommandHost, HttpCommandHost, SharedCommandH use distributed::graphql::VerifiedPrincipal; use distributed::microsvc::{router, Routes, Service, ROLE_KEY, USER_ID_KEY}; use distributed::{Aggregate, AggregateBuilder, Entity, InMemoryRepository, Snapshot}; +#[cfg(feature = "sqlite")] +use distributed::{AggregateRepository, SqliteRepository}; use serde::{Deserialize, Serialize}; use serde_json::json; +use serde_json::Value; #[derive(Default, Snapshot)] struct WaitAgg { @@ -91,9 +96,9 @@ impl CommandOutputType for IdPayload { } } -fn wait_service() -> Arc { +fn wait_service_with_repo(repo: distributed::InMemoryRepository) -> Arc { let causal = Routes::new() - .with_repo(InMemoryRepository::new().aggregate::()) + .with_repo(repo.aggregate::()) .typed_command( typed_command::>("todo.create").roles(["user"]), ) @@ -128,6 +133,33 @@ fn wait_service() -> Arc { ) } +fn wait_service() -> Arc { + wait_service_with_repo(InMemoryRepository::new()) +} + +#[cfg(feature = "sqlite")] +fn sqlite_wait_service(repository: SqliteRepository) -> Arc { + let causal = Routes::new() + .with_repo(AggregateRepository::<_, WaitAgg>::new(repository)) + .typed_command( + typed_command::>("todo.create").roles(["user"]), + ) + .create() + .invoke(|aggregate, input, _owner| { + aggregate.record(input.id.clone())?; + Ok::<_, distributed::EventRecordError>(()) + }) + .succeeded(|aggregate| IdPayload { + id: aggregate.entity().id().to_string(), + }); + Arc::new( + Service::new() + .named("causal-wait-path") + .with_http_command_routes() + .routes(causal), + ) +} + async fn start_http(service: Arc) -> String { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); @@ -203,6 +235,379 @@ async fn cell_wait_path_replays_once_after_internal_failure() { assert_eq!(attempts.load(Ordering::SeqCst), 2); } +#[tokio::test] +async fn celld_host_completes_remote_commit_once_and_rejects_changed_shard() { + use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + async fn command( + State(calls): State>, + headers: HeaderMap, + Json(body): Json, + ) -> (StatusCode, Json) { + calls.fetch_add(1, Ordering::SeqCst); + let causation_id = headers + .get(CELL_CAUSATION_ID_HEADER) + .and_then(|value| value.to_str().ok()) + .expect("gateway must bind the cell request to its reserved causation") + .to_string(); + ( + StatusCode::CREATED, + Json(json!({ + "payload": { "id": body["input"]["id"] }, + "receipt": { + "commandId": body["commandId"], + "causationId": causation_id, + "state": "succeeded", + "replayed": false + }, + "events": [] + })), + ) + } + + let calls = Arc::new(AtomicUsize::new(0)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(command)) + .with_state(Arc::clone(&calls)); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let repo = InMemoryRepository::new(); + let service = wait_service_with_repo(repo.clone()); + let host = CelldCommandHost::new( + format!("http://{addr}"), + Arc::clone(&service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |input| input.get("id").and_then(Value::as_str).map(str::to_owned), + |_command, _input, remote, _session| remote.clone(), + )); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "alice"); + session.set(ROLE_KEY, "user"); + let principal = VerifiedPrincipal::from_trusted_transport("alice"); + let command_id = "0190a000-0000-7000-8000-000000000109"; + + let first = host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-cell-once" }), + session.clone(), + principal.clone(), + None, + ) + .await + .expect("remote cell commit should complete the gateway ledger"); + assert_eq!(first.payload(), &json!({ "id": "todo-cell-once" })); + assert_eq!(first.state(), "succeeded"); + + drop(host); + drop(service); + let restarted_service = wait_service_with_repo(repo); + let restarted_host = CelldCommandHost::new( + format!("http://{addr}"), + Arc::clone(&restarted_service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |input| input.get("id").and_then(Value::as_str).map(str::to_owned), + |_command, _input, remote, _session| remote.clone(), + )); + let replay = restarted_host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-cell-once" }), + session.clone(), + principal.clone(), + None, + ) + .await + .expect("completed external receipt should replay durably"); + assert_eq!(replay.state(), "succeeded"); + assert_eq!(replay.payload(), first.payload()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + let conflict = restarted_host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-other-cell" }), + session, + principal, + None, + ) + .await + .expect_err("same command ID cannot move to another cell or input"); + assert!(matches!( + conflict, + distributed::microsvc::CausalDispatchError::CommandIdReuse + )); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + let different_binding_host = CelldCommandHost::new( + format!("http://{addr}"), + Arc::clone(&restarted_service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |_input| Some("todo-different-cell".into()), + |_command, _input, remote, _session| remote.clone(), + )); + let mut binding_session = distributed::microsvc::Session::new(); + binding_session.set(USER_ID_KEY, "alice"); + binding_session.set(ROLE_KEY, "user"); + let binding_conflict = different_binding_host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-cell-once" }), + binding_session, + VerifiedPrincipal::from_trusted_transport("alice"), + None, + ) + .await + .expect_err("the immutable route binding must fence a changed shard"); + assert!(matches!( + binding_conflict, + distributed::microsvc::CausalDispatchError::CommandIdReuse + )); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn celld_host_reclaims_an_ambiguous_receipt_with_the_same_causation() { + use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + + async fn command( + State(state): State>) >>, + headers: HeaderMap, + Json(body): Json, + ) -> (StatusCode, Json) { + let causation_id = headers + .get(CELL_CAUSATION_ID_HEADER) + .and_then(|value| value.to_str().ok()) + .expect("gateway must bind the cell request to its reserved causation") + .to_string(); + let call = state.0.fetch_add(1, Ordering::SeqCst); + if call == 0 { + *state.1.lock().unwrap() = Some(causation_id); + return (StatusCode::OK, Json(json!({ "not": "a receipt" }))); + } + assert_eq!( + state.1.lock().unwrap().as_deref(), + Some(causation_id.as_str()), + "reclaim must reuse the cell's original causation identity" + ); + ( + StatusCode::CREATED, + Json(json!({ + "payload": { "id": body["input"]["id"] }, + "receipt": { + "commandId": body["commandId"], + "causationId": causation_id, + "state": "succeeded", + "replayed": true + }, + "events": [] + })), + ) + } + + let state = Arc::new((AtomicUsize::new(0), Mutex::new(None))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(command)) + .with_state(Arc::clone(&state)); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let service = wait_service(); + let host = CelldCommandHost::new( + format!("http://{addr}"), + service, + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |input| input.get("id").and_then(Value::as_str).map(str::to_owned), + |_command, _input, remote, _session| remote.clone(), + )); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "alice"); + session.set(ROLE_KEY, "user"); + let principal = VerifiedPrincipal::from_trusted_transport("alice"); + let command_id = "0190a000-0000-7000-8000-000000000110"; + + let first = host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-ambiguous" }), + session.clone(), + principal.clone(), + None, + ) + .await + .expect_err("an undecodable remote response must remain retryable"); + assert!(matches!( + first, + distributed::microsvc::CausalDispatchError::Internal(_) + )); + + let retry = host + .invoke( + "todo.create", + command_id, + json!({ "id": "todo-ambiguous" }), + session, + principal, + None, + ) + .await + .expect("retry should reclaim the durable reservation"); + assert_eq!(retry.state(), "succeeded"); + assert_eq!(state.0.load(Ordering::SeqCst), 2); +} + +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn celld_host_replays_external_completion_after_sqlite_reopen() { + use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + async fn command( + State(calls): State>, + headers: HeaderMap, + Json(body): Json, + ) -> (StatusCode, Json) { + calls.fetch_add(1, Ordering::SeqCst); + let causation_id = headers + .get(CELL_CAUSATION_ID_HEADER) + .and_then(|value| value.to_str().ok()) + .expect("gateway must bind the cell request to its reserved causation"); + ( + StatusCode::CREATED, + Json(json!({ + "payload": { "id": body["input"]["id"] }, + "receipt": { + "commandId": body["commandId"], + "causationId": causation_id, + "state": "succeeded", + "replayed": false + }, + "events": [] + })), + ) + } + + let calls = Arc::new(AtomicUsize::new(0)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(command)) + .with_state(Arc::clone(&calls)); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let database_path = std::env::temp_dir().join(format!( + "distributed-celld-host-{}.sqlite", + uuid::Uuid::now_v7() + )); + let database_url = format!("sqlite://{}?mode=rwc", database_path.display()); + let repository = SqliteRepository::connect_and_migrate(&database_url) + .await + .expect("initial gateway ledger migration"); + let service = sqlite_wait_service(repository.clone()); + let host = CelldCommandHost::new( + format!("http://{addr}"), + Arc::clone(&service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |input| input.get("id").and_then(Value::as_str).map(str::to_owned), + |_command, _input, remote, _session| remote.clone(), + )); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "alice"); + session.set(ROLE_KEY, "user"); + let principal = VerifiedPrincipal::from_trusted_transport("alice"); + let command_id = "0190a000-0000-7000-8000-000000000111"; + let input = json!({ "id": "todo-sqlite-reopen" }); + + host.invoke( + "todo.create", + command_id, + input.clone(), + session.clone(), + principal.clone(), + None, + ) + .await + .expect("cell completion should be durable before response"); + drop(host); + drop(service); + drop(repository); + + let reopened_repository = SqliteRepository::connect_and_migrate(&database_url) + .await + .expect("reopen gateway ledger"); + let reopened_service = sqlite_wait_service(reopened_repository); + let reopened_host = CelldCommandHost::new( + format!("http://{addr}"), + Arc::clone(&reopened_service), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap() + .route(CelldRoute::new( + &["todo.create"], + "todo", + |input| input.get("id").and_then(Value::as_str).map(str::to_owned), + |_command, _input, remote, _session| remote.clone(), + )); + let replay = reopened_host + .invoke( + "todo.create", + command_id, + input, + session, + principal, + None, + ) + .await + .expect("reopened gateway should replay the durable cell receipt"); + assert_eq!(replay.state(), "succeeded"); + assert_eq!(replay.payload(), &json!({ "id": "todo-sqlite-reopen" })); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + let _ = std::fs::remove_file(database_path); +} + #[tokio::test] async fn http_wait_path_returns_command_id_and_receipt() { let base = start_http(wait_service()).await; diff --git a/tests/celld/worker/src/lib.rs b/tests/celld/worker/src/lib.rs index dd287ff38..7ff17413d 100644 --- a/tests/celld/worker/src/lib.rs +++ b/tests/celld/worker/src/lib.rs @@ -9,7 +9,7 @@ use chat_domain::{post, ChatMessage, ChatMessageState}; use distributed::cell_host::{ AggregateCell, CellCommandIdentity, CellDispatchError, CellDispatchResult, CellWaitPathRequest, CelldOutbox, InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, - CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, + CELL_CAUSATION_ID_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, }; use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; use serde::de::DeserializeOwned; @@ -372,7 +372,11 @@ fn request_cell_identity( ) -> std::result::Result { let service_id = required_internal_header(req, CELL_SERVICE_ID_HEADER)?; let principal_partition = required_internal_header(req, CELL_PRINCIPAL_PARTITION_HEADER)?; - CellCommandIdentity::new(service_id, principal_partition, command_id) + let identity = CellCommandIdentity::new(service_id, principal_partition, command_id)?; + match optional_internal_header(req, CELL_CAUSATION_ID_HEADER)? { + Some(causation_id) => identity.with_causation_id(causation_id), + None => Ok(identity), + } } fn required_internal_header( @@ -389,6 +393,18 @@ fn required_internal_header( .ok_or(CellDispatchError::Unauthorized) } +fn optional_internal_header( + req: &Request, + name: &str, +) -> std::result::Result, CellDispatchError> { + req.headers() + .get(name) + .map_err(|error| { + CellDispatchError::Internal(format!("could not read internal cell header: {error}")) + }) + .map(|value| value.map(|value| value.trim().to_string()).filter(|value| !value.is_empty())) +} + fn wait_path_ok( payload: Value, dispatch: &CellDispatchResult, From 87c9d637445adaa68d2c7b40d93f5c01bf233cb8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 01:13:18 -0500 Subject: [PATCH 083/484] fix: settle proven eventual command delivery --- js/README.md | 8 + js/src/replica/command-runtime/create.ts | 32 ++++ js/tests/replica-command-runtime.test.mjs | 170 ++++++++++++++++++++++ 3 files changed, 210 insertions(+) diff --git a/js/README.md b/js/README.md index e0669ad52..8dbe828bf 100644 --- a/js/README.md +++ b/js/README.md @@ -442,6 +442,14 @@ same replica and GraphQL transport. A command call: (`confirmDirectProjection`) before the call settles. The server waited in the command handler because it could; an event handler cannot. +An Eventual command may be terminal `succeeded` at a cell boundary while its +status envelope already carries every exact projection observation. Those +observations settle `receipt.projected` because they prove delivery of the +projection obligation; they do not retire the accepted optimistic layer. The +layer is retired only by a matching canonical query or live frame, so an +`@load` operation does not need to become `@live` merely to complete a causal +wait. A later query or navigation can still supply that canonical frame. + Applications do not provide list targets, merge functions, mutation update callbacks, board simulators, or invalidation maps. If the compiler cannot prove safe maintenance, the generated plan marks the affected projection stale and diff --git a/js/src/replica/command-runtime/create.ts b/js/src/replica/command-runtime/create.ts index 471ef75cc..f555e0b88 100644 --- a/js/src/replica/command-runtime/create.ts +++ b/js/src/replica/command-runtime/create.ts @@ -1,5 +1,6 @@ import { parseGraphqlResponseExtensions, + type DistributedCommandMetadata, type DistributedProtocolEnvelope } from '../../protocol.js'; import { @@ -34,6 +35,7 @@ import { pendingProjection, preparedDispatchKeys, preparedSemanticChanges, + projectionExpectationFingerprint, requireCommandEnvelope, requireCommandRejectionEnvelope, requireStatusEnvelope, @@ -85,6 +87,22 @@ import { type ReplicaCommandProjection } from '../projection-delta/index.js'; +function hasCompleteProjectionObservations( + metadata: DistributedCommandMetadata +): boolean { + if (metadata.expects.length === 0 || metadata.observations.length === 0) { + return false; + } + const observed = new Set( + metadata.observations + .filter((observation) => observation.causationId === metadata.causationId) + .map(projectionExpectationFingerprint) + ); + return metadata.expects.every((expectation) => + observed.has(projectionExpectationFingerprint(expectation)) + ); +} + function assertActualProjectionCapabilities( contract: ReplicaCommandProjection, delta: ProjectionDelta @@ -1038,6 +1056,20 @@ export function createReplicaCommandRuntime< if (tracker.pending !== undefined) { settleTrackedProjection(tracker, pending); } + } else if ( + metadata.state === 'succeeded' && + !prepared.revalidation.required && + !statusRequiresRevalidation && + hasCompleteProjectionObservations(metadata) + ) { + /* + * A cell may keep a committed external receipt in the public + * `succeeded` state after its exact modeled observation is durable. + * That proof settles the projected delivery wait, but it does not + * retire the accepted layer: no canonical query/live frame has + * confirmed read-model membership yet. + */ + settleTrackedProjection(tracker, pending); } else if ( metadata.state === 'atomic' && !prepared.revalidation.required && diff --git a/js/tests/replica-command-runtime.test.mjs b/js/tests/replica-command-runtime.test.mjs index a17865ff6..09348fd2e 100644 --- a/js/tests/replica-command-runtime.test.mjs +++ b/js/tests/replica-command-runtime.test.mjs @@ -1769,6 +1769,176 @@ test('terminal exact projection status settles without command-triggered revalid runtime.dispose(); }); +test('terminal succeeded status with exact observations settles delivery without retiring the layer', async () => { + const replica = new TestReplica(); + let pendingMetadata; + const runtime = createReplicaCommandRuntime( + replica, + { + dispatch(request) { + pendingMetadata = commandMetadata(request, { + actualTitle: 'accepted', + state: 'succeeded' + }); + return Promise.resolve( + envelope(request, { command: pendingMetadata }) + ); + }, + status(request) { + const terminalMetadata = Object.freeze({ + ...pendingMetadata, + state: 'succeeded', + observations: Object.freeze( + pendingMetadata.expects.map((expectation) => + Object.freeze({ + ...expectation, + causationId: pendingMetadata.causationId + }) + ) + ) + }); + return Promise.resolve( + statusEnvelope(request, terminalMetadata) + ); + } + }, + { change: artifact() }, + { status: STATUS } + ); + const receipt = await runtime.commands.change( + { id: 'todo-1', title: 'preview' }, + { commandId: COMMAND_A } + ); + + const projectedState = receipt.projected.then( + (outcome) => outcome.state, + () => 'rejected' + ); + try { + assert.equal((await receipt.status()).state, 'succeeded'); + const state = await Promise.race([ + projectedState, + new Promise((resolve) => + setTimeout(() => resolve('timed_out'), 100) + ) + ]); + assert.equal(state, 'atomic'); + assert.deepEqual(replica.revalidations, []); + assert.equal(replica.layer(COMMAND_A), 'accepted'); + assert.equal(replica.record('todo-1').fields.title, 'accepted'); + } finally { + runtime.dispose(); + } +}); + +test('terminal succeeded status ignores incomplete or mismatched observations', async () => { + const cases = [ + { + name: 'missing', + transform: () => [] + }, + { + name: 'causation', + transform: (observations) => + observations.map((observation) => ({ + ...observation, + causationId: 'cause:other' + })), + protocolFailure: true + }, + { + name: 'projection', + transform: (observations) => + observations.map((observation) => ({ + ...observation, + projection: 'program:other' + })), + protocolFailure: true + }, + { + name: 'scope', + transform: (observations) => + observations.map((observation) => ({ + ...observation, + scopeToken: 'scope:other' + })), + protocolFailure: true + } + ]; + + for (const { name, transform, protocolFailure = false } of cases) { + const replica = new TestReplica(); + let pendingMetadata; + const runtime = createReplicaCommandRuntime( + replica, + { + dispatch(request) { + pendingMetadata = commandMetadata(request, { + actualTitle: 'accepted', + state: 'succeeded' + }); + return Promise.resolve( + envelope(request, { command: pendingMetadata }) + ); + }, + status(request) { + const observations = pendingMetadata.expects.map( + (expectation) => ({ + ...expectation, + causationId: pendingMetadata.causationId + }) + ); + return Promise.resolve( + statusEnvelope(request, { + ...pendingMetadata, + state: 'succeeded', + observations: transform(observations) + }) + ); + } + }, + { change: artifact() }, + { status: STATUS } + ); + const receipt = await runtime.commands.change( + { id: 'todo-1', title: 'preview' }, + { commandId: COMMAND_A } + ); + const projectedState = receipt.projected.then( + (outcome) => outcome.state, + () => 'rejected' + ); + try { + if (protocolFailure) { + await assert.rejects( + receipt.status(), + { code: 'REPLICA_COMMAND_PROTOCOL_INVALID' }, + name + ); + await assert.rejects( + receipt.projected, + { code: 'REPLICA_COMMAND_PROTOCOL_INVALID' }, + name + ); + assert.equal(replica.layer(COMMAND_A), undefined, name); + continue; + } + assert.equal((await receipt.status()).state, 'succeeded', name); + const state = await Promise.race([ + projectedState, + new Promise((resolve) => + setTimeout(() => resolve('timed_out'), 50) + ) + ]); + assert.equal(state, 'timed_out', name); + assert.deepEqual(replica.revalidations, [], name); + assert.equal(replica.layer(COMMAND_A), 'accepted', name); + } finally { + runtime.dispose(); + } + } +}); + test('invalid live progression cannot poison a later valid status transition', async () => { const replica = new TestReplica(); let request; From 3cba1a97b470306b1c75360449adea2abd325da1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 02:06:20 -0500 Subject: [PATCH 084/484] test: add bounded auth refresh diagnostics --- js/src/sveltekit/replica.ts | 111 +++++++++++++++++- tests/e2e-ui/gateway/refresh.mjs | 4 + .../lib/components/shared/AuthRefresh.svelte | 58 ++++++++- tests/e2e-ui/ui/src/routes/+layout.svelte | 11 +- 4 files changed, 179 insertions(+), 5 deletions(-) diff --git a/js/src/sveltekit/replica.ts b/js/src/sveltekit/replica.ts index caf785cb4..5542999d6 100644 --- a/js/src/sveltekit/replica.ts +++ b/js/src/sveltekit/replica.ts @@ -80,6 +80,81 @@ export type SveltekitPageDataSessionSource = set(next: TData): void; }>; +function recordSessionDiagnostic(event: Readonly>): void { + const maxEvents = 128; + if (typeof globalThis === 'undefined') return; + const diagnostics = globalThis as typeof globalThis & { + __captureReplicaDiagnostics?: unknown; + __distributedSessionTrace?: unknown; + }; + if (diagnostics.__captureReplicaDiagnostics !== true) return; + if (!Array.isArray(diagnostics.__distributedSessionTrace)) { + diagnostics.__distributedSessionTrace = []; + } + const trace = diagnostics.__distributedSessionTrace as unknown[]; + trace.push(Object.freeze({ time: Date.now(), ...event })); + if (trace.length > maxEvents) trace.splice(0, trace.length - maxEvents); +} + +const sessionDiagnosticCredentialOrdinals = new Map(); +let nextSessionDiagnosticCredentialOrdinal = 1; +const maxSessionDiagnosticCredentials = 32; + +function sessionDiagnosticCredentialOrdinal( + value: Readonly<{ accessToken?: unknown }> | null | undefined +): number | undefined { + if (typeof globalThis === 'undefined') return undefined; + const diagnostics = globalThis as typeof globalThis & { + __captureReplicaDiagnostics?: unknown; + }; + if (diagnostics.__captureReplicaDiagnostics !== true) return undefined; + if (typeof value?.accessToken !== 'string' || value.accessToken.length === 0) { + return undefined; + } + let ordinal = sessionDiagnosticCredentialOrdinals.get(value.accessToken); + if (ordinal === undefined) { + if (sessionDiagnosticCredentialOrdinals.size >= maxSessionDiagnosticCredentials) { + const oldest = sessionDiagnosticCredentialOrdinals.keys().next().value; + if (typeof oldest === 'string') sessionDiagnosticCredentialOrdinals.delete(oldest); + } + ordinal = nextSessionDiagnosticCredentialOrdinal++; + sessionDiagnosticCredentialOrdinals.set(value.accessToken, ordinal); + } + return ordinal; +} + +function sessionDiagnosticSourceOrigin(): string { + if (typeof globalThis === 'undefined') return 'unattributed'; + const diagnostics = globalThis as typeof globalThis & { + __distributedSessionSourceOrigin?: unknown; + }; + return typeof diagnostics.__distributedSessionSourceOrigin === 'string' + ? diagnostics.__distributedSessionSourceOrigin + : 'unattributed'; +} + +function installSessionDiagnosticOrdinalBridge(): void { + if (typeof globalThis === 'undefined') return; + const diagnostics = globalThis as typeof globalThis & { + __captureReplicaDiagnostics?: unknown; + __distributedSessionCredentialOrdinal?: unknown; + }; + if (diagnostics.__captureReplicaDiagnostics !== true) return; + diagnostics.__distributedSessionCredentialOrdinal = (value: unknown): number | undefined => { + if (value === null || typeof value !== 'object') return undefined; + const pageData = value as { + accessToken?: unknown; + session?: { accessToken?: unknown } | null; + }; + return sessionDiagnosticCredentialOrdinal({ + accessToken: + typeof pageData.accessToken === 'string' + ? pageData.accessToken + : pageData.session?.accessToken + }); + }; +} + export type SveltekitReplicaHydration = Readonly<{ version: 1; state: import('../replica/index.js').ReplicaDehydratedState; @@ -611,6 +686,7 @@ export function sessionSourceFromPageData( export function createPageDataSessionSource( initial: TData ): SveltekitPageDataSessionSource { + installSessionDiagnosticOrdinalBridge(); let current = initial; const listeners = new Set<() => void>(); const source = Object.freeze({ @@ -626,6 +702,17 @@ export function createPageDataSessionSource( session: sessionSourceFromPageData(source), get: source.get, set(next: TData): void { + const pageData = next as SveltekitDistributedPageData; + const auth = authFromPageData(next); + recordSessionDiagnostic({ + kind: 'page-data-set', + origin: sessionDiagnosticSourceOrigin(), + credentialOrdinal: sessionDiagnosticCredentialOrdinal(auth), + hasHydration: pageData.distributed !== undefined, + hasAuthority: pageData.distributedAuthority !== undefined, + hasSession: next.session !== null && next.session !== undefined, + hasAccessToken: typeof pageData.accessToken === 'string' + }); current = next; for (const listener of [...listeners]) listener(); } @@ -1038,16 +1125,17 @@ function createAuthorizationFence( let queue = Promise.resolve(); let disposed = false; const read = (): Promise => { + const sourceOrigin = sessionDiagnosticSourceOrigin(); const candidate = Promise.resolve().then(() => { // Capture the credential and its independent server transfer together, // before another source notification can replace either value. const credential = source.getAuth(); const transfer = source.getHydration?.(); - return Promise.resolve(credential).then((auth) => ({ auth, transfer })); + return Promise.resolve(credential).then((auth) => ({ auth, transfer, sourceOrigin })); }); const transition = queue.then(async () => { try { - const { auth, transfer } = await candidate; + const { auth, transfer, sourceOrigin } = await candidate; const next = snapshotAuthCredential(auth); if ( current !== undefined && @@ -1056,7 +1144,24 @@ function createAuthorizationFence( const freshTransfer = transfer !== undefined && !seenHydrations.has(transfer.hydration) && !seenAuthorities.has(transfer.authority); - if (!freshTransfer || !refresh(transfer)) invalidate(); + const retained = freshTransfer && refresh(transfer); + recordSessionDiagnostic({ + kind: 'auth-credential-change', + sourceOrigin, + previousCredentialOrdinal: sessionDiagnosticCredentialOrdinal(current), + nextCredentialOrdinal: sessionDiagnosticCredentialOrdinal(next), + hasTransfer: transfer !== undefined, + freshTransfer, + retained, + reason: retained + ? 'fresh-transfer-retained' + : transfer === undefined + ? 'missing-transfer' + : !freshTransfer + ? 'replayed-transfer' + : 'refresh-rejected' + }); + if (!retained) invalidate(); } current = next; if (transfer !== undefined) { diff --git a/tests/e2e-ui/gateway/refresh.mjs b/tests/e2e-ui/gateway/refresh.mjs index c5895a35f..6182477a2 100644 --- a/tests/e2e-ui/gateway/refresh.mjs +++ b/tests/e2e-ui/gateway/refresh.mjs @@ -59,6 +59,10 @@ export async function verifySessionRefreshContinuity(page, origin) { const lost = await page.evaluate(()=>globalThis.__refreshContinuity.lost); if (lost) { console.error('Redacted refresh replica diagnostics:', JSON.stringify(await page.evaluate(()=>globalThis.__replicaDiagnosticSnapshot?.()))); + console.error('Redacted refresh lifecycle trace:', JSON.stringify(await page.evaluate(() => ({ + refresh: globalThis.__distributedRefreshTrace ?? [], + session: globalThis.__distributedSessionTrace ?? [] + })))); } assert.equal(lost,false,route+' rows were removed during token refresh: '+JSON.stringify(await page.evaluate(()=>globalThis.__refreshContinuity.events))); } finally { diff --git a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte index 0f32da8b8..e970f89d2 100644 --- a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte +++ b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte @@ -13,6 +13,48 @@ let refreshTimer: number | undefined; let retryTimer: number | undefined; + function traceRefresh(event: Readonly>) { + const maxEvents = 64; + const diagnostics = globalThis as typeof globalThis & { + __captureReplicaDiagnostics?: unknown; + __distributedRefreshTrace?: unknown; + }; + if (diagnostics.__captureReplicaDiagnostics !== true) return; + if (!Array.isArray(diagnostics.__distributedRefreshTrace)) { + diagnostics.__distributedRefreshTrace = []; + } + const trace = diagnostics.__distributedRefreshTrace as unknown[]; + trace.push({ + time: performance.now(), + ...event + }); + if (trace.length > maxEvents) trace.splice(0, trace.length - maxEvents); + } + + function withSessionSource(origin: string, action: () => T): T { + const diagnostics = globalThis as typeof globalThis & { + __captureReplicaDiagnostics?: unknown; + __distributedSessionSourceOrigin?: unknown; + }; + if (diagnostics.__captureReplicaDiagnostics !== true) return action(); + const previous = diagnostics.__distributedSessionSourceOrigin; + diagnostics.__distributedSessionSourceOrigin = origin; + try { + return action(); + } finally { + diagnostics.__distributedSessionSourceOrigin = previous; + } + } + + function credentialOrdinal(value: unknown): number | undefined { + const diagnostics = globalThis as typeof globalThis & { + __distributedSessionCredentialOrdinal?: unknown; + }; + return typeof diagnostics.__distributedSessionCredentialOrdinal === 'function' + ? (diagnostics.__distributedSessionCredentialOrdinal as (value: unknown) => number | undefined)(value) + : undefined; + } + function clearTimers() { if (refreshTimer !== undefined) window.clearTimeout(refreshTimer); if (retryTimer !== undefined) window.clearTimeout(retryTimer); @@ -22,6 +64,7 @@ async function refreshSession() { try { + traceRefresh({ kind: 'refresh-start' }); const response = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'same-origin', @@ -38,11 +81,24 @@ if (response.ok) { const result = await response.json(); - if (result.pageData) onRefresh(result.pageData); + traceRefresh({ + kind: 'refresh-response', + status: response.status, + hasPageData: Boolean(result.pageData), + hasDistributed: result.pageData?.distributed !== undefined, + hasAuthority: result.pageData?.distributedAuthority !== undefined, + credentialOrdinal: credentialOrdinal(result.pageData) + }); + if (result.pageData) { + withSessionSource('refresh-response', () => onRefresh(result.pageData)); + } + if (result.pageData) traceRefresh({ kind: 'refresh-seed-applied' }); } if (response.ok || response.status === 401) { + traceRefresh({ kind: 'invalidate-all-start', status: response.status }); await invalidateAll(); + traceRefresh({ kind: 'invalidate-all-complete', status: response.status }); return; } } catch (error) { diff --git a/tests/e2e-ui/ui/src/routes/+layout.svelte b/tests/e2e-ui/ui/src/routes/+layout.svelte index cd8bb97f4..828ced000 100644 --- a/tests/e2e-ui/ui/src/routes/+layout.svelte +++ b/tests/e2e-ui/ui/src/routes/+layout.svelte @@ -68,7 +68,16 @@ }); function applyPageData(next: SveltekitDistributedPageData) { - pageData.set(next); + const diagnostics = globalThis as typeof globalThis & Record; + const previousSourceOrigin = diagnostics.__distributedSessionSourceOrigin; + if (diagnostics.__captureReplicaDiagnostics === true) { + diagnostics.__distributedSessionSourceOrigin = 'sveltekit-data'; + } + try { + pageData.set(next); + } finally { + diagnostics.__distributedSessionSourceOrigin = previousSourceOrigin; + } if ( next.distributed === undefined || next.distributedAuthority === undefined || From 308bebb7fd411c9ba640c2e0f7f622674bb5c607 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 02:27:21 -0500 Subject: [PATCH 085/484] Revert "test: add bounded auth refresh diagnostics" This reverts commit 3cba1a97b470306b1c75360449adea2abd325da1. --- js/src/sveltekit/replica.ts | 111 +----------------- tests/e2e-ui/gateway/refresh.mjs | 4 - .../lib/components/shared/AuthRefresh.svelte | 58 +-------- tests/e2e-ui/ui/src/routes/+layout.svelte | 11 +- 4 files changed, 5 insertions(+), 179 deletions(-) diff --git a/js/src/sveltekit/replica.ts b/js/src/sveltekit/replica.ts index 5542999d6..caf785cb4 100644 --- a/js/src/sveltekit/replica.ts +++ b/js/src/sveltekit/replica.ts @@ -80,81 +80,6 @@ export type SveltekitPageDataSessionSource = set(next: TData): void; }>; -function recordSessionDiagnostic(event: Readonly>): void { - const maxEvents = 128; - if (typeof globalThis === 'undefined') return; - const diagnostics = globalThis as typeof globalThis & { - __captureReplicaDiagnostics?: unknown; - __distributedSessionTrace?: unknown; - }; - if (diagnostics.__captureReplicaDiagnostics !== true) return; - if (!Array.isArray(diagnostics.__distributedSessionTrace)) { - diagnostics.__distributedSessionTrace = []; - } - const trace = diagnostics.__distributedSessionTrace as unknown[]; - trace.push(Object.freeze({ time: Date.now(), ...event })); - if (trace.length > maxEvents) trace.splice(0, trace.length - maxEvents); -} - -const sessionDiagnosticCredentialOrdinals = new Map(); -let nextSessionDiagnosticCredentialOrdinal = 1; -const maxSessionDiagnosticCredentials = 32; - -function sessionDiagnosticCredentialOrdinal( - value: Readonly<{ accessToken?: unknown }> | null | undefined -): number | undefined { - if (typeof globalThis === 'undefined') return undefined; - const diagnostics = globalThis as typeof globalThis & { - __captureReplicaDiagnostics?: unknown; - }; - if (diagnostics.__captureReplicaDiagnostics !== true) return undefined; - if (typeof value?.accessToken !== 'string' || value.accessToken.length === 0) { - return undefined; - } - let ordinal = sessionDiagnosticCredentialOrdinals.get(value.accessToken); - if (ordinal === undefined) { - if (sessionDiagnosticCredentialOrdinals.size >= maxSessionDiagnosticCredentials) { - const oldest = sessionDiagnosticCredentialOrdinals.keys().next().value; - if (typeof oldest === 'string') sessionDiagnosticCredentialOrdinals.delete(oldest); - } - ordinal = nextSessionDiagnosticCredentialOrdinal++; - sessionDiagnosticCredentialOrdinals.set(value.accessToken, ordinal); - } - return ordinal; -} - -function sessionDiagnosticSourceOrigin(): string { - if (typeof globalThis === 'undefined') return 'unattributed'; - const diagnostics = globalThis as typeof globalThis & { - __distributedSessionSourceOrigin?: unknown; - }; - return typeof diagnostics.__distributedSessionSourceOrigin === 'string' - ? diagnostics.__distributedSessionSourceOrigin - : 'unattributed'; -} - -function installSessionDiagnosticOrdinalBridge(): void { - if (typeof globalThis === 'undefined') return; - const diagnostics = globalThis as typeof globalThis & { - __captureReplicaDiagnostics?: unknown; - __distributedSessionCredentialOrdinal?: unknown; - }; - if (diagnostics.__captureReplicaDiagnostics !== true) return; - diagnostics.__distributedSessionCredentialOrdinal = (value: unknown): number | undefined => { - if (value === null || typeof value !== 'object') return undefined; - const pageData = value as { - accessToken?: unknown; - session?: { accessToken?: unknown } | null; - }; - return sessionDiagnosticCredentialOrdinal({ - accessToken: - typeof pageData.accessToken === 'string' - ? pageData.accessToken - : pageData.session?.accessToken - }); - }; -} - export type SveltekitReplicaHydration = Readonly<{ version: 1; state: import('../replica/index.js').ReplicaDehydratedState; @@ -686,7 +611,6 @@ export function sessionSourceFromPageData( export function createPageDataSessionSource( initial: TData ): SveltekitPageDataSessionSource { - installSessionDiagnosticOrdinalBridge(); let current = initial; const listeners = new Set<() => void>(); const source = Object.freeze({ @@ -702,17 +626,6 @@ export function createPageDataSessionSource( session: sessionSourceFromPageData(source), get: source.get, set(next: TData): void { - const pageData = next as SveltekitDistributedPageData; - const auth = authFromPageData(next); - recordSessionDiagnostic({ - kind: 'page-data-set', - origin: sessionDiagnosticSourceOrigin(), - credentialOrdinal: sessionDiagnosticCredentialOrdinal(auth), - hasHydration: pageData.distributed !== undefined, - hasAuthority: pageData.distributedAuthority !== undefined, - hasSession: next.session !== null && next.session !== undefined, - hasAccessToken: typeof pageData.accessToken === 'string' - }); current = next; for (const listener of [...listeners]) listener(); } @@ -1125,17 +1038,16 @@ function createAuthorizationFence( let queue = Promise.resolve(); let disposed = false; const read = (): Promise => { - const sourceOrigin = sessionDiagnosticSourceOrigin(); const candidate = Promise.resolve().then(() => { // Capture the credential and its independent server transfer together, // before another source notification can replace either value. const credential = source.getAuth(); const transfer = source.getHydration?.(); - return Promise.resolve(credential).then((auth) => ({ auth, transfer, sourceOrigin })); + return Promise.resolve(credential).then((auth) => ({ auth, transfer })); }); const transition = queue.then(async () => { try { - const { auth, transfer, sourceOrigin } = await candidate; + const { auth, transfer } = await candidate; const next = snapshotAuthCredential(auth); if ( current !== undefined && @@ -1144,24 +1056,7 @@ function createAuthorizationFence( const freshTransfer = transfer !== undefined && !seenHydrations.has(transfer.hydration) && !seenAuthorities.has(transfer.authority); - const retained = freshTransfer && refresh(transfer); - recordSessionDiagnostic({ - kind: 'auth-credential-change', - sourceOrigin, - previousCredentialOrdinal: sessionDiagnosticCredentialOrdinal(current), - nextCredentialOrdinal: sessionDiagnosticCredentialOrdinal(next), - hasTransfer: transfer !== undefined, - freshTransfer, - retained, - reason: retained - ? 'fresh-transfer-retained' - : transfer === undefined - ? 'missing-transfer' - : !freshTransfer - ? 'replayed-transfer' - : 'refresh-rejected' - }); - if (!retained) invalidate(); + if (!freshTransfer || !refresh(transfer)) invalidate(); } current = next; if (transfer !== undefined) { diff --git a/tests/e2e-ui/gateway/refresh.mjs b/tests/e2e-ui/gateway/refresh.mjs index 6182477a2..c5895a35f 100644 --- a/tests/e2e-ui/gateway/refresh.mjs +++ b/tests/e2e-ui/gateway/refresh.mjs @@ -59,10 +59,6 @@ export async function verifySessionRefreshContinuity(page, origin) { const lost = await page.evaluate(()=>globalThis.__refreshContinuity.lost); if (lost) { console.error('Redacted refresh replica diagnostics:', JSON.stringify(await page.evaluate(()=>globalThis.__replicaDiagnosticSnapshot?.()))); - console.error('Redacted refresh lifecycle trace:', JSON.stringify(await page.evaluate(() => ({ - refresh: globalThis.__distributedRefreshTrace ?? [], - session: globalThis.__distributedSessionTrace ?? [] - })))); } assert.equal(lost,false,route+' rows were removed during token refresh: '+JSON.stringify(await page.evaluate(()=>globalThis.__refreshContinuity.events))); } finally { diff --git a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte index e970f89d2..0f32da8b8 100644 --- a/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte +++ b/tests/e2e-ui/ui/src/lib/components/shared/AuthRefresh.svelte @@ -13,48 +13,6 @@ let refreshTimer: number | undefined; let retryTimer: number | undefined; - function traceRefresh(event: Readonly>) { - const maxEvents = 64; - const diagnostics = globalThis as typeof globalThis & { - __captureReplicaDiagnostics?: unknown; - __distributedRefreshTrace?: unknown; - }; - if (diagnostics.__captureReplicaDiagnostics !== true) return; - if (!Array.isArray(diagnostics.__distributedRefreshTrace)) { - diagnostics.__distributedRefreshTrace = []; - } - const trace = diagnostics.__distributedRefreshTrace as unknown[]; - trace.push({ - time: performance.now(), - ...event - }); - if (trace.length > maxEvents) trace.splice(0, trace.length - maxEvents); - } - - function withSessionSource(origin: string, action: () => T): T { - const diagnostics = globalThis as typeof globalThis & { - __captureReplicaDiagnostics?: unknown; - __distributedSessionSourceOrigin?: unknown; - }; - if (diagnostics.__captureReplicaDiagnostics !== true) return action(); - const previous = diagnostics.__distributedSessionSourceOrigin; - diagnostics.__distributedSessionSourceOrigin = origin; - try { - return action(); - } finally { - diagnostics.__distributedSessionSourceOrigin = previous; - } - } - - function credentialOrdinal(value: unknown): number | undefined { - const diagnostics = globalThis as typeof globalThis & { - __distributedSessionCredentialOrdinal?: unknown; - }; - return typeof diagnostics.__distributedSessionCredentialOrdinal === 'function' - ? (diagnostics.__distributedSessionCredentialOrdinal as (value: unknown) => number | undefined)(value) - : undefined; - } - function clearTimers() { if (refreshTimer !== undefined) window.clearTimeout(refreshTimer); if (retryTimer !== undefined) window.clearTimeout(retryTimer); @@ -64,7 +22,6 @@ async function refreshSession() { try { - traceRefresh({ kind: 'refresh-start' }); const response = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'same-origin', @@ -81,24 +38,11 @@ if (response.ok) { const result = await response.json(); - traceRefresh({ - kind: 'refresh-response', - status: response.status, - hasPageData: Boolean(result.pageData), - hasDistributed: result.pageData?.distributed !== undefined, - hasAuthority: result.pageData?.distributedAuthority !== undefined, - credentialOrdinal: credentialOrdinal(result.pageData) - }); - if (result.pageData) { - withSessionSource('refresh-response', () => onRefresh(result.pageData)); - } - if (result.pageData) traceRefresh({ kind: 'refresh-seed-applied' }); + if (result.pageData) onRefresh(result.pageData); } if (response.ok || response.status === 401) { - traceRefresh({ kind: 'invalidate-all-start', status: response.status }); await invalidateAll(); - traceRefresh({ kind: 'invalidate-all-complete', status: response.status }); return; } } catch (error) { diff --git a/tests/e2e-ui/ui/src/routes/+layout.svelte b/tests/e2e-ui/ui/src/routes/+layout.svelte index 828ced000..cd8bb97f4 100644 --- a/tests/e2e-ui/ui/src/routes/+layout.svelte +++ b/tests/e2e-ui/ui/src/routes/+layout.svelte @@ -68,16 +68,7 @@ }); function applyPageData(next: SveltekitDistributedPageData) { - const diagnostics = globalThis as typeof globalThis & Record; - const previousSourceOrigin = diagnostics.__distributedSessionSourceOrigin; - if (diagnostics.__captureReplicaDiagnostics === true) { - diagnostics.__distributedSessionSourceOrigin = 'sveltekit-data'; - } - try { - pageData.set(next); - } finally { - diagnostics.__distributedSessionSourceOrigin = previousSourceOrigin; - } + pageData.set(next); if ( next.distributed === undefined || next.distributedAuthority === undefined || From c711d4ba3f90b068145d914f2705a035c7229147 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 06:16:44 -0500 Subject: [PATCH 086/484] fix: preserve CLI identity for lifecycle children --- distributed_cli/README.md | 7 ++ distributed_cli/src/cli.rs | 9 +- distributed_cli/src/lifecycle/build.rs | 59 ++++++++++++- distributed_cli/src/lifecycle/dev.rs | 1 + distributed_cli/src/lifecycle/mod.rs | 5 ++ distributed_cli/src/lifecycle/project.rs | 26 +++++- js/src/sveltekit/vite.ts | 35 +++++++- js/tests/sveltekit-vite.test.mjs | 108 +++++++++++++++++++++++ 8 files changed, 240 insertions(+), 10 deletions(-) diff --git a/distributed_cli/README.md b/distributed_cli/README.md index 95ff55e7e..bf7747f4a 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -69,6 +69,13 @@ after an upgrade so every member receives the matching lifecycle contract. Rust binaries remain in Cargo's target directory and SvelteKit output remains in its adapter-selected output directory. +The discovered lifecycle also carries the absolute executable that initiated the +CLI through its trusted compiler and UI child processes. Generated client +commands therefore use that exact binary even when another `distributed` +executable appears earlier on `PATH`, regardless of a project-local command +override. Standalone Vite integrations retain their documented command setting +and fallback behavior. + Use `--output json` for a machine-readable lifecycle report. The compatibility flags `--root`, `--catalog`, and `--config` exist for older low-level lifecycle fixtures; normal application builds do not use them. diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index 0ca5b3757..edc3a0eed 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -1074,7 +1074,7 @@ fn run_project_ui_script( if if_present { command.arg("--if-present"); } - let status = command + command .current_dir(ui_root) .env("DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE", "1") .env("DISTRIBUTED_LIFECYCLE_PROJECT_ROOT", &project.plan.root) @@ -1082,8 +1082,11 @@ fn run_project_ui_script( .env( "DISTRIBUTED_LIFECYCLE_GENERATION_ID", &generation.generation_id, - ) - .status()?; + ); + if let Some(executable) = project.plan.cli_executable.as_deref() { + command.env(crate::lifecycle::LIFECYCLE_CLI_EXECUTABLE_ENV, executable); + } + let status = command.status()?; if !status.success() { return Err(format!("SvelteKit UI `{script}` failed with {status}").into()); } diff --git a/distributed_cli/src/lifecycle/build.rs b/distributed_cli/src/lifecycle/build.rs index 2779de55f..2f3f65a61 100644 --- a/distributed_cli/src/lifecycle/build.rs +++ b/distributed_cli/src/lifecycle/build.rs @@ -17,7 +17,7 @@ use super::{ digest_bytes, validate_content_identity, validate_portable_path, validate_stable_value, ArtifactNodeReceipt, DistributedSourceIdentity, GenerationManifest, LifecycleConfig, LifecycleDevConfig, LifecycleError, LifecycleGraph, ReleaseManifest, - LIFECYCLE_CONFIG_SCHEMA_VERSION, + LIFECYCLE_CLI_EXECUTABLE_ENV, LIFECYCLE_CONFIG_SCHEMA_VERSION, }; pub const LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION: u32 = 1; @@ -176,6 +176,9 @@ pub struct LifecycleProjectPlan { pub config: LifecycleBuildConfig, /// Project-relative or absolute content-addressed lifecycle state directory. pub out: PathBuf, + /// Canonical executable that initiated discovered lifecycle work. `None` + /// is retained for the compatibility file-adapter API. + pub(crate) cli_executable: Option, } /// Per-invocation behavior for an already resolved lifecycle project. @@ -278,6 +281,7 @@ pub fn run_lifecycle_build( catalog, config, out: options.out.clone(), + cli_executable: None, }, &LifecycleBuildRequest::from(options), ) @@ -394,6 +398,7 @@ pub fn run_lifecycle_project_build( &node.outputs, executor, request.check, + project.cli_executable.as_deref(), request.cancel.as_deref(), )?; let output_identities = collect_node_outputs(stage.path(), node_id, &graph)?; @@ -641,6 +646,7 @@ fn execute_node( declared_outputs: &BTreeSet, executor: &LifecycleExecutor, check: bool, + cli_executable: Option<&Path>, cancel: Option<&AtomicBool>, ) -> Result<(), LifecycleError> { let root_value = root.to_string_lossy(); @@ -675,9 +681,11 @@ fn execute_node( .env("DISTRIBUTED_LIFECYCLE_ROOT", root) .env("DISTRIBUTED_LIFECYCLE_STAGE", stage) .env("DISTRIBUTED_LIFECYCLE_NODE", node_id) - .env("DISTRIBUTED_LIFECYCLE_CHECK", if check { "1" } else { "0" }) - .stdout(stdout) - .stderr(Stdio::piped()); + .env("DISTRIBUTED_LIFECYCLE_CHECK", if check { "1" } else { "0" }); + if let Some(executable) = cli_executable { + command.env(LIFECYCLE_CLI_EXECUTABLE_ENV, executable); + } + command.stdout(stdout).stderr(Stdio::piped()); let mut child = command.spawn().map_err(|error| { LifecycleError::new(format!( "lifecycle node `{node_id}` failed to start executor `{}`: {error}", @@ -1373,6 +1381,49 @@ mod tests { use super::*; use crate::lifecycle::graph::LifecycleErrorReason; + #[cfg(unix)] + #[test] + fn lifecycle_executor_receives_exact_cli_path_including_spaces() { + use std::os::unix::fs::PermissionsExt; + + let fixture = tempfile::tempdir().expect("create executor fixture"); + let stage = fixture.path().join("stage"); + fs::create_dir_all(&stage).expect("create executor stage"); + let script = fixture.path().join("print-cli.sh"); + fs::write( + &script, + "#!/bin/sh\nprintf '%s' \"$DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE\"\n", + ) + .expect("write executor script"); + let mut permissions = fs::metadata(&script).unwrap().permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&script, permissions).expect("make executor executable"); + let cli = fixture.path().join("cli with spaces").join("distributed"); + let mut outputs = BTreeSet::new(); + outputs.insert("cli-path.txt".to_string()); + + execute_node( + fixture.path(), + &stage, + "clients", + &outputs, + &LifecycleExecutor { + identity: "sha256:executor".to_string(), + program: script.to_string_lossy().into_owned(), + args: Vec::new(), + stdout: Some("cli-path.txt".to_string()), + }, + false, + Some(&cli), + None, + ) + .expect("executor should receive the initiating CLI identity"); + assert_eq!( + fs::read_to_string(stage.join("cli-path.txt")).unwrap(), + cli.to_string_lossy() + ); + } + #[test] fn activation_rejects_an_advanced_generation() { let fixture = tempfile::tempdir().expect("create activation fixture"); diff --git a/distributed_cli/src/lifecycle/dev.rs b/distributed_cli/src/lifecycle/dev.rs index 068a8212a..af615294a 100644 --- a/distributed_cli/src/lifecycle/dev.rs +++ b/distributed_cli/src/lifecycle/dev.rs @@ -255,6 +255,7 @@ pub fn run_lifecycle_dev( catalog, config, out: options.build.out.clone(), + cli_executable: None, }, build: LifecycleBuildRequest::from(&options.build), stop: Arc::clone(&options.stop), diff --git a/distributed_cli/src/lifecycle/mod.rs b/distributed_cli/src/lifecycle/mod.rs index 887edab69..60994496f 100644 --- a/distributed_cli/src/lifecycle/mod.rs +++ b/distributed_cli/src/lifecycle/mod.rs @@ -10,6 +10,11 @@ mod project; mod receipt; mod release; +/// Internal process contract carrying the canonical CLI that initiated a +/// discovered lifecycle. It is deliberately not part of user-authored +/// lifecycle configuration. +pub(crate) const LIFECYCLE_CLI_EXECUTABLE_ENV: &str = "DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE"; + pub use build::{ activate_lifecycle_project_generation, run_lifecycle_build, run_lifecycle_project_build, BuildDrift, LifecycleActivation, LifecycleBuildConfig, LifecycleBuildOptions, diff --git a/distributed_cli/src/lifecycle/project.rs b/distributed_cli/src/lifecycle/project.rs index 71716d137..5aeba7a0f 100644 --- a/distributed_cli/src/lifecycle/project.rs +++ b/distributed_cli/src/lifecycle/project.rs @@ -20,7 +20,7 @@ use crate::js_framework::{ use super::{ digest_bytes, DistributedSourceIdentity, LifecycleBuildConfig, LifecycleDevConfig, LifecycleDevProbe, LifecycleDevProcess, LifecycleError, LifecycleExecutor, - LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, + LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, LIFECYCLE_CLI_EXECUTABLE_ENV, }; const APPLICATION_NODE: &str = "application"; @@ -409,6 +409,7 @@ pub fn discover_lifecycle_project( catalog, config, out: root.join(out.unwrap_or_else(|| Path::new(".distributed/lifecycle"))), + cli_executable: Some(executable.clone()), }, }) } @@ -1069,6 +1070,10 @@ fn lifecycle_dev( ), ("AUTH_URL".to_string(), ui_url.clone()), ("AUTH_USE_SECURE_COOKIES".to_string(), "false".to_string()), + ( + LIFECYCLE_CLI_EXECUTABLE_ENV.to_string(), + executable.to_string_lossy().into_owned(), + ), ]); if lifecycle_owns_client_compile { ui_env.insert( @@ -1134,7 +1139,10 @@ fn lifecycle_dev( args, cwd: None, external_cwd: false, - env: BTreeMap::new(), + env: BTreeMap::from([( + LIFECYCLE_CLI_EXECUTABLE_ENV.to_string(), + executable.to_string_lossy().into_owned(), + )]), url: None, restart_on: BTreeSet::new(), ready_after_ms: 100, @@ -1360,6 +1368,13 @@ mod tests { .find(|args| args[0] == "--project-root") .map(|args| args[1].as_str()); assert_eq!(project_root, application.to_str()); + assert_eq!( + framework + .env + .get(LIFECYCLE_CLI_EXECUTABLE_ENV) + .map(String::as_str), + executable.to_str() + ); } #[test] @@ -1472,6 +1487,13 @@ mod tests { .map(String::as_str), project.path().to_str() ); + assert_eq!( + process + .env + .get(LIFECYCLE_CLI_EXECUTABLE_ENV) + .map(String::as_str), + executable.to_str() + ); assert!(process.restart_on.is_empty()); } diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 73d4fdf50..1c88f7b45 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -61,6 +61,7 @@ const MODULE_NAME = /^\$distributed(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/; const COMPILER_LOCK = join('.svelte-kit', 'distributed', 'compiler.lock'); const GENERATION_META = 'distributed-generation'; const MAX_LIFECYCLE_STATE_BYTES = 1024 * 1024; +const LIFECYCLE_CLI_EXECUTABLE_ENV = 'DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE'; const COMPILER_COORDINATORS = Symbol.for( '@hops-ops/distributed/sveltekit/compiler-coordinators/v1' ); @@ -951,7 +952,39 @@ function resolveIntegration( throw new TypeError('distributedSvelteKit requires configuration'); } const cwd = resolve(options.cwd ?? fallbackCwd); - const command = (options.command ?? 'distributed').trim(); + const lifecycleExecutable = process.env[LIFECYCLE_CLI_EXECUTABLE_ENV]; + const lifecycleRoot = process.env.DISTRIBUTED_LIFECYCLE_ROOT; + const lifecycleStage = process.env.DISTRIBUTED_LIFECYCLE_STAGE; + const hasLifecycleStage = lifecycleRoot !== undefined || lifecycleStage !== undefined; + const hasLifecycleOwnership = + process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE === '1'; + const lifecycleContext = hasLifecycleStage || hasLifecycleOwnership; + const validLifecyclePath = (value: string | undefined): value is string => + value !== undefined && + value.length > 0 && + value === value.trim() && + isAbsolute(value) && + !/[\u0000-\u001f\u007f]/.test(value); + let command: string; + if (lifecycleContext) { + if (!validLifecyclePath(lifecycleExecutable)) { + throw new TypeError( + 'Distributed lifecycle requires an absolute initiating executable identity' + ); + } + if ( + hasLifecycleStage && + (!validLifecyclePath(lifecycleRoot) || !validLifecyclePath(lifecycleStage)) + ) { + throw new TypeError( + 'Distributed lifecycle requires absolute root and stage identities' + ); + } + command = lifecycleExecutable; + } else { + command = options.command ?? 'distributed'; + } + command = command.trim(); if (command.length === 0) { throw new TypeError('Distributed SvelteKit command must not be empty'); } diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index 19baa475c..1b3add41a 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -920,6 +920,107 @@ test('lifecycle generation writes only to the immutable candidate stage', async ); }); +test('lifecycle compiler uses the initiating absolute CLI over an older PATH binary', async (t) => { + const { root, script, log } = await fixture(t); + const pathRoot = join(root, 'cli with spaces'); + const cli = join(pathRoot, 'distributed'); + const oldPathLog = join(root, 'old-path.log'); + await mkdir(pathRoot, { recursive: true }); + await symlink(process.execPath, cli); + const oldPath = join(root, 'older-path-bin'); + await mkdir(oldPath, { recursive: true }); + const oldDistributed = join(oldPath, 'distributed'); + await writeFile( + oldDistributed, + `#!/bin/sh\nprintf '%s\\n' "$*" >> "${oldPathLog}"\nprintf '%s\\n' 'older distributed executable selected' >&2\nexit 91\n`, + { encoding: 'utf8', mode: 0o755 } + ); + const previousPath = process.env.PATH; + const previousCli = process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + const previousLifecycleRoot = process.env.DISTRIBUTED_LIFECYCLE_ROOT; + const previousLifecycleStage = process.env.DISTRIBUTED_LIFECYCLE_STAGE; + process.env.PATH = `${oldPath}${process.platform === 'win32' ? ';' : ':'}${previousPath ?? ''}`; + process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = cli; + process.env.DISTRIBUTED_LIFECYCLE_ROOT = root; + process.env.DISTRIBUTED_LIFECYCLE_STAGE = join(root, '.distributed/lifecycle-stage'); + await mkdir(join(root, '.distributed/lifecycle-stage'), { recursive: true }); + t.after(() => { + if (previousPath === undefined) delete process.env.PATH; + else process.env.PATH = previousPath; + if (previousCli === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + else process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = previousCli; + if (previousLifecycleRoot === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_ROOT; + else process.env.DISTRIBUTED_LIFECYCLE_ROOT = previousLifecycleRoot; + if (previousLifecycleStage === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_STAGE; + else process.env.DISTRIBUTED_LIFECYCLE_STAGE = previousLifecycleStage; + }); + + await generateDistributedSvelteKitLifecycle( + { + cwd: root, + command: oldDistributed, + commandArgs: [script], + clients: clients() + }, + { projectRoot: root, stage: join(root, '.distributed/lifecycle-stage') } + ); + + assert.deepEqual( + (await commandLog(log)).map((args) => args[0]), + ['client-manifest', 'client', 'client-manifest', 'client'] + ); + await assert.rejects(readFile(oldPathLog), (error) => error?.code === 'ENOENT'); +}); + +test('lifecycle compiler fails closed when its initiating CLI identity is missing or relative', async (t) => { + const { root, script } = await fixture(t); + const stage = join(root, '.distributed/lifecycle-stage'); + await mkdir(stage, { recursive: true }); + const previousCli = process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + const previousClientOwnership = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + const previousLifecycleRoot = process.env.DISTRIBUTED_LIFECYCLE_ROOT; + const previousLifecycleStage = process.env.DISTRIBUTED_LIFECYCLE_STAGE; + process.env.DISTRIBUTED_LIFECYCLE_ROOT = root; + process.env.DISTRIBUTED_LIFECYCLE_STAGE = stage; + t.after(() => { + if (previousCli === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + else process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = previousCli; + if (previousLifecycleRoot === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_ROOT; + else process.env.DISTRIBUTED_LIFECYCLE_ROOT = previousLifecycleRoot; + if (previousLifecycleStage === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_STAGE; + else process.env.DISTRIBUTED_LIFECYCLE_STAGE = previousLifecycleStage; + if (previousClientOwnership === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + else process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = previousClientOwnership; + }); + process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = '1'; + delete process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + await assert.rejects( + generateDistributedSvelteKitLifecycle( + { cwd: root, command: process.execPath, commandArgs: [script], clients: clients() }, + { projectRoot: root, stage } + ), + /requires an absolute initiating executable identity/ + ); + delete process.env.DISTRIBUTED_LIFECYCLE_ROOT; + delete process.env.DISTRIBUTED_LIFECYCLE_STAGE; + await assert.rejects( + generateDistributedSvelteKit( + { cwd: root, command: process.execPath, commandArgs: [script], clients: clients() } + ), + /requires an absolute initiating executable identity/ + ); + process.env.DISTRIBUTED_LIFECYCLE_ROOT = root; + process.env.DISTRIBUTED_LIFECYCLE_STAGE = stage; + process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = 'relative/distributed'; + await assert.rejects( + generateDistributedSvelteKitLifecycle( + { cwd: root, command: process.execPath, commandArgs: [script], clients: clients() }, + { projectRoot: root, stage } + ), + /requires an absolute initiating executable identity/ + ); +}); + test('Vite compiles and resolves isolated user/admin physical entrypoints', async (t) => { const { root, script, log } = await fixture(t); const options = pluginOptions(root, script); @@ -1109,6 +1210,7 @@ test('supervised Vite defers generated-client compilation to the lifecycle', asy t.after(() => rm(lifecycleRoot, { recursive: true, force: true })); const previousLifecycle = process.env.DISTRIBUTED_LIFECYCLE_DIR; const previousClientOwnership = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + const previousCliExecutable = process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; const previousProjectRoot = process.env.DISTRIBUTED_LIFECYCLE_PROJECT_ROOT; const generation = `sha256:${'a'.repeat(64)}`; const activePointer = join(lifecycleRoot, 'active.json'); @@ -1125,6 +1227,7 @@ test('supervised Vite defers generated-client compilation to the lifecycle', asy ); process.env.DISTRIBUTED_LIFECYCLE_DIR = lifecycleRoot; process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = '1'; + process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = process.execPath; process.env.DISTRIBUTED_LIFECYCLE_PROJECT_ROOT = root; t.after(() => { if (previousLifecycle === undefined) { @@ -1137,6 +1240,11 @@ test('supervised Vite defers generated-client compilation to the lifecycle', asy } else { process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = previousClientOwnership; } + if (previousCliExecutable === undefined) { + delete process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + } else { + process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = previousCliExecutable; + } if (previousProjectRoot === undefined) { delete process.env.DISTRIBUTED_LIFECYCLE_PROJECT_ROOT; } else { From c947fcd3c0c77b2f6dd1d958e1ce04da1c0e83a0 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 06:30:04 -0500 Subject: [PATCH 087/484] fix: normalize lifecycle CLI launcher args --- js/src/sveltekit/vite.ts | 32 ++++++++++++++++++++++++-------- js/tests/sveltekit-vite.test.mjs | 17 +++++++++++++++-- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 1c88f7b45..7769b38fd 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -1110,19 +1110,22 @@ function resolveIntegration( manifestWatchRoots: Object.freeze(manifestWatchRoots(cwd, client.manifest)) }); }); + const commandArgs = (options.commandArgs ?? []).map((argument, index) => { + if (typeof argument !== 'string') { + throw new TypeError( + `Distributed commandArgs[${index}] must be a string` + ); + } + return argument; + }); return Object.freeze({ cwd, outputRoot: cwd, command, commandArgs: Object.freeze( - (options.commandArgs ?? []).map((argument, index) => { - if (typeof argument !== 'string') { - throw new TypeError( - `Distributed commandArgs[${index}] must be a string` - ); - } - return argument; - }) + lifecycleContext + ? lifecycleCommandArgs(commandArgs) + : commandArgs ), routesDir, libDir, @@ -1131,6 +1134,19 @@ function resolveIntegration( }); } +/** + * A lifecycle-owned UI may inherit a Cargo launcher prefix from the app's + * standalone Vite configuration (`cargo run ... --`). Once the trusted + * initiating executable replaces Cargo, only the arguments after that + * separator belong to the executable. Direct executable arguments remain + * unchanged; this keeps non-Cargo lifecycle integrations explicit. + */ +function lifecycleCommandArgs(args: readonly string[]): readonly string[] { + if (args[0] !== 'run') return args; + const separator = args.indexOf('--'); + return separator === -1 ? args : args.slice(separator + 1); +} + function relocateLifecycleOutputs( integration: ResolvedIntegration, lifecycle: Readonly<{ projectRoot: string; stage: string }> diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index 1b3add41a..c11e28d3d 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -958,8 +958,21 @@ test('lifecycle compiler uses the initiating absolute CLI over an older PATH bin await generateDistributedSvelteKitLifecycle( { cwd: root, - command: oldDistributed, - commandArgs: [script], + // The app's standalone config uses Cargo as its launcher. Lifecycle + // ownership must replace Cargo and retain only the suffix after `--`. + command: 'cargo', + commandArgs: [ + 'run', + '--quiet', + '--manifest-path', + join(root, 'Cargo.toml'), + '-p', + 'distributed_cli', + '--bin', + 'distributed', + '--', + script + ], clients: clients() }, { projectRoot: root, stage: join(root, '.distributed/lifecycle-stage') } From 0d0335804efd3391a2a91a5a48a327312a2297f5 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 06:32:27 -0500 Subject: [PATCH 088/484] fix: bind lifecycle wrapper normalization to cargo --- js/src/sveltekit/vite.ts | 25 ++++++++++++--- js/tests/sveltekit-vite.test.mjs | 53 ++++++++++++++++++++++++++++++-- 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 7769b38fd..edbc44426 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -959,6 +959,7 @@ function resolveIntegration( const hasLifecycleOwnership = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE === '1'; const lifecycleContext = hasLifecycleStage || hasLifecycleOwnership; + const configuredCommand = options.command ?? 'distributed'; const validLifecyclePath = (value: string | undefined): value is string => value !== undefined && value.length > 0 && @@ -982,7 +983,7 @@ function resolveIntegration( } command = lifecycleExecutable; } else { - command = options.command ?? 'distributed'; + command = configuredCommand; } command = command.trim(); if (command.length === 0) { @@ -1124,7 +1125,7 @@ function resolveIntegration( command, commandArgs: Object.freeze( lifecycleContext - ? lifecycleCommandArgs(commandArgs) + ? lifecycleCommandArgs(configuredCommand, commandArgs) : commandArgs ), routesDir, @@ -1141,10 +1142,24 @@ function resolveIntegration( * separator belong to the executable. Direct executable arguments remain * unchanged; this keeps non-Cargo lifecycle integrations explicit. */ -function lifecycleCommandArgs(args: readonly string[]): readonly string[] { - if (args[0] !== 'run') return args; +function lifecycleCommandArgs( + configuredCommand: string, + args: readonly string[] +): readonly string[] { + const launcher = basename(configuredCommand).replace(/\.exe$/i, ''); + if (launcher !== 'cargo') return args; + if (args[0] !== 'run') { + throw new TypeError( + 'Distributed lifecycle Cargo launcher arguments must begin with `run`' + ); + } const separator = args.indexOf('--'); - return separator === -1 ? args : args.slice(separator + 1); + if (separator === -1) { + throw new TypeError( + 'Distributed lifecycle Cargo launcher arguments must contain `--`' + ); + } + return args.slice(separator + 1); } function relocateLifecycleOutputs( diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index c11e28d3d..487cb328b 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -958,8 +958,43 @@ test('lifecycle compiler uses the initiating absolute CLI over an older PATH bin await generateDistributedSvelteKitLifecycle( { cwd: root, - // The app's standalone config uses Cargo as its launcher. Lifecycle - // ownership must replace Cargo and retain only the suffix after `--`. + command: oldDistributed, + commandArgs: [script], + clients: clients() + }, + { projectRoot: root, stage: join(root, '.distributed/lifecycle-stage') } + ); + + assert.deepEqual( + (await commandLog(log)).map((args) => args[0]), + ['client-manifest', 'client', 'client-manifest', 'client'] + ); + await assert.rejects(readFile(oldPathLog), (error) => error?.code === 'ENOENT'); +}); + +test('lifecycle compiler replaces an explicit Cargo launcher with the initiating CLI', async (t) => { + const { root, script, log } = await fixture(t); + const cli = join(root, 'distributed'); + await symlink(process.execPath, cli); + const previousCli = process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + const previousLifecycleRoot = process.env.DISTRIBUTED_LIFECYCLE_ROOT; + const previousLifecycleStage = process.env.DISTRIBUTED_LIFECYCLE_STAGE; + process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = cli; + process.env.DISTRIBUTED_LIFECYCLE_ROOT = root; + process.env.DISTRIBUTED_LIFECYCLE_STAGE = join(root, '.distributed/lifecycle-stage'); + await mkdir(join(root, '.distributed/lifecycle-stage'), { recursive: true }); + t.after(() => { + if (previousCli === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; + else process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE = previousCli; + if (previousLifecycleRoot === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_ROOT; + else process.env.DISTRIBUTED_LIFECYCLE_ROOT = previousLifecycleRoot; + if (previousLifecycleStage === undefined) delete process.env.DISTRIBUTED_LIFECYCLE_STAGE; + else process.env.DISTRIBUTED_LIFECYCLE_STAGE = previousLifecycleStage; + }); + + await generateDistributedSvelteKitLifecycle( + { + cwd: root, command: 'cargo', commandArgs: [ 'run', @@ -982,7 +1017,19 @@ test('lifecycle compiler uses the initiating absolute CLI over an older PATH bin (await commandLog(log)).map((args) => args[0]), ['client-manifest', 'client', 'client-manifest', 'client'] ); - await assert.rejects(readFile(oldPathLog), (error) => error?.code === 'ENOENT'); + + await assert.rejects( + generateDistributedSvelteKitLifecycle( + { + cwd: root, + command: 'cargo', + commandArgs: ['run', '--quiet', script], + clients: clients() + }, + { projectRoot: root, stage: join(root, '.distributed/lifecycle-stage') } + ), + /Cargo launcher arguments must contain `--`/ + ); }); test('lifecycle compiler fails closed when its initiating CLI identity is missing or relative', async (t) => { From 224dce82ba717908eedf9ff3d81d0075836ac51e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 06:38:00 -0500 Subject: [PATCH 089/484] fix: ignore launcher prefixes in lifecycle mode --- js/src/sveltekit/vite.ts | 44 ++++++++------------------------ js/tests/sveltekit-vite.test.mjs | 32 +++++++++-------------- 2 files changed, 23 insertions(+), 53 deletions(-) diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index edbc44426..1d72ea99a 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -127,7 +127,11 @@ export type DistributedSvelteKitViteOptions = Readonly<{ cwd?: string; /** Executable invoked without a shell. Defaults to `distributed`. */ command?: string; - /** Prefix argv, e.g. `cargo run ... --`; never interpreted by a shell. */ + /** + * Prefix argv for standalone command execution, e.g. `cargo run ... --`; + * never interpreted by a shell. Lifecycle-owned compilation invokes the + * trusted initiating executable directly and ignores this launcher prefix. + */ commandArgs?: readonly string[]; /** SvelteKit route source root. Defaults to `src/routes`. */ routesDir?: string; @@ -1123,11 +1127,12 @@ function resolveIntegration( cwd, outputRoot: cwd, command, - commandArgs: Object.freeze( - lifecycleContext - ? lifecycleCommandArgs(configuredCommand, commandArgs) - : commandArgs - ), + // A lifecycle-owned compile must be an invocation of the trusted + // initiating executable itself. A configured standalone prefix (most + // commonly `cargo run ... --`) belongs to the app's direct Vite mode; + // carrying it across would make the initiating binary parse launcher + // arguments as its own command and can select a different binary. + commandArgs: Object.freeze(lifecycleContext ? [] : commandArgs), routesDir, libDir, aliases, @@ -1135,33 +1140,6 @@ function resolveIntegration( }); } -/** - * A lifecycle-owned UI may inherit a Cargo launcher prefix from the app's - * standalone Vite configuration (`cargo run ... --`). Once the trusted - * initiating executable replaces Cargo, only the arguments after that - * separator belong to the executable. Direct executable arguments remain - * unchanged; this keeps non-Cargo lifecycle integrations explicit. - */ -function lifecycleCommandArgs( - configuredCommand: string, - args: readonly string[] -): readonly string[] { - const launcher = basename(configuredCommand).replace(/\.exe$/i, ''); - if (launcher !== 'cargo') return args; - if (args[0] !== 'run') { - throw new TypeError( - 'Distributed lifecycle Cargo launcher arguments must begin with `run`' - ); - } - const separator = args.indexOf('--'); - if (separator === -1) { - throw new TypeError( - 'Distributed lifecycle Cargo launcher arguments must contain `--`' - ); - } - return args.slice(separator + 1); -} - function relocateLifecycleOutputs( integration: ResolvedIntegration, lifecycle: Readonly<{ projectRoot: string; stage: string }> diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index 487cb328b..54969e806 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -138,8 +138,14 @@ process.stdout.write('generated fake client\n'); async function fixture(t) { const root = await mkdtemp(join(tmpdir(), 'distributed-vite-test-')); const script = join(root, 'fake-distributed.mjs'); + const executable = join(root, 'fake-distributed'); const log = join(root, 'commands.log'); await writeFile(script, fakeDistributedSource, 'utf8'); + await writeFile( + executable, + `#!/usr/bin/env node\nawait import(${JSON.stringify(pathToFileURL(script).href)});\n`, + { encoding: 'utf8', mode: 0o755 } + ); await writeFile(log, '', 'utf8'); await mkdir(join(root, 'src/routes/todos'), { recursive: true }); await mkdir(join(root, 'src/routes/admin'), { recursive: true }); @@ -174,7 +180,7 @@ async function fixture(t) { } await rm(root, { recursive: true, force: true }); }); - return { root, script, log }; + return { root, script, executable, log }; } function clients() { @@ -921,12 +927,12 @@ test('lifecycle generation writes only to the immutable candidate stage', async }); test('lifecycle compiler uses the initiating absolute CLI over an older PATH binary', async (t) => { - const { root, script, log } = await fixture(t); + const { root, script, executable, log } = await fixture(t); const pathRoot = join(root, 'cli with spaces'); const cli = join(pathRoot, 'distributed'); const oldPathLog = join(root, 'old-path.log'); await mkdir(pathRoot, { recursive: true }); - await symlink(process.execPath, cli); + await symlink(executable, cli); const oldPath = join(root, 'older-path-bin'); await mkdir(oldPath, { recursive: true }); const oldDistributed = join(oldPath, 'distributed'); @@ -972,10 +978,9 @@ test('lifecycle compiler uses the initiating absolute CLI over an older PATH bin await assert.rejects(readFile(oldPathLog), (error) => error?.code === 'ENOENT'); }); -test('lifecycle compiler replaces an explicit Cargo launcher with the initiating CLI', async (t) => { - const { root, script, log } = await fixture(t); - const cli = join(root, 'distributed'); - await symlink(process.execPath, cli); +test('lifecycle compiler invokes the initiating CLI without a configured launcher prefix', async (t) => { + const { root, script, executable, log } = await fixture(t); + const cli = executable; const previousCli = process.env.DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE; const previousLifecycleRoot = process.env.DISTRIBUTED_LIFECYCLE_ROOT; const previousLifecycleStage = process.env.DISTRIBUTED_LIFECYCLE_STAGE; @@ -1017,19 +1022,6 @@ test('lifecycle compiler replaces an explicit Cargo launcher with the initiating (await commandLog(log)).map((args) => args[0]), ['client-manifest', 'client', 'client-manifest', 'client'] ); - - await assert.rejects( - generateDistributedSvelteKitLifecycle( - { - cwd: root, - command: 'cargo', - commandArgs: ['run', '--quiet', script], - clients: clients() - }, - { projectRoot: root, stage: join(root, '.distributed/lifecycle-stage') } - ), - /Cargo launcher arguments must contain `--`/ - ); }); test('lifecycle compiler fails closed when its initiating CLI identity is missing or relative', async (t) => { From 7f74cced3857feec9055829a580f5f349218d3f7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 08:31:29 -0500 Subject: [PATCH 090/484] fix: carry trusted provenance across cell HTTP --- README.md | 36 +++ src/command_dispatch/host.rs | 290 ++++++++++++++++++++-- src/command_dispatch/mod.rs | 5 +- src/lib.rs | 5 +- tests/causal_wait_path/main.rs | 425 ++++++++++++++++++++++++++++++++- 5 files changed, 731 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 3840938e1..eed9d11de 100644 --- a/README.md +++ b/README.md @@ -1701,6 +1701,42 @@ curl http://localhost:3000/health claim names; handlers read them with `session.get("…")` or map claims to the convenience keys at the edge. +### Authenticated cell wait-path metadata + +An internal command host can carry a small, explicit set of already-authenticated +facts across the private cell HTTP boundary. Do not put producer or operation +claims in `Session`: ordinary cell calls forward only the authenticated user and +role keys. `CellRequestContext` requires an internal HTTP secret and reserves +framework identity and transport-control headers from application metadata. + +```rust,ignore +use distributed::command_dispatch::{ + CellRequestContext, HttpCommandHost, TrustedRequestMetadata, +}; + +let metadata = TrustedRequestMetadata::try_from_pairs([ + ("x-source-kind", "canonical-fact"), +])?; +let context = CellRequestContext::new("writer-service", "principal-partition") + .with_causation_id("0190a000-0000-7000-8000-000000000001") + .with_trusted_metadata(metadata); +let host = HttpCommandHost::new_internal("http://cell.internal", secret)?; +let (_status, body) = host + .post_cell_wait_path_with_context( + "order.submit", + "0190a000-0000-7000-8000-000000000002", + serde_json::json!({ "order_id": "order-1" }), + &session, + &context, + ) + .await?; +``` + +Metadata names must be canonical lowercase and values are bounded visible HTTP +text. Public callers cannot authenticate this path by supplying the reserved +headers themselves; the cell must validate the shared internal secret before +constructing its typed command identity. + ### gRPC Transport (requires `grpc` feature) The `grpc` feature adds a tonic-based gRPC transport using standard protobuf wire format (no `.proto` file needed): diff --git a/src/command_dispatch/host.rs b/src/command_dispatch/host.rs index c7f14b3c5..a4c30da73 100644 --- a/src/command_dispatch/host.rs +++ b/src/command_dispatch/host.rs @@ -1,6 +1,7 @@ //! Causal wait-path host used by GraphQL. Local in-process or HTTP loopback. use async_trait::async_trait; +use reqwest::header::{HeaderName, HeaderValue}; use reqwest::redirect::Policy; use serde_json::Value; use std::sync::Arc; @@ -17,6 +18,174 @@ use crate::microsvc::{ ROLE_KEY, USER_ID_KEY, }; +const MAX_TRUSTED_METADATA_HEADERS: usize = 16; +const MAX_TRUSTED_METADATA_BYTES: usize = 4096; + +/// Explicit metadata a trusted native adapter may carry across a cell HTTP +/// boundary. +/// +/// A [`Session`] is request input and may contain arbitrary transport keys. +/// It is intentionally not used to populate this type. Callers must build the +/// metadata from already-authenticated, canonical facts and pass it through +/// [`HttpCommandHost::post_cell_wait_path_with_context`]. The host rejects +/// framework identity, authorization, transport-control, and hop-by-hop +/// headers before opening the request. +#[derive(Clone, Debug, Default)] +pub struct TrustedRequestMetadata { + headers: Vec<(HeaderName, HeaderValue)>, + bytes: usize, +} + +impl TrustedRequestMetadata { + /// Create empty trusted metadata. + pub fn new() -> Self { + Self::default() + } + + /// Build trusted metadata from an explicit application allowlist. + /// + /// Header names must already be canonical lowercase. Values are limited to + /// visible HTTP header bytes and the total set is bounded to keep a native + /// adapter from turning the cell boundary into an unbounded side channel. + pub fn try_from_pairs(pairs: I) -> Result + where + I: IntoIterator, + K: AsRef, + V: AsRef, + { + let mut metadata = Self::new(); + for (name, value) in pairs { + metadata.try_insert(name.as_ref(), value.as_ref())?; + } + Ok(metadata) + } + + /// Add one explicitly configured metadata header. + pub fn try_insert(&mut self, name: &str, value: &str) -> Result<(), CausalDispatchError> { + if name.is_empty() || name != name.to_ascii_lowercase() { + return Err(CausalDispatchError::BadRequest( + "trusted metadata header names must be non-empty lowercase ASCII".into(), + )); + } + let name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| { + CausalDispatchError::BadRequest("trusted metadata header name is invalid".into()) + })?; + if is_reserved_trusted_metadata_header(name.as_str()) { + return Err(CausalDispatchError::BadRequest(format!( + "trusted metadata cannot override reserved header `{}`", + name.as_str() + ))); + } + if !value + .bytes() + .all(|byte| (0x20..=0x7e).contains(&byte) && byte != b'\r' && byte != b'\n') + { + return Err(CausalDispatchError::BadRequest( + "trusted metadata header values must contain visible HTTP bytes".into(), + )); + } + let value = HeaderValue::from_str(value).map_err(|_| { + CausalDispatchError::BadRequest("trusted metadata header value is invalid".into()) + })?; + if self.headers.iter().any(|(existing, _)| existing == &name) { + return Err(CausalDispatchError::BadRequest(format!( + "trusted metadata header `{}` is duplicated", + name.as_str() + ))); + } + if self.headers.len() >= MAX_TRUSTED_METADATA_HEADERS { + return Err(CausalDispatchError::BadRequest(format!( + "trusted metadata exceeds {} headers", + MAX_TRUSTED_METADATA_HEADERS + ))); + } + let bytes = name.as_str().len().saturating_add(value.as_bytes().len()); + if self.bytes.saturating_add(bytes) > MAX_TRUSTED_METADATA_BYTES { + return Err(CausalDispatchError::BadRequest(format!( + "trusted metadata exceeds {} bytes", + MAX_TRUSTED_METADATA_BYTES + ))); + } + self.bytes = self.bytes.saturating_add(bytes); + self.headers.push((name, value)); + Ok(()) + } + + pub fn is_empty(&self) -> bool { + self.headers.is_empty() + } + + fn apply_to(&self, mut request: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + for (name, value) in &self.headers { + request = request.header(name.clone(), value.clone()); + } + request + } +} + +fn is_reserved_trusted_metadata_header(name: &str) -> bool { + matches!( + name, + USER_ID_KEY + | ROLE_KEY + | CELL_CAUSATION_ID_HEADER + | CELL_INTERNAL_SECRET_HEADER + | CELL_PRINCIPAL_PARTITION_HEADER + | CELL_SERVICE_ID_HEADER + | "authorization" + | "cookie" + | "host" + | "content-length" + | "content-type" + | "connection" + | "keep-alive" + | "proxy-authenticate" + | "proxy-authorization" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + | "forwarded" + | "x-real-ip" + | "traceparent" + | "tracestate" + ) || name.starts_with("x-forwarded-") + || name.starts_with("x-envoy-") + || name.starts_with("x-distributed-") + || name.starts_with("x-celld-") + || name.starts_with("x-cell-") +} + +/// Identity and explicitly trusted metadata used for one internal cell call. +#[derive(Clone, Debug)] +pub struct CellRequestContext { + service_id: String, + principal_partition: String, + causation_id: Option, + trusted_metadata: TrustedRequestMetadata, +} + +impl CellRequestContext { + pub fn new(service_id: impl Into, principal_partition: impl Into) -> Self { + Self { + service_id: service_id.into(), + principal_partition: principal_partition.into(), + causation_id: None, + trusted_metadata: TrustedRequestMetadata::new(), + } + } + + pub fn with_causation_id(mut self, causation_id: impl Into) -> Self { + self.causation_id = Some(causation_id.into()); + self + } + + pub fn with_trusted_metadata(mut self, metadata: TrustedRequestMetadata) -> Self { + self.trusted_metadata = metadata; + self + } +} + /// Wait-path command host. GraphQL mutations call this instead of `Service`. #[async_trait] pub trait CommandHost: Send + Sync { @@ -340,7 +509,7 @@ impl HttpCommandHost { input: Value, session: &Session, ) -> Result<(u16, Value), CausalDispatchError> { - self.post_wait_path_inner(command, command_id, input, session, None, None) + self.post_wait_path_inner(command, command_id, input, session, None) .await } @@ -380,15 +549,32 @@ impl HttpCommandHost { principal_partition: &str, causation_id: Option<&str>, ) -> Result<(u16, Value), CausalDispatchError> { + let mut context = CellRequestContext::new(service_id, principal_partition); + if let Some(causation_id) = causation_id { + context = context.with_causation_id(causation_id); + } + self.post_cell_wait_path_with_context(command, command_id, input, session, &context) + .await + } + + /// POST a cell wait-path command with an explicitly authenticated request + /// context. Custom metadata is carried only through this internal cell + /// path; ordinary public session forwarding remains identity-only. + pub async fn post_cell_wait_path_with_context( + &self, + command: &str, + command_id: &str, + input: Value, + session: &Session, + context: &CellRequestContext, + ) -> Result<(u16, Value), CausalDispatchError> { + if self.internal_secret.is_none() { + return Err(CausalDispatchError::Internal( + "trusted cell metadata requires an internal HTTP secret".into(), + )); + } let first = self - .post_wait_path_inner( - command, - command_id, - input.clone(), - session, - Some((service_id, principal_partition)), - causation_id, - ) + .post_wait_path_inner(command, command_id, input.clone(), session, Some(context)) .await; if !matches!(&first, Ok((status, _)) if *status >= 500) { return first; @@ -399,15 +585,8 @@ impl HttpCommandHost { // producing the response. One replay closes that ambiguous response // window without reapplying the aggregate mutation; persistent // failures still surface unchanged. - self.post_wait_path_inner( - command, - command_id, - input, - session, - Some((service_id, principal_partition)), - causation_id, - ) - .await + self.post_wait_path_inner(command, command_id, input, session, Some(context)) + .await } async fn post_wait_path_inner( @@ -416,8 +595,7 @@ impl HttpCommandHost { command_id: &str, input: Value, session: &Session, - cell_identity: Option<(&str, &str)>, - causation_id: Option<&str>, + context: Option<&CellRequestContext>, ) -> Result<(u16, Value), CausalDispatchError> { let mut request = self.request_json( command, @@ -432,18 +610,22 @@ impl HttpCommandHost { if let Some(roles) = session.get(ROLE_KEY) { request = request.header(ROLE_KEY, roles); } - if let Some((service_id, principal_partition)) = cell_identity { + if let Some(context) = context { if self.internal_secret.is_none() { return Err(CausalDispatchError::Internal( "cell wait-path requires an internal HTTP secret".into(), )); } request = request - .header(CELL_SERVICE_ID_HEADER, service_id) - .header(CELL_PRINCIPAL_PARTITION_HEADER, principal_partition); - if let Some(causation_id) = causation_id { + .header(CELL_SERVICE_ID_HEADER, &context.service_id) + .header( + CELL_PRINCIPAL_PARTITION_HEADER, + &context.principal_partition, + ); + if let Some(causation_id) = &context.causation_id { request = request.header(CELL_CAUSATION_ID_HEADER, causation_id); } + request = context.trusted_metadata.apply_to(request); } let response = request.send().await.map_err(|err| { CausalDispatchError::Internal(format!("wait-path HTTP failed: {err}")) @@ -550,4 +732,64 @@ mod tests { session.set(USER_ID_KEY, "alice"); assert!(validate_principal_session(&session, &principal).is_ok()); } + + #[test] + fn trusted_metadata_rejects_reserved_headers_and_noncanonical_names() { + for name in [ + "x-user-id", + "X-User-Id", + "authorization", + "host", + "content-length", + "connection", + "x-forwarded-for", + CELL_INTERNAL_SECRET_HEADER, + ] { + assert!( + TrustedRequestMetadata::try_from_pairs([(name, "spoofed")]).is_err(), + "reserved or noncanonical header `{name}` must be rejected" + ); + } + } + + #[test] + fn trusted_metadata_enforces_values_duplicates_and_bounds() { + let mut metadata = TrustedRequestMetadata::new(); + metadata.try_insert("x-source", "trusted").unwrap(); + assert!(metadata.try_insert("x-source", "again").is_err()); + assert!(metadata.try_insert("x-control", "line\nfeed").is_err()); + + let too_many = (0..=MAX_TRUSTED_METADATA_HEADERS) + .map(|index| (format!("x-header-{index}"), "value".to_string())) + .collect::>(); + assert!(TrustedRequestMetadata::try_from_pairs(too_many).is_err()); + + let too_large = TrustedRequestMetadata::try_from_pairs([( + "x-large", + "x".repeat(MAX_TRUSTED_METADATA_BYTES), + )]); + assert!(too_large.is_err()); + } + + #[tokio::test] + async fn trusted_metadata_requires_an_internal_cell_host() { + let host = HttpCommandHost::new("http://127.0.0.1:1").unwrap(); + let metadata = TrustedRequestMetadata::try_from_pairs([("x-source", "trusted")]).unwrap(); + let context = + CellRequestContext::new("writer", "partition").with_trusted_metadata(metadata); + let result = host + .post_cell_wait_path_with_context( + "todo.create", + "command-1", + serde_json::json!({ "id": "todo" }), + &Session::new(), + &context, + ) + .await; + assert!(matches!( + result, + Err(CausalDispatchError::Internal(message)) + if message.contains("internal HTTP secret") + )); + } } diff --git a/src/command_dispatch/mod.rs b/src/command_dispatch/mod.rs index 05098cb9f..0e477018f 100644 --- a/src/command_dispatch/mod.rs +++ b/src/command_dispatch/mod.rs @@ -18,7 +18,10 @@ pub use error::CommandDispatchError; #[cfg(feature = "graphql")] pub(crate) use host::{validate_principal_session, validate_principal_session_if_present}; #[cfg(feature = "graphql")] -pub use host::{CommandHost, HttpCommandHost, LocalCommandHost, SharedCommandHost}; +pub use host::{ + CellRequestContext, CommandHost, HttpCommandHost, LocalCommandHost, SharedCommandHost, + TrustedRequestMetadata, +}; pub use local::LocalCommandDispatcher; pub use remote::{ RemoteCommandDispatcher, RemoteDispatchConfig, RemoteTrustMode, diff --git a/src/lib.rs b/src/lib.rs index c2f4fcb21..c84cc9b8a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -85,7 +85,10 @@ pub use command_dispatch::{ SharedCommandDispatcher, APPROVED_REMOTE_DISPATCH_PROFILE, COMMAND_DISPATCH_ENVELOPE_VERSION, }; #[cfg(feature = "graphql")] -pub use command_dispatch::{CommandHost, HttpCommandHost, LocalCommandHost, SharedCommandHost}; +pub use command_dispatch::{ + CellRequestContext, CommandHost, HttpCommandHost, LocalCommandHost, SharedCommandHost, + TrustedRequestMetadata, +}; // Domain events: typed outward contracts distinct from replay events/snapshots. pub use domain_event::{ diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index ab96b78ff..21d0ba10b 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -3,16 +3,25 @@ use std::sync::Arc; +use axum::http::StatusCode; use distributed::bus::{Bus, BusConsumer, InMemoryBus, TransportError}; use distributed::cell_host::{ - CelldCommandHost, CelldRoute, InternalHttpSecret, CELL_CAUSATION_ID_HEADER, + AggregateCell, CellCommandIdentity, CelldCommandHost, CelldRoute, InternalHttpSecret, + CELL_CAUSATION_ID_HEADER, CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, + CELL_SERVICE_ID_HEADER, }; use distributed::command::{ - typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, Succeeded, + typed_command, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, + PreparedCommand, Succeeded, +}; +use distributed::command_dispatch::{ + CellRequestContext, CommandHost, HttpCommandHost, SharedCommandHost, TrustedRequestMetadata, }; -use distributed::command_dispatch::{CommandHost, HttpCommandHost, SharedCommandHost}; use distributed::graphql::VerifiedPrincipal; -use distributed::microsvc::{router, Routes, Service, ROLE_KEY, USER_ID_KEY}; +use distributed::microsvc::{ + router, CausalCommandContext, HandlerError, PortableCommand, Routes, Service, Session, + ROLE_KEY, USER_ID_KEY, +}; use distributed::{Aggregate, AggregateBuilder, Entity, InMemoryRepository, Snapshot}; #[cfg(feature = "sqlite")] use distributed::{AggregateRepository, SqliteRepository}; @@ -20,6 +29,8 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use serde_json::Value; +const TRUSTED_CAUSATION_ID: &str = "0190a000-0000-7000-8000-000000000999"; + #[derive(Default, Snapshot)] struct WaitAgg { entity: Entity, @@ -137,6 +148,54 @@ fn wait_service() -> Arc { wait_service_with_repo(InMemoryRepository::new()) } +async fn handle_trusted_create( + ctx: &CausalCommandContext<'_, WaitAgg>, + input: IdInput, +) -> Result>, HandlerError> { + let trusted = [ + ("x-producer", "canonical-fact"), + (CELL_SERVICE_ID_HEADER, "generic-writer"), + (CELL_PRINCIPAL_PARTITION_HEADER, "generic-partition"), + (CELL_CAUSATION_ID_HEADER, TRUSTED_CAUSATION_ID), + ] + .into_iter() + .all(|(key, expected)| ctx.claim(key) == Some(expected)); + if !trusted { + return Err(HandlerError::Unauthorized( + "trusted producer metadata missing".into(), + )); + } + let repo = ctx.repo(); + if repo.get(&input.id).await?.is_some() { + return Err(HandlerError::Rejected(format!( + "cell item {} already exists", + input.id + ))); + } + let mut item = repo.create(); + item.record(input.id.clone()) + .map_err(|error| HandlerError::Rejected(error.to_string()))?; + repo.commit(item)?.succeeded(IdPayload { id: input.id }) +} + +struct TrustedCreate; + +impl PortableCommand for TrustedCreate +where + D: distributed::microsvc::CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + "generic.grant", + )) + .guarded( + |_ctx: &CausalCommandContext<'_, WaitAgg>| true, + handle_trusted_create, + ) + } +} + #[cfg(feature = "sqlite")] fn sqlite_wait_service(repository: SqliteRepository) -> Arc { let causal = Routes::new() @@ -170,6 +229,133 @@ async fn start_http(service: Arc) -> String { format!("http://{addr}") } +#[derive(Clone)] +struct TypedCellBridgeState { + cell: Arc>, + secret: InternalHttpSecret, +} + +fn typed_cell_bridge_error( + status: StatusCode, + code: impl Into, + message: impl Into, +) -> (StatusCode, axum::Json) { + ( + status, + axum::Json(json!({ + "code": code.into(), + "error": message.into(), + })), + ) +} + +async fn typed_cell_bridge( + axum::extract::State(state): axum::extract::State, + headers: axum::http::HeaderMap, + axum::Json(body): axum::Json, +) -> (StatusCode, axum::Json) { + let Some(secret) = headers + .get(CELL_INTERNAL_SECRET_HEADER) + .and_then(|value| value.to_str().ok()) + else { + return typed_cell_bridge_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "missing internal cell secret", + ); + }; + if !state.secret.matches(secret) { + return typed_cell_bridge_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "invalid internal cell secret", + ); + } + + let required_header = |name: &str| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned) + }; + let Some(service_id) = required_header(CELL_SERVICE_ID_HEADER) else { + return typed_cell_bridge_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "missing cell service identity", + ); + }; + let Some(principal_partition) = required_header(CELL_PRINCIPAL_PARTITION_HEADER) else { + return typed_cell_bridge_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "missing cell principal partition", + ); + }; + let Some(causation_id) = required_header(CELL_CAUSATION_ID_HEADER) else { + return typed_cell_bridge_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "missing cell causation identity", + ); + }; + let Some(command_id) = body.get("commandId").and_then(Value::as_str) else { + return typed_cell_bridge_error( + StatusCode::BAD_REQUEST, + "BAD_REQUEST", + "missing commandId", + ); + }; + let input = body.get("input").cloned().unwrap_or(Value::Null); + let identity = match CellCommandIdentity::new(service_id, principal_partition, command_id) + .and_then(|identity| identity.with_causation_id(causation_id)) + { + Ok(identity) => identity, + Err(error) => { + return typed_cell_bridge_error( + StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::BAD_REQUEST), + error.code(), + error.client_message(), + ) + } + }; + + // The bridge only constructs a Session after authenticating the internal + // host boundary. Public callers cannot turn arbitrary request headers into + // trusted producer claims because they cannot pass the secret check. + let mut session = Session::new(); + for (name, value) in &headers { + if let Ok(value) = value.to_str() { + session.set(name.as_str(), value); + } + } + + match state + .cell + .dispatch_idempotent("generic.grant", &identity, input, session) + .await + { + Ok(result) => ( + StatusCode::OK, + axum::Json(json!({ + "payload": result.payload(), + "receipt": { + "commandId": result.command_id(), + "causationId": result.causation_id(), + "state": result.state(), + "replayed": result.replayed(), + }, + "events": result.projection_events(), + })), + ), + Err(error) => typed_cell_bridge_error( + StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + error.code(), + error.client_message(), + ), + } +} + #[tokio::test] async fn cell_wait_path_replays_once_after_internal_failure() { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -235,6 +421,237 @@ async fn cell_wait_path_replays_once_after_internal_failure() { assert_eq!(attempts.load(Ordering::SeqCst), 2); } +#[tokio::test] +async fn trusted_native_metadata_reaches_cell_without_forwarding_session_headers() { + use axum::{ + extract::State, + http::{HeaderMap, StatusCode}, + routing::post, + Json, Router, + }; + use std::sync::Mutex; + + async fn command( + State(seen): State>>>>, + headers: HeaderMap, + Json(body): Json, + ) -> (StatusCode, Json) { + seen.lock().unwrap().push( + headers + .get("x-producer") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + ); + ( + StatusCode::CREATED, + Json(json!({ + "payload": { "id": body["input"]["id"] }, + "receipt": { + "commandId": body["commandId"], + "causationId": "cause-trusted", + "state": "succeeded", + "replayed": false + }, + "events": [] + })), + ) + } + + let seen = Arc::new(Mutex::new(Vec::new())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(command)) + .with_state(Arc::clone(&seen)); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let host = HttpCommandHost::new_internal( + format!("http://{addr}"), + InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(), + ) + .unwrap(); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "native-user"); + session.set(ROLE_KEY, "system"); + session.set("x-producer", "forged-public-header"); + let metadata = + TrustedRequestMetadata::try_from_pairs([("x-producer", "canonical-fact")]).unwrap(); + let context = CellRequestContext::new("generic-writer", "generic-partition") + .with_causation_id("canonical-causation") + .with_trusted_metadata(metadata); + + host.post_cell_wait_path_with_context( + "generic.grant", + "0190a000-0000-7000-8000-000000000120", + json!({ "id": "generic-grant-1" }), + &session, + &context, + ) + .await + .unwrap(); + host.post_cell_wait_path( + "generic.grant", + "0190a000-0000-7000-8000-000000000121", + json!({ "id": "generic-grant-2" }), + &session, + "generic-writer", + "generic-partition", + ) + .await + .unwrap(); + + assert_eq!( + *seen.lock().unwrap(), + vec![Some("canonical-fact".into()), None], + "only the explicit trusted context may carry custom producer metadata" + ); +} + +#[tokio::test] +async fn trusted_native_metadata_reaches_a_real_aggregate_cell() { + use axum::{routing::post, Router}; + + let secret = InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(); + let cell = Arc::new( + AggregateCell::::new("typed-cell-grant") + .unwrap() + .mount(TrustedCreate), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(typed_cell_bridge)) + .with_state(TypedCellBridgeState { + cell: Arc::clone(&cell), + secret: secret.clone(), + }); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let base = format!("http://{addr}"); + let host = HttpCommandHost::new_internal(base.clone(), secret.clone()).unwrap(); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "native-user"); + session.set(ROLE_KEY, "system"); + // This value models a public request header. The explicit native context + // below is the only trusted producer source for the cell command. + session.set("x-producer", "forged-public-header"); + let metadata = + TrustedRequestMetadata::try_from_pairs([("x-producer", "canonical-fact")]).unwrap(); + let context = CellRequestContext::new("generic-writer", "generic-partition") + .with_causation_id(TRUSTED_CAUSATION_ID) + .with_trusted_metadata(metadata); + + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + "0190a000-0000-7000-8000-000000000122", + json!({ "id": "typed-cell-grant" }), + &session, + &context, + ) + .await + .expect("typed cell command should receive the trusted context"); + assert_eq!(status, 200, "{body}"); + assert_eq!(body["payload"], json!({ "id": "typed-cell-grant" })); + assert_eq!(body["receipt"]["state"], "succeeded"); + assert_eq!(body["receipt"]["causationId"], TRUSTED_CAUSATION_ID); + assert_eq!(body["receipt"]["replayed"], false); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1, + "valid trusted cell dispatch must commit one aggregate event" + ); + + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + "0190a000-0000-7000-8000-000000000122", + json!({ "id": "typed-cell-grant" }), + &session, + &context, + ) + .await + .expect("same cell command identity should replay its durable result"); + assert_eq!(status, 200, "{body}"); + assert_eq!(body["receipt"]["replayed"], true); + assert_eq!(body["receipt"]["causationId"], TRUSTED_CAUSATION_ID); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1, + "replay must not append another aggregate event" + ); + + let client = reqwest::Client::new(); + let missing_secret = client + .post(format!("{base}/generic.grant")) + .header(CELL_SERVICE_ID_HEADER, "generic-writer") + .header(CELL_PRINCIPAL_PARTITION_HEADER, "generic-partition") + .header(CELL_CAUSATION_ID_HEADER, TRUSTED_CAUSATION_ID) + .header("x-producer", "canonical-fact") + .json(&json!({ + "commandId": "0190a000-0000-7000-8000-000000000124", + "input": { "id": "missing-secret" } + })) + .send() + .await + .unwrap(); + assert_eq!(missing_secret.status(), StatusCode::UNAUTHORIZED); + + let wrong_secret = client + .post(format!("{base}/generic.grant")) + .header(CELL_INTERNAL_SECRET_HEADER, "wrong-test-only-secret") + .header(CELL_SERVICE_ID_HEADER, "generic-writer") + .header(CELL_PRINCIPAL_PARTITION_HEADER, "generic-partition") + .header(CELL_CAUSATION_ID_HEADER, TRUSTED_CAUSATION_ID) + .header("x-producer", "canonical-fact") + .json(&json!({ + "commandId": "0190a000-0000-7000-8000-000000000125", + "input": { "id": "wrong-secret" } + })) + .send() + .await + .unwrap(); + assert_eq!(wrong_secret.status(), StatusCode::UNAUTHORIZED); + + let (status, body) = host + .post_cell_wait_path_with_causation( + "generic.grant", + "0190a000-0000-7000-8000-000000000126", + json!({ "id": "missing-producer" }), + &session, + "generic-writer", + "generic-partition", + Some(TRUSTED_CAUSATION_ID), + ) + .await + .expect("typed guard rejection should be returned by the cell bridge"); + assert_eq!(status, StatusCode::UNAUTHORIZED.as_u16(), "{body}"); + assert!(body["error"] + .as_str() + .is_some_and(|message| message.contains("trusted producer metadata"))); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1, + "unauthenticated provenance must not append an aggregate event" + ); +} + #[tokio::test] async fn celld_host_completes_remote_commit_once_and_rejects_changed_shard() { use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; From bf99b4a7626e78c77ada6aceb6387ecb9f4926af Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 10:28:05 -0500 Subject: [PATCH 091/484] test: fence changed trusted cell command bodies --- tests/causal_wait_path/main.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index 21d0ba10b..bbbf1a8c1 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -593,6 +593,28 @@ async fn trusted_native_metadata_reaches_a_real_aggregate_cell() { "replay must not append another aggregate event" ); + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + "0190a000-0000-7000-8000-000000000122", + json!({ "id": "different-input" }), + &session, + &context, + ) + .await + .expect("changed input should return a durable command-id conflict"); + assert_eq!(status, 409, "{body}"); + assert_eq!(body["code"], "COMMAND_ID_REUSE"); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1, + "a reused identity with a changed body must not append an event" + ); + let client = reqwest::Client::new(); let missing_secret = client .post(format!("{base}/generic.grant")) From 0e3286c991df083ea8650cac77e05ad0b7a829ec Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 10:37:12 -0500 Subject: [PATCH 092/484] test: cover authenticated transport recovery --- tests/causal_wait_path/main.rs | 128 +++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index bbbf1a8c1..52d2be177 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -674,6 +674,134 @@ async fn trusted_native_metadata_reaches_a_real_aggregate_cell() { ); } +#[tokio::test] +async fn authenticated_transport_recovery_requires_exact_no_effects_then_replays() { + use axum::{routing::post, Router}; + + let secret = InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(); + let cell = Arc::new( + AggregateCell::::new("recovery-cell") + .unwrap() + .mount(TrustedCreate), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = Router::new() + .fallback(post(typed_cell_bridge)) + .with_state(TypedCellBridgeState { + cell: Arc::clone(&cell), + secret: secret.clone(), + }); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let base = format!("http://{addr}"); + let host = HttpCommandHost::new_internal(base, secret).unwrap(); + let mut session = distributed::microsvc::Session::new(); + session.set(USER_ID_KEY, "native-user"); + session.set(ROLE_KEY, "system"); + + // The original command is authenticated at the HTTP boundary but lacks + // the producer claim required by the destination cell. This exact 401 is + // the only recoverable failure: the cell must have no receipt or event. + let (status, body) = host + .post_cell_wait_path_with_causation( + "generic.grant", + "0190a000-0000-7000-8000-000000000220", + json!({ "id": "recovery-cell" }), + &session, + "generic-writer", + "generic-partition", + Some(TRUSTED_CAUSATION_ID), + ) + .await + .unwrap(); + assert_eq!(status, StatusCode::UNAUTHORIZED.as_u16(), "{body}"); + assert!(body["error"] + .as_str() + .is_some_and(|message| message.contains("trusted producer metadata"))); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 0 + ); + + let metadata = + TrustedRequestMetadata::try_from_pairs([("x-producer", "canonical-fact")]).unwrap(); + let context = CellRequestContext::new("generic-writer", "generic-partition") + .with_causation_id(TRUSTED_CAUSATION_ID) + .with_trusted_metadata(metadata); + let recovery_command_id = "0190a000-0000-7000-8000-000000000221"; + + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + recovery_command_id, + json!({ "id": "recovery-cell" }), + &session, + &context, + ) + .await + .unwrap(); + assert_eq!(status, StatusCode::OK.as_u16(), "{body}"); + assert_eq!(body["receipt"]["replayed"], false); + assert_eq!(body["receipt"]["causationId"], TRUSTED_CAUSATION_ID); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1 + ); + + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + recovery_command_id, + json!({ "id": "recovery-cell" }), + &session, + &context, + ) + .await + .unwrap(); + assert_eq!(status, StatusCode::OK.as_u16(), "{body}"); + assert_eq!(body["receipt"]["replayed"], true); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1 + ); + + let (status, body) = host + .post_cell_wait_path_with_context( + "generic.grant", + recovery_command_id, + json!({ "id": "changed-recovery-body" }), + &session, + &context, + ) + .await + .unwrap(); + assert_eq!(status, StatusCode::CONFLICT.as_u16(), "{body}"); + assert_eq!(body["code"], "COMMAND_ID_REUSE"); + assert_eq!( + cell.durable_events() + .unwrap() + .iter() + .map(|stream| stream.events.len()) + .sum::(), + 1 + ); +} + #[tokio::test] async fn celld_host_completes_remote_commit_once_and_rejects_changed_shard() { use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; From f095c86392372e83e19bf1b138c3a55ef2c23094 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 10:40:46 -0500 Subject: [PATCH 093/484] test: narrow transport recovery evidence --- tests/causal_wait_path/main.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index 52d2be177..9870fd4d4 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -675,7 +675,7 @@ async fn trusted_native_metadata_reaches_a_real_aggregate_cell() { } #[tokio::test] -async fn authenticated_transport_recovery_requires_exact_no_effects_then_replays() { +async fn authenticated_transport_recovery_preserves_no_effects_then_replays() { use axum::{routing::post, Router}; let secret = InternalHttpSecret::new("test-only-internal-secret-32-bytes").unwrap(); @@ -703,8 +703,9 @@ async fn authenticated_transport_recovery_requires_exact_no_effects_then_replays session.set(ROLE_KEY, "system"); // The original command is authenticated at the HTTP boundary but lacks - // the producer claim required by the destination cell. This exact 401 is - // the only recoverable failure: the cell must have no receipt or event. + // the producer claim required by the destination cell. This fixture only + // proves that the rejected request produced no aggregate event; a caller + // must inspect its durable receipt/error classification before recovery. let (status, body) = host .post_cell_wait_path_with_causation( "generic.grant", From 16b571f117d6a9b3c2cdaaee2cfbe00f8a79ff95 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 17:22:42 -0500 Subject: [PATCH 094/484] fix!: reject incompatible aggregate event replay versions Fence generated handlers by the declared event schema version after upcasting, before decoding or invoking domain code. BREAKING CHANGE: aggregate! registrations for versioned handlers must declare version = N. Unsupported older and future event versions now fail replay even when their payload layout matches. Refs: incidents/aggregate-replay-event-version --- README.md | 16 +- distributed_macros/src/aggregate.rs | 46 ++++- distributed_macros/src/sourced.rs | 11 + tests/replay_event_version.rs | 305 ++++++++++++++++++++++++++++ tests/upcasting/aggregate.rs | 4 +- 5 files changed, 375 insertions(+), 7 deletions(-) create mode 100644 tests/replay_event_version.rs diff --git a/README.md b/README.md index eed9d11de..940e98238 100644 --- a/README.md +++ b/README.md @@ -1054,13 +1054,27 @@ fn upcast_initialized_v1_v2((id, task): InitV1) -> InitV2 { } aggregate!(Todo, entity { - "initialized"(id, task, priority) => initialize, + "initialized"(id, task, priority), version = 2 => initialize, "completed"() => complete(), } upcasters [ ("initialized", 1 => 2, InitV1 => InitV2, upcast_initialized_v1_v2), ]); ``` +Replay requires each event's schema version to match its registered handler +after upcasting. `#[sourced]` reads this version from `#[event(..., version = N)]`; +`aggregate!` declares it on the registration as above and must match the +corresponding `#[digest(..., version = N)]`. Omitted versions default to 1. +Older events need an explicit upcaster chain to the registered version; future +versions are rejected. Matching payload layouts do not bypass this check. +The check runs before payload decoding or handler invocation, including when +loading only the event tail after a snapshot in a native repository or cell. + +**Breaking change:** an `aggregate!` registration for a versioned handler must +now declare its current version. Histories with unsupported versions fail replay +instead of being interpreted using the current payload shape. Stored events are +unchanged; add the appropriate upcasters to read supported older versions. + ## Event Metadata Metadata lets you attach cross-cutting context — correlation IDs, causation IDs, user context, trace spans — to events without changing your domain model. diff --git a/distributed_macros/src/aggregate.rs b/distributed_macros/src/aggregate.rs index a3101b14f..e68d4b607 100644 --- a/distributed_macros/src/aggregate.rs +++ b/distributed_macros/src/aggregate.rs @@ -11,10 +11,10 @@ use syn::{ /// /// Both entry points produce a byte-identical impl: same associated /// `ReplayError = String`, same `entity`/`entity_mut`/`replay_event` bodies, and -/// the same optional `aggregate_type` and upcasters methods. Only the replay -/// match arms differ in how they are built upstream, so this helper takes them -/// (already rendered) along with the type name and entity field. Keeping one -/// emitter prevents the replay semantics of the two macros from drifting. +/// the same optional `aggregate_type` and upcasters methods. The version and +/// replay match arms are built upstream, so this helper takes them (already +/// rendered) along with the type name and entity field. Keeping the version +/// fence here prevents the replay semantics of the two macros from drifting. /// /// It emits only the `impl` block; callers still place `#upcaster_wrappers` /// (the free upcaster fns) where they already do. @@ -22,6 +22,7 @@ pub(crate) fn aggregate_impl_tokens( type_name: &Ident, entity_field: &Ident, aggregate_type_method: &Option, + version_arms: &[TokenStream2], replay_arms: &[TokenStream2], upcasters_method: &TokenStream2, ) -> TokenStream2 { @@ -43,6 +44,18 @@ pub(crate) fn aggregate_impl_tokens( &mut self, event: &distributed::EventRecord, ) -> Result<(), Self::ReplayError> { + // Hydration runs upcasters first. Payload compatibility alone + // cannot establish that an event has the handler's semantics. + let expected_version: u64 = match event.event_name.as_str() { + #(#version_arms)* + _ => return Err(format!("Unknown event: {}", event.event_name)), + }; + if event.event_version != expected_version { + return Err(format!( + "Unsupported event version for {}: expected {}, got {}", + event.event_name, expected_version, event.event_version, + )); + } match event.event_name.as_str() { #(#replay_arms)* _ => return Err(format!("Unknown event: {}", event.event_name)), @@ -178,6 +191,15 @@ pub(crate) fn expand_aggregate(input: TokenStream2) -> syn::Result let agg_name = &input.agg_name; let entity_field = &input.entity_field; + let version_arms: Vec<_> = input + .events + .iter() + .map(|event| { + let name = &event.event_name; + let version = &event.version; + quote! { #name => #version, } + }) + .collect(); // Generate replay match arms - deserialize and call method directly let replay_arms: Vec<_> = input @@ -249,6 +271,7 @@ pub(crate) fn expand_aggregate(input: TokenStream2) -> syn::Result agg_name, entity_field, &aggregate_type_method, + &version_arms, &replay_arms, &upcasters_method, ); @@ -327,6 +350,7 @@ struct AggregateInput { struct EventDef { event_name: LitStr, + version: syn::LitInt, args: Vec, method_name: Ident, method_args: Option>, // None = use event args, Some([]) = no args, Some([x,y]) = specific args @@ -382,6 +406,19 @@ impl Parse for AggregateInput { args_content.parse_terminated(Ident::parse, Token![,])?; let args: Vec = args.into_iter().collect(); + // `"renamed"(name), version = 2 => rename`; omitted versions + // have the same v1 default as #[digest] and #[event]. + let version = if content.peek(Token![,]) { + content.parse::()?; + let keyword: Ident = content.parse()?; + if keyword != "version" { + return Err(syn::Error::new(keyword.span(), "expected `version`")); + } + content.parse::()?; + content.parse::()? + } else { + syn::LitInt::new("1", event_name.span()) + }; content.parse::]>()?; let method_name: Ident = content.parse()?; @@ -398,6 +435,7 @@ impl Parse for AggregateInput { events.push(EventDef { event_name, + version, args, method_name, method_args, diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index 90caa3434..b96f63d57 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -212,6 +212,7 @@ fn find_and_remove_event_attr( struct EventMethodInfo { event_name: LitStr, + version: syn::LitInt, method_name: Ident, params: Vec<(Ident, syn::Type)>, /// Present when this recorder has `domain` and therefore a generated @@ -833,6 +834,7 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res }; event_methods.push(EventMethodInfo { + version: event_version(event_attr.version.as_ref()), event_name: event_attr.event_name, method_name: method.sig.ident.clone(), params, @@ -977,6 +979,14 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res // Generate impl Aggregate let entity_field = &args.entity_field; + let version_arms: Vec<_> = event_methods + .iter() + .map(|event| { + let name = &event.event_name; + let version = &event.version; + quote! { #name => #version, } + }) + .collect(); let replay_arms: Vec<_> = event_methods .iter() .map(|e| { @@ -1023,6 +1033,7 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res &struct_name, entity_field, &aggregate_type_method, + &version_arms, &replay_arms, &upcasters_method, ); diff --git a/tests/replay_event_version.rs b/tests/replay_event_version.rs new file mode 100644 index 000000000..8cf7b6452 --- /dev/null +++ b/tests/replay_event_version.rs @@ -0,0 +1,305 @@ +use distributed::{ + hydrate, hydrate_from_snapshot, Aggregate, AggregateRepository, CommitBatch, Entity, + EventRecord, RepositoryError, SnapshotRecord, SnapshotStore, Snapshottable, StreamIdentity, + StreamWrite, TransactionalCommit, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Default, Serialize, Deserialize, distributed::Snapshot)] +struct Versioned { + entity: Entity, + value: String, + calls: usize, +} + +#[distributed::sourced(entity)] +impl Versioned { + #[event("renamed", version = 2)] + fn rename(&mut self, value: String) { + self.value = value; + self.calls += 1; + } + + #[event("cleared", version = 2)] + fn clear(&mut self) { + self.value.clear(); + self.calls += 1; + } +} + +#[derive(Default, Serialize, Deserialize, distributed::Snapshot)] +struct Registered { + entity: Entity, + value: String, +} + +impl Registered { + #[distributed::digest("renamed", version = 2)] + fn rename(&mut self, value: String) { + self.value = value; + } + + #[distributed::digest("cleared")] + fn clear(&mut self) { + self.value.clear(); + } +} + +distributed::aggregate!(Registered, entity { + "renamed"(value), version = 2 => rename, + "cleared"() => clear(), + "ignored"(payload), version = 2 => clear(), +}); + +#[test] +fn sourced_rejects_same_shaped_older_and_future_events_before_mutation() { + for version in [0, 1, 3, u64::MAX] { + for (name, payload) in [ + ( + "renamed", + bitcode::serialize(&("changed".to_owned(),)).unwrap(), + ), + ("cleared", vec![]), + ] { + let mut aggregate = Versioned::default(); + aggregate.rename("unchanged".into()).unwrap(); + let before = serde_json::to_value(&aggregate.entity).unwrap(); + let event = EventRecord::new_versioned(name, payload, 2, version); + assert!( + aggregate.replay_event(&event).is_err(), + "accepted {name} v{version}" + ); + assert_eq!(aggregate.value, "unchanged"); + assert_eq!(aggregate.calls, 1); + assert_eq!(serde_json::to_value(&aggregate.entity).unwrap(), before); + } + } +} + +#[test] +fn aggregate_macro_rejects_same_shaped_versions_before_mutation() { + for (name, expected) in [("renamed", 2), ("cleared", 1), ("ignored", 2)] { + for version in [expected - 1, expected + 1, u64::MAX] { + let mut aggregate = Registered::default(); + aggregate.rename("unchanged".into()).unwrap(); + let before = serde_json::to_value(&aggregate.entity).unwrap(); + let event = EventRecord::new_versioned( + name, + bitcode::serialize(&("changed".to_owned(),)).unwrap(), + 2, + version, + ); + assert!(aggregate.replay_event(&event).is_err()); + assert_eq!(aggregate.value, "unchanged"); + assert_eq!(serde_json::to_value(&aggregate.entity).unwrap(), before); + } + } +} + +fn rename_event(version: u64, sequence: u64) -> EventRecord { + EventRecord::new_versioned( + "renamed", + bitcode::serialize(&("changed".to_owned(),)).unwrap(), + sequence, + version, + ) +} + +#[test] +fn exact_version_replays_with_both_macros() { + let mut entity = Entity::new(); + entity.load_from_history(vec![rename_event(2, 1)]); + let sourced = hydrate::(entity.clone()).unwrap(); + let registered = hydrate::(entity).unwrap(); + assert_eq!(sourced.value, "changed"); + assert_eq!(sourced.calls, 1); + assert_eq!(registered.value, "changed"); + assert_eq!(sourced.entity.version(), 1); + assert!(sourced.entity.new_events().is_empty()); +} + +fn snapshot() -> SnapshotRecord { + let mut aggregate = A::new_empty(); + aggregate.entity_mut().set_id("item"); + SnapshotRecord::new( + A::aggregate_type(), + "item", + 10, + A::SNAPSHOT_VERSION, + bitcode::serialize(&aggregate.create_snapshot()).unwrap(), + ) +} + +fn check_snapshot_tail() { + for version in [1, 2, 3] { + // Production cell and native repositories load only the suffix after a + // cached snapshot; its prefix still counts toward the next write fence. + let mut entity = Entity::new(); + entity.set_id("item"); + let event = rename_event(version, 11); + entity.load_tail_from_history(vec![event.clone()], 10); + let result = hydrate_from_snapshot::(entity, snapshot::()); + if version == 2 { + let aggregate = result.unwrap(); + assert_eq!(aggregate.entity().version(), 11); + assert_eq!(aggregate.entity().events(), &[event]); + assert!(aggregate.entity().new_events().is_empty()); + } else { + assert!(matches!(result, Err(RepositoryError::Replay(message)) + if message == format!("Unsupported event version for renamed: expected 2, got {version}"))); + } + } +} + +#[test] +fn snapshot_prefix_tail_checks_versions_for_both_macros() { + check_snapshot_tail::(); + check_snapshot_tail::(); +} + +#[derive(Default, Serialize, Deserialize, distributed::Snapshot)] +struct Upcasted { + entity: Entity, + value: String, +} + +#[derive(Default)] +struct RegisteredUpcast { + entity: Entity, + value: String, +} + +impl RegisteredUpcast { + #[distributed::digest("renamed", version = 2)] + fn rename(&mut self, value: String) { + self.value = value; + } +} + +distributed::aggregate!(RegisteredUpcast, entity { + "renamed"(value), version = 2 => rename, +} upcasters [ + ("renamed", 1 => 2, (String,) => (String,), convert_semantics), +]); + +#[derive(Default)] +struct IncompleteUpcast { + entity: Entity, +} + +#[distributed::sourced(entity, upcasters( + ("renamed", 1 => 2, (String,) => (String,), convert_semantics), +))] +impl IncompleteUpcast { + #[event("renamed", version = 3)] + fn rename(&mut self, _value: String) { + self.entity.set_id("incompatible-event-applied"); + } +} + +#[test] +fn incomplete_same_shaped_upcast_chain_is_rejected() { + let mut entity = Entity::new(); + entity.load_from_history(vec![rename_event(1, 1)]); + assert!( + matches!(hydrate::(entity), Err(RepositoryError::Replay(message)) + if message == "Unsupported event version for renamed: expected 3, got 2") + ); +} + +fn convert_semantics((value,): (String,)) -> (String,) { + (format!("v2:{value}"),) +} + +#[distributed::sourced(entity, upcasters( + ("renamed", 1 => 2, (String,) => (String,), convert_semantics), +))] +impl Upcasted { + #[event("renamed", version = 2)] + fn rename(&mut self, value: String) { + self.value = value; + } +} + +#[test] +fn same_shaped_upcast_precedes_guard_and_preserves_stored_history() { + let event = rename_event(1, 1); + let mut entity = Entity::new(); + entity.load_from_history(vec![event.clone()]); + let aggregate = hydrate::(entity).unwrap(); + assert_eq!(aggregate.value, "v2:changed"); + assert_eq!(aggregate.entity.events(), &[event]); + + let mut entity = Entity::new(); + let event = rename_event(1, 1); + entity.load_from_history(vec![event.clone()]); + let aggregate = hydrate::(entity).unwrap(); + assert_eq!(aggregate.value, "v2:changed"); + assert_eq!(aggregate.entity.events(), &[event]); + + let tail = rename_event(1, 11); + let mut entity = Entity::new(); + entity.set_id("item"); + entity.load_tail_from_history(vec![tail.clone()], 10); + let aggregate = hydrate_from_snapshot::(entity, snapshot::()).unwrap(); + assert_eq!(aggregate.value, "v2:changed"); + assert_eq!(aggregate.entity.version(), 11); + assert_eq!(aggregate.entity.events(), &[tail]); +} + +#[tokio::test] +async fn cell_repository_rejects_incompatible_tail_without_changing_storage() { + use distributed::cell_host::CellStreamStore; + + for version in [1, 2, 3] { + let store = CellStreamStore::new(Versioned::aggregate_type(), "item").unwrap(); + let identity = StreamIdentity::new(Versioned::aggregate_type(), "item").unwrap(); + let mut entity = Entity::new(); + entity.set_id("item"); + for _ in 0..10 { + entity + .digest_v("renamed", 2, &("prefix".to_owned(),)) + .unwrap(); + } + entity + .digest_v("renamed", version, &("changed".to_owned(),)) + .unwrap(); + store + .commit_batch(CommitBatch::new(vec![StreamWrite::new( + identity.clone(), + &mut entity, + )])) + .await + .unwrap(); + store + .save_snapshot(&identity, snapshot::()) + .await + .unwrap(); + let before = store.durable_state().unwrap(); + let repository = AggregateRepository::<_, Versioned>::new(store.clone()).with_snapshots(10); + let result = repository.get("item").await; + if version == 2 { + let aggregate = result.unwrap().unwrap(); + assert_eq!(aggregate.value, "changed"); + assert_eq!(aggregate.calls, 1, "snapshot prefix must not replay"); + assert_eq!(aggregate.entity.version(), 11); + } else { + assert!(matches!(result, Err(RepositoryError::Replay(_)))); + } + assert_eq!(store.durable_state().unwrap(), before); + } +} + +#[test] +fn full_hydration_rejects_same_shaped_unsupported_versions() { + for version in [1, 3] { + let mut entity = Entity::new(); + entity.load_from_history(vec![EventRecord::new_versioned( + "renamed", + bitcode::serialize(&("changed".to_owned(),)).unwrap(), + 1, + version, + )]); + assert!(hydrate::(entity).is_err()); + } +} diff --git a/tests/upcasting/aggregate.rs b/tests/upcasting/aggregate.rs index aaa7f0c82..e939c897b 100644 --- a/tests/upcasting/aggregate.rs +++ b/tests/upcasting/aggregate.rs @@ -71,7 +71,7 @@ impl TodoV2 { } distributed::aggregate!(TodoV2, entity, aggregate_type = "Todo" { - "initialized"(id, user_id, task, priority) => initialize, + "initialized"(id, user_id, task, priority), version = 2 => initialize, "completed"() => complete(), } upcasters [ ("initialized", 1 => 2, InitializedV1 => InitializedV2, upcast_initialized_v1_v2), @@ -120,7 +120,7 @@ impl TodoV3 { } distributed::aggregate!(TodoV3, entity, aggregate_type = "Todo" { - "initialized"(id, user_id, task, priority, due_date) => initialize, + "initialized"(id, user_id, task, priority, due_date), version = 3 => initialize, "completed"() => complete(), } upcasters [ ("initialized", 1 => 2, InitializedV1 => InitializedV2, upcast_initialized_v1_v2), From fd58eebe0ca717753d48a742d6ca9cbfe122d6d0 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Thu, 10 Sep 2026 18:07:44 -0500 Subject: [PATCH 095/484] fix!: retain unsigned command types for optimistic previews Preserve typed nonnegative integer ranges through command derives, portable metadata, generated codecs and U64 projection proofs. Reject inexact browser numbers before optimism or dispatch while preserving native unsigned range and signed codecs. BREAKING CHANGE: manually constructed command/surface fields require unsigned_integer metadata; the protocol fingerprint changes and services and generated clients must be rebuilt together. --- README.md | 3 + .../client_compiler/command_manifest/shape.rs | 6 + .../src/client_compiler/manifest/mod.rs | 2 +- .../client_compiler/manifest/projections.rs | 10 +- .../src/client_compiler/render/commands.rs | 10 +- distributed_cli/src/client_compiler/tests.rs | 54 +++- distributed_cli/tests/cli_client.rs | 2 +- distributed_cli/tests/cli_manifest.rs | 2 +- .../tests/fixtures/generated-commands.ts | 6 +- .../tests/fixtures/generated-operation.ts | 2 +- .../generated-recovery-preset-command.json | 2 +- .../fixtures/generated-scalar-operation.ts | 2 +- .../fixtures/generated-unsigned-command.json | 260 ++++++++++++++++++ .../tests/fixtures/orders-service/src/lib.rs | 3 + .../fixtures/runtime-bridge-operation.json | 2 +- .../fixtures/unique-key-bridge-operation.json | 2 +- distributed_macros/src/command_types.rs | 34 +++ .../application_command_duplicate_id.rs | 1 + .../application_command_duplicate_id.stderr | 14 +- docs/unsigned-command-inputs.md | 55 ++++ js/src/protocol.ts | 10 + js/src/replica/command-runtime/lib/output.ts | 7 +- js/src/replica/commands/clone.ts | 6 + js/src/unsigned-integer.ts | 17 ++ js/tests/protocol-transport.test.mjs | 16 ++ js/tests/replica-command-artifacts.test.mjs | 32 +++ js/tests/unsigned-command-output.test.mjs | 15 + src/application/command.rs | 3 + src/application/module.rs | 1 + src/command/input.rs | 56 ++++ src/command/mod.rs | 4 +- src/command/tests.rs | 16 ++ src/command/typed_command.rs | 10 +- src/command/types.rs | 49 ++++ src/graphql/client_manifest/codec.rs | 14 +- src/graphql/client_manifest/projections.rs | 52 +++- src/graphql/client_manifest/tests.rs | 33 ++- src/graphql/commands.rs | 1 + src/graphql/engine/protocol.rs | 8 + src/graphql/engine/tests.rs | 54 +++- src/graphql/projection_delta/runtime.rs | 30 ++ src/graphql/schema.rs | 2 + src/graphql/sdl.rs | 2 + src/graphql/surface/effects.rs | 8 + src/graphql/surface/tests.rs | 12 + src/graphql/surface/types.rs | 11 +- src/microsvc/service/tests.rs | 5 + tests/application_composition.rs | 2 + tests/application_plans.rs | 2 + tests/causal_public_invoke/main.rs | 2 + tests/causal_wait_path/main.rs | 2 + tests/e2e_ui_celld_nats_profile/main.rs | 3 + .../generated-draining-command-v2.json | 2 +- tests/graphql_commands/main.rs | 41 +++ tests/typed_commands/main.rs | 5 + 55 files changed, 964 insertions(+), 41 deletions(-) create mode 100644 distributed_cli/tests/fixtures/generated-unsigned-command.json create mode 100644 docs/unsigned-command-inputs.md create mode 100644 js/src/unsigned-integer.ts create mode 100644 js/tests/unsigned-command-output.test.mjs diff --git a/README.md b/README.md index 940e98238..95d8fe5a5 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,9 @@ Write the domain once, compose it into one `Service` or several, then generate the client. Each stage below uses real code from [`tests/e2e-ui`](tests/e2e-ui). +Unsigned command fields preserve their Rust range in generated client validation +and optimistic projections; see [unsigned command inputs](docs/unsigned-command-inputs.md). + ```mermaid sequenceDiagram actor Author diff --git a/distributed_cli/src/client_compiler/command_manifest/shape.rs b/distributed_cli/src/client_compiler/command_manifest/shape.rs index 09eba1a78..ef20cb8e2 100644 --- a/distributed_cli/src/client_compiler/command_manifest/shape.rs +++ b/distributed_cli/src/client_compiler/command_manifest/shape.rs @@ -219,6 +219,12 @@ fn validate_codec( ) -> Result<(), ClientCompileError> { match scalar_codecs.get(scalar) { Some(expected) if expected == codec => Ok(()), + Some(_) + if scalar == "BigInt" + && matches!(codec, "uint8" | "uint16" | "uint32" | "uint64_safe_integer") => + { + Ok(()) + } Some(expected) => Err(invalid( "client.manifest.command_type_codec", format!("{label} codec `{codec}` does not match `{scalar}` codec `{expected}`"), diff --git a/distributed_cli/src/client_compiler/manifest/mod.rs b/distributed_cli/src/client_compiler/manifest/mod.rs index 92e747912..5eac2d648 100644 --- a/distributed_cli/src/client_compiler/manifest/mod.rs +++ b/distributed_cli/src/client_compiler/manifest/mod.rs @@ -18,7 +18,7 @@ pub(crate) use util::{validate_hash, validate_nonempty}; const MANIFEST_VERSION: u64 = 2; const PROTOCOL_VERSION: u64 = 1; const PROTOCOL_FINGERPRINT: &str = - "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782"; + "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b"; pub(crate) const CLIENT_PROJECTION_PROGRAM_VERSION: u32 = 2; pub(crate) const CLIENT_PROJECTION_BINDING_VERSION: u32 = 1; diff --git a/distributed_cli/src/client_compiler/manifest/projections.rs b/distributed_cli/src/client_compiler/manifest/projections.rs index 8f57977c9..2543405b1 100644 --- a/distributed_cli/src/client_compiler/manifest/projections.rs +++ b/distributed_cli/src/client_compiler/manifest/projections.rs @@ -985,9 +985,7 @@ fn input_codec_compatible( (type_name, codec), ("Int", "int32") | ("BigInt", "json_number_precision_limited") ), - // Both numeric command codecs admit negative values. Without a - // non-negative refinement in the frozen manifest, neither proves U64. - ManifestProjectionValueType::U64 => false, + ManifestProjectionValueType::U64 => type_name == "BigInt" && unsigned_codec(codec), ManifestProjectionValueType::F64 => type_name == "Float" && codec == "float64", ManifestProjectionValueType::String => matches!( (type_name, codec), @@ -1004,7 +1002,7 @@ fn codec_compatible(codec: &str, expected: &ManifestProjectionValueType) -> bool ManifestProjectionValueType::I64 => { matches!(codec, "int32" | "json_number_precision_limited") } - ManifestProjectionValueType::U64 => false, + ManifestProjectionValueType::U64 => unsigned_codec(codec), ManifestProjectionValueType::F64 => codec == "float64", ManifestProjectionValueType::String | ManifestProjectionValueType::Enum(_) => { codec == "string" @@ -1013,6 +1011,10 @@ fn codec_compatible(codec: &str, expected: &ManifestProjectionValueType) -> bool } } +fn unsigned_codec(codec: &str) -> bool { + matches!(codec, "uint8" | "uint16" | "uint32" | "uint64_safe_integer") +} + fn constant_compatible( value: &ManifestProjectionValue, expected: &ManifestProjectionValueType, diff --git a/distributed_cli/src/client_compiler/render/commands.rs b/distributed_cli/src/client_compiler/render/commands.rs index 2de3d690e..d1657f434 100644 --- a/distributed_cli/src/client_compiler/render/commands.rs +++ b/distributed_cli/src/client_compiler/render/commands.rs @@ -428,7 +428,15 @@ fn render_command_field_type( } match field.codec.as_deref() { Some("boolean") => Ok("boolean".into()), - Some("float64" | "int32" | "json_number_precision_limited") => Ok("number".into()), + Some( + "float64" + | "int32" + | "json_number_precision_limited" + | "uint8" + | "uint16" + | "uint32" + | "uint64_safe_integer", + ) => Ok("number".into()), Some("string" | "base64" | "string_unvalidated_timestamp") => Ok("string".into()), Some("json") => Ok("ReplicaValue".into()), Some(codec) => Err(ClientCompileError::manifest( diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 52dd91697..680458e6c 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -266,7 +266,7 @@ pub(super) fn manifest() -> JsonValue { "service_id": "todos-service", "surface": {"kind": "role", "name": "user"}, "schema_fingerprint": fingerprint("schema"), - "protocol_fingerprint": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, "max_complexity": 500, @@ -3166,6 +3166,58 @@ fn command_protocol_and_extensions_are_preserved_exactly() { invalid_u64_source["projection_programs"][0]["arms"][0]["operations"][0]["fields"][1] ["assignment"]["expression"]["value_type"] = json!({"type": "u64"}); refresh_schema_fingerprint(&mut invalid_u64_source); + for codec in ["uint8", "uint16", "uint32", "uint64_safe_integer"] { + let mut unsigned = invalid_u64_source.clone(); + unsigned["commands"][0]["input"]["definition"]["fields"][1]["type_name"] = json!("BigInt"); + unsigned["commands"][0]["input"]["definition"]["fields"][1]["codec"] = json!(codec); + unsigned["models"][0]["fields"][2]["scalar"] = json!("BigInt"); + unsigned["models"][0]["fields"][2]["codec"] = json!("json_number_precision_limited"); + refresh_schema_fingerprint(&mut unsigned); + let compiled = compile_client(input_with_manifest( + unsigned.clone(), + "query Todos { todos { id priority } }", + )) + .expect("unsigned refined inputs prove U64 slots"); + let source = file(&compiled, "commands.ts"); + assert!(source.contains("readonly \"priority\": number;")); + let body = source + .split("export const Command_createTodo:") + .nth(1) + .unwrap() + .split_once(" = ") + .unwrap() + .1 + .split_once("\n};") + .unwrap() + .0; + let artifact: JsonValue = serde_json::from_str(&format!("{body}\n}}")).unwrap(); + assert_eq!(artifact["input"]["definition"]["fields"][1]["codec"], codec); + assert_eq!( + artifact["projection"]["preview"]["operations"][0]["mutation"]["fields"][1]["value"] + ["kind"], + "input" + ); + if codec == "uint64_safe_integer" { + let fixture: JsonValue = serde_json::from_str(include_str!( + "../../tests/fixtures/generated-unsigned-command.json" + )) + .unwrap(); + assert_eq!( + artifact, fixture, + "unsigned JS bridge must match generated output" + ); + } + unsigned["commands"][0]["extensions"]["trusted_presets"] = + json!([{"name": "priority", "codec": codec}]); + unsigned["commands"][0]["extensions"]["projection"]["preview_occurrences"][0]["values"] + [2]["source"] = json!({"kind": "trusted_preset", "name": "priority", "codec": codec}); + refresh_schema_fingerprint(&mut unsigned); + compile_client(input_with_manifest( + unsigned, + "query Todos { todos { id priority } }", + )) + .expect("unsigned trusted preset codec proves U64 slot"); + } let mut invalid_constant_source = value.clone(); invalid_constant_source["commands"][0]["extensions"]["projection"]["preview_occurrences"][0] ["values"][2]["source"] = diff --git a/distributed_cli/tests/cli_client.rs b/distributed_cli/tests/cli_client.rs index 53d29d906..72b64f5ad 100644 --- a/distributed_cli/tests/cli_client.rs +++ b/distributed_cli/tests/cli_client.rs @@ -17,7 +17,7 @@ const ROLE_MANIFEST: &str = r#"{ "name": "user" }, "schema_fingerprint": "sha256:758a97e4f7e1e538e8be86d24abd3d50a8da2d5813d29abd7a04bfa092d05189", - "protocol_fingerprint": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, "max_complexity": 500, diff --git a/distributed_cli/tests/cli_manifest.rs b/distributed_cli/tests/cli_manifest.rs index 86106da2d..90afb309d 100644 --- a/distributed_cli/tests/cli_manifest.rs +++ b/distributed_cli/tests/cli_manifest.rs @@ -78,7 +78,7 @@ fn client_manifest_uses_service_surface_export() { ); assert_eq!( manifest["protocol_fingerprint"], - "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782" + "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b" ); assert_eq!(manifest["models"][0]["id"], "OrderView"); assert_eq!(manifest["models"][0]["record_revisions"], true); diff --git a/distributed_cli/tests/fixtures/generated-commands.ts b/distributed_cli/tests/fixtures/generated-commands.ts index 6994f8724..f7403b9a9 100644 --- a/distributed_cli/tests/fixtures/generated-commands.ts +++ b/distributed_cli/tests/fixtures/generated-commands.ts @@ -67,7 +67,7 @@ export const Command_importTodos: ReplicaCommandArtifact TokenStream { + let mut current = ty; + while let Some(inner) = + extract_path_arg(current, "Option").or_else(|| extract_path_arg(current, "Vec")) + { + current = inner; + } + let Type::Path(path) = current else { + return quote! { None }; + }; + match path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .as_deref() + { + Some("u8") => quote! { Some(#framework::command::CommandUnsignedInteger::U8) }, + Some("u16") => quote! { Some(#framework::command::CommandUnsignedInteger::U16) }, + Some("u32") => quote! { Some(#framework::command::CommandUnsignedInteger::U32) }, + Some("u64") => quote! { Some(#framework::command::CommandUnsignedInteger::U64) }, + Some("usize") => quote! { + Some(match usize::BITS { + 16 => #framework::command::CommandUnsignedInteger::U16, + 32 => #framework::command::CommandUnsignedInteger::U32, + _ => #framework::command::CommandUnsignedInteger::U64, + }) + }, + _ => quote! { None }, + } +} + fn extract_path_arg<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> { let Type::Path(path) = ty else { return None; diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs index e173a3023..39b8e47b2 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs @@ -10,6 +10,7 @@ fn spec() -> CommandSpec { CommandTypeSpec { name: "DuplicateInput".into(), fields: vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr index 5377eae50..a6b983c15 100644 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr +++ b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr @@ -1,12 +1,12 @@ error[E0080]: evaluation panicked: duplicate command identity in module declaration - --> tests/compile_fail/application_command_duplicate_id.rs:38:1 + --> tests/compile_fail/application_command_duplicate_id.rs:39:1 | -38 | / distributed::module! { -39 | | pub DUPLICATE_MODULE { -40 | | id: "duplicates", -41 | | commands: [FIRST_DEFINITION, SECOND_DEFINITION], -42 | | } -43 | | } +39 | / distributed::module! { +40 | | pub DUPLICATE_MODULE { +41 | | id: "duplicates", +42 | | commands: [FIRST_DEFINITION, SECOND_DEFINITION], +43 | | } +44 | | } | |_^ evaluation of `_` failed inside this call | note: inside `assert_unique_command_ids` diff --git a/docs/unsigned-command-inputs.md b/docs/unsigned-command-inputs.md new file mode 100644 index 000000000..ae183f9ae --- /dev/null +++ b/docs/unsigned-command-inputs.md @@ -0,0 +1,55 @@ +# Unsigned command inputs and optimistic projections + +Use the Rust type that expresses the domain boundary: + +```rust,ignore +#[derive(serde::Deserialize, distributed::CommandInput)] +pub struct UpdateDocumentInput { + pub document_id: String, + pub expected_revision: u64, +} +``` + +`CommandInput` and `CommandOutput` retain unsigned width automatically, including +optional fields and list elements. A field remains GraphQL `BigInt` and TypeScript +`number`. Its generated command codec carries the narrower unsigned contract: + +| Rust type | Command codec | Browser range | +| --- | --- | --- | +| `u8` | `uint8` | 0–255 | +| `u16` | `uint16` | 0–65,535 | +| `u32` | `uint32` | 0–4,294,967,295 | +| `u64` | `uint64_safe_integer` | 0–9,007,199,254,740,991 | + +`usize` follows the target's pointer width. Fixed-width types are preferable +for portable domain contracts. + +For example, an event preview can bind `input.expected_revision` to a typed +`u64` event field. The manifest compiler now proves that assignment from the +unsigned codec, and the generated command prepares the same integer in its +optimistic projection and transport input. No browser annotation or handwritten +optimistic mutation is needed. + +Command preparation rejects negative numbers, negative zero, fractions, +non-finite numbers, strings, and numbers above the codec's maximum before any +optimistic effect or dispatch. The same validation applies to generated command +results and trusted presets. Explicit trusted presets targeting U64 projection +slots must declare an unsigned codec; an unrestricted signed `BigInt` preset +cannot establish that proof. + +JavaScript numbers cannot represent every `u64` exactly. The browser boundary +deliberately stops at `Number.MAX_SAFE_INTEGER`. Rust command execution retains +the full unsigned range, and projection constants and stored aggregate state +retain their existing full-width U64 representation. Signed command codecs and +SQL read-model scalar codecs are unchanged. + +## Regeneration + +This changes command contract and protocol fingerprints. Rebuild the service +and generated clients together with `distributed build` or `distributed dev`. +Mixed old/new artifacts fail the existing fingerprint check. + +Code that manually constructs `CommandTypeField` or `SurfaceTypeField` must +set `unsigned_integer` to the matching `CommandUnsignedInteger` variant, or +`None` for unrefined fields. Prefer derives so this metadata follows the Rust +type. A refinement on a non-`BigInt` field is rejected. diff --git a/js/src/protocol.ts b/js/src/protocol.ts index d6b3dd457..0cbcaac18 100644 --- a/js/src/protocol.ts +++ b/js/src/protocol.ts @@ -14,6 +14,7 @@ import { parseDistributedGenerationEnvelope, type DistributedGenerationEnvelope } from './generation.js'; +import { isUnsignedInteger, unsignedIntegerMaximum, type UnsignedIntegerCodec } from './unsigned-integer.js'; /** The only Distributed GraphQL protocol version understood by this package. */ export const DISTRIBUTED_PROTOCOL_VERSION = 1 as const; @@ -51,6 +52,7 @@ export type DistributedProjectionDisposition = 'revalidate'; /** Closed wire codecs for server-derived, client-visible trusted presets. */ export type DistributedTrustedPresetCodec = + | UnsignedIntegerCodec | 'string' | 'string_unvalidated_timestamp' | 'base64' @@ -828,6 +830,7 @@ export function isDistributedTrustedPresetCodec( value === 'int32' || value === 'float64' || value === 'json_number_precision_limited' || + (typeof value === 'string' && unsignedIntegerMaximum(value) !== undefined) || value === 'json' ); } @@ -845,6 +848,11 @@ function parseTrustedPresetValue( codec: DistributedTrustedPresetCodec, path: string ): DistributedProtocolValue { + const unsignedMaximum = unsignedIntegerMaximum(codec); + if (unsignedMaximum !== undefined) { + if (!isUnsignedInteger(value, unsignedMaximum)) invalid(path); + return value; + } switch (codec) { case 'string': case 'string_unvalidated_timestamp': @@ -887,6 +895,8 @@ function parseTrustedPresetValue( return Object.is(value, -0) ? 0 : value; case 'json': return cloneProtocolValue(value, path); + default: + return invalid(path); } } diff --git a/js/src/replica/command-runtime/lib/output.ts b/js/src/replica/command-runtime/lib/output.ts index 7929cd371..2f5c53099 100644 --- a/js/src/replica/command-runtime/lib/output.ts +++ b/js/src/replica/command-runtime/lib/output.ts @@ -13,6 +13,7 @@ import { import { ReplicaCommandRuntimeError } from '../errors.js'; import { compareCodeUnits } from '../../../lib/compare-code-units.js'; import { isPlainRecord } from '../../../lib/is-plain-record.js'; +import { isUnsignedInteger, unsignedIntegerMaximum } from '../../../unsigned-integer.js'; import { comparePropertyKeys, outputInvalid @@ -164,6 +165,11 @@ export function cloneOutputScalar( value: unknown, path: string ): ReplicaValue { + const unsignedMaximum = unsignedIntegerMaximum(codec); + if (unsignedMaximum !== undefined) { + if (!isUnsignedInteger(value, unsignedMaximum)) outputInvalid(path); + return value; + } switch (codec) { case 'string': case 'string_unvalidated_timestamp': @@ -251,4 +257,3 @@ export function cloneOutputJson( active.delete(value); return Object.freeze(output); } - diff --git a/js/src/replica/commands/clone.ts b/js/src/replica/commands/clone.ts index f6d1eb916..6c9230c0b 100644 --- a/js/src/replica/commands/clone.ts +++ b/js/src/replica/commands/clone.ts @@ -1,4 +1,5 @@ import type { ReplicaClientSurface, ReplicaValue } from '../types.js'; +import { isUnsignedInteger, unsignedIntegerMaximum } from '../../unsigned-integer.js'; import { createReplicaCommandId } from '../command-id.js'; import { isPlainRecord } from '../../lib/is-plain-record.js'; import { @@ -169,6 +170,11 @@ export function cloneScalar( value: unknown, path: string ): ReplicaValue { + const unsignedMaximum = unsignedIntegerMaximum(codec); + if (unsignedMaximum !== undefined) { + if (!isUnsignedInteger(value, unsignedMaximum)) inputInvalid(path); + return value; + } switch (codec) { case 'string': case 'string_unvalidated_timestamp': diff --git a/js/src/unsigned-integer.ts b/js/src/unsigned-integer.ts new file mode 100644 index 000000000..ec64f00ea --- /dev/null +++ b/js/src/unsigned-integer.ts @@ -0,0 +1,17 @@ +/** Exact browser-number refinements of Rust unsigned command integers. */ +export type UnsignedIntegerCodec = 'uint8' | 'uint16' | 'uint32' | 'uint64_safe_integer'; + +export function unsignedIntegerMaximum(codec: string | undefined): number | undefined { + switch (codec) { + case 'uint8': return 255; + case 'uint16': return 65_535; + case 'uint32': return 4_294_967_295; + case 'uint64_safe_integer': return Number.MAX_SAFE_INTEGER; + default: return undefined; + } +} + +export function isUnsignedInteger(value: unknown, maximum: number): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) + && !Object.is(value, -0) && value >= 0 && value <= maximum; +} diff --git a/js/tests/protocol-transport.test.mjs b/js/tests/protocol-transport.test.mjs index 35542556d..16ea9f5bc 100644 --- a/js/tests/protocol-transport.test.mjs +++ b/js/tests/protocol-transport.test.mjs @@ -103,6 +103,22 @@ function responseExtensions() { }; } +test('unsigned trusted presets accept only exact bounded integers', () => { + for (const [codec, maximum] of [['uint8', 255], ['uint16', 65_535], + ['uint32', 4_294_967_295], ['uint64_safe_integer', Number.MAX_SAFE_INTEGER]]) { + for (const value of [0, 1, maximum]) { + const envelope = distributedEnvelope(); + envelope.trustedPresets = [{ name: 'revision', codec, value }]; + assert.equal(parseDistributedProtocolEnvelope(envelope).trustedPresets[0].value, value); + } + for (const value of [-1, -0, 1.5, NaN, Infinity, maximum + 1, '1', 1n]) { + const envelope = distributedEnvelope(); + envelope.trustedPresets = [{ name: 'revision', codec, value }]; + assert.throws(() => parseDistributedProtocolEnvelope(envelope), DistributedProtocolError); + } + } +}); + test('protocol parser validates receipts while retaining future metadata opaquely', () => { assert.deepEqual(COMMAND_CONSISTENCY, { SUCCEEDED: 'succeeded', diff --git a/js/tests/replica-command-artifacts.test.mjs b/js/tests/replica-command-artifacts.test.mjs index 0b7abd29b..c01e3d381 100644 --- a/js/tests/replica-command-artifacts.test.mjs +++ b/js/tests/replica-command-artifacts.test.mjs @@ -32,6 +32,38 @@ const GENERATED_DRAINING_COMMAND = JSON.parse( ) ); +const GENERATED_UNSIGNED_COMMAND = JSON.parse(readFileSync(new URL( + '../../distributed_cli/tests/fixtures/generated-unsigned-command.json', import.meta.url +), 'utf8')); + +test('generated unsigned command preserves exact optimistic and transport values', () => { + for (const priority of [0, 1, Number.MAX_SAFE_INTEGER]) { + const prepared = prepareReplicaCommand(GENERATED_UNSIGNED_COMMAND, { + id: GENERATED_UUID, tenantId: 'tenant-1', title: 'Update', priority + }, { commandId: COMMAND_ID }); + assert.equal(prepared.transport.variables.input.priority, priority); + assert.equal(prepared.optimistic.operations[0].fields.priority, priority); + assert.equal(prepared.optimistic.operations[0].kind, 'upsert'); + } +}); + +test('unsigned command preparation rejects invalid values before producing optimism', () => { + for (const [codec, maximum] of [['uint8', 255], ['uint16', 65_535], + ['uint32', 4_294_967_295], ['uint64_safe_integer', Number.MAX_SAFE_INTEGER]]) { + const artifact = structuredClone(GENERATED_UNSIGNED_COMMAND); + artifact.input.definition.fields.find(field => field.name === 'priority').codec = codec; + const prepare = priority => prepareReplicaCommand(artifact, { + id: GENERATED_UUID, tenantId: 'tenant-1', title: 'Update', priority + }, { commandId: COMMAND_ID }); + assert.equal(prepare(maximum).optimistic.operations[0].fields.priority, maximum); + for (const invalid of [-1, -0, 0.5, NaN, Infinity, -Infinity, maximum + 1, + 2 ** 64, '1', 1n, null, undefined]) { + assert.throws(() => prepare(invalid), error => + error instanceof ReplicaCommandContractError && /input.priority/.test(error.message)); + } + } +}); + test('compiled recovery-only command drops unused presets without weakening validation', () => { const artifact = JSON.parse(readFileSync(new URL( '../../distributed_cli/tests/fixtures/generated-recovery-preset-command.json', import.meta.url diff --git a/js/tests/unsigned-command-output.test.mjs b/js/tests/unsigned-command-output.test.mjs new file mode 100644 index 000000000..357dec36b --- /dev/null +++ b/js/tests/unsigned-command-output.test.mjs @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { cloneOutputScalar } from '../dist/replica/command-runtime/lib/output.js'; + +test('unsigned command results reject lossy numbers before entering the replica', () => { + for (const [codec, maximum] of [['uint8', 255], ['uint16', 65_535], + ['uint32', 4_294_967_295], ['uint64_safe_integer', Number.MAX_SAFE_INTEGER]]) { + assert.equal(cloneOutputScalar(codec, maximum, 'result.revision'), maximum); + for (const value of [-1, -0, 0.5, NaN, Infinity, maximum + 1, 2 ** 64, '1']) { + assert.throws(() => cloneOutputScalar(codec, value, 'result.revision')); + } + } + assert.equal(cloneOutputScalar('json_number_precision_limited', -1, 'signed'), -1); + assert.equal(cloneOutputScalar('int32', -2_147_483_648, 'signed'), -2_147_483_648); +}); diff --git a/src/application/command.rs b/src/application/command.rs index f3a604c11..b1651e42e 100644 --- a/src/application/command.rs +++ b/src/application/command.rs @@ -22,6 +22,8 @@ pub struct CommandTypeField { pub list: bool, pub item_nullable: bool, #[serde(default, skip_serializing_if = "Option::is_none")] + pub unsigned_integer: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub nested: Option>, } @@ -43,6 +45,7 @@ impl From<&CommandTypeDef> for CommandTypeSpec { .fields .iter() .map(|field| CommandTypeField { + unsigned_integer: field.unsigned_integer, name: field.name.clone(), type_name: field.type_name.clone(), nullable: field.nullable, diff --git a/src/application/module.rs b/src/application/module.rs index e7122991f..d47d81848 100644 --- a/src/application/module.rs +++ b/src/application/module.rs @@ -664,6 +664,7 @@ fn surface_type_spec(definition: &SurfaceTypeDef) -> CommandTypeSpec { .fields .iter() .map(|field| super::command::CommandTypeField { + unsigned_integer: field.unsigned_integer, name: field.name.clone(), type_name: field.type_name.clone(), nullable: field.nullable, diff --git a/src/command/input.rs b/src/command/input.rs index f8fc5bc7e..94cc8ebe5 100644 --- a/src/command/input.rs +++ b/src/command/input.rs @@ -221,6 +221,23 @@ fn canonicalize_leaf( value: Value, path: &str, ) -> Result { + if let Some(unsigned) = field.unsigned_integer { + if field.type_name != "BigInt" || field.nested.is_some() { + return Err(CommandInputError::at( + path, + "unsigned refinement requires BigInt", + )); + } + return match value { + Value::Number(value) if value.as_u64().is_some_and(|n| n <= unsigned.max_value()) => { + Ok(Value::Number(value)) + } + _ => Err(CommandInputError::at( + path, + "must be an unsigned integer in range", + )), + }; + } if let Some(nested) = field.nested.as_deref() { return canonicalize_object(nested, value, path); } @@ -401,6 +418,7 @@ mod tests { nested: Option, ) -> CommandTypeField { CommandTypeField { + unsigned_integer: None, name: name.into(), type_name: type_name.into(), nullable, @@ -433,6 +451,44 @@ mod tests { ) } + #[test] + fn unsigned_inputs_preserve_full_rust_range_and_reject_invalid_values() { + use crate::command::CommandUnsignedInteger; + for unsigned in [ + CommandUnsignedInteger::U8, + CommandUnsignedInteger::U16, + CommandUnsignedInteger::U32, + CommandUnsignedInteger::U64, + ] { + let mut value_field = field("revision", "BigInt", false, false, false, None); + value_field.unsigned_integer = Some(unsigned); + let definition = CommandTypeDef::new("RevisionInput", vec![value_field]); + for value in [0, 1, unsigned.max_value()] { + assert_eq!( + canonicalize_command_input(&definition, json!({"revision": value})) + .unwrap() + .wire()["revision"], + json!(value) + ); + } + let mut invalid = vec![ + json!(-1), + json!(-0.0), + json!(1.5), + json!("1"), + serde_json::from_str("18446744073709551616").unwrap(), + ]; + if let Some(overflow) = unsigned.max_value().checked_add(1) { + invalid.push(json!(overflow)); + } + for value in invalid { + assert!( + canonicalize_command_input(&definition, json!({"revision": value})).is_err() + ); + } + } + } + #[test] fn key_order_is_canonical_but_lists_are_preserved() { let left = canonicalize_command_input( diff --git a/src/command/mod.rs b/src/command/mod.rs index 991e6beff..47915df88 100644 --- a/src/command/mod.rs +++ b/src/command/mod.rs @@ -12,7 +12,9 @@ pub(crate) mod input; mod types; pub(crate) use types::scalar_type_name; -pub use types::{CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField}; +pub use types::{ + CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, CommandUnsignedInteger, +}; mod direct_projection; mod effect_wire; diff --git a/src/command/tests.rs b/src/command/tests.rs index 9ae7d2eb9..e80dc9c96 100644 --- a/src/command/tests.rs +++ b/src/command/tests.rs @@ -22,6 +22,18 @@ fn command_ledger_fingerprint_preserves_the_v1_canonical_contract() { ); } +#[test] +fn unsigned_range_is_part_of_command_retry_identity() { + let mut signed = typed_command::>("revision.update").into_contract(); + signed.input.fields[0].type_name = "BigInt".into(); + let mut unsigned = signed.clone(); + unsigned.input.fields[0].unsigned_integer = Some(CommandUnsignedInteger::U64); + assert_ne!(signed.fingerprint_bytes(), unsigned.fingerprint_bytes()); + let mut narrower = unsigned.clone(); + narrower.input.fields[0].unsigned_integer = Some(CommandUnsignedInteger::U32); + assert_ne!(unsigned.fingerprint_bytes(), narrower.fingerprint_bytes()); +} + #[allow(dead_code)] #[derive(Deserialize)] struct Input { @@ -33,6 +45,7 @@ impl CommandInputType for Input { CommandTypeDef::new( "Input", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -141,6 +154,7 @@ impl CommandOutputType for Payload { CommandTypeDef::new( "Payload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -873,6 +887,7 @@ fn binding_canonicalizes_fields_and_roles_but_preserves_effect_order() { .roles(["writer", "admin"]) .into_contract(); first.input.fields.push(CommandTypeField { + unsigned_integer: None, name: "z_extra".into(), type_name: "String".into(), nullable: true, @@ -900,6 +915,7 @@ fn binding_canonicalizes_fields_and_roles_but_preserves_effect_order() { .roles(["writer", "admin"]) .into_contract(); reordered.input.fields.push(CommandTypeField { + unsigned_integer: None, name: "z_extra".into(), type_name: "String".into(), nullable: true, diff --git a/src/command/typed_command.rs b/src/command/typed_command.rs index 221b0ffe8..a51e1db66 100644 --- a/src/command/typed_command.rs +++ b/src/command/typed_command.rs @@ -347,14 +347,20 @@ fn canonical_command_type(definition: &CommandTypeDef) -> serde_json::Value { fields.sort_by(|left, right| left.name.cmp(&right.name)); serde_json::json!({ "name": definition.name, - "fields": fields.into_iter().map(|field| serde_json::json!({ + "fields": fields.into_iter().map(|field| { + let mut value = serde_json::json!({ "name": field.name, "type_name": field.type_name, "nullable": field.nullable, "list": field.list, "item_nullable": field.item_nullable, "nested": field.nested.as_deref().map(canonical_command_type), - })).collect::>(), + }); + if let Some(unsigned) = field.unsigned_integer { + value["unsigned_integer"] = serde_json::json!(unsigned); + } + value + }).collect::>(), }) } diff --git a/src/command/types.rs b/src/command/types.rs index 4e38cc946..7f055aefc 100644 --- a/src/command/types.rs +++ b/src/command/types.rs @@ -9,6 +9,51 @@ use std::any::TypeId; use crate::read_model::RelationalReadModel; use crate::table::ColumnType; +/// Rust unsigned integer range retained by command contracts and adapters. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CommandUnsignedInteger { + U8, + U16, + U32, + U64, +} + +impl CommandUnsignedInteger { + pub fn max_value(self) -> u64 { + match self { + Self::U8 => u64::from(u8::MAX), + Self::U16 => u64::from(u16::MAX), + Self::U32 => u64::from(u32::MAX), + Self::U64 => u64::MAX, + } + } + + /// Browser numbers must be exact; U64 therefore stops at 2^53 - 1. + pub fn client_codec(self) -> &'static str { + match self { + Self::U8 => "uint8", + Self::U16 => "uint16", + Self::U32 => "uint32", + Self::U64 => "uint64_safe_integer", + } + } + + pub fn from_client_codec(codec: &str) -> Option { + match codec { + "uint8" => Some(Self::U8), + "uint16" => Some(Self::U16), + "uint32" => Some(Self::U32), + "uint64_safe_integer" => Some(Self::U64), + _ => None, + } + } + + pub fn client_max_value(self) -> u64 { + self.max_value().min(9_007_199_254_740_991) + } +} + /// One field on a command input or output object. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CommandTypeField { @@ -18,6 +63,8 @@ pub struct CommandTypeField { pub list: bool, /// Whether list elements are nullable. Always `false` for non-list fields. pub item_nullable: bool, + /// A typed refinement of BigInt, including list elements when `list` is true. + pub unsigned_integer: Option, /// Nested object type definition when `type_name` is not a scalar. pub nested: Option>, } @@ -107,6 +154,8 @@ where ) }); CommandTypeField { + // Relational result codecs follow the read-model wire contract. + unsigned_integer: None, name: column.column_name.clone(), type_name: type_name.into(), nullable: column.nullable, diff --git a/src/graphql/client_manifest/codec.rs b/src/graphql/client_manifest/codec.rs index 957b0d6b6..dcd1bd2db 100644 --- a/src/graphql/client_manifest/codec.rs +++ b/src/graphql/client_manifest/codec.rs @@ -184,7 +184,17 @@ fn client_type(definition: &SurfaceTypeDef) -> Result Result { projection_binding_version: u32, projection_operation_semantics_version: u32, command_projection_extension_version: u32, + unsigned_command_codecs_version: u32, scalar_codecs: Vec, } hash_json(&ProtocolMaterial { @@ -275,6 +286,7 @@ pub(super) fn protocol_fingerprint() -> Result { super::projections::CLIENT_PROJECTION_OPERATION_SEMANTICS_VERSION, command_projection_extension_version: super::projections::COMMAND_PROJECTION_EXTENSION_VERSION, + unsigned_command_codecs_version: 1, scalar_codecs: supported_scalar_codecs(), }) } diff --git a/src/graphql/client_manifest/projections.rs b/src/graphql/client_manifest/projections.rs index bc79d5025..61f4284d8 100644 --- a/src/graphql/client_manifest/projections.rs +++ b/src/graphql/client_manifest/projections.rs @@ -1189,9 +1189,10 @@ fn input_field_compatible( ) -> bool { match expected { ProjectionValueType::Boolean => field.type_name == "Boolean", - ProjectionValueType::I64 | ProjectionValueType::U64 => { - matches!(field.type_name.as_str(), "BigInt" | "Int") + ProjectionValueType::I64 => { + matches!(field.type_name.as_str(), "BigInt" | "Int") && field.unsigned_integer.is_none() } + ProjectionValueType::U64 => field.type_name == "BigInt" && field.unsigned_integer.is_some(), ProjectionValueType::F64 => field.type_name == "Float", ProjectionValueType::String => { matches!(field.type_name.as_str(), "ID" | "String" | "Timestamptz") @@ -1211,8 +1212,11 @@ fn input_field_compatible( fn codec_compatible(codec: &str, expected: &ProjectionValueType) -> bool { match expected { ProjectionValueType::Boolean => codec == "boolean", - ProjectionValueType::I64 | ProjectionValueType::U64 => { - codec == "json_number_precision_limited" + ProjectionValueType::I64 => { + matches!(codec, "int32" | "json_number_precision_limited") + } + ProjectionValueType::U64 => { + crate::command::CommandUnsignedInteger::from_client_codec(codec).is_some() } ProjectionValueType::F64 => codec == "float64", ProjectionValueType::String | ProjectionValueType::Enum(_) => codec == "string", @@ -1416,6 +1420,7 @@ mod tests { input: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "TodoPreviewInput".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "value".into(), type_name: input_type.into(), nullable: false, @@ -1730,6 +1735,7 @@ mod tests { name: "TodoCreateInput".into(), fields: vec![ SurfaceTypeField { + unsigned_integer: None, name: "todo_id".into(), type_name: "ID".into(), nullable: false, @@ -1738,6 +1744,7 @@ mod tests { nested: None, }, SurfaceTypeField { + unsigned_integer: None, name: "title".into(), type_name: "String".into(), nullable: false, @@ -2303,6 +2310,43 @@ mod tests { let string_command = command("String"); let input = CommandProjectionPreviewSource::input(["value"]); + let mut unsigned_command = command("BigInt"); + let signed_command = unsigned_command.clone(); + let SurfaceCommandShape::Typed(definition) = &mut unsigned_command.input else { + unreachable!() + }; + definition.fields[0].unsigned_integer = Some(crate::command::CommandUnsignedInteger::U64); + for (command, allowed) in [(&unsigned_command, true), (&signed_command, false)] { + let source = client_preview_source( + &input, + true, + None, + Some(ProjectionPortableType::U64), + Some("u64"), + Some(false), + Some(true), + &ProjectionValueType::U64, + command, + ) + .unwrap(); + assert_eq!( + matches!(source, ClientProjectionPreviewSource::Input { .. }), + allowed + ); + } + assert!(codec_compatible( + "uint64_safe_integer", + &ProjectionValueType::U64 + )); + assert!(!codec_compatible( + "json_number_precision_limited", + &ProjectionValueType::U64 + )); + assert!(codec_compatible( + "json_number_precision_limited", + &ProjectionValueType::I64 + )); + assert_eq!( client_preview_source( &input, diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index c0cb568ba..4f2e876d6 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -191,6 +191,7 @@ impl CommandInputType for CompleteInput { CommandTypeDef::new( "CompleteTodoInput", vec![CommandTypeField { + unsigned_integer: None, name: "todo_id".into(), type_name: "String".into(), nullable: false, @@ -210,6 +211,7 @@ impl CommandOutputType for CompletePayload { CommandTypeDef::new( "CompleteTodoPayload", vec![CommandTypeField { + unsigned_integer: None, name: "todo_id".into(), type_name: "String".into(), nullable: false, @@ -491,6 +493,7 @@ fn projected_surface() -> Surface { .columns .iter() .map(|column| SurfaceTypeField { + unsigned_integer: None, name: column.name.clone(), type_name: column.scalar.clone(), nullable: column.nullable, @@ -507,6 +510,7 @@ fn projected_surface() -> Surface { input: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "ProjectTodoInput".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "todo_id".into(), type_name: "String".into(), nullable: false, @@ -767,7 +771,7 @@ fn role_manifest_is_deterministic_and_hides_denied_identity_and_commands() { ); assert_eq!( first.protocol_fingerprint, - "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782" + "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b" ); let user = first @@ -878,6 +882,33 @@ fn role_manifest_is_deterministic_and_hides_denied_identity_and_commands() { ); } +#[test] +fn unsigned_command_fields_export_refined_codecs_and_change_fingerprints() { + use crate::command::CommandUnsignedInteger; + let mut full = full_surface(); + let command = &mut full.commands[0]; + let SurfaceCommandShape::Typed(definition) = &mut command.input else { + unreachable!() + }; + definition.fields[0].type_name = "BigInt".into(); + let signed = manifest_for_all_models("todos-service", "user", &full); + let SurfaceCommandShape::Typed(definition) = &mut full.commands[0].input else { + unreachable!() + }; + definition.fields[0].unsigned_integer = Some(CommandUnsignedInteger::U64); + let unsigned = manifest_for_all_models("todos-service", "user", &full); + let wire = serde_json::to_value(&unsigned).unwrap(); + assert_eq!( + wire["commands"][0]["input"]["definition"]["fields"][0]["type_name"], + "BigInt" + ); + assert_eq!( + wire["commands"][0]["input"]["definition"]["fields"][0]["codec"], + "uint64_safe_integer" + ); + assert_ne!(signed.schema_fingerprint, unsigned.schema_fingerprint); +} + #[test] fn role_and_application_partition_manifests_hide_raw_paths_and_denied_values() { use crate::projection::placement::{ProjectionBindingState, ProjectionExecutionClass}; diff --git a/src/graphql/commands.rs b/src/graphql/commands.rs index 18d2ab970..c09c4c8db 100644 --- a/src/graphql/commands.rs +++ b/src/graphql/commands.rs @@ -31,6 +31,7 @@ fn surface_type(definition: &CommandTypeDef) -> SurfaceTypeDef { .fields .iter() .map(|field| SurfaceTypeField { + unsigned_integer: field.unsigned_integer, name: field.name.clone(), type_name: field.type_name.clone(), nullable: field.nullable, diff --git a/src/graphql/engine/protocol.rs b/src/graphql/engine/protocol.rs index 180577dee..36568159e 100644 --- a/src/graphql/engine/protocol.rs +++ b/src/graphql/engine/protocol.rs @@ -236,6 +236,14 @@ pub(crate) fn resolve_protocol_preset( } serde_json::Value::Number(parsed.into()) } + codec if crate::command::CommandUnsignedInteger::from_client_codec(codec).is_some() => { + let unsigned = crate::command::CommandUnsignedInteger::from_client_codec(codec)?; + let parsed = raw.parse::().ok()?; + if parsed > unsigned.client_max_value() || parsed.to_string() != raw { + return None; + } + serde_json::Value::Number(parsed.into()) + } "float64" => { let parsed = raw.parse::().ok()?; if !parsed.is_finite() { diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index ea2b2d2d9..8576815a4 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -943,6 +943,51 @@ mod client_surface_parity_tests { assert!(!response.extensions.contains_key("distributed")); } + #[test] + fn unsigned_presets_from_session_enforce_canonical_safe_ranges() { + for (codec, maximum) in [ + ("uint8", 255_u64), + ("uint16", 65_535), + ("uint32", 4_294_967_295), + ("uint64_safe_integer", 9_007_199_254_740_991), + ] { + let descriptor = ClientTrustedPresetDescriptor { + name: "x-revision".into(), + codec: codec.into(), + }; + let mut session = Session::new(); + for raw in ["0".to_string(), maximum.to_string()] { + session.set("x-revision", &raw); + assert_eq!( + crate::graphql::engine::protocol::resolve_protocol_preset( + &session, + &descriptor + ) + .unwrap() + .value, + serde_json::json!(raw.parse::().unwrap()) + ); + } + for raw in [ + "-1".to_string(), + "-0".into(), + "1.5".into(), + "1.0".into(), + "+1".into(), + "01".into(), + "NaN".into(), + (maximum + 1).to_string(), + ] { + session.set("x-revision", &raw); + assert!(crate::graphql::engine::protocol::resolve_protocol_preset( + &session, + &descriptor + ) + .is_none()); + } + } + } + #[cfg(feature = "sqlite")] #[tokio::test] async fn row_policy_presets_follow_sql_claim_case_normalization() { @@ -1472,6 +1517,7 @@ mod client_surface_parity_tests { nested: Option, ) -> CommandTypeField { CommandTypeField { + unsigned_integer: None, name: name.into(), type_name: type_name.into(), nullable, @@ -1885,28 +1931,28 @@ mod client_surface_parity_tests { #[cfg(feature = "sqlite")] const SQLITE_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:c1c3dd3f242f82225b486542b1737976f791e019f50e015f8755f48d70685f9a", + manifest: "sha256:7c8a181165a416610142c06f6b0ddca34358d884b738af10e11bf9b928817bed", static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", }; #[cfg(feature = "sqlite")] const SQLITE_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:94345b9e29bccaa77aa5083eb73014a1a102db7ce1f03f022a2f0e242b5c84d2", + manifest: "sha256:827e381234e72fa315daffa7a018f2c92f964d75ef70fbc86983b3aa704e52d9", static_sdl: "sha256:128b85bcd6485d14de62b0976e9f12e8b35ad9e7d96a5627d1edcfcabdb591b3", runtime_sdl: "sha256:c0b6d600d353357ab4f393897fb6b7ee51f69546f7a4cc4b6786e42abe621f5c", }; #[cfg(feature = "postgres")] const POSTGRES_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:c1c3dd3f242f82225b486542b1737976f791e019f50e015f8755f48d70685f9a", + manifest: "sha256:7c8a181165a416610142c06f6b0ddca34358d884b738af10e11bf9b928817bed", static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", }; #[cfg(feature = "postgres")] const POSTGRES_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:8ff2691f33789c8267b1338603b2ee3544841f8b17cc5b90ea2e851381dd36de", + manifest: "sha256:8e123332eb9ae3364290429e30feeee8a1da3cbad4004224382b8e6128c918a2", static_sdl: "sha256:afe92660c1700845ed5f3e0ddaacc4b481799c39f86b8eacecb46d1b8f99d421", runtime_sdl: "sha256:de4885736fdf22a57ccc55160d63b6d1a7fdb33728dec399e8a81d54ce7e8c09", }; diff --git a/src/graphql/projection_delta/runtime.rs b/src/graphql/projection_delta/runtime.rs index c8001d3bb..8ab93c6bd 100644 --- a/src/graphql/projection_delta/runtime.rs +++ b/src/graphql/projection_delta/runtime.rs @@ -810,6 +810,15 @@ fn trusted_preset_value_matches(codec: &str, value: &serde_json::Value) -> bool "json_number_precision_limited" => value .as_i64() .is_some_and(|value| (-9_007_199_254_740_991..=9_007_199_254_740_991).contains(&value)), + codec if crate::command::CommandUnsignedInteger::from_client_codec(codec).is_some() => { + crate::command::CommandUnsignedInteger::from_client_codec(codec).is_some_and( + |unsigned| { + value + .as_u64() + .is_some_and(|value| value <= unsigned.client_max_value()) + }, + ) + } "float64" => value.as_f64().is_some_and(f64::is_finite), "json" => true, _ => false, @@ -820,6 +829,27 @@ fn trusted_preset_value_matches(codec: &str, value: &serde_json::Value) -> bool mod trusted_preset_tests { use super::trusted_preset_value_matches; + #[test] + fn unsigned_presets_require_exact_bounded_integers() { + for (codec, max) in [ + ("uint8", 255_u64), + ("uint16", 65_535), + ("uint32", 4_294_967_295), + ("uint64_safe_integer", 9_007_199_254_740_991), + ] { + assert!(trusted_preset_value_matches(codec, &serde_json::json!(0))); + assert!(trusted_preset_value_matches(codec, &serde_json::json!(max))); + for invalid in [ + serde_json::json!(-1), + serde_json::json!(1.5), + serde_json::json!(max + 1), + serde_json::json!("1"), + ] { + assert!(!trusted_preset_value_matches(codec, &invalid)); + } + } + } + #[test] fn base64_preset_inventory_requires_canonical_standard_encoding() { assert!(trusted_preset_value_matches( diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 090bbd2e2..ca5b16627 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -1221,6 +1221,7 @@ mod causal_command_schema_tests { input: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "CompleteTodoInput".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -1232,6 +1233,7 @@ mod causal_command_schema_tests { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "CompleteTodoPayload".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/src/graphql/sdl.rs b/src/graphql/sdl.rs index 9c7dbda27..0bcdc2903 100644 --- a/src/graphql/sdl.rs +++ b/src/graphql/sdl.rs @@ -615,6 +615,7 @@ mod causal_command_sdl_tests { input: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "CompleteTodoInput".into(), fields: vec![crate::graphql::surface::SurfaceTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -626,6 +627,7 @@ mod causal_command_sdl_tests { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "CompleteTodoPayload".into(), fields: vec![crate::graphql::surface::SurfaceTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/src/graphql/surface/effects.rs b/src/graphql/surface/effects.rs index a7bf2e418..8934349d0 100644 --- a/src/graphql/surface/effects.rs +++ b/src/graphql/surface/effects.rs @@ -599,6 +599,14 @@ pub(in crate::graphql::surface) fn canonicalize_type_def( definition.name, field.name )); } + if field.unsigned_integer.is_some() + && (field.type_name != "BigInt" || field.nested.is_some()) + { + return Err(format!( + "command type `{}` field `{}` has an invalid unsigned refinement", + definition.name, field.name + )); + } if let Some(nested) = &mut field.nested { canonicalize_type_def(nested)?; if field.type_name != nested.name { diff --git a/src/graphql/surface/tests.rs b/src/graphql/surface/tests.rs index 1fa560d3f..72e5fe3e8 100644 --- a/src/graphql/surface/tests.rs +++ b/src/graphql/surface/tests.rs @@ -255,6 +255,7 @@ fn test_command( input: CommandTypeDef::new( "TestCommandInput", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -289,6 +290,7 @@ fn causal_surface_commands_accept_modeled_event_selectors_but_not_empty_authorit CommandTypeDef::new( "CausalPayload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -896,6 +898,7 @@ fn command_surface_rejects_duplicate_mutation_field_ids() { let output = CommandTypeDef::new( "TestCommandPayload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -934,6 +937,7 @@ fn command_surface_rejects_empty_nested_and_surface_colliding_types() { CommandTypeDef::new( "OuterPayload", vec![CommandTypeField { + unsigned_integer: None, name: "inner".into(), type_name: "InnerPayload".into(), nullable: false, @@ -955,6 +959,7 @@ fn command_surface_rejects_empty_nested_and_surface_colliding_types() { CommandTypeDef::new( "OrderView", vec![CommandTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -999,6 +1004,7 @@ fn projected_output_reuse_and_sdl_emission_use_the_same_exact_predicate() { let one_string_field = |name: &str| SurfaceTypeDef { name: name.into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -1065,6 +1071,7 @@ fn role_surface_legacy_effects_never_become_v2_client_authority() { name: "UpdateOrderInput".into(), fields: vec![ SurfaceTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -1073,6 +1080,7 @@ fn role_surface_legacy_effects_never_become_v2_client_authority() { nested: None, }, SurfaceTypeField { + unsigned_integer: None, name: "customer_id".into(), type_name: "String".into(), nullable: false, @@ -1098,6 +1106,7 @@ fn role_surface_legacy_effects_never_become_v2_client_authority() { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "AssignCustomerPayload".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -1132,6 +1141,7 @@ fn role_surface_legacy_effects_never_become_v2_client_authority() { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "ApplyPresetPayload".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -1938,6 +1948,7 @@ fn constant_validation_uses_exact_wire_scalar_domains() { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "ConstantPayload".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "ok".into(), type_name: "Boolean".into(), nullable: false, @@ -2000,6 +2011,7 @@ fn missing_surface_primary_key_column_is_a_configuration_error_not_a_panic() { output: SurfaceCommandShape::Typed(SurfaceTypeDef { name: "PatchOrderPayload".into(), fields: vec![SurfaceTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, diff --git a/src/graphql/surface/types.rs b/src/graphql/surface/types.rs index 628622cae..9222fa82c 100644 --- a/src/graphql/surface/types.rs +++ b/src/graphql/surface/types.rs @@ -172,6 +172,7 @@ pub struct SurfaceTypeField { pub nullable: bool, pub list: bool, pub item_nullable: bool, + pub unsigned_integer: Option, pub nested: Option>, } @@ -1065,14 +1066,20 @@ fn command_shape_value(shape: &SurfaceCommandShape) -> serde_json::Value { fn type_def_value(definition: &SurfaceTypeDef) -> serde_json::Value { serde_json::json!({ "name": definition.name, - "fields": definition.fields.iter().map(|field| serde_json::json!({ + "fields": definition.fields.iter().map(|field| { + let mut value = serde_json::json!({ "name": field.name, "type_name": field.type_name, "nullable": field.nullable, "list": field.list, "item_nullable": field.item_nullable, "nested": field.nested.as_deref().map(type_def_value), - })).collect::>(), + }); + if let Some(unsigned) = field.unsigned_integer { + value["unsigned_integer"] = serde_json::json!(unsigned); + } + value + }).collect::>(), }) } diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 0e99d74e9..6f9fcab98 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -82,6 +82,7 @@ fn one_string_field(name: &str, field: &str) -> CommandTypeDef { CommandTypeDef::new( name, vec![CommandTypeField { + unsigned_integer: None, name: field.into(), type_name: "String".into(), nullable: false, @@ -118,6 +119,7 @@ impl CommandInputType for CausalTestInput { "CausalTestInput", vec![ CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -126,6 +128,7 @@ impl CommandInputType for CausalTestInput { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "label".into(), type_name: "String".into(), nullable: false, @@ -614,6 +617,7 @@ impl CommandOutputType for CausalLifecycleView { "CausalLifecycleView", vec![ CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -622,6 +626,7 @@ impl CommandOutputType for CausalLifecycleView { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "label".into(), type_name: "String".into(), nullable: false, diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 3fc3e970d..d19bbd421 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -96,6 +96,7 @@ fn command(id: &str) -> CommandSpec { CommandTypeSpec { name: format!("{id}Input"), fields: vec![CommandTypeField { + unsigned_integer: None, name: "title".into(), type_name: "String".into(), nullable: false, @@ -107,6 +108,7 @@ fn command(id: &str) -> CommandSpec { CommandTypeSpec { name: format!("{id}Output"), fields: vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/application_plans.rs b/tests/application_plans.rs index 704f9f8c9..ff2c14470 100644 --- a/tests/application_plans.rs +++ b/tests/application_plans.rs @@ -14,6 +14,7 @@ fn portable_command(id: &str, consistency: CommandConsistency) -> CommandSpec { CommandTypeSpec { name: format!("{id}Input"), fields: vec![CommandTypeField { + unsigned_integer: None, name: "title".into(), type_name: "String".into(), nullable: false, @@ -25,6 +26,7 @@ fn portable_command(id: &str, consistency: CommandConsistency) -> CommandSpec { CommandTypeSpec { name: format!("{id}Output"), fields: vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/causal_public_invoke/main.rs b/tests/causal_public_invoke/main.rs index 671ca8399..5d5ab054b 100644 --- a/tests/causal_public_invoke/main.rs +++ b/tests/causal_public_invoke/main.rs @@ -56,6 +56,7 @@ impl CommandInputType for CompleteInput { CommandTypeDef::new( "CompleteInput", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -78,6 +79,7 @@ impl CommandOutputType for CompletePayload { CommandTypeDef::new( "CompletePayload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/causal_wait_path/main.rs b/tests/causal_wait_path/main.rs index 9870fd4d4..ad99a05a1 100644 --- a/tests/causal_wait_path/main.rs +++ b/tests/causal_wait_path/main.rs @@ -73,6 +73,7 @@ impl CommandInputType for IdInput { CommandTypeDef::new( "IdInput", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -95,6 +96,7 @@ impl CommandOutputType for IdPayload { CommandTypeDef::new( "IdPayload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/e2e_ui_celld_nats_profile/main.rs b/tests/e2e_ui_celld_nats_profile/main.rs index d06f30526..28632b6ce 100644 --- a/tests/e2e_ui_celld_nats_profile/main.rs +++ b/tests/e2e_ui_celld_nats_profile/main.rs @@ -163,6 +163,7 @@ mod live { "CreateInput", vec![ CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -171,6 +172,7 @@ mod live { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "title".into(), type_name: "String".into(), nullable: false, @@ -194,6 +196,7 @@ mod live { CommandTypeDef::new( "IdPayload", vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, diff --git a/tests/fixtures/generated-draining-command-v2.json b/tests/fixtures/generated-draining-command-v2.json index 17ccf0ae8..cdd7b72ed 100644 --- a/tests/fixtures/generated-draining-command-v2.json +++ b/tests/fixtures/generated-draining-command-v2.json @@ -38,7 +38,7 @@ }, "protocol": { "operation": "sha256:bb3a777dd32f7d40cccc173fafdbc7464f5dc50a3d17587909689a880fb0205a", - "protocolHash": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "protocolHash": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "schemaHash": "sha256:7e4d542ce141b2a9f350433b03603ae0ebfecd38c15b2e9d436fe8d0bca2662b", "surface": { "kind": "role", diff --git a/tests/graphql_commands/main.rs b/tests/graphql_commands/main.rs index fac88121a..9cc534d09 100644 --- a/tests/graphql_commands/main.rs +++ b/tests/graphql_commands/main.rs @@ -10,6 +10,7 @@ fn graphql_type_def_mapping_golden() { "CreateItemInput", vec![ CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -18,6 +19,7 @@ fn graphql_type_def_mapping_golden() { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "tags".into(), type_name: "String".into(), nullable: true, @@ -48,6 +50,45 @@ struct DerivedOutput { id: String, } +#[derive(distributed::CommandInput)] +#[allow(dead_code)] +struct UnsignedInput { + tiny: u8, + short: Option, + revisions: Vec>, + revision: u64, + signed: i64, +} + +#[test] +fn unsigned_command_derive_preserves_range_and_portable_contract() { + use distributed::command::{CommandInputType, CommandUnsignedInteger as Unsigned}; + let definition = UnsignedInput::command_type(); + assert_eq!( + definition + .fields + .iter() + .map(|field| field.unsigned_integer) + .collect::>(), + vec![ + Some(Unsigned::U8), + Some(Unsigned::U16), + Some(Unsigned::U32), + Some(Unsigned::U64), + None + ] + ); + assert!(definition + .fields + .iter() + .all(|field| field.type_name == "BigInt")); + assert!(definition.fields[2].list && definition.fields[2].item_nullable); + let portable = distributed::application::CommandTypeSpec::from(&definition); + let encoded = serde_json::to_value(&portable).unwrap(); + assert_eq!(encoded["fields"][3]["unsigned_integer"], "u64"); + assert!(encoded["fields"][4].get("unsigned_integer").is_none()); +} + #[derive(distributed::CommandInput, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[allow(dead_code)] diff --git a/tests/typed_commands/main.rs b/tests/typed_commands/main.rs index 626da1b27..6e17e90b9 100644 --- a/tests/typed_commands/main.rs +++ b/tests/typed_commands/main.rs @@ -142,6 +142,7 @@ impl CommandOutputType for PlanView { "PlanView", vec![ CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, @@ -150,6 +151,7 @@ impl CommandOutputType for PlanView { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "title".into(), type_name: "String".into(), nullable: false, @@ -158,6 +160,7 @@ impl CommandOutputType for PlanView { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "count".into(), type_name: "BigInt".into(), nullable: false, @@ -166,6 +169,7 @@ impl CommandOutputType for PlanView { nested: None, }, CommandTypeField { + unsigned_integer: None, name: "status".into(), type_name: "String".into(), nullable: false, @@ -1013,6 +1017,7 @@ fn object_type(name: &str) -> CommandTypeDef { CommandTypeDef::new( name, vec![CommandTypeField { + unsigned_integer: None, name: "id".into(), type_name: "String".into(), nullable: false, From df65eddfbb31c1d6e3c90f991b9bd555fd11c788 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 12 Sep 2026 15:52:46 -0500 Subject: [PATCH 096/484] fix: capture session authority before queued page updates (#252) Implements [[tasks/auth-refresh-continuity]]. --- .github/workflows/integration-gateway.yaml | 2 ++ js/src/sveltekit/replica.ts | 9 ++--- js/tests/sveltekit-ssr.test.mjs | 39 ++++++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml index 059896222..9196bbf4f 100644 --- a/.github/workflows/integration-gateway.yaml +++ b/.github/workflows/integration-gateway.yaml @@ -20,6 +20,8 @@ on: - 'tests/edge_query_delivery*' - 'js/src/replica/**' - 'js/tests/replica*' + - 'js/src/sveltekit/**' + - 'js/tests/sveltekit*' - 'tests/gateway*' - 'tests/gateway*/**' - '.github/workflows/integration-gateway.yaml' diff --git a/js/src/sveltekit/replica.ts b/js/src/sveltekit/replica.ts index caf785cb4..749e5952b 100644 --- a/js/src/sveltekit/replica.ts +++ b/js/src/sveltekit/replica.ts @@ -1038,13 +1038,14 @@ function createAuthorizationFence( let queue = Promise.resolve(); let disposed = false; const read = (): Promise => { - const candidate = Promise.resolve().then(() => { + const candidate = (async () => { // Capture the credential and its independent server transfer together, - // before another source notification can replace either value. + // synchronously at notification time. A queued read would observe a + // later seedless page update and lose the refresh's scope evidence. const credential = source.getAuth(); const transfer = source.getHydration?.(); - return Promise.resolve(credential).then((auth) => ({ auth, transfer })); - }); + return { auth: await credential, transfer }; + })(); const transition = queue.then(async () => { try { const { auth, transfer } = await candidate; diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index baeef371c..3b4cfaeff 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -557,6 +557,45 @@ test('fresh same-scope SSR authority rotates credentials without emptying the vi unsubscribe(); client.destroy(); }); +test('queued page-data updates retain the fresh authority before seedless invalidation', async () => { + const harness = serverHarness(); + const first = await harness.server.load(harness.event('alice', '1')); + const second = await harness.server.load(harness.event('alice', '2')); + const pageData = createPageDataSessionSource(first); + SsrWebSocket.instances.length = 0; + let fetches = 0; + const client = createDistributedSvelteKit({ + boundaries: [todosBoundary], session: pageData.session, + hydration: first.distributed, authority: first.distributedAuthority, + fetch: () => { fetches += 1; return new Promise(() => {}); }, + webSocket: SsrWebSocket + }); + const todos = client.operation(TodosArtifact).use(); + const values = []; + const unsubscribe = todos.subscribe(snapshot => values.push(snapshot.data.todos?.[0]?.title)); + await flushMicrotasks(); + const oldSocket = SsrWebSocket.instances[0]; + // A refresh supplies independent authority; invalidateAll then replaces it + // with normal data-request output, which intentionally contains no seed. + pageData.set({...second, accessToken: 'rotated-alice'}); + pageData.set({...second, accessToken: 'rotated-alice', distributed: undefined, distributedAuthority: undefined}); + await flushMicrotasks(); + assert.ok(values.every(value => value === 'alice:1'), JSON.stringify(values)); + assert.equal(fetches, 0); + assert.equal(oldSocket.closed, true); + const nextSocket = SsrWebSocket.instances.at(-1); + assert.notEqual(nextSocket, oldSocket); + nextSocket.open(); + await flushMicrotasks(); + assert.equal(nextSocket.sent[0].payload.authorization, 'Bearer rotated-alice'); + // A later, different credential cannot borrow the consumed transfer. + pageData.set({accessToken: 'unproven-rotation'}); + await flushMicrotasks(); + assert.equal(client.replica.scope, undefined); + assert.deepEqual(todos.get().data, {}); + unsubscribe(); client.destroy(); +}); + for (const kind of ['missing', 'replayed', 'historical', 'tampered', 'different-scope', 'logout']) { test(`credential change with ${kind} hydration still purges the old replica`, async () => { const harness = serverHarness(); From f79cdb0913541e3d2199d8942c1439d51f8fc0ee Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 12 Sep 2026 17:27:58 -0500 Subject: [PATCH 097/484] feat: share repeated projection material in application contracts (#249) * fix: preserve unsigned metadata in canonical surface contracts Refs [[unsigned-surface-metadata-breaks-canonical-typed-m]] * feat: share repeated projection material in application contracts Refs [[tasks/compact-historical-projection-contracts]] * fix: share Auth.js session reads within each request Implements [[incidents/distributed-pr249-refresh-continuity-20260912]] --- README.md | 4 + docs/compact-projection-contracts.md | 36 ++ docs/unsigned-command-inputs.md | 5 + src/application/manifest.rs | 13 +- src/application/mod.rs | 3 + src/application/projection_contract.rs | 383 ++++++++++++++++++ src/graphql/surface/projections.rs | 2 + tests/application_composition.rs | 158 ++++++++ tests/e2e-ui/ui/src/auth.ts | 14 +- tests/gateway-auth/run.mjs | 29 ++ .../routes/api/auth/session-reads/+server.ts | 17 + 11 files changed, 661 insertions(+), 3 deletions(-) create mode 100644 docs/compact-projection-contracts.md create mode 100644 src/application/projection_contract.rs create mode 100644 tests/gateway-auth/src/routes/api/auth/session-reads/+server.ts diff --git a/README.md b/README.md index 95d8fe5a5..7fe3a5724 100644 --- a/README.md +++ b/README.md @@ -2504,6 +2504,10 @@ inventories and validates their ownership; its convenience fields are unchanged. Portable artifacts remain bounded to 4 MiB. Version 1 artifacts must be regenerated with the matching CLI; they are not accepted as version 2. +Modeled projection contracts [share repeated operations and selector schemas](docs/compact-projection-contracts.md) +when smaller, preserving every current and retained event selector within the +same manifest budget. Runtime program identities and execution are unchanged. + For a full application, run `distributed build` or `distributed dev` from its Cargo workspace root. The CLI discovers the typed application, runtime binary, conventional `ui/` SvelteKit app, and `@hops-ops/distributed` dependency. A diff --git a/docs/compact-projection-contracts.md b/docs/compact-projection-contracts.md new file mode 100644 index 000000000..d20f32318 --- /dev/null +++ b/docs/compact-projection-contracts.md @@ -0,0 +1,36 @@ +# Shared projection material in application manifests + +Several exact event selectors can apply the same mutation. This is common when +retained state events and current events update the same read model. The +`projection!` authoring form already accepts multiple events per mutation; +application manifests now share identical operation lists and selector body +schemas when that reduces their encoded size. No authoring change is required. + +The modeled projection's `program` value uses the explicit +`shared_projection_program_v1` encoding when smaller than the expanded form. +Its `program` retains all original fields and every exact arm, replacing only +`operations` with `operations_ref` and selector `body_schema` with +`body_schema_ref`. These zero-based references address the wrapper's canonical +`operation_sets` and `body_schemas` tables. Operations are interned by their +complete canonical JSON, including ordering, IDs, expressions and effects; +schemas are interned by exact string equality. No historical selector is +removed, merged, treated as current, or exempted from replay validation. + +The runtime projection IR, program and binding IDs, server execution and client +projection-program exports are unchanged. The application Surface's artifact +fingerprints change deterministically when shared storage is used. Rebuild the +service and generated clients together. Existing expanded manifests remain accepted +and retain their existing encoding and fingerprints when decoded and re-encoded. + +Tools reading the opaque modeled `program` JSON can use +`distributed::application::expand_projection_program_contract(&value)` to read +either representation. Expansion returns exactly the original program JSON. +Unsupported encodings, invalid references, inline/reference ambiguity, duplicate +or unused table entries, and noncanonical table order fail validation. + +The complete encoded application manifest remains bounded at 4 MiB. Each opaque +modeled value remains bounded at 1 MiB; an expanded program also must fit the +existing 1 MiB budget. The decoder checks repeated byte costs before copying +shared values and validates programs individually, without retaining an expanded +copy of the whole application. Sharing is storage normalization, not an increase +in wire limits or a replacement for retained-history replay. diff --git a/docs/unsigned-command-inputs.md b/docs/unsigned-command-inputs.md index ae183f9ae..1766768cd 100644 --- a/docs/unsigned-command-inputs.md +++ b/docs/unsigned-command-inputs.md @@ -53,3 +53,8 @@ Code that manually constructs `CommandTypeField` or `SurfaceTypeField` must set `unsigned_integer` to the matching `CommandUnsignedInteger` variant, or `None` for unrefined fields. Prefer derives so this metadata follows the Rust type. A refinement on a non-`BigInt` field is rejected. + +Typed application manifests preserve `unsigned_integer` in canonical Surface +command input and output contracts, including nested types. Decoding and +re-encoding retains the same contract bytes and fingerprints. Unrefined fields +omit this metadata, preserving their existing canonical representation. diff --git a/src/application/manifest.rs b/src/application/manifest.rs index 51b931213..5e6e14c8f 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -879,6 +879,11 @@ fn validate_projection( let fields = modeled.as_object().ok_or_else(|| { ApplicationError::InvalidSpec("modeled projection must be an object".into()) })?; + if let Some(program) = fields.get("program") { + // Validate each shared value independently without retaining the + // expanded copies in the manifest or increasing the wire budget. + super::expand_projection_program_contract(program)?; + } let program_id = fields .get("program_id") .and_then(serde_json::Value::as_str) @@ -1852,14 +1857,18 @@ fn surface_command_type_value( serde_json::json!({ "name": definition.name, "fields": definition.fields.iter().map(|field| { - serde_json::json!({ + let mut value = serde_json::json!({ "name": field.name, "type_name": field.type_name, "nullable": field.nullable, "list": field.list, "item_nullable": field.item_nullable, "nested": field.nested.as_deref().map(|nested| surface_command_type_value(Some(nested))), - }) + }); + if let Some(unsigned) = field.unsigned_integer { + value["unsigned_integer"] = serde_json::json!(unsigned); + } + value }).collect::>(), }) } diff --git a/src/application/mod.rs b/src/application/mod.rs index 5e3be21d7..d34c10a0e 100644 --- a/src/application/mod.rs +++ b/src/application/mod.rs @@ -14,6 +14,7 @@ mod manifest; mod module; mod mount; mod plan; +mod projection_contract; mod registration; mod runtime; mod runtime_host; @@ -50,6 +51,8 @@ pub use plan::{ compile_deployment_plan, DeploymentPlan, PlanFingerprint, ProcessIntent, ProcessPlan, DEPLOYMENT_PLAN_SCHEMA_VERSION, MAX_DEPLOYMENT_PLAN_BYTES, }; +pub(crate) use projection_contract::compact_projection_program_contract; +pub use projection_contract::expand_projection_program_contract; pub use registration::{Application, ApplicationBuilder, ContractCompiler}; pub use runtime::{Runtime, RuntimeDialect}; pub use runtime_host::{bind_single_process, CapabilityProviders, RuntimeHost}; diff --git a/src/application/projection_contract.rs b/src/application/projection_contract.rs new file mode 100644 index 000000000..9e95fc4dc --- /dev/null +++ b/src/application/projection_contract.rs @@ -0,0 +1,383 @@ +//! Lossless sharing in application artifacts, independent of runtime program IR. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeMap; + +use super::{ApplicationError, ApplicationResult, MAX_MANIFEST_JSON_BYTES}; + +const ENCODING: &str = "shared_projection_program_v1"; + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct SharedProgram { + encoding: String, + program: Value, + operation_sets: Vec, + body_schemas: Vec, +} + +fn invalid(reason: &str) -> ApplicationError { + ApplicationError::InvalidSpec(format!("shared projection program: {reason}")) +} + +fn json_len(value: &impl Serialize) -> ApplicationResult { + // Stop counting before allocating an oversized encoding or expanding refs. + struct Counter(usize); + impl std::io::Write for Counter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(bytes.len()); + if self.0 > MAX_MANIFEST_JSON_BYTES { + return Err(std::io::Error::other( + "projection program exceeds JSON byte budget", + )); + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut counter = Counter(0); + serde_json::to_writer(&mut counter, value).map_err(|error| invalid(&error.to_string()))?; + Ok(counter.0) +} + +pub(crate) fn compact_projection_program_contract(value: Value) -> ApplicationResult { + let expanded_len = json_len(&value)?; + let mut program = value.clone(); + let arms = program + .get_mut("arms") + .and_then(Value::as_array_mut) + .ok_or_else(|| invalid("missing arms"))?; + let mut operations = BTreeMap::new(); + let mut schemas = BTreeMap::new(); + for arm in arms.iter() { + let operation = arm + .get("operations") + .filter(|value| value.is_array()) + .ok_or_else(|| invalid("missing operations"))?; + operations.insert( + serde_json::to_string(&super::canonical_json(operation))?, + operation.clone(), + ); + let schema = arm + .pointer("/selector/body_schema") + .and_then(Value::as_str) + .ok_or_else(|| invalid("missing selector body schema"))?; + schemas.insert(schema.to_owned(), ()); + } + let operation_sets: Vec<_> = operations.values().cloned().collect(); + let operation_indexes: BTreeMap<_, _> = operations + .keys() + .enumerate() + .map(|(i, key)| (key.clone(), i)) + .collect(); + let body_schemas: Vec<_> = schemas.into_keys().collect(); + for arm in arms { + let fields = arm + .as_object_mut() + .ok_or_else(|| invalid("arm must be an object"))?; + let operation = fields.remove("operations").unwrap(); + let key = serde_json::to_string(&super::canonical_json(&operation))?; + fields.insert( + "operations_ref".into(), + Value::from(operation_indexes[&key]), + ); + let selector = fields + .get_mut("selector") + .and_then(Value::as_object_mut) + .ok_or_else(|| invalid("selector must be an object"))?; + let schema = selector.remove("body_schema").unwrap(); + let index = body_schemas + .binary_search(&schema.as_str().unwrap().to_owned()) + .unwrap(); + selector.insert("body_schema_ref".into(), Value::from(index)); + } + let shared = serde_json::to_value(SharedProgram { + encoding: ENCODING.into(), + program, + operation_sets, + body_schemas, + })?; + // Single-arm/small programs keep their exact historical representation. + if json_len(&shared).is_ok_and(|len| len < expanded_len) { + Ok(shared) + } else { + Ok(value) + } +} + +/// Expand a modeled application-manifest program into its original program JSON. +/// +/// Accepts existing expanded values and `shared_projection_program_v1`. Sharing +/// changes artifact storage only: selectors, arm IDs, operations, runtime IR and +/// program digests are unchanged. References and table order are canonical, and +/// expansion is bounded by the existing 1 MiB opaque-contract budget before any +/// repeated operation list or schema is cloned. +pub fn expand_projection_program_contract(value: &Value) -> ApplicationResult { + json_len(value)?; + if value.get("encoding").is_none() { + return Ok(value.clone()); + } + let shared: SharedProgram = + serde_json::from_value(value.clone()).map_err(|error| invalid(&error.to_string()))?; + if shared.encoding != ENCODING { + return Err(invalid("unsupported encoding")); + } + if shared.operation_sets.iter().any(|value| !value.is_array()) { + return Err(invalid("operation sets must be arrays")); + } + let arms = shared + .program + .get("arms") + .and_then(Value::as_array) + .ok_or_else(|| invalid("missing arms"))?; + let mut expanded_len = json_len(&shared.program)? as i128; + let mut refs = Vec::with_capacity(arms.len()); + for arm in arms { + let operation_ref = arm + .get("operations_ref") + .and_then(Value::as_u64) + .and_then(|index| usize::try_from(index).ok()) + .ok_or_else(|| invalid("invalid operations reference"))?; + let schema_ref = arm + .pointer("/selector/body_schema_ref") + .and_then(Value::as_u64) + .and_then(|index| usize::try_from(index).ok()) + .ok_or_else(|| invalid("invalid body schema reference"))?; + let operation = shared + .operation_sets + .get(operation_ref) + .ok_or_else(|| invalid("operations reference out of bounds"))?; + let schema = shared + .body_schemas + .get(schema_ref) + .ok_or_else(|| invalid("body schema reference out of bounds"))?; + if arm.get("operations").is_some() || arm.pointer("/selector/body_schema").is_some() { + return Err(invalid("reference and inline material cannot coexist")); + } + // Replacing each `*_ref` key removes four key bytes and its index. + expanded_len += json_len(operation)? as i128 + json_len(schema)? as i128 + - json_len(&operation_ref)? as i128 + - json_len(&schema_ref)? as i128 + - 8; + if expanded_len > MAX_MANIFEST_JSON_BYTES as i128 { + return Err(invalid("expanded program exceeds JSON byte budget")); + } + refs.push((operation_ref, schema_ref)); + } + let mut expanded = shared.program; + for (arm, (operation_ref, schema_ref)) in expanded["arms"] + .as_array_mut() + .unwrap() + .iter_mut() + .zip(refs) + { + let fields = arm + .as_object_mut() + .ok_or_else(|| invalid("arm must be an object"))?; + fields.remove("operations_ref"); + fields.insert( + "operations".into(), + shared.operation_sets[operation_ref].clone(), + ); + let selector = fields + .get_mut("selector") + .and_then(Value::as_object_mut) + .ok_or_else(|| invalid("selector must be an object"))?; + selector.remove("body_schema_ref"); + selector.insert( + "body_schema".into(), + Value::from(shared.body_schemas[schema_ref].clone()), + ); + } + if compact_projection_program_contract(expanded.clone())? != *value { + return Err(invalid("noncanonical tables or references")); + } + Ok(expanded) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn history_program() -> Value { + let operations = json!([{ + "operation_id": "save", "staging_ordinal": 0, "kind": "upsert", + "model": "Repository", "storage": "repositories", + "fields": (0..40).map(|index| json!({ + "name": format!("field_{index}"), + "expression": {"kind": "body_path", "value_type": "string", "path": [format!("field_{index}")]} + })).collect::>() + }]); + json!({ + "ir_version": 1, "name": "repository", "version": 2, + "source_snapshots": true, + "arms": (0..32).map(|index| json!({ + "arm_id": format!("fact-{}", index % 16), + "selector": { + "occurrence_version": 1, "event_name": format!("repository.fact_{}", index % 16), + "event_version": index / 16 + 1, "body_kind": "state", + "body_type_name": "RepositoryState", "body_version": index / 16 + 1, + "body_schema": format!("state:v{}:{}", index / 16 + 1, "fields;".repeat(100)), + "body_fingerprint": format!("sha256:{:064x}", index / 16 + 1), + "body_codec": "json", "body_codec_version": 1, + }, + "operations": operations, + })).collect::>() + }) + } + + #[test] + fn shared_program_round_trip_preserves_all_current_and_retained_selectors() { + let original = history_program(); + let compact = compact_projection_program_contract(original.clone()).unwrap(); + assert_eq!(compact["encoding"], ENCODING); + assert_eq!(compact["operation_sets"].as_array().unwrap().len(), 1); + assert_eq!(compact["body_schemas"].as_array().unwrap().len(), 2); + assert_eq!(compact["program"]["arms"].as_array().unwrap().len(), 32); + assert!(json_len(&compact).unwrap() * 4 < json_len(&original).unwrap()); + assert_eq!( + expand_projection_program_contract(&compact).unwrap(), + original + ); + assert_eq!( + compact_projection_program_contract(original.clone()).unwrap(), + compact + ); + assert_eq!( + expand_projection_program_contract(&original).unwrap(), + original + ); + } + + #[test] + fn single_arm_keeps_existing_expanded_encoding() { + let mut original = history_program(); + original["arms"].as_array_mut().unwrap().truncate(1); + assert_eq!( + compact_projection_program_contract(original.clone()).unwrap(), + original + ); + } + + #[test] + fn shared_programs_fit_manifest_cap_and_legacy_artifacts_still_round_trip() { + use crate::application::{Application, ApplicationManifest, Module, ProjectionSpec}; + + let original = history_program(); + let compact = compact_projection_program_contract(original.clone()).unwrap(); + let module = |index: usize, program: &Value| { + let id = format!("history-{index:02}"); + let mut projection = + ProjectionSpec::try_new(&id, Vec::::new(), Vec::::new()).unwrap(); + projection.modeled_programs = vec!["program-history".into()]; + projection.modeled = vec![ + json!({"program_id": "program-history", "output_models": [], "program": program}), + ]; + // Recompute the ordinary ProjectionSpec fingerprint after setting + // its opaque behavior material, without altering that material. + let projection = projection.with_direct(false).unwrap(); + Module::new(id).projection(projection).build().unwrap() + }; + let expanded_modules = (0..32) + .map(|index| module(index, &original)) + .collect::>(); + let error = Application::try_new("history-app", expanded_modules, []).unwrap_err(); + assert!(error + .to_string() + .contains("application manifest exceeds 4194304 bytes")); + let modules = (0..32) + .map(|index| module(index, &compact)) + .collect::>(); + let application = Application::try_new("history-app", modules.clone(), []).unwrap(); + let bytes = application.manifest().canonical_bytes().unwrap(); + assert!(bytes.len() < crate::application::MAX_APPLICATION_MANIFEST_BYTES); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), + *application.manifest() + ); + assert_eq!( + Application::try_new("history-app", modules.into_iter().rev(), []) + .unwrap() + .manifest() + .canonical_bytes() + .unwrap(), + bytes + ); + for projection in &application.manifest().projections { + assert_eq!( + expand_projection_program_contract(&projection.modeled[0]["program"]).unwrap(), + original + ); + } + + let legacy = Application::try_new("legacy", [module(0, &original)], []).unwrap(); + let legacy_bytes = legacy.manifest().canonical_bytes().unwrap(); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&legacy_bytes) + .unwrap() + .canonical_bytes() + .unwrap(), + legacy_bytes + ); + } + + #[test] + fn shared_program_rejects_invalid_ambiguous_and_noncanonical_references() { + let compact = compact_projection_program_contract(history_program()).unwrap(); + let mut variants = Vec::new(); + for bad_ref in [ + json!(-1), + json!(0.5), + json!("0"), + json!(null), + json!(999999), + ] { + let mut invalid = compact.clone(); + invalid["program"]["arms"][0]["operations_ref"] = bad_ref; + variants.push(invalid); + } + let mut invalid = compact.clone(); + invalid["program"]["arms"][0]["selector"]["body_schema_ref"] = json!(999); + variants.push(invalid); + let mut invalid = compact.clone(); + invalid["program"]["arms"][0]["operations"] = json!([]); + variants.push(invalid); + let mut invalid = compact.clone(); + invalid["operation_sets"] + .as_array_mut() + .unwrap() + .push(json!([])); + variants.push(invalid); + let mut invalid = compact.clone(); + invalid["body_schemas"].as_array_mut().unwrap().reverse(); + for arm in invalid["program"]["arms"].as_array_mut().unwrap() { + arm["selector"]["body_schema_ref"] = + json!(1 - arm["selector"]["body_schema_ref"].as_u64().unwrap()); + } + variants.push(invalid); + let mut invalid = compact.clone(); + invalid["encoding"] = json!("future_encoding"); + variants.push(invalid); + let mut invalid = compact; + invalid["extra"] = json!(true); + variants.push(invalid); + for invalid in variants { + assert!(expand_projection_program_contract(&invalid).is_err()); + } + } + + #[test] + fn shared_program_rejects_expansion_beyond_existing_opaque_budget() { + let mut compact = compact_projection_program_contract(history_program()).unwrap(); + compact["operation_sets"][0] = json!([{"fields": "x".repeat(40_000)}]); + assert!(json_len(&compact).unwrap() < MAX_MANIFEST_JSON_BYTES); + assert!(expand_projection_program_contract(&compact) + .unwrap_err() + .to_string() + .contains("expanded program exceeds")); + } +} diff --git a/src/graphql/surface/projections.rs b/src/graphql/surface/projections.rs index 0e2e96577..253b38e96 100644 --- a/src/graphql/surface/projections.rs +++ b/src/graphql/surface/projections.rs @@ -124,6 +124,8 @@ impl SurfaceModeledProjection { } else { return Err("modeled projection has no canonical program material".to_owned()); }; + let program = crate::application::compact_projection_program_contract(program) + .map_err(|error| error.to_string())?; let binding = self.raw_binding.as_ref().map(|binding| { serde_json::json!({ "identity_version": binding.identity_version(), diff --git a/tests/application_composition.rs b/tests/application_composition.rs index d19bbd421..70e3c40d2 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -143,6 +143,164 @@ fn full_surface() -> Surface { .expect("non-empty Surface should compile") } +#[allow(dead_code)] +#[derive(Clone, Deserialize, CommandInput)] +struct UnsignedContractInput { + small: u8, + optional: Option, + items: Vec>, + revision: u64, + signed: i64, + title: String, +} + +#[derive(Clone, Serialize, CommandOutput)] +struct UnsignedContractOutput { + small: u8, + optional: Option, + items: Vec>, + revision: u64, + signed: i64, + title: String, +} + +#[allow(dead_code)] +#[derive(Clone, Deserialize, CommandInput)] +struct UnsignedContractInputEnvelope { + nested: UnsignedContractInput, +} + +#[derive(Clone, Serialize, CommandOutput)] +struct UnsignedContractOutputEnvelope { + nested: UnsignedContractOutput, +} + +#[derive(Default)] +struct UnsignedContractAggregate { + entity: distributed::Entity, +} + +impl distributed::Aggregate for UnsignedContractAggregate { + type ReplayError = String; + + fn aggregate_type() -> &'static str { + "unsigned-contract" + } + fn entity(&self) -> &distributed::Entity { + &self.entity + } + fn entity_mut(&mut self) -> &mut distributed::Entity { + &mut self.entity + } + fn replay_event(&mut self, _: &distributed::EventRecord) -> Result<(), String> { + Ok(()) + } +} + +#[test] +fn unsigned_surface_command_contract_round_trips() { + use distributed::microsvc::{CausalCommandContext, Routes, Service}; + use distributed::{AggregateRepository, InMemoryRepository}; + + let routes = Routes::new().with_repo(AggregateRepository::<_, UnsignedContractAggregate>::new( + InMemoryRepository::new(), + )); + let service = Service::new().named("unsigned-app").routes( + routes + .typed_command(typed_command::< + UnsignedContractInput, + Succeeded, + >("unsigned.flat")) + .handle( + |_: &CausalCommandContext<'_, UnsignedContractAggregate>, + _: UnsignedContractInput| async { + unreachable!("manifest compilation must not execute handlers") + }, + ) + .typed_command(typed_command::< + UnsignedContractInputEnvelope, + Succeeded, + >("unsigned.nested")) + .handle( + |_: &CausalCommandContext<'_, UnsignedContractAggregate>, + _: UnsignedContractInputEnvelope| async { + unreachable!("manifest compilation must not execute handlers") + }, + ), + ); + let surface = full_surface().with_service(&service).unwrap(); + let spec = SurfaceSpec::from_surface("web", &surface).unwrap(); + for command in spec.contract["commands"].as_array().unwrap() { + for direction in ["input", "output"] { + let mut fields = command[direction]["fields"].as_array().unwrap(); + if fields[0]["name"] == "nested" { + assert!(fields[0].get("unsigned_integer").is_none()); + fields = fields[0]["nested"]["fields"].as_array().unwrap(); + } + for (name, width) in [ + ("small", "u8"), + ("optional", "u16"), + ("items", "u32"), + ("revision", "u64"), + ] { + let field = fields.iter().find(|field| field["name"] == name).unwrap(); + assert_eq!(field["unsigned_integer"], width); + assert_eq!(field["type_name"], "BigInt"); + } + for name in ["signed", "title"] { + let field = fields.iter().find(|field| field["name"] == name).unwrap(); + assert!(field.get("unsigned_integer").is_none()); + } + } + } + let application = service.application("unsigned-app", spec).unwrap(); + let manifest = application.manifest(); + let bytes = manifest.canonical_bytes().unwrap(); + let decoded = ApplicationManifest::from_canonical_bytes(&bytes).unwrap(); + assert_eq!(&decoded, manifest); + assert_eq!(decoded.canonical_bytes().unwrap(), bytes); + + let mut tampered = manifest.clone(); + tampered.surfaces[0].contract["commands"][0]["input"]["fields"][0]["unsigned_integer"] = + serde_json::json!("u64"); + tampered.surfaces[0].fingerprint = distributed::application::sha256_fingerprint( + &tampered.surfaces[0].canonical_bytes().unwrap(), + ); + assert!(tampered + .refresh_fingerprints() + .unwrap_err() + .to_string() + .contains("surface contract material")); +} + +#[test] +fn ordinary_surface_command_contract_keeps_unrefined_field_shape() { + let module = command_module(); + let surface = full_surface().with_module(&module).unwrap(); + let spec = SurfaceSpec::from_surface("web", &surface).unwrap(); + for command in spec.contract["commands"].as_array().unwrap() { + for (direction, name) in [("input", "title"), ("output", "id")] { + assert_eq!( + command[direction]["fields"], + serde_json::json!([{ + "name": name, "type_name": "String", "nullable": false, + "list": false, "item_nullable": false, "nested": null, + }]) + ); + } + } + let application = Application::new("ordinary-app") + .module(module) + .surface(spec) + .build() + .unwrap(); + let bytes = application.manifest().canonical_bytes().unwrap(); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), + *application.manifest() + ); +} + #[test] fn generated_surface_above_opaque_json_budget_round_trips() { let tables = (0..500) diff --git a/tests/e2e-ui/ui/src/auth.ts b/tests/e2e-ui/ui/src/auth.ts index 49e888ad0..160b086bf 100644 --- a/tests/e2e-ui/ui/src/auth.ts +++ b/tests/e2e-ui/ui/src/auth.ts @@ -489,6 +489,18 @@ export const handle: Handle = ({ event, resolve }) => { } return setCookie(name, value, options); }; - return authHandle({ event, resolve }); + return authHandle({ + event, + resolve: (event) => { + const auth = event.locals.auth; + // Auth.js reads the original request cookie each time. Share the promise + // so hooks and loaders cannot refresh it into different credentials. + // Keep null sessions and failures cached for this request as well. + let session: ReturnType | undefined; + event.locals.auth = () => (session ??= Promise.resolve().then(() => auth())); + event.locals.getSession = event.locals.auth; + return resolve(event); + } + }); }; export { signIn, signOut }; diff --git a/tests/gateway-auth/run.mjs b/tests/gateway-auth/run.mjs index ed4e211fe..1d0199c8a 100644 --- a/tests/gateway-auth/run.mjs +++ b/tests/gateway-auth/run.mjs @@ -52,6 +52,14 @@ export async function exerciseAuth(fixture) { const context = await browser.newContext(); const page = await context.newPage(); assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 401); + const readSessions = async () => { + const response = await context.request.get(`${publicOrigin}/api/auth/session-reads`); + assert.equal(response.status(), 200); + const result = await response.json(); + assert.equal(result.sameSession, true, 'all request consumers must share one session'); + return result; + }; + assert.deepEqual(await readSessions(), { sameSession: true, authenticated: false, error: null, tokenDigest: null }); await page.goto(publicOrigin); await page.getByRole('link', { name: 'Log in' }).click(); await page.getByRole('button', { name: 'Continue as Alice' }).click(); @@ -66,6 +74,24 @@ export async function exerciseAuth(fixture) { // The real provider issues a 61-second access token. Cross the app's existing // 60-second refresh skew; no fake auth clock or forged session is involved. await new Promise(resolve => setTimeout(resolve, 2200)); + const refreshesBeforeReads = idp.refreshes(); + const firstReads = await readSessions(); + assert.equal(firstReads.authenticated, true); + assert.equal(idp.refreshes(), refreshesBeforeReads + 1, 'concurrent and sequential reads must refresh only once'); + // A later request must use its renewed cookie; after expiry it must refresh + // again. This also rejects a cache accidentally shared across requests. + await new Promise(resolve => setTimeout(resolve, 2200)); + const laterReads = await readSessions(); + assert.equal(laterReads.authenticated, true); + assert.notEqual(laterReads.tokenDigest, firstReads.tokenDigest); + assert.equal(idp.refreshes(), refreshesBeforeReads + 2); + const anonymous = await browser.newContext(); + try { + const response = await anonymous.request.get(`${publicOrigin}/api/auth/session-reads`); + assert.equal((await response.json()).authenticated, false, 'another browser must not inherit the session'); + } finally { await anonymous.close(); } + console.log('PASS request-local session reads share one refresh and later requests remain independent'); + await new Promise(resolve => setTimeout(resolve, 2200)); const refreshed = await context.request.post(`${publicOrigin}/api/auth/refresh`, { headers: { origin: publicOrigin } }); assert.equal(refreshed.status(), 200, JSON.stringify({ url: refreshed.url(), body: await refreshed.text(), cookies: (await context.cookies()).map(({name, expires, path}) => ({name, expires, path})), privateStatus: (await context.request.get(`${publicOrigin}/private`)).status() })); const refreshBody = await refreshed.json(); @@ -79,6 +105,9 @@ export async function exerciseAuth(fixture) { assert.equal((await context.request.get(`${publicOrigin}/private`)).status(), 200); idp.failRefresh(); await new Promise(resolve => setTimeout(resolve, 2200)); + const failedReads = await readSessions(); + assert.equal(failedReads.authenticated, false); + assert.equal(failedReads.error, 'RefreshAccessTokenError'); const failedRefresh = await context.request.post(`${publicOrigin}/api/auth/refresh`, { headers: { origin: publicOrigin } }); assert.equal(failedRefresh.status(), 401); assert.equal((await failedRefresh.json()).error, 'RefreshAccessTokenError'); diff --git a/tests/gateway-auth/src/routes/api/auth/session-reads/+server.ts b/tests/gateway-auth/src/routes/api/auth/session-reads/+server.ts new file mode 100644 index 000000000..65989b2c0 --- /dev/null +++ b/tests/gateway-auth/src/routes/api/auth/session-reads/+server.ts @@ -0,0 +1,17 @@ +import { createHash } from 'node:crypto'; +import { json } from '@sveltejs/kit'; +import { isCurrentSession } from '$lib/server/require-auth'; + +// Exercise concurrent first reads and later consumers against the real Auth.js +// request cookie, including the compatibility alias. Never expose credentials. +export async function GET({ locals }) { + const sessions = await Promise.all([locals.auth(), locals.auth(), locals.getSession()]); + sessions.push(await locals.auth(), await locals.getSession()); + const session = sessions[0]; + return json({ + sameSession: sessions.every(value => value === session), + authenticated: isCurrentSession(session), + error: session?.error ?? null, + tokenDigest: session?.accessToken ? createHash('sha256').update(session.accessToken).digest('hex') : null + }); +} From 5f3d79cb9fe0c1c7946075b852cf3c6480350abd Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Fri, 11 Sep 2026 03:07:26 -0500 Subject: [PATCH 098/484] feat: infer shared transition events and flat principal previews Implements [[tasks/distributed-sourced-authenticated-preview]] --- README.md | 41 +++- distributed_macros/src/domain_event.rs | 9 + distributed_macros/src/entry_tests.rs | 24 ++ distributed_macros/src/portable_command.rs | 16 +- distributed_macros/src/sourced.rs | 59 ++++- src/command/mod.rs | 6 +- src/command/projections.rs | 55 +++++ src/command/tests.rs | 77 ++++++ src/command/typed_command.rs | 19 +- src/microsvc/service/routes.rs | 14 +- tests/fixtures/flat_member_delete.graphql | 3 + tests/sourced/flat_preview.rs | 269 +++++++++++++++++++++ 12 files changed, 549 insertions(+), 43 deletions(-) create mode 100644 tests/fixtures/flat_member_delete.graphql diff --git a/README.md b/README.md index 7fe3a5724..c9eaae176 100644 --- a/README.md +++ b/README.md @@ -880,8 +880,47 @@ calls to the same recorder disagree, only their shared constants are retained. This does not predict authorization or guarantee an event will occur. Snapshot events continue to infer known values from recorder state assignments. +Public transitions can delegate to shared decision helpers in the same +`#[sourced]` impl. For example, `leave` and an owner-authorized `remove_member` +can both call a private `self.remove_member_decision(...)`. Each gets its own +`domain_commands::Leave` / `domain_commands::RemoveMember` witness containing +the outward events reachable through those helpers. Discovery follows static +`self.method(...)` calls, deduplicates events, and terminates on recursive helper +graphs. It does not follow foreign receivers or helpers outside the impl, and +does not propagate argument values through helpers. Literal arguments at the +recorder call still participate in the same conservative inference. + +For an event whose body contains the authenticated principal, bind that one +field using the existing command API: + +```rust,ignore +command_transition::>("group.leave") + .authenticated_user_field::( + "user_id", + ) +``` + +The second type is the exact serialized body. Use the flat event itself for +`domain = event` or `#[derive(DomainEvent)]`; state-capture events continue to +use their `DomainState` type. The equivalent `portable_command!` entry is: + +```rust,ignore +authenticated_user_field: ( + GroupMemberRemovedDomainEvent, + GroupMemberRemovedDomainEvent, + "user_id" +), +``` + +This gives a membership-delete projection the trusted `x-user-id` key without +adding a caller-controlled user ID to the command input. The framework checks +the exact event/body descriptor and serialized string field, including Serde +renames. The handler must still obtain the principal from its authenticated +session and enforce membership rules; this declaration only supplies the +generated preview's provenance. + See [the executable contract tests](tests/sourced/flat_preview.rs), including -the generated GraphQL client manifest and conflicting/dynamic-value cases. +the generated delete-projection client, helper replay and conflicting/dynamic-value cases. ### Durable Stream Identity diff --git a/distributed_macros/src/domain_event.rs b/distributed_macros/src/domain_event.rs index f94934981..cdc2cc56b 100644 --- a/distributed_macros/src/domain_event.rs +++ b/distributed_macros/src/domain_event.rs @@ -85,6 +85,15 @@ pub(crate) fn expand_domain_event(input: DeriveInput) -> syn::Result for #name {} + impl #framework::command::CommandProjectionBody for #name { + fn command_projection_descriptor( + _: &'static str, + _: u64, + ) -> #framework::DomainEventDescriptor { + ::DESCRIPTOR.clone() + } + } + impl #framework::projection::lower::ProjectionBodyMetadata for #name { #projection_metadata } diff --git a/distributed_macros/src/entry_tests.rs b/distributed_macros/src/entry_tests.rs index db362a09b..503e2cd42 100644 --- a/distributed_macros/src/entry_tests.rs +++ b/distributed_macros/src/entry_tests.rs @@ -257,6 +257,30 @@ mod tests { ); } + #[test] + fn sourced_helpers_ignore_other_receivers_and_nested_item_self() { + let output = sourced::expand_sourced( + quote! { entity, aggregate_type = "todo" }, + quote! { + impl Todo { + pub fn unrelated(&mut self, other: &mut Todo) { + other.record_completed().unwrap(); + struct Other; + impl Other { + fn action(&mut self) { self.record_completed(); } + } + } + #[event("todo.completed", domain = event)] + fn record_completed(&mut self) {} + } + }, + ) + .unwrap() + .to_string(); + assert!(!output.contains("pub enum Unrelated"), "{output}"); + assert!(!output.contains("pub mod domain_commands"), "{output}"); + } + #[test] fn expand_sourced_identity_mode_generates_independent_public_descriptor() { let attr = quote! { diff --git a/distributed_macros/src/portable_command.rs b/distributed_macros/src/portable_command.rs index 5ca69efdb..a8f636f2b 100644 --- a/distributed_macros/src/portable_command.rs +++ b/distributed_macros/src/portable_command.rs @@ -10,7 +10,7 @@ use syn::{parenthesized, Expr, Ident, LitStr, Token, Type}; struct AuthenticatedUserField { event: Type, - state: Type, + body: Type, field: LitStr, } @@ -20,18 +20,14 @@ impl Parse for AuthenticatedUserField { parenthesized!(values in input); let event = values.parse()?; values.parse::()?; - let state = values.parse()?; + let body = values.parse()?; values.parse::()?; let field = values.parse()?; if !values.is_empty() { return Err(values - .error("authenticated_user_field expects (EventType, StateType, \"field_name\")")); + .error("authenticated_user_field expects (EventType, BodyType, \"field_name\")")); } - Ok(Self { - event, - state, - field, - }) + Ok(Self { event, body, field }) } } @@ -217,9 +213,9 @@ pub fn expand(input: TokenStream) -> syn::Result { }); let authenticated_user_field = args.authenticated_user_field.as_ref().map(|value| { let event = &value.event; - let state = &value.state; + let body = &value.body; let field = &value.field; - quote! { .authenticated_user_field::<#event, #state>(#field) } + quote! { .authenticated_user_field::<#event, #body>(#field) } }); let preview_reduce_known_record = args.preview_reduce_known_record.as_ref().map(|preview| { quote! { diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index b96f63d57..df72ba90e 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -458,6 +458,15 @@ fn expand_domain_capture( impl distributed::domain_event::DomainEventBodyContract for #body_type {} + impl distributed::command::CommandProjectionBody for #body_type { + fn command_projection_descriptor( + _: &'static str, + _: u64, + ) -> distributed::DomainEventDescriptor { + ::DESCRIPTOR.clone() + } + } + impl distributed::projection::lower::ProjectionBodyMetadata for #body_type { #projection_metadata } @@ -1164,15 +1173,24 @@ fn discover_domain_command_transitions( return Vec::new(); } + // Only decision methods belong in the helper graph. A recorder's rewritten + // implementation includes replay/capture plumbing, not another decision. + let methods = impl_block + .items + .iter() + .filter_map(|item| match item { + syn::ImplItem::Fn(method) + if !event_methods + .iter() + .any(|event| event.method_name == method.sig.ident) => + { + Some((method.sig.ident.to_string(), method)) + } + _ => None, + }) + .collect::>(); let mut transitions = Vec::new(); - for item in &impl_block.items { - let syn::ImplItem::Fn(method) = item else { - continue; - }; - // Domain recorders themselves are not command transitions. - if recorders.contains_key(&method.sig.ident.to_string()) { - continue; - } + for (name, method) in &methods { if !matches!(method.vis, syn::Visibility::Public(_)) { continue; } @@ -1180,8 +1198,20 @@ fn discover_domain_command_transitions( let mut finder = DomainEventCallFinder { recorders: &recorders, found: std::collections::BTreeMap::new(), + calls: std::collections::BTreeSet::new(), }; - finder.visit_block(&method.block); + let mut pending = vec![name.clone()]; + let mut visited = std::collections::BTreeSet::new(); + while let Some(name) = pending.pop() { + if !visited.insert(name.clone()) { + continue; + } + let Some(callee) = methods.get(&name) else { + continue; + }; + finder.visit_block(&callee.block); + pending.extend(std::mem::take(&mut finder.calls)); + } if finder.found.is_empty() { continue; } @@ -1196,9 +1226,14 @@ fn discover_domain_command_transitions( struct DomainEventCallFinder<'a> { recorders: &'a std::collections::BTreeMap, found: std::collections::BTreeMap, + calls: std::collections::BTreeSet, } impl<'ast> Visit<'ast> for DomainEventCallFinder<'_> { + // A nested function/impl has its own receiver scope. Its `self` must not + // be confused with the aggregate, even when a method name happens to match. + fn visit_item(&mut self, _: &'ast syn::Item) {} + fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) { if is_self_receiver(&node.receiver) { if let Some(command_event) = self.recorders.get(&node.method.to_string()) { @@ -1227,6 +1262,8 @@ impl<'ast> Visit<'ast> for DomainEventCallFinder<'_> { }); }) .or_insert(candidate); + } else { + self.calls.insert(node.method.to_string()); } } syn::visit::visit_expr_method_call(self, node); @@ -1436,8 +1473,8 @@ fn expand_domain_commands_module( }); let doc = format!( "Outward domain-event set for `{aggregate_name}::{method_name}`.\n\n\ - Derived from direct `self.()` calls to `#[event(..., domain)]` \ - methods in this `#[sourced]` impl. Use with \ + Derived from `self.()` calls to `#[event(..., domain)]` \ + methods, including through decision helpers in this `#[sourced]` impl. Use with \ [`distributed::command::TypedCommand::emits_events`]." ); quote! { diff --git a/src/command/mod.rs b/src/command/mod.rs index 47915df88..81b8ff028 100644 --- a/src/command/mod.rs +++ b/src/command/mod.rs @@ -60,14 +60,14 @@ pub(crate) use projection_obligations::InputDefaultGenerator; pub(crate) use projection_obligations::{ validate_projection_confirmation_count, CommandInputDefault, CommandProjectionConfirmation, }; -pub(crate) use projections::CommandProjectionEvents; pub use projections::{ __command_projection_event_descriptor, __command_projection_event_preview, __command_projection_events, __command_projection_preview_constant, __command_projection_state_known_values, __command_projection_state_preview, CommandEventSet, - CommandProjectionEventSet, CommandProjectionPreview, CommandProjectionPreviewSource, - CommandProjectionPureArg, CommandProjectionPureReduce, + CommandProjectionBody, CommandProjectionEventSet, CommandProjectionPreview, + CommandProjectionPreviewSource, CommandProjectionPureArg, CommandProjectionPureReduce, }; +pub(crate) use projections::{authenticated_user_field_preview, CommandProjectionEvents}; // Re-exported for unit tests that resolve obligations through this module path. #[cfg_attr(not(test), allow(unused_imports))] pub(crate) use projection_obligations::{ diff --git a/src/command/projections.rs b/src/command/projections.rs index 20c00e587..ce51ba4a7 100644 --- a/src/command/projections.rs +++ b/src/command/projections.rs @@ -382,6 +382,12 @@ impl CommandProjectionEvents { ); return; } + if values.fields[0].body_type != Some(ProjectionPortableType::String) { + self.declaration_errors.push(format!( + "authenticated-user inference field `{rust_field}` must be a string body field" + )); + return; + } self.add_inferred_values(values); } @@ -627,6 +633,55 @@ pub fn __command_projection_event_descriptor( Ok(descriptor) } +/// Exact body descriptor used for authenticated command preview fields. +/// +/// State bodies receive this implementation automatically through `DomainState`. +/// `DomainEvent` derives and sourced flat event bodies implement it directly. +#[doc(hidden)] +pub trait CommandProjectionBody: Serialize + ProjectionBodyMetadata { + fn command_projection_descriptor( + event_name: &'static str, + event_version: u64, + ) -> DomainEventDescriptor; +} + +impl CommandProjectionBody for S { + fn command_projection_descriptor( + event_name: &'static str, + event_version: u64, + ) -> DomainEventDescriptor { + DomainEventDescriptor::state::(event_name, event_version) + } +} + +pub(crate) fn authenticated_user_field_preview( + rust_field: &'static str, +) -> CommandProjectionPreview +where + E: DomainEventBodyContract, + B: CommandProjectionBody, +{ + let descriptor = __command_projection_event_descriptor::().and_then(|descriptor| { + let expected = B::command_projection_descriptor(E::EVENT_NAME, E::EVENT_VERSION); + if descriptor != expected + || !matches!(descriptor.body.kind, DomainEventBodyKind::State | DomainEventBodyKind::Event) + { + return Err(format!( + "authenticated-user event contract `{}` differs from its exact typed body descriptor", + E::EVENT_NAME + )); + } + Ok(descriptor) + }); + structured_preview::( + __command_projection_events([descriptor]), + vec![( + rust_field, + CommandProjectionPreviewSource::trusted("x-user-id", "string"), + )], + ) +} + /// Build a structured state preview from generated body metadata. #[doc(hidden)] pub fn __command_projection_state_preview( diff --git a/src/command/tests.rs b/src/command/tests.rs index e80dc9c96..a5339bf26 100644 --- a/src/command/tests.rs +++ b/src/command/tests.rs @@ -284,6 +284,83 @@ fn authenticated_user_field_reuses_generated_event_schema_metadata() { ); assert_eq!(field.body_nullable, Some(false)); assert_eq!(field.body_always_present, Some(true)); + let previous = __command_projection_state_known_values::(vec![( + "status", + CommandProjectionPreviewSource::trusted("x-user-id", "string"), + )]); + assert_eq!(contract.projections.inferred_values[0].preview, previous); +} + +#[derive(Serialize, crate::DomainEvent)] +#[domain_event(name = "membership.removed", version = 1)] +struct MembershipRemoved { + #[serde(rename = "memberId")] + user_id: String, + revision: u64, + #[serde(skip)] + internal: String, +} + +impl crate::domain_event::DomainEventBodyContract for TodoCompleted {} + +#[test] +fn authenticated_flat_event_field_preserves_wire_name_and_rejects_invalid_bindings() { + let body = MembershipRemoved { + user_id: "member-1".into(), + revision: 1, + internal: "not serialized".into(), + }; + assert_eq!(body.internal, "not serialized"); + assert!(serde_json::to_value(&body) + .unwrap() + .get("internal") + .is_none()); + let command = |field| { + super::command_transition::>("member.leave") + .authenticated_user_field::(field) + .into_contract() + }; + let valid = command("user_id"); + TypedServiceCommandBinding::from_contracts("members", std::slice::from_ref(&valid)).unwrap(); + let field = &valid.projections.inferred_values[0].preview.fields[0]; + assert_eq!(field.body_path, ["memberId"]); + assert_eq!( + field.source, + CommandProjectionPreviewSource::trusted("x-user-id", "string") + ); + + for name in ["missing", "internal", "memberId", "revision"] { + assert!( + TypedServiceCommandBinding::from_contracts("members", &[command(name)]).is_err(), + "{name}" + ); + } + let mismatched = typed_command::>("todo.bad-body") + .emits(crate::events![DishonestStateContract]) + .authenticated_user_field::("status") + .into_contract(); + assert!( + TypedServiceCommandBinding::from_contracts("members", &[mismatched]) + .unwrap_err() + .contains("differs from its exact typed body descriptor") + ); + let mismatched_flat = typed_command::>("todo.bad-flat-body") + .emits(crate::events![TodoCompleted]) + .authenticated_user_field::("user_id") + .into_contract(); + assert!( + TypedServiceCommandBinding::from_contracts("members", &[mismatched_flat]) + .unwrap_err() + .contains("differs from its exact typed body descriptor") + ); + let undeclared = typed_command::>("member.undeclared") + .authenticated_user_field::("user_id") + .into_contract(); + assert!( + TypedServiceCommandBinding::from_contracts("members", &[undeclared]) + .unwrap_err() + .contains("outside its exact emitted event set") + ); } #[test] diff --git a/src/command/typed_command.rs b/src/command/typed_command.rs index a51e1db66..7bc86a0a0 100644 --- a/src/command/typed_command.rs +++ b/src/command/typed_command.rs @@ -21,8 +21,7 @@ use super::projection_obligations::{ }; use super::projection_proof::{canonical_json, CommandCommitProofError}; use super::projections::{ - CommandProjectionEvents, CommandProjectionPreview, CommandProjectionPreviewSource, - CommandProjectionPureReduce, + CommandProjectionEvents, CommandProjectionPreview, CommandProjectionPureReduce, }; use super::types::{scalar_type_name, CommandInputType, CommandTypeDef}; use crate::microsvc::Session; @@ -701,7 +700,10 @@ impl TypedCommand { self } - /// Declare that one emitted state field is the authenticated user id. + /// Declare that one emitted event-body field is the authenticated user id. + /// + /// `B` is the serialized body: a `DomainState` for state capture, or the + /// `DomainEvent` type itself for a flat event. Both use the same binding. /// /// This supplies the missing trusted `x-user-id` provenance to automatic /// event→mutation optimism when the projected model is not owner-filtered @@ -709,15 +711,12 @@ impl TypedCommand { /// command or rewrite handler input: the mount must still require a user /// and the handler must bind the same principal from its session. #[must_use] - pub fn authenticated_user_field(mut self, rust_field: &'static str) -> Self + pub fn authenticated_user_field(mut self, rust_field: &'static str) -> Self where - E: crate::domain_event::DomainEventBodyContract, - S: crate::DomainState + crate::projection::lower::ProjectionBodyMetadata, + E: crate::domain_event::DomainEventBodyContract, + B: super::CommandProjectionBody, { - let values = super::__command_projection_state_known_values::(vec![( - rust_field, - CommandProjectionPreviewSource::trusted("x-user-id", "string"), - )]); + let values = super::projections::authenticated_user_field_preview::(rust_field); self.contract .projections .add_authenticated_user_field(rust_field, values); diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 2f61bbcc0..33fb50819 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -651,20 +651,18 @@ where self } - /// Declare that one emitted state field is the authenticated `x-user-id`. + /// Declare that one emitted state or flat event-body field is the + /// authenticated `x-user-id`. `B` is the exact serialized body type. /// /// This is preview provenance only; command admission and handler-side /// principal binding remain mandatory. #[must_use] - pub fn authenticated_user_field(mut self, rust_field: &'static str) -> Self + pub fn authenticated_user_field(mut self, rust_field: &'static str) -> Self where - E: crate::domain_event::DomainEventBodyContract, - S: crate::DomainState + crate::projection::lower::ProjectionBodyMetadata, + E: crate::domain_event::DomainEventBodyContract, + B: crate::command::CommandProjectionBody, { - let values = crate::command::__command_projection_state_known_values::(vec![( - rust_field, - crate::command::CommandProjectionPreviewSource::trusted("x-user-id", "string"), - )]); + let values = crate::command::authenticated_user_field_preview::(rust_field); self.contract .projections .add_authenticated_user_field(rust_field, values); diff --git a/tests/fixtures/flat_member_delete.graphql b/tests/fixtures/flat_member_delete.graphql new file mode 100644 index 000000000..0f123cb33 --- /dev/null +++ b/tests/fixtures/flat_member_delete.graphql @@ -0,0 +1,3 @@ +mutation DeleteFlatMember { + delete_flat_members_by_pk(id: $input.member.id, user_id: $input.member.user_id) +} diff --git a/tests/sourced/flat_preview.rs b/tests/sourced/flat_preview.rs index 0dafe7cc9..4842ae52d 100644 --- a/tests/sourced/flat_preview.rs +++ b/tests/sourced/flat_preview.rs @@ -9,6 +9,64 @@ struct Review { #[distributed::sourced(entity, events = "ReviewEvent", aggregate_type = "review")] impl Review { + pub fn approve_via_helper(&mut self, id: String) -> distributed::SourcedResult { + self.recursive_helper(id, 2) + } + + fn recursive_helper(&mut self, id: String, remaining: u8) -> distributed::SourcedResult { + if remaining > 0 { + self.recursive_helper(id, remaining - 1) + } else { + self.approve(id) + } + } + + pub fn conflicting_helpers(&mut self, id: String) -> distributed::SourcedResult { + self.approve(id.clone())?; + self.reject(id) + } + + pub fn forwarded_literal(&mut self, id: String) -> distributed::SourcedResult { + self.status_helper(id, "approved".into()) + } + + fn status_helper(&mut self, id: String, status: String) -> distributed::SourcedResult { + self.record_status(id, status, true, 25, None, None)?; + Ok(()) + } + + pub fn approve_then_leave( + &mut self, + id: String, + user_id: String, + ) -> distributed::SourcedResult { + self.approve(id.clone())?; + self.leave(id, user_id) + } + + pub fn leave(&mut self, id: String, user_id: String) -> distributed::SourcedResult { + self.remove_member_decision(id, user_id) + } + + pub fn remove_member(&mut self, id: String, user_id: String) -> distributed::SourcedResult { + self.remove_member_decision(id, user_id) + } + + fn remove_member_decision( + &mut self, + id: String, + user_id: String, + ) -> distributed::SourcedResult { + self.record_member_removed(id, user_id)?; + Ok(()) + } + + #[event("review.member_removed", version = 1, domain = event)] + fn record_member_removed(&mut self, id: String, user_id: String) { + self.entity.set_id(id); + self.status = user_id; + } + pub fn approve(&mut self, id: String) -> distributed::SourcedResult { self.record_status( id, @@ -97,6 +155,68 @@ fn fields() -> Value { Value::Object(fields) } +#[tokio::test] +async fn shared_recursive_helpers_preserve_contracts_captures_and_replay() { + use distributed::AggregateBuilder; + + assert_eq!( + domain_commands::ApproveViaHelper::command_event_set(), + domain_commands::Approve::command_event_set(), + ); + assert_eq!( + fields::(), + fields::(), + ); + assert!(fields::() + .get("status") + .is_none()); + assert_eq!( + domain_commands::Leave::command_event_set(), + domain_commands::RemoveMember::command_event_set(), + ); + assert_eq!( + domain_commands::Leave::command_event_set(), + ::command_event_set(), + ); + assert_eq!( + domain_commands::ApproveThenLeave::command_event_set(), + distributed::events![ + ReviewMemberRemovedDomainEvent, + ReviewStatusRecordedDomainEvent + ], + ); + assert!(fields::() + .get("status") + .is_none()); + assert!(domain_commands::Leave::command_event_known_values().is_empty()); + + let mut review = Review::default(); + review.approve_via_helper("r1".into()).unwrap(); + review.conflicting_helpers("r1".into()).unwrap(); + review.forwarded_literal("r1".into()).unwrap(); + review + .approve_then_leave("r1".into(), "member-0".into()) + .unwrap(); + review.leave("r1".into(), "member-1".into()).unwrap(); + review + .remove_member("r1".into(), "member-2".into()) + .unwrap(); + let body: ReviewMemberRemovedDomainEvent = review + .entity + .pending_domain_events() + .last() + .unwrap() + .decode_body() + .unwrap(); + assert_eq!(body.id, "r1"); + assert_eq!(body.user_id, "member-2"); + let repository = distributed::InMemoryRepository::new().aggregate::(); + repository.commit(&mut review).await.unwrap(); + let loaded = repository.get("r1").await.unwrap().unwrap(); + assert_eq!(loaded.status, "member-2"); + assert!(loaded.entity.pending_domain_events().is_empty()); +} + #[test] fn flat_constants_match_recorded_body_without_running_the_command() { let values = fields::(); @@ -184,6 +304,13 @@ mod client_contract { status: String, } + #[derive(Clone, Default, Serialize, Deserialize, distributed::ReadModel)] + #[readmodel(table = "flat_members", primary_key = ["id", "user_id"])] + struct FlatMembers { + id: String, + user_id: String, + } + #[derive(Deserialize, distributed::CommandInput)] struct Input { id: String, @@ -206,6 +333,36 @@ mod client_contract { }; } + #[allow(non_snake_case)] + fn DeleteFlatMember() -> Mutation<()> { + distributed::mutation_file!("tests/fixtures/flat_member_delete.graphql") + } + + distributed::projection! { + const MEMBERS: ProjectionDescriptor = { + name: "flat_members", version: 1, epoch: "flat-members-v1", + model: FlatMembers, source: aggregate_snapshot, + on { events: [ReviewMemberRemovedDomainEvent], mutation: DeleteFlatMember, + input: {member: body}, }, + }; + } + + distributed::portable_command! { + name: "review.leave", + transition: domain_commands::Leave, + aggregate: Review, + input: Input, + outcome: Eventual, + shard: |input| input.id.clone(), + roles: ["user"], + field: "review_leave", + authenticated_user_field: ( + ReviewMemberRemovedDomainEvent, ReviewMemberRemovedDomainEvent, "user_id" + ), + guard: |ctx| ctx.session().user_id().is_some(), + handle: metadata_only, + } + async fn metadata_only( _ctx: &CausalCommandContext<'_, Review>, _input: Input, @@ -214,6 +371,118 @@ mod client_contract { panic!("manifest compilation must not execute a command") } + #[test] + fn authenticated_flat_delete_compiles_from_typed_and_portable_commands() { + use distributed::graphql::{ + ClientCommandShape, ClientProjectionExpression, ClientProjectionMutationKind, + }; + use distributed_cli::{ + compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, + }; + + let mounts = LocalProjectionMountsBuilder::new("members", "events") + .unwrap() + .eventual_model::("flat_members", MEMBERS, MEMBERS.epoch()) + .unwrap() + .build() + .unwrap(); + let mut previous = None; + for portable in [false, true] { + let routes = Routes::new().with_repo(AggregateRepository::<_, Review>::new( + InMemoryRepository::new(), + )); + let routes = if portable { + routes.mount(leave()) + } else { + routes.typed_command( + distributed::command::command_transition::>("review.leave") + .roles(["user"]) + .field_name("review_leave") + .authenticated_user_field::("user_id") + ).guarded(|ctx| ctx.session().user_id().is_some(), metadata_only) + }; + let service = Service::new().named("members").routes(routes); + let surface = build_surface( + &[FlatMembers::schema().clone()], + &SurfaceOptions::postgres(), + ) + .unwrap() + .with_projectors([mounts.projector("flat_members").unwrap()]) + .unwrap() + .with_service(&service) + .unwrap(); + let selected = surface_for_role( + &surface, + "user", + &std::collections::BTreeMap::from([( + "FlatMembers".into(), + RoleGrant::all_columns(), + )]), + ) + .unwrap(); + let manifest = DistributedClientSurfaceExport::from_selected("members", selected) + .unwrap() + .manifest() + .unwrap(); + let command = &manifest.commands[0]; + let ClientCommandShape::Object { definition } = &command.input else { + panic!("input object") + }; + assert_eq!( + definition + .fields + .iter() + .map(|field| field.name.as_str()) + .collect::>(), + ["id"] + ); + let projection = command.extensions.projection.as_ref().unwrap(); + assert_eq!(projection.preview_occurrences.len(), 1); + let operation = &manifest.projection_programs[0].arms[0].operations[0]; + assert_eq!(operation.kind, ClientProjectionMutationKind::Delete); + let key = operation + .key + .iter() + .find(|field| field.name == "user_id") + .unwrap(); + let ClientProjectionExpression::Slot { slot, .. } = &key.expression else { + panic!("user key slot") + }; + let value = projection.preview_occurrences[0] + .values + .iter() + .find(|value| &value.slot == slot) + .unwrap(); + assert_eq!( + value.source, + ClientProjectionPreviewSource::TrustedPreset { + name: "x-user-id".into(), + codec: "string".into() + } + ); + assert_eq!(command.extensions.trusted_presets.len(), 1); + assert_eq!(command.extensions.trusted_presets[0].name, "x-user-id"); + + let compiled = compile_client(ClientCompileInput::new( + serde_json::to_value(&manifest).unwrap(), + ClientSurfaceSelector::role("user"), + vec![ClientDocument::new( + "src/routes/members/+page.graphql", + "query Members @load { flat_members { id user_id } }", + )], + )) + .unwrap(); + assert_eq!(compiled.operations.len(), 1); + if let Some(previous) = &previous { + assert_eq!( + &compiled, previous, + "typed and portable registration must compile identically" + ); + } + previous = Some(compiled); + } + } + #[test] fn flat_domain_constant_reaches_generated_projection_slots() { let mounts = LocalProjectionMountsBuilder::new("reviews", "events") From fd3473f1802a30957e6e1b8a544cdd58f4ce39e9 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sat, 12 Sep 2026 20:25:18 -0500 Subject: [PATCH 099/484] fix: preserve custom sourced event body paths Keep command witness implementations in the aggregate lexical scope and use declared custom body contracts. Cover nested helper paths, exact metadata, captures and replay. Reapplies the verified fix from a5142aa1 onto the rebased PR 250 head. Resolves [[incidents/distributed-pr250-nested-sourced-paths-20260912]] --- README.md | 4 +- distributed_macros/src/entry_tests.rs | 36 +++++++ distributed_macros/src/sourced.rs | 61 +++++++----- tests/sourced/custom_body_helpers.rs | 131 ++++++++++++++++++++++++++ tests/sourced/domain_events.rs | 17 +++- tests/sourced/main.rs | 1 + 6 files changed, 224 insertions(+), 26 deletions(-) create mode 100644 tests/sourced/custom_body_helpers.rs diff --git a/README.md b/README.md index c9eaae176..e5b292922 100644 --- a/README.md +++ b/README.md @@ -888,7 +888,9 @@ the outward events reachable through those helpers. Discovery follows static `self.method(...)` calls, deduplicates events, and terminates on recursive helper graphs. It does not follow foreign receivers or helpers outside the impl, and does not propagate argument values through helpers. Literal arguments at the -recorder call still participate in the same conservative inference. +recorder call still participate in the same conservative inference. Custom +`domain = with(Body, adapter)` events use the declared body contract, including +qualified or relative type paths; adapter output is not inferred as constants. For an event whose body contains the authenticated principal, bind that one field using the existing command API: diff --git a/distributed_macros/src/entry_tests.rs b/distributed_macros/src/entry_tests.rs index 503e2cd42..5ec906a1a 100644 --- a/distributed_macros/src/entry_tests.rs +++ b/distributed_macros/src/entry_tests.rs @@ -281,6 +281,42 @@ mod tests { assert!(!output.contains("pub mod domain_commands"), "{output}"); } + #[test] + fn sourced_helper_custom_body_uses_declared_type_contract() { + for output_type in [ + quote!(crate::facts::BranchCreated), + quote!(super::facts::BranchCreated), + quote!(BranchCreated), + ] { + let output = sourced::expand_sourced( + quote! { entity, aggregate_type = "repository" }, + quote! { + impl Repository { + pub fn create(&mut self) { self.create_refs().unwrap(); } + fn create_refs(&mut self) { self.record_branch().unwrap(); } + #[event( + "repository.branch_created", + domain = with(#output_type, branch_created) + )] + fn record_branch(&mut self) {} + } + }, + ) + .unwrap() + .to_string(); + let descriptor = quote! { + distributed::command::__command_projection_event_descriptor::<#output_type,>() + } + .to_string(); + assert!(output.contains(&descriptor), "{output}"); + assert!(output.contains("for domain_commands :: Create"), "{output}"); + assert!( + !output.contains("RepositoryBranchCreatedDomainEvent"), + "{output}" + ); + } + } + #[test] fn expand_sourced_identity_mode_generates_independent_public_descriptor() { let attr = quote! { diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index df72ba90e..3e16ea43e 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -215,14 +215,14 @@ struct EventMethodInfo { version: syn::LitInt, method_name: Ident, params: Vec<(Ident, syn::Type)>, - /// Present when this recorder has `domain` and therefore a generated - /// outward domain-event marker type. + /// Present when this recorder has `domain` and therefore an exact outward + /// event contract (a generated marker or the explicitly declared body). command_event: Option, } #[derive(Clone)] struct DomainCommandEvent { - domain_event_type: Ident, + domain_event_type: Type, domain_state: Option, known_state_values: Vec, body_params: Vec<(Ident, Type)>, @@ -823,12 +823,19 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res ); method.block = new_body; - let command_event = if event_attr.domain.is_some() { + let command_event = if let Some(mode) = event_attr.domain.as_ref() { + let domain_event_type = match mode { + DomainMode::With { output, .. } => (**output).clone(), + _ => { + let marker = identity_domain_event_type( + &struct_name, + &event_attr.event_name, + )?; + syn::parse_quote!(#marker) + } + }; Some(DomainCommandEvent { - domain_event_type: identity_domain_event_type( - &struct_name, - &event_attr.event_name, - )?, + domain_event_type, domain_state: state_domain.then(|| args.domain_state.clone()).flatten(), known_state_values, body_params: if matches!(event_attr.domain, Some(DomainMode::Event)) { @@ -1249,8 +1256,9 @@ impl<'ast> Visit<'ast> for DomainEventCallFinder<'_> { }) }) .collect(); + let event_type = &command_event.domain_event_type; self.found - .entry(command_event.domain_event_type.to_string()) + .entry(quote!(#event_type).to_string()) .and_modify(|existing| { // A single event type can occur more than once, including // through branches. Only values shared by every call are known. @@ -1421,7 +1429,9 @@ fn expand_domain_commands_module( return TokenStream2::new(); } - let transition_items = transitions.iter().map(|transition| { + let mut transition_items = Vec::new(); + let mut transition_impls = Vec::new(); + for transition in transitions { let type_name = method_name_to_type_ident(&transition.method_name); let method_name = transition.method_name.to_string(); let aggregate_name = aggregate.to_string(); @@ -1437,9 +1447,9 @@ fn expand_domain_commands_module( } let event_type = &event.domain_event_type; let helper = if let Some(state) = &event.domain_state { - quote!(distributed::command::__command_projection_state_known_values::) + quote!(distributed::command::__command_projection_state_known_values::<#event_type, #state>) } else { - quote!(distributed::command::__command_projection_event_preview::) + quote!(distributed::command::__command_projection_event_preview::<#event_type, #event_type>) }; let fields = values.iter().map(|value| { let field = value.field.to_string(); @@ -1457,16 +1467,13 @@ fn expand_domain_commands_module( #helper(vec![#(#fields),*]) }) }); - let has_known_values = transition - .events - .iter() - .any(|event| !event.known_state_values.is_empty() || !event.known_body_values.is_empty()); + let has_known_values = transition.events.iter().any(|event| { + !event.known_state_values.is_empty() || !event.known_body_values.is_empty() + }); let known_values_method = has_known_values.then(|| { quote! { fn command_event_known_values( ) -> Vec { - #[allow(unused_imports)] - use super::*; vec![#(#known_value_items),*] } } @@ -1477,16 +1484,21 @@ fn expand_domain_commands_module( methods, including through decision helpers in this `#[sourced]` impl. Use with \ [`distributed::command::TypedCommand::emits_events`]." ); - quote! { + transition_items.push(quote! { #[doc = #doc] pub enum #type_name {} - - impl distributed::command::CommandEventSet for #type_name { + }); + // Keep authored types in the aggregate's lexical scope. Moving an + // explicit `with(super::facts::Body, ...)` path inside domain_commands + // would silently change its meaning (and generated aliases do not exist + // for custom bodies). The public witness still lives in that module. + transition_impls.push(quote! { + impl distributed::command::CommandEventSet for domain_commands::#type_name { fn command_event_set() -> distributed::command::CommandProjectionEventSet { distributed::command::__command_projection_events([ #( distributed::command::__command_projection_event_descriptor::< - super::#event_types, + #event_types, >() ),* ]) @@ -1494,8 +1506,8 @@ fn expand_domain_commands_module( #known_values_method } - } - }); + }); + } let aggregate_name = aggregate.to_string(); let module_doc = format!( @@ -1512,6 +1524,7 @@ fn expand_domain_commands_module( pub mod domain_commands { #(#transition_items)* } + #(#transition_impls)* } } diff --git a/tests/sourced/custom_body_helpers.rs b/tests/sourced/custom_body_helpers.rs new file mode 100644 index 000000000..f8de7a1f5 --- /dev/null +++ b/tests/sourced/custom_body_helpers.rs @@ -0,0 +1,131 @@ +use distributed::{command::CommandEventSet, AggregateBuilder, DomainEvent}; + +mod facts { + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] + #[domain_event(name = "repository.branch_created", version = 2)] + pub struct BranchCreated { + pub repository_id: String, + pub name: String, + } + + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] + #[domain_event(name = "repository.tag_created", version = 1)] + pub struct TagCreated { + pub repository_id: String, + pub name: String, + } +} + +mod repository { + use std::cell::Cell; + + #[derive(Default)] + pub struct Repository { + pub entity: distributed::Entity, + pub branch: String, + pub tag: String, + pub adapter_calls: Cell, + } + + #[distributed::sourced(entity, events = "RepositoryEvent", aggregate_type = "repository")] + impl Repository { + pub fn create(&mut self, id: String) -> distributed::SourcedResult { + self.create_refs(id) + } + + fn create_refs(&mut self, id: String) -> distributed::SourcedResult { + self.create_branch(id.clone())?; + self.record_branch(id, "main".into())?; + self.record_tag("v1".into())?; + Ok(()) + } + + fn create_branch(&mut self, id: String) -> distributed::SourcedResult { + self.record_branch(id, "initial".into())?; + Ok(()) + } + + #[event( + "repository.branch_created", + version = 2, + domain = with(crate::custom_body_helpers::facts::BranchCreated, branch_created) + )] + fn record_branch(&mut self, id: String, name: String) { + self.entity.set_id(id); + self.branch = name; + } + + #[event( + "repository.tag_created", + version = 1, + domain = with(super::facts::TagCreated, tag_created) + )] + fn record_tag(&mut self, name: String) { + self.tag = name; + } + } + + fn branch_created( + repository: &Repository, + _event: &RepositoryEvent, + ) -> super::facts::BranchCreated { + repository + .adapter_calls + .set(repository.adapter_calls.get() + 1); + super::facts::BranchCreated { + repository_id: repository.entity.id().to_owned(), + name: repository.branch.clone(), + } + } + + fn tag_created(repository: &Repository, _event: &RepositoryEvent) -> super::facts::TagCreated { + repository + .adapter_calls + .set(repository.adapter_calls.get() + 1); + super::facts::TagCreated { + repository_id: repository.entity.id().to_owned(), + name: repository.tag.clone(), + } + } +} + +#[tokio::test] +async fn helper_custom_bodies_preserve_paths_descriptors_and_replay() { + // Neither RepositoryBranchCreatedDomainEvent nor RepositoryTagCreatedDomainEvent + // exists: custom bodies, not naming-convention aliases, own these contracts. + assert_eq!( + repository::domain_commands::Create::command_event_set(), + distributed::events![facts::BranchCreated, facts::TagCreated], + ); + // Adapter output cannot be inferred from recorder arguments, even literals. + assert!(repository::domain_commands::Create::command_event_known_values().is_empty()); + + let mut aggregate = repository::Repository::default(); + aggregate.create("repo-1".into()).unwrap(); + let events = aggregate.entity.pending_domain_events(); + assert_eq!(events.len(), 3); + assert_eq!(aggregate.adapter_calls.get(), 3); + assert_eq!(events[0].descriptor(), &facts::BranchCreated::DESCRIPTOR); + assert_eq!(events[1].descriptor(), &facts::BranchCreated::DESCRIPTOR); + assert_eq!(events[2].descriptor(), &facts::TagCreated::DESCRIPTOR); + let branch: facts::BranchCreated = events[1].decode_body().unwrap(); + assert_eq!(branch.repository_id, "repo-1"); + assert_eq!(branch.name, "main"); + let tag: facts::TagCreated = events[2].decode_body().unwrap(); + assert_eq!(tag.repository_id, "repo-1"); + assert_eq!(tag.name, "v1"); + + let store = distributed::InMemoryRepository::new().aggregate::(); + store.commit(&mut aggregate).await.unwrap(); + let loaded = store.get("repo-1").await.unwrap().unwrap(); + assert_eq!(loaded.branch, "main"); + assert_eq!(loaded.tag, "v1"); + assert_eq!( + loaded.adapter_calls.get(), + 0, + "replay must not invoke adapters" + ); + assert!(loaded.entity.pending_domain_events().is_empty()); +} diff --git a/tests/sourced/domain_events.rs b/tests/sourced/domain_events.rs index 8d9dd0af6..22b0b0774 100644 --- a/tests/sourced/domain_events.rs +++ b/tests/sourced/domain_events.rs @@ -64,6 +64,15 @@ impl TodoLabelled { domain_state = DomainTodoState, )] impl DomainTodo { + pub fn label_via_helper(&mut self, label: String) -> distributed::SourcedResult { + self.label_helper(label) + } + + fn label_helper(&mut self, label: String) -> distributed::SourcedResult { + self.label(label)?; + Ok(()) + } + #[event("todo.created", version = 1, domain)] fn create(&mut self, todo_id: String, title: String) { self.entity.set_id(todo_id); @@ -192,11 +201,17 @@ fn identity_mode_reencodes_typed_fields_instead_of_reusing_replay_bytes() { #[test] fn custom_adapter_observes_the_successful_post_transition_state() { + use distributed::command::CommandEventSet; + + assert_eq!( + domain_commands::LabelViaHelper::command_event_set(), + ::command_event_set(), + ); let mut todo = DomainTodo::default(); todo.create("todo-1".into(), "First".into()).unwrap(); todo.complete().unwrap(); - todo.label("urgent".into()).unwrap(); + todo.label_via_helper("urgent".into()).unwrap(); let occurrence = todo.entity.pending_domain_events().last().unwrap(); let labelled = occurrence.decode_body::().unwrap(); diff --git a/tests/sourced/main.rs b/tests/sourced/main.rs index 81744562b..abc3b4992 100644 --- a/tests/sourced/main.rs +++ b/tests/sourced/main.rs @@ -1,4 +1,5 @@ mod aggregate; +mod custom_body_helpers; mod domain_events; mod flat_preview; From 2e394505b9cc21d561678a67726ed4ab1351ab5a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 13 Sep 2026 15:48:55 -0500 Subject: [PATCH 100/484] fix: accept key-only normalized projection manifests Allow complete operations to use an empty non-key field mask only when every exposed model field belongs to the normalized identity. Keep patch, key, and assignment validation unchanged. Implements [[tasks/graphql-qs-projection-model-15]] (cherry picked from commit 8b64e63f306da252fb5b64e799331e16ac464caa) --- .../client_compiler/manifest/projections.rs | 10 +- distributed_cli/src/client_compiler/tests.rs | 169 ++++++++++++++++++ 2 files changed, 178 insertions(+), 1 deletion(-) diff --git a/distributed_cli/src/client_compiler/manifest/projections.rs b/distributed_cli/src/client_compiler/manifest/projections.rs index 2543405b1..2e7cc5c0b 100644 --- a/distributed_cli/src/client_compiler/manifest/projections.rs +++ b/distributed_cli/src/client_compiler/manifest/projections.rs @@ -497,7 +497,15 @@ fn validate_operation( | ManifestProjectionMutationKind::Recreate | ManifestProjectionMutationKind::InsertRelated | ManifestProjectionMutationKind::UpsertRelated => { - if operation.fields.is_empty() { + // Identity assignments live in `key`, so a key-only normalized + // model has a complete row even with an empty non-key field mask. + if operation.fields.is_empty() + && model.fields.iter().any(|field| { + !identity + .iter() + .any(|key_field| key_field.name == field.name) + }) + { return Err(projection_error( "client.manifest.projection_field_mask", format!( diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 680458e6c..d455a4769 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -758,6 +758,175 @@ fn generated_command_types_manifest() -> JsonValue { value } +fn key_only_projection_manifest(composite: bool) -> JsonValue { + let mut value = generated_command_types_manifest(); + value["capabilities"]["live_queries"] = json!(false); + value["capabilities"]["live_resume"] = json!(false); + value["commands"][0]["extensions"]["consistency"]["kind"] = json!("eventual"); + value["commands"][0]["extensions"] + .as_object_mut() + .unwrap() + .remove("direct_projection"); + value["commands"][0]["output"]["definition"]["name"] = json!("ProjectTodoPayload"); + let key_names = if composite { + vec!["tenantId", "id"] + } else { + vec!["id"] + }; + value["models"][0]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["models"][0]["normalization"]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["models"][0]["filter_input"]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["roots"] = json!([by_pk_root()]); + value["roots"][0]["arguments"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + let arm = &mut value["projection_programs"][0]["arms"][0]; + arm["partition"] = json!({"kind": "unit"}); + arm["operations"][0]["fields"] = json!([]); + let key = arm["operations"][0]["key"].as_array_mut().unwrap(); + key.retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + for (ordinal, field) in key.iter_mut().enumerate() { + field["ordinal"] = json!(ordinal); + } + value["commands"][0]["extensions"]["projection"]["preview_occurrences"][0]["values"] + .as_array_mut() + .unwrap() + .retain(|slot| { + key_names + .iter() + .any(|name| slot["slot"] == format!("state.{name}")) + }); + refresh_schema_fingerprint(&mut value); + value +} + +#[test] +fn key_only_complete_projections_compile_identity_only_upserts() { + for composite in [false, true] { + for kind in [ + "insert", + "upsert", + "recreate", + "insert_related", + "upsert_related", + ] { + let mut value = key_only_projection_manifest(composite); + value["projection_programs"][0]["arms"][0]["operations"][0]["kind"] = json!(kind); + refresh_schema_fingerprint(&mut value); + let manifest = + ClientManifest::parse(value.clone(), &ClientSurfaceSelector::role("user")) + .unwrap_or_else(|error| panic!("{kind}, composite={composite}: {error}")); + let command = manifest + .commands + .iter() + .find(|command| command.extensions.projection.is_some()) + .expect("modeled command"); + let preview = super::projection_delta::compile_command_preview(command, &manifest) + .expect("compile identity-only preview") + .expect("projection preview"); + let preview = serde_json::to_value(preview).unwrap(); + assert_eq!( + preview["preview"]["operations"].as_array().unwrap().len(), + 1 + ); + let mutation = &preview["preview"]["operations"][0]["mutation"]; + assert_eq!(mutation["op"], "upsert"); + assert_eq!(mutation["fields"], json!([])); + assert_eq!(mutation["replace"], json!([])); + assert_eq!( + mutation["scope"]["key"].as_array().unwrap().len(), + if composite { 2 } else { 1 } + ); + assert_eq!(preview["preview"]["recoveries"], json!([])); + let query = if composite { + "query Todo { todo(id: \"1\", tenantId: \"tenant\") { id tenantId } }" + } else { + "query Todo { todo(id: \"1\") { id } }" + }; + let project = compile_client(ClientCompileInput::new( + value, + ClientSurfaceSelector::role("user"), + vec![ClientDocument::new("src/routes/todos/+page.graphql", query)], + )) + .expect("generate identity-only client"); + let commands = file(&project, "commands.ts"); + assert!(commands.contains("\"op\": \"upsert\"")); + assert!(commands.contains("\"fields\": []")); + assert!(commands.contains("\"replace\": []")); + } + } +} + +#[test] +fn key_only_projection_exception_preserves_field_mask_validation() { + for kind in [ + "insert", + "upsert", + "recreate", + "insert_related", + "upsert_related", + "patch", + "upsert_patch", + ] { + let mut value = generated_command_types_manifest(); + let operation = &mut value["projection_programs"][0]["arms"][0]["operations"][0]; + operation["kind"] = json!(kind); + operation["fields"] = json!([]); + refresh_schema_fingerprint(&mut value); + let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + .expect_err("non-key fields still require a field mask"); + assert_eq!( + error.code, "client.manifest.projection_field_mask", + "{kind}" + ); + } + for kind in ["patch", "upsert_patch"] { + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["kind"] = json!(kind); + refresh_schema_fingerprint(&mut value); + let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + .expect_err("key-only models do not allow empty patches"); + assert_eq!(error.code, "client.manifest.projection_field_mask"); + } + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["fields"] = json!([{ + "ordinal": 0, "name": "id", "assignment": {"kind": "set", "expression": { + "kind": "slot", "slot": "state.id", "value_type": {"type": "string"} + }} + }]); + refresh_schema_fingerprint(&mut value); + let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + .expect_err("identity must remain outside the field mask"); + assert_eq!(error.code, "client.manifest.projection_field_mask"); +} + +#[test] +fn key_only_projection_still_requires_the_exact_identity() { + for key in [ + json!([]), + json!([{"ordinal": 0, "name": "id", "expression": { + "kind": "slot", "slot": "state.id", "value_type": {"type": "string"} + }}]), + ] { + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["key"] = key; + refresh_schema_fingerprint(&mut value); + let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + .expect_err("missing composite identity fields must reject"); + assert_eq!(error.code, "client.manifest.projection_key"); + } +} + fn embedded_model_invalidation_manifest() -> JsonValue { let mut value = generated_command_types_manifest(); let command = &mut value["commands"][0]; From ce6c95041a51871dec3d6e85b87b069b55e3e2d3 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 13 Sep 2026 20:15:43 -0500 Subject: [PATCH 101/484] feat!: bind typed URL scalars to GraphQL variables Decode explicit built-in search scalars through shared generator/runtime bindings, retaining the operation codec as the validation and canonicalization authority. BREAKING CHANGE: searchParam requires a scalar argument; all mode moves to the third argument. Missing list parameters preserve GraphQL defaults. Regenerate v2 boundary plans and fingerprints with the runtime. Implements [[tasks/graphql-islands-4]] --- README.md | 2 +- js/README.md | 28 +++++- js/src/sveltekit/boundary-variables.ts | 77 ++++++++++------- js/src/sveltekit/index.ts | 1 + js/src/sveltekit/island-bindings.ts | 18 +++- js/src/sveltekit/islands/boundaries.ts | 33 +++---- js/src/sveltekit/search-variables.ts | 66 ++++++++++++++ js/src/sveltekit/server-replica.ts | 3 +- .../sveltekit-boundary-variables.test.mjs | 15 ++-- js/tests/sveltekit-search-scalars.test.mjs | 85 +++++++++++++++++++ js/tests/sveltekit-vite.test.mjs | 28 +++++- js/type-tests/sveltekit-adapter.ts | 24 +++++- 12 files changed, 314 insertions(+), 66 deletions(-) create mode 100644 js/src/sveltekit/search-variables.ts create mode 100644 js/tests/sveltekit-search-scalars.test.mjs diff --git a/README.md b/README.md index e5b292922..06602db7e 100644 --- a/README.md +++ b/README.md @@ -2052,7 +2052,7 @@ query SearchTodos($q: String! = "") @load @live { } ``` -A colocated binding can pass `q: searchParam('q')` directly. Callers do not +A colocated binding can pass `q: searchParam('q', 'String')` directly. Callers do not construct `%patterns%`: `%`, `_`, backslash, quotes and the escape character are literal text. The query engine binds an escaped pattern on both PostgreSQL and SQLite. An empty string matches every non-null string; use a bounded query diff --git a/js/README.md b/js/README.md index 8dbe828bf..91a27c420 100644 --- a/js/README.md +++ b/js/README.md @@ -173,7 +173,8 @@ import { } from '@hops-ops/distributed/sveltekit'; export default defineGraphqlIslandBindings({ - query: searchParam('q'), + query: searchParam('q', 'String'), + offset: searchParam('offset', 'Int'), viewerId: sessionClaim('user', 'id'), filters: forwardedProp('filters') }); @@ -187,6 +188,31 @@ any of those sources fails generation before transport. Central `boundaries` registrations remain an explicit-placement escape hatch and cannot be combined with a sidecar for the same operation. +Search bindings require an explicit built-in GraphQL scalar: `String`, `ID`, +`Int`, `Float`, or `Boolean`. Generation and runtime registration reject a +scalar or list shape that differs from the operation variable. For example, +`$offset: Int! = 0` with `searchParam('offset', 'Int')` resolves `?offset=20` +to the number `20`; an absent parameter retains the GraphQL default `0`. +`searchParam('id', 'ID', 'all')` binds repeated parameters to an `[ID!]` list +in URL order. Default `first` mode selects the first repeated value. Absent +parameters are omitted in both modes; nullable omission and required-variable +errors follow the operation codec. An empty string is a present value. + +Int and Float use strict decimal syntax, with no trimming, partial parsing, +hexadecimal, or leading plus/zeroes. Float additionally accepts a fraction +and/or exponent. Boolean accepts only `true` and `false`; String and ID retain +decoded URL text. Invalid values fail before transport, and errors omit their +contents. The operation codec still enforces Int's signed 32-bit range, list +limits, defaults, and canonical identity. JSON, enum and custom-scalar decoding +are not inferred from URL text. + +This is a breaking binding/adapter-plan v2 change: migrate `searchParam('q')` +to `searchParam('q', 'String')`, and the old second `all` argument to the third +argument after the scalar. Raw `search_param` sources must also include +`scalar`. Regenerate all boundary plans together with the runtime; v1 plans +and hydration fingerprints cannot be reused. Missing multi-value parameters +now preserve GraphQL defaults instead of producing an empty list. + The application lifecycle runs the client compiler before Vite starts and after declared GraphQL, binding, or Svelte ownership inputs change. Vite consumes the active immutable client tree and reloads its virtual modules only after atomic diff --git a/js/src/sveltekit/boundary-variables.ts b/js/src/sveltekit/boundary-variables.ts index 874e10e52..a3c3ba850 100644 --- a/js/src/sveltekit/boundary-variables.ts +++ b/js/src/sveltekit/boundary-variables.ts @@ -3,8 +3,14 @@ import { type ReplicaOperationArtifact } from '../replica/index.js'; import type { GraphqlVariables } from '../types.js'; +import type { ReplicaVariableInputRef } from '../replica/types.js'; +import { + decodeSearchScalar, + normalizeSearchParamSource, + type DistributedSearchParamSource +} from './search-variables.js'; -const BINDING_VERSION = 1; +export const DISTRIBUTED_BOUNDARY_BINDING_VERSION = 2; const GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/; const MAX_BINDING_VARIABLES = 128; const MAX_PATH_SEGMENTS = 16; @@ -12,13 +18,20 @@ const MAX_LITERAL_DEPTH = 32; const MAX_LITERAL_VALUES = 4_096; const HOSTILE_KEYS = new Set(['__proto__', 'prototype', 'constructor']); +type SearchScalarFor = + NonNullable extends string ? 'String' | 'ID' : + NonNullable extends number ? 'Int' | 'Float' : + NonNullable extends boolean ? 'Boolean' : never; + +type SearchSourceFor = unknown extends TValue + ? DistributedSearchParamSource + : NonNullable extends readonly (infer TItem)[] + ? DistributedSearchParamSource, 'all'> & { mode: 'all' } + : DistributedSearchParamSource, 'first'>; + export type DistributedBoundaryVariableSource = | Readonly<{ kind: 'route_param'; name: string }> - | Readonly<{ - kind: 'search_param'; - name: string; - mode?: 'first' | 'all'; - }> + | SearchSourceFor | Readonly<{ kind: 'trusted_session'; path: readonly string[] }> | Readonly<{ kind: 'constant'; value: TValue }> | Readonly<{ kind: 'forwarded_prop'; path: readonly string[] }> @@ -47,7 +60,7 @@ export type DistributedBoundaryBinding< TSession = unknown, TProps = Readonly> > = Readonly<{ - version: 1; + version: 2; id: string; artifactId: string; sources: DistributedBoundaryVariableSources; @@ -92,7 +105,7 @@ export function defineDistributedBoundaryBinding< sources: DistributedBoundaryVariableSources ): DistributedBoundaryBinding { const validated = validateSources(artifact, sources); - const id = `boundary-v${BINDING_VERSION}:${fnv1a64( + const id = `boundary-v${DISTRIBUTED_BOUNDARY_BINDING_VERSION}:${fnv1a64( `${artifact.id}\n${stableJson(validated)}` )}`; const resolve = ( @@ -100,7 +113,7 @@ export function defineDistributedBoundaryBinding< ): TVariables => resolveDistributedBoundaryVariables(artifact, validated, context); return Object.freeze({ - version: BINDING_VERSION, + version: DISTRIBUTED_BOUNDARY_BINDING_VERSION, id, artifactId: artifact.id, sources: validated, @@ -121,6 +134,9 @@ export function defineDistributedBoundaryOperation< artifact: ReplicaOperationArtifact, binding: DistributedBoundaryBinding ): DistributedBoundaryOperation { + if (binding.version !== DISTRIBUTED_BOUNDARY_BINDING_VERSION) { + throw new TypeError('Distributed boundary binding version is unsupported; regenerate the boundary plan'); + } if (binding.artifactId !== artifact.id) { throw new TypeError('Distributed boundary binding belongs to a different operation artifact'); } @@ -184,15 +200,12 @@ function resolveSource( } case 'search_param': { const search = context.search; - if (isSearchParams(search)) { - if (source.mode === 'all') return search.getAll(source.name); - const value = search.get(source.name); - return value === null ? OMITTED : value; - } - const value = ownValue(search, source.name); - if (value === undefined) return source.mode === 'all' ? [] : OMITTED; - if (source.mode === 'all') return Array.isArray(value) ? [...value] : [value]; - return Array.isArray(value) ? (value[0] ?? OMITTED) : value; + const value = isSearchParams(search) ? search.getAll(source.name) : ownValue(search, source.name); + const values = value === undefined ? [] : Array.isArray(value) ? value : [value]; + if (values.length === 0) return OMITTED; + return source.mode === 'all' + ? values.map((entry) => decodeSearchScalar(entry, source.scalar)) + : decodeSearchScalar(values[0], source.scalar); } case 'trusted_session': { const value = readPath(context.session, source.path, 'trusted session'); @@ -230,7 +243,7 @@ function validateSources( throw new TypeError(`Distributed boundary binding names unknown variable ${name}`); } const source = ownValue(sources, name); - entries.push([name, validateSource(source, name)]); + entries.push([name, validateSource(source, name, definitions[name]!)]); } for (const [name, definition] of Object.entries(definitions)) { const required = @@ -247,12 +260,22 @@ function validateSources( return Object.freeze(Object.fromEntries(entries)) as DistributedBoundaryVariableSources; } -function validateSource(value: unknown, variable: string): DistributedBoundaryVariableSource { +function variableGraphqlType(definition: ReplicaVariableInputRef): string { + if (definition.kind === 'list') return `[${variableGraphqlType(definition.item)}]`; + return definition.kind === 'scalar' ? definition.scalar : ''; +} + +function validateSource( + value: unknown, + variable: string, + definition: ReplicaVariableInputRef +): DistributedBoundaryVariableSource { const source = exactRecord(value, `binding source ${variable}`); - if (typeof source.kind !== 'string') { + const kind = ownValue(source, 'kind'); + if (typeof kind !== 'string') { throw new TypeError(`Distributed boundary source ${variable} has no kind`); } - switch (source.kind) { + switch (kind) { case 'omit': exactKeys(source, ['kind'], variable); return Object.freeze({ kind: 'omit' }); @@ -260,15 +283,7 @@ function validateSource(value: unknown, variable: string): DistributedBoundaryVa exactKeys(source, ['kind', 'name'], variable); return Object.freeze({ kind: 'route_param', name: safeName(source.name, variable) }); case 'search_param': { - exactKeys(source, ['kind', 'name', 'mode'], variable, ['mode']); - if (source.mode !== undefined && source.mode !== 'first' && source.mode !== 'all') { - throw new TypeError(`Distributed boundary source ${variable} has invalid search mode`); - } - return Object.freeze({ - kind: 'search_param', - name: safeName(source.name, variable), - ...(source.mode === undefined ? {} : { mode: source.mode }) - }); + return normalizeSearchParamSource(source, variable, variableGraphqlType(definition)); } case 'trusted_session': exactKeys(source, ['kind', 'path'], variable); diff --git a/js/src/sveltekit/index.ts b/js/src/sveltekit/index.ts index b4f3cd0ba..430bf2834 100644 --- a/js/src/sveltekit/index.ts +++ b/js/src/sveltekit/index.ts @@ -24,6 +24,7 @@ export { type DistributedBoundaryVariableSource, type DistributedBoundaryVariableSources } from './boundary-variables.js'; +export type { DistributedSearchParamSource, DistributedSearchScalar } from './search-variables.js'; export { constant, defineGraphqlIslandBindings, diff --git a/js/src/sveltekit/island-bindings.ts b/js/src/sveltekit/island-bindings.ts index 7987d41c3..478fbd5f8 100644 --- a/js/src/sveltekit/island-bindings.ts +++ b/js/src/sveltekit/island-bindings.ts @@ -3,6 +3,10 @@ import type { DistributedBoundaryVariableSource, DistributedBoundaryVariableSources } from './boundary-variables.js'; +import type { + DistributedSearchParamSource, + DistributedSearchScalar +} from './search-variables.js'; const GRAPHQL_ISLAND_BINDINGS = Symbol.for( '@hops-ops/distributed/graphql-island-bindings' @@ -60,11 +64,21 @@ export function routeParam(name: string): DistributedBoundaryVariableSource { return Object.freeze({ kind: 'route_param', name }); } +export function searchParam( + name: string, + scalar: TScalar +): DistributedSearchParamSource & { mode: 'first' }; +export function searchParam( + name: string, + scalar: TScalar, + mode: TMode +): DistributedSearchParamSource & { mode: TMode }; export function searchParam( name: string, + scalar: DistributedSearchScalar, mode: 'first' | 'all' = 'first' -): DistributedBoundaryVariableSource { - return Object.freeze({ kind: 'search_param', name, mode }); +): DistributedSearchParamSource & { mode: 'first' | 'all' } { + return Object.freeze({ kind: 'search_param', name, scalar, mode }); } export function sessionClaim(...path: string[]): DistributedBoundaryVariableSource { diff --git a/js/src/sveltekit/islands/boundaries.ts b/js/src/sveltekit/islands/boundaries.ts index 575f7a933..24e37b987 100644 --- a/js/src/sveltekit/islands/boundaries.ts +++ b/js/src/sveltekit/islands/boundaries.ts @@ -14,10 +14,14 @@ import { pathToFileURL } from 'node:url'; import { parse } from 'svelte/compiler'; -import type { DistributedBoundaryVariableSource } from '../boundary-variables.js'; +import { + DISTRIBUTED_BOUNDARY_BINDING_VERSION, + type DistributedBoundaryVariableSource +} from '../boundary-variables.js'; +import { normalizeSearchParamSource } from '../search-variables.js'; import { isGraphqlIslandBindings } from '../island-bindings.js'; -const BOUNDARY_PLAN_VERSION = 1; +const BOUNDARY_PLAN_VERSION = 2; const VARIABLE_CODEC_VERSION = 2; const MAX_COMPONENTS = 4_096; const MAX_ISLANDS = 4_096; @@ -80,7 +84,7 @@ export type DistributedSvelteKitBoundaryOccurrence = Readonly<{ directives: Readonly<{ load: boolean; live: boolean }>; liveCoverage: DistributedIslandPlanInput['liveCoverage']; binding: Readonly<{ - version: 1; + version: 2; id: string; discovery: 'route_param' | 'empty' | 'explicit'; sources: Readonly>; @@ -558,7 +562,7 @@ function boundaryBinding( if (explicit !== undefined) { let normalized: DistributedBoundaryVariableSource; try { - normalized = normalizeBindingSource(explicit, variable.name); + normalized = normalizeBindingSource(explicit, variable.name, variable.graphqlType); } catch { throw diagnostic( 'distributed.island.variable_source_invalid', @@ -590,8 +594,8 @@ function boundaryBinding( } const sourceRecord = Object.freeze(Object.fromEntries(sources)); return Object.freeze({ - version: 1, - id: `boundary-v1:${fnv1a64(`${entry.island.operationHash}\n${stableJson(sourceRecord)}`)}`, + version: DISTRIBUTED_BOUNDARY_BINDING_VERSION, + id: `boundary-v${DISTRIBUTED_BOUNDARY_BINDING_VERSION}:${fnv1a64(`${entry.island.operationHash}\n${stableJson(sourceRecord)}`)}`, discovery: hasExplicit ? 'explicit' : hasRoute ? 'route_param' : 'empty', sources: sourceRecord }); @@ -608,7 +612,8 @@ function routeParameterNames(route: string): readonly string[] { function normalizeBindingSource( value: unknown, - variable: string + variable: string, + graphqlType: string ): DistributedBoundaryVariableSource { if (value === null || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError(`Distributed boundary variable ${variable} source must be an object`); @@ -626,19 +631,7 @@ function normalizeBindingSource( return Object.freeze({ kind: 'route_param', name }); } case 'search_param': { - const name = ownDataValue(record, 'name'); - if (typeof name !== 'string' || name.length === 0) { - throw new TypeError(`Distributed boundary variable ${variable} source name is invalid`); - } - const mode = ownDataValue(record, 'mode'); - if (mode !== undefined && mode !== 'first' && mode !== 'all') { - throw new TypeError(`Distributed boundary variable ${variable} search mode is invalid`); - } - return Object.freeze({ - kind: 'search_param', - name, - ...(mode === undefined ? {} : { mode }) - }); + return normalizeSearchParamSource(record, variable, graphqlType); } case 'trusted_session': case 'forwarded_prop': { diff --git a/js/src/sveltekit/search-variables.ts b/js/src/sveltekit/search-variables.ts new file mode 100644 index 000000000..3fb3048f2 --- /dev/null +++ b/js/src/sveltekit/search-variables.ts @@ -0,0 +1,66 @@ +/** Explicit URL text decoding; the operation codec still validates the result. */ +export type DistributedSearchScalar = 'String' | 'ID' | 'Int' | 'Float' | 'Boolean'; + +export type DistributedSearchParamSource< + TScalar extends DistributedSearchScalar = DistributedSearchScalar, + TMode extends 'first' | 'all' = 'first' | 'all' +> = Readonly<{ + kind: 'search_param'; + name: string; + scalar: TScalar; + mode?: TMode; +}>; + +/** Shared by build-time generation and runtime registration. */ +export function normalizeSearchParamSource( + record: Record, + variable: string, + graphqlType: string +): DistributedSearchParamSource { + if ( + (Object.getPrototypeOf(record) !== Object.prototype && Object.getPrototypeOf(record) !== null) || + !['kind', 'name', 'scalar'].every((key) => Object.hasOwn(record, key)) + ) throw new TypeError(`Distributed boundary search source ${variable} requires own scalar fields`); + const allowed = new Set(['kind', 'name', 'scalar', 'mode']); + for (const key of Reflect.ownKeys(record)) { + const property = Object.getOwnPropertyDescriptor(record, key); + if (typeof key !== 'string' || !allowed.has(key) || property === undefined || !('value' in property)) { + throw new TypeError(`Distributed boundary search source ${variable} has an invalid field`); + } + } + const { name, scalar, mode = 'first' } = record; + if ( + typeof name !== 'string' || name.length === 0 || name.length > 512 || + !['String', 'ID', 'Int', 'Float', 'Boolean'].includes(scalar as string) || + (mode !== 'first' && mode !== 'all') + ) { + throw new TypeError(`Distributed boundary search source ${variable} requires a scalar and valid mode`); + } + const expected = mode === 'all' ? `[${scalar}]` : scalar; + if (graphqlType.replaceAll('!', '') !== expected) { + throw new TypeError(`Distributed boundary search source ${variable} does not match its GraphQL type`); + } + return Object.freeze({ + kind: 'search_param', name, scalar: scalar as DistributedSearchScalar, mode + }); +} + +export function decodeSearchScalar( + value: unknown, + scalar: DistributedSearchScalar +): string | number | boolean { + // Do not trim, parse partial numbers, infer JSON, or include URL values in errors. + if (typeof value !== 'string') throw new TypeError('Distributed search scalar requires URL text'); + if (scalar === 'String' || scalar === 'ID') return value; + if (scalar === 'Boolean') { + if (value === 'true') return true; + if (value === 'false') return false; + } else if ( + (scalar === 'Int' && /^-?(?:0|[1-9][0-9]*)$/.test(value)) || + (scalar === 'Float' && /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(value)) + ) { + const number = Number(value); + if (Number.isFinite(number)) return number; + } + throw new TypeError(`Distributed search scalar is not a valid ${scalar}`); +} diff --git a/js/src/sveltekit/server-replica.ts b/js/src/sveltekit/server-replica.ts index 99f81d02d..b4ce19bbf 100644 --- a/js/src/sveltekit/server-replica.ts +++ b/js/src/sveltekit/server-replica.ts @@ -9,6 +9,7 @@ import type { FetchLike } from '../request.js'; import type { GqlAuth, GraphqlVariables } from '../types.js'; import { authFromPageData, type PageGraphqlData } from './auth.js'; import { + DISTRIBUTED_BOUNDARY_BINDING_VERSION, resolveDistributedBoundaryVariables, type DistributedBoundaryOperation, type DistributedBoundaryVariableContext @@ -293,7 +294,7 @@ function validateBoundaryOperations( if ( operation === null || typeof operation !== 'object' || - operation.binding?.version !== 1 || + operation.binding?.version !== DISTRIBUTED_BOUNDARY_BINDING_VERSION || operation.binding.artifactId !== operation.artifact?.id ) { throw new TypeError(`invalid Distributed boundary operation at index ${index}`); diff --git a/js/tests/sveltekit-boundary-variables.test.mjs b/js/tests/sveltekit-boundary-variables.test.mjs index 0b528b717..aedd64cc6 100644 --- a/js/tests/sveltekit-boundary-variables.test.mjs +++ b/js/tests/sveltekit-boundary-variables.test.mjs @@ -6,7 +6,8 @@ import { createDistributedSvelteKitServer, DistributedSvelteKitBoundaryController, defineDistributedBoundaryBinding, - defineDistributedBoundaryOperation + defineDistributedBoundaryOperation, + searchParam } from '../dist/sveltekit/index.js'; import { createDistributedReplica } from '../dist/replica/index.js'; import { @@ -62,12 +63,12 @@ const BoundTodosArtifact = Object.freeze({ function binding(limit = 20) { return defineDistributedBoundaryBinding(BoundTodosArtifact, { id: { kind: 'route_param', name: 'itemId' }, - limit: { kind: 'constant', value: limit }, + limit: typeof limit === 'number' ? { kind: 'constant', value: limit } : limit, nil: { kind: 'constant', value: null }, omitted: { kind: 'omit' }, owner: { kind: 'trusted_session', path: ['user', 'id'] }, payload: { kind: 'forwarded_prop', path: ['filters'] }, - tags: { kind: 'search_param', name: 'tag', mode: 'all' } + tags: searchParam('tag', 'String', 'all') }); } @@ -137,8 +138,8 @@ test('one boundary binding canonicalizes route, search, session, constant, and f assert.equal(first.canonicalBytes(context()), JSON.stringify(variables)); assert.deepEqual( first.resolve({ ...context(), search: {} }).tags, - [], - 'an absent record-backed multi-value search parameter matches URLSearchParams.getAll' + undefined, + 'an absent multi-value search parameter is omitted so operation defaults can apply' ); assert.equal(binding().id, first.id, 'equivalent bindings have stable fingerprints'); assert.notEqual(binding(21).id, first.id, 'binding contract changes alter hydration identity'); @@ -187,7 +188,7 @@ test('boundary binding fails closed for missing values, hostile keys, accessors, }); test('SSR, hydration, component use, navigation read, and prefetch share canonical boundary variables', async () => { - const boundary = operation(); + const boundary = operation(binding(searchParam('pageSize', 'Int'))); const sent = []; const server = createDistributedSvelteKitServer({ boundaries: [boundary], @@ -195,6 +196,7 @@ test('SSR, hydration, component use, navigation read, and prefetch share canonic getRole: () => 'user' }); const serverContext = context(); + serverContext.search.set('pageSize', '20'); const page = await server.load({ locals: { session: serverContext.session }, route: { id: '/items/[itemId]' }, @@ -220,6 +222,7 @@ test('SSR, hydration, component use, navigation read, and prefetch share canonic assert.equal(page.gqlError, null); assert.deepEqual(page.distributed.bindings, [boundary.binding.id]); assert.deepEqual(sent, [boundary.binding.resolve(serverContext)]); + assert.equal(sent[0].limit, 20, 'URL text becomes a GraphQL Int before SSR transport'); let browserFetches = 0; const client = createDistributedSvelteKit({ diff --git a/js/tests/sveltekit-search-scalars.test.mjs b/js/tests/sveltekit-search-scalars.test.mjs new file mode 100644 index 000000000..846203b1c --- /dev/null +++ b/js/tests/sveltekit-search-scalars.test.mjs @@ -0,0 +1,85 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { defineDistributedBoundaryBinding, searchParam } from '../dist/sveltekit/index.js'; +import { TodosArtifact } from './fixtures/adapter-conformance.mjs'; + +function artifact(scalar, { list = false, nullable = false, defaults = {} } = {}) { + const item = { kind: 'scalar', scalar, codec: { Int: 'int32', Float: 'float64', Boolean: 'boolean', String: 'string', ID: 'string' }[scalar], nullable: false }; + return { ...TodosArtifact, variableCodec: { + version: 2, + limits: { maxDepth: 64, maxBoolWidth: 256, maxInList: 3 }, + variables: { value: list ? { kind: 'list', item, nullable, maxItems: 3 } : { ...item, nullable } }, + defaults, inputs: {} + } }; +} + +function resolve(scalar, search, options = {}) { + return defineDistributedBoundaryBinding(artifact(scalar, options), { + value: searchParam('q', scalar, options.list ? 'all' : 'first') + }).resolve({ params: {}, search, session: null, props: {} }); +} + +test('typed search scalars decode URL and record inputs with the same canonical result', () => { + for (const [scalar, text, expected] of [ + ['Int', '2147483647', 2147483647], ['Int', '-2147483648', -2147483648], + ['Int', '0', 0], ['Int', '-0', 0], ['Float', '1.25e2', 125], + ['Float', '-0.125', -0.125], ['Boolean', 'true', true], ['Boolean', 'false', false], + ['String', '雪 & café', '雪 & café'], ['ID', '001', '001'], ['String', '', ''] + ]) { + assert.deepEqual(resolve(scalar, new URLSearchParams({ q: text })), { value: expected }); + assert.deepEqual(resolve(scalar, { q: text }), { value: expected }); + } + assert.deepEqual(resolve('Int', new URLSearchParams('q=2&q=1'), { list: true }), { value: [2, 1] }); + assert.deepEqual(resolve('Int', { q: ['2', '1'] }, { list: true }), { value: [2, 1] }); + assert.deepEqual(resolve('Int', { q: ['2', '1'] }), { value: 2 }, 'first mode is explicit and deterministic'); +}); + +test('missing search inputs preserve defaults, nullable omission and required errors', () => { + for (const search of [new URLSearchParams(), {}, { q: [] }]) { + assert.deepEqual(resolve('Int', search, { defaults: { value: 25 } }), { value: 25 }); + assert.deepEqual(resolve('Int', search, { list: true, defaults: { value: [25] } }), { value: [25] }); + assert.deepEqual(resolve('Int', search, { nullable: true }), {}); + assert.deepEqual(resolve('Int', search, { list: true, nullable: true }), {}); + assert.throws(() => resolve('Int', search), /required variable is missing/); + } +}); + +test('numeric and boolean URL decoding fails closed without exposing values', () => { + for (const scalar of ['Int', 'Float', 'Boolean']) { + for (const value of ['', ' ', ' 1', '1 ', '+1', '01', '0x10', 'NaN', 'Infinity', 'true-secret', 'null']) { + assert.throws(() => resolve(scalar, { q: value }), (error) => { + assert.match(error.message, /Distributed search scalar/); + assert.doesNotMatch(error.message, /true-secret/); + return true; + }); + } + } + for (const value of ['1.5', '1e2', '1x', '2147483648', '-2147483649']) { + assert.throws(() => resolve('Int', { q: value })); + } + for (const value of ['.5', '1.', '1e999']) assert.throws(() => resolve('Float', { q: value })); + for (const value of ['1', '0', 'TRUE', 'False']) assert.throws(() => resolve('Boolean', { q: value })); + for (const value of [1, true, null, {}, [1], ['1', null]]) { + assert.throws(() => resolve('Int', { q: value }, { list: true }), /requires URL text/); + } + assert.throws(() => resolve('Int', { q: ['1', '2', '3', '4'] }, { list: true }), /limit|maximum|exceed/i); +}); + +test('search source registration rejects mismatched, untyped and unsafe contracts', () => { + for (const source of [ + { kind: 'search_param', name: 'q' }, + searchParam('q', 'String'), searchParam('q', 'Int', 'all'), + { ...searchParam('q', 'Int'), fallback: 0 }, + { ...searchParam('q', 'Int'), scalar: 'JSON' }, + { ...searchParam('q', 'Int'), mode: 'last' } + ]) assert.throws(() => defineDistributedBoundaryBinding(artifact('Int'), { value: source })); + for (const enumerable of [true, false]) { + const getter = { ...searchParam('q', 'Int') }; + Object.defineProperty(getter, 'scalar', { enumerable, get() { throw new Error('must not execute'); } }); + assert.throws(() => defineDistributedBoundaryBinding(artifact('Int'), { value: getter }), /invalid field/); + } + assert.throws(() => defineDistributedBoundaryBinding(artifact('Int', { list: true }), { value: searchParam('q', 'Int') })); + const bound = defineDistributedBoundaryBinding(artifact('Int'), { value: searchParam('q', 'Int') }); + assert.equal(bound.version, 2); + assert.match(bound.id, /^boundary-v2:/); +}); diff --git a/js/tests/sveltekit-vite.test.mjs b/js/tests/sveltekit-vite.test.mjs index 54969e806..c5a46dee4 100644 --- a/js/tests/sveltekit-vite.test.mjs +++ b/js/tests/sveltekit-vite.test.mjs @@ -13,6 +13,8 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { Worker } from 'node:worker_threads'; import test from 'node:test'; +import { defineDistributedBoundaryBinding } from '../dist/sveltekit/index.js'; +import { TodosArtifact } from './fixtures/adapter-conformance.mjs'; import { analyzeDistributedSvelteKitBoundaries, @@ -339,15 +341,31 @@ test('boundary plans generate route-variable bindings and fail unprovable requir await writeFile( sidecar, `import { defineGraphqlIslandBindings, searchParam } from ${JSON.stringify(helper)};\n` + - `export default defineGraphqlIslandBindings({ limit: searchParam('pageSize') });\n` + `export default defineGraphqlIslandBindings({ limit: searchParam('pageSize', 'Int') });\n` ); const colocated = await analyzeDistributedSvelteKitBoundaries({ cwd: root, clients: [{ module: '$distributed', inventory: required }] }); assert.deepEqual(colocated[0].boundaries[0].islands[0].binding.sources, { - limit: { kind: 'search_param', name: 'pageSize', mode: 'first' } + limit: { kind: 'search_param', name: 'pageSize', scalar: 'Int', mode: 'first' } }); + const plannedBinding = colocated[0].boundaries[0].islands[0].binding; + const executable = defineDistributedBoundaryBinding({ + ...TodosArtifact, + id: required.islands[0].operationHash, + protocol: { ...TodosArtifact.protocol, operation: required.islands[0].operationHash }, + variableCodec: { + version: 2, + limits: { maxDepth: 64, maxBoolWidth: 256, maxInList: 1000 }, + variables: { limit: { kind: 'scalar', scalar: 'Int', codec: 'int32', nullable: false } }, + defaults: {}, inputs: {} + } + }, plannedBinding.sources); + assert.equal(plannedBinding.version, 2); + assert.equal(plannedBinding.id, executable.id, 'generator and runtime share the exact v2 fingerprint'); + assert.deepEqual(executable.resolve({ params: {}, search: new URLSearchParams('pageSize=20'), session: null, props: {} }), { limit: 20 }); + assert.throws(() => validateDistributedSvelteKitBoundaryPlan({ ...colocated[0], version: 1 }), /boundary_plan_invalid/); await assert.rejects( analyzeDistributedSvelteKitBoundaries({ cwd: root, @@ -370,6 +388,10 @@ test('boundary plans generate route-variable bindings and fail unprovable requir ); await rm(sidecar); for (const hostile of [ + { kind: 'search_param', name: 'pageSize' }, + { kind: 'search_param', name: 'pageSize', scalar: 'String' }, + { kind: 'search_param', name: 'pageSize', scalar: 'Int', mode: 'all' }, + { kind: 'search_param', name: 'pageSize', scalar: 'Int', fallback: 20 }, { kind: 'trusted_session', path: ['__proto__'] }, { kind: 'query_result', path: ['items', 'limit'] } ]) { @@ -863,7 +885,7 @@ test('boundary diagnostics reject cycles, stale plans, and unbounded layout live ); assert.throws( () => validateDistributedSvelteKitBoundaryPlan( - { version: 2, module: '$distributed', boundaries: [], unplaced: [] }, + { version: 1, module: '$distributed', boundaries: [], unplaced: [] }, '$distributed' ), /\[distributed\.island\.boundary_plan_invalid\]/ diff --git a/js/type-tests/sveltekit-adapter.ts b/js/type-tests/sveltekit-adapter.ts index 3d4b6b091..79169476a 100644 --- a/js/type-tests/sveltekit-adapter.ts +++ b/js/type-tests/sveltekit-adapter.ts @@ -3,7 +3,9 @@ import { createDistributedSvelteKit, createDistributedSvelteKitServer, defineDistributedBoundaryBinding, - defineDistributedBoundaryOperation + defineDistributedBoundaryOperation, + defineGraphqlIslandBindings, + searchParam } from '@hops-ops/distributed/sveltekit'; import { distributedSvelteKit } from '@hops-ops/distributed/sveltekit/vite'; import type { @@ -21,6 +23,26 @@ type Todo = { type TodosResult = { todos: readonly Todo[] }; type TodoResult = { todo: Todo | null }; +defineGraphqlIslandBindings<{ limit?: number; enabled: boolean; ids: readonly string[] }>({ + limit: searchParam('limit', 'Int'), + enabled: searchParam('enabled', 'Boolean'), + ids: searchParam('id', 'ID', 'all') +}); +defineGraphqlIslandBindings<{ limit: number }>({ + // @ts-expect-error URL text must explicitly decode to the generated number type. + limit: searchParam('limit', 'String') +}); +defineGraphqlIslandBindings<{ ids: readonly string[] }>({ + // @ts-expect-error A generated list requires all mode. + ids: searchParam('id', 'ID') +}); +defineGraphqlIslandBindings<{ limit: number }>({ + // @ts-expect-error A scalar variable cannot use all mode. + limit: searchParam('limit', 'Int', 'all') +}); +// @ts-expect-error Untyped search parameters were removed in binding v2. +searchParam('limit'); + declare const replica: DistributedReplica; declare const Todos: ReplicaOperationArtifact< TodosResult, From 9e5aea081ea1d06d5e7133a80e376df7f805aee5 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 14 Sep 2026 02:04:16 -0500 Subject: [PATCH 102/484] fix: align aggregate manifest capacity with CLI ingress Bound complete application and structured Surface catalogs at 16 MiB while retaining 1 MiB opaque/expanded program budgets and all structural and canonical validation. Preserve every current and retained selector. Verify large canonical round-trips, oversized rejection, lossless shared programs and duplicate inventory rejection below the aggregate cap. Implements [[tasks/contract-lifecycle-tooling-9]] --- README.md | 9 +++-- docs/compact-projection-contracts.md | 14 ++++++-- src/application/manifest.rs | 49 ++++++++++++++++++++------ src/application/projection_contract.rs | 13 ++++--- tests/application_composition.rs | 8 +++-- 5 files changed, 70 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 06602db7e..77a2476b6 100644 --- a/README.md +++ b/README.md @@ -2500,11 +2500,14 @@ Command namespaces such as `orders.submit` supply module names; there is no second module list to maintain. Assembly rejects commands missing from the Surface or exposed by the Surface without a Service owner. Role-selected client exports remain authorization views of that full contract. Complete application -manifests are bounded at 4 MiB; each opaque JSON contract remains bounded at +manifests are bounded at 16 MiB; each opaque JSON contract remains bounded at 1 MiB. A generated Surface contract uses the complete-manifest budget rather than the opaque-value cap; its typed contents and the existing collection, string and nesting limits are still validated. The complete artifact, including -all surfaces and module inventories, must fit within 4 MiB. +all surfaces and module inventories, must fit within 16 MiB, matching the CLI +manifest ingress budget. Older tooling capped at 4 MiB must be rebuilt before +consuming larger artifacts; encoding versions and existing fingerprints do not +change. An event-driven policy that emits through another aggregate can explicitly carry the incoming command's causal identity before recording its events: @@ -2542,7 +2545,7 @@ Application manifest wire version 2 stores module declarations and selected Surface contracts without repeating top-level `commands`, `events`, `models`, or `projections`. The Rust `ApplicationManifest` decoder reconstructs those inventories and validates their ownership; its convenience fields are unchanged. -Portable artifacts remain bounded to 4 MiB. Version 1 artifacts must be +Portable application artifacts remain bounded to 16 MiB. Version 1 artifacts must be regenerated with the matching CLI; they are not accepted as version 2. Modeled projection contracts [share repeated operations and selector schemas](docs/compact-projection-contracts.md) diff --git a/docs/compact-projection-contracts.md b/docs/compact-projection-contracts.md index d20f32318..820d8c66f 100644 --- a/docs/compact-projection-contracts.md +++ b/docs/compact-projection-contracts.md @@ -28,9 +28,17 @@ either representation. Expansion returns exactly the original program JSON. Unsupported encodings, invalid references, inline/reference ambiguity, duplicate or unused table entries, and noncanonical table order fail validation. -The complete encoded application manifest remains bounded at 4 MiB. Each opaque +The complete encoded application manifest is bounded at 16 MiB, matching CLI +manifest ingress. This aggregate budget accommodates complete current and +retained-selector catalogs composed from many independently bounded contracts. +Older framework readers capped at 4 MiB reject larger artifacts; rebuild tooling +and applications together. Existing bytes, fingerprints and encoding versions +are unchanged for manifests that already fit. + +Each opaque modeled value remains bounded at 1 MiB; an expanded program also must fit the existing 1 MiB budget. The decoder checks repeated byte costs before copying shared values and validates programs individually, without retaining an expanded -copy of the whole application. Sharing is storage normalization, not an increase -in wire limits or a replacement for retained-history replay. +copy of the whole application. Collection, string and depth limits remain +unchanged. Sharing is storage normalization, not a replacement for +retained-history replay. diff --git a/src/application/manifest.rs b/src/application/manifest.rs index 5e6e14c8f..15b28795d 100644 --- a/src/application/manifest.rs +++ b/src/application/manifest.rs @@ -14,7 +14,9 @@ pub const APPLICATION_MANIFEST_SCHEMA_VERSION: u32 = 2; /// /// A complete manifest carries authoritative module declarations and selected /// Surface contracts. Flattened inventories are reconstructed, not serialized. -pub const MAX_APPLICATION_MANIFEST_BYTES: usize = 4 * 1024 * 1024; +/// Match the CLI manifest ingress budget so complete retained-selector catalogs +/// can compose many independently bounded contracts without dropping history. +pub const MAX_APPLICATION_MANIFEST_BYTES: usize = 16 * 1024 * 1024; pub const MAX_MANIFEST_COLLECTION_ITEMS: usize = 4096; pub const MAX_MANIFEST_STRING_BYTES: usize = 4096; /// Per-value JSON bound. Several independently bounded contracts may comprise @@ -2176,11 +2178,16 @@ mod size_limit_tests { deep = serde_json::json!([deep]); } assert!(validate(&deep).is_err()); - let oversized = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 1024]); + let oversized = serde_json::json!(vec![ + "x".repeat(MAX_MANIFEST_STRING_BYTES); + MAX_MANIFEST_COLLECTION_ITEMS + ]); assert!(validate(&oversized) .unwrap_err() .to_string() - .contains("exceeds 4194304 JSON bytes")); + .contains(&format!( + "exceeds {MAX_APPLICATION_MANIFEST_BYTES} JSON bytes" + ))); } #[test] @@ -2196,11 +2203,11 @@ mod size_limit_tests { } #[test] - fn manifest_accepts_multiple_bounded_contracts_beyond_one_mib() { + fn manifest_accepts_multiple_bounded_contracts_beyond_four_mib() { let value = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 200]); assert!(serde_json::to_vec(&value).unwrap().len() < MAX_MANIFEST_JSON_BYTES); let mut manifest = ApplicationManifest::new("large-app"); - for index in 0..2 { + for index in 0..6 { manifest.extensions.push( ApplicationExtension::try_new(format!("large.contract.{index}"), 1, value.clone()) .unwrap(), @@ -2208,17 +2215,30 @@ mod size_limit_tests { } let bytes = manifest.canonical_bytes().unwrap(); - assert!(bytes.len() > 1024 * 1024); + assert!(bytes.len() > 4 * 1024 * 1024); assert!(bytes.len() < MAX_APPLICATION_MANIFEST_BYTES); - ApplicationManifest::from_canonical_bytes(&bytes).unwrap(); + let decoded = ApplicationManifest::from_canonical_bytes(&bytes).unwrap(); + assert_eq!(decoded.canonical_bytes().unwrap(), bytes); + for index in 0..6 { + assert_eq!( + decoded + .extensions + .iter() + .find(|extension| extension.id == format!("large.contract.{index}")) + .unwrap() + .value, + value, + ); + } } #[test] - fn manifest_rejects_multiple_contracts_beyond_four_mib() { + fn manifest_rejects_multiple_contracts_beyond_aggregate_budget() { let value = serde_json::json!(vec!["x".repeat(MAX_MANIFEST_STRING_BYTES); 230]); assert!(serde_json::to_vec(&value).unwrap().len() < MAX_MANIFEST_JSON_BYTES); let mut manifest = ApplicationManifest::new("oversized-app"); - for index in 0..5 { + let contract_bytes = serde_json::to_vec(&value).unwrap().len(); + for index in 0..=MAX_APPLICATION_MANIFEST_BYTES / contract_bytes { manifest.extensions.push( ApplicationExtension::try_new(format!("large.contract.{index}"), 1, value.clone()) .unwrap(), @@ -2226,9 +2246,16 @@ mod size_limit_tests { } let error = manifest.canonical_bytes().unwrap_err().to_string(); - assert!(error.contains("application manifest exceeds 4194304 bytes")); + assert!(error.contains(&format!( + "application manifest exceeds {MAX_APPLICATION_MANIFEST_BYTES} bytes" + ))); let oversized_bytes = serde_json::to_vec(&manifest).unwrap(); assert!(oversized_bytes.len() > MAX_APPLICATION_MANIFEST_BYTES); - assert!(ApplicationManifest::from_canonical_bytes(&oversized_bytes).is_err()); + let error = ApplicationManifest::from_canonical_bytes(&oversized_bytes) + .unwrap_err() + .to_string(); + assert!(error.contains(&format!( + "application manifest bytes must be between 1 and {MAX_APPLICATION_MANIFEST_BYTES}" + ))); } } diff --git a/src/application/projection_contract.rs b/src/application/projection_contract.rs index 9e95fc4dc..827df1251 100644 --- a/src/application/projection_contract.rs +++ b/src/application/projection_contract.rs @@ -285,16 +285,21 @@ mod tests { let expanded_modules = (0..32) .map(|index| module(index, &original)) .collect::>(); - let error = Application::try_new("history-app", expanded_modules, []).unwrap_err(); - assert!(error - .to_string() - .contains("application manifest exceeds 4194304 bytes")); + let expanded_application = + Application::try_new("history-app", expanded_modules, []).unwrap(); + let expanded_bytes = expanded_application.manifest().canonical_bytes().unwrap(); + assert!(expanded_bytes.len() > 4 * 1024 * 1024); + assert_eq!( + ApplicationManifest::from_canonical_bytes(&expanded_bytes).unwrap(), + *expanded_application.manifest() + ); let modules = (0..32) .map(|index| module(index, &compact)) .collect::>(); let application = Application::try_new("history-app", modules.clone(), []).unwrap(); let bytes = application.manifest().canonical_bytes().unwrap(); assert!(bytes.len() < crate::application::MAX_APPLICATION_MANIFEST_BYTES); + assert!(bytes.len() < expanded_bytes.len()); assert_eq!( ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), *application.manifest() diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 70e3c40d2..0e13722d4 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -534,8 +534,12 @@ fn normalized_manifest_fits_without_serializing_duplicate_model_inventory() { let mut redundant = serde_json::from_slice::(&bytes).unwrap(); redundant["models"] = serde_json::to_value(&manifest.models).unwrap(); let redundant_bytes = serde_json::to_vec(&redundant).unwrap(); - assert!(redundant_bytes.len() > MAX_APPLICATION_MANIFEST_BYTES); - assert!(ApplicationManifest::from_canonical_bytes(&redundant_bytes).is_err()); + assert!(redundant_bytes.len() > 4 * 1024 * 1024); + assert!(redundant_bytes.len() < MAX_APPLICATION_MANIFEST_BYTES); + let error = ApplicationManifest::from_canonical_bytes(&redundant_bytes) + .unwrap_err() + .to_string(); + assert!(error.contains("unknown field `models`"), "{error}"); assert_eq!( ApplicationManifest::from_canonical_bytes(&bytes).unwrap(), manifest From 3b3811d9cde8f73b020c2366affbf2db8c1c4985 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 14 Sep 2026 14:06:45 -0500 Subject: [PATCH 103/484] fix: separate retained projection arm catalog capacity Allow up to 256 historical program arms while retaining all 128-item execution limits and existing byte budgets. Refs: [[tasks/graphql-qs-projection-model-15]] --- .../client_compiler/manifest/projections.rs | 7 +- distributed_cli/src/client_compiler/tests.rs | 104 ++++++++++++++++++ 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/distributed_cli/src/client_compiler/manifest/projections.rs b/distributed_cli/src/client_compiler/manifest/projections.rs index 2e7cc5c0b..9ecc967e4 100644 --- a/distributed_cli/src/client_compiler/manifest/projections.rs +++ b/distributed_cli/src/client_compiler/manifest/projections.rs @@ -3,6 +3,9 @@ use std::collections::{BTreeMap, BTreeSet}; use super::*; const MAX_PROJECTION_ITEMS: usize = 128; +// Retained event versions grow the catalog without expanding a command's +// selected capabilities or an occurrence's executable operation budget. +const MAX_PROJECTION_PROGRAM_ARMS: usize = 256; // Frozen with `distributed::MAX_PROJECTION_EXPRESSION_DEPTH`. The CLI crate is // intentionally dependency-free from the runtime crate, so keep a boundary // test below to prevent this executable-contract limit from drifting. @@ -348,11 +351,11 @@ fn validate_program( } validate_program_id(&program.program_id)?; validate_nonempty(&program.name, "projection program name")?; - if program.arms.is_empty() || program.arms.len() > MAX_PROJECTION_ITEMS { + if program.arms.is_empty() || program.arms.len() > MAX_PROJECTION_PROGRAM_ARMS { return Err(projection_error( "client.manifest.projection_program_arms", format!( - "projection program `{}` must contain 1..={MAX_PROJECTION_ITEMS} arms", + "projection program `{}` must contain 1..={MAX_PROJECTION_PROGRAM_ARMS} arms", program.program_id ), )); diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index d455a4769..407f832f5 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -758,6 +758,110 @@ fn generated_command_types_manifest() -> JsonValue { value } +fn retained_projection_catalog(arm_count: usize) -> JsonValue { + let mut value = generated_command_types_manifest(); + let arms = value["projection_programs"][0]["arms"] + .as_array_mut() + .unwrap(); + let template = arms[0].clone(); + for index in 1..arm_count { + let mut arm = template.clone(); + arm["arm"] = json!(format!("retained-{index:03}")); + arm["event"] = json!({ + "id": format!("event:todo.retained:v{index:03}"), + "name": "todo.retained", + "version": index + }); + arm["operations"][0]["operation"] = json!(format!("retained-upsert-{index:03}")); + arms.push(arm); + } + refresh_schema_fingerprint(&mut value); + value +} + +#[test] +fn retained_projection_catalog_compiles_134_and_256_arms_with_one_selected_capability() { + let selected_preview = |manifest: &ClientManifest| { + let command = manifest + .commands + .iter() + .find(|command| command.extensions.projection.is_some()) + .unwrap(); + serde_json::to_value( + super::projection_delta::compile_command_preview(command, manifest) + .unwrap() + .unwrap(), + ) + .unwrap() + }; + let baseline = ClientManifest::parse( + generated_command_types_manifest(), + &ClientSurfaceSelector::role("user"), + ) + .unwrap(); + let expected = selected_preview(&baseline); + assert_eq!( + expected["capabilities"]["arms"].as_array().unwrap().len(), + 1 + ); + for count in [128, 134, 256] { + let value = retained_projection_catalog(count); + let manifest = ClientManifest::parse(value.clone(), &ClientSurfaceSelector::role("user")) + .unwrap_or_else(|error| panic!("{count} retained arms: {error}")); + assert_eq!(manifest.projection_programs[0].arms.len(), count); + assert_eq!(selected_preview(&manifest), expected); + compile_client(ClientCompileInput::new( + value, + ClientSurfaceSelector::role("user"), + vec![ClientDocument::new( + "src/routes/todos/+page.graphql", + "query Todo { todo(id: \"1\", tenantId: \"tenant\") { id tenantId } }", + )], + )) + .unwrap_or_else(|error| panic!("compile {count} retained arms: {error}")); + } +} + +#[test] +fn retained_projection_catalog_rejects_257_arms_and_preserves_nested_limits() { + let error = ClientManifest::parse( + retained_projection_catalog(257), + &ClientSurfaceSelector::role("user"), + ) + .unwrap_err(); + assert_eq!(error.code, "client.manifest.projection_program_arms"); + for (mutation, expected) in [ + (0, "client.manifest.projection_arm_id"), + (1, "client.manifest.projection_arm_order"), + (2, "client.manifest.projection_operation_id"), + (3, "client.manifest.projection_operations"), + (4, "client.manifest.command_projection_inventory"), + ] { + let mut value = retained_projection_catalog(134); + let arms = value["projection_programs"][0]["arms"] + .as_array_mut() + .unwrap(); + match mutation { + 0 => arms[1]["arm"] = arms[0]["arm"].clone(), + 1 => arms.swap(0, 1), + 2 => { + arms[1]["operations"][0]["operation"] = + arms[0]["operations"][0]["operation"].clone() + } + 3 => arms[1]["operations"] = json!(vec![arms[1]["operations"][0].clone(); 129]), + 4 => { + let projection = &mut value["commands"][0]["extensions"]["projection"]; + projection["program_arms"] = + json!(vec![projection["program_arms"][0].clone(); 129]); + } + _ => unreachable!(), + } + refresh_schema_fingerprint(&mut value); + let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")).unwrap_err(); + assert_eq!(error.code, expected, "mutation {mutation}"); + } +} + fn key_only_projection_manifest(composite: bool) -> JsonValue { let mut value = generated_command_types_manifest(); value["capabilities"]["live_queries"] = json!(false); From 7f8ef853404999d3148cbb591c3903cc7b065092 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 14 Sep 2026 16:36:50 -0500 Subject: [PATCH 104/484] feat: add bounded typed read-model keyset scans Read-only equality selection with opaque schema-scoped cursors, row versions and bounded pages. Support in-memory, queued, SQLite and PostgreSQL; existing adapters default to explicit unsupported without changing PK/include behavior. Tests: keyset integration 2 passed across in-memory/queued/SQLite; read-model library 17 passed; SQLite+PostgreSQL cargo check passed. No live PostgreSQL claim. See specs/distributed/bounded-readmodel-scan/index and tasks/git-forge-team-hosting-3. --- docs/bounded-read-model-scans.md | 33 +++++ src/in_memory_repo/repository.rs | 5 + src/queued_repo/repository.rs | 5 + src/read_model/in_memory.rs | 22 +++ src/read_model/mod.rs | 2 + src/read_model/scan.rs | 235 ++++++++++++++++++++++++++++++ src/repository/traits.rs | 8 + src/sqlx_repo/read_model/mod.rs | 2 + src/sqlx_repo/read_model/scan.rs | 71 +++++++++ src/sqlx_repo/repo/read_models.rs | 14 ++ tests/read_model_keyset/main.rs | 168 +++++++++++++++++++++ 11 files changed, 565 insertions(+) create mode 100644 docs/bounded-read-model-scans.md create mode 100644 src/read_model/scan.rs create mode 100644 src/sqlx_repo/read_model/scan.rs create mode 100644 tests/read_model_keyset/main.rs diff --git a/docs/bounded-read-model-scans.md b/docs/bounded-read-model-scans.md new file mode 100644 index 000000000..123c52db3 --- /dev/null +++ b/docs/bounded-read-model-scans.md @@ -0,0 +1,33 @@ +# Bounded read-model scans + +`RelationalReadModelQueryStore::scan_read_model` reads normalized rows with +declared types and row versions. It does not load aggregates, authorize commands, +or expose arbitrary SQL. Unsupported adapters return an explicit error. + +```rust,ignore +use distributed::read_model::ReadModelScanRequest; +let request = ReadModelScanRequest::new::(scope, 100, cursor)?; +let page = store.scan_read_model(request).await?; +let rows = page.typed::()?; +let cursor = page.next; +``` + +The initial capability supports a single non-null text primary key, at most 16 +typed equality filters and 1–100 returned rows. Filters support text, nullable +NULL, booleans and signed/unsigned integers within the SQL signed range. Text +filters and cursor keys are bounded to 4096 bytes; NUL is rejected. Composite +keys, joins, includes, offsets, JSON/float predicates and operational tables are +not supported. Schemas and filter types are validated before storage access. + +The opaque cursor binds the exact schema and equality scope. Only page size may +change. In-memory, queued and SQLite/PostgreSQL repositories retain row versions +and use bytewise ascending key order. The SQL adapter materializes at most one +extra row to decide whether a next page exists; the in-memory adapter keeps at +most that many selected rows while scanning its test/development store. + +Pages are separate current reads, not a multi-page transaction. Updates between +pages are visible; new keys before an already-consumed cursor are not revisited. +Consumers must validate command fences against the owning aggregate and provide +event-driven reconciliation for late rows. In particular, an empty first scan +does not prove a concurrently created row will never need processing. This API +does not provide an authorization bypass or replace a public GraphQL read policy. diff --git a/src/in_memory_repo/repository.rs b/src/in_memory_repo/repository.rs index 55db22277..c2da67630 100644 --- a/src/in_memory_repo/repository.rs +++ b/src/in_memory_repo/repository.rs @@ -847,6 +847,11 @@ impl ReadModelWritePlanStore for InMemoryRepository { } impl RelationalReadModelQueryStore for InMemoryRepository { + fn scan_read_model(&self, request: crate::read_model::ReadModelScanRequest) + -> impl Future> + Send + '_ { + self.model_store.scan_read_model(request) + } + fn read_model_query_capabilities(&self) -> ReadModelQueryCapabilities { self.model_store.read_model_query_capabilities() } diff --git a/src/queued_repo/repository.rs b/src/queued_repo/repository.rs index 58e4125dc..66bc0f6cc 100644 --- a/src/queued_repo/repository.rs +++ b/src/queued_repo/repository.rs @@ -603,6 +603,11 @@ where R: RelationalReadModelQueryStore, L: LockManager, { + fn scan_read_model(&self, request: crate::read_model::ReadModelScanRequest) + -> impl Future> + Send + '_ { + self.inner.scan_read_model(request) + } + fn read_model_query_capabilities(&self) -> ReadModelQueryCapabilities { self.inner.read_model_query_capabilities() } diff --git a/src/read_model/in_memory.rs b/src/read_model/in_memory.rs index ce82fdac4..7850e606e 100644 --- a/src/read_model/in_memory.rs +++ b/src/read_model/in_memory.rs @@ -330,6 +330,28 @@ struct IncludeSpec { } impl RelationalReadModelQueryStore for InMemoryReadModelStore { + fn scan_read_model(&self, request: super::ReadModelScanRequest) + -> impl Future> + Send + '_ { + async move { + request.validate()?; + let registry = self.schema_registry.read().map_err(|_| TableStoreError::Storage("schema registry lock poisoned".into()))?; + if registry.schema_for_model(&request.schema.model_name).is_some_and(|s| s != &request.schema) { + return Err(TableStoreError::Metadata("scan schema differs from registered model".into())); + } + let rows = self.relational_rows.read().map_err(|_| TableStoreError::Storage("row lock poisoned".into()))?; + let prefix = format!("{}:", request.schema.table_name); + let mut selected = BTreeMap::new(); + for (storage_key, row) in rows.iter() { + if !storage_key.starts_with(&prefix) || !request.matches(&row.values) { continue; } + let Some(RowValue::String(key)) = row.values.get(request.key_column()) else { return Err(TableStoreError::Metadata("invalid scan row key".into())); }; + if request.after().is_some_and(|after| key.as_str() <= after) { continue; } + selected.insert(key, row); + if selected.len() > usize::from(request.limit) + 1 { selected.pop_last(); } + } + request.finish(selected.into_values().map(|row| Versioned { data: row.values.clone(), version: row.version }).collect()) + } + } + fn read_model_query_capabilities(&self) -> ReadModelQueryCapabilities { ReadModelQueryCapabilities::relationship_includes() } diff --git a/src/read_model/mod.rs b/src/read_model/mod.rs index 6a4bfcba7..92b78d31d 100644 --- a/src/read_model/mod.rs +++ b/src/read_model/mod.rs @@ -29,6 +29,7 @@ mod capabilities; pub mod change; pub(crate) mod in_memory; mod load; +mod scan; mod plan; mod workspace; @@ -90,6 +91,7 @@ pub trait RelationalReadModelIncludes: RelationalReadModel { } pub use capabilities::ReadModelQueryCapabilities; +pub use scan::{ReadModelScanCursor, ReadModelScanPage, ReadModelScanRequest}; pub use in_memory::InMemoryReadModelStore; pub use load::{ ReadModelIncludeRows, ReadModelLoadBuilder, ReadModelLoadGraph, ReadModelLoadRequest, diff --git a/src/read_model/scan.rs b/src/read_model/scan.rs new file mode 100644 index 000000000..5bb32bc58 --- /dev/null +++ b/src/read_model/scan.rs @@ -0,0 +1,235 @@ +//! Bounded read-only equality/keyset selection. A row is not authorization. +use super::{RelationalReadModel, Versioned}; +use crate::table::{ColumnType, RowValue, RowValues, TableSchema, TableStoreError}; + +/// Opaque continuation tied to exactly one declared schema and equality scope. +/// Pages are current reads, not a cross-page database snapshot. +#[derive(Clone, Debug, PartialEq)] +pub struct ReadModelScanCursor { + schema: TableSchema, + equals: RowValues, + after: String, +} +impl ReadModelScanCursor { + pub fn after(&self) -> &str { + &self.after + } +} + +#[derive(Clone, Debug)] +pub struct ReadModelScanRequest { + pub(crate) schema: TableSchema, + pub(crate) equals: RowValues, + pub(crate) cursor: Option, + pub(crate) limit: u16, +} +impl ReadModelScanRequest { + /// Single nonnullable text PK, at most 16 scalar equality predicates and + /// 1..=100 rows. No offsets, joins, includes, raw SQL or aggregate reads. + pub fn new( + equals: RowValues, + limit: u16, + cursor: Option, + ) -> Result { + let request = Self { + schema: M::schema().clone(), + equals, + cursor, + limit, + }; + request.validate()?; + Ok(request) + } + pub(crate) fn validate(&self) -> Result<(), TableStoreError> { + let invalid = + |message: &str| TableStoreError::Metadata(format!("read-model keyset scan: {message}")); + self.schema.validate()?; + if !self.schema.kind.is_read_model() { + return Err(invalid("operational tables are not read models")); + } + if !(1..=100).contains(&self.limit) || self.equals.len() > 16 { + return Err(invalid( + "limit must be 1..=100; at most 16 equality predicates", + )); + } + if self.schema.primary_key.columns.len() != 1 { + return Err(invalid("single text primary key required")); + } + let primary = self + .schema + .columns + .iter() + .find(|c| c.column_name == self.key_column()) + .ok_or_else(|| invalid("missing primary key"))?; + if primary.column_type != ColumnType::Text || primary.nullable { + return Err(invalid("nonnullable text primary key required")); + } + for (name, value) in self.equals.iter() { + let column = self + .schema + .columns + .iter() + .find(|c| c.column_name == name) + .ok_or_else(|| invalid("unknown filter column"))?; + let valid = match (&column.column_type, value) { + (_, RowValue::Null) => column.nullable, + (ColumnType::Text, RowValue::String(value)) => { + value.len() <= 4096 && !value.contains('\0') + } + (ColumnType::Boolean, RowValue::Bool(_)) + | (ColumnType::Integer, RowValue::I64(_)) => true, + (ColumnType::UnsignedInteger, RowValue::U64(value)) => *value <= i64::MAX as u64, + (ColumnType::UnsignedInteger, RowValue::I64(value)) => *value >= 0, + _ => false, + }; + if !valid { + return Err(invalid("unsupported or mismatched scalar filter")); + } + } + if let Some(cursor) = &self.cursor { + if cursor.schema != self.schema + || cursor.equals != self.equals + || cursor.after.len() > 4096 + || cursor.after.contains('\0') + { + return Err(invalid("cursor does not match schema/filter scope")); + } + } + Ok(()) + } + pub(crate) fn key_column(&self) -> &str { + &self.schema.primary_key.columns[0] + } + pub(crate) fn after(&self) -> Option<&str> { + self.cursor.as_ref().map(|c| c.after.as_str()) + } + pub(crate) fn matches(&self, row: &RowValues) -> bool { + self.equals + .iter() + .all(|(name, expected)| match (row.get(name), expected) { + (Some(RowValue::I64(actual)), RowValue::U64(expected)) => { + *actual >= 0 && *actual as u64 == *expected + } + (Some(RowValue::U64(actual)), RowValue::I64(expected)) => { + *expected >= 0 && *actual == *expected as u64 + } + (Some(actual), expected) => actual == expected, + _ => false, + }) + } + pub(crate) fn finish( + &self, + mut rows: Vec>, + ) -> Result { + let more = rows.len() > usize::from(self.limit); + rows.truncate(usize::from(self.limit)); + let next = if more { + let Some(RowValue::String(after)) = + rows.last().and_then(|r| r.data.get(self.key_column())) + else { + return Err(TableStoreError::Metadata( + "scan returned invalid primary key".into(), + )); + }; + if after.len() > 4096 || after.contains('\0') { + return Err(TableStoreError::Metadata( + "scan primary key exceeds cursor bound".into(), + )); + } + Some(ReadModelScanCursor { + schema: self.schema.clone(), + equals: self.equals.clone(), + after: after.clone(), + }) + } else { + None + }; + Ok(ReadModelScanPage { + rows, + next, + schema: self.schema.clone(), + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ReadModelScanPage { + pub rows: Vec>, + pub next: Option, + schema: TableSchema, +} +impl ReadModelScanPage { + pub fn typed(&self) -> Result>, TableStoreError> { + if M::schema() != &self.schema { + return Err(TableStoreError::Metadata( + "scan page belongs to another model".into(), + )); + } + self.rows + .iter() + .map(|row| { + Ok(Versioned { + data: M::from_row(row.data.clone())?, + version: row.version, + }) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::table::{PrimaryKey, TableColumn, TableKind}; + fn request() -> ReadModelScanRequest { + let schema = TableSchema { + model_name: "Page".into(), + table_name: "pages".into(), + columns: vec![TableColumn::new("id", "id", ColumnType::Text)], + primary_key: PrimaryKey::new(["id"]), + relationships: vec![], indexes: vec![], foreign_keys: vec![], version_column: Some("_sourced_version".into()), kind: TableKind::ReadModel, + }; + ReadModelScanRequest { + schema, + equals: RowValues::new(), + cursor: None, + limit: 10, + } + } + #[test] + fn malformed_schemas_and_cursor_scopes_fail_before_io() { + let good = request(); + good.validate().unwrap(); + let mut bad = good.clone(); + bad.schema.kind = TableKind::Operational; + assert!(bad.validate().is_err()); + let mut bad = good.clone(); + bad.schema.primary_key.columns.push("extra".into()); + assert!(bad.validate().is_err()); + let mut bad = good.clone(); + bad.schema.columns[0].column_type = ColumnType::Integer; + assert!(bad.validate().is_err()); + let mut bad = good.clone(); + bad.schema.columns[0].nullable = true; + assert!(bad.validate().is_err()); + let mut bad = good.clone(); + bad.cursor = Some(ReadModelScanCursor { + schema: good.schema.clone(), + equals: filter(), + after: "key".into(), + }); + assert!(bad.validate().is_err()); + let mut bad = good.clone(); + bad.cursor = Some(ReadModelScanCursor { + schema: good.schema.clone(), + equals: RowValues::new(), + after: "x".repeat(4097), + }); + assert!(bad.validate().is_err()); + } + fn filter() -> RowValues { + let mut values = RowValues::new(); + values.insert("id", RowValue::String("key".into())); + values + } +} diff --git a/src/repository/traits.rs b/src/repository/traits.rs index 7a6513262..93d310440 100644 --- a/src/repository/traits.rs +++ b/src/repository/traits.rs @@ -197,6 +197,14 @@ pub trait ReadModelWritePlanStore: Send + Sync { pub trait RelationalReadModelQueryStore: Send + Sync { fn read_model_query_capabilities(&self) -> ReadModelQueryCapabilities; + /// Optional bounded normalized-row scan. Unsupported adapters fail closed. + fn scan_read_model( + &self, + _request: crate::read_model::ReadModelScanRequest, + ) -> impl Future> + Send + '_ { + async { Err(TableStoreError::Metadata("bounded read-model scan is unsupported by this adapter".into())) } + } + fn load_graph( &self, request: ReadModelLoadRequest, diff --git a/src/sqlx_repo/read_model/mod.rs b/src/sqlx_repo/read_model/mod.rs index 08b611035..12c91ff2f 100644 --- a/src/sqlx_repo/read_model/mod.rs +++ b/src/sqlx_repo/read_model/mod.rs @@ -15,6 +15,8 @@ mod backend; mod load; mod query; +mod scan; +pub(crate) use scan::scan_read_model; mod schema_registry; mod validation; mod write_plan; diff --git a/src/sqlx_repo/read_model/scan.rs b/src/sqlx_repo/read_model/scan.rs new file mode 100644 index 000000000..37e7b7fc5 --- /dev/null +++ b/src/sqlx_repo/read_model/scan.rs @@ -0,0 +1,71 @@ +//! The bounded scan lowers declared columns and typed binds through the shared +//! relational adapter. Applications never construct query text. +use super::{ + column_by_name, quote_identifier, relational_row_select, row_to_versioned_values, + SqlxReadModelBackend, +}; +use crate::{ + read_model::{ReadModelScanPage, ReadModelScanRequest}, + table::{RowValue, TableStoreError}, +}; +use sqlx::{Database, Encode, Executor, IntoArguments, Type}; + +pub(crate) async fn scan_read_model( + pool: &sqlx::Pool, + request: ReadModelScanRequest, +) -> Result +where + DB: SqlxReadModelBackend, + for<'c> &'c sqlx::Pool: Executor<'c, Database = DB>, + ::Arguments: IntoArguments, + for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, + for<'r> &'r str: sqlx::ColumnIndex<::Row>, +{ + request.validate()?; + let schema = &request.schema; + let collation = if DB::BACKEND == "postgres" { + " COLLATE \"C\"" + } else { + " COLLATE BINARY" + }; + let mut builder = relational_row_select::(schema)?; + builder.push(" WHERE 1=1"); + for (name, value) in request.equals.iter() { + builder.push(" AND "); + builder.push(quote_identifier(name)); + if column_by_name(schema, name)?.column_type == crate::ColumnType::Text { + builder.push(collation); + } + if matches!(value, RowValue::Null) { + builder.push(" IS NULL"); + } else { + builder.push(" = "); + DB::push_row_value_bind(&mut builder, value.clone(), column_by_name(schema, name)?)?; + } + } + // Bytewise text order matches Rust and remains stable across database locales. + if let Some(after) = request.after() { + builder.push(" AND "); + builder.push(quote_identifier(request.key_column())); + builder.push(collation); + builder.push(" > "); + DB::push_row_value_bind( + &mut builder, + RowValue::String(after.into()), + column_by_name(schema, request.key_column())?, + )?; + } + builder.push(" ORDER BY "); + builder.push(quote_identifier(request.key_column())); + builder.push(collation); + builder.push(" ASC LIMIT "); + builder.push_bind(i64::from(request.limit) + 1); + let rows = builder.build().fetch_all(pool).await.map_err(|error| { + crate::sqlx_repo::read_model_storage_error(DB::BACKEND, "scan read-model page", error) + })?; + request.finish( + rows.iter() + .map(|row| row_to_versioned_values::(schema, row)) + .collect::>()?, + ) +} diff --git a/src/sqlx_repo/repo/read_models.rs b/src/sqlx_repo/repo/read_models.rs index d32ae226d..0185679c8 100644 --- a/src/sqlx_repo/repo/read_models.rs +++ b/src/sqlx_repo/repo/read_models.rs @@ -47,6 +47,20 @@ where for<'q> i64: Encode<'q, DB> + Type + sqlx::Decode<'q, DB>, for<'r> &'r str: sqlx::ColumnIndex, { + fn scan_read_model(&self, request: crate::read_model::ReadModelScanRequest) + -> impl Future> + Send + '_ { + async move { + request.validate()?; + { + let registry = self.read_model_schemas.read().map_err(|_| TableStoreError::Storage("schema registry lock poisoned".into()))?; + if registry.schema_for_model(&request.schema.model_name).is_some_and(|s| s != &request.schema) { + return Err(TableStoreError::Metadata("scan schema differs from registered model".into())); + } + } + crate::sqlx_repo::read_model::scan_read_model(&self.pool, request).await + } + } + fn read_model_query_capabilities(&self) -> ReadModelQueryCapabilities { ReadModelQueryCapabilities::relationship_includes() } diff --git a/tests/read_model_keyset/main.rs b/tests/read_model_keyset/main.rs new file mode 100644 index 000000000..a33b5a9e5 --- /dev/null +++ b/tests/read_model_keyset/main.rs @@ -0,0 +1,168 @@ +use distributed::read_model::{ReadModelScanRequest, ReadModelWritePlanBuilder}; +use distributed::{ + ReadModel, ReadModelWritePlanStore, RelationalReadModelQueryStore, RowValue, RowValues, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] +#[readmodel(primary_key = ["id"])] +struct ScanCandidate { + #[readmodel(id)] + id: String, + scope: String, + source: Option, + enabled: bool, + generation: u64, +} +fn filter(scope: &str) -> RowValues { + let mut values = RowValues::new(); + values.insert("scope", RowValue::String(scope.into())); + values +} +async fn exercise(store: &S) { + let mut plan = ReadModelWritePlanBuilder::new(); + for index in 0..230 { + plan.upsert(&ScanCandidate { + id: format!("candidate-{index:03}"), + scope: if index < 205 { "repo" } else { "foreign" }.into(), + source: (index % 2 == 0).then(|| "storage".into()), + enabled: index % 2 == 0, + generation: 1, + }) + .unwrap(); + } + plan.commit(store).await.unwrap(); + let mut cursor = None; + let mut ids = Vec::new(); + loop { + let page = store + .scan_read_model( + ReadModelScanRequest::new::(filter("repo"), 100, cursor).unwrap(), + ) + .await + .unwrap(); + assert!(page.rows.len() <= 100); + assert!(page.rows.iter().all(|r| r.version == 1)); + ids.extend( + page.typed::() + .unwrap() + .into_iter() + .map(|r| r.data.id), + ); + cursor = page.next; + if cursor.is_none() { + break; + } + } + assert_eq!( + ids, + (0..205) + .map(|i| format!("candidate-{i:03}")) + .collect::>() + ); + let first = store + .scan_read_model( + ReadModelScanRequest::new::(filter("repo"), 100, None).unwrap(), + ) + .await + .unwrap(); + let cursor = first.next.unwrap(); + assert_eq!(cursor.after(), "candidate-099"); + assert!(ReadModelScanRequest::new::( + filter("foreign"), + 100, + Some(cursor.clone()) + ) + .is_err()); + let mut update = ReadModelWritePlanBuilder::new(); + update + .upsert(&ScanCandidate { + id: "candidate-100".into(), + scope: "repo".into(), + source: None, + enabled: false, + generation: 2, + }) + .unwrap(); + update + .upsert(&ScanCandidate { + id: "candidate-099-new".into(), + scope: "repo".into(), + source: None, + enabled: false, + generation: 2, + }) + .unwrap(); + update.commit(store).await.unwrap(); + let second = store + .scan_read_model( + ReadModelScanRequest::new::(filter("repo"), 2, Some(cursor)).unwrap(), + ) + .await + .unwrap(); + let rows = second.typed::().unwrap(); + assert_eq!(rows[0].data.id, "candidate-099-new"); + assert_eq!(rows[1].data.id, "candidate-100"); + assert_eq!(rows[1].version, 2); + let mut null = filter("repo"); + null.insert("source", RowValue::Null); + null.insert("generation", RowValue::U64(2)); + let page = store + .scan_read_model(ReadModelScanRequest::new::(null, 100, None).unwrap()) + .await + .unwrap(); + assert_eq!(page.rows.len(), 2); + assert!(page.next.is_none()); + let empty = store + .scan_read_model( + ReadModelScanRequest::new::(filter("absent"), 100, None).unwrap(), + ) + .await + .unwrap(); + assert!(empty.rows.is_empty()); + assert!(empty.next.is_none()); + for limit in [0, 101, u16::MAX] { + assert!(ReadModelScanRequest::new::(filter("repo"), limit, None).is_err()); + } + for (name, value) in [ + ("missing", RowValue::String("x".into())), + ("generation", RowValue::String("1".into())), + ("scope", RowValue::Null), + ("generation", RowValue::U64(u64::MAX)), + ("enabled", RowValue::I64(1)), + ] { + let mut bad = RowValues::new(); + bad.insert(name, value); + assert!(ReadModelScanRequest::new::(bad, 1, None).is_err()); + } +} +#[tokio::test] +async fn bounded_keyset_in_memory_and_queued_repository() { + let store = distributed::InMemoryRepository::new(); + store + .model_store() + .register_schema::() + .unwrap(); + exercise(&store).await; + let inner = distributed::InMemoryRepository::new(); + inner + .model_store() + .register_schema::() + .unwrap(); + let queued = distributed::QueuedRepository::new(inner); + exercise(&queued).await; +} +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn bounded_keyset_sqlite_preserves_scope_cursor_and_row_versions() { + let store = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let mut registry = distributed::TableSchemaRegistry::new(); + registry.register::().unwrap(); + store + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + exercise(&store).await; +} From b522d0cc47fd3699bcddad5c7a73f72cc133b809 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 15 Sep 2026 15:52:24 -0500 Subject: [PATCH 105/484] fix: authorize rotated credentials on SvelteKit data loads --- docs/session-refresh-continuity.md | 20 +++++++++++++++ js/README.md | 7 ++++-- js/src/sveltekit/server-replica.ts | 11 ++++---- js/tests/sveltekit-ssr.test.mjs | 40 +++++++++++++++++++++++++++--- tests/e2e-ui/gateway/README.md | 3 +++ tests/e2e-ui/gateway/run.mjs | 13 +++++++++- 6 files changed, 82 insertions(+), 12 deletions(-) create mode 100644 docs/session-refresh-continuity.md diff --git a/docs/session-refresh-continuity.md b/docs/session-refresh-continuity.md new file mode 100644 index 000000000..aff035585 --- /dev/null +++ b/docs/session-refresh-continuity.md @@ -0,0 +1,20 @@ +# Session refresh continuity + +The server loader must pair a credential with independently authorized route +data on both document and SvelteKit data requests. A follow-up `invalidateAll` +request can rotate the credential again, or observe a cookie renewed by another +request. Returning only that credential leaves the browser no proof that its +existing replica scope remains authorized. + +Each request executes only its compiler-selected, bounded route/layout loads. +Routes without selections do no GraphQL work. This deliberately removes the +previous blanket data-request shortcut; data navigation remains client-side, +but selected reads run on the server to obtain fresh authority. There is no +token-derived scope, cached-proof reuse, or authorization fallback. + +The client keeps its existing rules: a fresh exact-scope transfer can rotate +transports without dropping rows or newer command state; missing, replayed, +tampered or different-scope authority still purges. SSR request isolation and +Auth.js request-local session memoization remain required. The gateway's original +Todo/Chat MutationObserver assertion is unchanged and detects transient removals, +not merely eventual recovery. diff --git a/js/README.md b/js/README.md index 91a27c420..6aeff5244 100644 --- a/js/README.md +++ b/js/README.md @@ -399,8 +399,11 @@ or reuse an old transfer. Logout, changed scopes, and invalid hydration still purge the generation. The sample auth refresh endpoint returns an authorized seed for the current -route before invalidating SvelteKit page data. Ordinary SPA navigation still -skips server GraphQL work. +route before invalidating SvelteKit page data. Follow-up data loads and ordinary +SPA navigation execute their bounded server selections too: those requests can +rotate credentials independently and need their own fresh authority. Routes +without selections still do no GraphQL work. See +[session refresh continuity](../docs/session-refresh-continuity.md). Confirmed records and indexes under an active scope stay until auth/scope change, stale+revalidate, or a newer authoritative write. Same-scope soft diff --git a/js/src/sveltekit/server-replica.ts b/js/src/sveltekit/server-replica.ts index b4ce19bbf..2fcb0a5b8 100644 --- a/js/src/sveltekit/server-replica.ts +++ b/js/src/sveltekit/server-replica.ts @@ -89,12 +89,11 @@ export function createDistributedSvelteKitServer< accessToken, engineRole }; - if (event.isDataRequest === true) { - return { - ...pageData, - gqlError: null - }; - } + // Data requests may rotate the cookie again after an auth refresh, or + // observe a credential renewed by a concurrent request. A credential + // without fresh server authority cannot preserve the browser's scope. + // Resolve the same bounded route selections for document and data loads; + // warm same-scope hydration merges without replacing newer command state. const auth = options.getAuth?.(pageData, event) ?? authFromPageData(pageData); const routeId = routeIdentity(event); diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index 3b4cfaeff..63bfa3f7d 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -277,7 +277,7 @@ test('SSR abort settles while forwarded parent data remains pending', async () = assert.equal(parentCalls, 1); }); -test('client-side data requests skip GraphQL so navigation stays SPA', async () => { +test('client-side data requests carry their own authorized route seed', async () => { const harness = serverHarness(); const document = await harness.server.load(harness.event('alice')); assert.equal(harness.calls.length, 1); @@ -287,8 +287,10 @@ test('client-side data requests skip GraphQL so navigation stays SPA', async () ...harness.event('alice'), isDataRequest: true }); - assert.equal(harness.calls.length, 1, 'SPA data request must not seed a new replica'); - assert.equal(dataNav.distributed, undefined); + assert.equal(harness.calls.length, 2, 'one authorized selection per document or data load'); + assert.ok(dataNav.distributed); + assert.ok(dataNav.distributedAuthority); + assert.notEqual(dataNav.distributed, document.distributed); assert.equal(dataNav.gqlError, null); assert.equal(dataNav.accessToken, 'alice'); }); @@ -596,6 +598,38 @@ test('queued page-data updates retain the fresh authority before seedless invali unsubscribe(); client.destroy(); }); +test('a credential rotated by follow-up data loading carries independent authority', async () => { + const harness = serverHarness(); + const first = await harness.server.load(harness.event('alice')); + const refresh = await harness.server.load(harness.event('alice', '2')); + const pageData = createPageDataSessionSource(first); + const client = createDistributedSvelteKit({ + boundaries: [todosBoundary], session: pageData.session, + hydration: first.distributed, authority: first.distributedAuthority, + fetch: () => new Promise(() => {}), webSocket: SsrWebSocket + }); + const todos = client.operation(TodosArtifact).use({}, {live:false}); + const values = []; + const unsubscribe = todos.subscribe(snapshot => values.push(snapshot.data.todos?.[0]?.title)); + await flushMicrotasks(); + pageData.set({...refresh, accessToken:'refresh-credential'}); + await flushMicrotasks(); + // The follow-up request can legitimately rotate again (elapsed refresh skew + // or another request renewing the cookie). Its authority must be independent + // of the already-consumed refresh transfer, not inferred from the token. + const event = harness.event('alice', '3'); + const fetch = event.fetch; + event.locals.session.accessToken = 'follow-up-credential'; + event.fetch = (url, init) => fetch(url, {...init, headers:{...init.headers, authorization:'Bearer alice'}}); + const navigation = await harness.server.load({...event, isDataRequest:true}); + pageData.set(navigation); + await flushMicrotasks(); + assert.ok(navigation.distributedAuthority, 'changed data-request credential needs fresh server authority'); + assert.ok(values.every(value => value === 'alice:1'), JSON.stringify(values)); + assert.equal(client.replica.scope.cacheScope, 'cache:alice'); + unsubscribe(); client.destroy(); +}); + for (const kind of ['missing', 'replayed', 'historical', 'tampered', 'different-scope', 'logout']) { test(`credential change with ${kind} hydration still purges the old replica`, async () => { const harness = serverHarness(); diff --git a/tests/e2e-ui/gateway/README.md b/tests/e2e-ui/gateway/README.md index 41b7460e2..ac68cd9e5 100644 --- a/tests/e2e-ui/gateway/README.md +++ b/tests/e2e-ui/gateway/README.md @@ -18,3 +18,6 @@ refetch, an old HTTP/cache response arriving after another move, and a real old live frame replayed after a confirmed Chat command. Mutation observers detect transient regressions as well as the final state. Logs omit session payloads and are saved under ignored `artifacts/`. +The first follow-up Todo data request is held across the fixture's refresh skew, +forcing another real credential rotation after the refresh proof was consumed. +The unchanged Todo/Chat continuity assertion must pass through this interleaving. diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 1282a02d9..1668452a9 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -81,7 +81,18 @@ try{ await page.goto(publicOrigin+'/blob');await expect(page.getByTestId('blob-start-game')).toBeEnabled();await page.getByTestId('blob-start-game').click();await expect(page.locator('.blob-board')).toBeVisible({timeout:20000}); await verifyBlobRace(page); await verifyLiveRace(page,publicOrigin); - await verifySessionRefreshContinuity(page,publicOrigin); + // Force the follow-up data loader across the fixture's five-second refresh + // skew. The independent refresh proof has already been consumed, so a + // second rotated credential must arrive with its own server authority. + let delayedRefreshData=false; + const delayRefreshData=async route=>{ + if(!delayedRefreshData){delayedRefreshData=true;await new Promise(resolve=>setTimeout(resolve,6000));} + await route.continue(); + }; + await page.route('**/todos/__data.json*',delayRefreshData); + try{await verifySessionRefreshContinuity(page,publicOrigin);} + finally{await page.unroute('**/todos/__data.json*',delayRefreshData);} + assert.ok(delayedRefreshData,'continuity proof must exercise follow-up credential rotation'); if(process.env.GATEWAY_LIFECYCLE==='1'){ assert.ok(devMode,'full reload proof requires the CLI dev host'); const storage=path.join(temporary,'reload-auth.json');await context.storageState({path:storage}); From 4b2352bcdf2b56422470cb2e3b445c31d2e7b779 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 15 Sep 2026 16:19:11 -0500 Subject: [PATCH 106/484] fix: retain live layout subscriptions during warm hydration Preserve active live cursors and local operation fences during same-scope data navigation; merge route seeds without regressing confirmed state. Credential reauthorization remains fail-closed. Reproduces and fixes PR227 live-stack Chat navigation failure. Original browser assertions unchanged; 403 JS tests, generated TypeScript, and both gateway delivery modes pass. --- docs/session-refresh-continuity.md | 9 +++ .../impl-hydration-orchestrate.ts | 76 +++++++++++++++++-- js/tests/replica-protocol.test.mjs | 7 +- js/tests/replica-scope-ssr.test.mjs | 16 ++++ js/tests/sveltekit-ssr.test.mjs | 58 ++++++++++++++ tests/e2e-ui/gateway/README.md | 7 ++ tests/e2e-ui/gateway/run.mjs | 8 ++ tests/e2e-ui/playwright.config.ts | 2 +- 8 files changed, 172 insertions(+), 11 deletions(-) diff --git a/docs/session-refresh-continuity.md b/docs/session-refresh-continuity.md index aff035585..8dd624d2e 100644 --- a/docs/session-refresh-continuity.md +++ b/docs/session-refresh-continuity.md @@ -18,3 +18,12 @@ tampered or different-scope authority still purges. SSR request isolation and Auth.js request-local session memoization remain required. The gateway's original Todo/Chat MutationObserver assertion is unchanged and detects transient removals, not merely eventual recovery. + +## Retained layout navigation + +An authorized data seed for an unchanged credential and scope is a cache merge, +not a transport reauthorization. Child navigation must retain the layout's exact +live subscription and local operation fences until its last owner releases it. +Seed merging must not regress confirmed record clocks, live cursors or membership. +Credential changes still require independent authority and transport rotation; +missing authority and changed scope still invalidate the prior replica. diff --git a/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts b/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts index e21655d36..06bbe382e 100644 --- a/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts +++ b/js/src/replica/distributed-replica/impl-hydration-orchestrate.ts @@ -24,7 +24,11 @@ import type { ReplicaAuthoritativeScope, ReplicaDehydratedState } from '../types.js'; -import { freezeRecordClock } from './clocks.js'; +import { + compareIndexVector, + compareRecordClock, + freezeRecordClock +} from './clocks.js'; import { trustedPresetInventoryFingerprint } from './helpers.js'; import { hydrationMetadataConsistent, @@ -419,21 +423,71 @@ export function hydrateReplica( // Warm same-scope re-hydrate (soft nav / second SSR seed): keep confirmed // records and indexes the route seed omitted. Seed keys upsert; purge only // happens on auth/scope change (closeAuthorizationGeneration path). - host.closeActiveTransports(); - host.queryStates.clear(); + // A route seed is not a transport handoff. In particular its query-only + // protocol must not replace a retained layout's live cursor or generation. + const retainedIndexes = new Set(); + for (const group of host.operationProtocols.values()) { + if (group.live !== undefined && group.live.retiredAtRevision === undefined) { + for (const key of group.live.indexKeys) retainedIndexes.add(key); + } + } for (const [key, group] of parsed.operationProtocols) { - host.operationProtocols.set(key, group); + const previous = host.operationProtocols.get(key); + if (previous?.live !== undefined && previous.live.retiredAtRevision === undefined) continue; + const before = previous?.query; + const incoming = group.query; + if ( + incoming !== undefined && + [...incoming.indexKeys].some((index) => retainedIndexes.has(index)) + ) continue; + if (before !== undefined && incoming !== undefined) { + const disposition = before.snapshotScope === incoming.snapshotScope + ? compareIndexVector( + before.indexClocks, + [...incoming.indexClocks].map( + ([projection, clock]) => ({ projection, ...clock }) + ) + ) + : 'incomparable'; + if (disposition === 'lower' || disposition === 'incomparable') { + for (const index of incoming.indexKeys) retainedIndexes.add(index); + continue; + } + } + host.operationProtocols.set(key, { + ...group, + ...(previous?.live === undefined ? {} : { live: previous.live }) + }); } for (const [key, generation] of parsed.operationGenerations) { - host.operationGenerations.set(key, generation); + // These are replica-local callback fences, not comparable server clocks. + if (!host.operationGenerations.has(key)) { + host.operationGenerations.set(key, generation); + } } + const retainedRecords = new Set(); for (const [key, clock] of parsed.recordClocks) { + const previous = host.recordClocks.get(key); + if ( + previous !== undefined && ( + previous.scopeToken !== clock.scopeToken || + compareRecordClock(previous, clock) > 0 + ) + ) { + retainedRecords.add(key); + continue; + } host.recordClocks.set(key, clock); } for (const [scopeToken, key] of parsed.recordKeysByScope) { - host.recordKeysByScope.set(scopeToken, key); + if (!retainedRecords.has(key)) host.recordKeysByScope.set(scopeToken, key); } for (const [scopeToken, clock] of parsed.anonymousRecordClocks) { + const previous = host.anonymousRecordClocks.get(scopeToken); + if ( + previous !== undefined && + compareRecordClock(previous.clock, clock.clock) > 0 + ) continue; host.anonymousRecordClocks.set(scopeToken, clock); } host.setTrustedPresets(parsed.trustedPresets); @@ -458,7 +512,15 @@ export function hydrateReplica( : {}) }) ); - host.engine.mergeConfirmed(parsed.cache); + host.engine.mergeConfirmed({ + ...parsed.cache, + records: parsed.cache.records.filter( + (record) => !retainedRecords.has(record.key) + ), + indexes: parsed.cache.indexes.filter( + (index) => !retainedIndexes.has(index.key) + ) + }); } else { host.closeAuthorizationGeneration(); host.queryStates.clear(); diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index b76de6401..42095e281 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -2311,15 +2311,16 @@ test('retired live ownership survives dehydration before a later handoff', () => })); assert.equal(current.get().data.games.length, 1); assert.equal(restored.hydrate(dehydrated, dehydrated.scope), true); - assert.equal(restoredObservers.length, 2); - restoredObservers[1].next(gamesFrame({ + assert.equal(current.get().data.games[0].owner.name, 'hydrated handoff'); + assert.equal(restoredObservers.length, 1, 'same-scope hydration retains the active receiver'); + restoredObservers[0].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '4', ownerId: 'user-1', ownerName: 'active receiver after hydrate', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); const contender = restored.watch(previousPage, {}, { live: true }); - restoredObservers[2].next(oldFrame); + restoredObservers[1].next(oldFrame); assert.equal(current.get().data.games[0].owner.name, 'active receiver after hydrate'); contender.destroy(); current.destroy(); diff --git a/js/tests/replica-scope-ssr.test.mjs b/js/tests/replica-scope-ssr.test.mjs index 40dee17c5..4b9d216bc 100644 --- a/js/tests/replica-scope-ssr.test.mjs +++ b/js/tests/replica-scope-ssr.test.mjs @@ -411,6 +411,22 @@ test('same-scope re-hydrate retains confirmed indexes omitted from a later route ); }); +test('older same-scope route seed cannot regress confirmed query membership or record clocks', () => { + const old = createDistributedReplica(); + write(old, Todos, [{ id: 'todo-1', title: 'old' }], { position: '1' }); + old.read(Todos, {}); + const seed = old.dehydrate(); + const warm = createDistributedReplica(); + write(warm, Todos, [{ id: 'todo-1', title: 'current' }, { id: 'todo-2', title: 'new member' }], { position: '3' }); + warm.read(Todos, {}); + const before = warm.dehydrate(); + assert.equal(warm.hydrate(seed, seed.scope), true); + assert.deepEqual(warm.read(Todos, {}).data.todos, [{ id: 'todo-1', title: 'current' }, { id: 'todo-2', title: 'new member' }]); + const after = warm.dehydrate(); + assert.deepEqual(after.payload.operations, before.payload.operations); + assert.deepEqual(after.payload.recordClocks, before.payload.recordClocks); +}); + test('hydration rejects malformed, cross-scope, and elevated-schema state atomically', () => { const current = createDistributedReplica(); write(current, Todos, [{ id: 'todo-1', title: 'current' }]); diff --git a/js/tests/sveltekit-ssr.test.mjs b/js/tests/sveltekit-ssr.test.mjs index 63bfa3f7d..fab42abc4 100644 --- a/js/tests/sveltekit-ssr.test.mjs +++ b/js/tests/sveltekit-ssr.test.mjs @@ -406,6 +406,64 @@ test('route misses do no GraphQL work and same-scope soft-nav merges overlapping client.destroy(); }); +for (const mode of ['resumable', 'snapshot']) { +test(`same-scope data hydration retains the ${mode} live subscription until its owner releases`, async () => { + const harness = serverHarness(); + const first = await harness.server.load(harness.event('alice', '1')); + const second = await harness.server.load({ ...harness.event('alice', '2'), isDataRequest: true }); + SsrWebSocket.instances.length = 0; + const client = createDistributedSvelteKit({ + boundaries: [todosBoundary], + session: { getAuth: () => ({ accessToken: 'alice' }) }, + hydration: first.distributed, + authority: first.distributedAuthority, + fetch: async () => { throw new Error('hydrated navigation must not fetch'); }, + webSocket: SsrWebSocket + }); + const todos = client.operation(TodosArtifact).use(); + const release = todos.subscribe(() => undefined); + await flushMicrotasks(); + const socket = SsrWebSocket.instances[0]; + socket.open(); + socket.receive({ type: 'connection_ack' }); + await flushMicrotasks(); + const subscription = socket.sent.find((frame) => frame.type === 'subscribe'); + assert.ok(subscription); + assert.equal(client.hydrate(second.distributed, second.distributedAuthority), true); + await flushMicrotasks(); + assert.equal(socket.closed, false); + assert.equal(socket.sent.some((frame) => frame.type === 'complete'), false); + assert.equal(SsrWebSocket.instances.length, 1); + const receive = (position, rows) => socket.receive({ + type: 'next', id: subscription.id, + payload: todoFrame(TodosArtifact, rows, { cacheScope: 'cache:alice', position, source: 'live', mode }) + }); + const rows = [ + { id: 'todo-alice', title: 'newer live row', status: 'open' }, + { id: 'live-only', title: 'newer live member', status: 'open' } + ]; + receive('3', rows); + await flushMicrotasks(); + assert.deepEqual(todos.get().data.todos, rows); + const before = client.replica.dehydrate().payload.operations; + assert.equal(client.hydrate(second.distributed, second.distributedAuthority), true); + assert.deepEqual(todos.get().data.todos, rows, 'stale route seed must not regress live records or membership'); + assert.deepEqual(client.replica.dehydrate().payload.operations, before, 'live cursor and local operation generation must survive query-only seed'); + receive('4', [{ ...rows[0], title: 'continued live stream' }]); + await flushMicrotasks(); + assert.equal(todos.get().data.todos[0].title, 'continued live stream'); + assert.equal(todos.get().data.todos.length, 1); + assert.equal(socket.closed, false); + assert.equal(socket.sent.some((frame) => frame.type === 'complete'), false); + release(); + assert.equal(socket.sent.filter((frame) => frame.type === 'complete' && frame.id === subscription.id).length, 1); + const later = await harness.server.load({ ...harness.event('alice', '5'), isDataRequest: true }); + assert.equal(client.hydrate(later.distributed, later.distributedAuthority), true); + assert.equal(todos.get().data.todos[0].title, 'alice:5', 'a released live owner must not block a later route seed'); + client.destroy(); +}); +} + test('auth changes purge old data, abort live work, and reject cross-scope hydration', async () => { const harness = serverHarness(); const [alice, bob] = await Promise.all([ diff --git a/tests/e2e-ui/gateway/README.md b/tests/e2e-ui/gateway/README.md index ac68cd9e5..f0aa4e3ff 100644 --- a/tests/e2e-ui/gateway/README.md +++ b/tests/e2e-ui/gateway/README.md @@ -21,3 +21,10 @@ are saved under ignored `artifacts/`. The first follow-up Todo data request is held across the fixture's refresh skew, forcing another real credential rotation after the refresh proof was consumed. The unchanged Todo/Chat continuity assertion must pass through this interleaving. + +With `npm ci --prefix tests/e2e-ui`, set `GATEWAY_LAYOUT_TESTS=1` to additionally +run the existing authenticated and anonymous Chat layout Playwright tests against +this isolated gateway. The runner passes its temporary authenticated storage via +`E2E_USER_STORAGE_STATE`; the original test assertions remain unchanged. They +require the same subscription ID throughout child navigation and completion only +on layout exit, without browser GraphQL mount fetches. diff --git a/tests/e2e-ui/gateway/run.mjs b/tests/e2e-ui/gateway/run.mjs index 1668452a9..a170d72d5 100644 --- a/tests/e2e-ui/gateway/run.mjs +++ b/tests/e2e-ui/gateway/run.mjs @@ -63,6 +63,14 @@ try{ await page.getByRole('button',{name:'Continue as Alice'}).click(); await page.waitForURL(url=>url.origin===publicOrigin&&!url.pathname.startsWith('/auth')&&!url.pathname.startsWith('/login')); const session=await(await context.request.get(publicOrigin+'/auth/session')).json();assert.equal(session.user.id,'alice'); + if(process.env.GATEWAY_LAYOUT_TESTS==='1'){ + const storage=path.join(temporary,'layout-auth.json');await context.storageState({path:storage}); + const layout=launch(process.execPath,['node_modules/@playwright/test/cli.js','test','e2e/chat.user.spec.ts','e2e/unauth.anon.spec.ts','--no-deps','--project=chromium-user','--project=chromium-anon','--grep','layout island survives'],{env:{...environment,PUBLIC_ORIGIN:publicOrigin,E2E_USER_STORAGE_STATE:storage}}); + layout.child.stdout.on('data',chunk=>process.stdout.write(chunk)); + const [code]=await once(layout.child,'exit'); + await writeFile(path.join(artifacts,'layout-'+delivery+'.log'),layout.logs()); + assert.equal(code,0,layout.logs()); + } await page.goto(publicOrigin+'/todos');await expect(page.getByRole('heading',{name:/todos/i})).toBeVisible(); const unauthenticated=await fetch(publicOrigin+'/graphql',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({query:'query { todos { todo_id } }'})}); assert.match(unauthenticated.headers.get('content-type'),/json/); diff --git a/tests/e2e-ui/playwright.config.ts b/tests/e2e-ui/playwright.config.ts index 1b3de976b..75e2687fa 100644 --- a/tests/e2e-ui/playwright.config.ts +++ b/tests/e2e-ui/playwright.config.ts @@ -70,7 +70,7 @@ export default defineConfig({ testMatch: /.*\.user\.spec\.ts/, use: { ...devices['Desktop Chrome'], - storageState: path.join(root, 'e2e/.auth/alice.json') + storageState: process.env.E2E_USER_STORAGE_STATE || path.join(root, 'e2e/.auth/alice.json') } }, { From 6217944e051797bdc3641269de7d1f83f2f95615 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 15 Sep 2026 16:31:53 -0500 Subject: [PATCH 107/484] test: observe celld settlement before replaying commands Queue acceptance and a competing drain are not a local deletion barrier. Wait with bounded read-only probes before replay and retain exact zero-outbox, stable-envelope and event-count assertions. A deterministic held-ack test proves the race. 13 dispatcher and 9 watchdog tests pass; full celld 0.5 storage conformance passes twice. No production change or version pin. --- src/outbox_worker/outbox_dispatch.rs | 54 ++++++++++++++++++++++++++++ tests/celld/README.md | 6 ++++ tests/celld/storage-conformance.mjs | 16 ++++++++- 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/outbox_worker/outbox_dispatch.rs b/src/outbox_worker/outbox_dispatch.rs index 166f7e23f..b99080257 100644 --- a/src/outbox_worker/outbox_dispatch.rs +++ b/src/outbox_worker/outbox_dispatch.rs @@ -682,6 +682,60 @@ mod tests { assert_eq!(dispatcher.publisher.ids().len(), 2); } + #[test] + fn queue_acceptance_and_competing_drain_do_not_imply_claim_settlement() { + use std::future::{poll_fn, Future}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::task::Poll; + + struct HeldAcknowledgement { + accepted: AtomicBool, + release: Mutex>>, + } + + impl MessagePublisher for HeldAcknowledgement { + async fn publish(&self, _message: Message) -> Result<(), TransportError> { + // The queue row is externally visible before the publisher's + // response reaches the alarm that owns the local claim. + self.accepted.store(true, Ordering::SeqCst); + let release = self.release.lock().unwrap().take().unwrap(); + release.await.unwrap(); + Ok(()) + } + } + + block_on(async { + let repo = InMemoryRepository::new(); + let id = store_message(&repo, outbox("accepted-before-settlement")); + let (release, response) = tokio::sync::oneshot::channel(); + let alarm = OutboxDispatcher::new( + repo.outbox_store(), + HeldAcknowledgement { + accepted: AtomicBool::new(false), + release: Mutex::new(Some(response)), + }, + "alarm:test", + Duration::from_secs(60), + 3, + ); + let mut pending = Box::pin(alarm.dispatch_batch(1)); + assert!(poll_fn(|cx| Poll::Ready(pending.as_mut().poll(cx))) + .await + .is_pending()); + assert!(alarm.publisher.accepted.load(Ordering::SeqCst)); + assert_eq!(repo.outbox_storage().read().unwrap().len(), 1); + + let replay_drain = dispatcher(&repo, false, 3).dispatch_batch(1).await.unwrap(); + assert_eq!(replay_drain.claimed, 0); + assert_eq!(replay_drain.published, 0); + assert_eq!(repo.outbox_storage().read().unwrap().len(), 1); + + release.send(()).unwrap(); + assert_eq!(pending.await.unwrap().published, 1); + assert!(!repo.outbox_storage().read().unwrap().contains_key(&id)); + }); + } + /// Publisher that fails one specific message id and records the rest. struct SelectiveFailPublisher { fail_id: String, diff --git a/tests/celld/README.md b/tests/celld/README.md index 83cafaf8a..649599cb4 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -175,6 +175,12 @@ also retains 1,101 unsent messages and more than 8 MiB of event payload in one snapshot-backed cell, restarts it, and verifies that alarms drain the backlog without another aggregate request. Events and receipts remain; delivered outbox rows do not. +Queue row visibility is not a local settlement barrier: publication and deletion +are separate awaited operations, and a competing replay drain may find every row +already claimed by an alarm. The crash proof uses bounded read-only probes to +observe zero local outbox rows before replay or another command. Exact zero-row, +stable-envelope and event-count assertions remain; no sleep substitutes for +observing settlement. It prints and retains its temporary artifact directory. Fault probes are feature-gated out of ordinary Worker builds. CI runs this proof separately from the full Queue/NATS/browser profile. diff --git a/tests/celld/storage-conformance.mjs b/tests/celld/storage-conformance.mjs index b13bbab38..30e170be4 100644 --- a/tests/celld/storage-conformance.mjs +++ b/tests/celld/storage-conformance.mjs @@ -99,6 +99,16 @@ async function probe(id, operation) { assert.equal(response.status, 200, `${operation}: ${await response.clone().text()}`); return operation === "inspect" ? response.json() : response.text(); } +async function settledCounts(id, expectedEvents) { + // Queue acceptance precedes the alarm's local DELETE. A competing command + // drain cannot join that in-flight claim; observe completion without nudging + // the cell with another command. The probe is read-only and errors still fail. + return until(`local outbox settlement for ${id}`, async () => { + const { counts } = await probe(id, "inspect"); + assert.equal(counts.events, expectedEvents); + return counts.outbox === 0 && counts; + }); +} async function command(id, name, input, command = commandId(), extraHeaders = {}) { const response = await post(id, name, { commandId: command, input }, extraHeaders); const body = await response.json(); @@ -204,6 +214,7 @@ try { return rows.length >= before + 2 && rows; }); assert.equal(retried[before].body, retried[before + 1].body, "stable delivery envelope survives restart"); + await settledCounts("settlement-crash", 1); const replay = await command("settlement-crash", "todo.create", { title: "delivery proof" }, cid); assert.equal(replay.receipt.replayed, true); assert.deepEqual(replay.payload, original.payload); @@ -221,7 +232,9 @@ try { await start(); await until("prearmed alarm publishes a committed row without another cell request", async () => (await queueRows()).length > beforeDeferred); - await record("committed-before-send restart", (await probe("commit-crash", "inspect")).counts); + const committedSettlement = await settledCounts("commit-crash", 1); + assert.equal(committedSettlement.outbox, 0); + await record("committed-before-send restart", committedSettlement); // Grow event history AND an unsent outbox beyond the former single-value // ceiling. Claim failures cannot reject an already committed command. @@ -246,6 +259,7 @@ try { await start(); await until("large pending outbox drains from alarms without a cell request", async () => (await queueRows(true))[0]?.count >= beforeGrowth + 1101, 120_000); + await settledCounts("growth", 1101); const oldRetry = await command("growth", "todo.create", { title: "0 " + payload }, firstId); assert.equal(oldRetry.receipt.replayed, true); assert.deepEqual(oldRetry.events, first.events); From 42609bd4efe694fb4dd1941c58f85470e295dc3c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 21 Sep 2026 15:37:38 -0500 Subject: [PATCH 108/484] perf: reuse immutable protocol surface manifests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retain engine-owned selected exports and share compiled metadata across request seeds. Principal, preset values, scope tokens and visibility authorization remain per request. Public manifests remain independent clones. Validated 1052 library and43 protocol integration tests. In the retained Forge runtime, repeated authenticated GraphQL fell from about1.1s to14–22ms; warm page DOM times fell from3–7s to97–291ms. Cold dev compilation remains separately documented. --- docs/protocol-manifest-reuse.md | 44 ++++++++++++++++ src/graphql/client_manifest/export.rs | 30 ++++++++--- src/graphql/client_manifest/tests.rs | 69 +++++++++++++++++++++++++ src/graphql/engine/builder.rs | 17 ++++-- src/graphql/engine/core.rs | 1 + src/graphql/engine/request.rs | 23 ++------- src/graphql/engine/tests.rs | 64 +++++++++++++++++++++++ src/graphql/projection_delta/runtime.rs | 4 +- 8 files changed, 220 insertions(+), 32 deletions(-) create mode 100644 docs/protocol-manifest-reuse.md diff --git a/docs/protocol-manifest-reuse.md b/docs/protocol-manifest-reuse.md new file mode 100644 index 000000000..93a610319 --- /dev/null +++ b/docs/protocol-manifest-reuse.md @@ -0,0 +1,44 @@ +# Immutable protocol manifest reuse + +Runtime contract: a selected client surface export owns immutable service, +role/application selection, surface IR and execution limits. Its derived manifest +can be initialized once and shared across clones. Public callers still receive +independently mutable manifest copies. Errors are deterministic for that export +and may be retained; creating another export/engine creates a separate cache. + +The engine must retain the exact exports already validated during protocol +construction, including distinct role and application identities. Request seeds +may borrow their compiled manifests, but must still validate principal, asserted +roles, resolved preset values, authorization generation, visibility surface, +cache-scope HMAC and issuance time for each request. No session, token, result row, +authorization decision or request seed is cached. + +Observed baseline in Forge: authenticated document TTFB around 2.9–4.1 seconds, +simple authenticated GraphQL queries around 1.1 seconds. Native sampling identifies +ProtocolProjectionRequestSeed::new → export.manifest → projection manifest +lowering as repeated CPU work. Validation must cover cache/clone concurrency, +mutable-return independence, role/application/limits isolation and existing +protocol privacy/authority tests, followed by same-route runtime measurements. +No deadline, authentication, SSR or live-subscription behavior may be weakened. + +## Measured local validation + +Same retained Forge stack, same authenticated user and paths, September 21: + +| Warm document (DOM ready) | Before | After | +| --- | ---: | ---: | +| Dashboard | 3140 ms | 116 ms | +| Personal repository, including default-ref redirect | 7445 ms | 291 ms | +| Organization People | 3350 ms | 192 ms | +| ChangeSets | 4123 ms | 97 ms | + +Three direct authenticated GraphQL queries fell from 1143/1135/1072 ms to +22/15/14 ms. These are local observations, not performance assertions or an SLA. +The first repository document after the development server restart still took +18.7 seconds; the warm comparison does not hide that cold-development cost. + +Framework library: 1052 passed, 3 explicit ignored. GraphQL/identity/causal HTTP +integration targets: 43 passed. Added tests exercise concurrent first use, +independent mutable returns, role/application/limit separation, rebuilt-engine +isolation, and actual repeated protocol accumulators retaining/releasing shared +metadata without retaining request authority. Existing auth/privacy checks remain. diff --git a/src/graphql/client_manifest/export.rs b/src/graphql/client_manifest/export.rs index a7be2ffb9..141c2fed4 100644 --- a/src/graphql/client_manifest/export.rs +++ b/src/graphql/client_manifest/export.rs @@ -6,6 +6,9 @@ pub struct DistributedClientSurfaceExport { identity: ClientSurfaceIdentity, surface: Arc, execution: ClientExecutionLimits, + // All inputs are immutable and private. Clones share only compiled metadata, + // never request authority, preset values, tokens or read results. + manifest: Arc>>, } /// Do not transitively format the selected Surface: it retains a private full @@ -32,6 +35,7 @@ impl DistributedClientSurfaceExport { identity, surface: surface.into(), execution, + manifest: Arc::new(std::sync::OnceLock::new()), } } @@ -116,18 +120,32 @@ impl DistributedClientSurfaceExport { } pub fn manifest(&self) -> Result { - client_manifest_from_surface_with_execution( - &self.service_id, - self.identity.clone(), - &self.surface, - self.execution.clone(), - ) + self.manifest_ref().cloned() + } + + pub(crate) fn manifest_ref(&self) -> Result<&DistributedClientManifest, ClientManifestError> { + self.manifest + .get_or_init(|| { + client_manifest_from_surface_with_execution( + &self.service_id, + self.identity.clone(), + &self.surface, + self.execution.clone(), + ) + }) + .as_ref() + .map_err(Clone::clone) } pub fn service_id(&self) -> &str { &self.service_id } + #[cfg(test)] + pub(crate) fn manifest_cache_owners(&self) -> usize { + Arc::strong_count(&self.manifest) + } + pub fn identity(&self) -> &ClientSurfaceIdentity { &self.identity } diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 4f2e876d6..a1b338a1f 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -754,6 +754,75 @@ fn manifest_for_all_models( .expect("client manifest") } +#[test] +fn selected_export_cache_is_shared_concurrently_but_returned_manifests_are_independent() { + let full = full_surface(); + let selected = surface_for_role(&full, "user", &grants()["user"]).unwrap(); + let fresh = client_manifest_from_surface( + "todos-service", + ClientSurfaceIdentity::role("user"), + &selected, + ) + .unwrap(); + let export = DistributedClientSurfaceExport::from_selected("todos-service", selected).unwrap(); + let barrier = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let export = export.clone(); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + let manifest = export.manifest_ref().unwrap(); + ( + manifest as *const DistributedClientManifest as usize, + manifest.clone(), + ) + }) + }) + .collect(); + let expected_address = + export.manifest_ref().unwrap() as *const DistributedClientManifest as usize; + for thread in threads { + let (address, manifest) = thread.join().unwrap(); + assert_eq!(address, expected_address); + assert_eq!(manifest, fresh); + } + let mut detached = export.manifest().unwrap(); + detached.models.clear(); + detached.projection_programs.clear(); + detached.schema_fingerprint.clear(); + assert_eq!(export.manifest_ref().unwrap(), &fresh); + assert_eq!(export.clone().manifest().unwrap(), fresh); +} + +#[test] +fn selected_export_caches_do_not_alias_role_application_or_execution_limits() { + let full = full_surface(); + let grants = grants(); + let user = surface_for_role(&full, "user", &grants["user"]).unwrap(); + let admin = surface_for_role(&full, "admin", &grants["admin"]).unwrap(); + let application = + surface_for_application(&full, "web", &["user".into()], &["user".into()], &grants).unwrap(); + let user_export = + DistributedClientSurfaceExport::from_selected("todos-service", user.clone()).unwrap(); + let admin_export = + DistributedClientSurfaceExport::from_selected("todos-service", admin).unwrap(); + let app_export = + DistributedClientSurfaceExport::from_selected("todos-service", application).unwrap(); + let mut limits = ClientExecutionLimits::default(); + limits.max_bool_width += 1; + let limited = + DistributedClientSurfaceExport::from_selected_with_execution("todos-service", user, limits) + .unwrap(); + let baseline = user_export.manifest_ref().unwrap(); + for other in [&admin_export, &app_export, &limited] { + let manifest = other.manifest_ref().unwrap(); + assert!(!std::ptr::eq(baseline, manifest)); + assert_ne!(baseline.schema_fingerprint, manifest.schema_fingerprint); + } + assert_ne!(user_export.identity(), app_export.identity()); +} + #[test] fn role_manifest_is_deterministic_and_hides_denied_identity_and_commands() { let full = full_surface(); diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 4ccc46b86..aeca975c9 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -836,7 +836,7 @@ impl GraphqlEngineBuilder { .expect("protocol configuration validated a service ID"); let (authorization_fingerprint, claim_keys) = role_authorization_info(role, &self.permissions)?; - let manifest = DistributedClientSurfaceExport::from_selected_with_execution( + let export = DistributedClientSurfaceExport::from_selected_with_execution( service_id, Arc::clone(&role_surface), ClientExecutionLimits::from_runtime( @@ -847,17 +847,22 @@ impl GraphqlEngineBuilder { ) .map_err(|error| GraphqlBuildError(error.to_string()))?, ) - .and_then(|export| export.manifest()) .map_err(|error| { GraphqlBuildError(format!( "failed to derive GraphQL protocol surface for role `{role}`: {error}" )) })?; + let manifest = export.manifest().map_err(|error| { + GraphqlBuildError(format!( + "failed to derive GraphQL protocol surface for role `{role}`: {error}" + )) + })?; let trusted_presets = protocol_trusted_presets(&manifest)?; protocol_roles.insert( role.clone(), ProtocolRoleInfo { surface: ProtocolSurfaceInfo { + export, schema_fingerprint: manifest.schema_fingerprint, protocol_fingerprint: manifest.protocol_fingerprint, trusted_presets, @@ -915,7 +920,7 @@ impl GraphqlEngineBuilder { .service_id .as_deref() .expect("protocol configuration validated a service ID"); - let manifest = DistributedClientSurfaceExport::from_selected_with_execution( + let export = DistributedClientSurfaceExport::from_selected_with_execution( service_id, Arc::clone(&application_surface), ClientExecutionLimits::from_runtime( @@ -926,7 +931,10 @@ impl GraphqlEngineBuilder { ) .map_err(|error| GraphqlBuildError(error.to_string()))?, ) - .and_then(|export| export.manifest()) + .map_err(|error| GraphqlBuildError(format!( + "failed to derive GraphQL protocol surface for application `{application}`: {error}" + )))?; + let manifest = export.manifest() .map_err(|error| { GraphqlBuildError(format!( "failed to derive GraphQL protocol surface for application `{application}`: {error}" @@ -990,6 +998,7 @@ impl GraphqlEngineBuilder { schema_roles: registration.schema_roles.clone(), privilege_key, surface: ProtocolSurfaceInfo { + export, schema_fingerprint: manifest.schema_fingerprint, protocol_fingerprint: manifest.protocol_fingerprint, trusted_presets, diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index b453f60ad..f90815d07 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -170,6 +170,7 @@ pub(crate) struct RoleModelPerm { #[derive(Clone)] pub(crate) struct ProtocolSurfaceInfo { + pub(crate) export: DistributedClientSurfaceExport, pub(crate) schema_fingerprint: String, pub(crate) protocol_fingerprint: String, pub(crate) trusted_presets: Vec, diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index e8d3c2e77..bf027f643 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -298,26 +298,9 @@ impl GraphqlEngine { .get(&authority.privilege_role) .cloned() .ok_or(())?; - let selected_surface = match &surface_identity { - ClientSurfaceIdentity::Role { name } => self.inner.role_surfaces.get(name), - ClientSurfaceIdentity::Application { name, .. } => { - self.inner.application_surfaces.get(name) - } - } - .cloned() - .ok_or(())?; - let export = DistributedClientSurfaceExport::from_selected_with_execution( - &runtime.service_id, - selected_surface, - ClientExecutionLimits::from_runtime( - self.inner.max_depth, - self.inner.max_complexity, - self.inner.max_bool_width, - self.inner.max_in_list, - ) - .map_err(|_| ())?, - ) - .map_err(|_| ())?; + // Selected by the verified authority above; this exact immutable + // export was validated when the engine's protocol surface was built. + let export = surface_info.export.clone(); let issued_at_unix_ms = crate::time::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|_| ())? diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index 8576815a4..151512583 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -142,6 +142,70 @@ mod client_surface_parity_tests { .unwrap() } + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn protocol_surface_export_cache_is_engine_scoped_and_shared_by_engine_clones() { + let engine = Arc::new(protocol_engine("first-engine")); + let cloned = engine.clone(); + let another = protocol_engine("second-engine"); + let export = &engine.inner.protocol.as_ref().unwrap().roles["user"] + .surface + .export; + let cloned_export = &cloned.inner.protocol.as_ref().unwrap().roles["user"] + .surface + .export; + let other_export = &another.inner.protocol.as_ref().unwrap().roles["user"] + .surface + .export; + assert!(std::ptr::eq( + export.manifest_ref().unwrap(), + cloned_export.manifest_ref().unwrap() + )); + assert!(!std::ptr::eq( + export.manifest_ref().unwrap(), + other_export.manifest_ref().unwrap() + )); + let fresh = engine + .client_surface_for_role("user") + .unwrap() + .manifest() + .unwrap(); + assert_eq!(export.manifest_ref().unwrap(), &fresh); + assert_eq!(other_export.manifest_ref().unwrap(), &fresh); + } + + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn repeated_protocol_accumulators_reuse_metadata_but_release_request_authority() { + use crate::graphql::identity::VerifiedPrincipal; + let engine = protocol_engine("request-cache-test"); + let export = &engine.inner.protocol.as_ref().unwrap().roles["user"] + .surface + .export; + let owners = export.manifest_cache_owners(); + let mut session = Session::new(); + session.set("x-roles", "user"); + let request = Request::new("{ __typename }").data(VerifiedPrincipal::test_oidc( + "https://issuer.example", + "principal-a", + &["orders-service"], + )); + let authority = resolve_execution_authority(&engine.inner, &session, &request).unwrap(); + let first = engine + .protocol_accumulator(&authority, &session, &request) + .unwrap_or_else(|_| panic!("first request authority")) + .unwrap(); + assert_eq!(export.manifest_cache_owners(), owners + 1); + let second = engine + .protocol_accumulator(&authority, &session, &request) + .unwrap_or_else(|_| panic!("second request authority")) + .unwrap(); + assert_eq!(export.manifest_cache_owners(), owners + 2); + drop(first); + drop(second); + assert_eq!(export.manifest_cache_owners(), owners); + } + #[cfg(feature = "sqlite")] fn policy_protocol_engine(namespace: &str, claim_key: &str) -> GraphqlEngine { let pool = sqlx::sqlite::SqlitePoolOptions::new() diff --git a/src/graphql/projection_delta/runtime.rs b/src/graphql/projection_delta/runtime.rs index 8ab93c6bd..4d1f68eb3 100644 --- a/src/graphql/projection_delta/runtime.rs +++ b/src/graphql/projection_delta/runtime.rs @@ -105,9 +105,9 @@ impl ProtocolProjectionRequestSeed { return Err(ProjectionRuntimeAuthorityError::InvalidAuthority); } let manifest = export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; - let expected = crate::graphql::client_manifest::trusted_preset_descriptors(&manifest) + let expected = crate::graphql::client_manifest::trusted_preset_descriptors(manifest) .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; let mut preset_names = BTreeSet::new(); if trusted_presets.len() != expected.len() From 770ac48ba145a2bab9821b5dae8b4438e10a05f7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 21 Sep 2026 16:13:32 -0500 Subject: [PATCH 109/484] fix: recover snapshot streams behind retired page ownership Preserve pre-disposal frame fencing, then reopen only the blocked receiver beyond the retirement boundary. Keep unrelated layout subscriptions active. Refs Forge repository preparing incident; all403 JS tests and actual fresh repository live transition pass. --- docs/live-retired-owner-handoff.md | 21 +++++++++++++ js/src/replica/distributed-replica/impl.ts | 27 ++++++++++++----- js/src/replica/distributed-replica/types.ts | 1 + js/tests/replica-protocol.test.mjs | 33 +++++++++++++++++++-- 4 files changed, 73 insertions(+), 9 deletions(-) create mode 100644 docs/live-retired-owner-handoff.md diff --git a/docs/live-retired-owner-handoff.md b/docs/live-retired-owner-handoff.md new file mode 100644 index 000000000..f0c46f441 --- /dev/null +++ b/docs/live-retired-owner-handoff.md @@ -0,0 +1,21 @@ +# Snapshot stream handoff after owner disposal + +A snapshot live stream can begin while a previous route still owns a shared +relationship index. Its buffered frames must not acquire that graph merely +because the old route later disposes: their start fence predates disposal. +However, retaining that fence forever leaves the new route permanently pending. + +When an incoming snapshot is blocked by a retired owner's index, reopen that +contending operation at a fresh local start fence. Reject the triggering old +frame and all subsequent callbacks from its retired transport. Only a new +server-authorized initial frame may take over the graph. A still-active owner +continues to block; normal same-scope hydration must not restart retained layout +subscriptions. No application polling, forced refresh, or optimistic-state +suppression is part of this recovery. + +Runtime evidence: Forge's creation page received completed/ready rows, but the +prior NewRepository operation owned a shared topology relationship at revision +24, retired at 27, after the new subscription had already started. Entity clocks +advanced while the complete-empty root index remained fenced. The existing +pre-disposal protocol test covers safety; a fresh-receiver continuation covers +liveness after the same boundary. diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index a18077834..60c6ac38c 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -1614,6 +1614,12 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { if (source !== 'live' && sourceSwitched) { this.#restartLive(key); } + if (source === 'live' && sharedDisposition.restartAfterRetirement) { + // This receiver began before a shared owner retired. Its buffered + // frame stays fenced, but a fresh receiver starts after that boundary + // and can obtain an authoritative replacement without polling. + this.#restartLive(key); + } this.#trustedPresets = nextTrustedPresets; this.#protocolGeneration = nextProtocolGeneration; this.#resumeLiveWatches(); @@ -2327,6 +2333,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { let lower = false; let higher = false; let incomparable = false; + let restartAfterRetirement = false; let equalRevision: string | undefined; let latestOwnerRevision: string | undefined; for (const [key, group] of this.#operationProtocols) { @@ -2348,16 +2355,18 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { !snapshot.indexesComparable && state === group.live && state.retiredAtRevision !== undefined && - liveStart !== undefined && - compareCanonicalDecimalStrings( - liveStart, - state.retiredAtRevision - ) > 0 + liveStart !== undefined ) { // A disposed stream is no longer an owner. Its boundary is // still retained so a stream that started before disposal // cannot win merely because the old transport later closed. - continue; + if (compareCanonicalDecimalStrings(liveStart, state.retiredAtRevision) > 0) { + continue; + } + // Reopen at most once per observed retirement boundary: the + // replacement's allocated start is strictly newer. Active + // siblings never trigger this recovery and remain fenced. + restartAfterRetirement = true; } latestOwnerRevision = latestOwnerRevision === undefined || @@ -2429,7 +2438,11 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { * explicit synchronous ingress retains its caller-defined order. */ if (requestRevision === undefined && source === 'live') { - return { compared: true, disposition: 'lower' }; + return { + compared: true, + disposition: 'lower', + ...(restartAfterRetirement ? { restartAfterRetirement: true } : {}) + }; } if (requestRevision === undefined) return { compared: false }; return latestOwnerRevision !== undefined && diff --git a/js/src/replica/distributed-replica/types.ts b/js/src/replica/distributed-replica/types.ts index 4ae8faade..ebbcbefea 100644 --- a/js/src/replica/distributed-replica/types.ts +++ b/js/src/replica/distributed-replica/types.ts @@ -169,6 +169,7 @@ export type SharedIndexDisposition = { readonly compared: boolean; readonly disposition?: 'equal' | 'higher' | 'lower'; readonly indexRevision?: string; + readonly restartAfterRetirement?: boolean; }; export type CapturedReplicaOptimisticOperation = diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index 42095e281..7b4c374bd 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -2022,13 +2022,14 @@ test('snapshot live takes over a nested graph from a disposed page subscription' test('snapshot live keeps a stream started before disposal behind the retired owner', () => { const observers = []; + const closed = []; const previousPage = { ...FeaturedGamesWithOwner, live: { id: 'live:featured-owner-before-disposal', document: 'subscription FeaturedOwnerBeforeDisposal { featuredGames { id owner { id name } } }' } }; const replica = createDistributedReplica({ transport: { fetch() { throw new Error('complete snapshot must not force HTTP fallback'); }, - subscribe(_request, observer) { observers.push(observer); return () => {}; } + subscribe(_request, observer) { observers.push(observer); return () => { closed.push(observer); }; } } }); const oldFrame = (ownerName) => gamesFrame({ artifact: previousPage, responseKey: 'featuredGames', operation: previousPage.live.id, @@ -2052,6 +2053,9 @@ test('snapshot live keeps a stream started before disposal behind the retired ow live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(current.get().data.games, []); + const layout = replica.watch(Todos, {}, { live: true }); + observers[2].next(wireFrame({ operation: Todos.live.id, indexesComparable: false, + live: { mode: 'snapshot', reset: true }, rows: [{ id: 'retained', title: 'layout' }] })); oldWatch.destroy(); observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', @@ -2060,7 +2064,30 @@ test('snapshot live keeps a stream started before disposal behind the retired ow live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(current.get().data.games, []); + assert.equal(observers.length, 4, 'retired ownership must reopen only the contender after the disposal fence'); + assert.deepEqual(closed, [observers[0], observers[1]]); + assert.equal(layout.get().live, 'active'); + observers[1].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '5', + ownerId: 'user-1', ownerName: 'queued old receiver', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.deepEqual(current.get().data.games, [], 'old receiver stays fenced after reopening'); + observers[3].next(gamesFrame({ + artifact: GamesWithOwnerLiveOperation, responseKey: 'games', + operation: GamesWithOwnerLiveOperation.live.id, position: '6', + ownerId: 'user-1', ownerName: 'fresh authoritative receiver', indexesComparable: false, + live: { mode: 'snapshot', reset: true, cursors: [] } + })); + assert.equal(current.get().data.games[0].owner.name, 'fresh authoritative receiver'); + assert.equal(observers.length, 4, 'the same retirement boundary cannot reopen repeatedly'); + observers[2].next(wireFrame({ operation: Todos.live.id, indexesComparable: false, + live: { mode: 'snapshot', reset: true }, revision: '2', rows: [{ id: 'retained', title: 'continued layout' }] })); + assert.equal(layout.get().data.todos[0].title, 'continued layout'); current.destroy(); + layout.destroy(); + assert.deepEqual(closed, [observers[0], observers[1], observers[3], observers[2]]); }); test('reopening a retired live owner restores its ownership fence', () => { @@ -2195,6 +2222,7 @@ test('two watches retire shared live ownership only after final disposal', () => live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(startedBeforeFinalRelease.get().data.games, []); + assert.equal(observers.length, 3, 'the final release enables one fresh contender receiver'); startedBeforeFinalRelease.destroy(); const afterFinalRelease = replica.watch( @@ -2202,7 +2230,8 @@ test('two watches retire shared live ownership only after final disposal', () => {}, { live: true } ); - observers[2].next(gamesFrame({ + assert.equal(observers.length, 4, 'reopening after disposal creates another receiver'); + observers[3].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '5', ownerId: 'user-1', ownerName: 'after final release', indexesComparable: false, From 652d7b295281f55a304ec2208965a8eeb3aee280 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 21 Sep 2026 21:43:53 -0500 Subject: [PATCH 110/484] fix: retain event delivery during application reload --- docs/reloading-event-delivery.md | 13 +++++++++ src/bus/runner/tests.rs | 48 ++++++++++++++++++++++++++++++++ src/microsvc/error.rs | 21 ++++++++++++-- src/microsvc/http.rs | 1 + src/microsvc/service/runtime.rs | 10 ++----- src/telemetry.rs | 2 +- 6 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 docs/reloading-event-delivery.md diff --git a/docs/reloading-event-delivery.md b/docs/reloading-event-delivery.md new file mode 100644 index 000000000..0bd61ce9b --- /dev/null +++ b/docs/reloading-event-delivery.md @@ -0,0 +1,13 @@ +# Event delivery during application reload + +A supervisor generation gate is temporary infrastructure state, not a domain +rejection. Both direct command admission and bus dispatch return typed +`ApplicationReloading` while closed. Bus conversion classifies it as retryable +and retains/stops the receive loop: NAK the exact delivery, then surface the +error to the host's bounded restart policy. It must never Ack, Term or apply +ordinary permanent-failure policy. After activation the same delivery can run. + +Business validation/authorization failures retain their existing permanent +classification and configured settlement policy. No gate bypass or implicit +success is introduced. This does not change general infrastructure NAK delay; +hosts/brokers still own retry timing for other transport outages. diff --git a/src/bus/runner/tests.rs b/src/bus/runner/tests.rs index a31074c26..5319d8c0b 100644 --- a/src/bus/runner/tests.rs +++ b/src/bus/runner/tests.rs @@ -207,6 +207,54 @@ fn run_with( } // --- tests -------------------------------------------------------------- +#[test] +fn application_reload_retains_exact_delivery_then_succeeds_after_activation() { + use std::sync::atomic::{AtomicBool, Ordering}; + let recorder = Recorder::new(); + let open = Arc::new(AtomicBool::new(false)); + let gate = open.clone(); + let effects = recorder.clone(); + let router = Arc::new( + Handlers::new().on_event("reload", move |message: &Message| { + let admitted = gate.load(Ordering::SeqCst); + let effects = effects.clone(); + let id = message.id().unwrap().to_owned(); + async move { + if !admitted { + return Err(crate::microsvc::HandlerError::ApplicationReloading.into()); + } + effects.push(Event::Handled(id)); + Ok(()) + } + }), + ); + let message = event_message("reload", Some("retained-event")); + let source = || FakeSource { + queue: vec![message.clone()].into_iter().collect(), + recorder: recorder.clone(), + settle_ok: true, + recv_error: false, + decode_error: false, + }; + let error = block_on(run_source( + router.clone(), + source(), + RunOptions::idempotent(), + )) + .unwrap_err(); + assert!(error.is_retryable()); + assert!(error.should_retain_and_stop()); + assert!( + matches!(recorder.events().as_slice(), [Event::Nack(reason)] if reason.contains("reloading")) + ); + open.store(true, Ordering::SeqCst); + block_on(run_source(router, source(), RunOptions::idempotent())).unwrap(); + assert_eq!( + &recorder.events()[1..], + &[Event::Handled("retained-event".into()), Event::Ack] + ); +} + #[test] fn success_dispatches_then_acks_in_order() { let result = run(vec![event_message("ok", None)], RunOptions::idempotent()); diff --git a/src/microsvc/error.rs b/src/microsvc/error.rs index 437eb8e40..e52a2bb23 100644 --- a/src/microsvc/error.rs +++ b/src/microsvc/error.rs @@ -14,6 +14,9 @@ use crate::{repository::RepositoryError, EventRecordError}; #[derive(Debug)] #[non_exhaustive] pub enum HandlerError { + /// Supervisor generation admission is temporarily closed. Retain the exact + /// delivery and stop the receive loop until the host retries after reload. + ApplicationReloading, /// No handler registered for this command name. UnknownCommand(String), /// Payload decode / deserialization failed. @@ -51,6 +54,7 @@ pub enum HandlerError { impl fmt::Display for HandlerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + HandlerError::ApplicationReloading => f.write_str("application generation is reloading"), HandlerError::UnknownCommand(name) => write!(f, "unknown command: {}", name), HandlerError::DecodeFailed(msg) => write!(f, "decode failed: {}", msg), HandlerError::Rejected(msg) => write!(f, "rejected: {}", msg), @@ -142,6 +146,7 @@ impl HandlerError { /// Map this error to an HTTP-style status code. pub fn status_code(&self) -> u16 { match self { + HandlerError::ApplicationReloading => 503, HandlerError::UnknownCommand(_) => 404, HandlerError::DecodeFailed(_) => 400, HandlerError::Rejected(_) => 422, @@ -201,7 +206,8 @@ impl HandlerError { TransportErrorKind::Permanent } } - HandlerError::ProjectionRepairPending { .. } + HandlerError::ApplicationReloading + | HandlerError::ProjectionRepairPending { .. } | HandlerError::NotFound(_) | HandlerError::Other(_) => TransportErrorKind::Retryable, HandlerError::ProjectionTerminalRecorded { .. } @@ -228,7 +234,8 @@ impl From for TransportError { let kind = error.transport_error_kind(); let retain_and_stop = matches!( error, - HandlerError::ProjectionTerminalRecorded { .. } + HandlerError::ApplicationReloading + | HandlerError::ProjectionTerminalRecorded { .. } | HandlerError::ProjectionDeliveryHalted { .. } ); let transport = TransportError::new(kind, error.to_string()).with_source(error); @@ -244,6 +251,16 @@ impl From for TransportError { mod tests { use super::*; + #[test] + fn application_reloading_retains_delivery_without_reclassifying_business_errors() { + let reload = TransportError::from(HandlerError::ApplicationReloading); + assert!(reload.is_retryable()); + assert!(reload.should_retain_and_stop()); + let rejection = TransportError::from(HandlerError::Rejected("invalid slug".into())); + assert!(rejection.is_permanent()); + assert!(!rejection.should_retain_and_stop()); + } + #[test] fn transient_handler_errors_are_retryable() { for error in [ diff --git a/src/microsvc/http.rs b/src/microsvc/http.rs index e46fa56a2..b9835faa0 100644 --- a/src/microsvc/http.rs +++ b/src/microsvc/http.rs @@ -197,6 +197,7 @@ async fn command_handler( fn status_for_error(error: &HandlerError) -> StatusCode { match error { + HandlerError::ApplicationReloading => StatusCode::SERVICE_UNAVAILABLE, HandlerError::UnknownCommand(_) | HandlerError::NotFound(_) => StatusCode::NOT_FOUND, HandlerError::DecodeFailed(_) | HandlerError::GuardRejected(_) => StatusCode::BAD_REQUEST, HandlerError::Rejected(_) => StatusCode::UNPROCESSABLE_ENTITY, diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 688b5a46d..67afbf02b 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -40,9 +40,7 @@ fn ensure_lifecycle_mutations_open() -> Result<(), HandlerError> { if crate::microsvc::lifecycle_mutations_open() { Ok(()) } else { - Err(HandlerError::Rejected( - "application generation is reloading".into(), - )) + Err(HandlerError::ApplicationReloading) } } @@ -1064,11 +1062,7 @@ impl Service { message: &Message, ordered: Option<&OrderedDelivery>, ) -> Result { - if !crate::microsvc::lifecycle_mutations_open() { - return Err(HandlerError::Rejected( - "application generation is reloading".into(), - )); - } + ensure_lifecycle_mutations_open()?; if !self.handles_message(message.kind, &message.name) { return Err(HandlerError::UnknownCommand(message.name.clone())); } diff --git a/src/telemetry.rs b/src/telemetry.rs index e538ce152..2a318b932 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -162,7 +162,7 @@ pub(crate) fn handler_error_status(error: &HandlerError) -> &'static str { | HandlerError::ProjectionTerminalRecorded { .. } | HandlerError::ProjectionDeliveryHalted { .. } => dispatch_status::REPOSITORY_ERROR, HandlerError::GuardRejected(_) => dispatch_status::GUARD_REJECTED, - HandlerError::Other(_) => dispatch_status::OTHER_ERROR, + HandlerError::ApplicationReloading | HandlerError::Other(_) => dispatch_status::OTHER_ERROR, } } From 60eeba36b47f80ba947223f105d3e9bbf3fd6a3b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 28 Sep 2026 14:02:45 -0500 Subject: [PATCH 111/484] feat: retain authenticated external facts with source ordering --- docs/external-facts.md | 45 +++ migrations/inventory.json | 12 + .../0009_projection_delivery_aliases.sql | 15 + .../0009_projection_delivery_aliases.sql | 15 + src/bus/nats.rs | 308 ++++++++++++++++-- src/bus/nats_bus.rs | 6 +- src/domain_event/derived_tests.rs | 105 ++++++ src/domain_event/mod.rs | 2 +- src/domain_event/occurrence.rs | 133 +++++++- .../projection_protocol/state.rs | 1 + .../projection_protocol/state_impl.rs | 29 +- .../projection_protocol/store_impl.rs | 32 +- .../projection_protocol/tests.rs | 5 + src/lib.rs | 18 +- src/microsvc/projector/runtime.rs | 24 ++ src/outbox/message.rs | 8 +- src/projection/plan.rs | 8 + src/projection/program.rs | 16 + src/projection/source_snapshot_tests.rs | 6 +- src/projection_protocol/source_snapshot.rs | 23 +- src/projection_protocol/store/identity.rs | 2 + .../store/scenario_tests.rs | 179 ++++++++++ src/sqlx_repo/projection_protocol/identity.rs | 69 ++-- .../projection_protocol/postgres_tests.rs | 172 +++++++--- .../projection_protocol/store_impl.rs | 71 ++-- src/sqlx_repo/projection_protocol/tests.rs | 135 +++++--- src/sqlx_repo/projection_protocol/types.rs | 1 + src/sqlx_repo/projection_protocol/writes.rs | 33 +- src/sqlx_repo/repo/backend.rs | 18 +- tests/nats_transport/main.rs | 211 ++++++++++++ 30 files changed, 1499 insertions(+), 203 deletions(-) create mode 100644 docs/external-facts.md create mode 100644 migrations/postgres/0009_projection_delivery_aliases.sql create mode 100644 migrations/sqlite/0009_projection_delivery_aliases.sql diff --git a/docs/external-facts.md b/docs/external-facts.md new file mode 100644 index 000000000..5428c43f2 --- /dev/null +++ b/docs/external-facts.md @@ -0,0 +1,45 @@ +# Authenticated external facts + +`DomainEventOccurrence::capture_external` represents an authenticated fact from +an external ledger, webhook or other durable source. It does not create an +aggregate, command receipt or business authorization. The adapter must verify +the source before calling the typed constructor. Deserializing an occurrence +alone does not authenticate its origin. + +The source identity consists of producer, stream, numeric position and member +key. Members of one external transaction share its position, with distinct keys. +The logical occurrence ID depends only on that identity. Changing its descriptor, +body, timestamp or metadata preserves the ID and must fail the existing durable +input fingerprint fence. Retries must reproduce the same canonical bytes. When +the source has no timestamp, an adapter may explicitly use the Unix epoch as an +unknown-time sentinel; it must not present adapter receipt time as source time. + +An `external_snapshot` projection applies full-row source snapshots. It orders +each external stream/member independently of actual broker delivery positions; +it does not invent an aggregate sequence. Existing aggregate projection and +command APIs retain their authority and fencing rules. Derived external facts +retain their source provenance, but are not accepted as direct source snapshots. + +NATS publishes external facts with a content-bound broker dedup key and a +separate reserved logical occurrence ID header. Thus identical retries within +the broker dedup window collapse, but altered bytes reach durable validation. +Different logical source facts with identical bodies never collapse. Retained +archive reads verify these headers and preserve external occurrences for replay. +Malformed or ambiguous identity headers fail permanently before dispatch and +remain unacknowledged. The supervisor sees the error; the adapter does not +silently terminate the message or advance progress past it. + +An identical logical input redelivered at a new broker cursor advances only the +delivery checkpoint within its execution generation. It does not repeat row +changes, observations or business effects. A new execution generation applies +its first delivery normally. Original and alias cursor bindings remain immutable, +and one canonical topology-wide message identity arbitrates concurrent partition +claims. Migration 0009 adds delivery aliases without deleting canonical identity +or failure records. SQL mutation continues to use the existing partition lock. + +Permanent input identities and their aliases must be retained for the replay +and source-conflict horizon. A bounded broker dedup window is not such a fence. +An ingress that acknowledges an external cursor must first establish its own +required durable qualification (for example, a history projection atomically +committed with the protocol fingerprint), and retain source replay until then. +Publishing is not approval, and waiting for all UI consumers is unnecessary. diff --git a/migrations/inventory.json b/migrations/inventory.json index 25b8cc134..5a16b6163 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -96,6 +96,18 @@ "path": "migrations/postgres/0008_external_command_binding.sql", "sha256": "2f93c5685cde1d5cafd444d3a28dbcbf01f16cd44a566c7af61a7bd2a793a163" } + }, + { + "version": 9, + "description": "projection delivery aliases", + "sqlite": { + "path": "migrations/sqlite/0009_projection_delivery_aliases.sql", + "sha256": "b7fafebbe898fe7d05b6fb385eb6db4fd850fc9d314357bb91582fa5c00f38a4" + }, + "postgres": { + "path": "migrations/postgres/0009_projection_delivery_aliases.sql", + "sha256": "19845d4bfcb30d1bf43cb485a6bb9f765a6c1db7abf74fb004046457af83a2b9" + } } ] } diff --git a/migrations/postgres/0009_projection_delivery_aliases.sql b/migrations/postgres/0009_projection_delivery_aliases.sql new file mode 100644 index 000000000..2eee335d6 --- /dev/null +++ b/migrations/postgres/0009_projection_delivery_aliases.sql @@ -0,0 +1,15 @@ +-- Alternate broker delivery positions for an already immutable logical input. +-- Keep the canonical globally unique message binding and all historical rows. +CREATE TABLE projection_input_delivery_aliases ( + topology_hash bytea NOT NULL, + partition_hash bytea NOT NULL, + source_hash bytea NOT NULL, + source_partition_hash bytea NOT NULL, + source_epoch text NOT NULL, + source_position bigint NOT NULL CHECK (source_position >= 0), + message_id text NOT NULL, + PRIMARY KEY (topology_hash, partition_hash, source_hash, source_partition_hash, source_epoch, source_position), + FOREIGN KEY (topology_hash, message_id) + REFERENCES projection_input_identities (topology_hash, message_id) +); + diff --git a/migrations/sqlite/0009_projection_delivery_aliases.sql b/migrations/sqlite/0009_projection_delivery_aliases.sql new file mode 100644 index 000000000..c9f391bec --- /dev/null +++ b/migrations/sqlite/0009_projection_delivery_aliases.sql @@ -0,0 +1,15 @@ +-- Alternate broker delivery positions for an already immutable logical input. +-- Keep the canonical globally unique message binding and all historical rows. +CREATE TABLE projection_input_delivery_aliases ( + topology_hash BLOB NOT NULL, + partition_hash BLOB NOT NULL, + source_hash BLOB NOT NULL, + source_partition_hash BLOB NOT NULL, + source_epoch text NOT NULL, + source_position bigint NOT NULL CHECK (source_position >= 0), + message_id text NOT NULL, + PRIMARY KEY (topology_hash, partition_hash, source_hash, source_partition_hash, source_epoch, source_position), + FOREIGN KEY (topology_hash, message_id) + REFERENCES projection_input_identities (topology_hash, message_id) +); + diff --git a/src/bus/nats.rs b/src/bus/nats.rs index f18b72a30..814400344 100644 --- a/src/bus/nats.rs +++ b/src/bus/nats.rs @@ -4,8 +4,9 @@ //! to a subject (waiting for the JetStream publish ack — the durable publish //! threshold), and [`NatsJetStreamSource`] pulls from a durable consumer and //! settles via JetStream ack semantics (ack→`Ack`, nack→`Nak`, dead-letter/park→ -//! `Term`). The stable message id rides as the `Nats-Msg-Id` header so JetStream -//! dedup and downstream `Message.id` agree. +//! `Term`). Aggregate message IDs use `Nats-Msg-Id` unchanged. External facts +//! retain their logical source identity separately; their broker dedup ID also +//! binds content so altered retries reach the durable conflict fence. //! //! Requires the `nats` feature. Integration-tested in `tests/nats_transport` //! against a JetStream-enabled server (see `compose.yaml`). @@ -30,6 +31,148 @@ const MESSAGE_ID_HEADER: &str = "Nats-Msg-Id"; const MESSAGE_KIND_HEADER: &str = "X-Sourced-Kind"; /// Header carrying the canonical payload media type. const CONTENT_TYPE_HEADER: &str = "Content-Type"; +/// External occurrences separate immutable fact identity from broker dedup. +const LOGICAL_ID_HEADER: &str = "X-Distributed-Occurrence-Id"; + +fn external_dedup_id(payload: &[u8]) -> String { + use sha2::{Digest, Sha256}; + let mut digest = Sha256::new(); + digest.update(b"distributed.nats.external-occurrence.v1\0"); + // Canonical occurrence bytes include the immutable logical source identity. + digest.update(payload); + format!("external:sha256:{:x}", digest.finalize()) +} + +fn external_occurrence( + message: &Message, +) -> Result, TransportError> { + let Ok(event) = crate::DomainEventOccurrence::from_canonical_bytes(&message.payload) else { + return Ok(None); + }; + if event.external_source().is_none() { + return Ok(None); + } + if message.kind != super::MessageKind::Event + || message.id() != Some(event.id()) + || message.name() != event.descriptor().name + { + return Err(TransportError::permanent( + "external occurrence differs from transport identity", + )); + } + Ok(Some(event)) +} + +pub(super) fn archived_identity_matches( + event: &crate::DomainEventOccurrence, + payload: &[u8], + headers: &async_nats::HeaderMap, +) -> bool { + decode_headers( + event.descriptor().name.to_string(), + payload.to_vec(), + Some(headers), + ) + .is_ok_and(|message| { + message.kind == super::MessageKind::Event && message.id() == Some(event.id()) + }) +} + +fn unambiguous_identity_headers(headers: &async_nats::HeaderMap) -> bool { + [LOGICAL_ID_HEADER, MESSAGE_ID_HEADER, MESSAGE_KIND_HEADER] + .iter() + .all(|reserved| { + headers + .iter() + .filter(|(key, _)| key.to_string().eq_ignore_ascii_case(reserved)) + .map(|(_, values)| values.len()) + .sum::() + <= 1 + }) +} + +fn decode_headers( + name: String, + payload: Vec, + headers: Option<&async_nats::HeaderMap>, +) -> Result { + if headers.is_some_and(|headers| !unambiguous_identity_headers(headers)) { + return Err(TransportError::permanent( + "ambiguous occurrence identity header", + )); + } + let values: Vec<_> = headers + .into_iter() + .flat_map(|headers| headers.iter()) + .flat_map(|(key, values)| { + values + .iter() + .map(move |value| (key.to_string(), value.to_string())) + }) + .collect(); + // External publishers always emit the exact kind. Do not let the generic + // transport's permissive unknown-kind default turn poison into an event. + if crate::DomainEventOccurrence::from_canonical_bytes(&payload) + .is_ok_and(|event| event.external_source().is_some()) + && !values + .iter() + .any(|(key, value)| key.eq_ignore_ascii_case(MESSAGE_KIND_HEADER) && value == "event") + { + return Err(TransportError::permanent( + "external occurrence event kind is missing or invalid", + )); + } + let mut message = message_from_wire( + name, + payload, + Some(MESSAGE_ID_HEADER), + MESSAGE_KIND_HEADER, + values, + ); + take_content_type(&mut message); + restore_external_identity(&mut message)?; + Ok(message) +} + +fn restore_external_identity(message: &mut Message) -> Result<(), TransportError> { + let ids: Vec<_> = message + .metadata + .iter() + .filter(|(key, _)| key.eq_ignore_ascii_case(LOGICAL_ID_HEADER)) + .map(|(_, value)| value.clone()) + .collect(); + message + .metadata + .retain(|(key, _)| !key.eq_ignore_ascii_case(LOGICAL_ID_HEADER)); + if ids.is_empty() { + if crate::DomainEventOccurrence::from_canonical_bytes(&message.payload) + .is_ok_and(|event| event.external_source().is_some()) + { + return Err(TransportError::permanent( + "external occurrence logical identity is missing", + )); + } + return Ok(()); + } + if ids.len() != 1 || message.id() != Some(external_dedup_id(&message.payload).as_str()) { + return Err(TransportError::permanent( + "invalid external occurrence transport identity", + )); + } + let event = crate::DomainEventOccurrence::from_canonical_bytes(&message.payload) + .map_err(|_| TransportError::permanent("invalid external occurrence payload"))?; + if event.external_source().is_none() + || event.id() != ids[0] + || event.descriptor().name != message.name() + || message.kind != super::MessageKind::Event + { + return Err(TransportError::permanent( + "external occurrence differs from transport identity", + )); + } + message.id = Some(ids[0].clone()); + Ok(()) +} /// Publishes canonical messages to a NATS JetStream subject. /// @@ -78,15 +221,23 @@ impl MessagePublisher for NatsPublisher { let subject = self.subject(&message); let mut headers = async_nats::HeaderMap::new(); for (key, value) in &message.metadata { - if [MESSAGE_ID_HEADER, MESSAGE_KIND_HEADER, CONTENT_TYPE_HEADER] - .iter() - .any(|reserved| key.eq_ignore_ascii_case(reserved)) + if [ + MESSAGE_ID_HEADER, + MESSAGE_KIND_HEADER, + CONTENT_TYPE_HEADER, + LOGICAL_ID_HEADER, + ] + .iter() + .any(|reserved| key.eq_ignore_ascii_case(reserved)) { continue; } headers.insert(key.as_str(), value.as_str()); } - if let Some(id) = message.id() { + if let Some(event) = external_occurrence(&message)? { + headers.insert(MESSAGE_ID_HEADER, external_dedup_id(&message.payload)); + headers.insert(LOGICAL_ID_HEADER, event.id()); + } else if let Some(id) = message.id() { headers.insert(MESSAGE_ID_HEADER, id); } headers.insert(MESSAGE_KIND_HEADER, message.kind.as_str()); @@ -217,10 +368,11 @@ impl MessageSource for NatsJetStreamSource { match batch.next().await { Some(Ok(message)) => { - return Ok(Some(NatsReceived::from_jetstream( - message, - self.strip_prefix.as_deref(), - ))) + // Fail closed before dispatch without acknowledging or overriding + // the supervisor's permanent-error policy. The durable delivery is + // retained for operator repair; no later cursor is falsely sealed. + return NatsReceived::from_jetstream(message, self.strip_prefix.as_deref()) + .map(Some); } Some(Err(err)) => return Err(retryable("nats batch message", err)), None if self.idle_poll.is_zero() => return Ok(None), @@ -238,34 +390,19 @@ pub struct NatsReceived { } impl NatsReceived { - fn from_jetstream(raw: jetstream::Message, strip_prefix: Option<&str>) -> Self { + fn from_jetstream( + raw: jetstream::Message, + strip_prefix: Option<&str>, + ) -> Result { let name = strip_address_prefix(raw.subject.to_string(), strip_prefix); let payload = raw.payload.to_vec(); - let headers: Vec<(String, String)> = raw - .headers - .as_ref() - .into_iter() - .flat_map(|headers| headers.iter()) - .filter_map(|(key, values)| { - values - .last() - .map(|value| (key.to_string(), value.to_string())) - }) - .collect(); - let mut message = message_from_wire( - name, - payload, - Some(MESSAGE_ID_HEADER), - MESSAGE_KIND_HEADER, - headers, - ); - take_content_type(&mut message); + let message = decode_headers(name, payload, raw.headers.as_ref())?; let ordered = jetstream_ordered(&raw); - Self { + Ok(Self { raw, message, ordered, - } + }) } async fn settle(self, kind: AckKind) -> Result<(), TransportError> { @@ -344,6 +481,113 @@ mod tests { use super::*; use crate::bus::MessageKind; + #[derive(serde::Serialize, serde::Deserialize, crate::DomainEvent)] + #[domain_event(name = "external.balance_recorded", version = 1)] + struct Balance { + value: u64, + } + + fn external_message(position: u64, value: u64) -> Message { + let event = crate::DomainEventOccurrence::capture_external( + crate::ExternalEventSource { + producer: "ledger.adapter".into(), + stream: "account-one".into(), + position, + key: "balance".into(), + }, + std::time::UNIX_EPOCH, + Default::default(), + &Balance { value }, + ) + .unwrap(); + Message::new( + event.descriptor().name.to_string(), + MessageKind::Event, + event.canonical_bytes().unwrap(), + ) + .with_id(event.id()) + } + + #[test] + fn external_nats_identity_binds_logical_fact_and_content_without_changing_aggregate_ids() { + let first = external_message(1, 10); + let altered = external_message(1, 11); + let next = external_message(2, 10); + assert_eq!(first.id(), altered.id()); + assert_ne!( + external_dedup_id(&first.payload), + external_dedup_id(&altered.payload) + ); + assert_ne!( + external_dedup_id(&first.payload), + external_dedup_id(&next.payload) + ); + let mut wire = first.clone(); + wire.id = Some(external_dedup_id(&wire.payload)); + wire.metadata + .push((LOGICAL_ID_HEADER.into(), first.id().unwrap().into())); + restore_external_identity(&mut wire).unwrap(); + assert_eq!(wire.id, first.id); + assert_eq!(wire.payload, first.payload); + assert_eq!(wire.metadata, first.metadata); + let mut ordinary = Message::new("record.changed", MessageKind::Event, b"{}".to_vec()) + .with_id("aggregate-message"); + assert!(external_occurrence(&ordinary).unwrap().is_none()); + restore_external_identity(&mut ordinary).unwrap(); + assert_eq!(ordinary.id(), Some("aggregate-message")); + } + + #[test] + fn external_nats_forged_or_ambiguous_logical_headers_fail_closed() { + let first = external_message(1, 10); + for (logical, broker) in [ + ("forged".to_string(), external_dedup_id(&first.payload)), + (first.id().unwrap().to_string(), "forged-broker".to_string()), + ] { + let mut wire = first.clone(); + wire.id = Some(broker); + wire.metadata.push((LOGICAL_ID_HEADER.into(), logical)); + assert!(restore_external_identity(&mut wire).is_err()); + } + let mut repeated = first.clone(); + repeated.id = Some(external_dedup_id(&first.payload)); + repeated.metadata = vec![ + (LOGICAL_ID_HEADER.into(), first.id().unwrap().into()), + (LOGICAL_ID_HEADER.to_lowercase(), first.id().unwrap().into()), + ]; + assert!(restore_external_identity(&mut repeated).is_err()); + } + + #[test] + fn retained_archive_rejects_same_ambiguity_as_live_delivery() { + let message = external_message(1, 10); + let event = crate::DomainEventOccurrence::from_canonical_bytes(&message.payload).unwrap(); + let mut headers = async_nats::HeaderMap::new(); + headers.insert(MESSAGE_ID_HEADER, external_dedup_id(&message.payload)); + headers.insert(LOGICAL_ID_HEADER, event.id()); + headers.insert(MESSAGE_KIND_HEADER, "event"); + assert!(archived_identity_matches( + &event, + &message.payload, + &headers + )); + for name in [ + LOGICAL_ID_HEADER.to_string(), + LOGICAL_ID_HEADER.to_lowercase(), + MESSAGE_ID_HEADER.to_string(), + MESSAGE_ID_HEADER.to_lowercase(), + ] { + let mut forged = headers.clone(); + forged.append(name, "conflicting-extra-value"); + assert!(!unambiguous_identity_headers(&forged)); + assert!(!archived_identity_matches( + &event, + &message.payload, + &forged + )); + } + } + #[test] fn content_type_selection_removes_every_case_variant() { let mut message = Message::new("example.recorded", MessageKind::Event, Vec::new()) diff --git a/src/bus/nats_bus.rs b/src/bus/nats_bus.rs index 6f0a9feb3..2f37a08a3 100644 --- a/src/bus/nats_bus.rs +++ b/src/bus/nats_bus.rs @@ -290,7 +290,11 @@ impl NatsBus { TransportError::permanent(format!("invalid archived occurrence: {e}")) })?; if event.descriptor().name != name - || message.headers.get("Nats-Msg-Id").map(|v| v.as_str()) != Some(event.id()) + || !super::nats::archived_identity_matches( + &event, + &message.payload, + &message.headers, + ) { return Err(TransportError::permanent( "archived occurrence differs from its transport identity", diff --git a/src/domain_event/derived_tests.rs b/src/domain_event/derived_tests.rs index fd71e4bd7..b46a9e711 100644 --- a/src/domain_event/derived_tests.rs +++ b/src/domain_event/derived_tests.rs @@ -24,6 +24,111 @@ crate::projection! { on { events: [Indexed], mutation: SaveDerived, input: { row: body }, }, }; } +crate::projection! { + const EXTERNAL_ROWS: ProjectionDescriptor = { + name: "external-source-rows", version: 1, epoch: "external-v1", model: DerivedRows, + source: external_snapshot, + on { events: [Indexed], mutation: SaveDerived, input: { row: body }, }, + }; +} + +fn external(position: u64, bytes: u64) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + ExternalEventSource { + producer: "external.ledger".into(), + stream: "source:account".into(), + position, + key: "balance".into(), + }, + std::time::UNIX_EPOCH, + Default::default(), + &Indexed { bytes }, + ) + .unwrap() +} + +#[test] +fn external_occurrence_has_no_aggregate_and_stable_content_independent_identity() { + let first = external(7, 10); + let retry = external(7, 10); + let conflict = external(7, 11); + assert_eq!(first, retry); + assert_eq!(first.id(), conflict.id()); + assert_ne!( + first.canonical_bytes().unwrap(), + conflict.canonical_bytes().unwrap() + ); + assert_ne!(first.id(), external(8, 10).id()); + let wire = serde_json::to_value(&first).unwrap(); + assert!(wire.get("aggregate_type").is_none()); + assert!(wire.get("aggregate_id").is_none()); + assert!(wire.get("aggregate_sequence").is_none()); + assert_eq!( + DomainEventOccurrence::from_canonical_bytes(&first.canonical_bytes().unwrap()).unwrap(), + first + ); + let outbox = crate::OutboxMessage::from_domain_event_occurrence(&first).unwrap(); + assert_eq!(outbox.domain_event_occurrence().unwrap(), first); + let derived = first + .derive("indexer", "summary", &Indexed { bytes: 12 }) + .unwrap(); + assert_eq!(derived.external_source(), first.external_source()); + assert_eq!( + DomainEventOccurrence::from_canonical_bytes(&derived.canonical_bytes().unwrap()).unwrap(), + derived + ); +} + +#[test] +fn external_source_snapshots_fence_positions_conflicts_and_origin() { + use crate::projection_protocol::SourceSnapshotVersion as Version; + let first = external(7, 10); + let fence = Version::from_occurrence(&first).unwrap(); + assert!(!Version::from_occurrence(&external(6, 9)) + .unwrap() + .advances(&fence) + .unwrap()); + assert!(!Version::from_occurrence(&first) + .unwrap() + .advances(&fence) + .unwrap()); + assert!(Version::from_occurrence(&external(8, 11)) + .unwrap() + .advances(&fence) + .unwrap()); + assert!(Version::from_occurrence(&external(7, 11)) + .unwrap() + .advances(&fence) + .is_err()); + assert!(Version::from_occurrence(&source()) + .unwrap() + .advances(&fence) + .is_err()); + assert!(EXTERNAL_ROWS + .server_executor() + .unwrap() + .plan(&first) + .is_ok()); + assert!(EXTERNAL_ROWS + .server_executor() + .unwrap() + .plan(&source()) + .is_err()); + assert!(SNAPSHOT_ROWS + .server_executor() + .unwrap() + .plan(&first) + .is_err()); + assert!(DERIVED_ROWS.server_executor().unwrap().plan(&first).is_ok()); + let derived = first + .derive("indexer", "summary", &Indexed { bytes: 12 }) + .unwrap(); + assert!(EXTERNAL_ROWS + .server_executor() + .unwrap() + .plan(&derived) + .is_err()); +} #[derive(Serialize)] struct Indexed { diff --git a/src/domain_event/mod.rs b/src/domain_event/mod.rs index 0843f9e62..ccdb1bfd2 100644 --- a/src/domain_event/mod.rs +++ b/src/domain_event/mod.rs @@ -22,7 +22,7 @@ pub use descriptor::{ pub use occurrence::{ DomainEventCaptureError, DomainEventCaptureOutcome, DomainEventCapturePoison, DomainEventCommitGuardError, DomainEventDerivation, DomainEventEnvelope, DomainEventOccurrence, - DOMAIN_EVENT_OCCURRENCE_VERSION, + ExternalEventSource, DOMAIN_EVENT_OCCURRENCE_VERSION, }; pub(crate) use canonical::canonical_json_bytes; diff --git a/src/domain_event/occurrence.rs b/src/domain_event/occurrence.rs index 592bb11dd..15c52175a 100644 --- a/src/domain_event/occurrence.rs +++ b/src/domain_event/occurrence.rs @@ -22,6 +22,21 @@ use super::{ /// Version of the canonical [`DomainEventOccurrence`] envelope. pub const DOMAIN_EVENT_OCCURRENCE_VERSION: u16 = 1; +/// Provenance of a committed fact supplied by an authenticated source adapter. +/// This is not an aggregate identity or a claim that a domain command ran. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalEventSource { + /// Configured, authenticated producer identity (not a user input). + pub producer: String, + /// Immutable source/stream identity; replacing a source requires a new ID. + pub stream: String, + /// Source-owned position, never a broker delivery position. + pub position: u64, + /// Stable member identity within a source position, e.g. a ref in a push. + pub key: String, +} + /// Provenance of a typed fact produced while handling an earlier occurrence. /// The envelope's aggregate fields still describe the originating transition, /// not a new aggregate commit by this producer. @@ -56,6 +71,8 @@ pub struct DomainEventEnvelope { /// One exact typed outward event captured at aggregate transition time. #[derive(Clone, PartialEq, Eq, Serialize)] pub struct DomainEventOccurrence { + #[serde(skip_serializing_if = "Option::is_none")] + external: Option, #[serde(skip_serializing_if = "Option::is_none")] derivation: Option, /// Canonical occurrence envelope version. @@ -65,10 +82,13 @@ pub struct DomainEventOccurrence { /// Semantic event and body schema. descriptor: DomainEventDescriptor, /// Stable aggregate type name. + #[serde(skip_serializing_if = "String::is_empty")] aggregate_type: String, /// Stable aggregate stream identifier. + #[serde(skip_serializing_if = "String::is_empty")] aggregate_id: String, /// Aggregate event sequence that caused this occurrence. + #[serde(skip_serializing_if = "is_zero")] aggregate_sequence: u64, /// Zero-based publication position within one aggregate sequence. publication_ordinal: u32, @@ -129,6 +149,7 @@ impl DomainEventOccurrence { validate_stable_message_id(Some(&id)).map_err(DomainEventCaptureError::OccurrenceId)?; let occurrence = Self { + external: None, derivation: None, occurrence_version: DOMAIN_EVENT_OCCURRENCE_VERSION, id, @@ -145,6 +166,51 @@ impl DomainEventOccurrence { Ok(occurrence) } + /// Capture a typed external fact after the source adapter authenticates + /// its bytes and resolves trusted routing. This constructor validates + /// structure, not authentication: it must not be exposed as a user command. + /// The stable identity excludes payload bytes so persistent input evidence + /// can reject a changed payload at an existing source position/key. + pub fn capture_external( + source: ExternalEventSource, + occurred_at: SystemTime, + metadata: BTreeMap, + body: &T, + ) -> Result { + validate_external(&source)?; + let descriptor = T::DESCRIPTOR.clone(); + validate_descriptor(&descriptor)?; + if descriptor.body.kind != DomainEventBodyKind::Event { + return Err(DomainEventCaptureError::InvalidExternalSource); + } + let result = Self { + id: external_id(&source), + external: Some(source), + derivation: None, + occurrence_version: DOMAIN_EVENT_OCCURRENCE_VERSION, + descriptor, + aggregate_type: String::new(), + aggregate_id: String::new(), + aggregate_sequence: 0, + publication_ordinal: 0, + occurred_at_unix_ms: occurred_at + .duration_since(UNIX_EPOCH) + .map_err(|_| DomainEventCaptureError::TimestampBeforeUnixEpoch)? + .as_millis() + .try_into() + .map_err(|_| DomainEventCaptureError::TimestampOverflow)?, + body: canonical_json_bytes(body)?, + metadata, + }; + result.canonical_bytes()?; + Ok(result) + } + + /// Explicit external provenance, including for derived external facts. + pub fn external_source(&self) -> Option<&ExternalEventSource> { + self.external.as_ref() + } + /// Return the immutable canonical body bytes. pub fn body_bytes(&self) -> &[u8] { &self.body @@ -218,6 +284,9 @@ impl DomainEventOccurrence { } hash.update(self.aggregate_sequence.to_be_bytes()); hash.update(self.publication_ordinal.to_be_bytes()); + if let Some(source) = &self.external { + hash_component(&mut hash, &canonical_json_bytes(source)?); + } hash.update(self.occurred_at_unix_ms.to_be_bytes()); hash_component(&mut hash, &canonical_json_bytes(&self.descriptor)?); hash_component(&mut hash, &self.body); @@ -332,6 +401,7 @@ impl DomainEventOccurrence { let wire: DomainEventOccurrenceWire = serde_json::from_slice(bytes) .map_err(|error| DomainEventCaptureError::OccurrenceDecoding(error.to_string()))?; let occurrence = Self { + external: wire.external, derivation: wire.derivation, occurrence_version: wire.occurrence_version, id: wire.id, @@ -359,15 +429,27 @@ impl DomainEventOccurrence { }); } validate_descriptor(&self.descriptor)?; - validate_message_name(&self.aggregate_type) - .map_err(DomainEventCaptureError::AggregateType)?; - validate_stable_message_id(Some(&self.aggregate_id)) - .map_err(DomainEventCaptureError::AggregateId)?; + if let Some(source) = &self.external { + validate_external(source)?; + if !self.aggregate_type.is_empty() + || !self.aggregate_id.is_empty() + || self.aggregate_sequence != 0 + || self.publication_ordinal != 0 + || self.descriptor.body.kind != DomainEventBodyKind::Event + { + return Err(DomainEventCaptureError::InvalidExternalSource); + } + } else { + validate_message_name(&self.aggregate_type) + .map_err(DomainEventCaptureError::AggregateType)?; + validate_stable_message_id(Some(&self.aggregate_id)) + .map_err(DomainEventCaptureError::AggregateId)?; + if self.aggregate_sequence == 0 { + return Err(DomainEventCaptureError::ZeroAggregateSequence); + } + } validate_stable_message_id(Some(&self.id)) .map_err(DomainEventCaptureError::OccurrenceId)?; - if self.aggregate_sequence == 0 { - return Err(DomainEventCaptureError::ZeroAggregateSequence); - } if self.body.len() > MAX_DOMAIN_EVENT_BODY_BYTES { return Err(DomainEventCaptureError::BodyTooLarge { len: self.body.len(), @@ -388,6 +470,8 @@ impl DomainEventOccurrence { }; let expected_id = if self.derivation.is_some() { self.derived_identity()? + } else if let Some(source) = &self.external { + external_id(source) } else { occurrence_id(&self.descriptor, &envelope) }; @@ -407,13 +491,18 @@ impl DomainEventOccurrence { #[derive(Deserialize)] struct DomainEventOccurrenceWire { + #[serde(default)] + external: Option, #[serde(default)] derivation: Option, occurrence_version: u16, id: String, descriptor: DomainEventDescriptor, + #[serde(default)] aggregate_type: String, + #[serde(default)] aggregate_id: String, + #[serde(default)] aggregate_sequence: u64, publication_ordinal: u32, occurred_at_unix_ms: u64, @@ -422,6 +511,33 @@ struct DomainEventOccurrenceWire { metadata: BTreeMap, } +fn is_zero(value: &u64) -> bool { + *value == 0 +} + +fn validate_external(source: &ExternalEventSource) -> Result<(), DomainEventCaptureError> { + if validate_message_name(&source.producer).is_err() + || validate_stable_message_id(Some(&source.stream)).is_err() + || source.position == 0 + || source.key.is_empty() + || source.key.len() > 1024 + || source.key.chars().any(char::is_control) + { + return Err(DomainEventCaptureError::InvalidExternalSource); + } + Ok(()) +} + +fn external_id(source: &ExternalEventSource) -> String { + let mut digest = Sha256::new(); + digest.update(b"distributed.external-event.occurrence/v1\0"); + for value in [&source.producer, &source.stream, &source.key] { + hash_component(&mut digest, value.as_bytes()); + } + digest.update(source.position.to_be_bytes()); + format!("ee1:sha256:{:x}", digest.finalize()) +} + fn occurrence_id(descriptor: &DomainEventDescriptor, envelope: &DomainEventEnvelope) -> String { let mut digest = Sha256::new(); digest.update(b"distributed.domain-event.occurrence/v1\0"); @@ -489,6 +605,8 @@ fn validate_fingerprint(fingerprint: &str) -> Result<(), DomainEventCaptureError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum DomainEventCaptureError { + /// Invalid external provenance or mixed aggregate/external envelope. + InvalidExternalSource, /// Derived provenance has an invalid producer, output key or source identity. InvalidDerivation, /// Semantic event name violated transport naming rules. @@ -569,6 +687,7 @@ pub enum DomainEventCaptureError { impl fmt::Display for DomainEventCaptureError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::InvalidExternalSource => formatter.write_str("invalid external-event source"), Self::InvalidDerivation => formatter.write_str("invalid domain-event derivation"), Self::EventName(error) => write!(formatter, "invalid domain-event name: {error}"), Self::AggregateType(error) => write!(formatter, "invalid aggregate type: {error}"), diff --git a/src/in_memory_repo/projection_protocol/state.rs b/src/in_memory_repo/projection_protocol/state.rs index 2ce23b504..4050b536f 100644 --- a/src/in_memory_repo/projection_protocol/state.rs +++ b/src/in_memory_repo/projection_protocol/state.rs @@ -289,6 +289,7 @@ pub(in crate::in_memory_repo) fn reject_causal_owned_plans( pub(super) enum InputDisposition { New, + Redelivery, Duplicate(ProjectionCheckpoint), Stale(ProjectionCheckpoint), } diff --git a/src/in_memory_repo/projection_protocol/state_impl.rs b/src/in_memory_repo/projection_protocol/state_impl.rs index 383e80464..2b8098235 100644 --- a/src/in_memory_repo/projection_protocol/state_impl.rs +++ b/src/in_memory_repo/projection_protocol/state_impl.rs @@ -236,6 +236,21 @@ impl InMemoryProjectionProtocolState { gap_free, }; self.validate_input_identity(&candidate)?; + let repeated_effect = self + .messages + .get(&MessageKey { + topology: cursor.topology().clone(), + message_id: message_id.to_string(), + }) + .is_some_and(|identity| { + self.applied_receipts + .contains_key(&CursorReceiptKey::new(&identity.cursor, generation)) + || self.applied_receipts.iter().any(|(key, receipt)| { + key.generation == generation + && key.partition == PartitionKey::from_input(cursor) + && receipt.message_id == message_id + }) + }); if let Some(receipt) = self .applied_receipts .get(&CursorReceiptKey::new(cursor, generation)) @@ -252,7 +267,11 @@ impl InMemoryProjectionProtocolState { let input_key = InputKey::new(cursor, generation); let Some(previous) = self.inputs.get(&input_key) else { self.reject_reused_message(cursor, fingerprint, message_id, causation_id, gap_free)?; - return Ok(InputDisposition::New); + return Ok(if repeated_effect { + InputDisposition::Redelivery + } else { + InputDisposition::New + }); }; match cursor.compare_position(&previous.cursor) { @@ -292,7 +311,11 @@ impl InMemoryProjectionProtocolState { { return Err(ProjectionProtocolError::IncomparableInput); } - Ok(InputDisposition::New) + Ok(if repeated_effect { + InputDisposition::Redelivery + } else { + InputDisposition::New + }) } } } @@ -310,7 +333,7 @@ impl InMemoryProjectionProtocolState { message_id: message_id.to_string(), }; if let Some(previous) = self.messages.get(&key) { - if previous.cursor != *cursor + if previous.cursor.compare_position(cursor) == RevisionComparison::Incomparable || previous.fingerprint != fingerprint || previous.causation_id != causation_id || previous.gap_free != gap_free diff --git a/src/in_memory_repo/projection_protocol/store_impl.rs b/src/in_memory_repo/projection_protocol/store_impl.rs index be530e460..f7e92882c 100644 --- a/src/in_memory_repo/projection_protocol/store_impl.rs +++ b/src/in_memory_repo/projection_protocol/store_impl.rs @@ -104,7 +104,7 @@ impl ProjectionProtocolStore for InMemoryRepository { fn commit_projection( &self, - batch: ProjectionCommitBatch, + mut batch: ProjectionCommitBatch, ) -> impl Future> + Send + '_ { async move { @@ -129,7 +129,7 @@ impl ProjectionProtocolStore for InMemoryRepository { .map_err(|_| RepositoryError::LockPoisoned("projection inbox write"))?; protocol.validate_partition(&partition_key, &batch.input, &batch.change_epoch)?; - match protocol.classify_input( + let redelivery = match protocol.classify_input( &batch.input.cursor, batch.input.fingerprint, &batch.input.message_id, @@ -151,12 +151,21 @@ impl ProjectionProtocolStore for InMemoryRepository { } InputDisposition::New => { protocol.validate_pending_retry(&partition_key, &batch.input)?; + false } - } + InputDisposition::Redelivery => { + protocol.validate_pending_retry(&partition_key, &batch.input)?; + batch.mutations.clear(); + batch.observations.clear(); + true + } + }; let receipt = batch.input.inbox_receipt(); receipt.validate()?; - if inbox.contains(&(receipt.consumer.clone(), receipt.message_id.clone())) { + if !redelivery + && inbox.contains(&(receipt.consumer.clone(), receipt.message_id.clone())) + { return Err(ProjectionProtocolError::MessageIdReuse { message_id: batch.input.message_id.clone(), }); @@ -413,7 +422,11 @@ impl ProjectionProtocolStore for InMemoryRepository { *inbox = staged_inbox; Ok(ProjectionCommitResult { - outcome: ProjectionCommitOutcome::Applied, + outcome: if redelivery { + ProjectionCommitOutcome::Duplicate + } else { + ProjectionCommitOutcome::Applied + }, checkpoint: Some(checkpoint), records, changes, @@ -496,6 +509,11 @@ impl ProjectionProtocolStore for InMemoryRepository { InputDisposition::New => { protocol.validate_pending_retry(&partition_key, &batch.input)?; } + InputDisposition::Redelivery => { + return Err(ProjectionProtocolError::InvalidBatch( + "an already applied message cannot record a new failure".into(), + )) + } InputDisposition::Duplicate(_) | InputDisposition::Stale(_) => { return Err(ProjectionProtocolError::InvalidBatch( "cannot record terminal failure for an already processed input".into(), @@ -677,6 +695,10 @@ impl ProjectionProtocolStore for InMemoryRepository { protocol.validate_pending_retry(&partition_key, input)?; Ok(ProjectionInputDisposition::Pending) } + InputDisposition::Redelivery => { + protocol.validate_pending_retry(&partition_key, input)?; + Ok(ProjectionInputDisposition::Redelivery) + } } } } diff --git a/src/in_memory_repo/projection_protocol/tests.rs b/src/in_memory_repo/projection_protocol/tests.rs index 017549216..83ed88c49 100644 --- a/src/in_memory_repo/projection_protocol/tests.rs +++ b/src/in_memory_repo/projection_protocol/tests.rs @@ -2314,6 +2314,11 @@ async fn input_disposition_is_read_only_exact_and_repair_fenced() { .await; } +#[tokio::test] +async fn identical_redelivery_advances_only_broker_checkpoint() { + crate::projection_protocol::scenario_tests::identical_redelivery_advances_only_broker_checkpoint(ProjectionScenario).await; +} + #[tokio::test] async fn repair_generation_retries_only_the_exact_failed_input() { let repository = repository().await; diff --git a/src/lib.rs b/src/lib.rs index c84cc9b8a..2af2b194b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -79,16 +79,16 @@ pub use application::{ MountSelector, ProcessIntent, ProcessPreset, ProjectionSpec, Runtime, RuntimeDialect, SurfaceSpec, APPLICATION_MANIFEST_SCHEMA_VERSION, DEPLOYMENT_PLAN_SCHEMA_VERSION, }; -pub use command_dispatch::{ - CommandDispatchEnvelope, CommandDispatchError, CommandDispatchReceipt, CommandDispatcher, - LocalCommandDispatcher, RemoteCommandDispatcher, RemoteDispatchConfig, RemoteTrustMode, - SharedCommandDispatcher, APPROVED_REMOTE_DISPATCH_PROFILE, COMMAND_DISPATCH_ENVELOPE_VERSION, -}; #[cfg(feature = "graphql")] pub use command_dispatch::{ CellRequestContext, CommandHost, HttpCommandHost, LocalCommandHost, SharedCommandHost, TrustedRequestMetadata, }; +pub use command_dispatch::{ + CommandDispatchEnvelope, CommandDispatchError, CommandDispatchReceipt, CommandDispatcher, + LocalCommandDispatcher, RemoteCommandDispatcher, RemoteDispatchConfig, RemoteTrustMode, + SharedCommandDispatcher, APPROVED_REMOTE_DISPATCH_PROFILE, COMMAND_DISPATCH_ENVELOPE_VERSION, +}; // Domain events: typed outward contracts distinct from replay events/snapshots. pub use domain_event::{ @@ -96,8 +96,9 @@ pub use domain_event::{ DomainEventBodyKind, DomainEventCaptureError, DomainEventCaptureOutcome, DomainEventCapturePoison, DomainEventCommitGuardError, DomainEventDescriptor, DomainEventEnvelope, DomainEventOccurrence, DomainState, DomainStateDescriptor, - DOMAIN_EVENT_BODY_CODEC, DOMAIN_EVENT_BODY_CODEC_VERSION, DOMAIN_EVENT_OCCURRENCE_VERSION, - MAX_DOMAIN_EVENT_BODY_BYTES, MAX_DOMAIN_EVENT_OCCURRENCE_WIRE_BYTES, + ExternalEventSource, DOMAIN_EVENT_BODY_CODEC, DOMAIN_EVENT_BODY_CODEC_VERSION, + DOMAIN_EVENT_OCCURRENCE_VERSION, MAX_DOMAIN_EVENT_BODY_BYTES, + MAX_DOMAIN_EVENT_OCCURRENCE_WIRE_BYTES, }; // Logical projection contracts. Physical read-model lowering deliberately lives @@ -316,6 +317,9 @@ macro_rules! __projection_source_policy { ($program:expr, aggregate_snapshot) => { $program.with_source_snapshots() }; + ($program:expr, external_snapshot) => { + $program.with_external_source_snapshots() + }; } /// Map `input: { key: body | aggregate_id }` keywords for [`projection!`]. diff --git a/src/microsvc/projector/runtime.rs b/src/microsvc/projector/runtime.rs index 26b391241..f776540ed 100644 --- a/src/microsvc/projector/runtime.rs +++ b/src/microsvc/projector/runtime.rs @@ -292,6 +292,18 @@ where )?; match store.projection_input_disposition(&trusted).await? { ProjectionInputDisposition::Pending => {} + ProjectionInputDisposition::Redelivery => { + store + .commit_projection(crate::projection_protocol::ProjectionCommitBatch { + input: trusted, + change_epoch: self.change_epoch.clone(), + ownership: self.compiled.ownership().to_vec(), + mutations: Vec::new(), + observations: Vec::new(), + }) + .await?; + return Ok(()); + } ProjectionInputDisposition::Duplicate(_) | ProjectionInputDisposition::Stale(_) => { return Ok(()) } @@ -568,6 +580,18 @@ where )?; match store.projection_input_disposition(&trusted).await? { ProjectionInputDisposition::Pending => {} + ProjectionInputDisposition::Redelivery => { + store + .commit_projection(crate::projection_protocol::ProjectionCommitBatch { + input: trusted, + change_epoch: self.change_epoch.clone(), + ownership: self.compiled.ownership().to_vec(), + mutations: Vec::new(), + observations: Vec::new(), + }) + .await?; + return Ok(()); + } ProjectionInputDisposition::Duplicate(_) | ProjectionInputDisposition::Stale(_) => { return Ok(()) } diff --git a/src/outbox/message.rs b/src/outbox/message.rs index c14e1bf6f..2b5cb5e0b 100644 --- a/src/outbox/message.rs +++ b/src/outbox/message.rs @@ -297,9 +297,11 @@ impl OutboxMessage { ), ) .map_err(|error| DomainEventCaptureError::BodyEncoding(error.to_string()))?; - message.source_aggregate_type = Some(occurrence.aggregate_type().to_string()); - message.source_aggregate_id = Some(occurrence.aggregate_id().to_string()); - message.source_sequence = Some(occurrence.aggregate_sequence()); + if occurrence.external_source().is_none() { + message.source_aggregate_type = Some(occurrence.aggregate_type().to_string()); + message.source_aggregate_id = Some(occurrence.aggregate_id().to_string()); + message.source_sequence = Some(occurrence.aggregate_sequence()); + } Ok(message) } diff --git a/src/projection/plan.rs b/src/projection/plan.rs index 82b704ece..478607503 100644 --- a/src/projection/plan.rs +++ b/src/projection/plan.rs @@ -390,6 +390,14 @@ impl ResolvedProjectionPlan { if program.source_snapshots() && occurrence.derivation().is_some() { return Err(ProjectionProgramError::DerivedSourceSnapshot); } + if program.source_snapshots() + && program.external_source_snapshots() != occurrence.external_source().is_some() + { + return Err(ProjectionProgramError::InvalidOperation { + operation: program.name().into(), + reason: "snapshot origin does not match the declared source policy".into(), + }); + } let matches = program .arms() .iter() diff --git a/src/projection/program.rs b/src/projection/program.rs index 23dd83e53..67c9ffef3 100644 --- a/src/projection/program.rs +++ b/src/projection/program.rs @@ -645,6 +645,8 @@ pub struct ProjectionProgram { arms: Vec, #[serde(skip_serializing_if = "std::ops::Not::not")] source_snapshots: bool, + #[serde(skip_serializing_if = "std::ops::Not::not")] + external_source_snapshots: bool, } impl ProjectionProgram { @@ -694,6 +696,7 @@ impl ProjectionProgram { partition, arms, source_snapshots: false, + external_source_snapshots: false, }) } @@ -726,6 +729,19 @@ impl ProjectionProgram { self.source_snapshots } + /// Fence complete external snapshots by the authenticated source position. + /// Aggregate and external snapshot programs reject each other's origins. + pub fn with_external_source_snapshots(self) -> Result { + let mut program = self.with_source_snapshots()?; + program.external_source_snapshots = true; + Ok(program) + } + + /// Whether snapshots require external source provenance rather than an aggregate. + pub fn external_source_snapshots(&self) -> bool { + self.external_source_snapshots + } + /// Return the stable program name. pub fn name(&self) -> &str { &self.name diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs index 44de952c4..2a388b370 100644 --- a/src/projection/source_snapshot_tests.rs +++ b/src/projection/source_snapshot_tests.rs @@ -589,7 +589,11 @@ async fn rebuild_matrix(store: &impl ProjectionProtocolStore) { h.apply(store, &first, 1).await.unwrap().outcome, ProjectionCommitOutcome::Duplicate ); - h.apply(store, &first, 2).await.unwrap_err(); // same message, different position is still rejected + let replayed = h.apply(store, &first, 2).await.unwrap(); + assert_eq!(replayed.outcome, ProjectionCommitOutcome::Duplicate); + assert_eq!(replayed.checkpoint.unwrap().input().position(), 2); + assert_eq!(replayed.changes.len(), 1); + assert_eq!(replayed.changes[0].kind, ProjectionChangeKind::Checkpoint); h.apply(store, &removed, 3).await.unwrap(); // Exact inventory CAS rejects modifications made after begin, including inserts. diff --git a/src/projection_protocol/source_snapshot.rs b/src/projection_protocol/source_snapshot.rs index fdf8d6542..ecf624496 100644 --- a/src/projection_protocol/source_snapshot.rs +++ b/src/projection_protocol/source_snapshot.rs @@ -12,6 +12,8 @@ use sha2::{Digest, Sha256}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SourceSnapshotVersion { + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + external: bool, aggregate_type: String, aggregate_id: String, sequence: u64, @@ -46,7 +48,25 @@ impl SourceSnapshotVersion { let canonical = event .canonical_bytes() .map_err(|error| ProjectionProtocolError::InvalidBatch(error.to_string()))?; + if let Some(source) = event.external_source() { + let mut stream = Sha256::new(); + stream.update(b"distributed.external-source-snapshot.v1\0"); + for part in [&source.stream, &source.key] { + stream.update((part.len() as u64).to_be_bytes()); + stream.update(part.as_bytes()); + } + return Ok(Self { + external: true, + aggregate_type: source.producer.clone(), + aggregate_id: format!("external:{:x}", stream.finalize()), + sequence: source.position, + publication_ordinal: 0, + occurrence_id: event.id().into(), + occurrence_fingerprint: Sha256::digest(canonical).into(), + }); + } Ok(Self { + external: false, aggregate_type: event.aggregate_type().into(), aggregate_id: event.aggregate_id().into(), sequence: event.aggregate_sequence(), @@ -58,7 +78,8 @@ impl SourceSnapshotVersion { /// True only when this occurrence advances the same authoritative stream. pub(crate) fn advances(&self, current: &Self) -> Result { - if self.aggregate_type != current.aggregate_type + if self.external != current.external + || self.aggregate_type != current.aggregate_type || self.aggregate_id != current.aggregate_id { return Err(ProjectionProtocolError::InvalidBatch( diff --git a/src/projection_protocol/store/identity.rs b/src/projection_protocol/store/identity.rs index 4f2aef328..2716acb2d 100644 --- a/src/projection_protocol/store/identity.rs +++ b/src/projection_protocol/store/identity.rs @@ -182,6 +182,8 @@ impl TrustedProjectionInput { #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum ProjectionInputDisposition { Pending, + /// Identical logical input at a new adapter-authenticated broker position. + Redelivery, Duplicate(ProjectionCheckpoint), Stale(ProjectionCheckpoint), } diff --git a/src/projection_protocol/store/scenario_tests.rs b/src/projection_protocol/store/scenario_tests.rs index 251254c15..22fa5dbe8 100644 --- a/src/projection_protocol/store/scenario_tests.rs +++ b/src/projection_protocol/store/scenario_tests.rs @@ -266,6 +266,185 @@ pub(crate) async fn input_disposition_is_read_only_exact_and_repair_fenced( ); } +pub(crate) async fn identical_redelivery_advances_only_broker_checkpoint( + scenario: impl ProjectionProtocolScenario, +) { + let store = scenario.repository().await; + let first = scenario.input( + 1, + b"immutable-input", + "message-repeat", + "cause-repeat", + ProjectionGeneration::initial(), + ); + let mutation = scenario.mutation( + ProjectionRecordExpectation::Missing, + ProjectionMutationKind::Upsert, + ); + let scope = mutation.scope.clone(); + store + .commit_projection(scenario.batch(first.clone(), vec![mutation], Vec::new())) + .await + .unwrap(); + let original = store.projection_record(&scope).await.unwrap().unwrap(); + let repeat = scenario.input( + 2, + b"immutable-input", + "message-repeat", + "cause-repeat", + ProjectionGeneration::initial(), + ); + assert_eq!( + store.projection_input_disposition(&repeat).await.unwrap(), + ProjectionInputDisposition::Redelivery + ); + // Even a caller that supplies effects again cannot repeat them. + let repeated = store + .commit_projection(scenario.batch( + repeat.clone(), + vec![scenario.mutation( + ProjectionRecordExpectation::Missing, + ProjectionMutationKind::Upsert, + )], + Vec::new(), + )) + .await + .unwrap(); + assert_eq!(repeated.outcome, ProjectionCommitOutcome::Duplicate); + assert_eq!(repeated.checkpoint.unwrap().input().position(), 2); + assert_eq!(repeated.changes.len(), 1); + assert_eq!(repeated.changes[0].kind, ProjectionChangeKind::Checkpoint); + assert_eq!( + store.projection_record(&scope).await.unwrap().unwrap(), + original + ); + assert!(matches!( + store.projection_input_disposition(&repeat).await.unwrap(), + ProjectionInputDisposition::Duplicate(_) + )); + let next = scenario.input( + 3, + b"next-input", + "message-next", + "cause-next", + ProjectionGeneration::initial(), + ); + store + .commit_projection(scenario.batch(next, Vec::new(), Vec::new())) + .await + .unwrap(); + // Every alias position permanently retains the original bytes and identity. + let substitution = scenario.input( + 2, + b"immutable-input", + "substituted-message", + "cause-repeat", + ProjectionGeneration::initial(), + ); + assert!(matches!( + store.projection_input_disposition(&substitution).await, + Err(ProjectionProtocolError::InputCorruption) + )); + let altered = scenario.input( + 4, + b"changed-input", + "message-repeat", + "cause-repeat", + ProjectionGeneration::initial(), + ); + assert!(store.projection_input_disposition(&altered).await.is_err()); + let other_partition = scenario.input_for_partition( + ProjectionPartition::new(b"other-partition".to_vec()).unwrap(), + 1, + b"immutable-input", + "message-repeat", + "cause-repeat", + ); + assert!(matches!( + store.projection_input_disposition(&other_partition).await, + Err(ProjectionProtocolError::MessageIdReuse { .. }) + )); + + // A repaired generation owns a fresh execution history. An old-generation + // receipt must not suppress that generation's first actual delivery. + let failed = scenario.input( + 4, + b"repair-input", + "repair-message", + "repair-cause", + ProjectionGeneration::initial(), + ); + store + .record_projection_failure( + ProjectionFailureBatch::new( + failed, + scenario.change_epoch(), + "repair-redelivery", + "fixture", + b"failure".to_vec(), + ) + .unwrap(), + ) + .await + .unwrap(); + let generation = store + .repair_projection( + &scenario.topology(), + &scenario.partition(), + "repair-redelivery", + ) + .await + .unwrap(); + store + .commit_projection(scenario.batch( + scenario.input( + 4, + b"repair-input", + "repair-message", + "repair-cause", + generation, + ), + Vec::new(), + Vec::new(), + )) + .await + .unwrap(); + let replay = scenario.input( + 5, + b"immutable-input", + "message-repeat", + "cause-repeat", + generation, + ); + assert_eq!( + store.projection_input_disposition(&replay).await.unwrap(), + ProjectionInputDisposition::Pending + ); + let applied = store + .commit_projection(scenario.batch( + replay, + vec![scenario.mutation( + ProjectionRecordExpectation::Exact(original.revision), + ProjectionMutationKind::Upsert, + )], + Vec::new(), + )) + .await + .unwrap(); + assert_eq!(applied.outcome, ProjectionCommitOutcome::Applied); + let repeated = scenario.input( + 6, + b"immutable-input", + "message-repeat", + "cause-repeat", + generation, + ); + assert_eq!( + store.projection_input_disposition(&repeated).await.unwrap(), + ProjectionInputDisposition::Redelivery + ); +} + pub(crate) async fn message_identity_is_topology_wide_across_projection_partitions( scenario: impl ProjectionProtocolScenario, ) { diff --git a/src/sqlx_repo/projection_protocol/identity.rs b/src/sqlx_repo/projection_protocol/identity.rs index 402929790..dbddd84bb 100644 --- a/src/sqlx_repo/projection_protocol/identity.rs +++ b/src/sqlx_repo/projection_protocol/identity.rs @@ -278,6 +278,14 @@ where pub(super) fn input_identity_cursor_matches( identity: &StoredInputIdentity, input: &TrustedProjectionInput, +) -> bool { + input_identity_scope_matches(identity, input) + && identity.source_position == input.cursor.position() +} + +fn input_identity_scope_matches( + identity: &StoredInputIdentity, + input: &TrustedProjectionInput, ) -> bool { let source = input.cursor.source(); identity.partition_bytes == input.cursor.projection_partition().canonical_bytes() @@ -287,7 +295,6 @@ pub(super) fn input_identity_cursor_matches( && identity.source_partition_bytes == source.canonical_partition_bytes() && identity.source_partition_hash == digest_bytes(source.partition_digest()) && identity.source_epoch == *input.cursor.epoch() - && identity.source_position == input.cursor.position() } pub(super) fn input_identity_matches( @@ -325,7 +332,14 @@ where identity.source_hash, identity.source_partition_bytes, identity.source_partition_hash, \ identity.source_epoch, identity.source_position, identity.input_hash, \ identity.message_id, identity.causation_id, identity.gap_free \ - FROM projection_input_identities identity JOIN projection_partitions partition \ + FROM (SELECT * FROM projection_input_identities UNION ALL \ + SELECT canonical.topology_hash, alias.partition_hash, canonical.source_bytes, \ + alias.source_hash, canonical.source_partition_bytes, alias.source_partition_hash, \ + alias.source_epoch, alias.source_position, canonical.input_hash, canonical.message_id, \ + canonical.causation_id, canonical.gap_free \ + FROM projection_input_delivery_aliases alias JOIN projection_input_identities canonical \ + ON canonical.topology_hash = alias.topology_hash AND canonical.message_id = alias.message_id) identity \ + JOIN projection_partitions partition \ ON partition.topology_hash = identity.topology_hash \ AND partition.partition_hash = identity.partition_hash \ WHERE identity.topology_hash = ", @@ -857,15 +871,20 @@ where } } if let Some(identity) = input_identity_by_message_in_tx(tx, input).await? { - if !input_identity_cursor_matches(&identity, input) { + if !input_identity_scope_matches(&identity, input) { return Err(ProjectionProtocolError::MessageIdReuse { message_id: input.message_id.clone(), }); } - if !input_identity_matches(&identity, input) { - return Err(ProjectionProtocolError::InputCorruption); + if identity.input_fingerprint != input.fingerprint + || identity.causation_id != input.causation_id + || identity.gap_free != input.gap_free + { + return Err(ProjectionProtocolError::MessageIdReuse { + message_id: input.message_id.clone(), + }); } - if exact_identity.is_none() { + if exact_identity.is_none() && identity.source_position == input.cursor.position() { return Err(corrupt_storage( "projection message identity exists without its exact cursor identity", )); @@ -959,9 +978,17 @@ where )?)); } - if let Some(receipt) = receipt_by_message_in_tx(tx, input).await? { + let repeated_effect = if let Some(receipt) = receipt_by_message_in_tx(tx, input).await? { verify_stored_change(state, &receipt.change)?; - if !receipt_matches_input(&receipt, input) { + let mut original_input = input.clone(); + original_input.cursor = ProjectionInputCursor::new( + input.cursor.topology().clone(), + input.cursor.projection_partition().clone(), + input.cursor.source().clone(), + input.cursor.epoch().clone(), + receipt.source_position, + )?; + if !receipt_matches_input(&receipt, &original_input) { return Err(ProjectionProtocolError::MessageIdReuse { message_id: input.message_id.clone(), }); @@ -971,17 +998,17 @@ where "failed input receipt exists without a stopped partition", )); } - return Ok(InputDisposition::Duplicate(checkpoint_from_stored( - &input.cursor, - receipt.source_epoch, - receipt.source_position, - receipt.change, - receipt.gap_free, - )?)); - } + true + } else { + false + }; let Some(previous) = current_input_cursor_in_tx(tx, input).await? else { - return Ok(InputDisposition::New); + return Ok(if repeated_effect { + InputDisposition::Redelivery + } else { + InputDisposition::New + }); }; verify_stored_change(state, &previous.change)?; if previous.gap_free != input.gap_free { @@ -1007,7 +1034,7 @@ where { return Err(ProjectionProtocolError::InputCorruption); } - if !verify_inherited_cursor_in_tx(tx, input, &previous).await? { + if !repeated_effect && !verify_inherited_cursor_in_tx(tx, input, &previous).await? { return Err(corrupt_storage( "projection input cursor has no receipt and was not inherited by repair", )); @@ -1026,5 +1053,9 @@ where { return Err(ProjectionProtocolError::IncomparableInput); } - Ok(InputDisposition::New) + Ok(if repeated_effect { + InputDisposition::Redelivery + } else { + InputDisposition::New + }) } diff --git a/src/sqlx_repo/projection_protocol/postgres_tests.rs b/src/sqlx_repo/projection_protocol/postgres_tests.rs index 07ae6f960..357db7a49 100644 --- a/src/sqlx_repo/projection_protocol/postgres_tests.rs +++ b/src/sqlx_repo/projection_protocol/postgres_tests.rs @@ -11,20 +11,119 @@ mod postgres_tests { }; use crate::projection_protocol::{ ProjectionCheckpointProbe, ProjectionExecutionSnapshotBatchRequest, - ProjectionGraphSnapshotRequest, ProjectionQuerySnapshotRequest, - ProjectionObservationRequest, ProjectionRecordMutation, ProjectionScopeCodec, + ProjectionGraphSnapshotRequest, ProjectionObservationRequest, + ProjectionQuerySnapshotRequest, ProjectionRecordMutation, ProjectionScopeCodec, }; use crate::repository::{CommitBatch, ReadModelWritePlanStore}; use crate::table::{ ColumnType, DeleteTableRowMutation, ExpectedVersion, ForeignKey, PrimaryKey, - RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, RowWriteMode, - TableColumn, TableKind, TableRowMutation, TableSchema, TableSchemaRegistry, - TableStoreError, TableWritePlan, + RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, RowWriteMode, TableColumn, + TableKind, TableRowMutation, TableSchema, TableSchemaRegistry, TableStoreError, + TableWritePlan, }; static POSTGRES_PROJECTION_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + #[tokio::test] + async fn postgres_redelivery_identity_is_atomic_across_partition_and_cursor_races() { + let Ok(url) = std::env::var("DISTRIBUTED_TEST_POSTGRES_URL") else { + return; + }; + let _test_guard = POSTGRES_PROJECTION_TEST_LOCK.lock().await; + let repository = SqlxRepository::::connect_and_migrate(&url) + .await + .unwrap(); + let mut registry = TableSchemaRegistry::new(); + registry.register_schema(schema().clone()).unwrap(); + repository + .bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + repository + .register_projection_models(&topology(), &[ownership()]) + .await + .unwrap(); + let unique = uuid::Uuid::now_v7().to_string(); + let topology = topology(); + let input = |partition: &str, position: u64, id: &str, bytes: &[u8]| { + TrustedProjectionInput::mint( + ProjectionInputCursor::new( + topology.clone(), + ProjectionPartition::new(format!("{unique}-{partition}").into_bytes()).unwrap(), + ProjectionSource::new("broker", b"retained-stream".to_vec()).unwrap(), + ProjectionEpoch::new("broker-v1").unwrap(), + position, + ) + .unwrap(), + ProjectionInputFingerprint::from_canonical_bytes(bytes), + format!("{unique}-{id}"), + "cause", + ProjectionGeneration::initial(), + false, + ) + .unwrap() + }; + let batch = |input| ProjectionCommitBatch { + input, + change_epoch: ProjectionEpoch::new("changes-v1").unwrap(), + ownership: vec![ownership()], + mutations: Vec::new(), + observations: Vec::new(), + }; + // The canonical unique topology/message binding arbitrates different + // partition locks: only one scope/content may ever claim this identity. + let (a, b) = tokio::join!( + repository.commit_projection(batch(input("a", 1, "shared", b"one"))), + repository.commit_projection(batch(input("b", 1, "shared", b"two"))), + ); + assert_eq!( + usize::from(a.is_ok()) + usize::from(b.is_ok()), + 1, + "a={a:?}, b={b:?}" + ); + let (partition, bytes) = if a.is_ok() { + ("a", b"one".as_slice()) + } else { + ("b", b"two".as_slice()) + }; + let duplicate = input(partition, 2, "shared", bytes); + assert_eq!( + repository + .projection_input_disposition(&duplicate) + .await + .unwrap(), + ProjectionInputDisposition::Redelivery + ); + // Alias and new canonical input race for exactly the same broker cursor. + // Partition serialization must forbid a cross-table double binding. + let (alias, canonical) = tokio::join!( + repository.commit_projection(batch(duplicate.clone())), + repository.commit_projection(batch(input(partition, 2, "different", b"different"))), + ); + assert_eq!( + usize::from(alias.is_ok()) + usize::from(canonical.is_ok()), + 1 + ); + let loser = if alias.is_ok() { + input(partition, 2, "different", b"different") + } else { + duplicate + }; + assert!(matches!( + repository.projection_input_disposition(&loser).await, + Err(ProjectionProtocolError::InputCorruption) + )); + let repeated = repository + .commit_projection(batch(input(partition, 3, "shared", bytes))) + .await + .unwrap(); + assert_eq!(repeated.outcome, ProjectionCommitOutcome::Duplicate); + assert_eq!(repeated.checkpoint.unwrap().input().position(), 3); + assert_eq!(repeated.changes.len(), 1); + assert_eq!(repeated.changes[0].kind, ProjectionChangeKind::Checkpoint); + } + fn topology() -> ProjectorTopologyId { ProjectorTopologyId::new(1, "postgres_projection_runtime", [71; 32]).unwrap() } @@ -136,16 +235,10 @@ mod postgres_tests { fn graph_ownership() -> Vec { vec![ - ProjectionModelOwnership::new( - "PostgresGraphParentView", - "postgres_graph_parent_views", - ) - .unwrap(), - ProjectionModelOwnership::new( - "PostgresGraphChildView", - "postgres_graph_child_views", - ) - .unwrap(), + ProjectionModelOwnership::new("PostgresGraphParentView", "postgres_graph_parent_views") + .unwrap(), + ProjectionModelOwnership::new("PostgresGraphChildView", "postgres_graph_child_views") + .unwrap(), ] } @@ -163,12 +256,14 @@ mod postgres_tests { fn graph_key(model: &str) -> RowKey { RowKey::new([( "id", - RowValue::String(match model { - "PostgresGraphParentView" => "parent-1", - "PostgresGraphChildView" => "child-1", - other => panic!("unknown PostgreSQL graph model {other}"), - } - .into()), + RowValue::String( + match model { + "PostgresGraphParentView" => "parent-1", + "PostgresGraphChildView" => "child-1", + other => panic!("unknown PostgreSQL graph model {other}"), + } + .into(), + ), )]) } @@ -240,10 +335,7 @@ mod postgres_tests { ProjectionGraphSnapshotRequest::new( root, [ - ( - "children".into(), - Arc::new(graph_child_schema().clone()), - ), + ("children".into(), Arc::new(graph_child_schema().clone())), ( "featured_children".into(), Arc::new(graph_child_schema().clone()), @@ -318,10 +410,7 @@ mod postgres_tests { } fn matrix_key(scenario: usize, index: usize) -> RowKey { - RowKey::new([( - "id", - RowValue::String(format!("matrix-{scenario}-{index}")), - )]) + RowKey::new([("id", RowValue::String(format!("matrix-{scenario}-{index}")))]) } fn matrix_scope(scenario: usize, index: usize) -> ProjectionRecordScope { @@ -341,10 +430,7 @@ mod postgres_tests { expectation: ProjectionRecordExpectation, ) -> ProjectionRecordMutation { let mut values = RowValues::new(); - values.insert( - "id", - RowValue::String(format!("matrix-{scenario}-{index}")), - ); + values.insert("id", RowValue::String(format!("matrix-{scenario}-{index}"))); values.insert("value", RowValue::String(value.into())); ProjectionRecordMutation::new( matrix_scope(scenario, index), @@ -386,15 +472,10 @@ mod postgres_tests { .unwrap() } - fn matrix_snapshot_request( - scenario: usize, - index: usize, - ) -> ProjectionQuerySnapshotRequest { + fn matrix_snapshot_request(scenario: usize, index: usize) -> ProjectionQuerySnapshotRequest { ProjectionQuerySnapshotRequest::new( &matrix_codec(), - Some(&serde_json::json!(format!( - "postgres-matrix-{scenario}" - ))), + Some(&serde_json::json!(format!("postgres-matrix-{scenario}"))), "PostgresProjectionMatrixView", matrix_key(scenario, index), Vec::new(), @@ -788,9 +869,9 @@ mod postgres_tests { assert!( matches!( repository.commit_projection(failed_batch()).await, - Err(ProjectionProtocolError::Table(TableStoreError::BackendStorage { - .. - })) + Err(ProjectionProtocolError::Table( + TableStoreError::BackendStorage { .. } + )) ), "failure position {fail_at}" ); @@ -822,7 +903,10 @@ mod postgres_tests { ) }) .collect::>(); - assert_eq!(physical_after, physical_before, "failure position {fail_at}"); + assert_eq!( + physical_after, physical_before, + "failure position {fail_at}" + ); for (index, expected) in snapshots_before.iter().enumerate() { assert_eq!( &repository diff --git a/src/sqlx_repo/projection_protocol/store_impl.rs b/src/sqlx_repo/projection_protocol/store_impl.rs index 353378e58..021651a9e 100644 --- a/src/sqlx_repo/projection_protocol/store_impl.rs +++ b/src/sqlx_repo/projection_protocol/store_impl.rs @@ -332,12 +332,12 @@ where fn commit_projection( &self, - batch: ProjectionCommitBatch, + mut batch: ProjectionCommitBatch, ) -> impl Future> + Send + '_ { async move { batch.validate()?; - let write_plan = TableWritePlan::new( + let mut write_plan = TableWritePlan::new( batch .mutations .iter() @@ -357,24 +357,35 @@ where lock_partition_in_tx(&mut tx, &topology, &partition, &batch.change_epoch).await?; validate_input_identity_in_tx(&mut tx, &batch.input).await?; ensure_active_input(&state, &batch.input)?; - match classify_validated_input_in_tx(&mut tx, &batch.input, &state).await? { - InputDisposition::Duplicate(checkpoint) => { - return Ok(ProjectionCommitResult::not_applied( - ProjectionCommitOutcome::Duplicate, - Some(checkpoint), - )); - } - InputDisposition::Stale(checkpoint) => { - return Ok(ProjectionCommitResult::not_applied( - ProjectionCommitOutcome::StaleInput, - Some(checkpoint), - )); - } - InputDisposition::New => { - ensure_pending_retry_input_in_tx(&mut tx, &state, &batch.input).await?; - } + let redelivery = + match classify_validated_input_in_tx(&mut tx, &batch.input, &state).await? { + InputDisposition::Duplicate(checkpoint) => { + return Ok(ProjectionCommitResult::not_applied( + ProjectionCommitOutcome::Duplicate, + Some(checkpoint), + )); + } + InputDisposition::Stale(checkpoint) => { + return Ok(ProjectionCommitResult::not_applied( + ProjectionCommitOutcome::StaleInput, + Some(checkpoint), + )); + } + InputDisposition::New => { + ensure_pending_retry_input_in_tx(&mut tx, &state, &batch.input).await?; + false + } + InputDisposition::Redelivery => { + ensure_pending_retry_input_in_tx(&mut tx, &state, &batch.input).await?; + batch.mutations.clear(); + batch.observations.clear(); + write_plan = TableWritePlan::new(Vec::new()); + true + } + }; + if !redelivery { + ensure_inbox_available_in_tx(&mut tx, &batch.input).await?; } - ensure_inbox_available_in_tx(&mut tx, &batch.input).await?; ensure_partition_ownership_in_tx(&mut tx, &topology, &partition, &batch.ownership) .await?; @@ -585,9 +596,11 @@ where } store_input_cursor_in_tx(&mut tx, &batch.input, &final_change).await?; insert_input_identity_in_tx(&mut tx, &batch.input).await?; - insert_input_receipt_in_tx(&mut tx, &batch.input, "applied", None, &final_change) - .await?; - insert_inbox_in_tx(&mut tx, &batch.input).await?; + if !redelivery { + insert_input_receipt_in_tx(&mut tx, &batch.input, "applied", None, &final_change) + .await?; + insert_inbox_in_tx(&mut tx, &batch.input).await?; + } update_partition_head_in_tx( &mut tx, &topology, @@ -621,7 +634,11 @@ where tables: changed_tables, }); Ok(ProjectionCommitResult { - outcome: ProjectionCommitOutcome::Applied, + outcome: if redelivery { + ProjectionCommitOutcome::Duplicate + } else { + ProjectionCommitOutcome::Applied + }, checkpoint: Some(checkpoint), records, changes, @@ -710,7 +727,9 @@ where InputDisposition::New => { ensure_pending_retry_input_in_tx(&mut tx, &state, &batch.input).await?; } - InputDisposition::Duplicate(_) | InputDisposition::Stale(_) => { + InputDisposition::Duplicate(_) + | InputDisposition::Stale(_) + | InputDisposition::Redelivery => { return Err(ProjectionProtocolError::InvalidBatch( "cannot record terminal failure for an already processed input".into(), )); @@ -907,6 +926,10 @@ where ensure_pending_retry_input_in_tx(&mut tx, &state, input).await?; Ok(ProjectionInputDisposition::Pending) } + InputDisposition::Redelivery => { + ensure_pending_retry_input_in_tx(&mut tx, &state, input).await?; + Ok(ProjectionInputDisposition::Redelivery) + } InputDisposition::Duplicate(checkpoint) => { Ok(ProjectionInputDisposition::Duplicate(checkpoint)) } diff --git a/src/sqlx_repo/projection_protocol/tests.rs b/src/sqlx_repo/projection_protocol/tests.rs index f91a3a8b7..66c0277c3 100644 --- a/src/sqlx_repo/projection_protocol/tests.rs +++ b/src/sqlx_repo/projection_protocol/tests.rs @@ -16,15 +16,14 @@ mod tests { }; use crate::projection_protocol::{ ProjectionCheckpointProbe, ProjectionExecutionSnapshotBatchRequest, - ProjectionGraphSnapshotRequest, ProjectionObservationRequest, - ProjectionLiveRecordRequest, ProjectionQuerySnapshotRequest, ProjectionRecordMutation, - ProjectionScopeCodec, + ProjectionGraphSnapshotRequest, ProjectionLiveRecordRequest, ProjectionObservationRequest, + ProjectionQuerySnapshotRequest, ProjectionRecordMutation, ProjectionScopeCodec, }; use crate::repository::{CommitBatch, ReadModelWritePlanStore, TransactionalCommit}; use crate::table::{ ColumnType, DeleteTableRowMutation, ExpectedVersion, ForeignKey, PrimaryKey, - RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, RowWriteMode, - TableColumn, TableKind, TableRowMutation, TableSchema, TableSchemaRegistry, + RelationshipDef, RelationshipKind, RowKey, RowValue, RowValues, RowWriteMode, TableColumn, + TableKind, TableRowMutation, TableSchema, TableSchemaRegistry, }; fn topology() -> ProjectorTopologyId { @@ -231,12 +230,14 @@ mod tests { fn graph_key(model: &str) -> RowKey { RowKey::new([( "id", - RowValue::String(match model { - "SqlGraphParentView" => "parent-1", - "SqlGraphChildView" => "child-1", - other => panic!("unknown SQL graph model {other}"), - } - .into()), + RowValue::String( + match model { + "SqlGraphParentView" => "parent-1", + "SqlGraphChildView" => "child-1", + other => panic!("unknown SQL graph model {other}"), + } + .into(), + ), )]) } @@ -289,10 +290,7 @@ mod tests { ProjectionGraphSnapshotRequest::new( root, [ - ( - "children".into(), - Arc::new(graph_child_schema().clone()), - ), + ("children".into(), Arc::new(graph_child_schema().clone())), ( "featured_children".into(), Arc::new(graph_child_schema().clone()), @@ -751,6 +749,11 @@ mod tests { .await; } + #[tokio::test] + async fn sqlite_identical_redelivery_advances_only_broker_checkpoint() { + crate::projection_protocol::scenario_tests::identical_redelivery_advances_only_broker_checkpoint(ProjectionScenario).await; + } + #[tokio::test] async fn sqlite_obligation_and_unpartitioned_live_evidence_are_exact_and_durable() { let evidence_repository = repository().await; @@ -1052,8 +1055,8 @@ mod tests { } #[tokio::test] - async fn sqlite_modeled_projection_identity_is_durable_across_restart_and_null_history_stays_readable() - { + async fn sqlite_modeled_projection_identity_is_durable_across_restart_and_null_history_stays_readable( + ) { let (repository, database_path) = wal_repository_with_retention(16).await; let program_a = semantic_program_id('a'); let scope = record_scope(); @@ -1104,7 +1107,11 @@ mod tests { ProjectionChangeRead::Changes { changes, .. } => changes, other => panic!("restarted repository must retain projection changes: {other:?}"), }; - assert_eq!(changes.len(), 1, "the staged observation shares the record change"); + assert_eq!( + changes.len(), + 1, + "the staged observation shares the record change" + ); assert!(changes .iter() .all(|change| change.program_id == Some(program_a))); @@ -1117,20 +1124,16 @@ mod tests { // Rows written before semantic identities existed remain useful after // migration, but their null identity cannot mint modeled proof. - sqlx::query( - "UPDATE projection_changes SET program_id = NULL WHERE causation_id = ?", - ) - .bind("semantic-identity-cause-a") - .execute(reopened.pool()) - .await - .unwrap(); - sqlx::query( - "UPDATE projection_observations SET program_id = NULL WHERE causation_id = ?", - ) - .bind("semantic-identity-cause-a") - .execute(reopened.pool()) - .await - .unwrap(); + sqlx::query("UPDATE projection_changes SET program_id = NULL WHERE causation_id = ?") + .bind("semantic-identity-cause-a") + .execute(reopened.pool()) + .await + .unwrap(); + sqlx::query("UPDATE projection_observations SET program_id = NULL WHERE causation_id = ?") + .bind("semantic-identity-cause-a") + .execute(reopened.pool()) + .await + .unwrap(); let null_history = reopened .projection_causation_evidence(&selected) .await @@ -1139,16 +1142,24 @@ mod tests { assert_eq!(null_history.observations[0].program_id, None); let readable = reopened .projection_live_record_batch( - &ProjectionLiveRecordBatchRequest::new(vec![ - ProjectionLiveRecordRequest::new(&scope_codec(), "SqlTodoView", record_key()) - .unwrap(), - ]) + &ProjectionLiveRecordBatchRequest::new(vec![ProjectionLiveRecordRequest::new( + &scope_codec(), + "SqlTodoView", + record_key(), + ) + .unwrap()]) .unwrap(), ) .await .unwrap(); - assert!(readable.records[0].is_some(), "unversioned rows remain readable"); - assert_eq!(readable.records[0].as_ref().unwrap().revision.scope(), &scope); + assert!( + readable.records[0].is_some(), + "unversioned rows remain readable" + ); + assert_eq!( + readable.records[0].as_ref().unwrap().revision.scope(), + &scope + ); remove_wal_database(reopened, &database_path).await; } @@ -2259,9 +2270,9 @@ mod tests { assert!( matches!( repository.commit_projection(failed_batch()).await, - Err(ProjectionProtocolError::Table(TableStoreError::BackendStorage { - .. - })) + Err(ProjectionProtocolError::Table( + TableStoreError::BackendStorage { .. } + )) ), "failure position {fail_at}" ); @@ -2286,7 +2297,10 @@ mod tests { ) }) .collect::>(); - assert_eq!(physical_after, physical_before, "failure position {fail_at}"); + assert_eq!( + physical_after, physical_before, + "failure position {fail_at}" + ); for (index, expected) in snapshots_before.iter().enumerate() { assert_eq!( &repository @@ -2955,8 +2969,15 @@ mod tests { let (cache_store, cache_pool, cache_tables, cache_before) = { let pool = crate::graphql::GraphqlPool::Sqlite(repository.pool().clone()); let tables = vec!["sql_todo_views".to_owned()]; - let store = crate::graphql::delivery::GatewayVersionStore::install(&pool, "atomic-cache-test", tables.clone()).await.unwrap(); - let before = serde_json::to_value(store.current(&pool, &tables).await.unwrap()).unwrap(); + let store = crate::graphql::delivery::GatewayVersionStore::install( + &pool, + "atomic-cache-test", + tables.clone(), + ) + .await + .unwrap(); + let before = + serde_json::to_value(store.current(&pool, &tables).await.unwrap()).unwrap(); (store, pool, tables, before) }; let command_id = uuid::Uuid::now_v7().hyphenated().to_string(); @@ -3010,8 +3031,17 @@ mod tests { #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] let cache_committed = { - let committed = serde_json::to_value(cache_store.current(&cache_pool, &cache_tables).await.unwrap()).unwrap(); - assert_ne!(committed, cache_before, "Atomic result and cache dependency versions commit together"); + let committed = serde_json::to_value( + cache_store + .current(&cache_pool, &cache_tables) + .await + .unwrap(), + ) + .unwrap(); + assert_ne!( + committed, cache_before, + "Atomic result and cache dependency versions commit together" + ); committed }; let metadata = repository @@ -3109,8 +3139,17 @@ mod tests { CommandLookup::InProgress { .. } )); #[cfg(all(feature = "graphql", feature = "gateway-delivery"))] - assert_eq!(serde_json::to_value(cache_store.current(&cache_pool, &cache_tables).await.unwrap()).unwrap(), cache_committed, - "failed Atomic ledger completion must roll back cache versions too"); + assert_eq!( + serde_json::to_value( + cache_store + .current(&cache_pool, &cache_tables) + .await + .unwrap() + ) + .unwrap(), + cache_committed, + "failed Atomic ledger completion must roll back cache versions too" + ); sqlx::query("DROP TRIGGER fail_direct_ledger_completion") .execute(repository.pool()) .await diff --git a/src/sqlx_repo/projection_protocol/types.rs b/src/sqlx_repo/projection_protocol/types.rs index 27f6e6b0e..7c152d1be 100644 --- a/src/sqlx_repo/projection_protocol/types.rs +++ b/src/sqlx_repo/projection_protocol/types.rs @@ -64,6 +64,7 @@ pub(super) struct StoredFailure { pub(super) enum InputDisposition { New, + Redelivery, Duplicate(ProjectionCheckpoint), Stale(ProjectionCheckpoint), } diff --git a/src/sqlx_repo/projection_protocol/writes.rs b/src/sqlx_repo/projection_protocol/writes.rs index fd5472a61..4fc24a8dc 100644 --- a/src/sqlx_repo/projection_protocol/writes.rs +++ b/src/sqlx_repo/projection_protocol/writes.rs @@ -975,9 +975,36 @@ where return Err(ProjectionProtocolError::InputCorruption); } if input_identity_by_message_in_tx(tx, input).await?.is_some() { - return Err(ProjectionProtocolError::MessageIdReuse { - message_id: input.message_id.clone(), - }); + // The canonical unique binding wins races across projection partitions. + // Revalidate against it before retaining a distinct broker delivery. + validate_input_identity_in_tx(tx, input).await?; + let mut alias = QueryBuilder::::new( + "INSERT INTO projection_input_delivery_aliases \ + (topology_hash, partition_hash, source_hash, source_partition_hash, \ + source_epoch, source_position, message_id) VALUES (", + ); + alias.push_bind(topology_hash.as_slice()); + alias.push(", ").push_bind(partition_hash.as_slice()); + alias.push(", ").push_bind(source_hash.as_slice()); + alias.push(", ").push_bind(source_partition_hash.as_slice()); + alias.push(", ").push_bind(cursor.epoch().as_str()); + alias.push(", ").push_bind(to_i64::( + cursor.position(), + "projection alias position", + )?); + alias.push(", ").push_bind(input.message_id.as_str()); + alias.push(") ON CONFLICT DO NOTHING"); + alias.build().execute(&mut **tx).await.map_err(|error| { + protocol_storage_error::("insert projection delivery alias", error) + })?; + let stored = input_identity_by_cursor_in_tx(tx, input) + .await? + .ok_or_else(|| corrupt_storage("projection alias insert has no readable identity"))?; + return if input_identity_matches(&stored, input) { + Ok(()) + } else { + Err(ProjectionProtocolError::InputCorruption) + }; } Err(corrupt_storage( "projection input identity collided without a readable conflicting row", diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 71eeac174..8b749fb1c 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -47,7 +47,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); assert_eq!( descriptions, vec![ @@ -58,7 +58,8 @@ mod tests { "projection source snapshots", "gateway dependency versions", "projection program identity", - "external command binding" + "external command binding", + "projection delivery aliases" ] ); assert_eq!( @@ -96,6 +97,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0008_external_command_binding.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0009_projection_delivery_aliases.sql" + )), ] ); } @@ -115,7 +120,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); assert_eq!( descriptions, vec![ @@ -126,7 +131,8 @@ mod tests { "projection source snapshots", "gateway dependency versions", "projection program identity", - "external command binding" + "external command binding", + "projection delivery aliases" ] ); assert_eq!( @@ -164,6 +170,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0008_external_command_binding.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0009_projection_delivery_aliases.sql" + )), ] ); } diff --git a/tests/nats_transport/main.rs b/tests/nats_transport/main.rs index 9b6c293b5..e00284393 100644 --- a/tests/nats_transport/main.rs +++ b/tests/nats_transport/main.rs @@ -28,6 +28,217 @@ fn nats_url() -> Option { env_support::broker_env("NATS_URL", "nats transport test") } +#[derive(serde::Serialize, distributed::DomainEvent)] +#[domain_event(name = "ledger.external_balance", version = 1)] +struct ExternalBalance { + value: u64, +} + +fn external_balance(position: u64, value: u64) -> distributed::DomainEventOccurrence { + distributed::DomainEventOccurrence::capture_external( + distributed::ExternalEventSource { + producer: "ledger-webhook".into(), + stream: "account-one".into(), + position, + key: "balance".into(), + }, + std::time::UNIX_EPOCH, + Default::default(), + &ExternalBalance { value }, + ) + .unwrap() +} + +#[tokio::test] +async fn external_identity_content_conflicts_and_retained_archive_survive_broker_dedup() { + use distributed::bus::{Bus, MessageSource, ReceivedMessage}; + let Some(url) = nats_url() else { return }; + let namespace = unique("external_archive"); + let bus = NatsBus::connect(&url).namespace(&namespace).await.unwrap(); + let stream = bus.ensure_stream().await.unwrap(); + let stream_name = stream.cached_info().config.name.clone(); + let mut source = NatsJetStreamSource::connect( + &url, + &stream_name, + vec![format!("{namespace}.>")], + &unique("external_consumer"), + ) + .await + .unwrap() + .with_strip_prefix(format!("{namespace}.evt.")); + let first = external_balance(1, 10); + let altered = external_balance(1, 11); + let next = external_balance(2, 10); + assert_eq!(first.id(), altered.id()); + for event in [&first, &first, &altered, &next] { + bus.publish_message( + distributed::OutboxMessage::from_domain_event_occurrence(event) + .unwrap() + .into(), + ) + .await + .unwrap(); + } + // Identical retry deduplicates, altered bytes with the same logical source + // identity must remain visible to the permanent projection conflict fence. + for expected in [&first, &altered, &next] { + let received = source.recv().await.unwrap().unwrap(); + assert_eq!(received.message().id(), Some(expected.id())); + assert_eq!( + received.message().payload(), + expected.canonical_bytes().unwrap() + ); + received.ack().await.unwrap(); + } + assert!(source.recv().await.unwrap().is_none()); + let archive = bus.retained_domain_events().await.unwrap(); + assert_eq!(archive.len(), 3); + assert_eq!(bus.retained_domain_events().await.unwrap(), archive); + let js = async_nats::jetstream::new(async_nats::connect(&url).await.unwrap()); + js.delete_stream(&stream_name).await.unwrap(); +} + +#[tokio::test] +async fn archive_and_live_decode_reject_the_same_poisoned_identity_and_kind_headers() { + use distributed::bus::MessageSource; + use sha2::{Digest, Sha256}; + let Some(url) = nats_url() else { return }; + let js = async_nats::jetstream::new(async_nats::connect(&url).await.unwrap()); + for case in [ + "duplicate", + "wrong-kind", + "missing-kind", + "lowercase-aggregate", + ] { + let namespace = unique("archive_poison"); + let bus = NatsBus::connect(&url).namespace(&namespace).await.unwrap(); + let stream = bus.ensure_stream().await.unwrap(); + let stream_name = stream.cached_info().config.name.clone(); + let mut source = NatsJetStreamSource::connect( + &url, + &stream_name, + vec![format!("{namespace}.>")], + &unique("consumer"), + ) + .await + .unwrap() + .with_strip_prefix(format!("{namespace}.evt.")); + let mut event = external_balance(1, 10); + if case == "lowercase-aggregate" { + let mut entity = distributed::Entity::with_id("account"); + entity.digest("fixture", &()).unwrap(); + entity + .capture_domain_event("ledger", &ExternalBalance { value: 10 }) + .unwrap(); + event = entity.pending_domain_events()[0].clone(); + } + let bytes = event.canonical_bytes().unwrap(); + let mut headers = async_nats::HeaderMap::new(); + headers.insert( + "x-sourced-payload-codec", + "distributed.domain-event-occurrence+json", + ); + if case != "missing-kind" { + headers.insert( + "X-Sourced-Kind", + if case == "wrong-kind" { + "command" + } else { + "event" + }, + ); + } + if event.external_source().is_some() { + let mut hash = Sha256::new(); + hash.update(b"distributed.nats.external-occurrence.v1\0"); + hash.update(&bytes); + headers.insert( + "Nats-Msg-Id", + format!("external:sha256:{:x}", hash.finalize()), + ); + headers.insert("X-Distributed-Occurrence-Id", event.id()); + if case == "duplicate" { + headers.append("x-distributed-occurrence-id", "forged-extra"); + } + } else { + headers.insert("Nats-Msg-Id", event.id()); + headers.insert("x-distributed-occurrence-id", "forged-logical"); + } + js.publish_with_headers( + format!("{namespace}.evt.{}", event.descriptor().name), + headers, + bytes.into(), + ) + .await + .unwrap() + .await + .unwrap(); + assert!( + bus.retained_domain_events().await.is_err(), + "archive accepted {case}" + ); + assert!(source.recv().await.is_err(), "live accepted {case}"); + js.delete_stream(&stream_name).await.unwrap(); + } +} + +#[tokio::test] +async fn malformed_external_headers_fail_closed_without_ack_or_false_progress() { + use distributed::bus::MessageSource; + let Some(url) = nats_url() else { return }; + let prefix = unique("external_poison"); + let subject = format!("{prefix}.ledger.external_balance"); + let stream_name = unique("EXTERNAL_POISON"); + let durable = unique("poison_consumer"); + let mut source = + NatsJetStreamSource::connect(&url, &stream_name, vec![subject.clone()], &durable) + .await + .unwrap() + .with_strip_prefix(format!("{prefix}.")); + let js = async_nats::jetstream::new(async_nats::connect(&url).await.unwrap()); + let event = external_balance(1, 10); + let mut headers = async_nats::HeaderMap::new(); + headers.insert("Nats-Msg-Id", "forged"); + headers.insert("X-Sourced-Kind", "event"); + headers.append("X-Distributed-Occurrence-Id", event.id()); + headers.append("X-Distributed-Occurrence-Id", event.id()); + js.publish_with_headers(subject, headers, event.canonical_bytes().unwrap().into()) + .await + .unwrap() + .await + .unwrap(); + let publisher = NatsPublisher::connect(&url) + .await + .unwrap() + .with_subject_prefix(&prefix); + publisher + .publish( + distributed::OutboxMessage::from_domain_event_occurrence(&external_balance(2, 20)) + .unwrap() + .into(), + ) + .await + .unwrap(); + let error = match source.recv().await { + Err(error) => error, + _ => panic!("poison must fail closed"), + }; + assert!(error.is_permanent()); + let mut stream = js.get_stream(&stream_name).await.unwrap(); + let mut consumer: async_nats::jetstream::consumer::Consumer< + async_nats::jetstream::consumer::pull::Config, + > = stream.get_consumer(&durable).await.unwrap(); + let info = consumer.info().await.unwrap(); + assert_eq!(info.ack_floor.stream_sequence, 0); + assert_eq!(info.num_ack_pending, 1); + assert_eq!( + info.num_pending, 1, + "later input was not dispatched past poison" + ); + assert_eq!(stream.info().await.unwrap().state.messages, 2); + js.delete_stream(&stream_name).await.unwrap(); +} + #[tokio::test] async fn derived_facts_round_trip_after_interrupted_publish_prefix() { let Some(url) = nats_url() else { return }; From 42bb6c8a9756ea983312fb1b39493e4450b4b0b8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 28 Sep 2026 14:13:49 -0500 Subject: [PATCH 112/484] test: include delivery aliases in migration upgrade assertions --- distributed_cli/src/contracts/tests.rs | 2 +- tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 1c05512d7..2edef446b 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index f5dd02de3..b2630adc1 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 8); + assert_eq!(latest_version, 9); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 8f62df91f..63af41672 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 8); + assert_eq!(latest_version, 9); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From d986c3d2104221deafb31c80ca9c6d651c3c40ce Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 28 Sep 2026 16:28:18 -0500 Subject: [PATCH 113/484] fix: rebuild snapshots with explicit external source identities --- docs/external-facts.md | 12 ++ src/projection/rebuild.rs | 61 +++++++-- src/projection/source_snapshot_tests.rs | 166 ++++++++++++++++++++++++ 3 files changed, 228 insertions(+), 11 deletions(-) diff --git a/docs/external-facts.md b/docs/external-facts.md index 5428c43f2..57bbcbea2 100644 --- a/docs/external-facts.md +++ b/docs/external-facts.md @@ -43,3 +43,15 @@ An ingress that acknowledges an external cursor must first establish its own required durable qualification (for example, a history projection atomically committed with the protocol fingerprint), and retain source replay until then. Publishing is not approval, and waiting for all UI consumers is unnecessary. + +Offline snapshot rebuild preserves these same identities. It distinguishes +original aggregate positions, original external stream/position/member keys, +and derived occurrence IDs; unrelated external facts cannot collide at empty +aggregate fields. Duplicate logical IDs must retain identical canonical bytes. +Aggregate projections still require a complete original aggregate sequence +prefix. External positions may be sparse or shared by different members, so +the source adapter must certify the complete retained source range instead of +inventing a contiguous aggregate history. Rebuild still rejects omitted stored +source versions, changed content at one source position, a different source +claiming an existing row, and derived facts used as snapshot authority. It does +not run business handlers, republish events, or reset delivery cursors. diff --git a/src/projection/rebuild.rs b/src/projection/rebuild.rs index 26506ffc1..b9553ea69 100644 --- a/src/projection/rebuild.rs +++ b/src/projection/rebuild.rs @@ -11,6 +11,33 @@ pub(crate) const MAX_REBUILD_RECORDS: usize = 10_000; const MAX_HISTORY_EVENTS: usize = 100_000; const MAX_HISTORY_BYTES: usize = 64 * 1024 * 1024; +#[derive(PartialEq, Eq, PartialOrd, Ord)] +enum HistoryIdentity { + Aggregate(String, String, u64, u32), + External(String, String, u64, String), + Derived(String), +} + +fn history_identity(event: &DomainEventOccurrence) -> HistoryIdentity { + if event.derivation().is_some() { + HistoryIdentity::Derived(event.id().to_owned()) + } else if let Some(source) = event.external_source() { + HistoryIdentity::External( + source.producer.clone(), + source.stream.clone(), + source.position, + source.key.clone(), + ) + } else { + HistoryIdentity::Aggregate( + event.aggregate_type().into(), + event.aggregate_id().into(), + event.aggregate_sequence(), + event.publication_ordinal(), + ) + } +} + pub(crate) fn invalid(detail: impl ToString) -> ProjectionProtocolError { ProjectionProtocolError::InvalidBatch(detail.to_string()) } @@ -154,8 +181,12 @@ impl SnapshotProjectionRebuild { /// /// The caller must supply the entire publication history through the /// quiescent source head, not a filtered consumer window. This method checks - /// covered record identities, sequence prefixes and conflicting duplicates; + /// covered record identities, aggregate sequence prefixes and conflicting duplicates; /// it cannot discover unpublished or externally deleted source history. + /// External source positions can legitimately be sparse (including between + /// members of one source transaction). Their completeness must be certified + /// by the source adapter/archive; no aggregate prefix is invented for them. + /// Stored external row versions must still occur in the supplied history. pub fn from_complete_history( self, history: &[DomainEventOccurrence], @@ -167,6 +198,7 @@ impl SnapshotProjectionRebuild { } let mut bytes = 0usize; let mut identities = BTreeMap::new(); + let mut logical_ids = BTreeMap::new(); let mut sequences: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); let mut rows: HashMap = HashMap::new(); let mut relevant = BTreeSet::new(); @@ -184,15 +216,20 @@ impl SnapshotProjectionRebuild { event.aggregate_type().to_owned(), event.aggregate_id().to_owned(), ); - sequences - .entry(stream.clone()) - .or_default() - .insert(event.aggregate_sequence()); - let identity = ( - stream.clone(), - event.aggregate_sequence(), - event.publication_ordinal(), - ); + if event.external_source().is_none() && event.derivation().is_none() { + sequences + .entry(stream.clone()) + .or_default() + .insert(event.aggregate_sequence()); + } + if let Some(previous) = logical_ids.insert(event.id(), canonical.clone()) { + if previous != canonical { + return Err(invalid( + "snapshot rebuild history contains conflicting logical identities", + )); + } + } + let identity = history_identity(event); if let Some(previous) = identities.insert(identity, canonical.clone()) { if previous != canonical { return Err(invalid( @@ -204,7 +241,9 @@ impl SnapshotProjectionRebuild { if !self.executor.matches(event) { continue; } - relevant.insert(stream); + if event.external_source().is_none() && event.derivation().is_none() { + relevant.insert(stream); + } let lowered = self.executor.plan(event).map_err(invalid)?; if !lowered.resolved.source_snapshots() { return Err(invalid("snapshot rebuild resolved a non-snapshot program")); diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs index 2a388b370..c78d3a3d9 100644 --- a/src/projection/source_snapshot_tests.rs +++ b/src/projection/source_snapshot_tests.rs @@ -21,6 +21,56 @@ struct SnapshotRow { } type SourceSnapshotRows = SnapshotRow; +#[derive(serde::Serialize)] +struct ExternalRow { + id: String, + title: String, +} +impl crate::DomainEvent for ExternalRow { + const DESCRIPTOR: DomainEventDescriptor = DomainEventDescriptor { + name: std::borrow::Cow::Borrowed("external.ledger.changed"), + version: 1, + body: crate::domain_event::DomainEventBodyDescriptor::distributed_json( + crate::domain_event::DomainEventBodyKind::Event, + "ExternalRow", + 1, + "external-row-v1", + "sha256:1111111111111111111111111111111111111111111111111111111111111111", + ), + }; +} +impl DomainEventContract for ExternalRow { + const EVENT_NAME: &'static str = "external.ledger.changed"; + const EVENT_VERSION: u64 = 1; + fn descriptor() -> DomainEventDescriptor { + ::DESCRIPTOR.clone() + } +} +crate::projection! { + const EXTERNAL_SNAPSHOTS: ProjectionDescriptor = { + name: "external-rebuild-test", version: 1, epoch: "external-rebuild-v1", model: SnapshotRow, + source: external_snapshot, + on { events: [ExternalRow], mutation: SaveSnapshot, input: { row: body }, }, + }; +} +fn external_row(stream: &str, key: &str, position: u64, title: &str) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + crate::domain_event::ExternalEventSource { + producer: "external.ledger".into(), + stream: stream.into(), + position, + key: key.into(), + }, + std::time::UNIX_EPOCH, + Default::default(), + &ExternalRow { + id: key.into(), + title: title.into(), + }, + ) + .unwrap() +} + struct Changed; impl DomainEventContract for Changed { const EVENT_NAME: &'static str = "snapshot.changed"; @@ -670,6 +720,122 @@ async fn snapshot_rebuild_memory() { rebuild_matrix(&crate::InMemoryRepository::new()).await; } +#[tokio::test] +async fn snapshot_rebuild_external_sparse_members_and_mixed_origins() { + use crate::projection::rebuild::SnapshotProjectionRebuild; + let store = crate::InMemoryRepository::new(); + let mounts = crate::LocalProjectionMountsBuilder::new("external-test", "events") + .unwrap() + .eventual_model::( + "external-rebuild", + EXTERNAL_SNAPSHOTS, + "external-rebuild-v1", + ) + .unwrap() + .build() + .unwrap(); + let projector = mounts.projector("external-rebuild").unwrap(); + async fn bootstrap( + store: &crate::InMemoryRepository, + projector: &crate::graphql::SurfaceProjector, + ) { + let (_, binding) = projector.modeled[0].raw().unwrap(); + let physical = binding.physical_topology().unwrap(); + let compiled = CompiledProjectionTopology::from_modeled_binding( + ProjectorTopologyId::new(physical.version(), physical.name(), physical.digest()) + .unwrap(), + binding + .outputs() + .iter() + .map(|output| (output.model(), output.storage(), output.schema())), + ) + .unwrap(); + store + .register_projection_models(compiled.topology(), compiled.ownership()) + .await + .unwrap(); + } + bootstrap(&store, &projector).await; + let capture = SnapshotProjectionRebuild::begin(&store, &projector) + .await + .unwrap(); + let a = external_row("ledger-a", "a", 7, "old"); + let b = external_row("ledger-a", "b", 7, "same transaction, different member"); + let newer = external_row("ledger-a", "a", 42, "new"); + let aggregate = event("aggregate", 1, "unrelated", false); + let derived = aggregate + .derive( + "ledger-indexer", + "summary", + &ExternalRow { + id: "derived".into(), + title: "not a snapshot".into(), + }, + ) + .unwrap(); + // Derived facts which match a snapshot arm remain invalid, not silently + // converted into source versions. + assert!(SnapshotProjectionRebuild::begin(&store, &projector) + .await + .unwrap() + .from_complete_history(&[a.clone(), derived.clone()]) + .is_err()); + let history = [ + newer.clone(), + b.clone(), + a.clone(), + aggregate.clone(), + a.clone(), + ]; + let plan = capture.from_complete_history(&history).unwrap(); + assert_eq!(plan.record_count(), 2); + assert_eq!(plan.apply(&store).await.unwrap(), 2); + let read = SnapshotProjectionRebuild::begin(&store, &projector) + .await + .unwrap(); + assert!( + read.from_complete_history(&[a.clone(), b.clone()]).is_err(), + "stored newer source evidence cannot disappear" + ); + for conflict in [ + external_row("ledger-a", "a", 42, "altered"), + external_row("other-ledger", "a", 43, "new"), + ] { + let mut changed = history.to_vec(); + changed.push(conflict); + assert!(SnapshotProjectionRebuild::begin(&store, &projector) + .await + .unwrap() + .from_complete_history(&changed) + .is_err()); + } + // An aggregate projector ignores unrelated external facts and derived + // events, but still requires its own complete aggregate prefix. + let aggregate_store = crate::InMemoryRepository::new(); + let aggregate_projector = rebuild_projector(); + bootstrap(&aggregate_store, &aggregate_projector).await; + let mixed = [aggregate.clone(), a, b, newer, derived]; + assert_eq!( + SnapshotProjectionRebuild::begin(&aggregate_store, &aggregate_projector) + .await + .unwrap() + .from_complete_history(&mixed) + .unwrap() + .record_count(), + 1 + ); + assert!( + SnapshotProjectionRebuild::begin(&aggregate_store, &aggregate_projector) + .await + .unwrap() + .from_complete_history(&[ + event("aggregate", 2, "missing prefix", false), + external_row("ledger", "c", 100, "unrelated") + ]) + .is_err() + ); +} + #[cfg(feature = "sqlite")] #[tokio::test] async fn snapshot_rebuild_sqlite() { From 4e716b3fef3db1f26b0d7a05bc88f58035035351 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 28 Sep 2026 16:37:16 -0500 Subject: [PATCH 114/484] fix: identify missing aggregate rebuild source positions --- src/projection/rebuild.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/projection/rebuild.rs b/src/projection/rebuild.rs index b9553ea69..297d496d0 100644 --- a/src/projection/rebuild.rs +++ b/src/projection/rebuild.rs @@ -303,14 +303,14 @@ impl SnapshotProjectionRebuild { } for stream in relevant { let sequence = &sequences[&stream]; - if sequence - .iter() - .copied() - .ne(1..=sequence.last().copied().unwrap_or(0)) + if let Some((expected, found)) = (1..) + .zip(sequence.iter().copied()) + .find(|(expected, found)| expected != found) { - return Err(invalid( - "snapshot rebuild requires a complete aggregate sequence prefix", - )); + return Err(invalid(format!( + "snapshot rebuild requires a complete aggregate sequence prefix for {}/{}: expected {}, found {}", + stream.0, stream.1, expected, found, + ))); } } for current in &self.expected { From 745ddc071127c6840fc70ba939191a3907848638 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 28 Sep 2026 16:59:16 -0500 Subject: [PATCH 115/484] fix: verify private stream coverage during snapshot rebuild Keep public archive prefix checks fail-closed. Qualify reviewed original single-publication aggregate logs without synthesizing private publications; retain external identity and source snapshot fences. --- distributed_cli/tests/cli_lifecycle.rs | 1 + docs/external-facts.md | 21 +++ src/projection/rebuild.rs | 208 ++++++++++++++++++++++++ src/projection/source_snapshot_tests.rs | 151 +++++++++++++++++ 4 files changed, 381 insertions(+) diff --git a/distributed_cli/tests/cli_lifecycle.rs b/distributed_cli/tests/cli_lifecycle.rs index eda70d1a4..72d2363c4 100644 --- a/distributed_cli/tests/cli_lifecycle.rs +++ b/distributed_cli/tests/cli_lifecycle.rs @@ -286,6 +286,7 @@ exit 1 fs::write(path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); } +#[track_caller] fn wait_until(timeout: Duration, predicate: impl Fn() -> bool) { let started = std::time::Instant::now(); while !predicate() { diff --git a/docs/external-facts.md b/docs/external-facts.md index 57bbcbea2..e3cdef685 100644 --- a/docs/external-facts.md +++ b/docs/external-facts.md @@ -55,3 +55,24 @@ inventing a contiguous aggregate history. Rebuild still rejects omitted stored source versions, changed content at one source position, a different source claiming an existing row, and derived facts used as snapshot authority. It does not run business handlers, republish events, or reset delivery cursors. + +Some original aggregate records are intentionally private and therefore absent +from the public archive. Public-archive-only rebuild remains fail-closed at such +a gap. An offline adapter can instead supply `AggregateRebuildCoverage`, built +from a complete original quiescent event-store stream, its independently read +head, an explicit authored private-contract inventory, and the retained public +occurrences. Missing or reordered records, unknown private contracts, missing +publications, changed public identities, and cross-stream substitution fail. +Every witnessed public occurrence must remain byte-identical in the rebuild +history. No private record is fabricated as a public event. +This constructor deliberately supports only authored single-publication streams +(one ordinal-zero occurrence per non-private record). The adapter must establish +that emitter contract; arbitrary one-to-many publication completeness cannot be +inferred from archive absence and is not covered by this API. + +This is an operator trust boundary, not cryptographic authentication of an +arbitrary export: retain the original source provenance and review the artifact +digest. The digest prevents substitution of the reviewed artifact. It does not +prove arbitrary private payloads reconstruct a public JSON state. Authored +event-to-public contract mappings and typed projection body validation remain +required; an absent broker message never makes a source record private. diff --git a/src/projection/rebuild.rs b/src/projection/rebuild.rs index 297d496d0..afc352f4f 100644 --- a/src/projection/rebuild.rs +++ b/src/projection/rebuild.rs @@ -6,6 +6,8 @@ use crate::projection::lower::ProjectionServerExecutorDescriptor; use crate::projection_protocol::*; use crate::table::{TableMutation, TableWritePlan}; use crate::DomainEventOccurrence; +use crate::{repository::StreamIdentity, EventRecord}; +use sha2::{Digest, Sha256}; pub(crate) const MAX_REBUILD_RECORDS: usize = 10_000; const MAX_HISTORY_EVENTS: usize = 100_000; @@ -38,6 +40,158 @@ fn history_identity(event: &DomainEventOccurrence) -> HistoryIdentity { } } +/// Offline evidence from one original, quiescent aggregate event store. +/// +/// This does not authenticate arbitrary supplied data. The operator/source +/// adapter must retain and review the original store export and its digest. +/// Private event records are never converted into public occurrences. Explicit +/// private contracts must come from the authored aggregate, not archive absence. +/// Public JSON bodies remain authenticated retained publications, not a claimed +/// reconstruction from private payload bytes. +#[derive(Clone)] +pub struct AggregateRebuildCoverage { + stream: (String, String), + head: u64, + public: BTreeMap, + source_digest: [u8; 32], +} + +impl AggregateRebuildCoverage { + /// Validate a complete original stream against its independently captured + /// head and retained public publications. The trusted offline adapter must + /// bind `identity`, `head` and `records` to the same quiescent source store. + /// `private_contracts` is an explicit authored contract inventory, never a + /// list inferred from missing broker messages. + /// This bounded adapter supports only authored streams that emit exactly + /// one public occurrence (ordinal zero) per non-private source record. The + /// caller must verify that contract; arbitrary one-to-many emitters require + /// an independently complete publication manifest and are not supported. + pub fn from_retained_stream( + identity: &StreamIdentity, + head: u64, + records: &[EventRecord], + private_contracts: &[(&str, u64)], + public_history: &[DomainEventOccurrence], + ) -> Result { + if records.is_empty() + || head != records.len() as u64 + || records.len() > MAX_HISTORY_EVENTS + || public_history.len() > MAX_HISTORY_EVENTS + { + return Err(invalid( + "aggregate coverage requires a bounded nonempty original stream", + )); + } + let stream = ( + identity.aggregate_type().to_owned(), + identity.aggregate_id().to_owned(), + ); + let mut public = BTreeMap::new(); + let mut public_bytes = 0usize; + let mut private = BTreeSet::new(); + for contract in private_contracts { + if contract.0.is_empty() || contract.1 == 0 || !private.insert(*contract) { + return Err(invalid("invalid or duplicate private contract inventory")); + } + } + let mut positions: BTreeMap> = BTreeMap::new(); + for event in public_history.iter().filter(|event| { + event.external_source().is_none() + && event.derivation().is_none() + && event.aggregate_type() == stream.0 + && event.aggregate_id() == stream.1 + }) { + let bytes = event.canonical_bytes().map_err(invalid)?; + public_bytes = public_bytes + .checked_add(bytes.len()) + .ok_or_else(|| invalid("coverage public size overflow"))?; + if public_bytes > MAX_HISTORY_BYTES { + return Err(invalid("aggregate coverage public history exceeds 64 MiB")); + } + let fingerprint: [u8; 32] = Sha256::digest(bytes).into(); + if let Some(previous) = public.insert(event.id().into(), fingerprint) { + if previous != fingerprint { + return Err(invalid("aggregate coverage public identity conflict")); + } + continue; + } + positions + .entry(event.aggregate_sequence()) + .or_default() + .push(event); + } + let mut digest = Sha256::new(); + let mut total = 0usize; + for (offset, record) in records.iter().enumerate() { + if record.sequence != offset as u64 + 1 + || record.event_version == 0 + || record.event_name.is_empty() + || record.payload_codec.is_empty() + || record.payload_codec_version == 0 + { + return Err(invalid( + "aggregate coverage has a missing, reordered or invalid original record", + )); + } + let bytes = crate::domain_event::canonical_json_bytes(record).map_err(invalid)?; + total = total + .checked_add(bytes.len()) + .ok_or_else(|| invalid("coverage size overflow"))?; + if total > MAX_HISTORY_BYTES { + return Err(invalid("aggregate coverage exceeds 64 MiB")); + } + digest.update((bytes.len() as u64).to_be_bytes()); + digest.update(bytes); + let declared_private = + private.contains(&(record.event_name.as_str(), record.event_version)); + let occurrences = positions.remove(&record.sequence).unwrap_or_default(); + if declared_private { + if !occurrences.is_empty() { + return Err(invalid( + "private source contract conflicts with a public occurrence", + )); + } + } else { + if occurrences.is_empty() { + return Err(invalid( + "aggregate coverage omits a required public occurrence", + )); + } + if occurrences.len() != 1 || occurrences[0].publication_ordinal() != 0 { + return Err(invalid( + "aggregate coverage requires an authored single-publication stream", + )); + } + for occurrence in occurrences { + if occurrence.descriptor().name != record.event_name + || occurrence.descriptor().version != record.event_version + || record.metadata.get("causation_id").map(String::as_str) + != occurrence.causation_id() + { + return Err(invalid("aggregate coverage public occurrence differs from its original source record")); + } + } + } + } + if !positions.is_empty() { + return Err(invalid( + "aggregate coverage ends before a public occurrence", + )); + } + Ok(Self { + stream, + head, + public, + source_digest: digest.finalize().into(), + }) + } + + /// Content identity of the validated original private record sequence. + pub fn source_digest(&self) -> [u8; 32] { + self.source_digest + } +} + pub(crate) fn invalid(detail: impl ToString) -> ProjectionProtocolError { ProjectionProtocolError::InvalidBatch(detail.to_string()) } @@ -190,12 +344,27 @@ impl SnapshotProjectionRebuild { pub fn from_complete_history( self, history: &[DomainEventOccurrence], + ) -> Result { + self.from_complete_history_with_coverage(history, &[]) + } + + /// Rebuild with independently retained original aggregate-log evidence. + /// The original public-archive-only method remains strict when no witness + /// is supplied. Every public identity captured by a witness must be present + /// with the same canonical bytes in this history. + pub fn from_complete_history_with_coverage( + self, + history: &[DomainEventOccurrence], + coverage: &[AggregateRebuildCoverage], ) -> Result { if history.len() > MAX_HISTORY_EVENTS { return Err(invalid( "snapshot rebuild history exceeds 100000 occurrences", )); } + if coverage.len() > MAX_REBUILD_RECORDS { + return Err(invalid("aggregate coverage exceeds 10000 streams")); + } let mut bytes = 0usize; let mut identities = BTreeMap::new(); let mut logical_ids = BTreeMap::new(); @@ -204,6 +373,12 @@ impl SnapshotProjectionRebuild { let mut relevant = BTreeSet::new(); let mut versions: HashMap> = HashMap::new(); + let mut covered = BTreeMap::new(); + for witness in coverage { + if covered.insert(witness.stream.clone(), witness).is_some() { + return Err(invalid("duplicate aggregate coverage stream")); + } + } for event in history { let canonical = event.canonical_bytes().map_err(invalid)?; bytes = bytes @@ -301,8 +476,41 @@ impl SnapshotProjectionRebuild { } } } + for witness in covered.values() { + for (id, expected) in &witness.public { + let bytes = logical_ids + .get(id.as_str()) + .ok_or_else(|| invalid("rebuild history omits witnessed public occurrence"))?; + if <[u8; 32]>::from(Sha256::digest(bytes)) != *expected { + return Err(invalid( + "rebuild history differs from witnessed public content", + )); + } + } + } for stream in relevant { let sequence = &sequences[&stream]; + if let Some(witness) = covered.get(&stream) { + if sequence.last().is_some_and(|last| *last > witness.head) { + return Err(invalid( + "public history exceeds its original source coverage", + )); + } + // Every public occurrence for a covered stream must be in the + // exact reviewed inventory, including ones irrelevant to this + // particular projection. + for event in history.iter().filter(|event| { + event.external_source().is_none() + && event.derivation().is_none() + && event.aggregate_type() == stream.0 + && event.aggregate_id() == stream.1 + }) { + if !witness.public.contains_key(event.id()) { + return Err(invalid("unwitnessed public occurrence in covered stream")); + } + } + continue; + } if let Some((expected, found)) = (1..) .zip(sequence.iter().copied()) .find(|(expected, found)| expected != found) diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs index c78d3a3d9..a6c32552a 100644 --- a/src/projection/source_snapshot_tests.rs +++ b/src/projection/source_snapshot_tests.rs @@ -720,6 +720,157 @@ async fn snapshot_rebuild_memory() { rebuild_matrix(&crate::InMemoryRepository::new()).await; } +#[tokio::test] +async fn snapshot_rebuild_original_private_log_coverage() { + use crate::projection::rebuild::{AggregateRebuildCoverage, SnapshotProjectionRebuild}; + let identity = crate::repository::StreamIdentity::new("snapshot-item", "a").unwrap(); + let first = event("a", 1, "old", false); + let third = event("a", 3, "current", false); + let history = [first.clone(), third.clone()]; + let mut records = Vec::new(); + for (sequence, name) in [ + (1, "snapshot.changed"), + (2, "snapshot.private"), + (3, "snapshot.changed"), + ] { + let mut record = crate::EventRecord::new(name, vec![sequence as u8], sequence); + record + .metadata + .insert("causation_id".into(), format!("cause-a-{sequence}")); + records.push(record); + } + let private = [("snapshot.private", 1)]; + let witness = + AggregateRebuildCoverage::from_retained_stream(&identity, 3, &records, &private, &history) + .unwrap(); + assert_eq!( + witness.source_digest(), + AggregateRebuildCoverage::from_retained_stream(&identity, 3, &records, &private, &history) + .unwrap() + .source_digest() + ); + let store = crate::InMemoryRepository::new(); + // This also exercises the original complete-prefix path and registers the + // physical owner; retain its existing rows/tombstone source versions. + rebuild_matrix(&store).await; + let projector = rebuild_projector(); + let fresh_store = crate::InMemoryRepository::new(); + let (_, binding) = projector.modeled[0].raw().unwrap(); + let physical = binding.physical_topology().unwrap(); + let compiled = CompiledProjectionTopology::from_modeled_binding( + ProjectorTopologyId::new(physical.version(), physical.name(), physical.digest()).unwrap(), + binding + .outputs() + .iter() + .map(|output| (output.model(), output.storage(), output.schema())), + ) + .unwrap(); + fresh_store + .register_projection_models(compiled.topology(), compiled.ownership()) + .await + .unwrap(); + assert!(SnapshotProjectionRebuild::begin(&fresh_store, &projector) + .await + .unwrap() + .from_complete_history(&history) + .is_err()); + let plan = SnapshotProjectionRebuild::begin(&fresh_store, &projector) + .await + .unwrap() + .from_complete_history_with_coverage(&history, &[witness.clone()]) + .unwrap(); + assert_eq!(plan.apply(&fresh_store).await.unwrap(), 1); + let read = SnapshotProjectionRebuild::begin(&fresh_store, &projector) + .await + .unwrap(); + let harness = Harness { + codec: read.context.compiled.codec(), + }; + assert_eq!( + harness + .read(&fresh_store, "a") + .await + .row + .unwrap() + .get("title"), + Some(&RowValue::String("current".into())) + ); + + for altered in [ + vec![first.clone()], + vec![first.clone(), event("a", 3, "altered", false)], + vec![ + first.clone(), + third.clone(), + event("a", 4, "unwitnessed", false), + ], + ] { + assert!(SnapshotProjectionRebuild::begin(&fresh_store, &projector) + .await + .unwrap() + .from_complete_history_with_coverage(&altered, &[witness.clone()]) + .is_err()); + } + // A witness for this stream cannot cover a missing prefix in another. + let mut mixed = history.to_vec(); + mixed.push(event("other", 2, "missing prefix", false)); + mixed.push(external_row("ledger", "external", 901, "sparse")); + assert!(SnapshotProjectionRebuild::begin(&fresh_store, &projector) + .await + .unwrap() + .from_complete_history_with_coverage(&mixed, &[witness]) + .is_err()); + let bad = |head, + records: &[crate::EventRecord], + private: &[(&str, u64)], + history: &[DomainEventOccurrence]| { + assert!(AggregateRebuildCoverage::from_retained_stream( + &identity, head, records, private, history + ) + .is_err()); + }; + bad(4, &records, &private, &history); // independently captured head, truncated export + bad(3, &records[..2], &private, &history); + bad(3, &records, &[], &history); // absence never declares a record private + bad(3, &records, &[("snapshot.private", 2)], &history); + bad(3, &records, &private, &[third]); // missing required publication + let mut multiple = history.to_vec(); + multiple.push(occurrence("a", 3, 1, "a", "second publication", false)); + bad(3, &records, &private, &multiple); + let duplicate = [history[0].clone(), history[0].clone(), history[1].clone()]; + assert!(AggregateRebuildCoverage::from_retained_stream( + &identity, 3, &records, &private, &duplicate + ) + .is_ok()); + bad( + 3, + &records, + &[("snapshot.changed", 1), ("snapshot.private", 1)], + &history, + ); + for index in [0, 2] { + let mut changed = records.clone(); + changed[index].event_name = "different.public.contract".into(); + bad(3, &changed, &private, &history); + changed = records.clone(); + changed[index].event_version += 1; + bad(3, &changed, &private, &history); + changed = records.clone(); + changed[index] + .metadata + .insert("causation_id".into(), "different-command".into()); + bad(3, &changed, &private, &history); + } + let other = crate::repository::StreamIdentity::new("snapshot-item", "wrong").unwrap(); + assert!(AggregateRebuildCoverage::from_retained_stream( + &other, 3, &records, &private, &history + ) + .is_err()); + let mut reordered = records.clone(); + reordered.swap(0, 1); + bad(3, &reordered, &private, &history); +} + #[tokio::test] async fn snapshot_rebuild_external_sparse_members_and_mixed_origins() { use crate::projection::rebuild::SnapshotProjectionRebuild; From 086745b4d9cb5a348bbfdc6891d4bf8a3bd07246 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 29 Sep 2026 21:49:18 -0500 Subject: [PATCH 116/484] fix: surface live execution failures instead of envelope errors A failed @live execution (e.g. a statement timeout while storage is unreachable) reached clients as an error-only frame with only the base envelope. The replica required snapshot/live metadata on every live frame with errors, so it replaced the real GraphQL error with "Invalid Distributed GraphQL protocol envelope at extensions.distributed.live". Spec (docs/live-query-delivery.md) now defines that frame as a terminal, receipt-only failure frame. The client surfaces its errors, admits no data, cursors, ownership or command receipts, and reopens the subscription with 1s-30s backoff so live queries recover without a reload. The server producer stops after its first error so a failure can never take a later frame's snapshot/live metadata. Data-bearing frames without live metadata remain invalid. Resolves [[incidents/forge-dashboard-protocol-20260929]] Co-Authored-By: Claude Opus 5.5 --- docs/gateway/live-sharing.md | 2 + docs/live-query-delivery.md | 41 +++ .../replica/distributed-replica/constants.ts | 3 + js/src/replica/distributed-replica/helpers.ts | 24 ++ .../distributed-replica/impl-fetch-live.ts | 78 +++++- js/src/replica/distributed-replica/impl.ts | 15 +- js/src/replica/distributed-replica/types.ts | 4 + js/tests/replica-protocol.test.mjs | 245 ++++++++++++++++++ src/graphql/subscribe.rs | 22 +- tests/graphql_query_protocol/main.rs | 126 +++++++++ 10 files changed, 546 insertions(+), 14 deletions(-) diff --git a/docs/gateway/live-sharing.md b/docs/gateway/live-sharing.md index 404f7bf58..531b281a1 100644 --- a/docs/gateway/live-sharing.md +++ b/docs/gateway/live-sharing.md @@ -37,6 +37,8 @@ If a slow consumer cannot preserve all evidence within its queue, it receives `LIVE_RESET_REQUIRED`; a blocked socket is closed so it must reconnect. No latest-value replacement silently discards confirmation proof. Group deadline, upstream loss and incomplete/invalid origin envelopes also require recovery. +An origin failure frame (an error-only live execution result) carries no evidence +and is not fanned out; the group's consumers receive `LIVE_RESET_REQUIRED`. Dropping a consumer releases only its lease. Last leave aborts the actual upstream stream, socket and origin change-feed receiver, including a pending origin SQL diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md index 78931e7af..3c584c8fd 100644 --- a/docs/live-query-delivery.md +++ b/docs/live-query-delivery.md @@ -12,6 +12,47 @@ Every live response declares `extensions.distributed.live.mode`: - `resumable`: a result with matching, nonempty index and cursor vectors. Existing resume validation, reset, replay and causal reconciliation rules apply. +A failed execution has no result and therefore no `live` metadata. It is sent +as the terminal failure frame described below. + +## Failed live executions + +A live execution that fails (for example a storage error or statement timeout) +has no result. The server sends exactly one **failure frame** and then completes +the operation. The failure ends that subscription: the server sends no more +frames for it and never attaches a later execution's metadata to the failure +frame. A failure frame has: + +- `data` that is `null` or absent; +- a nonempty `errors` array, where each entry is an object with a string + `message`; +- a valid base `extensions.distributed` envelope (`protocolVersion`, + `schemaHash`, `authorizationGeneration`, `cacheScope`, `operation`, and + `trustedPresets` when the surface has any), with no `snapshot`, `live` or + `command`. + +The client checks the envelope's binding, schema, operation and authorization +generation in the same way as for any other response. The failure frame then +works like an HTTP error response: it admits nothing. It writes no data or +membership, advances no cursor or operation generation, takes no ownership and +confirms no command. The client shows the original GraphQL errors for that +operation and keeps any previously admitted data readable. It closes the +failed stream. After a bounded backoff (1s, doubling to at most 30s), it opens +a fresh subscription for the operation's current watches. That subscription +resumes from the last admitted cursors, if there are any. The backoff resets +when an admitted frame arrives, and that frame also replaces the errors. This is +how a live query recovers after its storage comes back, without a page reload. +Disposing the last watch or ending the authorization generation cancels a +pending reopen. + +Only an error-only frame is a failure frame. A live frame that carries non-null +`data` (including partial data with errors) without both `snapshot` and `live` +is invalid, as are frames with `errors` that are absent, empty or malformed and +lack live metadata, and frames with a `snapshot` or `live` but not both. A +response without the `extensions.distributed` envelope is invalid as before. +Intermediaries that cannot relay a failure frame, such as shared gateway live +fan-out, end the consumer with `LIVE_RESET_REQUIRED` instead. + Snapshot delivery does not relax read permissions or invent causal evidence. Changes affecting only denied rows must not produce activity frames. A row leaving the authorized result disappears from that operation's membership; diff --git a/js/src/replica/distributed-replica/constants.ts b/js/src/replica/distributed-replica/constants.ts index 4bb101799..35cdaaabc 100644 --- a/js/src/replica/distributed-replica/constants.ts +++ b/js/src/replica/distributed-replica/constants.ts @@ -11,3 +11,6 @@ export const EMPTY_CACHE_SNAPSHOT = Object.freeze({ records: Object.freeze([]), indexes: Object.freeze([]) }); +/** Reopen backoff after a live failure frame (`docs/live-query-delivery.md`). */ +export const LIVE_FAILURE_RETRY_BASE_MS = 1_000; +export const LIVE_FAILURE_RETRY_MAX_MS = 30_000; diff --git a/js/src/replica/distributed-replica/helpers.ts b/js/src/replica/distributed-replica/helpers.ts index e67e19ce0..868aec65b 100644 --- a/js/src/replica/distributed-replica/helpers.ts +++ b/js/src/replica/distributed-replica/helpers.ts @@ -736,6 +736,30 @@ export function stableErrors( return deepEqual(current, next) ? current : freezeErrors(next); } +/** + * GraphQL payload of a live failure frame (`docs/live-query-delivery.md`): no + * result data and a nonempty list of errors that each carry a string message. + * Callers also require absent snapshot, live and command metadata. Partial + * data with errors is never a failure payload. + */ +export function isGraphqlFailurePayload(envelope: { + readonly data?: unknown; + readonly errors?: unknown; +}): envelope is { readonly data?: null; readonly errors: readonly GqlError[] } { + return ( + (envelope.data === undefined || envelope.data === null) && + Array.isArray(envelope.errors) && + envelope.errors.length > 0 && + envelope.errors.every( + (error: unknown) => + error !== null && + typeof error === 'object' && + !Array.isArray(error) && + typeof (error as { message?: unknown }).message === 'string' + ) + ); +} + export function graphqlError(error: unknown): GqlError { return Object.freeze({ message: error instanceof Error ? error.message : String(error), diff --git a/js/src/replica/distributed-replica/impl-fetch-live.ts b/js/src/replica/distributed-replica/impl-fetch-live.ts index 5211aeee4..e8ba4bbde 100644 --- a/js/src/replica/distributed-replica/impl-fetch-live.ts +++ b/js/src/replica/distributed-replica/impl-fetch-live.ts @@ -1,4 +1,4 @@ -import type { GraphqlVariables } from '../../types.js'; +import type { GqlError, GraphqlVariables } from '../../types.js'; import { type DistributedLiveCursor, type DistributedProtocolEnvelope @@ -10,8 +10,13 @@ import type { ReplicaTransport, ReplicaWriteSource } from '../types.js'; +import { + LIVE_FAILURE_RETRY_BASE_MS, + LIVE_FAILURE_RETRY_MAX_MS +} from './constants.js'; import { graphqlError, + isGraphqlFailurePayload, replicaClientRequestExtensions, stableErrors } from './helpers.js'; @@ -68,6 +73,7 @@ export function closeActiveTransports(host: FetchLiveHost): void { for (const [key, entry] of host.lives) { retireLiveProtocol(host, key); entry.active = false; + cancelLiveRetry(entry); try { entry.unsubscribe(); } catch { @@ -311,7 +317,7 @@ export function retainLive( return; } try { - host.writeCanonicalResult( + const distributed = host.writeCanonicalResult( watch.artifact, watch.variables, result, @@ -319,9 +325,19 @@ export function retainLive( undefined, projectionGeneration ); + // Accepted without a snapshot, an error-only frame is the + // receipt-only failure frame: it admitted nothing. + if ( + distributed.snapshot === undefined && + isGraphqlFailurePayload(result) + ) { + failLive(host, watch, entry, result.errors); + return; + } state.live = 'active'; entry.operationGeneration = host.operationGeneration(watch.key); + entry.failures = undefined; } catch (error) { state.live = 'error'; state.errors = stableErrors(state.errors, [graphqlError(error)]); @@ -433,6 +449,7 @@ export function restartLive(host: FetchLiveHost, key: string): void { const count = previous.count; retireLiveProtocol(host, key); previous.active = false; + cancelLiveRetry(previous); host.lives.delete(key); try { previous.unsubscribe(); @@ -473,12 +490,69 @@ export function releaseLive(host: FetchLiveHost, key: string): void { if (entry.count > 0) return; retireLiveProtocol(host, key); entry.active = false; + cancelLiveRetry(entry); host.lives.delete(key); entry.unsubscribe(); host.queryState(key).live = 'off'; host.emitState(key, false); } +/** + * Surface a live failure frame and close its terminal stream + * (`docs/live-query-delivery.md`). The frame was receipt-only: no data, + * cursor, operation generation or ownership changed. The inactive entry stays + * registered, as in fallbackFromLive, so ingestion's resumeLiveWatches cannot + * bypass the backoff; the timer reopens the operation's current watches. + */ +function failLive( + host: FetchLiveHost, + watch: ReplicaWatchState, + entry: LiveEntry, + errors: readonly GqlError[] +): void { + if (!entry.active || host.lives.get(watch.key) !== entry) return; + retireLiveProtocol(host, watch.key); + entry.active = false; + const unsubscribe = entry.unsubscribe; + entry.unsubscribe = () => undefined; + try { + unsubscribe(); + } catch { + // The failed stream is fenced; transport cleanup is best effort. + } + const failures = (entry.failures ?? 0) + 1; + entry.failures = failures; + const delay = Math.min( + LIVE_FAILURE_RETRY_BASE_MS * 2 ** Math.min(failures - 1, 30), + LIVE_FAILURE_RETRY_MAX_MS + ); + entry.retry = setTimeout(() => { + entry.retry = undefined; + if ( + host.lives.get(watch.key) !== entry || + entry.active || + entry.protocolGeneration !== host.protocolGenerationSequence() + ) { + return; + } + restartLive(host, watch.key); + const replacement = host.lives.get(watch.key); + if (replacement !== undefined && replacement !== entry) { + replacement.failures = failures; + } + }, delay); + const state = host.queryState(watch.key); + state.live = 'error'; + state.errors = stableErrors(state.errors, errors); + host.emitState(watch.key, false); +} + +function cancelLiveRetry(entry: LiveEntry): void { + if (entry.retry === undefined) return; + clearTimeout(entry.retry); + entry.retry = undefined; +} + /** * Mark protocol state as no longer backed by a live transport. The state is * retained for cache and hydration bookkeeping, but a later live stream may diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index 60c6ac38c..df2752ea0 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -140,6 +140,7 @@ import { indexKeyFromTarget, indexMaintenanceSnapshot, indexSemanticLayer, + isGraphqlFailurePayload, operationKey, prepareRecordEvidence, protocolOperationSource, @@ -1153,8 +1154,20 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { if (live !== undefined && snapshot === undefined) { protocolInvalid('extensions.distributed.snapshot'); } + // A failed live execution has no result: an error-only frame with only + // the base envelope. It is receipt-only, like an HTTP error response, + // and must not carry a command receipt or create stream state. + const liveFailure = + source === 'live' && + snapshot === undefined && + live === undefined && + isGraphqlFailurePayload(envelope); + if (liveFailure && distributed.command !== undefined) { + protocolInvalid('extensions.distributed.command'); + } if ( source === 'live' && + !liveFailure && (envelope.data !== undefined || envelope.errors !== undefined) && (snapshot === undefined || live === undefined) ) { @@ -1167,7 +1180,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { } const operationSource = protocolOperationSource(source); const operationState = - operation === undefined + operation === undefined || liveFailure ? undefined : this.#operationProtocol(key, operation, operationSource); if (snapshot === undefined || operationState === undefined) { diff --git a/js/src/replica/distributed-replica/types.ts b/js/src/replica/distributed-replica/types.ts index ebbcbefea..41998d425 100644 --- a/js/src/replica/distributed-replica/types.ts +++ b/js/src/replica/distributed-replica/types.ts @@ -33,6 +33,10 @@ export type LiveEntry = { /** Local fence for taking over query snapshots that preceded this stream. */ startRevision: string; operationGeneration?: number; + /** Consecutive failed live executions; drives the reopen backoff. */ + failures?: number; + /** Pending reopen of this inactive entry after a live failure frame. */ + retry?: ReturnType; }; export type ProtocolGeneration = { diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index 7b4c374bd..e71ef9cd4 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -2602,6 +2602,251 @@ test('terminal live errors close their stream and allow a later HTTP retry', asy assert.equal(unsubscribeCount, 2); }); +/** Error-only live failure frame: base envelope, no snapshot/live/command. */ +function liveFailureFrame(options = {}) { + return { + ...(options.omitData ? {} : { data: null }), + ...(options.omitErrors + ? {} + : { + errors: options.errors ?? [ + { + message: 'statement timeout', + path: ['todos'], + extensions: { code: 'TIMEOUT' } + } + ] + }), + ...(options.data === undefined ? {} : { data: options.data }), + extensions: { + distributed: { + protocolVersion: DISTRIBUTED_PROTOCOL_VERSION, + schemaHash: 'schema-a', + authorizationGeneration: 'auth-1', + cacheScope: 'cache:a', + operation: options.operation ?? 'live:todos', + ...options.distributed + } + } + }; +} + +function liveFailureHarness() { + const fetches = []; + const subscriptions = []; + let unsubscribeCount = 0; + const replica = createDistributedReplica({ + transport: { + fetch() { + let resolve; + const promise = new Promise((done) => { + resolve = done; + }); + fetches.push({ resolve }); + return promise; + }, + subscribe(request, observer) { + subscriptions.push({ request, observer }); + return () => { + unsubscribeCount += 1; + }; + } + } + }); + return { + replica, + fetches, + subscriptions, + unsubscribes: () => unsubscribeCount + }; +} + +test('live failure frames surface the GraphQL error, admit nothing, and reopen with backoff', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { replica, fetches, subscriptions, unsubscribes } = liveFailureHarness(); + const watch = replica.watch(Todos, {}, { live: true }); + await Promise.resolve(); + assert.equal(subscriptions.length, 1); + subscriptions[0].observer.next( + wireFrame({ + operation: 'live:todos', + position: '2', + rows: [{ id: 'todo-live', title: 'admitted before failure' }], + recordScope: 'record:live', + live: { mode: 'resumable', reset: true } + }) + ); + const admitted = [{ id: 'todo-live', title: 'admitted before failure' }]; + assert.deepEqual(watch.get().data.todos, admitted); + assert.deepEqual(watch.get().errors, []); + const fetchesBeforeFailure = fetches.length; + + subscriptions[0].observer.next(liveFailureFrame()); + assert.equal(watch.get().errors[0].message, 'statement timeout'); + assert.equal(watch.get().errors[0].extensions.code, 'TIMEOUT'); + assert.equal(watch.get().live, 'error'); + assert.deepEqual(watch.get().data.todos, admitted); + assert.deepEqual(replica.read(Todos, {}).data.todos, admitted); + // The failure is terminal: the stream is closed and the server's trailing + // complete neither falls back to HTTP nor reopens outside the backoff. + assert.equal(unsubscribes(), 1); + subscriptions[0].observer.complete(); + assert.equal(fetches.length, fetchesBeforeFailure); + assert.equal(watch.get().live, 'error'); + // Receipt-only ingestion (here a failing HTTP read) resumes live watches; + // the failed one keeps waiting for its backoff. + replica.writeResult( + Todos, + {}, + liveFailureFrame({ operation: 'query:todos' }), + 'network' + ); + assert.equal(subscriptions.length, 1); + assert.deepEqual(replica.read(Todos, {}).data.todos, admitted); + + t.mock.timers.tick(999); + assert.equal(subscriptions.length, 1); + t.mock.timers.tick(1); + assert.equal(subscriptions.length, 2); + // No cursor or ownership moved: the reopen resumes at the admitted cursor. + assert.deepEqual(subscriptions[1].request.resume, [ + { projection: 'todos-projector', position: '2', token: 'resume:2' } + ]); + assert.equal(watch.get().errors[0].message, 'statement timeout'); + + subscriptions[1].observer.next(liveFailureFrame({ omitData: true })); + assert.equal(unsubscribes(), 2); + t.mock.timers.tick(1999); + assert.equal(subscriptions.length, 2, 'consecutive failures double the backoff'); + t.mock.timers.tick(1); + assert.equal(subscriptions.length, 3); + + subscriptions[2].observer.next( + wireFrame({ + operation: 'live:todos', + position: '3', + rows: [{ id: 'todo-live', title: 'recovered' }], + recordScope: 'record:live', + live: { mode: 'resumable' } + }) + ); + assert.deepEqual(watch.get().errors, []); + assert.equal(watch.get().live, 'active'); + assert.deepEqual(watch.get().data.todos, [ + { id: 'todo-live', title: 'recovered' } + ]); + + subscriptions[2].observer.next(liveFailureFrame()); + t.mock.timers.tick(1000); + assert.equal(subscriptions.length, 4, 'an admitted frame resets the backoff'); + + subscriptions[3].observer.next(liveFailureFrame()); + watch.destroy(); + t.mock.timers.tick(30_000); + assert.equal(subscriptions.length, 4, 'disposing the last watch cancels the reopen'); +}); + +test('authorization invalidation cancels a pending live failure reopen', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { replica, subscriptions } = liveFailureHarness(); + const watch = replica.watch(Todos, {}, { live: true }); + await Promise.resolve(); + subscriptions[0].observer.next(liveFailureFrame()); + assert.equal(watch.get().errors[0].message, 'statement timeout'); + replica.invalidateAuthorization(); + t.mock.timers.tick(30_000); + assert.equal(subscriptions.length, 1); + watch.destroy(); +}); + +test('live frames that are not error-only failures stay strict and admit nothing', async () => { + const cases = [ + { + name: 'partial data with errors and no live metadata', + frame: liveFailureFrame({ + data: { todos: [{ id: 'todo-partial', title: 'partial' }] } + }), + path: 'extensions.distributed.live' + }, + { + name: 'data-bearing snapshot without live metadata', + frame: wireFrame({ + operation: 'live:todos', + position: '9', + rows: [{ id: 'todo-unscoped', title: 'unscoped' }] + }), + path: 'extensions.distributed.live' + }, + { + name: 'empty errors', + frame: liveFailureFrame({ errors: [] }), + path: 'extensions.distributed.live' + }, + { + name: 'null data without errors', + frame: liveFailureFrame({ omitErrors: true }), + path: 'extensions.distributed.live' + }, + { + name: 'errors without a string message', + frame: liveFailureFrame({ errors: [{ message: 42 }] }), + path: 'extensions.distributed.live' + }, + { + name: 'command receipt on a failure frame', + frame: liveFailureFrame({ + distributed: { command: commandReceipt() } + }), + path: 'extensions.distributed.command' + }, + { + name: 'failure frame for another operation', + frame: liveFailureFrame({ operation: 'live:todos-other' }), + path: 'extensions.distributed.operation' + }, + { + name: 'failure frame without the distributed envelope', + frame: { + data: null, + errors: [{ message: 'statement timeout' }] + }, + path: 'extensions.distributed' + } + ]; + for (const { name, frame, path } of cases) { + const { replica, fetches, subscriptions, unsubscribes } = + liveFailureHarness(); + const watch = replica.watch(Todos, {}, { live: true }); + await Promise.resolve(); + subscriptions[0].observer.next( + wireFrame({ + operation: 'live:todos', + position: '2', + rows: [{ id: 'todo-live', title: 'admitted' }], + recordScope: 'record:live', + live: { mode: 'resumable', reset: true } + }) + ); + const fetchCount = fetches.length; + subscriptions[0].observer.next(frame); + assert.equal(watch.get().live, 'error', name); + assert.equal( + watch.get().errors[0].message, + `Invalid Distributed GraphQL protocol envelope at ${path}`, + name + ); + assert.deepEqual( + replica.read(Todos, {}).data.todos, + [{ id: 'todo-live', title: 'admitted' }], + name + ); + assert.equal(unsubscribes(), 0, `${name}: not a terminal failure frame`); + assert.equal(fetches.length, fetchCount, name); + assert.equal(subscriptions.length, 1, name); + watch.destroy(); + } +}); + test('live advancement fences an overlapping refresh while a later clean refresh succeeds', async () => { const fetches = []; const subscriptions = []; diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index c4a9c9f0b..e800fbcf4 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -5,6 +5,13 @@ //! 2. Listens on [`ChangeHub`] (fed by `change_stream` / repo broadcast). //! 3. On dirty tables intersecting the plan footprint, debounces, re-executes, //! and yields only when the response hash changes (hash-gated push). +//! +//! A failed execution is terminal (`docs/live-query-delivery.md`): the producer +//! yields one error and stops. GraphQL ends the subscription on that error, and +//! the failure frame carries only the base protocol envelope. Protocol frame +//! metadata is a FIFO consumed by each emitted response, so producing another +//! frame after an error could let the error response take that later frame's +//! snapshot/live metadata. use std::collections::BTreeSet; use std::pin::Pin; @@ -201,14 +208,8 @@ pub(crate) async fn live_query_stream( continue; // hash gate: no push on no-change } if let Err(error) = executed.record_protocol_metadata(protocol.as_ref()) { - if tx - .send(Err(async_graphql::Error::new(error))) - .await - .is_err() - { - return; - } - continue; + let _ = tx.send(Err(async_graphql::Error::new(error))).await; + return; } last_hash = Some(executed.hash); if tx.send(Ok(executed.value)).await.is_err() { @@ -216,9 +217,8 @@ pub(crate) async fn live_query_stream( } } Err(e) => { - if tx.send(Err(async_graphql::Error::new(e))).await.is_err() { - return; - } + let _ = tx.send(Err(async_graphql::Error::new(e))).await; + return; } } } diff --git a/tests/graphql_query_protocol/main.rs b/tests/graphql_query_protocol/main.rs index 85378dafc..7aede5674 100644 --- a/tests/graphql_query_protocol/main.rs +++ b/tests/graphql_query_protocol/main.rs @@ -949,6 +949,132 @@ async fn live_subscription_frames_keep_data_and_metadata_in_fifo_order() { ); } +async fn rename_causal_table(repository: &SqliteRepository, from: &str, to: &str) { + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {from} RENAME TO {to}" + ))) + .execute(repository.pool()) + .await + .expect("rename live read-model table"); +} + +/// A failure frame is error-only, carries the valid base envelope, and has no +/// snapshot, live or command metadata (`docs/live-query-delivery.md`). +fn assert_live_failure_frame(response: async_graphql::Response) { + assert!(response.is_err(), "expected a failed live execution"); + let response = serde_json::to_value(response).expect("GraphQL wire response"); + assert!( + response.get("data").is_none_or(Value::is_null), + "a failure frame carries no result data: {response}" + ); + let errors = response["errors"].as_array().expect("failure errors"); + assert!(!errors.is_empty(), "{response}"); + assert!( + errors.iter().all(|error| error["message"] + .as_str() + .is_some_and(|message| !message.is_empty())), + "{response}" + ); + let distributed = distributed_envelope(&response); + assert_eq!(distributed["protocolVersion"], 1, "{response}"); + for field in [ + "schemaHash", + "authorizationGeneration", + "cacheScope", + "operation", + ] { + assert!( + distributed[field] + .as_str() + .is_some_and(|value| !value.is_empty()), + "failure frame base envelope requires `{field}`: {response}" + ); + } + assert!( + distributed + .get("trustedPresets") + .is_none_or(Value::is_array), + "{response}" + ); + for field in ["snapshot", "live", "command"] { + assert!( + distributed.get(field).is_none(), + "failure frame must not carry `{field}`: {response}" + ); + } +} + +async fn assert_stream_ended(stream: &mut BoxStream<'static, async_graphql::Response>) { + let next = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .expect("a failed live subscription must complete"); + assert!( + next.is_none(), + "a failure frame is terminal; unexpected frame: {:?}", + next.map(serde_json::to_value) + ); +} + +#[tokio::test] +async fn live_subscription_initial_failure_is_one_terminal_error_only_frame() { + let fixture = protocol_fixture_with_rows().await; + rename_causal_table( + &fixture.repository, + "causal_query_views", + "causal_query_views_offline", + ) + .await; + let mut stream = fixture + .engine + .execute_stream(&user_session(), Request::new(LIVE_SUBSCRIPTION)); + + let failure = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .expect("timeout waiting for failure frame") + .expect("a failed live execution still emits one frame"); + assert_live_failure_frame(failure); + assert_stream_ended(&mut stream).await; +} + +#[tokio::test] +async fn live_subscription_refresh_failure_is_terminal_and_never_takes_later_metadata() { + let fixture = protocol_fixture_with_rows().await; + let mut stream = fixture + .engine + .execute_stream(&user_session(), Request::new(LIVE_SUBSCRIPTION)); + let first = next_wire_frame(&mut stream).await; + assert_live_frame(&first, "causal_query_views", "causal row", "1", false); + + rename_causal_table( + &fixture.repository, + "causal_query_views", + "causal_query_views_offline", + ) + .await; + fixture + .repository + .publish_read_model_change(distributed::ReadModelChange::new(["causal_query_views"])); + // Leave the failure unconsumed while storage recovers and a new projection + // commits. A producer that kept running would enqueue that result's + // snapshot/live metadata ahead of the failure response's envelope. + tokio::time::sleep(Duration::from_millis(400)).await; + rename_causal_table( + &fixture.repository, + "causal_query_views_offline", + "causal_query_views", + ) + .await; + project_item(&fixture.repository, &fixture.bus, 2, "causal row 2").await; + tokio::time::sleep(Duration::from_millis(400)).await; + + let failure = tokio::time::timeout(Duration::from_secs(2), stream.next()) + .await + .expect("timeout waiting for failure frame") + .expect("the refresh failure is delivered"); + assert_live_failure_frame(failure); + assert_stream_ended(&mut stream).await; +} + #[tokio::test] async fn live_subscription_replays_delete_tombstone_and_observation() { let fixture = protocol_fixture_with_rows().await; From ca697613f8c0dd59e9b9bbb462fb07937c78e2de Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 30 Sep 2026 01:31:09 -0500 Subject: [PATCH 117/484] feat: add consumer delivery lanes and NATS retry backoff A single sequential event consumer ran every route for a delivery before receiving the next, so latency-sensitive process policies waited 1-4s behind unrelated projections and kernel effects. A permanently failing message NAK'd without delay was redelivered ~6/s between every new message. - Opt-in delivery lanes (`Service::lane`) within one durable consumer: each lane runs deliveries in broker order; a delivery is acknowledged only after every lane settles it; bounded in-flight window. Sources that settle only in order (Kafka, SQL) keep the sequential loop. - Retryable NATS NAKs back off by delivery count (50ms doubling to 5s, configurable), so a failing message cannot monopolize a consumer. Spec: docs/consumer-delivery-lanes.md (incl. cross-delivery reordering constraints). Tests: lane unit tests, service lane tests, NATS integration tests (publish-after-idle, backoff, lanes over JetStream). Implements [[tasks/forge-provisioning-latency-20260930]] Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- docs/consumer-delivery-lanes.md | 99 +++++ docs/reloading-event-delivery.md | 6 +- src/bus/mod.rs | 9 +- src/bus/nats.rs | 107 ++++- src/bus/nats_bus.rs | 13 +- src/bus/router.rs | 77 ++++ src/bus/run_options.rs | 15 + src/bus/runner/lane_tests.rs | 548 ++++++++++++++++++++++++ src/bus/runner/mod.rs | 2 + src/bus/runner/receive_loop.rs | 686 ++++++++++++++++++++++++------- src/bus/source.rs | 11 + src/microsvc/message_router.rs | 22 +- src/microsvc/mod.rs | 2 +- src/microsvc/service/mod.rs | 2 +- src/microsvc/service/runtime.rs | 122 +++++- src/microsvc/service/tests.rs | 96 +++++ tests/nats_transport/main.rs | 222 ++++++++++ 18 files changed, 1867 insertions(+), 183 deletions(-) create mode 100644 docs/consumer-delivery-lanes.md create mode 100644 src/bus/runner/lane_tests.rs diff --git a/README.md b/README.md index 77a2476b6..59a79bdde 100644 --- a/README.md +++ b/README.md @@ -1539,7 +1539,16 @@ bus.listen( ``` Retryable failures (e.g. transient `NotFound`) are nacked for redelivery; the runner -never silently acks a handler error. +never silently acks a handler error. NATS JetStream NAKs back off by delivery count +(50 ms doubling to 5 s by default) so a repeatedly failing message cannot monopolize +a consumer; retries stay unlimited. A deterministic, durably recorded rejection is a +permanent error, not a retryable one. + +A service can place independent route bundles in named delivery lanes +(`Service::lane(name, routes)`). Each lane keeps broker order and runs +concurrently with the others, and a delivery is settled only after every lane +finished it. See [consumer delivery lanes](docs/consumer-delivery-lanes.md) for +the contract and when a route may leave the default lane. ### Transport boundaries (producer vs consumer) diff --git a/docs/consumer-delivery-lanes.md b/docs/consumer-delivery-lanes.md new file mode 100644 index 000000000..94878d7e6 --- /dev/null +++ b/docs/consumer-delivery-lanes.md @@ -0,0 +1,99 @@ +# Consumer delivery lanes and retry backoff + +One durable consumer (`listen`/`subscribe` group) delivers messages in broker +order and, by default, runs every registered route for a message before it +receives the next one. That is the simplest ordering contract, but it couples +latency across unrelated work: a process-manager policy that only turns a fact +into the next idempotent command waits behind every projection and slow +external effect registered for earlier messages. It also lets one message +that keeps failing monopolize the consumer. + +## Retry backoff for retryable failures + +A retryable failure NAKs the delivery so the broker redelivers it later. On +NATS JetStream the NAK carries a delay derived from the delivery count: +`base * 2^(delivered - 1)`, capped (defaults 50 ms and 5 s; +`NatsBus::with_nack_backoff` / `NatsJetStreamSource::with_nack_backoff`). +The first retry is still prompt. A message that fails every time stops +being redelivered ahead of newer messages in a hot loop. Retries remain +unlimited and the message is still retained; only the redelivery time moves. +Setting the base to zero restores an immediate NAK. + +This is not a substitute for classifying failures correctly. A command +rejection that is durably recorded under a deterministic command identity +replays the same rejection on every retry. The handler must return a +permanent error, which the configured failure policy (dead-letter by default) +settles and records in transport metrics. Transient infrastructure failures +stay retryable. + +## Lanes + +A router may partition its routes into named **lanes**. `Service::lane(name, +routes)` registers a route bundle in a lane. Plain `Service::routes` uses the +default lane. Lanes are opt-in. A service that registers no named lane runs +exactly as before. + +When a router has more than one lane and the source settles each delivery +independently (`MessageSource::settles_independently`, true for NATS +JetStream), the runner: + +1. receives messages in broker order and hands each one to every lane that + has a route for it; +2. runs each lane's messages strictly in receive order, one at a time, with + the lane's routes in registration order. This is the same order a + single-lane consumer gives those routes; +3. runs different lanes concurrently, so a slow route in one lane cannot delay + another lane; +4. settles a delivery only after every lane that received it has finished it. + Any retryable lane failure NAKs the delivery, and redelivery runs all of its + lanes again. A permanent failure applies the failure policy once; +5. bounds the number of received but unsettled deliveries + (`RunOptions::with_lane_window`, default 16). When the window is full the + runner stops receiving until a delivery settles; +6. stops a lane at its first stop-class failure (`FailurePolicy::Stop` or a + retain-and-stop error such as `ApplicationReloading`). That delivery is + settled as in sequential mode. Later deliveries queued for the halted lane + are NAKed, not skipped. Other in-flight deliveries finish and settle, then + the run returns the error. + +The default lane keeps its existing behavior, including route-order +dependencies between its routes within one delivery. + +Sources whose acknowledgement is positional (Kafka offset commits) or +lease-based (SQL table rows) report `settles_independently() == false`. For +them the runner keeps the sequential loop and dispatches every lane's routes +in order for each message. Lanes then change nothing about delivery. + +### What a lane must satisfy + +Put a route bundle in its own lane only when **no route in another lane +depends on its effects within the same delivery, and it depends on none of +theirs**. Typical examples are process-manager policies that read only the +delivered fact and send idempotent commands. A route that reads a projection +written by an earlier route for the same message must stay in that route's +lane. + +Lanes also reorder effects **across deliveries**: one lane may finish later +messages while another lane is still working on earlier ones. A route whose +correctness (or whose downstream readers' correctness) needs another lane's +effects from an *earlier* message — for example, a process policy that +completes a workflow the UI then reads through a projection maintained in +another lane — must share that lane, or its readers must tolerate the +projection arriving later. Forge hit this: provisioning completed before the +read-access projection existed, producing transient 404s, until the +derivation moved into the process lane. + +Lanes do not weaken existing guarantees: + +- **Ordering:** each lane observes deliveries in broker order. A redelivery + (after NAK or ack-wait expiry) can arrive after later messages. That is + already true for a single-lane consumer. +- **At-least-once:** a delivery is acknowledged only after all of its lanes + succeeded. A crash or failure before that redelivers it to every lane, so + every route must stay idempotent, as today. +- **Failure policy and DLQ:** unchanged, applied once per delivery after all + lanes finish. +- **Ack deadline:** a delivery waiting in a busy lane still counts against the + broker's ack wait. Keep the window small enough that a lane's backlog clears + well within it. An expired delivery is redelivered, which is safe under the + idempotency requirement. diff --git a/docs/reloading-event-delivery.md b/docs/reloading-event-delivery.md index 0bd61ce9b..c22c35ddf 100644 --- a/docs/reloading-event-delivery.md +++ b/docs/reloading-event-delivery.md @@ -9,5 +9,7 @@ ordinary permanent-failure policy. After activation the same delivery can run. Business validation/authorization failures retain their existing permanent classification and configured settlement policy. No gate bypass or implicit -success is introduced. This does not change general infrastructure NAK delay; -hosts/brokers still own retry timing for other transport outages. +success is introduced. The NAK uses the transport's ordinary retry spacing +(NATS JetStream: delivery-count backoff, see +[consumer delivery lanes and retry backoff](consumer-delivery-lanes.md)); the +gate adds no delay of its own. diff --git a/src/bus/mod.rs b/src/bus/mod.rs index 07ca9d09a..c6d1b4bad 100644 --- a/src/bus/mod.rs +++ b/src/bus/mod.rs @@ -130,7 +130,10 @@ pub use knative::knative_triggers; #[cfg(feature = "http")] pub use knative_bus::KnativeBus; #[cfg(feature = "nats")] -pub use nats::{NatsJetStreamSource, NatsPublisher, NatsReceived}; +pub use nats::{ + NackBackoff, NatsJetStreamSource, NatsPublisher, NatsReceived, DEFAULT_NACK_BACKOFF_BASE, + DEFAULT_NACK_BACKOFF_MAX, +}; #[cfg(feature = "nats")] pub use nats_bus::{NatsBus, NatsBusConnect}; #[cfg(feature = "rabbitmq")] @@ -162,8 +165,8 @@ pub use ordered_delivery::OrderedDelivery; #[cfg(feature = "postgres")] pub use postgres_bus::{LogReceived, PostgresBus, QueueReceived}; pub use publisher::MessagePublisher; -pub use router::MessageRouter; -pub use run_options::{ConsumerDeliveryMode, InboxHook, NoInbox, RunOptions}; +pub use router::{LaneSet, MessageRouter}; +pub use run_options::{ConsumerDeliveryMode, InboxHook, NoInbox, RunOptions, DEFAULT_LANE_WINDOW}; pub use runner::run_source; pub use source::{MessageSource, ReceivedMessage}; #[cfg(feature = "sqlite")] diff --git a/src/bus/nats.rs b/src/bus/nats.rs index 814400344..ceebfd21e 100644 --- a/src/bus/nats.rs +++ b/src/bus/nats.rs @@ -3,8 +3,8 @@ //! Maps the canonical [`Message`] onto NATS JetStream: [`NatsPublisher`] publishes //! to a subject (waiting for the JetStream publish ack — the durable publish //! threshold), and [`NatsJetStreamSource`] pulls from a durable consumer and -//! settles via JetStream ack semantics (ack→`Ack`, nack→`Nak`, dead-letter/park→ -//! `Term`). Aggregate message IDs use `Nats-Msg-Id` unchanged. External facts +//! settles via JetStream ack semantics (ack→`Ack`, nack→`Nak` with a +//! delivery-count [`NackBackoff`] delay, dead-letter/park→`Term`). Aggregate message IDs use `Nats-Msg-Id` unchanged. External facts //! retain their logical source identity separately; their broker dedup ID also //! binds content so altered retries reach the durable conflict fence. //! @@ -260,12 +260,65 @@ impl MessagePublisher for NatsPublisher { } } +/// Default first delay for a retryable NAK; doubles per delivery attempt. +pub const DEFAULT_NACK_BACKOFF_BASE: Duration = Duration::from_millis(50); +/// Default ceiling for a retryable NAK delay. +pub const DEFAULT_NACK_BACKOFF_MAX: Duration = Duration::from_secs(5); + +/// Redelivery delay requested with a retryable NAK. +/// +/// `base * 2^(delivered - 1)`, capped at `max`. A zero `base` requests +/// immediate redelivery (the broker's own policy). Retries stay unlimited; +/// only their spacing changes, so one failing delivery cannot monopolize a +/// consumer ahead of newer messages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NackBackoff { + base: Duration, + max: Duration, +} + +impl NackBackoff { + /// Backoff starting at `base` and capped at `max` (at least `base`). + pub fn new(base: Duration, max: Duration) -> Self { + Self { + base, + max: max.max(base), + } + } + + /// Immediate NAK without a delay. + pub fn immediate() -> Self { + Self::new(Duration::ZERO, Duration::ZERO) + } + + /// Delay for a delivery that has been delivered `delivered` times (1-based). + pub fn delay(&self, delivered: u64) -> Option { + if self.base.is_zero() { + return None; + } + let doublings = delivered.saturating_sub(1).min(30) as u32; + Some( + self.base + .checked_mul(1u32 << doublings) + .unwrap_or(self.max) + .min(self.max), + ) + } +} + +impl Default for NackBackoff { + fn default() -> Self { + Self::new(DEFAULT_NACK_BACKOFF_BASE, DEFAULT_NACK_BACKOFF_MAX) + } +} + /// A pull-based JetStream source bound to a durable consumer. pub struct NatsJetStreamSource { consumer: Consumer, fetch_timeout: Duration, strip_prefix: Option, idle_poll: Duration, + nack_backoff: NackBackoff, } impl NatsJetStreamSource { @@ -276,9 +329,16 @@ impl NatsJetStreamSource { fetch_timeout: Duration::from_millis(500), strip_prefix: None, idle_poll: Duration::ZERO, + nack_backoff: NackBackoff::default(), } } + /// Space retryable NAK redeliveries (see [`NackBackoff`]). + pub fn with_nack_backoff(mut self, backoff: NackBackoff) -> Self { + self.nack_backoff = backoff; + self + } + /// How long `recv` waits for a message before returning `Ok(None)`. pub fn with_fetch_timeout(mut self, timeout: Duration) -> Self { self.fetch_timeout = timeout; @@ -355,6 +415,11 @@ impl MessageSource for NatsJetStreamSource { "nats" } + fn settles_independently(&self) -> bool { + // JetStream explicit acks settle each delivery by its own reply subject. + true + } + async fn recv(&mut self) -> Result, TransportError> { loop { let mut batch = self @@ -372,7 +437,7 @@ impl MessageSource for NatsJetStreamSource { // the supervisor's permanent-error policy. The durable delivery is // retained for operator repair; no later cursor is falsely sealed. return NatsReceived::from_jetstream(message, self.strip_prefix.as_deref()) - .map(Some); + .map(|received| Some(received.with_nack_backoff(self.nack_backoff))); } Some(Err(err)) => return Err(retryable("nats batch message", err)), None if self.idle_poll.is_zero() => return Ok(None), @@ -387,6 +452,7 @@ pub struct NatsReceived { raw: jetstream::Message, message: Message, ordered: Option, + nack_backoff: NackBackoff, } impl NatsReceived { @@ -402,9 +468,23 @@ impl NatsReceived { raw, message, ordered, + nack_backoff: NackBackoff::default(), }) } + fn with_nack_backoff(mut self, backoff: NackBackoff) -> Self { + self.nack_backoff = backoff; + self + } + + /// Delivery attempt count reported by JetStream (1 for the first delivery). + fn delivered(&self) -> u64 { + self.raw + .info() + .map(|info| u64::try_from(info.delivered).unwrap_or(1)) + .unwrap_or(1) + } + async fn settle(self, kind: AckKind) -> Result<(), TransportError> { match kind { AckKind::Ack => self @@ -461,8 +541,10 @@ impl ReceivedMessage for NatsReceived { } async fn nack(self, _reason: &str) -> Result<(), TransportError> { - // Nak with no delay: JetStream redelivers per the consumer policy. - self.settle(AckKind::Nak(None)).await + // Redeliver after a delivery-count backoff so a message that keeps + // failing cannot be redelivered ahead of newer messages in a hot loop. + let delay = self.nack_backoff.delay(self.delivered()); + self.settle(AckKind::Nak(delay)).await } async fn dead_letter(self, _reason: &str) -> Result<(), TransportError> { @@ -588,6 +670,21 @@ mod tests { } } + #[test] + fn nack_backoff_doubles_from_base_and_caps() { + let backoff = NackBackoff::default(); + assert_eq!(backoff.delay(1), Some(Duration::from_millis(50))); + assert_eq!(backoff.delay(2), Some(Duration::from_millis(100))); + assert_eq!(backoff.delay(4), Some(Duration::from_millis(400))); + assert_eq!(backoff.delay(8), Some(Duration::from_secs(5))); + assert_eq!(backoff.delay(u64::MAX), Some(Duration::from_secs(5))); + // Delivery counts from a broker that never reports one still back off. + assert_eq!(backoff.delay(0), Some(Duration::from_millis(50))); + assert_eq!(NackBackoff::immediate().delay(9), None); + let custom = NackBackoff::new(Duration::from_millis(10), Duration::from_millis(5)); + assert_eq!(custom.delay(3), Some(Duration::from_millis(10))); + } + #[test] fn content_type_selection_removes_every_case_variant() { let mut message = Message::new("example.recorded", MessageKind::Event, Vec::new()) diff --git a/src/bus/nats_bus.rs b/src/bus/nats_bus.rs index 2f37a08a3..67999d174 100644 --- a/src/bus/nats_bus.rs +++ b/src/bus/nats_bus.rs @@ -31,7 +31,7 @@ use async_nats::jetstream; use async_nats::jetstream::consumer::pull::Config as PullConfig; use async_nats::jetstream::stream::{Config as StreamConfig, Stream}; -use super::nats::{NatsJetStreamSource, NatsPublisher}; +use super::nats::{NackBackoff, NatsJetStreamSource, NatsPublisher}; use super::{ retryable, run_source, Bus, BusConsumer, BusTopologyConfig, MessagePublisher, MessageRouter, RunOptions, TransportError, @@ -49,6 +49,7 @@ pub struct NatsBus { topology: BusTopologyConfig, fetch_timeout: Duration, idle_poll: Duration, + nack_backoff: NackBackoff, } /// Awaitable builder returned by [`NatsBus::connect`]. @@ -113,6 +114,7 @@ impl NatsBus { topology: BusTopologyConfig::default(), fetch_timeout: DEFAULT_FETCH_TIMEOUT, idle_poll: Duration::ZERO, + nack_backoff: NackBackoff::default(), } } @@ -175,6 +177,12 @@ impl NatsBus { self } + /// Space retryable NAK redeliveries for `listen`/`subscribe` sources. + pub fn with_nack_backoff(mut self, backoff: NackBackoff) -> Self { + self.nack_backoff = backoff; + self + } + /// Sanitize the group into a valid NATS consumer-name token. Consumer names /// cannot contain `.`, `*`, `>`, or whitespace, so map them to `_`. fn durable_base(group: &str) -> String { @@ -365,7 +373,8 @@ impl NatsBus { Ok(NatsJetStreamSource::new(consumer) .with_fetch_timeout(self.fetch_timeout) .with_strip_prefix(strip_prefix) - .with_idle_poll(self.idle_poll)) + .with_idle_poll(self.idle_poll) + .with_nack_backoff(self.nack_backoff)) } /// Shared consume path for `listen` (commands) and `subscribe` (events): diff --git a/src/bus/router.rs b/src/bus/router.rs index 0ad35dd94..78df6b245 100644 --- a/src/bus/router.rs +++ b/src/bus/router.rs @@ -61,4 +61,81 @@ pub trait MessageRouter: Send + Sync { ) -> impl Future> + Send { self.dispatch(message) } + + /// Number of independent delivery lanes (at least 1). + /// + /// Lanes are opt-in route groups that a receive loop may run concurrently + /// while each lane keeps delivery order. See + /// `docs/consumer-delivery-lanes.md`. The default single lane preserves the + /// sequential contract. + fn delivery_lanes(&self) -> usize { + 1 + } + + /// Lanes that have a handler for `(kind, name)`. Empty means unhandled. + fn lanes_for(&self, kind: MessageKind, name: &str) -> LaneSet { + if self.handles(kind, name) { + LaneSet::single(0) + } else { + LaneSet::EMPTY + } + } + + /// Run only the routes of `lane` for one delivered message. + /// + /// Routers that report more than one lane must override this. The default + /// is correct only for the single default lane. + fn dispatch_lane( + &self, + message: &Message, + ordered: Option<&OrderedDelivery>, + _lane: usize, + ) -> impl Future> + Send { + self.dispatch_ordered(message, ordered) + } +} + +/// A set of delivery lane indexes (at most [`LaneSet::MAX_LANES`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct LaneSet(u64); + +impl LaneSet { + /// Highest supported number of lanes for one router. + pub const MAX_LANES: usize = 64; + /// No lanes: the router does not handle the message. + pub const EMPTY: Self = Self(0); + + /// A set containing only `lane`. + pub fn single(lane: usize) -> Self { + Self::EMPTY.with(lane) + } + + /// Add `lane` to the set. + /// + /// # Panics + /// When `lane >= MAX_LANES`. + pub fn with(self, lane: usize) -> Self { + assert!(lane < Self::MAX_LANES, "delivery lane index out of range"); + Self(self.0 | (1 << lane)) + } + + /// Whether the set is empty. + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// Number of lanes in the set. + pub fn len(self) -> usize { + self.0.count_ones() as usize + } + + /// Whether `lane` is in the set. + pub fn contains(self, lane: usize) -> bool { + lane < Self::MAX_LANES && self.0 & (1 << lane) != 0 + } + + /// Lane indexes in ascending order. + pub fn iter(self) -> impl Iterator { + (0..Self::MAX_LANES).filter(move |lane| self.contains(*lane)) + } } diff --git a/src/bus/run_options.rs b/src/bus/run_options.rs index 2a98ae450..3ed4e58ad 100644 --- a/src/bus/run_options.rs +++ b/src/bus/run_options.rs @@ -70,14 +70,21 @@ pub struct RunOptions { pub delivery_mode: ConsumerDeliveryMode, /// What the runner does with a permanent handler/transport failure. pub failure_policy: FailurePolicy, + /// Maximum received-but-unsettled deliveries when a router runs several + /// delivery lanes concurrently. Ignored for single-lane routers. + pub lane_window: usize, } +/// Default bound on unsettled deliveries for a multi-lane run. +pub const DEFAULT_LANE_WINDOW: usize = 16; + impl Default for RunOptions { /// Idempotent delivery with the default [`FailurePolicy`]. fn default() -> Self { Self { delivery_mode: ConsumerDeliveryMode::default(), failure_policy: FailurePolicy::default(), + lane_window: DEFAULT_LANE_WINDOW, } } } @@ -98,6 +105,7 @@ impl RunOptions { Self { delivery_mode: ConsumerDeliveryMode::Inbox(hook), failure_policy: FailurePolicy::default(), + lane_window: DEFAULT_LANE_WINDOW, } } @@ -107,6 +115,13 @@ impl RunOptions { self } + /// Bound the received-but-unsettled deliveries of a multi-lane run. + /// Values below 1 are raised to 1. + pub fn with_lane_window(mut self, window: usize) -> Self { + self.lane_window = window.max(1); + self + } + /// Whether this run dispatches directly without an inbox. pub fn is_idempotent(&self) -> bool { matches!(self.delivery_mode, ConsumerDeliveryMode::Idempotent) diff --git a/src/bus/runner/lane_tests.rs b/src/bus/runner/lane_tests.rs new file mode 100644 index 000000000..e81faba11 --- /dev/null +++ b/src/bus/runner/lane_tests.rs @@ -0,0 +1,548 @@ +//! Delivery-lane runner contract (`docs/consumer-delivery-lanes.md`). +//! +//! Runtime-free like the sequential runner tests: a busy-poll executor with a +//! no-op waker. Gated handlers wake themselves so `FuturesUnordered` re-polls +//! them, and `block_on` fails after a bounded number of polls instead of +//! hanging, so a lane that is blocked behind another lane is a test failure. +use super::run_source; +use crate::bus::source::{MessageSource, ReceivedMessage}; +use crate::bus::{ + FailurePolicy, LaneSet, Message, MessageKind, MessageRouter, RunOptions, TransportError, +}; +use std::collections::VecDeque; +use std::future::{poll_fn, Future}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::Poll; + +const POLL_LIMIT: usize = 200_000; + +fn block_on(future: F) -> F::Output { + use std::ptr; + use std::task::{Context, RawWaker, RawWakerVTable, Waker}; + + const VTABLE: RawWakerVTable = RawWakerVTable::new( + |_| RawWaker::new(ptr::null(), &VTABLE), + |_| {}, + |_| {}, + |_| {}, + ); + let waker = unsafe { Waker::from_raw(RawWaker::new(ptr::null(), &VTABLE)) }; + let mut cx = Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + for _ in 0..POLL_LIMIT { + if let Poll::Ready(output) = future.as_mut().poll(&mut cx) { + return output; + } + } + panic!("runner made no progress: a lane is blocked behind another lane"); +} + +/// Resolve once `ready` returns true, yielding (and self-waking) until then. +async fn wait_until(ready: impl Fn() -> bool) { + poll_fn(|cx| { + if ready() { + Poll::Ready(()) + } else { + cx.waker().wake_by_ref(); + Poll::Pending + } + }) + .await +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Event { + Received(String), + Ran(usize, String), + Ack(String), + Nack(String), + DeadLetter(String), +} + +#[derive(Default)] +struct Log(Mutex>); + +impl Log { + fn push(&self, event: Event) { + self.0.lock().unwrap().push(event); + } + fn events(&self) -> Vec { + self.0.lock().unwrap().clone() + } + fn ran(&self, lane: usize) -> Vec { + self.events() + .into_iter() + .filter_map(|event| match event { + Event::Ran(l, id) if l == lane => Some(id), + _ => None, + }) + .collect() + } + fn position(&self, wanted: &Event) -> usize { + self.events() + .iter() + .position(|event| event == wanted) + .unwrap_or_else(|| panic!("missing {wanted:?} in {:?}", self.events())) + } +} + +struct Received { + message: Message, + log: Arc, + unsettled: Arc, +} + +impl Received { + fn id(&self) -> String { + self.message.id().unwrap().to_owned() + } + fn settle(self, event: Event) -> Result<(), TransportError> { + self.unsettled.fetch_sub(1, Ordering::SeqCst); + self.log.push(event); + Ok(()) + } +} + +impl ReceivedMessage for Received { + fn message(&self) -> &Message { + &self.message + } + async fn ack(self) -> Result<(), TransportError> { + let id = self.id(); + self.settle(Event::Ack(id)) + } + async fn nack(self, _reason: &str) -> Result<(), TransportError> { + let id = self.id(); + self.settle(Event::Nack(id)) + } + async fn dead_letter(self, _reason: &str) -> Result<(), TransportError> { + let id = self.id(); + self.settle(Event::DeadLetter(id)) + } +} + +struct Source { + queue: VecDeque, + log: Arc, + independent: bool, + unsettled: Arc, + max_unsettled: Arc, +} + +impl MessageSource for Source { + type Received = Received; + + fn settles_independently(&self) -> bool { + self.independent + } + + async fn recv(&mut self) -> Result, TransportError> { + let Some(message) = self.queue.pop_front() else { + return Ok(None); + }; + let unsettled = self.unsettled.fetch_add(1, Ordering::SeqCst) + 1; + self.max_unsettled.fetch_max(unsettled, Ordering::SeqCst); + self.log + .push(Event::Received(message.id().unwrap().to_owned())); + Ok(Some(Received { + message, + log: self.log.clone(), + unsettled: self.unsettled.clone(), + })) + } +} + +type Behavior = Arc Result<(), TransportError> + Send + Sync>; +type Gate = Arc bool + Send + Sync>; + +/// Lane 0 = "projection" (default), lane 1 = "process". Every message named +/// `both` reaches both lanes; `process.only` reaches lane 1; `unhandled` none. +struct LaneRouter { + log: Arc, + behavior: Behavior, + gate: Gate, +} + +impl MessageRouter for LaneRouter { + fn consumer_group(&self) -> Option<&str> { + Some("lane-test") + } + fn handles(&self, kind: MessageKind, name: &str) -> bool { + !self.lanes_for(kind, name).is_empty() + } + fn subscription_plan(&self) -> crate::bus::SubscriptionPlan { + crate::bus::SubscriptionPlan::default() + } + async fn dispatch(&self, message: &Message) -> Result<(), TransportError> { + for lane in self.lanes_for(message.kind, message.name()).iter() { + self.dispatch_lane(message, None, lane).await?; + } + Ok(()) + } + fn delivery_lanes(&self) -> usize { + 2 + } + fn lanes_for(&self, _kind: MessageKind, name: &str) -> LaneSet { + match name { + "both" => LaneSet::single(0).with(1), + "process.only" => LaneSet::single(1), + _ => LaneSet::EMPTY, + } + } + async fn dispatch_lane( + &self, + message: &Message, + _ordered: Option<&crate::bus::OrderedDelivery>, + lane: usize, + ) -> Result<(), TransportError> { + let gate = self.gate.clone(); + let message_for_gate = message.clone(); + wait_until(move || gate(lane, &message_for_gate)).await; + self.log + .push(Event::Ran(lane, message.id().unwrap().to_owned())); + (self.behavior)(lane, message) + } +} + +fn message(name: &str, id: &str) -> Message { + Message::new(name, MessageKind::Event, b"{}".to_vec()).with_id(id) +} + +struct Harness { + log: Arc, + max_unsettled: Arc, + outcome: Result<(), TransportError>, +} + +fn run_lanes( + messages: Vec, + independent: bool, + options: RunOptions, + behavior: Behavior, + gate: impl Fn(&Arc) -> Gate, +) -> Harness { + let log = Arc::new(Log::default()); + let max_unsettled = Arc::new(AtomicUsize::new(0)); + let router = Arc::new(LaneRouter { + log: log.clone(), + behavior, + gate: gate(&log), + }); + let source = Source { + queue: messages.into_iter().collect(), + log: log.clone(), + independent, + unsettled: Arc::new(AtomicUsize::new(0)), + max_unsettled: max_unsettled.clone(), + }; + let outcome = block_on(run_source(router, source, options)); + Harness { + log, + max_unsettled, + outcome, + } +} + +fn ok() -> Behavior { + Arc::new(|_, _| Ok(())) +} + +fn open() -> impl Fn(&Arc) -> Gate { + |_| Arc::new(|_, _| true) +} + +/// The slow lane-0 route for `m1` finishes only after the process lane has +/// handled every later message, which is impossible if lanes were sequential. +#[test] +fn slow_projection_lane_does_not_delay_process_lane() { + let messages = vec![ + message("both", "m1"), + message("both", "m2"), + message("process.only", "m3"), + ]; + let harness = run_lanes(messages, true, RunOptions::idempotent(), ok(), |log| { + let log = log.clone(); + Arc::new(move |lane, message| { + lane != 0 || message.id() != Some("m1") || log.ran(1).len() == 3 + }) + }); + harness.outcome.unwrap(); + let log = &harness.log; + assert_eq!(log.ran(1), ["m1", "m2", "m3"], "process lane keeps order"); + assert_eq!(log.ran(0), ["m1", "m2"], "projection lane keeps order"); + // m3 (process only) settles before m1, whose slow lane was still running. + assert!(log.position(&Event::Ack("m3".into())) < log.position(&Event::Ack("m1".into()))); + // Every delivery is acknowledged only after all of its lanes ran. + for id in ["m1", "m2"] { + let ack = log.position(&Event::Ack(id.into())); + assert!(log.position(&Event::Ran(0, id.into())) < ack); + assert!(log.position(&Event::Ran(1, id.into())) < ack); + } +} + +#[test] +fn retryable_failure_in_one_lane_nacks_after_every_lane_finished() { + let harness = run_lanes( + vec![message("both", "m1"), message("both", "m2")], + true, + RunOptions::idempotent(), + Arc::new(|lane, message| { + if lane == 1 && message.id() == Some("m1") { + Err(TransportError::retryable("cell unavailable")) + } else { + Ok(()) + } + }), + open(), + ); + harness.outcome.unwrap(); + let log = &harness.log; + let nack = log.position(&Event::Nack("m1".into())); + assert!(log.position(&Event::Ran(0, "m1".into())) < nack); + assert!(log.position(&Event::Ran(1, "m1".into())) < nack); + assert!(!log.events().contains(&Event::Ack("m1".into()))); + assert!(log.events().contains(&Event::Ack("m2".into()))); +} + +#[test] +fn permanent_failure_applies_failure_policy_once_per_delivery() { + let harness = run_lanes( + vec![message("both", "m1")], + true, + RunOptions::idempotent(), + Arc::new(|lane, _| { + if lane == 0 { + Err(TransportError::permanent("rejected")) + } else { + Ok(()) + } + }), + open(), + ); + harness.outcome.unwrap(); + let settled: Vec<_> = harness + .log + .events() + .into_iter() + .filter(|event| matches!(event, Event::Ack(_) | Event::Nack(_) | Event::DeadLetter(_))) + .collect(); + assert_eq!(settled, [Event::DeadLetter("m1".into())]); +} + +#[test] +fn retryable_wins_over_permanent_so_a_recoverable_delivery_is_retained() { + let harness = run_lanes( + vec![message("both", "m1")], + true, + RunOptions::idempotent(), + Arc::new(|lane, _| { + if lane == 0 { + Err(TransportError::permanent("rejected")) + } else { + Err(TransportError::retryable("transient")) + } + }), + open(), + ); + harness.outcome.unwrap(); + assert!(harness.log.events().contains(&Event::Nack("m1".into()))); + assert!(!harness + .log + .events() + .contains(&Event::DeadLetter("m1".into()))); +} + +#[test] +fn window_bounds_unsettled_deliveries() { + let released = Arc::new(AtomicBool::new(false)); + let messages = (1..=6) + .map(|n| message("process.only", &format!("m{n}"))) + .collect(); + let release = released.clone(); + let harness = run_lanes( + messages, + true, + RunOptions::idempotent().with_lane_window(2), + ok(), + move |log| { + let log = log.clone(); + let release = release.clone(); + Arc::new(move |_, _| { + // Hold the lane until the runner has had every chance to + // over-receive, then release it. + let received = log + .events() + .iter() + .filter(|event| matches!(event, Event::Received(_))) + .count(); + if received >= 2 { + release.store(true, Ordering::SeqCst); + } + release.load(Ordering::SeqCst) + }) + }, + ); + harness.outcome.unwrap(); + assert!(released.load(Ordering::SeqCst)); + assert_eq!(harness.max_unsettled.load(Ordering::SeqCst), 2); + assert_eq!(harness.log.ran(1), ["m1", "m2", "m3", "m4", "m5", "m6"]); +} + +#[test] +fn stop_class_failure_halts_only_its_lane_and_retains_queued_deliveries() { + let harness = run_lanes( + vec![ + message("both", "m1"), + message("both", "m2"), + message("both", "m3"), + ], + true, + RunOptions::idempotent(), + Arc::new(|lane, message| { + if lane == 0 && message.id() == Some("m1") { + Err(TransportError::permanent("durable projection failure").retain_and_stop()) + } else { + Ok(()) + } + }), + |log| { + // Keep lane 0 on m1 until lane 1 has queued work behind it. + let log = log.clone(); + Arc::new(move |lane, message| { + lane != 0 || message.id() != Some("m1") || !log.ran(1).is_empty() + }) + }, + ); + let error = harness.outcome.unwrap_err(); + assert!(error.should_retain_and_stop()); + let log = &harness.log; + // The halted lane never runs later deliveries... + assert_eq!(log.ran(0), ["m1"]); + // ...and they are NAKed (retained), never acknowledged. + for id in ["m1", "m2", "m3"] { + let settled = log.events().into_iter().find(|event| { + matches!(event, Event::Ack(x) | Event::Nack(x) | Event::DeadLetter(x) if x == id) + }); + assert!( + matches!(settled, None | Some(Event::Nack(_))), + "{id} must not be acknowledged after its lane halted: {settled:?}" + ); + } + assert!(log.events().contains(&Event::Nack("m1".into()))); +} + +#[test] +fn stop_policy_on_permanent_failure_stops_without_settling_that_delivery() { + let harness = run_lanes( + vec![message("both", "m1")], + true, + RunOptions::idempotent().with_failure_policy(FailurePolicy::Stop), + Arc::new(|lane, _| { + if lane == 1 { + Err(TransportError::permanent("nope")) + } else { + Ok(()) + } + }), + open(), + ); + assert!(harness.outcome.unwrap_err().is_permanent()); + assert!(!harness + .log + .events() + .iter() + .any(|event| matches!(event, Event::Ack(_) | Event::Nack(_) | Event::DeadLetter(_)))); +} + +#[test] +fn unhandled_messages_are_acked_without_running_lanes() { + let harness = run_lanes( + vec![message("unhandled", "m1")], + true, + RunOptions::idempotent(), + ok(), + open(), + ); + harness.outcome.unwrap(); + assert_eq!( + harness.log.events(), + [Event::Received("m1".into()), Event::Ack("m1".into())] + ); +} + +/// A source without independent settlement keeps the sequential contract: +/// one delivery at a time, every lane's routes in order. +#[test] +fn positional_sources_keep_sequential_delivery() { + let harness = run_lanes( + vec![message("both", "m1"), message("both", "m2")], + false, + RunOptions::idempotent(), + ok(), + open(), + ); + harness.outcome.unwrap(); + assert_eq!( + harness.log.events(), + [ + Event::Received("m1".into()), + Event::Ran(0, "m1".into()), + Event::Ran(1, "m1".into()), + Event::Ack("m1".into()), + Event::Received("m2".into()), + Event::Ran(0, "m2".into()), + Event::Ran(1, "m2".into()), + Event::Ack("m2".into()), + ] + ); + assert_eq!(harness.max_unsettled.load(Ordering::SeqCst), 1); +} + +/// Redelivery after a NAK runs every lane again; handlers stay idempotent and +/// the second attempt acknowledges. +#[test] +fn redelivery_after_nack_reruns_all_lanes_then_acks() { + let attempts = Arc::new(AtomicUsize::new(0)); + let seen = attempts.clone(); + let log = Arc::new(Log::default()); + let router = Arc::new(LaneRouter { + log: log.clone(), + behavior: Arc::new(move |lane, _| { + if lane == 1 && seen.fetch_add(1, Ordering::SeqCst) == 0 { + Err(TransportError::retryable("first attempt")) + } else { + Ok(()) + } + }), + gate: Arc::new(|_, _| true), + }); + let source = |messages: Vec| Source { + queue: messages.into_iter().collect(), + log: log.clone(), + independent: true, + unsettled: Arc::new(AtomicUsize::new(0)), + max_unsettled: Arc::new(AtomicUsize::new(0)), + }; + block_on(run_source( + router.clone(), + source(vec![message("both", "m1")]), + RunOptions::idempotent(), + )) + .unwrap(); + // The broker redelivers the NAKed message. + block_on(run_source( + router, + source(vec![message("both", "m1")]), + RunOptions::idempotent(), + )) + .unwrap(); + assert_eq!(log.ran(0), ["m1", "m1"]); + assert_eq!(log.ran(1), ["m1", "m1"]); + let settled: Vec<_> = log + .events() + .into_iter() + .filter(|event| matches!(event, Event::Ack(_) | Event::Nack(_))) + .collect(); + assert_eq!(settled, [Event::Nack("m1".into()), Event::Ack("m1".into())]); +} diff --git a/src/bus/runner/mod.rs b/src/bus/runner/mod.rs index 2e105dd0b..ec865b16d 100644 --- a/src/bus/runner/mod.rs +++ b/src/bus/runner/mod.rs @@ -9,6 +9,8 @@ mod receive_loop; +#[cfg(test)] +mod lane_tests; #[cfg(test)] mod tests; diff --git a/src/bus/runner/receive_loop.rs b/src/bus/runner/receive_loop.rs index c04ce8426..01e120ce7 100644 --- a/src/bus/runner/receive_loop.rs +++ b/src/bus/runner/receive_loop.rs @@ -1,9 +1,14 @@ -use std::future::Future; +use std::collections::{HashMap, VecDeque}; +use std::future::{poll_fn, Future}; +use std::pin::Pin; use std::sync::Arc; +use std::task::Poll; + +use futures_util::stream::{FuturesUnordered, StreamExt}; use crate::bus::source::{MessageSource, ReceivedMessage}; use crate::bus::{FailureAction, MessageRouter, RunOptions, TransportError, TransportErrorKind}; -use crate::bus::{Message, MessageKind}; +use crate::bus::{Message, MessageKind, OrderedDelivery}; /// Run the receive loop for a direct transport source. /// @@ -29,6 +34,14 @@ use crate::bus::{Message, MessageKind}; /// swallowed: a returned `Err` ends the run and the supervisor may restart it /// (already-committed effects make redelivery safe). /// +/// When the router declares several [delivery lanes](MessageRouter::delivery_lanes) +/// and the source [settles independently](MessageSource::settles_independently), +/// lanes run concurrently while each keeps receive order, and a delivery is +/// settled once every lane that received it has finished. The number of +/// unsettled deliveries is bounded by [`RunOptions::lane_window`]. See +/// `docs/consumer-delivery-lanes.md`. Otherwise every message runs all of its +/// routes before the next message is received. +/// /// Inbox note: until the consumer-inbox subtask lands, inbox mode enforces the /// stable-id requirement and then dispatches like idempotent mode. The /// receipt-commit wrapping that makes it effectively-once is added there. @@ -36,6 +49,22 @@ use crate::bus::{Message, MessageKind}; /// `I: Send` keeps the returned future `Send` so the runner can be spawned on a /// multi-threaded executor regardless of the inbox hook type. pub async fn run_source( + router: Arc, + source: S, + options: RunOptions, +) -> Result<(), TransportError> +where + R: MessageRouter, + S: MessageSource, + I: Send, +{ + if router.delivery_lanes() > 1 && source.settles_independently() { + return LaneRun::new(router, source, options).run().await; + } + run_sequential(router, source, options).await +} + +async fn run_sequential( router: Arc, mut source: S, options: RunOptions, @@ -52,192 +81,547 @@ where let Some(received) = recv_next(&mut source, service, transport).await? else { break; }; - - // A delivery the transport could not decode is a permanent failure: it - // carries no valid message to dispatch, and it must NOT be treated as an - // empty message (which would route to ack-and-ignore below and silently - // drop a corrupt row). Route it through the failure policy directly, the - // same as a permanent dispatch failure, so it is dead-lettered/parked. - if let Some(error) = received.decode_error() { - let action = options.failure_policy.resolve(error); - record_transport_failure(service, transport, error.kind(), action); - let kind = received.message().kind; - match action { - FailureAction::Nack => { - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::NACK, - crate::telemetry::transport_outcome::NACK, - || received.nack(&reason), - ) - .await?; - } - FailureAction::DeadLetter => { - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::DEAD_LETTER, - crate::telemetry::transport_outcome::DEAD_LETTER, - || received.dead_letter(&reason), - ) - .await?; - } - FailureAction::Park => { - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::PARK, - crate::telemetry::transport_outcome::PARK, - || received.park(&reason), - ) - .await?; - } - FailureAction::LogAndAck => { - eprintln!("[bus::runner] dropping undecodable message after permanent failure: {error}"); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::ACK, - crate::telemetry::transport_outcome::LOG_AND_ACK, - || received.ack(), - ) - .await?; - } - FailureAction::Stop => return Err(TransportError::permanent(error.to_string())), - } + if received.decode_error().is_some() { + settle_permanent_decode(service, transport, &options, received).await?; continue; } - // No handler for this message: intentionally ignore (ack) rather than - // dead-letter, so unrelated fan-out events don't pile into the DLQ. if !router.handles(received.message().kind, received.message().name()) { - let kind = received.message().kind; + settle_ignored(service, transport, received).await?; + continue; + } + let kind = received.message().kind; + let result = dispatch( + router.as_ref(), + &options, + received.message(), + received.ordered_delivery(), + ) + .await; + settle_result(service, transport, &options, received, kind, result).await?; + } + Ok(()) +} + +/// A delivery the transport could not decode is a permanent failure: it +/// carries no valid message to dispatch, and it must NOT be treated as an +/// empty message (which would route to ack-and-ignore and silently drop a +/// corrupt row). Route it through the failure policy directly, the same as a +/// permanent dispatch failure, so it is dead-lettered/parked. +async fn settle_permanent_decode( + service: Option<&str>, + transport: &str, + options: &RunOptions, + received: M, +) -> Result<(), TransportError> { + let Some(error) = received.decode_error() else { + return Ok(()); + }; + let action = options.failure_policy.resolve(error); + record_transport_failure(service, transport, error.kind(), action); + let kind = received.message().kind; + let reason = error.to_string(); + match action { + FailureAction::Nack => { + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::NACK, + crate::telemetry::transport_outcome::NACK, + || received.nack(&reason), + ) + .await + } + FailureAction::DeadLetter => { + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::DEAD_LETTER, + crate::telemetry::transport_outcome::DEAD_LETTER, + || received.dead_letter(&reason), + ) + .await + } + FailureAction::Park => { + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::PARK, + crate::telemetry::transport_outcome::PARK, + || received.park(&reason), + ) + .await + } + FailureAction::LogAndAck => { + eprintln!( + "[bus::runner] dropping undecodable message after permanent failure: {reason}" + ); settle_and_record( service, transport, kind, crate::telemetry::transport_outcome::ACK, - crate::telemetry::transport_outcome::IGNORED, + crate::telemetry::transport_outcome::LOG_AND_ACK, || received.ack(), ) + .await + } + FailureAction::Stop => Err(TransportError::permanent(reason)), + } +} + +/// No handler for this message: intentionally ignore (ack) rather than +/// dead-letter, so unrelated fan-out events don't pile into the DLQ. +async fn settle_ignored( + service: Option<&str>, + transport: &str, + received: M, +) -> Result<(), TransportError> { + let kind = received.message().kind; + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::ACK, + crate::telemetry::transport_outcome::IGNORED, + || received.ack(), + ) + .await +} + +/// Settle one dispatched delivery exactly as the sequential runner always has. +/// +/// Returns `Err` when the run must end: a retain-and-stop failure (after NAKing +/// the exact delivery), a `Stop` policy (without settling), or a settle error. +async fn settle_result( + service: Option<&str>, + transport: &str, + options: &RunOptions, + received: M, + kind: MessageKind, + result: Result<(), TransportError>, +) -> Result<(), TransportError> { + match result { + Ok(()) => { + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::ACK, + crate::telemetry::transport_outcome::ACK, + || received.ack(), + ) + .await + } + Err(error) if error.should_retain_and_stop() => { + record_transport_failure( + service, + transport, + error.kind(), + crate::telemetry::transport_outcome::NACK, + ); + let reason = error.to_string(); + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::NACK, + crate::telemetry::transport_outcome::NACK, + || received.nack(&reason), + ) .await?; - continue; + Err(error) } - let kind = received.message().kind; - match dispatch( - router.as_ref(), - &options, - received.message(), - received.ordered_delivery(), - ) - .await - { - Ok(()) => { + Err(error) => match options.failure_policy.resolve(&error) { + action @ FailureAction::Nack => { + record_transport_failure(service, transport, error.kind(), action); + let reason = error.to_string(); settle_and_record( service, transport, kind, - crate::telemetry::transport_outcome::ACK, - crate::telemetry::transport_outcome::ACK, - || received.ack(), + crate::telemetry::transport_outcome::NACK, + crate::telemetry::transport_outcome::NACK, + || received.nack(&reason), + ) + .await + } + action @ FailureAction::DeadLetter => { + record_transport_failure(service, transport, error.kind(), action); + let reason = error.to_string(); + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::DEAD_LETTER, + crate::telemetry::transport_outcome::DEAD_LETTER, + || received.dead_letter(&reason), + ) + .await + } + action @ FailureAction::Park => { + record_transport_failure(service, transport, error.kind(), action); + let reason = error.to_string(); + settle_and_record( + service, + transport, + kind, + crate::telemetry::transport_outcome::PARK, + crate::telemetry::transport_outcome::PARK, + || received.park(&reason), ) - .await?; + .await } - Err(error) if error.should_retain_and_stop() => { + FailureAction::LogAndAck => { record_transport_failure( service, transport, error.kind(), - crate::telemetry::transport_outcome::NACK, + FailureAction::LogAndAck, + ); + eprintln!( + "[bus::runner] dropping message '{}' after permanent failure: {error}", + received.message().name() ); - let reason = error.to_string(); settle_and_record( service, transport, kind, - crate::telemetry::transport_outcome::NACK, - crate::telemetry::transport_outcome::NACK, - || received.nack(&reason), + crate::telemetry::transport_outcome::ACK, + crate::telemetry::transport_outcome::LOG_AND_ACK, + || received.ack(), ) - .await?; - return Err(error); + .await + } + FailureAction::Stop => { + record_transport_failure(service, transport, error.kind(), FailureAction::Stop); + Err(error) + } + }, + } +} + +// --- delivery lanes ------------------------------------------------------ + +type LaneDone = (u64, usize, Result<(), TransportError>); +type LaneFuture<'r> = Pin + Send + 'r>>; +type RecvOutput = ( + S, + Result::Received>, TransportError>, +); +type RecvFuture<'s, S> = Pin> + Send + 's>>; + +struct InFlight { + received: M, + message: Arc, + ordered: Option, + kind: MessageKind, + remaining: usize, + stop: Option, + retryable: Option, + permanent: Option, +} + +enum Step { + Received(RecvOutput), + Lane(LaneDone), +} + +/// Concurrent lanes over one ordered source. See `docs/consumer-delivery-lanes.md`. +struct LaneRun<'r, R, S: MessageSource + 'r, I> { + router: Arc, + options: RunOptions, + transport: &'static str, + source: Option, + receiving: Option>, + running: FuturesUnordered>, + lane_busy: Vec, + lane_halted: Vec, + queues: Vec>, + in_flight: HashMap>, + next_sequence: u64, + /// Set when the source drained (`Ok(None)`) or failed to receive. + source_finished: Option>, + stop_error: Option, +} + +impl<'r, R, S, I> LaneRun<'r, R, S, I> +where + R: MessageRouter + 'r, + S: MessageSource + 'r, + I: Send, +{ + fn new(router: Arc, source: S, options: RunOptions) -> Self { + let lanes = router.delivery_lanes().min(crate::bus::LaneSet::MAX_LANES); + let transport = source.transport_name(); + Self { + router, + options, + transport, + source: Some(source), + receiving: None, + running: FuturesUnordered::new(), + lane_busy: vec![false; lanes], + lane_halted: vec![false; lanes], + queues: vec![VecDeque::new(); lanes], + in_flight: HashMap::new(), + next_sequence: 0, + source_finished: None, + stop_error: None, + } + } + + fn service(&self) -> Option { + self.router.consumer_group().map(str::to_owned) + } + + fn stopping(&self) -> bool { + self.stop_error.is_some() || self.source_finished.is_some() + } + + async fn run(mut self) -> Result<(), TransportError> { + loop { + self.start_idle_lanes().await; + if self.receiving.is_none() + && !self.stopping() + && self.in_flight.len() < self.options.lane_window.max(1) + { + if let Some(mut source) = self.source.take() { + self.receiving = Some(Box::pin(async move { + let result = source.recv().await; + (source, result) + })); + } } - Err(error) => match options.failure_policy.resolve(&error) { - action @ FailureAction::Nack => { - record_transport_failure(service, transport, error.kind(), action); - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::NACK, - crate::telemetry::transport_outcome::NACK, - || received.nack(&reason), - ) - .await?; + if self.in_flight.is_empty() && self.receiving.is_none() && self.stopping() { + if let Some(error) = self.stop_error.take() { + return Err(error); } - action @ FailureAction::DeadLetter => { - record_transport_failure(service, transport, error.kind(), action); - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::DEAD_LETTER, - crate::telemetry::transport_outcome::DEAD_LETTER, - || received.dead_letter(&reason), - ) - .await?; + return self.source_finished.take().unwrap_or(Ok(())); + } + + let running = &mut self.running; + let receiving = &mut self.receiving; + let step: Step = poll_fn(|cx| { + if let Poll::Ready(Some(done)) = running.poll_next_unpin(cx) { + return Poll::Ready(Step::Lane(done)); } - action @ FailureAction::Park => { - record_transport_failure(service, transport, error.kind(), action); - let reason = error.to_string(); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::PARK, - crate::telemetry::transport_outcome::PARK, - || received.park(&reason), - ) - .await?; + if let Some(future) = receiving.as_mut() { + if let Poll::Ready(output) = future.as_mut().poll(cx) { + return Poll::Ready(Step::Received(output)); + } } - FailureAction::LogAndAck => { - record_transport_failure( - service, - transport, - error.kind(), - FailureAction::LogAndAck, - ); - eprintln!( - "[bus::runner] dropping message '{}' after permanent failure: {error}", - received.message().name() - ); - settle_and_record( - service, - transport, - kind, - crate::telemetry::transport_outcome::ACK, - crate::telemetry::transport_outcome::LOG_AND_ACK, - || received.ack(), - ) - .await?; + Poll::Pending + }) + .await; + match step { + Step::Received((source, result)) => { + self.receiving = None; + self.source = Some(source); + self.accept(result).await; } - FailureAction::Stop => { - record_transport_failure(service, transport, error.kind(), FailureAction::Stop); - return Err(error); + Step::Lane((sequence, lane, result)) => { + self.lane_busy[lane] = false; + self.finish_lane(sequence, lane, result).await; } + } + } + } + + /// Start the next queued delivery on every idle lane. A halted lane NAKs + /// its queued deliveries instead of running them. + async fn start_idle_lanes(&mut self) { + for lane in 0..self.queues.len() { + while self.lane_halted[lane] { + let Some(sequence) = self.queues[lane].pop_front() else { + break; + }; + let halted = TransportError::retryable( + "delivery lane halted after a stop-class failure; delivery retained", + ); + self.finish_lane(sequence, lane, Err(halted)).await; + } + if self.lane_busy[lane] { + continue; + } + let Some(sequence) = self.queues[lane].pop_front() else { + continue; + }; + let Some(entry) = self.in_flight.get(&sequence) else { + continue; + }; + let router = Arc::clone(&self.router); + let message = Arc::clone(&entry.message); + let ordered = entry.ordered.clone(); + self.lane_busy[lane] = true; + self.running.push(Box::pin(async move { + let result = dispatch_lane(router.as_ref(), &message, ordered.as_ref(), lane).await; + (sequence, lane, result) + })); + } + } + + async fn accept(&mut self, result: Result, TransportError>) { + let service = self.service(); + let service = service.as_deref(); + let received = match result { + Ok(Some(received)) => received, + Ok(None) => { + self.source_finished = Some(Ok(())); + return; + } + Err(error) => { + record_transport_failure( + service, + self.transport, + error.kind(), + crate::telemetry::failure_action::RECV_ERROR, + ); + self.source_finished = Some(Err(error)); + return; + } + }; + if received.decode_error().is_some() { + let outcome = + settle_permanent_decode(service, self.transport, &self.options, received).await; + self.record_stop(outcome); + return; + } + let kind = received.message().kind; + let lanes = self.router.lanes_for(kind, received.message().name()); + if lanes.is_empty() { + let outcome = settle_ignored(service, self.transport, received).await; + self.record_stop(outcome); + return; + } + if let Err(error) = self.options.validate_message_id(received.message()) { + let error = TransportError::permanent(error.to_string()).with_source(error); + let outcome = settle_result( + service, + self.transport, + &self.options, + received, + kind, + Err(error), + ) + .await; + self.record_stop(outcome); + return; + } + let sequence = self.next_sequence; + self.next_sequence += 1; + let message = Arc::new(received.message().clone()); + let ordered = received.ordered_delivery().cloned(); + let mut remaining = 0; + let lane_count = self.queues.len(); + for lane in lanes.iter().filter(|lane| *lane < lane_count) { + self.queues[lane].push_back(sequence); + remaining += 1; + } + self.in_flight.insert( + sequence, + InFlight { + received, + message, + ordered, + kind, + remaining, + stop: None, + retryable: None, + permanent: None, }, + ); + if remaining == 0 { + // Lanes beyond this runner's range cannot run; keep it retryable. + let error = TransportError::retryable("delivery lane out of range"); + self.settle_entry(sequence, Some(error)).await; } } - Ok(()) + + async fn finish_lane( + &mut self, + sequence: u64, + lane: usize, + result: Result<(), TransportError>, + ) { + let stops = |error: &TransportError, options: &RunOptions| { + error.should_retain_and_stop() + || options.failure_policy.resolve(error) == FailureAction::Stop + }; + let Some(entry) = self.in_flight.get_mut(&sequence) else { + return; + }; + entry.remaining = entry.remaining.saturating_sub(1); + if let Err(error) = result { + if stops(&error, &self.options) { + self.lane_halted[lane] = true; + entry.stop.get_or_insert(error); + } else if error.is_retryable() { + entry.retryable.get_or_insert(error); + } else { + entry.permanent.get_or_insert(error); + } + } + if entry.remaining == 0 { + self.settle_entry(sequence, None).await; + } + } + + /// Settle a delivery whose lanes all finished. A stop-class failure wins, + /// then any retryable failure (so a delivery that may still succeed is + /// redelivered), then a permanent one. + async fn settle_entry(&mut self, sequence: u64, extra: Option) { + let Some(entry) = self.in_flight.remove(&sequence) else { + return; + }; + let error = entry.stop.or(entry.retryable).or(extra).or(entry.permanent); + let service = self.service(); + let outcome = settle_result( + service.as_deref(), + self.transport, + &self.options, + entry.received, + entry.kind, + error.map_or(Ok(()), Err), + ) + .await; + self.record_stop(outcome); + } + + fn record_stop(&mut self, outcome: Result<(), TransportError>) { + if let Err(error) = outcome { + self.stop_error.get_or_insert(error); + } + } +} + +async fn dispatch_lane( + router: &R, + message: &Message, + ordered: Option<&OrderedDelivery>, + lane: usize, +) -> Result<(), TransportError> { + #[cfg(feature = "otel")] + { + use tracing::Instrument as _; + + let span = transport_receive_span(message); + crate::trace_context::set_span_parent_from_metadata_if_no_current_span( + &span, + &message.metadata, + ); + return router + .dispatch_lane(message, ordered, lane) + .instrument(span) + .await; + } + + #[cfg(not(feature = "otel"))] + { + router.dispatch_lane(message, ordered, lane).await + } } async fn settle_and_record( diff --git a/src/bus/source.rs b/src/bus/source.rs index a96c10bb3..8d4406382 100644 --- a/src/bus/source.rs +++ b/src/bus/source.rs @@ -33,6 +33,17 @@ pub trait MessageSource: Send { "unknown" } + /// Whether each delivery can be settled independently of the others, in + /// any order, while later deliveries are still being received. + /// + /// True only for per-message acknowledgements (for example NATS JetStream + /// explicit acks). Positional (offset commit) and lease-based sources keep + /// the default `false`, and the runner then processes one delivery at a + /// time even when the router has several delivery lanes. + fn settles_independently(&self) -> bool { + false + } + /// Receive the next message, if any. fn recv( &mut self, diff --git a/src/microsvc/message_router.rs b/src/microsvc/message_router.rs index 20d213024..983dd5e45 100644 --- a/src/microsvc/message_router.rs +++ b/src/microsvc/message_router.rs @@ -5,7 +5,7 @@ //! retryable/permanent vocabulary happens here, on the microsvc side, so the //! bus-core runner only ever sees an already-classified `TransportError`. -use crate::bus::{MessageRouter, OrderedDelivery, TransportError}; +use crate::bus::{LaneSet, MessageRouter, OrderedDelivery, TransportError}; use crate::microsvc::{Message, MessageKind, Service, SubscriptionPlan}; impl MessageRouter for Service { @@ -39,4 +39,24 @@ impl MessageRouter for Service { .map(|_| ()) .map_err(TransportError::from) } + + fn delivery_lanes(&self) -> usize { + self.delivery_lane_names().len() + } + + fn lanes_for(&self, kind: MessageKind, name: &str) -> LaneSet { + self.lanes_for_message(kind, name) + } + + async fn dispatch_lane( + &self, + message: &Message, + ordered: Option<&OrderedDelivery>, + lane: usize, + ) -> Result<(), TransportError> { + self.dispatch_lane_message(message, ordered, Some(lane)) + .await + .map(|_| ()) + .map_err(TransportError::from) + } } diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index 3ea157bb0..d7e5703fb 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -113,7 +113,7 @@ pub use service::{ CausalCommitBuilder, CausalRepository, CommandRequest, CommandResponse, DeliveryKind, DirectReadModelProjection, HandlerNames, HandlerSpec, PortableCommand, PreparedCausalCommit, PreparedCommandHandler, RouteBuilder, Routes, Service, ThinCommandBuilder, ThinCommandInvoked, - ThinCommandLoaded, TypedRouteBuilder, + ThinCommandLoaded, TypedRouteBuilder, DEFAULT_DELIVERY_LANE, }; #[cfg(feature = "graphql")] pub(crate) use service::{ diff --git a/src/microsvc/service/mod.rs b/src/microsvc/service/mod.rs index a9592c7d5..c744b7e91 100644 --- a/src/microsvc/service/mod.rs +++ b/src/microsvc/service/mod.rs @@ -60,7 +60,7 @@ pub use routes::{ DeliveryKind, HandlerNames, HandlerSpec, PortableCommand, RouteBuilder, Routes, ThinCommandBuilder, ThinCommandInvoked, ThinCommandLoaded, TypedRouteBuilder, }; -pub use runtime::Service; +pub use runtime::{Service, DEFAULT_DELIVERY_LANE}; #[cfg(test)] mod tests; diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 67afbf02b..5b32169c1 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -55,11 +55,18 @@ pub(crate) type ServiceRunner = Box< + Sync, >; +/// Name of the delivery lane that plain [`Service::routes`] registers into. +pub const DEFAULT_DELIVERY_LANE: &str = "default"; + /// A microservice deployment that routes messages to one or more route bundles. pub struct Service { name: Option, pub(super) routes: Vec>, index: HashMap>>, + /// Delivery lane of each route bundle (parallel to `routes`); 0 is default. + route_lanes: Vec, + /// Lane names by index; index 0 is the unnamed default lane. + lane_names: Vec<&'static str>, handler_specs: Vec, causal_command_policy: CausalCommandPolicy, runner: Option, @@ -78,6 +85,8 @@ impl Service { name: None, routes: Vec::new(), index: HashMap::new(), + route_lanes: Vec::new(), + lane_names: vec![DEFAULT_DELIVERY_LANE], handler_specs: Vec::new(), causal_command_policy: CausalCommandPolicy::default(), runner: None, @@ -492,6 +501,60 @@ impl Service { self } + /// Add a route bundle to a named delivery lane. + /// + /// Lanes of one consumer run concurrently when the transport settles each + /// delivery independently; each lane keeps delivery order and a delivery is + /// settled only after all of its lanes finished. Use a lane only for routes + /// that neither depend on nor are depended on by routes of other lanes + /// within the same delivery (see `docs/consumer-delivery-lanes.md`). + /// + /// # Panics + /// When `lane` is empty, names the default lane, or exceeds the lane limit. + pub fn lane(mut self, lane: &'static str, routes: Routes) -> Self + where + D: Send + Sync + 'static, + { + assert!( + !lane.trim().is_empty() && lane != DEFAULT_DELIVERY_LANE, + "a named delivery lane must be non-empty and not `{DEFAULT_DELIVERY_LANE}`" + ); + let index = match self.lane_names.iter().position(|name| *name == lane) { + Some(index) => index, + None => { + assert!( + self.lane_names.len() < crate::bus::LaneSet::MAX_LANES, + "too many delivery lanes" + ); + self.lane_names.push(lane); + self.lane_names.len() - 1 + } + }; + self.add_routes(routes); + *self + .route_lanes + .last_mut() + .expect("add_routes registers one bundle") = index; + self + } + + /// Delivery lane names by index; index 0 is the default lane. + pub fn delivery_lane_names(&self) -> &[&'static str] { + &self.lane_names + } + + /// Lanes with a route for `(kind, name)`. + pub fn lanes_for_message(&self, kind: MessageKind, name: &str) -> crate::bus::LaneSet { + self.index + .get(&kind) + .and_then(|by_name| by_name.get(name)) + .into_iter() + .flatten() + .fold(crate::bus::LaneSet::EMPTY, |lanes, route| { + lanes.with(self.route_lanes[*route]) + }) + } + pub(super) fn add_routes(&mut self, routes: Routes) where D: Send + Sync + 'static, @@ -567,6 +630,7 @@ impl Service { self.handler_specs.extend_from_slice(routes.handler_specs()); self.registered_command_mounts.extend(command_mounts); self.routes.push(Box::new(routes)); + self.route_lanes.push(0); } pub(crate) fn typed_command_contracts(&self) -> Vec { @@ -1006,7 +1070,8 @@ impl Service { metadata, }; - self.invoke_with_dispatch_span(&message, input, session, None) + let route_indices = self.lane_route_indices(&message, None)?; + self.invoke_with_dispatch_span(&message, input, session, None, route_indices) .await } @@ -1037,10 +1102,21 @@ impl Service { &self, message: &Message, ordered: Option<&OrderedDelivery>, + ) -> Result { + self.dispatch_lane_message(message, ordered, None).await + } + + /// Dispatch only the routes of one delivery lane (`None` runs every lane + /// in registration order). + pub(crate) async fn dispatch_lane_message( + &self, + message: &Message, + ordered: Option<&OrderedDelivery>, + lane: Option, ) -> Result { #[cfg(feature = "metrics")] let started = Instant::now(); - let result = self.dispatch_message_inner(message, ordered).await; + let result = self.dispatch_message_inner(message, ordered, lane).await; #[cfg(feature = "metrics")] { let error = result.as_ref().err(); @@ -1061,17 +1137,17 @@ impl Service { &self, message: &Message, ordered: Option<&OrderedDelivery>, + lane: Option, ) -> Result { ensure_lifecycle_mutations_open()?; if !self.handles_message(message.kind, &message.name) { return Err(HandlerError::UnknownCommand(message.name.clone())); } - let route_indices = self - .index - .get(&message.kind) - .and_then(|by_name| by_name.get(message.name())) - .ok_or_else(|| HandlerError::UnknownCommand(message.name.clone()))?; + let route_indices = self.lane_route_indices(message, lane)?; + if route_indices.is_empty() { + return Err(HandlerError::UnknownCommand(message.name.clone())); + } let projector_only = route_indices .iter() .all(|index| self.routes[*index].is_causal_projector(message)); @@ -1093,16 +1169,34 @@ impl Service { } }; let session = message_to_session(message); - self.invoke_with_dispatch_span(message, input, session, ordered) + self.invoke_with_dispatch_span(message, input, session, ordered, route_indices) .await } + fn lane_route_indices( + &self, + message: &Message, + lane: Option, + ) -> Result, HandlerError> { + let all = self + .index + .get(&message.kind) + .and_then(|by_name| by_name.get(message.name())) + .ok_or_else(|| HandlerError::UnknownCommand(message.name.clone()))?; + Ok(all + .iter() + .copied() + .filter(|route| lane.is_none_or(|lane| self.route_lanes[*route] == lane)) + .collect()) + } + async fn invoke_with_dispatch_span( &self, message: &Message, input: Value, session: Session, ordered: Option<&OrderedDelivery>, + route_indices: Vec, ) -> Result { #[cfg(feature = "otel")] { @@ -1114,14 +1208,15 @@ impl Service { &message.metadata, ); return self - .invoke(message, input, session, ordered) + .invoke(message, input, session, ordered, route_indices) .instrument(span) .await; } #[cfg(not(feature = "otel"))] { - self.invoke(message, input, session, ordered).await + self.invoke(message, input, session, ordered, route_indices) + .await } } @@ -1131,13 +1226,8 @@ impl Service { input: Value, session: Session, ordered: Option<&OrderedDelivery>, + route_indices: Vec, ) -> Result { - let route_indices = self - .index - .get(&message.kind) - .and_then(|by_name| by_name.get(message.name.as_str())) - .cloned() - .ok_or_else(|| HandlerError::UnknownCommand(message.name.clone()))?; #[cfg(feature = "otel")] let handler_span = microsvc_handler_span(message); let dispatch = async move { diff --git a/src/microsvc/service/tests.rs b/src/microsvc/service/tests.rs index 6f9fcab98..8fdf19e5b 100644 --- a/src/microsvc/service/tests.rs +++ b/src/microsvc/service/tests.rs @@ -4170,3 +4170,99 @@ fn command_request_requires_session_variables_field() { let result: Result = serde_json::from_str(json); assert!(result.is_err()); } + +type LaneLog = std::sync::Arc>>; + +fn lane_log() -> LaneLog { + std::sync::Arc::new(std::sync::Mutex::new(Vec::new())) +} + +fn lane_recorder(log: &LaneLog, label: &'static str) -> Routes<()> { + let log = log.clone(); + test_routes() + .events(&["fact.recorded", "fact.other"]) + .handle(move |ctx: &Context<()>| { + log.lock() + .unwrap() + .push(format!("{label}:{}", ctx.message().name())); + async move { Ok(json!({})) } + }) +} + +#[tokio::test] +async fn named_lanes_partition_routes_and_default_dispatch_runs_all_in_order() { + use crate::bus::{LaneSet, MessageRouter}; + let log = lane_log(); + let service = Service::new() + .routes(lane_recorder(&log, "projection-a")) + .lane("process", lane_recorder(&log, "policy")) + .routes(lane_recorder(&log, "projection-b")) + .lane( + "process", + test_routes() + .event("fact.process_only") + .handle(|_: &Context<()>| async move { Ok(json!({})) }), + ); + + assert_eq!( + service.delivery_lane_names(), + &[DEFAULT_DELIVERY_LANE, "process"] + ); + assert_eq!(MessageRouter::delivery_lanes(&service), 2); + assert_eq!( + MessageRouter::lanes_for(&service, MessageKind::Event, "fact.recorded"), + LaneSet::single(0).with(1) + ); + assert_eq!( + MessageRouter::lanes_for(&service, MessageKind::Event, "fact.process_only"), + LaneSet::single(1) + ); + assert!(MessageRouter::lanes_for(&service, MessageKind::Event, "fact.unknown").is_empty()); + + let message = Message::new("fact.recorded", MessageKind::Event, b"{}".to_vec()).with_id("e1"); + MessageRouter::dispatch_lane(&service, &message, None, 1) + .await + .unwrap(); + assert_eq!(*log.lock().unwrap(), ["policy:fact.recorded"]); + log.lock().unwrap().clear(); + MessageRouter::dispatch_lane(&service, &message, None, 0) + .await + .unwrap(); + assert_eq!( + *log.lock().unwrap(), + ["projection-a:fact.recorded", "projection-b:fact.recorded"] + ); + // Without lanes (sequential transports), every route runs in + // registration order exactly as before lanes existed. + log.lock().unwrap().clear(); + service.dispatch_message(&message).await.unwrap(); + assert_eq!( + *log.lock().unwrap(), + [ + "projection-a:fact.recorded", + "policy:fact.recorded", + "projection-b:fact.recorded" + ] + ); + // A lane with no route for the message is an unknown-route error, never a + // silent success. + let only = Message::new("fact.process_only", MessageKind::Event, b"{}".to_vec()); + assert!(MessageRouter::dispatch_lane(&service, &only, None, 0) + .await + .is_err()); +} + +#[test] +fn service_without_named_lanes_reports_one_lane() { + use crate::bus::MessageRouter; + let log = lane_log(); + let service = Service::new().routes(lane_recorder(&log, "only")); + assert_eq!(MessageRouter::delivery_lanes(&service), 1); +} + +#[test] +#[should_panic(expected = "named delivery lane")] +fn default_lane_name_cannot_be_used_as_a_named_lane() { + let log = lane_log(); + let _ = Service::new().lane(DEFAULT_DELIVERY_LANE, lane_recorder(&log, "x")); +} diff --git a/tests/nats_transport/main.rs b/tests/nats_transport/main.rs index e00284393..5f35b00fe 100644 --- a/tests/nats_transport/main.rs +++ b/tests/nats_transport/main.rs @@ -709,3 +709,225 @@ async fn undecodable_payload_dead_letters_without_blocking() { "the message behind the garbage is still handled" ); } + +// ---- latency: idle delivery, retry backoff, delivery lanes ---- +// See docs/consumer-delivery-lanes.md. + +/// A long-lived consumer that has gone through several empty fetches must +/// still hand a newly published message to its handler immediately; it must +/// not sleep out an idle interval or a fetch expiry first. +#[tokio::test] +async fn message_published_after_empty_fetches_is_delivered_promptly() { + let Some(url) = nats_url() else { return }; + let subject = unique("latency.idle"); + let source = NatsJetStreamSource::connect( + &url, + &unique("STREAM"), + vec![subject.clone()], + &unique("consumer"), + ) + .await + .expect("connect source") + .with_fetch_timeout(Duration::from_millis(500)) + .with_idle_poll(Duration::from_millis(25)); + let handled = Arc::new(Mutex::new(None::)); + let record = handled.clone(); + let router = Arc::new(Handlers::new().on_event(&subject, move |_: &Message| { + record + .lock() + .unwrap() + .get_or_insert_with(std::time::Instant::now); + async { Ok(()) } + })); + let consumer = tokio::spawn(run_source(router, source, RunOptions::idempotent())); + // Several empty 500 ms fetches expire first. + tokio::time::sleep(Duration::from_millis(1_300)).await; + let publisher = NatsPublisher::connect(&url).await.expect("publisher"); + let published = std::time::Instant::now(); + publisher + .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("late")) + .await + .expect("publish"); + let latency = tokio::time::timeout(Duration::from_secs(3), async { + loop { + if let Some(at) = *handled.lock().unwrap() { + return at.duration_since(published); + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("idle consumer delivered the message"); + consumer.abort(); + assert!( + latency < Duration::from_millis(250), + "idle delivery took {latency:?}" + ); +} + +/// A message that keeps failing retryably is redelivered with growing +/// delays instead of a hot loop, and a newer message is not delayed by it. +#[tokio::test] +async fn retryable_nack_backs_off_without_starving_newer_messages() { + let Some(url) = nats_url() else { return }; + let subject = unique("latency.retry"); + let source = NatsJetStreamSource::connect( + &url, + &unique("STREAM"), + vec![subject.clone()], + &unique("consumer"), + ) + .await + .expect("connect source") + .with_fetch_timeout(Duration::from_millis(500)) + .with_idle_poll(Duration::from_millis(25)); + let poison_attempts = Arc::new(AtomicUsize::new(0)); + let fresh_at = Arc::new(Mutex::new(None::)); + let (attempts, fresh) = (poison_attempts.clone(), fresh_at.clone()); + let router = Arc::new( + Handlers::new().on_event(&subject, move |message: &Message| { + let poison = message.id() == Some("poison"); + if poison { + attempts.fetch_add(1, Ordering::SeqCst); + } else { + fresh + .lock() + .unwrap() + .get_or_insert_with(std::time::Instant::now); + } + async move { + if poison { + Err(TransportError::retryable("rejected until repaired")) + } else { + Ok(()) + } + } + }), + ); + let consumer = tokio::spawn(run_source(router, source, RunOptions::idempotent())); + let publisher = NatsPublisher::connect(&url).await.expect("publisher"); + publisher + .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("poison")) + .await + .expect("publish poison"); + tokio::time::sleep(Duration::from_millis(300)).await; + let published = std::time::Instant::now(); + publisher + .publish(Message::new(&subject, MessageKind::Event, b"{}".to_vec()).with_id("fresh")) + .await + .expect("publish fresh"); + tokio::time::sleep(Duration::from_millis(1_200)).await; + consumer.abort(); + let fresh_latency = fresh_at + .lock() + .unwrap() + .expect("fresh message handled") + .duration_since(published); + let attempts = poison_attempts.load(Ordering::SeqCst); + assert!( + fresh_latency < Duration::from_millis(250), + "fresh message waited {fresh_latency:?}" + ); + // 50 ms doubling over ~1.5 s allows at most ~6 attempts; an immediate + // NAK loop redelivers hundreds of times in the same window. + assert!( + (2..=8).contains(&attempts), + "poison retried {attempts} times: retries must continue but back off" + ); +} + +/// With the process policy in its own lane, a slow projection route for an +/// earlier message does not delay the policy for a later message, and every +/// delivery is still acknowledged exactly once after all of its lanes ran. +#[tokio::test] +async fn slow_default_lane_does_not_delay_process_lane_over_jetstream() { + let Some(url) = nats_url() else { return }; + let namespace = unique("lanes").to_lowercase(); + let bus = nats_bus(&url, &namespace, "lanes") + .await + .with_idle_poll(Duration::from_millis(25)); + let started = std::time::Instant::now(); + let projection_done = Arc::new(Mutex::new(Vec::<(String, Duration)>::new())); + let policy_done = Arc::new(Mutex::new(Vec::<(String, Duration)>::new())); + let (projected, policed) = (projection_done.clone(), policy_done.clone()); + let service = Service::new() + .named("lanes") + .routes( + Routes::new() + .with_dependencies(()) + .event("fact.recorded") + .handle(move |ctx: &Context<()>| { + let id = ctx.message().id().unwrap_or_default().to_owned(); + let projected = projected.clone(); + async move { + if id == "m1" { + // A slow projection / external effect. + tokio::time::sleep(Duration::from_millis(1_500)).await; + } + projected.lock().unwrap().push((id, started.elapsed())); + Ok(json!({})) + } + }), + ) + .lane( + "process", + Routes::new() + .with_dependencies(()) + .event("fact.recorded") + .handle(move |ctx: &Context<()>| { + let id = ctx.message().id().unwrap_or_default().to_owned(); + let policed = policed.clone(); + async move { + policed.lock().unwrap().push((id, started.elapsed())); + Ok(json!({})) + } + }), + ) + .with_bus(bus.clone()); + let consumer = tokio::spawn(service.run(RunOptions::idempotent())); + tokio::time::sleep(Duration::from_millis(700)).await; + use distributed::bus::Bus; + for id in ["m1", "m2"] { + bus.publish_message( + Message::new("fact.recorded", MessageKind::Event, b"{}".to_vec()).with_id(id), + ) + .await + .expect("publish"); + } + tokio::time::sleep(Duration::from_millis(2_500)).await; + consumer.abort(); + let policed = policy_done.lock().unwrap().clone(); + let projected = projection_done.lock().unwrap().clone(); + assert_eq!( + policed + .iter() + .map(|(id, _)| id.as_str()) + .collect::>(), + ["m1", "m2"], + "process lane keeps delivery order" + ); + assert_eq!( + projected + .iter() + .map(|(id, _)| id.as_str()) + .collect::>(), + ["m1", "m2"], + "default lane keeps delivery order" + ); + let m2_policy = policed[1].1; + let m1_projection = projected[0].1; + assert!( + m2_policy + Duration::from_millis(1_000) < m1_projection, + "process lane waited for the slow lane: m2 policy at {m2_policy:?}, m1 projection at {m1_projection:?}" + ); + // Both deliveries were acknowledged: nothing pending or awaiting ack. + let stream = bus.ensure_stream().await.expect("stream"); + let mut durable = stream + .get_consumer::("lanes_evt") + .await + .expect("durable exists"); + let info = durable.info().await.expect("consumer info"); + assert_eq!(info.num_ack_pending, 0, "every delivery was settled"); + assert_eq!(info.num_pending, 0); + assert_eq!(info.num_redelivered, 0, "no delivery ran twice"); +} From a37e07a8c231e2697322fd50bb2c549fe26a2866 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Wed, 30 Sep 2026 01:31:09 -0500 Subject: [PATCH 118/484] fix: accept live frames that agree with shared-root owners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pages that open several live subscriptions over the same root lookup (e.g. git_repositories by id) let the first subscriber own the shared root list and rejected every later whole frame, including frames whose shared lists were identical. Fields only the rejected subscription selects (a repository's branch refs) never updated after a push, and stored rows could drift from rejected lists ("Loading branches…"). A live frame is now admitted when it provably agrees with the owner on every shared list (same rows, order and nulls; owner complete and current); it writes only its own lists. Disagreement or unprovable agreement is still rejected, and the rejected subscription reopens when another query rewrites a shared list. Spec: docs/live-query-delivery.md. Tests: replica-protocol (new agreement/rejection cases; 408/408). Resolves [[incidents/forge-branches-page-writes-disabled-20260930]] Co-Authored-By: Claude Opus 5.5 --- docs/live-query-delivery.md | 18 ++ js/src/replica/distributed-replica/helpers.ts | 111 +++++++-- js/src/replica/distributed-replica/impl.ts | 117 ++++++++- js/src/replica/distributed-replica/types.ts | 11 + js/tests/replica-protocol.test.mjs | 224 +++++++++++++++++- 5 files changed, 447 insertions(+), 34 deletions(-) diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md index 3c584c8fd..aa373488d 100644 --- a/docs/live-query-delivery.md +++ b/docs/live-query-delivery.md @@ -71,6 +71,24 @@ empty result acquire rows without waiting for another page load. It does not override an independently active live stream or query ownership acquired after the subscription started; those results have no safe cross-stream ordering. +Independent streams often share an index without disagreeing about it. A +layout and a page may both select +`repositories(where: { id: { _eq: $id } }, limit: 1)` and then different +relationships below that row. A snapshot frame whose shared indexes have the +same membership as the independent owner's is admitted. Each such index must +contain the same normalized record keys in the same order and the same null +value, and the owner's index must be complete and not stale. The owner keeps +those shared indexes, and the frame writes only its other indexes and its +records. The resulting graph is exactly the frame's server result, so nothing +is fabricated and no cross-stream order is assumed. + +The whole frame is rejected as before if any shared membership differs or +cannot be established. That includes GraphQL errors, operation-local embedded +rows and rows without record evidence. The subscription is then reopened after +another operation next writes one of those shared indexes. The fresh result is +checked against the owner's new membership, so a stream whose frame arrived +before the owner caught up does not wait for its own next server change. + When the last watch for a live operation is disposed, its local ownership is retired at a monotonically increasing local boundary. A later live subscription may take over an incomparable shared index only when that subscription started diff --git a/js/src/replica/distributed-replica/helpers.ts b/js/src/replica/distributed-replica/helpers.ts index 868aec65b..d8ebd69d6 100644 --- a/js/src/replica/distributed-replica/helpers.ts +++ b/js/src/replica/distributed-replica/helpers.ts @@ -105,6 +105,41 @@ export function prepareRecordEvidence( }; } +/** + * Membership a result would write for one index: normalized record keys in + * response order. `null` means it cannot be established from the response + * alone (blocked by errors, missing, embedded, or without record evidence). + */ +export type ReplicaIndexMembership = { + readonly records: readonly string[]; + readonly nullValue: boolean; +}; + +export type ReplicaIndexMemberships = Map; + +function recordMembership( + memberships: ReplicaIndexMemberships | undefined, + key: string, + membership: ReplicaIndexMembership | null +): void { + if (memberships === undefined) return; + const previous = memberships.get(key); + if (previous === undefined) { + memberships.set(key, membership); + return; + } + // One response reaching an index twice must agree with itself. + if ( + previous === null || + membership === null || + previous.nullValue !== membership.nullValue || + previous.records.length !== membership.records.length || + previous.records.some((record, ordinal) => record !== membership.records[ordinal]) + ) { + memberships.set(key, null); + } +} + export function replicaResultIndexKeys< TData, TVariables extends GraphqlVariables @@ -112,7 +147,8 @@ export function replicaResultIndexKeys< artifact: ReplicaOperationArtifact, variables: TVariables, envelope: ReplicaResultEnvelope, - snapshot: DistributedQuerySnapshot + snapshot: DistributedQuerySnapshot, + memberships?: ReplicaIndexMemberships ): ReadonlySet { const keys = new Set(); if ( @@ -156,6 +192,7 @@ export function replicaResultIndexKeys< root.responseKey ) ) { + recordMembership(memberships, rootKey, null); continue; } const value = envelope.data[root.responseKey]; @@ -163,6 +200,7 @@ export function replicaResultIndexKeys< value === null && resultPathHasErrors(errorPaths, rootPath) ) { + recordMembership(memberships, rootKey, null); continue; } collectResultBranchIndexKeys( @@ -174,7 +212,8 @@ export function replicaResultIndexKeys< variables, errorPaths, evidencePaths, - keys + keys, + memberships ); } return keys; @@ -189,11 +228,23 @@ export function collectResultBranchIndexKeys( variables: GraphqlVariables, errorPaths: readonly (readonly (string | number)[])[], evidencePaths: ReadonlySet, - keys: Set + keys: Set, + memberships?: ReplicaIndexMemberships ): void { - if (value === null || value === undefined) return; + if (value === null) { + recordMembership( + memberships, + enclosingIndexKey, + selection.nullable ? { records: [], nullValue: true } : null + ); + return; + } + if (value === undefined) { + recordMembership(memberships, enclosingIndexKey, null); + return; + } if (selection.cardinality === 'one') { - collectResultObjectIndexKeys( + const recordKey = collectResultObjectIndexKeys( artifactId, selection.selection, value, @@ -203,14 +254,28 @@ export function collectResultBranchIndexKeys( variables, errorPaths, evidencePaths, - keys + keys, + memberships + ); + recordMembership( + memberships, + enclosingIndexKey, + recordKey === undefined ? null : { records: [recordKey], nullValue: false } ); return; } - if (!Array.isArray(value)) return; + if (!Array.isArray(value)) { + recordMembership(memberships, enclosingIndexKey, null); + return; + } + const records: string[] = []; + let certain = true; for (const [ordinal, entry] of value.entries()) { - if (entry === null || entry === undefined) continue; - collectResultObjectIndexKeys( + if (entry === null || entry === undefined) { + certain = false; + continue; + } + const recordKey = collectResultObjectIndexKeys( artifactId, selection.selection, entry, @@ -220,9 +285,17 @@ export function collectResultBranchIndexKeys( variables, errorPaths, evidencePaths, - keys + keys, + memberships ); + if (recordKey === undefined) certain = false; + else records.push(recordKey); } + recordMembership( + memberships, + enclosingIndexKey, + certain ? { records, nullValue: false } : null + ); } export function collectResultObjectIndexKeys( @@ -235,10 +308,11 @@ export function collectResultObjectIndexKeys( variables: GraphqlVariables, errorPaths: readonly (readonly (string | number)[])[], evidencePaths: ReadonlySet, - keys: Set -): void { + keys: Set, + memberships?: ReplicaIndexMemberships +): string | undefined { if (resultPathBlocked(errorPaths, path) || !isReplicaResultObject(value)) { - return; + return undefined; } const fields = new Map(); for (const member of selection.members) { @@ -260,6 +334,7 @@ export function collectResultObjectIndexKeys( } } let parentKey: string; + let normalized = false; if ( selection.storage.kind === 'normalized' && evidencePaths.has(responsePathKey(path.map(String))) @@ -268,7 +343,8 @@ export function collectResultObjectIndexKeys( const value = fields.get(field); return value === undefined || value === null ? [] : [value]; }); - if (identity.length !== selection.storage.identityFields.length) return; + if (identity.length !== selection.storage.identityFields.length) return undefined; + normalized = true; parentKey = replicaRecordKey( { id: selection.storage.model, @@ -300,6 +376,7 @@ export function collectResultObjectIndexKeys( resultPathBlocked(errorPaths, branchPath) || !Object.prototype.hasOwnProperty.call(value, member.responseKey) ) { + recordMembership(memberships, branchKey, null); continue; } const branchValue = value[member.responseKey]; @@ -307,6 +384,7 @@ export function collectResultObjectIndexKeys( branchValue === null && resultPathHasErrors(errorPaths, branchPath) ) { + recordMembership(memberships, branchKey, null); continue; } collectResultBranchIndexKeys( @@ -318,9 +396,12 @@ export function collectResultObjectIndexKeys( variables, errorPaths, evidencePaths, - keys + keys, + memberships ); } + // Embedded rows are operation-local; they never share an index membership. + return normalized ? parentKey : undefined; } export function resultPathBlocked( diff --git a/js/src/replica/distributed-replica/impl.ts b/js/src/replica/distributed-replica/impl.ts index df2752ea0..dfb3dd46f 100644 --- a/js/src/replica/distributed-replica/impl.ts +++ b/js/src/replica/distributed-replica/impl.ts @@ -145,6 +145,7 @@ import { prepareRecordEvidence, protocolOperationSource, replicaResultIndexKeys, + type ReplicaIndexMemberships, reportSafely, reportUnhandledObserverError, snapshotFrom, @@ -1215,18 +1216,35 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { handoff && activeState !== undefined ? compareSnapshotToOperationState(activeState, snapshot) : 'fresh'; - const sharedDisposition = this.#sharedIndexDisposition( + const incomingMemberships: ReplicaIndexMemberships = new Map(); + const fencedSharedDisposition = this.#sharedIndexDisposition( key, replicaResultIndexKeys( artifact, stableVariables, envelope, - snapshot + snapshot, + incomingMemberships ), snapshot, requestRevision, source ); + /* + * A snapshot frame that agrees with an independent owner on every + * index they share is exactly its server result once admitted: the + * owner keeps those indexes and this frame writes only the rest + * (docs/live-query-delivery.md). Disagreement keeps the atomic fence. + */ + const fencedIndexKeys = + snapshotLive ? fencedSharedDisposition.fencedIndexKeys : undefined; + const sharedMembershipAdmitted = + fencedIndexKeys !== undefined && + (envelope.errors ?? []).length === 0 && + this.#fencedMembershipsMatch(fencedIndexKeys, incomingMemberships); + const sharedDisposition: SharedIndexDisposition = sharedMembershipAdmitted + ? { compared: false } + : fencedSharedDisposition; // A non-resumable stream has no causal vector to compare. An HTTP // refresh may replace it only if the request began after its last // accepted membership. fetchWatch also fences intervening live frames. @@ -1486,7 +1504,10 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { let summary: ReturnType; try { const update = (writer: BaseCacheWriter) => { - const guarded = this.#guardIndexWriter(writer); + const guarded = this.#guardIndexWriter( + writer, + sharedMembershipAdmitted ? fencedIndexKeys : undefined + ); this.#applyTombstoneEvidence( guarded, recordEvidence.tombstones, @@ -1627,6 +1648,24 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { if (source !== 'live' && sourceSwitched) { this.#restartLive(key); } + if (source === 'live') { + const liveEntry = this.#lives.get(key); + if (liveEntry !== undefined) { + liveEntry.fencedIndexKeys = + fencedIndexKeys !== undefined && !sharedMembershipAdmitted + ? fencedIndexKeys + : undefined; + } + } + if (writeIndexes) { + this.#reopenStreamsFencedBy( + key, + summary.indexKeys.filter( + (indexKey) => + !(sharedMembershipAdmitted && fencedIndexKeys!.has(indexKey)) + ) + ); + } if (source === 'live' && sharedDisposition.restartAfterRetirement) { // This receiver began before a shared owner retired. Its buffered // frame stays fenced, but a fresh receiver starts after that boundary @@ -1825,7 +1864,12 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { } } - #guardIndexWriter(writer: BaseCacheWriter): BaseCacheWriter { + #guardIndexWriter( + writer: BaseCacheWriter, + ownedElsewhere?: ReadonlySet + ): BaseCacheWriter { + // Equal shared memberships stay with their independent owner. + const skip = (key: string): boolean => ownedElsewhere?.has(key) === true; return { recordClock: (key) => writer.recordClock(key), writeRecord: (write) => writer.writeRecord(write), @@ -1833,6 +1877,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { writer.tombstoneRecord(key, revision, incarnation), discardRecord: (key) => writer.discardRecord(key), writeIndex: (write) => { + if (skip(write.key)) return false; const recordsForIndex = this.#membershipFences.get(write.key); if (write.complete === true && recordsForIndex !== undefined) { const visible = @@ -1860,11 +1905,59 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { return wrote; }, markIndexStale: (key, reason, revision) => - writer.markIndexStale(key, reason, revision), - deleteIndex: (key, revision) => writer.deleteIndex(key, revision) + !skip(key) && writer.markIndexStale(key, reason, revision), + deleteIndex: (key, revision) => + !skip(key) && writer.deleteIndex(key, revision) }; } + #fencedMembershipsMatch( + fencedIndexKeys: ReadonlySet, + incoming: ReplicaIndexMemberships + ): boolean { + return this.#engine.readConfirmed((reader) => { + for (const indexKey of fencedIndexKeys) { + const membership = incoming.get(indexKey); + const current = reader.index(indexKey); + if ( + membership === undefined || + membership === null || + current === undefined || + !current.complete || + (current.staleRevision !== undefined && + compareCanonicalDecimalStrings(current.staleRevision, current.revision) > 0) || + (current.metadata?.nullValue === true) !== membership.nullValue || + current.records.length !== membership.records.length || + current.records.some( + (record, ordinal) => record !== membership.records[ordinal] + ) + ) { + return false; + } + } + return true; + }); + } + + /** + * Reopen live streams whose last frame was fenced by a shared index that + * another operation has now rewritten, so a fresh authoritative result is + * compared against the new owner membership. + */ + #reopenStreamsFencedBy(writerKey: string, writtenKeys: readonly string[]): void { + if (writtenKeys.length === 0) return; + const reopen: string[] = []; + for (const [liveKey, entry] of this.#lives) { + if (liveKey === writerKey || !entry.active) continue; + const fenced = entry.fencedIndexKeys; + if (fenced === undefined) continue; + if (writtenKeys.some((indexKey) => fenced.has(indexKey))) { + reopen.push(liveKey); + } + } + for (const liveKey of reopen) this.#restartLive(liveKey); + } + #flushDeferredMembershipConfirms(): void { for (const commandId of [...this.#deferredMembershipConfirms]) { if (this.#commandHasMembershipFence(commandId)) continue; @@ -2347,23 +2440,23 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { let higher = false; let incomparable = false; let restartAfterRetirement = false; + const fencedIndexKeys = new Set(); let equalRevision: string | undefined; let latestOwnerRevision: string | undefined; for (const [key, group] of this.#operationProtocols) { if (key === currentKey) continue; for (const state of [group.query, group.live]) { if (state?.indexRevision === undefined) continue; - let ownsIncomingIndex = false; + const ownedIncomingKeys: string[] = []; for (const indexKey of state.indexKeys) { if ( incomingIndexKeys.has(indexKey) && confirmedRevisions.get(indexKey) === state.indexRevision ) { - ownsIncomingIndex = true; - break; + ownedIncomingKeys.push(indexKey); } } - if (!ownsIncomingIndex) continue; + if (ownedIncomingKeys.length === 0) continue; if ( !snapshot.indexesComparable && state === group.live && @@ -2418,6 +2511,7 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { compareCanonicalDecimalStrings(liveStart, state.indexRevision) > 0 ) continue; incomparable = true; + for (const indexKey of ownedIncomingKeys) fencedIndexKeys.add(indexKey); continue; } compared = true; @@ -2454,7 +2548,8 @@ export class DistributedReplicaImpl implements DistributedReplicaApi { return { compared: true, disposition: 'lower', - ...(restartAfterRetirement ? { restartAfterRetirement: true } : {}) + ...(restartAfterRetirement ? { restartAfterRetirement: true } : {}), + ...(!snapshot.indexesComparable ? { fencedIndexKeys } : {}) }; } if (requestRevision === undefined) return { compared: false }; diff --git a/js/src/replica/distributed-replica/types.ts b/js/src/replica/distributed-replica/types.ts index 41998d425..686038609 100644 --- a/js/src/replica/distributed-replica/types.ts +++ b/js/src/replica/distributed-replica/types.ts @@ -37,6 +37,11 @@ export type LiveEntry = { failures?: number; /** Pending reopen of this inactive entry after a live failure frame. */ retry?: ReturnType; + /** + * Shared indexes whose independent owner disagreed with this stream's last + * frame. Another operation rewriting one of them reopens this stream. + */ + fencedIndexKeys?: ReadonlySet; }; export type ProtocolGeneration = { @@ -174,6 +179,12 @@ export type SharedIndexDisposition = { readonly disposition?: 'equal' | 'higher' | 'lower'; readonly indexRevision?: string; readonly restartAfterRetirement?: boolean; + /** + * Incoming indexes owned by an independent live stream or later query + * owner. A snapshot frame may be admitted without writing them when its + * membership for each is identical to the owner's. + */ + readonly fencedIndexKeys?: ReadonlySet; }; export type CapturedReplicaOptimisticOperation = diff --git a/js/tests/replica-protocol.test.mjs b/js/tests/replica-protocol.test.mjs index e71ef9cd4..f7955b84f 100644 --- a/js/tests/replica-protocol.test.mjs +++ b/js/tests/replica-protocol.test.mjs @@ -1945,6 +1945,209 @@ test('snapshot live cannot supersede an incomparable sibling index owner', async assert.equal(unsubscribeCount, 1); }); +// A layout and a page commonly open independent snapshot streams over the same +// root row and select different relationships below it. +const GamesRootLive = Object.freeze({ + ...GamesWithOwner, + id: 'query:games-root-live', + document: 'query GamesRoot { games { id owner_id } }', + protocol: Object.freeze({ + ...GamesWithOwner.protocol, + operation: 'query:games-root-live' + }), + live: Object.freeze({ + id: 'live:games-root', + document: 'subscription GamesRootLive { games { id owner_id } }' + }), + roots: Object.freeze([ + Object.freeze({ + ...GamesWithOwner.roots[0], + selection: Object.freeze({ + ...GamesWithOwner.roots[0].selection, + members: Object.freeze( + GamesWithOwner.roots[0].selection.members.filter( + (member) => member.kind === 'scalar' + ) + ) + }) + }) + ]) +}); + +function sharedGamesFrame({ artifact, games, revision = '1', withOwner }) { + const records = games.flatMap((game, index) => [ + { + path: ['games', String(index)], + model: 'GameView', + scopeToken: `record:${game.id}`, + incarnation: '1', + revision, + tombstone: false + }, + ...(withOwner + ? [{ + path: ['games', String(index), 'owner'], + model: 'UserView', + scopeToken: `record:${game.owner_id}`, + incarnation: '1', + revision, + tombstone: false + }] + : []) + ]); + return { + data: { + games: games.map((game) => withOwner + ? { id: game.id, owner_id: game.owner_id, owner: { id: game.owner_id, name: game.name } } + : { id: game.id, owner_id: game.owner_id }) + }, + extensions: { + distributed: { + protocolVersion: DISTRIBUTED_PROTOCOL_VERSION, + schemaHash: 'schema-a', + authorizationGeneration: 'auth-1', + cacheScope: 'cache:a', + operation: artifact.live.id, + snapshot: { + scopeToken: `snapshot:${artifact.id}`, + recordsComplete: true, + indexesComparable: false, + records, + indexes: [], + observations: [] + }, + live: { mode: 'snapshot', reset: true, cursors: [] } + } + } + }; +} + +function sharedGamesHarness() { + const subscriptions = []; + const replica = createDistributedReplica({ + transport: { + fetch() { + return new Promise(() => {}); + }, + subscribe(request, observer) { + const subscription = { operation: request.operationId, observer, closed: false }; + subscriptions.push(subscription); + return () => { + subscription.closed = true; + }; + } + } + }); + const latest = (operation) => + subscriptions.filter((entry) => entry.operation === operation).at(-1); + return { replica, subscriptions, latest }; +} + +test('snapshot live admits a frame whose shared membership matches an independent owner', () => { + const { replica, latest } = sharedGamesHarness(); + const layout = replica.watch(GamesRootLive, {}, { live: true }); + latest('live:games-root').observer.next(sharedGamesFrame({ + artifact: GamesRootLive, games: [{ id: 'game-1', owner_id: 'user-1' }] + })); + const page = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + const pageStream = latest('live:games-with-owner'); + pageStream.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, + games: [{ id: 'game-1', owner_id: 'user-1', name: 'Owner' }] + })); + assert.deepEqual(replica.read(GamesWithOwnerLiveOperation, {}).data.games, [ + { id: 'game-1', owner_id: 'user-1', owner: { id: 'user-1', name: 'Owner' } } + ], 'the first page frame renders although the layout owns the shared root'); + + // A later page frame changes only its own relationship below the shared row. + pageStream.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, revision: '2', + games: [{ id: 'game-1', owner_id: 'user-2', name: 'Second' }] + })); + assert.deepEqual(replica.read(GamesWithOwnerLiveOperation, {}).data.games, [ + { id: 'game-1', owner_id: 'user-2', owner: { id: 'user-2', name: 'Second' } } + ], 'a live update to a relationship-joined row is delivered'); + + // The admitted page stream did not take the shared root from the layout. + latest('live:games-root').observer.next(sharedGamesFrame({ + artifact: GamesRootLive, revision: '3', + games: [{ id: 'game-1', owner_id: 'user-2' }, { id: 'game-3', owner_id: 'user-3' }] + })); + assert.deepEqual( + replica.read(GamesRootLive, {}).data.games.map((game) => game.id), + ['game-1', 'game-3'] + ); + pageStream.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, revision: '3', + games: [ + { id: 'game-1', owner_id: 'user-2', name: 'Second' }, + { id: 'game-3', owner_id: 'user-3', name: 'Third' } + ] + })); + assert.deepEqual( + replica.read(GamesWithOwnerLiveOperation, {}).data.games.map((game) => game.owner.name), + ['Second', 'Third'] + ); + assert.equal(page.get().live, 'active'); + assert.equal(pageStream.closed, false, 'agreeing frames never reopen the stream'); + page.destroy(); + layout.destroy(); +}); + +test('snapshot live keeps a disagreeing frame fenced and reopens after the owner catches up', () => { + const { replica, subscriptions, latest } = sharedGamesHarness(); + const layout = replica.watch(GamesRootLive, {}, { live: true }); + latest('live:games-root').observer.next(sharedGamesFrame({ + artifact: GamesRootLive, games: [{ id: 'game-1', owner_id: 'user-1' }] + })); + const page = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + const firstPageStream = latest('live:games-with-owner'); + // The page stream observed a newer membership than the layout owner. + firstPageStream.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, revision: '2', + games: [ + { id: 'game-1', owner_id: 'user-1', name: 'Owner' }, + { id: 'game-2', owner_id: 'user-2', name: 'Second' } + ] + })); + assert.deepEqual( + replica.read(GamesRootLive, {}).data.games.map((game) => game.id), + ['game-1'], + 'a disagreeing frame cannot replace the independent owner membership' + ); + assert.equal(firstPageStream.closed, false); + const subscriptionCount = subscriptions.length; + + latest('live:games-root').observer.next(sharedGamesFrame({ + artifact: GamesRootLive, revision: '2', + games: [{ id: 'game-1', owner_id: 'user-1' }, { id: 'game-2', owner_id: 'user-2' }] + })); + assert.equal(firstPageStream.closed, true, 'the owner rewrite reopens the fenced stream'); + assert.equal(subscriptions.length, subscriptionCount + 1); + const reopened = latest('live:games-with-owner'); + assert.notEqual(reopened, firstPageStream); + + // A late frame from the closed stream stays fenced. + firstPageStream.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, revision: '2', + games: [{ id: 'game-1', owner_id: 'user-1', name: 'Late' }] + })); + reopened.observer.next(sharedGamesFrame({ + artifact: GamesWithOwnerLiveOperation, withOwner: true, revision: '2', + games: [ + { id: 'game-1', owner_id: 'user-1', name: 'Owner' }, + { id: 'game-2', owner_id: 'user-2', name: 'Second' } + ] + })); + assert.deepEqual( + replica.read(GamesWithOwnerLiveOperation, {}).data.games.map((game) => game.owner.name), + ['Owner', 'Second'] + ); + assert.equal(page.get().live, 'active'); + page.destroy(); + layout.destroy(); +}); + test('snapshot live replaces SSR membership, updates and removes rows, and fences disposal', () => { let observer; const replica = createDistributedReplica({ transport: { @@ -2046,10 +2249,12 @@ test('snapshot live keeps a stream started before disposal behind the retired ow empty.extensions.distributed.snapshot.records = []; replica.writeResult(GamesWithOwnerLiveOperation, {}, empty, 'ssr'); const current = replica.watch(GamesWithOwnerLiveOperation, {}, { live: true }); + // The contender disagrees with the active owner's shared owner membership; + // agreeing frames are admitted (docs/live-query-delivery.md). observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '3', - ownerId: 'user-1', ownerName: 'started before disposal', indexesComparable: false, + ownerId: 'user-2', ownerName: 'started before disposal', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(current.get().data.games, []); @@ -2060,7 +2265,7 @@ test('snapshot live keeps a stream started before disposal behind the retired ow observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '4', - ownerId: 'user-1', ownerName: 'still started before disposal', indexesComparable: false, + ownerId: 'user-2', ownerName: 'still started before disposal', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(current.get().data.games, []); @@ -2070,7 +2275,7 @@ test('snapshot live keeps a stream started before disposal behind the retired ow observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '5', - ownerId: 'user-1', ownerName: 'queued old receiver', indexesComparable: false, + ownerId: 'user-2', ownerName: 'queued old receiver', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(current.get().data.games, [], 'old receiver stays fenced after reopening'); @@ -2096,8 +2301,8 @@ test('reopening a retired live owner restores its ownership fence', () => { ...FeaturedGamesWithOwner, live: { id: 'live:featured-owner-reopened', document: 'subscription FeaturedOwnerReopened { featuredGames { id owner { id name } } }' } }; - const frame = (artifact, responseKey, operation, position, ownerName) => gamesFrame({ - artifact, responseKey, operation, position, ownerId: 'user-1', ownerName, + const frame = (artifact, responseKey, operation, position, ownerName, ownerId = 'user-1') => gamesFrame({ + artifact, responseKey, operation, position, ownerId, ownerName, indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } }); const replica = createDistributedReplica({ transport: { @@ -2126,7 +2331,9 @@ test('reopening a retired live owner restores its ownership fence', () => { 'games', GamesWithOwnerLiveOperation.live.id, '4', - 'current contender' + 'current contender', + // Disagrees with the reopened owner; an agreeing frame is admitted. + 'user-2' )); assert.deepEqual(current.get().data.games, []); reopened.destroy(); @@ -2209,7 +2416,8 @@ test('two watches retire shared live ownership only after final disposal', () => observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '3', - ownerId: 'user-1', ownerName: 'before final release', indexesComparable: false, + // Disagrees with the owner; an agreeing frame is admitted. + ownerId: 'user-2', ownerName: 'before final release', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(startedBeforeFinalRelease.get().data.games, []); @@ -2218,7 +2426,7 @@ test('two watches retire shared live ownership only after final disposal', () => observers[1].next(gamesFrame({ artifact: GamesWithOwnerLiveOperation, responseKey: 'games', operation: GamesWithOwnerLiveOperation.live.id, position: '4', - ownerId: 'user-1', ownerName: 'still before final release', indexesComparable: false, + ownerId: 'user-2', ownerName: 'still before final release', indexesComparable: false, live: { mode: 'snapshot', reset: true, cursors: [] } })); assert.deepEqual(startedBeforeFinalRelease.get().data.games, []); From 2ab34adebeb2272689f6f639d7dc0484f01145a8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:45:38 -0500 Subject: [PATCH 119/484] feat(leaderboard): add sorted-set leaderboard projection Add a dedicated leaderboard module instead of forcing sorted sets into the relational read-model traits: a typed LeaderboardStore (submit with max/min/replace/increment, rank, score, top, around, reset, staging + promote rebuild, prune_applied), an InMemoryLeaderboard matching Redis ordering, a LeaderboardProjector that applies DomainEventOccurrences or outbox messages idempotently (per-board applied-key set keyed by "#") and rebuilds into staging boards. The new `redis` feature (redis 1.7.1, tokio) adds RedisLeaderboard, whose idempotent apply is one atomic Lua script, and a bounded fire-and-forget BackgroundLeaderboard so Redis outages never block gameplay. Default features are unchanged. Refs [[tasks/gr-p9-redis]] --- Cargo.toml | 3 + README.md | 1 + compose.yaml | 12 + src/leaderboard/background.rs | 298 +++++++++++++++++++ src/leaderboard/conformance.rs | 271 +++++++++++++++++ src/leaderboard/in_memory.rs | 224 ++++++++++++++ src/leaderboard/mod.rs | 519 +++++++++++++++++++++++++++++++++ src/leaderboard/projector.rs | 504 ++++++++++++++++++++++++++++++++ src/leaderboard/redis.rs | 473 ++++++++++++++++++++++++++++++ src/lib.rs | 1 + 10 files changed, 2306 insertions(+) create mode 100644 src/leaderboard/background.rs create mode 100644 src/leaderboard/conformance.rs create mode 100644 src/leaderboard/in_memory.rs create mode 100644 src/leaderboard/mod.rs create mode 100644 src/leaderboard/projector.rs create mode 100644 src/leaderboard/redis.rs diff --git a/Cargo.toml b/Cargo.toml index fc02e1729..23d347b5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,8 @@ sqlite = ["dep:sqlx", "dep:tokio", "sqlx/migrate", "sqlx/runtime-tokio", "sqlx/s nats = ["dep:async-nats", "dep:futures", "dep:tokio"] rabbitmq = ["dep:lapin", "dep:futures", "dep:tokio"] kafka = ["dep:rdkafka", "dep:tokio"] +# Redis sorted-set leaderboards and the Redis Streams `MessagePublisher`. +redis = ["dep:redis", "dep:tokio"] workers-rs = ["dep:worker"] otel = ["dep:opentelemetry", "dep:opentelemetry_sdk", "dep:tracing", "dep:tracing-opentelemetry"] graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:hmac", "dep:jsonwebtoken", "http", "axum?/ws"] @@ -75,6 +77,7 @@ base64 = "0.23.0" futures = { version = "0.3", optional = true } lapin = { version = "4", optional = true } rdkafka = { version = "0.39", features = ["cmake-build", "tokio"], optional = true } +redis = { version = "1.7.1", default-features = false, features = ["script", "streams", "tokio-comp", "connection-manager"], optional = true } reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"], optional = true } jsonwebtoken = { version = "9", optional = true } bitcode = { version = "0.6.9", features = ["serde"] } diff --git a/README.md b/README.md index 59a79bdde..47b31c59d 100644 --- a/README.md +++ b/README.md @@ -704,6 +704,7 @@ network servers. | `nats` | No | `NatsBus` (NATS JetStream source/publisher). | | `rabbitmq` | No | `RabbitBus` (RabbitMQ source/publisher). | | `kafka` | No | `KafkaBus` (Kafka source/publisher). | +| `redis` | No | `leaderboard::RedisLeaderboard` (sorted-set leaderboards, `BackgroundLeaderboard`) and `bus::RedisStreamPublisher` (Redis Streams `XADD`, id dedupe). The `leaderboard` module and `InMemoryLeaderboard` are always available. | > The `InMemoryBus`, `PostgresBus`, and `SqliteBus` need no separate broker > feature. SQL-backed bus support comes from the matching `postgres` or `sqlite` diff --git a/compose.yaml b/compose.yaml index 37ceb4c76..40e5dbd5d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -14,6 +14,8 @@ # cargo test --test kafka_transport --features kafka # NATS_URL=nats://localhost:4222 \ # cargo test --test nats_transport --features nats +# REDIS_URL=redis://127.0.0.1:6379 \ +# cargo test --test redis_leaderboard --features redis services: postgres: image: postgres:18 @@ -73,3 +75,13 @@ services: interval: 5s timeout: 5s retries: 20 + + redis: + image: redis:8.2-alpine + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 5s + retries: 20 diff --git a/src/leaderboard/background.rs b/src/leaderboard/background.rs new file mode 100644 index 000000000..0bc5ff8c6 --- /dev/null +++ b/src/leaderboard/background.rs @@ -0,0 +1,298 @@ +//! Fire-and-forget leaderboard updates on a background task. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::mpsc; + +use crate::DomainEventOccurrence; + +use super::{LeaderboardErrorKind, LeaderboardProjection, LeaderboardProjector, LeaderboardStore}; + +/// Tuning for [`BackgroundLeaderboard`]. +#[derive(Debug, Clone)] +pub struct BackgroundLeaderboardOptions { + /// Queue capacity; [`BackgroundLeaderboard::submit`] drops when full. + pub capacity: usize, + /// Attempts per occurrence while the store is unavailable (>= 1). + pub max_attempts: u32, + /// Delay before the first retry; doubles per attempt. + pub retry_backoff: Duration, +} + +impl Default for BackgroundLeaderboardOptions { + fn default() -> Self { + Self { + capacity: 4_096, + max_attempts: 3, + retry_backoff: Duration::from_millis(50), + } + } +} + +/// Counters exposed by [`BackgroundLeaderboard::stats`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BackgroundStats { + /// Occurrences accepted into the queue. + pub enqueued: u64, + /// Occurrences rejected because the queue was full or closed. + pub dropped: u64, + /// Occurrences fully applied (including duplicates). + pub applied: u64, + /// Occurrences abandoned after an invalid change or exhausted retries. + pub failed: u64, +} + +#[derive(Default)] +struct Counters { + enqueued: AtomicU64, + dropped: AtomicU64, + applied: AtomicU64, + failed: AtomicU64, +} + +/// A bounded in-process queue in front of a [`LeaderboardProjector`]. +/// +/// [`submit`](Self::submit) never awaits and never fails the caller: it is safe +/// to call from a gameplay command path or zone tick. A background task applies +/// occurrences in order, retrying while the store is unavailable; when the +/// queue is full or retries are exhausted the update is dropped and counted. +/// Because applies are idempotent, any loss is repaired by replaying the event +/// stream or rebuilding the board — for guaranteed delivery feed the projector +/// from the outbox instead (see the [module docs](super)). +pub struct BackgroundLeaderboard { + tx: mpsc::Sender, + counters: Arc, +} + +impl BackgroundLeaderboard { + /// Spawn the worker on the current Tokio runtime. The worker stops once + /// every handle is dropped and the queue drains. + pub fn spawn( + projector: LeaderboardProjector, + options: BackgroundLeaderboardOptions, + ) -> Self + where + S: LeaderboardStore + ?Sized + 'static, + P: LeaderboardProjection + ?Sized + 'static, + { + let (tx, mut rx) = mpsc::channel::(options.capacity.max(1)); + let counters = Arc::new(Counters::default()); + let worker = Arc::clone(&counters); + tokio::spawn(async move { + while let Some(event) = rx.recv().await { + let mut backoff = options.retry_backoff; + let mut attempt = 1; + loop { + match projector.apply_event(&event).await { + Ok(_) => { + worker.applied.fetch_add(1, Ordering::Relaxed); + break; + } + Err(err) + if err.kind() == LeaderboardErrorKind::Unavailable + && attempt < options.max_attempts.max(1) => + { + tokio::time::sleep(backoff).await; + backoff = backoff.saturating_mul(2); + attempt += 1; + } + Err(_) => { + worker.failed.fetch_add(1, Ordering::Relaxed); + break; + } + } + } + } + }); + Self { tx, counters } + } + + /// Enqueue an occurrence without waiting; returns `false` (and counts a + /// drop) when the queue is full or the worker has stopped. + pub fn submit(&self, event: DomainEventOccurrence) -> bool { + match self.tx.try_send(event) { + Ok(()) => { + self.counters.enqueued.fetch_add(1, Ordering::Relaxed); + true + } + Err(_) => { + self.counters.dropped.fetch_add(1, Ordering::Relaxed); + false + } + } + } + + /// A snapshot of the counters. + pub fn stats(&self) -> BackgroundStats { + BackgroundStats { + enqueued: self.counters.enqueued.load(Ordering::Relaxed), + dropped: self.counters.dropped.load(Ordering::Relaxed), + applied: self.counters.applied.load(Ordering::Relaxed), + failed: self.counters.failed.load(Ordering::Relaxed), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::leaderboard::{ + ApplyKey, ApplyOutcome, Board, InMemoryLeaderboard, LeaderboardChange, LeaderboardEntry, + LeaderboardError, ScorePolicy, ScoreSubmission, + }; + use async_trait::async_trait; + use std::sync::atomic::AtomicU32; + use std::time::UNIX_EPOCH; + + #[derive(serde::Serialize, serde::Deserialize, crate::DomainEvent)] + #[domain_event(name = "test.points_won", version = 1)] + struct PointsWon { + points: u32, + } + + fn event(position: u64) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + crate::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "points".into(), + }, + UNIX_EPOCH, + Default::default(), + &PointsWon { points: 1 }, + ) + .unwrap() + } + + fn board() -> Board { + Board::high_first("points").unwrap() + } + + fn projection(_: &DomainEventOccurrence) -> Result, LeaderboardError> { + Ok(vec![LeaderboardChange::new( + board(), + ScoreSubmission::new("p", 1.0, ScorePolicy::Increment), + )]) + } + + /// Fails the first `failures` applies as unavailable, then delegates. + struct Flaky { + inner: InMemoryLeaderboard, + failures: AtomicU32, + } + + #[async_trait] + impl LeaderboardStore for Flaky { + async fn submit(&self, b: &Board, s: &ScoreSubmission) -> Result { + self.inner.submit(b, s).await + } + async fn apply( + &self, + b: &Board, + s: &ScoreSubmission, + k: &ApplyKey, + ) -> Result { + // Only the single background worker calls `apply`, so load-then-store is race-free. + let remaining = self.failures.load(Ordering::SeqCst); + if remaining > 0 { + self.failures.store(remaining - 1, Ordering::SeqCst); + return Err(LeaderboardError::unavailable("blip")); + } + self.inner.apply(b, s, k).await + } + async fn score(&self, b: &Board, m: &str) -> Result, LeaderboardError> { + self.inner.score(b, m).await + } + async fn rank(&self, b: &Board, m: &str) -> Result, LeaderboardError> { + self.inner.rank(b, m).await + } + async fn top( + &self, + b: &Board, + n: usize, + ) -> Result, LeaderboardError> { + self.inner.top(b, n).await + } + async fn around( + &self, + b: &Board, + m: &str, + r: usize, + ) -> Result, LeaderboardError> { + self.inner.around(b, m, r).await + } + async fn len(&self, b: &Board) -> Result { + self.inner.len(b).await + } + async fn remove(&self, b: &Board, m: &str) -> Result { + self.inner.remove(b, m).await + } + async fn reset(&self, b: &Board) -> Result<(), LeaderboardError> { + self.inner.reset(b).await + } + async fn promote(&self, b: &Board) -> Result<(), LeaderboardError> { + self.inner.promote(b).await + } + async fn prune_applied(&self, b: &Board, t: u64) -> Result { + self.inner.prune_applied(b, t).await + } + } + + async fn settle(handle: &BackgroundLeaderboard, done: u64) { + for _ in 0..200 { + let stats = handle.stats(); + if stats.applied + stats.failed >= done { + return; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("background worker did not settle: {:?}", handle.stats()); + } + + #[tokio::test] + async fn retries_through_a_blip_then_drops_when_exhausted() { + let store = Arc::new(Flaky { + inner: InMemoryLeaderboard::new(), + failures: AtomicU32::new(2), + }); + let projector = LeaderboardProjector::new(Arc::clone(&store), Arc::new(projection)); + let options = BackgroundLeaderboardOptions { + capacity: 8, + max_attempts: 3, + retry_backoff: Duration::from_millis(1), + }; + let handle = BackgroundLeaderboard::spawn(projector, options); + assert!(handle.submit(event(1))); + settle(&handle, 1).await; + assert_eq!(store.score(&board(), "p").await.unwrap(), Some(1.0)); + + store.failures.store(10, Ordering::SeqCst); + assert!(handle.submit(event(2))); + settle(&handle, 2).await; + let stats = handle.stats(); + assert_eq!((stats.applied, stats.failed), (1, 1)); + assert_eq!(store.score(&board(), "p").await.unwrap(), Some(1.0)); + } + + #[tokio::test(flavor = "current_thread")] + async fn submit_never_blocks_and_counts_drops_when_full() { + let projector = + LeaderboardProjector::new(Arc::new(InMemoryLeaderboard::new()), Arc::new(projection)); + let options = BackgroundLeaderboardOptions { + capacity: 2, + ..BackgroundLeaderboardOptions::default() + }; + let handle = BackgroundLeaderboard::spawn(projector, options); + // The current-thread worker cannot run until we yield, so the third + // submit finds the queue full. + assert!(handle.submit(event(1))); + assert!(handle.submit(event(2))); + assert!(!handle.submit(event(3))); + assert_eq!(handle.stats().dropped, 1); + settle(&handle, 2).await; + assert_eq!(handle.stats().applied, 2); + } +} diff --git a/src/leaderboard/conformance.rs b/src/leaderboard/conformance.rs new file mode 100644 index 000000000..9596857aa --- /dev/null +++ b/src/leaderboard/conformance.rs @@ -0,0 +1,271 @@ +//! Behavioural contract every [`LeaderboardStore`] must satisfy. +//! +//! Run by the in-memory unit tests and by the Redis integration test, so both +//! implementations are held to identical ordering, policy, idempotency and +//! rebuild semantics. Panics on the first violation. + +use super::{ + ApplyKey, ApplyOutcome, Board, LeaderboardErrorKind, LeaderboardStore, ScorePolicy, + ScoreSubmission, +}; + +fn sub(member: &str, score: f64, policy: ScorePolicy) -> ScoreSubmission { + ScoreSubmission::new(member, score, policy) +} + +fn rows(entries: &[super::LeaderboardEntry]) -> Vec<(u64, &str, f64)> { + entries + .iter() + .map(|e| (e.rank, e.member.as_str(), e.score)) + .collect() +} + +/// Run the whole contract using boards whose names start with `prefix`. +/// Boards are reset first, so a shared Redis is fine with a unique prefix. +pub async fn run_store_contract(store: &S, prefix: &str) { + policies(store, prefix).await; + ordering_and_queries(store, prefix).await; + idempotent_apply(store, prefix).await; + rebuild_and_promote(store, prefix).await; + validation(store, prefix).await; +} + +async fn fresh(store: &S, board: Board) -> Board { + store.reset(&board).await.unwrap(); + store.reset(&board.staging()).await.unwrap(); + board +} + +async fn policies(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-policies")).unwrap(), + ) + .await; + use ScorePolicy::*; + assert_eq!( + store.submit(&board, &sub("max", 10.0, Max)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("max", 5.0, Max)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("max", 12.5, Max)).await.unwrap(), + 12.5 + ); + assert_eq!( + store.submit(&board, &sub("min", 10.0, Min)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("min", 15.0, Min)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("min", -3.0, Min)).await.unwrap(), + -3.0 + ); + assert_eq!( + store + .submit(&board, &sub("rep", 10.0, Replace)) + .await + .unwrap(), + 10.0 + ); + assert_eq!( + store + .submit(&board, &sub("rep", 1.0, Replace)) + .await + .unwrap(), + 1.0 + ); + assert_eq!( + store + .submit(&board, &sub("inc", 2.5, Increment)) + .await + .unwrap(), + 2.5 + ); + assert_eq!( + store + .submit(&board, &sub("inc", 4.0, Increment)) + .await + .unwrap(), + 6.5 + ); + assert_eq!( + store + .submit(&board, &sub("inc", -1.5, Increment)) + .await + .unwrap(), + 5.0 + ); + assert_eq!(store.score(&board, "max").await.unwrap(), Some(12.5)); + assert_eq!(store.score(&board, "missing").await.unwrap(), None); + assert_eq!(store.len(&board).await.unwrap(), 4); + assert!(store.remove(&board, "rep").await.unwrap()); + assert!(!store.remove(&board, "rep").await.unwrap()); + assert_eq!(store.len(&board).await.unwrap(), 3); +} + +async fn ordering_and_queries(store: &S, prefix: &str) { + let high = fresh(store, Board::high_first(format!("{prefix}-high")).unwrap()).await; + let low = fresh(store, Board::low_first(format!("{prefix}-low")).unwrap()).await; + for (member, score) in [ + ("a", 30.0), + ("b", 10.0), + ("c", 20.0), + ("d", 20.0), + ("e", 5.0), + ] { + for board in [&high, &low] { + store + .submit(board, &sub(member, score, ScorePolicy::Replace)) + .await + .unwrap(); + } + } + // Ties break by member bytes: descending on HighFirst, ascending on LowFirst. + assert_eq!( + rows(&store.top(&high, 10).await.unwrap()), + vec![ + (0, "a", 30.0), + (1, "d", 20.0), + (2, "c", 20.0), + (3, "b", 10.0), + (4, "e", 5.0) + ] + ); + assert_eq!( + rows(&store.top(&low, 2).await.unwrap()), + vec![(0, "e", 5.0), (1, "b", 10.0)] + ); + assert!(store.top(&high, 0).await.unwrap().is_empty()); + assert_eq!(store.rank(&high, "a").await.unwrap(), Some(0)); + assert_eq!(store.rank(&high, "c").await.unwrap(), Some(2)); + assert_eq!(store.rank(&low, "a").await.unwrap(), Some(4)); + assert_eq!(store.rank(&low, "zz").await.unwrap(), None); + assert_eq!( + rows(&store.around(&high, "c", 1).await.unwrap()), + vec![(1, "d", 20.0), (2, "c", 20.0), (3, "b", 10.0)] + ); + assert_eq!( + rows(&store.around(&high, "a", 2).await.unwrap()), + vec![(0, "a", 30.0), (1, "d", 20.0), (2, "c", 20.0)] + ); + assert_eq!( + rows(&store.around(&low, "a", 1).await.unwrap()), + vec![(3, "d", 20.0), (4, "a", 30.0)] + ); + assert_eq!( + rows(&store.around(&low, "b", 0).await.unwrap()), + vec![(1, "b", 10.0)] + ); + assert!(store.around(&high, "zz", 3).await.unwrap().is_empty()); +} + +async fn idempotent_apply(store: &S, prefix: &str) { + let board = fresh(store, Board::high_first(format!("{prefix}-apply")).unwrap()).await; + let inc = sub("p", 5.0, ScorePolicy::Increment); + let k1 = ApplyKey::new("evt-1#0", 1_000); + let k2 = ApplyKey::new("evt-2#0", 2_000); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 5.0 } + ); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Duplicate { score: Some(5.0) } + ); + assert_eq!( + store.apply(&board, &inc, &k2).await.unwrap(), + ApplyOutcome::Applied { score: 10.0 } + ); + // Duplicate detection is per board: the same key applies to another board. + let other = fresh( + store, + Board::high_first(format!("{prefix}-apply-other")).unwrap(), + ) + .await; + assert!(!store.apply(&other, &inc, &k1).await.unwrap().is_duplicate()); + // Pruning forgets old keys only. + assert_eq!(store.prune_applied(&board, 1_500).await.unwrap(), 1); + assert!(store.apply(&board, &inc, &k2).await.unwrap().is_duplicate()); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 15.0 } + ); + // A non-improving Max still records its key. + let max = sub("p", 1.0, ScorePolicy::Max); + let k3 = ApplyKey::new("evt-3#0", 3_000); + assert_eq!( + store.apply(&board, &max, &k3).await.unwrap(), + ApplyOutcome::Applied { score: 15.0 } + ); + assert!(store.apply(&board, &max, &k3).await.unwrap().is_duplicate()); + // Reset clears scores and applied keys. + store.reset(&board).await.unwrap(); + assert_eq!(store.len(&board).await.unwrap(), 0); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 5.0 } + ); +} + +async fn rebuild_and_promote(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-rebuild")).unwrap(), + ) + .await; + let staging = board.staging(); + store + .submit(&board, &sub("old", 99.0, ScorePolicy::Replace)) + .await + .unwrap(); + let key = ApplyKey::new("evt-r#0", 10); + store + .apply(&staging, &sub("new", 7.0, ScorePolicy::Increment), &key) + .await + .unwrap(); + // Staging is invisible to live reads until promoted. + assert_eq!(store.score(&board, "new").await.unwrap(), None); + store.promote(&board).await.unwrap(); + assert_eq!(store.score(&board, "old").await.unwrap(), None); + assert_eq!(store.score(&board, "new").await.unwrap(), Some(7.0)); + assert_eq!(store.len(&staging).await.unwrap(), 0); + // The applied keys moved with the scores. + assert!(store + .apply(&board, &sub("new", 7.0, ScorePolicy::Increment), &key) + .await + .unwrap() + .is_duplicate()); + // Promoting an empty staging board empties live. + store.promote(&board).await.unwrap(); + assert_eq!(store.len(&board).await.unwrap(), 0); +} + +async fn validation(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-invalid")).unwrap(), + ) + .await; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = store + .submit(&board, &sub("p", bad, ScorePolicy::Replace)) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Invalid); + } + let err = store + .submit(&board, &sub("", 1.0, ScorePolicy::Replace)) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Invalid); + assert!(Board::high_first("").is_err()); + assert!(Board::high_first("a{b}").is_err()); + assert_eq!(store.len(&board).await.unwrap(), 0); +} diff --git a/src/leaderboard/in_memory.rs b/src/leaderboard/in_memory.rs new file mode 100644 index 000000000..faf690293 --- /dev/null +++ b/src/leaderboard/in_memory.rs @@ -0,0 +1,224 @@ +//! Dependency-free [`LeaderboardStore`] for tests and demos. + +use std::collections::HashMap; +use std::sync::Mutex; + +use async_trait::async_trait; + +use super::{ + validate_member, ApplyKey, ApplyOutcome, Board, LeaderboardEntry, LeaderboardError, + LeaderboardStore, ScoreOrder, ScorePolicy, ScoreSubmission, +}; + +#[derive(Debug, Default, Clone)] +struct BoardState { + scores: HashMap, + applied: HashMap, +} + +impl BoardState { + fn submit(&mut self, submission: &ScoreSubmission) -> Result { + let existing = self.scores.get(&submission.member).copied(); + let score = submission.score; + let next = match submission.policy { + ScorePolicy::Increment => existing.unwrap_or(0.0) + score, + ScorePolicy::Max => existing.map_or(score, |current| current.max(score)), + ScorePolicy::Min => existing.map_or(score, |current| current.min(score)), + ScorePolicy::Replace => score, + }; + if !next.is_finite() { + return Err(LeaderboardError::invalid("resulting score is not finite")); + } + self.scores.insert(submission.member.clone(), next); + Ok(next) + } + + /// Rows in rank order, matching Redis `ZRANGE`/`ZREVRANGE` tie-breaks. + fn ordered(&self, order: ScoreOrder) -> Vec<(&String, f64)> { + let mut rows: Vec<_> = self.scores.iter().map(|(m, s)| (m, *s)).collect(); + rows.sort_by(|a, b| { + a.1.total_cmp(&b.1) + .then_with(|| a.0.as_bytes().cmp(b.0.as_bytes())) + }); + if order == ScoreOrder::HighFirst { + rows.reverse(); + } + rows + } +} + +fn entries(rows: &[(&String, f64)], start: usize, end: usize) -> Vec { + rows[start..end] + .iter() + .enumerate() + .map(|(offset, (member, score))| LeaderboardEntry { + rank: (start + offset) as u64, + member: (*member).clone(), + score: *score, + }) + .collect() +} + +/// An in-process [`LeaderboardStore`] with the same semantics as the Redis +/// implementation. Queries sort on each call, so it is meant for tests, demos +/// and small boards. +#[derive(Debug, Default)] +pub struct InMemoryLeaderboard { + boards: Mutex>, +} + +impl InMemoryLeaderboard { + /// An empty store. + pub fn new() -> Self { + Self::default() + } + + fn with_board(&self, board: &Board, f: impl FnOnce(&mut BoardState) -> R) -> R { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + let state = boards + .entry((board.name().to_string(), board.is_staging())) + .or_default(); + f(state) + } +} + +#[async_trait] +impl LeaderboardStore for InMemoryLeaderboard { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + submission.validate()?; + self.with_board(board, |state| state.submit(submission)) + } + + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + submission.validate()?; + key.validate()?; + self.with_board(board, |state| { + if state.applied.contains_key(&key.id) { + return Ok(ApplyOutcome::Duplicate { + score: state.scores.get(&submission.member).copied(), + }); + } + let score = state.submit(submission)?; + state.applied.insert(key.id.clone(), key.at_unix_ms); + Ok(ApplyOutcome::Applied { score }) + }) + } + + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| state.scores.get(member).copied())) + } + + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| { + state + .ordered(board.order()) + .iter() + .position(|(m, _)| m.as_str() == member) + .map(|rank| rank as u64) + })) + } + + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + Ok(self.with_board(board, |state| { + let rows = state.ordered(board.order()); + entries(&rows, 0, n.min(rows.len())) + })) + } + + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| { + let rows = state.ordered(board.order()); + let Some(rank) = rows.iter().position(|(m, _)| m.as_str() == member) else { + return Vec::new(); + }; + let start = rank.saturating_sub(radius); + let end = rank + .saturating_add(radius) + .saturating_add(1) + .min(rows.len()); + entries(&rows, start, end) + })) + } + + async fn len(&self, board: &Board) -> Result { + Ok(self.with_board(board, |state| state.scores.len() as u64)) + } + + async fn remove(&self, board: &Board, member: &str) -> Result { + validate_member(member)?; + Ok(self.with_board(board, |state| state.scores.remove(member).is_some())) + } + + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + boards.remove(&(board.name().to_string(), board.is_staging())); + Ok(()) + } + + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + let staged = boards + .remove(&(board.name().to_string(), true)) + .unwrap_or_default(); + boards.insert((board.name().to_string(), false), staged); + Ok(()) + } + + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + Ok(self.with_board(board, |state| { + let before = state.applied.len(); + state.applied.retain(|_, at| *at >= before_unix_ms); + (before - state.applied.len()) as u64 + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn in_memory_store_satisfies_the_leaderboard_contract() { + let store = InMemoryLeaderboard::new(); + crate::leaderboard::conformance::run_store_contract(&store, "contract").await; + } + + #[tokio::test] + async fn boards_are_isolated_by_name_and_variant() { + let store = InMemoryLeaderboard::new(); + let a = Board::high_first("a").unwrap(); + let b = Board::high_first("b").unwrap(); + store + .submit(&a, &ScoreSubmission::new("p", 1.0, ScorePolicy::Replace)) + .await + .unwrap(); + assert_eq!(store.len(&b).await.unwrap(), 0); + assert_eq!(store.len(&a.staging()).await.unwrap(), 0); + assert_eq!(store.len(&a).await.unwrap(), 1); + } +} diff --git a/src/leaderboard/mod.rs b/src/leaderboard/mod.rs new file mode 100644 index 000000000..72a7b9888 --- /dev/null +++ b/src/leaderboard/mod.rs @@ -0,0 +1,519 @@ +//! Sorted-set leaderboards as a rebuildable projection target. +//! +//! Leaderboards are a poor fit for the relational read-model traits +//! ([`ReadModelWritePlanStore`](crate::ReadModelWritePlanStore) and friends): +//! the hot queries are *rank of member*, *top N* and *members around a member*, +//! which a sorted set answers in `O(log n)` while a SQL table needs a window +//! function or a full index scan per request. This module is therefore a +//! dedicated, typed seam rather than another relational backend. +//! +//! # Pieces +//! +//! - [`LeaderboardStore`] — the typed store API: [`submit`](LeaderboardStore::submit) +//! a score under a [`ScorePolicy`], [`rank`](LeaderboardStore::rank), +//! [`score`](LeaderboardStore::score), [`top`](LeaderboardStore::top), +//! [`around`](LeaderboardStore::around), [`reset`](LeaderboardStore::reset) +//! and the rebuild primitives ([`Board::staging`] + [`promote`](LeaderboardStore::promote)). +//! - [`InMemoryLeaderboard`] — a dependency-free implementation with the same +//! ordering and tie-break semantics as Redis, for tests and demos. +//! - `RedisLeaderboard` (feature `redis`) — Redis sorted sets, with every +//! idempotent write executed by one Lua script. +//! - [`LeaderboardProjector`] — maps [`DomainEventOccurrence`](crate::DomainEventOccurrence)s (directly, or +//! decoded from an outbox [`Message`](crate::bus::Message)) to score changes +//! through a [`LeaderboardProjection`], applies them idempotently and +//! rebuilds boards from an event history. +//! - `BackgroundLeaderboard` (feature `redis`) — a bounded, fire-and-forget +//! in-process queue in front of a projector, so a Redis outage never blocks +//! gameplay. +//! +//! # How it plugs into projections +//! +//! A leaderboard is an *eventual* projection: the source of truth stays the +//! aggregate event stream, and the board can be thrown away and rebuilt at any +//! time. There are two ways to feed it: +//! +//! 1. **Outbox / bus (durable, recommended for production).** Publish domain +//! events through the outbox as usual and subscribe a consumer whose handler +//! calls [`LeaderboardProjector::apply_message`]. The handler returns a +//! classified [`TransportError`](crate::bus::TransportError): a Redis outage +//! is retryable (the message is redelivered), an undecodable payload is +//! permanent. Because gameplay commands only commit to the event store and +//! outbox, a Redis blip delays the board but never blocks a command. +//! 2. **In-process (best effort).** Hand committed occurrences to a +//! `BackgroundLeaderboard`, which applies them on a background task and +//! drops (and counts) updates when its queue is full or Redis stays down. +//! Dropped updates are healed by the next rebuild. +//! +//! # Idempotency +//! +//! At-least-once delivery and replays must not double-increment. Each change +//! applied by the projector carries an [`ApplyKey`]: the occurrence id plus the +//! change's index within that occurrence (`"#"`), and the +//! occurrence timestamp. A store records applied keys *per board* in a second +//! structure (in Redis, a sorted set of applied ids scored by event time) and +//! checks-and-records them atomically with the score change (in Redis, one Lua +//! script, so the check, the `ZADD`/`ZINCRBY` and the record cannot interleave +//! with another writer). A duplicate returns [`ApplyOutcome::Duplicate`] and +//! changes nothing. Projections must therefore be deterministic: the same +//! occurrence must always produce the same changes in the same order. +//! +//! The applied-key set grows with the number of applied changes. Two ways keep +//! it bounded: [`LeaderboardStore::prune_applied`] forgets keys older than a +//! cutoff (safe once redelivery older than the cutoff is impossible — e.g. +//! beyond the bus retention window), and a rebuild starts from an empty set. +//! +//! # Rebuild +//! +//! [`LeaderboardProjector::begin_rebuild`] writes into the *staging* variant +//! of each board ([`Board::staging`]) and [`LeaderboardRebuild::commit`] +//! atomically promotes staging over live, so readers never see a half-built +//! board. Live updates applied while a rebuild runs land on the old live board +//! and are discarded by the promote; replay the tail of the stream from the +//! rebuild's starting cursor after committing — the promoted applied-key set +//! makes overlapping replay safe. + +mod in_memory; +mod projector; + +#[cfg(feature = "redis")] +mod background; +#[cfg(feature = "redis")] +mod redis; + +use std::fmt; + +use async_trait::async_trait; + +pub use in_memory::InMemoryLeaderboard; +pub use projector::{ + LeaderboardChange, LeaderboardProjection, LeaderboardProjector, LeaderboardRebuild, + ProjectionReport, +}; + +#[cfg(feature = "redis")] +pub use background::{BackgroundLeaderboard, BackgroundLeaderboardOptions, BackgroundStats}; +#[cfg(feature = "redis")] +pub use redis::{RedisLeaderboard, DEFAULT_REDIS_LEADERBOARD_PREFIX}; + +/// Maximum board name length in bytes. +pub const MAX_BOARD_NAME_LEN: usize = 200; +/// Maximum member length in bytes. +pub const MAX_MEMBER_LEN: usize = 512; + +/// Which end of the sorted set ranks first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ScoreOrder { + /// Highest score is rank 0 (points, kills, gold). + HighFirst, + /// Lowest score is rank 0 (speedrun times, deaths). + LowFirst, +} + +/// How a submitted score combines with a member's existing score. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ScorePolicy { + /// Keep the greater of the existing and submitted score (`ZADD GT`). + Max, + /// Keep the lesser of the existing and submitted score (`ZADD LT`). + Min, + /// Overwrite the existing score. + Replace, + /// Add the submitted score to the existing score (`ZINCRBY`); absent + /// members start at zero. + Increment, +} + +impl ScorePolicy { + pub(crate) fn as_str(self) -> &'static str { + match self { + ScorePolicy::Max => "max", + ScorePolicy::Min => "min", + ScorePolicy::Replace => "replace", + ScorePolicy::Increment => "increment", + } + } +} + +/// A named leaderboard and its rank order. +/// +/// Every board has a *live* variant (what queries read) and a *staging* +/// variant (what a rebuild writes); [`LeaderboardStore::promote`] atomically +/// replaces live with staging. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Board { + name: String, + order: ScoreOrder, + staging: bool, +} + +impl Board { + /// A live board. Names are 1..=[`MAX_BOARD_NAME_LEN`] bytes, without + /// control characters or `{`/`}` (reserved for Redis Cluster hash tags). + pub fn new(name: impl Into, order: ScoreOrder) -> Result { + let name = name.into(); + if name.is_empty() + || name.len() > MAX_BOARD_NAME_LEN + || name.chars().any(|c| c.is_control() || c == '{' || c == '}') + { + return Err(LeaderboardError::invalid(format!( + "invalid board name {name:?}" + ))); + } + Ok(Self { + name, + order, + staging: false, + }) + } + + /// A live board where the highest score ranks first. + pub fn high_first(name: impl Into) -> Result { + Self::new(name, ScoreOrder::HighFirst) + } + + /// A live board where the lowest score ranks first. + pub fn low_first(name: impl Into) -> Result { + Self::new(name, ScoreOrder::LowFirst) + } + + /// The board name. + pub fn name(&self) -> &str { + &self.name + } + + /// The board's rank order. + pub fn order(&self) -> ScoreOrder { + self.order + } + + /// Whether this is the staging (rebuild) variant. + pub fn is_staging(&self) -> bool { + self.staging + } + + /// The staging variant of this board. + pub fn staging(&self) -> Board { + Board { + staging: true, + ..self.clone() + } + } + + /// The live variant of this board. + pub fn live(&self) -> Board { + Board { + staging: false, + ..self.clone() + } + } +} + +/// One score submission for one member. +#[derive(Debug, Clone, PartialEq)] +pub struct ScoreSubmission { + /// The ranked member (player id, guild id, ...). + pub member: String, + /// The submitted score. Must be finite. + pub score: f64, + /// How the score combines with the existing one. + pub policy: ScorePolicy, +} + +impl ScoreSubmission { + /// Build a submission. + pub fn new(member: impl Into, score: f64, policy: ScorePolicy) -> Self { + Self { + member: member.into(), + score, + policy, + } + } + + pub(crate) fn validate(&self) -> Result<(), LeaderboardError> { + validate_member(&self.member)?; + if !self.score.is_finite() { + return Err(LeaderboardError::invalid("score must be finite")); + } + Ok(()) + } +} + +pub(crate) fn validate_member(member: &str) -> Result<(), LeaderboardError> { + if member.is_empty() || member.len() > MAX_MEMBER_LEN { + return Err(LeaderboardError::invalid(format!( + "member must be 1..={MAX_MEMBER_LEN} bytes" + ))); + } + Ok(()) +} + +/// The deduplication identity of one applied change. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ApplyKey { + /// Stable id; the projector uses `"#"`. + pub id: String, + /// Event time in Unix milliseconds; [`LeaderboardStore::prune_applied`] + /// forgets keys older than a cutoff. + pub at_unix_ms: u64, +} + +impl ApplyKey { + /// Build an apply key. + pub fn new(id: impl Into, at_unix_ms: u64) -> Self { + Self { + id: id.into(), + at_unix_ms, + } + } + + pub(crate) fn validate(&self) -> Result<(), LeaderboardError> { + if self.id.is_empty() || self.id.len() > MAX_MEMBER_LEN { + return Err(LeaderboardError::invalid(format!( + "apply key must be 1..={MAX_MEMBER_LEN} bytes" + ))); + } + Ok(()) + } +} + +/// Result of an idempotent [`LeaderboardStore::apply`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ApplyOutcome { + /// The change was applied (a `Max`/`Min` submission that did not beat the + /// existing score still counts as applied). Carries the resulting score. + Applied { + /// Member score after the change. + score: f64, + }, + /// The key was already applied; nothing changed. + Duplicate { + /// Current member score, if any. + score: Option, + }, +} + +impl ApplyOutcome { + /// Whether this was a duplicate. + pub fn is_duplicate(&self) -> bool { + matches!(self, ApplyOutcome::Duplicate { .. }) + } +} + +/// One ranked row. +#[derive(Debug, Clone, PartialEq)] +pub struct LeaderboardEntry { + /// Zero-based rank in the board's [`ScoreOrder`]. + pub rank: u64, + /// The member. + pub member: String, + /// The member's score. + pub score: f64, +} + +/// Leaderboard failure classification. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LeaderboardErrorKind { + /// Bad input (board name, member, non-finite score) or an undecodable + /// event. Retrying the same input will not help. + Invalid, + /// The backing store is unreachable or timed out. Retry later. + Unavailable, +} + +/// A leaderboard error. +#[derive(Debug, Clone)] +pub struct LeaderboardError { + kind: LeaderboardErrorKind, + message: String, +} + +impl LeaderboardError { + /// An invalid-input error. + pub fn invalid(message: impl Into) -> Self { + Self { + kind: LeaderboardErrorKind::Invalid, + message: message.into(), + } + } + + /// A store-unavailable error. + pub fn unavailable(message: impl Into) -> Self { + Self { + kind: LeaderboardErrorKind::Unavailable, + message: message.into(), + } + } + + /// The classification. + pub fn kind(&self) -> LeaderboardErrorKind { + self.kind + } + + /// The diagnostic message. + pub fn message(&self) -> &str { + &self.message + } + + /// Map to a transport error: unavailable is retryable, invalid permanent. + pub fn into_transport_error(self) -> crate::bus::TransportError { + match self.kind { + LeaderboardErrorKind::Unavailable => { + crate::bus::TransportError::retryable(self.to_string()) + } + LeaderboardErrorKind::Invalid => { + crate::bus::TransportError::permanent(self.to_string()) + } + } + } +} + +impl fmt::Display for LeaderboardError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + LeaderboardErrorKind::Invalid => "invalid", + LeaderboardErrorKind::Unavailable => "unavailable", + }; + write!(f, "leaderboard error ({kind}): {}", self.message) + } +} + +impl std::error::Error for LeaderboardError {} + +impl From for crate::bus::TransportError { + fn from(err: LeaderboardError) -> Self { + err.into_transport_error() + } +} + +/// A sorted-set leaderboard store. +/// +/// Ordering contract (shared by every implementation, matching Redis): rows +/// sort by score in the board's [`ScoreOrder`]; equal scores tie-break by the +/// member's bytes — ascending for [`ScoreOrder::LowFirst`], descending for +/// [`ScoreOrder::HighFirst`] (exactly `ZRANGE` / `ZREVRANGE`). Ranks are +/// zero-based. +#[async_trait] +pub trait LeaderboardStore: Send + Sync { + /// Submit a score without deduplication and return the resulting score. + /// + /// Use for direct, already-authoritative writes. Projections should use + /// [`apply`](LeaderboardStore::apply) so redelivery is harmless. + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result; + + /// Apply a score submission at most once per `key` and board, atomically + /// with recording the key. + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result; + + /// A member's score, if ranked. + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError>; + + /// A member's zero-based rank, if ranked. + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError>; + + /// The first `n` rows. + async fn top(&self, board: &Board, n: usize) + -> Result, LeaderboardError>; + + /// Up to `radius` rows either side of `member`, plus the member; empty if + /// the member is not ranked. Read atomically. + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError>; + + /// Number of ranked members. + async fn len(&self, board: &Board) -> Result; + + /// Remove a member; returns whether it was ranked. + async fn remove(&self, board: &Board, member: &str) -> Result; + + /// Delete every score and applied key of this board variant. + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError>; + + /// Atomically replace the live board (scores and applied keys) with its + /// staging variant. An absent staging board promotes as empty. + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError>; + + /// Forget applied keys recorded with `at_unix_ms < before_unix_ms`; + /// returns how many were forgotten. + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result; +} + +#[async_trait] +impl LeaderboardStore for std::sync::Arc { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + (**self).submit(board, submission).await + } + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + (**self).apply(board, submission, key).await + } + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + (**self).score(board, member).await + } + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + (**self).rank(board, member).await + } + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + (**self).top(board, n).await + } + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + (**self).around(board, member, radius).await + } + async fn len(&self, board: &Board) -> Result { + (**self).len(board).await + } + async fn remove(&self, board: &Board, member: &str) -> Result { + (**self).remove(board, member).await + } + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + (**self).reset(board).await + } + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + (**self).promote(board).await + } + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + (**self).prune_applied(board, before_unix_ms).await + } +} + +/// Shared behavioural contract run against every implementation. +#[cfg(any(test, feature = "redis"))] +#[doc(hidden)] +pub mod conformance; diff --git a/src/leaderboard/projector.rs b/src/leaderboard/projector.rs new file mode 100644 index 000000000..6d8020aa0 --- /dev/null +++ b/src/leaderboard/projector.rs @@ -0,0 +1,504 @@ +//! Event → leaderboard projection, with idempotent apply and rebuild. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use crate::bus::{Message, TransportError}; +use crate::DomainEventOccurrence; + +use super::{ApplyKey, ApplyOutcome, Board, LeaderboardError, LeaderboardStore, ScoreSubmission}; + +/// One score change a projection derives from an occurrence. +#[derive(Debug, Clone, PartialEq)] +pub struct LeaderboardChange { + /// The live board to change (the projector redirects it to staging during + /// a rebuild). + pub board: Board, + /// The submission. + pub submission: ScoreSubmission, +} + +impl LeaderboardChange { + /// Build a change. + pub fn new(board: Board, submission: ScoreSubmission) -> Self { + Self { board, submission } + } +} + +/// Maps domain event occurrences to leaderboard changes. +/// +/// Must be deterministic: replaying an occurrence must yield the same changes +/// in the same order, because each change's dedupe key is +/// `"#"`. Closures +/// `Fn(&DomainEventOccurrence) -> Result, LeaderboardError>` +/// implement this trait and handle every event name. +pub trait LeaderboardProjection: Send + Sync { + /// Whether this projection cares about the event name. Messages for other + /// names are acknowledged without decoding. + fn handles(&self, _event_name: &str) -> bool { + true + } + + /// Changes for one occurrence (possibly none). + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError>; +} + +impl LeaderboardProjection for F +where + F: Fn(&DomainEventOccurrence) -> Result, LeaderboardError> + Send + Sync, +{ + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError> { + self(event) + } +} + +/// Counts from applying one or more occurrences. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ProjectionReport { + /// Changes applied. + pub applied: u64, + /// Changes skipped as already applied. + pub duplicates: u64, + /// Occurrences skipped because the projection does not handle them. + pub ignored: u64, +} + +impl ProjectionReport { + fn merge(&mut self, other: ProjectionReport) { + self.applied += other.applied; + self.duplicates += other.duplicates; + self.ignored += other.ignored; + } +} + +/// Applies a [`LeaderboardProjection`] to a [`LeaderboardStore`]. +pub struct LeaderboardProjector { + store: Arc, + projection: Arc

, +} + +impl Clone for LeaderboardProjector { + fn clone(&self) -> Self { + Self { + store: Arc::clone(&self.store), + projection: Arc::clone(&self.projection), + } + } +} + +impl LeaderboardProjector +where + S: LeaderboardStore + ?Sized, + P: LeaderboardProjection + ?Sized, +{ + /// A projector over a store and projection. + pub fn new(store: Arc, projection: Arc

) -> Self { + Self { store, projection } + } + + /// The store. + pub fn store(&self) -> &Arc { + &self.store + } + + /// Apply one occurrence to the live boards, idempotently. + pub async fn apply_event( + &self, + event: &DomainEventOccurrence, + ) -> Result { + self.apply_to(event, false).await + } + + async fn apply_to( + &self, + event: &DomainEventOccurrence, + staging: bool, + ) -> Result { + if !self.projection.handles(&event.descriptor().name) { + return Ok(ProjectionReport { + ignored: 1, + ..ProjectionReport::default() + }); + } + let changes = self.projection.project(event)?; + self.apply_changes(event, changes, staging).await + } + + async fn apply_changes( + &self, + event: &DomainEventOccurrence, + changes: Vec, + staging: bool, + ) -> Result { + let mut report = ProjectionReport::default(); + for (index, change) in changes.into_iter().enumerate() { + let board = if staging { + change.board.staging() + } else { + change.board.live() + }; + let key = ApplyKey::new( + format!("{}#{index}", event.id()), + event.occurred_at_unix_ms(), + ); + match self.store.apply(&board, &change.submission, &key).await? { + ApplyOutcome::Applied { .. } => report.applied += 1, + ApplyOutcome::Duplicate { .. } => report.duplicates += 1, + } + } + Ok(report) + } + + /// Decode an outbox/bus message carrying a canonical + /// [`DomainEventOccurrence`] and apply it. + /// + /// Suitable as a bus event handler body: an unavailable store maps to a + /// retryable [`TransportError`] (redelivery is safe thanks to dedupe), an + /// undecodable payload or invalid change to a permanent one. + pub async fn apply_message( + &self, + message: &Message, + ) -> Result { + if !self.projection.handles(message.name()) { + return Ok(ProjectionReport { + ignored: 1, + ..ProjectionReport::default() + }); + } + let event = + DomainEventOccurrence::from_canonical_bytes(message.payload()).map_err(|err| { + TransportError::permanent(format!("leaderboard: undecodable occurrence: {err}")) + })?; + self.apply_event(&event).await.map_err(Into::into) + } + + /// Start a rebuild of `boards` (live variants) into their staging + /// variants. Boards the projection touches during the rebuild but that are + /// not listed are added (and promoted) automatically; listed boards that + /// receive no changes are promoted empty. + pub async fn begin_rebuild( + &self, + boards: &[Board], + ) -> Result, LeaderboardError> { + let mut rebuild = LeaderboardRebuild { + projector: self.clone(), + boards: BTreeMap::new(), + report: ProjectionReport::default(), + }; + for board in boards { + rebuild.touch(board).await?; + } + Ok(rebuild) + } + + /// Rebuild from a complete event history in one call: begin, apply every + /// occurrence, commit. + pub async fn rebuild( + &self, + boards: &[Board], + events: I, + ) -> Result + where + I: IntoIterator, + I::Item: std::borrow::Borrow, + { + let mut rebuild = self.begin_rebuild(boards).await?; + for event in events { + rebuild + .apply_event(std::borrow::Borrow::borrow(&event)) + .await?; + } + rebuild.commit().await + } +} + +/// An in-progress rebuild; feed it the event history (from any sync or async +/// source) and [`commit`](LeaderboardRebuild::commit). +pub struct LeaderboardRebuild { + projector: LeaderboardProjector, + boards: BTreeMap, + report: ProjectionReport, +} + +impl LeaderboardRebuild +where + S: LeaderboardStore + ?Sized, + P: LeaderboardProjection + ?Sized, +{ + async fn touch(&mut self, board: &Board) -> Result<(), LeaderboardError> { + if !self.boards.contains_key(board.name()) { + self.projector.store.reset(&board.staging()).await?; + self.boards.insert(board.name().to_string(), board.live()); + } + Ok(()) + } + + /// Apply one historical occurrence to the staging boards. + pub async fn apply_event( + &mut self, + event: &DomainEventOccurrence, + ) -> Result<(), LeaderboardError> { + if !self.projector.projection.handles(&event.descriptor().name) { + self.report.ignored += 1; + return Ok(()); + } + let changes = self.projector.projection.project(event)?; + for change in &changes { + self.touch(&change.board).await?; + } + let report = self.projector.apply_changes(event, changes, true).await?; + self.report.merge(report); + Ok(()) + } + + /// Boards that will be promoted. + pub fn boards(&self) -> impl Iterator { + self.boards.values() + } + + /// Atomically promote every staging board over its live board. + pub async fn commit(self) -> Result { + for board in self.boards.values() { + self.projector.store.promote(board).await?; + } + Ok(self.report) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bus::MessageKind; + use crate::leaderboard::{InMemoryLeaderboard, LeaderboardErrorKind, ScorePolicy}; + use std::time::{Duration, UNIX_EPOCH}; + + #[derive(serde::Serialize, serde::Deserialize, crate::DomainEvent)] + #[domain_event(name = "test.monster_slain", version = 1)] + struct MonsterSlain { + player: String, + xp: u32, + } + + #[derive(serde::Serialize, serde::Deserialize, crate::DomainEvent)] + #[domain_event(name = "test.chat_sent", version = 1)] + struct ChatSent { + text: String, + } + + fn slain(position: u64, player: &str, xp: u32) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + crate::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "kill".into(), + }, + UNIX_EPOCH + Duration::from_millis(position * 1_000), + Default::default(), + &MonsterSlain { + player: player.into(), + xp, + }, + ) + .unwrap() + } + + fn chat(position: u64) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + crate::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "chat".into(), + }, + UNIX_EPOCH, + Default::default(), + &ChatSent { text: "hi".into() }, + ) + .unwrap() + } + + fn message(event: &DomainEventOccurrence) -> Message { + Message::new( + event.descriptor().name.to_string(), + MessageKind::Event, + event.canonical_bytes().unwrap(), + ) + .with_id(event.id()) + } + + struct XpProjection; + + impl LeaderboardProjection for XpProjection { + fn handles(&self, name: &str) -> bool { + name == "test.monster_slain" + } + + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError> { + let body: MonsterSlain = event + .decode_body() + .map_err(|err| LeaderboardError::invalid(err.to_string()))?; + Ok(vec![ + LeaderboardChange::new( + xp_board(), + ScoreSubmission::new(&body.player, f64::from(body.xp), ScorePolicy::Increment), + ), + LeaderboardChange::new( + best_board(), + ScoreSubmission::new(&body.player, f64::from(body.xp), ScorePolicy::Max), + ), + ]) + } + } + + fn xp_board() -> Board { + Board::high_first("xp").unwrap() + } + + fn best_board() -> Board { + Board::high_first("best-kill").unwrap() + } + + fn projector() -> LeaderboardProjector { + LeaderboardProjector::new(Arc::new(InMemoryLeaderboard::new()), Arc::new(XpProjection)) + } + + #[tokio::test] + async fn replayed_events_do_not_double_increment() { + let projector = projector(); + let events = [ + slain(1, "ann", 10), + slain(2, "bob", 30), + slain(3, "ann", 25), + ]; + for event in &events { + let report = projector.apply_event(event).await.unwrap(); + assert_eq!(report.applied, 2); + } + for event in &events { + let report = projector.apply_event(event).await.unwrap(); + assert_eq!(report.duplicates, 2); + assert_eq!(report.applied, 0); + } + let store = projector.store(); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + assert_eq!(store.score(&best_board(), "ann").await.unwrap(), Some(25.0)); + assert_eq!(store.rank(&xp_board(), "ann").await.unwrap(), Some(0)); + assert_eq!(store.rank(&best_board(), "bob").await.unwrap(), Some(0)); + } + + #[tokio::test] + async fn messages_decode_and_classify_errors() { + let projector = projector(); + let first = message(&slain(1, "ann", 10)); + assert_eq!(projector.apply_message(&first).await.unwrap().applied, 2); + assert_eq!(projector.apply_message(&first).await.unwrap().duplicates, 2); + + let ignored = projector.apply_message(&message(&chat(2))).await.unwrap(); + assert_eq!(ignored.ignored, 1); + + let garbage = Message::new("test.monster_slain", MessageKind::Event, b"nope".to_vec()); + assert!(projector + .apply_message(&garbage) + .await + .unwrap_err() + .is_permanent()); + + assert!(LeaderboardError::unavailable("down") + .into_transport_error() + .is_retryable()); + assert_eq!( + LeaderboardError::invalid("x").kind(), + LeaderboardErrorKind::Invalid + ); + } + + #[tokio::test] + async fn rebuild_replaces_drifted_live_boards_atomically() { + let projector = projector(); + let history = vec![ + slain(1, "ann", 10), + slain(2, "bob", 30), + slain(3, "ann", 25), + ]; + for event in &history { + projector.apply_event(event).await.unwrap(); + } + let store = Arc::clone(projector.store()); + // Drift: a direct write and a stale board that the history never touches. + store + .submit( + &xp_board(), + &ScoreSubmission::new("cheater", 1e9, ScorePolicy::Replace), + ) + .await + .unwrap(); + let stale = Board::high_first("retired").unwrap(); + store + .submit( + &stale, + &ScoreSubmission::new("x", 1.0, ScorePolicy::Replace), + ) + .await + .unwrap(); + + // Boards are discovered from the history; `stale` is listed so it empties. + let mut rebuild = projector + .begin_rebuild(std::slice::from_ref(&stale)) + .await + .unwrap(); + for event in &history[..2] { + rebuild.apply_event(event).await.unwrap(); + } + // Mid-rebuild, live reads still see the old boards. + assert_eq!( + store.score(&xp_board(), "cheater").await.unwrap(), + Some(1e9) + ); + rebuild.apply_event(&history[2]).await.unwrap(); + let names: Vec<_> = rebuild.boards().map(|b| b.name().to_string()).collect(); + assert_eq!(names, vec!["best-kill", "retired", "xp"]); + let report = rebuild.commit().await.unwrap(); + assert_eq!(report.applied, 6); + + assert_eq!(store.score(&xp_board(), "cheater").await.unwrap(), None); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + assert_eq!(store.len(&stale).await.unwrap(), 0); + // Tail replay after commit is deduplicated by the promoted applied keys. + let report = projector.apply_event(&history[2]).await.unwrap(); + assert_eq!(report.duplicates, 2); + + // The one-shot helper yields the same result. + let report = projector.rebuild(&[], &history).await.unwrap(); + assert_eq!(report.applied, 6); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + } + + #[tokio::test] + async fn closures_are_projections() { + let projection = |event: &DomainEventOccurrence| { + Ok(vec![LeaderboardChange::new( + Board::low_first("first-seen").unwrap(), + ScoreSubmission::new("zone", event.occurred_at_unix_ms() as f64, ScorePolicy::Min), + )]) + }; + let projector = + LeaderboardProjector::new(Arc::new(InMemoryLeaderboard::new()), Arc::new(projection)); + projector.apply_event(&slain(5, "a", 1)).await.unwrap(); + projector.apply_event(&slain(2, "a", 1)).await.unwrap(); + let board = Board::low_first("first-seen").unwrap(); + assert_eq!( + projector.store().score(&board, "zone").await.unwrap(), + Some(2_000.0) + ); + } +} diff --git a/src/leaderboard/redis.rs b/src/leaderboard/redis.rs new file mode 100644 index 000000000..d1591c266 --- /dev/null +++ b/src/leaderboard/redis.rs @@ -0,0 +1,473 @@ +//! Redis sorted-set [`LeaderboardStore`]. +//! +//! # Key layout +//! +//! Each board variant owns two keys sharing the `{}` hash tag, so +//! every key a script touches lives in one Redis Cluster slot: +//! +//! - `:{}::scores` — `ZSET member → score`; +//! - `:{}::applied` — `ZSET apply-key → event ms`. +//! +//! # Atomicity +//! +//! [`apply`](LeaderboardStore::apply) runs one Lua script that checks the +//! applied set, changes the score (`ZADD GT|LT`, `ZADD` or `ZINCRBY`) and +//! records the key; Redis executes scripts atomically, so concurrent or +//! redelivered applies cannot double-count. [`around`](LeaderboardStore::around) +//! reads rank and range in one script, and [`promote`](LeaderboardStore::promote) +//! renames staging over live in one script. `ZADD GT/LT` requires Redis 6.2+. +//! +//! Scores cross the Lua boundary as strings (Lua numbers would truncate to +//! integers in replies), using Redis' round-trip-exact `%.17g` formatting. + +use std::time::Duration; + +use async_trait::async_trait; +use redis::aio::{ConnectionManager, ConnectionManagerConfig}; +use redis::{Client, Script, Value}; + +use super::{ + validate_member, ApplyKey, ApplyOutcome, Board, LeaderboardEntry, LeaderboardError, + LeaderboardStore, ScoreOrder, ScoreSubmission, +}; + +/// Default key prefix. +pub const DEFAULT_REDIS_LEADERBOARD_PREFIX: &str = "distributed:lb"; + +const APPLY_SCRIPT: &str = r#" +local id = ARGV[4] +if id ~= '' and redis.call('ZSCORE', KEYS[2], id) then + return {0, redis.call('ZSCORE', KEYS[1], ARGV[1])} +end +local policy = ARGV[3] +local score +if policy == 'increment' then + score = redis.call('ZINCRBY', KEYS[1], ARGV[2], ARGV[1]) +else + if policy == 'max' then + redis.call('ZADD', KEYS[1], 'GT', ARGV[2], ARGV[1]) + elseif policy == 'min' then + redis.call('ZADD', KEYS[1], 'LT', ARGV[2], ARGV[1]) + else + redis.call('ZADD', KEYS[1], ARGV[2], ARGV[1]) + end + score = redis.call('ZSCORE', KEYS[1], ARGV[1]) +end +if id ~= '' then + redis.call('ZADD', KEYS[2], ARGV[5], id) +end +return {1, score} +"#; + +const AROUND_SCRIPT: &str = r#" +local high = ARGV[2] == 'high' +local rank +if high then + rank = redis.call('ZREVRANK', KEYS[1], ARGV[1]) +else + rank = redis.call('ZRANK', KEYS[1], ARGV[1]) +end +if not rank then + return {} +end +local radius = tonumber(ARGV[3]) +local start = rank - radius +if start < 0 then start = 0 end +local stop = rank + radius +local rows +if high then + rows = redis.call('ZREVRANGE', KEYS[1], start, stop, 'WITHSCORES') +else + rows = redis.call('ZRANGE', KEYS[1], start, stop, 'WITHSCORES') +end +table.insert(rows, 1, start) +return rows +"#; + +const PROMOTE_SCRIPT: &str = r#" +redis.call('DEL', KEYS[3], KEYS[4]) +if redis.call('EXISTS', KEYS[1]) == 1 then + redis.call('RENAME', KEYS[1], KEYS[3]) +end +if redis.call('EXISTS', KEYS[2]) == 1 then + redis.call('RENAME', KEYS[2], KEYS[4]) +end +return 1 +"#; + +/// A [`LeaderboardStore`] on Redis sorted sets. +/// +/// Uses a [`ConnectionManager`], which multiplexes requests and reconnects in +/// the background; [`connect`](RedisLeaderboard::connect) configures short +/// connection/response timeouts so callers fail fast (as +/// [`LeaderboardErrorKind::Unavailable`](super::LeaderboardErrorKind::Unavailable)) +/// instead of hanging while Redis is down. +#[derive(Clone)] +pub struct RedisLeaderboard { + conn: ConnectionManager, + prefix: String, + apply: Script, + around: Script, + promote: Script, +} + +pub(crate) fn unavailable(context: &str, err: redis::RedisError) -> LeaderboardError { + LeaderboardError::unavailable(format!("redis {context}: {err}")) +} + +impl RedisLeaderboard { + /// Default connection and response timeout used by [`connect`](Self::connect). + pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2); + + /// Connect lazily to `url` (e.g. `redis://127.0.0.1:6379`). Construction + /// does not contact Redis, so service start-up never waits on it. + pub fn connect(url: &str) -> Result { + let client = Client::open(url) + .map_err(|err| LeaderboardError::invalid(format!("redis url: {err}")))?; + let config = ConnectionManagerConfig::new() + .set_connection_timeout(Some(Self::DEFAULT_TIMEOUT)) + .set_response_timeout(Some(Self::DEFAULT_TIMEOUT)) + .set_number_of_retries(1); + let conn = client + .get_connection_manager_lazy(config) + .map_err(|err| unavailable("connect", err))?; + Ok(Self::new(conn)) + } + + /// Wrap an existing connection manager. + pub fn new(conn: ConnectionManager) -> Self { + Self { + conn, + prefix: DEFAULT_REDIS_LEADERBOARD_PREFIX.to_string(), + apply: Script::new(APPLY_SCRIPT), + around: Script::new(AROUND_SCRIPT), + promote: Script::new(PROMOTE_SCRIPT), + } + } + + /// Use a different key prefix (e.g. per environment or per test). + pub fn with_prefix(mut self, prefix: impl Into) -> Self { + self.prefix = prefix.into(); + self + } + + fn key(&self, board: &Board, staging: bool, part: &str) -> String { + let variant = if staging { "staging" } else { "live" }; + format!("{}:{{{}}}:{variant}:{part}", self.prefix, board.name()) + } + + fn scores(&self, board: &Board) -> String { + self.key(board, board.is_staging(), "scores") + } + + fn applied(&self, board: &Board) -> String { + self.key(board, board.is_staging(), "applied") + } + + async fn run_apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: Option<&ApplyKey>, + ) -> Result<(bool, Option), LeaderboardError> { + submission.validate()?; + if let Some(key) = key { + key.validate()?; + } + let mut conn = self.conn.clone(); + let reply: Value = self + .apply + .key(self.scores(board)) + .key(self.applied(board)) + .arg(&submission.member) + .arg(format_score(submission.score)) + .arg(submission.policy.as_str()) + .arg(key.map_or("", |k| k.id.as_str())) + .arg(key.map_or(0, |k| k.at_unix_ms)) + .invoke_async(&mut conn) + .await + .map_err(|err| map_write_error("apply", err))?; + let Value::Array(items) = reply else { + return Err(LeaderboardError::unavailable( + "redis apply: unexpected reply", + )); + }; + let applied = matches!(items.first(), Some(Value::Int(1))); + let score = match items.get(1) { + Some(value) => parse_optional_score(value)?, + None => None, + }; + Ok((applied, score)) + } + + fn parse_rows( + &self, + values: &[Value], + first_rank: u64, + ) -> Result, LeaderboardError> { + values + .chunks(2) + .enumerate() + .map(|(offset, pair)| { + let [member, score] = pair else { + return Err(LeaderboardError::unavailable("redis: odd WITHSCORES reply")); + }; + Ok(LeaderboardEntry { + rank: first_rank + offset as u64, + member: parse_string(member)?, + score: parse_optional_score(score)? + .ok_or_else(|| LeaderboardError::unavailable("redis: missing score"))?, + }) + }) + .collect() + } +} + +/// A write that Redis rejects as an error reply (e.g. an increment overflowing +/// to infinity, or a server too old for `ZADD GT`) is not transient. +fn map_write_error(context: &str, err: redis::RedisError) -> LeaderboardError { + if err.kind() == redis::ErrorKind::Server(redis::ServerErrorKind::ResponseError) { + LeaderboardError::invalid(format!("redis {context}: {err}")) + } else { + unavailable(context, err) + } +} + +fn format_score(score: f64) -> String { + // Rust's shortest round-trip representation; Redis parses it with strtod. + format!("{score:?}") +} + +fn parse_string(value: &Value) -> Result { + match value { + Value::BulkString(bytes) => String::from_utf8(bytes.clone()) + .map_err(|_| LeaderboardError::unavailable("redis: non-utf8 member")), + Value::SimpleString(s) => Ok(s.clone()), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected member reply", + )), + } +} + +fn parse_optional_score(value: &Value) -> Result, LeaderboardError> { + match value { + Value::Nil => Ok(None), + Value::Boolean(false) => Ok(None), + Value::Double(score) => Ok(Some(*score)), + Value::Int(score) => Ok(Some(*score as f64)), + other => { + let text = parse_string(other)?; + text.parse::() + .map(Some) + .map_err(|_| LeaderboardError::unavailable(format!("redis: bad score {text:?}"))) + } + } +} + +fn parse_rank(value: &Value) -> Result { + match value { + Value::Int(rank) if *rank >= 0 => Ok(*rank as u64), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected rank reply", + )), + } +} + +#[async_trait] +impl LeaderboardStore for RedisLeaderboard { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + let (_, score) = self.run_apply(board, submission, None).await?; + score.ok_or_else(|| LeaderboardError::unavailable("redis submit: missing score")) + } + + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + match self.run_apply(board, submission, Some(key)).await? { + (true, Some(score)) => Ok(ApplyOutcome::Applied { score }), + (true, None) => Err(LeaderboardError::unavailable("redis apply: missing score")), + (false, score) => Ok(ApplyOutcome::Duplicate { score }), + } + } + + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + let mut conn = self.conn.clone(); + let value: Value = redis::cmd("ZSCORE") + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZSCORE", err))?; + parse_optional_score(&value) + } + + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + let command = match board.order() { + ScoreOrder::HighFirst => "ZREVRANK", + ScoreOrder::LowFirst => "ZRANK", + }; + let mut conn = self.conn.clone(); + let value: Value = redis::cmd(command) + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable(command, err))?; + match value { + Value::Nil => Ok(None), + other => parse_rank(&other).map(Some), + } + } + + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + if n == 0 { + return Ok(Vec::new()); + } + let command = match board.order() { + ScoreOrder::HighFirst => "ZREVRANGE", + ScoreOrder::LowFirst => "ZRANGE", + }; + let stop = i64::try_from(n - 1).unwrap_or(i64::MAX); + let mut conn = self.conn.clone(); + let value: Value = redis::cmd(command) + .arg(self.scores(board)) + .arg(0) + .arg(stop) + .arg("WITHSCORES") + .query_async(&mut conn) + .await + .map_err(|err| unavailable(command, err))?; + match value { + Value::Array(values) => self.parse_rows(&flatten_pairs(values), 0), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected range reply", + )), + } + } + + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + validate_member(member)?; + let order = match board.order() { + ScoreOrder::HighFirst => "high", + ScoreOrder::LowFirst => "low", + }; + // Keep the Lua arithmetic inside exact double range. + let radius = radius.min(1 << 40); + let mut conn = self.conn.clone(); + let value: Value = self + .around + .key(self.scores(board)) + .arg(member) + .arg(order) + .arg(radius) + .invoke_async(&mut conn) + .await + .map_err(|err| unavailable("around", err))?; + let Value::Array(values) = value else { + return Err(LeaderboardError::unavailable( + "redis: unexpected around reply", + )); + }; + let Some((first, rows)) = values.split_first() else { + return Ok(Vec::new()); + }; + self.parse_rows(rows, parse_rank(first)?) + } + + async fn len(&self, board: &Board) -> Result { + let mut conn = self.conn.clone(); + let value: Value = redis::cmd("ZCARD") + .arg(self.scores(board)) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZCARD", err))?; + parse_rank(&value) + } + + async fn remove(&self, board: &Board, member: &str) -> Result { + validate_member(member)?; + let mut conn = self.conn.clone(); + let removed: i64 = redis::cmd("ZREM") + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZREM", err))?; + Ok(removed > 0) + } + + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut conn = self.conn.clone(); + let _: i64 = redis::cmd("DEL") + .arg(self.scores(board)) + .arg(self.applied(board)) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("DEL", err))?; + Ok(()) + } + + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut conn = self.conn.clone(); + let _: i64 = self + .promote + .key(self.key(board, true, "scores")) + .key(self.key(board, true, "applied")) + .key(self.key(board, false, "scores")) + .key(self.key(board, false, "applied")) + .invoke_async(&mut conn) + .await + .map_err(|err| unavailable("promote", err))?; + Ok(()) + } + + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + let mut conn = self.conn.clone(); + let removed: i64 = redis::cmd("ZREMRANGEBYSCORE") + .arg(self.applied(board)) + .arg("-inf") + .arg(format!("({before_unix_ms}")) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZREMRANGEBYSCORE", err))?; + Ok(removed.max(0) as u64) + } +} + +/// RESP3 servers reply to `WITHSCORES` with `[[member, score], ...]`; RESP2 +/// with a flat list. Normalize to flat. +fn flatten_pairs(values: Vec) -> Vec { + if values.iter().all(|v| matches!(v, Value::Array(_))) { + values + .into_iter() + .flat_map(|v| match v { + Value::Array(pair) => pair, + other => vec![other], + }) + .collect() + } else { + values + } +} diff --git a/src/lib.rs b/src/lib.rs index 2af2b194b..a12975ed9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,6 +38,7 @@ pub mod emitter; pub mod gateway; pub mod graphql; mod in_memory_repo; +pub mod leaderboard; pub mod lock; #[cfg(feature = "metrics")] pub mod metrics; From a2fb97c5ffac03cdc3591d38179e453ef5369193 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:45:39 -0500 Subject: [PATCH 120/484] feat(bus): add Redis Streams message publisher RedisStreamPublisher implements MessagePublisher with XADD. Messages with a stable id are published by one Lua script that SET NX EXs a dedupe marker (sharing the stream hash tag) before appending, so outbox retries inside the window do not duplicate entries. Integration tests cover the leaderboard contract, projector replay and rebuild, and publisher dedupe against REDIS_URL (skipped with a log line when unset), plus an always-on unreachable-server test. Refs [[tasks/gr-p9-redis]] --- src/bus/mod.rs | 6 + src/bus/redis_streams.rs | 180 +++++++++++++++++++++++++++ tests/redis_leaderboard/main.rs | 208 ++++++++++++++++++++++++++++++++ 3 files changed, 394 insertions(+) create mode 100644 src/bus/redis_streams.rs create mode 100644 tests/redis_leaderboard/main.rs diff --git a/src/bus/mod.rs b/src/bus/mod.rs index c6d1b4bad..5e6bb6da6 100644 --- a/src/bus/mod.rs +++ b/src/bus/mod.rs @@ -110,6 +110,8 @@ mod publisher; mod rabbitmq; #[cfg(feature = "rabbitmq")] mod rabbitmq_bus; +#[cfg(feature = "redis")] +mod redis_streams; mod router; mod run_options; mod runner; @@ -165,6 +167,10 @@ pub use ordered_delivery::OrderedDelivery; #[cfg(feature = "postgres")] pub use postgres_bus::{LogReceived, PostgresBus, QueueReceived}; pub use publisher::MessagePublisher; +#[cfg(feature = "redis")] +pub use redis_streams::{ + RedisStreamPublisher, DEFAULT_REDIS_DEDUPE_TTL, DEFAULT_REDIS_STREAM_PREFIX, +}; pub use router::{LaneSet, MessageRouter}; pub use run_options::{ConsumerDeliveryMode, InboxHook, NoInbox, RunOptions, DEFAULT_LANE_WINDOW}; pub use runner::run_source; diff --git a/src/bus/redis_streams.rs b/src/bus/redis_streams.rs new file mode 100644 index 000000000..10ae6d00c --- /dev/null +++ b/src/bus/redis_streams.rs @@ -0,0 +1,180 @@ +//! Redis Streams [`MessagePublisher`]. +//! +//! Each [`Message`] becomes one `XADD` entry with the fields `id`, `name`, +//! `kind`, `content_type`, `payload` (raw bytes) and one `meta:` field per +//! metadata pair. By default the stream key is `:{}`; +//! [`RedisStreamPublisher::with_stream`] sends everything to one stream. +//! +//! # Dedupe +//! +//! Redis Streams do not deduplicate natively, so a message with a stable id +//! is published by a Lua script that first `SET NX EX`s a marker key +//! `:dedupe:` and only `XADD`s when the marker was new — both +//! in one atomic script, with the marker sharing the stream's hash tag so it +//! works on Redis Cluster. A retried outbox row inside the dedupe window +//! therefore resolves `Ok` without a second entry. Messages without an id are +//! appended unconditionally. +//! +//! # Publish threshold +//! +//! `publish` resolves `Ok` once Redis replies to the script, i.e. the entry is +//! in the primary's memory. Durability beyond that depends on the server's +//! AOF/replication configuration; any error or timeout is retryable so the +//! outbox row stays pending. + +use std::time::Duration; + +use redis::aio::{ConnectionManager, ConnectionManagerConfig}; +use redis::{Client, Script, Value}; + +use super::{Message, MessagePublisher, TransportError}; + +/// Default stream key prefix. +pub const DEFAULT_REDIS_STREAM_PREFIX: &str = "distributed:stream"; +/// Default dedupe window. +pub const DEFAULT_REDIS_DEDUPE_TTL: Duration = Duration::from_secs(24 * 60 * 60); + +const PUBLISH_SCRIPT: &str = r#" +local ttl = tonumber(ARGV[1]) +local maxlen = tonumber(ARGV[2]) +if KEYS[2] ~= nil then + if not redis.call('SET', KEYS[2], '1', 'NX', 'EX', ttl) then + return 0 + end +end +local args = {'XADD', KEYS[1]} +if maxlen > 0 then + table.insert(args, 'MAXLEN') + table.insert(args, '~') + table.insert(args, maxlen) +end +table.insert(args, '*') +for i = 3, #ARGV do + table.insert(args, ARGV[i]) +end +redis.call(unpack(args)) +return 1 +"#; + +/// Publishes canonical messages to Redis Streams with `XADD`. +#[derive(Clone)] +pub struct RedisStreamPublisher { + conn: ConnectionManager, + prefix: String, + stream: Option, + dedupe_ttl: Duration, + max_len: u64, + script: Script, +} + +fn retryable(context: &str, err: impl std::fmt::Display) -> TransportError { + TransportError::retryable(format!("redis {context}: {err}")) +} + +impl RedisStreamPublisher { + /// Connect lazily to `url`; construction never contacts Redis. + pub fn connect(url: &str) -> Result { + let client = Client::open(url) + .map_err(|err| TransportError::permanent(format!("redis url: {err}")))?; + let config = ConnectionManagerConfig::new() + .set_connection_timeout(Some(Duration::from_secs(2))) + .set_response_timeout(Some(Duration::from_secs(5))) + .set_number_of_retries(1); + let conn = client + .get_connection_manager_lazy(config) + .map_err(|err| retryable("connect", err))?; + Ok(Self::new(conn)) + } + + /// Wrap an existing connection manager. + pub fn new(conn: ConnectionManager) -> Self { + Self { + conn, + prefix: DEFAULT_REDIS_STREAM_PREFIX.to_string(), + stream: None, + dedupe_ttl: DEFAULT_REDIS_DEDUPE_TTL, + max_len: 0, + script: Script::new(PUBLISH_SCRIPT), + } + } + + /// Key prefix for per-name streams (default [`DEFAULT_REDIS_STREAM_PREFIX`]). + pub fn with_prefix(mut self, prefix: impl Into) -> Self { + self.prefix = prefix.into(); + self + } + + /// Publish every message to this exact stream key instead of one stream + /// per message name. + pub fn with_stream(mut self, stream: impl Into) -> Self { + self.stream = Some(stream.into()); + self + } + + /// How long a published id suppresses re-publication (minimum 1s). + pub fn with_dedupe_ttl(mut self, ttl: Duration) -> Self { + self.dedupe_ttl = ttl.max(Duration::from_secs(1)); + self + } + + /// Approximate `MAXLEN ~` trim applied on every `XADD`; 0 disables. + pub fn with_max_len(mut self, max_len: u64) -> Self { + self.max_len = max_len; + self + } + + /// The stream key a message is published to. + pub fn stream_key(&self, message: &Message) -> String { + match &self.stream { + Some(stream) => stream.clone(), + None => format!("{}:{{{}}}", self.prefix, message.name()), + } + } + + /// The dedupe marker key for `id` on `stream`. + pub fn dedupe_key(stream: &str, id: &str) -> String { + format!("{stream}:dedupe:{id}") + } + + /// Publish and report whether a new entry was appended (`false` means the + /// id was already published within the dedupe window). + pub async fn publish_entry(&self, message: &Message) -> Result { + message + .validate_name() + .map_err(|err| TransportError::permanent(err.to_string()))?; + let stream = self.stream_key(message); + let mut invocation = self.script.prepare_invoke(); + invocation.key(&stream); + if let Some(id) = message.id() { + invocation.key(Self::dedupe_key(&stream, id)); + } + invocation + .arg(self.dedupe_ttl.as_secs()) + .arg(self.max_len) + .arg("id") + .arg(message.id().unwrap_or("")) + .arg("name") + .arg(message.name()) + .arg("kind") + .arg(message.kind.as_str()) + .arg("content_type") + .arg(&message.content_type) + .arg("payload") + .arg(message.payload()); + for (key, value) in &message.metadata { + invocation.arg(format!("meta:{key}")).arg(value); + } + let mut conn = self.conn.clone(); + let reply: Value = invocation + .invoke_async(&mut conn) + .await + .map_err(|err| retryable("XADD", err))?; + Ok(matches!(reply, Value::Int(1))) + } +} + +impl MessagePublisher for RedisStreamPublisher { + async fn publish(&self, message: Message) -> Result<(), TransportError> { + self.publish_entry(&message).await.map(|_| ()) + } +} diff --git a/tests/redis_leaderboard/main.rs b/tests/redis_leaderboard/main.rs new file mode 100644 index 000000000..3078932cc --- /dev/null +++ b/tests/redis_leaderboard/main.rs @@ -0,0 +1,208 @@ +//! Redis leaderboard store and Redis Streams publisher integration tests. +//! +//! Tests that need a server skip (with a logged reason) when `REDIS_URL` is +//! unset; the unavailable-server test always runs. +//! +//! REDIS_URL=redis://127.0.0.1:6379 cargo test --test redis_leaderboard --features redis +#![cfg(feature = "redis")] + +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use distributed::bus::{Message, MessageKind, MessagePublisher, RedisStreamPublisher}; +use distributed::leaderboard::{ + conformance, Board, LeaderboardChange, LeaderboardError, LeaderboardErrorKind, + LeaderboardProjector, LeaderboardStore, RedisLeaderboard, ScorePolicy, ScoreSubmission, +}; +use distributed::DomainEventOccurrence; + +#[path = "../support/env.rs"] +mod env_support; + +/// `XRANGE` reply row: entry id and field/value pairs. +type StreamEntry = (String, Vec<(String, Vec)>); + +fn redis_url() -> Option { + env_support::broker_env("REDIS_URL", "redis leaderboard test") +} + +fn unique(prefix: &str) -> String { + format!("{prefix}-{}", uuid::Uuid::now_v7().simple()) +} + +#[derive(serde::Serialize, serde::Deserialize, distributed::DomainEvent)] +#[domain_event(name = "dungeon.gold_looted", version = 1)] +struct GoldLooted { + player: String, + gold: u32, +} + +fn looted(position: u64, player: &str, gold: u32) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + distributed::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-7".into(), + position, + key: "loot".into(), + }, + UNIX_EPOCH + Duration::from_secs(position), + Default::default(), + &GoldLooted { + player: player.into(), + gold, + }, + ) + .unwrap() +} + +#[tokio::test] +async fn redis_store_satisfies_the_leaderboard_contract() { + let Some(url) = redis_url() else { return }; + let store = RedisLeaderboard::connect(&url) + .unwrap() + .with_prefix(unique("test:lb")); + conformance::run_store_contract(&store, "contract").await; +} + +#[tokio::test] +async fn redis_projector_dedupes_replays_and_rebuilds() { + let Some(url) = redis_url() else { return }; + let store = Arc::new( + RedisLeaderboard::connect(&url) + .unwrap() + .with_prefix(unique("test:lb")), + ); + let board = Board::high_first("gold").unwrap(); + let projection_board = board.clone(); + let projection = move |event: &DomainEventOccurrence| { + let body: GoldLooted = event + .decode_body() + .map_err(|err| LeaderboardError::invalid(err.to_string()))?; + Ok(vec![LeaderboardChange::new( + projection_board.clone(), + ScoreSubmission::new(body.player, f64::from(body.gold), ScorePolicy::Increment), + )]) + }; + let projector = LeaderboardProjector::new(Arc::clone(&store), Arc::new(projection)); + let history = vec![ + looted(1, "ann", 10), + looted(2, "bob", 7), + looted(3, "ann", 5), + ]; + + for event in &history { + let message = Message::new( + event.descriptor().name.to_string(), + MessageKind::Event, + event.canonical_bytes().unwrap(), + ) + .with_id(event.id()); + assert_eq!(projector.apply_message(&message).await.unwrap().applied, 1); + // Redelivery is a no-op. + assert_eq!( + projector.apply_message(&message).await.unwrap().duplicates, + 1 + ); + } + assert_eq!(store.score(&board, "ann").await.unwrap(), Some(15.0)); + + store + .submit( + &board, + &ScoreSubmission::new("drift", 99.0, ScorePolicy::Replace), + ) + .await + .unwrap(); + let report = projector + .rebuild(std::slice::from_ref(&board), &history) + .await + .unwrap(); + assert_eq!(report.applied, 3); + let top = store.top(&board, 10).await.unwrap(); + let rows: Vec<_> = top.iter().map(|e| (e.member.as_str(), e.score)).collect(); + assert_eq!(rows, vec![("ann", 15.0), ("bob", 7.0)]); + assert_eq!( + projector.apply_event(&history[2]).await.unwrap().duplicates, + 1 + ); + store.reset(&board).await.unwrap(); +} + +#[tokio::test] +async fn redis_stream_publisher_appends_and_dedupes_by_message_id() { + let Some(url) = redis_url() else { return }; + let stream = unique("test:stream"); + let publisher = RedisStreamPublisher::connect(&url) + .unwrap() + .with_stream(stream.clone()); + let message = Message::new( + "dungeon.gold_looted", + MessageKind::Event, + b"\x00bin".to_vec(), + ) + .with_id("msg-1") + .with_metadata("correlation_id", "corr-1"); + assert!(publisher.publish_entry(&message).await.unwrap()); + assert!(!publisher.publish_entry(&message).await.unwrap()); + publisher.publish(message.clone()).await.unwrap(); + publisher + .publish(Message::new( + "dungeon.gold_looted", + MessageKind::Event, + vec![], + )) + .await + .unwrap(); + + let client = redis::Client::open(url.as_str()).unwrap(); + let mut conn = client.get_multiplexed_async_connection().await.unwrap(); + let len: u64 = redis::cmd("XLEN") + .arg(&stream) + .query_async(&mut conn) + .await + .unwrap(); + assert_eq!(len, 2, "the duplicate id must not append a second entry"); + let entries: Vec = redis::cmd("XRANGE") + .arg(&stream) + .arg("-") + .arg("+") + .query_async(&mut conn) + .await + .unwrap(); + let fields: std::collections::HashMap<_, _> = entries[0].1.iter().cloned().collect(); + assert_eq!(fields["id"], b"msg-1"); + assert_eq!(fields["kind"], b"event"); + assert_eq!(fields["payload"], b"\x00bin"); + assert_eq!(fields["meta:correlation_id"], b"corr-1"); + let _: i64 = redis::cmd("DEL") + .arg(&stream) + .arg(RedisStreamPublisher::dedupe_key(&stream, "msg-1")) + .query_async(&mut conn) + .await + .unwrap(); +} + +#[tokio::test] +async fn unreachable_redis_fails_fast_as_retryable() { + // Port 1 is never a Redis server; construction must not block. + let store = RedisLeaderboard::connect("redis://127.0.0.1:1").unwrap(); + let board = Board::high_first("gold").unwrap(); + let started = std::time::Instant::now(); + let err = store + .submit( + &board, + &ScoreSubmission::new("p", 1.0, ScorePolicy::Increment), + ) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Unavailable); + assert!(err.into_transport_error().is_retryable()); + assert!(started.elapsed() < Duration::from_secs(10)); + + let publisher = RedisStreamPublisher::connect("redis://127.0.0.1:1").unwrap(); + let err = publisher + .publish(Message::new("dungeon.gold_looted", MessageKind::Event, vec![]).with_id("x")) + .await + .unwrap_err(); + assert!(err.is_retryable()); +} From 95416313f88af390a35ec0b777a8a1a8e8e77271 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:51:17 -0500 Subject: [PATCH 121/484] feat(cell_host): add native durable SQLite cells (cell-sqlite) Native hosts can now persist aggregate cells in one SQLite file per cell through the same store the Workers host uses. A synchronous rusqlite executor exposes the Durable Object read/transaction surface, so schema bootstrap, the per-command transaction (events, snapshots, ledger receipt, outbox rows) and lease-fenced outbox settlement are shared code. - cell-sqlite feature (rusqlite 0.39, bundled; native only, no-op on wasm32); default features and the workers-rs build are unchanged - CellSqlitePath (root dir + sanitized instance name, or explicit file), CellStreamStore::open_sqlite{,_parent}, AggregateCell::open_sqlite*, from_store*, drain_outbox_with, CellOutboxStore - sealed row stored in the cell file; with_sealed_row_reducer updates it inside the command transaction (reference host applies it on commit) - cell files are bound to their instance name; Exclusive/Parent ownership rules apply to every backend - restart, idempotent replay, rollback and outbox drain tests [[tasks/gr-p1-native-durable-cells]] --- Cargo.toml | 9 + build.rs | 2 +- src/microsvc/cell_host/cell.rs | 110 +++++ src/microsvc/cell_host/mod.rs | 26 +- src/microsvc/cell_host/native_sql_executor.rs | 294 ++++++++++++ src/microsvc/cell_host/native_sqlite.rs | 362 +++++++++++++++ src/microsvc/cell_host/sql_executor.rs | 32 +- src/microsvc/cell_host/sql_store.rs | 227 +++++++-- src/microsvc/cell_host/store.rs | 209 ++++++++- src/microsvc/cell_host/tests.rs | 40 ++ src/microsvc/cell_host/tests/native_sqlite.rs | 431 ++++++++++++++++++ src/repository/migrations.rs | 7 +- src/repository/mod.rs | 3 +- src/repository/sql/outbox.rs | 2 + tests/celld/README.md | 28 ++ 15 files changed, 1702 insertions(+), 80 deletions(-) create mode 100644 src/microsvc/cell_host/native_sql_executor.rs create mode 100644 src/microsvc/cell_host/native_sqlite.rs create mode 100644 src/microsvc/cell_host/tests/native_sqlite.rs diff --git a/Cargo.toml b/Cargo.toml index fc02e1729..e306f3892 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,6 +57,10 @@ nats = ["dep:async-nats", "dep:futures", "dep:tokio"] rabbitmq = ["dep:lapin", "dep:futures", "dep:tokio"] kafka = ["dep:rdkafka", "dep:tokio"] workers-rs = ["dep:worker"] +# Native durable aggregate cells: one synchronous SQLite file per cell, same +# SQL store and one-transaction-per-command contract as Durable Object cells. +# Separate from `sqlite` (async SQLx pool + tokio); no-op on wasm32. +cell-sqlite = ["dep:rusqlite"] otel = ["dep:opentelemetry", "dep:opentelemetry_sdk", "dep:tracing", "dep:tracing-opentelemetry"] graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:hmac", "dep:jsonwebtoken", "http", "axum?/ws"] @@ -99,6 +103,11 @@ uuid = { version = "1", features = ["v7"] } url = { version = "2", optional = true } worker = { version = "0.8", features = ["queue"], optional = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# libsqlite3-sys 0.37 stays inside SQLx 0.9's accepted range, so `sqlite` and +# `cell-sqlite` link one bundled SQLite when enabled together. +rusqlite = { version = "0.39", features = ["bundled"], optional = true } + [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] js-sys = "0.3" uuid = { version = "1", features = ["v7", "js"] } diff --git a/build.rs b/build.rs index c406446f3..56da375ba 100644 --- a/build.rs +++ b/build.rs @@ -162,7 +162,7 @@ fn emit_migration_inventory() { fn emit_dialect(generated: &mut String, name: &str, dialect: Dialect, inventory: &Inventory) { match dialect { - Dialect::Sqlite => generated.push_str("#[cfg(any(feature = \"sqlite\", all(feature = \"workers-rs\", target_arch = \"wasm32\")))]\n"), + Dialect::Sqlite => generated.push_str("#[cfg(any(feature = \"sqlite\", all(feature = \"workers-rs\", target_arch = \"wasm32\"), all(feature = \"cell-sqlite\", not(target_arch = \"wasm32\"))))]\n"), Dialect::Postgres => generated.push_str("#[cfg(feature = \"postgres\")]\n"), } generated.push_str("pub(crate) const "); diff --git a/src/microsvc/cell_host/cell.rs b/src/microsvc/cell_host/cell.rs index b74904a13..0b5181584 100644 --- a/src/microsvc/cell_host/cell.rs +++ b/src/microsvc/cell_host/cell.rs @@ -78,6 +78,92 @@ where }) } + /// Open a durable cell backed by its own SQLite file (`cell-sqlite`). + /// + /// The file is `location.resolve("{aggregate_type}:{shard_id}")`. Each + /// command commits events, snapshots, its ledger receipt and outbox rows + /// in one SQLite transaction, exactly as `from_state` does on Workers. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn open_sqlite( + location: &super::CellSqlitePath, + shard_id: impl Into, + ) -> Result { + let shard = StreamIdentity::new(A::aggregate_type(), shard_id.into())?; + Self::from_store(CellStreamStore::open_sqlite(location, shard)?) + } + + /// Host a prepared exclusive store (for example a SQLite cell configured + /// with [`CellStreamStore::with_sealed_row_reducer`]). + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + pub fn from_store(store: CellStreamStore) -> Result { + let shard = Self::store_shard(&store)?; + Ok(Self::from_repository( + shard, + AggregateRepository::new(store), + )) + } + + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + fn store_shard(store: &CellStreamStore) -> Result { + match store.identity() { + Some(identity) if identity.aggregate_type() == A::aggregate_type() => { + Ok(identity.clone()) + } + Some(identity) => Err(RepositoryError::Model(format!( + "cell store `{identity}` does not hold aggregate type `{}`", + A::aggregate_type() + ))), + None => Err(RepositoryError::Model( + "aggregate cells require an exclusive cell store".into(), + )), + } + } + + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + fn from_repository( + shard: StreamIdentity, + repository: AggregateRepository, + ) -> Self { + Self { + shard, + routes: Routes::from_dependencies(repository), + #[cfg(feature = "workers-rs")] + celld_outbox: None, + #[cfg(all(feature = "workers-rs", any(target_arch = "wasm32", test)))] + activity: Default::default(), + } + } + + /// Native equivalent of the celld alarm drain: one claim -> publish -> + /// delete pass over this cell's committed outbox (lease-fenced rows). + /// + /// Call it at startup (rows survive a restart), after dispatch for low + /// latency, and periodically; or hand [`Self::outbox_dispatcher`] to an + /// `OutboxDrainRunner` on a tokio runtime. Publication failures are + /// released (or failed after `max_attempts`) for the next pass. A crash + /// between publish and delete re-delivers the same stable message id, so + /// delivery is at-least-once and consumers must deduplicate. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + pub async fn drain_outbox_with

( + &self, + publisher: P, + lease: Duration, + max_attempts: u32, + batch_size: usize, + ) -> Result + where + P: crate::bus::MessagePublisher, + { + self.outbox_dispatcher( + publisher, + format!("cell-outbox:{}", self.instance_name()), + lease, + max_attempts, + ) + .dispatch_batch(batch_size) + .await + } + /// Open the named runtime-owned SQLite cell. Mount commands and configure /// its Queue binding before dispatch; no in-memory persistence path exists. #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] @@ -376,6 +462,30 @@ where }) } + /// Open a durable SQLite cell with repository snapshot caching. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn open_sqlite_with_snapshots( + location: &super::CellSqlitePath, + shard_id: impl Into, + frequency: u64, + ) -> Result { + let shard = StreamIdentity::new(A::aggregate_type(), shard_id.into())?; + Self::from_store_with_snapshots(CellStreamStore::open_sqlite(location, shard)?, frequency) + } + + /// Host a prepared exclusive store with repository snapshot caching. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + pub fn from_store_with_snapshots( + store: CellStreamStore, + frequency: u64, + ) -> Result { + let shard = Self::store_shard(&store)?; + Ok(Self::from_repository( + shard, + AggregateRepository::new(store).with_snapshots(frequency), + )) + } + /// Open a cell with repository snapshot caching (`with_snapshots`). #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn new_with_snapshots( diff --git a/src/microsvc/cell_host/mod.rs b/src/microsvc/cell_host/mod.rs index 8209bd249..26b354ae1 100644 --- a/src/microsvc/cell_host/mod.rs +++ b/src/microsvc/cell_host/mod.rs @@ -12,6 +12,14 @@ //! The GraphQL wait-path (`CelldCommandHost`) is the same for every aggregate: //! routes only supply kind, shard, and payload. Aggregate Workers own outbox //! delivery through celld Queue. +//! +//! Durable storage is one SQLite database per cell on both targets, through +//! one shared store (`sql_store.rs`): Durable Object `storage.sql` on +//! `workers-rs`/wasm32, and a synchronous rusqlite file per cell on native +//! hosts with the `cell-sqlite` feature (`CellSqlitePath`, +//! `AggregateCell::open_sqlite`). `cell-sqlite` selects a storage backend +//! only; the cell host itself stays ungated (`PCH-DEC-005`). Without it, +//! native cells use the in-process reference host. pub(crate) mod causal; mod cell; @@ -20,9 +28,19 @@ mod celld_outbox; #[cfg(feature = "graphql")] mod command; mod internal_auth; +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +mod native_sqlite; #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] mod sql_executor; -#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +// Native durable cells reuse the Durable Object store over a rusqlite executor +// with the same `read`/`transaction` surface (see `native_sql_executor.rs`). +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +#[path = "native_sql_executor.rs"] +mod sql_executor; +#[cfg(any( + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) +))] mod sql_store; mod store; mod wire; @@ -43,11 +61,15 @@ pub use command::{CelldCommandHost, CelldRoute}; pub use internal_auth::{ InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, }; +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +pub use native_sqlite::{CellOutboxStore, CellSqlitePath, NATIVE_CELL_SQLITE_EXTENSION}; +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +pub use sql_store::CellSqlOutboxStore; pub use store::CellStreamStore; #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub use store::{ DurableAggregateCellState, DurableCellCommand, DurableCellEvents, DurableCellSnapshot, - DURABLE_AGGREGATE_CELL_STATE_VERSION, + SealedRowReducer, DURABLE_AGGREGATE_CELL_STATE_VERSION, }; pub(crate) use wire::validate_cell_projection_events; pub use wire::{ diff --git a/src/microsvc/cell_host/native_sql_executor.rs b/src/microsvc/cell_host/native_sql_executor.rs new file mode 100644 index 000000000..3efe856e9 --- /dev/null +++ b/src/microsvc/cell_host/native_sql_executor.rs @@ -0,0 +1,294 @@ +//! Native execution of the shared cell SQL repository operations. +//! +//! This is the `cell-sqlite` counterpart of the Durable Object executor in +//! `sql_executor.rs`. Both expose the same `CellSqlConnection::{read, +//! transaction}` surface to `sql_store.rs`, so schema bootstrap, commits, +//! ledger fencing and outbox leases are one shared implementation. +//! +//! # Why a synchronous binding (rusqlite), not SQLx +//! +//! Durable Object `storage.transactionSync` runs the whole command commit in +//! one synchronous callback: nothing can yield between the domain, snapshot, +//! receipt and delivery participants. `rusqlite` gives the same shape natively: +//! `BEGIN IMMEDIATE`, the shared operations completed by `finish_sql` without +//! awaiting, then `COMMIT` (or `ROLLBACK` on any error). An async SQLx pool +//! would need a different, await-based transaction owner and would let the +//! shared store observe a different atomicity contract on each target. +//! +//! One connection per cell file is held behind a mutex; reads and transactions +//! from the same process are serialized just like Durable Object input gates. +//! SQLite calls block the calling thread for their (local, short) duration. + +use std::collections::HashMap; +use std::path::Path; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime}; + +use rusqlite::types::Value; +use rusqlite::Connection; + +use crate::repository::sql::{SqlBind, SqlExecutor, SqlPart, SqlRow, Statement}; +use crate::repository::{sqlite_codec, RepositoryError}; + +/// How long a writer waits for another process holding the same cell file. +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Clone)] +pub(crate) struct CellSqlConnection(Arc>); + +impl CellSqlConnection { + /// Open (creating when absent) one cell's SQLite file. + pub fn open(path: &Path) -> Result { + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent).map_err(|error| { + RepositoryError::permanent_storage("create cell directory", error) + })?; + } + let connection = Connection::open(path).map_err(sqlite_error)?; + connection + .busy_timeout(BUSY_TIMEOUT) + .map_err(sqlite_error)?; + // WAL keeps readers off the writer; FULL syncs every commit so an + // acknowledged command survives power loss, not only process loss. + connection + .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get::<_, String>(0)) + .map_err(sqlite_error)?; + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(sqlite_error)?; + Ok(Self(Arc::new(Mutex::new(connection)))) + } + + fn lock(&self) -> MutexGuard<'_, Connection> { + match self.0.lock() { + Ok(guard) => guard, + Err(poisoned) => { + // A panic inside a transaction callback left it open. Roll it + // back so no partial command can be committed by a later one. + let guard = poisoned.into_inner(); + if !guard.is_autocommit() { + let _ = guard.execute_batch("ROLLBACK"); + } + self.0.clear_poison(); + guard + } + } + } + + /// Run reads outside an explicit transaction, serialized with commits. + pub fn read>( + &self, + operation: impl FnOnce(&mut CellSqlExecutor<'_>) -> Result, + ) -> Result { + let mut guard = self.lock(); + operation(&mut CellSqlExecutor(&mut guard)) + } + + /// Run `operation` in one `BEGIN IMMEDIATE` transaction. Any error rolls + /// back every participant; nothing is committed before `COMMIT` returns. + pub fn transaction>( + &self, + operation: impl FnOnce(&mut CellSqlExecutor<'_>) -> Result, + ) -> Result { + let mut guard = self.lock(); + guard + .execute_batch("BEGIN IMMEDIATE") + .map_err(sqlite_error)?; + match operation(&mut CellSqlExecutor(&mut guard)) { + Ok(value) => match guard.execute_batch("COMMIT") { + Ok(()) => Ok(value), + Err(error) => { + let _ = guard.execute_batch("ROLLBACK"); + Err(sqlite_error(error).into()) + } + }, + Err(error) => { + guard.execute_batch("ROLLBACK").map_err(sqlite_error)?; + Err(error) + } + } + } +} + +pub(crate) struct CellSqlExecutor<'a>(&'a mut Connection); +pub(crate) struct CellSqlRow(HashMap); + +impl CellSqlRow { + fn value(&self, column: &str) -> Result<&Value, RepositoryError> { + self.0 + .get(column) + .ok_or_else(|| RepositoryError::Model(format!("cell SQL row is missing {column}"))) + } + fn invalid(column: &str) -> RepositoryError { + RepositoryError::Model(format!( + "cell SQL column {column} has the wrong storage type" + )) + } +} + +impl SqlRow for CellSqlRow { + fn text(&self, column: &'static str) -> Result { + match self.value(column)? { + Value::Text(value) => Ok(value.clone()), + _ => Err(Self::invalid(column)), + } + } + fn integer(&self, column: &'static str) -> Result { + match self.value(column)? { + Value::Integer(value) => Ok(*value), + _ => Err(Self::invalid(column)), + } + } + fn optional_text(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + Value::Null => Ok(None), + _ => self.text(column).map(Some), + } + } + fn optional_timestamp( + &self, + column: &'static str, + ) -> Result, RepositoryError> { + match self.value(column)? { + Value::Null => Ok(None), + _ => self.timestamp(column).map(Some), + } + } + fn optional_integer(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + Value::Null => Ok(None), + _ => self.integer(column).map(Some), + } + } + fn bytes(&self, column: &'static str) -> Result, RepositoryError> { + match self.value(column)? { + Value::Blob(value) => Ok(value.clone()), + _ => Err(Self::invalid(column)), + } + } + fn timestamp(&self, column: &'static str) -> Result { + match self.value(column)? { + Value::Text(value) => sqlite_codec::decode(value), + Value::Real(value) => sqlite_codec::decode_epoch(*value), + Value::Integer(value) => sqlite_codec::decode_epoch(*value as f64), + _ => Err(Self::invalid(column)), + } + } +} + +/// Render a structural statement exactly as the Durable Object executor does: +/// same SQLite expressions, `?` placeholders and value storage classes. +fn render(statement: Statement<'_>) -> Result<(String, Vec), RepositoryError> { + let mut sql = String::new(); + let mut bindings = Vec::new(); + for part in statement.0 { + match part { + SqlPart::TimestampCompare { + column, + operator, + value, + } => { + sql.push_str(&format!( + "CAST({column} AS REAL) {operator} CAST(? AS REAL)" + )); + bindings.push(Value::Text(sqlite_codec::encode(value)?)); + } + SqlPart::LedgerNow | SqlPart::LedgerNowEpoch => { + sql.push_str("unixepoch('now','subsec')") + } + SqlPart::LedgerDeadline(duration) => { + sql.push_str("(unixepoch('now','subsec') + ?)"); + bindings.push(Value::Real(duration.as_secs_f64())); + } + SqlPart::LedgerDeadlineIsLive(deadline) => { + sql.push_str("CAST(? AS REAL) > unixepoch('now','subsec')"); + bindings.push(Value::Text(sqlite_codec::encode(deadline)?)); + } + SqlPart::LedgerJson(json) => { + sql.push('?'); + bindings.push(Value::Text(json)); + } + SqlPart::Sql(text) => sql.push_str(&text), + SqlPart::Bind(value) => { + sql.push('?'); + bindings.push(match value { + SqlBind::Text(value) | SqlBind::Metadata(value) => Value::Text(value), + SqlBind::Bytes(value) => Value::Blob(value.into_owned()), + SqlBind::Integer(value) => Value::Integer(value), + SqlBind::Timestamp(value) => Value::Text(sqlite_codec::encode(value)?), + }); + } + } + } + Ok((sql, bindings)) +} + +impl CellSqlExecutor<'_> { + fn query_rows(&mut self, statement: Statement<'_>) -> Result, RepositoryError> { + let (sql, bindings) = render(statement)?; + let mut prepared = self.0.prepare_cached(&sql).map_err(sqlite_error)?; + let names = prepared + .column_names() + .into_iter() + .map(String::from) + .collect::>(); + let mut rows = prepared + .query(rusqlite::params_from_iter(bindings)) + .map_err(sqlite_error)?; + let mut result = Vec::new(); + while let Some(row) = rows.next().map_err(sqlite_error)? { + let mut values = HashMap::with_capacity(names.len()); + for (index, name) in names.iter().enumerate() { + values.insert( + name.clone(), + row.get::<_, Value>(index).map_err(sqlite_error)?, + ); + } + result.push(CellSqlRow(values)); + } + Ok(result) + } + + fn execute_statement(&mut self, statement: Statement<'_>) -> Result { + let (sql, bindings) = render(statement)?; + if bindings.is_empty() { + // Validated migrations run as one whole script, as `storage.sql.exec` + // does; never split SQL text on semicolons. + self.0.execute_batch(&sql).map_err(sqlite_error)?; + return Ok(self.0.changes()); + } + let mut prepared = self.0.prepare_cached(&sql).map_err(sqlite_error)?; + let written = prepared + .execute(rusqlite::params_from_iter(bindings)) + .map_err(sqlite_error)?; + Ok(written as u64) + } +} + +impl SqlExecutor for CellSqlExecutor<'_> { + type Row = CellSqlRow; + const EVENT_SELECT: &'static str = sqlite_codec::EVENT_SELECT; + const SNAPSHOT_SELECT: &'static str = sqlite_codec::SNAPSHOT_SELECT; + const OUTBOX_SELECT: &'static str = sqlite_codec::OUTBOX_SELECT; + const NOW: &'static str = "CURRENT_TIMESTAMP"; + const COMMAND_LEDGER_SELECT: &'static str = sqlite_codec::COMMAND_LEDGER_SELECT; + const COMMAND_LEDGER_LOCK_SUFFIX: &'static str = ""; + const COMMAND_LEDGER_COMPACTION_LOCK_SUFFIX: &'static str = ""; + + async fn query(&mut self, statement: Statement<'_>) -> Result, RepositoryError> { + self.query_rows(statement) + } + + async fn execute(&mut self, statement: Statement<'_>) -> Result { + self.execute_statement(statement) + } +} + +fn sqlite_error(error: rusqlite::Error) -> RepositoryError { + // Match the Durable Object adapter: storage failures are never allowed to + // permanently discard a command or pending delivery. + RepositoryError::retryable_storage("cell SQL", error) +} diff --git a/src/microsvc/cell_host/native_sqlite.rs b/src/microsvc/cell_host/native_sqlite.rs new file mode 100644 index 000000000..bc9abf8f8 --- /dev/null +++ b/src/microsvc/cell_host/native_sqlite.rs @@ -0,0 +1,362 @@ +//! Native durable cell storage (`cell-sqlite`). +//! +//! Deployment model: one SQLite file per cell instance, the native analogue of +//! one Durable Object per `{aggregate_type}:{shard}`. [`CellSqlitePath`] +//! derives the file from a root directory and the sanitized instance name, or +//! names one file explicitly. Every command commits its events, snapshots, +//! command-ledger receipt, outbox rows and (optionally) the sealed row in one +//! SQLite transaction through the store shared with Workers (`sql_store.rs`). +//! +//! The in-process reference host ([`CellStreamStore::new`] and friends) is +//! unchanged and still backs the whole-state export used by conformance +//! fixtures; the SQLite backend is selected only by the `open_sqlite*` +//! constructors. +//! +//! [`CellStreamStore::new`]: super::CellStreamStore::new + +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +use super::sql_store::{CellSqlOutboxStore, CellSqlRepository}; +use crate::command_ledger::{ + AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, + CausalStorageIdentity, CausalTransactionalCommit, CommandLedgerError, CommandLedgerKey, + CommandLedgerStore, CommandLookup, CommandLookupScope, CommandReservation, + ExternalCommandCompletion, ReservationOutcome, +}; +use crate::entity::Entity; +use crate::microsvc::HasOutboxStore; +use crate::outbox::{OutboxMessage, OutboxMessageStatus}; +use crate::outbox_worker::{ClaimOutboxMessages, OutboxBacklogStats, OutboxClaimRef, OutboxStore}; +use crate::repository::{ + CommitBatch, GetStream, RepositoryError, SnapshotStore, StreamIdentity, TransactionalCommit, +}; +use crate::snapshot::SnapshotRecord; +use crate::{InMemoryOutboxStore, InMemoryRepository}; + +/// File extension used for cell files derived from a root directory. +pub const NATIVE_CELL_SQLITE_EXTENSION: &str = "sqlite3"; + +/// Longest sanitized instance name kept verbatim in a derived file name. +const MAX_FILE_STEM: usize = 120; + +/// Where a native cell keeps its SQLite file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CellSqlitePath { + /// One file per cell under this directory: + /// `{root}/{sanitized instance name}.sqlite3`. + Root(PathBuf), + /// This exact file. The file is bound to the first cell that opens it. + File(PathBuf), +} + +impl CellSqlitePath { + /// Derive one file per cell instance under `dir`. + pub fn root(dir: impl Into) -> Self { + Self::Root(dir.into()) + } + + /// Use exactly `path` for one cell. + pub fn file(path: impl Into) -> Self { + Self::File(path.into()) + } + + /// The database file for `instance_name` (`{aggregate_type}:{shard}`). + pub fn resolve(&self, instance_name: &str) -> PathBuf { + match self { + Self::Root(root) => root.join(Self::file_name(instance_name)), + Self::File(path) => path.clone(), + } + } + + /// Injective, filesystem-safe file name for an instance name. + /// + /// `[A-Za-z0-9_-]` and non-leading `.` are kept; every other byte is + /// percent-encoded, so `game:a` and `game_a` never share a file. Very long + /// names keep a readable prefix plus a SHA-256 suffix of the full name. + pub fn file_name(instance_name: &str) -> String { + let mut stem = String::with_capacity(instance_name.len()); + for (index, byte) in instance_name.bytes().enumerate() { + let keep = byte.is_ascii_alphanumeric() + || byte == b'-' + || byte == b'_' + || (byte == b'.' && index != 0); + if keep { + stem.push(byte as char); + } else { + stem.push_str(&format!("%{byte:02X}")); + } + } + if stem.is_empty() { + stem.push_str("%00"); + } + if stem.len() > MAX_FILE_STEM { + let digest = format!("{:x}", Sha256::digest(instance_name.as_bytes())); + let mut cut = MAX_FILE_STEM - 33; + while !stem.is_char_boundary(cut) { + cut -= 1; + } + stem = format!("{}~{}", &stem[..cut], &digest[..32]); + } + format!("{stem}.{NATIVE_CELL_SQLITE_EXTENSION}") + } + + pub(super) fn open(&self, instance_name: &str) -> Result { + CellSqlRepository::open(Path::new(&self.resolve(instance_name)), instance_name) + } +} + +/// Native cell backend: the in-process reference host or a SQLite file. +#[derive(Clone)] +pub(super) enum NativeCellRepository { + Memory(InMemoryRepository), + Sql(CellSqlRepository), +} + +impl NativeCellRepository { + pub(super) fn memory(&self) -> Result<&InMemoryRepository, RepositoryError> { + match self { + Self::Memory(memory) => Ok(memory), + Self::Sql(_) => Err(RepositoryError::Model( + "SQLite cells persist rows directly; whole-state export/restore is only \ + available on the in-process reference host" + .into(), + )), + } + } + + pub(super) fn sql(&self) -> Option<&CellSqlRepository> { + match self { + Self::Sql(sql) => Some(sql), + Self::Memory(_) => None, + } + } + + pub(super) fn sql_mut(&mut self) -> Option<&mut CellSqlRepository> { + match self { + Self::Sql(sql) => Some(sql), + Self::Memory(_) => None, + } + } +} + +macro_rules! delegate { + ($self:ident, $inner:ident => $call:expr) => { + match $self { + NativeCellRepository::Memory($inner) => $call, + NativeCellRepository::Sql($inner) => $call, + } + }; +} + +impl GetStream for NativeCellRepository { + async fn get_stream( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + delegate!(self, inner => GetStream::get_stream(inner, identity).await) + } + + async fn get_stream_tail( + &self, + identity: &StreamIdentity, + after_version: u64, + ) -> Result, RepositoryError> { + delegate!(self, inner => GetStream::get_stream_tail(inner, identity, after_version).await) + } +} + +impl CausalGetStream for NativeCellRepository { + async fn get_causal_stream( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + delegate!(self, inner => CausalGetStream::get_causal_stream(inner, identity).await) + } + + async fn get_causal_stream_tail( + &self, + identity: &StreamIdentity, + after_version: u64, + ) -> Result, RepositoryError> { + delegate!(self, inner => inner.get_causal_stream_tail(identity, after_version).await) + } +} + +impl SnapshotStore for NativeCellRepository { + async fn get_snapshot( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + delegate!(self, inner => SnapshotStore::get_snapshot(inner, identity).await) + } + + async fn get_snapshots( + &self, + identities: &[StreamIdentity], + ) -> Result, RepositoryError> { + delegate!(self, inner => SnapshotStore::get_snapshots(inner, identities).await) + } + + async fn save_snapshot( + &self, + identity: &StreamIdentity, + record: SnapshotRecord, + ) -> Result<(), RepositoryError> { + delegate!(self, inner => SnapshotStore::save_snapshot(inner, identity, record).await) + } + + async fn delete_snapshot(&self, identity: &StreamIdentity) -> Result { + delegate!(self, inner => SnapshotStore::delete_snapshot(inner, identity).await) + } +} + +impl CausalRepositoryIdentity for NativeCellRepository { + fn causal_storage_identity(&self) -> CausalStorageIdentity { + delegate!(self, inner => CausalRepositoryIdentity::causal_storage_identity(inner)) + } +} + +impl CommandLedgerStore for NativeCellRepository { + async fn reserve_command( + &self, + reservation: CommandReservation, + ) -> Result { + delegate!(self, inner => CommandLedgerStore::reserve_command(inner, reservation).await) + } + + async fn lookup_command( + &self, + key: &CommandLedgerKey, + scope: CommandLookupScope<'_>, + ) -> Result { + delegate!(self, inner => CommandLedgerStore::lookup_command(inner, key, scope).await) + } + + async fn mark_retryable_unknown( + &self, + attempt: AttemptFence, + ) -> Result<(), CommandLedgerError> { + delegate!(self, inner => CommandLedgerStore::mark_retryable_unknown(inner, attempt).await) + } + + async fn complete_external_command( + &self, + completion: ExternalCommandCompletion, + ) -> Result<(), CommandLedgerError> { + delegate!(self, inner => CommandLedgerStore::complete_external_command(inner, completion).await) + } + + async fn compact_expired_commands(&self, limit: usize) -> Result { + delegate!(self, inner => CommandLedgerStore::compact_expired_commands(inner, limit).await) + } +} + +impl TransactionalCommit for NativeCellRepository { + async fn commit_batch(&self, batch: CommitBatch<'_>) -> Result<(), RepositoryError> { + delegate!(self, inner => TransactionalCommit::commit_batch(inner, batch).await) + } +} + +impl CausalTransactionalCommit for NativeCellRepository { + async fn commit_causal_batch( + &self, + batch: CausalCommitBatch<'_>, + ) -> Result<(), CommandLedgerError> { + delegate!(self, inner => CausalTransactionalCommit::commit_causal_batch(inner, batch).await) + } +} + +impl HasOutboxStore for NativeCellRepository { + type OutboxStore = CellOutboxStore; + + fn outbox_store(&self) -> CellOutboxStore { + match self { + Self::Memory(inner) => CellOutboxStore::Memory(inner.outbox_store()), + Self::Sql(inner) => CellOutboxStore::Sql(HasOutboxStore::outbox_store(inner)), + } + } +} + +/// Outbox of a native cell: the reference host's rows or the cell's SQLite +/// `outbox_messages` table (lease-fenced claim, publish, delete). +#[derive(Clone)] +pub enum CellOutboxStore { + Memory(InMemoryOutboxStore), + Sql(CellSqlOutboxStore), +} + +macro_rules! delegate_outbox { + ($self:ident, $inner:ident => $call:expr) => { + match $self { + CellOutboxStore::Memory($inner) => $call, + CellOutboxStore::Sql($inner) => $call, + } + }; +} + +impl OutboxStore for CellOutboxStore { + async fn messages_by_status( + &self, + status: OutboxMessageStatus, + limit: usize, + ) -> Result, RepositoryError> { + delegate_outbox!(self, inner => inner.messages_by_status(status, limit).await) + } + + async fn backlog_stats(&self) -> Result { + delegate_outbox!(self, inner => inner.backlog_stats().await) + } + + async fn claim( + &self, + request: ClaimOutboxMessages, + ) -> Result, RepositoryError> { + delegate_outbox!(self, inner => inner.claim(request).await) + } + + async fn complete(&self, claim: &OutboxClaimRef) -> Result<(), RepositoryError> { + delegate_outbox!(self, inner => inner.complete(claim).await) + } + + async fn complete_many(&self, claims: &[OutboxClaimRef]) -> Result<(), RepositoryError> { + delegate_outbox!(self, inner => inner.complete_many(claims).await) + } + + async fn release(&self, claim: &OutboxClaimRef, error: &str) -> Result<(), RepositoryError> { + delegate_outbox!(self, inner => inner.release(claim, error).await) + } + + async fn fail(&self, claim: &OutboxClaimRef, error: &str) -> Result<(), RepositoryError> { + delegate_outbox!(self, inner => inner.fail(claim, error).await) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_names_are_safe_and_injective() { + assert_eq!(CellSqlitePath::file_name("game:g1"), "game%3Ag1.sqlite3"); + assert_ne!( + CellSqlitePath::file_name("game:a"), + CellSqlitePath::file_name("game_a") + ); + assert_eq!(CellSqlitePath::file_name(".."), "%2E..sqlite3"); + assert_eq!(CellSqlitePath::file_name("a/../b"), "a%2F..%2Fb.sqlite3"); + let long = format!("Room:{}", "x".repeat(400)); + let name = CellSqlitePath::file_name(&long); + assert!(name.len() < 140, "{name}"); + assert_ne!(name, CellSqlitePath::file_name(&format!("{long}y"))); + assert_eq!( + CellSqlitePath::root("/data/cells").resolve("Room:r1"), + PathBuf::from("/data/cells/Room%3Ar1.sqlite3") + ); + assert_eq!( + CellSqlitePath::file("/tmp/one.db").resolve("Room:r1"), + PathBuf::from("/tmp/one.db") + ); + } +} diff --git a/src/microsvc/cell_host/sql_executor.rs b/src/microsvc/cell_host/sql_executor.rs index 9c394e7a5..8deb49b2f 100644 --- a/src/microsvc/cell_host/sql_executor.rs +++ b/src/microsvc/cell_host/sql_executor.rs @@ -5,8 +5,6 @@ //! commit cannot yield between its domain and delivery/receipt participants. use std::collections::HashMap; -use std::future::Future; -use std::task::{Context, Poll, Waker}; use std::time::SystemTime; use worker::js_sys::{Function, Reflect}; @@ -42,10 +40,19 @@ impl CellSqlConnection { }) } - pub fn executor(&self) -> CellSqlExecutor { + fn executor(&self) -> CellSqlExecutor { CellSqlExecutor(self.sql.clone()) } + /// Run reads outside an explicit transaction. The Durable Object input + /// gate already serializes them with this cell's commits. + pub fn read>( + &self, + operation: impl FnOnce(&mut CellSqlExecutor) -> Result, + ) -> Result { + operation(&mut self.executor()) + } + pub fn transaction>( &self, operation: impl FnOnce(&mut CellSqlExecutor) -> Result, @@ -81,25 +88,6 @@ impl CellSqlConnection { } } -/// Shared SQL operations are async for SQLx, but every call through the cell -/// executor completes synchronously. Refuse accidental async work; never spin -/// or let a pending future outlive the transaction callback. -pub(crate) fn finish_sql>( - future: impl Future>, -) -> Result { - let mut future = std::pin::pin!(future); - match future - .as_mut() - .poll(&mut Context::from_waker(Waker::noop())) - { - Poll::Ready(result) => result, - Poll::Pending => Err(RepositoryError::Model( - "cell SQL transaction attempted to await asynchronous work".into(), - ) - .into()), - } -} - #[derive(Clone)] pub(crate) struct CellSqlExecutor(SqlStorage); pub(crate) struct CellSqlRow(HashMap); diff --git a/src/microsvc/cell_host/sql_store.rs b/src/microsvc/cell_host/sql_store.rs index b39e00efd..ab2acf98d 100644 --- a/src/microsvc/cell_host/sql_store.rs +++ b/src/microsvc/cell_host/sql_store.rs @@ -1,10 +1,20 @@ //! Cell-local execution of the ordinary SQL event/snapshot/receipt repository. //! No in-memory working copy and no whole-cell export are used here. +//! +//! Shared by both cell executors: Durable Object `storage.sql` on +//! `workers-rs`/wasm32 and a synchronous rusqlite file on native +//! `cell-sqlite`. Each executor supplies only `read` and a synchronous +//! all-or-nothing `transaction`; schema bootstrap, the command commit, ledger +//! fencing and outbox leases below are identical on both targets. + +use std::future::Future; +use std::task::{Context, Poll, Waker}; use sha2::{Digest, Sha256}; +#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] use worker::State; -use super::sql_executor::{finish_sql, CellSqlConnection}; +use super::sql_executor::CellSqlConnection; use crate::command_ledger::{ AttemptFence, CausalCommitBatch, CausalGetStream, CausalRepositoryIdentity, CausalStorageIdentity, CausalTransactionalCommit, CommandCompletion, CommandLedgerError, @@ -26,15 +36,80 @@ use crate::snapshot::SnapshotRecord; // Both shared insert planners split large commands within the same transaction. const MAX_SQL_BIND_PARAMS: usize = 100; +/// Shared SQL operations are async for SQLx, but every call through a cell +/// executor completes synchronously. Refuse accidental async work; never spin +/// or let a pending future outlive the transaction callback. +pub(super) fn finish_sql>( + future: impl Future>, +) -> Result { + let mut future = std::pin::pin!(future); + match future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + Poll::Ready(result) => result, + Poll::Pending => Err(RepositoryError::Model( + "cell SQL transaction attempted to await asynchronous work".into(), + ) + .into()), + } +} + +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +use super::store::SealedRowReducer; + #[derive(Clone)] pub(super) struct CellSqlRepository { connection: CellSqlConnection, identity: CausalStorageIdentity, + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + sealed_row_reducer: Option, } impl CellSqlRepository { + #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] pub fn from_state(state: State) -> Result { let connection = CellSqlConnection::from_state(state)?; + Self::initialize(&connection)?; + Ok(Self { + connection, + identity: CausalStorageIdentity::new(), + }) + } + + /// Open one native cell file. The file is bound to `instance_name` on + /// first open; reopening it as another cell fails closed. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn open(path: &std::path::Path, instance_name: &str) -> Result { + let connection = CellSqlConnection::open(path)?; + Self::initialize(&connection)?; + connection + .transaction(|executor| finish_sql(native::bind_instance(executor, instance_name)))?; + Ok(Self { + connection, + identity: CausalStorageIdentity::new(), + sealed_row_reducer: None, + }) + } + + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn set_sealed_row_reducer(&mut self, reducer: SealedRowReducer) { + self.sealed_row_reducer = Some(reducer); + } + + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn sealed_row(&self) -> Result, RepositoryError> { + self.connection + .read(|executor| finish_sql(native::sealed_row(executor))) + } + + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn replace_sealed_row(&self, row: &serde_json::Value) -> Result<(), RepositoryError> { + self.connection + .transaction(|executor| finish_sql(native::write_sealed_row(executor, row))) + } + + fn initialize(connection: &CellSqlConnection) -> Result<(), RepositoryError> { connection.transaction(|executor| finish_sql(async { let tables = executor.query(Statement::new("SELECT name FROM sqlite_master WHERE type = 'table'")).await?; let tables = tables.iter().map(|row| row.text("name")).collect::, _>>()?; @@ -66,11 +141,7 @@ impl CellSqlRepository { .bind(migration.version.into()).sql(", ").bind(checksum.as_str().into()).sql(")")).await?; } Ok::<_, RepositoryError>(()) - }))?; - Ok(Self { - connection, - identity: CausalStorageIdentity::new(), - }) + })) } fn commit( @@ -130,6 +201,19 @@ impl CellSqlRepository { let SnapshotWrite::Save { identity, record } = snapshot; sql::save_snapshot(executor, identity, record).await?; } + // Native sealed read-model row: same transaction, so a reducer + // error or lost ledger lease rolls the row back with the events. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + if let Some(reducer) = &self.sealed_row_reducer { + if prepared.iter().any(|append| !append.events.is_empty()) { + let current = native::sealed_row(executor).await?; + if let Some(next) = reducer(current.as_ref(), &prepared)? { + if current.as_ref() != Some(&next) { + native::write_sealed_row(executor, &next).await?; + } + } + } + } // Same final fenced write as SQLx. A lost lease rolls back every // participant, and entities are marked committed only afterwards. if let Some(completion) = &completion { @@ -150,22 +234,16 @@ impl GetStream for CellSqlRepository { &self, identity: &StreamIdentity, ) -> Result, RepositoryError> { - finish_sql(sql::load_stream( - &mut self.connection.executor(), - identity, - None, - )) + self.connection + .read(|executor| finish_sql(sql::load_stream(executor, identity, None))) } async fn get_stream_tail( &self, identity: &StreamIdentity, after_version: u64, ) -> Result, RepositoryError> { - finish_sql(sql::load_stream( - &mut self.connection.executor(), - identity, - Some(after_version), - )) + self.connection + .read(|executor| finish_sql(sql::load_stream(executor, identity, Some(after_version)))) } } impl CausalGetStream for CellSqlRepository { @@ -189,10 +267,8 @@ impl SnapshotStore for CellSqlRepository { &self, identity: &StreamIdentity, ) -> Result, RepositoryError> { - finish_sql(sql::load_snapshot( - &mut self.connection.executor(), - identity, - )) + self.connection + .read(|executor| finish_sql(sql::load_snapshot(executor, identity))) } async fn save_snapshot( &self, @@ -293,20 +369,22 @@ impl OutboxStore for CellSqlOutboxStore { // Match the native no-practical-bound convention within JS's exact // integer range; never round a bound crossing the runtime binding. let limit = (limit as u64).min(9_007_199_254_740_991) as i64; - let rows = finish_sql( - self.connection.executor().query( - Statement::new("SELECT ") - .sql(crate::repository::sqlite_codec::OUTBOX_SELECT) - .sql(" FROM outbox_messages WHERE status = ") - .bind(status.as_str().into()) - .sql(" ORDER BY CAST(created_at AS REAL), message_id LIMIT ") - .bind(limit.into()), - ), - )?; + let rows = self.connection.read(|executor| { + finish_sql( + executor.query( + Statement::new("SELECT ") + .sql(crate::repository::sqlite_codec::OUTBOX_SELECT) + .sql(" FROM outbox_messages WHERE status = ") + .bind(status.as_str().into()) + .sql(" ORDER BY CAST(created_at AS REAL), message_id LIMIT ") + .bind(limit.into()), + ), + ) + })?; rows.into_iter().map(outbox::from_row).collect() } async fn backlog_stats(&self) -> Result { - let rows = finish_sql(self.connection.executor().query(Statement::new("SELECT COUNT(*) AS pending, MIN(CAST(created_at AS REAL)) AS oldest FROM outbox_messages WHERE status = 'pending'")))?; + let rows = self.connection.read(|executor| finish_sql(executor.query(Statement::new("SELECT COUNT(*) AS pending, MIN(CAST(created_at AS REAL)) AS oldest FROM outbox_messages WHERE status = 'pending'"))))?; let row = rows .first() .ok_or_else(|| RepositoryError::Model("outbox count returned no row".into()))?; @@ -350,3 +428,90 @@ impl CellSqlOutboxStore { }) } } + +/// Native-only cell metadata: the instance binding and the sealed row. Kept +/// out of the shared migration inventory so Durable Object schemas (and their +/// checksummed history) are unchanged by the native store. +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +mod native { + use super::*; + use serde_json::Value; + + const CREATE: &str = "CREATE TABLE IF NOT EXISTS __distributed_native_cell (id INTEGER PRIMARY KEY CHECK (id = 1), instance_name TEXT NOT NULL, sealed_row TEXT)"; + + pub(super) async fn bind_instance( + executor: &mut impl SqlExecutor, + instance_name: &str, + ) -> Result<(), RepositoryError> { + executor.execute(Statement::new(CREATE)).await?; + let rows = executor + .query(Statement::new( + "SELECT instance_name FROM __distributed_native_cell WHERE id = 1", + )) + .await?; + match rows.first() { + Some(row) => { + let bound = row.text("instance_name")?; + if bound != instance_name { + return Err(RepositoryError::Model(format!( + "cell SQLite file belongs to `{bound}`, not `{instance_name}`" + ))); + } + } + None => { + executor + .execute( + Statement::new( + "INSERT INTO __distributed_native_cell (id, instance_name) VALUES (1, ", + ) + .bind(instance_name.into()) + .sql(")"), + ) + .await?; + } + } + Ok(()) + } + + pub(super) async fn sealed_row( + executor: &mut impl SqlExecutor, + ) -> Result, RepositoryError> { + let rows = executor + .query(Statement::new( + "SELECT sealed_row FROM __distributed_native_cell WHERE id = 1", + )) + .await?; + match rows + .first() + .map(|row| row.optional_text("sealed_row")) + .transpose()? + .flatten() + { + Some(json) => serde_json::from_str(&json).map(Some).map_err(|error| { + RepositoryError::Model(format!("cell sealed row is invalid JSON: {error}")) + }), + None => Ok(None), + } + } + + pub(super) async fn write_sealed_row( + executor: &mut impl SqlExecutor, + row: &Value, + ) -> Result<(), RepositoryError> { + let json = serde_json::to_string(row) + .map_err(|error| RepositoryError::Model(format!("cell sealed row: {error}")))?; + let written = executor + .execute( + Statement::new("UPDATE __distributed_native_cell SET sealed_row = ") + .bind(json.as_str().into()) + .sql(" WHERE id = 1"), + ) + .await?; + if written != 1 { + return Err(RepositoryError::Model( + "cell SQLite file has no instance binding".into(), + )); + } + Ok(()) + } +} diff --git a/src/microsvc/cell_host/store.rs b/src/microsvc/cell_host/store.rs index 23d263941..13bd07805 100644 --- a/src/microsvc/cell_host/store.rs +++ b/src/microsvc/cell_host/store.rs @@ -1,5 +1,7 @@ //! One cell's private command-side repository, with enforced stream ownership. -//! Workers use runtime-owned SQLite; native tests use the in-process reference host. +//! Workers use runtime-owned SQLite. Native hosts use the in-process reference +//! host, or with `cell-sqlite` one SQLite file per cell sharing the Workers +//! store (`open_sqlite*`). Ownership checks below apply to every backend. use std::future::Future; use std::sync::Arc; @@ -23,6 +25,8 @@ use crate::entity::EventRecord; use crate::microsvc::HasOutboxStore; #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use crate::outbox::OutboxMessage; +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +use crate::repository::{validate_commit_batch, PreparedEventAppend}; use crate::repository::{ CommitBatch, GetStream, RepositoryError, SnapshotStore, SnapshotWrite, StreamIdentity, TransactionalCommit, @@ -30,8 +34,13 @@ use crate::repository::{ use crate::snapshot::SnapshotRecord; #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] use crate::InMemoryRepository; -#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +#[cfg(not(any( + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) +)))] type CellRepository = InMemoryRepository; +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +type CellRepository = super::native_sqlite::NativeCellRepository; #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] type CellRepository = CellSqlRepository; #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] @@ -79,6 +88,17 @@ pub struct DurableCellCommand { pub body: String, } +/// Sealed read-model row reducer run in the same transaction as a command's +/// events (native hosts). Receives the current row and the event appends of +/// the commit; `Ok(Some(row))` replaces the row, `Ok(None)` keeps it, and an +/// error rolls the whole command back. +#[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] +pub type SealedRowReducer = Arc< + dyn Fn(Option<&Value>, &[PreparedEventAppend<'_>]) -> Result, RepositoryError> + + Send + + Sync, +>; + /// Current native restart-test export version. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub const DURABLE_AGGREGATE_CELL_STATE_VERSION: u16 = 1; @@ -117,6 +137,8 @@ pub struct CellStreamStore { inner: CellRepository, #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] sealed_row: Arc>>, + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + sealed_row_reducer: Option, } impl CellStreamStore { @@ -153,11 +175,7 @@ impl CellStreamStore { /// Bind a store to one exact stream identity. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn for_identity(identity: StreamIdentity) -> Self { - Self { - ownership: CellOwnership::Exclusive(identity), - inner: InMemoryRepository::new(), - sealed_row: Arc::new(Mutex::new(None)), - } + Self::native(CellOwnership::Exclusive(identity), memory_repository()) } /// Parent-shard cell: `"{parent_type}:{parent_id}"` (bomberman `game:{id}`). @@ -170,14 +188,118 @@ impl CellStreamStore { parent_id: impl Into, owns: impl Fn(&StreamIdentity) -> bool + Send + Sync + 'static, ) -> Result { - Ok(Self { - ownership: CellOwnership::Parent { + Ok(Self::native( + CellOwnership::Parent { name: StreamIdentity::new(parent_type, parent_id)?, owns: Arc::new(owns), }, - inner: InMemoryRepository::new(), + memory_repository(), + )) + } + + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + fn native(ownership: CellOwnership, inner: CellRepository) -> Self { + Self { + ownership, + inner, sealed_row: Arc::new(Mutex::new(None)), - }) + sealed_row_reducer: None, + } + } + + /// Open a durable exclusive cell backed by its own SQLite file. + /// + /// The file is `location.resolve("{type}:{id}")`; every command commits + /// events, snapshots, ledger receipt, outbox rows and the sealed row (see + /// [`Self::with_sealed_row_reducer`]) in one SQLite transaction. Dropping + /// every handle and reopening the same file restores the identical cell. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn open_sqlite( + location: &super::CellSqlitePath, + identity: StreamIdentity, + ) -> Result { + let sql = location.open(&identity.to_string())?; + Ok(Self::native( + CellOwnership::Exclusive(identity), + super::native_sqlite::NativeCellRepository::Sql(sql), + )) + } + + /// Open a durable parent-shard cell (`"{parent_type}:{parent_id}"`) whose + /// owned sibling streams share one SQLite file. As on Workers, the + /// predicate never grants access to another cell's file. + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn open_sqlite_parent( + location: &super::CellSqlitePath, + parent_type: impl Into, + parent_id: impl Into, + owns: impl Fn(&StreamIdentity) -> bool + Send + Sync + 'static, + ) -> Result { + let name = StreamIdentity::new(parent_type, parent_id)?; + let sql = location.open(&name.to_string())?; + Ok(Self::native( + CellOwnership::Parent { + name, + owns: Arc::new(owns), + }, + super::native_sqlite::NativeCellRepository::Sql(sql), + )) + } + + /// Whether this cell persists to a SQLite file (`open_sqlite*`). + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + pub fn is_sqlite(&self) -> bool { + self.inner.sql().is_some() + } + + /// Maintain the sealed read-model row from each commit's events, inside + /// the command's transaction (SQLite cells) or alongside its in-memory + /// commit (reference host). A reducer error rejects the command. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + pub fn with_sealed_row_reducer( + mut self, + reducer: impl Fn(Option<&Value>, &[PreparedEventAppend<'_>]) -> Result, RepositoryError> + + Send + + Sync + + 'static, + ) -> Self { + let reducer: SealedRowReducer = Arc::new(reducer); + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + if let Some(sql) = self.inner.sql_mut() { + sql.set_sealed_row_reducer(Arc::clone(&reducer)); + } + self.sealed_row_reducer = Some(reducer); + self + } + + /// The in-process reference repository backing whole-state export. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + fn memory(&self) -> Result<&InMemoryRepository, RepositoryError> { + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + return self.inner.memory(); + #[cfg(not(all(feature = "cell-sqlite", not(target_arch = "wasm32"))))] + Ok(&self.inner) + } + + /// Reference-host sealed-row reduction. SQLite cells reduce inside their + /// commit transaction instead, so this returns `None` for them. + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + fn reduce_memory_sealed_row( + &self, + batch: &CommitBatch<'_>, + ) -> Result, RepositoryError> { + let Some(reducer) = &self.sealed_row_reducer else { + return Ok(None); + }; + if self.memory().is_err() { + return Ok(None); + } + let prepared = validate_commit_batch(batch)?; + if prepared.iter().all(|append| append.events.is_empty()) { + return Ok(None); + } + let current = self.sealed_row()?; + reducer(current.as_ref(), &prepared) } /// Named exclusive-cell constructor used by [`super::AggregateCell`]. @@ -225,6 +347,10 @@ impl CellStreamStore { /// Sealed read-model row for GET on this cell instance. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn sealed_row(&self) -> Result, RepositoryError> { + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + if let Some(sql) = self.inner.sql() { + return sql.sealed_row(); + } self.sealed_row .lock() .map(|guard| guard.clone()) @@ -234,6 +360,10 @@ impl CellStreamStore { /// Replace the sealed read-model row (Atomic board / Todo view). #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn replace_sealed_row(&self, row: Value) -> Result<(), RepositoryError> { + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + if let Some(sql) = self.inner.sql() { + return sql.replace_sealed_row(&row); + } let mut guard = self .sealed_row .lock() @@ -246,7 +376,7 @@ impl CellStreamStore { #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_events(&self) -> Result, RepositoryError> { Ok(self - .inner + .memory()? .clone_events()? .into_iter() .map(|(stream, events)| DurableCellEvents { stream, events }) @@ -256,7 +386,7 @@ impl CellStreamStore { /// Outbox rows committed with this cell's events (same private SQLite). #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_outbox(&self) -> Result, RepositoryError> { - self.inner.clone_outbox() + self.memory()?.clone_outbox() } /// Restore outbox rows from Durable Object SQLite. @@ -265,7 +395,7 @@ impl CellStreamStore { &self, messages: Vec, ) -> Result<(), RepositoryError> { - self.inner.replace_outbox(messages) + self.memory()?.replace_outbox(messages) } /// Replace the working event log from Durable Object SQLite. @@ -274,7 +404,7 @@ impl CellStreamStore { &self, events: Vec, ) -> Result<(), RepositoryError> { - self.inner.replace_events( + self.memory()?.replace_events( events .into_iter() .map(|row| (row.stream, row.events)) @@ -286,7 +416,7 @@ impl CellStreamStore { #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_snapshots(&self) -> Result, RepositoryError> { Ok(self - .inner + .memory()? .clone_snapshots()? .into_iter() .map(|(stream, record)| DurableCellSnapshot { @@ -308,7 +438,7 @@ impl CellStreamStore { &self, snapshots: Vec, ) -> Result<(), RepositoryError> { - self.inner.replace_snapshots( + self.memory()?.replace_snapshots( snapshots .into_iter() .map(|row| { @@ -334,7 +464,7 @@ impl CellStreamStore { /// Fenced command rows committed with this cell's domain effects. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_commands(&self) -> Result, RepositoryError> { - self.inner + self.memory()? .clone_command_ledger()? .into_iter() .map(|record| { @@ -365,7 +495,7 @@ impl CellStreamStore { } records.push(record); } - self.inner.replace_command_ledger(records) + self.memory()?.replace_command_ledger(records) } /// Export every durable concern as one versioned persistence envelope. @@ -565,7 +695,14 @@ impl TransactionalCommit for CellStreamStore { ) -> impl Future> + Send + 'a { async move { self.ensure_batch(&batch)?; - TransactionalCommit::commit_batch(&self.inner, batch).await + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + let sealed = self.reduce_memory_sealed_row(&batch)?; + TransactionalCommit::commit_batch(&self.inner, batch).await?; + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + if let Some(row) = sealed { + self.replace_sealed_row(row)?; + } + Ok(()) } } } @@ -578,14 +715,29 @@ impl CausalTransactionalCommit for CellStreamStore { async move { self.ensure_batch(&batch.domain) .map_err(CommandLedgerError::Storage)?; - CausalTransactionalCommit::commit_causal_batch(&self.inner, batch).await + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + let sealed = self + .reduce_memory_sealed_row(&batch.domain) + .map_err(CommandLedgerError::Storage)?; + CausalTransactionalCommit::commit_causal_batch(&self.inner, batch).await?; + #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + if let Some(row) = sealed { + self.replace_sealed_row(row) + .map_err(CommandLedgerError::Storage)?; + } + Ok(()) } } } impl HasOutboxStore for CellStreamStore { - #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] + #[cfg(not(any( + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) + )))] type OutboxStore = crate::InMemoryOutboxStore; + #[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] + type OutboxStore = super::native_sqlite::CellOutboxStore; #[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] type OutboxStore = super::sql_store::CellSqlOutboxStore; @@ -608,3 +760,16 @@ impl crate::microsvc::dependencies::CausalHostProjections for CellStreamStore { ) } } + +#[cfg(not(any( + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) +)))] +fn memory_repository() -> CellRepository { + InMemoryRepository::new() +} + +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +fn memory_repository() -> CellRepository { + super::native_sqlite::NativeCellRepository::Memory(InMemoryRepository::new()) +} diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index f93c682f4..99d893c9e 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -626,3 +626,43 @@ fn cargo_features_keep_sqlite_and_do_not_add_celld() { "PCH-DEC-005: do not add a celld Cargo feature beside sqlite/postgres" ); } + +#[tokio::test] +async fn reference_host_applies_the_sealed_row_reducer_on_commit() { + let store = CellStreamStore::new("CellItem", "item-s") + .unwrap() + .with_sealed_row_reducer(|current, appends| { + let seen = current.and_then(|row| row["events"].as_u64()).unwrap_or(0); + let added = appends + .iter() + .map(|append| append.events.len() as u64) + .sum::(); + Ok(Some(json!({ "events": seen + added }))) + }); + let cell = AggregateCell::::from_store(store) + .unwrap() + .mount(Create) + .mount(Complete); + cell.dispatch( + "cell_item.create", + json!({ "id": "item-s", "title": "seal" }), + owner_session(), + ) + .await + .unwrap(); + cell.dispatch( + "cell_item.complete", + json!({ "id": "item-s" }), + owner_session(), + ) + .await + .unwrap(); + assert_eq!(cell.sealed_row().unwrap(), Some(json!({ "events": 2 }))); + assert!(AggregateCell::::from_store( + CellStreamStore::for_parent_shard("game", "g1", |_| true).unwrap() + ) + .is_err()); +} + +#[cfg(all(feature = "cell-sqlite", not(target_arch = "wasm32")))] +mod native_sqlite; diff --git a/src/microsvc/cell_host/tests/native_sqlite.rs b/src/microsvc/cell_host/tests/native_sqlite.rs new file mode 100644 index 000000000..8affe2094 --- /dev/null +++ b/src/microsvc/cell_host/tests/native_sqlite.rs @@ -0,0 +1,431 @@ +//! Native durable cells (`cell-sqlite`): restart, replay, outbox and +//! ownership conformance against real SQLite files. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::{json, Value}; + +use super::super::{ + AggregateCell, CellCommandIdentity, CellDispatchError, CellSqlitePath, CellStreamStore, +}; +use super::{owner_session, CellItem, Complete, Create, Publish}; +use crate::bus::{Message, MessagePublisher, TransportError}; +use crate::entity::{Entity, EventRecord}; +use crate::microsvc::HasOutboxStore; +use crate::outbox::{OutboxMessage, OutboxMessageStatus}; +use crate::outbox_worker::{ClaimOutboxMessages, OutboxClaimRef, OutboxStore}; +use crate::repository::{ + CommitBatch, GetStream, PreparedEventAppend, RepositoryError, SnapshotStore, StreamIdentity, + StreamWrite, TransactionalCommit, +}; +use crate::snapshot::SnapshotRecord; + +struct TempRoot(PathBuf); + +impl TempRoot { + fn new() -> Self { + Self(std::env::temp_dir().join(format!("distributed-cell-sqlite-{}", uuid::Uuid::now_v7()))) + } + + fn location(&self) -> CellSqlitePath { + CellSqlitePath::root(&self.0) + } +} + +impl Drop for TempRoot { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[derive(Debug, PartialEq)] +struct CellDump { + events: Vec, + snapshot: Option, + outbox: Vec, + sealed: Option, +} + +/// Read every durable concern of one exclusive cell through a fresh handle, +/// which is dropped again before returning. +async fn dump(location: &CellSqlitePath, shard: &str) -> CellDump { + let identity = StreamIdentity::new("CellItem", shard).unwrap(); + let store = CellStreamStore::open_sqlite(location, identity.clone()).unwrap(); + assert!(store.is_sqlite()); + let events = GetStream::get_stream(&store, &identity) + .await + .unwrap() + .map(|entity| entity.events().to_vec()) + .unwrap_or_default(); + let snapshot = SnapshotStore::get_snapshot(&store, &identity) + .await + .unwrap(); + let outbox_store = store.outbox_store(); + let mut outbox = Vec::new(); + for status in [ + OutboxMessageStatus::Pending, + OutboxMessageStatus::InFlight, + OutboxMessageStatus::Failed, + ] { + outbox.extend(outbox_store.messages_by_status(status, 100).await.unwrap()); + } + CellDump { + events, + snapshot, + outbox, + sealed: store.sealed_row().unwrap(), + } +} + +fn count_events( + current: Option<&Value>, + appends: &[PreparedEventAppend<'_>], +) -> Result, RepositoryError> { + let mut count = current.and_then(|row| row["events"].as_u64()).unwrap_or(0); + let mut last = current + .map(|row| row["last"].clone()) + .unwrap_or(Value::Null); + for append in appends { + for event in append.events { + count += 1; + last = Value::String(event.event_name.clone()); + } + } + Ok(Some(json!({ "events": count, "last": last }))) +} + +fn identity(command_id: &str) -> CellCommandIdentity { + CellCommandIdentity::new("cell-test-service", "principal-alice", command_id).unwrap() +} + +fn sqlite_cell(location: &CellSqlitePath, shard: &str) -> AggregateCell { + let store = + CellStreamStore::open_sqlite(location, StreamIdentity::new("CellItem", shard).unwrap()) + .unwrap() + .with_sealed_row_reducer(count_events); + AggregateCell::::from_store_with_snapshots(store, 1) + .unwrap() + .mount(Create) + .mount(Complete) + .mount(Publish) +} + +#[tokio::test] +async fn sqlite_cell_reopens_identically_and_replays_recorded_outcomes() { + let root = TempRoot::new(); + let location = root.location(); + let create_id = identity("0190a000-0000-7000-8000-000000000501"); + let complete_id = identity("0190a000-0000-7000-8000-000000000502"); + let create_input = json!({ "id": "item-1", "title": "ship" }); + + let cell = sqlite_cell(&location, "item-1"); + let created = cell + .dispatch_idempotent( + "cell_item.create", + &create_id, + create_input.clone(), + owner_session(), + ) + .await + .unwrap(); + let completed = cell + .dispatch_idempotent( + "cell_item.complete", + &complete_id, + json!({ "id": "item-1" }), + owner_session(), + ) + .await + .unwrap(); + assert!(!created.replayed() && !completed.replayed()); + // Whole-state export is a reference-host API; SQLite cells persist rows. + assert!(cell.durable_state().is_err()); + + let before = dump(&location, "item-1").await; + assert_eq!(before.events.len(), 2); + assert_eq!( + before.snapshot.as_ref().map(|record| record.version), + Some(2) + ); + assert_eq!( + before.sealed, + Some(json!({ "events": 2, "last": "cell_item.completed" })) + ); + assert!(before.outbox.is_empty(), "create/complete publish nothing"); + + // Drop every handle: nothing survives except the cell's SQLite file. + drop(cell); + assert!(location.resolve("CellItem:item-1").is_file()); + + let after = dump(&location, "item-1").await; + assert_eq!(after, before, "reopen must restore identical cell state"); + + let reopened = AggregateCell::::open_sqlite_with_snapshots(&location, "item-1", 1) + .unwrap() + .mount(Create) + .mount(Complete); + let loaded = reopened.load().await.unwrap().expect("durable aggregate"); + assert_eq!(loaded.title, "ship"); + assert!(loaded.done); + assert_eq!(loaded.entity.snapshot_version(), 2); + assert_eq!( + reopened.sealed_row().unwrap(), + Some(json!({ "events": 2, "last": "cell_item.completed" })) + ); + + // Create would be rejected ("already exists") if it ran again; the durable + // ledger must return the recorded outcome without invoking the handler. + let replay = reopened + .dispatch_idempotent( + "cell_item.create", + &create_id, + create_input, + owner_session(), + ) + .await + .expect("durable replay after reopen"); + assert!(replay.replayed()); + assert_eq!(replay.payload(), created.payload()); + assert_eq!(replay.causation_id(), created.causation_id()); + assert_eq!(replay.projection_events(), created.projection_events()); + + let reuse = reopened + .dispatch_idempotent( + "cell_item.create", + &create_id, + json!({ "id": "item-1", "title": "different" }), + owner_session(), + ) + .await + .unwrap_err(); + assert!(matches!(reuse, CellDispatchError::CommandIdReuse)); + + drop(reopened); + assert_eq!(dump(&location, "item-1").await, before, "replay re-applied"); +} + +#[tokio::test] +async fn sealed_row_reducer_failure_rolls_back_the_whole_command() { + let root = TempRoot::new(); + let location = root.location(); + let store = CellStreamStore::open_sqlite( + &location, + StreamIdentity::new("CellItem", "item-r").unwrap(), + ) + .unwrap() + .with_sealed_row_reducer(|current, appends| { + if appends + .iter() + .flat_map(|append| append.events) + .any(|event| event.event_name == "cell_item.completed") + { + return Err(RepositoryError::Model("sealed row rejected".into())); + } + count_events(current, appends) + }); + let cell = AggregateCell::::from_store_with_snapshots(store, 1) + .unwrap() + .mount(Create) + .mount(Complete); + cell.dispatch_idempotent( + "cell_item.create", + &identity("0190a000-0000-7000-8000-000000000511"), + json!({ "id": "item-r", "title": "keep" }), + owner_session(), + ) + .await + .unwrap(); + let before = dump(&location, "item-r").await; + + assert!(cell + .dispatch_idempotent( + "cell_item.complete", + &identity("0190a000-0000-7000-8000-000000000512"), + json!({ "id": "item-r" }), + owner_session(), + ) + .await + .is_err()); + drop(cell); + + let after = dump(&location, "item-r").await; + assert_eq!(after, before, "events, snapshot and sealed row roll back"); + assert_eq!(after.events.len(), 1); + assert_eq!(after.snapshot.map(|record| record.version), Some(1)); +} + +#[derive(Clone, Default)] +struct RecordingPublisher { + fail: Arc, + published: Arc>>>, +} + +impl MessagePublisher for RecordingPublisher { + async fn publish(&self, message: Message) -> Result<(), TransportError> { + if self.fail.load(Ordering::SeqCst) { + return Err(TransportError::retryable("transport down")); + } + self.published.lock().unwrap().push(message.id); + Ok(()) + } +} + +#[tokio::test] +async fn outbox_rows_survive_reopen_and_drain_at_least_once() { + let root = TempRoot::new(); + let location = root.location(); + let cell = sqlite_cell(&location, "pub-1"); + cell.dispatch_idempotent( + "cell_item.publish", + &identity("0190a000-0000-7000-8000-000000000521"), + json!({ "id": "pub-1", "title": "news" }), + owner_session(), + ) + .await + .unwrap(); + + // A drain that fails to publish releases the row for a later pass. + let publisher = RecordingPublisher::default(); + publisher.fail.store(true, Ordering::SeqCst); + let outcome = cell + .drain_outbox_with(publisher.clone(), Duration::from_secs(30), 10, 10) + .await + .unwrap(); + assert_eq!((outcome.claimed, outcome.released), (1, 1)); + drop(cell); + + let pending = dump(&location, "pub-1").await.outbox; + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].status, OutboxMessageStatus::Pending); + let message_id = pending[0].id.clone(); + + // Simulate a crash mid-drain: claimed with a short lease, never settled. + let store = + CellStreamStore::open_sqlite(&location, StreamIdentity::new("CellItem", "pub-1").unwrap()) + .unwrap(); + let claimed = store + .outbox_store() + .claim(ClaimOutboxMessages::new( + "crashed-worker", + 10, + Duration::from_millis(200), + )) + .await + .unwrap(); + assert_eq!(claimed.len(), 1); + let stale = OutboxClaimRef::from_message(&claimed[0]).unwrap(); + drop(store); + + // Restart. The row survives as in-flight under the dead worker's lease. + let reopened = sqlite_cell(&location, "pub-1"); + let outbox = dump(&location, "pub-1").await.outbox; + assert_eq!(outbox.len(), 1); + assert_eq!(outbox[0].status, OutboxMessageStatus::InFlight); + publisher.fail.store(false, Ordering::SeqCst); + let fenced = reopened + .drain_outbox_with(publisher.clone(), Duration::from_secs(30), 10, 10) + .await + .unwrap(); + assert_eq!(fenced.claimed, 0, "a live lease is not stolen"); + + tokio::time::sleep(Duration::from_millis(250)).await; + let store = + CellStreamStore::open_sqlite(&location, StreamIdentity::new("CellItem", "pub-1").unwrap()) + .unwrap(); + assert!( + store.outbox_store().complete(&stale).await.is_err(), + "an expired lease cannot delete the row" + ); + drop(store); + + let drained = reopened + .drain_outbox_with(publisher.clone(), Duration::from_secs(30), 10, 10) + .await + .unwrap(); + assert_eq!((drained.claimed, drained.published), (1, 1)); + assert_eq!( + publisher.published.lock().unwrap().as_slice(), + &[Some(message_id)] + ); + drop(reopened); + + let after = dump(&location, "pub-1").await; + assert!(after.outbox.is_empty(), "published rows are deleted"); + assert_eq!(after.events.len(), 1); +} + +#[tokio::test] +async fn sqlite_cells_enforce_ownership_and_file_binding() { + let root = TempRoot::new(); + let location = root.location(); + + let exclusive = CellStreamStore::open_sqlite( + &location, + StreamIdentity::new("CellItem", "item-1").unwrap(), + ) + .unwrap(); + let mut foreign = Entity::with_id("item-2"); + foreign.digest_empty("created").unwrap(); + let error = TransactionalCommit::commit_batch( + &exclusive, + CommitBatch::new(vec![StreamWrite::new( + StreamIdentity::new("CellItem", "item-2").unwrap(), + &mut foreign, + )]), + ) + .await + .unwrap_err(); + assert!( + matches!(error, RepositoryError::Model(message) if message.contains("cannot access stream")) + ); + + let owns = |game: &'static str| { + move |identity: &StreamIdentity| identity.aggregate_id().starts_with(game) + }; + let game_1 = CellStreamStore::open_sqlite_parent(&location, "game", "g1", owns("g1:")).unwrap(); + let mut player = Entity::with_id("g1:player:1"); + player.digest_empty("joined").unwrap(); + let mut bomb = Entity::with_id("g1:bomb:1"); + bomb.digest_empty("placed").unwrap(); + let player_id = StreamIdentity::new("Player", "g1:player:1").unwrap(); + let bomb_id = StreamIdentity::new("Bomb", "g1:bomb:1").unwrap(); + TransactionalCommit::commit_batch( + &game_1, + CommitBatch::new(vec![ + StreamWrite::new(player_id.clone(), &mut player), + StreamWrite::new(bomb_id.clone(), &mut bomb), + ]), + ) + .await + .unwrap(); + drop(game_1); + + let game_1 = CellStreamStore::open_sqlite_parent(&location, "game", "g1", owns("g1:")).unwrap(); + assert!(GetStream::get_stream(&game_1, &player_id) + .await + .unwrap() + .is_some()); + assert!(GetStream::get_stream(&game_1, &bomb_id) + .await + .unwrap() + .is_some()); + let game_2 = CellStreamStore::open_sqlite_parent(&location, "game", "g2", owns("g2:")).unwrap(); + assert!(GetStream::get_stream(&game_2, &player_id).await.is_err()); + assert_ne!( + location.resolve("game:g1"), + location.resolve("game:g2"), + "one SQLite file per cell" + ); + + // An explicit file is bound to the first cell that opens it. + let file = CellSqlitePath::file(root.0.join("explicit.db")); + CellStreamStore::open_sqlite(&file, StreamIdentity::new("CellItem", "a").unwrap()).unwrap(); + let error = CellStreamStore::open_sqlite(&file, StreamIdentity::new("CellItem", "b").unwrap()) + .err() + .expect("file bound to CellItem:a"); + assert!(error.to_string().contains("belongs to"), "{error}"); + CellStreamStore::open_sqlite(&file, StreamIdentity::new("CellItem", "a").unwrap()).unwrap(); +} diff --git a/src/repository/migrations.rs b/src/repository/migrations.rs index 5d0a10b1b..d08d3f261 100644 --- a/src/repository/migrations.rs +++ b/src/repository/migrations.rs @@ -3,6 +3,8 @@ #[derive(Clone, Copy)] pub(crate) struct EmbeddedMigration { pub(crate) version: i64, + // Read by the SQLx adapters only; cell executors do not report it. + #[cfg_attr(not(any(feature = "sqlite", feature = "postgres")), allow(dead_code))] pub(crate) description: &'static str, pub(crate) sql: &'static str, } @@ -12,7 +14,10 @@ include!(concat!(env!("OUT_DIR"), "/migration_inventory.rs")); /// Cells host commands, not read-model projectors. These are the event, /// snapshot, delivery and command-ledger migrations from the native inventory. /// Projection-owned tables are initialized by their separate query host. -#[cfg(all(feature = "workers-rs", target_arch = "wasm32"))] +#[cfg(any( + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) +))] pub(crate) fn cell_migrations() -> impl Iterator { SQLITE_MIGRATIONS .iter() diff --git a/src/repository/mod.rs b/src/repository/mod.rs index 29c100c17..1957b2ba5 100644 --- a/src/repository/mod.rs +++ b/src/repository/mod.rs @@ -4,7 +4,8 @@ mod inbox; #[cfg(any( feature = "sqlite", feature = "postgres", - all(feature = "workers-rs", target_arch = "wasm32") + all(feature = "workers-rs", target_arch = "wasm32"), + all(feature = "cell-sqlite", not(target_arch = "wasm32")) ))] pub(crate) mod migrations; pub(crate) mod sql; diff --git a/src/repository/sql/outbox.rs b/src/repository/sql/outbox.rs index 438a04d84..1e70581bb 100644 --- a/src/repository/sql/outbox.rs +++ b/src/repository/sql/outbox.rs @@ -10,6 +10,8 @@ use std::time::SystemTime; pub(crate) struct OutboxInsert<'a> { pub statement: Statement<'a>, + // Read by the SQLx adapters only; cell executors do not report it. + #[cfg_attr(not(any(feature = "sqlite", feature = "postgres")), allow(dead_code))] pub first_id: &'a str, } diff --git a/tests/celld/README.md b/tests/celld/README.md index 649599cb4..b9aceb3af 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -62,6 +62,34 @@ The whole-state export/restore and `persist_and_drain_outbox` APIs are not available on the Worker host. Native in-process conformance fixtures are not a production persistence adapter. +### Native durable cells (`cell-sqlite`) + +Native hosts get the same store with the `cell-sqlite` Cargo feature: one +SQLite file per cell, executed through a synchronous rusqlite connection that +exposes the same `read`/`transaction` surface as `storage.transactionSync`. +Schema bootstrap, the per-command transaction (events, snapshots, ledger +receipt, outbox rows) and lease-fenced outbox settlement are the shared +`sql_store.rs` code, not a copy. Native cells additionally keep the sealed +read-model row in the same file and, with +`CellStreamStore::with_sealed_row_reducer`, update it inside the command +transaction. + +```rust,ignore +let cells = CellSqlitePath::root("var/cells"); // var/cells/Todo%3At1.sqlite3 +let cell = AggregateCell::::open_sqlite_with_snapshots(&cells, "t1", 100)? + .mount(create()); +let result = cell.dispatch_idempotent(command, &identity, input, session).await?; + +// Alarm equivalent: run at startup, after dispatch and periodically, or spawn +// OutboxDrainRunner::new(cell.outbox_dispatcher(..)) on a tokio runtime. +let drained = cell.drain_outbox_with(publisher, lease, max_attempts, 100).await?; +``` + +Dropping every handle and reopening the file restores the identical cell, and +an already-applied idempotent command replays its recorded outcome. A file is +bound to the first cell instance that opens it. Whole-state export/restore +remains a reference-host (in-memory) API and is rejected for SQLite cells. + Existing `cell_state` databases are rejected with an explicit migration-required error. They are not silently reset or opened through a legacy adapter. Back up retained development data and migrate it explicitly before changing an existing From fb62353c77963448da94dc36feb2d41f94cbdcd2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:52:09 -0500 Subject: [PATCH 122/484] feat(outbox): honour deliver_at for durable scheduled messages OutboxMessage gains `deliver_at: Option` (serde default, None = immediately deliverable) with deliver_at/deliver_after builders. SQL stores persist it in the existing `next_available_at` column, which every claim query already filtered on, so no migration is needed. The in-memory claim, explicit-id claims and the in-transaction pre-claim of the publish-hook fallback (aggregate commits and causal routes) all leave a scheduled row pending until it is due. A released row stays immediately retryable. Tests: scheduled_outbox (in-memory, sqlite, restart survival on a sqlite file DB, postgres when DATABASE_URL is set) and a unit test for the immediate-publish fallback. Refs [[tasks/gr-p6-coordination-primitives]] --- src/microsvc/service/routes.rs | 10 +- src/outbox/commit.rs | 64 ++++++++++- src/outbox/message.rs | 40 ++++++- src/outbox/table.rs | 6 +- src/postgres_repo/mod.rs | 6 +- src/repository/sql/outbox.rs | 14 ++- src/repository/sqlite_codec.rs | 2 +- tests/scheduled_outbox/main.rs | 196 +++++++++++++++++++++++++++++++++ 8 files changed, 327 insertions(+), 11 deletions(-) create mode 100644 tests/scheduled_outbox/main.rs diff --git a/src/microsvc/service/routes.rs b/src/microsvc/service/routes.rs index 33fb50819..a1171ee10 100644 --- a/src/microsvc/service/routes.rs +++ b/src/microsvc/service/routes.rs @@ -2172,7 +2172,7 @@ where for message in &mut batch.outbox_messages { message.overwrite_causation_id(attempt.causation_id().as_str()); outbox_ids.push(message.id().to_string()); - if let Some(now) = claim_now { + if let Some(now) = claim_now.filter(|now| message.is_due_at(*now)) { if let Err(error) = message.claim_at(&config.worker_id, config.lease, now) { claim_error = Some(error.to_string()); break; @@ -2190,7 +2190,13 @@ where .await; } if config.schedule.is_none() { - fallback_rows = batch.outbox_messages.clone(); + // Scheduled rows were left pending (unclaimed) above. + fallback_rows = batch + .outbox_messages + .iter() + .filter(|message| message.is_in_flight()) + .cloned() + .collect(); } } diff --git a/src/outbox/commit.rs b/src/outbox/commit.rs index 26e47fd85..5b7490a99 100644 --- a/src/outbox/commit.rs +++ b/src/outbox/commit.rs @@ -254,10 +254,14 @@ where if let Some(config) = publisher { if config.schedule.is_none() { let now = crate::time::now(); + // Scheduled (not yet due) rows stay pending for the worker + // that honours `deliver_at`; only due rows are pre-claimed. for message in &mut self.outbox_messages { - message.claim_at(&config.worker_id, config.lease, now)?; + if message.is_due_at(now) { + message.claim_at(&config.worker_id, config.lease, now)?; + fallback_rows.push(message.clone()); + } } - fallback_rows = self.outbox_messages.clone(); } } @@ -486,6 +490,62 @@ mod tests { .expect("immediate publish should finish after the gate opens"); } + struct RecordingHook { + published: Mutex>, + } + + impl OutboxPublishHook for RecordingHook { + fn publish_claimed<'a>( + &'a self, + claimed: Vec, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + self.published + .lock() + .unwrap() + .extend(claimed.iter().map(|m| m.id().to_string())); + Ok(()) + }) + } + } + + #[tokio::test] + async fn immediate_publish_leaves_scheduled_rows_pending() { + let hook = Arc::new(RecordingHook { + published: Mutex::new(Vec::new()), + }); + let mut repo = InMemoryRepository::new().aggregate::(); + repo.set_outbox_publisher(OutboxPublisherConfig::new( + Arc::clone(&hook) as Arc, + "immediate:test", + Duration::from_secs(5), + )); + let mut aggregate = Dummy::default(); + aggregate.touch().unwrap(); + let now = crate::time::now(); + let due = OutboxMessage::create("due", "T", vec![]).unwrap(); + let timer = OutboxMessage::create("timer", "T", vec![]) + .unwrap() + .deliver_after(now, Duration::from_secs(3600)); + repo.outbox(due) + .outbox(timer) + .commit(&mut aggregate) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(1), async { + while hook.published.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(*hook.published.lock().unwrap(), vec!["due".to_string()]); + let pending = repo.repo().outbox_store().pending(10).await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].id(), "timer"); + assert!(pending[0].deliver_at.is_some()); + } + #[tokio::test] async fn outbox_helper_commits_both_entities() { let repo = InMemoryRepository::new().aggregate::(); diff --git a/src/outbox/message.rs b/src/outbox/message.rs index 2b5cb5e0b..069e74e84 100644 --- a/src/outbox/message.rs +++ b/src/outbox/message.rs @@ -125,6 +125,13 @@ pub struct OutboxMessage { pub source_aggregate_type: Option, pub source_aggregate_id: Option, pub source_sequence: Option, + /// Earliest time a worker may claim this message (a durable timer / + /// scheduled command). `None` means immediately deliverable. SQL stores + /// persist it in the existing `next_available_at` column, so a scheduled + /// message survives restart and is skipped by every claim query until it + /// is due. See [`OutboxMessage::deliver_at()`]. + #[serde(default)] + pub deliver_at: Option, } impl Default for OutboxMessage { @@ -146,6 +153,7 @@ impl Default for OutboxMessage { source_aggregate_type: None, source_aggregate_id: None, source_sequence: None, + deliver_at: None, } } } @@ -374,8 +382,37 @@ impl OutboxMessage { self.is_in_flight() && self.leased_until.map(|until| until <= now).unwrap_or(true) } + /// Whether the message is claimable at `now`: pending and due (see + /// [`deliver_at`](Self::deliver_at())), or in flight with an expired lease. pub fn is_claimable_at(&self, now: SystemTime) -> bool { - self.is_pending() || self.has_expired_lease_at(now) + (self.is_pending() && self.is_due_at(now)) || self.has_expired_lease_at(now) + } + + /// Whether the scheduled delivery time (if any) has been reached. + pub fn is_due_at(&self, now: SystemTime) -> bool { + self.deliver_at.is_none_or(|at| at <= now) + } + + /// Schedule this message: no worker claims it before `at`. This is the + /// durable-timer primitive — commit the message with the aggregate change + /// that arms the timer, and it survives restarts like any outbox row. + /// Times in the past (or `None` via [`deliver_now`](Self::deliver_now)) + /// are immediately deliverable. + pub fn deliver_at(mut self, at: SystemTime) -> Self { + self.deliver_at = Some(at); + self + } + + /// Schedule this message `delay` after `now` (see [`deliver_at`](Self::deliver_at())). + pub fn deliver_after(self, now: SystemTime, delay: Duration) -> Self { + let at = now.checked_add(delay).unwrap_or(now); + self.deliver_at(at) + } + + /// Clear any schedule so the message is immediately deliverable. + pub fn deliver_now(mut self) -> Self { + self.deliver_at = None; + self } pub fn is_claimed_by(&self, worker_id: &str) -> bool { @@ -441,6 +478,7 @@ impl OutboxMessage { self.source_aggregate_type = None; self.source_aggregate_id = None; self.source_sequence = None; + self.deliver_at = None; Ok(()) } diff --git a/src/outbox/table.rs b/src/outbox/table.rs index 2383df679..c234a865e 100644 --- a/src/outbox/table.rs +++ b/src/outbox/table.rs @@ -104,7 +104,11 @@ pub fn outbox_message_row_values(message: &OutboxMessage) -> Result system_time_epoch_secs(at)?.max(created_at), + None => created_at, + }; + row.insert("next_available_at", RowValue::U64(next_available_at)); row.insert("claimed_by", optional_string(&message.worker_id)); row.insert( "claimed_until", diff --git a/src/postgres_repo/mod.rs b/src/postgres_repo/mod.rs index f58cab009..7fcf236e7 100644 --- a/src/postgres_repo/mod.rs +++ b/src/postgres_repo/mod.rs @@ -101,7 +101,8 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { source_aggregate_id, \ source_sequence, \ correlation_id, \ - causation_id"; + causation_id, \ + EXTRACT(EPOCH FROM next_available_at)::double precision AS next_available_at"; const ORDER_BY_CREATED_AT: &'static str = "created_at"; const OUTBOX_OLDEST_CREATED_AT_SELECT: &'static str = "EXTRACT(EPOCH FROM MIN(created_at))::double precision AS oldest_created_at"; @@ -287,7 +288,8 @@ impl crate::sqlx_repo::repo::SqlxRepoBackend for Postgres { message.source_aggregate_id, message.source_sequence, message.correlation_id, - message.causation_id + message.causation_id, + EXTRACT(EPOCH FROM message.next_available_at)::double precision AS next_available_at "#, ) .bind(OutboxMessageStatus::Pending.as_str()) diff --git a/src/repository/sql/outbox.rs b/src/repository/sql/outbox.rs index 438a04d84..f8f68c68a 100644 --- a/src/repository/sql/outbox.rs +++ b/src/repository/sql/outbox.rs @@ -51,7 +51,11 @@ pub(crate) fn inserts( )), Some(SqlBind::from(message.status.as_str())), Some(SqlBind::Timestamp(message.created_at)), - Some(SqlBind::Timestamp(message.created_at)), + // `next_available_at` doubles as the durable timer: a scheduled + // message is invisible to every claim query until it is due. + Some(SqlBind::Timestamp( + message.deliver_at.unwrap_or(message.created_at), + )), message.worker_id.as_deref().map(SqlBind::from), message.leased_until.map(SqlBind::Timestamp), Some(SqlBind::Integer(i64::from(message.attempts))), @@ -93,6 +97,11 @@ pub(crate) fn from_row(row: impl SqlRow) -> Result created_at); Ok(OutboxMessage { id: row.text("message_id")?, event_type: row.text("event_type")?, @@ -102,7 +111,7 @@ pub(crate) fn from_row(row: impl SqlRow) -> Result Result Result { let duration = timestamp.duration_since(UNIX_EPOCH).map_err(|error| { diff --git a/tests/scheduled_outbox/main.rs b/tests/scheduled_outbox/main.rs new file mode 100644 index 000000000..111045604 --- /dev/null +++ b/tests/scheduled_outbox/main.rs @@ -0,0 +1,196 @@ +//! Durable timers: `OutboxMessage::deliver_at` is honoured by every outbox +//! store's claim query and survives restart (SQLite file database). +//! Postgres skips without `DATABASE_URL`. + +#[cfg(feature = "sqlite")] +#[path = "../support/sqlite.rs"] +mod sqlite_support; + +use std::time::{Duration, SystemTime}; + +use distributed::{ + ClaimOutboxMessages, CommitBatch, InMemoryRepository, OutboxMessage, OutboxStore, + TransactionalCommit, +}; + +const LEASE: Duration = Duration::from_secs(60); + +fn messages(now: SystemTime) -> Vec { + vec![ + OutboxMessage::create_to("immediate", "Ping", "q", vec![1]).unwrap(), + OutboxMessage::create_to("past", "Ping", "q", vec![2]) + .unwrap() + .deliver_at(now - Duration::from_secs(5)), + OutboxMessage::create_to("future", "Ping", "q", vec![3]) + .unwrap() + .deliver_after(now, Duration::from_secs(3600)), + ] +} + +async fn commit_messages(repo: &R, messages: Vec) { + let mut batch = CommitBatch::empty(); + batch.outbox_messages = messages; + repo.commit_batch(batch).await.unwrap(); +} + +/// Due rows are claimable (by poll and by explicit id); the future row is +/// listed as pending with its schedule but never claimed. +async fn scenario_schedule_honoured(store: &S) { + let pending = store.pending(10).await.unwrap(); + assert_eq!(pending.len(), 3); + let future = pending.iter().find(|m| m.id() == "future").unwrap(); + assert!(future.deliver_at.is_some()); + assert!(pending + .iter() + .find(|m| m.id() == "immediate") + .unwrap() + .deliver_at + .is_none()); + + let by_id = store + .claim(ClaimOutboxMessages::for_ids( + "w", + vec!["future".into()], + LEASE, + )) + .await + .unwrap(); + assert!( + by_id.is_empty(), + "explicit-id claim must not bypass the schedule" + ); + + let mut claimed: Vec = store + .claim(ClaimOutboxMessages::new("w", 10, LEASE).to_destination("q")) + .await + .unwrap() + .iter() + .map(|m| m.id().to_string()) + .collect(); + claimed.sort(); + assert_eq!(claimed, vec!["immediate".to_string(), "past".to_string()]); +} + +#[tokio::test] +async fn in_memory_store_honours_deliver_at() { + let repo = InMemoryRepository::new(); + commit_messages(&repo, messages(SystemTime::now())).await; + scenario_schedule_honoured(&repo.outbox_store()).await; +} + +#[test] +fn deliver_at_round_trips_through_serde_and_defaults_to_none() { + let message = OutboxMessage::create("m", "T", vec![]) + .unwrap() + .deliver_after(SystemTime::now(), Duration::from_secs(1)); + let json = serde_json::to_value(&message).unwrap(); + let back: OutboxMessage = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(back.deliver_at, message.deliver_at); + let mut legacy = json; + legacy.as_object_mut().unwrap().remove("deliver_at"); + let old: OutboxMessage = serde_json::from_value(legacy).unwrap(); + assert_eq!( + old.deliver_at, None, + "rows without the field stay immediate" + ); +} + +#[cfg(feature = "sqlite")] +mod sqlite_backend { + use super::*; + use crate::sqlite_support::TempDb; + use distributed::{OutboxClaimRef, SqliteRepository}; + + #[tokio::test] + async fn sqlite_store_honours_deliver_at() { + let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + commit_messages(&repo, messages(SystemTime::now())).await; + scenario_schedule_honoured(&repo.outbox_store()).await; + } + + #[tokio::test] + async fn scheduled_message_survives_restart_and_fires_when_due() { + let db = TempDb::new("scheduled_outbox_restart"); + let delay = Duration::from_millis(400); + let due_at; + { + let repo = SqliteRepository::new(db.pool().await); + repo.migrate().await.unwrap(); + let timer = OutboxMessage::create_to("timer-1", "Timeout", "saga", b"t".to_vec()) + .unwrap() + .deliver_after(SystemTime::now(), delay); + due_at = timer.deliver_at.unwrap(); + commit_messages(&repo, vec![timer]).await; + repo.pool().close().await; + } // process "crashes" + + let repo = SqliteRepository::new(db.pool().await); + let store = repo.outbox_store(); + let pending = store.pending(10).await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].deliver_at, Some(due_at), "schedule persisted"); + let early = store + .claim(ClaimOutboxMessages::new("w", 10, LEASE)) + .await + .unwrap(); + assert!(early.is_empty(), "not claimable before it is due"); + + // The one unavoidable wait: the SQL claim compares against wall time. + let remaining = due_at.duration_since(SystemTime::now()).unwrap_or_default(); + tokio::time::sleep(remaining + Duration::from_millis(50)).await; + + let fired = store + .claim(ClaimOutboxMessages::new("w", 10, LEASE)) + .await + .unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].payload, b"t"); + store + .complete(&OutboxClaimRef::from_message(&fired[0]).unwrap()) + .await + .unwrap(); + + // Released (retried) rows are immediately claimable again: the + // release bumps `next_available_at` to now, not back to the schedule. + let retry = OutboxMessage::create_to("timer-2", "Timeout", "saga", vec![]) + .unwrap() + .deliver_at(SystemTime::now() - Duration::from_millis(1)); + commit_messages(&repo, vec![retry]).await; + let claimed = store + .claim(ClaimOutboxMessages::new("w", 10, LEASE)) + .await + .unwrap(); + let claim = OutboxClaimRef::from_message(&claimed[0]).unwrap(); + store.release(&claim, "transient").await.unwrap(); + let again = store + .claim(ClaimOutboxMessages::new("w", 10, LEASE)) + .await + .unwrap(); + assert_eq!(again.len(), 1); + assert_eq!(again[0].attempts, 2); + } +} + +#[cfg(feature = "postgres")] +#[path = "../support/postgres.rs"] +mod postgres_support; + +#[cfg(feature = "postgres")] +mod postgres_backend { + use super::*; + use crate::postgres_support::PostgresTestSchema; + + #[tokio::test] + async fn postgres_store_honours_deliver_at() { + let Some(schema) = + PostgresTestSchema::create_from_env("sched", "skipping postgres schedule test").await + else { + return; + }; + let repo = schema.repository().await; + commit_messages(&repo, messages(SystemTime::now())).await; + scenario_schedule_honoured(&repo.outbox_store()).await; + } +} From a6645d0f1f8809216ad4012ca99b8a2a03d7f285 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:52:40 -0500 Subject: [PATCH 123/484] feat(lease): add TTL leases with monotonic fencing tokens New `distributed::lease` module: LeaseStore (acquire/renew/release/ current/check_fence), FencingToken, a serializable resource-side Fence high-water mark, InMemoryLeaseStore on an injectable Clock, and SqliteLeaseStore/PostgresLeaseStore. Each SQL operation is a single conditional statement on the database clock. Every acquisition bumps the per-key token. Release keeps the row (expires_at = 0), so tokens never reset. It is a sibling of `lock` rather than an extension: Lock has no holder, renewal or token, and deletes aggregate_locks rows on release. Migration 10 `coordination leases` (sqlite + postgres) creates coordination_leases. Adds `distributed::clock` (Clock, SystemClock, ManualClock) for deterministic tests. Tests: coordination_lease (lifecycle, stale fence rejection, concurrent acquire races, expiry takeover; in-memory with ManualClock, sqlite across pools, postgres when DATABASE_URL is set). Refs [[tasks/gr-p6-coordination-primitives]] --- migrations/inventory.json | 12 + .../postgres/0010_coordination_leases.sql | 15 + .../sqlite/0010_coordination_leases.sql | 15 + src/clock.rs | 92 ++++ src/lease/fence.rs | 71 ++++ src/lease/in_memory.rs | 181 ++++++++ src/lease/mod.rs | 259 +++++++++++ src/lease/sqlx_store.rs | 402 ++++++++++++++++++ src/lib.rs | 10 + src/sqlx_repo/repo/backend.rs | 18 +- tests/coordination_lease/main.rs | 360 ++++++++++++++++ tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 13 files changed, 1433 insertions(+), 6 deletions(-) create mode 100644 migrations/postgres/0010_coordination_leases.sql create mode 100644 migrations/sqlite/0010_coordination_leases.sql create mode 100644 src/clock.rs create mode 100644 src/lease/fence.rs create mode 100644 src/lease/in_memory.rs create mode 100644 src/lease/mod.rs create mode 100644 src/lease/sqlx_store.rs create mode 100644 tests/coordination_lease/main.rs diff --git a/migrations/inventory.json b/migrations/inventory.json index 5a16b6163..1b923d11e 100644 --- a/migrations/inventory.json +++ b/migrations/inventory.json @@ -108,6 +108,18 @@ "path": "migrations/postgres/0009_projection_delivery_aliases.sql", "sha256": "19845d4bfcb30d1bf43cb485a6bb9f765a6c1db7abf74fb004046457af83a2b9" } + }, + { + "version": 10, + "description": "coordination leases", + "sqlite": { + "path": "migrations/sqlite/0010_coordination_leases.sql", + "sha256": "ec39b6bc567b2cbe06a8ba162b3b330735a67d83d8c19044f3e39e84df4119d7" + }, + "postgres": { + "path": "migrations/postgres/0010_coordination_leases.sql", + "sha256": "f5494517f00ba6f4a00ca140fcb77ac49444d6d7bdf3ac575d00e043f8c01072" + } } ] } diff --git a/migrations/postgres/0010_coordination_leases.sql b/migrations/postgres/0010_coordination_leases.sql new file mode 100644 index 000000000..30f0bd59f --- /dev/null +++ b/migrations/postgres/0010_coordination_leases.sql @@ -0,0 +1,15 @@ +-- Durable TTL leases with monotonic fencing tokens (see `distributed::lease`). +-- One row per lease key. `fencing_token` increments on every acquisition and +-- is never reset: release sets `expires_at = 0` and keeps the row, so a later +-- holder always receives a strictly greater token. `acquired_at`/`expires_at` +-- are epoch seconds from the database clock (clock_timestamp()). +CREATE TABLE IF NOT EXISTS coordination_leases ( + lease_key text NOT NULL PRIMARY KEY, + holder text NOT NULL, + fencing_token bigint NOT NULL, + acquired_at double precision NOT NULL, + expires_at double precision NOT NULL, + CHECK (lease_key <> ''), + CHECK (holder <> ''), + CHECK (fencing_token > 0) +); diff --git a/migrations/sqlite/0010_coordination_leases.sql b/migrations/sqlite/0010_coordination_leases.sql new file mode 100644 index 000000000..f69763f00 --- /dev/null +++ b/migrations/sqlite/0010_coordination_leases.sql @@ -0,0 +1,15 @@ +-- Durable TTL leases with monotonic fencing tokens (see `distributed::lease`). +-- One row per lease key. `fencing_token` increments on every acquisition and +-- is never reset: release sets `expires_at = 0` and keeps the row, so a later +-- holder always receives a strictly greater token. `acquired_at`/`expires_at` +-- are epoch seconds from the database clock (unixepoch('now','subsec')). +CREATE TABLE IF NOT EXISTS coordination_leases ( + lease_key TEXT NOT NULL PRIMARY KEY, + holder TEXT NOT NULL, + fencing_token INTEGER NOT NULL, + acquired_at REAL NOT NULL, + expires_at REAL NOT NULL, + CHECK (lease_key <> ''), + CHECK (holder <> ''), + CHECK (fencing_token > 0) +); diff --git a/src/clock.rs b/src/clock.rs new file mode 100644 index 000000000..09d21a445 --- /dev/null +++ b/src/clock.rs @@ -0,0 +1,92 @@ +//! Injectable wall clock for coordination primitives. +//! +//! Sagas compute step deadlines and the in-memory [`lease`](crate::lease) +//! store evaluates TTLs against a [`Clock`] so tests can drive time +//! deterministically with a [`ManualClock`] instead of sleeping. Production +//! code uses [`SystemClock`]. (The SQL lease stores deliberately use the +//! *database* clock instead, so every process agrees on one authoritative +//! time source.) + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +/// A source of "now". +pub trait Clock: Send + Sync { + /// The current wall-clock time. + fn now(&self) -> SystemTime; +} + +/// The process wall clock. +#[derive(Debug, Clone, Copy, Default)] +pub struct SystemClock; + +impl Clock for SystemClock { + fn now(&self) -> SystemTime { + crate::time::now() + } +} + +/// A clock that only moves when told to. Clones share the same time, so a +/// test can hand one clone to the code under test and advance another. +#[derive(Debug, Clone)] +pub struct ManualClock { + now: Arc>, +} + +impl ManualClock { + /// A manual clock frozen at `start`. + pub fn new(start: SystemTime) -> Self { + Self { + now: Arc::new(Mutex::new(start)), + } + } + + /// A manual clock frozen at the current wall-clock time. + pub fn starting_now() -> Self { + Self::new(crate::time::now()) + } + + /// Move the clock forward by `by`. + pub fn advance(&self, by: Duration) { + let mut now = self.now.lock().unwrap_or_else(|p| p.into_inner()); + *now = now.checked_add(by).unwrap_or(*now); + } + + /// Jump the clock to `at` (may move backwards; leases and sagas must + /// tolerate that, since real clocks step too). + pub fn set(&self, at: SystemTime) { + *self.now.lock().unwrap_or_else(|p| p.into_inner()) = at; + } +} + +impl Default for ManualClock { + fn default() -> Self { + Self::starting_now() + } +} + +impl Clock for ManualClock { + fn now(&self) -> SystemTime { + *self.now.lock().unwrap_or_else(|p| p.into_inner()) + } +} + +impl Clock for Arc { + fn now(&self) -> SystemTime { + (**self).now() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn manual_clock_clones_share_time() { + let start = SystemTime::UNIX_EPOCH + Duration::from_secs(100); + let clock = ManualClock::new(start); + let other = clock.clone(); + other.advance(Duration::from_secs(5)); + assert_eq!(clock.now(), start + Duration::from_secs(5)); + } +} diff --git a/src/lease/fence.rs b/src/lease/fence.rs new file mode 100644 index 000000000..a4a3588c2 --- /dev/null +++ b/src/lease/fence.rs @@ -0,0 +1,71 @@ +use serde::{Deserialize, Serialize}; + +use super::{FencingToken, LeaseError}; + +/// Resource-side fencing high-water mark. +/// +/// Embed one in the state a lease protects (it is `Serialize`, so it can live +/// in an event-sourced aggregate and be rebuilt on replay). Call +/// [`admit`](Self::admit) with the token carried by each write: tokens older +/// than the newest admitted one are rejected, equal tokens (the same holder +/// writing again) and newer tokens (a new holder) are accepted. +/// +/// Because the check and the write happen in the same cell/transaction, this +/// is the authoritative fence; [`LeaseStore::check_fence`](super::LeaseStore::check_fence) +/// is only advisory. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Fence { + high_water: Option, +} + +impl Fence { + /// An empty fence (admits any token). + pub const fn new() -> Self { + Self { high_water: None } + } + + /// The newest token admitted so far. + pub fn high_water(&self) -> Option { + self.high_water + } + + /// Whether `token` would be admitted, without recording it. + pub fn would_admit(&self, token: FencingToken) -> bool { + self.high_water.is_none_or(|seen| token >= seen) + } + + /// Admit `token` (raising the high-water mark) or reject it as stale. + /// `key` only labels the error. + pub fn admit(&mut self, key: &str, token: FencingToken) -> Result<(), LeaseError> { + match self.high_water { + Some(current) if token < current => Err(LeaseError::StaleFence { + key: key.to_string(), + presented: token, + current, + }), + _ => { + self.high_water = Some(token); + Ok(()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fence_rejects_only_older_tokens() { + let mut fence = Fence::new(); + fence.admit("k", FencingToken::new(2)).unwrap(); + fence.admit("k", FencingToken::new(2)).unwrap(); + assert!(matches!( + fence.admit("k", FencingToken::new(1)), + Err(LeaseError::StaleFence { .. }) + )); + fence.admit("k", FencingToken::new(5)).unwrap(); + assert_eq!(fence.high_water(), Some(FencingToken::new(5))); + assert!(!fence.would_admit(FencingToken::new(4))); + } +} diff --git a/src/lease/in_memory.rs b/src/lease/in_memory.rs new file mode 100644 index 000000000..9be092b49 --- /dev/null +++ b/src/lease/in_memory.rs @@ -0,0 +1,181 @@ +#![expect( + clippy::manual_async_fn, + reason = "trait impls return impl Future + Send to preserve public Send bounds" +)] + +use std::collections::HashMap; +use std::future::Future; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +use crate::clock::{Clock, SystemClock}; + +use super::{validate_request, FencingToken, Lease, LeaseError, LeaseStore}; + +#[derive(Debug, Clone)] +struct Entry { + holder: String, + token: u64, + /// `UNIX_EPOCH` once released (the entry, and its token, are retained). + expires_at: SystemTime, +} + +impl Entry { + fn lease(&self, key: &str) -> Lease { + Lease { + key: key.to_string(), + holder: self.holder.clone(), + token: FencingToken::new(self.token), + expires_at: self.expires_at, + } + } + + fn is_live(&self, now: SystemTime) -> bool { + self.expires_at > now + } + + fn held_by(&self, lease: &Lease, now: SystemTime) -> bool { + self.is_live(now) && self.holder == lease.holder && self.token == lease.token.get() + } +} + +/// Process-local [`LeaseStore`]. Clones share state. Time comes from the +/// injected [`Clock`] — pass a [`ManualClock`](crate::clock::ManualClock) to +/// test expiry without sleeping. +#[derive(Clone)] +pub struct InMemoryLeaseStore { + clock: C, + entries: Arc>>, +} + +impl InMemoryLeaseStore { + /// A store on the system clock. + pub fn new() -> Self { + Self::with_clock(SystemClock) + } +} + +impl Default for InMemoryLeaseStore { + fn default() -> Self { + Self::new() + } +} + +impl InMemoryLeaseStore { + /// A store on an explicit clock. + pub fn with_clock(clock: C) -> Self { + Self { + clock, + entries: Arc::new(Mutex::new(HashMap::new())), + } + } + + fn entries(&self) -> std::sync::MutexGuard<'_, HashMap> { + // Mutations never run user code while holding the guard, so a poison + // cannot leave an entry half-written; recover rather than fail. + self.entries.lock().unwrap_or_else(|p| p.into_inner()) + } + + fn deadline(now: SystemTime, ttl: Duration) -> Result { + now.checked_add(ttl) + .ok_or_else(|| LeaseError::Invalid("lease ttl overflows the clock".into())) + } +} + +impl LeaseStore for InMemoryLeaseStore { + fn acquire<'a>( + &'a self, + key: &'a str, + holder: &'a str, + ttl: Duration, + ) -> impl Future> + Send + 'a { + async move { + validate_request(key, holder, ttl)?; + let now = self.clock.now(); + let expires_at = Self::deadline(now, ttl)?; + let mut entries = self.entries(); + match entries.get_mut(key) { + Some(entry) if entry.is_live(now) => { + if entry.holder == holder { + Ok(entry.lease(key)) + } else { + Err(LeaseError::Held { + key: key.to_string(), + holder: entry.holder.clone(), + expires_at: entry.expires_at, + }) + } + } + Some(entry) => { + entry.holder = holder.to_string(); + entry.token += 1; + entry.expires_at = expires_at; + Ok(entry.lease(key)) + } + None => { + let entry = Entry { + holder: holder.to_string(), + token: 1, + expires_at, + }; + let lease = entry.lease(key); + entries.insert(key.to_string(), entry); + Ok(lease) + } + } + } + } + + fn renew<'a>( + &'a self, + lease: &'a Lease, + ttl: Duration, + ) -> impl Future> + Send + 'a { + async move { + validate_request(&lease.key, &lease.holder, ttl)?; + let now = self.clock.now(); + let expires_at = Self::deadline(now, ttl)?; + let mut entries = self.entries(); + match entries.get_mut(&lease.key) { + Some(entry) if entry.held_by(lease, now) => { + entry.expires_at = expires_at; + Ok(entry.lease(&lease.key)) + } + _ => Err(LeaseError::Lost { + key: lease.key.clone(), + }), + } + } + } + + fn release<'a>( + &'a self, + lease: &'a Lease, + ) -> impl Future> + Send + 'a { + async move { + let now = self.clock.now(); + let mut entries = self.entries(); + match entries.get_mut(&lease.key) { + Some(entry) if entry.held_by(lease, now) => { + entry.expires_at = SystemTime::UNIX_EPOCH; + Ok(true) + } + _ => Ok(false), + } + } + } + + fn current<'a>( + &'a self, + key: &'a str, + ) -> impl Future, LeaseError>> + Send + 'a { + async move { + let now = self.clock.now(); + Ok(self + .entries() + .get(key) + .filter(|entry| entry.is_live(now)) + .map(|entry| entry.lease(key))) + } + } +} diff --git a/src/lease/mod.rs b/src/lease/mod.rs new file mode 100644 index 000000000..8cc1afa44 --- /dev/null +++ b/src/lease/mod.rs @@ -0,0 +1,259 @@ +//! Lease - TTL leases with monotonic fencing tokens. +//! +//! A [`Lease`] grants one *holder* exclusive ownership of a *key* (a boss +//! controller, a play-session item, an encounter settlement, ...) until its +//! TTL elapses. Holders [`renew`](LeaseStore::renew) to keep it and +//! [`release`](LeaseStore::release) to hand it back early. A crashed holder's +//! lease simply expires and becomes acquirable by someone else. +//! +//! ## Fencing +//! +//! A TTL alone cannot stop a paused/partitioned former holder from writing +//! after its lease was taken over. Every successful acquisition therefore +//! carries a [`FencingToken`] that is **strictly greater** than every token +//! previously issued for that key — the counter survives release and expiry. +//! Renewal keeps the token (same acquisition). Writers attach the token to +//! every protected write, and the resource rejects tokens older than the +//! newest it has seen: +//! +//! - embed a [`Fence`] in the protected aggregate/state and call +//! [`Fence::admit`] before applying a write (the robust pattern: the check +//! is atomic with the write because it lives in the same cell), or +//! - ask the store with [`LeaseStore::check_fence`] (a point-in-time check — +//! useful for diagnostics and cheap early rejection, but not atomic with a +//! write elsewhere). +//! +//! ## Why a sibling of [`crate::lock`] +//! +//! The [`lock`](crate::lock) module is an internal mutual-exclusion +//! optimisation behind `QueuedRepository`: its `Lock` trait is a +//! lock/unlock gate with no holder identity, no renewal and no token, and its +//! `aggregate_locks` rows are deleted on release (so a token stored there +//! would reset). Bolting fencing onto that trait would change its contract for +//! every repository; this module keeps a separate, explicit API and a separate +//! `coordination_leases` table whose rows are retained after release so the +//! token stays monotonic. +//! +//! ## Backends +//! +//! - [`InMemoryLeaseStore`] — process-local, driven by an injectable +//! [`Clock`](crate::clock::Clock) (use a +//! [`ManualClock`](crate::clock::ManualClock) in tests). +//! - `SqliteLeaseStore` / `PostgresLeaseStore` (features `sqlite` / +//! `postgres`) — durable, cross-process, evaluated against the **database +//! clock** so processes never disagree about expiry. The table is created +//! by the repository migrations (`0010_coordination_leases`) or standalone +//! with `migrate`. +//! +//! ```ignore +//! use distributed::lease::{InMemoryLeaseStore, LeaseStore, Fence}; +//! use std::time::Duration; +//! +//! let leases = InMemoryLeaseStore::new(); +//! let lease = leases.acquire("boss:hydra", "zone-7", Duration::from_secs(15)).await?; +//! // ... every 5s: +//! let lease = leases.renew(&lease, Duration::from_secs(15)).await?; +//! // the protected state rejects writes from a superseded controller: +//! boss.fence.admit("boss:hydra", lease.token)?; +//! ``` + +mod fence; +mod in_memory; +#[cfg(any(feature = "postgres", feature = "sqlite"))] +mod sqlx_store; + +pub use fence::Fence; +pub use in_memory::InMemoryLeaseStore; +#[cfg(any(feature = "postgres", feature = "sqlite"))] +pub use sqlx_store::{LeaseDialect, SqlxLeaseStore}; +#[cfg(feature = "postgres")] +pub use sqlx_store::{PostgresLeaseDialect, PostgresLeaseStore}; +#[cfg(feature = "sqlite")] +pub use sqlx_store::{SqliteLeaseDialect, SqliteLeaseStore}; + +use std::fmt; +use std::future::Future; +use std::time::{Duration, SystemTime}; + +use serde::{Deserialize, Serialize}; + +use crate::lock::RetryClass; + +/// Monotonic per-key fencing token. Every acquisition of a key gets a token +/// strictly greater than all earlier acquisitions of that key. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct FencingToken(u64); + +impl FencingToken { + /// Wrap a raw token value (e.g. one carried in a command payload). + pub const fn new(value: u64) -> Self { + Self(value) + } + + /// The raw token value. + pub const fn get(self) -> u64 { + self.0 + } +} + +impl fmt::Display for FencingToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// A held lease: `holder` owns `key` until `expires_at`, fenced by `token`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Lease { + pub key: String, + pub holder: String, + pub token: FencingToken, + /// Expiry as seen by the store's clock (the database clock for SQL stores). + pub expires_at: SystemTime, +} + +impl Lease { + /// Whether the lease has expired at `now` (by the caller's clock — the + /// store's own check is authoritative). + pub fn is_expired_at(&self, now: SystemTime) -> bool { + self.expires_at <= now + } +} + +/// Lease operation failure. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum LeaseError { + /// `acquire`: another holder owns an unexpired lease on the key. + Held { + key: String, + holder: String, + expires_at: SystemTime, + }, + /// `renew`/`check_fence`: the presented lease is no longer the live + /// lease for the key (expired, released, or superseded). + Lost { key: String }, + /// A write carried a fencing token older than the newest one seen. + StaleFence { + key: String, + presented: FencingToken, + current: FencingToken, + }, + /// Invalid arguments (empty key/holder, zero TTL). + Invalid(String), + /// A transient backend failure (I/O, `SQLITE_BUSY`, pool timeout). + Backend(String), +} + +impl LeaseError { + /// Retry classification, shared vocabulary with [`crate::lock::LockError`]. + pub fn kind(&self) -> RetryClass { + match self { + LeaseError::Held { .. } | LeaseError::Backend(_) => RetryClass::Retryable, + LeaseError::Lost { .. } | LeaseError::StaleFence { .. } | LeaseError::Invalid(_) => { + RetryClass::Permanent + } + } + } + + /// Whether a retry may succeed. + pub fn is_retryable(&self) -> bool { + self.kind().is_retryable() + } +} + +impl fmt::Display for LeaseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LeaseError::Held { key, holder, .. } => { + write!(f, "lease `{key}` is held by `{holder}`") + } + LeaseError::Lost { key } => write!(f, "lease `{key}` is no longer held"), + LeaseError::StaleFence { + key, + presented, + current, + } => write!( + f, + "stale fencing token {presented} for `{key}` (current {current})" + ), + LeaseError::Invalid(message) => write!(f, "invalid lease request: {message}"), + LeaseError::Backend(message) => write!(f, "lease backend error: {message}"), + } + } +} + +impl std::error::Error for LeaseError {} + +/// Store of TTL leases with monotonic fencing tokens. +pub trait LeaseStore: Send + Sync { + /// Acquire `key` for `holder` for `ttl`. + /// + /// - free, expired or released key: a new lease with the next token; + /// - live lease already held by `holder`: that lease, unchanged + /// (idempotent on a lost-response retry — call [`renew`](Self::renew) + /// to extend it); + /// - live lease held by someone else: [`LeaseError::Held`]. + fn acquire<'a>( + &'a self, + key: &'a str, + holder: &'a str, + ttl: Duration, + ) -> impl Future> + Send + 'a; + + /// Extend a live lease to `now + ttl`, keeping its token. Fails with + /// [`LeaseError::Lost`] if it expired or was superseded — the holder must + /// stop acting and re-acquire (getting a new token). + fn renew<'a>( + &'a self, + lease: &'a Lease, + ttl: Duration, + ) -> impl Future> + Send + 'a; + + /// Release a lease early. Returns `false` (not an error) when it was no + /// longer held. The token counter is retained. + fn release<'a>( + &'a self, + lease: &'a Lease, + ) -> impl Future> + Send + 'a; + + /// The live lease on `key`, if any. + fn current<'a>( + &'a self, + key: &'a str, + ) -> impl Future, LeaseError>> + Send + 'a; + + /// Point-in-time fence check: `Ok` iff `token` is the live lease's token. + fn check_fence<'a>( + &'a self, + key: &'a str, + token: FencingToken, + ) -> impl Future> + Send + 'a { + async move { + match self.current(key).await? { + Some(lease) if lease.token == token => Ok(()), + Some(lease) if lease.token > token => Err(LeaseError::StaleFence { + key: key.to_string(), + presented: token, + current: lease.token, + }), + _ => Err(LeaseError::Lost { + key: key.to_string(), + }), + } + } + } +} + +pub(crate) fn validate_request(key: &str, holder: &str, ttl: Duration) -> Result<(), LeaseError> { + if key.is_empty() { + return Err(LeaseError::Invalid("lease key must not be empty".into())); + } + if holder.is_empty() { + return Err(LeaseError::Invalid("lease holder must not be empty".into())); + } + if ttl.is_zero() { + return Err(LeaseError::Invalid("lease ttl must be positive".into())); + } + Ok(()) +} diff --git a/src/lease/sqlx_store.rs b/src/lease/sqlx_store.rs new file mode 100644 index 000000000..da8697914 --- /dev/null +++ b/src/lease/sqlx_store.rs @@ -0,0 +1,402 @@ +//! Durable SQLx lease stores (`coordination_leases` table). +//! +//! Mirrors the [`crate::lock`] SQLx layout: dialect-neutral machinery in +//! [`SqlxLeaseStore`], per-backend SQL in a zero-sized [`LeaseDialect`] +//! marker. All expiry decisions use the **database clock** +//! (`unixepoch('now','subsec')` / `extract(epoch from now())`), so processes +//! with skewed clocks still agree on who holds a lease. +//! +//! Each statement is a single atomic conditional write: +//! +//! - acquire = upsert that inserts token 1, or takes over an expired/released +//! row with `fencing_token + 1`, and is a no-op on a live row; +//! - renew = update guarded by `(holder, fencing_token, unexpired)`; +//! - release = the same guard, setting `expires_at = 0` and **keeping** the +//! row so the token never resets. +#![expect( + clippy::manual_async_fn, + reason = "trait impls return impl Future + Send to preserve public Send bounds" +)] + +use std::future::Future; +use std::marker::PhantomData; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use sqlx::{Database, Encode, FromRow, IntoArguments, Pool, Type}; + +use super::{validate_request, FencingToken, Lease, LeaseError, LeaseStore}; + +/// Per-backend SQL for [`SqlxLeaseStore`]. +pub trait LeaseDialect: Send + Sync + 'static { + /// The sqlx driver this dialect targets. + type Db: Database; + + /// Idempotent `coordination_leases` DDL, `;`-separated. The repository + /// migration `0010_coordination_leases` creates the same table. + const DDL: &'static str; + /// Binds `(key, holder, ttl_secs)`; `RETURNING holder, fencing_token, + /// expires_at` only when this call acquired. + const ACQUIRE_SQL: &'static str; + /// Binds `(key, holder, token, ttl_secs)`; `RETURNING holder, + /// fencing_token, expires_at` only when the lease was live and ours. + const RENEW_SQL: &'static str; + /// Binds `(key, holder, token)`; `RETURNING holder, fencing_token, + /// expires_at` only when the lease was live and ours. + const RELEASE_SQL: &'static str; + /// Binds `(key)`; returns `holder, fencing_token, expires_at, db_now`. + const CURRENT_SQL: &'static str; + + /// Whether an error is a transient busy condition (SQLite `SQLITE_BUSY`). + fn is_busy(_err: &sqlx::Error) -> bool { + false + } +} + +type LeaseRow = (String, i64, f64); +type CurrentRow = (String, i64, f64, f64); + +/// Durable [`LeaseStore`] over a SQLx pool. Cheap to clone. +pub struct SqlxLeaseStore { + pool: Pool, + dialect: PhantomData, +} + +impl Clone for SqlxLeaseStore { + fn clone(&self) -> Self { + Self { + pool: self.pool.clone(), + dialect: PhantomData, + } + } +} + +impl SqlxLeaseStore { + /// A store over an existing pool. The pool's database must already have + /// the `coordination_leases` table (repository migrations or + /// [`migrate`](Self::migrate)). + pub fn new(pool: Pool) -> Self { + Self { + pool, + dialect: PhantomData, + } + } + + /// The underlying pool. + pub fn pool(&self) -> &Pool { + &self.pool + } +} + +fn backend_error(op: &str, err: sqlx::Error) -> LeaseError { + if D::is_busy(&err) { + LeaseError::Backend(format!("lease {op} busy: {err}")) + } else { + LeaseError::Backend(format!("lease {op} failed: {err}")) + } +} + +fn epoch_to_time(secs: f64) -> SystemTime { + if secs.is_finite() && secs > 0.0 { + UNIX_EPOCH + Duration::from_secs_f64(secs) + } else { + UNIX_EPOCH + } +} + +fn lease_from_row(key: &str, (holder, token, expires_at): LeaseRow) -> Result { + let token = u64::try_from(token) + .map_err(|_| LeaseError::Backend(format!("invalid stored fencing token {token}")))?; + Ok(Lease { + key: key.to_string(), + holder, + token: FencingToken::new(token), + expires_at: epoch_to_time(expires_at), + }) +} + +fn token_bind(lease: &Lease) -> Result { + i64::try_from(lease.token.get()) + .map_err(|_| LeaseError::Invalid("fencing token exceeds storage range".into())) +} + +impl SqlxLeaseStore +where + D: LeaseDialect, + for<'c> &'c Pool: sqlx::Executor<'c, Database = D::Db>, + ::Arguments: IntoArguments, + for<'q> &'q str: Encode<'q, D::Db> + Type, + for<'q> f64: Encode<'q, D::Db> + Type, + for<'q> i64: Encode<'q, D::Db> + Type, + for<'r> LeaseRow: FromRow<'r, ::Row>, + for<'r> CurrentRow: FromRow<'r, ::Row>, +{ + /// Create the `coordination_leases` table for standalone use. + pub async fn migrate(pool: &Pool) -> Result<(), LeaseError> { + for statement in D::DDL.split(';') { + let statement = statement.trim(); + if statement.is_empty() { + continue; + } + sqlx::query(statement) + .execute(pool) + .await + .map_err(|err| backend_error::("migrate", err))?; + } + Ok(()) + } + + async fn current_row(&self, key: &str) -> Result, LeaseError> { + let row = sqlx::query_as::<_, CurrentRow>(D::CURRENT_SQL) + .bind(key) + .fetch_optional(&self.pool) + .await + .map_err(|err| backend_error::("read", err))?; + row.map(|(holder, token, expires_at, now)| { + Ok(( + lease_from_row(key, (holder, token, expires_at))?, + epoch_to_time(now), + )) + }) + .transpose() + } +} + +impl LeaseStore for SqlxLeaseStore +where + D: LeaseDialect, + for<'c> &'c Pool: sqlx::Executor<'c, Database = D::Db>, + ::Arguments: IntoArguments, + for<'q> &'q str: Encode<'q, D::Db> + Type, + for<'q> f64: Encode<'q, D::Db> + Type, + for<'q> i64: Encode<'q, D::Db> + Type, + for<'r> LeaseRow: FromRow<'r, ::Row>, + for<'r> CurrentRow: FromRow<'r, ::Row>, +{ + fn acquire<'a>( + &'a self, + key: &'a str, + holder: &'a str, + ttl: Duration, + ) -> impl Future> + Send + 'a { + async move { + validate_request(key, holder, ttl)?; + let acquired = sqlx::query_as::<_, LeaseRow>(D::ACQUIRE_SQL) + .bind(key) + .bind(holder) + .bind(ttl.as_secs_f64()) + .fetch_optional(&self.pool) + .await + .map_err(|err| backend_error::("acquire", err))?; + if let Some(row) = acquired { + return lease_from_row(key, row); + } + // Live row: ours (idempotent retry) or someone else's. + match self.current_row(key).await? { + Some((lease, now)) if lease.expires_at > now => { + if lease.holder == holder { + Ok(lease) + } else { + Err(LeaseError::Held { + key: key.to_string(), + holder: lease.holder, + expires_at: lease.expires_at, + }) + } + } + // Expired between the two statements: report contention and + // let the caller retry rather than loop here. + _ => Err(LeaseError::Backend(format!( + "lease `{key}` changed during acquire; retry" + ))), + } + } + } + + fn renew<'a>( + &'a self, + lease: &'a Lease, + ttl: Duration, + ) -> impl Future> + Send + 'a { + async move { + validate_request(&lease.key, &lease.holder, ttl)?; + let row = sqlx::query_as::<_, LeaseRow>(D::RENEW_SQL) + .bind(lease.key.as_str()) + .bind(lease.holder.as_str()) + .bind(token_bind(lease)?) + .bind(ttl.as_secs_f64()) + .fetch_optional(&self.pool) + .await + .map_err(|err| backend_error::("renew", err))?; + match row { + Some(row) => lease_from_row(&lease.key, row), + None => Err(LeaseError::Lost { + key: lease.key.clone(), + }), + } + } + } + + fn release<'a>( + &'a self, + lease: &'a Lease, + ) -> impl Future> + Send + 'a { + async move { + let row = sqlx::query_as::<_, LeaseRow>(D::RELEASE_SQL) + .bind(lease.key.as_str()) + .bind(lease.holder.as_str()) + .bind(token_bind(lease)?) + .fetch_optional(&self.pool) + .await + .map_err(|err| backend_error::("release", err))?; + Ok(row.is_some()) + } + } + + fn current<'a>( + &'a self, + key: &'a str, + ) -> impl Future, LeaseError>> + Send + 'a { + async move { + Ok(self + .current_row(key) + .await? + .filter(|(lease, now)| lease.expires_at > *now) + .map(|(lease, _)| lease)) + } + } +} + +// --------------------------------------------------------------------------- +// SQLite +// --------------------------------------------------------------------------- + +/// SQLite [`LeaseDialect`]: `?n` placeholders, `unixepoch('now','subsec')`. +#[cfg(feature = "sqlite")] +#[derive(Debug, Clone, Copy)] +pub struct SqliteLeaseDialect; + +#[cfg(feature = "sqlite")] +impl LeaseDialect for SqliteLeaseDialect { + type Db = sqlx::Sqlite; + + const DDL: &'static str = "\ +CREATE TABLE IF NOT EXISTS coordination_leases (\ + lease_key TEXT NOT NULL PRIMARY KEY,\ + holder TEXT NOT NULL,\ + fencing_token INTEGER NOT NULL,\ + acquired_at REAL NOT NULL,\ + expires_at REAL NOT NULL,\ + CHECK (lease_key <> ''),\ + CHECK (holder <> ''),\ + CHECK (fencing_token > 0)\ +)"; + + const ACQUIRE_SQL: &'static str = r#" + INSERT INTO coordination_leases (lease_key, holder, fencing_token, acquired_at, expires_at) + VALUES (?1, ?2, 1, unixepoch('now','subsec'), unixepoch('now','subsec') + ?3) + ON CONFLICT (lease_key) DO UPDATE + SET holder = excluded.holder, + fencing_token = coordination_leases.fencing_token + 1, + acquired_at = excluded.acquired_at, + expires_at = excluded.expires_at + WHERE coordination_leases.expires_at <= unixepoch('now','subsec') + RETURNING holder, fencing_token, expires_at + "#; + + const RENEW_SQL: &'static str = r#" + UPDATE coordination_leases + SET expires_at = unixepoch('now','subsec') + ?4 + WHERE lease_key = ?1 AND holder = ?2 AND fencing_token = ?3 + AND expires_at > unixepoch('now','subsec') + RETURNING holder, fencing_token, expires_at + "#; + + const RELEASE_SQL: &'static str = r#" + UPDATE coordination_leases + SET expires_at = 0 + WHERE lease_key = ?1 AND holder = ?2 AND fencing_token = ?3 + AND expires_at > unixepoch('now','subsec') + RETURNING holder, fencing_token, expires_at + "#; + + const CURRENT_SQL: &'static str = r#" + SELECT holder, fencing_token, expires_at, unixepoch('now','subsec') AS db_now + FROM coordination_leases + WHERE lease_key = ?1 + "#; + + fn is_busy(err: &sqlx::Error) -> bool { + crate::sqlx_repo::is_sqlite_busy(err) + } +} + +/// SQLite-backed [`LeaseStore`]. Cross-process use needs a shared file DB. +#[cfg(feature = "sqlite")] +pub type SqliteLeaseStore = SqlxLeaseStore; + +// --------------------------------------------------------------------------- +// Postgres +// --------------------------------------------------------------------------- + +/// Postgres [`LeaseDialect`]: `$n` placeholders, `extract(epoch from now())`. +#[cfg(feature = "postgres")] +#[derive(Debug, Clone, Copy)] +pub struct PostgresLeaseDialect; + +#[cfg(feature = "postgres")] +impl LeaseDialect for PostgresLeaseDialect { + type Db = sqlx::Postgres; + + const DDL: &'static str = "\ +CREATE TABLE IF NOT EXISTS coordination_leases (\ + lease_key text NOT NULL PRIMARY KEY,\ + holder text NOT NULL,\ + fencing_token bigint NOT NULL,\ + acquired_at double precision NOT NULL,\ + expires_at double precision NOT NULL,\ + CHECK (lease_key <> ''),\ + CHECK (holder <> ''),\ + CHECK (fencing_token > 0)\ +)"; + + const ACQUIRE_SQL: &'static str = r#" + INSERT INTO coordination_leases (lease_key, holder, fencing_token, acquired_at, expires_at) + VALUES ($1, $2, 1, + extract(epoch from clock_timestamp())::double precision, + extract(epoch from clock_timestamp())::double precision + $3) + ON CONFLICT (lease_key) DO UPDATE + SET holder = EXCLUDED.holder, + fencing_token = coordination_leases.fencing_token + 1, + acquired_at = EXCLUDED.acquired_at, + expires_at = EXCLUDED.expires_at + WHERE coordination_leases.expires_at <= extract(epoch from clock_timestamp())::double precision + RETURNING holder, fencing_token, expires_at + "#; + + const RENEW_SQL: &'static str = r#" + UPDATE coordination_leases + SET expires_at = extract(epoch from clock_timestamp())::double precision + $4 + WHERE lease_key = $1 AND holder = $2 AND fencing_token = $3 + AND expires_at > extract(epoch from clock_timestamp())::double precision + RETURNING holder, fencing_token, expires_at + "#; + + const RELEASE_SQL: &'static str = r#" + UPDATE coordination_leases + SET expires_at = 0 + WHERE lease_key = $1 AND holder = $2 AND fencing_token = $3 + AND expires_at > extract(epoch from clock_timestamp())::double precision + RETURNING holder, fencing_token, expires_at + "#; + + const CURRENT_SQL: &'static str = r#" + SELECT holder, fencing_token, expires_at, + extract(epoch from clock_timestamp())::double precision AS db_now + FROM coordination_leases + WHERE lease_key = $1 + "#; +} + +/// Postgres-backed [`LeaseStore`]. +#[cfg(feature = "postgres")] +pub type PostgresLeaseStore = SqlxLeaseStore; diff --git a/src/lib.rs b/src/lib.rs index 2af2b194b..bf00ae1c3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,7 @@ mod time; pub mod aggregate; pub mod application; pub mod bus; +pub mod clock; pub mod command; pub mod command_dispatch; pub mod domain_event; @@ -38,6 +39,7 @@ pub mod emitter; pub mod gateway; pub mod graphql; mod in_memory_repo; +pub mod lease; pub mod lock; #[cfg(feature = "metrics")] pub mod metrics; @@ -362,6 +364,14 @@ pub use lock::{PostgresLock, PostgresLockManager}; #[cfg(feature = "sqlite")] pub use lock::{SqliteLock, SqliteLockManager}; +// Coordination primitives: injectable clock and fenced leases. +pub use clock::{Clock, ManualClock, SystemClock}; +#[cfg(feature = "postgres")] +pub use lease::PostgresLeaseStore; +#[cfg(feature = "sqlite")] +pub use lease::SqliteLeaseStore; +pub use lease::{Fence, FencingToken, InMemoryLeaseStore, Lease, LeaseError, LeaseStore}; + // Outbox: commit concerns (aggregate + outbox in one commit). // // Low-level row plumbing (`outbox_message_insert_plan`, `outbox_message_row_values`) diff --git a/src/sqlx_repo/repo/backend.rs b/src/sqlx_repo/repo/backend.rs index 8b749fb1c..1882c062a 100644 --- a/src/sqlx_repo/repo/backend.rs +++ b/src/sqlx_repo/repo/backend.rs @@ -47,7 +47,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); assert_eq!( descriptions, vec![ @@ -59,7 +59,8 @@ mod tests { "gateway dependency versions", "projection program identity", "external command binding", - "projection delivery aliases" + "projection delivery aliases", + "coordination leases" ] ); assert_eq!( @@ -101,6 +102,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/sqlite/0009_projection_delivery_aliases.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/sqlite/0010_coordination_leases.sql" + )), ] ); } @@ -120,7 +125,7 @@ mod tests { .iter() .map(|migration| migration.sql) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); assert_eq!( descriptions, vec![ @@ -132,7 +137,8 @@ mod tests { "gateway dependency versions", "projection program identity", "external command binding", - "projection delivery aliases" + "projection delivery aliases", + "coordination leases" ] ); assert_eq!( @@ -174,6 +180,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/migrations/postgres/0009_projection_delivery_aliases.sql" )), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/migrations/postgres/0010_coordination_leases.sql" + )), ] ); } diff --git a/tests/coordination_lease/main.rs b/tests/coordination_lease/main.rs new file mode 100644 index 000000000..60b08f8e9 --- /dev/null +++ b/tests/coordination_lease/main.rs @@ -0,0 +1,360 @@ +//! Lease + fencing-token conformance for `InMemoryLeaseStore`, +//! `SqliteLeaseStore` and `PostgresLeaseStore`. +//! +//! Generic `scenario_*` helpers run against any `LeaseStore`. Expiry is driven +//! by a `ManualClock` for the in-memory store (no sleeps) and by short TTLs on +//! the database clock for the SQL stores. Postgres skips without +//! `DATABASE_URL`. + +#[cfg(feature = "sqlite")] +#[path = "../support/sqlite.rs"] +mod sqlite_support; + +use std::sync::Arc; +use std::time::Duration; + +use distributed::lease::{Fence, FencingToken, Lease, LeaseError, LeaseStore}; +use distributed::{InMemoryLeaseStore, ManualClock}; + +const TTL: Duration = Duration::from_secs(30); + +// =========================================================================== +// Generic scenarios +// =========================================================================== + +/// Acquire, contend, renew (same token), release, re-acquire (bigger token). +async fn scenario_lifecycle(store: &L) { + let first = store.acquire("boss:hydra", "zone-a", TTL).await.unwrap(); + assert_eq!(first.holder, "zone-a"); + + match store.acquire("boss:hydra", "zone-b", TTL).await { + Err(LeaseError::Held { holder, .. }) => assert_eq!(holder, "zone-a"), + other => panic!("contended acquire must be Held, got {other:?}"), + } + + // Same holder re-acquiring a live lease is an idempotent retry. + let again = store.acquire("boss:hydra", "zone-a", TTL).await.unwrap(); + assert_eq!(again.token, first.token); + + let renewed = store.renew(&first, TTL).await.unwrap(); + assert_eq!(renewed.token, first.token, "renewal keeps the token"); + assert!(renewed.expires_at >= first.expires_at); + + assert_eq!( + store.current("boss:hydra").await.unwrap(), + Some(renewed.clone()) + ); + store.check_fence("boss:hydra", first.token).await.unwrap(); + + assert!(store.release(&renewed).await.unwrap()); + assert!( + !store.release(&renewed).await.unwrap(), + "double release is a no-op" + ); + assert_eq!(store.current("boss:hydra").await.unwrap(), None); + assert!(matches!( + store.renew(&renewed, TTL).await, + Err(LeaseError::Lost { .. }) + )); + + let next = store.acquire("boss:hydra", "zone-b", TTL).await.unwrap(); + assert!( + next.token > first.token, + "tokens stay monotonic across release: {} then {}", + first.token, + next.token + ); +} + +/// A superseded holder's token is rejected by both the store check and a +/// resource-side `Fence`. +async fn scenario_stale_fence_rejected(store: &L) { + let old = store.acquire("item:sword", "session-1", TTL).await.unwrap(); + let mut fence = Fence::new(); + fence.admit("item:sword", old.token).unwrap(); + + store.release(&old).await.unwrap(); + let new = store.acquire("item:sword", "session-2", TTL).await.unwrap(); + assert!(new.token > old.token); + fence.admit("item:sword", new.token).unwrap(); + + // The paused former holder wakes up and tries to write. + match fence.admit("item:sword", old.token) { + Err(LeaseError::StaleFence { + presented, current, .. + }) => { + assert_eq!(presented, old.token); + assert_eq!(current, new.token); + } + other => panic!("stale token must be rejected, got {other:?}"), + } + assert!(matches!( + store.check_fence("item:sword", old.token).await, + Err(LeaseError::StaleFence { .. }) + )); + assert!(matches!( + store.renew(&old, TTL).await, + Err(LeaseError::Lost { .. }) + )); + store.check_fence("item:sword", new.token).await.unwrap(); +} + +/// Many holders race for one key: exactly one wins, the rest see `Held`. +async fn scenario_concurrent_acquire(store: &L) { + let contenders = 16; + let mut tasks = Vec::new(); + for n in 0..contenders { + let store = store.clone(); + tasks.push(tokio::spawn(async move { + store + .acquire("encounter:42", &format!("worker-{n}"), TTL) + .await + })); + } + let mut winners: Vec = Vec::new(); + for task in tasks { + match task.await.unwrap() { + Ok(lease) => winners.push(lease), + Err(LeaseError::Held { .. }) => {} + Err(other) => panic!("unexpected acquire error: {other}"), + } + } + assert_eq!(winners.len(), 1, "exactly one contender wins: {winners:?}"); + assert_eq!( + store.current("encounter:42").await.unwrap().unwrap(), + winners[0] + ); +} + +fn assert_invalid_inputs_rejected(result: Result) { + assert!(matches!(result, Err(LeaseError::Invalid(_))), "{result:?}"); +} + +// =========================================================================== +// In-memory (ManualClock: no sleeps) +// =========================================================================== + +mod in_memory { + use super::*; + + fn store() -> (ManualClock, InMemoryLeaseStore) { + let clock = ManualClock::starting_now(); + (clock.clone(), InMemoryLeaseStore::with_clock(clock)) + } + + #[tokio::test] + async fn lifecycle() { + scenario_lifecycle(&store().1).await; + } + + #[tokio::test] + async fn stale_fence_rejected() { + scenario_stale_fence_rejected(&store().1).await; + } + + #[tokio::test] + async fn concurrent_acquire_has_one_winner() { + scenario_concurrent_acquire(&store().1).await; + } + + #[tokio::test] + async fn invalid_inputs_rejected() { + let (_, store) = store(); + assert_invalid_inputs_rejected(store.acquire("", "h", TTL).await); + assert_invalid_inputs_rejected(store.acquire("k", "", TTL).await); + assert_invalid_inputs_rejected(store.acquire("k", "h", Duration::ZERO).await); + } + + #[tokio::test] + async fn expiry_takeover_bumps_token_and_fences_old_holder() { + let (clock, store) = store(); + let ttl = Duration::from_secs(15); + let old = store.acquire("boss:lich", "zone-a", ttl).await.unwrap(); + + // Renewed every 5s it never lapses. + for _ in 0..4 { + clock.advance(Duration::from_secs(5)); + store.renew(&old, ttl).await.unwrap(); + } + assert!(matches!( + store.acquire("boss:lich", "zone-b", ttl).await, + Err(LeaseError::Held { .. }) + )); + + // The holder stalls past its TTL; another controller takes over. + clock.advance(ttl); + assert_eq!(store.current("boss:lich").await.unwrap(), None); + let new = store.acquire("boss:lich", "zone-b", ttl).await.unwrap(); + assert_eq!(new.token, FencingToken::new(old.token.get() + 1)); + assert!(matches!( + store.renew(&old, ttl).await, + Err(LeaseError::Lost { .. }) + )); + assert!(!store.release(&old).await.unwrap()); + assert!(matches!( + store.check_fence("boss:lich", old.token).await, + Err(LeaseError::StaleFence { .. }) + )); + } + + #[tokio::test] + async fn concurrent_takeover_after_expiry_has_one_winner() { + let (clock, store) = store(); + let ttl = Duration::from_secs(10); + let first = store.acquire("k", "a", ttl).await.unwrap(); + clock.advance(ttl); + let store = Arc::new(store); + let mut tasks = Vec::new(); + for n in 0..8 { + let store = Arc::clone(&store); + tasks.push(tokio::spawn(async move { + store.acquire("k", &format!("h{n}"), ttl).await + })); + } + let mut tokens = Vec::new(); + for task in tasks { + if let Ok(lease) = task.await.unwrap() { + tokens.push(lease.token); + } + } + assert_eq!(tokens, vec![FencingToken::new(first.token.get() + 1)]); + } +} + +// =========================================================================== +// SQLite (shared temp-file database; database clock) +// =========================================================================== + +#[cfg(feature = "sqlite")] +mod sqlite_backend { + use super::*; + use crate::sqlite_support::TempDb; + use distributed::{SqliteLeaseStore, SqliteRepository}; + + async fn store(db: &TempDb) -> SqliteLeaseStore { + let pool = db.pool().await; + // The repository migrations create `coordination_leases`. + SqliteRepository::migrate_pool(&pool).await.unwrap(); + SqliteLeaseStore::new(pool) + } + + #[tokio::test] + async fn lifecycle() { + let db = TempDb::new("lease_lifecycle"); + scenario_lifecycle(&store(&db).await).await; + } + + #[tokio::test] + async fn stale_fence_rejected() { + let db = TempDb::new("lease_fence"); + scenario_stale_fence_rejected(&store(&db).await).await; + } + + #[tokio::test] + async fn concurrent_acquire_across_pools_has_one_winner() { + let db = TempDb::new("lease_race"); + let a = store(&db).await; + scenario_concurrent_acquire(&a).await; + // A second "process" (pool) sees the same holder. + let b = SqliteLeaseStore::new(db.pool().await); + assert!(matches!( + b.acquire("encounter:42", "other-process", TTL).await, + Err(LeaseError::Held { .. }) + )); + } + + #[tokio::test] + async fn standalone_migrate_is_idempotent() { + let db = TempDb::new("lease_migrate"); + let pool = db.pool().await; + SqliteLeaseStore::migrate(&pool).await.unwrap(); + SqliteLeaseStore::migrate(&pool).await.unwrap(); + let store = SqliteLeaseStore::new(pool); + store.acquire("k", "h", TTL).await.unwrap(); + } + + #[tokio::test] + async fn expiry_takeover_bumps_token_across_processes() { + let db = TempDb::new("lease_expiry"); + let a = store(&db).await; + let b = SqliteLeaseStore::new(db.pool().await); + let ttl = Duration::from_millis(200); + let old = a.acquire("boss:lich", "zone-a", ttl).await.unwrap(); + tokio::time::sleep(Duration::from_millis(350)).await; + let new = b + .acquire("boss:lich", "zone-b", Duration::from_secs(30)) + .await + .unwrap(); + assert_eq!(new.token, FencingToken::new(old.token.get() + 1)); + assert!(matches!( + a.renew(&old, ttl).await, + Err(LeaseError::Lost { .. }) + )); + assert!(matches!( + a.check_fence("boss:lich", old.token).await, + Err(LeaseError::StaleFence { .. }) + )); + } +} + +// =========================================================================== +// Postgres (skips when DATABASE_URL is unset) +// =========================================================================== + +#[cfg(feature = "postgres")] +#[path = "../support/postgres.rs"] +mod postgres_support; + +#[cfg(feature = "postgres")] +mod postgres_backend { + use super::*; + use crate::postgres_support::PostgresTestSchema; + use distributed::PostgresLeaseStore; + + async fn store() -> Option<(PostgresTestSchema, PostgresLeaseStore)> { + let schema = + PostgresTestSchema::create_from_env("leases", "skipping postgres lease test").await?; + let store = PostgresLeaseStore::new(schema.repository().await.pool().clone()); + Some((schema, store)) + } + + #[tokio::test] + async fn lifecycle() { + let Some((_schema, store)) = store().await else { + return; + }; + scenario_lifecycle(&store).await; + } + + #[tokio::test] + async fn stale_fence_rejected() { + let Some((_schema, store)) = store().await else { + return; + }; + scenario_stale_fence_rejected(&store).await; + } + + #[tokio::test] + async fn concurrent_acquire_has_one_winner() { + let Some((_schema, store)) = store().await else { + return; + }; + scenario_concurrent_acquire(&store).await; + } + + #[tokio::test] + async fn expiry_takeover_bumps_token() { + let Some((_schema, store)) = store().await else { + return; + }; + let ttl = Duration::from_millis(200); + let old = store.acquire("boss:lich", "zone-a", ttl).await.unwrap(); + tokio::time::sleep(Duration::from_millis(350)).await; + let new = store.acquire("boss:lich", "zone-b", TTL).await.unwrap(); + assert_eq!(new.token, FencingToken::new(old.token.get() + 1)); + assert!(matches!( + store.renew(&old, ttl).await, + Err(LeaseError::Lost { .. }) + )); + } +} diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index b2630adc1..af7f7bd62 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 9); + assert_eq!(latest_version, 10); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index 63af41672..3f1511574 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -201,7 +201,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 9); + assert_eq!(latest_version, 10); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From f603cf04847a6bbb6819c63f0fed905ea2279d6d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:52:41 -0500 Subject: [PATCH 124/484] feat(saga): add event-sourced saga process manager New `distributed::saga` module. Saga is a plain event-sourced aggregate, one stream per instance. The definition lists ordered steps, action/compensation commands and a deterministic reply fold. Each transition returns the participant command plus a durable `saga-timeout` timer (deliver_at). Both commit atomically with the saga's events. Semantics: a rejection compensates the applied steps in reverse. A timeout compensates the timed-out step too, because its outcome is unknown. Compensations retry up to MAX_COMPENSATION_ATTEMPTS, then the saga is Stuck. Processed message ids are recorded (Duplicate). Late replies and stale timers are Ignored. Command and reply ids are deterministic. SagaReply builds participant replies, and SagaRunner loads, transitions and commits, retrying on ConcurrentWrite. Worked example and tests: tests/saga_transfer, a two-cell wallet transfer covering happy path, rejection compensation, timeout compensation with tombstoned late credit, compensation-before-action, compensation retry to Stuck, dedupe, and restart survival on sqlite. Docs: docs/coordination-primitives.md. Refs [[tasks/gr-p6-coordination-primitives]] --- README.md | 8 + docs/coordination-primitives.md | 152 ++++++++ src/lib.rs | 7 +- src/saga/definition.rs | 121 ++++++ src/saga/error.rs | 49 +++ src/saga/message.rs | 293 +++++++++++++++ src/saga/mod.rs | 95 +++++ src/saga/runner.rs | 137 +++++++ src/saga/state.rs | 610 +++++++++++++++++++++++++++++++ tests/saga_transfer/main.rs | 627 ++++++++++++++++++++++++++++++++ 10 files changed, 2098 insertions(+), 1 deletion(-) create mode 100644 docs/coordination-primitives.md create mode 100644 src/saga/definition.rs create mode 100644 src/saga/error.rs create mode 100644 src/saga/message.rs create mode 100644 src/saga/mod.rs create mode 100644 src/saga/runner.rs create mode 100644 src/saga/state.rs create mode 100644 tests/saga_transfer/main.rs diff --git a/README.md b/README.md index 59a79bdde..14b59e4cd 100644 --- a/README.md +++ b/README.md @@ -1406,6 +1406,14 @@ not an atomic external effect plus publish. Aggregate decisions still use a transactional outbox. Bound external reads and make effects idempotent before using this pattern. +### Scheduled messages, sagas and fenced leases + +`OutboxMessage::deliver_at(at)` turns an outbox row into a durable timer that +no claim path delivers before `at`. Cross-cell workflows use the event-sourced +`Saga` process manager (`distributed::saga`). Single-owner work uses TTL +leases with monotonic fencing tokens (`distributed::lease`). See +[coordination primitives](docs/coordination-primitives.md). + ### Publishing the Outbox How a committed row reaches the bus depends on whether a bus is attached to the diff --git a/docs/coordination-primitives.md b/docs/coordination-primitives.md new file mode 100644 index 000000000..608a31b5c --- /dev/null +++ b/docs/coordination-primitives.md @@ -0,0 +1,152 @@ +# Coordination primitives: sagas, durable timers and fenced leases + +A cell has one atomic boundary. Work that spans cells, or must happen later, +or must be owned by exactly one process at a time needs explicit +coordination. Three primitives cover the common shapes: a zone transfer, an +encounter settlement with a deadline, a boss controller that must never run +twice. + +| Need | Primitive | Module | +|------|-----------|--------| +| Change state in two cells with rollback | Saga / process manager | `distributed::saga` | +| Run something at a time in the future, across restarts | `OutboxMessage::deliver_at` | `distributed::outbox` | +| One owner per key, with stale writers rejected | Lease with fencing token | `distributed::lease` | +| Deterministic time in tests | `Clock`, `ManualClock` | `distributed::clock` | + +All three are dependency-free in core. The SQL lease stores follow the +existing `sqlite` / `postgres` features. No new cargo feature was added and +default features are unchanged. + +## Durable timers: `deliver_at` + +```rust +let timer = OutboxMessage::create_to(id, "settle-encounter", "encounters", payload)? + .deliver_after(now, Duration::from_secs(10)); +repo.outbox(timer).commit(&mut encounter).await?; +``` + +A scheduled outbox row is committed with the change that arms it, so it is +exactly as durable as that change. Every claim path skips it until it is due: + +- the in-memory store (`OutboxMessage::is_claimable_at`); +- the SQLite and Postgres claim queries, which already filtered on the + `next_available_at` column. That column now stores `deliver_at` and falls + back to `created_at`, so **no schema change was needed** and existing rows + (and `None`) stay immediately deliverable; +- explicit-id claims (`ClaimOutboxMessages::for_ids`), so the after-commit + immediate publisher cannot bypass the schedule; +- the in-transaction pre-claim used when a repository has a publish hook but + no worker mailbox (aggregate commits and causal routes). Scheduled rows are + left pending. + +The drain worker (`OutboxDrainRunner`) picks a due row up on its next poll, +so a timer fires within one poll interval of its deadline. `release` (a +retry) resets availability to now, so a timer that failed to publish is +retried promptly instead of being re-delayed. `OutboxMessage.deliver_at` is +`#[serde(default)]`. + +## Leases with fencing tokens + +```rust +let lease = leases.acquire("boss:hydra", "zone-7", Duration::from_secs(15)).await?; +// every 5s +let lease = leases.renew(&lease, Duration::from_secs(15)).await?; // Err(Lost) => stop acting +// in the protected aggregate (same cell, same transaction as the write): +self.fence.admit("boss:hydra", cmd.fencing_token)?; // Err(StaleFence) => reject +``` + +- `acquire` gives a free, expired or released key to the caller with a token + strictly greater than any earlier token for that key. Re-acquiring a live + lease you already hold returns it unchanged (an idempotent retry). A key + held by someone else returns `LeaseError::Held`. +- `renew` extends a live lease and keeps its token. `release` ends it early. + The row is **kept**, with `expires_at = 0`, so the counter never resets. +- `Fence` is a serializable high-water mark to embed in the protected state. + It admits tokens greater than or equal to the newest one seen. This is the + authoritative check. `LeaseStore::check_fence` is only a point-in-time + advisory check. + +Backends: `InMemoryLeaseStore` (use a `ManualClock` in tests), +`SqliteLeaseStore` and `PostgresLeaseStore`. Every SQL operation is one +atomic conditional statement evaluated against the **database clock**. The +`coordination_leases` table comes from repository migration +`0010_coordination_leases` (inventory version 10), or from +`SqlxLeaseStore::migrate` for standalone pools. + +This is a sibling of `distributed::lock`, not an extension of it. The lock +module is `QueuedRepository`'s internal mutual-exclusion optimization. Its +`Lock` trait has no holder identity, renewal or token, and it deletes +`aggregate_locks` rows on release, which would reset a token. + +## Sagas + +A saga is an event-sourced aggregate, `Saga`, with one +stream per instance. The definition is pure. It lists the steps, says which +command performs each step and which command undoes it, and folds reply +payloads into the saga data. The framework owns the state machine. + +```text +start ─► dispatch(step 0) ─► reply ok ─► dispatch(step 1) ─► reply ok ─► Completed + │ │ + │ reply failed │ timeout (outcome unknown) + ▼ ▼ + compensate applied steps compensate applied steps + step 1 + in reverse ─► Compensated in reverse ─► Compensated + (or Stuck after MAX_COMPENSATION_ATTEMPTS) +``` + +Each transition returns outbox messages that are committed **with** the +saga's events: the participant command, plus a `saga-timeout` timer to the +saga's own `REPLY_TO` queue, scheduled with `deliver_at = now + step.timeout`. +A crash between deciding and sending is impossible. A timer for a step that +already finished arrives later and is `Ignored`. + +Participants answer with `SagaReply::from_outbox(&cmd)?.succeeded(..)` or +`.failed(reason)` and commit the reply with their own state change. Inbound +replies and timers become `SagaMessage::from_outbox` / `from_bus` and go to +`SagaRunner::handle`. Inside a `microsvc` handler you can also call +`Saga::handle` and commit with `ctx.repo().outbox(..)`. + +Guarantees and obligations: + +- **Idempotent.** The saga records every message id that changed its state, + so a redelivery is `Duplicate`. Late replies and superseded timers are + `Ignored`. Concurrent handlers are fenced by the saga stream's optimistic + version, and `SagaRunner` reloads and retries on `ConcurrentWrite`. +- **Deterministic ids.** Command ids are `type:saga:step:phase:attempt` and a + reply id is `:reply`. Participants dedupe on the command id + (an inbox receipt or aggregate state) and do not re-emit a reply on + redelivery. +- **A timeout means the outcome is unknown,** so the timed-out step is + compensated as well. Compensations must be idempotent and must tolerate + arriving *before* their action. The participant records a tombstone for + the saga id and rejects a late action. +- **`on_step_succeeded` is replayed,** so keep it deterministic. + +### Worked example + +`tests/saga_transfer/main.rs` moves value between wallets in two separate +cells. The `debit` step goes to the source cell (compensated by `refund`) and +the `credit` step goes to the target cell (compensated by `reverse_credit`). +A test network delivers outbox rows whose `deliver_at` is due on a +`ManualClock`, so timeouts fire without sleeping. The scenarios are: + +- the happy path, including an idempotent restart and ignored leftover timers; +- target rejection, where the debit is refunded; +- source rejection, where nothing needs compensating; +- target timeout, where both steps are compensated and the late credit is + neutralized; +- the compensation arriving before the late action, where the tombstone + rejects the credit; +- compensation timeouts that are retried and then marked `Stuck`; +- duplicate command delivery and duplicate replies; +- saga state and its timer surviving a restart on a SQLite file database. + +## Tests + +```sh +cargo test --features sqlite,postgres --test saga_transfer --test coordination_lease --test scheduled_outbox +cargo test --features sqlite --lib -- outbox lease clock +``` + +The Postgres cases skip when `DATABASE_URL` is unset (see `compose.yaml`). diff --git a/src/lib.rs b/src/lib.rs index bf00ae1c3..bbf82e32c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,6 +55,7 @@ pub mod projection; pub mod projection_protocol; pub mod queued_repo; pub mod read_model; +pub mod saga; pub mod snapshot; #[cfg(feature = "sqlite")] pub mod sqlite_repo; @@ -364,13 +365,17 @@ pub use lock::{PostgresLock, PostgresLockManager}; #[cfg(feature = "sqlite")] pub use lock::{SqliteLock, SqliteLockManager}; -// Coordination primitives: injectable clock and fenced leases. +// Coordination primitives: injectable clock, fenced leases, sagas. pub use clock::{Clock, ManualClock, SystemClock}; #[cfg(feature = "postgres")] pub use lease::PostgresLeaseStore; #[cfg(feature = "sqlite")] pub use lease::SqliteLeaseStore; pub use lease::{Fence, FencingToken, InMemoryLeaseStore, Lease, LeaseError, LeaseStore}; +pub use saga::{ + Saga, SagaCommand, SagaDefinition, SagaError, SagaMessage, SagaOutcome, SagaReply, SagaRunner, + SagaStatus, SagaStep, +}; // Outbox: commit concerns (aggregate + outbox in one commit). // diff --git a/src/saga/definition.rs b/src/saga/definition.rs new file mode 100644 index 000000000..bef69dd95 --- /dev/null +++ b/src/saga/definition.rs @@ -0,0 +1,121 @@ +use std::time::Duration; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +use super::SagaError; + +/// One forward step of a saga: a command sent to another cell, awaited for a +/// reply until `timeout` elapses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SagaStep { + /// Stable step name (persisted in events and message metadata). + pub name: &'static str, + /// How long to wait for the step's reply before treating it as failed + /// (outcome unknown → the step is compensated too). + pub timeout: Duration, + /// How long to wait for each compensation attempt's reply before retrying. + pub compensation_timeout: Duration, +} + +impl SagaStep { + /// A step whose compensation uses the same timeout. + pub const fn new(name: &'static str, timeout: Duration) -> Self { + Self { + name, + timeout, + compensation_timeout: timeout, + } + } + + /// Override the per-attempt compensation timeout. + pub const fn with_compensation_timeout(mut self, timeout: Duration) -> Self { + self.compensation_timeout = timeout; + self + } +} + +/// A command the saga sends to a participant cell. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SagaCommand { + /// Point-to-point destination (the participant cell's queue). + pub destination: String, + /// Command name (outbox `event_type` / bus message name). + pub command_type: String, + /// Encoded command payload. + pub payload: Vec, +} + +impl SagaCommand { + /// A command with a raw payload. + pub fn new( + destination: impl Into, + command_type: impl Into, + payload: Vec, + ) -> Self { + Self { + destination: destination.into(), + command_type: command_type.into(), + payload, + } + } + + /// A command with a JSON payload (what `microsvc` handlers decode with + /// `ctx.input`). + pub fn json( + destination: impl Into, + command_type: impl Into, + payload: &T, + ) -> Result { + let payload = serde_json::to_vec(payload) + .map_err(|err| SagaError::Definition(format!("encode saga command: {err}")))?; + Ok(Self::new(destination, command_type, payload)) + } +} + +/// Static description of a saga (process manager). +/// +/// The definition is pure: it maps the saga's data to the commands for each +/// step and compensation. The framework owns the state machine, persistence +/// (the [`Saga`](super::Saga) aggregate), timers and dedupe. +/// +/// Everything a definition returns must be a deterministic function of its +/// inputs — [`on_step_succeeded`](Self::on_step_succeeded) in particular runs +/// again on every replay. +pub trait SagaDefinition: Send + Sync + 'static { + /// Durable aggregate type of the saga streams (e.g. `"zone.transfer"`). + const SAGA_TYPE: &'static str; + /// Destination queue on which this saga receives replies and timers. + const REPLY_TO: &'static str; + /// Compensation attempts (dispatch + retries) before the saga is marked + /// [`Stuck`](super::SagaStatus::Stuck) for operator attention. + const MAX_COMPENSATION_ATTEMPTS: u32 = 5; + + /// The saga's own data (inputs plus anything folded in from replies). + type Data: Serialize + DeserializeOwned + Clone + Default + Send + Sync + 'static; + + /// Forward steps, executed in order. + fn steps() -> &'static [SagaStep]; + + /// The command that performs `step`. + fn action(step: &str, saga_id: &str, data: &Self::Data) -> Result; + + /// The command that undoes `step`, or `None` when the step needs no + /// compensation. Compensations must be idempotent **and** must tolerate + /// arriving before (or instead of) the action they undo — the participant + /// should record a tombstone so a late action is rejected. + fn compensation( + step: &str, + saga_id: &str, + data: &Self::Data, + ) -> Result, SagaError> { + let _ = (step, saga_id, data); + Ok(None) + } + + /// Fold a successful step's reply payload into the saga data. Replayed — + /// keep it deterministic. Default: ignore the output. + fn on_step_succeeded(step: &str, data: &mut Self::Data, output: &[u8]) { + let _ = (step, data, output); + } +} diff --git a/src/saga/error.rs b/src/saga/error.rs new file mode 100644 index 000000000..b4a43b866 --- /dev/null +++ b/src/saga/error.rs @@ -0,0 +1,49 @@ +use std::fmt; + +use crate::repository::RepositoryError; +use crate::EventRecordError; + +/// Saga failure. +#[derive(Debug)] +#[non_exhaustive] +pub enum SagaError { + /// The saga stream does not exist (message for an unknown saga). + NotFound { saga_id: String }, + /// `handle` on a saga that was never started. + NotStarted, + /// The definition produced an invalid step/command. + Definition(String), + /// A message lacked or had malformed saga metadata. + Malformed(String), + /// Event encode/decode failure. + Event(EventRecordError), + /// Persistence failure (including `ConcurrentWrite` after retries). + Repository(RepositoryError), +} + +impl fmt::Display for SagaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SagaError::NotFound { saga_id } => write!(f, "saga `{saga_id}` not found"), + SagaError::NotStarted => write!(f, "saga has not been started"), + SagaError::Definition(message) => write!(f, "saga definition error: {message}"), + SagaError::Malformed(message) => write!(f, "malformed saga message: {message}"), + SagaError::Event(err) => write!(f, "saga event error: {}", err.message), + SagaError::Repository(err) => write!(f, "saga repository error: {err}"), + } + } +} + +impl std::error::Error for SagaError {} + +impl From for SagaError { + fn from(err: EventRecordError) -> Self { + SagaError::Event(err) + } +} + +impl From for SagaError { + fn from(err: RepositoryError) -> Self { + SagaError::Repository(err) + } +} diff --git a/src/saga/message.rs b/src/saga/message.rs new file mode 100644 index 000000000..596ef2fb5 --- /dev/null +++ b/src/saga/message.rs @@ -0,0 +1,293 @@ +//! Saga wire envelope: metadata keys, inbound [`SagaMessage`] parsing and the +//! participant-side [`SagaReply`] builder. + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use super::SagaError; +use crate::outbox::OutboxMessage; + +/// Message name of a participant's reply to a saga command. +pub const SAGA_REPLY: &str = "saga-reply"; +/// Message name of a saga's own scheduled timeout. +pub const SAGA_TIMEOUT: &str = "saga-timeout"; + +/// Metadata key: saga aggregate type. +pub const META_SAGA_TYPE: &str = "saga-type"; +/// Metadata key: saga id. +pub const META_SAGA_ID: &str = "saga-id"; +/// Metadata key: step name. +pub const META_STEP: &str = "saga-step"; +/// Metadata key: [`SagaPhase`] (`action` / `compensation`). +pub const META_PHASE: &str = "saga-phase"; +/// Metadata key: dispatch attempt (1-based). +pub const META_ATTEMPT: &str = "saga-attempt"; +/// Metadata key: where replies must be sent. +pub const META_REPLY_TO: &str = "saga-reply-to"; +/// Metadata key: id of the command a reply/timeout belongs to. +pub const META_COMMAND_ID: &str = "saga-command-id"; +/// Metadata key on replies: `succeeded` / `failed`. +pub const META_OUTCOME: &str = "saga-outcome"; + +const OUTCOME_SUCCEEDED: &str = "succeeded"; +const OUTCOME_FAILED: &str = "failed"; + +/// Whether a dispatched command performs a step or undoes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum SagaPhase { + Action, + Compensation, +} + +impl SagaPhase { + pub fn as_str(self) -> &'static str { + match self { + SagaPhase::Action => "action", + SagaPhase::Compensation => "compensation", + } + } + + fn parse(value: &str) -> Result { + match value { + "action" => Ok(SagaPhase::Action), + "compensation" => Ok(SagaPhase::Compensation), + other => Err(SagaError::Malformed(format!( + "unknown saga phase `{other}`" + ))), + } + } +} + +/// What an inbound saga message reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SagaSignal { + /// The participant applied the command; `output` is its reply payload. + Succeeded { output: Vec }, + /// The participant rejected the command (a definitive "did not apply"). + Failed { reason: String }, + /// The saga's own timer fired before a reply arrived. + TimedOut, +} + +/// An inbound message addressed to a saga (a reply or a timeout). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SagaMessage { + /// Transport message id — the dedupe key. + pub message_id: String, + pub saga_type: String, + pub saga_id: String, + pub step: String, + pub phase: SagaPhase, + pub attempt: u32, + pub signal: SagaSignal, +} + +impl SagaMessage { + /// Whether a message name is one a saga consumes. + pub fn is_saga_message(name: &str) -> bool { + name == SAGA_REPLY || name == SAGA_TIMEOUT + } + + /// Parse from transport parts (works for outbox rows and bus messages). + pub fn from_parts<'a>( + message_id: &str, + name: &str, + metadata: impl IntoIterator, + payload: &[u8], + ) -> Result { + let metadata: HashMap<&str, &str> = metadata.into_iter().collect(); + let get = |key: &str| { + metadata + .get(key) + .copied() + .ok_or_else(|| SagaError::Malformed(format!("missing `{key}` metadata"))) + }; + if message_id.is_empty() { + return Err(SagaError::Malformed("saga message has no id".into())); + } + let signal = match name { + SAGA_TIMEOUT => SagaSignal::TimedOut, + SAGA_REPLY => match get(META_OUTCOME)? { + OUTCOME_SUCCEEDED => SagaSignal::Succeeded { + output: payload.to_vec(), + }, + OUTCOME_FAILED => SagaSignal::Failed { + reason: String::from_utf8_lossy(payload).into_owned(), + }, + other => { + return Err(SagaError::Malformed(format!( + "unknown saga outcome `{other}`" + ))) + } + }, + other => { + return Err(SagaError::Malformed(format!( + "`{other}` is not a saga message" + ))) + } + }; + let attempt = get(META_ATTEMPT)? + .parse::() + .map_err(|_| SagaError::Malformed("invalid saga attempt".into()))?; + Ok(Self { + message_id: message_id.to_string(), + saga_type: get(META_SAGA_TYPE)?.to_string(), + saga_id: get(META_SAGA_ID)?.to_string(), + step: get(META_STEP)?.to_string(), + phase: SagaPhase::parse(get(META_PHASE)?)?, + attempt, + signal, + }) + } + + /// Parse a delivered outbox row. + pub fn from_outbox(message: &OutboxMessage) -> Result { + Self::from_parts( + message.id(), + &message.event_type, + message + .metadata + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + &message.payload, + ) + } + + /// Parse a bus/transport message. + pub fn from_bus(message: &crate::bus::Message) -> Result { + let id = message + .id() + .ok_or_else(|| SagaError::Malformed("saga message has no id".into()))?; + Self::from_parts( + id, + message.name(), + message + .metadata + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + message.payload(), + ) + } +} + +/// Participant-side helper: build the reply to a saga command. +/// +/// The reply id is derived from the command id, so a participant that +/// processes the same command twice (at-least-once delivery) emits the same +/// reply id and the saga dedupes it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SagaReply { + command_id: String, + reply_to: String, + metadata: HashMap, +} + +impl SagaReply { + /// From a command's id and metadata (e.g. a received outbox row or bus + /// message). Fails when the command was not sent by a saga. + pub fn from_parts<'a>( + command_id: &str, + metadata: impl IntoIterator, + ) -> Result { + let mut carried = HashMap::new(); + for (key, value) in metadata { + if [ + META_SAGA_TYPE, + META_SAGA_ID, + META_STEP, + META_PHASE, + META_ATTEMPT, + META_REPLY_TO, + ] + .contains(&key) + { + carried.insert(key.to_string(), value.to_string()); + } + } + let reply_to = carried + .get(META_REPLY_TO) + .cloned() + .ok_or_else(|| SagaError::Malformed("command has no saga reply-to".into()))?; + if command_id.is_empty() { + return Err(SagaError::Malformed("saga command has no id".into())); + } + Ok(Self { + command_id: command_id.to_string(), + reply_to, + metadata: carried, + }) + } + + /// From a received outbox row. + pub fn from_outbox(command: &OutboxMessage) -> Result { + Self::from_parts( + command.id(), + command + .metadata + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + ) + } + + /// From a received bus message. + pub fn from_bus(command: &crate::bus::Message) -> Result { + let id = command + .id() + .ok_or_else(|| SagaError::Malformed("saga command has no id".into()))?; + Self::from_parts( + id, + command + .metadata + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + ) + } + + /// The command id this reply answers (useful as the participant's own + /// dedupe / tombstone key). + pub fn command_id(&self) -> &str { + &self.command_id + } + + /// Saga id the command belongs to. + pub fn saga_id(&self) -> Option<&str> { + self.metadata.get(META_SAGA_ID).map(String::as_str) + } + + /// "The command was applied" with a reply payload. + pub fn succeeded(&self, output: Vec) -> Result { + self.build(OUTCOME_SUCCEEDED, output) + } + + /// "The command was applied" with a JSON reply payload. + pub fn succeeded_json(&self, output: &T) -> Result { + let bytes = serde_json::to_vec(output) + .map_err(|err| SagaError::Malformed(format!("encode saga reply: {err}")))?; + self.succeeded(bytes) + } + + /// "The command was rejected" (definitively not applied). + pub fn failed(&self, reason: impl Into) -> Result { + self.build(OUTCOME_FAILED, reason.into().into_bytes()) + } + + fn build(&self, outcome: &str, payload: Vec) -> Result { + let mut message = OutboxMessage::create_to( + format!("{}:reply", self.command_id), + SAGA_REPLY, + self.reply_to.clone(), + payload, + )?; + for (key, value) in &self.metadata { + message.set_meta(key.clone(), value.clone()); + } + message.set_meta(META_COMMAND_ID, self.command_id.clone()); + message.set_meta(META_OUTCOME, outcome); + if let Some(saga_id) = self.saga_id() { + message.set_correlation_id(saga_id.to_string()); + } + message.set_causation_id(self.command_id.clone()); + Ok(message) + } +} diff --git a/src/saga/mod.rs b/src/saga/mod.rs new file mode 100644 index 000000000..76590ddce --- /dev/null +++ b/src/saga/mod.rs @@ -0,0 +1,95 @@ +//! Saga - event-sourced process managers for cross-cell workflows. +//! +//! A cell has one atomic boundary. Anything that must change state in two +//! cells (moving a player between zones, transferring a corpse's inventory, +//! settling an encounter across participants) is a **saga**: a sequence of +//! steps, each a command to one cell, with a compensating command per step +//! that undoes it if a later step fails. +//! +//! ## Model +//! +//! - A [`SagaDefinition`] is a pure description: ordered [`SagaStep`]s, the +//! [`SagaCommand`] for each step's action and (optional) compensation, and +//! how to fold reply payloads into the saga's `Data`. +//! - [`Saga`] is an ordinary event-sourced [`Aggregate`](crate::Aggregate) +//! (one stream per saga instance). Its events record every dispatch, reply, +//! failure and compensation, so a saga survives restarts and its history is +//! auditable. +//! - Every transition returns the outbox messages to commit **with** the +//! saga's events: the participant command plus a durable timeout timer +//! (an [`OutboxMessage`](crate::OutboxMessage) with +//! [`deliver_at`](crate::OutboxMessage::deliver_at())). A crash can never +//! lose a dispatched command or its timer. +//! - Participants reply with [`SagaReply`] (`succeeded` / `failed`), routed to +//! [`SagaDefinition::REPLY_TO`]. Replies and timers arrive as +//! [`SagaMessage`]s and are fed to [`Saga::handle`] / [`SagaRunner::handle`]. +//! +//! ## Semantics +//! +//! - **Forward**: step *n* succeeds → step *n+1* is dispatched; after the last +//! step the saga is [`Completed`](SagaStatus::Completed). +//! - **Rejection**: a `failed` reply means "definitely not applied"; the saga +//! compensates the previously applied steps in reverse order. +//! - **Timeout**: the outcome is unknown, so the timed-out step is +//! compensated *as well*. Compensations therefore must be idempotent and +//! must tolerate arriving before (or instead of) their action — the +//! participant records a tombstone keyed by saga id so a late action is +//! rejected. The worked example in `tests/saga_transfer` shows this. +//! - **Compensation retries**: a failed/timed-out compensation is +//! re-dispatched (new attempt, new timer) up to +//! [`SagaDefinition::MAX_COMPENSATION_ATTEMPTS`], then the saga is +//! [`Stuck`](SagaStatus::Stuck) for an operator. +//! - **Idempotency**: message ids that changed state are stored in the saga +//! ([`SagaOutcome::Duplicate`] on redelivery); late replies and superseded +//! timers are [`SagaOutcome::Ignored`]. Command ids are deterministic +//! (`type:id:step:phase:attempt`), so participants can dedupe with consumer +//! inbox receipts keyed by the command id, and reply ids derive from them. +//! - **Concurrency**: the saga stream's optimistic version is the fence; +//! [`SagaRunner`] reloads and retries on `ConcurrentWrite`. +//! +//! ## Example +//! +//! ```ignore +//! struct Transfer; +//! impl SagaDefinition for Transfer { +//! const SAGA_TYPE: &'static str = "bank.transfer"; +//! const REPLY_TO: &'static str = "transfer-saga"; +//! type Data = TransferData; +//! fn steps() -> &'static [SagaStep] { +//! const STEPS: &[SagaStep] = &[ +//! SagaStep::new("debit", Duration::from_secs(10)), +//! SagaStep::new("credit", Duration::from_secs(10)), +//! ]; +//! STEPS +//! } +//! fn action(step: &str, id: &str, d: &TransferData) -> Result { +//! match step { +//! "debit" => SagaCommand::json(&d.from_cell, "wallet.debit", &Move::new(id, d)), +//! _ => SagaCommand::json(&d.to_cell, "wallet.credit", &Move::new(id, d)), +//! } +//! } +//! fn compensation(step: &str, id: &str, d: &TransferData) +//! -> Result, SagaError> { /* refund / reverse */ } +//! } +//! +//! let runner = SagaRunner::<_, Transfer>::new(repo); +//! runner.start("t-1", data).await?; // commits saga + debit cmd + timer +//! runner.handle(&SagaMessage::from_bus(&msg)?).await?; // replies and timers +//! ``` +//! +//! See `docs/coordination-primitives.md` for the full walkthrough. + +mod definition; +mod error; +mod message; +mod runner; +mod state; + +pub use definition::{SagaCommand, SagaDefinition, SagaStep}; +pub use error::SagaError; +pub use message::{ + SagaMessage, SagaPhase, SagaReply, SagaSignal, META_ATTEMPT, META_COMMAND_ID, META_OUTCOME, + META_PHASE, META_REPLY_TO, META_SAGA_ID, META_SAGA_TYPE, META_STEP, SAGA_REPLY, SAGA_TIMEOUT, +}; +pub use runner::SagaRunner; +pub use state::{Saga, SagaCursor, SagaFailure, SagaOutcome, SagaStatus, SagaTransition}; diff --git a/src/saga/runner.rs b/src/saga/runner.rs new file mode 100644 index 000000000..ebc7bd8c3 --- /dev/null +++ b/src/saga/runner.rs @@ -0,0 +1,137 @@ +use crate::aggregate::{AggregateBuilder, AggregateRepository}; +use crate::clock::{Clock, SystemClock}; +use crate::repository::{GetStream, RepositoryError, TransactionalCommit}; + +use super::{Saga, SagaDefinition, SagaError, SagaMessage, SagaOutcome, SagaTransition}; + +/// Attempts before a persistent `ConcurrentWrite` is surfaced. +const CONCURRENT_WRITE_RETRIES: usize = 3; + +/// Load → transition → commit driver for a [`Saga`]. +/// +/// Each call loads the saga, applies one transition and commits the saga's +/// new events **together with** the commands and timers it emitted, in one +/// repository transaction. A concurrent handler of the same saga loses on the +/// stream version and is retried (the reload then sees the winner's state, +/// so a duplicate message becomes a no-op). +/// +/// Use an *unqueued* repository: correctness comes from optimistic stream +/// versions, and the runner does not hold `QueuedRepository` locks across a +/// no-op. Inside a `microsvc` handler with a queued repo, call +/// [`Saga::start`]/[`Saga::handle`] directly and commit with +/// `ctx.repo().outbox(..).commit(&mut saga)`. +pub struct SagaRunner { + repo: AggregateRepository>, + clock: C, +} + +impl SagaRunner { + /// A runner on the system clock. + pub fn new(repo: R) -> Self { + Self::with_clock(repo, SystemClock) + } +} + +impl SagaRunner { + /// A runner on an explicit clock (use a `ManualClock` in tests). + pub fn with_clock(repo: R, clock: C) -> Self { + Self { + repo: repo.aggregate::>(), + clock, + } + } + + /// The typed saga repository. + pub fn repository(&self) -> &AggregateRepository> { + &self.repo + } +} + +impl SagaRunner +where + R: GetStream + TransactionalCommit, + D: SagaDefinition, + C: Clock, +{ + /// Load a saga. + pub async fn get(&self, saga_id: &str) -> Result>, SagaError> { + Ok(self.repo.get(saga_id).await?) + } + + /// Start saga `saga_id` (idempotent: an existing saga yields + /// [`SagaOutcome::Duplicate`]). + pub async fn start(&self, saga_id: &str, data: D::Data) -> Result { + self.retrying(saga_id, true, |saga, now| { + saga.start(saga_id, data.clone(), now) + }) + .await + } + + /// Apply an inbound reply/timeout. + pub async fn handle(&self, message: &SagaMessage) -> Result { + if message.saga_type != D::SAGA_TYPE { + return Err(SagaError::Malformed(format!( + "message for saga type `{}` delivered to `{}`", + message.saga_type, + D::SAGA_TYPE + ))); + } + self.retrying(&message.saga_id, false, |saga, now| { + saga.handle(message, now) + }) + .await + } + + async fn retrying( + &self, + saga_id: &str, + create: bool, + mut transition: impl FnMut( + &mut Saga, + std::time::SystemTime, + ) -> Result, + ) -> Result { + let mut attempt = 0; + loop { + attempt += 1; + let mut saga = match self.repo.get(saga_id).await? { + Some(saga) => saga, + None if create => Saga::::new(), + None => { + return Err(SagaError::NotFound { + saga_id: saga_id.to_string(), + }) + } + }; + let result = transition(&mut saga, self.clock.now())?; + if result.outcome != SagaOutcome::Applied { + return Ok(result); + } + match self.commit(&mut saga, result.messages.clone()).await { + Ok(()) => return Ok(result), + Err(RepositoryError::ConcurrentWrite { .. }) + if attempt < CONCURRENT_WRITE_RETRIES => + { + continue + } + Err(err) => return Err(err.into()), + } + } + } + + async fn commit( + &self, + saga: &mut Saga, + messages: Vec, + ) -> Result<(), RepositoryError> { + let mut messages = messages.into_iter(); + let Some(first) = messages.next() else { + return self.repo.commit(saga).await; + }; + let mut commit = self.repo.outbox(first); + for message in messages { + commit = commit.outbox(message); + } + commit.commit(saga).await.map(|_| ()) + } +} diff --git a/src/saga/state.rs b/src/saga/state.rs new file mode 100644 index 000000000..23887dcbe --- /dev/null +++ b/src/saga/state.rs @@ -0,0 +1,610 @@ +//! The [`Saga`] aggregate: an event-sourced process manager. + +use std::collections::BTreeSet; +use std::fmt; +use std::marker::PhantomData; +use std::time::SystemTime; + +use serde::{Deserialize, Serialize}; + +use super::message::{ + SagaMessage, SagaPhase, SagaSignal, META_ATTEMPT, META_COMMAND_ID, META_PHASE, META_REPLY_TO, + META_SAGA_ID, META_SAGA_TYPE, META_STEP, SAGA_TIMEOUT, +}; +use super::{SagaDefinition, SagaError}; +use crate::aggregate::Aggregate; +use crate::entity::{Entity, EventRecord}; +use crate::outbox::OutboxMessage; + +/// Lifecycle of a saga. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SagaStatus { + /// No `started` event yet. + #[default] + NotStarted, + /// Executing forward steps. + Running, + /// A step failed or timed out; undoing completed steps in reverse. + Compensating, + /// Every step succeeded. + Completed, + /// A step failed and every applied step was compensated. + Compensated, + /// A compensation exhausted its attempts; needs operator attention. + Stuck, +} + +impl SagaStatus { + /// Completed, compensated or stuck: no further messages are acted on. + pub fn is_terminal(self) -> bool { + matches!( + self, + SagaStatus::Completed | SagaStatus::Compensated | SagaStatus::Stuck + ) + } +} + +/// Why the forward path stopped. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SagaFailure { + pub step: String, + pub reason: String, + pub timed_out: bool, +} + +/// The command currently awaited. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SagaCursor { + pub step: u32, + pub phase: SagaPhase, + pub attempt: u32, + pub deadline: SystemTime, +} + +/// Persisted saga events. Event names are `saga.`; payloads are the +/// bitcode-encoded variant. +#[derive(Clone, Debug, Serialize, Deserialize)] +enum SagaEvent { + Started { + data: T, + }, + Dispatched { + cursor: SagaCursor, + }, + StepSucceeded { + step: u32, + message_id: String, + output: Vec, + }, + StepFailed { + step: u32, + message_id: String, + reason: String, + timed_out: bool, + }, + CompensationSucceeded { + step: u32, + message_id: String, + }, + CompensationFailed { + step: u32, + message_id: String, + reason: String, + }, + Completed, + Compensated, + Stuck { + reason: String, + }, +} + +impl SagaEvent { + fn name(&self) -> &'static str { + match self { + SagaEvent::Started { .. } => "saga.started", + SagaEvent::Dispatched { .. } => "saga.dispatched", + SagaEvent::StepSucceeded { .. } => "saga.step_succeeded", + SagaEvent::StepFailed { .. } => "saga.step_failed", + SagaEvent::CompensationSucceeded { .. } => "saga.compensation_succeeded", + SagaEvent::CompensationFailed { .. } => "saga.compensation_failed", + SagaEvent::Completed => "saga.completed", + SagaEvent::Compensated => "saga.compensated", + SagaEvent::Stuck { .. } => "saga.stuck", + } + } +} + +/// How a message was handled. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SagaOutcome { + /// New events were recorded (and possibly commands/timers emitted). + Applied, + /// This message id was already processed: nothing to do, ack it. + Duplicate, + /// Stale or irrelevant (late reply, superseded timer, terminal saga): ack it. + Ignored, +} + +/// Result of a saga transition: commit the aggregate together with +/// `messages` (commands to participants and the saga's own timers) in one +/// transaction. +#[derive(Debug)] +pub struct SagaTransition { + pub outcome: SagaOutcome, + pub messages: Vec, +} + +impl SagaTransition { + fn unchanged(outcome: SagaOutcome) -> Self { + Self { + outcome, + messages: Vec::new(), + } + } +} + +/// An event-sourced saga / process manager for definition `D`. +/// +/// `Saga` is an ordinary [`Aggregate`]: load and commit it with any +/// repository (`repo.aggregate::>()`). Its methods record events +/// and *return* the outbox messages to commit alongside them; commit both in +/// one batch (`repo.outbox(..).commit(&mut saga)`, or use +/// [`SagaRunner`](super::SagaRunner) which does exactly that). +/// +/// Idempotency: every reply/timeout message id that changed state is stored +/// in the saga, so a redelivery is reported as [`SagaOutcome::Duplicate`] +/// and emits nothing. Optimistic stream versions fence concurrent handlers. +pub struct Saga { + entity: Entity, + data: D::Data, + status: SagaStatus, + cursor: Option, + /// Steps that took (or may have taken) effect, oldest first — the + /// compensation stack. + applied: Vec, + failure: Option, + processed: BTreeSet, + _definition: PhantomData D>, +} + +impl Default for Saga { + fn default() -> Self { + Self { + entity: Entity::default(), + data: D::Data::default(), + status: SagaStatus::NotStarted, + cursor: None, + applied: Vec::new(), + failure: None, + processed: BTreeSet::new(), + _definition: PhantomData, + } + } +} + +impl fmt::Debug for Saga { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Saga") + .field("type", &D::SAGA_TYPE) + .field("id", &self.entity.id()) + .field("status", &self.status) + .field("cursor", &self.cursor) + .field("applied", &self.applied) + .field("failure", &self.failure) + .finish() + } +} + +impl Aggregate for Saga { + type ReplayError = SagaError; + + fn aggregate_type() -> &'static str { + D::SAGA_TYPE + } + + fn entity(&self) -> &Entity { + &self.entity + } + + fn entity_mut(&mut self) -> &mut Entity { + &mut self.entity + } + + fn replay_event(&mut self, event: &EventRecord) -> Result<(), SagaError> { + let event: SagaEvent = event.decode()?; + self.apply(event); + Ok(()) + } +} + +impl Saga { + pub fn new() -> Self { + Self::default() + } + + pub fn id(&self) -> &str { + self.entity.id() + } + + pub fn status(&self) -> SagaStatus { + self.status + } + + pub fn data(&self) -> &D::Data { + &self.data + } + + /// The command currently awaited, if any. + pub fn cursor(&self) -> Option<&SagaCursor> { + self.cursor.as_ref() + } + + /// Why the forward path stopped, once it has. + pub fn failure(&self) -> Option<&SagaFailure> { + self.failure.as_ref() + } + + /// Names of the steps currently on the compensation stack. + pub fn applied_steps(&self) -> Vec<&'static str> { + self.applied + .iter() + .filter_map(|index| D::steps().get(*index as usize).map(|step| step.name)) + .collect() + } + + /// Whether `message_id` has already been processed. + pub fn has_processed(&self, message_id: &str) -> bool { + self.processed.contains(message_id) + } + + // --------------------------------------------------------------------- + // Commands + // --------------------------------------------------------------------- + + /// Start the saga and dispatch its first step. Starting an already + /// started saga is a no-op [`SagaOutcome::Duplicate`]. + pub fn start( + &mut self, + saga_id: impl Into, + data: D::Data, + now: SystemTime, + ) -> Result { + if self.status != SagaStatus::NotStarted { + return Ok(SagaTransition::unchanged(SagaOutcome::Duplicate)); + } + let saga_id = saga_id.into(); + if saga_id.is_empty() { + return Err(SagaError::Definition("saga id must not be empty".into())); + } + self.entity.set_id(&saga_id); + self.entity.set_correlation_id(saga_id); + let mut messages = Vec::new(); + self.record(SagaEvent::Started { data })?; + self.advance_from(0, now, &mut messages)?; + Ok(SagaTransition { + outcome: SagaOutcome::Applied, + messages, + }) + } + + /// React to a reply or timeout. See [`SagaOutcome`] for the no-op cases. + pub fn handle( + &mut self, + message: &SagaMessage, + now: SystemTime, + ) -> Result { + if self.status == SagaStatus::NotStarted { + return Err(SagaError::NotStarted); + } + if message.saga_type != D::SAGA_TYPE || message.saga_id != self.id() { + return Err(SagaError::Malformed(format!( + "message for {}/{} delivered to {}/{}", + message.saga_type, + message.saga_id, + D::SAGA_TYPE, + self.id() + ))); + } + if self.processed.contains(&message.message_id) { + return Ok(SagaTransition::unchanged(SagaOutcome::Duplicate)); + } + if self.status.is_terminal() { + return Ok(SagaTransition::unchanged(SagaOutcome::Ignored)); + } + let Some(cursor) = self.cursor.clone() else { + return Ok(SagaTransition::unchanged(SagaOutcome::Ignored)); + }; + let Some(step) = step_index::(&message.step) else { + return Err(SagaError::Malformed(format!( + "unknown saga step `{}`", + message.step + ))); + }; + if step != cursor.step || message.phase != cursor.phase { + // A late reply/timer for a step we already moved past. + return Ok(SagaTransition::unchanged(SagaOutcome::Ignored)); + } + let current_attempt = message.attempt == cursor.attempt; + let mut messages = Vec::new(); + let id = message.message_id.clone(); + match (cursor.phase, &message.signal) { + (SagaPhase::Action, SagaSignal::Succeeded { output }) => { + self.record(SagaEvent::StepSucceeded { + step, + message_id: id, + output: output.clone(), + })?; + self.advance_from(step as usize + 1, now, &mut messages)?; + } + (SagaPhase::Action, SagaSignal::Failed { reason }) if current_attempt => { + self.record(SagaEvent::StepFailed { + step, + message_id: id, + reason: reason.clone(), + timed_out: false, + })?; + self.compensate_next(now, &mut messages)?; + } + (SagaPhase::Action, SagaSignal::TimedOut) if current_attempt => { + self.record(SagaEvent::StepFailed { + step, + message_id: id, + reason: format!("step `{}` timed out", message.step), + timed_out: true, + })?; + self.compensate_next(now, &mut messages)?; + } + (SagaPhase::Compensation, SagaSignal::Succeeded { .. }) => { + self.record(SagaEvent::CompensationSucceeded { + step, + message_id: id, + })?; + self.compensate_next(now, &mut messages)?; + } + (SagaPhase::Compensation, SagaSignal::Failed { reason }) if current_attempt => { + self.compensation_failed(step, id, reason.clone(), &cursor, now, &mut messages)?; + } + (SagaPhase::Compensation, SagaSignal::TimedOut) if current_attempt => { + let reason = format!("compensation of `{}` timed out", message.step); + self.compensation_failed(step, id, reason, &cursor, now, &mut messages)?; + } + // Failure/timeout of a superseded attempt. + _ => return Ok(SagaTransition::unchanged(SagaOutcome::Ignored)), + } + Ok(SagaTransition { + outcome: SagaOutcome::Applied, + messages, + }) + } + + // --------------------------------------------------------------------- + // Transitions + // --------------------------------------------------------------------- + + /// Dispatch step `next`, or complete when there is none. + fn advance_from( + &mut self, + next: usize, + now: SystemTime, + messages: &mut Vec, + ) -> Result<(), SagaError> { + let Some(step) = D::steps().get(next) else { + return self.record(SagaEvent::Completed); + }; + let command = D::action(step.name, self.id(), &self.data)?; + self.dispatch(next as u32, SagaPhase::Action, 1, command, now, messages) + } + + /// Dispatch the next compensation from the stack, or finish compensating. + fn compensate_next( + &mut self, + now: SystemTime, + messages: &mut Vec, + ) -> Result<(), SagaError> { + for &index in self.applied.clone().iter().rev() { + let step = &D::steps()[index as usize]; + if let Some(command) = D::compensation(step.name, self.id(), &self.data)? { + return self.dispatch(index, SagaPhase::Compensation, 1, command, now, messages); + } + } + self.record(SagaEvent::Compensated) + } + + fn compensation_failed( + &mut self, + step: u32, + message_id: String, + reason: String, + cursor: &SagaCursor, + now: SystemTime, + messages: &mut Vec, + ) -> Result<(), SagaError> { + self.record(SagaEvent::CompensationFailed { + step, + message_id, + reason: reason.clone(), + })?; + if cursor.attempt >= D::MAX_COMPENSATION_ATTEMPTS { + return self.record(SagaEvent::Stuck { reason }); + } + let name = D::steps()[step as usize].name; + let command = D::compensation(name, self.id(), &self.data)?.ok_or_else(|| { + SagaError::Definition(format!("compensation for `{name}` disappeared")) + })?; + self.dispatch( + step, + SagaPhase::Compensation, + cursor.attempt + 1, + command, + now, + messages, + ) + } + + /// Record a dispatch and emit the command plus its durable timeout timer. + fn dispatch( + &mut self, + step: u32, + phase: SagaPhase, + attempt: u32, + command: super::SagaCommand, + now: SystemTime, + messages: &mut Vec, + ) -> Result<(), SagaError> { + let definition = &D::steps()[step as usize]; + let timeout = match phase { + SagaPhase::Action => definition.timeout, + SagaPhase::Compensation => definition.compensation_timeout, + }; + let deadline = now + .checked_add(timeout) + .ok_or_else(|| SagaError::Definition("saga step timeout overflows".into()))?; + let command_id = format!( + "{}:{}:{}:{}:{}", + D::SAGA_TYPE, + self.id(), + definition.name, + phase.as_str(), + attempt + ); + let saga_id = self.id().to_string(); + let metadata = [ + (META_SAGA_TYPE, D::SAGA_TYPE.to_string()), + (META_SAGA_ID, saga_id.clone()), + (META_STEP, definition.name.to_string()), + (META_PHASE, phase.as_str().to_string()), + (META_ATTEMPT, attempt.to_string()), + (META_REPLY_TO, D::REPLY_TO.to_string()), + ]; + + let mut outbound = OutboxMessage::create_to( + command_id.clone(), + command.command_type, + command.destination, + command.payload, + )?; + let mut timer = OutboxMessage::create_to( + format!("{command_id}:timeout"), + SAGA_TIMEOUT, + D::REPLY_TO, + Vec::new(), + )? + .deliver_at(deadline); + for message in [&mut outbound, &mut timer] { + for (key, value) in &metadata { + message.set_meta(*key, value.clone()); + } + message.set_correlation_id(saga_id.clone()); + } + timer.set_meta(META_COMMAND_ID, command_id); + + self.record(SagaEvent::Dispatched { + cursor: SagaCursor { + step, + phase, + attempt, + deadline, + }, + })?; + messages.push(outbound); + messages.push(timer); + Ok(()) + } + + // --------------------------------------------------------------------- + // Event recording / folding + // --------------------------------------------------------------------- + + fn record(&mut self, event: SagaEvent) -> Result<(), SagaError> { + self.entity.digest(event.name(), &event)?; + self.apply(event); + Ok(()) + } + + /// Pure state fold, shared by live recording and replay. + fn apply(&mut self, event: SagaEvent) { + match event { + SagaEvent::Started { data } => { + self.data = data; + self.status = SagaStatus::Running; + } + SagaEvent::Dispatched { cursor } => { + if cursor.phase == SagaPhase::Compensation { + self.status = SagaStatus::Compensating; + // Steps above this one had no compensation; drop them. + if let Some(position) = self.applied.iter().rposition(|s| *s == cursor.step) { + self.applied.truncate(position + 1); + } + } + self.cursor = Some(cursor); + } + SagaEvent::StepSucceeded { + step, + message_id, + output, + } => { + if let Some(definition) = D::steps().get(step as usize) { + D::on_step_succeeded(definition.name, &mut self.data, &output); + } + self.applied.push(step); + self.processed.insert(message_id); + self.cursor = None; + } + SagaEvent::StepFailed { + step, + message_id, + reason, + timed_out, + } => { + // A timed-out step may still have applied: compensate it too. + if timed_out { + self.applied.push(step); + } + self.failure = Some(SagaFailure { + step: D::steps() + .get(step as usize) + .map(|s| s.name.to_string()) + .unwrap_or_default(), + reason, + timed_out, + }); + self.processed.insert(message_id); + self.status = SagaStatus::Compensating; + self.cursor = None; + } + SagaEvent::CompensationSucceeded { step, message_id } => { + if let Some(position) = self.applied.iter().rposition(|s| *s == step) { + self.applied.truncate(position); + } + self.processed.insert(message_id); + self.cursor = None; + } + SagaEvent::CompensationFailed { message_id, .. } => { + self.processed.insert(message_id); + } + SagaEvent::Completed => { + self.status = SagaStatus::Completed; + self.cursor = None; + } + SagaEvent::Compensated => { + self.status = SagaStatus::Compensated; + self.applied.clear(); + self.cursor = None; + } + SagaEvent::Stuck { reason } => { + self.status = SagaStatus::Stuck; + if let Some(failure) = &mut self.failure { + failure.reason = format!("{}; {reason}", failure.reason); + } + self.cursor = None; + } + } + } +} + +fn step_index(name: &str) -> Option { + D::steps() + .iter() + .position(|step| step.name == name) + .map(|index| index as u32) +} diff --git a/tests/saga_transfer/main.rs b/tests/saga_transfer/main.rs new file mode 100644 index 000000000..fbaf4c399 --- /dev/null +++ b/tests/saga_transfer/main.rs @@ -0,0 +1,627 @@ +//! Worked example: a two-cell transfer saga. +//! +//! Two wallets live in two *different* cells (separate repositories — no +//! shared transaction). Moving value between them is a saga: +//! +//! 1. `debit` → source cell (compensation: `refund`) +//! 2. `credit` → target cell (compensation: `reverse_credit`) +//! +//! A target rejection compensates the debit; a target timeout compensates +//! both (the credit may have applied), and participants tombstone a +//! compensated transfer so a late action is rejected. Time is a +//! `ManualClock`; the test "network" delivers outbox rows whose `deliver_at` +//! is due on that clock, so timeouts fire without sleeping. + +#[cfg(feature = "sqlite")] +#[path = "../support/sqlite.rs"] +mod sqlite_support; + +use std::collections::{BTreeSet, HashSet}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime}; + +use serde::{Deserialize, Serialize}; + +use distributed::saga::SagaCursor; +use distributed::{ + sourced, AggregateBuilder, AggregateRepository, ClaimOutboxMessages, Entity, + InMemoryOutboxStore, InMemoryRepository, ManualClock, OutboxClaimRef, OutboxMessage, + OutboxStore, Saga, SagaCommand, SagaDefinition, SagaError, SagaMessage, SagaOutcome, SagaReply, + SagaRunner, SagaStatus, SagaStep, +}; + +// =========================================================================== +// Participant domain: a wallet (one per cell) +// =========================================================================== + +#[derive(Default)] +pub struct Wallet { + pub entity: Entity, + balance: i64, + accepts_credit: bool, + /// Transfers whose action applied here (dedupe). + applied: BTreeSet, + /// Compensated transfers (tombstones: a late action is rejected). + cancelled: BTreeSet, + /// Saga command ids already handled (the participant's dedupe record; + /// a consumer inbox receipt keyed by the command id works the same way). + handled: BTreeSet, +} + +#[allow(dead_code)] +#[sourced(entity, aggregate_type = "example.wallet")] +impl Wallet { + #[event("opened")] + pub fn open(&mut self, id: String, balance: i64, accepts_credit: bool) { + self.entity.set_id(&id); + self.balance = balance; + self.accepts_credit = accepts_credit; + } + + #[event("moved")] + pub fn moved(&mut self, command: String, transfer: String, delta: i64) { + self.balance += delta; + self.applied.insert(transfer); + self.handled.insert(command); + } + + #[event("cancelled")] + pub fn cancelled(&mut self, command: String, transfer: String, delta: i64) { + self.balance += delta; + self.applied.remove(&transfer); + self.cancelled.insert(transfer); + self.handled.insert(command); + } + + #[event("rejected")] + pub fn rejected(&mut self, command: String) { + self.handled.insert(command); + } + + #[event("acknowledged")] + pub fn acknowledged(&mut self, command: String) { + self.handled.insert(command); + } + + pub fn balance(&self) -> i64 { + self.balance + } +} + +#[derive(Serialize, Deserialize)] +struct MoveCmd { + transfer: String, + wallet: String, + amount: i64, +} + +// =========================================================================== +// The saga definition +// =========================================================================== + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct TransferData { + from: String, + to: String, + amount: i64, + /// Folded in from the credit reply (shows `on_step_succeeded`). + credit_receipt: Option, +} + +pub struct Transfer; + +const SOURCE_CELL: &str = "source-cell"; +const TARGET_CELL: &str = "target-cell"; + +impl SagaDefinition for Transfer { + const SAGA_TYPE: &'static str = "example.transfer"; + const REPLY_TO: &'static str = "transfer-saga"; + const MAX_COMPENSATION_ATTEMPTS: u32 = 3; + type Data = TransferData; + + fn steps() -> &'static [SagaStep] { + const STEPS: &[SagaStep] = &[ + SagaStep::new("debit", Duration::from_secs(10)), + SagaStep::new("credit", Duration::from_secs(10)), + ]; + STEPS + } + + fn action(step: &str, saga_id: &str, data: &TransferData) -> Result { + let (cell, kind, wallet) = match step { + "debit" => (SOURCE_CELL, "wallet.debit", &data.from), + "credit" => (TARGET_CELL, "wallet.credit", &data.to), + other => return Err(SagaError::Definition(format!("unknown step {other}"))), + }; + SagaCommand::json( + cell, + kind, + &MoveCmd { + transfer: saga_id.into(), + wallet: wallet.clone(), + amount: data.amount, + }, + ) + } + + fn compensation( + step: &str, + saga_id: &str, + data: &TransferData, + ) -> Result, SagaError> { + let (cell, kind, wallet) = match step { + "debit" => (SOURCE_CELL, "wallet.refund", &data.from), + "credit" => (TARGET_CELL, "wallet.reverse_credit", &data.to), + other => return Err(SagaError::Definition(format!("unknown step {other}"))), + }; + SagaCommand::json( + cell, + kind, + &MoveCmd { + transfer: saga_id.into(), + wallet: wallet.clone(), + amount: data.amount, + }, + ) + .map(Some) + } + + fn on_step_succeeded(step: &str, data: &mut TransferData, output: &[u8]) { + if step == "credit" { + data.credit_receipt = Some(String::from_utf8_lossy(output).into_owned()); + } + } +} + +// =========================================================================== +// Participant handler: one cell, one atomic commit (wallet + reply) +// =========================================================================== + +struct Cell { + wallets: AggregateRepository, + outbox: InMemoryOutboxStore, +} + +impl Cell { + fn new() -> Self { + let repo = InMemoryRepository::new(); + Self { + outbox: repo.outbox_store(), + wallets: repo.aggregate::(), + } + } + + async fn open(&self, id: &str, balance: i64, accepts_credit: bool) { + let mut wallet = Wallet::default(); + wallet.open(id.into(), balance, accepts_credit).unwrap(); + self.wallets.commit(&mut wallet).await.unwrap(); + } + + async fn balance(&self, id: &str) -> i64 { + self.wallets.get(id).await.unwrap().unwrap().balance() + } + + async fn handle(&self, command: &OutboxMessage) { + let reply = SagaReply::from_outbox(command).unwrap(); + let cmd: MoveCmd = serde_json::from_slice(&command.payload).unwrap(); + let mut wallet = self.wallets.get(&cmd.wallet).await.unwrap().unwrap(); + if wallet.handled.contains(command.id()) { + return; // redelivery: effects and reply were committed the first time + } + let t = cmd.transfer.clone(); + let c = command.id().to_string(); + let outcome = match command.event_type.as_str() { + "wallet.debit" | "wallet.credit" => { + let debit = command.event_type == "wallet.debit"; + if wallet.cancelled.contains(&t) { + Err("transfer was cancelled") + } else if debit && wallet.balance < cmd.amount { + Err("insufficient funds") + } else if !debit && !wallet.accepts_credit { + Err("wallet does not accept credits") + } else { + let delta = if debit { -cmd.amount } else { cmd.amount }; + wallet.moved(c.clone(), t, delta).unwrap(); + Ok(()) + } + } + "wallet.refund" | "wallet.reverse_credit" => { + if !wallet.cancelled.contains(&t) { + let delta = match (wallet.applied.contains(&t), command.event_type.as_str()) { + (false, _) => 0, // tombstone only: action never applied + (true, "wallet.refund") => cmd.amount, + (true, _) => -cmd.amount, + }; + wallet.cancelled(c.clone(), t, delta).unwrap(); + } else { + wallet.acknowledged(c.clone()).unwrap(); + } + Ok(()) + } + other => panic!("unexpected command {other}"), + }; + let reply = match outcome { + Ok(()) => reply.succeeded(format!("receipt:{c}").into_bytes()), + Err(reason) => { + wallet.rejected(c).unwrap(); + reply.failed(reason) + } + } + .unwrap(); + self.wallets + .outbox(reply) + .commit(&mut wallet) + .await + .unwrap(); + } +} + +// =========================================================================== +// The test "network" +// =========================================================================== + +struct World { + clock: ManualClock, + saga: SagaRunner, + saga_outbox: InMemoryOutboxStore, + source: Cell, + target: Cell, + /// Destinations that are currently unreachable (messages stay queued). + down: Mutex>, +} + +impl World { + async fn new(target_accepts_credit: bool) -> Self { + // Start the manual clock in the past so the in-memory store's + // wall-clock claim never hides a row the manual clock says is due. + let clock = ManualClock::new(SystemTime::now() - Duration::from_secs(3600)); + let saga_repo = InMemoryRepository::new(); + let world = Self { + saga_outbox: saga_repo.outbox_store(), + saga: SagaRunner::with_clock(saga_repo, clock.clone()), + clock, + source: Cell::new(), + target: Cell::new(), + down: Mutex::new(HashSet::new()), + }; + world.source.open("alice", 100, true).await; + world.target.open("bob", 0, target_accepts_credit).await; + world + } + + fn data(amount: i64) -> TransferData { + TransferData { + from: "alice".into(), + to: "bob".into(), + amount, + credit_receipt: None, + } + } + + fn set_down(&self, destination: &'static str, down: bool) { + let mut set = self.down.lock().unwrap(); + if down { + set.insert(destination); + } else { + set.remove(destination); + } + } + + /// Claim every due, reachable row from one outbox. + async fn take_due(&self, store: &InMemoryOutboxStore) -> Vec { + let now = distributed::Clock::now(&self.clock); + let down = self.down.lock().unwrap().clone(); + let ids: Vec = store + .pending(1000) + .await + .unwrap() + .into_iter() + .filter(|m| m.is_due_at(now)) + .filter(|m| !down.contains(m.destination.as_deref().unwrap_or_default())) + .map(|m| m.id().to_string()) + .collect(); + if ids.is_empty() { + return Vec::new(); + } + let claimed = store + .claim(ClaimOutboxMessages::for_ids( + "net", + ids, + Duration::from_secs(60), + )) + .await + .unwrap(); + for message in &claimed { + store + .complete(&OutboxClaimRef::from_message(message).unwrap()) + .await + .unwrap(); + } + claimed + } + + /// Deliver until quiescent; returns saga outcomes observed. + async fn pump(&self) -> Vec { + let mut outcomes = Vec::new(); + loop { + let mut batch = Vec::new(); + for store in [&self.saga_outbox, &self.source.outbox, &self.target.outbox] { + batch.extend(self.take_due(store).await); + } + if batch.is_empty() { + return outcomes; + } + for message in batch { + match message.destination.as_deref() { + Some(SOURCE_CELL) => self.source.handle(&message).await, + Some(TARGET_CELL) => self.target.handle(&message).await, + Some(Transfer::REPLY_TO) => { + let saga_message = SagaMessage::from_outbox(&message).unwrap(); + outcomes.push(self.saga.handle(&saga_message).await.unwrap().outcome); + } + other => panic!("no route for {other:?}"), + } + } + } + } + + async fn saga_state(&self, id: &str) -> Saga { + self.saga.get(id).await.unwrap().unwrap() + } + + async fn balances(&self) -> (i64, i64) { + ( + self.source.balance("alice").await, + self.target.balance("bob").await, + ) + } +} + +// =========================================================================== +// Scenarios +// =========================================================================== + +#[tokio::test] +async fn happy_path_moves_value_between_cells() { + let world = World::new(true).await; + let started = world.saga.start("t-1", World::data(30)).await.unwrap(); + assert_eq!(started.outcome, SagaOutcome::Applied); + // Debit command + its durable timeout timer. + assert_eq!(started.messages.len(), 2); + assert!(started.messages[1].deliver_at.is_some()); + + world.pump().await; + let saga = world.saga_state("t-1").await; + assert_eq!(saga.status(), SagaStatus::Completed); + assert_eq!(world.balances().await, (70, 30)); + assert!(saga + .data() + .credit_receipt + .as_deref() + .unwrap() + .contains("credit")); + + // Starting again is idempotent. + let again = world.saga.start("t-1", World::data(30)).await.unwrap(); + assert_eq!(again.outcome, SagaOutcome::Duplicate); + + // The leftover timers fire later and are ignored. + world.clock.advance(Duration::from_secs(60)); + let outcomes = world.pump().await; + assert_eq!(outcomes, vec![SagaOutcome::Ignored, SagaOutcome::Ignored]); + assert_eq!(world.balances().await, (70, 30)); +} + +#[tokio::test] +async fn target_rejection_compensates_the_debit() { + let world = World::new(false).await; + world.saga.start("t-2", World::data(40)).await.unwrap(); + world.pump().await; + + let saga = world.saga_state("t-2").await; + assert_eq!(saga.status(), SagaStatus::Compensated); + let failure = saga.failure().unwrap(); + assert_eq!(failure.step, "credit"); + assert!(!failure.timed_out); + assert!(failure.reason.contains("does not accept")); + assert_eq!(world.balances().await, (100, 0), "debit was refunded"); +} + +#[tokio::test] +async fn source_rejection_needs_no_compensation() { + let world = World::new(true).await; + world.saga.start("t-3", World::data(500)).await.unwrap(); + world.pump().await; + let saga = world.saga_state("t-3").await; + assert_eq!(saga.status(), SagaStatus::Compensated); + assert_eq!(saga.failure().unwrap().step, "debit"); + assert_eq!(world.balances().await, (100, 0)); +} + +#[tokio::test] +async fn target_timeout_compensates_and_tombstones_late_credit() { + let world = World::new(true).await; + world.set_down(TARGET_CELL, true); + world.saga.start("t-4", World::data(25)).await.unwrap(); + world.pump().await; + + // Debit applied, credit stuck in the target's queue. + let saga = world.saga_state("t-4").await; + assert_eq!(saga.status(), SagaStatus::Running); + let SagaCursor { step, attempt, .. } = saga.cursor().unwrap().clone(); + assert_eq!((step, attempt), (1, 1)); + assert_eq!(world.balances().await.0, 75); + + // No reply within 10s: the durable timer fires (manual clock, no sleep). + world.clock.advance(Duration::from_secs(9)); + world.pump().await; + assert_eq!(world.saga_state("t-4").await.status(), SagaStatus::Running); + world.clock.advance(Duration::from_secs(2)); + world.pump().await; + + let saga = world.saga_state("t-4").await; + assert_eq!(saga.status(), SagaStatus::Compensating); + assert!(saga.failure().unwrap().timed_out); + // Outcome unknown: both steps are on the compensation stack. + assert_eq!(saga.applied_steps(), vec!["debit", "credit"]); + + // The target comes back. Its queue holds the late credit *and* the + // reverse_credit compensation; whichever order they run in, the + // tombstone keeps the books balanced. + world.set_down(TARGET_CELL, false); + world.pump().await; + let saga = world.saga_state("t-4").await; + assert_eq!(saga.status(), SagaStatus::Compensated); + assert_eq!(world.balances().await, (100, 0), "value is conserved"); +} + +#[tokio::test] +async fn compensation_arriving_before_late_action_tombstones_it() { + let world = World::new(true).await; + world.set_down(TARGET_CELL, true); + world.saga.start("t-4b", World::data(25)).await.unwrap(); + world.pump().await; + world.clock.advance(Duration::from_secs(11)); + world.pump().await; + + // Deliver the target's queue in the worst order: compensation first. + world.set_down(TARGET_CELL, false); + let mut queued: Vec = world + .take_due(&world.saga_outbox) + .await + .into_iter() + .filter(|m| m.destination.as_deref() == Some(TARGET_CELL)) + .collect(); + queued.sort_by_key(|m| m.event_type != "wallet.reverse_credit"); + assert_eq!(queued.len(), 2); + for message in &queued { + world.target.handle(message).await; + } + assert_eq!(world.balances().await.1, 0, "late credit was rejected"); + + world.pump().await; + assert_eq!( + world.saga_state("t-4b").await.status(), + SagaStatus::Compensated + ); + assert_eq!(world.balances().await, (100, 0)); +} + +#[tokio::test] +async fn compensation_timeouts_retry_then_mark_stuck() { + let world = World::new(false).await; + world.saga.start("t-5", World::data(10)).await.unwrap(); + // Let the debit apply, then take the source down before the refund. + world.set_down(TARGET_CELL, true); + world.pump().await; + world.set_down(SOURCE_CELL, true); + world.set_down(TARGET_CELL, false); + world.pump().await; + let saga = world.saga_state("t-5").await; + assert_eq!(saga.status(), SagaStatus::Compensating); + assert_eq!(saga.cursor().unwrap().attempt, 1); + + for attempt in 2..=Transfer::MAX_COMPENSATION_ATTEMPTS { + world.clock.advance(Duration::from_secs(11)); + world.pump().await; + assert_eq!( + world.saga_state("t-5").await.cursor().unwrap().attempt, + attempt + ); + } + world.clock.advance(Duration::from_secs(11)); + world.pump().await; + assert_eq!(world.saga_state("t-5").await.status(), SagaStatus::Stuck); +} + +#[tokio::test] +async fn duplicate_replies_are_deduplicated() { + let world = World::new(true).await; + world.set_down(TARGET_CELL, true); + world.saga.start("t-6", World::data(5)).await.unwrap(); + + // Deliver the debit command twice to the source cell (at-least-once). + let commands = world.take_due(&world.saga_outbox).await; + let debit = commands + .iter() + .find(|m| m.destination.as_deref() == Some(SOURCE_CELL)) + .unwrap(); + world.source.handle(debit).await; + world.source.handle(debit).await; + assert_eq!(world.balances().await.0, 95, "debit applied once"); + + // The redelivery emitted nothing; deliver the one reply twice and the + // saga applies it once. + let replies = world.take_due(&world.source.outbox).await; + assert_eq!(replies.len(), 1); + let reply = SagaMessage::from_outbox(&replies[0]).unwrap(); + assert_eq!( + world.saga.handle(&reply).await.unwrap().outcome, + SagaOutcome::Applied + ); + assert_eq!( + world.saga.handle(&reply).await.unwrap().outcome, + SagaOutcome::Duplicate + ); +} + +#[tokio::test] +async fn saga_aggregate_replays_to_the_same_state() { + let world = World::new(false).await; + world.saga.start("t-7", World::data(40)).await.unwrap(); + world.pump().await; + let loaded = world.saga_state("t-7").await; + assert_eq!(loaded.status(), SagaStatus::Compensated); + assert_eq!(loaded.applied_steps(), Vec::<&str>::new()); + assert!(loaded.cursor().is_none()); +} + +// =========================================================================== +// Restart survival on a SQLite file database +// =========================================================================== + +#[cfg(feature = "sqlite")] +#[tokio::test] +async fn saga_and_its_timer_survive_restart_on_sqlite() { + use crate::sqlite_support::TempDb; + use distributed::{SqliteRepository, SystemClock}; + + let db = TempDb::new("saga_restart"); + let clock = ManualClock::new(SystemTime::now()); + { + let repo = SqliteRepository::new(db.pool().await); + repo.migrate().await.unwrap(); + let runner = SagaRunner::<_, Transfer, _>::with_clock(repo, clock.clone()); + runner.start("t-8", World::data(10)).await.unwrap(); + } // "crash": every handle dropped + + let repo = SqliteRepository::new(db.pool().await); + let store = repo.outbox_store(); + let pending = store.pending(10).await.unwrap(); + assert_eq!(pending.len(), 2); + let timer = pending + .iter() + .find(|m| m.event_type == distributed::saga::SAGA_TIMEOUT) + .unwrap(); + let deadline = timer.deliver_at.expect("timer keeps its schedule"); + + // Only the debit command is claimable now; the timer is not yet due. + let claimed = store + .claim(ClaimOutboxMessages::new("w", 10, Duration::from_secs(60))) + .await + .unwrap(); + assert_eq!(claimed.len(), 1); + assert_eq!(claimed[0].event_type, "wallet.debit"); + + // Once due (the timer was armed 10s after the manual start time, which + // is ~now), the restarted runner times the step out and compensates. + let saga_message = SagaMessage::from_outbox(timer).unwrap(); + let runner = SagaRunner::<_, Transfer, _>::with_clock(repo, SystemClock); + let saga = runner.get("t-8").await.unwrap().unwrap(); + assert_eq!(saga.cursor().unwrap().deadline, deadline); + let outcome = runner.handle(&saga_message).await.unwrap(); + assert_eq!(outcome.outcome, SagaOutcome::Applied); + let saga = runner.get("t-8").await.unwrap().unwrap(); + assert_eq!(saga.status(), SagaStatus::Compensating); + assert_eq!(saga.applied_steps(), vec!["debit"]); +} From bcd489dc95d69deca10c693c9916460e939f9d6b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 14:55:42 -0500 Subject: [PATCH 125/484] feat(game): add distributed_game zone runtime crate Introduce the distributed_game workspace member: a Zone trait plus a synchronous ZoneHost runtime with lifecycle hooks (create, auth, join, leave, observe, dispose), capacity, per-zone simulation-time timers, fixed timestep with catch-up cap, patch cadence independent of the tick rate, and Hot/Idle/Dormant activity tiers with observable transitions. Inputs are buffered per player (sequence dedupe, bounded, sanitize hook, next/latest/drain policies) and the last processed sequence is acked in every Delta. Clocks are injectable (system/manual) and each zone gets a seeded xoshiro256** RNG derived from world seed and zone id; a test proves identical state hashes for identical seed and input log. Facts are emitted without blocking the tick into a bounded queue; a FactFeed worker commits them through a FactSink with retries and backoff and settlements return on later ticks. The cell feature adds CellFactSink, which dispatches facts into an AggregateCell via dispatch_idempotent with a server-built Session whose principal comes only from the verified ticket. FactStamp helpers stamp zone/tick/content version into EventRecord metadata. The binary protocol codecs, entity schema with quantization and the interest-managed delta replicator used by the host are included here; the transport and protocol spec follow. Refs [[tasks/gr-p2-zone-runtime]] --- Cargo.toml | 2 +- distributed_game/Cargo.toml | 33 + distributed_game/src/cell.rs | 128 ++ distributed_game/src/clock.rs | 76 ++ distributed_game/src/facts.rs | 384 ++++++ distributed_game/src/host.rs | 1110 ++++++++++++++++++ distributed_game/src/input.rs | 202 ++++ distributed_game/src/interest.rs | 110 ++ distributed_game/src/lib.rs | 62 + distributed_game/src/protocol/messages.rs | 638 ++++++++++ distributed_game/src/protocol/mod.rs | 30 + distributed_game/src/protocol/wire.rs | 287 +++++ distributed_game/src/replication.rs | 395 +++++++ distributed_game/src/rng.rs | 121 ++ distributed_game/src/schema.rs | 476 ++++++++ distributed_game/src/stamp.rs | 98 ++ distributed_game/src/timers.rs | 127 ++ distributed_game/src/timestep.rs | 115 ++ distributed_game/src/zone.rs | 195 +++ distributed_game/tests/cell_sink/main.rs | 167 +++ distributed_game/tests/zone_runtime/arena.rs | 259 ++++ distributed_game/tests/zone_runtime/main.rs | 527 +++++++++ 22 files changed, 5541 insertions(+), 1 deletion(-) create mode 100644 distributed_game/Cargo.toml create mode 100644 distributed_game/src/cell.rs create mode 100644 distributed_game/src/clock.rs create mode 100644 distributed_game/src/facts.rs create mode 100644 distributed_game/src/host.rs create mode 100644 distributed_game/src/input.rs create mode 100644 distributed_game/src/interest.rs create mode 100644 distributed_game/src/lib.rs create mode 100644 distributed_game/src/protocol/messages.rs create mode 100644 distributed_game/src/protocol/mod.rs create mode 100644 distributed_game/src/protocol/wire.rs create mode 100644 distributed_game/src/replication.rs create mode 100644 distributed_game/src/rng.rs create mode 100644 distributed_game/src/schema.rs create mode 100644 distributed_game/src/stamp.rs create mode 100644 distributed_game/src/timers.rs create mode 100644 distributed_game/src/timestep.rs create mode 100644 distributed_game/src/zone.rs create mode 100644 distributed_game/tests/cell_sink/main.rs create mode 100644 distributed_game/tests/zone_runtime/arena.rs create mode 100644 distributed_game/tests/zone_runtime/main.rs diff --git a/Cargo.toml b/Cargo.toml index fc02e1729..1382ecf8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["distributed_macros", "distributed_cli"] +members = ["distributed_macros", "distributed_cli", "distributed_game"] exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker"] resolver = "2" diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml new file mode 100644 index 000000000..2aeb54a9a --- /dev/null +++ b/distributed_game/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "distributed_game" +description = "Authoritative multiplayer zone runtime for `distributed`: fixed-timestep zones, sequenced inputs, non-blocking durable facts, interest-managed binary replication and an optional WebSocket transport." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" + +[lib] +path = "src/lib.rs" + +[features] +default = [] +# Tokio-driven fact worker (`spawn_fact_worker`). Core stays runtime-agnostic. +runtime = ["dep:tokio"] +# Adapter that commits facts into a `distributed` AggregateCell. +cell = ["dep:distributed", "dep:sha2"] + +[dependencies] +serde_json = "1" +tokio = { version = "1", default-features = false, features = ["rt", "sync", "time"], optional = true } +distributed = { path = "..", default-features = false, optional = true } +sha2 = { version = "0.10", optional = true } + +[dev-dependencies] +tokio = { version = "1", features = ["full", "test-util"] } +serde = { version = "1", features = ["derive"] } + +[[test]] +name = "cell_sink" +path = "tests/cell_sink/main.rs" +required-features = ["cell", "runtime"] diff --git a/distributed_game/src/cell.rs b/distributed_game/src/cell.rs new file mode 100644 index 000000000..62e363df0 --- /dev/null +++ b/distributed_game/src/cell.rs @@ -0,0 +1,128 @@ +//! [`CellFactSink`]: commit facts as idempotent commands into a +//! `distributed` [`AggregateCell`]. +//! +//! For each fact the sink: +//! 1. takes the principal **only** from [`Fact::principal`] — bound by the +//! host from the player's verified ticket — or a configured system +//! principal for zone facts; client payloads never supply identity; +//! 2. builds a trusted server-side [`Session`] (`x-user-id` = principal, plus +//! the [`FactStamp`](crate::FactStamp) as `x-game-*` variables so handlers +//! can [`stamp_metadata`](crate::stamp_metadata) their events); +//! 3. derives a deterministic UUIDv7-shaped command id from +//! `sha256(service_id ‖ 0x00 ‖ fact key)`, so retries and re-emissions of +//! the same key replay through the cell's command ledger instead of +//! committing twice; +//! 4. calls [`AggregateCell::dispatch_idempotent`]. +//! +//! `InProgress` and `Internal` errors are retryable; everything else is +//! permanent. + +use std::sync::Arc; + +use distributed::cell_host::{AggregateCell, CellCommandIdentity, CellDispatchError}; +use distributed::microsvc::Session; +use distributed::{Aggregate, USER_ID_KEY}; +use sha2::{Digest, Sha256}; + +use crate::facts::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; + +/// Fact sink backed by an aggregate cell. +pub struct CellFactSink +where + A: Aggregate + Send + Sync + 'static, +{ + cell: Arc>, + service_id: String, + system_principal: String, +} + +impl CellFactSink +where + A: Aggregate + Send + Sync + 'static, +{ + /// Sink dispatching into `cell` under command-ledger `service_id`. + /// Zone facts without a player use `system_principal`. + pub fn new( + cell: Arc>, + service_id: impl Into, + system_principal: impl Into, + ) -> Self { + Self { + cell, + service_id: service_id.into(), + system_principal: system_principal.into(), + } + } +} + +/// Deterministic UUIDv7-shaped command id for a fact key. +pub fn command_id_for(service_id: &str, key: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(service_id.as_bytes()); + hasher.update([0u8]); + hasher.update(key.as_bytes()); + let digest = hasher.finalize(); + let mut b = [0u8; 16]; + b.copy_from_slice(&digest[..16]); + b[6] = (b[6] & 0x0f) | 0x70; + b[8] = (b[8] & 0x3f) | 0x80; + let hex: String = b.iter().map(|x| format!("{x:02x}")).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} + +/// Trusted session for a fact: principal + stamp. +pub fn trusted_session(principal: &str, fact: &Fact) -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, principal); + for (key, value) in fact.stamp().session_vars() { + session.set(key, value); + } + session +} + +fn classify(error: CellDispatchError) -> FactError { + match error { + CellDispatchError::InProgress | CellDispatchError::Internal(_) => { + FactError::Retryable(format!("{error:?}")) + } + other => FactError::Permanent(format!("{}: {other:?}", other.code())), + } +} + +impl FactSink for CellFactSink +where + A: Aggregate + Send + Sync + 'static, +{ + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + let principal = fact.principal().unwrap_or(&self.system_principal); + let identity = CellCommandIdentity::new( + self.service_id.clone(), + principal, + command_id_for(&self.service_id, fact.key()), + ) + .map_err(|e| FactError::Permanent(format!("{e:?}")))?; + let result = self + .cell + .dispatch_idempotent( + fact.command(), + &identity, + fact.input().clone(), + trusted_session(principal, fact), + ) + .await + .map_err(classify)?; + Ok(FactReceipt { + payload: result.payload().clone(), + replayed: result.replayed(), + }) + }) + } +} diff --git a/distributed_game/src/clock.rs b/distributed_game/src/clock.rs new file mode 100644 index 000000000..1554b7158 --- /dev/null +++ b/distributed_game/src/clock.rs @@ -0,0 +1,76 @@ +//! Injectable monotonic clocks. +//! +//! The runtime never reads wall time directly. Every [`ZoneHost`](crate::ZoneHost) +//! is built with an `Arc`; production uses [`SystemClock`] and tests +//! use [`ManualClock`] to drive time explicitly, which (together with the seeded +//! [`ZoneRng`](crate::ZoneRng)) makes simulation runs reproducible. +//! +//! A clock reports elapsed time since its own origin as a [`Duration`]. Only +//! differences matter to the runtime; values are also sent to clients as +//! "server time" in milliseconds for clock synchronization. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// Monotonic time source. +pub trait Clock: Send + Sync + 'static { + /// Time elapsed since this clock's origin. Must never go backwards. + fn now(&self) -> Duration; +} + +/// Real monotonic clock backed by [`Instant`]. +#[derive(Debug, Clone)] +pub struct SystemClock { + origin: Instant, +} + +impl SystemClock { + /// Clock whose origin is "now". + pub fn new() -> Self { + Self { + origin: Instant::now(), + } + } +} + +impl Default for SystemClock { + fn default() -> Self { + Self::new() + } +} + +impl Clock for SystemClock { + fn now(&self) -> Duration { + self.origin.elapsed() + } +} + +/// Virtual clock advanced explicitly; clones share the same time. +#[derive(Debug, Clone, Default)] +pub struct ManualClock { + nanos: Arc, +} + +impl ManualClock { + /// Clock starting at zero. + pub fn new() -> Self { + Self::default() + } + + /// Move time forward by `by`. + pub fn advance(&self, by: Duration) { + self.nanos.fetch_add(by.as_nanos() as u64, Ordering::SeqCst); + } + + /// Jump to an absolute time. Ignored if it would move time backwards. + pub fn set(&self, to: Duration) { + self.nanos.fetch_max(to.as_nanos() as u64, Ordering::SeqCst); + } +} + +impl Clock for ManualClock { + fn now(&self) -> Duration { + Duration::from_nanos(self.nanos.load(Ordering::SeqCst)) + } +} diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs new file mode 100644 index 000000000..e72f0263d --- /dev/null +++ b/distributed_game/src/facts.rs @@ -0,0 +1,384 @@ +//! Non-blocking durable facts. +//! +//! A *fact* is a meaningful, durable outcome of simulation ("enemy killed, +//! credit XP to player P"). Zones emit facts during a tick through +//! [`Ctx::emit_fact`](crate::Ctx::emit_fact); the call only enqueues. A +//! [`FactSink`] commits them asynchronously on a worker ([`FactFeed::run`] or +//! `spawn_fact_worker` with the `runtime` feature) with bounded retries and +//! exponential backoff; the resulting [`FactSettlement`] is delivered back to +//! the zone (`Zone::on_fact_settled`) at the start of a later tick. +//! **The tick never awaits storage.** +//! +//! Guarantees: +//! - Bounded: at most `capacity` facts may be unsettled; beyond that +//! `emit_fact` returns [`EmitError::Backpressure`] and the game decides +//! (retry next tick, freeze, drop a cosmetic fact). +//! - Idempotent: each fact has a caller-chosen idempotency key. The queue +//! rejects a key already in flight; sinks must treat a repeated key as a +//! replay (the cell adapter maps it onto `dispatch_idempotent`). +//! - Trusted identity: the principal is bound by the host from the player's +//! verified ticket — zones and clients cannot set it. + +use std::collections::{HashSet, VecDeque}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use serde_json::Value; + +use crate::stamp::FactStamp; + +/// Boxed `Send` future used by [`FactSink`]. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// A durable outcome to commit. +#[derive(Debug, Clone, PartialEq)] +pub struct Fact { + key: String, + command: String, + input: Value, + principal: Option, + stamp: FactStamp, +} + +impl Fact { + /// `key` must be unique per logical outcome (e.g. `"kill:{zone}:{tick}:{enemy}"`); + /// `command` names the durable command; `input` is its payload. + pub fn new(key: impl Into, command: impl Into, input: Value) -> Self { + Self { + key: key.into(), + command: command.into(), + input, + principal: None, + stamp: FactStamp::default(), + } + } + + /// Idempotency key. + pub fn key(&self) -> &str { + &self.key + } + + /// Command name. + pub fn command(&self) -> &str { + &self.command + } + + /// Command input. + pub fn input(&self) -> &Value { + &self.input + } + + /// Verified principal (from the player's ticket), or None for zone/system facts. + pub fn principal(&self) -> Option<&str> { + self.principal.as_deref() + } + + /// Provenance stamp. + pub fn stamp(&self) -> &FactStamp { + &self.stamp + } + + pub(crate) fn bind(mut self, principal: Option, stamp: FactStamp) -> Self { + self.principal = principal; + self.stamp = stamp; + self + } + + /// Build a fact with an explicit principal/stamp. Only for sinks' own + /// tests and tooling; zones go through `Ctx::emit_fact_for`. + pub fn trusted( + key: impl Into, + command: impl Into, + input: Value, + principal: Option, + stamp: FactStamp, + ) -> Self { + Self::new(key, command, input).bind(principal, stamp) + } +} + +/// Sink failure classification. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FactError { + /// Transient; retried with backoff. + Retryable(String), + /// Will never succeed; settles as failed immediately. + Permanent(String), +} + +/// Successful commit. +#[derive(Debug, Clone, PartialEq)] +pub struct FactReceipt { + /// Sink-specific result payload. + pub payload: Value, + /// True when the sink recognised the key as already committed. + pub replayed: bool, +} + +/// Final outcome of one fact. +#[derive(Debug, Clone, PartialEq)] +pub enum FactOutcome { + /// Durably committed. + Committed(FactReceipt), + /// Gave up. + Failed { + /// Last error. + error: FactError, + /// Attempts made. + attempts: u32, + }, +} + +/// Delivered to the zone on a later tick. +#[derive(Debug, Clone, PartialEq)] +pub struct FactSettlement { + /// Idempotency key. + pub key: String, + /// Command name. + pub command: String, + /// Outcome. + pub outcome: FactOutcome, +} + +/// Durable commit target. +pub trait FactSink: Send + Sync + 'static { + /// Commit one fact. Must be idempotent per [`Fact::key`]. + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result>; +} + +/// Retry/backoff policy. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RetryPolicy { + /// Total attempts including the first (>= 1). + pub max_attempts: u32, + /// Delay after the first retryable failure; doubles each time. + pub base_backoff: Duration, + /// Backoff ceiling. + pub max_backoff: Duration, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_attempts: 8, + base_backoff: Duration::from_millis(50), + max_backoff: Duration::from_secs(5), + } + } +} + +impl RetryPolicy { + /// Backoff before attempt `attempt + 1` (attempt >= 1). + pub fn backoff(&self, attempt: u32) -> Duration { + let factor = 1u32 << attempt.saturating_sub(1).min(20); + self.base_backoff + .saturating_mul(factor) + .min(self.max_backoff) + } +} + +/// Why `emit_fact` refused a fact. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EmitError { + /// `capacity` facts are unsettled. + Backpressure, + /// A fact with this key is already in flight. + DuplicateKey, + /// The host has no fact queue attached. + NoSink, + /// The player is unknown (cannot bind a principal). + UnknownPlayer, +} + +#[derive(Debug, Default)] +struct Shared { + queue: Mutex>, + waker: Mutex>, + closed: AtomicBool, +} + +impl Shared { + fn wake(&self) { + if let Some(waker) = self.waker.lock().expect("waker lock").take() { + waker.wake(); + } + } +} + +/// Zone-side handle: enqueue facts, collect settlements. Never blocks. +#[derive(Debug)] +pub struct FactQueue { + shared: Arc, + settlements: mpsc::Receiver, + in_flight: HashSet, + capacity: usize, +} + +/// Worker-side handle consumed by [`FactFeed::run`]. +#[derive(Debug)] +pub struct FactFeed { + shared: Arc, + settlements: mpsc::Sender, + policy: RetryPolicy, +} + +/// Create a queue allowing `capacity` unsettled facts. +pub fn fact_channel(capacity: usize, policy: RetryPolicy) -> (FactQueue, FactFeed) { + let shared = Arc::new(Shared::default()); + let (tx, rx) = mpsc::channel(); + ( + FactQueue { + shared: shared.clone(), + settlements: rx, + in_flight: HashSet::new(), + capacity: capacity.max(1), + }, + FactFeed { + shared, + settlements: tx, + policy, + }, + ) +} + +impl FactQueue { + /// Enqueue without blocking. + pub fn try_send(&mut self, fact: Fact) -> Result<(), EmitError> { + if self.in_flight.contains(fact.key()) { + return Err(EmitError::DuplicateKey); + } + if self.in_flight.len() >= self.capacity { + return Err(EmitError::Backpressure); + } + self.in_flight.insert(fact.key.clone()); + self.shared + .queue + .lock() + .expect("fact queue lock") + .push_back(fact); + self.shared.wake(); + Ok(()) + } + + /// Settlements that arrived since the last call. + pub fn drain(&mut self) -> Vec { + let settled: Vec<_> = self.settlements.try_iter().collect(); + for s in &settled { + self.in_flight.remove(&s.key); + } + settled + } + + /// Unsettled facts. + pub fn in_flight(&self) -> usize { + self.in_flight.len() + } +} + +impl Drop for FactQueue { + fn drop(&mut self) { + self.shared.closed.store(true, Ordering::SeqCst); + self.shared.wake(); + } +} + +struct NextFact<'a>(&'a Shared); + +impl Future for NextFact<'_> { + type Output = Option; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let shared = self.0; + // Register before checking so a concurrent push cannot be missed. + *shared.waker.lock().expect("waker lock") = Some(cx.waker().clone()); + if let Some(fact) = shared.queue.lock().expect("fact queue lock").pop_front() { + return Poll::Ready(Some(fact)); + } + if shared.closed.load(Ordering::SeqCst) { + return Poll::Ready(None); + } + Poll::Pending + } +} + +impl FactFeed { + /// Commit facts in emission order until the queue is dropped and drained. + /// `sleep` provides the runtime's timer for backoff. + pub async fn run(self, sink: S, sleep: F) + where + S: FactSink, + F: Fn(Duration) -> Fut, + Fut: Future, + { + while let Some(fact) = NextFact(&self.shared).await { + let mut attempts = 0; + let outcome = loop { + attempts += 1; + match sink.commit(&fact).await { + Ok(receipt) => break FactOutcome::Committed(receipt), + Err(FactError::Retryable(_)) if attempts < self.policy.max_attempts.max(1) => { + sleep(self.policy.backoff(attempts)).await; + } + Err(error) => break FactOutcome::Failed { error, attempts }, + } + }; + let _ = self.settlements.send(FactSettlement { + key: fact.key, + command: fact.command, + outcome, + }); + } + } +} + +/// Run a [`FactFeed`] on the current Tokio runtime. +#[cfg(feature = "runtime")] +pub fn spawn_fact_worker(feed: FactFeed, sink: S) -> tokio::task::JoinHandle<()> { + tokio::spawn(feed.run(sink, tokio::time::sleep)) +} + +/// In-memory sink that records commits and replays repeated keys. +/// Useful for tests and local development. +#[derive(Debug, Default, Clone)] +pub struct MemoryFactSink { + committed: Arc>>, +} + +impl MemoryFactSink { + /// Empty sink. + pub fn new() -> Self { + Self::default() + } + + /// Facts committed so far (one per key). + pub fn committed(&self) -> Vec { + self.committed.lock().expect("sink lock").clone() + } +} + +impl FactSink for MemoryFactSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + let mut committed = self.committed.lock().expect("sink lock"); + let replayed = committed.iter().any(|f| f.key == fact.key); + if !replayed { + committed.push(fact.clone()); + } + Ok(FactReceipt { + payload: Value::Null, + replayed, + }) + }) + } +} + +impl FactSink for Arc { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + (**self).commit(fact) + } +} diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs new file mode 100644 index 000000000..01eadb615 --- /dev/null +++ b/distributed_game/src/host.rs @@ -0,0 +1,1110 @@ +//! [`ZoneHost`]: drives one [`Zone`] — lifecycle, fixed timestep, activity +//! tiers, inputs, timers, facts and replication. +//! +//! The host is synchronous and transport-agnostic. A driver (the `net` +//! server, a test, a custom loop) calls: +//! +//! - [`join`](ZoneHost::join) / [`reconnect`](ZoneHost::reconnect) / +//! [`disconnect`](ZoneHost::disconnect) for membership, +//! - [`push_input`](ZoneHost::push_input) for wire inputs, +//! - [`advance`](ZoneHost::advance) whenever time may have passed (it reads +//! the injected [`Clock`], runs due fixed steps and patches, and reports +//! when it next wants to be called), +//! - [`drain_outbound`](ZoneHost::drain_outbound) to collect encoded frames. +//! +//! **Cadence.** Ticks run at `tick_rate` with an accumulator and catch-up cap +//! ([`FixedTimestep`]). Patches (Deltas) run at `patch_rate` on the clock, +//! independent of the tick rate. +//! +//! **Tiers.** Hot while any client is connected, any player is inside its +//! reconnect grace window, or [`Zone::has_pending_work`] is true. Otherwise +//! Idle: ticks at `idle_tick_rate` (or not at all when `None`). After +//! `dormant_after` in Idle with no unsettled facts and +//! [`Zone::wants_background`] false the zone becomes Dormant: no ticks, +//! simulation time stops (timers pause) and the zone is eligible for +//! hibernation. Joins, reconnects and inputs wake it to Hot. Transitions are +//! reported in [`AdvanceReport::transitions`] and via +//! [`Zone::on_tier_changed`]. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +use crate::clock::Clock; +use crate::facts::{EmitError, Fact, FactQueue}; +use crate::input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; +use crate::interest::{InterestConfig, View}; +use crate::protocol::{error, kick, Notice, Role, ServerMessage, Welcome}; +use crate::replication::{ClientReplica, EncodedWorld, WorldView}; +use crate::rng::ZoneRng; +use crate::schema::EntitySchema; +use crate::stamp::FactStamp; +use crate::timers::{TimerId, Timers}; +use crate::timestep::{rate_to_step, FixedTimestep}; +use crate::zone::{ + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, + Tier, Viewer, Zone, +}; + +/// Host tuning. +#[derive(Debug, Clone, PartialEq)] +pub struct HostConfig { + /// Hot ticks per second. + pub tick_rate: u32, + /// Deltas per second (independent of `tick_rate`). + pub patch_rate: u32, + /// Idle ticks per second; `None` = no ticks while Idle. + pub idle_tick_rate: Option, + /// Time in Idle before Dormant. + pub dormant_after: Duration, + /// Max fixed steps per `advance` before backlog is dropped. + pub max_catch_up: u32, + /// Player capacity. + pub max_players: usize, + /// Observer capacity. + pub max_observers: usize, + /// Per-player input buffer bound. + pub input_capacity: usize, + /// How long a dropped player is kept for reconnect. + pub reconnect_grace: Duration, + /// Per-client create+update bytes per Delta. + pub byte_budget: usize, + /// Radius of views the zone has not set explicitly (centered at origin). + pub default_view_radius: f32, + /// Interest grid settings. + pub interest: InterestConfig, + /// Content version; when non-empty, clients must match it exactly. + pub content_version: String, + /// World seed; the zone RNG derives from it and the zone id. + pub world_seed: u64, +} + +impl Default for HostConfig { + fn default() -> Self { + Self { + tick_rate: 30, + patch_rate: 20, + idle_tick_rate: Some(1), + dormant_after: Duration::from_secs(30), + max_catch_up: 5, + max_players: 64, + max_observers: 16, + input_capacity: 32, + reconnect_grace: Duration::from_secs(15), + byte_budget: 4096, + default_view_radius: 64.0, + interest: InterestConfig::default(), + content_version: String::new(), + world_seed: 0, + } + } +} + +/// Something for the transport to do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outbound { + /// Send this binary frame. + Frame { + /// Destination. + client: ClientId, + /// Encoded server message. + frame: Vec, + }, + /// Close the connection after previously queued frames. + Close { + /// Connection to close. + client: ClientId, + }, +} + +/// Result of [`ZoneHost::advance`]. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct AdvanceReport { + /// Fixed steps simulated. + pub ticks: u32, + /// Backlog dropped by the catch-up cap. + pub dropped: Duration, + /// Whether Deltas were produced. + pub patched: bool, + /// Tier transitions since the previous report. + pub transitions: Vec<(Tier, Tier)>, + /// Clock time at which the host next wants `advance` (None = only on + /// external events, i.e. Dormant). + pub next_wake: Option, +} + +/// Admission failure (code from [`protocol::error`](crate::protocol::error)). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JoinError { + /// Error code. + pub code: u32, + /// Message. + pub message: String, +} + +impl JoinError { + fn new(code: u32, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } +} + +/// Successful admission. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Joined { + /// New connection id. + pub client: ClientId, + /// Player or observer it is bound to. + pub viewer: Viewer, +} + +struct PlayerSlot { + info: PlayerInfo, + inputs: InputBuffer, + client: Option, + view: View, + grace_until: Option, + reconnect_token: String, + session_id: String, +} + +struct ObserverSlot { + client: ClientId, + view: View, +} + +struct ClientSlot { + viewer: Viewer, + replica: ClientReplica, +} + +/// Host state reachable from hooks through [`Ctx`]. +pub(crate) struct Core { + zone_id: String, + config: HostConfig, + clock: Arc, + rng: ZoneRng, + timers: Timers, + tick: u64, + sim_time: Duration, + dt: Duration, + tier: Tier, + players: BTreeMap>, + observers: BTreeMap, + clients: BTreeMap, + next_id: u32, + outbound: Vec, + facts: Option, + pending_kicks: Vec<(PlayerId, String)>, +} + +impl Core { + fn next_id(&mut self) -> u32 { + self.next_id += 1; + self.next_id + } + + fn client_of(&self, viewer: Viewer) -> Option { + match viewer { + Viewer::Player(p) => self.players.get(&p).and_then(|s| s.client), + Viewer::Observer(o) => self.observers.get(&o).map(|s| s.client), + } + } + + fn send(&mut self, client: ClientId, frame: Vec) { + self.outbound.push(Outbound::Frame { client, frame }); + } + + fn server_message(&mut self, client: ClientId, message: &ServerMessage) { + let frame = message.encode(&()).expect("non-delta messages encode"); + self.send(client, frame); + } + + fn server_time_ms(&self) -> f64 { + self.clock.now().as_secs_f64() * 1000.0 + } + + fn in_flight(&self) -> usize { + self.facts.as_ref().map_or(0, FactQueue::in_flight) + } +} + +/// Hook context: everything a zone may touch besides its own state. +pub struct Ctx<'a, Z: Zone> { + core: &'a mut Core, +} + +impl Ctx<'_, Z> { + /// Zone id. + pub fn zone_id(&self) -> &str { + &self.core.zone_id + } + + /// Ticks simulated so far (the current tick inside `on_tick`). + pub fn tick(&self) -> u64 { + self.core.tick + } + + /// Step length of the current tick (Hot or Idle rate). + pub fn dt(&self) -> Duration { + self.core.dt + } + + /// Step length in seconds. + pub fn dt_secs(&self) -> f32 { + self.core.dt.as_secs_f32() + } + + /// Simulation time (sum of all step lengths). + pub fn sim_time(&self) -> Duration { + self.core.sim_time + } + + /// Host clock (not deterministic across runs with a real clock). + pub fn now(&self) -> Duration { + self.core.clock.now() + } + + /// Current activity tier. + pub fn tier(&self) -> Tier { + self.core.tier + } + + /// Content version. + pub fn content_version(&self) -> &str { + &self.core.config.content_version + } + + /// The zone's deterministic RNG. + pub fn rng(&mut self) -> &mut ZoneRng { + &mut self.core.rng + } + + /// One-shot timer after `after` of simulation time. + pub fn set_timeout(&mut self, after: Duration, timer: Z::Timer) -> TimerId { + let now = self.core.sim_time; + self.core.timers.once(now, after, timer) + } + + /// Repeating timer every `every` of simulation time. + pub fn set_interval(&mut self, every: Duration, timer: Z::Timer) -> TimerId { + let now = self.core.sim_time; + self.core.timers.interval(now, every, timer) + } + + /// Cancel a timer. + pub fn cancel_timer(&mut self, id: TimerId) -> bool { + self.core.timers.cancel(id) + } + + /// Players (connected or within the reconnect grace window). + pub fn players(&self) -> impl Iterator + '_ { + self.core.players.values().map(|slot| &slot.info) + } + + /// One player. + pub fn player(&self, id: PlayerId) -> Option<&PlayerInfo> { + self.core.players.get(&id).map(|slot| &slot.info) + } + + /// Consume buffered inputs of `player`; advances its ack. + pub fn take_inputs( + &mut self, + player: PlayerId, + policy: ConsumePolicy, + ) -> Vec> { + self.core + .players + .get_mut(&player) + .map(|slot| slot.inputs.take(policy)) + .unwrap_or_default() + } + + /// Emit a zone/system fact (no principal). Never blocks. + pub fn emit_fact(&mut self, fact: Fact) -> Result<(), EmitError> { + self.emit(fact, None) + } + + /// Emit a fact on behalf of `player`; the principal is bound from the + /// player's verified ticket. Never blocks. + pub fn emit_fact_for(&mut self, player: PlayerId, fact: Fact) -> Result<(), EmitError> { + let principal = self + .core + .players + .get(&player) + .map(|slot| slot.info.principal.clone()) + .ok_or(EmitError::UnknownPlayer)?; + self.emit(fact, Some(principal)) + } + + fn emit(&mut self, fact: Fact, principal: Option) -> Result<(), EmitError> { + let stamp = FactStamp { + zone_id: self.core.zone_id.clone(), + tick: self.core.tick, + content_version: self.core.config.content_version.clone(), + }; + self.core + .facts + .as_mut() + .ok_or(EmitError::NoSink)? + .try_send(fact.bind(principal, stamp)) + } + + /// Unsettled facts. + pub fn facts_in_flight(&self) -> usize { + self.core.in_flight() + } + + /// Reliable event to one viewer (dropped if it has no live connection). + pub fn send_event(&mut self, to: impl Into, type_id: u32, payload: Vec) { + if let Some(client) = self.core.client_of(to.into()) { + self.core + .server_message(client, &ServerMessage::Event { type_id, payload }); + } + } + + /// Reliable event to every connection. + pub fn broadcast_event(&mut self, type_id: u32, payload: Vec) { + let frame = ServerMessage::Event { type_id, payload } + .encode(&()) + .expect("event encodes"); + let clients: Vec<_> = self.core.clients.keys().copied().collect(); + for client in clients { + self.core.send(client, frame.clone()); + } + } + + /// Set a viewer's area of interest. + pub fn set_view(&mut self, viewer: impl Into, view: View) { + match viewer.into() { + Viewer::Player(p) => { + if let Some(slot) = self.core.players.get_mut(&p) { + slot.view = view; + } + } + Viewer::Observer(o) => { + if let Some(slot) = self.core.observers.get_mut(&o) { + slot.view = view; + } + } + } + } + + /// Remove a player after the current hook returns. + pub fn kick(&mut self, player: PlayerId, message: impl Into) { + self.core.pending_kicks.push((player, message.into())); + } +} + +/// Runs one zone. See the module docs. +pub struct ZoneHost { + zone: Z, + core: Core, + schema: EntitySchema, + hot: FixedTimestep, + idle: Option, + last_advance: Duration, + idle_since: Duration, + next_patch: Duration, + transitions: Vec<(Tier, Tier)>, + frozen: bool, + disposed: bool, + token_source: Box String + Send>, +} + +macro_rules! hook { + ($host:ident . $method:ident ( $($arg:expr),* )) => { + $host.zone.$method(&mut Ctx { core: &mut $host.core } $(, $arg)*) + }; +} + +impl ZoneHost { + /// Create the zone (`on_create`). Starts Hot. + pub fn new( + zone_id: impl Into, + config: HostConfig, + clock: Arc, + zone_config: Z::Config, + ) -> Self { + let zone_id = zone_id.into(); + let now = clock.now(); + let mut core = Core { + rng: ZoneRng::for_zone(config.world_seed, &zone_id), + zone_id, + clock, + timers: Timers::default(), + tick: 0, + sim_time: Duration::ZERO, + dt: rate_to_step(config.tick_rate), + tier: Tier::Hot, + players: BTreeMap::new(), + observers: BTreeMap::new(), + clients: BTreeMap::new(), + next_id: 0, + outbound: Vec::new(), + facts: None, + pending_kicks: Vec::new(), + config, + }; + let zone = Z::on_create(&mut Ctx { core: &mut core }, zone_config); + let hot = FixedTimestep::from_rate(core.config.tick_rate, core.config.max_catch_up); + let idle = core + .config + .idle_tick_rate + .map(|hz| FixedTimestep::from_rate(hz, core.config.max_catch_up)); + let mut host = Self { + zone, + core, + schema: Z::schema(), + hot, + idle, + last_advance: now, + idle_since: now, + next_patch: now, + transitions: Vec::new(), + frozen: false, + disposed: false, + token_source: Box::new(default_token), + }; + host.process_kicks(); + host + } + + /// Attach the zone side of a fact channel. + pub fn with_facts(mut self, facts: FactQueue) -> Self { + self.core.facts = Some(facts); + self + } + + /// Replace the reconnect/session token generator (must be unpredictable). + pub fn with_token_source(mut self, source: impl FnMut() -> String + Send + 'static) -> Self { + self.token_source = Box::new(source); + self + } + + /// Zone id. + pub fn zone_id(&self) -> &str { + &self.core.zone_id + } + + /// The game state. + pub fn zone(&self) -> &Z { + &self.zone + } + + /// Mutable game state (operator tooling; bypasses determinism). + pub fn zone_mut(&mut self) -> &mut Z { + &mut self.zone + } + + /// Host configuration. + pub fn config(&self) -> &HostConfig { + &self.core.config + } + + /// Replicated schema. + pub fn schema(&self) -> &EntitySchema { + &self.schema + } + + /// Current tier. + pub fn tier(&self) -> Tier { + self.core.tier + } + + /// Ticks simulated. + pub fn tick(&self) -> u64 { + self.core.tick + } + + /// Players (including those in the grace window). + pub fn player_count(&self) -> usize { + self.core.players.len() + } + + /// Live connections. + pub fn client_count(&self) -> usize { + self.core.clients.len() + } + + /// Viewer bound to a connection. + pub fn viewer_of(&self, client: ClientId) -> Option { + self.core.clients.get(&client).map(|slot| slot.viewer) + } + + /// Unsettled facts. + pub fn facts_in_flight(&self) -> usize { + self.core.in_flight() + } + + /// True after [`dispose`](Self::dispose). + pub fn is_disposed(&self) -> bool { + self.disposed + } + + /// True while frozen. + pub fn is_frozen(&self) -> bool { + self.frozen + } + + /// Server clock in ms (for Pong). + pub fn server_time_ms(&self) -> f64 { + self.core.server_time_ms() + } + + /// Frames and closes produced since the last call, in order. + pub fn drain_outbound(&mut self) -> Vec { + std::mem::take(&mut self.core.outbound) + } + + /// Admit a verified ticket holder. + pub fn join( + &mut self, + claims: &TicketClaims, + capabilities: u32, + content_version: &str, + ) -> Result { + if self.disposed { + return Err(JoinError::new(error::NOT_FOUND, "zone disposed")); + } + if claims.zone != self.core.zone_id { + return Err(JoinError::new( + error::UNAUTHORIZED, + "ticket is for another zone", + )); + } + let expected = &self.core.config.content_version; + if !expected.is_empty() && content_version != expected { + return Err(JoinError::new( + error::VERSION_MISMATCH, + format!("content version {content_version} != {expected}"), + )); + } + let existing = self + .core + .players + .values() + .find(|slot| slot.info.principal == claims.principal) + .map(|slot| slot.info.id); + let capacity_ok = match claims.role { + Role::Player => { + existing.is_some() || self.core.players.len() < self.core.config.max_players + } + Role::Observer => self.core.observers.len() < self.core.config.max_observers, + }; + if !capacity_ok { + return Err(JoinError::new(error::ZONE_FULL, "zone is full")); + } + let request = JoinRequest { + claims, + capabilities, + content_version, + }; + if let Admission::Reject(message) = hook!(self.on_auth(&request)) { + self.process_kicks(); + return Err(JoinError::new(error::REJECTED, message)); + } + self.wake(); + let client = ClientId(self.core.next_id()); + let joined = match (claims.role, existing) { + (Role::Player, Some(player)) => { + self.bind_player(player, client, capabilities); + Joined { + client, + viewer: Viewer::Player(player), + } + } + (Role::Player, None) => { + let player = PlayerId(self.core.next_id()); + let radius = self.core.config.default_view_radius; + let capacity = self.core.config.input_capacity; + self.core.players.insert( + player, + PlayerSlot { + info: PlayerInfo { + id: player, + principal: claims.principal.clone(), + capabilities, + connected: true, + }, + inputs: InputBuffer::new(capacity), + client: None, + view: View::new(0.0, 0.0, radius), + grace_until: None, + reconnect_token: String::new(), + session_id: (self.token_source)(), + }, + ); + self.bind_player(player, client, capabilities); + hook!(self.on_join(player)); + Joined { + client, + viewer: Viewer::Player(player), + } + } + (Role::Observer, _) => { + let observer = ObserverId(self.core.next_id()); + let session_id = (self.token_source)(); + self.core.observers.insert( + observer, + ObserverSlot { + client, + view: View::new(0.0, 0.0, self.core.config.default_view_radius), + }, + ); + self.attach_client(client, Viewer::Observer(observer)); + self.welcome(client, session_id, String::new(), Role::Observer); + hook!(self.on_observe(observer)); + Joined { + client, + viewer: Viewer::Observer(observer), + } + } + }; + self.process_kicks(); + Ok(joined) + } + + /// Resume a player's session with the token from its last Welcome. + pub fn reconnect(&mut self, token: &str, capabilities: u32) -> Result { + let player = (!token.is_empty() && !self.disposed) + .then(|| { + self.core + .players + .values() + .find(|slot| slot.reconnect_token == token) + .map(|slot| slot.info.id) + }) + .flatten() + .ok_or_else(|| JoinError::new(error::RECONNECT_FAILED, "unknown or expired token"))?; + self.wake(); + let client = ClientId(self.core.next_id()); + self.bind_player(player, client, capabilities); + Ok(Joined { + client, + viewer: Viewer::Player(player), + }) + } + + fn attach_client(&mut self, client: ClientId, viewer: Viewer) { + self.core.clients.insert( + client, + ClientSlot { + viewer, + replica: ClientReplica::new(), + }, + ); + } + + fn bind_player(&mut self, player: PlayerId, client: ClientId, capabilities: u32) { + let token = (self.token_source)(); + let slot = self.core.players.get_mut(&player).expect("player exists"); + let previous = slot.client.replace(client); + slot.grace_until = None; + slot.info.connected = true; + slot.info.capabilities = capabilities; + slot.reconnect_token = token.clone(); + let session_id = slot.session_id.clone(); + if let Some(old) = previous { + self.core.clients.remove(&old); + self.core.server_message( + old, + &ServerMessage::Kick { + code: kick::REPLACED, + message: "replaced by a newer connection".into(), + }, + ); + self.core.outbound.push(Outbound::Close { client: old }); + } + self.attach_client(client, Viewer::Player(player)); + self.welcome(client, session_id, token, Role::Player); + } + + fn welcome(&mut self, client: ClientId, session_id: String, token: String, role: Role) { + let welcome = ServerMessage::Welcome(Welcome { + session_id, + zone_id: self.core.zone_id.clone(), + role, + tick_rate: self.core.config.tick_rate, + patch_rate: self.core.config.patch_rate, + server_tick: self.core.tick as u32, + server_time: self.core.server_time_ms(), + reconnect_token: token, + content_version: self.core.config.content_version.clone(), + schema: self.schema.clone(), + }); + self.core.server_message(client, &welcome); + } + + /// A connection ended. Graceful (Leave) removes the player now; otherwise + /// the player stays (disconnected) for `reconnect_grace`. + pub fn disconnect(&mut self, client: ClientId, graceful: bool) { + let Some(slot) = self.core.clients.remove(&client) else { + return; + }; + match slot.viewer { + Viewer::Player(player) => { + if graceful { + self.remove_player(player, LeaveReason::Left, None); + } else if let Some(p) = self.core.players.get_mut(&player) { + p.client = None; + p.info.connected = false; + p.inputs.clear(); + p.grace_until = Some(self.core.clock.now() + self.core.config.reconnect_grace); + } + } + Viewer::Observer(observer) => { + self.core.observers.remove(&observer); + hook!(self.on_unobserve(observer)); + } + } + self.process_kicks(); + } + + /// Offer a wire input from `client`. Decodes and sanitizes via the zone. + pub fn push_input( + &mut self, + client: ClientId, + seq: u32, + client_tick: u32, + payload: &[u8], + ) -> PushOutcome { + let Some(Viewer::Player(player)) = self.viewer_of(client) else { + return PushOutcome::UnknownClient; + }; + if self.frozen { + return PushOutcome::Rejected; + } + let Some(slot) = self.core.players.get(&player) else { + return PushOutcome::UnknownClient; + }; + if let Some(outcome) = slot.inputs.precheck(seq) { + return outcome; + } + let Some(input) = self + .zone + .decode_input(player, payload) + .and_then(|input| self.zone.sanitize_input(player, input)) + else { + return PushOutcome::Rejected; + }; + self.wake(); + self.core + .players + .get_mut(&player) + .expect("player exists") + .inputs + .push(seq, client_tick, input) + } + + /// Send a reliable event (operator/server side). + pub fn send_event(&mut self, to: Viewer, type_id: u32, payload: Vec) { + Ctx { + core: &mut self.core, + } + .send_event(to, type_id, payload); + } + + /// Kick a player now. + pub fn kick(&mut self, player: PlayerId, message: impl Into) { + self.core.pending_kicks.push((player, message.into())); + self.process_kicks(); + } + + /// Freeze: ticks stop and inputs are rejected; clients get Freeze. + pub fn freeze(&mut self, notice: Notice) { + self.frozen = true; + self.broadcast(&ServerMessage::Freeze(notice)); + } + + /// Resume after [`freeze`](Self::freeze); the frozen backlog is not simulated. + pub fn resume(&mut self, notice: Notice) { + self.frozen = false; + self.hot.reset(); + if let Some(idle) = &mut self.idle { + idle.reset(); + } + self.broadcast(&ServerMessage::Resume(notice)); + } + + /// Tell a player to move to `target_zone`, then remove it + /// (`LeaveReason::Handoff`). The transfer saga is the caller's concern. + pub fn handoff(&mut self, player: PlayerId, target_zone: &str, transfer_ticket: &str) { + let message = ServerMessage::Handoff { + target_zone: target_zone.into(), + transfer_ticket: transfer_ticket.into(), + }; + self.remove_player(player, LeaveReason::Handoff, Some(message)); + self.process_kicks(); + } + + /// Kick everyone (`on_leave(Disposed)` / `on_unobserve`), call + /// `on_dispose`, clear timers. The host stops ticking afterwards. + pub fn dispose(&mut self) { + if self.disposed { + return; + } + let bye = ServerMessage::Kick { + code: kick::ZONE_DISPOSED, + message: "zone disposed".into(), + }; + let players: Vec<_> = self.core.players.keys().copied().collect(); + for player in players { + self.remove_player(player, LeaveReason::Disposed, Some(bye.clone())); + } + let observers: Vec<_> = self.core.observers.keys().copied().collect(); + for observer in observers { + if let Some(slot) = self.core.observers.remove(&observer) { + self.core.clients.remove(&slot.client); + self.core.server_message(slot.client, &bye); + self.core.outbound.push(Outbound::Close { + client: slot.client, + }); + } + hook!(self.on_unobserve(observer)); + } + hook!(self.on_dispose()); + self.core.pending_kicks.clear(); + self.core.timers.clear(); + self.disposed = true; + } + + fn broadcast(&mut self, message: &ServerMessage) { + let clients: Vec<_> = self.core.clients.keys().copied().collect(); + for client in clients { + self.core.server_message(client, message); + } + } + + fn remove_player( + &mut self, + player: PlayerId, + reason: LeaveReason, + last: Option, + ) { + let Some(slot) = self.core.players.remove(&player) else { + return; + }; + if let Some(client) = slot.client { + self.core.clients.remove(&client); + if let Some(message) = last { + self.core.server_message(client, &message); + } + self.core.outbound.push(Outbound::Close { client }); + } + hook!(self.on_leave(player, reason)); + } + + fn process_kicks(&mut self) { + while let Some((player, message)) = self.core.pending_kicks.pop() { + let kick = ServerMessage::Kick { + code: kick::BY_ZONE, + message, + }; + self.remove_player(player, LeaveReason::Kicked, Some(kick)); + } + } + + fn wake(&mut self) { + let now = self.core.clock.now(); + self.set_tier(Tier::Hot, now); + } + + fn set_tier(&mut self, to: Tier, now: Duration) { + let from = self.core.tier; + if from == to { + return; + } + self.core.tier = to; + self.hot.reset(); + if let Some(idle) = &mut self.idle { + idle.reset(); + } + match to { + Tier::Hot => self.next_patch = now, + Tier::Idle => self.idle_since = now, + Tier::Dormant => {} + } + self.transitions.push((from, to)); + hook!(self.on_tier_changed(from, to)); + self.process_kicks(); + } + + fn evaluate_tier(&mut self, now: Duration) { + let present = !self.core.players.is_empty() || !self.core.clients.is_empty(); + if present || self.zone.has_pending_work() { + self.set_tier(Tier::Hot, now); + return; + } + match self.core.tier { + Tier::Hot => self.set_tier(Tier::Idle, now), + Tier::Idle => { + if now.saturating_sub(self.idle_since) >= self.core.config.dormant_after + && self.core.in_flight() == 0 + && !self.zone.wants_background() + { + self.set_tier(Tier::Dormant, now); + } + } + Tier::Dormant => {} + } + } + + fn deliver_settlements(&mut self) { + let settled = match &mut self.core.facts { + Some(queue) => queue.drain(), + None => return, + }; + for settlement in settled { + hook!(self.on_fact_settled(settlement)); + } + self.process_kicks(); + } + + fn tick_once(&mut self, dt: Duration) { + self.core.tick += 1; + self.core.sim_time += dt; + self.core.dt = dt; + self.deliver_settlements(); + let due = self.core.timers.due(self.core.sim_time); + for (id, timer) in due { + hook!(self.on_timer(id, timer)); + } + hook!(self.on_tick()); + self.process_kicks(); + } + + fn patch(&mut self) { + let mut view = WorldView::default(); + self.zone.replicate(&mut view); + let core = &mut self.core; + let world = EncodedWorld::build(&self.schema, view, &core.config.interest); + let tick = core.tick as u32; + let budget = core.config.byte_budget; + let mut frames = Vec::with_capacity(core.clients.len()); + for (client, slot) in core.clients.iter_mut() { + let (view, ack) = match slot.viewer { + Viewer::Player(p) => match core.players.get(&p) { + Some(player) => (player.view, player.inputs.last_processed()), + None => continue, + }, + Viewer::Observer(o) => match core.observers.get(&o) { + Some(observer) => (observer.view, 0), + None => continue, + }, + }; + let (frame, _) = slot.replica.build_delta( + &self.schema, + &world, + &core.config.interest, + &view, + budget, + tick, + ack, + ); + frames.push(Outbound::Frame { + client: *client, + frame, + }); + } + core.outbound.extend(frames); + } + + /// Run due ticks and patches for the time elapsed on the clock. + pub fn advance(&mut self) -> AdvanceReport { + let mut report = AdvanceReport::default(); + if self.disposed { + return report; + } + let now = self.core.clock.now(); + let elapsed = now.saturating_sub(self.last_advance); + self.last_advance = now; + + let expired: Vec<_> = self + .core + .players + .values() + .filter(|slot| slot.grace_until.is_some_and(|until| until <= now)) + .map(|slot| slot.info.id) + .collect(); + for player in expired { + self.remove_player(player, LeaveReason::Disconnected, None); + } + self.process_kicks(); + self.evaluate_tier(now); + + let (steps, dt) = match self.core.tier { + Tier::Hot => (self.hot.advance(elapsed), self.hot.step()), + Tier::Idle => match &mut self.idle { + Some(idle) => (idle.advance(elapsed), idle.step()), + None => Default::default(), + }, + Tier::Dormant => Default::default(), + }; + report.dropped = steps.dropped; + if !self.frozen { + for _ in 0..steps.steps { + self.tick_once(dt); + } + report.ticks = steps.steps; + } + if report.ticks == 0 { + self.deliver_settlements(); + } + + let patch_interval = rate_to_step(self.core.config.patch_rate); + if self.core.tier == Tier::Hot && !self.core.clients.is_empty() && now >= self.next_patch { + self.patch(); + report.patched = true; + self.next_patch = if now - self.next_patch >= patch_interval { + now + patch_interval + } else { + self.next_patch + patch_interval + }; + } + + let mut wake = match self.core.tier { + Tier::Hot => { + let mut at = now + self.hot.until_next(); + if !self.core.clients.is_empty() { + at = at.min(self.next_patch); + } + Some(at) + } + Tier::Idle => { + let dormant_at = self.idle_since + self.core.config.dormant_after; + let tick_at = self.idle.as_ref().map(|idle| now + idle.until_next()); + Some(tick_at.map_or(dormant_at, |t| t.min(dormant_at)).max(now)) + } + Tier::Dormant => None, + }; + for slot in self.core.players.values() { + if let Some(until) = slot.grace_until { + wake = Some(wake.map_or(until, |w| w.min(until))); + } + } + report.next_wake = wake; + report.transitions = std::mem::take(&mut self.transitions); + report + } +} + +fn default_token() -> String { + use std::collections::hash_map::RandomState; + use std::hash::{BuildHasher, Hasher}; + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let mut out = String::with_capacity(32); + for _ in 0..2 { + let mut hasher = RandomState::new().build_hasher(); + hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed)); + hasher.write_u128(nanos); + out.push_str(&format!("{:016x}", hasher.finish())); + } + out +} diff --git a/distributed_game/src/input.rs b/distributed_game/src/input.rs new file mode 100644 index 000000000..f9454dab7 --- /dev/null +++ b/distributed_game/src/input.rs @@ -0,0 +1,202 @@ +//! Per-player sequenced input buffers. +//! +//! Clients number inputs with a strictly increasing sequence starting at 1. +//! The buffer keeps inputs ordered by sequence, drops duplicates and inputs at +//! or below the last processed sequence, and is bounded (overflow drops the +//! oldest queued input so latency stays bounded). The zone consumes inputs +//! during a tick with a [`ConsumePolicy`]; the highest consumed sequence +//! becomes the **ack** sent back in every Delta so a predicting client can +//! discard confirmed inputs and replay the rest (reconciliation). +//! +//! Sanitizing (clamping/validating game input) happens before buffering via +//! [`Zone::sanitize_input`](crate::Zone::sanitize_input). + +use std::collections::VecDeque; + +/// How a tick consumes queued inputs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsumePolicy { + /// Oldest queued input only (one input per tick; lockstep-style). + Next, + /// Newest queued input; older queued inputs are discarded but acked. + Latest, + /// Every queued input in sequence order. + Drain, +} + +/// Outcome of offering an input to a buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PushOutcome { + /// Queued. + Accepted, + /// Same sequence already queued. + Duplicate, + /// Sequence at or below the last processed sequence. + Stale, + /// Queued after dropping the oldest queued input (buffer full). + AcceptedDroppedOldest, + /// Rejected by the zone's sanitize hook. + Rejected, + /// Sender is not an admitted player. + UnknownClient, +} + +/// One buffered input. +#[derive(Debug, Clone, PartialEq)] +pub struct SequencedInput { + /// Client sequence (>= 1). + pub seq: u32, + /// Client's predicted tick when the input was sampled (informational). + pub client_tick: u32, + /// Sanitized game input. + pub input: I, +} + +/// Bounded, deduplicating, ordered input queue for one player. +#[derive(Debug, Clone)] +pub struct InputBuffer { + queue: VecDeque>, + capacity: usize, + last_processed: u32, + dropped: u64, +} + +impl InputBuffer { + /// Buffer holding at most `capacity` (>= 1) inputs. + pub fn new(capacity: usize) -> Self { + Self { + queue: VecDeque::new(), + capacity: capacity.max(1), + last_processed: 0, + dropped: 0, + } + } + + /// Highest consumed sequence (0 = none). Sent to the client as `ack_seq`. + pub fn last_processed(&self) -> u32 { + self.last_processed + } + + /// Queued input count. + pub fn len(&self) -> usize { + self.queue.len() + } + + /// True when nothing is queued. + pub fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + /// Inputs dropped by overflow so far. + pub fn dropped(&self) -> u64 { + self.dropped + } + + /// Check whether `seq` would be accepted, without inserting. + pub fn precheck(&self, seq: u32) -> Option { + if seq <= self.last_processed { + return Some(PushOutcome::Stale); + } + if self.queue.iter().any(|queued| queued.seq == seq) { + return Some(PushOutcome::Duplicate); + } + None + } + + /// Insert in sequence order. + pub fn push(&mut self, seq: u32, client_tick: u32, input: I) -> PushOutcome { + if let Some(outcome) = self.precheck(seq) { + return outcome; + } + let position = self + .queue + .iter() + .position(|queued| queued.seq > seq) + .unwrap_or(self.queue.len()); + self.queue.insert( + position, + SequencedInput { + seq, + client_tick, + input, + }, + ); + if self.queue.len() > self.capacity { + self.queue.pop_front(); + self.dropped += 1; + return PushOutcome::AcceptedDroppedOldest; + } + PushOutcome::Accepted + } + + /// Consume per `policy`, advancing the ack to the highest consumed or + /// discarded sequence. + pub fn take(&mut self, policy: ConsumePolicy) -> Vec> { + let taken: Vec<_> = match policy { + ConsumePolicy::Next => self.queue.pop_front().into_iter().collect(), + ConsumePolicy::Drain => self.queue.drain(..).collect(), + ConsumePolicy::Latest => { + let latest = self.queue.pop_back(); + self.queue.clear(); + latest.into_iter().collect() + } + }; + if let Some(last) = taken.last() { + self.last_processed = self.last_processed.max(last.seq); + } + taken + } + + /// Reset the queue (keeps the ack so stale resends are still rejected). + pub fn clear(&mut self) { + self.queue.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dedupes_orders_and_acks() { + let mut buf = InputBuffer::new(8); + assert_eq!(buf.push(2, 0, 'b'), PushOutcome::Accepted); + assert_eq!(buf.push(1, 0, 'a'), PushOutcome::Accepted); + assert_eq!(buf.push(2, 0, 'x'), PushOutcome::Duplicate); + let next = buf.take(ConsumePolicy::Next); + assert_eq!(next[0].input, 'a'); + assert_eq!(buf.last_processed(), 1); + assert_eq!(buf.push(1, 0, 'z'), PushOutcome::Stale); + assert_eq!(buf.take(ConsumePolicy::Drain).len(), 1); + assert_eq!(buf.last_processed(), 2); + } + + #[test] + fn latest_discards_but_acks_older() { + let mut buf = InputBuffer::new(8); + for seq in 1..=5 { + buf.push(seq, 0, seq); + } + let taken = buf.take(ConsumePolicy::Latest); + assert_eq!(taken.len(), 1); + assert_eq!(taken[0].input, 5); + assert_eq!(buf.last_processed(), 5); + assert!(buf.is_empty()); + } + + #[test] + fn bounded_drops_oldest() { + let mut buf = InputBuffer::new(2); + buf.push(1, 0, ()); + buf.push(2, 0, ()); + assert_eq!(buf.push(3, 0, ()), PushOutcome::AcceptedDroppedOldest); + assert_eq!(buf.len(), 2); + assert_eq!(buf.dropped(), 1); + let seqs: Vec<_> = buf + .take(ConsumePolicy::Drain) + .iter() + .map(|i| i.seq) + .collect(); + assert_eq!(seqs, vec![2, 3]); + } +} diff --git a/distributed_game/src/interest.rs b/distributed_game/src/interest.rs new file mode 100644 index 000000000..b041cdc66 --- /dev/null +++ b/distributed_game/src/interest.rs @@ -0,0 +1,110 @@ +//! Interest management: a uniform spatial grid and circular views. +//! +//! Each connected client has a [`View`] (center + radius) on the zone's 2D +//! interest plane (games in 3D usually map x/z). An entity *enters* a view +//! when within `radius` and *leaves* only beyond `radius * (1 + leave_margin)` +//! (hysteresis prevents create/remove flicker at the edge). Entities marked +//! global are visible to everyone regardless of distance. + +use std::collections::HashMap; + +/// A client's area of interest. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct View { + /// Center x. + pub x: f32, + /// Center y. + pub y: f32, + /// Enter radius. + pub radius: f32, +} + +impl View { + /// View at (x, y) with `radius`. + pub fn new(x: f32, y: f32, radius: f32) -> Self { + Self { x, y, radius } + } + + /// Distance from the view center. + pub fn distance(&self, x: f32, y: f32) -> f32 { + ((x - self.x).powi(2) + (y - self.y).powi(2)).sqrt() + } +} + +/// Grid and hysteresis settings. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct InterestConfig { + /// Grid cell edge length (world units); ~view radius / 2 works well. + pub cell_size: f32, + /// Extra fraction of the radius before a known entity leaves the view. + pub leave_margin: f32, +} + +impl Default for InterestConfig { + fn default() -> Self { + Self { + cell_size: 16.0, + leave_margin: 0.1, + } + } +} + +/// Uniform grid of entity indices. +#[derive(Debug, Clone)] +pub struct SpatialGrid { + cell: f32, + cells: HashMap<(i32, i32), Vec>, +} + +impl SpatialGrid { + /// Empty grid with `cell_size` (clamped to > 0). + pub fn new(cell_size: f32) -> Self { + Self { + cell: if cell_size > 0.0 { cell_size } else { 1.0 }, + cells: HashMap::new(), + } + } + + fn key(&self, x: f32, y: f32) -> (i32, i32) { + ( + (x / self.cell).floor() as i32, + (y / self.cell).floor() as i32, + ) + } + + /// Remove everything. + pub fn clear(&mut self) { + self.cells.clear(); + } + + /// Index an item at (x, y). + pub fn insert(&mut self, item: u32, x: f32, y: f32) { + let key = self.key(x, y); + self.cells.entry(key).or_default().push(item); + } + + /// Items in cells overlapping the circle's bounding box (caller filters + /// by exact distance). + pub fn query(&self, x: f32, y: f32, radius: f32, out: &mut Vec) { + let r = radius.max(0.0); + let (x0, y0) = self.key(x - r, y - r); + let (x1, y1) = self.key(x + r, y + r); + // Large views degrade to scanning occupied cells. + let span = (i64::from(x1) - i64::from(x0) + 1) * (i64::from(y1) - i64::from(y0) + 1); + if span > self.cells.len() as i64 { + for (&(cx, cy), items) in &self.cells { + if (x0..=x1).contains(&cx) && (y0..=y1).contains(&cy) { + out.extend_from_slice(items); + } + } + return; + } + for cx in x0..=x1 { + for cy in y0..=y1 { + if let Some(items) = self.cells.get(&(cx, cy)) { + out.extend_from_slice(items); + } + } + } + } +} diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs new file mode 100644 index 000000000..f226243c2 --- /dev/null +++ b/distributed_game/src/lib.rs @@ -0,0 +1,62 @@ +//! Authoritative multiplayer zone runtime for `distributed`. +//! +//! - [`Zone`] (implemented by the game) + [`ZoneHost`] (runtime): lifecycle +//! hooks, capacity, per-zone timers, fixed timestep with catch-up cap, +//! activity tiers (Hot / Idle / Dormant), sequenced input buffers with acks. +//! - Determinism: injectable [`Clock`] and per-zone seeded [`ZoneRng`]. +//! - Durable outcomes: zones emit [`Fact`]s during a tick; a [`FactSink`] +//! commits them asynchronously and settlements come back on later ticks. +//! With the `cell` feature, [`cell::CellFactSink`] dispatches them into a +//! `distributed` `AggregateCell` idempotently with a server-built Session. +//! - Replication: an [`EntitySchema`] shipped in Welcome, per-client deltas +//! against last-sent state, spatial interest and a byte budget with +//! priority accumulation. Wire format: [`protocol`] / `PROTOCOL.md`. +//! +//! Physics is out of scope: games bring their own and run it in `on_tick`. +//! +//! # Extension seams (later phases) +//! Hibernation reads [`Tier::Dormant`]; directory/placement wraps +//! [`ZoneHost::new`] / [`ZoneHost::dispose`]; handoff sagas start from +//! [`ZoneHost::handoff`] + [`LeaveReason::Handoff`]; content barriers use +//! [`ZoneHost::freeze`] / [`ZoneHost::resume`]; metrics hook +//! [`AdvanceReport`] and [`replication::DeltaStats`]. + +#![warn(missing_docs)] + +#[cfg(feature = "cell")] +pub mod cell; +pub mod clock; +pub mod facts; +pub mod host; +pub mod input; +pub mod interest; +pub mod protocol; +pub mod replication; +pub mod rng; +pub mod schema; +pub mod stamp; +pub mod timers; +pub mod timestep; +pub mod zone; + +pub use clock::{Clock, ManualClock, SystemClock}; +#[cfg(feature = "runtime")] +pub use facts::spawn_fact_worker; +pub use facts::{ + fact_channel, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, FactReceipt, + FactSettlement, FactSink, MemoryFactSink, RetryPolicy, +}; +pub use host::{AdvanceReport, Ctx, HostConfig, JoinError, Joined, Outbound, ZoneHost}; +pub use input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; +pub use interest::{InterestConfig, View}; +pub use protocol::{ClientMessage, ClientMirror, Role, ServerMessage, PROTOCOL_VERSION}; +pub use replication::{EntityState, WorldView}; +pub use rng::{Fnv64, ZoneRng}; +pub use schema::{EntitySchema, FieldType, FieldValue, KindDef}; +pub use stamp::{stamp_metadata, FactStamp}; +pub use timers::TimerId; +pub use timestep::FixedTimestep; +pub use zone::{ + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, + Tier, Viewer, Zone, +}; diff --git a/distributed_game/src/protocol/messages.rs b/distributed_game/src/protocol/messages.rs new file mode 100644 index 000000000..2c153fbd7 --- /dev/null +++ b/distributed_game/src/protocol/messages.rs @@ -0,0 +1,638 @@ +//! Message types and their codecs (`PROTOCOL.md` §6–§7). + +use std::collections::BTreeMap; + +use super::wire::{DecodeError, Reader, Writer}; +use crate::schema::{EntitySchema, FieldValue}; + +/// Wire protocol version spoken by this crate. +pub const PROTOCOL_VERSION: u32 = 1; + +/// Message type bytes. +pub mod tag { + /// Client → server Hello. + pub const HELLO: u8 = 0x01; + /// Client → server Input. + pub const INPUT: u8 = 0x02; + /// Client → server Ping. + pub const PING: u8 = 0x03; + /// Client → server Leave. + pub const LEAVE: u8 = 0x04; + /// Server → client Welcome. + pub const WELCOME: u8 = 0x80; + /// Server → client Delta. + pub const DELTA: u8 = 0x81; + /// Server → client Event. + pub const EVENT: u8 = 0x82; + /// Server → client Pong. + pub const PONG: u8 = 0x83; + /// Server → client Freeze. + pub const FREEZE: u8 = 0x84; + /// Server → client Resume. + pub const RESUME: u8 = 0x85; + /// Server → client Handoff. + pub const HANDOFF: u8 = 0x86; + /// Server → client Kick. + pub const KICK: u8 = 0x87; + /// Server → client Error. + pub const ERROR: u8 = 0x88; +} + +/// Kick reason codes. +pub mod kick { + /// Removed by zone logic. + pub const BY_ZONE: u32 = 1; + /// Same principal connected again; this connection was replaced. + pub const REPLACED: u32 = 2; + /// Server shutting down. + pub const SHUTDOWN: u32 = 3; + /// Input rate limit abuse. + pub const RATE_LIMITED: u32 = 4; + /// Zone disposed. + pub const ZONE_DISPOSED: u32 = 5; + /// Outbound queue overflow (client too slow). + pub const SLOW_CONSUMER: u32 = 6; +} + +/// Error codes. +pub mod error { + /// Malformed or unexpected message. + pub const BAD_MESSAGE: u32 = 1; + /// Ticket missing, invalid, expired or replayed. + pub const UNAUTHORIZED: u32 = 2; + /// Zone `on_auth` rejected the join. + pub const REJECTED: u32 = 3; + /// Zone at capacity. + pub const ZONE_FULL: u32 = 4; + /// Protocol or content version mismatch. + pub const VERSION_MISMATCH: u32 = 5; + /// Input dropped by rate limiting (sent at most once per second). + pub const RATE_LIMITED: u32 = 6; + /// Unknown zone. + pub const NOT_FOUND: u32 = 7; + /// Reconnect token unknown or grace window elapsed. + pub const RECONNECT_FAILED: u32 = 8; +} + +/// Client handshake. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Hello { + /// Must equal [`PROTOCOL_VERSION`]. + pub protocol_version: u32, + /// Game content version the client was built against. + pub content_version: String, + /// Game-defined capability bits (opaque to the runtime). + pub capabilities: u32, + /// Signed admission ticket (empty when reconnecting). + pub ticket: String, + /// Reconnect token from a previous Welcome (empty for a fresh join). + pub reconnect_token: String, +} + +/// Messages a client sends. +#[derive(Debug, Clone, PartialEq)] +pub enum ClientMessage { + /// Handshake; must be the first message. + Hello(Hello), + /// Sequenced input. + Input { + /// Strictly increasing per connection lifetime, starting at 1. + seq: u32, + /// Client's predicted tick when sampled. + client_tick: u32, + /// Game-defined input bytes. + payload: Vec, + }, + /// Clock sync probe. + Ping { + /// Client clock in ms (echoed). + client_time: f64, + }, + /// Graceful leave (no reconnect grace). + Leave, +} + +impl ClientMessage { + /// Encode one message (one WebSocket binary frame). + pub fn encode(&self) -> Vec { + let mut w = Writer::new(); + match self { + Self::Hello(h) => { + w.u8(tag::HELLO) + .varuint(h.protocol_version) + .string(&h.content_version) + .varuint(h.capabilities) + .string(&h.ticket) + .string(&h.reconnect_token); + } + Self::Input { + seq, + client_tick, + payload, + } => { + w.u8(tag::INPUT) + .varuint(*seq) + .varuint(*client_tick) + .bytes(payload); + } + Self::Ping { client_time } => { + w.u8(tag::PING).f64(*client_time); + } + Self::Leave => { + w.u8(tag::LEAVE); + } + } + w.into_bytes() + } + + /// Decode one message. + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let message = match r.u8()? { + tag::HELLO => Self::Hello(Hello { + protocol_version: r.varuint()?, + content_version: r.string()?, + capabilities: r.varuint()?, + ticket: r.string()?, + reconnect_token: r.string()?, + }), + tag::INPUT => Self::Input { + seq: r.varuint()?, + client_tick: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + tag::PING => Self::Ping { + client_time: r.f64()?, + }, + tag::LEAVE => Self::Leave, + other => return Err(DecodeError::UnknownMessage(other)), + }; + r.finish()?; + Ok(message) + } +} + +/// Connection role. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Owns a player in the zone. Wire `0`. + Player, + /// Read-only observer. Wire `1`. + Observer, +} + +/// Server handshake reply. +#[derive(Debug, Clone, PartialEq)] +pub struct Welcome { + /// Opaque session id (stable across reconnects of the same player). + pub session_id: String, + /// Zone joined. + pub zone_id: String, + /// Admitted role. + pub role: Role, + /// Simulation ticks per second (Hot tier). + pub tick_rate: u32, + /// Deltas per second. + pub patch_rate: u32, + /// Current server tick. + pub server_tick: u32, + /// Server clock in ms. + pub server_time: f64, + /// Token for Hello.reconnect_token after a drop. + pub reconnect_token: String, + /// Server content version. + pub content_version: String, + /// Replicated entity schema. + pub schema: EntitySchema, +} + +/// Full entity state for a create. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityCreate { + /// Entity id. + pub id: u32, + /// Kind id. + pub kind: u16, + /// Every field, schema order. + pub fields: Vec, +} + +/// Changed fields of a known entity. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityUpdate { + /// Entity id. + pub id: u32, + /// Bit `i` set = field `i` present. + pub mask: u32, + /// Present fields in ascending index order. + pub fields: Vec, +} + +/// One replication patch. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Delta { + /// Server tick the state belongs to. + pub server_tick: u32, + /// Highest processed input sequence of this client (0 = none). + pub ack_seq: u32, + /// Ids to forget (applied first). + pub removes: Vec, + /// New entities (applied second). + pub creates: Vec, + /// Field changes (applied last). + pub updates: Vec, +} + +/// Freeze/Resume notice. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Notice { + /// Machine-readable reason. + pub reason: String, + /// Version involved (e.g. content version being rolled out). + pub version: String, + /// Human-readable notes. + pub notes: String, +} + +/// Messages the server sends. +#[derive(Debug, Clone, PartialEq)] +pub enum ServerMessage { + /// Handshake accepted. + Welcome(Welcome), + /// Replication patch. + Delta(Delta), + /// Reliable game event. + Event { + /// Game-defined event type. + type_id: u32, + /// Game-defined payload. + payload: Vec, + }, + /// Clock sync reply. + Pong { + /// Echoed client time (ms). + client_time: f64, + /// Server clock (ms). + server_time: f64, + }, + /// Simulation frozen (inputs ignored until Resume). + Freeze(Notice), + /// Simulation resumed. + Resume(Notice), + /// Move to another zone. + Handoff { + /// Destination zone id. + target_zone: String, + /// Ticket to present in the next Hello. + transfer_ticket: String, + }, + /// Removed from the zone; the server closes the socket. + Kick { + /// See [`kick`]. + code: u32, + /// Text. + message: String, + }, + /// Request-level error; handshake errors are followed by close. + Error { + /// See [`error`]. + code: u32, + /// Text. + message: String, + }, +} + +/// What a Delta decoder/encoder needs to know about the client's view. +pub trait EntityKinds { + /// Schema from the Welcome. + fn schema(&self) -> Option<&EntitySchema>; + /// Kind of a known entity id. + fn kind_of(&self, id: u32) -> Option; +} + +/// No schema: Deltas cannot be decoded. +impl EntityKinds for () { + fn schema(&self) -> Option<&EntitySchema> { + None + } + fn kind_of(&self, _: u32) -> Option { + None + } +} + +/// Schema plus an explicit id→kind table (fixtures/tests). +impl EntityKinds for (EntitySchema, BTreeMap) { + fn schema(&self) -> Option<&EntitySchema> { + Some(&self.0) + } + fn kind_of(&self, id: u32) -> Option { + self.1.get(&id).copied() + } +} + +impl ServerMessage { + /// Encode one message. Deltas need `kinds` (schema + known ids). + pub fn encode(&self, kinds: &dyn EntityKinds) -> Result, DecodeError> { + let mut w = Writer::new(); + match self { + Self::Welcome(m) => { + w.u8(tag::WELCOME) + .string(&m.session_id) + .string(&m.zone_id) + .u8(match m.role { + Role::Player => 0, + Role::Observer => 1, + }) + .varuint(m.tick_rate) + .varuint(m.patch_rate) + .varuint(m.server_tick) + .f64(m.server_time) + .string(&m.reconnect_token) + .string(&m.content_version); + m.schema.encode(&mut w); + } + Self::Delta(d) => encode_delta(&mut w, d, kinds)?, + Self::Event { type_id, payload } => { + w.u8(tag::EVENT).varuint(*type_id).bytes(payload); + } + Self::Pong { + client_time, + server_time, + } => { + w.u8(tag::PONG).f64(*client_time).f64(*server_time); + } + Self::Freeze(n) | Self::Resume(n) => { + let t = if matches!(self, Self::Freeze(_)) { + tag::FREEZE + } else { + tag::RESUME + }; + w.u8(t) + .string(&n.reason) + .string(&n.version) + .string(&n.notes); + } + Self::Handoff { + target_zone, + transfer_ticket, + } => { + w.u8(tag::HANDOFF) + .string(target_zone) + .string(transfer_ticket); + } + Self::Kick { code, message } => { + w.u8(tag::KICK).varuint(*code).string(message); + } + Self::Error { code, message } => { + w.u8(tag::ERROR).varuint(*code).string(message); + } + } + Ok(w.into_bytes()) + } + + /// Decode one message. Deltas need `kinds`. + pub fn decode(bytes: &[u8], kinds: &dyn EntityKinds) -> Result { + let mut r = Reader::new(bytes); + let message = match r.u8()? { + tag::WELCOME => Self::Welcome(Welcome { + session_id: r.string()?, + zone_id: r.string()?, + role: match r.u8()? { + 0 => Role::Player, + 1 => Role::Observer, + _ => return Err(DecodeError::Invalid("role")), + }, + tick_rate: r.varuint()?, + patch_rate: r.varuint()?, + server_tick: r.varuint()?, + server_time: r.f64()?, + reconnect_token: r.string()?, + content_version: r.string()?, + schema: EntitySchema::decode(&mut r)?, + }), + tag::DELTA => Self::Delta(decode_delta(&mut r, kinds)?), + tag::EVENT => Self::Event { + type_id: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + tag::PONG => Self::Pong { + client_time: r.f64()?, + server_time: r.f64()?, + }, + t @ (tag::FREEZE | tag::RESUME) => { + let notice = Notice { + reason: r.string()?, + version: r.string()?, + notes: r.string()?, + }; + if t == tag::FREEZE { + Self::Freeze(notice) + } else { + Self::Resume(notice) + } + } + tag::HANDOFF => Self::Handoff { + target_zone: r.string()?, + transfer_ticket: r.string()?, + }, + tag::KICK => Self::Kick { + code: r.varuint()?, + message: r.string()?, + }, + tag::ERROR => Self::Error { + code: r.varuint()?, + message: r.string()?, + }, + other => return Err(DecodeError::UnknownMessage(other)), + }; + r.finish()?; + Ok(message) + } +} + +fn kind_lookup( + id: u32, + created: &BTreeMap, + kinds: &dyn EntityKinds, +) -> Result { + created + .get(&id) + .copied() + .or_else(|| kinds.kind_of(id)) + .ok_or(DecodeError::UnknownEntity(id)) +} + +fn encode_delta(w: &mut Writer, d: &Delta, kinds: &dyn EntityKinds) -> Result<(), DecodeError> { + let schema = kinds + .schema() + .ok_or(DecodeError::Invalid("delta needs a schema"))?; + w.u8(tag::DELTA).varuint(d.server_tick).varuint(d.ack_seq); + w.varuint(d.removes.len() as u32); + for id in &d.removes { + w.varuint(*id); + } + let mut created = BTreeMap::new(); + w.varuint(d.creates.len() as u32); + for c in &d.creates { + let kind = schema.get(c.kind).ok_or(DecodeError::UnknownEntity(c.id))?; + if kind.fields.len() != c.fields.len() { + return Err(DecodeError::Invalid("create must carry every field")); + } + w.varuint(c.id).varuint(u32::from(c.kind)); + for (def, value) in kind.fields.iter().zip(&c.fields) { + def.ty.encode(w, value); + } + created.insert(c.id, c.kind); + } + w.varuint(d.updates.len() as u32); + for u in &d.updates { + let kind_id = kind_lookup(u.id, &created, kinds)?; + let kind = schema + .get(kind_id) + .ok_or(DecodeError::UnknownEntity(u.id))?; + w.varuint(u.id).varuint(u.mask); + let mut values = u.fields.iter(); + for (index, def) in kind.fields.iter().enumerate() { + if u.mask & (1 << index) != 0 { + let value = values + .next() + .ok_or(DecodeError::Invalid("mask/field count mismatch"))?; + def.ty.encode(w, value); + } + } + } + Ok(()) +} + +fn decode_delta(r: &mut Reader<'_>, kinds: &dyn EntityKinds) -> Result { + let schema = kinds + .schema() + .ok_or(DecodeError::Invalid("delta needs a schema"))?; + let mut delta = Delta { + server_tick: r.varuint()?, + ack_seq: r.varuint()?, + ..Delta::default() + }; + for _ in 0..r.varuint()? { + delta.removes.push(r.varuint()?); + } + let mut created = BTreeMap::new(); + for _ in 0..r.varuint()? { + let id = r.varuint()?; + let kind_id = u16::try_from(r.varuint()?).map_err(|_| DecodeError::Invalid("kind"))?; + let kind = schema.get(kind_id).ok_or(DecodeError::UnknownEntity(id))?; + let mut fields = Vec::with_capacity(kind.fields.len()); + for def in &kind.fields { + fields.push(def.ty.decode(r)?); + } + created.insert(id, kind_id); + delta.creates.push(EntityCreate { + id, + kind: kind_id, + fields, + }); + } + for _ in 0..r.varuint()? { + let id = r.varuint()?; + let kind = schema + .get(kind_lookup(id, &created, kinds)?) + .ok_or(DecodeError::UnknownEntity(id))?; + let mask = r.varuint()?; + if kind.fields.len() < 32 && mask >> kind.fields.len() != 0 { + return Err(DecodeError::Invalid("mask names a field the kind lacks")); + } + let mut fields = Vec::new(); + for (index, def) in kind.fields.iter().enumerate() { + if mask & (1 << index) != 0 { + fields.push(def.ty.decode(r)?); + } + } + delta.updates.push(EntityUpdate { id, mask, fields }); + } + Ok(delta) +} + +/// Mirrored entity on a client. +#[derive(Debug, Clone, PartialEq)] +pub struct MirrorEntity { + /// Kind id. + pub kind: u16, + /// Current decoded field values. + pub fields: Vec, +} + +/// Reference client-side state: decodes server frames and applies Deltas. +/// +/// This is the normative behaviour a client implementation (e.g. JS) must +/// match; it is also what the crate's own tests use. +#[derive(Debug, Clone, Default)] +pub struct ClientMirror { + /// Last Welcome. + pub welcome: Option, + /// Known entities. + pub entities: BTreeMap, + /// Last Delta tick. + pub server_tick: u32, + /// Last acked input sequence. + pub ack_seq: u32, +} + +impl EntityKinds for ClientMirror { + fn schema(&self) -> Option<&EntitySchema> { + self.welcome.as_ref().map(|w| &w.schema) + } + fn kind_of(&self, id: u32) -> Option { + self.entities.get(&id).map(|e| e.kind) + } +} + +impl ClientMirror { + /// Empty mirror. + pub fn new() -> Self { + Self::default() + } + + /// Decode a frame and apply it. Welcome resets all entities. + pub fn apply(&mut self, frame: &[u8]) -> Result { + let message = ServerMessage::decode(frame, self)?; + match &message { + ServerMessage::Welcome(w) => { + self.welcome = Some(w.clone()); + self.entities.clear(); + self.server_tick = w.server_tick; + } + ServerMessage::Delta(d) => { + for id in &d.removes { + self.entities.remove(id); + } + for c in &d.creates { + self.entities.insert( + c.id, + MirrorEntity { + kind: c.kind, + fields: c.fields.clone(), + }, + ); + } + for u in &d.updates { + let entity = self + .entities + .get_mut(&u.id) + .ok_or(DecodeError::UnknownEntity(u.id))?; + let mut values = u.fields.iter(); + for (index, slot) in entity.fields.iter_mut().enumerate() { + if u.mask & (1 << index) != 0 { + if let Some(v) = values.next() { + *slot = v.clone(); + } + } + } + } + self.server_tick = d.server_tick; + self.ack_seq = d.ack_seq; + } + _ => {} + } + Ok(message) + } +} diff --git a/distributed_game/src/protocol/mod.rs b/distributed_game/src/protocol/mod.rs new file mode 100644 index 000000000..b1ac0eded --- /dev/null +++ b/distributed_game/src/protocol/mod.rs @@ -0,0 +1,30 @@ +//! Binary wire protocol (normative spec: `PROTOCOL.md`). +//! +//! One message per WebSocket binary frame; the first byte is the message +//! type. [`wire`] holds the primitives, [`messages`] the message codecs and +//! the reference [`ClientMirror`](messages::ClientMirror). + +pub mod messages; +pub mod wire; + +pub use messages::*; +pub use wire::{DecodeError, Reader, Writer}; + +/// Length-prefix a frame (`varuint` length) for stream transports that lack +/// message boundaries (`PROTOCOL.md` §1.2). +pub fn frame_stream(message: &[u8]) -> Vec { + let mut w = Writer::new(); + w.bytes(message); + w.into_bytes() +} + +/// Split one length-prefixed frame off the front of `buf`; returns the frame +/// and the bytes consumed, or `None` when more data is needed. +pub fn unframe_stream(buf: &[u8]) -> Result, DecodeError> { + let mut r = Reader::new(buf); + match r.bytes() { + Ok(frame) => Ok(Some((frame, buf.len() - r.remaining()))), + Err(DecodeError::UnexpectedEof) => Ok(None), + Err(e) => Err(e), + } +} diff --git a/distributed_game/src/protocol/wire.rs b/distributed_game/src/protocol/wire.rs new file mode 100644 index 000000000..b81f77346 --- /dev/null +++ b/distributed_game/src/protocol/wire.rs @@ -0,0 +1,287 @@ +//! Primitive wire encodings (see `PROTOCOL.md` §2). +//! +//! All multi-byte fixed-width numbers are little-endian. `varuint` is +//! unsigned LEB128 (7 bits per byte, low group first, high bit = continue); +//! encoders always emit the minimal form. `varint` is a zigzag-mapped +//! `varuint`. Strings are UTF-8 prefixed by a `varuint` byte length; short +//! strings use a single `u8` length. + +use std::fmt; + +/// Largest `string`/`bytes` length accepted by decoders (1 MiB). +pub const MAX_BLOB_LEN: usize = 1 << 20; + +/// Decoding failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DecodeError { + /// Input ended mid-value. + UnexpectedEof, + /// A varuint exceeded 32 bits. + VarintOverflow, + /// A string was not valid UTF-8. + InvalidUtf8, + /// Unknown message type byte. + UnknownMessage(u8), + /// Unknown field type tag in a schema. + UnknownFieldType(u8), + /// Delta referenced an entity kind / id the decoder does not know. + UnknownEntity(u32), + /// Structurally invalid value. + Invalid(&'static str), + /// Bytes left over after a complete message. + TrailingBytes(usize), +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self:?}") + } +} + +impl std::error::Error for DecodeError {} + +/// Append-only encoder. +#[derive(Debug, Default, Clone)] +pub struct Writer { + buf: Vec, +} + +impl Writer { + /// Empty writer. + pub fn new() -> Self { + Self::default() + } + + /// Bytes written so far. + pub fn len(&self) -> usize { + self.buf.len() + } + + /// True if nothing was written. + pub fn is_empty(&self) -> bool { + self.buf.is_empty() + } + + /// Finish and take the bytes. + pub fn into_bytes(self) -> Vec { + self.buf + } + + /// Borrow the bytes. + pub fn as_bytes(&self) -> &[u8] { + &self.buf + } + + /// Discard contents, keeping capacity. + pub fn clear(&mut self) { + self.buf.clear(); + } + + /// Raw bytes, no prefix. + pub fn raw(&mut self, bytes: &[u8]) -> &mut Self { + self.buf.extend_from_slice(bytes); + self + } + + /// One byte. + pub fn u8(&mut self, v: u8) -> &mut Self { + self.buf.push(v); + self + } + + /// `0x00`/`0x01`. + pub fn bool(&mut self, v: bool) -> &mut Self { + self.u8(u8::from(v)) + } + + /// Unsigned LEB128 (max 5 bytes). + pub fn varuint(&mut self, mut v: u32) -> &mut Self { + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + self.buf.push(byte); + return self; + } + self.buf.push(byte | 0x80); + } + } + + /// Zigzag-mapped signed varint: `(v << 1) ^ (v >> 31)`. + pub fn varint(&mut self, v: i32) -> &mut Self { + self.varuint(((v << 1) ^ (v >> 31)) as u32) + } + + /// IEEE-754 binary32, little-endian. + pub fn f32(&mut self, v: f32) -> &mut Self { + self.raw(&v.to_le_bytes()) + } + + /// IEEE-754 binary64, little-endian. + pub fn f64(&mut self, v: f64) -> &mut Self { + self.raw(&v.to_le_bytes()) + } + + /// `varuint` length + UTF-8. + pub fn string(&mut self, v: &str) -> &mut Self { + self.bytes(v.as_bytes()) + } + + /// `u8` length + UTF-8; truncated at a char boundary to <= 255 bytes. + pub fn short_string(&mut self, v: &str) -> &mut Self { + let mut end = v.len().min(255); + while !v.is_char_boundary(end) { + end -= 1; + } + self.u8(end as u8).raw(&v.as_bytes()[..end]) + } + + /// `varuint` length + raw bytes. + pub fn bytes(&mut self, v: &[u8]) -> &mut Self { + self.varuint(v.len() as u32).raw(v) + } +} + +/// Cursor over a byte slice. +#[derive(Debug, Clone)] +pub struct Reader<'a> { + buf: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + /// Read from the start of `buf`. + pub fn new(buf: &'a [u8]) -> Self { + Self { buf, pos: 0 } + } + + /// Bytes not yet consumed. + pub fn remaining(&self) -> usize { + self.buf.len() - self.pos + } + + /// Error unless fully consumed. + pub fn finish(&self) -> Result<(), DecodeError> { + match self.remaining() { + 0 => Ok(()), + n => Err(DecodeError::TrailingBytes(n)), + } + } + + /// Next `n` raw bytes. + pub fn raw(&mut self, n: usize) -> Result<&'a [u8], DecodeError> { + if self.remaining() < n { + return Err(DecodeError::UnexpectedEof); + } + let slice = &self.buf[self.pos..self.pos + n]; + self.pos += n; + Ok(slice) + } + + /// One byte. + pub fn u8(&mut self) -> Result { + Ok(self.raw(1)?[0]) + } + + /// Strict bool (`0` or `1`). + pub fn bool(&mut self) -> Result { + match self.u8()? { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(DecodeError::Invalid("bool must be 0 or 1")), + } + } + + /// Unsigned LEB128 up to 32 bits. + pub fn varuint(&mut self) -> Result { + let mut value: u32 = 0; + for index in 0..5 { + let byte = self.u8()?; + if index == 4 && byte > 0x0f { + return Err(DecodeError::VarintOverflow); + } + value |= u32::from(byte & 0x7f) << (7 * index); + if byte & 0x80 == 0 { + return Ok(value); + } + } + Err(DecodeError::VarintOverflow) + } + + /// Zigzag signed varint. + pub fn varint(&mut self) -> Result { + let raw = self.varuint()?; + Ok(((raw >> 1) as i32) ^ -((raw & 1) as i32)) + } + + /// binary32 LE. + pub fn f32(&mut self) -> Result { + let bytes = self.raw(4)?; + Ok(f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + /// binary64 LE. + pub fn f64(&mut self) -> Result { + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(self.raw(8)?); + Ok(f64::from_le_bytes(bytes)) + } + + /// `varuint` length + raw bytes. + pub fn bytes(&mut self) -> Result<&'a [u8], DecodeError> { + let len = self.varuint()? as usize; + if len > MAX_BLOB_LEN { + return Err(DecodeError::Invalid("length exceeds 1 MiB")); + } + self.raw(len) + } + + /// `varuint` length + UTF-8. + pub fn string(&mut self) -> Result { + let bytes = self.bytes()?; + String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::InvalidUtf8) + } + + /// `u8` length + UTF-8. + pub fn short_string(&mut self) -> Result { + let len = self.u8()? as usize; + String::from_utf8(self.raw(len)?.to_vec()).map_err(|_| DecodeError::InvalidUtf8) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn varuint_round_trips_and_is_minimal() { + for (value, hex) in [ + (0u32, "00"), + (1, "01"), + (127, "7f"), + (128, "8001"), + (300, "ac02"), + (u32::MAX, "ffffffff0f"), + ] { + let mut w = Writer::new(); + w.varuint(value); + let got: String = w.as_bytes().iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(got, hex); + assert_eq!(Reader::new(w.as_bytes()).varuint().unwrap(), value); + } + assert_eq!( + Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x10]).varuint(), + Err(DecodeError::VarintOverflow) + ); + } + + #[test] + fn zigzag_round_trips() { + for (value, raw) in [(0, 0u32), (-1, 1), (1, 2), (-2, 3), (i32::MIN, u32::MAX)] { + let mut w = Writer::new(); + w.varint(value); + assert_eq!(Reader::new(w.as_bytes()).varuint().unwrap(), raw); + assert_eq!(Reader::new(w.as_bytes()).varint().unwrap(), value); + } + } +} diff --git a/distributed_game/src/replication.rs b/distributed_game/src/replication.rs new file mode 100644 index 000000000..3b434daba --- /dev/null +++ b/distributed_game/src/replication.rs @@ -0,0 +1,395 @@ +//! Per-client delta replication with interest and a byte budget. +//! +//! Each patch the zone describes its replicated entities into a +//! [`WorldView`]. Field values are encoded once per patch; every client then +//! gets a Delta computed against **what was last sent to that client** +//! (valid because the transport is reliable and ordered): +//! +//! - entities entering the client's [`View`] → *create* (all fields); +//! - known entities with changed encoded fields → *update* (bitmask + fields); +//! - known entities gone or out of view → *remove* (id only, never budgeted). +//! +//! Creates and updates compete for the per-client byte budget. Each candidate +//! gets `priority = kind.priority × entity.priority × max(field priority) × +//! 1/(1 + distance/radius)` added to a per-entity **accumulator**; candidates +//! are sent in accumulator order until the budget is spent and sent entities +//! reset to zero. Starved entities keep accumulating, so everything is +//! eventually sent. At least one candidate is sent per patch even if it alone +//! exceeds the budget. Change detection compares encoded bytes, so +//! sub-quantum jitter never costs bandwidth. + +use std::collections::{HashMap, HashSet}; + +use crate::interest::{InterestConfig, SpatialGrid, View}; +use crate::protocol::{tag, Writer}; +use crate::schema::{EntitySchema, FieldValue}; + +/// One replicated entity as described by the zone for this patch. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityState { + /// Game-assigned id (unique within the zone). + pub id: u32, + /// Kind id from the schema. + pub kind: u16, + /// Interest-plane x. + pub x: f32, + /// Interest-plane y. + pub y: f32, + /// Priority multiplier (default 1). + pub priority: f32, + /// Visible to every client regardless of view. + pub global: bool, + /// Field values in schema order (missing trailing fields encode as zero). + pub fields: Vec, +} + +impl EntityState { + /// Spatial entity at (x, y). + pub fn new(id: u32, kind: u16, x: f32, y: f32, fields: Vec) -> Self { + Self { + id, + kind, + x, + y, + priority: 1.0, + global: false, + fields, + } + } + + /// Mark visible to everyone. + pub fn global(mut self) -> Self { + self.global = true; + self + } + + /// Set the priority multiplier. + pub fn priority(mut self, p: f32) -> Self { + self.priority = p; + self + } +} + +/// Collector the zone fills in `Zone::replicate`. +#[derive(Debug, Clone, Default)] +pub struct WorldView { + entities: Vec, +} + +impl WorldView { + /// Add an entity. + pub fn push(&mut self, entity: EntityState) { + self.entities.push(entity); + } + + /// Entities pushed so far. + pub fn entities(&self) -> &[EntityState] { + &self.entities + } +} + +#[derive(Debug, Clone)] +struct EncodedEntity { + id: u32, + kind: u16, + x: f32, + y: f32, + priority: f32, + global: bool, + data: Vec, + offsets: Vec, +} + +impl EncodedEntity { + fn field(&self, index: usize) -> &[u8] { + &self.data[self.offsets[index]..self.offsets[index + 1]] + } +} + +/// A patch's encoded world, shared by every client. +#[derive(Debug, Clone)] +pub struct EncodedWorld { + entities: Vec, + by_id: HashMap, + grid: SpatialGrid, + globals: Vec, +} + +impl EncodedWorld { + /// Encode `view` against `schema`. Entities of unknown kinds or duplicate + /// ids are skipped. + pub fn build(schema: &EntitySchema, view: WorldView, interest: &InterestConfig) -> Self { + let mut world = Self { + entities: Vec::with_capacity(view.entities.len()), + by_id: HashMap::new(), + grid: SpatialGrid::new(interest.cell_size), + globals: Vec::new(), + }; + let zero = FieldValue::U(0); + for e in view.entities { + let Some(kind) = schema.get(e.kind) else { + continue; + }; + if world.by_id.contains_key(&e.id) { + continue; + } + let mut w = Writer::new(); + let mut offsets = Vec::with_capacity(kind.fields.len() + 1); + for (index, def) in kind.fields.iter().enumerate() { + offsets.push(w.len()); + def.ty.encode(&mut w, e.fields.get(index).unwrap_or(&zero)); + } + offsets.push(w.len()); + let index = world.entities.len() as u32; + if e.global { + world.globals.push(index); + } else { + world.grid.insert(index, e.x, e.y); + } + world.by_id.insert(e.id, index as usize); + world.entities.push(EncodedEntity { + id: e.id, + kind: e.kind, + x: e.x, + y: e.y, + priority: e.priority, + global: e.global, + data: w.into_bytes(), + offsets, + }); + } + world + } + + /// Entity count. + pub fn len(&self) -> usize { + self.entities.len() + } + + /// True when empty. + pub fn is_empty(&self) -> bool { + self.entities.is_empty() + } +} + +#[derive(Debug, Clone)] +struct Known { + data: Vec, + offsets: Vec, +} + +/// Counters from one Delta build. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeltaStats { + /// Creates sent. + pub creates: usize, + /// Updates sent. + pub updates: usize, + /// Removes sent. + pub removes: usize, + /// Candidates deferred by the budget. + pub deferred: usize, + /// Create+update section bytes (what the budget limits). + pub budget_bytes: usize, +} + +/// What one client has been sent. +#[derive(Debug, Clone, Default)] +pub struct ClientReplica { + known: HashMap, + accum: HashMap, +} + +enum Candidate { + Create, + Update(u32), +} + +impl ClientReplica { + /// Fresh replica (client knows nothing). + pub fn new() -> Self { + Self::default() + } + + /// Forget everything (e.g. after reconnect the client gets fresh creates). + pub fn reset(&mut self) { + self.known.clear(); + self.accum.clear(); + } + + /// Ids the client currently knows. + pub fn known_ids(&self) -> impl Iterator + '_ { + self.known.keys().copied() + } + + /// Build this client's Delta frame and update the last-sent state. + #[allow(clippy::too_many_arguments)] + pub fn build_delta( + &mut self, + schema: &EntitySchema, + world: &EncodedWorld, + interest: &InterestConfig, + view: &View, + budget: usize, + server_tick: u32, + ack_seq: u32, + ) -> (Vec, DeltaStats) { + let radius = view.radius.max(0.0); + let stay_radius = radius * (1.0 + interest.leave_margin.max(0.0)); + let mut hits = Vec::new(); + world.grid.query(view.x, view.y, stay_radius, &mut hits); + hits.extend_from_slice(&world.globals); + + // Visible entities with their distance. + let mut visible: Vec<(usize, f32)> = Vec::new(); + let mut seen = HashSet::new(); + for index in hits { + let index = index as usize; + let e = &world.entities[index]; + if !seen.insert(e.id) { + continue; + } + let d = if e.global { + 0.0 + } else { + view.distance(e.x, e.y) + }; + let limit = if self.known.contains_key(&e.id) { + stay_radius + } else { + radius + }; + if e.global || d <= limit { + visible.push((index, d)); + } + } + + let visible_ids: HashSet = + visible.iter().map(|(i, _)| world.entities[*i].id).collect(); + let mut removes: Vec = self + .known + .keys() + .copied() + .filter(|id| !visible_ids.contains(id)) + .collect(); + removes.sort_unstable(); + for id in &removes { + self.known.remove(id); + } + + // Candidates with accumulated priority. + let mut candidates: Vec<(usize, Candidate, f32)> = Vec::new(); + for (index, d) in visible { + let e = &world.entities[index]; + let Some(kind) = schema.get(e.kind) else { + continue; + }; + let (candidate, field_prio) = match self.known.get(&e.id) { + None => ( + Candidate::Create, + kind.fields + .iter() + .map(|f| f.priority) + .fold(1.0_f32, f32::max), + ), + Some(known) => { + let mut mask = 0u32; + let mut prio = 0.0_f32; + for (i, def) in kind.fields.iter().enumerate() { + let old = &known.data[known.offsets[i]..known.offsets[i + 1]]; + if old != e.field(i) { + mask |= 1 << i; + prio = prio.max(def.priority); + } + } + if mask == 0 { + continue; + } + (Candidate::Update(mask), prio) + } + }; + let distance_factor = 1.0 / (1.0 + d / radius.max(f32::EPSILON)); + let gain = (kind.priority * e.priority * field_prio * distance_factor).max(1e-6); + let accum = self.accum.entry(e.id).or_insert(0.0); + *accum += gain; + candidates.push((index, candidate, *accum)); + } + let candidate_ids: HashSet = candidates + .iter() + .map(|(i, _, _)| world.entities[*i].id) + .collect(); + self.accum.retain(|id, _| candidate_ids.contains(id)); + candidates.sort_by(|a, b| { + b.2.total_cmp(&a.2) + .then(world.entities[a.0].id.cmp(&world.entities[b.0].id)) + }); + + let mut stats = DeltaStats { + removes: removes.len(), + ..DeltaStats::default() + }; + let mut creates = Writer::new(); + let mut updates = Writer::new(); + let mut scratch = Writer::new(); + for (index, candidate, _) in candidates { + let e = &world.entities[index]; + scratch.clear(); + match candidate { + Candidate::Create => { + scratch + .varuint(e.id) + .varuint(u32::from(e.kind)) + .raw(&e.data); + } + Candidate::Update(mask) => { + scratch.varuint(e.id).varuint(mask); + for i in 0..e.offsets.len() - 1 { + if mask & (1 << i) != 0 { + scratch.raw(e.field(i)); + } + } + } + } + let used = creates.len() + updates.len(); + if used > 0 && used + scratch.len() > budget { + stats.deferred += 1; + continue; + } + match candidate { + Candidate::Create => { + creates.raw(scratch.as_bytes()); + stats.creates += 1; + } + Candidate::Update(_) => { + updates.raw(scratch.as_bytes()); + stats.updates += 1; + } + } + self.accum.remove(&e.id); + self.known.insert( + e.id, + Known { + data: e.data.clone(), + offsets: e.offsets.clone(), + }, + ); + } + stats.budget_bytes = creates.len() + updates.len(); + + let mut frame = Writer::new(); + frame + .u8(tag::DELTA) + .varuint(server_tick) + .varuint(ack_seq) + .varuint(removes.len() as u32); + for id in &removes { + frame.varuint(*id); + } + frame + .varuint(stats.creates as u32) + .raw(creates.as_bytes()) + .varuint(stats.updates as u32) + .raw(updates.as_bytes()); + (frame.into_bytes(), stats) + } +} diff --git a/distributed_game/src/rng.rs b/distributed_game/src/rng.rs new file mode 100644 index 000000000..bfa94f460 --- /dev/null +++ b/distributed_game/src/rng.rs @@ -0,0 +1,121 @@ +//! Seeded deterministic per-zone random numbers. +//! +//! [`ZoneRng`] is xoshiro256** seeded through SplitMix64. A zone's generator is +//! derived from the deployment's world seed and the zone id +//! ([`ZoneRng::for_zone`]), so the same world seed, zone id and input log +//! always reproduce the same simulation. Zones must take randomness only from +//! [`Ctx::rng`](crate::Ctx::rng) to stay deterministic. + +/// 64-bit FNV-1a, used for seed derivation and as a cheap state-hash helper. +#[derive(Debug, Clone, Copy)] +pub struct Fnv64(u64); + +impl Fnv64 { + const OFFSET: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + /// Fresh hasher. + pub fn new() -> Self { + Self(Self::OFFSET) + } + + /// Mix raw bytes. + pub fn write(&mut self, bytes: &[u8]) -> &mut Self { + for byte in bytes { + self.0 ^= u64::from(*byte); + self.0 = self.0.wrapping_mul(Self::PRIME); + } + self + } + + /// Mix a little-endian u64. + pub fn write_u64(&mut self, value: u64) -> &mut Self { + self.write(&value.to_le_bytes()) + } + + /// Mix an f32 by its bit pattern. + pub fn write_f32(&mut self, value: f32) -> &mut Self { + self.write(&value.to_bits().to_le_bytes()) + } + + /// Current digest. + pub fn finish(&self) -> u64 { + self.0 + } +} + +impl Default for Fnv64 { + fn default() -> Self { + Self::new() + } +} + +fn splitmix64(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// Deterministic xoshiro256** generator. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneRng { + s: [u64; 4], +} + +impl ZoneRng { + /// Seed directly. + pub fn from_seed(seed: u64) -> Self { + let mut sm = seed; + let s = [ + splitmix64(&mut sm), + splitmix64(&mut sm), + splitmix64(&mut sm), + splitmix64(&mut sm), + ]; + Self { s } + } + + /// Derive a zone's generator: `seed = world_seed ^ fnv1a64(zone_id)`. + pub fn for_zone(world_seed: u64, zone_id: &str) -> Self { + Self::from_seed(world_seed ^ Fnv64::new().write(zone_id.as_bytes()).finish()) + } + + /// Next 64 random bits. + pub fn next_u64(&mut self) -> u64 { + let result = self.s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let t = self.s[1] << 17; + self.s[2] ^= self.s[0]; + self.s[3] ^= self.s[1]; + self.s[1] ^= self.s[2]; + self.s[0] ^= self.s[3]; + self.s[2] ^= t; + self.s[3] = self.s[3].rotate_left(45); + result + } + + /// Next 32 random bits (high half of [`next_u64`](Self::next_u64)). + pub fn next_u32(&mut self) -> u32 { + (self.next_u64() >> 32) as u32 + } + + /// Uniform float in `[0, 1)` with 24 bits of precision. + pub fn next_f32(&mut self) -> f32 { + (self.next_u64() >> 40) as f32 * (1.0 / (1u32 << 24) as f32) + } + + /// Uniform integer in `[low, high)`; returns `low` when the range is empty. + pub fn range_u32(&mut self, low: u32, high: u32) -> u32 { + if high <= low { + return low; + } + let span = u64::from(high - low); + low + ((u64::from(self.next_u32()) * span) >> 32) as u32 + } + + /// Bernoulli trial with probability `p`. + pub fn chance(&mut self, p: f32) -> bool { + self.next_f32() < p + } +} diff --git a/distributed_game/src/schema.rs b/distributed_game/src/schema.rs new file mode 100644 index 000000000..888135e2a --- /dev/null +++ b/distributed_game/src/schema.rs @@ -0,0 +1,476 @@ +//! Entity schema: kinds, component fields, field types and quantization. +//! +//! The game describes what it replicates once ([`EntitySchema`]). The schema +//! is serialized into every Welcome so a generic client can decode Deltas +//! without generated code. Each kind has at most [`MAX_FIELDS`] fields; field +//! order is the wire order and the bit order of update masks. +//! +//! Quantization is specified bit-exactly in `PROTOCOL.md` §4 and computed in +//! `f64` so a JavaScript client (whose numbers are `f64`) reproduces the same +//! integers and decoded `f32` values. Use [`FieldType::quantize`] / +//! [`FieldType::canonicalize`] on the server when prediction must match what +//! clients will see. + +use crate::protocol::wire::{DecodeError, Reader, Writer}; + +/// Maximum fields per entity kind (update masks are a 32-bit varuint). +pub const MAX_FIELDS: usize = 32; + +/// `2π` as used by angle quantization. +pub const TAU: f64 = std::f64::consts::TAU; + +/// Wire type of one component field. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FieldType { + /// `u8` 0/1. Tag 0. + Bool, + /// One raw byte. Tag 1. + U8, + /// varuint, 0..=65535. Tag 2. + U16, + /// varuint. Tag 3. + U32, + /// zigzag varint. Tag 4. + I32, + /// binary32 LE. Tag 5. + F32, + /// Clamped linear quantization to `bits` (1..=32), sent as varuint. Tag 6. + QuantF32 { + /// Lower bound (inclusive). + min: f32, + /// Upper bound (inclusive). + max: f32, + /// Precision in bits. + bits: u8, + }, + /// Radians wrapped to `[0, 2π)` and quantized to `bits` (1..=32). Tag 7. + Angle { + /// Precision in bits. + bits: u8, + }, + /// `u8` length + UTF-8 (<= 255 bytes). Tag 8. + ShortStr, + /// varuint length + raw bytes. Tag 9. + Bytes, +} + +/// A field value. Decoded values use the canonical variant for the type: +/// Bool→`Bool`, U8/U16/U32→`U`, I32→`I`, F32/QuantF32/Angle→`F`, +/// ShortStr→`Str`, Bytes→`Bytes`. Encoding coerces numeric variants to the +/// field's type (saturating), so games may supply any numeric variant. +#[derive(Debug, Clone, PartialEq)] +pub enum FieldValue { + /// Boolean. + Bool(bool), + /// Unsigned integer. + U(u32), + /// Signed integer. + I(i32), + /// Float. + F(f32), + /// Text. + Str(String), + /// Opaque bytes. + Bytes(Vec), +} + +impl FieldValue { + fn as_f64(&self) -> f64 { + match self { + Self::Bool(v) => f64::from(u8::from(*v)), + Self::U(v) => f64::from(*v), + Self::I(v) => f64::from(*v), + Self::F(v) => f64::from(*v), + Self::Str(_) | Self::Bytes(_) => 0.0, + } + } +} + +impl FieldType { + /// Clamped linear quantization (`PROTOCOL.md` §4.1). + pub fn quantize_linear(v: f32, min: f32, max: f32, bits: u8) -> u32 { + let maxq = max_q(bits); + let (lo, hi) = (f64::from(min), f64::from(max)); + if hi <= lo { + return 0; + } + let mut x = f64::from(v); + if x.is_nan() { + x = lo; + } + let x = x.clamp(lo, hi); + let t = (x - lo) / (hi - lo); + (t * maxq + 0.5).floor().min(maxq) as u32 + } + + /// Inverse of [`quantize_linear`](Self::quantize_linear). + pub fn dequantize_linear(q: u32, min: f32, max: f32, bits: u8) -> f32 { + let maxq = max_q(bits); + let (lo, hi) = (f64::from(min), f64::from(max)); + (lo + (f64::from(q) / maxq) * (hi - lo)) as f32 + } + + /// Angle quantization (`PROTOCOL.md` §4.2). + pub fn quantize_angle(v: f32, bits: u8) -> u32 { + let steps = steps(bits); + let mut a = f64::from(v); + if !a.is_finite() { + return 0; + } + a %= TAU; + if a < 0.0 { + a += TAU; + } + let q = ((a / TAU) * steps + 0.5).floor(); + (q % steps) as u32 + } + + /// Inverse of [`quantize_angle`](Self::quantize_angle). + pub fn dequantize_angle(q: u32, bits: u8) -> f32 { + ((f64::from(q) * TAU) / steps(bits)) as f32 + } + + /// The value a client will decode for `value` (round-trip through the wire). + pub fn canonicalize(&self, value: &FieldValue) -> FieldValue { + let mut w = Writer::new(); + self.encode(&mut w, value); + self.decode(&mut Reader::new(w.as_bytes())) + .expect("encoded field must decode") + } + + /// Wire tag. + pub fn tag(&self) -> u8 { + match self { + Self::Bool => 0, + Self::U8 => 1, + Self::U16 => 2, + Self::U32 => 3, + Self::I32 => 4, + Self::F32 => 5, + Self::QuantF32 { .. } => 6, + Self::Angle { .. } => 7, + Self::ShortStr => 8, + Self::Bytes => 9, + } + } + + /// Encode a value of this type (coercing numerics). + pub fn encode(&self, w: &mut Writer, value: &FieldValue) { + let n = value.as_f64(); + match self { + Self::Bool => { + w.bool(n != 0.0); + } + Self::U8 => { + w.u8(n.clamp(0.0, 255.0) as u8); + } + Self::U16 => { + w.varuint(n.clamp(0.0, 65535.0) as u32); + } + Self::U32 => { + w.varuint(match value { + FieldValue::U(v) => *v, + _ => n.clamp(0.0, f64::from(u32::MAX)) as u32, + }); + } + Self::I32 => { + w.varint(match value { + FieldValue::I(v) => *v, + _ => n.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32, + }); + } + Self::F32 => { + w.f32(n as f32); + } + Self::QuantF32 { min, max, bits } => { + w.varuint(Self::quantize_linear(n as f32, *min, *max, *bits)); + } + Self::Angle { bits } => { + w.varuint(Self::quantize_angle(n as f32, *bits)); + } + Self::ShortStr => { + w.short_string(match value { + FieldValue::Str(s) => s, + _ => "", + }); + } + Self::Bytes => { + w.bytes(match value { + FieldValue::Bytes(b) => b, + FieldValue::Str(s) => s.as_bytes(), + _ => &[], + }); + } + } + } + + /// Decode a value of this type. + pub fn decode(&self, r: &mut Reader<'_>) -> Result { + Ok(match self { + Self::Bool => FieldValue::Bool(r.bool()?), + Self::U8 => FieldValue::U(u32::from(r.u8()?)), + Self::U16 => { + let v = r.varuint()?; + if v > 65535 { + return Err(DecodeError::Invalid("u16 out of range")); + } + FieldValue::U(v) + } + Self::U32 => FieldValue::U(r.varuint()?), + Self::I32 => FieldValue::I(r.varint()?), + Self::F32 => FieldValue::F(r.f32()?), + Self::QuantF32 { min, max, bits } => { + let q = r.varuint()?; + if f64::from(q) > max_q(*bits) { + return Err(DecodeError::Invalid("quantized value out of range")); + } + FieldValue::F(Self::dequantize_linear(q, *min, *max, *bits)) + } + Self::Angle { bits } => { + let q = r.varuint()?; + if f64::from(q) >= steps(*bits) { + return Err(DecodeError::Invalid("angle out of range")); + } + FieldValue::F(Self::dequantize_angle(q, *bits)) + } + Self::ShortStr => FieldValue::Str(r.short_string()?), + Self::Bytes => FieldValue::Bytes(r.bytes()?.to_vec()), + }) + } + + fn write_def(&self, w: &mut Writer) { + w.u8(self.tag()); + match self { + Self::QuantF32 { min, max, bits } => { + w.f32(*min).f32(*max).u8(*bits); + } + Self::Angle { bits } => { + w.u8(*bits); + } + _ => {} + } + } + + fn read_def(r: &mut Reader<'_>) -> Result { + let tag = r.u8()?; + Ok(match tag { + 0 => Self::Bool, + 1 => Self::U8, + 2 => Self::U16, + 3 => Self::U32, + 4 => Self::I32, + 5 => Self::F32, + 6 => { + let (min, max, bits) = (r.f32()?, r.f32()?, r.u8()?); + check_bits(bits)?; + Self::QuantF32 { min, max, bits } + } + 7 => { + let bits = r.u8()?; + check_bits(bits)?; + Self::Angle { bits } + } + 8 => Self::ShortStr, + 9 => Self::Bytes, + other => return Err(DecodeError::UnknownFieldType(other)), + }) + } +} + +fn check_bits(bits: u8) -> Result<(), DecodeError> { + if (1..=32).contains(&bits) { + Ok(()) + } else { + Err(DecodeError::Invalid("quantization bits must be 1..=32")) + } +} + +fn max_q(bits: u8) -> f64 { + ((1u64 << bits.clamp(1, 32)) - 1) as f64 +} + +fn steps(bits: u8) -> f64 { + (1u64 << bits.clamp(1, 32)) as f64 +} + +/// One component field of a kind. +#[derive(Debug, Clone, PartialEq)] +pub struct FieldDef { + /// Name (informational for generic clients). + pub name: String, + /// Wire type. + pub ty: FieldType, + /// Server-side replication priority multiplier (not sent on the wire). + pub priority: f32, +} + +/// An entity kind: id, name and ordered fields. +#[derive(Debug, Clone, PartialEq)] +pub struct KindDef { + /// Kind id (varuint on the wire). + pub id: u16, + /// Name. + pub name: String, + /// Ordered fields (<= [`MAX_FIELDS`]). + pub fields: Vec, + /// Server-side priority multiplier (not sent on the wire). + pub priority: f32, +} + +impl KindDef { + /// New kind with priority 1. + pub fn new(id: u16, name: impl Into) -> Self { + Self { + id, + name: name.into(), + fields: Vec::new(), + priority: 1.0, + } + } + + /// Append a field with priority 1. + pub fn field(self, name: impl Into, ty: FieldType) -> Self { + self.field_with_priority(name, ty, 1.0) + } + + /// Append a field with an explicit priority. + pub fn field_with_priority(mut self, name: impl Into, ty: FieldType, p: f32) -> Self { + assert!(self.fields.len() < MAX_FIELDS, "at most 32 fields per kind"); + if let FieldType::QuantF32 { bits, .. } | FieldType::Angle { bits } = ty { + assert!((1..=32).contains(&bits), "quantization bits must be 1..=32"); + } + self.fields.push(FieldDef { + name: name.into(), + ty, + priority: p, + }); + self + } + + /// Set the kind priority multiplier. + pub fn priority(mut self, p: f32) -> Self { + self.priority = p; + self + } +} + +/// All replicated kinds of a zone type. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct EntitySchema { + kinds: Vec, +} + +impl EntitySchema { + /// Empty schema. + pub fn new() -> Self { + Self::default() + } + + /// Add a kind (ids must be unique). + pub fn kind(mut self, kind: KindDef) -> Self { + assert!(self.get(kind.id).is_none(), "duplicate kind id {}", kind.id); + self.kinds.push(kind); + self + } + + /// Kinds in declaration order. + pub fn kinds(&self) -> &[KindDef] { + &self.kinds + } + + /// Look up a kind. + pub fn get(&self, id: u16) -> Option<&KindDef> { + self.kinds.iter().find(|kind| kind.id == id) + } + + /// Serialize (`PROTOCOL.md` §5). + pub fn encode(&self, w: &mut Writer) { + w.varuint(self.kinds.len() as u32); + for kind in &self.kinds { + w.varuint(u32::from(kind.id)) + .string(&kind.name) + .varuint(kind.fields.len() as u32); + for field in &kind.fields { + w.string(&field.name); + field.ty.write_def(w); + } + } + } + + /// Deserialize; server-only priorities decode as 1. + pub fn decode(r: &mut Reader<'_>) -> Result { + let count = r.varuint()?; + let mut schema = Self::new(); + for _ in 0..count { + let id = r.varuint()?; + let id = u16::try_from(id).map_err(|_| DecodeError::Invalid("kind id > u16"))?; + let name = r.string()?; + let field_count = r.varuint()? as usize; + if field_count > MAX_FIELDS { + return Err(DecodeError::Invalid("more than 32 fields")); + } + let mut kind = KindDef::new(id, name); + for _ in 0..field_count { + let name = r.string()?; + let ty = FieldType::read_def(r)?; + kind = kind.field(name, ty); + } + if schema.get(id).is_some() { + return Err(DecodeError::Invalid("duplicate kind id")); + } + schema.kinds.push(kind); + } + Ok(schema) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn linear_quantization_rounds_half_up_and_clamps() { + let q = |v| FieldType::quantize_linear(v, -10.0, 10.0, 8); + assert_eq!(q(-10.0), 0); + assert_eq!(q(10.0), 255); + assert_eq!(q(99.0), 255); + assert_eq!(q(f32::NAN), 0); + assert_eq!(q(0.0), 128); // 127.5 rounds up + let back = FieldType::dequantize_linear(128, -10.0, 10.0, 8); + assert!((back - 0.039_215_688).abs() < 1e-6); + } + + #[test] + fn angle_wraps() { + let bits = 8; + assert_eq!(FieldType::quantize_angle(0.0, bits), 0); + assert_eq!(FieldType::quantize_angle(-0.000_001, bits), 0); + assert_eq!(FieldType::quantize_angle(std::f32::consts::PI, bits), 128); + assert_eq!( + FieldType::quantize_angle(-std::f32::consts::FRAC_PI_2, bits), + 192 + ); + } + + #[test] + fn schema_round_trips() { + let schema = EntitySchema::new().kind( + KindDef::new(3, "orb") + .field( + "x", + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 12, + }, + ) + .field("yaw", FieldType::Angle { bits: 10 }) + .field("name", FieldType::ShortStr), + ); + let mut w = Writer::new(); + schema.encode(&mut w); + let mut r = Reader::new(w.as_bytes()); + assert_eq!(EntitySchema::decode(&mut r).unwrap(), schema); + r.finish().unwrap(); + } +} diff --git a/distributed_game/src/stamp.rs b/distributed_game/src/stamp.rs new file mode 100644 index 000000000..a9d7401ab --- /dev/null +++ b/distributed_game/src/stamp.rs @@ -0,0 +1,98 @@ +//! Tick stamping: provenance of committed facts. +//! +//! Every [`Fact`](crate::Fact) carries a [`FactStamp`] (zone id, tick, +//! content version) filled in by the host when the zone emits it. The cell +//! adapter forwards the stamp as trusted session variables; command handlers +//! copy it into `EventRecord.metadata` with [`stamp_metadata`] (or +//! `stamp_event_record` with the `cell` feature) so every durable event +//! records exactly which simulation tick produced it. + +use std::collections::HashMap; + +/// Metadata key for the zone id. +pub const META_ZONE: &str = "game.zone"; +/// Metadata key for the zone tick (decimal). +pub const META_TICK: &str = "game.tick"; +/// Metadata key for the content version. +pub const META_CONTENT_VERSION: &str = "game.content_version"; + +/// Session-variable prefix used to carry a stamp through a trusted Session. +pub const SESSION_PREFIX: &str = "x-game-"; + +/// Where and when a fact was produced. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct FactStamp { + /// Zone id. + pub zone_id: String, + /// Zone tick during which the fact was emitted. + pub tick: u64, + /// Content version the zone was running. + pub content_version: String, +} + +impl FactStamp { + /// Metadata entries for this stamp. + pub fn entries(&self) -> [(&'static str, String); 3] { + [ + (META_ZONE, self.zone_id.clone()), + (META_TICK, self.tick.to_string()), + (META_CONTENT_VERSION, self.content_version.clone()), + ] + } + + /// Session variables (`x-game-zone`, `x-game-tick`, `x-game-content-version`). + pub fn session_vars(&self) -> [(String, String); 3] { + [ + (format!("{SESSION_PREFIX}zone"), self.zone_id.clone()), + (format!("{SESSION_PREFIX}tick"), self.tick.to_string()), + ( + format!("{SESSION_PREFIX}content-version"), + self.content_version.clone(), + ), + ] + } + + /// Read a stamp back from session variables (None if absent/malformed). + pub fn from_session_vars(vars: &HashMap) -> Option { + Some(Self { + zone_id: vars.get(&format!("{SESSION_PREFIX}zone"))?.clone(), + tick: vars.get(&format!("{SESSION_PREFIX}tick"))?.parse().ok()?, + content_version: vars + .get(&format!("{SESSION_PREFIX}content-version"))? + .clone(), + }) + } +} + +/// Insert the stamp into an event metadata map. +pub fn stamp_metadata(metadata: &mut HashMap, stamp: &FactStamp) { + for (key, value) in stamp.entries() { + metadata.insert(key.to_string(), value); + } +} + +/// Stamp a `distributed` event record's metadata. +#[cfg(feature = "cell")] +pub fn stamp_event_record(record: &mut distributed::EventRecord, stamp: &FactStamp) { + stamp_metadata(&mut record.metadata, stamp); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stamp_round_trips_through_session_vars_and_metadata() { + let stamp = FactStamp { + zone_id: "z1".into(), + tick: 42, + content_version: "c7".into(), + }; + let vars: HashMap<_, _> = stamp.session_vars().into_iter().collect(); + assert_eq!(FactStamp::from_session_vars(&vars), Some(stamp.clone())); + let mut meta = HashMap::new(); + stamp_metadata(&mut meta, &stamp); + assert_eq!(meta[META_TICK], "42"); + assert_eq!(meta[META_ZONE], "z1"); + } +} diff --git a/distributed_game/src/timers.rs b/distributed_game/src/timers.rs new file mode 100644 index 000000000..3d02fd581 --- /dev/null +++ b/distributed_game/src/timers.rs @@ -0,0 +1,127 @@ +//! Per-zone timers measured in simulation time. +//! +//! Timers are owned by the zone's host, fire only during ticks (in schedule +//! order, before `on_tick`), and are all cleared when the zone is disposed. +//! Because they run on simulation time they are deterministic and they pause +//! while a zone is Dormant (simulation time does not advance without ticks). + +use std::time::Duration; + +/// Handle for cancelling a timer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TimerId(pub u64); + +#[derive(Debug)] +struct Entry { + id: TimerId, + due: Duration, + every: Option, + payload: T, +} + +/// Timer set holding game-defined payloads `T`. +#[derive(Debug)] +pub struct Timers { + next_id: u64, + entries: Vec>, +} + +impl Default for Timers { + fn default() -> Self { + Self { + next_id: 1, + entries: Vec::new(), + } + } +} + +impl Timers { + /// Fire once at `now + after`. + pub fn once(&mut self, now: Duration, after: Duration, payload: T) -> TimerId { + self.insert(now + after, None, payload) + } + + /// Fire every `every` (minimum 1ns), first at `now + every`. + pub fn interval(&mut self, now: Duration, every: Duration, payload: T) -> TimerId { + let every = every.max(Duration::from_nanos(1)); + self.insert(now + every, Some(every), payload) + } + + fn insert(&mut self, due: Duration, every: Option, payload: T) -> TimerId { + let id = TimerId(self.next_id); + self.next_id += 1; + self.entries.push(Entry { + id, + due, + every, + payload, + }); + id + } + + /// Cancel; returns whether the timer existed. + pub fn cancel(&mut self, id: TimerId) -> bool { + let before = self.entries.len(); + self.entries.retain(|entry| entry.id != id); + before != self.entries.len() + } + + /// Number of live timers. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// True when no timers are scheduled. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Remove every timer. + pub fn clear(&mut self) { + self.entries.clear(); + } + + /// Collect timers due at `now`, ordered by (due, id). Interval timers are + /// rescheduled; an interval fires at most once per call. + pub fn due(&mut self, now: Duration) -> Vec<(TimerId, T)> { + let mut fired: Vec<(Duration, TimerId, T)> = Vec::new(); + let mut index = 0; + while index < self.entries.len() { + if self.entries[index].due <= now { + let entry = &mut self.entries[index]; + fired.push((entry.due, entry.id, entry.payload.clone())); + if let Some(every) = entry.every { + while entry.due <= now { + entry.due += every; + } + index += 1; + } else { + self.entries.swap_remove(index); + } + } else { + index += 1; + } + } + fired.sort_by_key(|(due, id, _)| (*due, *id)); + fired.into_iter().map(|(_, id, p)| (id, p)).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn once_and_interval_fire_in_order() { + let mut timers = Timers::default(); + let ms = Duration::from_millis; + let a = timers.once(ms(0), ms(30), "a"); + let b = timers.interval(ms(0), ms(10), "b"); + assert!(timers.due(ms(5)).is_empty()); + assert_eq!(timers.due(ms(10)), vec![(b, "b")]); + assert_eq!(timers.due(ms(30)), vec![(b, "b"), (a, "a")]); + assert!(timers.cancel(b)); + assert!(timers.due(ms(100)).is_empty()); + assert!(timers.is_empty()); + } +} diff --git a/distributed_game/src/timestep.rs b/distributed_game/src/timestep.rs new file mode 100644 index 000000000..91ef699a4 --- /dev/null +++ b/distributed_game/src/timestep.rs @@ -0,0 +1,115 @@ +//! Fixed timestep with an accumulator and a catch-up cap. +//! +//! Real elapsed time is added to an accumulator; whole steps are consumed +//! from it. When a host falls behind (GC pause, overloaded core, debugger) at +//! most `max_catch_up` steps run per advance and the remaining backlog is +//! **dropped** rather than carried forward, so a slow tick can never cause an +//! ever-growing backlog (the "spiral of death"). Arithmetic is in integer +//! nanoseconds so step counts are exact and reproducible. + +use std::time::Duration; + +/// Result of feeding elapsed time into a [`FixedTimestep`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Steps { + /// Whole steps to simulate now. + pub steps: u32, + /// Backlog discarded because the catch-up cap was hit. + pub dropped: Duration, +} + +/// Accumulator for one fixed step length. +#[derive(Debug, Clone)] +pub struct FixedTimestep { + step_nanos: u64, + accumulator: u64, + max_catch_up: u32, +} + +impl FixedTimestep { + /// Steps of `step` length, running at most `max_catch_up` (>= 1) per call. + pub fn new(step: Duration, max_catch_up: u32) -> Self { + Self { + step_nanos: (step.as_nanos() as u64).max(1), + accumulator: 0, + max_catch_up: max_catch_up.max(1), + } + } + + /// Step for a rate in Hz. + pub fn from_rate(hz: u32, max_catch_up: u32) -> Self { + Self::new(rate_to_step(hz), max_catch_up) + } + + /// Length of one step. + pub fn step(&self) -> Duration { + Duration::from_nanos(self.step_nanos) + } + + /// Time accumulated toward the next step. + pub fn pending(&self) -> Duration { + Duration::from_nanos(self.accumulator) + } + + /// Time until the next whole step is available. + pub fn until_next(&self) -> Duration { + Duration::from_nanos(self.step_nanos.saturating_sub(self.accumulator)) + } + + /// Fraction of a step accumulated (render interpolation alpha). + pub fn alpha(&self) -> f32 { + self.accumulator as f32 / self.step_nanos as f32 + } + + /// Discard accumulated time (used on activity-tier changes). + pub fn reset(&mut self) { + self.accumulator = 0; + } + + /// Feed real elapsed time and take whole steps. + pub fn advance(&mut self, elapsed: Duration) -> Steps { + self.accumulator = self.accumulator.saturating_add(elapsed.as_nanos() as u64); + let available = self.accumulator / self.step_nanos; + let steps = available.min(u64::from(self.max_catch_up)); + self.accumulator -= steps * self.step_nanos; + let mut dropped = 0; + if available > steps { + // Keep only the sub-step remainder; drop the rest of the backlog. + dropped = self.accumulator - self.accumulator % self.step_nanos; + self.accumulator %= self.step_nanos; + } + Steps { + steps: steps as u32, + dropped: Duration::from_nanos(dropped), + } + } +} + +/// `1 / hz` seconds (zero Hz is treated as 1 Hz). +pub fn rate_to_step(hz: u32) -> Duration { + Duration::from_nanos(1_000_000_000 / u64::from(hz.max(1))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accumulates_partial_steps() { + let mut ts = FixedTimestep::new(Duration::from_millis(10), 4); + assert_eq!(ts.advance(Duration::from_millis(7)).steps, 0); + assert_eq!(ts.advance(Duration::from_millis(7)).steps, 1); + assert_eq!(ts.pending(), Duration::from_millis(4)); + } + + #[test] + fn catch_up_is_capped_and_backlog_dropped() { + let mut ts = FixedTimestep::new(Duration::from_millis(10), 3); + let s = ts.advance(Duration::from_millis(1_005)); + assert_eq!(s.steps, 3); + assert_eq!(s.dropped, Duration::from_millis(970)); + assert_eq!(ts.pending(), Duration::from_millis(5)); + // Next normal frame is unaffected by the old backlog. + assert_eq!(ts.advance(Duration::from_millis(10)).steps, 1); + } +} diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs new file mode 100644 index 000000000..73519af34 --- /dev/null +++ b/distributed_game/src/zone.rs @@ -0,0 +1,195 @@ +//! The [`Zone`] trait a game implements, and the identity types it sees. +//! +//! A zone is one authoritative simulation instance (a dungeon floor, a match, +//! a town shard). The [`ZoneHost`](crate::ZoneHost) owns it and calls these +//! hooks; every hook gets a [`Ctx`](crate::Ctx) for timers, RNG, inputs, +//! facts, events and views. Hooks are synchronous and must not block: durable +//! work goes through facts, never through awaited storage. +//! +//! Lifecycle: `on_create` → (`on_auth` → `on_join` | `on_observe`)* with +//! `on_tick`/`on_timer`/`on_fact_settled` interleaved → `on_leave` / +//! `on_unobserve` → `on_dispose`. + +use crate::facts::FactSettlement; +use crate::host::Ctx; +use crate::protocol::Role; +use crate::replication::WorldView; +use crate::schema::EntitySchema; +use crate::timers::TimerId; + +/// Stable id of a player within a zone (survives reconnects). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PlayerId(pub u32); + +/// Id of a read-only observer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ObserverId(pub u32); + +/// Id of one transport connection (changes on reconnect). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ClientId(pub u32); + +/// Anything that has a view and receives events. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Viewer { + /// A player. + Player(PlayerId), + /// An observer. + Observer(ObserverId), +} + +impl From for Viewer { + fn from(id: PlayerId) -> Self { + Self::Player(id) + } +} + +impl From for Viewer { + fn from(id: ObserverId) -> Self { + Self::Observer(id) + } +} + +/// Claims from a **verified** admission ticket. The principal is the only +/// identity the runtime trusts; nothing in client payloads can change it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TicketClaims { + /// Verified principal (`sub`). + pub principal: String, + /// Zone the ticket admits to. + pub zone: String, + /// Expiry, Unix seconds. + pub expires_at: u64, + /// Single-use nonce. + pub nonce: String, + /// Player or observer. + pub role: Role, +} + +/// Admission request seen by [`Zone::on_auth`]. +#[derive(Debug, Clone, Copy)] +pub struct JoinRequest<'a> { + /// Verified claims. + pub claims: &'a TicketClaims, + /// Hello capabilities (game-defined bits). + pub capabilities: u32, + /// Client content version. + pub content_version: &'a str, +} + +/// `on_auth` decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Admission { + /// Let them in. + Admit, + /// Refuse with a message. + Reject(String), +} + +/// Why a player left. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LeaveReason { + /// Client sent Leave. + Left, + /// Connection lost and the reconnect grace window elapsed. + Disconnected, + /// Removed by the zone or operator. + Kicked, + /// Handed off to another zone. + Handoff, + /// Zone disposed. + Disposed, +} + +/// Player as seen by the zone. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlayerInfo { + /// Stable id. + pub id: PlayerId, + /// Verified principal from the ticket. + pub principal: String, + /// Hello capabilities. + pub capabilities: u32, + /// False while inside the reconnect grace window. + pub connected: bool, +} + +/// Activity tier of a zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Tier { + /// Clients connected or work pending: full tick rate, patches flowing. + Hot, + /// Empty: optional slow clock for background simulation. + Idle, + /// No ticks; eligible for hibernation. + Dormant, +} + +/// A game zone. See the module docs for the lifecycle. +pub trait Zone: Sized + Send + 'static { + /// Construction parameters. + type Config; + /// Decoded, sanitized player input. + type Input: Send + 'static; + /// Timer payload. + type Timer: Clone + Send + 'static; + + /// Replicated entity schema (called once at creation). + fn schema() -> EntitySchema; + + /// Build the zone. Timers and RNG are available through `ctx`. + fn on_create(ctx: &mut Ctx<'_, Self>, config: Self::Config) -> Self; + + /// Decide admission for a verified ticket (capacity is checked first). + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, _request: &JoinRequest<'_>) -> Admission { + Admission::Admit + } + + /// A player joined (not called on reconnect). + fn on_join(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId) {} + + /// A player left for `reason` (not called on a disconnect still inside the grace window). + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId, _reason: LeaveReason) {} + + /// An observer subscribed. + fn on_observe(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} + + /// An observer left. + fn on_unobserve(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} + + /// Decode raw input bytes from the wire; `None` drops the input. + fn decode_input(&self, player: PlayerId, payload: &[u8]) -> Option; + + /// Validate/clamp an input before buffering; `None` rejects it. + fn sanitize_input(&self, _player: PlayerId, input: Self::Input) -> Option { + Some(input) + } + + /// One fixed simulation step (`ctx.dt()` is the step length of the tier). + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>); + + /// A timer fired (before `on_tick` of the same tick). + fn on_timer(&mut self, _ctx: &mut Ctx<'_, Self>, _id: TimerId, _timer: Self::Timer) {} + + /// A fact emitted earlier settled. + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, _settlement: FactSettlement) {} + + /// The activity tier changed. + fn on_tier_changed(&mut self, _ctx: &mut Ctx<'_, Self>, _from: Tier, _to: Tier) {} + + /// True keeps the zone Hot even with nobody connected. + fn has_pending_work(&self) -> bool { + false + } + + /// True keeps an empty zone Idle (background clock) instead of Dormant. + fn wants_background(&self) -> bool { + false + } + + /// Describe replicated entities for this patch. + fn replicate(&self, out: &mut WorldView); + + /// The zone is being destroyed; timers are cleared afterwards. + fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) {} +} diff --git a/distributed_game/tests/cell_sink/main.rs b/distributed_game/tests/cell_sink/main.rs new file mode 100644 index 000000000..9cf78fc0f --- /dev/null +++ b/distributed_game/tests/cell_sink/main.rs @@ -0,0 +1,167 @@ +//! Facts committed into a real `distributed` AggregateCell through +//! `dispatch_idempotent` with a server-built trusted Session. + +use std::sync::Arc; +use std::time::Duration; + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use distributed_game::cell::{command_id_for, CellFactSink}; +use distributed_game::{ + fact_channel, spawn_fact_worker, Fact, FactOutcome, FactStamp, RetryPolicy, +}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +struct Hero { + entity: Entity, + xp: u32, +} + +#[sourced(entity, aggregate_type = "Hero", events = "HeroEvent")] +impl Hero { + #[event("hero.xp_credited", version = 1)] + fn credit(&mut self, id: String, amount: u32) { + self.entity.set_id(id); + self.xp += amount; + } +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +struct CreditInput { + amount: u32, +} + +#[derive(Debug, Serialize, distributed::CommandOutput)] +struct CreditPayload { + hero: String, + xp: u32, + tick: String, +} + +struct CreditXp; + +impl PortableCommand for CreditXp +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + "hero.credit_xp", + )) + .guarded( + |ctx: &CausalCommandContext<'_, Hero>| ctx.session().user_id().is_some(), + handle_credit, + ) + } +} + +async fn handle_credit( + ctx: &CausalCommandContext<'_, Hero>, + input: CreditInput, +) -> Result>, HandlerError> { + // Identity comes from the trusted session, never from the input. + let principal = ctx.session().user_id().unwrap_or_default().to_string(); + let tick = ctx.session().get("x-game-tick").unwrap_or("").to_string(); + let repo = ctx.repo(); + let mut hero = match repo.get(&principal).await? { + Some(hero) => hero, + None => repo.create(), + }; + hero.credit(principal.clone(), input.amount) + .map_err(|e| HandlerError::Rejected(e.to_string()))?; + let xp = hero.xp; + repo.commit(hero)?.succeeded(CreditPayload { + hero: principal, + xp, + tick, + }) +} + +#[test] +fn command_ids_are_deterministic_uuidv7_shaped() { + let a = command_id_for("svc", "coin:z1:7"); + assert_eq!(a, command_id_for("svc", "coin:z1:7")); + assert_ne!(a, command_id_for("svc", "coin:z1:8")); + assert_eq!(&a[14..15], "7"); + assert!(matches!(&a[19..20], "8" | "9" | "a" | "b")); +} + +#[tokio::test] +async fn facts_dispatch_idempotently_with_trusted_principal() { + let cell = Arc::new(AggregateCell::::new("alice").unwrap().mount(CreditXp)); + let sink = CellFactSink::new(cell.clone(), "game-svc", "zone-system"); + let (mut queue, feed) = fact_channel(16, RetryPolicy::default()); + let worker = spawn_fact_worker(feed, sink); + + let stamp = FactStamp { + zone_id: "z1".into(), + tick: 99, + content_version: "c1".into(), + }; + let fact = Fact::trusted( + "coin:z1:7", + "hero.credit_xp", + json!({ "amount": 10 }), + Some("alice".into()), + stamp.clone(), + ); + queue.try_send(fact.clone()).unwrap(); + let first = wait_one(&mut queue).await; + queue.try_send(fact).unwrap(); + let replay = wait_one(&mut queue).await; + + let FactOutcome::Committed(first) = first.outcome else { + panic!("first commit failed: {first:?}") + }; + let FactOutcome::Committed(replay) = replay.outcome else { + panic!("replay failed: {replay:?}") + }; + assert!(!first.replayed); + assert!( + replay.replayed, + "same key replays through the command ledger" + ); + assert_eq!(first.payload["hero"], "alice"); + assert_eq!(first.payload["xp"], 10); + assert_eq!(first.payload["tick"], "99"); + assert_eq!(cell.load().await.unwrap().unwrap().xp, 10, "credited once"); + + // Payload-supplied identity is not a declared input: permanent failure. + let forged = Fact::trusted( + "coin:z1:8", + "hero.credit_xp", + json!({ "amount": 10, "principal": "mallory" }), + Some("alice".into()), + stamp, + ); + queue.try_send(forged).unwrap(); + let forged = wait_one(&mut queue).await; + assert!(matches!( + forged.outcome, + FactOutcome::Failed { + error: distributed_game::FactError::Permanent(_), + .. + } + )); + assert_eq!(cell.load().await.unwrap().unwrap().xp, 10); + + drop(queue); + worker.await.unwrap(); +} + +async fn wait_one(queue: &mut distributed_game::FactQueue) -> distributed_game::FactSettlement { + for _ in 0..500 { + if let Some(s) = queue.drain().pop() { + return s; + } + tokio::time::sleep(Duration::from_millis(2)).await; + } + panic!("no settlement") +} diff --git a/distributed_game/tests/zone_runtime/arena.rs b/distributed_game/tests/zone_runtime/arena.rs new file mode 100644 index 000000000..c64fd01ba --- /dev/null +++ b/distributed_game/tests/zone_runtime/arena.rs @@ -0,0 +1,259 @@ +//! Shared test zone: avatars move by input, coins spawn on a timer, picking a +//! coin emits a durable fact credited to the verified principal. +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::time::Duration; + +use distributed_game::{ + Admission, ConsumePolicy, Ctx, EntitySchema, EntityState, Fact, FactSettlement, FieldType, + FieldValue, Fnv64, JoinRequest, KindDef, LeaveReason, ObserverId, PlayerId, Tier, TimerId, + View, WorldView, Zone, +}; +use serde_json::json; + +pub const AVATAR: u16 = 1; +pub const COIN: u16 = 2; + +#[derive(Debug, Clone, Default)] +pub struct ArenaConfig { + pub fact_every_tick: bool, + pub reject_principal: Option, + pub background: bool, + pub spawn_every: Option, +} + +#[derive(Debug, Clone)] +pub struct Avatar { + pub entity: u32, + pub x: f32, + pub y: f32, + pub score: u32, +} + +#[derive(Debug, Clone)] +pub enum ArenaTimer { + SpawnCoin, +} + +pub struct Arena { + pub cfg: ArenaConfig, + pub avatars: BTreeMap, + pub coins: BTreeMap, + pub next_entity: u32, + pub log: Vec, + pub settled: Vec, + pub emit_errors: Vec, + pub ticks: u64, + pub timer_fires: u64, + pub tiers: Vec<(Tier, Tier)>, +} + +impl Arena { + pub fn state_hash(&self) -> u64 { + let mut h = Fnv64::new(); + for (id, a) in &self.avatars { + h.write_u64(u64::from(id.0)) + .write_f32(a.x) + .write_f32(a.y) + .write_u64(u64::from(a.score)); + } + for (id, (x, y)) in &self.coins { + h.write_u64(u64::from(*id)).write_f32(*x).write_f32(*y); + } + h.write_u64(self.ticks); + h.finish() + } + + fn spawn_coin(&mut self, ctx: &mut Ctx<'_, Self>) { + let x = ctx.rng().next_f32() * 100.0; + let y = ctx.rng().next_f32() * 100.0; + self.next_entity += 1; + self.coins.insert(self.next_entity, (x, y)); + } +} + +impl Zone for Arena { + type Config = ArenaConfig; + type Input = (i8, i8); + type Timer = ArenaTimer; + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: 0.0, + max: 100.0, + bits: 16, + }; + EntitySchema::new() + .kind( + KindDef::new(AVATAR, "avatar") + .field("x", pos) + .field("y", pos) + .field("score", FieldType::U16), + ) + .kind( + KindDef::new(COIN, "coin") + .field("x", pos) + .field("y", pos) + .priority(0.5), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, cfg: ArenaConfig) -> Self { + if let Some(every) = cfg.spawn_every { + ctx.set_interval(every, ArenaTimer::SpawnCoin); + } + Self { + cfg, + avatars: BTreeMap::new(), + coins: BTreeMap::new(), + next_entity: 1000, + log: vec!["create".into()], + settled: Vec::new(), + emit_errors: Vec::new(), + ticks: 0, + timer_fires: 0, + tiers: Vec::new(), + } + } + + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, req: &JoinRequest<'_>) -> Admission { + if self.cfg.reject_principal.as_deref() == Some(req.claims.principal.as_str()) { + return Admission::Reject("banned".into()); + } + Admission::Admit + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let x = 10.0 + ctx.rng().next_f32() * 80.0; + let y = 10.0 + ctx.rng().next_f32() * 80.0; + self.avatars.insert( + player, + Avatar { + entity: player.0, + x, + y, + score: 0, + }, + ); + ctx.set_view(player, View::new(x, y, 30.0)); + let principal = ctx.player(player).unwrap().principal.clone(); + self.log.push(format!("join:{principal}")); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, reason: LeaveReason) { + self.avatars.remove(&player); + self.log.push(format!("leave:{reason:?}")); + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + ctx.set_view(observer, View::new(50.0, 50.0, 1000.0)); + self.log.push("observe".into()); + } + + fn on_unobserve(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) { + self.log.push("unobserve".into()); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option<(i8, i8)> { + match payload { + [dx, dy] => Some((*dx as i8, *dy as i8)), + _ => None, + } + } + + fn sanitize_input(&self, _player: PlayerId, (dx, dy): (i8, i8)) -> Option<(i8, i8)> { + if dx.unsigned_abs() > 4 || dy.unsigned_abs() > 4 { + return None; + } + Some((dx.clamp(-1, 1), dy.clamp(-1, 1))) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.ticks += 1; + let dt = ctx.dt_secs(); + let players: Vec = self.avatars.keys().copied().collect(); + for player in players { + let inputs = ctx.take_inputs(player, ConsumePolicy::Drain); + let avatar = self.avatars.get_mut(&player).unwrap(); + for input in inputs { + avatar.x = (avatar.x + f32::from(input.input.0) * 10.0 * dt).clamp(0.0, 100.0); + avatar.y = (avatar.y + f32::from(input.input.1) * 10.0 * dt).clamp(0.0, 100.0); + } + let (ax, ay) = (avatar.x, avatar.y); + let picked: Vec = self + .coins + .iter() + .filter(|(_, (x, y))| (x - ax).powi(2) + (y - ay).powi(2) < 4.0) + .map(|(id, _)| *id) + .collect(); + for coin in picked { + self.coins.remove(&coin); + self.avatars.get_mut(&player).unwrap().score += 1; + let fact = Fact::new( + format!("coin:{}:{coin}", ctx.zone_id()), + "credit_xp", + json!({ "amount": 10 }), + ); + if let Err(e) = ctx.emit_fact_for(player, fact) { + self.emit_errors.push(e); + } + } + ctx.set_view(player, View::new(ax, ay, 30.0)); + } + if self.cfg.fact_every_tick { + let fact = Fact::new(format!("tick:{}", ctx.tick()), "heartbeat", json!(null)); + if let Err(e) = ctx.emit_fact(fact) { + self.emit_errors.push(e); + } + } + } + + fn on_timer(&mut self, ctx: &mut Ctx<'_, Self>, _id: TimerId, timer: ArenaTimer) { + self.timer_fires += 1; + match timer { + ArenaTimer::SpawnCoin => self.spawn_coin(ctx), + } + } + + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + self.settled.push(settlement); + } + + fn on_tier_changed(&mut self, _ctx: &mut Ctx<'_, Self>, from: Tier, to: Tier) { + self.tiers.push((from, to)); + } + + fn wants_background(&self) -> bool { + self.cfg.background + } + + fn replicate(&self, out: &mut WorldView) { + for a in self.avatars.values() { + out.push(EntityState::new( + a.entity, + AVATAR, + a.x, + a.y, + vec![ + FieldValue::F(a.x), + FieldValue::F(a.y), + FieldValue::U(a.score), + ], + )); + } + for (id, (x, y)) in &self.coins { + out.push(EntityState::new( + *id, + COIN, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y)], + )); + } + } + + fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) { + self.log.push("dispose".into()); + } +} diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs new file mode 100644 index 000000000..bfd0e3e64 --- /dev/null +++ b/distributed_game/tests/zone_runtime/main.rs @@ -0,0 +1,527 @@ +//! P2 zone runtime behaviour: lifecycle, cadence, tiers, inputs, +//! determinism and non-blocking facts. + +mod arena; + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use arena::{Arena, ArenaConfig}; +use distributed_game::protocol::{error, ServerMessage}; +use distributed_game::{ + fact_channel, ClientId, ClientMirror, EmitError, Fact, FactError, FactOutcome, FactReceipt, + FactSink, HostConfig, LeaveReason, ManualClock, MemoryFactSink, Outbound, PushOutcome, + RetryPolicy, Role, SystemClock, TicketClaims, Tier, ZoneHost, +}; + +const MS: fn(u64) -> Duration = Duration::from_millis; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + } +} + +fn host(config: HostConfig, clock: &ManualClock, cfg: ArenaConfig) -> ZoneHost { + ZoneHost::new("z1", config, Arc::new(clock.clone()), cfg) +} + +fn frames_for(out: &[Outbound], client: ClientId) -> Vec> { + out.iter() + .filter_map(|o| match o { + Outbound::Frame { client: c, frame } if *c == client => Some(frame.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn lifecycle_hooks_capacity_and_auth() { + let clock = ManualClock::new(); + let config = HostConfig { + max_players: 2, + ..HostConfig::default() + }; + let mut h = host( + config, + &clock, + ArenaConfig { + reject_principal: Some("mallory".into()), + spawn_every: Some(MS(100)), + ..Default::default() + }, + ); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let err = h.join(&claims("mallory", "z1"), 0, "").unwrap_err(); + assert_eq!(err.code, error::REJECTED); + let err = h.join(&claims("bob", "other-zone"), 0, "").unwrap_err(); + assert_eq!(err.code, error::UNAUTHORIZED); + h.join(&claims("bob", "z1"), 0, "").unwrap(); + let err = h.join(&claims("carol", "z1"), 0, "").unwrap_err(); + assert_eq!(err.code, error::ZONE_FULL); + + // Welcome is the first frame for a joined client. + let out = h.drain_outbound(); + let mut mirror = ClientMirror::new(); + let first = frames_for(&out, a.client).remove(0); + assert!(matches!( + mirror.apply(&first).unwrap(), + ServerMessage::Welcome(_) + )); + + clock.advance(MS(500)); + h.advance(); + assert!(h.zone().timer_fires > 0); + h.disconnect(a.client, true); + h.dispose(); + assert!(h.is_disposed()); + let fires = h.zone().timer_fires; + clock.advance(MS(1_000)); + assert_eq!(h.advance().ticks, 0, "disposed zones never tick"); + assert_eq!(h.zone().timer_fires, fires, "timers cleared on dispose"); + assert_eq!( + h.zone().log, + vec![ + "create", + "join:alice", + "join:bob", + "leave:Left", + "leave:Disposed", + "dispose" + ] + ); +} + +#[test] +fn fixed_timestep_caps_catch_up_and_patches_independently() { + let clock = ManualClock::new(); + let config = HostConfig { + tick_rate: 50, + patch_rate: 10, + max_catch_up: 5, + ..HostConfig::default() + }; + let mut h = host(config, &clock, ArenaConfig::default()); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + h.advance(); + h.drain_outbound(); + + // A 2s stall runs at most 5 steps and drops the rest. + clock.advance(Duration::from_secs(2)); + let report = h.advance(); + assert_eq!(report.ticks, 5); + assert!(report.dropped >= Duration::from_millis(1_900)); + + // Steady state: 1s in 2 ms frames = 50 ticks, 10 patches. + let (mut ticks, mut patches) = (0, 0); + let start = h.tick(); + for _ in 0..500 { + clock.advance(MS(2)); + let r = h.advance(); + ticks += r.ticks; + patches += u32::from(r.patched); + } + assert_eq!(ticks, 50); + assert_eq!(h.tick() - start, 50); + assert!((9..=11).contains(&patches), "patches = {patches}"); +} + +#[test] +fn activity_tiers_hot_idle_dormant_and_wake() { + let clock = ManualClock::new(); + let config = HostConfig { + tick_rate: 20, + idle_tick_rate: Some(2), + dormant_after: Duration::from_secs(5), + ..HostConfig::default() + }; + let mut h = host(config.clone(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(h.tier(), Tier::Hot); + let mut ticks = 0; + for _ in 0..20 { + clock.advance(MS(50)); + ticks += h.advance().ticks; + } + assert_eq!(ticks, 20); + + h.disconnect(a.client, true); + let r = h.advance(); + assert_eq!(h.tier(), Tier::Idle); + assert_eq!(r.transitions, vec![(Tier::Hot, Tier::Idle)]); + clock.advance(Duration::from_secs(2)); + assert_eq!(h.advance().ticks, 4, "idle runs the slow clock"); + + clock.advance(Duration::from_secs(4)); + let r = h.advance(); + assert_eq!(h.tier(), Tier::Dormant); + assert_eq!(r.transitions, vec![(Tier::Idle, Tier::Dormant)]); + assert_eq!(r.next_wake, None); + clock.advance(Duration::from_secs(10)); + assert_eq!(h.advance().ticks, 0, "dormant zones do not tick"); + + h.join(&claims("bob", "z1"), 0, "").unwrap(); + assert_eq!(h.tier(), Tier::Hot); + let r = h.advance(); + assert_eq!(r.transitions, vec![(Tier::Dormant, Tier::Hot)]); + assert_eq!(r.ticks, 0, "no catch-up for dormant time"); + assert_eq!( + h.zone().tiers, + vec![ + (Tier::Hot, Tier::Idle), + (Tier::Idle, Tier::Dormant), + (Tier::Dormant, Tier::Hot) + ] + ); + + // Background zones stay Idle instead of going Dormant. + let mut bg = host( + config, + &clock, + ArenaConfig { + background: true, + ..Default::default() + }, + ); + bg.advance(); + clock.advance(Duration::from_secs(60)); + bg.advance(); + assert_eq!(bg.tier(), Tier::Idle); +} + +#[test] +fn reconnect_within_grace_keeps_player_then_expires() { + let clock = ManualClock::new(); + let config = HostConfig { + reconnect_grace: Duration::from_secs(3), + ..HostConfig::default() + }; + let mut h = host(config, &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let out = h.drain_outbound(); + let mut mirror = ClientMirror::new(); + mirror.apply(&frames_for(&out, a.client)[0]).unwrap(); + let token = mirror.welcome.as_ref().unwrap().reconnect_token.clone(); + assert!(!token.is_empty()); + + h.disconnect(a.client, false); + clock.advance(Duration::from_secs(1)); + h.advance(); + assert_eq!(h.player_count(), 1); + let b = h.reconnect(&token, 0).unwrap(); + assert_eq!(b.viewer, a.viewer, "same player after reconnect"); + assert!(h.reconnect(&token, 0).is_err(), "tokens rotate on use"); + assert_eq!(h.zone().log, vec!["create", "join:alice"]); + + h.disconnect(b.client, false); + clock.advance(Duration::from_secs(4)); + h.advance(); + assert_eq!(h.player_count(), 0); + assert_eq!(h.zone().log.last().unwrap(), "leave:Disconnected"); + let _ = LeaveReason::Disconnected; +} + +#[test] +fn inputs_are_sanitized_deduped_and_acked_in_deltas() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(h.push_input(a.client, 1, 0, &[1, 0]), PushOutcome::Accepted); + assert_eq!( + h.push_input(a.client, 1, 0, &[1, 0]), + PushOutcome::Duplicate + ); + assert_eq!(h.push_input(a.client, 2, 0, &[9, 0]), PushOutcome::Rejected); + assert_eq!(h.push_input(a.client, 3, 0, &[1]), PushOutcome::Rejected); + assert_eq!(h.push_input(a.client, 4, 0, &[0, 1]), PushOutcome::Accepted); + assert_eq!( + h.push_input(ClientId(999), 1, 0, &[0, 1]), + PushOutcome::UnknownClient + ); + + clock.advance(MS(100)); + let r = h.advance(); + assert!(r.ticks > 0 && r.patched); + assert_eq!(h.push_input(a.client, 4, 0, &[0, 1]), PushOutcome::Stale); + let mut mirror = ClientMirror::new(); + for frame in frames_for(&h.drain_outbound(), a.client) { + mirror.apply(&frame).unwrap(); + } + assert_eq!(mirror.ack_seq, 4); + assert_eq!(mirror.entities.len(), 1, "own avatar replicated"); +} + +fn run_scripted(seed: u64) -> (u64, u64) { + let clock = ManualClock::new(); + let config = HostConfig { + world_seed: seed, + ..HostConfig::default() + }; + let (queue, _feed) = fact_channel(10_000, RetryPolicy::default()); + let mut h = host( + config, + &clock, + ArenaConfig { + spawn_every: Some(MS(200)), + ..Default::default() + }, + ) + .with_facts(queue); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let b = h.join(&claims("bob", "z1"), 0, "").unwrap(); + let mut seq = 0; + for step in 0..600u32 { + if step % 3 == 0 { + seq += 1; + let dx = ((step / 7) % 3) as i8 - 1; + let dy = ((step / 11) % 3) as i8 - 1; + h.push_input(a.client, seq, step, &[dx as u8, dy as u8]); + h.push_input(b.client, seq, step, &[dy as u8, dx as u8]); + } + clock.advance(MS(7)); + h.advance(); + h.drain_outbound(); + } + (h.zone().state_hash(), h.tick()) +} + +#[test] +fn same_seed_and_input_log_reproduce_state() { + let first = run_scripted(42); + let second = run_scripted(42); + assert_eq!(first, second); + assert_ne!(run_scripted(7).0, first.0, "different seed diverges"); +} + +/// Sink that takes `delay` per commit (simulated slow storage). +struct SlowSink { + delay: Duration, + inner: MemoryFactSink, +} + +impl FactSink for SlowSink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::facts::BoxFuture<'a, Result> { + Box::pin(async move { + tokio::time::sleep(self.delay).await; + self.inner.commit(fact).await + }) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slow_sink_never_stalls_the_tick() { + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(10_000, RetryPolicy::default()); + tokio::spawn(feed.run( + SlowSink { + delay: MS(100), + inner: sink.clone(), + }, + tokio::time::sleep, + )); + let config = HostConfig { + tick_rate: 50, + ..HostConfig::default() + }; + let clock = Arc::new(SystemClock::new()); + let mut h = ZoneHost::::new( + "z1", + config, + clock, + ArenaConfig { + fact_every_tick: true, + ..Default::default() + }, + ) + .with_facts(queue); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + + let start = Instant::now(); + let mut worst = Duration::ZERO; + let mut ticks = 0; + while start.elapsed() < MS(600) { + let t0 = Instant::now(); + let r = h.advance(); + worst = worst.max(t0.elapsed()); + ticks += r.ticks; + h.drain_outbound(); + tokio::time::sleep(MS(5)).await; + } + // 600 ms at 50 Hz = 30 ticks; storage at 10 commits/s must not slow it. + assert!(ticks >= 27, "ticks = {ticks}"); + assert!(worst < MS(25), "an advance took {worst:?}"); + assert!( + h.facts_in_flight() > 10, + "facts are still queued behind slow storage" + ); + assert!(h.zone().emit_errors.is_empty()); + let settled = h.zone().settled.len(); + assert!( + settled >= 2, + "settlements flow back on later ticks ({settled})" + ); + assert!(h + .zone() + .settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + assert!(sink.committed().len() >= settled); +} + +struct FlakySink { + failures_left: AtomicU32, + permanent_key: String, +} + +impl FactSink for FlakySink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::facts::BoxFuture<'a, Result> { + Box::pin(async move { + if fact.key() == self.permanent_key { + return Err(FactError::Permanent("no such player".into())); + } + if self.failures_left.load(Ordering::SeqCst) > 0 { + self.failures_left.fetch_sub(1, Ordering::SeqCst); + return Err(FactError::Retryable("busy".into())); + } + Ok(FactReceipt { + payload: serde_json::json!({ "ok": fact.key() }), + replayed: false, + }) + }) + } +} + +#[tokio::test] +async fn retries_backoff_permanent_failure_backpressure_and_principal_binding() { + let (mut queue, feed) = fact_channel( + 2, + RetryPolicy { + max_attempts: 5, + base_backoff: MS(1), + max_backoff: MS(4), + }, + ); + let worker = tokio::spawn(feed.run( + FlakySink { + failures_left: AtomicU32::new(2), + permanent_key: "bad".into(), + }, + tokio::time::sleep, + )); + queue + .try_send(Fact::new("good", "credit_xp", serde_json::json!({}))) + .unwrap(); + assert_eq!( + queue.try_send(Fact::new("good", "credit_xp", serde_json::json!({}))), + Err(EmitError::DuplicateKey) + ); + queue + .try_send(Fact::new("bad", "credit_xp", serde_json::json!({}))) + .unwrap(); + assert_eq!( + queue.try_send(Fact::new("third", "credit_xp", serde_json::json!({}))), + Err(EmitError::Backpressure) + ); + let mut settled = Vec::new(); + while settled.len() < 2 { + settled.extend(queue.drain()); + tokio::time::sleep(MS(2)).await; + } + assert!(matches!(settled[0].outcome, FactOutcome::Committed(_))); + assert!(matches!( + settled[1].outcome, + FactOutcome::Failed { + error: FactError::Permanent(_), + attempts: 1 + } + )); + assert_eq!(queue.in_flight(), 0); + drop(queue); + worker.await.unwrap(); + + // Principal and stamp are bound by the host from the verified ticket. + let clock = ManualClock::new(); + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(100, RetryPolicy::default()); + let worker = tokio::spawn(feed.run(sink.clone(), tokio::time::sleep)); + let mut h = host( + HostConfig { + content_version: "c1".into(), + ..HostConfig::default() + }, + &clock, + ArenaConfig::default(), + ) + .with_facts(queue); + let a = h.join(&claims("alice", "z1"), 0, "c1").unwrap(); + let player = match a.viewer { + distributed_game::Viewer::Player(p) => p, + _ => unreachable!(), + }; + let (x, y) = { + let av = &h.zone().avatars[&player]; + (av.x, av.y) + }; + h.zone_mut().coins.insert(77, (x, y)); + clock.advance(MS(40)); + h.advance(); + let tick = h.tick(); + drop(h); + worker.await.unwrap(); + let committed = sink.committed(); + assert_eq!(committed.len(), 1); + assert_eq!(committed[0].principal(), Some("alice")); + assert_eq!(committed[0].key(), "coin:z1:77"); + assert_eq!(committed[0].stamp().zone_id, "z1"); + assert_eq!(committed[0].stamp().content_version, "c1"); + assert!(committed[0].stamp().tick >= 1 && committed[0].stamp().tick <= tick); +} + +#[test] +fn observers_receive_deltas_without_owning_a_player() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + let mut obs_claims = claims("watcher", "z1"); + obs_claims.role = Role::Observer; + let o = h.join(&obs_claims, 0, "").unwrap(); + assert_eq!(h.player_count(), 1); + assert_eq!( + h.push_input(o.client, 1, 0, &[1, 0]), + PushOutcome::UnknownClient + ); + clock.advance(MS(100)); + h.advance(); + let mut mirror = ClientMirror::new(); + for frame in frames_for(&h.drain_outbound(), o.client) { + mirror.apply(&frame).unwrap(); + } + assert_eq!(mirror.welcome.as_ref().unwrap().role, Role::Observer); + assert_eq!(mirror.entities.len(), 1); + h.disconnect(o.client, false); + assert!(h.zone().log.contains(&"unobserve".to_string())); +} + +#[test] +fn same_principal_replaces_previous_connection() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let b = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(a.viewer, b.viewer); + assert_eq!(h.client_count(), 1); + let out = h.drain_outbound(); + assert!(out.contains(&Outbound::Close { client: a.client })); + assert_eq!(h.zone().log, vec!["create", "join:alice"]); +} From 4c556c589b3b0df1b7c73e36b7ceeaa7a2304148 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:00:06 -0500 Subject: [PATCH 126/484] feat(game): add replication protocol, interest and ws transport Document the v1 binary wire protocol in PROTOCOL.md (little-endian, LEB128 varints, one message per WebSocket frame) with worked byte examples for Hello, Input, Welcome (including the entity schema) and Delta, bit-exact f64 quantization rules for quant_f32 and angle fields, and HS256 ticket rules. Golden fixtures (primitives, quantization, messages) are generated into tests/fixtures for the JS client. Replication is per client against last-sent state with a uniform spatial grid, view radius with leave hysteresis, global entities, observer subscriptions and a byte budget driven by priority accumulation so starved entities are eventually sent. The net feature adds GameServer: an axum WebSocket server hosting many zones (one task per zone, routed by /zones/{zone_id}), binary frames only, HMAC-SHA256 ticket admission with single-use nonces where the principal comes only from the verified ticket, per-connection input rate limiting, reconnect tokens within the grace window, dev latency and jitter simulation, and graceful shutdown. An end-to-end test drives it with tokio-tungstenite. Refs [[tasks/gr-p3-replication-transport]] --- distributed_game/Cargo.toml | 12 + distributed_game/PROTOCOL.md | 452 +++++++++++ distributed_game/README.md | 124 +++ distributed_game/src/lib.rs | 8 + distributed_game/src/net/mod.rs | 760 ++++++++++++++++++ distributed_game/src/net/ticket.rs | 222 +++++ distributed_game/src/protocol/mod.rs | 2 +- distributed_game/src/schema.rs | 2 +- distributed_game/src/zone.rs | 2 +- distributed_game/tests/fixtures/messages.json | 511 ++++++++++++ .../tests/fixtures/primitives.json | 138 ++++ .../tests/fixtures/quantization.json | 574 +++++++++++++ distributed_game/tests/golden/main.rs | 521 ++++++++++++ distributed_game/tests/net_e2e/main.rs | 296 +++++++ distributed_game/tests/replication/main.rs | 178 ++++ 15 files changed, 3799 insertions(+), 3 deletions(-) create mode 100644 distributed_game/PROTOCOL.md create mode 100644 distributed_game/README.md create mode 100644 distributed_game/src/net/mod.rs create mode 100644 distributed_game/src/net/ticket.rs create mode 100644 distributed_game/tests/fixtures/messages.json create mode 100644 distributed_game/tests/fixtures/primitives.json create mode 100644 distributed_game/tests/fixtures/quantization.json create mode 100644 distributed_game/tests/golden/main.rs create mode 100644 distributed_game/tests/net_e2e/main.rs create mode 100644 distributed_game/tests/replication/main.rs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 2aeb54a9a..0519169df 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -16,17 +16,29 @@ default = [] runtime = ["dep:tokio"] # Adapter that commits facts into a `distributed` AggregateCell. cell = ["dep:distributed", "dep:sha2"] +# axum WebSocket zone server with signed-ticket admission. +net = ["runtime", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros"] [dependencies] serde_json = "1" tokio = { version = "1", default-features = false, features = ["rt", "sync", "time"], optional = true } distributed = { path = "..", default-features = false, optional = true } +axum = { version = "0.8", default-features = false, features = ["ws", "tokio", "http1"], optional = true } +hmac = { version = "0.12", optional = true } sha2 = { version = "0.10", optional = true } +base64 = { version = "0.23", optional = true } [dev-dependencies] tokio = { version = "1", features = ["full", "test-util"] } +tokio-tungstenite = "0.30" +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } serde = { version = "1", features = ["derive"] } +[[test]] +name = "net_e2e" +path = "tests/net_e2e/main.rs" +required-features = ["net"] + [[test]] name = "cell_sink" path = "tests/cell_sink/main.rs" diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md new file mode 100644 index 000000000..7a490bca2 --- /dev/null +++ b/distributed_game/PROTOCOL.md @@ -0,0 +1,452 @@ +# distributed_game wire protocol — version 1 + +Normative specification of the binary protocol spoken between a +`distributed_game` zone server and its clients. The Rust implementation +lives in `src/protocol/` and `src/schema.rs`; the reference client-side +state machine is `protocol::ClientMirror`. Golden byte fixtures for +independent implementations live in `tests/fixtures/*.json` (§9). + +Key words MUST / MUST NOT / SHOULD / MAY are used as in RFC 2119. + +--- + +## 1. Transport and framing + +### 1.1 WebSocket (normative transport) + +- Endpoint: `GET /zones/{zone_id}` upgraded to a WebSocket. The path + selects the zone; the zone in the admission ticket MUST equal it. +- Every protocol message is exactly **one binary WebSocket message**. + There is no additional length prefix inside a WebSocket message. +- Text messages are a protocol violation: the server replies + `Error(BAD_MESSAGE)` and closes. +- The transport is reliable and ordered. Deltas are encoded against the + last state the server *sent* to that connection (§7.2), so a client MUST + apply every server message in order and MUST NOT skip any. +- Byte 0 of every message is the **message type** (§6). Client→server + types are `0x01..0x7f`; server→client types are `0x80..0xff`. +- Servers reject inbound messages larger than 64 KiB by default. + +### 1.2 Stream framing (non-message transports) + +For byte-stream transports (raw TCP, pipes, test harnesses) each message +is prefixed with its byte length as a `varuint` (§2): `varuint(len) ‖ message`. +WebSocket transports MUST NOT use this prefix. + +## 2. Primitive encodings + +All multi-byte fixed-width numbers are **little-endian**. + +| Name | Encoding | +|---|---| +| `u8` | 1 byte. | +| `bool` | `u8`, `0x00` = false, `0x01` = true. Any other value is a decode error. | +| `varuint` | Unsigned LEB128 of a 32-bit value: 7 bits per byte, least-significant group first; bit 7 (`0x80`) set means another byte follows. At most 5 bytes; in the 5th byte only the low 4 bits may be set (`<= 0x0f`), otherwise decode error (overflow). Encoders MUST emit the minimal form. | +| `varint` | Signed 32-bit, zigzag-mapped then `varuint`: `z = (v << 1) ^ (v >> 31)` (arithmetic shift); decode `v = (z >>> 1) ^ -(z & 1)`. | +| `f32` | IEEE-754 binary32, 4 bytes LE. | +| `f64` | IEEE-754 binary64, 8 bytes LE. | +| `string` | `varuint` byte length, then that many bytes of UTF-8. Length MUST be <= 1 MiB. Invalid UTF-8 is a decode error. | +| `bytes` | `varuint` length, then raw bytes (<= 1 MiB). | +| `short_string` | `u8` byte length (0..255), then UTF-8. Encoders truncate at a char boundary to fit 255 bytes. | + +Examples (from `fixtures/primitives.json`): + +| Value | Kind | Bytes | +|---|---|---| +| 0 | varuint | `00` | +| 127 | varuint | `7f` | +| 128 | varuint | `80 01` | +| 300 | varuint | `ac 02` | +| 4294967295 | varuint | `ff ff ff ff 0f` | +| -1 | varint | `01` | +| 1 | varint | `02` | +| -64 | varint | `7f` | +| 64 | varint | `80 01` | +| 1.5 | f32 | `00 00 c0 3f` | +| 1234.5 | f64 | `00 00 00 00 00 4a 93 40` | +| "hi" | string | `02 68 69` | +| "héros" | string | `06 68 c3 a9 72 6f 73` | + +JavaScript note: `varuint` values up to `2^32-1` exceed the int32 range; +decode with multiplication (`value += (b & 0x7f) * 2 ** shift`) or `>>> 0`, +never with signed `<<` on the 5th byte. + +## 3. Ids, ticks and times + +- **Sequence numbers** (`seq`) are `varuint`, start at **1** per connection + and strictly increase. `ack_seq = 0` means "nothing processed yet". +- **Ticks** are `varuint` holding the low 32 bits of the server's tick + counter. +- **Times** (`server_time`, `client_time`) are `f64` milliseconds on the + sender's own monotonic clock (origin arbitrary). Clients estimate + offset/RTT from Ping/Pong: + `rtt = now - pong.client_time`; `offset = pong.server_time + rtt/2 - now`. +- **Entity ids** are `varuint`, assigned by the game, unique within a zone. + An id MAY be reused after its remove has been sent. +- **Kind ids** are `varuint` values `<= 65535`. + +## 4. Field types and quantization + +Each component field has a wire type. Type tags appear in the schema (§5). + +| Tag | Type | Params (in schema) | Value encoding | Decoded value | +|---|---|---|---|---| +| 0 | `bool` | — | `bool` | boolean | +| 1 | `u8` | — | 1 raw byte | unsigned int | +| 2 | `u16` | — | `varuint` (MUST be <= 65535) | unsigned int | +| 3 | `u32` | — | `varuint` | unsigned int | +| 4 | `i32` | — | `varint` (zigzag) | signed int | +| 5 | `f32` | — | `f32` | float | +| 6 | `quant_f32` | `f32 min`, `f32 max`, `u8 bits` (1..32) | `varuint q` | float | +| 7 | `angle` | `u8 bits` (1..32) | `varuint q` | float (radians, `[0, 2π)`) | +| 8 | `short_str` | — | `short_string` | string | +| 9 | `bytes` | — | `bytes` | byte array | + +Unknown tags are a decode error. + +All quantization math below is performed in **IEEE-754 binary64** +(JavaScript `number`) in exactly the order written; conversions to f32 +are round-to-nearest-even (`Math.fround`). `floor` is mathematical floor. +Server and client MUST use identical formulas so client-side prediction +can reproduce exactly what the server will send. + +### 4.1 `quant_f32 {min, max, bits}` + +``` +maxq = 2^bits - 1 (as f64) +lo = f64(min); hi = f64(max) +encode(v): v is an f32 widened to f64 + if hi <= lo: q = 0 + else: + x = isNaN(v) ? lo : v + x = clamp(x, lo, hi) + t = (x - lo) / (hi - lo) + q = min(floor(t * maxq + 0.5), maxq) (round half up) +decode(q): + q MUST be <= maxq, otherwise decode error + v = fround(lo + (q / maxq) * (hi - lo)) +``` + +Worked example (`min=-100, max=100, bits=16`, from `fixtures/quantization.json`): +`v = 0.0` → `t = 0.5` → `q = floor(0.5 * 65535 + 0.5) = 32768` → bytes +`80 80 02`; decodes to `fround(-100 + (32768/65535) * 200) = 0.0015259022` +(bits `3ac800c8`). `v = 250` clamps to `q = 65535` (`ff ff 03`) → `100.0`. + +### 4.2 `angle {bits}` + +``` +TAU = 6.283185307179586 (2π as f64) +steps = 2^bits (as f64) +encode(v): + if !isFinite(v): q = 0 + else: + a = v % TAU (truncated remainder, JS `%`, C fmod) + if a < 0: a = a + TAU + q = floor((a / TAU) * steps + 0.5) % steps +decode(q): + q MUST be < steps, otherwise decode error + v = fround((q * TAU) / steps) +``` + +Example (`bits=8`): `π` → `q = 128`; `-π/2` → `a = 3π/2` → `q = 192`; +`-0.000001` → `a ≈ TAU` → `q = 256 % 256 = 0`. + +### 4.3 Coercion (server side) + +The server coerces game-supplied values to the field type (numeric +saturation, `bool` = non-zero). Clients only ever see canonical values. + +## 5. Entity schema encoding + +Sent inside Welcome. A generic client decodes Deltas with it, no codegen. + +``` +schema := varuint kind_count, kind* +kind := varuint kind_id, string name, varuint field_count (<= 32), field* +field := string name, u8 type_tag, params +params := (tag 6) f32 min, f32 max, u8 bits + | (tag 7) u8 bits + | (other tags) nothing +``` + +Field order is wire order: field `i` is bit `i` of update masks. A kind +has at most 32 fields. Duplicate kind ids are a decode error. Server-side +replication priorities are not transmitted. + +## 6. Messages + +### 6.1 Type bytes + +| Byte | Direction | Message | +|---|---|---| +| `0x01` | C→S | Hello | +| `0x02` | C→S | Input | +| `0x03` | C→S | Ping | +| `0x04` | C→S | Leave | +| `0x80` | S→C | Welcome | +| `0x81` | S→C | Delta | +| `0x82` | S→C | Event | +| `0x83` | S→C | Pong | +| `0x84` | S→C | Freeze | +| `0x85` | S→C | Resume | +| `0x86` | S→C | Handoff | +| `0x87` | S→C | Kick | +| `0x88` | S→C | Error | + +Unknown type bytes and trailing bytes after a complete message are +decode errors. + +### 6.2 Client → server + +``` +Hello := 0x01, varuint protocol_version, string content_version, + varuint capabilities, string ticket, string reconnect_token +Input := 0x02, varuint seq, varuint client_tick, bytes payload +Ping := 0x03, f64 client_time +Leave := 0x04 +``` + +- **Hello** MUST be the first message, sent within the server's hello + timeout (default 5 s). `protocol_version` MUST be `1`. + `content_version` MUST equal the server's when the server pins one. + `capabilities` are game-defined bits, opaque to the runtime. For a fresh + join `ticket` is a signed admission ticket (§8) and `reconnect_token` is + empty; for a reconnect `ticket` MAY be empty and `reconnect_token` is the + token from the last Welcome. A second Hello gets `Error(BAD_MESSAGE)`. +- **Input**: `payload` is game-defined. Duplicate or already-processed + `seq` values are ignored. Inputs are rate limited per connection + (default 120/s, burst 240); excess inputs are dropped and the server + sends `Error(RATE_LIMITED)` at most once per second; sustained abuse + gets `Kick(RATE_LIMITED)`. Observers' inputs are ignored. +- **Ping**: the server answers with Pong immediately. +- **Leave**: graceful exit; the player is removed at once (no reconnect + grace). + +Worked example — Hello (`version 1, content "c1", caps 5, ticket "t.k.n"`): + +``` +01 type Hello +01 protocol_version 1 +02 63 31 content_version "c1" +05 capabilities 5 +05 74 2e 6b 2e 6e ticket "t.k.n" +00 reconnect_token "" +``` + +Input (`seq 300, client_tick 1000, payload 01 ff`): `02 ac02 e807 02 01ff`. +Ping (`1234.5`): `03 0000000000004a9340`. Leave: `04`. + +### 6.3 Server → client + +``` +Welcome := 0x80, string session_id, string zone_id, u8 role, + varuint tick_rate, varuint patch_rate, varuint server_tick, + f64 server_time, string reconnect_token, string content_version, + schema +Delta := 0x81, see §7 +Event := 0x82, varuint type_id, bytes payload +Pong := 0x83, f64 client_time, f64 server_time +Freeze := 0x84, string reason, string version, string notes +Resume := 0x85, string reason, string version, string notes +Handoff := 0x86, string target_zone, string transfer_ticket +Kick := 0x87, varuint code, string message +Error := 0x88, varuint code, string message +``` + +- **Welcome**: `role` `0` = player, `1` = observer. `session_id` is stable + across reconnects of the same player. `reconnect_token` is single-use and + rotated on every Welcome (empty for observers). A client MUST discard all + mirrored entities on Welcome; the server resends creates afterwards. + `tick_rate`/`patch_rate` are Hz. +- **Event**: reliable, ordered, game-defined (`type_id`, `payload`). Events + are queued when emitted and may arrive before the Delta of the tick that + produced them. +- **Pong**: echoes `client_time`; `server_time` is the server clock. +- **Freeze**: the zone stops simulating; inputs are rejected until + **Resume**. Used for content rollouts (`version`) and maintenance. +- **Handoff**: the player has been removed from this zone; connect to + `target_zone` and present `transfer_ticket` as the Hello ticket. The + server closes the socket. +- **Kick**: the session is over; the server closes the socket. + Codes: `1` BY_ZONE, `2` REPLACED (same principal connected again), + `3` SHUTDOWN, `4` RATE_LIMITED, `5` ZONE_DISPOSED, `6` SLOW_CONSUMER. +- **Error**: codes `1` BAD_MESSAGE, `2` UNAUTHORIZED, `3` REJECTED, + `4` ZONE_FULL, `5` VERSION_MISMATCH, `6` RATE_LIMITED, `7` NOT_FOUND, + `8` RECONNECT_FAILED. Errors during the handshake are followed by close; + `BAD_MESSAGE` and `RATE_LIMITED` after joining are not. + +Worked example — Welcome (session "s1", zone "z1", player, 30 Hz ticks, +20 Hz patches, tick 42, time 1000.25 ms, token "rt", content "c1", +schema of `fixtures/messages.json`): + +``` +80 Welcome +02 73 31 session_id "s1" +02 7a 31 zone_id "z1" +00 role player +1e tick_rate 30 +14 patch_rate 20 +2a server_tick 42 +00 00 00 00 00 42 8f 40 server_time 1000.25 +02 72 74 reconnect_token "rt" +02 63 31 content_version "c1" +02 2 kinds + 01 04 68 65 72 6f 0a kind 1 "hero", 10 fields + 05 616c697665 00 "alive" bool + 05 6c6576656c 01 "level" u8 + 02 6870 02 "hp" u16 + 04 676f6c64 03 "gold" u32 + 02 647a 04 "dz" i32 + 05 7370656564 05 "speed" f32 + 01 78 06 0000c8c2 0000c842 10 "x" quant_f32 min -100 max 100 bits 16 + 03 796177 07 0a "yaw" angle bits 10 + 04 6e616d65 08 "name" short_str + 03 746167 09 "tag" bytes + 02 03 6f 72 62 01 kind 2 "orb", 1 field + 01 78 06 00000000 00008042 0c "x" quant_f32 min 0 max 64 bits 12 +``` + +## 7. Delta + +### 7.1 Encoding + +``` +Delta := 0x81, varuint server_tick, varuint ack_seq, + varuint remove_count, varuint id * remove_count, + varuint create_count, create * create_count, + varuint update_count, update * update_count +create := varuint id, varuint kind_id, value(field_0) … value(field_{n-1}) +update := varuint id, varuint mask, value(field_i) for each set bit i, ascending +``` + +- `ack_seq` is the highest input `seq` of this connection's player that + the simulation has consumed (or discarded under a "latest" policy). + Prediction: drop pending inputs with `seq <= ack_seq`, reset to the + authoritative state, replay the rest. +- A **create** carries every field of the kind in schema order. +- An **update** carries a 32-bit field bitmask as a `varuint` (bit `i` set = + field `i` present) followed by only those fields in ascending `i`. A + mask bit `>= field_count` is a decode error. An update's kind is the + kind of the entity as known by the client (from its create, possibly + earlier in the same Delta). +- The server always sends a Delta every patch to every connection, even + when empty (it carries `server_tick` and `ack_seq`). + +### 7.2 Applying (normative, see `ClientMirror::apply`) + +1. Remove every id in `removes`. +2. Insert every create (replacing any existing entry with the same id). +3. For each update, overwrite the present fields of the known entity. An + update for an unknown id is a protocol error. +4. Set `server_tick` and `ack_seq`. + +### 7.3 Server semantics (informative) + +- Deltas are computed per connection against what was last **sent** to it. +- Interest: each connection has a view (center, radius) on the zone's 2D + interest plane. An entity is created when within `radius` and removed + when beyond `radius × (1 + leave_margin)` (default margin 0.1) or gone. + Global entities are visible everywhere. +- Change detection compares encoded field bytes, so changes smaller than + the quantization step are never sent. +- Per-connection byte budget (default 4096 B of create+update data per + Delta): candidates gain `kind priority × entity priority × max(changed + field priority) × 1/(1 + distance/radius)` per patch into an + accumulator; the highest accumulators are sent first and reset; + deferred entities keep accumulating, so none starve. At least one + candidate is sent per Delta. Removes are never budgeted. + +### 7.4 Worked example + +`fixtures/messages.json` → `delta`, with the client already knowing +entity 5 (kind 1 "hero") and 6 (kind 2 "orb"): + +``` +81 Delta +c8 01 server_tick 200 +11 ack_seq 17 +02 09 82 01 removes [9, 130] +02 2 creates + ac 02 01 id 300, kind 1 + 01 alive true + 07 level 7 + ac 02 hp 300 + f0 a2 04 gold 70000 + 03 dz -2 (zigzag 3) + 00 00 c0 3f speed 1.5 + 00 x -100.0 (q 0) + 00 yaw 0 (q 0) + 03 41 6e 61 name "Ana" + 02 de ad tag de ad + ad 02 02 id 301, kind 2 + 80 10 x 32.0 → q 2048 (12 bits over 0..64) +03 3 updates + 05 44 id 5, mask 0b0100_0100 (fields 2 and 6) + ab 02 hp 299 + 80 80 02 x q 32768 → 0.0015259022 + 06 01 id 6, mask 0b1 + ff 1f x q 4095 → 64.0 + ad 02 01 id 301 (created above), mask 0b1 + 00 x q 0 → 0.0 +``` + +Full hex: `81c801110209820102ac02010107ac02f0a204030000c03f000003416e6102deadad02028010030544ab028080020601ff1fad020100`. + +An empty Delta at tick 43: `81 2b 00 00 00 00`. + +## 8. Admission tickets + +A ticket is a compact JWT signed with **HS256** (HMAC-SHA256 over the +ASCII `base64url(header) "." base64url(claims)` with a shared secret; +unpadded base64url). Any HS256 JWT library can mint one. + +- Header: `{"alg":"HS256","typ":"JWT"}`; any other `alg` is rejected. +- Claims: + - `sub` (string, required) — the **principal**. The server takes + identity only from this verified claim; nothing in Hello, Input or any + payload can set or change it. + - `zone` (string, required) — MUST equal the route's zone id. + - `exp` (integer Unix seconds, required) — rejected when `exp <= now`. + - `nonce` (string, required) — single use; reuse before `exp` is + rejected. + - `role` (string, optional) — `"player"` (default) or `"observer"`. + Observers receive Deltas and Events but own no player and cannot send + inputs. +- Failures produce `Error(UNAUTHORIZED)` and close. + +Reconnect: after an abrupt disconnect the player stays in the zone for +the reconnect grace window (default 15 s). A Hello with the last Welcome's +`reconnect_token` rebinds the same player (same `session_id`, new token, +fresh creates). After the window the player is removed and the token +fails with `Error(RECONNECT_FAILED)`. A fresh join of the same principal +replaces any existing connection (`Kick(REPLACED)` to the old one). + +## 9. Golden fixtures + +`tests/fixtures/` (regenerate with `UPDATE_GOLDEN=1 cargo test -p +distributed_game --test golden`; a drift fails the test): + +- `primitives.json` — `{cases: [{kind, value, hex}]}` for varuint, varint, + f32, f64, string, short_string. +- `quantization.json` — `{cases: [{field, input_bits, q, hex, decoded}]}`; + `input_bits` is the input f32 bit pattern (hex, big-endian digits), + `q` the quantized integer, `hex` its varuint bytes. +- `messages.json` — `{messages: [{name, direction, hex, decoded, + known_entities?, schema?}]}`. Delta entries include the schema and the + `known_entities` (`[{id, kind}]`) needed to decode updates. + +JSON conventions in `decoded`: + +- byte arrays are lowercase hex strings; +- floats are `{"f32": number, "bits": "xxxxxxxx"}` (`bits` is the exact + binary32 pattern; compare bits, not decimal text); +- field values are tagged: `{"bool"}`, `{"u"}`, `{"i"}`, `{"f32","bits"}`, + `{"str"}`, `{"bytes"}`; +- schema fields are `{"name", "type", ...params}` with `type` one of + `bool u8 u16 u32 i32 f32 quant_f32 angle short_str bytes`. + +## 10. Versioning + +`protocol_version` changes on any incompatible wire change. Message type +bytes `0x05..0x7f` and `0x89..0xff`, and field type tags `10..255`, are +reserved for future versions. diff --git a/distributed_game/README.md b/distributed_game/README.md new file mode 100644 index 000000000..e0ab068f7 --- /dev/null +++ b/distributed_game/README.md @@ -0,0 +1,124 @@ +# distributed_game + +Authoritative multiplayer zone runtime for the `distributed` CQRS/ES +framework. A game implements [`Zone`]; [`ZoneHost`] runs it with a fixed +timestep, activity tiers, sequenced inputs, timers, seeded RNG, +non-blocking durable facts and interest-managed binary replication. The +optional `net` feature serves many zones over WebSockets. + +Physics is out of scope: bring your own and step it in `on_tick`. + +## Features + +| Feature | Adds | Deps | +|---|---|---| +| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | +| `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | +| `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | +| `net` | `net::GameServer` (axum WebSocket), HMAC tickets | `axum`, `hmac`, `sha2`, `base64`, `tokio` | + +## Minimal zone + +```rust +use std::sync::Arc; +use std::time::Duration; +use distributed_game::*; + +struct Room { x: f32 } + +impl Zone for Room { + type Config = (); + type Input = i8; // -1, 0, 1 + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new().kind( + KindDef::new(1, "dot") + .field("x", FieldType::QuantF32 { min: -50.0, max: 50.0, bits: 12 }), + ) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { Room { x: 0.0 } } + + fn decode_input(&self, _p: PlayerId, bytes: &[u8]) -> Option { + bytes.first().map(|b| *b as i8) + } + + fn sanitize_input(&self, _p: PlayerId, dx: i8) -> Option { + (-1..=1).contains(&dx).then_some(dx) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + for p in players { + for input in ctx.take_inputs(p, ConsumePolicy::Drain) { + self.x += f32::from(input.input) * 5.0 * ctx.dt_secs(); + } + } + } + + fn replicate(&self, out: &mut WorldView) { + out.push(EntityState::new(1, 1, self.x, 0.0, vec![FieldValue::F(self.x)])); + } +} + +let clock = ManualClock::new(); +let mut host = ZoneHost::::new("room-1", HostConfig::default(), Arc::new(clock.clone()), ()); +let claims = TicketClaims { + principal: "alice".into(), zone: "room-1".into(), + expires_at: u64::MAX, nonce: "n".into(), role: Role::Player, +}; +let joined = host.join(&claims, 0, "").unwrap(); +host.push_input(joined.client, 1, 0, &[1]); +clock.advance(Duration::from_millis(100)); +host.advance(); +for out in host.drain_outbound() { /* send Outbound::Frame bytes to the client */ } +``` + +Serving it (`net`): + +```rust,ignore +let server = GameServer::::new(ServerConfig::new(TicketKey::new(secret)), |zone_id| { + zone_id.starts_with("room-").then_some(()) +}); +server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_signal).await?; +``` + +## Durable facts + +Zones never await storage. Emit a fact during a tick: + +```rust,ignore +ctx.emit_fact_for(player, Fact::new(format!("kill:{zone}:{tick}:{enemy}"), "hero.credit_xp", json!({"amount": 25})))?; +``` + +The host binds the principal from the player's **verified ticket** and +stamps zone/tick/content version. A `FactSink` commits facts on a worker +with bounded retries/backoff; `Zone::on_fact_settled` receives the outcome +on a later tick. `cell::CellFactSink` dispatches into an `AggregateCell` +with a deterministic command id per fact key, so retries replay instead of +double-crediting. + +## Protocol + +See [`PROTOCOL.md`](PROTOCOL.md) — binary, little-endian, varints, one +message per WebSocket frame, schema shipped in Welcome so generic clients +need no codegen. Golden fixtures for other implementations are in +`tests/fixtures/`. + +## Tests + +```sh +cargo test -p distributed_game --all-features +UPDATE_GOLDEN=1 cargo test -p distributed_game --test golden # accept wire changes +``` + +## Extension seams (later phases) + +- Hibernation / directory: `Tier::Dormant`, `ZoneHost::dispose`, zone + factory in `GameServer`. +- Handoff saga: `ZoneHost::handoff` + `LeaveReason::Handoff` + Handoff message. +- Content barrier: `ZoneHost::freeze` / `resume`. +- Metrics: `AdvanceReport`, `replication::DeltaStats`, `PushOutcome`. +- Rewind/lag compensation: `SequencedInput::client_tick`, deterministic + `ZoneRng` and `ManualClock`. diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index f226243c2..6f998e0bc 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -11,6 +11,8 @@ //! - Replication: an [`EntitySchema`] shipped in Welcome, per-client deltas //! against last-sent state, spatial interest and a byte budget with //! priority accumulation. Wire format: [`protocol`] / `PROTOCOL.md`. +//! - Transport (`net` feature): axum WebSocket server hosting many zones +//! with HMAC-signed ticket admission ([`net`]). //! //! Physics is out of scope: games bring their own and run it in `on_tick`. //! @@ -30,6 +32,8 @@ pub mod facts; pub mod host; pub mod input; pub mod interest; +#[cfg(feature = "net")] +pub mod net; pub mod protocol; pub mod replication; pub mod rng; @@ -60,3 +64,7 @@ pub use zone::{ Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, Tier, Viewer, Zone, }; + +#[doc = include_str!("../README.md")] +#[cfg(doctest)] +pub struct ReadmeDoctests; diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs new file mode 100644 index 000000000..5bb5cda46 --- /dev/null +++ b/distributed_game/src/net/mod.rs @@ -0,0 +1,760 @@ +//! WebSocket transport (`net` feature): one axum server hosting many zones. +//! +//! - Route: `GET /zones/{zone_id}` upgrades to a WebSocket. Zones are created +//! on first use through the game's factory and each runs on its own Tokio +//! task driving a [`ZoneHost`]. +//! - Binary frames only (one protocol message per frame); text frames get +//! `Error(BAD_MESSAGE)` and are closed. +//! - Admission: the first frame must be Hello within `hello_timeout`. A fresh +//! join needs a ticket verified with [`TicketKey`] (signature, expiry, +//! zone == route zone, single-use nonce). The principal comes **only** from +//! the verified ticket. A reconnect presents the Welcome's reconnect token +//! within the host's `reconnect_grace`. +//! - Inputs are rate limited per connection with a token bucket; excess +//! inputs are dropped (one `Error(RATE_LIMITED)` per second) and sustained +//! abuse is kicked. +//! - [`NetSim`] adds latency/jitter in both directions for development. +//! - [`GameServer::serve`] shuts down gracefully: every zone kicks its +//! clients with `Kick(SHUTDOWN)`, runs `on_dispose`, and connections close. + +pub mod ticket; + +use std::collections::{HashMap, VecDeque}; +use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{Path, State}; +use axum::response::Response; +use axum::routing::get; +use axum::Router; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::JoinHandle; +use tokio::time::Instant; + +pub use ticket::{NonceCache, TicketError, TicketKey}; + +use crate::clock::{Clock, SystemClock}; +use crate::facts::{fact_channel, spawn_fact_worker, FactQueue, FactSink, RetryPolicy}; +use crate::host::{HostConfig, JoinError, Joined, Outbound, ZoneHost}; +use crate::protocol::{error, kick, ClientMessage, ServerMessage, PROTOCOL_VERSION}; +use crate::rng::ZoneRng; +use crate::zone::{ClientId, Zone}; + +/// Development latency/jitter simulation (applied to each direction). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct NetSim { + /// Fixed one-way delay. + pub latency: Duration, + /// Extra uniform random delay in `[0, jitter]` (order is preserved). + pub jitter: Duration, +} + +/// Server settings. +#[derive(Debug, Clone)] +pub struct ServerConfig { + /// Settings for every hosted zone. + pub host: HostConfig, + /// HMAC key for admission tickets. + pub ticket_key: TicketKey, + /// Deadline for the first (Hello) frame. + pub hello_timeout: Duration, + /// Sustained inputs per second per connection. + pub input_rate: f64, + /// Input burst size. + pub input_burst: f64, + /// Outbound frames buffered per connection before it is dropped as slow. + pub outbound_queue: usize, + /// Largest accepted inbound frame. + pub max_frame_bytes: usize, + /// Optional dev latency simulation. + pub net_sim: Option, +} + +impl ServerConfig { + /// Defaults with the given ticket key. + pub fn new(ticket_key: TicketKey) -> Self { + Self { + host: HostConfig::default(), + ticket_key, + hello_timeout: Duration::from_secs(5), + input_rate: 120.0, + input_burst: 240.0, + outbound_queue: 512, + max_frame_bytes: 64 * 1024, + net_sim: None, + } + } +} + +enum ZoneCmd { + Join { + claims: crate::zone::TicketClaims, + capabilities: u32, + content_version: String, + out: mpsc::Sender, + reply: oneshot::Sender>, + }, + Reconnect { + token: String, + capabilities: u32, + out: mpsc::Sender, + reply: oneshot::Sender>, + }, + Input { + client: ClientId, + seq: u32, + client_tick: u32, + payload: Vec, + }, + Disconnect { + client: ClientId, + graceful: bool, + }, +} + +enum ConnOut { + Frame(Vec), + Close, +} + +type ConfigFactory = dyn Fn(&str) -> Option<::Config> + Send + Sync; +type FactsFactory = dyn Fn(&str) -> Option + Send + Sync; + +struct Inner { + config: ServerConfig, + clock: Arc, + factory: Box>, + facts: Option>, + nonces: Mutex, + zones: Mutex>>, + tasks: Mutex>>, + shutdown: watch::Sender, + token_counter: AtomicU64, +} + +/// Multi-zone WebSocket game server. +pub struct GameServer { + inner: Arc>, +} + +impl Clone for GameServer { + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + } + } +} + +impl GameServer +where + Z: Zone, + Z::Config: Send, +{ + /// Server whose zones are created by `factory(zone_id)`; `None` = 404. + pub fn new( + config: ServerConfig, + factory: impl Fn(&str) -> Option + Send + Sync + 'static, + ) -> Self { + Self::with_clock(config, Arc::new(SystemClock::new()), factory) + } + + /// Same as [`new`](Self::new) with an explicit clock. + pub fn with_clock( + config: ServerConfig, + clock: Arc, + factory: impl Fn(&str) -> Option + Send + Sync + 'static, + ) -> Self { + let (shutdown, _) = watch::channel(false); + Self { + inner: Arc::new(Inner { + config, + clock, + factory: Box::new(factory), + facts: None, + nonces: Mutex::new(NonceCache::default()), + zones: Mutex::new(HashMap::new()), + tasks: Mutex::new(Vec::new()), + shutdown, + token_counter: AtomicU64::new(0), + }), + } + } + + /// Commit every zone's facts through `sink` (one worker per zone). + /// Must be called before the server is cloned or served. + pub fn with_fact_sink( + mut self, + sink: S, + capacity: usize, + policy: RetryPolicy, + ) -> Self { + let sink = Arc::new(sink); + let inner = Arc::get_mut(&mut self.inner).expect("configure before sharing the server"); + inner.facts = Some(Box::new(move |_zone: &str| { + let (queue, feed) = fact_channel(capacity, policy); + spawn_fact_worker(feed, sink.clone()); + Some(queue) + })); + self + } + + /// axum router exposing `GET /zones/{zone_id}`. + pub fn router(&self) -> Router { + Router::new() + .route("/zones/{zone_id}", get(upgrade::)) + .with_state(self.inner.clone()) + } + + /// Ids of zones currently hosted. + pub fn zone_ids(&self) -> Vec { + let mut ids: Vec<_> = self + .inner + .zones + .lock() + .expect("zones") + .keys() + .cloned() + .collect(); + ids.sort(); + ids + } + + /// Begin graceful shutdown of every zone. + pub fn shutdown(&self) { + let _ = self.inner.shutdown.send(true); + } + + /// Serve until `signal` resolves, then shut every zone down and wait for + /// zone tasks to finish. + pub async fn serve( + self, + listener: tokio::net::TcpListener, + signal: impl Future + Send + 'static, + ) -> std::io::Result<()> { + let server = self.clone(); + let mut stopped = self.inner.shutdown.subscribe(); + axum::serve(listener, self.router()) + .with_graceful_shutdown(async move { + tokio::select! { + _ = signal => {} + _ = stopped.wait_for(|stop| *stop) => {} + } + server.shutdown(); + }) + .await?; + let tasks: Vec<_> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks")); + for task in tasks { + let _ = task.await; + } + Ok(()) + } +} + +fn zone_sender(inner: &Arc>, zone_id: &str) -> Option> +where + Z: Zone, + Z::Config: Send, +{ + if *inner.shutdown.borrow() { + return None; + } + let mut zones = inner.zones.lock().expect("zones"); + if let Some(tx) = zones.get(zone_id).filter(|tx| !tx.is_closed()) { + return Some(tx.clone()); + } + let zone_config = (inner.factory)(zone_id)?; + let (tx, rx) = mpsc::channel(1024); + zones.insert(zone_id.to_string(), tx.clone()); + let facts = inner.facts.as_ref().and_then(|f| f(zone_id)); + let task = tokio::spawn(run_zone::( + inner.clone(), + zone_id.to_string(), + zone_config, + facts, + rx, + )); + inner.tasks.lock().expect("tasks").push(task); + Some(tx) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +async fn run_zone( + inner: Arc>, + zone_id: String, + zone_config: Z::Config, + facts: Option, + mut rx: mpsc::Receiver, +) { + let key = inner.config.ticket_key.clone(); + let token_inner = inner.clone(); + let token_zone = zone_id.clone(); + let mut host = ZoneHost::::new( + zone_id.clone(), + inner.config.host.clone(), + inner.clock.clone(), + zone_config, + ) + .with_token_source(move || { + let n = token_inner.token_counter.fetch_add(1, Ordering::Relaxed); + let seed = format!( + "token|{token_zone}|{n}|{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + ); + key.hmac(seed.as_bytes())[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() + }); + if let Some(queue) = facts { + host = host.with_facts(queue); + } + let mut conns: HashMap> = HashMap::new(); + let mut shutdown = inner.shutdown.subscribe(); + loop { + let report = host.advance(); + route(&mut host, &mut conns); + let sleep_for = report + .next_wake + .map(|at| at.saturating_sub(inner.clock.now())); + tokio::select! { + biased; + _ = shutdown.wait_for(|stop| *stop) => { + let bye = ServerMessage::Kick { code: kick::SHUTDOWN, message: "server shutting down".into() }; + let frame = bye.encode(&()).expect("kick encodes"); + for out in conns.values() { + let _ = out.try_send(ConnOut::Frame(frame.clone())); + let _ = out.try_send(ConnOut::Close); + } + conns.clear(); + host.dispose(); + host.drain_outbound(); + break; + } + cmd = rx.recv() => { + let Some(cmd) = cmd else { break }; + handle_cmd(&mut host, &mut conns, cmd); + // Drain whatever else is queued before ticking again. + while let Ok(cmd) = rx.try_recv() { + handle_cmd(&mut host, &mut conns, cmd); + } + route(&mut host, &mut conns); + } + _ = async { + match sleep_for { + Some(d) => tokio::time::sleep(d).await, + None => std::future::pending().await, + } + } => {} + } + } + inner.zones.lock().expect("zones").remove(&zone_id); +} + +fn handle_cmd( + host: &mut ZoneHost, + conns: &mut HashMap>, + cmd: ZoneCmd, +) { + match cmd { + ZoneCmd::Join { + claims, + capabilities, + content_version, + out, + reply, + } => { + let result = host.join(&claims, capabilities, &content_version); + if let Ok(joined) = &result { + conns.insert(joined.client, out); + } + let _ = reply.send(result); + } + ZoneCmd::Reconnect { + token, + capabilities, + out, + reply, + } => { + let result = host.reconnect(&token, capabilities); + if let Ok(joined) = &result { + conns.insert(joined.client, out); + } + let _ = reply.send(result); + } + ZoneCmd::Input { + client, + seq, + client_tick, + payload, + } => { + host.push_input(client, seq, client_tick, &payload); + } + ZoneCmd::Disconnect { client, graceful } => { + conns.remove(&client); + host.disconnect(client, graceful); + } + } +} + +fn route(host: &mut ZoneHost, conns: &mut HashMap>) { + for outbound in host.drain_outbound() { + match outbound { + Outbound::Frame { client, frame } => { + let Some(out) = conns.get(&client) else { + continue; + }; + if out.try_send(ConnOut::Frame(frame)).is_err() { + // Slow or gone: drop the connection; the player keeps its grace window. + let out = conns.remove(&client).expect("present"); + let _ = out.try_send(ConnOut::Close); + host.disconnect(client, false); + } + } + Outbound::Close { client } => { + if let Some(out) = conns.remove(&client) { + let _ = out.try_send(ConnOut::Close); + } + } + } + } +} + +async fn upgrade( + ws: WebSocketUpgrade, + Path(zone_id): Path, + State(inner): State>>, +) -> Response +where + Z: Zone, + Z::Config: Send, +{ + let max = inner.config.max_frame_bytes; + ws.max_message_size(max) + .on_upgrade(move |socket| connection(inner, zone_id, socket)) +} + +fn error_frame(code: u32, message: impl Into) -> Vec { + ServerMessage::Error { + code, + message: message.into(), + } + .encode(&()) + .expect("error encodes") +} + +async fn reject(mut socket: WebSocket, code: u32, message: impl Into) { + let _ = socket + .send(Message::Binary(error_frame(code, message).into())) + .await; + let _ = socket.send(Message::Close(None)).await; +} + +/// Order-preserving delay line for [`NetSim`]. +struct DelayLine { + sim: Option, + rng: ZoneRng, + queue: VecDeque<(Instant, T)>, + last: Instant, +} + +impl DelayLine { + fn new(sim: Option, seed: u64) -> Self { + Self { + sim, + rng: ZoneRng::from_seed(seed), + queue: VecDeque::new(), + last: Instant::now(), + } + } + + /// Returns the item immediately when no simulation is configured. + fn push(&mut self, item: T) -> Option { + let Some(sim) = self.sim else { + return Some(item); + }; + let jitter = sim.jitter.mul_f32(self.rng.next_f32()); + let at = (Instant::now() + sim.latency + jitter).max(self.last); + self.last = at; + self.queue.push_back((at, item)); + None + } + + fn next_due(&self) -> Option { + self.queue.front().map(|(at, _)| *at) + } + + fn pop_due(&mut self) -> Option { + if self.queue.front()?.0 <= Instant::now() { + self.queue.pop_front().map(|(_, item)| item) + } else { + None + } + } +} + +async fn sleep_until_opt(at: Option) { + match at { + Some(at) => tokio::time::sleep_until(at).await, + None => std::future::pending().await, + } +} + +struct Bucket { + tokens: f64, + rate: f64, + burst: f64, + last: Instant, + dropped_in_row: u32, + last_warned: Option, +} + +impl Bucket { + fn take(&mut self) -> bool { + let now = Instant::now(); + self.tokens = + (self.tokens + now.duration_since(self.last).as_secs_f64() * self.rate).min(self.burst); + self.last = now; + if self.tokens >= 1.0 { + self.tokens -= 1.0; + self.dropped_in_row = 0; + true + } else { + self.dropped_in_row += 1; + false + } + } +} + +enum Inbound { + Input { + seq: u32, + client_tick: u32, + payload: Vec, + }, + Ping(f64), +} + +async fn connection(inner: Arc>, zone_id: String, mut socket: WebSocket) +where + Z: Zone, + Z::Config: Send, +{ + let cfg = &inner.config; + // 1. Hello. + let first = tokio::time::timeout(cfg.hello_timeout, socket.recv()).await; + let hello = match first { + Ok(Some(Ok(Message::Binary(bytes)))) => match ClientMessage::decode(&bytes) { + Ok(ClientMessage::Hello(hello)) => hello, + _ => return reject(socket, error::BAD_MESSAGE, "expected Hello").await, + }, + Ok(Some(Ok(_))) => return reject(socket, error::BAD_MESSAGE, "binary frames only").await, + _ => return, + }; + if hello.protocol_version != PROTOCOL_VERSION { + return reject( + socket, + error::VERSION_MISMATCH, + format!("protocol {} != {PROTOCOL_VERSION}", hello.protocol_version), + ) + .await; + } + let Some(zone) = zone_sender(&inner, &zone_id) else { + return reject(socket, error::NOT_FOUND, "unknown zone").await; + }; + let (out_tx, mut out_rx) = mpsc::channel(cfg.outbound_queue.max(1)); + let (reply_tx, reply_rx) = oneshot::channel(); + let cmd = if hello.reconnect_token.is_empty() { + let now = unix_now(); + let claims = match cfg.ticket_key.verify(&hello.ticket, now) { + Ok(claims) => claims, + Err(e) => return reject(socket, error::UNAUTHORIZED, format!("{e:?}")).await, + }; + if claims.zone != zone_id { + return reject(socket, error::UNAUTHORIZED, "ticket is for another zone").await; + } + let replay = inner.nonces.lock().expect("nonces").check_and_insert( + &claims.nonce, + claims.expires_at, + now, + ); + if let Err(e) = replay { + return reject(socket, error::UNAUTHORIZED, format!("{e:?}")).await; + } + ZoneCmd::Join { + claims, + capabilities: hello.capabilities, + content_version: hello.content_version, + out: out_tx, + reply: reply_tx, + } + } else { + ZoneCmd::Reconnect { + token: hello.reconnect_token, + capabilities: hello.capabilities, + out: out_tx, + reply: reply_tx, + } + }; + if zone.send(cmd).await.is_err() { + return reject(socket, error::NOT_FOUND, "zone stopped").await; + } + let client = match reply_rx.await { + Ok(Ok(joined)) => joined.client, + Ok(Err(e)) => return reject(socket, e.code, e.message).await, + Err(_) => return reject(socket, error::NOT_FOUND, "zone stopped").await, + }; + + // 2. Session loop. + let seed = u64::from(client.0) ^ unix_now(); + let mut outbound: DelayLine = DelayLine::new(cfg.net_sim, seed); + let mut inbound: DelayLine = DelayLine::new(cfg.net_sim, !seed); + let mut bucket = Bucket { + tokens: cfg.input_burst, + rate: cfg.input_rate, + burst: cfg.input_burst, + last: Instant::now(), + dropped_in_row: 0, + last_warned: None, + }; + let mut graceful = false; + let mut notify_zone = true; + 'session: loop { + // Flush due delayed items. + while let Some(item) = outbound.pop_due() { + match send_out(&mut socket, item).await { + Ok(true) => {} + _ => { + notify_zone = false; + break 'session; + } + } + } + while let Some(item) = inbound.pop_due() { + if !forward_in(&inner, &zone, &mut socket, &mut outbound, client, item).await { + break 'session; + } + } + let next = match (outbound.next_due(), inbound.next_due()) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + tokio::select! { + out = out_rx.recv() => { + let Some(out) = out else { notify_zone = false; break }; + if let Some(out) = outbound.push(out) { + if !send_out(&mut socket, out).await.unwrap_or(false) { + notify_zone = false; + break; + } + } + } + msg = socket.recv() => { + let bytes = match msg { + Some(Ok(Message::Binary(bytes))) => bytes, + Some(Ok(Message::Ping(_) | Message::Pong(_))) => continue, + Some(Ok(Message::Text(_))) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, "binary frames only").into())).await; + break; + } + _ => break, + }; + let item = match ClientMessage::decode(&bytes) { + Ok(ClientMessage::Input { seq, client_tick, payload }) => { + if !bucket.take() { + if bucket.dropped_in_row as f64 > cfg.input_burst { + let kick = ServerMessage::Kick { code: kick::RATE_LIMITED, message: "input flood".into() }; + let _ = socket.send(Message::Binary(kick.encode(&()).expect("kick").into())).await; + break; + } + let now = Instant::now(); + if bucket.last_warned.is_none_or(|t| now.duration_since(t) >= Duration::from_secs(1)) { + bucket.last_warned = Some(now); + let _ = socket.send(Message::Binary(error_frame(error::RATE_LIMITED, "input dropped").into())).await; + } + continue; + } + Inbound::Input { seq, client_tick, payload } + } + Ok(ClientMessage::Ping { client_time }) => Inbound::Ping(client_time), + Ok(ClientMessage::Leave) => { graceful = true; break; } + Ok(ClientMessage::Hello(_)) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, "already joined").into())).await; + continue; + } + Err(e) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, e.to_string()).into())).await; + continue; + } + }; + if let Some(item) = inbound.push(item) { + if !forward_in(&inner, &zone, &mut socket, &mut outbound, client, item).await { + break; + } + } + } + _ = sleep_until_opt(next) => {} + } + } + if notify_zone { + let _ = zone.send(ZoneCmd::Disconnect { client, graceful }).await; + } + let _ = socket.send(Message::Close(None)).await; +} + +/// Ok(false) when the connection should end. +async fn send_out(socket: &mut WebSocket, out: ConnOut) -> Result { + match out { + ConnOut::Frame(frame) => { + socket.send(Message::Binary(frame.into())).await?; + Ok(true) + } + ConnOut::Close => Ok(false), + } +} + +async fn forward_in( + inner: &Arc>, + zone: &mpsc::Sender, + socket: &mut WebSocket, + outbound: &mut DelayLine, + client: ClientId, + item: Inbound, +) -> bool { + match item { + Inbound::Input { + seq, + client_tick, + payload, + } => zone + .send(ZoneCmd::Input { + client, + seq, + client_tick, + payload, + }) + .await + .is_ok(), + Inbound::Ping(client_time) => { + let pong = ServerMessage::Pong { + client_time, + server_time: inner.clock.now().as_secs_f64() * 1000.0, + } + .encode(&()) + .expect("pong encodes"); + match outbound.push(ConnOut::Frame(pong)) { + Some(out) => send_out(socket, out).await.unwrap_or(false), + None => true, + } + } + } +} diff --git a/distributed_game/src/net/ticket.rs b/distributed_game/src/net/ticket.rs new file mode 100644 index 000000000..10ff8da5c --- /dev/null +++ b/distributed_game/src/net/ticket.rs @@ -0,0 +1,222 @@ +//! HMAC-SHA256 signed admission tickets (JWT HS256 compact form). +//! +//! `base64url(header) "." base64url(claims) "." base64url(HMAC-SHA256(key, +//! base64url(header) "." base64url(claims)))`, unpadded base64url. The header +//! must be `{"alg":"HS256",...}`; claims are +//! `{"sub","zone","exp","nonce","role"?}` where `exp` is Unix seconds and +//! `role` is `"player"` (default) or `"observer"`. Any HS256 JWT library can +//! mint them. The principal is taken **only** from a verified `sub`. + +use std::collections::HashMap; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use hmac::{Hmac, Mac}; +use serde_json::{json, Value}; +use sha2::Sha256; + +use crate::protocol::Role; +use crate::zone::TicketClaims; + +type HmacSha256 = Hmac; + +/// Why a ticket was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TicketError { + /// Not three base64url segments of JSON. + Malformed, + /// Header `alg` is not HS256. + UnsupportedAlgorithm, + /// Signature mismatch. + BadSignature, + /// Required claim missing or mistyped. + MissingClaim(&'static str), + /// `exp` in the past. + Expired, + /// Nonce already used. + Replayed, +} + +/// Shared HMAC key. +#[derive(Clone)] +pub struct TicketKey { + secret: Vec, +} + +impl std::fmt::Debug for TicketKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("TicketKey([redacted])") + } +} + +impl TicketKey { + /// Key from secret bytes. + pub fn new(secret: impl Into>) -> Self { + Self { + secret: secret.into(), + } + } + + fn mac(&self) -> HmacSha256 { + HmacSha256::new_from_slice(&self.secret).expect("HMAC accepts any key length") + } + + /// HMAC-SHA256 of `data`. + pub fn hmac(&self, data: &[u8]) -> Vec { + let mut mac = self.mac(); + mac.update(data); + mac.finalize().into_bytes().to_vec() + } + + /// Mint a ticket (dev tooling and tests; production issuers can use any + /// HS256 JWT library). + pub fn sign(&self, claims: &TicketClaims) -> String { + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let body = json!({ + "sub": claims.principal, + "zone": claims.zone, + "exp": claims.expires_at, + "nonce": claims.nonce, + "role": match claims.role { Role::Player => "player", Role::Observer => "observer" }, + }); + let payload = URL_SAFE_NO_PAD.encode(body.to_string()); + let signing_input = format!("{header}.{payload}"); + let sig = URL_SAFE_NO_PAD.encode(self.hmac(signing_input.as_bytes())); + format!("{signing_input}.{sig}") + } + + /// Verify signature and expiry (`now_unix` seconds). Nonce reuse is + /// checked separately with a [`NonceCache`]. + pub fn verify(&self, ticket: &str, now_unix: u64) -> Result { + let mut parts = ticket.split('.'); + let (Some(h), Some(p), Some(s), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(TicketError::Malformed); + }; + let header: Value = decode_json(h)?; + if header.get("alg").and_then(Value::as_str) != Some("HS256") { + return Err(TicketError::UnsupportedAlgorithm); + } + let sig = URL_SAFE_NO_PAD + .decode(s) + .map_err(|_| TicketError::Malformed)?; + let mut mac = self.mac(); + mac.update(h.as_bytes()); + mac.update(b"."); + mac.update(p.as_bytes()); + mac.verify_slice(&sig) + .map_err(|_| TicketError::BadSignature)?; + let claims: Value = decode_json(p)?; + let text = |name: &'static str| { + claims + .get(name) + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string) + .ok_or(TicketError::MissingClaim(name)) + }; + let expires_at = claims + .get("exp") + .and_then(Value::as_u64) + .ok_or(TicketError::MissingClaim("exp"))?; + if expires_at <= now_unix { + return Err(TicketError::Expired); + } + let role = match claims.get("role").and_then(Value::as_str) { + None | Some("player") => Role::Player, + Some("observer") => Role::Observer, + Some(_) => return Err(TicketError::MissingClaim("role")), + }; + Ok(TicketClaims { + principal: text("sub")?, + zone: text("zone")?, + expires_at, + nonce: text("nonce")?, + role, + }) + } +} + +fn decode_json(segment: &str) -> Result { + let bytes = URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| TicketError::Malformed)?; + serde_json::from_slice(&bytes).map_err(|_| TicketError::Malformed) +} + +/// Remembers used nonces until their ticket expires (single-use tickets). +#[derive(Debug, Default)] +pub struct NonceCache { + seen: HashMap, +} + +impl NonceCache { + /// Record `nonce`; `Err(Replayed)` if already used and unexpired. + pub fn check_and_insert( + &mut self, + nonce: &str, + expires_at: u64, + now_unix: u64, + ) -> Result<(), TicketError> { + if self.seen.len() > 1024 { + self.seen.retain(|_, exp| *exp > now_unix); + } + match self.seen.get(nonce) { + Some(exp) if *exp > now_unix => Err(TicketError::Replayed), + _ => { + self.seen.insert(nonce.to_string(), expires_at); + Ok(()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn claims() -> TicketClaims { + TicketClaims { + principal: "alice".into(), + zone: "z1".into(), + expires_at: 2_000, + nonce: "n1".into(), + role: Role::Player, + } + } + + #[test] + fn signs_and_verifies() { + let key = TicketKey::new("secret"); + let ticket = key.sign(&claims()); + assert_eq!(key.verify(&ticket, 1_000).unwrap(), claims()); + assert_eq!(key.verify(&ticket, 2_000), Err(TicketError::Expired)); + assert_eq!( + TicketKey::new("other").verify(&ticket, 1_000), + Err(TicketError::BadSignature) + ); + } + + #[test] + fn tampered_principal_is_rejected() { + let key = TicketKey::new("secret"); + let ticket = key.sign(&claims()); + let parts: Vec<_> = ticket.split('.').collect(); + let forged = + URL_SAFE_NO_PAD.encode(r#"{"sub":"mallory","zone":"z1","exp":2000,"nonce":"n1"}"#); + let forged = format!("{}.{}.{}", parts[0], forged, parts[2]); + assert_eq!(key.verify(&forged, 1_000), Err(TicketError::BadSignature)); + } + + #[test] + fn nonce_is_single_use() { + let mut cache = NonceCache::default(); + assert!(cache.check_and_insert("n", 10, 1).is_ok()); + assert_eq!( + cache.check_and_insert("n", 10, 2), + Err(TicketError::Replayed) + ); + assert!(cache.check_and_insert("n", 20, 11).is_ok()); + } +} diff --git a/distributed_game/src/protocol/mod.rs b/distributed_game/src/protocol/mod.rs index b1ac0eded..080f41e30 100644 --- a/distributed_game/src/protocol/mod.rs +++ b/distributed_game/src/protocol/mod.rs @@ -2,7 +2,7 @@ //! //! One message per WebSocket binary frame; the first byte is the message //! type. [`wire`] holds the primitives, [`messages`] the message codecs and -//! the reference [`ClientMirror`](messages::ClientMirror). +//! the reference [`ClientMirror`]. pub mod messages; pub mod wire; diff --git a/distributed_game/src/schema.rs b/distributed_game/src/schema.rs index 888135e2a..24c774bfb 100644 --- a/distributed_game/src/schema.rs +++ b/distributed_game/src/schema.rs @@ -7,7 +7,7 @@ //! //! Quantization is specified bit-exactly in `PROTOCOL.md` §4 and computed in //! `f64` so a JavaScript client (whose numbers are `f64`) reproduces the same -//! integers and decoded `f32` values. Use [`FieldType::quantize`] / +//! integers and decoded `f32` values. Use [`FieldType::quantize_linear`] / //! [`FieldType::canonicalize`] on the server when prediction must match what //! clients will see. diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index 73519af34..0a70726e1 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -2,7 +2,7 @@ //! //! A zone is one authoritative simulation instance (a dungeon floor, a match, //! a town shard). The [`ZoneHost`](crate::ZoneHost) owns it and calls these -//! hooks; every hook gets a [`Ctx`](crate::Ctx) for timers, RNG, inputs, +//! hooks; every hook gets a [`Ctx`] for timers, RNG, inputs, //! facts, events and views. Hooks are synchronous and must not block: durable //! work goes through facts, never through awaited storage. //! diff --git a/distributed_game/tests/fixtures/messages.json b/distributed_game/tests/fixtures/messages.json new file mode 100644 index 000000000..323b09e16 --- /dev/null +++ b/distributed_game/tests/fixtures/messages.json @@ -0,0 +1,511 @@ +{ + "messages": [ + { + "decoded": { + "capabilities": 5, + "content_version": "c1", + "protocol_version": 1, + "reconnect_token": "", + "ticket": "t.k.n", + "type": "Hello" + }, + "direction": "client_to_server", + "hex": "01010263310505742e6b2e6e00", + "name": "hello" + }, + { + "decoded": { + "capabilities": 0, + "content_version": "c1", + "protocol_version": 1, + "reconnect_token": "abcd", + "ticket": "", + "type": "Hello" + }, + "direction": "client_to_server", + "hex": "010102633100000461626364", + "name": "hello_reconnect" + }, + { + "decoded": { + "client_tick": 1000, + "payload": "01ff", + "seq": 300, + "type": "Input" + }, + "direction": "client_to_server", + "hex": "02ac02e8070201ff", + "name": "input" + }, + { + "decoded": { + "client_time": 1234.5, + "type": "Ping" + }, + "direction": "client_to_server", + "hex": "0300000000004a9340", + "name": "ping" + }, + { + "decoded": { + "type": "Leave" + }, + "direction": "client_to_server", + "hex": "04", + "name": "leave" + }, + { + "decoded": { + "content_version": "c1", + "patch_rate": 20, + "reconnect_token": "rt", + "role": "player", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ], + "server_tick": 42, + "server_time": 1000.25, + "session_id": "s1", + "tick_rate": 30, + "type": "Welcome", + "zone_id": "z1" + }, + "direction": "server_to_client", + "hex": "80027331027a31001e142a0000000000428f400272740263310201046865726f0a05616c69766500056c6576656c010268700204676f6c640302647a04057370656564050178060000c8c20000c8421003796177070a046e616d6508037461670902036f72620101780600000000000080420c", + "name": "welcome" + }, + { + "decoded": { + "ack_seq": 0, + "creates": [], + "removes": [], + "server_tick": 43, + "type": "Delta", + "updates": [] + }, + "direction": "server_to_client", + "hex": "812b00000000", + "known_entities": [ + { + "id": 5, + "kind": 1 + }, + { + "id": 6, + "kind": 2 + } + ], + "name": "delta_empty", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ] + }, + { + "decoded": { + "ack_seq": 17, + "creates": [ + { + "fields": [ + { + "bool": true + }, + { + "u": 7 + }, + { + "u": 300 + }, + { + "u": 70000 + }, + { + "i": -2 + }, + { + "bits": "3fc00000", + "f32": 1.5 + }, + { + "bits": "c2c80000", + "f32": -100.0 + }, + { + "bits": "00000000", + "f32": 0.0 + }, + { + "str": "Ana" + }, + { + "bytes": "dead" + } + ], + "id": 300, + "kind": 1 + }, + { + "fields": [ + { + "bits": "42000801", + "f32": 32.007816314697266 + } + ], + "id": 301, + "kind": 2 + } + ], + "removes": [ + 9, + 130 + ], + "server_tick": 200, + "type": "Delta", + "updates": [ + { + "fields": [ + { + "u": 299 + }, + { + "bits": "3ac800c8", + "f32": 0.0015259021893143654 + } + ], + "id": 5, + "mask": 68 + }, + { + "fields": [ + { + "bits": "42800000", + "f32": 64.0 + } + ], + "id": 6, + "mask": 1 + }, + { + "fields": [ + { + "bits": "00000000", + "f32": 0.0 + } + ], + "id": 301, + "mask": 1 + } + ] + }, + "direction": "server_to_client", + "hex": "81c801110209820102ac02010107ac02f0a204030000c03f000003416e6102deadad02028010030544ab028080020601ff1fad020100", + "known_entities": [ + { + "id": 5, + "kind": 1 + }, + { + "id": 6, + "kind": 2 + } + ], + "name": "delta", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ] + }, + { + "decoded": { + "payload": "7870", + "type": "Event", + "type_id": 3 + }, + "direction": "server_to_client", + "hex": "8203027870", + "name": "event" + }, + { + "decoded": { + "client_time": 1234.5, + "server_time": 99.0, + "type": "Pong" + }, + "direction": "server_to_client", + "hex": "8300000000004a93400000000000c05840", + "name": "pong" + }, + { + "decoded": { + "notes": "brb", + "reason": "content_update", + "type": "Freeze", + "version": "c2" + }, + "direction": "server_to_client", + "hex": "840e636f6e74656e745f75706461746502633203627262", + "name": "freeze" + }, + { + "decoded": { + "notes": "", + "reason": "content_update", + "type": "Resume", + "version": "c2" + }, + "direction": "server_to_client", + "hex": "850e636f6e74656e745f75706461746502633200", + "name": "resume" + }, + { + "decoded": { + "target_zone": "z2", + "transfer_ticket": "tt", + "type": "Handoff" + }, + "direction": "server_to_client", + "hex": "86027a32027474", + "name": "handoff" + }, + { + "decoded": { + "code": 3, + "message": "bye", + "type": "Kick" + }, + "direction": "server_to_client", + "hex": "870303627965", + "name": "kick" + }, + { + "decoded": { + "code": 2, + "message": "Expired", + "type": "Error" + }, + "direction": "server_to_client", + "hex": "88020745787069726564", + "name": "error" + } + ] +} diff --git a/distributed_game/tests/fixtures/primitives.json b/distributed_game/tests/fixtures/primitives.json new file mode 100644 index 000000000..b6e5088a0 --- /dev/null +++ b/distributed_game/tests/fixtures/primitives.json @@ -0,0 +1,138 @@ +{ + "cases": [ + { + "hex": "00", + "kind": "varuint", + "value": 0 + }, + { + "hex": "01", + "kind": "varuint", + "value": 1 + }, + { + "hex": "7f", + "kind": "varuint", + "value": 127 + }, + { + "hex": "8001", + "kind": "varuint", + "value": 128 + }, + { + "hex": "ac02", + "kind": "varuint", + "value": 300 + }, + { + "hex": "808001", + "kind": "varuint", + "value": 16384 + }, + { + "hex": "ffffffff0f", + "kind": "varuint", + "value": 4294967295 + }, + { + "hex": "00", + "kind": "varint", + "value": 0 + }, + { + "hex": "01", + "kind": "varint", + "value": -1 + }, + { + "hex": "02", + "kind": "varint", + "value": 1 + }, + { + "hex": "7f", + "kind": "varint", + "value": -64 + }, + { + "hex": "8001", + "kind": "varint", + "value": 64 + }, + { + "hex": "ffffffff0f", + "kind": "varint", + "value": -2147483648 + }, + { + "hex": "feffffff0f", + "kind": "varint", + "value": 2147483647 + }, + { + "hex": "0000c03f", + "kind": "f32", + "value": { + "bits": "3fc00000", + "f32": 1.5 + } + }, + { + "hex": "00000080", + "kind": "f32", + "value": { + "bits": "80000000", + "f32": -0.0 + } + }, + { + "hex": "db0f4940", + "kind": "f32", + "value": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + } + }, + { + "hex": "00000000004a9340", + "kind": "f64", + "value": 1234.5 + }, + { + "hex": "9a9999999999b93f", + "kind": "f64", + "value": 0.1 + }, + { + "hex": "00", + "kind": "string", + "value": "" + }, + { + "hex": "00", + "kind": "short_string", + "value": "" + }, + { + "hex": "026869", + "kind": "string", + "value": "hi" + }, + { + "hex": "026869", + "kind": "short_string", + "value": "hi" + }, + { + "hex": "0668c3a9726f73", + "kind": "string", + "value": "héros" + }, + { + "hex": "0668c3a9726f73", + "kind": "short_string", + "value": "héros" + } + ] +} diff --git a/distributed_game/tests/fixtures/quantization.json b/distributed_game/tests/fixtures/quantization.json new file mode 100644 index 000000000..80ca1f3cc --- /dev/null +++ b/distributed_game/tests/fixtures/quantization.json @@ -0,0 +1,574 @@ +{ + "cases": [ + { + "decoded": { + "bits": "c2c80000", + "f32": -100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "c2c80000", + "q": 0 + }, + { + "decoded": { + "bits": "3ac800c8", + "f32": 0.0015259021893143654 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "808002", + "input_bits": "00000000", + "q": 32768 + }, + { + "decoded": { + "bits": "420532f5", + "f32": 33.29976272583008 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "9fd502", + "input_bits": "42053333", + "q": 43679 + }, + { + "decoded": { + "bits": "42c80000", + "f32": 100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "ffff03", + "input_bits": "42c7ff7d", + "q": 65535 + }, + { + "decoded": { + "bits": "42c80000", + "f32": 100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "ffff03", + "input_bits": "437a0000", + "q": 65535 + }, + { + "decoded": { + "bits": "c2c80000", + "f32": -100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "ce6e6b28", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3ea80a81", + "f32": 0.3282051384449005 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "15", + "input_bits": "3eaaaaab", + "q": 21 + }, + { + "decoded": { + "bits": "41ffefff", + "f32": 31.992185592651367 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ff0f", + "input_bits": "41ffeb85", + "q": 2047 + }, + { + "decoded": { + "bits": "42800000", + "f32": 64.0 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ff1f", + "input_bits": "42800000", + "q": 4095 + }, + { + "decoded": { + "bits": "bf800000", + "f32": -1.0 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "bf800000", + "q": 0 + }, + { + "decoded": { + "bits": "3b808081", + "f32": 0.003921568859368563 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "8001", + "input_bits": "00000000", + "q": 128 + }, + { + "decoded": { + "bits": "3efefeff", + "f32": 0.49803921580314636 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "bf01", + "input_bits": "3f000000", + "q": 191 + }, + { + "decoded": { + "bits": "bf800000", + "f32": -1.0 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "7fc00000", + "q": 0 + }, + { + "decoded": { + "bits": "3dfcd6ea", + "f32": 0.12345679104328156 + }, + "field": { + "bits": 32, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "c0baebfc01", + "input_bits": "3dfcd6ea", + "q": 530242880 + }, + { + "decoded": { + "bits": "3f800000", + "f32": 1.0 + }, + "field": { + "bits": 32, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ffffffff0f", + "input_bits": "3f800000", + "q": 4294967295 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f80ce28", + "f32": 1.006291389465332 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "29", + "input_bits": "3f800000", + "q": 41 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "8001", + "input_bits": "40490fdb", + "q": 128 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "c001", + "input_bits": "bfc90fdb", + "q": 192 + }, + { + "decoded": { + "bits": "3f36365e", + "f32": 0.7117670774459839 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "1d", + "input_bits": "40e00000", + "q": 29 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f800518", + "f32": 1.0001554489135742 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "a301", + "input_bits": "3f800000", + "q": 163 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "8004", + "input_bits": "40490fdb", + "q": 512 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "8006", + "input_bits": "bfc90fdb", + "q": 768 + }, + { + "decoded": { + "bits": "3f37c87e", + "f32": 0.7179030179977417 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "75", + "input_bits": "40e00000", + "q": 117 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f7ffd9f", + "f32": 0.9999637007713318 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "be51", + "input_bits": "3f800000", + "q": 10430 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "808002", + "input_bits": "40490fdb", + "q": 32768 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "808003", + "input_bits": "bfc90fdb", + "q": 49152 + }, + { + "decoded": { + "bits": "3f378360", + "f32": 0.7168483734130859 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "b53a", + "input_bits": "40e00000", + "q": 7477 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + } + ] +} diff --git a/distributed_game/tests/golden/main.rs b/distributed_game/tests/golden/main.rs new file mode 100644 index 000000000..ee7a8767d --- /dev/null +++ b/distributed_game/tests/golden/main.rs @@ -0,0 +1,521 @@ +//! Golden byte fixtures for independent (e.g. JavaScript) implementations. +//! +//! Writes `tests/fixtures/*.json` when missing or when `UPDATE_GOLDEN=1`; +//! otherwise asserts the encoder still produces exactly the committed bytes +//! and that every fixture decodes back to its structure. JSON conventions are +//! documented in `PROTOCOL.md` §9. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use distributed_game::protocol::{ + error, kick, ClientMessage, Delta, EntityCreate, EntityUpdate, Hello, Notice, Reader, + ServerMessage, Welcome, Writer, +}; +use distributed_game::{EntitySchema, FieldType, FieldValue, KindDef, Role, PROTOCOL_VERSION}; +use serde_json::{json, Value}; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() +} + +fn f32j(v: f32) -> Value { + json!({ "f32": f64::from(v), "bits": format!("{:08x}", v.to_bits()) }) +} + +fn field_type_json(ty: &FieldType) -> Value { + match ty { + FieldType::Bool => json!({ "type": "bool" }), + FieldType::U8 => json!({ "type": "u8" }), + FieldType::U16 => json!({ "type": "u16" }), + FieldType::U32 => json!({ "type": "u32" }), + FieldType::I32 => json!({ "type": "i32" }), + FieldType::F32 => json!({ "type": "f32" }), + FieldType::QuantF32 { min, max, bits } => { + json!({ "type": "quant_f32", "min": f32j(*min), "max": f32j(*max), "bits": bits }) + } + FieldType::Angle { bits } => json!({ "type": "angle", "bits": bits }), + FieldType::ShortStr => json!({ "type": "short_str" }), + FieldType::Bytes => json!({ "type": "bytes" }), + } +} + +fn schema_json(schema: &EntitySchema) -> Value { + Value::Array( + schema + .kinds() + .iter() + .map(|k| { + json!({ + "id": k.id, + "name": k.name, + "fields": k.fields.iter().map(|f| { + let mut v = field_type_json(&f.ty); + v["name"] = json!(f.name); + v + }).collect::>(), + }) + }) + .collect(), + ) +} + +fn value_json(v: &FieldValue) -> Value { + match v { + FieldValue::Bool(b) => json!({ "bool": b }), + FieldValue::U(u) => json!({ "u": u }), + FieldValue::I(i) => json!({ "i": i }), + FieldValue::F(f) => f32j(*f), + FieldValue::Str(s) => json!({ "str": s }), + FieldValue::Bytes(b) => json!({ "bytes": hex(b) }), + } +} + +fn client_json(m: &ClientMessage) -> Value { + match m { + ClientMessage::Hello(h) => json!({ + "type": "Hello", + "protocol_version": h.protocol_version, + "content_version": h.content_version, + "capabilities": h.capabilities, + "ticket": h.ticket, + "reconnect_token": h.reconnect_token, + }), + ClientMessage::Input { + seq, + client_tick, + payload, + } => { + json!({ "type": "Input", "seq": seq, "client_tick": client_tick, "payload": hex(payload) }) + } + ClientMessage::Ping { client_time } => { + json!({ "type": "Ping", "client_time": client_time }) + } + ClientMessage::Leave => json!({ "type": "Leave" }), + } +} + +fn server_json(m: &ServerMessage) -> Value { + match m { + ServerMessage::Welcome(w) => json!({ + "type": "Welcome", + "session_id": w.session_id, + "zone_id": w.zone_id, + "role": match w.role { Role::Player => "player", Role::Observer => "observer" }, + "tick_rate": w.tick_rate, + "patch_rate": w.patch_rate, + "server_tick": w.server_tick, + "server_time": w.server_time, + "reconnect_token": w.reconnect_token, + "content_version": w.content_version, + "schema": schema_json(&w.schema), + }), + ServerMessage::Delta(d) => json!({ + "type": "Delta", + "server_tick": d.server_tick, + "ack_seq": d.ack_seq, + "removes": d.removes, + "creates": d.creates.iter().map(|c| json!({ + "id": c.id, "kind": c.kind, + "fields": c.fields.iter().map(value_json).collect::>(), + })).collect::>(), + "updates": d.updates.iter().map(|u| json!({ + "id": u.id, "mask": u.mask, + "fields": u.fields.iter().map(value_json).collect::>(), + })).collect::>(), + }), + ServerMessage::Event { type_id, payload } => { + json!({ "type": "Event", "type_id": type_id, "payload": hex(payload) }) + } + ServerMessage::Pong { + client_time, + server_time, + } => json!({ "type": "Pong", "client_time": client_time, "server_time": server_time }), + ServerMessage::Freeze(n) | ServerMessage::Resume(n) => json!({ + "type": if matches!(m, ServerMessage::Freeze(_)) { "Freeze" } else { "Resume" }, + "reason": n.reason, "version": n.version, "notes": n.notes, + }), + ServerMessage::Handoff { + target_zone, + transfer_ticket, + } => { + json!({ "type": "Handoff", "target_zone": target_zone, "transfer_ticket": transfer_ticket }) + } + ServerMessage::Kick { code, message } => { + json!({ "type": "Kick", "code": code, "message": message }) + } + ServerMessage::Error { code, message } => { + json!({ "type": "Error", "code": code, "message": message }) + } + } +} + +fn fixture_schema() -> EntitySchema { + EntitySchema::new() + .kind( + KindDef::new(1, "hero") + .field("alive", FieldType::Bool) + .field("level", FieldType::U8) + .field("hp", FieldType::U16) + .field("gold", FieldType::U32) + .field("dz", FieldType::I32) + .field("speed", FieldType::F32) + .field( + "x", + FieldType::QuantF32 { + min: -100.0, + max: 100.0, + bits: 16, + }, + ) + .field("yaw", FieldType::Angle { bits: 10 }) + .field("name", FieldType::ShortStr) + .field("tag", FieldType::Bytes), + ) + .kind(KindDef::new(2, "orb").field( + "x", + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 12, + }, + )) +} + +fn fixtures_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +fn check_or_write(name: &str, value: Value) { + let path = fixtures_dir().join(name); + let text = serde_json::to_string_pretty(&value).unwrap() + "\n"; + if std::env::var("UPDATE_GOLDEN").is_ok() || !path.exists() { + std::fs::create_dir_all(fixtures_dir()).unwrap(); + std::fs::write(&path, &text).unwrap(); + return; + } + let committed = std::fs::read_to_string(&path).unwrap(); + assert_eq!( + committed, text, + "{name} drifted; the wire format changed (UPDATE_GOLDEN=1 to accept)" + ); +} + +#[test] +fn primitives() { + let mut cases = Vec::new(); + for v in [0u32, 1, 127, 128, 300, 16_384, u32::MAX] { + let mut w = Writer::new(); + w.varuint(v); + cases.push(json!({ "kind": "varuint", "value": v, "hex": hex(w.as_bytes()) })); + } + for v in [0i32, -1, 1, -64, 64, i32::MIN, i32::MAX] { + let mut w = Writer::new(); + w.varint(v); + assert_eq!(Reader::new(w.as_bytes()).varint().unwrap(), v); + cases.push(json!({ "kind": "varint", "value": v, "hex": hex(w.as_bytes()) })); + } + for v in [1.5f32, -0.0, std::f32::consts::PI] { + let mut w = Writer::new(); + w.f32(v); + cases.push(json!({ "kind": "f32", "value": f32j(v), "hex": hex(w.as_bytes()) })); + } + for v in [1234.5f64, 0.1] { + let mut w = Writer::new(); + w.f64(v); + cases.push(json!({ "kind": "f64", "value": v, "hex": hex(w.as_bytes()) })); + } + for s in ["", "hi", "héros"] { + let mut w = Writer::new(); + w.string(s); + cases.push(json!({ "kind": "string", "value": s, "hex": hex(w.as_bytes()) })); + let mut w = Writer::new(); + w.short_string(s); + cases.push(json!({ "kind": "short_string", "value": s, "hex": hex(w.as_bytes()) })); + } + check_or_write("primitives.json", json!({ "cases": cases })); +} + +#[test] +fn quantization() { + let mut cases = Vec::new(); + let linear = [ + ( + -100.0f32, + 100.0f32, + 16u8, + vec![-100.0f32, 0.0, 33.3, 99.999, 250.0, -1e9], + ), + (0.0, 64.0, 12, vec![0.0, 1.0 / 3.0, 31.99, 64.0]), + (-1.0, 1.0, 8, vec![-1.0, 0.0, 0.5, f32::NAN]), + (0.0, 1.0, 32, vec![0.123_456_79, 1.0]), + ]; + for (min, max, bits, values) in linear { + let ty = FieldType::QuantF32 { min, max, bits }; + for v in values { + let mut w = Writer::new(); + ty.encode(&mut w, &FieldValue::F(v)); + let q = Reader::new(w.as_bytes()).varuint().unwrap(); + let FieldValue::F(back) = ty.canonicalize(&FieldValue::F(v)) else { + panic!() + }; + cases.push(json!({ + "field": field_type_json(&ty), + "input_bits": format!("{:08x}", v.to_bits()), + "q": q, + "hex": hex(w.as_bytes()), + "decoded": f32j(back), + })); + } + } + for bits in [8u8, 10, 16] { + let ty = FieldType::Angle { bits }; + for v in [ + 0.0f32, + 1.0, + std::f32::consts::PI, + -std::f32::consts::FRAC_PI_2, + 7.0, + -0.000_001, + ] { + let mut w = Writer::new(); + ty.encode(&mut w, &FieldValue::F(v)); + let q = Reader::new(w.as_bytes()).varuint().unwrap(); + let FieldValue::F(back) = ty.canonicalize(&FieldValue::F(v)) else { + panic!() + }; + cases.push(json!({ + "field": field_type_json(&ty), + "input_bits": format!("{:08x}", v.to_bits()), + "q": q, + "hex": hex(w.as_bytes()), + "decoded": f32j(back), + })); + } + } + check_or_write("quantization.json", json!({ "cases": cases })); +} + +#[test] +fn messages() { + let schema = fixture_schema(); + let mut out = Vec::new(); + + let client = vec![ + ( + "hello", + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: "c1".into(), + capabilities: 5, + ticket: "t.k.n".into(), + reconnect_token: String::new(), + }), + ), + ( + "hello_reconnect", + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: "c1".into(), + capabilities: 0, + ticket: String::new(), + reconnect_token: "abcd".into(), + }), + ), + ( + "input", + ClientMessage::Input { + seq: 300, + client_tick: 1_000, + payload: vec![0x01, 0xff], + }, + ), + ( + "ping", + ClientMessage::Ping { + client_time: 1234.5, + }, + ), + ("leave", ClientMessage::Leave), + ]; + for (name, msg) in client { + let bytes = msg.encode(); + assert_eq!(ClientMessage::decode(&bytes).unwrap(), msg); + out.push(json!({ + "name": name, "direction": "client_to_server", + "hex": hex(&bytes), "decoded": client_json(&msg), + })); + } + + let known: BTreeMap = [(5u32, 1u16), (6, 2)].into_iter().collect(); + let ctx = (schema.clone(), known.clone()); + let hero_fields = vec![ + FieldValue::Bool(true), + FieldValue::U(7), + FieldValue::U(300), + FieldValue::U(70_000), + FieldValue::I(-2), + FieldValue::F(1.5), + FieldValue::F(-100.0), + FieldValue::F(0.0), + FieldValue::Str("Ana".into()), + FieldValue::Bytes(vec![0xde, 0xad]), + ]; + let server = vec![ + ( + "welcome", + ServerMessage::Welcome(Welcome { + session_id: "s1".into(), + zone_id: "z1".into(), + role: Role::Player, + tick_rate: 30, + patch_rate: 20, + server_tick: 42, + server_time: 1000.25, + reconnect_token: "rt".into(), + content_version: "c1".into(), + schema: schema.clone(), + }), + ), + ( + "delta_empty", + ServerMessage::Delta(Delta { + server_tick: 43, + ack_seq: 0, + ..Delta::default() + }), + ), + ( + "delta", + ServerMessage::Delta(Delta { + server_tick: 200, + ack_seq: 17, + removes: vec![9, 130], + creates: vec![ + EntityCreate { + id: 300, + kind: 1, + fields: hero_fields, + }, + EntityCreate { + id: 301, + kind: 2, + fields: vec![FieldValue::F(32.0)], + }, + ], + updates: vec![ + EntityUpdate { + id: 5, + mask: 0b0100_0100, + fields: vec![FieldValue::U(299), FieldValue::F(0.0)], + }, + EntityUpdate { + id: 6, + mask: 0b1, + fields: vec![FieldValue::F(64.0)], + }, + EntityUpdate { + id: 301, + mask: 0b1, + fields: vec![FieldValue::F(0.0)], + }, + ], + }), + ), + ( + "event", + ServerMessage::Event { + type_id: 3, + payload: b"xp".to_vec(), + }, + ), + ( + "pong", + ServerMessage::Pong { + client_time: 1234.5, + server_time: 99.0, + }, + ), + ( + "freeze", + ServerMessage::Freeze(Notice { + reason: "content_update".into(), + version: "c2".into(), + notes: "brb".into(), + }), + ), + ( + "resume", + ServerMessage::Resume(Notice { + reason: "content_update".into(), + version: "c2".into(), + notes: String::new(), + }), + ), + ( + "handoff", + ServerMessage::Handoff { + target_zone: "z2".into(), + transfer_ticket: "tt".into(), + }, + ), + ( + "kick", + ServerMessage::Kick { + code: kick::SHUTDOWN, + message: "bye".into(), + }, + ), + ( + "error", + ServerMessage::Error { + code: error::UNAUTHORIZED, + message: "Expired".into(), + }, + ), + ]; + for (name, msg) in server { + let bytes = msg.encode(&ctx).unwrap(); + let decoded = ServerMessage::decode(&bytes, &ctx).unwrap(); + // Quantized values decode to their canonical form; compare JSON of + // the decoded message (what a client will see). + let mut entry = json!({ + "name": name, "direction": "server_to_client", + "hex": hex(&bytes), "decoded": server_json(&decoded), + }); + if matches!(msg, ServerMessage::Delta(_)) { + entry["known_entities"] = json!(known + .iter() + .map(|(id, kind)| json!({ "id": id, "kind": kind })) + .collect::>()); + entry["schema"] = schema_json(&schema); + } + // Re-encoding the decoded form is byte-identical. + assert_eq!(decoded.encode(&ctx).unwrap(), bytes, "{name}"); + out.push(entry); + } + check_or_write("messages.json", json!({ "messages": out })); + + // Fixture hex decodes back (guards hand edits). + let text = std::fs::read_to_string(fixtures_dir().join("messages.json")).unwrap(); + let parsed: Value = serde_json::from_str(&text).unwrap(); + for m in parsed["messages"].as_array().unwrap() { + let bytes = unhex(m["hex"].as_str().unwrap()); + if m["direction"] == "client_to_server" { + assert_eq!( + client_json(&ClientMessage::decode(&bytes).unwrap()), + m["decoded"] + ); + } else { + let msg = ServerMessage::decode(&bytes, &ctx).unwrap(); + assert_eq!(server_json(&msg), m["decoded"]); + } + } +} diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs new file mode 100644 index 000000000..26873f33e --- /dev/null +++ b/distributed_game/tests/net_e2e/main.rs @@ -0,0 +1,296 @@ +//! End-to-end: a real WebSocket client joins through signed-ticket +//! admission, sends inputs, receives deltas, reconnects and is shut down. + +#[path = "../zone_runtime/arena.rs"] +mod arena; + +use std::time::Duration; + +use arena::{Arena, ArenaConfig, AVATAR}; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; +use distributed_game::protocol::{error, kick, Hello}; +use distributed_game::{ + ClientMessage, ClientMirror, FieldValue, MemoryFactSink, RetryPolicy, Role, ServerMessage, + TicketClaims, PROTOCOL_VERSION, +}; +use futures_util::{SinkExt, StreamExt}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +type Ws = WebSocketStream>; + +const SECRET: &str = "dev-secret"; + +fn ticket(principal: &str, zone: &str, nonce: &str, role: Role) -> String { + TicketKey::new(SECRET).sign(&TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role, + }) +} + +async fn start( + net_sim: Option, +) -> (String, GameServer, tokio::task::JoinHandle<()>) { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + config.net_sim = net_sim; + let server = GameServer::::new(config, |zone_id| { + zone_id.starts_with('z').then(ArenaConfig::default) + }) + .with_fact_sink(MemoryFactSink::new(), 64, RetryPolicy::default()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + (format!("ws://{addr}"), server, handle) +} + +async fn send(ws: &mut Ws, msg: ClientMessage) { + ws.send(Message::Binary(msg.encode().into())).await.unwrap(); +} + +async fn hello(ws: &mut Ws, ticket: String, reconnect_token: String) { + send( + ws, + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: String::new(), + capabilities: 0, + ticket, + reconnect_token, + }), + ) + .await; +} + +/// Next decoded server message (skipping non-binary frames). +async fn next(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + let frame = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("server message within 5s")?; + match frame { + Ok(Message::Binary(bytes)) => return Some(mirror.apply(&bytes).unwrap()), + Ok(Message::Close(_)) | Err(_) => return None, + Ok(_) => continue, + } + } +} + +async fn connect(url: &str, zone: &str) -> Ws { + connect_async(format!("{url}/zones/{zone}")) + .await + .unwrap() + .0 +} + +async fn expect_error(url: &str, zone: &str, ticket: String, code: u32) { + let mut ws = connect(url, zone).await; + hello(&mut ws, ticket, String::new()).await; + let mut mirror = ClientMirror::new(); + match next(&mut ws, &mut mirror).await { + Some(ServerMessage::Error { code: got, .. }) => assert_eq!(got, code), + other => panic!("expected error {code}, got {other:?}"), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn client_joins_sends_inputs_receives_deltas_and_reconnects() { + let (url, server, handle) = start(None).await; + + let mut ws = connect(&url, "z1").await; + hello( + &mut ws, + ticket("alice", "z1", "n1", Role::Player), + String::new(), + ) + .await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome") + }; + assert_eq!(welcome.zone_id, "z1"); + assert_eq!(welcome.role, Role::Player); + assert_eq!(welcome.tick_rate, 30); + assert_eq!(welcome.schema.kinds().len(), 2); + + // Wait for the first delta carrying our avatar. + while mirror.entities.is_empty() { + next(&mut ws, &mut mirror).await.unwrap(); + } + let (&avatar_id, avatar) = mirror.entities.iter().next().unwrap(); + assert_eq!(avatar.kind, AVATAR); + let FieldValue::F(start_x) = avatar.fields[0] else { + panic!() + }; + + for seq in 1..=10 { + send( + &mut ws, + ClientMessage::Input { + seq, + client_tick: seq, + payload: vec![1, 0], + }, + ) + .await; + } + send(&mut ws, ClientMessage::Ping { client_time: 123.5 }).await; + let mut pong = None; + while mirror.ack_seq < 10 || pong.is_none() { + match next(&mut ws, &mut mirror).await.unwrap() { + ServerMessage::Pong { + client_time, + server_time, + } => pong = Some((client_time, server_time)), + ServerMessage::Delta(_) | ServerMessage::Event { .. } => {} + other => panic!("unexpected {other:?}"), + } + } + assert_eq!(pong.unwrap().0, 123.5); + // Let the next patch carry the moved position. + for _ in 0..3 { + next(&mut ws, &mut mirror).await.unwrap(); + } + let FieldValue::F(x) = mirror.entities[&avatar_id].fields[0] else { + panic!() + }; + assert!( + x > start_x, + "server-side movement replicated ({start_x} -> {x})" + ); + + // Text frames are refused. + ws.send(Message::Text("hi".into())).await.unwrap(); + match next(&mut ws, &mut mirror).await { + Some(ServerMessage::Error { code, .. }) => assert_eq!(code, error::BAD_MESSAGE), + other => panic!("expected BAD_MESSAGE, got {other:?}"), + } + drop(ws); // abrupt drop: player stays for the grace window + + // Reconnect with the token from Welcome. + let mut ws = connect(&url, "z1").await; + hello(&mut ws, String::new(), welcome.reconnect_token.clone()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(again)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome on reconnect") + }; + assert_eq!(again.session_id, welcome.session_id); + assert_ne!(again.reconnect_token, welcome.reconnect_token); + while !mirror.entities.contains_key(&avatar_id) { + next(&mut ws, &mut mirror).await.unwrap(); + } + + // Admission failures. + expect_error( + &url, + "z1", + ticket("bob", "z1", "n1", Role::Player), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + ticket("bob", "z2", "n2", Role::Player), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "nope", + ticket("bob", "nope", "n3", Role::Player), + error::NOT_FOUND, + ) + .await; + let forged = TicketKey::new("wrong").sign(&TicketClaims { + principal: "bob".into(), + zone: "z1".into(), + expires_at: 4_000_000_000, + nonce: "n4".into(), + role: Role::Player, + }); + expect_error(&url, "z1", forged, error::UNAUTHORIZED).await; + + // Observers see the world without a player. + let mut obs = connect(&url, "z1").await; + hello( + &mut obs, + ticket("watcher", "z1", "n5", Role::Observer), + String::new(), + ) + .await; + let mut obs_mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(w)) = next(&mut obs, &mut obs_mirror).await else { + panic!() + }; + assert_eq!(w.role, Role::Observer); + while obs_mirror.entities.is_empty() { + next(&mut obs, &mut obs_mirror).await.unwrap(); + } + + // Graceful shutdown kicks everyone. + server.shutdown(); + let mut kicked = false; + while let Some(msg) = next(&mut ws, &mut mirror).await { + if let ServerMessage::Kick { code, .. } = msg { + assert_eq!(code, kick::SHUTDOWN); + kicked = true; + } + } + assert!(kicked); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn latency_simulation_delays_but_preserves_order() { + let sim = NetSim { + latency: Duration::from_millis(40), + jitter: Duration::from_millis(20), + }; + let (url, server, handle) = start(Some(sim)).await; + let mut ws = connect(&url, "z9").await; + hello( + &mut ws, + ticket("carol", "z9", "m1", Role::Player), + String::new(), + ) + .await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next(&mut ws, &mut mirror).await, + Some(ServerMessage::Welcome(_)) + )); + let start = std::time::Instant::now(); + send(&mut ws, ClientMessage::Ping { client_time: 1.0 }).await; + let mut last_tick = 0; + loop { + match next(&mut ws, &mut mirror).await.unwrap() { + ServerMessage::Pong { .. } => break, + ServerMessage::Delta(d) => { + assert!(d.server_tick >= last_tick, "ordered"); + last_tick = d.server_tick; + } + _ => {} + } + } + assert!( + start.elapsed() >= Duration::from_millis(80), + "two one-way delays" + ); + server.shutdown(); + let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; +} diff --git a/distributed_game/tests/replication/main.rs b/distributed_game/tests/replication/main.rs new file mode 100644 index 000000000..3b51285d3 --- /dev/null +++ b/distributed_game/tests/replication/main.rs @@ -0,0 +1,178 @@ +//! P3 replication: interest enter/leave with hysteresis, global entities, +//! change detection and byte-budget fairness. + +use std::collections::BTreeMap; + +use distributed_game::protocol::{Delta, ServerMessage}; +use distributed_game::replication::{ClientReplica, EncodedWorld}; +use distributed_game::{ + ClientMirror, EntitySchema, EntityState, FieldType, FieldValue, InterestConfig, KindDef, View, + WorldView, +}; + +fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -1000.0, + max: 1000.0, + bits: 20, + }; + EntitySchema::new().kind( + KindDef::new(1, "thing") + .field("x", pos) + .field("y", pos) + .field("hp", FieldType::U16), + ) +} + +fn thing(id: u32, x: f32, y: f32, hp: u32) -> EntityState { + EntityState::new( + id, + 1, + x, + y, + vec![FieldValue::F(x), FieldValue::F(y), FieldValue::U(hp)], + ) +} + +struct Client { + replica: ClientReplica, + mirror: ClientMirror, + view: View, + budget: usize, +} + +impl Client { + fn new(view: View, budget: usize) -> Self { + // Seed the mirror with the schema as a Welcome would. + let mut mirror = ClientMirror::new(); + mirror.welcome = Some(distributed_game::protocol::Welcome { + session_id: "s".into(), + zone_id: "z".into(), + role: distributed_game::Role::Player, + tick_rate: 30, + patch_rate: 20, + server_tick: 0, + server_time: 0.0, + reconnect_token: String::new(), + content_version: String::new(), + schema: schema(), + }); + Self { + replica: ClientReplica::new(), + mirror, + view, + budget, + } + } + + fn patch(&mut self, entities: Vec, tick: u32) -> Delta { + let mut view = WorldView::default(); + for e in entities { + view.push(e); + } + let interest = InterestConfig { + cell_size: 8.0, + leave_margin: 0.1, + }; + let world = EncodedWorld::build(&schema(), view, &interest); + let (frame, _) = self.replica.build_delta( + &schema(), + &world, + &interest, + &self.view, + self.budget, + tick, + 0, + ); + match self.mirror.apply(&frame).unwrap() { + ServerMessage::Delta(d) => d, + other => panic!("{other:?}"), + } + } +} + +#[test] +fn entities_enter_and_leave_views_with_hysteresis() { + let mut c = Client::new(View::new(0.0, 0.0, 10.0), 10_000); + let far = thing(2, 50.0, 50.0, 1); + + let d = c.patch(vec![thing(1, 5.0, 0.0, 10), far.clone()], 1); + assert_eq!(d.creates.iter().map(|e| e.id).collect::>(), vec![1]); + + // Inside the leave margin (10 * 1.1 = 11): update, not remove. + let d = c.patch(vec![thing(1, 10.5, 0.0, 10), far.clone()], 2); + assert!(d.removes.is_empty()); + assert_eq!(d.updates.len(), 1); + assert_eq!(d.updates[0].mask, 0b001, "only x changed"); + + // Beyond the margin: remove. + let d = c.patch(vec![thing(1, 12.0, 0.0, 10), far.clone()], 3); + assert_eq!(d.removes, vec![1]); + assert!(c.mirror.entities.is_empty()); + + // Back inside the enter radius: full create again. + let d = c.patch(vec![thing(1, 9.0, 0.0, 7), far.clone()], 4); + assert_eq!(d.creates.len(), 1); + assert_eq!(c.mirror.entities[&1].fields[2], FieldValue::U(7)); + + // Despawn: remove. + let d = c.patch(vec![far], 5); + assert_eq!(d.removes, vec![1]); +} + +#[test] +fn global_entities_ignore_distance_and_unchanged_state_is_free() { + let mut c = Client::new(View::new(0.0, 0.0, 10.0), 10_000); + let d = c.patch(vec![thing(9, 900.0, 900.0, 1).global()], 1); + assert_eq!(d.creates.len(), 1); + let d = c.patch(vec![thing(9, 900.0, 900.0, 1).global()], 2); + assert!(d.creates.is_empty() && d.updates.is_empty() && d.removes.is_empty()); + // Sub-quantum jitter (20-bit over 2000 units ≈ 0.0019) is not a change. + let d = c.patch(vec![thing(9, 900.000_1, 900.0, 1).global()], 3); + assert!(d.updates.is_empty()); +} + +#[test] +fn byte_budget_prioritizes_but_never_starves() { + // 60 entities all changing every patch; budget fits ~8 updates. + let mut c = Client::new(View::new(0.0, 0.0, 100.0), 64); + let n = 60u32; + let mut last_sent: BTreeMap = BTreeMap::new(); + let mut max_gap: BTreeMap = BTreeMap::new(); + let mut sends: BTreeMap = BTreeMap::new(); + for tick in 1..=200u32 { + let entities = (1..=n) + .map(|id| { + // Entity 1 is close (high priority), the rest spread out. + let d = if id == 1 { 1.0 } else { 10.0 + id as f32 }; + thing(id, d, 0.0, tick) + }) + .collect(); + let delta = c.patch(entities, tick); + let sent: Vec = delta + .creates + .iter() + .map(|e| e.id) + .chain(delta.updates.iter().map(|u| u.id)) + .collect(); + assert!(!sent.is_empty()); + for id in sent { + let gap = tick - last_sent.get(&id).copied().unwrap_or(0); + let g = max_gap.entry(id).or_insert(0); + *g = (*g).max(gap); + last_sent.insert(id, tick); + *sends.entry(id).or_insert(0) += 1; + } + } + assert_eq!(sends.len(), n as usize, "every entity was sent"); + let worst = max_gap.values().max().copied().unwrap(); + assert!(worst <= 30, "bounded staleness, worst gap {worst} patches"); + assert!( + sends[&1] > sends[&n] * 4 / 3, + "near entity sent more often ({} vs {})", + sends[&1], + sends[&n] + ); + // Mirror converges to the server state for everything sent recently. + assert_eq!(c.mirror.entities.len(), n as usize); +} From dee4acfe50b0f45721768edf0ade9018d15111e2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:16:38 -0500 Subject: [PATCH 127/484] feat(js): add game client SDK with codec, replica and prediction New `@hops-ops/distributed/game` subpath: a byte-exact implementation of distributed_game PROTOCOL.md v1 (varints, schema from Welcome, quantization identical to Rust), GameConnection (handshake, reconnect token with grace fallback to a fresh app ticket, Ping/Pong clock sync, typed events, injectable socket and scheduler), EntityReplica with interpolation buffers, Predictor with ease/snap/replace reconciliation and a multi-zone GameClient that follows Handoff without blanking the rendered world. Tests assert every Rust golden fixture byte-for-byte and cover replica interpolation, divergence correction, reconnect and handoff over a fake socket. Refs [[tasks/gr-p4-client-sdk]] --- js/package.json | 4 + js/src/game/client.ts | 481 +++++++++++++++++ js/src/game/clock.ts | 111 ++++ js/src/game/connection.ts | 605 ++++++++++++++++++++++ js/src/game/emitter.ts | 53 ++ js/src/game/index.ts | 121 +++++ js/src/game/messages.ts | 448 ++++++++++++++++ js/src/game/prediction.ts | 272 ++++++++++ js/src/game/replica.ts | 324 ++++++++++++ js/src/game/schema.ts | 333 ++++++++++++ js/src/game/wire.ts | 283 ++++++++++ js/tests/fixtures/game-harness.mjs | 232 +++++++++ js/tests/game-codec.test.mjs | 444 ++++++++++++++++ js/tests/game-connection.test.mjs | 389 ++++++++++++++ js/tests/game-replica-prediction.test.mjs | 140 +++++ 15 files changed, 4240 insertions(+) create mode 100644 js/src/game/client.ts create mode 100644 js/src/game/clock.ts create mode 100644 js/src/game/connection.ts create mode 100644 js/src/game/emitter.ts create mode 100644 js/src/game/index.ts create mode 100644 js/src/game/messages.ts create mode 100644 js/src/game/prediction.ts create mode 100644 js/src/game/replica.ts create mode 100644 js/src/game/schema.ts create mode 100644 js/src/game/wire.ts create mode 100644 js/tests/fixtures/game-harness.mjs create mode 100644 js/tests/game-codec.test.mjs create mode 100644 js/tests/game-connection.test.mjs create mode 100644 js/tests/game-replica-prediction.test.mjs diff --git a/js/package.json b/js/package.json index 9ddee7f00..a3d1de708 100644 --- a/js/package.json +++ b/js/package.json @@ -34,6 +34,10 @@ "types": "./dist/react/index.d.ts", "import": "./dist/react/index.js" }, + "./game": { + "types": "./dist/game/index.d.ts", + "import": "./dist/game/index.js" + }, "./package.json": "./package.json", "./replica/lazy": { "types": "./dist/replica/lazy.d.ts", diff --git a/js/src/game/client.ts b/js/src/game/client.ts new file mode 100644 index 000000000..292ce49ac --- /dev/null +++ b/js/src/game/client.ts @@ -0,0 +1,481 @@ +/** + * Multi-zone game client: one authoritative connection (the zone that owns + * the player) plus observer connections to neighbouring zones, merged into + * one rendered world tagged by zone. Follows Handoff messages by connecting + * to the target zone with the transfer ticket and swapping authority without + * blanking the rendered world. + */ +import { + GameConnection, + type GameCloseInfo, + type GameConnectionOptions, + type GameReconnectOptions, + type GameScheduler, + type GameSocketFactory, + type GameTicketSource, + defaultScheduler +} from './connection.js'; +import { Emitter } from './emitter.js'; +import type { + DeltaMessage, + ErrorMessage, + EventMessage, + FreezeMessage, + HandoffMessage, + KickMessage, + ResumeMessage, + WelcomeMessage +} from './messages.js'; +import { Predictor, type Correction, type PredictorOptions } from './prediction.js'; +import { + EntityReplica, + type EntityFields, + type InterpolationPolicy, + type ReplicaEntity +} from './replica.js'; + +export type ZoneRole = 'authority' | 'observer' | 'retired'; + +/** One zone known to the client. */ +export type GameZoneView = Readonly<{ + zoneId: string; + role: ZoneRole; + connection: GameConnection; + replica: EntityReplica; +}>; + +export type RenderedEntity = Readonly<{ + /** `${zoneId}:${id}` — entity ids are only unique within a zone. */ + key: string; + zoneId: string; + id: number; + kind: number; + kindName: string; + fields: EntityFields; + /** From the authoritative zone (vs. observed neighbour / retired). */ + authoritative: boolean; + /** The locally controlled, predicted entity. */ + predicted: boolean; + stale: boolean; +}>; + +export type ControlledEntityResolver = ( + context: Readonly<{ zoneId: string; welcome: WelcomeMessage; replica: EntityReplica }> +) => number | undefined; + +export type GamePredictionOptions = PredictorOptions & + Readonly<{ + /** Encode an input to its game-defined payload bytes. */ + encodeInput(input: TInput): Uint8Array; + /** + * Which entity the player controls in a zone. Re-evaluated on every + * authoritative Delta until it returns an id; `setControlledEntity` + * overrides it (e.g. from a game Event). + */ + controlledEntity?: ControlledEntityResolver; + }>; + +export type GameClientOptions = Readonly<{ + /** WebSocket URL for a zone, e.g. `(z) => \`wss://game.example/zones/${z}\``. */ + url: (zoneId: string) => string; + /** Fresh player ticket for a zone (joins and post-grace rejoins). */ + ticket: GameTicketSource; + /** Observer ticket for a zone. Defaults to `ticket` with `role: 'observer'`. */ + observerTicket?: GameTicketSource; + contentVersion?: string; + capabilities?: number; + socket?: GameSocketFactory; + scheduler?: GameScheduler; + reconnect?: false | GameReconnectOptions; + pingIntervalMs?: number; + /** + * Render delay behind the server clock. Default: two patch intervals of + * the zone (100 ms at 20 Hz). + */ + interpolationDelayMs?: number | ((zone: GameZoneView) => number); + interpolation?: InterpolationPolicy; + staleGraceMs?: number; + historyMs?: number; + prediction?: GamePredictionOptions; + /** After a handoff, keep the previous zone rendered this long once the target delivered its first Delta. Default 500 ms. */ + handoffRetainMs?: number; + /** Default input dt (ms) when `sendInput` omits it. Default: 1000 / tickRate. */ + inputDtMs?: number; + onListenerError?: (error: unknown) => void; +}>; + +export type GameClientEvents = { + authority: [string, WelcomeMessage]; + welcome: [string, WelcomeMessage]; + delta: [string, DeltaMessage]; + event: [string, EventMessage]; + freeze: [string, FreezeMessage]; + resume: [string, ResumeMessage]; + kick: [string, KickMessage]; + error: [string, ErrorMessage]; + handoff: [{ from: string; to: string; message: HandoffMessage }]; + handoffComplete: [{ from: string; to: string }]; + correction: [Correction]; + zoneClosed: [string, GameCloseInfo]; +}; + +type Zone = { + zoneId: string; + role: ZoneRole; + connection: GameConnection; + replica: EntityReplica; + offs: (() => void)[]; + firstDeltaSeen: boolean; + dropTimer?: unknown; +}; + +export class GameClient { + readonly #options: GameClientOptions; + readonly #scheduler: GameScheduler; + readonly #emitter: Emitter; + readonly #zones = new Map(); + readonly #retired = new Map(); + /** Connections superseded by a new one sharing their replica; not rendered. */ + readonly #priors = new Set(); + readonly #predictor: Predictor | undefined; + #authority: Zone | undefined; + #controlledOverride: number | undefined; + #closed = false; + + constructor(options: GameClientOptions) { + this.#options = options; + this.#scheduler = options.scheduler ?? defaultScheduler; + this.#emitter = new Emitter(options.onListenerError); + this.#predictor = + options.prediction === undefined ? undefined : new Predictor(options.prediction); + } + + on( + type: K, + listener: (...args: GameClientEvents[K]) => void + ): () => void { + return this.#emitter.on(type, listener); + } + + /** The authoritative zone, if any. */ + get authority(): GameZoneView | undefined { + return this.#authority; + } + + get predictor(): Predictor | undefined { + return this.#predictor; + } + + /** Every zone currently rendered (authority, observers, retired). */ + zones(): GameZoneView[] { + return [...this.#zones.values(), ...this.#retired.values()]; + } + + zone(zoneId: string): GameZoneView | undefined { + return this.#zones.get(zoneId) ?? this.#retired.get(zoneId); + } + + /** Join `zoneId` as the player's authoritative zone. */ + connect(zoneId: string, initialTicket?: string): Promise { + this.#assertOpen(); + const previous = this.#authority; + if (previous?.zoneId === zoneId) return previous.connection.connect(); + const zone = this.#adopt(zoneId, 'authority', initialTicket); + this.#authority = zone; + if (previous !== undefined) this.#retire(previous, false); + return zone.connection.connect(); + } + + /** Observe a neighbouring zone (read-only; merged into `render`). */ + observe(zoneId: string): Promise { + this.#assertOpen(); + const existing = this.#zones.get(zoneId); + if (existing !== undefined) return existing.connection.connect(); + return this.#adopt(zoneId, 'observer').connection.connect(); + } + + /** Stop observing a zone. */ + unobserve(zoneId: string): void { + const zone = this.#zones.get(zoneId); + if (zone === undefined || zone.role !== 'observer') return; + this.#drop(zone); + } + + /** Override which entity is controlled (e.g. announced by a game Event). */ + setControlledEntity(id: number | undefined): void { + this.#controlledOverride = id; + this.#bindControlled(true); + } + + /** + * Send an input on the authoritative connection and apply it to the + * prediction. Returns the sequence number, or undefined if not sent. + */ + sendInput(input: TInput, dtMs?: number): number | undefined { + const authority = this.#authority; + const prediction = this.#options.prediction; + if (authority === undefined || prediction === undefined) return undefined; + const connection = authority.connection; + if (!connection.canSendInput()) return undefined; + const seq = connection.sendInput(prediction.encodeInput(input)); + if (seq === undefined) return undefined; + const tickRate = connection.welcome?.tickRate || 30; + this.#predictor!.record(seq, input, dtMs ?? this.#options.inputDtMs ?? 1000 / tickRate); + return seq; + } + + /** Send raw input bytes (no prediction). */ + sendRawInput(payload: Uint8Array): number | undefined { + return this.#authority?.connection.sendInput(payload); + } + + /** Render delay in effect for a zone. */ + interpolationDelay(zone: GameZoneView): number { + const configured = this.#options.interpolationDelayMs; + if (typeof configured === 'number') return configured; + if (typeof configured === 'function') return configured(zone); + const patchRate = zone.connection.welcome?.patchRate || 20; + return 2 * (1000 / patchRate); + } + + /** + * The merged world to draw now: every zone sampled at its own + * `serverNow - interpolationDelay`, the controlled entity at its predicted + * (present) state with correction smoothing. + */ + render(): RenderedEntity[] { + const out: RenderedEntity[] = []; + const now = this.#scheduler.now(); + const predictor = this.#predictor; + const controlled = + predictor?.active === true && this.#authority !== undefined ? predictor.entityId : undefined; + for (const zone of this.zones()) { + const renderTime = zone.connection.serverNow() - this.interpolationDelay(zone); + const authoritative = zone === this.#authority; + for (const entity of zone.replica.sample(renderTime)) { + const isControlled = authoritative && entity.id === controlled && !entity.stale; + out.push( + rendered(zone.zoneId, entity, authoritative, isControlled, isControlled ? predictor!.current(now) : undefined) + ); + } + } + return out; + } + + /** Close every connection (graceful Leave on the authority). */ + close(): void { + if (this.#closed) return; + this.#closed = true; + for (const zone of [...this.#zones.values(), ...this.#retired.values(), ...this.#priors]) { + this.#drop(zone); + } + this.#authority = undefined; + } + + #assertOpen(): void { + if (this.#closed) throw new Error('GameClient is closed'); + } + + #connectionOptions(zoneId: string, role: 'authority' | 'observer', initialTicket?: string): GameConnectionOptions { + const o = this.#options; + const observerTicket: GameTicketSource = + o.observerTicket ?? ((request) => o.ticket({ ...request, role: 'observer' })); + return { + url: o.url(zoneId), + zoneId, + role: role === 'authority' ? 'player' : 'observer', + ticket: role === 'authority' ? o.ticket : observerTicket, + initialTicket, + contentVersion: o.contentVersion, + capabilities: o.capabilities, + socket: o.socket, + scheduler: this.#scheduler, + reconnect: o.reconnect, + pingIntervalMs: o.pingIntervalMs, + onListenerError: o.onListenerError + }; + } + + /** + * Create the zone entry for `zoneId` in `role`. An existing view of the + * same zone (observer, or retired after a handoff) hands its replica over + * so already-rendered entities continue without a gap. + */ + #adopt(zoneId: string, role: 'authority' | 'observer', initialTicket?: string): Zone { + const prior = this.#zones.get(zoneId) ?? this.#retired.get(zoneId); + const replica = + prior?.replica ?? + new EntityReplica({ + interpolation: this.#options.interpolation, + staleGraceMs: this.#options.staleGraceMs, + historyMs: this.#options.historyMs + }); + const connection = new GameConnection(this.#connectionOptions(zoneId, role, initialTicket)); + const zone: Zone = { zoneId, role, connection, replica, offs: [], firstDeltaSeen: false }; + if (prior !== undefined) { + // The prior connection keeps feeding the shared replica until the + // new one is welcomed, then it is closed. + this.#zones.delete(zoneId); + this.#retired.delete(zoneId); + if (prior.dropTimer !== undefined) this.#scheduler.clearTimeout(prior.dropTimer); + const off = connection.on('welcome', () => { + off(); + this.#closeConnection(prior); + }); + prior.role = 'retired'; + this.#priors.add(prior); + } + this.#zones.set(zoneId, zone); + this.#wire(zone); + return zone; + } + + #wire(zone: Zone): void { + const c = zone.connection; + zone.offs.push( + c.on('welcome', (welcome) => { + zone.replica.reset(welcome.schema, c.serverNow()); + zone.firstDeltaSeen = false; + if (zone === this.#authority) { + this.#predictor?.resetSession(); + this.#bindControlled(true); + this.#emitter.emit('authority', zone.zoneId, welcome); + } + this.#emitter.emit('welcome', zone.zoneId, welcome); + }), + c.on('delta', (delta) => this.#onDelta(zone, delta)), + c.on('event', (event) => this.#emitter.emit('event', zone.zoneId, event)), + c.on('freeze', (m) => this.#emitter.emit('freeze', zone.zoneId, m)), + c.on('resume', (m) => this.#emitter.emit('resume', zone.zoneId, m)), + c.on('kick', (m) => this.#emitter.emit('kick', zone.zoneId, m)), + c.on('error', (m) => this.#emitter.emit('error', zone.zoneId, m)), + c.on('handoff', (m) => this.#onHandoff(zone, m)), + c.on('close', (info) => { + this.#emitter.emit('zoneClosed', zone.zoneId, info); + }) + ); + } + + #onDelta(zone: Zone, delta: DeltaMessage): void { + zone.replica.applyDelta(delta, zone.connection.tickTime(delta.serverTick)); + if (!zone.firstDeltaSeen) { + zone.firstDeltaSeen = true; + if (zone === this.#authority) this.#scheduleRetiredDrop(); + } + if (zone === this.#authority && this.#predictor !== undefined) { + this.#bindControlled(false); + const id = this.#predictor.entityId; + if (id !== undefined) { + const entity = zone.replica.get(id); + if (entity !== undefined && !this.#predictor.active) { + this.#predictor.bind(id, zone.replica.schema?.byId.get(entity.kind), entity.fields); + } + const correction = this.#predictor.reconcile( + delta.ackSeq, + entity?.fields, + this.#scheduler.now() + ); + if (correction !== undefined && Object.keys(correction.resolved).length > 0) { + this.#emitter.emit('correction', correction); + } + } + } + this.#emitter.emit('delta', zone.zoneId, delta); + } + + #bindControlled(force: boolean): void { + const predictor = this.#predictor; + const authority = this.#authority; + if (predictor === undefined || authority === undefined) return; + const welcome = authority.connection.welcome; + let id = this.#controlledOverride; + if (id === undefined && welcome !== undefined) { + id = this.#options.prediction?.controlledEntity?.({ + zoneId: authority.zoneId, + welcome, + replica: authority.replica + }); + } + if (!force && id === predictor.entityId) return; + const entity = id === undefined ? undefined : authority.replica.get(id); + predictor.bind( + id, + entity === undefined ? undefined : authority.replica.schema?.byId.get(entity.kind), + entity?.fields + ); + } + + #onHandoff(zone: Zone, message: HandoffMessage): void { + if (zone !== this.#authority) return; + const from = zone.zoneId; + const to = message.targetZone; + this.#emitter.emit('handoff', { from, to, message }); + this.#controlledOverride = undefined; + this.#predictor?.bind(undefined); + const target = this.#adopt(to, 'authority', message.transferTicket); + this.#authority = target; + // Keep rendering the old zone until the new authority has content. + this.#retire(zone, true); + const off = target.connection.on('delta', () => { + off(); + this.#emitter.emit('handoffComplete', { from, to }); + }); + void target.connection.connect().catch(() => undefined); + } + + #retire(zone: Zone, keepRendering: boolean): void { + if (this.#zones.get(zone.zoneId) === zone) this.#zones.delete(zone.zoneId); + if (!keepRendering) { + this.#drop(zone); + return; + } + zone.role = 'retired'; + this.#retired.set(zone.zoneId, zone); + if (this.#authority?.firstDeltaSeen) this.#scheduleRetiredDrop(); + } + + #scheduleRetiredDrop(): void { + const retain = this.#options.handoffRetainMs ?? 500; + for (const zone of this.#retired.values()) { + if (zone.dropTimer !== undefined) continue; + zone.dropTimer = this.#scheduler.setTimeout(() => { + zone.dropTimer = undefined; + if (this.#retired.get(zone.zoneId) === zone) this.#drop(zone); + }, retain); + } + } + + #closeConnection(zone: Zone): void { + for (const off of zone.offs) off(); + zone.offs = []; + zone.connection.close({ leave: zone.role !== 'retired' }); + this.#priors.delete(zone); + if (this.#retired.get(zone.zoneId) === zone) this.#retired.delete(zone.zoneId); + } + + #drop(zone: Zone): void { + if (zone.dropTimer !== undefined) this.#scheduler.clearTimeout(zone.dropTimer); + this.#closeConnection(zone); + if (this.#zones.get(zone.zoneId) === zone) this.#zones.delete(zone.zoneId); + } +} + +function rendered( + zoneId: string, + entity: ReplicaEntity, + authoritative: boolean, + predicted: boolean, + predictedFields: EntityFields | undefined +): RenderedEntity { + return { + key: `${zoneId}:${entity.id}`, + zoneId, + id: entity.id, + kind: entity.kind, + kindName: entity.kindName, + fields: predictedFields === undefined ? entity.fields : { ...entity.fields, ...predictedFields }, + authoritative, + predicted: predicted && predictedFields !== undefined, + stale: entity.stale + }; +} diff --git a/js/src/game/clock.ts b/js/src/game/clock.ts new file mode 100644 index 000000000..5f46e07a7 --- /dev/null +++ b/js/src/game/clock.ts @@ -0,0 +1,111 @@ +/** + * Ping/Pong clock synchronization (`PROTOCOL.md` §3). + * + * Per sample: `rtt = now - pong.clientTime`, + * `offset = pong.serverTime + rtt/2 - now`. RTT and jitter are smoothed like + * TCP's SRTT/RTTVAR (RFC 6298 gains 1/8 and 1/4). The offset estimate uses + * the lowest-RTT samples of a sliding window (they carry the least queueing + * asymmetry) and moves toward new estimates gradually so the rendered + * server timeline never jumps by more than `maxSlewPerSample`. + */ + +export type ClockSyncOptions = Readonly<{ + /** Samples kept for the offset estimate. Default 16. */ + window?: number; + /** Largest offset correction applied per sample once synced (ms). Default 25. */ + maxSlewPerSample?: number; +}>; + +export type ClockSample = Readonly<{ rtt: number; offset: number; at: number }>; + +export class ClockSync { + readonly #window: number; + readonly #maxSlew: number; + #samples: ClockSample[] = []; + #offset = 0; + #rtt = 0; + #jitter = 0; + #synced = false; + #seeded = false; + + constructor(options: ClockSyncOptions = {}) { + this.#window = Math.max(1, options.window ?? 16); + this.#maxSlew = options.maxSlewPerSample ?? 25; + } + + /** Estimated `serverClock - localClock` in ms. */ + get offset(): number { + return this.#offset; + } + + /** Smoothed round-trip time in ms. */ + get rtt(): number { + return this.#rtt; + } + + /** Smoothed RTT variation (jitter) in ms. */ + get jitter(): number { + return this.#jitter; + } + + /** True once at least one Pong was observed. */ + get synced(): boolean { + return this.#synced; + } + + get samples(): readonly ClockSample[] { + return this.#samples; + } + + /** Coarse seed from a Welcome (`serverTime` at receipt, latency unknown). */ + seed(serverTime: number, now: number): void { + if (this.#synced) return; + this.#offset = serverTime - now; + this.#seeded = true; + } + + /** Forget samples (a new connection may face a different path or server). */ + reset(): void { + this.#samples = []; + this.#synced = false; + this.#seeded = false; + this.#rtt = 0; + this.#jitter = 0; + } + + /** Fold in one Pong; returns the raw sample. */ + observe(clientTime: number, serverTime: number, now: number): ClockSample | undefined { + const rtt = now - clientTime; + if (!(rtt >= 0) || !Number.isFinite(serverTime)) return undefined; + const sample = { rtt, offset: serverTime + rtt / 2 - now, at: now }; + this.#samples.push(sample); + if (this.#samples.length > this.#window) this.#samples.shift(); + + if (!this.#synced) { + this.#rtt = rtt; + this.#jitter = rtt / 2; + } else { + this.#jitter += (Math.abs(rtt - this.#rtt) - this.#jitter) / 4; + this.#rtt += (rtt - this.#rtt) / 8; + } + + const best = [...this.#samples].sort((a, b) => a.rtt - b.rtt); + const keep = best.slice(0, Math.max(1, Math.ceil(best.length / 2))); + const offsets = keep.map((s) => s.offset).sort((a, b) => a - b); + const target = offsets[Math.floor(offsets.length / 2)]; + if (!this.#synced) { + this.#offset = target; + this.#synced = true; + } else { + const delta = target - this.#offset; + this.#offset += Math.max(-this.#maxSlew, Math.min(this.#maxSlew, delta)); + } + this.#seeded = true; + return sample; + } + + /** Server clock estimate for local time `now`. */ + serverNow(now: number): number { + return now + (this.#seeded ? this.#offset : 0); + } +} diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts new file mode 100644 index 000000000..b46cf9288 --- /dev/null +++ b/js/src/game/connection.ts @@ -0,0 +1,605 @@ +/** + * One WebSocket connection to one zone (`PROTOCOL.md` §1, §6, §8). + * + * Handles the Hello/Welcome handshake, reconnect-token resumption inside the + * server's grace window with fallback to a freshly fetched ticket, Ping/Pong + * clock sync, sequenced inputs and typed server events. The transport and + * timers are injectable so tests drive it with an in-memory socket. + */ +import { ClockSync, type ClockSyncOptions } from './clock.js'; +import { Emitter } from './emitter.js'; +import { + encodeClientMessage, + GAME_PROTOCOL_VERSION, + GameClientMirror, + GameErrorCode, + type DeltaMessage, + type ErrorMessage, + type EventMessage, + type FreezeMessage, + type GameClientMessage, + type GameRole, + type GameServerMessage, + type HandoffMessage, + type KickMessage, + type ResumeMessage, + type WelcomeMessage +} from './messages.js'; + +/** Minimal WebSocket surface (the browser `WebSocket` satisfies it). */ +export interface GameSocket { + binaryType?: string; + send(data: Uint8Array): void; + close(code?: number, reason?: string): void; + onopen: ((event?: unknown) => void) | null; + onmessage: ((event: { data: unknown }) => void) | null; + onclose: ((event?: { code?: number; reason?: string }) => void) | null; + onerror: ((event?: unknown) => void) | null; +} + +export type GameSocketFactory = (url: string) => GameSocket; + +/** Clock and timers (injectable for deterministic tests). */ +export type GameScheduler = Readonly<{ + now(): number; + setTimeout(callback: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +}>; + +export const defaultScheduler: GameScheduler = Object.freeze({ + now: () => globalThis.performance?.now() ?? Date.now(), + setTimeout: (callback: () => void, ms: number) => globalThis.setTimeout(callback, ms), + clearTimeout: (handle: unknown) => + globalThis.clearTimeout(handle as ReturnType) +}); + +/** Why the app is being asked for a ticket. */ +export type GameTicketRequest = Readonly<{ + zoneId: string; + role: GameRole; + reason: 'join' | 'rejoin'; +}>; + +/** + * Supplies a signed admission ticket. Called for the first join (unless + * `initialTicket` is given) and again whenever a reconnect token can no + * longer be used, so it should fetch a fresh ticket (tickets are single use). + */ +export type GameTicketSource = (request: GameTicketRequest) => string | Promise; + +export type GameReconnectOptions = Readonly<{ + /** Server reconnect grace window (default 15000 ms, matching the server). */ + graceMs?: number; + /** Give up after this many consecutive failed attempts (default 10). */ + maxAttempts?: number; + /** Delay before attempt `n` (1-based). Default 250·2^(n-1) ms capped at 5 s. */ + backoffMs?: (attempt: number) => number; +}>; + +export type GameConnectionOptions = Readonly<{ + /** WebSocket URL of the zone endpoint, e.g. `wss://host/zones/z1`. */ + url: string; + zoneId: string; + /** Expected role (informational; the ticket decides). Default `player`. */ + role?: GameRole; + ticket: GameTicketSource; + /** Ticket for the first Hello only (e.g. a Handoff transfer ticket). */ + initialTicket?: string; + contentVersion?: string; + capabilities?: number; + socket?: GameSocketFactory; + scheduler?: GameScheduler; + /** `false` disables automatic reconnect. */ + reconnect?: false | GameReconnectOptions; + /** Ping cadence while open (default 1000 ms; first ping right after Welcome). */ + pingIntervalMs?: number; + clock?: ClockSyncOptions; + onListenerError?: (error: unknown) => void; +}>; + +export type GameConnectionState = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'; + +export type GameCloseReason = + | 'client' + | 'kick' + | 'handoff' + | 'rejected' + | 'reconnect-exhausted' + | 'connect-failed'; + +export type GameCloseInfo = Readonly<{ + reason: GameCloseReason; + code?: number; + message?: string; +}>; + +export type GameWelcomeInfo = Readonly<{ + /** True when this Welcome resumed the session with a reconnect token. */ + resumed: boolean; + /** True for any Welcome after the first on this connection object. */ + reconnected: boolean; +}>; + +export type GameConnectionEvents = { + welcome: [WelcomeMessage, GameWelcomeInfo]; + delta: [DeltaMessage]; + event: [EventMessage]; + freeze: [FreezeMessage]; + resume: [ResumeMessage]; + handoff: [HandoffMessage]; + kick: [KickMessage]; + error: [ErrorMessage]; + pong: [{ rtt: number; offset: number; jitter: number }]; + state: [GameConnectionState]; + disconnect: [{ code?: number; reason?: string }]; + protocolError: [unknown]; + close: [GameCloseInfo]; +}; + +type Attempt = { socket: GameSocket; mode: 'fresh' | 'resume'; welcomed: boolean }; + +const defaultBackoff = (attempt: number): number => Math.min(5000, 250 * 2 ** (attempt - 1)); + +export class GameConnection { + readonly zoneId: string; + readonly url: string; + readonly clock: ClockSync; + readonly mirror = new GameClientMirror(); + + readonly #options: GameConnectionOptions; + readonly #scheduler: GameScheduler; + readonly #socketFactory: GameSocketFactory; + readonly #emitter: Emitter; + readonly #reconnect: Required | undefined; + readonly #pingIntervalMs: number; + + #state: GameConnectionState = 'idle'; + #attempt: Attempt | undefined; + #initialTicket: string | undefined; + #reconnectToken = ''; + #sessionId: string | undefined; + #welcomes = 0; + #disconnectedAt: number | undefined; + #failedAttempts = 0; + #pingTimer: unknown; + #retryTimer: unknown; + #terminal: GameCloseInfo | undefined; + #seq = 0; + #frozen = false; + #connectWaiters: { resolve: (w: WelcomeMessage) => void; reject: (e: unknown) => void }[] = []; + + constructor(options: GameConnectionOptions) { + this.#options = options; + this.zoneId = options.zoneId; + this.url = options.url; + this.#initialTicket = options.initialTicket; + this.#scheduler = options.scheduler ?? defaultScheduler; + const factory = + options.socket ?? + ((url: string) => { + const Ctor = (globalThis as { WebSocket?: new (url: string) => GameSocket }).WebSocket; + if (Ctor === undefined) throw new TypeError('WebSocket is unavailable in this runtime'); + return new Ctor(url); + }); + this.#socketFactory = factory; + this.#emitter = new Emitter(options.onListenerError); + this.#reconnect = + options.reconnect === false + ? undefined + : { + graceMs: options.reconnect?.graceMs ?? 15000, + maxAttempts: options.reconnect?.maxAttempts ?? 10, + backoffMs: options.reconnect?.backoffMs ?? defaultBackoff + }; + this.#pingIntervalMs = options.pingIntervalMs ?? 1000; + this.clock = new ClockSync(options.clock); + } + + get state(): GameConnectionState { + return this.#state; + } + + get welcome(): WelcomeMessage | undefined { + return this.mirror.welcome; + } + + get sessionId(): string | undefined { + return this.#sessionId; + } + + get role(): GameRole | undefined { + return this.mirror.welcome?.role; + } + + /** Reconnect token from the latest Welcome (rotated on every Welcome). */ + get reconnectToken(): string { + return this.#reconnectToken; + } + + /** True between Freeze and Resume. */ + get frozen(): boolean { + return this.#frozen; + } + + /** Last input sequence number sent on the current session. */ + get lastSeq(): number { + return this.#seq; + } + + get scheduler(): GameScheduler { + return this.#scheduler; + } + + on( + type: K, + listener: (...args: GameConnectionEvents[K]) => void + ): () => void { + return this.#emitter.on(type, listener); + } + + /** Local monotonic time. */ + now(): number { + return this.#scheduler.now(); + } + + /** Estimated server clock (ms) now. */ + serverNow(): number { + return this.clock.serverNow(this.#scheduler.now()); + } + + /** Server time a tick belongs to, from the Welcome's tick/time anchor. */ + tickTime(tick: number): number { + const w = this.mirror.welcome; + if (w === undefined || w.tickRate === 0) return this.serverNow(); + // Ticks are the low 32 bits: interpret the difference as int32. + const diff = (tick - w.serverTick) | 0; + return w.serverTime + (diff * 1000) / w.tickRate; + } + + /** Estimated server tick at the current server time (wraps at 2^32). */ + estimatedServerTick(): number { + const w = this.mirror.welcome; + if (w === undefined) return 0; + const ticks = Math.floor(((this.serverNow() - w.serverTime) * w.tickRate) / 1000); + return (w.serverTick + ticks) >>> 0; + } + + /** Open the connection; resolves with the first Welcome. */ + connect(): Promise { + if (this.#state === 'closed') { + return Promise.reject(new Error(`game connection ${this.zoneId} is closed`)); + } + const promise = new Promise((resolve, reject) => { + if (this.#state === 'open' && this.mirror.welcome !== undefined) { + resolve(this.mirror.welcome); + return; + } + this.#connectWaiters.push({ resolve, reject }); + }); + if (this.#state === 'idle') { + this.#setState('connecting'); + void this.#open('fresh'); + } + return promise; + } + + /** + * Send one input. Returns its sequence number, or `undefined` when it was + * not sent (not open, observer, or frozen). + */ + sendInput(payload: Uint8Array, clientTick = this.estimatedServerTick()): number | undefined { + if (!this.canSendInput()) return undefined; + this.#seq += 1; + this.#send({ type: 'Input', seq: this.#seq, clientTick: clientTick >>> 0, payload }); + return this.#seq; + } + + canSendInput(): boolean { + return this.#state === 'open' && this.mirror.welcome?.role === 'player' && !this.#frozen; + } + + /** Send a Ping now (also sent automatically). */ + ping(): void { + if (this.#state !== 'open') return; + this.#send({ type: 'Ping', clientTime: this.#scheduler.now() }); + } + + /** + * Close for good. With `leave` (default) a graceful Leave is sent first so + * the server removes the player immediately instead of holding it for the + * reconnect grace window. + */ + close(options: { leave?: boolean } = {}): void { + if (this.#state === 'closed') return; + if ((options.leave ?? true) && this.#state === 'open') this.#send({ type: 'Leave' }); + this.#finish({ reason: 'client' }); + } + + /** Simulate an abrupt transport loss (tests, "airplane mode" toggles). */ + dropTransport(): void { + this.#attempt?.socket.close(4000, 'dropped by client'); + } + + #setState(state: GameConnectionState): void { + if (this.#state === state) return; + this.#state = state; + this.#emitter.emit('state', state); + } + + #send(message: GameClientMessage): void { + const socket = this.#attempt?.socket; + if (socket === undefined) return; + try { + socket.send(encodeClientMessage(message)); + } catch { + // A failing send surfaces as a close; reconnect logic handles it. + } + } + + async #open(mode: 'fresh' | 'resume'): Promise { + let ticket = ''; + if (mode === 'fresh') { + try { + if (this.#initialTicket !== undefined) { + ticket = this.#initialTicket; + this.#initialTicket = undefined; + } else { + ticket = await this.#options.ticket({ + zoneId: this.zoneId, + role: this.#options.role ?? 'player', + reason: this.#welcomes === 0 ? 'join' : 'rejoin' + }); + } + } catch (error) { + if (this.#state === 'closed') return; + this.#attemptFailed(error); + return; + } + if (this.#state === 'closed') return; + } + const token = mode === 'resume' ? this.#reconnectToken : ''; + let socket: GameSocket; + try { + socket = this.#socketFactory(this.url); + } catch (error) { + this.#attemptFailed(error); + return; + } + const attempt: Attempt = { socket, mode, welcomed: false }; + this.#attempt = attempt; + try { + socket.binaryType = 'arraybuffer'; + } catch { + // Some fakes expose a read-only binaryType. + } + socket.onopen = () => { + if (this.#attempt !== attempt) return; + this.#send({ + type: 'Hello', + protocolVersion: GAME_PROTOCOL_VERSION, + contentVersion: this.#options.contentVersion ?? '', + capabilities: this.#options.capabilities ?? 0, + ticket, + reconnectToken: token + }); + }; + socket.onmessage = (event) => { + if (this.#attempt !== attempt) return; + const bytes = toBytes(event.data); + if (bytes === undefined) return; + this.#receive(attempt, bytes); + }; + socket.onerror = () => undefined; + socket.onclose = (event) => { + if (this.#attempt !== attempt) return; + this.#attempt = undefined; + this.#onSocketClosed(attempt, event?.code, event?.reason); + }; + } + + #receive(attempt: Attempt, bytes: Uint8Array): void { + let message: GameServerMessage; + try { + message = this.mirror.apply(bytes); + } catch (error) { + // Deltas are relative to everything sent before: after a decode + // failure the mirror is unusable. Drop and resynchronize. + this.#emitter.emit('protocolError', error); + attempt.socket.close(1002, 'protocol error'); + return; + } + switch (message.type) { + case 'Welcome': + this.#onWelcome(attempt, message); + break; + case 'Delta': + this.#emitter.emit('delta', message); + break; + case 'Event': + this.#emitter.emit('event', message); + break; + case 'Pong': { + const sample = this.clock.observe( + message.clientTime, + message.serverTime, + this.#scheduler.now() + ); + if (sample !== undefined) { + this.#emitter.emit('pong', { + rtt: this.clock.rtt, + offset: this.clock.offset, + jitter: this.clock.jitter + }); + } + break; + } + case 'Freeze': + this.#frozen = true; + this.#emitter.emit('freeze', message); + break; + case 'Resume': + this.#frozen = false; + this.#emitter.emit('resume', message); + break; + case 'Handoff': + this.#terminal = { reason: 'handoff' }; + this.#emitter.emit('handoff', message); + break; + case 'Kick': + this.#terminal = { reason: 'kick', code: message.code, message: message.message }; + this.#emitter.emit('kick', message); + break; + case 'Error': + this.#onError(attempt, message); + break; + } + } + + #onWelcome(attempt: Attempt, welcome: WelcomeMessage): void { + const reconnected = this.#welcomes > 0; + this.#welcomes += 1; + attempt.welcomed = true; + this.#failedAttempts = 0; + this.#disconnectedAt = undefined; + this.#reconnectToken = welcome.reconnectToken; + this.#sessionId = welcome.sessionId; + this.#seq = 0; + this.#frozen = false; + this.clock.reset(); + this.clock.seed(welcome.serverTime, this.#scheduler.now()); + this.#setState('open'); + this.#startPing(); + this.#emitter.emit('welcome', welcome, { resumed: attempt.mode === 'resume', reconnected }); + const waiters = this.#connectWaiters; + this.#connectWaiters = []; + for (const waiter of waiters) waiter.resolve(welcome); + } + + #onError(attempt: Attempt, error: ErrorMessage): void { + this.#emitter.emit('error', error); + if (attempt.welcomed) return; // post-join errors are advisory (§6.3) + if (attempt.mode === 'resume' && error.code === GameErrorCode.RECONNECT_FAILED) { + // Grace window elapsed or token unknown: the server closes; the + // close handler falls back to a fresh ticket. + this.#reconnectToken = ''; + return; + } + this.#terminal = { reason: 'rejected', code: error.code, message: error.message }; + } + + #onSocketClosed(attempt: Attempt, code?: number, reason?: string): void { + this.#stopPing(); + if (this.#state === 'closed') return; + this.#emitter.emit('disconnect', { code, reason }); + if (this.#terminal !== undefined) { + this.#finish(this.#terminal); + return; + } + if (attempt.welcomed) { + this.#disconnectedAt = this.#scheduler.now(); + this.#failedAttempts = 0; + } + if (this.#welcomes === 0 && this.#reconnect === undefined) { + this.#finish({ reason: 'connect-failed', code, message: reason }); + return; + } + this.#attemptFailed(new Error(`socket closed (${code ?? 'no code'})`), attempt.welcomed); + } + + #attemptFailed(error: unknown, justDropped = false): void { + if (this.#state === 'closed') return; + if (this.#reconnect === undefined) { + this.#finish({ + reason: this.#welcomes === 0 ? 'connect-failed' : 'reconnect-exhausted', + message: String(error) + }); + return; + } + if (!justDropped) this.#failedAttempts += 1; + if (this.#failedAttempts >= this.#reconnect.maxAttempts) { + this.#finish({ + reason: this.#welcomes === 0 ? 'connect-failed' : 'reconnect-exhausted', + message: String(error) + }); + return; + } + this.#setState(this.#welcomes === 0 ? 'connecting' : 'reconnecting'); + const delay = justDropped ? 0 : this.#reconnect.backoffMs(this.#failedAttempts); + this.#retryTimer = this.#scheduler.setTimeout(() => { + this.#retryTimer = undefined; + if (this.#state === 'closed') return; + const withinGrace = + this.#reconnectToken !== '' && + this.#disconnectedAt !== undefined && + this.#scheduler.now() - this.#disconnectedAt < this.#reconnect!.graceMs; + void this.#open(withinGrace ? 'resume' : 'fresh'); + }, delay); + } + + #startPing(): void { + this.#stopPing(); + this.ping(); + const tick = () => { + this.#pingTimer = this.#scheduler.setTimeout(() => { + if (this.#state !== 'open') return; + this.ping(); + tick(); + }, this.#pingIntervalMs); + }; + tick(); + } + + #stopPing(): void { + if (this.#pingTimer !== undefined) { + this.#scheduler.clearTimeout(this.#pingTimer); + this.#pingTimer = undefined; + } + } + + #finish(info: GameCloseInfo): void { + if (this.#state === 'closed') return; + this.#stopPing(); + if (this.#retryTimer !== undefined) { + this.#scheduler.clearTimeout(this.#retryTimer); + this.#retryTimer = undefined; + } + const attempt = this.#attempt; + this.#attempt = undefined; + if (attempt !== undefined) { + try { + attempt.socket.close(1000, info.reason); + } catch { + // already closed + } + } + this.#setState('closed'); + const waiters = this.#connectWaiters; + this.#connectWaiters = []; + const failure = new GameConnectionClosedError(this.zoneId, info); + for (const waiter of waiters) waiter.reject(failure); + this.#emitter.emit('close', info); + } +} + +/** Rejection of `connect()` when the connection closed before a Welcome. */ +export class GameConnectionClosedError extends Error { + readonly info: GameCloseInfo; + constructor(zoneId: string, info: GameCloseInfo) { + super( + `game connection to ${zoneId} closed: ${info.reason}${ + info.message === undefined ? '' : ` (${info.message})` + }` + ); + this.name = 'GameConnectionClosedError'; + this.info = info; + } +} + +function toBytes(data: unknown): Uint8Array | undefined { + if (data instanceof Uint8Array) return data; + if (data instanceof ArrayBuffer) return new Uint8Array(data); + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + } + return undefined; // text frames are not part of the protocol +} diff --git a/js/src/game/emitter.ts b/js/src/game/emitter.ts new file mode 100644 index 000000000..c82b13c21 --- /dev/null +++ b/js/src/game/emitter.ts @@ -0,0 +1,53 @@ +type AnyListener = (...args: unknown[]) => void; + +/** Tiny typed event emitter; listener errors never break the network loop. */ +export class Emitter> { + readonly #listeners = new Map>(); + readonly #onListenerError: (error: unknown) => void; + + constructor(onListenerError?: (error: unknown) => void) { + this.#onListenerError = + onListenerError ?? + ((error) => { + queueMicrotask(() => { + throw error; + }); + }); + } + + on(type: K, listener: (...args: TEvents[K]) => void): () => void { + let set = this.#listeners.get(type); + if (set === undefined) { + set = new Set(); + this.#listeners.set(type, set); + } + set.add(listener as unknown as AnyListener); + return () => { + set.delete(listener as unknown as AnyListener); + }; + } + + once(type: K, listener: (...args: TEvents[K]) => void): () => void { + const off = this.on(type, (...args) => { + off(); + listener(...args); + }); + return off; + } + + emit(type: K, ...args: TEvents[K]): void { + const set = this.#listeners.get(type); + if (set === undefined) return; + for (const listener of [...set]) { + try { + (listener as unknown as (...a: TEvents[K]) => void)(...args); + } catch (error) { + this.#onListenerError(error); + } + } + } + + clear(): void { + this.#listeners.clear(); + } +} diff --git a/js/src/game/index.ts b/js/src/game/index.ts new file mode 100644 index 000000000..ed248fbe1 --- /dev/null +++ b/js/src/game/index.ts @@ -0,0 +1,121 @@ +/** + * Browser client SDK for `distributed_game` authoritative zones. + * + * - Codec: `PROTOCOL.md` v1 byte-exact (golden-fixture tested). + * - `GameConnection`: one zone WebSocket — handshake, reconnect, clock sync. + * - `EntityReplica`: schema-driven entity store with interpolation buffers. + * - `Predictor`: client prediction + per-field reconciliation policies. + * - `GameClient`: authority + observer zones, merged render, handoff. + */ +export { + MAX_BLOB_LEN, + GameDecodeError, + WireReader, + WireWriter, + frameStream, + unframeStream, + toHex, + fromHex, + type GameDecodeErrorCode +} from './wire.js'; +export { + MAX_FIELDS, + TAU, + canonicalizeField, + decodeField, + decodeSchema, + defineGameSchema, + dequantizeAngle, + dequantizeLinear, + encodeField, + encodeSchema, + quantizeAngle, + quantizeLinear, + type FieldTypeName, + type FieldValue, + type GameFieldDef, + type GameKindDef, + type GameSchema +} from './schema.js'; +export { + GAME_PROTOCOL_VERSION, + GameClientMirror, + GameErrorCode, + GameKickCode, + GameMessageTag, + decodeClientMessage, + decodeServerMessage, + encodeClientMessage, + encodeServerMessage, + maskHas, + type DeltaMessage, + type EntityCreate, + type EntityKinds, + type EntityUpdate, + type ErrorMessage, + type EventMessage, + type FreezeMessage, + type GameClientMessage, + type GameRole, + type GameServerMessage, + type HandoffMessage, + type HelloMessage, + type InputMessage, + type KickMessage, + type LeaveMessage, + type MirrorEntity, + type NoticeFields, + type PingMessage, + type PongMessage, + type ResumeMessage, + type WelcomeMessage +} from './messages.js'; +export { ClockSync, type ClockSample, type ClockSyncOptions } from './clock.js'; +export { + GameConnection, + GameConnectionClosedError, + defaultScheduler, + type GameCloseInfo, + type GameCloseReason, + type GameConnectionEvents, + type GameConnectionOptions, + type GameConnectionState, + type GameReconnectOptions, + type GameScheduler, + type GameSocket, + type GameSocketFactory, + type GameTicketRequest, + type GameTicketSource, + type GameWelcomeInfo +} from './connection.js'; +export { + EntityReplica, + angleDelta, + defaultInterpolationMode, + interpolateValue, + wrapAngle, + type EntityFields, + type EntityReplicaOptions, + type InterpolationMode, + type InterpolationPolicy, + type ReplicaEntity +} from './replica.js'; +export { + Predictor, + type Correction, + type CorrectionPolicies, + type CorrectionPolicy, + type PendingInput, + type PredictFn, + type PredictorOptions +} from './prediction.js'; +export { + GameClient, + type ControlledEntityResolver, + type GameClientEvents, + type GameClientOptions, + type GamePredictionOptions, + type GameZoneView, + type RenderedEntity, + type ZoneRole +} from './client.js'; diff --git a/js/src/game/messages.ts b/js/src/game/messages.ts new file mode 100644 index 000000000..d05628d12 --- /dev/null +++ b/js/src/game/messages.ts @@ -0,0 +1,448 @@ +/** + * Message codecs (`PROTOCOL.md` §6–§7) and the reference client mirror + * (§7.2, matching Rust `protocol::ClientMirror`). + */ +import { + decodeField, + decodeSchema, + encodeField, + encodeSchema, + type FieldValue, + type GameSchema +} from './schema.js'; +import { GameDecodeError, WireReader, WireWriter } from './wire.js'; + +/** Wire protocol version spoken by this client. */ +export const GAME_PROTOCOL_VERSION = 1; + +/** Message type bytes (§6.1). */ +export const GameMessageTag = Object.freeze({ + HELLO: 0x01, + INPUT: 0x02, + PING: 0x03, + LEAVE: 0x04, + WELCOME: 0x80, + DELTA: 0x81, + EVENT: 0x82, + PONG: 0x83, + FREEZE: 0x84, + RESUME: 0x85, + HANDOFF: 0x86, + KICK: 0x87, + ERROR: 0x88 +}); + +/** Kick codes. */ +export const GameKickCode = Object.freeze({ + BY_ZONE: 1, + REPLACED: 2, + SHUTDOWN: 3, + RATE_LIMITED: 4, + ZONE_DISPOSED: 5, + SLOW_CONSUMER: 6 +}); + +/** Error codes. */ +export const GameErrorCode = Object.freeze({ + BAD_MESSAGE: 1, + UNAUTHORIZED: 2, + REJECTED: 3, + ZONE_FULL: 4, + VERSION_MISMATCH: 5, + RATE_LIMITED: 6, + NOT_FOUND: 7, + RECONNECT_FAILED: 8 +}); + +export type HelloMessage = Readonly<{ + type: 'Hello'; + protocolVersion: number; + contentVersion: string; + capabilities: number; + ticket: string; + reconnectToken: string; +}>; +export type InputMessage = Readonly<{ + type: 'Input'; + seq: number; + clientTick: number; + payload: Uint8Array; +}>; +export type PingMessage = Readonly<{ type: 'Ping'; clientTime: number }>; +export type LeaveMessage = Readonly<{ type: 'Leave' }>; +export type GameClientMessage = HelloMessage | InputMessage | PingMessage | LeaveMessage; + +export type GameRole = 'player' | 'observer'; + +export type WelcomeMessage = Readonly<{ + type: 'Welcome'; + sessionId: string; + zoneId: string; + role: GameRole; + tickRate: number; + patchRate: number; + serverTick: number; + serverTime: number; + reconnectToken: string; + contentVersion: string; + schema: GameSchema; +}>; +export type EntityCreate = Readonly<{ + id: number; + kind: number; + fields: readonly FieldValue[]; +}>; +export type EntityUpdate = Readonly<{ + id: number; + mask: number; + fields: readonly FieldValue[]; +}>; +export type DeltaMessage = Readonly<{ + type: 'Delta'; + serverTick: number; + ackSeq: number; + removes: readonly number[]; + creates: readonly EntityCreate[]; + updates: readonly EntityUpdate[]; +}>; +export type EventMessage = Readonly<{ type: 'Event'; typeId: number; payload: Uint8Array }>; +export type PongMessage = Readonly<{ type: 'Pong'; clientTime: number; serverTime: number }>; +export type NoticeFields = Readonly<{ reason: string; version: string; notes: string }>; +export type FreezeMessage = NoticeFields & Readonly<{ type: 'Freeze' }>; +export type ResumeMessage = NoticeFields & Readonly<{ type: 'Resume' }>; +export type HandoffMessage = Readonly<{ + type: 'Handoff'; + targetZone: string; + transferTicket: string; +}>; +export type KickMessage = Readonly<{ type: 'Kick'; code: number; message: string }>; +export type ErrorMessage = Readonly<{ type: 'Error'; code: number; message: string }>; +export type GameServerMessage = + | WelcomeMessage + | DeltaMessage + | EventMessage + | PongMessage + | FreezeMessage + | ResumeMessage + | HandoffMessage + | KickMessage + | ErrorMessage; + +/** What the Delta codec needs: the Welcome schema and the kind of each known id. */ +export type EntityKinds = Readonly<{ + schema: GameSchema | undefined; + kindOf(id: number): number | undefined; +}>; + +const NO_KINDS: EntityKinds = { schema: undefined, kindOf: () => undefined }; + +/** Encode one client message (one WebSocket binary frame). */ +export function encodeClientMessage(message: GameClientMessage): Uint8Array { + const w = new WireWriter(); + switch (message.type) { + case 'Hello': + w.u8(GameMessageTag.HELLO) + .varuint(message.protocolVersion) + .string(message.contentVersion) + .varuint(message.capabilities) + .string(message.ticket) + .string(message.reconnectToken); + break; + case 'Input': + w.u8(GameMessageTag.INPUT) + .varuint(message.seq) + .varuint(message.clientTick) + .bytes(message.payload); + break; + case 'Ping': + w.u8(GameMessageTag.PING).f64(message.clientTime); + break; + case 'Leave': + w.u8(GameMessageTag.LEAVE); + break; + } + return w.finish(); +} + +/** Decode one client message. */ +export function decodeClientMessage(bytes: Uint8Array): GameClientMessage { + const r = new WireReader(bytes); + let message: GameClientMessage; + const tag = r.u8(); + switch (tag) { + case GameMessageTag.HELLO: + message = { + type: 'Hello', + protocolVersion: r.varuint(), + contentVersion: r.string(), + capabilities: r.varuint(), + ticket: r.string(), + reconnectToken: r.string() + }; + break; + case GameMessageTag.INPUT: + message = { type: 'Input', seq: r.varuint(), clientTick: r.varuint(), payload: r.bytes() }; + break; + case GameMessageTag.PING: + message = { type: 'Ping', clientTime: r.f64() }; + break; + case GameMessageTag.LEAVE: + message = { type: 'Leave' }; + break; + default: + throw new GameDecodeError('UNKNOWN_MESSAGE', `message type 0x${tag.toString(16)}`); + } + r.finish(); + return message; +} + +/** Encode one server message (used by test servers and tooling). */ +export function encodeServerMessage( + message: GameServerMessage, + kinds: EntityKinds = NO_KINDS +): Uint8Array { + const w = new WireWriter(); + switch (message.type) { + case 'Welcome': + w.u8(GameMessageTag.WELCOME) + .string(message.sessionId) + .string(message.zoneId) + .u8(message.role === 'player' ? 0 : 1) + .varuint(message.tickRate) + .varuint(message.patchRate) + .varuint(message.serverTick) + .f64(message.serverTime) + .string(message.reconnectToken) + .string(message.contentVersion); + encodeSchema(w, message.schema); + break; + case 'Delta': + encodeDelta(w, message, kinds); + break; + case 'Event': + w.u8(GameMessageTag.EVENT).varuint(message.typeId).bytes(message.payload); + break; + case 'Pong': + w.u8(GameMessageTag.PONG).f64(message.clientTime).f64(message.serverTime); + break; + case 'Freeze': + case 'Resume': + w.u8(message.type === 'Freeze' ? GameMessageTag.FREEZE : GameMessageTag.RESUME) + .string(message.reason) + .string(message.version) + .string(message.notes); + break; + case 'Handoff': + w.u8(GameMessageTag.HANDOFF).string(message.targetZone).string(message.transferTicket); + break; + case 'Kick': + w.u8(GameMessageTag.KICK).varuint(message.code).string(message.message); + break; + case 'Error': + w.u8(GameMessageTag.ERROR).varuint(message.code).string(message.message); + break; + } + return w.finish(); +} + +/** Decode one server message. Deltas need `kinds` (schema + known ids). */ +export function decodeServerMessage( + bytes: Uint8Array, + kinds: EntityKinds = NO_KINDS +): GameServerMessage { + const r = new WireReader(bytes); + let message: GameServerMessage; + const tag = r.u8(); + switch (tag) { + case GameMessageTag.WELCOME: { + const sessionId = r.string(); + const zoneId = r.string(); + const roleByte = r.u8(); + if (roleByte > 1) throw new GameDecodeError('INVALID', 'role'); + message = { + type: 'Welcome', + sessionId, + zoneId, + role: roleByte === 0 ? 'player' : 'observer', + tickRate: r.varuint(), + patchRate: r.varuint(), + serverTick: r.varuint(), + serverTime: r.f64(), + reconnectToken: r.string(), + contentVersion: r.string(), + schema: decodeSchema(r) + }; + break; + } + case GameMessageTag.DELTA: + message = decodeDelta(r, kinds); + break; + case GameMessageTag.EVENT: + message = { type: 'Event', typeId: r.varuint(), payload: r.bytes() }; + break; + case GameMessageTag.PONG: + message = { type: 'Pong', clientTime: r.f64(), serverTime: r.f64() }; + break; + case GameMessageTag.FREEZE: + case GameMessageTag.RESUME: + message = { + type: tag === GameMessageTag.FREEZE ? 'Freeze' : 'Resume', + reason: r.string(), + version: r.string(), + notes: r.string() + }; + break; + case GameMessageTag.HANDOFF: + message = { type: 'Handoff', targetZone: r.string(), transferTicket: r.string() }; + break; + case GameMessageTag.KICK: + message = { type: 'Kick', code: r.varuint(), message: r.string() }; + break; + case GameMessageTag.ERROR: + message = { type: 'Error', code: r.varuint(), message: r.string() }; + break; + default: + throw new GameDecodeError('UNKNOWN_MESSAGE', `message type 0x${tag.toString(16)}`); + } + r.finish(); + return message; +} + +function requireSchema(kinds: EntityKinds): GameSchema { + if (kinds.schema === undefined) throw new GameDecodeError('INVALID', 'delta needs a schema'); + return kinds.schema; +} + +function kindLookup(id: number, created: Map, kinds: EntityKinds): number { + const kind = created.get(id) ?? kinds.kindOf(id); + if (kind === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${id}`); + return kind; +} + +function encodeDelta(w: WireWriter, d: DeltaMessage, kinds: EntityKinds): void { + const schema = requireSchema(kinds); + w.u8(GameMessageTag.DELTA).varuint(d.serverTick).varuint(d.ackSeq); + w.varuint(d.removes.length); + for (const id of d.removes) w.varuint(id); + const created = new Map(); + w.varuint(d.creates.length); + for (const c of d.creates) { + const kind = schema.byId.get(c.kind); + if (kind === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${c.id}`); + if (kind.fields.length !== c.fields.length) { + throw new GameDecodeError('INVALID', 'create must carry every field'); + } + w.varuint(c.id).varuint(c.kind); + kind.fields.forEach((def, i) => encodeField(w, def, c.fields[i])); + created.set(c.id, c.kind); + } + w.varuint(d.updates.length); + for (const u of d.updates) { + const kind = schema.byId.get(kindLookup(u.id, created, kinds)); + if (kind === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${u.id}`); + w.varuint(u.id).varuint(u.mask); + let next = 0; + kind.fields.forEach((def, i) => { + if (maskHas(u.mask, i)) { + if (next >= u.fields.length) { + throw new GameDecodeError('INVALID', 'mask/field count mismatch'); + } + encodeField(w, def, u.fields[next++]); + } + }); + } +} + +/** Bit `i` of a u32 mask (safe for bit 31). */ +export function maskHas(mask: number, index: number): boolean { + return ((mask >>> index) & 1) === 1; +} + +function decodeDelta(r: WireReader, kinds: EntityKinds): DeltaMessage { + const schema = requireSchema(kinds); + const serverTick = r.varuint(); + const ackSeq = r.varuint(); + const removes: number[] = []; + for (let n = r.varuint(); n > 0; n -= 1) removes.push(r.varuint()); + const created = new Map(); + const creates: EntityCreate[] = []; + for (let n = r.varuint(); n > 0; n -= 1) { + const id = r.varuint(); + const kindId = r.varuint(); + if (kindId > 0xffff) throw new GameDecodeError('INVALID', 'kind'); + const kind = schema.byId.get(kindId); + if (kind === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${id}`); + const fields = kind.fields.map((def) => decodeField(r, def)); + created.set(id, kindId); + creates.push({ id, kind: kindId, fields }); + } + const updates: EntityUpdate[] = []; + for (let n = r.varuint(); n > 0; n -= 1) { + const id = r.varuint(); + const kind = schema.byId.get(kindLookup(id, created, kinds)); + if (kind === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${id}`); + const mask = r.varuint(); + if (kind.fields.length < 32 && Math.floor(mask / 2 ** kind.fields.length) !== 0) { + throw new GameDecodeError('INVALID', 'mask names a field the kind lacks'); + } + const fields: FieldValue[] = []; + kind.fields.forEach((def, i) => { + if (maskHas(mask, i)) fields.push(decodeField(r, def)); + }); + updates.push({ id, mask, fields }); + } + return { type: 'Delta', serverTick, ackSeq, removes, creates, updates }; +} + +export type MirrorEntity = { kind: number; fields: FieldValue[] }; + +/** + * Normative client-side state (§7.2): decodes frames and applies Deltas. + * Mirrors Rust `ClientMirror`; higher layers (replica, prediction) build on + * the decoded messages it returns. + */ +export class GameClientMirror implements EntityKinds { + welcome: WelcomeMessage | undefined; + readonly entities = new Map(); + serverTick = 0; + ackSeq = 0; + + get schema(): GameSchema | undefined { + return this.welcome?.schema; + } + + kindOf(id: number): number | undefined { + return this.entities.get(id)?.kind; + } + + /** Decode a frame and apply it. A Welcome resets all entities. */ + apply(frame: Uint8Array): GameServerMessage { + const message = decodeServerMessage(frame, this); + this.applyDecoded(message); + return message; + } + + applyDecoded(message: GameServerMessage): void { + if (message.type === 'Welcome') { + this.welcome = message; + this.entities.clear(); + this.serverTick = message.serverTick; + this.ackSeq = 0; + } else if (message.type === 'Delta') { + for (const id of message.removes) this.entities.delete(id); + for (const c of message.creates) { + this.entities.set(c.id, { kind: c.kind, fields: [...c.fields] }); + } + for (const u of message.updates) { + const entity = this.entities.get(u.id); + if (entity === undefined) throw new GameDecodeError('UNKNOWN_ENTITY', `entity ${u.id}`); + let next = 0; + for (let i = 0; i < entity.fields.length; i += 1) { + if (maskHas(u.mask, i)) entity.fields[i] = u.fields[next++]; + } + } + this.serverTick = message.serverTick; + this.ackSeq = message.ackSeq; + } + } +} diff --git a/js/src/game/prediction.ts b/js/src/game/prediction.ts new file mode 100644 index 000000000..5f2b29821 --- /dev/null +++ b/js/src/game/prediction.ts @@ -0,0 +1,272 @@ +/** + * Client-side prediction and server reconciliation for the locally + * controlled entity (`PROTOCOL.md` §7.1 `ack_seq`). + * + * Every sent input is applied immediately through the app's `predict` and + * kept until the server acknowledges it. On each authoritative Delta the + * predictor rebases: authoritative state + replay of inputs with + * `seq > ack_seq`. Any difference between what was displayed and the rebased + * prediction is resolved per field: + * + * - `ease` – adopt the rebased value but carry the visual error as an + * offset that decays linearly to zero over `durationMs`. + * - `snap` – adopt the rebased value immediately. + * - `replace` – the field is server-owned: show the authoritative value as + * is, never replaying inputs over it (hp, score, …). + */ +import { angleDelta, wrapAngle, type EntityFields } from './replica.js'; +import { canonicalizeField, type FieldValue, type GameKindDef } from './schema.js'; + +export type CorrectionPolicy = + | Readonly<{ mode: 'ease'; durationMs?: number }> + | Readonly<{ mode: 'snap' }> + | Readonly<{ mode: 'replace' }>; + +/** Per kind name → per field name → policy. */ +export type CorrectionPolicies = Readonly< + Record>> +>; + +export type PredictFn = ( + state: EntityFields, + input: TInput, + dtMs: number +) => Readonly>; + +export type PredictorOptions = Readonly<{ + predict: PredictFn; + corrections?: CorrectionPolicies; + /** Policy for fields not listed. Default `{ mode: 'ease', durationMs: 100 }`. */ + defaultCorrection?: CorrectionPolicy; + /** Inputs kept unacknowledged before the oldest is dropped. Default 256. */ + maxPending?: number; + /** + * Round every predicted step through the field's wire quantization. + * Enable only when the server simulation itself canonicalizes state each + * tick (`FieldType::canonicalize`); otherwise the server keeps full + * precision and per-step rounding would drift. Default false. + */ + canonicalize?: boolean; + /** Differences at or below this are ignored (no correction). Default 1e-6. */ + epsilon?: number; +}>; + +export type PendingInput = Readonly<{ + seq: number; + input: TInput; + dtMs: number; +}>; + +/** Divergence observed by one reconciliation (predicted − rebased). */ +export type Correction = Readonly<{ + ackSeq: number; + replayed: number; + /** Per numeric field: previous prediction minus rebased prediction. */ + errors: Readonly>; + /** Fields whose prediction diverged and how each was resolved. */ + resolved: Readonly>; +}>; + +type Offset = { value: number; start: number; durationMs: number; angle: boolean }; + +const DEFAULT_CORRECTION: CorrectionPolicy = Object.freeze({ mode: 'ease', durationMs: 100 }); + +export class Predictor { + readonly #options: PredictorOptions; + #kind: GameKindDef | undefined; + #entityId: number | undefined; + #pending: PendingInput[] = []; + #authoritative: Record | undefined; + #predicted: Record | undefined; + #offsets = new Map(); + #lastAck = 0; + + constructor(options: PredictorOptions) { + this.#options = options; + } + + get entityId(): number | undefined { + return this.#entityId; + } + + get kind(): GameKindDef | undefined { + return this.#kind; + } + + get pending(): readonly PendingInput[] { + return this.#pending; + } + + get lastAck(): number { + return this.#lastAck; + } + + /** True when an entity is bound and its authoritative state is known. */ + get active(): boolean { + return this.#predicted !== undefined; + } + + /** + * Bind (or rebind) the controlled entity. Clears pending inputs: they + * belonged to the previous binding or session. + */ + bind(entityId: number | undefined, kind?: GameKindDef, authoritative?: EntityFields): void { + this.#entityId = entityId; + this.#kind = entityId === undefined ? undefined : kind; + this.#pending = []; + this.#offsets.clear(); + this.#lastAck = 0; + this.#authoritative = authoritative === undefined ? undefined : { ...authoritative }; + this.#predicted = authoritative === undefined ? undefined : { ...authoritative }; + } + + /** New session (Welcome): sequence numbers restart, pending inputs are void. */ + resetSession(): void { + this.#pending = []; + this.#lastAck = 0; + } + + /** + * Record an input that was sent with `seq` and apply it to the + * prediction. Inputs recorded before authoritative state is known are + * kept and replayed once it arrives. + */ + record(seq: number, input: TInput, dtMs: number): void { + this.#pending.push({ seq, input, dtMs }); + const max = this.#options.maxPending ?? 256; + if (this.#pending.length > max) this.#pending.splice(0, this.#pending.length - max); + if (this.#predicted !== undefined) { + this.#predicted = this.#step(this.#predicted, input, dtMs); + } + } + + /** + * Rebase onto authoritative state after a Delta. `authoritative` is the + * entity's latest server fields (or undefined if it is not visible). + */ + reconcile(ackSeq: number, authoritative: EntityFields | undefined, now: number): Correction | undefined { + if (ackSeq > this.#lastAck) this.#lastAck = ackSeq; + this.#pending = this.#pending.filter((p) => p.seq > this.#lastAck); + if (authoritative === undefined || this.#kind === undefined) return undefined; + const before = this.#predicted === undefined ? undefined : this.current(now); + const previous = this.#predicted; + this.#authoritative = { ...authoritative }; + + let rebased: Record = { ...authoritative }; + for (const p of this.#pending) rebased = this.#step(rebased, p.input, p.dtMs); + + const errors: Record = {}; + const resolved: Record = {}; + const epsilon = this.#options.epsilon ?? 1e-6; + for (const field of this.#kind.fields) { + const name = field.name; + const policy = this.#policy(name); + const angle = field.type === 'angle'; + if (policy.mode === 'replace') { + rebased[name] = authoritative[name]; + this.#offsets.delete(name); + } + if (previous === undefined || before === undefined) continue; + const oldValue = previous[name]; + const newValue = rebased[name]; + if (typeof oldValue === 'number' && typeof newValue === 'number') { + const error = angle ? -angleDelta(oldValue, newValue) : oldValue - newValue; + if (Math.abs(error) > epsilon) { + errors[name] = error; + resolved[name] = policy.mode; + } + if (policy.mode === 'ease') { + const shown = before[name]; + const visual = + typeof shown === 'number' + ? angle + ? -angleDelta(shown, newValue) + : shown - newValue + : 0; + const duration = policy.durationMs ?? 100; + if (Math.abs(visual) > epsilon && duration > 0) { + this.#offsets.set(name, { value: visual, start: now, durationMs: duration, angle }); + } else { + this.#offsets.delete(name); + } + } else { + this.#offsets.delete(name); + } + } else if (!sameValue(oldValue, newValue)) { + resolved[name] = policy.mode === 'ease' ? 'snap' : policy.mode; + } + } + this.#predicted = rebased; + return { ackSeq: this.#lastAck, replayed: this.#pending.length, errors, resolved }; + } + + /** Latest authoritative fields seen for the controlled entity. */ + authoritative(): EntityFields | undefined { + return this.#authoritative; + } + + /** Prediction without visual smoothing. */ + predicted(): EntityFields | undefined { + return this.#predicted; + } + + /** Prediction with decaying correction offsets applied (what to render). */ + current(now: number): EntityFields | undefined { + const predicted = this.#predicted; + if (predicted === undefined) return undefined; + if (this.#offsets.size === 0) return predicted; + const out: Record = { ...predicted }; + for (const [name, offset] of this.#offsets) { + const k = 1 - (now - offset.start) / offset.durationMs; + const value = predicted[name]; + if (k <= 0 || typeof value !== 'number') { + this.#offsets.delete(name); + continue; + } + const shifted = value + offset.value * Math.min(1, k); + out[name] = offset.angle ? wrapAngle(shifted) : shifted; + } + return out; + } + + /** Remaining visual correction per field (diagnostics/tests). */ + visualError(now: number): Readonly> { + const out: Record = {}; + for (const [name, offset] of this.#offsets) { + const k = 1 - (now - offset.start) / offset.durationMs; + if (k > 0) out[name] = offset.value * Math.min(1, k); + } + return out; + } + + #policy(field: string): CorrectionPolicy { + const kindName = this.#kind?.name ?? ''; + return ( + this.#options.corrections?.[kindName]?.[field] ?? + this.#options.defaultCorrection ?? + DEFAULT_CORRECTION + ); + } + + #step(state: Record, input: TInput, dtMs: number): Record { + const next = { ...state, ...this.#options.predict(state, input, dtMs) }; + const kind = this.#kind; + if (kind !== undefined) { + for (const field of kind.fields) { + if (this.#policy(field.name).mode === 'replace') { + next[field.name] = state[field.name]; + } else if (this.#options.canonicalize ?? false) { + next[field.name] = canonicalizeField(field, next[field.name]); + } + } + } + return next; + } +} + +function sameValue(a: FieldValue | undefined, b: FieldValue | undefined): boolean { + if (a instanceof Uint8Array && b instanceof Uint8Array) { + return a.length === b.length && a.every((v, i) => v === b[i]); + } + return a === b; +} diff --git a/js/src/game/replica.ts b/js/src/game/replica.ts new file mode 100644 index 000000000..d5037c413 --- /dev/null +++ b/js/src/game/replica.ts @@ -0,0 +1,324 @@ +/** + * Generic entity replica driven by Deltas, with per-entity snapshot history + * for interpolated rendering at `serverNow - interpolationDelay`. + * + * Entities are decoded with the Welcome schema; no generated code. Each + * entity keeps a short time-ordered snapshot buffer on its zone's server + * timeline (tick → time via the Welcome anchor). Sampling between two + * snapshots interpolates per field: `lerp` (linear), `angle` (shortest arc, + * wrapped to [0, 2π)) or `step` (hold the older value). + */ +import { maskHas, type DeltaMessage } from './messages.js'; +import { TAU, type FieldValue, type GameKindDef, type GameSchema } from './schema.js'; + +export type InterpolationMode = 'lerp' | 'angle' | 'step'; + +/** Per kind name → per field name → mode. Unlisted fields use type defaults. */ +export type InterpolationPolicy = Readonly< + Record>> +>; + +export type EntityReplicaOptions = Readonly<{ + interpolation?: InterpolationPolicy; + /** Snapshot history kept per entity (server ms). Default 1000. */ + historyMs?: number; + /** Hard cap on snapshots per entity. Default 64. */ + maxSnapshots?: number; + /** + * After a Welcome (reconnect, authority swap) previously known entities + * stay rendered as stale until re-created or until this much server + * time passed. Default 1000 ms. + */ + staleGraceMs?: number; +}>; + +/** One entity's fields keyed by schema field name. */ +export type EntityFields = Readonly>; + +export type ReplicaEntity = Readonly<{ + id: number; + kind: number; + kindName: string; + fields: EntityFields; + /** Known before the latest Welcome and not yet re-created. */ + stale: boolean; +}>; + +type Snapshot = { time: number; values: FieldValue[] }; + +type Entry = { + id: number; + kind: GameKindDef; + modes: InterpolationMode[]; + snapshots: Snapshot[]; + stale: boolean; + staleSince: number; +}; + +/** Default interpolation for a field type. */ +export function defaultInterpolationMode(type: string): InterpolationMode { + if (type === 'f32' || type === 'quant_f32') return 'lerp'; + if (type === 'angle') return 'angle'; + return 'step'; +} + +/** Shortest signed angular difference `b - a`, in (-π, π]. */ +export function angleDelta(a: number, b: number): number { + let d = (b - a) % TAU; + if (d > Math.PI) d -= TAU; + else if (d <= -Math.PI) d += TAU; + return d; +} + +/** Wrap radians into [0, 2π). */ +export function wrapAngle(a: number): number { + const w = a % TAU; + return w < 0 ? w + TAU : w; +} + +export function interpolateValue( + mode: InterpolationMode, + a: FieldValue, + b: FieldValue, + t: number +): FieldValue { + if (typeof a !== 'number' || typeof b !== 'number' || mode === 'step') return t >= 1 ? b : a; + if (mode === 'angle') return wrapAngle(a + angleDelta(a, b) * t); + return a + (b - a) * t; +} + +export class EntityReplica { + readonly #options: Required> & { + interpolation: InterpolationPolicy; + }; + #schema: GameSchema | undefined; + readonly #entries = new Map(); + #lastDeltaTime: number | undefined; + #serverTick = 0; + #ackSeq = 0; + + constructor(options: EntityReplicaOptions = {}) { + this.#options = { + interpolation: options.interpolation ?? {}, + historyMs: options.historyMs ?? 1000, + maxSnapshots: Math.max(2, options.maxSnapshots ?? 64), + staleGraceMs: options.staleGraceMs ?? 1000 + }; + } + + get schema(): GameSchema | undefined { + return this.#schema; + } + + get serverTick(): number { + return this.#serverTick; + } + + get ackSeq(): number { + return this.#ackSeq; + } + + get size(): number { + return this.#entries.size; + } + + /** + * A Welcome arrived: adopt its schema and mark everything stale. Stale + * entities keep rendering (holding their last value) so a reconnect or + * authority swap does not blank the world; a re-create of the same id + * and kind revives the entity with its history intact. + */ + reset(schema: GameSchema, time: number): void { + this.#schema = schema; + this.#lastDeltaTime = undefined; + this.#ackSeq = 0; + for (const entry of this.#entries.values()) { + const kind = schema.byId.get(entry.kind.id); + if (kind === undefined || !sameKindShape(kind, entry.kind)) { + this.#entries.delete(entry.id); + continue; + } + if (!entry.stale) { + entry.stale = true; + entry.staleSince = time; + } + } + } + + /** Remove every entity. */ + clear(): void { + this.#entries.clear(); + this.#lastDeltaTime = undefined; + } + + /** Apply one decoded Delta stamped with its server time. */ + applyDelta(delta: DeltaMessage, time: number): void { + const schema = this.#schema; + if (schema === undefined) throw new Error('EntityReplica.applyDelta before reset(schema)'); + const previous = this.#lastDeltaTime; + for (const id of delta.removes) { + const entry = this.#entries.get(id); + if (entry !== undefined && !entry.stale) this.#entries.delete(id); + } + for (const create of delta.creates) { + const kind = schema.byId.get(create.kind); + if (kind === undefined) continue; + const existing = this.#entries.get(create.id); + if (existing !== undefined && existing.stale && existing.kind.id === create.kind) { + existing.stale = false; + this.#hold(existing, previous); + this.#push(existing, time, [...create.fields]); + continue; + } + this.#entries.set(create.id, { + id: create.id, + kind, + modes: this.#modes(kind), + snapshots: [{ time, values: [...create.fields] }], + stale: false, + staleSince: 0 + }); + } + for (const update of delta.updates) { + const entry = this.#entries.get(update.id); + if (entry === undefined || entry.stale) continue; + const last = entry.snapshots[entry.snapshots.length - 1]; + const values = [...last.values]; + let next = 0; + for (let i = 0; i < values.length; i += 1) { + if (maskHas(update.mask, i)) values[i] = update.fields[next++]; + } + this.#hold(entry, previous); + this.#push(entry, time, values); + } + for (const entry of this.#entries.values()) { + if (entry.stale && time - entry.staleSince > this.#options.staleGraceMs) { + this.#entries.delete(entry.id); + } + } + this.#lastDeltaTime = time; + this.#serverTick = delta.serverTick; + this.#ackSeq = delta.ackSeq; + } + + /** Drop stale entities whose grace elapsed at server time `time`. */ + pruneStale(time: number, graceMs = this.#options.staleGraceMs): void { + for (const entry of this.#entries.values()) { + if (entry.stale && time - entry.staleSince > graceMs) this.#entries.delete(entry.id); + } + } + + has(id: number): boolean { + const entry = this.#entries.get(id); + return entry !== undefined && !entry.stale; + } + + /** Latest authoritative state of a live entity. */ + get(id: number): ReplicaEntity | undefined { + const entry = this.#entries.get(id); + if (entry === undefined || entry.stale) return undefined; + return view(entry, entry.snapshots[entry.snapshots.length - 1].values); + } + + /** Latest authoritative state of every live (non-stale) entity. */ + entities(): ReplicaEntity[] { + const out: ReplicaEntity[] = []; + for (const entry of this.#entries.values()) { + if (!entry.stale) out.push(view(entry, entry.snapshots[entry.snapshots.length - 1].values)); + } + return out; + } + + /** Interpolated state of one entity at server time `renderTime`. */ + sampleEntity(id: number, renderTime: number): ReplicaEntity | undefined { + const entry = this.#entries.get(id); + return entry === undefined ? undefined : view(entry, sampleEntry(entry, renderTime)); + } + + /** Interpolated state of every entity (stale ones hold their last value). */ + sample(renderTime: number): ReplicaEntity[] { + const out: ReplicaEntity[] = []; + for (const entry of this.#entries.values()) { + out.push(view(entry, sampleEntry(entry, renderTime))); + } + return out; + } + + /** Snapshot times of an entity (diagnostics/tests). */ + history(id: number): readonly { time: number; fields: EntityFields }[] { + const entry = this.#entries.get(id); + if (entry === undefined) return []; + return entry.snapshots.map((s) => ({ time: s.time, fields: fieldsOf(entry.kind, s.values) })); + } + + #modes(kind: GameKindDef): InterpolationMode[] { + const overrides = this.#options.interpolation[kind.name] ?? {}; + return kind.fields.map((f) => overrides[f.name] ?? defaultInterpolationMode(f.type)); + } + + /** + * Unchanged fields are not sent, so an entity absent from the previous + * Delta was still at its last value then. Insert that "hold" sample so + * interpolation does not smear a late change over the quiet interval. + */ + #hold(entry: Entry, previous: number | undefined): void { + if (previous === undefined) return; + const last = entry.snapshots[entry.snapshots.length - 1]; + if (last.time < previous) this.#push(entry, previous, [...last.values]); + } + + #push(entry: Entry, time: number, values: FieldValue[]): void { + const snapshots = entry.snapshots; + const last = snapshots[snapshots.length - 1]; + if (last !== undefined && time <= last.time) { + last.values = values; + } else { + snapshots.push({ time, values }); + } + const horizon = time - this.#options.historyMs; + while ( + snapshots.length > 2 && + (snapshots.length > this.#options.maxSnapshots || snapshots[1].time <= horizon) + ) { + snapshots.shift(); + } + } +} + +function sameKindShape(a: GameKindDef, b: GameKindDef): boolean { + return ( + a.fields.length === b.fields.length && + a.fields.every((f, i) => f.name === b.fields[i].name && f.type === b.fields[i].type) + ); +} + +function sampleEntry(entry: Entry, renderTime: number): FieldValue[] { + const snaps = entry.snapshots; + const last = snaps[snaps.length - 1]; + if (entry.stale || renderTime >= last.time) return last.values; + if (renderTime <= snaps[0].time) return snaps[0].values; + let i = snaps.length - 2; + while (i > 0 && snaps[i].time > renderTime) i -= 1; + const a = snaps[i]; + const b = snaps[i + 1]; + const t = (renderTime - a.time) / (b.time - a.time); + return a.values.map((value, f) => interpolateValue(entry.modes[f], value, b.values[f], t)); +} + +function fieldsOf(kind: GameKindDef, values: readonly FieldValue[]): EntityFields { + const fields: Record = {}; + kind.fields.forEach((f, i) => { + fields[f.name] = values[i]; + }); + return fields; +} + +function view(entry: Entry, values: readonly FieldValue[]): ReplicaEntity { + return { + id: entry.id, + kind: entry.kind.id, + kindName: entry.kind.name, + fields: fieldsOf(entry.kind, values), + stale: entry.stale + }; +} diff --git a/js/src/game/schema.ts b/js/src/game/schema.ts new file mode 100644 index 000000000..a8eeba4dc --- /dev/null +++ b/js/src/game/schema.ts @@ -0,0 +1,333 @@ +/** + * Entity schema, field types and quantization (`PROTOCOL.md` §4–§5). + * + * Quantization math runs in binary64 in exactly the order the spec writes it + * so this client reproduces the Rust server's integers and decoded binary32 + * values bit-for-bit (verified against the golden fixtures). + */ +import { GameDecodeError, type WireReader, type WireWriter } from './wire.js'; + +/** Maximum fields per kind (update masks are 32-bit). */ +export const MAX_FIELDS = 32; + +/** 2π as used by angle quantization. */ +export const TAU = 6.283185307179586; + +export type FieldTypeName = + | 'bool' + | 'u8' + | 'u16' + | 'u32' + | 'i32' + | 'f32' + | 'quant_f32' + | 'angle' + | 'short_str' + | 'bytes'; + +const TYPE_TAGS: readonly FieldTypeName[] = [ + 'bool', + 'u8', + 'u16', + 'u32', + 'i32', + 'f32', + 'quant_f32', + 'angle', + 'short_str', + 'bytes' +]; + +/** One component field. `min`/`max`/`bits` are present for quantized types. */ +export type GameFieldDef = Readonly<{ + name: string; + type: FieldTypeName; + /** `quant_f32` lower bound (a binary32 value). */ + min?: number; + /** `quant_f32` upper bound (a binary32 value). */ + max?: number; + /** `quant_f32` / `angle` precision, 1..=32. */ + bits?: number; +}>; + +export type GameKindDef = Readonly<{ + id: number; + name: string; + fields: readonly GameFieldDef[]; +}>; + +/** Decoded schema from a Welcome. */ +export type GameSchema = Readonly<{ + kinds: readonly GameKindDef[]; + /** Kind lookup by id. */ + byId: ReadonlyMap; +}>; + +/** + * A decoded field value: `boolean` (bool), `number` (integers and floats), + * `string` (short_str) or `Uint8Array` (bytes). + */ +export type FieldValue = boolean | number | string | Uint8Array; + +/** Build a schema (validates ids, field counts and quantization params). */ +export function defineGameSchema(kinds: readonly GameKindDef[]): GameSchema { + const byId = new Map(); + const frozen: GameKindDef[] = []; + for (const kind of kinds) { + if (!Number.isInteger(kind.id) || kind.id < 0 || kind.id > 0xffff) { + throw new GameDecodeError('INVALID', 'kind id > u16'); + } + if (byId.has(kind.id)) throw new GameDecodeError('INVALID', 'duplicate kind id'); + if (kind.fields.length > MAX_FIELDS) { + throw new GameDecodeError('INVALID', 'more than 32 fields'); + } + const fields = kind.fields.map((field) => { + if (!TYPE_TAGS.includes(field.type)) { + throw new GameDecodeError('UNKNOWN_FIELD_TYPE', field.type); + } + if (field.type === 'quant_f32' || field.type === 'angle') checkBits(field.bits); + if (field.type === 'quant_f32') { + return Object.freeze({ + name: field.name, + type: field.type, + min: Math.fround(field.min ?? 0), + max: Math.fround(field.max ?? 0), + bits: field.bits + }); + } + if (field.type === 'angle') { + return Object.freeze({ name: field.name, type: field.type, bits: field.bits }); + } + return Object.freeze({ name: field.name, type: field.type }); + }); + const def = Object.freeze({ id: kind.id, name: kind.name, fields: Object.freeze(fields) }); + byId.set(kind.id, def); + frozen.push(def); + } + return Object.freeze({ kinds: Object.freeze(frozen), byId }); +} + +function checkBits(bits: number | undefined): asserts bits is number { + if (bits === undefined || !Number.isInteger(bits) || bits < 1 || bits > 32) { + throw new GameDecodeError('INVALID', 'quantization bits must be 1..=32'); + } +} + +const maxQ = (bits: number): number => 2 ** bits - 1; +const steps = (bits: number): number => 2 ** bits; + +/** Clamped linear quantization (§4.1). `value` is widened from binary32. */ +export function quantizeLinear(value: number, min: number, max: number, bits: number): number { + const v = Math.fround(value); + const lo = Math.fround(min); + const hi = Math.fround(max); + const mq = maxQ(bits); + if (hi <= lo) return 0; + let x = Number.isNaN(v) ? lo : v; + x = Math.min(Math.max(x, lo), hi); + const t = (x - lo) / (hi - lo); + return Math.min(Math.floor(t * mq + 0.5), mq); +} + +/** Inverse of {@link quantizeLinear}. */ +export function dequantizeLinear(q: number, min: number, max: number, bits: number): number { + const lo = Math.fround(min); + const hi = Math.fround(max); + return Math.fround(lo + (q / maxQ(bits)) * (hi - lo)); +} + +/** Angle quantization (§4.2): radians wrapped to [0, 2π). */ +export function quantizeAngle(value: number, bits: number): number { + let a = Math.fround(value); + if (!Number.isFinite(a)) return 0; + const s = steps(bits); + a %= TAU; + if (a < 0) a += TAU; + return Math.floor((a / TAU) * s + 0.5) % s; +} + +/** Inverse of {@link quantizeAngle}. */ +export function dequantizeAngle(q: number, bits: number): number { + return Math.fround((q * TAU) / steps(bits)); +} + +function numeric(value: FieldValue): number { + if (typeof value === 'boolean') return value ? 1 : 0; + if (typeof value === 'number') return value; + return 0; +} + +function saturate(n: number, lo: number, hi: number): number { + // Rust `f64 as uN` semantics: NaN → 0, saturating, truncating. + if (Number.isNaN(n)) return 0; + return Math.trunc(Math.min(Math.max(n, lo), hi)); +} + +/** Encode one field value, coercing like the server (§4.3). */ +export function encodeField(w: WireWriter, field: GameFieldDef, value: FieldValue): void { + const n = numeric(value); + switch (field.type) { + case 'bool': + w.bool(n !== 0); // Rust `n != 0.0`: NaN is true + return; + case 'u8': + w.u8(saturate(n, 0, 255)); + return; + case 'u16': + w.varuint(saturate(n, 0, 65535)); + return; + case 'u32': + w.varuint(saturate(n, 0, 0xffff_ffff)); + return; + case 'i32': + w.varint(saturate(n, -0x8000_0000, 0x7fff_ffff)); + return; + case 'f32': + w.f32(n); + return; + case 'quant_f32': + w.varuint(quantizeLinear(n, field.min!, field.max!, field.bits!)); + return; + case 'angle': + w.varuint(quantizeAngle(n, field.bits!)); + return; + case 'short_str': + w.shortString(typeof value === 'string' ? value : ''); + return; + case 'bytes': + w.bytes( + value instanceof Uint8Array + ? value + : typeof value === 'string' + ? new TextEncoder().encode(value) + : new Uint8Array(0) + ); + return; + } +} + +/** Decode one field value. */ +export function decodeField(r: WireReader, field: GameFieldDef): FieldValue { + switch (field.type) { + case 'bool': + return r.bool(); + case 'u8': + return r.u8(); + case 'u16': { + const v = r.varuint(); + if (v > 65535) throw new GameDecodeError('INVALID', 'u16 out of range'); + return v; + } + case 'u32': + return r.varuint(); + case 'i32': + return r.varint(); + case 'f32': + return r.f32(); + case 'quant_f32': { + const q = r.varuint(); + if (q > maxQ(field.bits!)) { + throw new GameDecodeError('INVALID', 'quantized value out of range'); + } + return dequantizeLinear(q, field.min!, field.max!, field.bits!); + } + case 'angle': { + const q = r.varuint(); + if (q >= steps(field.bits!)) throw new GameDecodeError('INVALID', 'angle out of range'); + return dequantizeAngle(q, field.bits!); + } + case 'short_str': + return r.shortString(); + case 'bytes': + return r.bytes(); + } +} + +/** + * The value a client will decode for `value` — what the server will send + * after quantization. Use it in `predict` so predicted state matches the + * authoritative wire precision. + */ +export function canonicalizeField(field: GameFieldDef, value: FieldValue): FieldValue { + switch (field.type) { + case 'quant_f32': + return dequantizeLinear( + quantizeLinear(numeric(value), field.min!, field.max!, field.bits!), + field.min!, + field.max!, + field.bits! + ); + case 'angle': + return dequantizeAngle(quantizeAngle(numeric(value), field.bits!), field.bits!); + case 'f32': + return Math.fround(numeric(value)); + case 'bool': + return numeric(value) !== 0; + case 'u8': + return saturate(numeric(value), 0, 255); + case 'u16': + return saturate(numeric(value), 0, 65535); + case 'u32': + return saturate(numeric(value), 0, 0xffff_ffff); + case 'i32': + return saturate(numeric(value), -0x8000_0000, 0x7fff_ffff); + default: + return value; + } +} + +/** Serialize a schema (§5). */ +export function encodeSchema(w: WireWriter, schema: GameSchema): void { + w.varuint(schema.kinds.length); + for (const kind of schema.kinds) { + w.varuint(kind.id).string(kind.name).varuint(kind.fields.length); + for (const field of kind.fields) { + w.string(field.name).u8(TYPE_TAGS.indexOf(field.type)); + if (field.type === 'quant_f32') { + w.f32(field.min!).f32(field.max!).u8(field.bits!); + } else if (field.type === 'angle') { + w.u8(field.bits!); + } + } + } +} + +/** Deserialize a schema (§5). */ +export function decodeSchema(r: WireReader): GameSchema { + const count = r.varuint(); + const kinds: GameKindDef[] = []; + const seen = new Set(); + for (let k = 0; k < count; k += 1) { + const id = r.varuint(); + if (id > 0xffff) throw new GameDecodeError('INVALID', 'kind id > u16'); + const name = r.string(); + const fieldCount = r.varuint(); + if (fieldCount > MAX_FIELDS) throw new GameDecodeError('INVALID', 'more than 32 fields'); + const fields: GameFieldDef[] = []; + for (let f = 0; f < fieldCount; f += 1) { + const fieldName = r.string(); + const tag = r.u8(); + const type = TYPE_TAGS[tag]; + if (type === undefined) { + throw new GameDecodeError('UNKNOWN_FIELD_TYPE', `field type tag ${tag}`); + } + if (type === 'quant_f32') { + const min = r.f32(); + const max = r.f32(); + const bits = r.u8(); + checkBits(bits); + fields.push({ name: fieldName, type, min, max, bits }); + } else if (type === 'angle') { + const bits = r.u8(); + checkBits(bits); + fields.push({ name: fieldName, type, bits }); + } else { + fields.push({ name: fieldName, type }); + } + } + if (seen.has(id)) throw new GameDecodeError('INVALID', 'duplicate kind id'); + seen.add(id); + kinds.push({ id, name, fields }); + } + return defineGameSchema(kinds); +} diff --git a/js/src/game/wire.ts b/js/src/game/wire.ts new file mode 100644 index 000000000..394e30e04 --- /dev/null +++ b/js/src/game/wire.ts @@ -0,0 +1,283 @@ +/** + * Primitive wire encodings of the `distributed_game` protocol + * (`distributed_game/PROTOCOL.md` §2). Little-endian fixed-width numbers, + * minimal unsigned LEB128 `varuint`, zigzag `varint`, length-prefixed UTF-8. + */ + +/** Largest `string`/`bytes` length accepted by decoders (1 MiB). */ +export const MAX_BLOB_LEN = 1 << 20; + +export type GameDecodeErrorCode = + | 'UNEXPECTED_EOF' + | 'VARINT_OVERFLOW' + | 'INVALID_UTF8' + | 'UNKNOWN_MESSAGE' + | 'UNKNOWN_FIELD_TYPE' + | 'UNKNOWN_ENTITY' + | 'INVALID' + | 'TRAILING_BYTES'; + +/** Any malformed or unexpected byte sequence. */ +export class GameDecodeError extends Error { + readonly code: GameDecodeErrorCode; + constructor(code: GameDecodeErrorCode, message: string) { + super(`${code}: ${message}`); + this.name = 'GameDecodeError'; + this.code = code; + } +} + +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder('utf-8', { fatal: true }); + +function assertU32(value: number, what: string): number { + if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) { + throw new RangeError(`${what} must be an unsigned 32-bit integer, got ${value}`); + } + return value; +} + +function assertI32(value: number, what: string): number { + if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) { + throw new RangeError(`${what} must be a signed 32-bit integer, got ${value}`); + } + return value; +} + +/** Growable append-only encoder. */ +export class WireWriter { + #buf: Uint8Array; + #view: DataView; + #len = 0; + + constructor(capacity = 64) { + this.#buf = new Uint8Array(capacity); + this.#view = new DataView(this.#buf.buffer); + } + + get length(): number { + return this.#len; + } + + /** Copy of the bytes written so far. */ + finish(): Uint8Array { + return this.#buf.slice(0, this.#len); + } + + #reserve(extra: number): void { + const need = this.#len + extra; + if (need <= this.#buf.length) return; + let size = this.#buf.length * 2; + while (size < need) size *= 2; + const next = new Uint8Array(size); + next.set(this.#buf.subarray(0, this.#len)); + this.#buf = next; + this.#view = new DataView(next.buffer); + } + + raw(bytes: Uint8Array): this { + this.#reserve(bytes.length); + this.#buf.set(bytes, this.#len); + this.#len += bytes.length; + return this; + } + + u8(value: number): this { + if (!Number.isInteger(value) || value < 0 || value > 255) { + throw new RangeError(`u8 out of range: ${value}`); + } + this.#reserve(1); + this.#buf[this.#len++] = value; + return this; + } + + bool(value: boolean): this { + return this.u8(value ? 1 : 0); + } + + /** Minimal unsigned LEB128 of a u32. */ + varuint(value: number): this { + let v = assertU32(value, 'varuint'); + this.#reserve(5); + for (;;) { + const byte = v & 0x7f; + v = Math.floor(v / 128); + if (v === 0) { + this.#buf[this.#len++] = byte; + return this; + } + this.#buf[this.#len++] = byte | 0x80; + } + } + + /** Zigzag-mapped signed varint. */ + varint(value: number): this { + const v = assertI32(value, 'varint'); + return this.varuint(((v << 1) ^ (v >> 31)) >>> 0); + } + + f32(value: number): this { + this.#reserve(4); + this.#view.setFloat32(this.#len, value, true); + this.#len += 4; + return this; + } + + f64(value: number): this { + this.#reserve(8); + this.#view.setFloat64(this.#len, value, true); + this.#len += 8; + return this; + } + + bytes(value: Uint8Array): this { + return this.varuint(value.length).raw(value); + } + + string(value: string): this { + return this.bytes(utf8Encoder.encode(value)); + } + + /** `u8` length + UTF-8, truncated at a char boundary to fit 255 bytes. */ + shortString(value: string): this { + const bytes = utf8Encoder.encode(value); + let end = Math.min(bytes.length, 255); + // Back off continuation bytes (0b10xx_xxxx) so we cut on a boundary. + while (end < bytes.length && end > 0 && (bytes[end] & 0xc0) === 0x80) end -= 1; + return this.u8(end).raw(bytes.subarray(0, end)); + } +} + +/** Cursor over one message. */ +export class WireReader { + readonly #buf: Uint8Array; + readonly #view: DataView; + #pos = 0; + + constructor(buf: Uint8Array) { + this.#buf = buf; + this.#view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + } + + get remaining(): number { + return this.#buf.length - this.#pos; + } + + /** Error unless every byte was consumed. */ + finish(): void { + if (this.remaining !== 0) { + throw new GameDecodeError('TRAILING_BYTES', `${this.remaining} trailing bytes`); + } + } + + raw(n: number): Uint8Array { + if (this.remaining < n) throw new GameDecodeError('UNEXPECTED_EOF', 'input ended mid-value'); + const out = this.#buf.slice(this.#pos, this.#pos + n); + this.#pos += n; + return out; + } + + u8(): number { + if (this.remaining < 1) throw new GameDecodeError('UNEXPECTED_EOF', 'input ended mid-value'); + return this.#buf[this.#pos++]; + } + + bool(): boolean { + const byte = this.u8(); + if (byte === 0) return false; + if (byte === 1) return true; + throw new GameDecodeError('INVALID', 'bool must be 0 or 1'); + } + + varuint(): number { + let value = 0; + for (let index = 0; index < 5; index += 1) { + const byte = this.u8(); + if (index === 4 && byte > 0x0f) { + throw new GameDecodeError('VARINT_OVERFLOW', 'varuint exceeds 32 bits'); + } + // Multiplication, not `<<`: the 5th group would overflow int32. + value += (byte & 0x7f) * 2 ** (7 * index); + if ((byte & 0x80) === 0) return value; + } + throw new GameDecodeError('VARINT_OVERFLOW', 'varuint exceeds 32 bits'); + } + + varint(): number { + const z = this.varuint(); + return (z >>> 1) ^ -(z & 1); + } + + f32(): number { + if (this.remaining < 4) throw new GameDecodeError('UNEXPECTED_EOF', 'input ended mid-value'); + const value = this.#view.getFloat32(this.#pos, true); + this.#pos += 4; + return value; + } + + f64(): number { + if (this.remaining < 8) throw new GameDecodeError('UNEXPECTED_EOF', 'input ended mid-value'); + const value = this.#view.getFloat64(this.#pos, true); + this.#pos += 8; + return value; + } + + bytes(): Uint8Array { + const len = this.varuint(); + if (len > MAX_BLOB_LEN) throw new GameDecodeError('INVALID', 'length exceeds 1 MiB'); + return this.raw(len); + } + + string(): string { + return decodeUtf8(this.bytes()); + } + + shortString(): string { + return decodeUtf8(this.raw(this.u8())); + } +} + +function decodeUtf8(bytes: Uint8Array): string { + try { + return utf8Decoder.decode(bytes); + } catch { + throw new GameDecodeError('INVALID_UTF8', 'string is not valid UTF-8'); + } +} + +/** Length-prefix a message for byte-stream transports (§1.2). */ +export function frameStream(message: Uint8Array): Uint8Array { + return new WireWriter(message.length + 5).bytes(message).finish(); +} + +/** + * Split one length-prefixed frame off the front of `buf`. Returns + * `undefined` when more bytes are needed. + */ +export function unframeStream( + buf: Uint8Array +): { frame: Uint8Array; consumed: number } | undefined { + const reader = new WireReader(buf); + try { + const frame = reader.bytes(); + return { frame, consumed: buf.length - reader.remaining }; + } catch (error) { + if (error instanceof GameDecodeError && error.code === 'UNEXPECTED_EOF') return undefined; + throw error; + } +} + +/** Lowercase hex of bytes. */ +export function toHex(bytes: Uint8Array): string { + let out = ''; + for (const byte of bytes) out += byte.toString(16).padStart(2, '0'); + return out; +} + +/** Bytes of a hex string. */ +export function fromHex(hex: string): Uint8Array { + if (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) throw new TypeError('invalid hex'); + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16); + return out; +} diff --git a/js/tests/fixtures/game-harness.mjs b/js/tests/fixtures/game-harness.mjs new file mode 100644 index 000000000..aaa786aa8 --- /dev/null +++ b/js/tests/fixtures/game-harness.mjs @@ -0,0 +1,232 @@ +/** + * In-memory transport and deterministic scheduler for game client tests. + * The fake server side speaks the real binary protocol through the SDK codec. + */ +import { + decodeClientMessage, + defineGameSchema, + encodeServerMessage +} from '@hops-ops/distributed/game'; + +export const ARENA_SCHEMA = defineGameSchema([ + { + id: 1, + name: 'avatar', + fields: [ + { name: 'x', type: 'quant_f32', min: -1000, max: 1000, bits: 24 }, + { name: 'y', type: 'quant_f32', min: -1000, max: 1000, bits: 24 }, + { name: 'yaw', type: 'angle', bits: 16 }, + { name: 'hp', type: 'u16' }, + { name: 'name', type: 'short_str' } + ] + }, + { + id: 2, + name: 'coin', + fields: [ + { name: 'x', type: 'quant_f32', min: -1000, max: 1000, bits: 24 }, + { name: 'y', type: 'quant_f32', min: -1000, max: 1000, bits: 24 } + ] + } +]); + +/** Manual clock + timers. */ +export class FakeScheduler { + time = 0; + #timers = new Map(); + #next = 1; + + now = () => this.time; + + setTimeout = (callback, ms) => { + const id = this.#next++; + this.#timers.set(id, { at: this.time + Math.max(0, ms), callback, id }); + return id; + }; + + clearTimeout = (id) => { + this.#timers.delete(id); + }; + + /** Advance time, firing due timers in order. */ + async advance(ms) { + const end = this.time + ms; + for (;;) { + await flush(); + let due; + for (const timer of this.#timers.values()) { + if (timer.at <= end && (due === undefined || timer.at < due.at || (timer.at === due.at && timer.id < due.id))) { + due = timer; + } + } + if (due === undefined) break; + this.#timers.delete(due.id); + this.time = due.at; + due.callback(); + } + this.time = end; + await flush(); + } +} + +export async function flush() { + for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); +} + +/** Server-side end of one fake socket. */ +export class ServerConn { + inbox = []; + closed = false; + closeCode; + #client; + #kinds = new Map(); + #schema; + + constructor(network, url, client) { + this.network = network; + this.url = url; + this.zoneId = url.split('/').pop(); + this.#client = client; + } + + get lastHello() { + return this.inbox.find((m) => m.type === 'Hello'); + } + + inputs() { + return this.inbox.filter((m) => m.type === 'Input'); + } + + /** Encode and deliver a server message (tracks entity kinds for updates). */ + send(message) { + if (this.closed) return; + if (message.type === 'Welcome') { + this.#schema = message.schema; + this.#kinds.clear(); + } + const bytes = encodeServerMessage(message, { + schema: this.#schema, + kindOf: (id) => this.#kinds.get(id) + }); + if (message.type === 'Delta') { + for (const id of message.removes) this.#kinds.delete(id); + for (const c of message.creates) this.#kinds.set(c.id, c.kind); + } + this.#client.onmessage?.({ data: bytes.buffer }); + } + + /** Server closes the socket. */ + close(code = 1000, reason = '') { + if (this.closed) return; + this.closed = true; + this.closeCode = code; + this.#client.readyState = 3; + queueMicrotask(() => this.#client.onclose?.({ code, reason })); + } + + receive(bytes) { + const message = decodeClientMessage(new Uint8Array(bytes)); + this.inbox.push(message); + this.network.onMessage?.(this, message); + } +} + +class FakeClientSocket { + binaryType = 'blob'; + readyState = 0; + onopen = null; + onmessage = null; + onclose = null; + onerror = null; + + constructor(network, url) { + this.server = new ServerConn(network, url, this); + queueMicrotask(() => { + if (network.refuse(url)) { + this.server.closed = true; + this.readyState = 3; + this.onclose?.({ code: 1006, reason: 'refused' }); + return; + } + this.readyState = 1; + network.onConnect?.(this.server); + this.onopen?.({}); + }); + } + + send(data) { + if (this.readyState !== 1 || this.server.closed) return; + this.server.receive(data.slice().buffer); + } + + close(code = 1000, reason = '') { + if (this.readyState === 3) return; + this.readyState = 3; + this.server.closed = true; + queueMicrotask(() => this.onclose?.({ code, reason })); + } +} + +/** + * Fake network. `onConnect(serverConn)` / `onMessage(serverConn, message)` + * script the server; `down` refuses new connections. + */ +export class FakeNetwork { + connections = []; + down = false; + onConnect; + onMessage; + + factory = (url) => { + const socket = new FakeClientSocket(this, url); + this.connections.push(socket.server); + return socket; + }; + + refuse() { + return this.down; + } + + open(zoneId) { + return this.connections.filter((c) => !c.closed && c.zoneId === zoneId); + } + + last(zoneId) { + const list = this.connections.filter((c) => zoneId === undefined || c.zoneId === zoneId); + return list[list.length - 1]; + } +} + +/** A Welcome for the arena schema. */ +export function welcome(overrides = {}) { + return { + type: 'Welcome', + sessionId: 's1', + zoneId: 'z1', + role: 'player', + tickRate: 30, + patchRate: 20, + serverTick: 100, + serverTime: 5000, + reconnectToken: 'rt-1', + contentVersion: '', + schema: ARENA_SCHEMA, + ...overrides + }; +} + +export function delta(overrides = {}) { + return { + type: 'Delta', + serverTick: 100, + ackSeq: 0, + removes: [], + creates: [], + updates: [], + ...overrides + }; +} + +export function avatar(id, x, y = 0, extra = {}) { + return { id, kind: 1, fields: [x, y, extra.yaw ?? 0, extra.hp ?? 100, extra.name ?? 'p'] }; +} diff --git a/js/tests/game-codec.test.mjs b/js/tests/game-codec.test.mjs new file mode 100644 index 000000000..efa848331 --- /dev/null +++ b/js/tests/game-codec.test.mjs @@ -0,0 +1,444 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +import { + GameClientMirror, + GameDecodeError, + WireReader, + WireWriter, + decodeClientMessage, + decodeServerMessage, + defineGameSchema, + dequantizeAngle, + dequantizeLinear, + encodeClientMessage, + encodeServerMessage, + frameStream, + fromHex, + quantizeAngle, + quantizeLinear, + toHex, + unframeStream +} from '@hops-ops/distributed/game'; + +// Golden fixtures produced by the Rust crate (`cargo test --test golden`). +const FIXTURES = new URL('../../distributed_game/tests/fixtures/', import.meta.url); +const fixture = (name) => JSON.parse(readFileSync(new URL(name, FIXTURES), 'utf8')); + +function f32FromBits(bits) { + const view = new DataView(new ArrayBuffer(4)); + view.setUint32(0, Number.parseInt(bits, 16)); + return view.getFloat32(0); +} + +function bitsOfF32(value) { + const view = new DataView(new ArrayBuffer(4)); + view.setFloat32(0, value); + return view.getUint32(0).toString(16).padStart(8, '0'); +} + +function schemaFromJson(kinds) { + return defineGameSchema( + kinds.map((kind) => ({ + id: kind.id, + name: kind.name, + fields: kind.fields.map((field) => + field.type === 'quant_f32' + ? { + name: field.name, + type: field.type, + min: f32FromBits(field.min.bits), + max: f32FromBits(field.max.bits), + bits: field.bits + } + : field.type === 'angle' + ? { name: field.name, type: field.type, bits: field.bits } + : { name: field.name, type: field.type } + ) + })) + ); +} + +function schemaToJson(schema) { + return schema.kinds.map((kind) => ({ + fields: kind.fields.map((field) => { + if (field.type === 'quant_f32') { + return { + bits: field.bits, + max: { bits: bitsOfF32(field.max), f32: field.max }, + min: { bits: bitsOfF32(field.min), f32: field.min }, + name: field.name, + type: field.type + }; + } + if (field.type === 'angle') return { bits: field.bits, name: field.name, type: field.type }; + return { name: field.name, type: field.type }; + }), + id: kind.id, + name: kind.name + })); +} + +function valueFromJson(tagged) { + if ('bool' in tagged) return tagged.bool; + if ('u' in tagged) return tagged.u; + if ('i' in tagged) return tagged.i; + if ('bits' in tagged) return f32FromBits(tagged.bits); + if ('str' in tagged) return tagged.str; + if ('bytes' in tagged) return fromHex(tagged.bytes); + throw new Error(`unknown tagged value ${JSON.stringify(tagged)}`); +} + +function valueToJson(field, value) { + switch (field.type) { + case 'bool': + return { bool: value }; + case 'u8': + case 'u16': + case 'u32': + return { u: value }; + case 'i32': + return { i: value }; + case 'f32': + case 'quant_f32': + case 'angle': + return { bits: bitsOfF32(value) }; + case 'short_str': + return { str: value }; + case 'bytes': + return { bytes: toHex(value) }; + } +} + +/** Compare tagged values, floats by exact bit pattern only. */ +function normalizeTagged(tagged) { + return 'bits' in tagged ? { bits: tagged.bits } : tagged; +} + +function kindsFor(entry) { + const schema = schemaFromJson(entry.schema); + const known = new Map((entry.known_entities ?? []).map((e) => [e.id, e.kind])); + return { schema, kindOf: (id) => known.get(id) }; +} + +function messageFromJson(decoded, schema) { + switch (decoded.type) { + case 'Hello': + return { + type: 'Hello', + protocolVersion: decoded.protocol_version, + contentVersion: decoded.content_version, + capabilities: decoded.capabilities, + ticket: decoded.ticket, + reconnectToken: decoded.reconnect_token + }; + case 'Input': + return { + type: 'Input', + seq: decoded.seq, + clientTick: decoded.client_tick, + payload: fromHex(decoded.payload) + }; + case 'Ping': + return { type: 'Ping', clientTime: decoded.client_time }; + case 'Leave': + return { type: 'Leave' }; + case 'Welcome': + return { + type: 'Welcome', + sessionId: decoded.session_id, + zoneId: decoded.zone_id, + role: decoded.role, + tickRate: decoded.tick_rate, + patchRate: decoded.patch_rate, + serverTick: decoded.server_tick, + serverTime: decoded.server_time, + reconnectToken: decoded.reconnect_token, + contentVersion: decoded.content_version, + schema: schemaFromJson(decoded.schema) + }; + case 'Delta': + return { + type: 'Delta', + serverTick: decoded.server_tick, + ackSeq: decoded.ack_seq, + removes: decoded.removes, + creates: decoded.creates.map((c) => ({ + id: c.id, + kind: c.kind, + fields: c.fields.map(valueFromJson) + })), + updates: decoded.updates.map((u) => ({ + id: u.id, + mask: u.mask, + fields: u.fields.map(valueFromJson) + })) + }; + case 'Event': + return { type: 'Event', typeId: decoded.type_id, payload: fromHex(decoded.payload) }; + case 'Pong': + return { type: 'Pong', clientTime: decoded.client_time, serverTime: decoded.server_time }; + case 'Freeze': + case 'Resume': + return { + type: decoded.type, + reason: decoded.reason, + version: decoded.version, + notes: decoded.notes + }; + case 'Handoff': + return { + type: 'Handoff', + targetZone: decoded.target_zone, + transferTicket: decoded.transfer_ticket + }; + case 'Kick': + case 'Error': + return { type: decoded.type, code: decoded.code, message: decoded.message }; + } + throw new Error(`unhandled ${decoded.type} (${schema})`); +} + +function messageToJson(message, kinds) { + switch (message.type) { + case 'Hello': + return { + capabilities: message.capabilities, + content_version: message.contentVersion, + protocol_version: message.protocolVersion, + reconnect_token: message.reconnectToken, + ticket: message.ticket, + type: 'Hello' + }; + case 'Input': + return { + client_tick: message.clientTick, + payload: toHex(message.payload), + seq: message.seq, + type: 'Input' + }; + case 'Ping': + return { client_time: message.clientTime, type: 'Ping' }; + case 'Leave': + return { type: 'Leave' }; + case 'Welcome': + return { + content_version: message.contentVersion, + patch_rate: message.patchRate, + reconnect_token: message.reconnectToken, + role: message.role, + schema: schemaToJson(message.schema), + server_tick: message.serverTick, + server_time: message.serverTime, + session_id: message.sessionId, + tick_rate: message.tickRate, + type: 'Welcome', + zone_id: message.zoneId + }; + case 'Delta': { + const created = new Map(message.creates.map((c) => [c.id, c.kind])); + const kindDef = (id) => + kinds.schema.byId.get(created.get(id) ?? kinds.kindOf(id)); + return { + ack_seq: message.ackSeq, + creates: message.creates.map((c) => ({ + fields: c.fields.map((v, i) => valueToJson(kinds.schema.byId.get(c.kind).fields[i], v)), + id: c.id, + kind: c.kind + })), + removes: message.removes, + server_tick: message.serverTick, + type: 'Delta', + updates: message.updates.map((u) => { + const fields = kindDef(u.id).fields.filter((_, i) => (u.mask >>> i) & 1); + return { + fields: u.fields.map((v, i) => valueToJson(fields[i], v)), + id: u.id, + mask: u.mask + }; + }) + }; + } + case 'Event': + return { payload: toHex(message.payload), type: 'Event', type_id: message.typeId }; + case 'Pong': + return { client_time: message.clientTime, server_time: message.serverTime, type: 'Pong' }; + case 'Freeze': + case 'Resume': + return { notes: message.notes, reason: message.reason, type: message.type, version: message.version }; + case 'Handoff': + return { + target_zone: message.targetZone, + transfer_ticket: message.transferTicket, + type: 'Handoff' + }; + case 'Kick': + case 'Error': + return { code: message.code, message: message.message, type: message.type }; + } +} + +/** Deep-normalize a fixture `decoded` value: floats compare by bits only. */ +function normalizeDecoded(value) { + if (Array.isArray(value)) return value.map(normalizeDecoded); + if (value !== null && typeof value === 'object') { + if ('bits' in value && 'f32' in value) return { bits: value.bits }; + const out = {}; + for (const key of Object.keys(value).sort()) out[key] = normalizeDecoded(value[key]); + return out; + } + return value; +} + +test('primitives match the Rust golden bytes in both directions', () => { + const { cases } = fixture('primitives.json'); + assert.ok(cases.length >= 20); + for (const c of cases) { + const w = new WireWriter(); + const value = typeof c.value === 'object' && c.value !== null ? f32FromBits(c.value.bits) : c.value; + switch (c.kind) { + case 'varuint': + w.varuint(value); + break; + case 'varint': + w.varint(value); + break; + case 'f32': + w.f32(value); + break; + case 'f64': + w.f64(value); + break; + case 'string': + w.string(value); + break; + case 'short_string': + w.shortString(value); + break; + default: + assert.fail(`unknown primitive kind ${c.kind}`); + } + assert.equal(toHex(w.finish()), c.hex, `${c.kind} ${JSON.stringify(c.value)}`); + + const r = new WireReader(fromHex(c.hex)); + const decoded = { + varuint: () => r.varuint(), + varint: () => r.varint(), + f32: () => r.f32(), + f64: () => r.f64(), + string: () => r.string(), + short_string: () => r.shortString() + }[c.kind](); + r.finish(); + if (c.kind === 'f32') { + assert.equal(bitsOfF32(decoded), c.value.bits); + } else { + assert.ok(Object.is(decoded, value), `${c.kind} decode ${c.hex}`); + } + } +}); + +test('quantization reproduces the Rust integers and binary32 results exactly', () => { + const { cases } = fixture('quantization.json'); + assert.ok(cases.length > 30); + for (const c of cases) { + const input = f32FromBits(c.input_bits); + let q; + let back; + if (c.field.type === 'quant_f32') { + const min = f32FromBits(c.field.min.bits); + const max = f32FromBits(c.field.max.bits); + q = quantizeLinear(input, min, max, c.field.bits); + back = dequantizeLinear(q, min, max, c.field.bits); + } else { + q = quantizeAngle(input, c.field.bits); + back = dequantizeAngle(q, c.field.bits); + } + assert.equal(q, c.q, `${c.field.type} input ${c.input_bits}`); + assert.equal(toHex(new WireWriter().varuint(q).finish()), c.hex); + assert.equal(bitsOfF32(back), c.decoded.bits, `${c.field.type} decode q=${c.q}`); + } +}); + +test('every message fixture encodes and decodes byte-exactly', () => { + const { messages } = fixture('messages.json'); + const names = messages.map((m) => m.name); + for (const required of ['hello', 'hello_reconnect', 'input', 'ping', 'leave', 'welcome', 'delta', 'delta_empty', 'event', 'pong', 'freeze', 'resume', 'handoff', 'kick', 'error']) { + assert.ok(names.includes(required), `fixture ${required}`); + } + for (const entry of messages) { + const kinds = entry.schema === undefined ? undefined : kindsFor(entry); + const message = messageFromJson(entry.decoded); + const bytes = + entry.direction === 'client_to_server' + ? encodeClientMessage(message) + : encodeServerMessage(message, kinds); + assert.equal(toHex(bytes), entry.hex, `encode ${entry.name}`); + + const decoded = + entry.direction === 'client_to_server' + ? decodeClientMessage(fromHex(entry.hex)) + : decodeServerMessage(fromHex(entry.hex), kinds); + assert.deepEqual( + normalizeDecoded(messageToJson(decoded, kinds)), + normalizeDecoded(entry.decoded), + `decode ${entry.name}` + ); + } +}); + +test('client mirror applies the golden delta like Rust ClientMirror', () => { + const { messages } = fixture('messages.json'); + const welcome = messages.find((m) => m.name === 'welcome'); + const delta = messages.find((m) => m.name === 'delta'); + const mirror = new GameClientMirror(); + const hello = mirror.apply(fromHex(welcome.hex)); + assert.equal(hello.type, 'Welcome'); + // Seed the entities the delta fixture assumes are known. + mirror.entities.set(5, { kind: 1, fields: [true, 1, 10, 0, 0, 0, 0, 0, 'x', new Uint8Array()] }); + mirror.entities.set(6, { kind: 2, fields: [1] }); + mirror.entities.set(9, { kind: 2, fields: [2] }); + mirror.apply(fromHex(delta.hex)); + assert.equal(mirror.serverTick, 200); + assert.equal(mirror.ackSeq, 17); + assert.equal(mirror.entities.has(9), false); + assert.equal(mirror.entities.get(5).fields[2], 299); + assert.equal(bitsOfF32(mirror.entities.get(5).fields[6]), '3ac800c8'); + assert.equal(mirror.entities.get(6).fields[0], 64); + assert.equal(mirror.entities.get(300).fields[8], 'Ana'); + assert.equal(mirror.entities.get(301).fields[0], 0); +}); + +test('decoders reject malformed input like the Rust reference', () => { + const reject = (hex, code, kinds) => + assert.throws( + () => decodeServerMessage(fromHex(hex), kinds), + (error) => error instanceof GameDecodeError && error.code === code, + hex + ); + reject('ffffffff10', 'UNKNOWN_MESSAGE'); + reject('8203027870ff', 'TRAILING_BYTES'); + reject('8203057870', 'UNEXPECTED_EOF'); + assert.throws(() => new WireReader(fromHex('ffffffff10')).varuint(), /VARINT_OVERFLOW/); + assert.throws(() => new WireReader(fromHex('02')).bool(), /INVALID/); + assert.throws(() => new WireReader(fromHex('02c328')).string(), /INVALID_UTF8/); + assert.throws(() => decodeClientMessage(fromHex('05')), /UNKNOWN_MESSAGE/); + // A delta update for an unknown entity id. + const { messages } = fixture('messages.json'); + const delta = messages.find((m) => m.name === 'delta'); + const schema = kindsFor(delta).schema; + reject(delta.hex, 'UNKNOWN_ENTITY', { schema, kindOf: () => undefined }); + // A mask bit beyond the kind's fields (orb has 1 field): id 6, mask 0b10. + reject('812b0000000106020000', 'INVALID', { schema, kindOf: () => 2 }); + // Short strings truncate on a UTF-8 boundary at 255 bytes. + const long = 'é'.repeat(200); + const bytes = new WireWriter().shortString(long).finish(); + assert.equal(bytes[0], 254); + assert.equal(new WireReader(bytes).shortString(), 'é'.repeat(127)); + // Stream framing round-trips. + const framed = frameStream(fromHex('04')); + assert.deepEqual([...framed], [1, 4]); + assert.deepEqual(unframeStream(framed), { frame: fromHex('04'), consumed: 2 }); + assert.equal(unframeStream(fromHex('05')), undefined); +}); diff --git a/js/tests/game-connection.test.mjs b/js/tests/game-connection.test.mjs new file mode 100644 index 000000000..956c97bc9 --- /dev/null +++ b/js/tests/game-connection.test.mjs @@ -0,0 +1,389 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + GAME_PROTOCOL_VERSION, + GameClient, + GameConnection, + GameErrorCode, + GameKickCode +} from '@hops-ops/distributed/game'; + +import { + FakeNetwork, + FakeScheduler, + avatar, + delta, + flush, + welcome +} from './fixtures/game-harness.mjs'; + +/** A scripted zone: tickets `t::` admit; tokens rotate per Welcome. */ +function scriptedServer(network, { graceTokens = true } = {}) { + const tokens = new Set(); + let issued = 0; + network.onMessage = (conn, message) => { + if (message.type === 'Hello') { + if (message.reconnectToken !== '') { + if (!graceTokens || !tokens.delete(message.reconnectToken)) { + conn.send({ type: 'Error', code: GameErrorCode.RECONNECT_FAILED, message: 'expired' }); + conn.close(1008); + return; + } + } else if (!message.ticket.startsWith(`t:${conn.zoneId}`) && !message.ticket.startsWith('transfer:')) { + conn.send({ type: 'Error', code: GameErrorCode.UNAUTHORIZED, message: 'bad ticket' }); + conn.close(1008); + return; + } + issued += 1; + const token = `rt-${issued}`; + tokens.add(token); + conn.send(welcome({ zoneId: conn.zoneId, reconnectToken: token, serverTime: 10_000 })); + } + if (message.type === 'Ping') { + conn.send({ type: 'Pong', clientTime: message.clientTime, serverTime: 10_000 + message.clientTime }); + } + }; + return tokens; +} + +function connection(network, scheduler, overrides = {}) { + const tickets = []; + const conn = new GameConnection({ + url: 'ws://game.test/zones/z1', + zoneId: 'z1', + ticket: (request) => { + tickets.push(request); + return `t:z1:${tickets.length}`; + }, + contentVersion: 'c1', + capabilities: 5, + socket: network.factory, + scheduler, + ...overrides + }); + return { conn, tickets }; +} + +test('handshake sends Hello with versions, capabilities and the app ticket', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const { conn, tickets } = connection(network, scheduler); + const states = []; + conn.on('state', (s) => states.push(s)); + const w = await conn.connect(); + assert.equal(w.zoneId, 'z1'); + assert.deepEqual(network.last().lastHello, { + type: 'Hello', + protocolVersion: GAME_PROTOCOL_VERSION, + contentVersion: 'c1', + capabilities: 5, + ticket: 't:z1:1', + reconnectToken: '' + }); + assert.deepEqual(tickets, [{ zoneId: 'z1', role: 'player', reason: 'join' }]); + assert.deepEqual(states, ['connecting', 'open']); + assert.equal(conn.reconnectToken, 'rt-1'); + conn.close(); + await flush(); + assert.deepEqual(network.last().inbox.at(-1), { type: 'Leave' }, 'clean close sends Leave'); + assert.equal(conn.state, 'closed'); +}); + +test('ping/pong estimates offset, rtt and jitter', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + const pongs = []; + // Server clock = client clock + 10000; replies after a scripted delay. + let delay = 40; + network.onMessage = (conn, message) => { + if (message.type === 'Hello') conn.send(welcome({ serverTime: 10_000 + scheduler.now() })); + if (message.type === 'Ping') { + const d = delay; + scheduler.setTimeout(() => { + conn.send({ + type: 'Pong', + clientTime: message.clientTime, + serverTime: message.clientTime + d / 2 + 10_000 + }); + }, d); + } + }; + const { conn } = connection(network, scheduler, { pingIntervalMs: 500 }); + conn.on('pong', (p) => pongs.push(p)); + await conn.connect(); + await scheduler.advance(600); + assert.equal(pongs.length, 2); + assert.equal(conn.clock.rtt, 40); + assert.equal(conn.clock.offset, 10_000); + delay = 80; + await scheduler.advance(2000); + assert.ok(conn.clock.rtt > 40 && conn.clock.rtt < 80, `smoothed rtt ${conn.clock.rtt}`); + assert.ok(conn.clock.jitter > 0); + assert.equal(conn.clock.offset, 10_000, 'symmetric delay keeps the offset exact'); + assert.equal(conn.serverNow(), scheduler.now() + 10_000); + conn.close(); +}); + +test('typed events surface Event/Freeze/Resume/Error and inputs are sequenced', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const { conn } = connection(network, scheduler); + const seen = []; + for (const type of ['event', 'freeze', 'resume', 'error', 'delta']) { + conn.on(type, (m) => seen.push(m.type)); + } + await conn.connect(); + const server = network.last(); + assert.equal(conn.sendInput(new Uint8Array([1, 0]), 7), 1); + assert.equal(conn.sendInput(new Uint8Array([1, 1]), 8), 2); + server.send({ type: 'Freeze', reason: 'content_update', version: 'c2', notes: '' }); + assert.equal(conn.sendInput(new Uint8Array([9])), undefined, 'no inputs while frozen'); + server.send({ type: 'Resume', reason: 'content_update', version: 'c2', notes: '' }); + server.send({ type: 'Event', typeId: 3, payload: new Uint8Array([1]) }); + server.send({ type: 'Error', code: GameErrorCode.RATE_LIMITED, message: 'slow down' }); + server.send(delta({ creates: [avatar(1, 3)] })); + assert.equal(conn.state, 'open', 'post-join errors are advisory'); + assert.deepEqual(seen, ['Freeze', 'Resume', 'Event', 'Error', 'Delta']); + assert.deepEqual( + server.inputs().map((i) => [i.seq, i.clientTick, [...i.payload]]), + [ + [1, 7, [1, 0]], + [2, 8, [1, 1]] + ] + ); + conn.close(); +}); + +test('reconnects with the token inside the grace window, then falls back to a fresh ticket', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + const tokens = scriptedServer(network); + const { conn, tickets } = connection(network, scheduler, { + reconnect: { graceMs: 15_000, maxAttempts: 100, backoffMs: () => 1000 } + }); + const welcomes = []; + conn.on('welcome', (w, info) => welcomes.push({ token: w.reconnectToken, ...info })); + await conn.connect(); + conn.sendInput(new Uint8Array([1])); + + // 1) Abrupt drop: resume with the token, empty ticket. + network.last().close(1006); + await scheduler.advance(10); + let hello = network.last().lastHello; + assert.equal(hello.ticket, ''); + assert.equal(hello.reconnectToken, 'rt-1'); + assert.deepEqual(welcomes.at(-1), { token: 'rt-2', resumed: true, reconnected: true }); + assert.equal(conn.lastSeq, 0, 'sequence numbers restart per connection'); + assert.equal(tickets.length, 1, 'no new ticket needed'); + + // 2) Server unreachable longer than the grace window → fresh ticket. + network.down = true; + network.last().close(1006); + await scheduler.advance(16_000); + network.down = false; + await scheduler.advance(1000); + hello = network.last().lastHello; + assert.equal(hello.reconnectToken, ''); + // Past the grace window every attempt uses a freshly fetched ticket. + assert.ok(tickets.length > 2); + assert.equal(hello.ticket, `t:z1:${tickets.length}`); + assert.deepEqual(tickets.at(-1), { zoneId: 'z1', role: 'player', reason: 'rejoin' }); + assert.equal(conn.state, 'open'); + + // 3) Token rejected by the server (RECONNECT_FAILED) → fresh ticket. + tokens.clear(); + network.last().close(1006); + await scheduler.advance(10); + assert.equal(network.last().lastHello.reconnectToken, 'rt-3'); + assert.equal(conn.state, 'reconnecting'); + await scheduler.advance(1000); + hello = network.last().lastHello; + assert.equal(hello.reconnectToken, ''); + assert.equal(hello.ticket, `t:z1:${tickets.length}`); + assert.equal(conn.state, 'open'); + assert.equal(welcomes.at(-1).resumed, false); + conn.close(); +}); + +test('kick and handshake rejection close without reconnecting', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const { conn } = connection(network, scheduler); + const closes = []; + conn.on('close', (info) => closes.push(info)); + await conn.connect(); + network.last().send({ type: 'Kick', code: GameKickCode.REPLACED, message: 'again' }); + network.last().close(); + await scheduler.advance(5000); + assert.equal(conn.state, 'closed'); + assert.deepEqual(closes, [{ reason: 'kick', code: 2, message: 'again' }]); + assert.equal(network.connections.length, 1); + + const bad = new GameConnection({ + url: 'ws://game.test/zones/z1', + zoneId: 'z1', + ticket: () => 'forged', + socket: network.factory, + scheduler + }); + await assert.rejects(bad.connect(), (error) => error.info.reason === 'rejected' && error.info.code === 2); +}); + +test('a protocol violation drops the socket and resynchronizes via reconnect', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const { conn } = connection(network, scheduler); + const errors = []; + conn.on('protocolError', (e) => errors.push(e.code)); + await conn.connect(); + // Update for an entity the client never saw. + network.last().send(delta({ creates: [avatar(1, 0)] })); + const server = network.last(); + server.send({ type: 'Event', typeId: 1, payload: new Uint8Array() }); + conn.mirror.entities.clear(); // simulate divergence + server.send(delta({ updates: [{ id: 1, mask: 1, fields: [3] }] })); + await scheduler.advance(10); + assert.deepEqual(errors, ['UNKNOWN_ENTITY']); + assert.equal(network.last().lastHello.reconnectToken, 'rt-1'); + assert.equal(conn.state, 'open'); + conn.close(); +}); + +/** Game client used for the multi-zone tests. */ +function gameClient(network, scheduler, extra = {}) { + return new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: ({ zoneId, role }) => (role === 'observer' ? `t:${zoneId}:observer` : `t:${zoneId}:player`), + socket: network.factory, + scheduler, + pingIntervalMs: 60_000, + prediction: { + encodeInput: (dx) => new Uint8Array([dx & 0xff, 0]), + predict: (s, dx, dt) => ({ x: s.x + (dx * 10 * dt) / 1000 }), + corrections: { avatar: { x: { mode: 'ease', durationMs: 100 }, hp: { mode: 'replace' } } }, + controlledEntity: ({ zoneId }) => (zoneId === 'z1' ? 7 : 70) + }, + ...extra + }); +} + +test('game client predicts its entity, reconciles on ack and interpolates others', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const client = gameClient(network, scheduler, { inputDtMs: 100 }); + const corrections = []; + client.on('correction', (c) => corrections.push(c)); + await client.connect('z1'); + const server = network.last('z1'); + // Welcome anchor: tick 100 @ 10000 ms, 30 Hz. + server.send(delta({ serverTick: 100, creates: [avatar(7, 0), avatar(8, 0)] })); + assert.equal(client.sendInput(1), 1); + assert.equal(client.sendInput(1), 2); + assert.deepEqual(server.inputs().map((i) => i.seq), [1, 2]); + let me = client.render().find((e) => e.id === 7); + assert.equal(me.predicted, true); + assert.ok(Math.abs(me.fields.x - 2) < 1e-3, `predicted ${me.fields.x}`); + + // Server consumed seq 1 but the avatar only moved 0.5 (it hit something). + server.send( + delta({ serverTick: 103, ackSeq: 1, updates: [{ id: 7, mask: 1, fields: [0.5] }, { id: 8, mask: 1, fields: [30] }] }) + ); + assert.equal(corrections.length, 1); + assert.ok(Math.abs(corrections[0].errors.x - 0.5) < 1e-3); + assert.deepEqual(client.predictor.pending.map((p) => p.seq), [2]); + me = client.render().find((e) => e.id === 7); + assert.ok(Math.abs(me.fields.x - 2) < 1e-3, 'ease: no visual pop'); + await scheduler.advance(100); + me = client.render().find((e) => e.id === 7); + assert.ok(Math.abs(me.fields.x - 1.5) < 1e-3, `eased to rebased prediction, got ${me.fields.x}`); + + // Entity 8 is interpolated at serverNow - 100 ms between tick 100 and 103. + const other = (t) => { + scheduler.time = t; + return client.render().find((e) => e.id === 8).fields.x; + }; + // serverNow = local + 10000; render at serverNow - 100 ms (2 patches at + // 20 Hz); tick 100 ↦ 10000 ms, tick 103 ↦ 10100 ms. + assert.ok(Math.abs(other(150) - 15) < 1e-3, `midway ${other(150)}`); + assert.ok(Math.abs(other(500) - 30) < 1e-3); + client.close(); +}); + +test('observer zones merge into the rendered world tagged by zone', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const client = gameClient(network, scheduler); + await client.connect('z1'); + await client.observe('z2'); + assert.equal(network.last('z2').lastHello.ticket, 't:z2:observer'); + network.last('z1').send(delta({ creates: [avatar(1, 0)] })); + network.last('z2').send(delta({ creates: [avatar(1, 900)] })); + scheduler.time = 1000; + const keys = client.render().map((e) => [e.key, e.authoritative]).sort(); + assert.deepEqual(keys, [ + ['z1:1', true], + ['z2:1', false] + ]); + client.unobserve('z2'); + await flush(); + assert.deepEqual(client.render().map((e) => e.key), ['z1:1']); + client.close(); +}); + +test('handoff connects to the target with the transfer ticket without blanking the world', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const client = gameClient(network, scheduler, { handoffRetainMs: 300 }); + const events = []; + client.on('handoff', (h) => events.push(['handoff', h.from, h.to])); + client.on('handoffComplete', (h) => events.push(['complete', h.from, h.to])); + client.on('authority', (zone) => events.push(['authority', zone])); + await client.connect('z1'); + await client.observe('z2'); + const z1 = network.last('z1'); + const z2Observer = network.last('z2'); + z1.send(delta({ creates: [avatar(7, 99), avatar(8, 50)] })); + z2Observer.send(delta({ creates: [avatar(70, 101), avatar(71, 120)] })); + scheduler.time = 1000; + assert.equal(client.render().length, 4); + + // Zone 1 hands the player to zone 2. + z1.send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:abc' }); + z1.close(); + await flush(); + const target = network.last('z2'); + assert.notEqual(target, z2Observer); + assert.equal(target.lastHello.ticket, 'transfer:abc'); + assert.equal(client.authority.zoneId, 'z2'); + assert.equal(z2Observer.closed, true, 'observer replaced once the authority was welcomed'); + // Nothing disappears while the new authority has not sent creates yet. + assert.deepEqual( + client.render().map((e) => e.key).sort(), + ['z1:7', 'z1:8', 'z2:70', 'z2:71'] + ); + assert.ok(client.render().filter((e) => e.zoneId === 'z2').every((e) => e.stale)); + + target.send(delta({ creates: [avatar(70, 102), avatar(71, 120)] })); + assert.deepEqual(events, [ + ['authority', 'z1'], + ['handoff', 'z1', 'z2'], + ['authority', 'z2'], + ['complete', 'z1', 'z2'] + ]); + const after = client.render(); + assert.ok(after.find((e) => e.key === 'z2:70').predicted, 'prediction rebinds to the new zone entity'); + assert.ok(after.some((e) => e.key === 'z1:8'), 'old zone retained briefly'); + await scheduler.advance(400); + assert.deepEqual(client.render().map((e) => e.key).sort(), ['z2:70', 'z2:71']); + assert.equal(client.sendInput(1), 1); + assert.equal(target.inputs().length, 1); + client.close(); +}); diff --git a/js/tests/game-replica-prediction.test.mjs b/js/tests/game-replica-prediction.test.mjs new file mode 100644 index 000000000..98305a5a6 --- /dev/null +++ b/js/tests/game-replica-prediction.test.mjs @@ -0,0 +1,140 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { EntityReplica, Predictor, TAU, angleDelta } from '@hops-ops/distributed/game'; + +import { ARENA_SCHEMA, avatar, delta } from './fixtures/game-harness.mjs'; + +const close = (actual, expected, eps = 1e-3, message) => + assert.ok(Math.abs(actual - expected) <= eps, `${message ?? ''} expected ${expected}, got ${actual}`); + +test('replica interpolates lerp, shortest-path angle and step fields', () => { + const replica = new EntityReplica(); + replica.reset(ARENA_SCHEMA, 0); + replica.applyDelta(delta({ creates: [avatar(7, 0, 10, { yaw: 6.0, hp: 100, name: 'a' })] }), 1000); + replica.applyDelta( + delta({ + serverTick: 103, + updates: [{ id: 7, mask: 0b11111, fields: [100, 20, 0.2, 50, 'b'] }] + }), + 1100 + ); + + const mid = replica.sampleEntity(7, 1050); + close(mid.fields.x, 50, 1e-3, 'x lerp'); + close(mid.fields.y, 15, 1e-3, 'y lerp'); + // 6.0 → 0.2 crosses 2π: halfway is ≈ 6.2416 (wrapped), not 3.1. + const expectedYaw = (6.0 + angleDelta(6.0, 0.2) / 2 + TAU) % TAU; + close(mid.fields.yaw, expectedYaw, 1e-3, 'yaw shortest arc'); + assert.ok(mid.fields.yaw > 6, 'angle interpolation took the short way'); + assert.equal(mid.fields.hp, 100, 'u16 steps (holds older value)'); + assert.equal(mid.fields.name, 'a'); + + // Clamp outside the buffer: no extrapolation. + close(replica.sampleEntity(7, 5000).fields.x, 100); + close(replica.sampleEntity(7, 0).fields.x, 0); + assert.equal(replica.sampleEntity(7, 1100).fields.hp, 50); + assert.equal(replica.get(7).fields.hp, 50, 'get() is the latest authoritative state'); +}); + +test('replica inserts hold samples for quiet intervals and honours overrides', () => { + const replica = new EntityReplica({ interpolation: { avatar: { hp: 'lerp', x: 'step' } } }); + replica.reset(ARENA_SCHEMA, 0); + replica.applyDelta(delta({ creates: [avatar(1, 0, 0, { hp: 0 })] }), 0); + replica.applyDelta(delta({ serverTick: 101 }), 50); // entity unchanged at t=50 + replica.applyDelta(delta({ serverTick: 102 }), 100); // still unchanged at t=100 + replica.applyDelta( + delta({ serverTick: 103, updates: [{ id: 1, mask: 0b1001, fields: [10, 100] }] }), + 150 + ); + // It was still at y=0/hp=0 at t=100, so t=125 is halfway from the hold sample. + assert.deepEqual( + replica.history(1).map((h) => h.time), + [0, 100, 150] + ); + const s = replica.sampleEntity(1, 125); + close(s.fields.hp, 50, 1e-9, 'hp lerp override'); + assert.equal(s.fields.x, 0, 'x step override'); + close(replica.sampleEntity(1, 50).fields.hp, 0, 1e-9); +}); + +test('welcome marks entities stale; re-create revives them with history', () => { + const replica = new EntityReplica({ staleGraceMs: 200 }); + replica.reset(ARENA_SCHEMA, 0); + replica.applyDelta(delta({ creates: [avatar(1, 0), avatar(2, 5)] }), 1000); + replica.reset(ARENA_SCHEMA, 1050); + assert.equal(replica.get(1), undefined); + assert.equal(replica.sample(1050).length, 2, 'stale entities keep rendering'); + assert.ok(replica.sample(1050).every((e) => e.stale)); + + replica.applyDelta(delta({ creates: [avatar(1, 10)] }), 1100); + assert.equal(replica.get(1).fields.x, 10); + close(replica.sampleEntity(1, 1050).fields.x, 5, 1e-3, 'history kept across the welcome'); + assert.equal(replica.sampleEntity(2, 1100).stale, true); + replica.applyDelta(delta({ serverTick: 110 }), 1300); + assert.equal(replica.sampleEntity(2, 1300), undefined, 'stale entity dropped after grace'); + assert.equal(replica.size, 1); +}); + +/** Scripted 1D mover: input is a velocity (units/s). */ +const moverPredict = (state, input, dtMs) => ({ x: state.x + (input * dtMs) / 1000 }); + +function boundPredictor(policy) { + const predictor = new Predictor({ + predict: moverPredict, + corrections: { avatar: { x: policy, hp: { mode: 'replace' } } } + }); + const kind = ARENA_SCHEMA.byId.get(1); + predictor.bind(7, kind, { x: 0, y: 0, yaw: 0, hp: 100, name: 'p' }); + return predictor; +} + +test('prediction replays unacked inputs over authoritative state', () => { + const predictor = boundPredictor({ mode: 'snap' }); + for (let seq = 1; seq <= 5; seq += 1) predictor.record(seq, 10, 100); // +1 per input + close(predictor.predicted().x, 5, 1e-9); + + // Server consumed 1..3 and agrees exactly: no correction. + const agree = predictor.reconcile(3, { x: 3, y: 0, yaw: 0, hp: 100, name: 'p' }, 0); + assert.equal(agree.replayed, 2); + assert.deepEqual(agree.errors, {}); + close(predictor.predicted().x, 5, 1e-9); + assert.deepEqual(predictor.pending.map((p) => p.seq), [4, 5]); +}); + +test('ease blends the divergence out over time while snap jumps', () => { + const authoritative = { x: 1, y: 0, yaw: 0, hp: 80, name: 'p' }; // server hit a wall + const eased = boundPredictor({ mode: 'ease', durationMs: 200 }); + const snapped = boundPredictor({ mode: 'snap' }); + for (const p of [eased, snapped]) { + for (let seq = 1; seq <= 4; seq += 1) p.record(seq, 10, 100); + } + // Ack 3: rebased = 1 (authoritative) + 1 (replayed seq 4) = 2; we showed 4. + const ce = eased.reconcile(3, authoritative, 1000); + const cs = snapped.reconcile(3, authoritative, 1000); + close(ce.errors.x, 2, 1e-9); + assert.equal(ce.resolved.x, 'ease'); + assert.equal(cs.resolved.x, 'snap'); + + close(snapped.current(1000).x, 2, 1e-9, 'snap shows the rebased value at once'); + close(eased.current(1000).x, 4, 1e-9, 'ease starts from what was shown'); + close(eased.current(1100).x, 3, 1e-9, 'half the error left halfway through'); + close(eased.current(1200).x, 2, 1e-9, 'converged after durationMs'); + close(eased.current(5000).x, 2, 1e-9); + assert.deepEqual(eased.visualError(5000), {}); + + // `replace` fields are server-owned: never replayed, shown as-is. + assert.equal(eased.current(1000).hp, 80); + assert.equal(ce.resolved.hp, 'replace'); +}); + +test('a new correction while easing starts from the currently displayed value', () => { + const p = boundPredictor({ mode: 'ease', durationMs: 100 }); + p.record(1, 10, 1000); // predicted x = 10 + p.reconcile(0, { x: 0, y: 0, yaw: 0, hp: 100, name: 'p' }, 0); // still pending: 10 + p.reconcile(1, { x: 4, y: 0, yaw: 0, hp: 100, name: 'p' }, 0); // server says 4 + close(p.current(50).x, 7, 1e-9); + p.reconcile(1, { x: 0, y: 0, yaw: 0, hp: 100, name: 'p' }, 50); // server corrects again + close(p.current(50).x, 7, 1e-9, 'no visual pop'); + close(p.current(150).x, 0, 1e-9); +}); From 864aebcd13d6e63aeeac69e94d95ac424e67e880 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:19:56 -0500 Subject: [PATCH 128/484] feat(game): add rewind lag compensation and record/replay Lag compensation: a bounded per-zone ring buffer of entity hit volumes (sphere / vertical capsule + numeric fields) filled by the new Zone::record_rewind hook after every tick. Ctx::rewind() exposes exact and interpolated lookups and segment/ray/point hit tests evaluated at the shooter's view time (client_tick minus a game-reported interpolation delay), clamped to HostConfig::rewind.max_rewind. Record/replay: Recorder wraps a ZoneHost and logs every stimulus with its clock reading plus per-tick state hashes and fact settlements with their delivery tick, into a compact DGR1 file. replay() re-runs it on a ManualClock with a scripted fact queue and reports the first divergence with the suspect stimuli. Zone::state_hash lets games cover unreplicated state (default: hash the replicated WorldView). AdvanceReport additively gains dropped_ticks, tick_durations, entities, per-frame DeltaStats, settlements and tick hashes. No wire change. [[tasks/gr-p8-netcode-ops]] --- distributed_game/Cargo.toml | 5 + distributed_game/src/facts.rs | 58 ++ distributed_game/src/host.rs | 116 ++- distributed_game/src/lib.rs | 8 +- distributed_game/src/replay.rs | 1208 ++++++++++++++++++++++++ distributed_game/src/rewind.rs | 759 +++++++++++++++ distributed_game/src/zone.rs | 12 + distributed_game/tests/netcode/main.rs | 362 +++++++ 8 files changed, 2520 insertions(+), 8 deletions(-) create mode 100644 distributed_game/src/replay.rs create mode 100644 distributed_game/src/rewind.rs create mode 100644 distributed_game/tests/netcode/main.rs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 0519169df..920f0b5c4 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -34,6 +34,11 @@ tokio-tungstenite = "0.30" futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } serde = { version = "1", features = ["derive"] } +[[test]] +name = "netcode" +path = "tests/netcode/main.rs" +required-features = ["runtime"] + [[test]] name = "net_e2e" path = "tests/net_e2e/main.rs" diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs index e72f0263d..522b8c6a3 100644 --- a/distributed_game/src/facts.rs +++ b/distributed_game/src/facts.rs @@ -217,6 +217,7 @@ pub struct FactQueue { settlements: mpsc::Receiver, in_flight: HashSet, capacity: usize, + script: Option, } /// Worker-side handle consumed by [`FactFeed::run`]. @@ -237,6 +238,7 @@ pub fn fact_channel(capacity: usize, policy: RetryPolicy) -> (FactQueue, FactFee settlements: rx, in_flight: HashSet::new(), capacity: capacity.max(1), + script: None, }, FactFeed { shared, @@ -256,6 +258,9 @@ impl FactQueue { return Err(EmitError::Backpressure); } self.in_flight.insert(fact.key.clone()); + if self.script.is_some() { + return Ok(()); + } self.shared .queue .lock() @@ -278,6 +283,59 @@ impl FactQueue { pub fn in_flight(&self) -> usize { self.in_flight.len() } + + /// Queue whose settlements come from a script instead of a worker + /// (record/replay). Emitted facts are tracked for backpressure and + /// duplicate keys exactly like a live queue but never committed. + pub fn scripted(capacity: usize) -> (Self, SettlementScript) { + let (mut queue, _feed) = fact_channel(capacity, RetryPolicy::default()); + let script = SettlementScript::default(); + queue.script = Some(script.clone()); + (queue, script) + } + + /// Settlements due at `tick`: scripted ones scheduled at or before it, + /// otherwise whatever the worker delivered. + pub(crate) fn drain_at(&mut self, tick: u64) -> Vec { + let Some(script) = &self.script else { + return self.drain(); + }; + let mut due = Vec::new(); + { + let mut queue = script.0.lock().expect("script lock"); + while queue.front().is_some_and(|(at, _)| *at <= tick) { + due.push(queue.pop_front().expect("front").1); + } + } + for s in &due { + self.in_flight.remove(&s.key); + } + due + } +} + +/// Feeds scripted settlements into a [`FactQueue::scripted`] queue. +#[derive(Debug, Clone, Default)] +pub struct SettlementScript(Arc>>); + +impl SettlementScript { + /// Deliver `settlement` on the first settlement point at or after `tick`. + pub fn push(&self, tick: u64, settlement: FactSettlement) { + self.0 + .lock() + .expect("script lock") + .push_back((tick, settlement)); + } + + /// Scheduled but not yet delivered. + pub fn len(&self) -> usize { + self.0.lock().expect("script lock").len() + } + + /// True when nothing is scheduled. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } impl Drop for FactQueue { diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 01eadb615..b494cb07c 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -31,11 +31,12 @@ use std::sync::Arc; use std::time::Duration; use crate::clock::Clock; -use crate::facts::{EmitError, Fact, FactQueue}; +use crate::facts::{EmitError, Fact, FactQueue, FactSettlement}; use crate::input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; use crate::interest::{InterestConfig, View}; use crate::protocol::{error, kick, Notice, Role, ServerMessage, Welcome}; -use crate::replication::{ClientReplica, EncodedWorld, WorldView}; +use crate::replication::{ClientReplica, DeltaStats, EncodedWorld, WorldView}; +use crate::rewind::{Rewind, RewindConfig, RewindFrame}; use crate::rng::ZoneRng; use crate::schema::EntitySchema; use crate::stamp::FactStamp; @@ -77,6 +78,8 @@ pub struct HostConfig { pub content_version: String, /// World seed; the zone RNG derives from it and the zone id. pub world_seed: u64, + /// Lag-compensation history ([`Ctx::rewind`]). + pub rewind: RewindConfig, } impl Default for HostConfig { @@ -96,6 +99,7 @@ impl Default for HostConfig { interest: InterestConfig::default(), content_version: String::new(), world_seed: 0, + rewind: RewindConfig::default(), } } } @@ -131,6 +135,31 @@ pub struct AdvanceReport { /// Clock time at which the host next wants `advance` (None = only on /// external events, i.e. Dormant). pub next_wake: Option, + /// Fixed steps dropped by the catch-up cap (`dropped` / step). + pub dropped_ticks: u32, + /// Wall time spent in each simulated tick (metrics only; never fed back + /// into the simulation). + pub tick_durations: Vec, + /// Replicated entity count when a patch ran. + pub entities: Option, + /// One entry per Delta frame built. + pub frames: Vec, + /// Settlements delivered to the zone, with the tick they were delivered on. + pub settled: Vec<(u64, FactSettlement)>, + /// `(tick, state hash)` after each tick, when + /// [`ZoneHost::set_tick_hashing`] is on. + pub tick_hashes: Vec<(u64, u64)>, +} + +/// One Delta frame built by a patch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FrameStats { + /// Destination. + pub client: ClientId, + /// Encoded frame size. + pub bytes: usize, + /// Replication counters. + pub stats: DeltaStats, } /// Admission failure (code from [`protocol::error`](crate::protocol::error)). @@ -198,6 +227,7 @@ pub(crate) struct Core { outbound: Vec, facts: Option, pending_kicks: Vec<(PlayerId, String)>, + rewind: Rewind, } impl Core { @@ -357,6 +387,11 @@ impl Ctx<'_, Z> { self.core.in_flight() } + /// Lag-compensation history (filled by [`Zone::record_rewind`]). + pub fn rewind(&self) -> &Rewind { + &self.core.rewind + } + /// Reliable event to one viewer (dropped if it has no live connection). pub fn send_event(&mut self, to: impl Into, type_id: u32, payload: Vec) { if let Some(client) = self.core.client_of(to.into()) { @@ -412,6 +447,8 @@ pub struct ZoneHost { frozen: bool, disposed: bool, token_source: Box String + Send>, + pending: AdvanceReport, + hash_ticks: bool, } macro_rules! hook { @@ -446,6 +483,7 @@ impl ZoneHost { outbound: Vec::new(), facts: None, pending_kicks: Vec::new(), + rewind: Rewind::new(config.rewind, config.tick_rate), config, }; let zone = Z::on_create(&mut Ctx { core: &mut core }, zone_config); @@ -467,6 +505,8 @@ impl ZoneHost { frozen: false, disposed: false, token_source: Box::new(default_token), + pending: AdvanceReport::default(), + hash_ticks: false, }; host.process_kicks(); host @@ -529,6 +569,39 @@ impl ZoneHost { self.core.clients.len() } + /// Observers. + pub fn observer_count(&self) -> usize { + self.core.observers.len() + } + + /// Lag-compensation history. + pub fn rewind(&self) -> &Rewind { + &self.core.rewind + } + + /// Report a state hash after every tick in + /// [`AdvanceReport::tick_hashes`] (record/replay; costs a hash per tick). + pub fn set_tick_hashing(&mut self, on: bool) { + self.hash_ticks = on; + } + + /// Deterministic digest of tick, simulation time, RNG state and + /// [`Zone::state_hash`] (or, when the zone has none, its replicated + /// [`WorldView`]). + pub fn state_hash(&self) -> u64 { + let zone = self.zone.state_hash().unwrap_or_else(|| { + let mut view = WorldView::default(); + self.zone.replicate(&mut view); + crate::replay::hash_world(&view) + }); + let mut h = crate::rng::Fnv64::new(); + h.write_u64(self.core.tick) + .write_u64(self.core.sim_time.as_nanos() as u64) + .write_u64(self.core.rng.clone().next_u64()) + .write_u64(zone); + h.finish() + } + /// Viewer bound to a connection. pub fn viewer_of(&self, client: ClientId) -> Option { self.core.clients.get(&client).map(|slot| slot.viewer) @@ -953,17 +1026,20 @@ impl ZoneHost { } fn deliver_settlements(&mut self) { + let tick = self.core.tick; let settled = match &mut self.core.facts { - Some(queue) => queue.drain(), + Some(queue) => queue.drain_at(tick), None => return, }; for settlement in settled { + self.pending.settled.push((tick, settlement.clone())); hook!(self.on_fact_settled(settlement)); } self.process_kicks(); } fn tick_once(&mut self, dt: Duration) { + let started = std::time::Instant::now(); self.core.tick += 1; self.core.sim_time += dt; self.core.dt = dt; @@ -974,12 +1050,26 @@ impl ZoneHost { } hook!(self.on_tick()); self.process_kicks(); + let mut frame = RewindFrame::default(); + self.zone.record_rewind(&mut frame); + let entities = frame.into_entities(); + if !entities.is_empty() || !self.core.rewind.is_empty() { + self.core + .rewind + .record(self.core.tick, self.core.sim_time, entities); + } + self.pending.tick_durations.push(started.elapsed()); + if self.hash_ticks { + let hash = self.state_hash(); + self.pending.tick_hashes.push((self.core.tick, hash)); + } } fn patch(&mut self) { let mut view = WorldView::default(); self.zone.replicate(&mut view); let core = &mut self.core; + self.pending.entities = Some(view.entities().len()); let world = EncodedWorld::build(&self.schema, view, &core.config.interest); let tick = core.tick as u32; let budget = core.config.byte_budget; @@ -995,7 +1085,7 @@ impl ZoneHost { None => continue, }, }; - let (frame, _) = slot.replica.build_delta( + let (frame, stats) = slot.replica.build_delta( &self.schema, &world, &core.config.interest, @@ -1004,6 +1094,11 @@ impl ZoneHost { tick, ack, ); + self.pending.frames.push(FrameStats { + client: *client, + bytes: frame.len(), + stats, + }); frames.push(Outbound::Frame { client: *client, frame, @@ -1014,7 +1109,7 @@ impl ZoneHost { /// Run due ticks and patches for the time elapsed on the clock. pub fn advance(&mut self) -> AdvanceReport { - let mut report = AdvanceReport::default(); + let mut report = std::mem::take(&mut self.pending); if self.disposed { return report; } @@ -1044,6 +1139,9 @@ impl ZoneHost { Tier::Dormant => Default::default(), }; report.dropped = steps.dropped; + if !dt.is_zero() { + report.dropped_ticks = (steps.dropped.as_nanos() / dt.as_nanos()) as u32; + } if !self.frozen { for _ in 0..steps.steps { self.tick_once(dt); @@ -1087,11 +1185,17 @@ impl ZoneHost { } report.next_wake = wake; report.transitions = std::mem::take(&mut self.transitions); + let pending = std::mem::take(&mut self.pending); + report.tick_durations.extend(pending.tick_durations); + report.entities = pending.entities; + report.frames.extend(pending.frames); + report.settled.extend(pending.settled); + report.tick_hashes.extend(pending.tick_hashes); report } } -fn default_token() -> String { +pub(crate) fn default_token() -> String { use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 6f998e0bc..c709c9b61 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -35,7 +35,9 @@ pub mod interest; #[cfg(feature = "net")] pub mod net; pub mod protocol; +pub mod replay; pub mod replication; +pub mod rewind; pub mod rng; pub mod schema; pub mod stamp; @@ -48,13 +50,15 @@ pub use clock::{Clock, ManualClock, SystemClock}; pub use facts::spawn_fact_worker; pub use facts::{ fact_channel, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, FactReceipt, - FactSettlement, FactSink, MemoryFactSink, RetryPolicy, + FactSettlement, FactSink, MemoryFactSink, RetryPolicy, SettlementScript, }; -pub use host::{AdvanceReport, Ctx, HostConfig, JoinError, Joined, Outbound, ZoneHost}; +pub use host::{AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, ZoneHost}; pub use input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; pub use interest::{InterestConfig, View}; pub use protocol::{ClientMessage, ClientMirror, Role, ServerMessage, PROTOCOL_VERSION}; +pub use replay::{replay, Recorder, Recording}; pub use replication::{EntityState, WorldView}; +pub use rewind::{Historic, HitQuery, Rewind, RewindConfig, RewindFrame, ShotTiming}; pub use rng::{Fnv64, ZoneRng}; pub use schema::{EntitySchema, FieldType, FieldValue, KindDef}; pub use stamp::{stamp_metadata, FactStamp}; diff --git a/distributed_game/src/replay.rs b/distributed_game/src/replay.rs new file mode 100644 index 000000000..2e9e01498 --- /dev/null +++ b/distributed_game/src/replay.rs @@ -0,0 +1,1208 @@ +//! Deterministic record/replay. +//! +//! A [`Recorder`] wraps a [`ZoneHost`] and logs every external stimulus with +//! the clock reading it happened at: joins, reconnects, disconnects, inputs +//! (sequence, client tick, payload, outcome), kicks, freeze/resume, dispose, +//! and each `advance` together with the fact settlements delivered during it +//! (tagged with the tick they were delivered on) and a state hash after every +//! tick. Timers, RNG draws and tier changes are *not* logged: they are +//! derived from those inputs and the clock, so replay reproduces them. +//! +//! [`replay`] rebuilds a fresh host on a [`ManualClock`], feeds the log back +//! (settlements through a [`FactQueue::scripted`] queue so they land on the +//! same tick) and compares the per-tick hashes. The first mismatch is +//! returned as a [`Divergence`] whose `Display` shows the tick, the hashes +//! and the stimuli applied since the last matching advance. +//! +//! Requirements for a zone to replay: all randomness from +//! [`Ctx::rng`](crate::Ctx::rng), all time from `ctx.dt()` / `ctx.sim_time()` +//! (never `ctx.now()` or wall time), no iteration over `HashMap`s that feeds +//! state. Override [`Zone::state_hash`] to cover unreplicated state. +//! +//! The file is compact binary (`DGR1`, varints; see [`Recording::encode`]). +//! Reconnect tokens are stored as indices into the host's token sequence, +//! never as secrets. Zone construction parameters are opaque bytes chosen by +//! the caller ([`Recording::zone_config`]); [`replay`] takes the decoded +//! `Z::Config`. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::clock::{Clock, ManualClock}; +use crate::facts::{FactError, FactOutcome, FactQueue, FactReceipt, FactSettlement}; +use crate::host::{AdvanceReport, HostConfig, JoinError, Joined, Outbound, ZoneHost}; +use crate::input::PushOutcome; +use crate::interest::InterestConfig; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::protocol::{Notice, Role}; +use crate::replication::WorldView; +use crate::rewind::RewindConfig; +use crate::rng::Fnv64; +use crate::schema::FieldValue; +use crate::zone::{ClientId, PlayerId, TicketClaims, Zone}; + +const MAGIC: &[u8; 4] = b"DGR1"; + +/// FNV digest of a replicated world (entity order, ids, kinds, positions, +/// priorities and field values). +pub fn hash_world(view: &WorldView) -> u64 { + let mut h = Fnv64::new(); + for e in view.entities() { + h.write_u64(u64::from(e.id)) + .write_u64(u64::from(e.kind)) + .write_f32(e.x) + .write_f32(e.y) + .write_f32(e.priority) + .write(&[u8::from(e.global)]); + for f in &e.fields { + match f { + FieldValue::Bool(v) => h.write(&[0, u8::from(*v)]), + FieldValue::U(v) => h.write(&[1]).write_u64(u64::from(*v)), + FieldValue::I(v) => h.write(&[2]).write(&v.to_le_bytes()), + FieldValue::F(v) => h.write(&[3]).write_f32(*v), + FieldValue::Str(v) => h.write(&[4]).write_u64(v.len() as u64).write(v.as_bytes()), + FieldValue::Bytes(v) => h.write(&[5]).write_u64(v.len() as u64).write(v), + }; + } + } + h.finish() +} + +/// Result of a recorded join/reconnect. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JoinResult { + /// Admitted on this connection id. + Joined(u32), + /// Refused with this error code. + Refused(u32), +} + +impl From<&Result> for JoinResult { + fn from(r: &Result) -> Self { + match r { + Ok(j) => Self::Joined(j.client.0), + Err(e) => Self::Refused(e.code), + } + } +} + +/// One recorded stimulus. `at` is the host clock when it happened. +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + /// [`ZoneHost::join`]. + Join { + /// Clock. + at: Duration, + /// Verified claims. + claims: TicketClaims, + /// Hello capabilities. + capabilities: u32, + /// Client content version. + content_version: String, + /// Outcome. + result: JoinResult, + }, + /// [`ZoneHost::reconnect`]. + Reconnect { + /// Clock. + at: Duration, + /// Index of the token in the host's token sequence (`u32::MAX` = unknown). + token: u32, + /// Hello capabilities. + capabilities: u32, + /// Outcome. + result: JoinResult, + }, + /// [`ZoneHost::disconnect`]. + Disconnect { + /// Clock. + at: Duration, + /// Connection. + client: u32, + /// Leave vs drop. + graceful: bool, + }, + /// [`ZoneHost::push_input`]. + Input { + /// Clock. + at: Duration, + /// Connection. + client: u32, + /// Sequence. + seq: u32, + /// Client tick. + client_tick: u32, + /// Raw payload. + payload: Vec, + /// Outcome. + outcome: PushOutcome, + }, + /// [`ZoneHost::kick`]. + Kick { + /// Clock. + at: Duration, + /// Player. + player: u32, + /// Message. + message: String, + }, + /// [`ZoneHost::freeze`]. + Freeze { + /// Clock. + at: Duration, + /// Notice. + notice: Notice, + }, + /// [`ZoneHost::resume`]. + Resume { + /// Clock. + at: Duration, + /// Notice. + notice: Notice, + }, + /// [`ZoneHost::dispose`]. + Dispose { + /// Clock. + at: Duration, + }, + /// [`ZoneHost::advance`]. + Advance { + /// Clock. + at: Duration, + /// Settlements delivered, with their delivery tick. + settled: Vec<(u64, FactSettlement)>, + /// `(tick, hash)` after each tick simulated. + hashes: Vec<(u64, u64)>, + }, +} + +impl Event { + /// Clock reading. + pub fn at(&self) -> Duration { + match self { + Self::Join { at, .. } + | Self::Reconnect { at, .. } + | Self::Disconnect { at, .. } + | Self::Input { at, .. } + | Self::Kick { at, .. } + | Self::Freeze { at, .. } + | Self::Resume { at, .. } + | Self::Dispose { at } + | Self::Advance { at, .. } => *at, + } + } +} + +impl fmt::Display for Event { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ms = self.at().as_secs_f64() * 1000.0; + match self { + Self::Join { + claims, result, .. + } => write!(f, "@{ms:.1}ms join {} -> {result:?}", claims.principal), + Self::Reconnect { token, result, .. } => { + write!(f, "@{ms:.1}ms reconnect token#{token} -> {result:?}") + } + Self::Disconnect { + client, graceful, .. + } => write!(f, "@{ms:.1}ms disconnect client {client} graceful={graceful}"), + Self::Input { + client, + seq, + client_tick, + payload, + outcome, + .. + } => write!( + f, + "@{ms:.1}ms input client {client} seq {seq} client_tick {client_tick} payload {payload:02x?} -> {outcome:?}" + ), + Self::Kick { + player, message, .. + } => write!(f, "@{ms:.1}ms kick player {player}: {message}"), + Self::Freeze { notice, .. } => write!(f, "@{ms:.1}ms freeze {}", notice.reason), + Self::Resume { notice, .. } => write!(f, "@{ms:.1}ms resume {}", notice.reason), + Self::Dispose { .. } => write!(f, "@{ms:.1}ms dispose"), + Self::Advance { + settled, hashes, .. + } => { + let ticks = match (hashes.first(), hashes.last()) { + (Some(a), Some(b)) => format!("ticks {}..={}", a.0, b.0), + _ => "no ticks".into(), + }; + write!(f, "@{ms:.1}ms advance {ticks}, {} settled", settled.len()) + } + } + } +} + +/// A recorded session. +#[derive(Debug, Clone, PartialEq)] +pub struct Recording { + /// Zone id (seeds the RNG). + pub zone_id: String, + /// Host configuration. + pub config: HostConfig, + /// Clock when the host was created. + pub created_at: Duration, + /// Fact queue capacity, when a queue was attached. + pub fact_capacity: Option, + /// Caller-encoded zone construction parameters (opaque). + pub zone_config: Vec, + /// Stimuli in order. + pub events: Vec, +} + +/// File decode failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RecordingError { + /// Not a `DGR1` file. + BadMagic, + /// Malformed content. + Decode(String), +} + +impl fmt::Display for RecordingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BadMagic => write!(f, "not a distributed_game recording"), + Self::Decode(e) => write!(f, "malformed recording: {e}"), + } + } +} + +impl std::error::Error for RecordingError {} + +impl From for RecordingError { + fn from(e: DecodeError) -> Self { + Self::Decode(e.to_string()) + } +} + +fn bad(what: &'static str) -> RecordingError { + RecordingError::Decode(what.into()) +} + +fn put_u64(w: &mut Writer, mut v: u64) { + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + w.u8(byte); + return; + } + w.u8(byte | 0x80); + } +} + +fn get_u64(r: &mut Reader<'_>) -> Result { + let mut v = 0u64; + for i in 0..10 { + let byte = r.u8()?; + v |= u64::from(byte & 0x7f) << (7 * i); + if byte & 0x80 == 0 { + return Ok(v); + } + } + Err(bad("u64 varint overflow")) +} + +fn put_dur(w: &mut Writer, d: Duration) { + put_u64(w, d.as_nanos() as u64); +} + +fn get_dur(r: &mut Reader<'_>) -> Result { + Ok(Duration::from_nanos(get_u64(r)?)) +} + +fn put_notice(w: &mut Writer, n: &Notice) { + w.string(&n.reason).string(&n.version).string(&n.notes); +} + +fn get_notice(r: &mut Reader<'_>) -> Result { + Ok(Notice { + reason: r.string()?, + version: r.string()?, + notes: r.string()?, + }) +} + +fn put_join_result(w: &mut Writer, j: &JoinResult) { + match j { + JoinResult::Joined(c) => w.u8(0).varuint(*c), + JoinResult::Refused(c) => w.u8(1).varuint(*c), + }; +} + +fn get_join_result(r: &mut Reader<'_>) -> Result { + match r.u8()? { + 0 => Ok(JoinResult::Joined(r.varuint()?)), + 1 => Ok(JoinResult::Refused(r.varuint()?)), + _ => Err(bad("join result")), + } +} + +const OUTCOMES: [PushOutcome; 6] = [ + PushOutcome::Accepted, + PushOutcome::Duplicate, + PushOutcome::Stale, + PushOutcome::AcceptedDroppedOldest, + PushOutcome::Rejected, + PushOutcome::UnknownClient, +]; + +fn put_settlement(w: &mut Writer, tick: u64, s: &FactSettlement) { + put_u64(w, tick); + w.string(&s.key).string(&s.command); + match &s.outcome { + FactOutcome::Committed(receipt) => { + w.u8(0) + .string(&receipt.payload.to_string()) + .bool(receipt.replayed); + } + FactOutcome::Failed { error, attempts } => { + let (kind, msg) = match error { + FactError::Retryable(m) => (0, m), + FactError::Permanent(m) => (1, m), + }; + w.u8(1).u8(kind).string(msg).varuint(*attempts); + } + } +} + +fn get_settlement(r: &mut Reader<'_>) -> Result<(u64, FactSettlement), RecordingError> { + let tick = get_u64(r)?; + let key = r.string()?; + let command = r.string()?; + let outcome = match r.u8()? { + 0 => { + let payload = serde_json::from_str(&r.string()?).map_err(|_| bad("receipt json"))?; + FactOutcome::Committed(FactReceipt { + payload, + replayed: r.bool()?, + }) + } + 1 => { + let kind = r.u8()?; + let msg = r.string()?; + let error = match kind { + 0 => FactError::Retryable(msg), + 1 => FactError::Permanent(msg), + _ => return Err(bad("fact error kind")), + }; + FactOutcome::Failed { + error, + attempts: r.varuint()?, + } + } + _ => return Err(bad("fact outcome")), + }; + Ok(( + tick, + FactSettlement { + key, + command, + outcome, + }, + )) +} + +fn put_config(w: &mut Writer, c: &HostConfig) { + w.varuint(c.tick_rate).varuint(c.patch_rate); + match c.idle_tick_rate { + Some(hz) => w.u8(1).varuint(hz), + None => w.u8(0), + }; + put_dur(w, c.dormant_after); + w.varuint(c.max_catch_up); + put_u64(w, c.max_players as u64); + put_u64(w, c.max_observers as u64); + put_u64(w, c.input_capacity as u64); + put_dur(w, c.reconnect_grace); + put_u64(w, c.byte_budget as u64); + w.f32(c.default_view_radius) + .f32(c.interest.cell_size) + .f32(c.interest.leave_margin) + .string(&c.content_version); + put_u64(w, c.world_seed); + put_dur(w, c.rewind.max_rewind); + put_u64(w, c.rewind.max_frames as u64); +} + +fn get_config(r: &mut Reader<'_>) -> Result { + Ok(HostConfig { + tick_rate: r.varuint()?, + patch_rate: r.varuint()?, + idle_tick_rate: match r.u8()? { + 0 => None, + _ => Some(r.varuint()?), + }, + dormant_after: get_dur(r)?, + max_catch_up: r.varuint()?, + max_players: get_u64(r)? as usize, + max_observers: get_u64(r)? as usize, + input_capacity: get_u64(r)? as usize, + reconnect_grace: get_dur(r)?, + byte_budget: get_u64(r)? as usize, + default_view_radius: r.f32()?, + interest: InterestConfig { + cell_size: r.f32()?, + leave_margin: r.f32()?, + }, + content_version: r.string()?, + world_seed: get_u64(r)?, + rewind: RewindConfig { + max_rewind: get_dur(r)?, + max_frames: get_u64(r)? as usize, + }, + }) +} + +impl Recording { + /// Compact binary encoding: + /// `"DGR1" ‖ zone_id ‖ config ‖ created_at ‖ fact_capacity? ‖ zone_config ‖ + /// varuint(event count) ‖ events`. Integers are LEB128 varints, + /// durations are nanosecond varints, clock readings are delta-coded + /// against the previous event, hashes are 8 raw bytes. + pub fn encode(&self) -> Vec { + let mut w = Writer::new(); + w.raw(MAGIC).string(&self.zone_id); + put_config(&mut w, &self.config); + put_dur(&mut w, self.created_at); + match self.fact_capacity { + Some(c) => { + w.u8(1); + put_u64(&mut w, c as u64); + } + None => { + w.u8(0); + } + } + put_u64(&mut w, self.zone_config.len() as u64); + w.raw(&self.zone_config); + put_u64(&mut w, self.events.len() as u64); + let mut last = self.created_at; + for event in &self.events { + let at = event.at(); + put_dur(&mut w, at.saturating_sub(last)); + last = at; + match event { + Event::Join { + claims, + capabilities, + content_version, + result, + .. + } => { + w.u8(0) + .string(&claims.principal) + .string(&claims.zone) + .string(&claims.nonce); + put_u64(&mut w, claims.expires_at); + w.u8(match claims.role { + Role::Player => 0, + Role::Observer => 1, + }) + .varuint(*capabilities) + .string(content_version); + put_join_result(&mut w, result); + } + Event::Reconnect { + token, + capabilities, + result, + .. + } => { + w.u8(1).varuint(*token).varuint(*capabilities); + put_join_result(&mut w, result); + } + Event::Disconnect { + client, graceful, .. + } => { + w.u8(2).varuint(*client).bool(*graceful); + } + Event::Input { + client, + seq, + client_tick, + payload, + outcome, + .. + } => { + let code = OUTCOMES.iter().position(|o| o == outcome).unwrap_or(0) as u8; + w.u8(3) + .varuint(*client) + .varuint(*seq) + .varuint(*client_tick) + .bytes(payload) + .u8(code); + } + Event::Kick { + player, message, .. + } => { + w.u8(4).varuint(*player).string(message); + } + Event::Freeze { notice, .. } => { + w.u8(5); + put_notice(&mut w, notice); + } + Event::Resume { notice, .. } => { + w.u8(6); + put_notice(&mut w, notice); + } + Event::Dispose { .. } => { + w.u8(7); + } + Event::Advance { + settled, hashes, .. + } => { + w.u8(8); + put_u64(&mut w, settled.len() as u64); + for (tick, s) in settled { + put_settlement(&mut w, *tick, s); + } + put_u64(&mut w, hashes.len() as u64); + if let Some((first, _)) = hashes.first() { + put_u64(&mut w, *first); + } + for (_, hash) in hashes { + w.raw(&hash.to_le_bytes()); + } + } + } + } + w.into_bytes() + } + + /// Decode [`encode`](Self::encode) output. + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + if r.raw(4).map_err(|_| RecordingError::BadMagic)? != MAGIC { + return Err(RecordingError::BadMagic); + } + let zone_id = r.string()?; + let config = get_config(&mut r)?; + let created_at = get_dur(&mut r)?; + let fact_capacity = match r.u8()? { + 0 => None, + _ => Some(get_u64(&mut r)? as usize), + }; + let len = get_u64(&mut r)? as usize; + let zone_config = r.raw(len)?.to_vec(); + let count = get_u64(&mut r)? as usize; + let mut events = Vec::with_capacity(count.min(1 << 20)); + let mut at = created_at; + for _ in 0..count { + at += get_dur(&mut r)?; + let event = match r.u8()? { + 0 => { + let principal = r.string()?; + let zone = r.string()?; + let nonce = r.string()?; + let expires_at = get_u64(&mut r)?; + let role = match r.u8()? { + 0 => Role::Player, + _ => Role::Observer, + }; + Event::Join { + at, + claims: TicketClaims { + principal, + zone, + expires_at, + nonce, + role, + }, + capabilities: r.varuint()?, + content_version: r.string()?, + result: get_join_result(&mut r)?, + } + } + 1 => Event::Reconnect { + at, + token: r.varuint()?, + capabilities: r.varuint()?, + result: get_join_result(&mut r)?, + }, + 2 => Event::Disconnect { + at, + client: r.varuint()?, + graceful: r.bool()?, + }, + 3 => Event::Input { + at, + client: r.varuint()?, + seq: r.varuint()?, + client_tick: r.varuint()?, + payload: r.bytes()?.to_vec(), + outcome: *OUTCOMES.get(r.u8()? as usize).ok_or(bad("input outcome"))?, + }, + 4 => Event::Kick { + at, + player: r.varuint()?, + message: r.string()?, + }, + 5 => Event::Freeze { + at, + notice: get_notice(&mut r)?, + }, + 6 => Event::Resume { + at, + notice: get_notice(&mut r)?, + }, + 7 => Event::Dispose { at }, + 8 => { + let n = get_u64(&mut r)? as usize; + let mut settled = Vec::with_capacity(n.min(1 << 16)); + for _ in 0..n { + settled.push(get_settlement(&mut r)?); + } + let n = get_u64(&mut r)?; + let mut hashes = Vec::with_capacity((n as usize).min(1 << 16)); + if n > 0 { + let first = get_u64(&mut r)?; + for i in 0..n { + let mut b = [0u8; 8]; + b.copy_from_slice(r.raw(8)?); + hashes.push((first + i, u64::from_le_bytes(b))); + } + } + Event::Advance { + at, + settled, + hashes, + } + } + _ => return Err(bad("event tag")), + }; + events.push(event); + } + r.finish()?; + Ok(Self { + zone_id, + config, + created_at, + fact_capacity, + zone_config, + events, + }) + } + + /// Write [`encode`](Self::encode) output to `path`. + pub fn save(&self, path: impl AsRef) -> std::io::Result<()> { + std::fs::write(path, self.encode()) + } + + /// Read a file written by [`save`](Self::save). + pub fn load(path: impl AsRef) -> std::io::Result { + let bytes = std::fs::read(path)?; + Self::decode(&bytes).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) + } + + /// Simulated ticks in the recording. + pub fn tick_count(&self) -> usize { + self.events + .iter() + .map(|e| match e { + Event::Advance { hashes, .. } => hashes.len(), + _ => 0, + }) + .sum() + } +} + +/// Records a session while driving a [`ZoneHost`]. Use its methods instead +/// of the host's so every stimulus is logged. +pub struct Recorder { + host: ZoneHost, + clock: Arc, + recording: Recording, + tokens: Arc>>, +} + +impl Recorder { + /// Create the host (as [`ZoneHost::new`]) and start recording. + /// `zone_config_bytes` is stored verbatim for whoever replays. + pub fn new( + zone_id: impl Into, + config: HostConfig, + clock: Arc, + zone_config: Z::Config, + zone_config_bytes: Vec, + ) -> Self { + let zone_id = zone_id.into(); + let created_at = clock.now(); + let tokens = Arc::new(Mutex::new(Vec::new())); + let sink = tokens.clone(); + let mut host = ZoneHost::new(zone_id.clone(), config.clone(), clock.clone(), zone_config) + .with_token_source(move || { + let token = crate::host::default_token(); + sink.lock().expect("tokens").push(token.clone()); + token + }); + host.set_tick_hashing(true); + Self { + host, + clock, + recording: Recording { + zone_id, + config, + created_at, + fact_capacity: None, + zone_config: zone_config_bytes, + events: Vec::new(), + }, + tokens, + } + } + + /// Attach a live fact queue (as [`ZoneHost::with_facts`]); `capacity` + /// must be the capacity it was created with. + pub fn with_facts(mut self, facts: FactQueue, capacity: usize) -> Self { + self.host = self.host.with_facts(facts); + self.recording.fact_capacity = Some(capacity); + self + } + + /// The host (read-only: mutations bypassing the recorder break replay). + pub fn host(&self) -> &ZoneHost { + &self.host + } + + /// The recording so far. + pub fn recording(&self) -> &Recording { + &self.recording + } + + /// Stop and return the recording. + pub fn finish(self) -> Recording { + self.recording + } + + fn now(&self) -> Duration { + self.clock.now() + } + + /// [`ZoneHost::join`]. + pub fn join( + &mut self, + claims: &TicketClaims, + capabilities: u32, + content_version: &str, + ) -> Result { + let at = self.now(); + let result = self.host.join(claims, capabilities, content_version); + self.recording.events.push(Event::Join { + at, + claims: claims.clone(), + capabilities, + content_version: content_version.into(), + result: (&result).into(), + }); + result + } + + /// [`ZoneHost::reconnect`]. + pub fn reconnect(&mut self, token: &str, capabilities: u32) -> Result { + let at = self.now(); + let index = self + .tokens + .lock() + .expect("tokens") + .iter() + .position(|t| t == token) + .map_or(u32::MAX, |i| i as u32); + let result = self.host.reconnect(token, capabilities); + self.recording.events.push(Event::Reconnect { + at, + token: index, + capabilities, + result: (&result).into(), + }); + result + } + + /// [`ZoneHost::disconnect`]. + pub fn disconnect(&mut self, client: ClientId, graceful: bool) { + let at = self.now(); + self.host.disconnect(client, graceful); + self.recording.events.push(Event::Disconnect { + at, + client: client.0, + graceful, + }); + } + + /// [`ZoneHost::push_input`]. + pub fn push_input( + &mut self, + client: ClientId, + seq: u32, + client_tick: u32, + payload: &[u8], + ) -> PushOutcome { + let at = self.now(); + let outcome = self.host.push_input(client, seq, client_tick, payload); + self.recording.events.push(Event::Input { + at, + client: client.0, + seq, + client_tick, + payload: payload.to_vec(), + outcome, + }); + outcome + } + + /// [`ZoneHost::kick`]. + pub fn kick(&mut self, player: PlayerId, message: &str) { + let at = self.now(); + self.host.kick(player, message); + self.recording.events.push(Event::Kick { + at, + player: player.0, + message: message.into(), + }); + } + + /// [`ZoneHost::freeze`]. + pub fn freeze(&mut self, notice: Notice) { + let at = self.now(); + self.host.freeze(notice.clone()); + self.recording.events.push(Event::Freeze { at, notice }); + } + + /// [`ZoneHost::resume`]. + pub fn resume(&mut self, notice: Notice) { + let at = self.now(); + self.host.resume(notice.clone()); + self.recording.events.push(Event::Resume { at, notice }); + } + + /// [`ZoneHost::dispose`]. + pub fn dispose(&mut self) { + let at = self.now(); + self.host.dispose(); + self.recording.events.push(Event::Dispose { at }); + } + + /// [`ZoneHost::advance`]. + pub fn advance(&mut self) -> AdvanceReport { + let at = self.now(); + let report = self.host.advance(); + self.recording.events.push(Event::Advance { + at, + settled: report.settled.clone(), + hashes: report.tick_hashes.clone(), + }); + report + } + + /// [`ZoneHost::drain_outbound`]. + pub fn drain_outbound(&mut self) -> Vec { + self.host.drain_outbound() + } +} + +/// What diverged. +#[derive(Debug, Clone, PartialEq)] +pub enum DivergenceKind { + /// State hash after a tick differs. + StateHash { + /// Recorded. + expected: u64, + /// Replayed. + actual: u64, + }, + /// The advance simulated different ticks. + Ticks { + /// Recorded ticks. + expected: Vec, + /// Replayed ticks. + actual: Vec, + }, + /// An input was accepted/rejected differently. + InputOutcome { + /// Recorded. + expected: PushOutcome, + /// Replayed. + actual: PushOutcome, + }, + /// A join/reconnect resolved differently. + Join { + /// Recorded. + expected: JoinResult, + /// Replayed. + actual: JoinResult, + }, +} + +/// First point where a replay departed from its recording. +#[derive(Debug, Clone, PartialEq)] +pub struct Divergence { + /// Index into [`Recording::events`]. + pub event_index: usize, + /// Tick at which it was detected (the diverging tick for hashes). + pub tick: u64, + /// What differed. + pub kind: DivergenceKind, + /// Last matching tick (0 = none). + pub last_good_tick: u64, + /// Stimuli applied since the last matching advance (most likely cause). + pub suspects: Vec, +} + +impl fmt::Display for Divergence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.kind { + DivergenceKind::StateHash { expected, actual } => write!( + f, + "replay diverged at tick {} (event #{}): state hash {actual:016x} != recorded {expected:016x}", + self.tick, self.event_index + )?, + DivergenceKind::Ticks { expected, actual } => write!( + f, + "replay diverged at tick {} (event #{}): simulated ticks {actual:?} != recorded {expected:?}", + self.tick, self.event_index + )?, + DivergenceKind::InputOutcome { expected, actual } => write!( + f, + "replay diverged at tick {} (event #{}): input outcome {actual:?} != recorded {expected:?}", + self.tick, self.event_index + )?, + DivergenceKind::Join { expected, actual } => write!( + f, + "replay diverged at tick {} (event #{}): join {actual:?} != recorded {expected:?}", + self.tick, self.event_index + )?, + } + write!(f, "\n last matching tick: {}", self.last_good_tick)?; + if !self.suspects.is_empty() { + write!(f, "\n stimuli since then:")?; + for s in &self.suspects { + write!(f, "\n {s}")?; + } + } + Ok(()) + } +} + +impl std::error::Error for Divergence {} + +/// Successful replay summary. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReplaySummary { + /// Events applied. + pub events: usize, + /// Ticks simulated and verified. + pub ticks: u64, + /// Hash after the last tick. + pub final_hash: u64, +} + +/// Replay `recording` through a fresh host on a [`ManualClock`] and verify +/// every per-tick state hash. +pub fn replay( + recording: &Recording, + zone_config: Z::Config, +) -> Result { + replay_with::(recording, zone_config, |_| {}) +} + +/// [`replay`] with a callback after each event (inspection, tooling). +pub fn replay_with( + recording: &Recording, + zone_config: Z::Config, + mut inspect: impl FnMut(&ZoneHost), +) -> Result { + let clock = ManualClock::new(); + clock.set(recording.created_at); + let counter = Arc::new(Mutex::new(0u32)); + let source = counter.clone(); + let mut host = ZoneHost::::new( + recording.zone_id.clone(), + recording.config.clone(), + Arc::new(clock.clone()), + zone_config, + ) + .with_token_source(move || { + let mut n = source.lock().expect("counter"); + *n += 1; + format!("replay-token-{}", *n - 1) + }); + host.set_tick_hashing(true); + let mut script = None; + if let Some(capacity) = recording.fact_capacity { + let (queue, s) = FactQueue::scripted(capacity); + host = host.with_facts(queue); + script = Some(s); + } + let mut last_good_tick = 0u64; + let mut suspects: Vec = Vec::new(); + let mut last_hash = 0u64; + let mut ticks = 0u64; + let diverge = |event_index: usize, + tick: u64, + kind: DivergenceKind, + last_good_tick: u64, + suspects: &[String]| Divergence { + event_index, + tick, + kind, + last_good_tick, + suspects: suspects.to_vec(), + }; + for (index, event) in recording.events.iter().enumerate() { + clock.set(event.at()); + match event { + Event::Join { + claims, + capabilities, + content_version, + result, + .. + } => { + let actual = JoinResult::from(&host.join(claims, *capabilities, content_version)); + if &actual != result { + return Err(diverge( + index, + host.tick(), + DivergenceKind::Join { + expected: result.clone(), + actual, + }, + last_good_tick, + &suspects, + )); + } + } + Event::Reconnect { + token, + capabilities, + result, + .. + } => { + let token = if *token == u32::MAX { + String::new() + } else { + format!("replay-token-{token}") + }; + let actual = JoinResult::from(&host.reconnect(&token, *capabilities)); + if &actual != result { + return Err(diverge( + index, + host.tick(), + DivergenceKind::Join { + expected: result.clone(), + actual, + }, + last_good_tick, + &suspects, + )); + } + } + Event::Disconnect { + client, graceful, .. + } => host.disconnect(ClientId(*client), *graceful), + Event::Input { + client, + seq, + client_tick, + payload, + outcome, + .. + } => { + let actual = host.push_input(ClientId(*client), *seq, *client_tick, payload); + if actual != *outcome { + return Err(diverge( + index, + host.tick(), + DivergenceKind::InputOutcome { + expected: *outcome, + actual, + }, + last_good_tick, + &suspects, + )); + } + } + Event::Kick { + player, message, .. + } => host.kick(PlayerId(*player), message.clone()), + Event::Freeze { notice, .. } => host.freeze(notice.clone()), + Event::Resume { notice, .. } => host.resume(notice.clone()), + Event::Dispose { .. } => host.dispose(), + Event::Advance { + settled, hashes, .. + } => { + if let Some(script) = &script { + for (tick, s) in settled { + script.push(*tick, s.clone()); + } + } + let report = host.advance(); + host.drain_outbound(); + let expected_ticks: Vec = hashes.iter().map(|(t, _)| *t).collect(); + let actual_ticks: Vec = report.tick_hashes.iter().map(|(t, _)| *t).collect(); + for ((tick, expected), (_, actual)) in hashes.iter().zip(&report.tick_hashes) { + if expected != actual { + suspects.push(event.to_string()); + return Err(diverge( + index, + *tick, + DivergenceKind::StateHash { + expected: *expected, + actual: *actual, + }, + last_good_tick, + &suspects, + )); + } + last_good_tick = *tick; + } + if expected_ticks != actual_ticks { + suspects.push(event.to_string()); + return Err(diverge( + index, + host.tick(), + DivergenceKind::Ticks { + expected: expected_ticks, + actual: actual_ticks, + }, + last_good_tick, + &suspects, + )); + } + if let Some((_, h)) = report.tick_hashes.last() { + last_hash = *h; + ticks += report.tick_hashes.len() as u64; + suspects.clear(); + } + inspect(&host); + continue; + } + } + suspects.push(event.to_string()); + host.drain_outbound(); + inspect(&host); + } + Ok(ReplaySummary { + events: recording.events.len(), + ticks, + final_hash: last_hash, + }) +} + +/// Per-tick hashes of a recording (for diffing two recordings). +pub fn tick_hashes(recording: &Recording) -> BTreeMap { + recording + .events + .iter() + .flat_map(|e| match e { + Event::Advance { hashes, .. } => hashes.clone(), + _ => Vec::new(), + }) + .collect() +} diff --git a/distributed_game/src/rewind.rs b/distributed_game/src/rewind.rs new file mode 100644 index 000000000..766d19bbe --- /dev/null +++ b/distributed_game/src/rewind.rs @@ -0,0 +1,759 @@ +//! Lag compensation: bounded per-entity history and hit tests at the +//! shooter's view time. +//! +//! A client renders remote entities in the past (it interpolates between the +//! last few Deltas). When it fires, it aimed at what it *saw*, not at where +//! targets are on the server now. The host therefore keeps a short ring +//! buffer of entity hit volumes per tick ([`Zone::record_rewind`]) and a zone +//! resolves a shot against that history: +//! +//! ```text +//! view_time = time_of(client_tick) - interp_delay (client-reported) +//! age = latest_recorded_time - view_time +//! age = min(age, max_rewind) (anti-cheat clamp) +//! ``` +//! +//! `client_tick` is the input's [`SequencedInput::client_tick`]; the +//! interpolation delay is game-defined and travels **inside the game's input +//! payload** (no wire change), e.g. as a `u16` of milliseconds. Whatever the +//! client claims, the rewind never exceeds [`RewindConfig::max_rewind`] nor +//! the recorded history, and never goes into the future. +//! +//! Inside a hook: `ctx.rewind().hit_test_shot(timing, &HitQuery::ray(..), |id| id != me)`. +//! +//! Coordinates are 3D (`[x, y, z]`); 2D games use `z = 0` and spheres. +//! Capsules are vertical (axis along `z`), centred on the entity position. +//! +//! [`Zone::record_rewind`]: crate::Zone::record_rewind +//! [`SequencedInput::client_tick`]: crate::SequencedInput::client_tick + +use std::collections::VecDeque; +use std::time::Duration; + +/// 3D vector. +pub type Vec3 = [f32; 3]; + +/// Rewind tuning (part of [`HostConfig`](crate::HostConfig)). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RewindConfig { + /// Furthest a shot may be evaluated in the past (cheat clamp). + pub max_rewind: Duration, + /// Hard cap on stored ticks regardless of tick rate. + pub max_frames: usize, +} + +impl Default for RewindConfig { + fn default() -> Self { + Self { + max_rewind: Duration::from_millis(500), + max_frames: 256, + } + } +} + +/// Hit volume of a historical entity. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Shape { + /// Sphere centred on the entity position. + Sphere { + /// Radius. + radius: f32, + }, + /// Vertical capsule centred on the entity position. + Capsule { + /// Distance from the centre to each cap centre along `z`. + half_height: f32, + /// Radius. + radius: f32, + }, +} + +impl Shape { + fn radius(&self) -> f32 { + match *self { + Self::Sphere { radius } | Self::Capsule { radius, .. } => radius, + } + } + + fn segment(&self, pos: Vec3) -> (Vec3, Vec3) { + match *self { + Self::Sphere { .. } => (pos, pos), + Self::Capsule { half_height, .. } => ( + [pos[0], pos[1], pos[2] - half_height], + [pos[0], pos[1], pos[2] + half_height], + ), + } + } +} + +/// One entity's state at one tick. +#[derive(Debug, Clone, PartialEq)] +pub struct Historic { + /// Entity id (same id space as replication). + pub id: u32, + /// Position. + pub pos: Vec3, + /// Hit volume. + pub shape: Shape, + /// Arbitrary numeric fields (interpolated linearly by [`Rewind::at_time`]). + pub fields: Vec, +} + +impl Historic { + /// Entity with a sphere hit volume. + pub fn sphere(id: u32, pos: Vec3, radius: f32) -> Self { + Self { + id, + pos, + shape: Shape::Sphere { radius }, + fields: Vec::new(), + } + } + + /// Entity with a vertical capsule hit volume. + pub fn capsule(id: u32, pos: Vec3, half_height: f32, radius: f32) -> Self { + Self { + id, + pos, + shape: Shape::Capsule { + half_height, + radius, + }, + fields: Vec::new(), + } + } + + /// Attach numeric fields. + pub fn with_fields(mut self, fields: Vec) -> Self { + self.fields = fields; + self + } +} + +/// All recorded entities at one tick. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct RewindFrame { + tick: u64, + time: Duration, + entities: Vec, +} + +impl RewindFrame { + /// Record an entity (filled by [`Zone::record_rewind`](crate::Zone::record_rewind)). + pub fn push(&mut self, entity: Historic) { + self.entities.push(entity); + } + + /// Tick this frame describes (state after that tick's `on_tick`). + pub fn tick(&self) -> u64 { + self.tick + } + + /// Simulation time of that tick. + pub fn time(&self) -> Duration { + self.time + } + + /// Entities, sorted by id. + pub fn entities(&self) -> &[Historic] { + &self.entities + } + + pub(crate) fn into_entities(self) -> Vec { + self.entities + } + + /// One entity. + pub fn get(&self, id: u32) -> Option<&Historic> { + self.entities + .binary_search_by_key(&id, |e| e.id) + .ok() + .map(|i| &self.entities[i]) + } +} + +/// What the client reports with a shot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShotTiming { + /// Server tick the client's view was based on (input `client_tick`). + pub client_tick: u32, + /// How far behind `client_tick` the client was rendering. + pub interp_delay: Duration, +} + +/// A shot time after clamping. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResolvedTime { + /// Simulation time the shot is evaluated at. + pub time: Duration, + /// How far behind the latest recorded tick that is. + pub age: Duration, + /// Age the client asked for. + pub requested_age: Duration, + /// True when the request was limited by `max_rewind` or the history. + pub clamped: bool, +} + +/// Geometric query. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum HitQuery { + /// Segment `from → to` (rays are segments with a max distance). + Segment { + /// Start. + from: Vec3, + /// End. + to: Vec3, + }, + /// Sphere (melee, explosion, point-in-radius with `radius = 0`). + Sphere { + /// Centre. + center: Vec3, + /// Radius. + radius: f32, + }, +} + +impl HitQuery { + /// Ray from `origin` along `dir` (need not be normalised) up to `max_dist`. + pub fn ray(origin: Vec3, dir: Vec3, max_dist: f32) -> Self { + let n = norm(dir); + let to = if n > 0.0 { + add(origin, scale(dir, max_dist / n)) + } else { + origin + }; + Self::Segment { from: origin, to } + } + + /// Point-in-radius test. + pub fn point(at: Vec3, radius: f32) -> Self { + Self::Sphere { center: at, radius } + } +} + +/// Nearest hit of a query. +#[derive(Debug, Clone, PartialEq)] +pub struct RewindHit { + /// Entity hit. + pub id: u32, + /// Distance along the segment to the entry point (segments), or + /// centre-to-surface distance (spheres; 0 when overlapping the centre). + pub distance: f32, + /// The entity as it was at the evaluated time. + pub entity: Historic, +} + +/// Bounded ring buffer of [`RewindFrame`]s. Reached through +/// [`Ctx::rewind`](crate::Ctx::rewind). +#[derive(Debug, Clone)] +pub struct Rewind { + config: RewindConfig, + capacity: usize, + frames: VecDeque, +} + +impl Rewind { + /// History sized for `max_rewind` at `tick_rate` (plus slack), capped by + /// `max_frames`. + pub fn new(config: RewindConfig, tick_rate: u32) -> Self { + let per_tick = 1.0 / f64::from(tick_rate.max(1)); + let needed = (config.max_rewind.as_secs_f64() / per_tick).ceil() as usize + 2; + Self { + capacity: needed.clamp(2, config.max_frames.max(2)), + config, + frames: VecDeque::new(), + } + } + + /// Configuration. + pub fn config(&self) -> &RewindConfig { + &self.config + } + + /// Stored frames bound. + pub fn capacity(&self) -> usize { + self.capacity + } + + /// Store a frame (called by the host after each tick). Entities are + /// sorted by id; frames must arrive in tick order. + pub fn record(&mut self, tick: u64, time: Duration, mut entities: Vec) { + entities.sort_by_key(|e| e.id); + if self.frames.len() >= self.capacity { + self.frames.pop_front(); + } + self.frames.push_back(RewindFrame { + tick, + time, + entities, + }); + } + + /// Forget everything (e.g. after a teleport-everything reset). + pub fn clear(&mut self) { + self.frames.clear(); + } + + /// Newest frame (the state clients were last sent). + pub fn latest(&self) -> Option<&RewindFrame> { + self.frames.back() + } + + /// Oldest stored frame. + pub fn oldest(&self) -> Option<&RewindFrame> { + self.frames.front() + } + + /// Stored frame count. + pub fn len(&self) -> usize { + self.frames.len() + } + + /// True when nothing has been recorded. + pub fn is_empty(&self) -> bool { + self.frames.is_empty() + } + + /// Exact frame for `tick`. + pub fn at(&self, tick: u64) -> Option<&RewindFrame> { + let first = self.frames.front()?.tick; + let index = tick.checked_sub(first)? as usize; + self.frames + .get(index) + .filter(|f| f.tick == tick) + .or_else(|| self.frames.iter().find(|f| f.tick == tick)) + } + + /// Simulation time of `tick` (32-bit wire tick, unwrapped against the + /// latest frame). Ticks outside the history are extrapolated with the + /// latest step; future ticks map to the latest time. + pub fn time_of(&self, client_tick: u32) -> Option { + let latest = self.frames.back()?; + let behind = (latest.tick as u32).wrapping_sub(client_tick) as i32; + if behind <= 0 { + return Some(latest.time); + } + let tick = latest.tick.saturating_sub(behind as u64); + if let Some(frame) = self.at(tick) { + return Some(frame.time); + } + let step = self.step(); + Some( + latest + .time + .saturating_sub(step.saturating_mul(behind as u32)), + ) + } + + fn step(&self) -> Duration { + let n = self.frames.len(); + if n < 2 { + return Duration::ZERO; + } + let (a, b) = (&self.frames[n - 2], &self.frames[n - 1]); + let ticks = b.tick.saturating_sub(a.tick).max(1) as u32; + b.time.saturating_sub(a.time) / ticks + } + + /// Clamp a client's view time: never older than `max_rewind` or the + /// oldest frame, never newer than the latest frame. + pub fn resolve(&self, timing: ShotTiming) -> Option { + let latest = self.frames.back()?.time; + let oldest = self.frames.front()?.time; + let wanted = self + .time_of(timing.client_tick)? + .saturating_sub(timing.interp_delay); + let requested_age = latest.saturating_sub(wanted); + let floor = latest.saturating_sub(self.config.max_rewind).max(oldest); + let time = wanted.max(floor); + Some(ResolvedTime { + time, + age: latest - time, + requested_age, + clamped: time != wanted, + }) + } + + /// Entities at `time`, interpolated between the surrounding frames + /// (positions and numeric fields lerp; shape and membership come from + /// the earlier frame). Clamped to the stored range. + pub fn at_time(&self, time: Duration) -> Option> { + let (a, b, alpha) = self.bracket(time)?; + Some( + a.entities + .iter() + .map(|e| match b.get(e.id) { + Some(next) if alpha > 0.0 => lerp_entity(e, next, alpha), + _ => e.clone(), + }) + .collect(), + ) + } + + /// One entity at `time` (see [`at_time`](Self::at_time)). + pub fn entity_at(&self, id: u32, time: Duration) -> Option { + let (a, b, alpha) = self.bracket(time)?; + let e = a.get(id)?; + Some(match b.get(id) { + Some(next) if alpha > 0.0 => lerp_entity(e, next, alpha), + _ => e.clone(), + }) + } + + fn bracket(&self, time: Duration) -> Option<(&RewindFrame, &RewindFrame, f32)> { + let first = self.frames.front()?; + let last = self.frames.back()?; + if time <= first.time { + return Some((first, first, 0.0)); + } + if time >= last.time { + return Some((last, last, 0.0)); + } + let index = self.frames.partition_point(|f| f.time <= time); + let (a, b) = (&self.frames[index - 1], &self.frames[index]); + let span = (b.time - a.time).as_secs_f32(); + let alpha = if span > 0.0 { + (time - a.time).as_secs_f32() / span + } else { + 0.0 + }; + Some((a, b, alpha)) + } + + /// Nearest entity hit by `query` at `time` among those `filter` accepts. + pub fn hit_test( + &self, + time: Duration, + query: &HitQuery, + mut filter: impl FnMut(u32) -> bool, + ) -> Option { + let entities = self.at_time(time)?; + let mut best: Option = None; + for e in entities { + if !filter(e.id) { + continue; + } + if let Some(distance) = intersect(query, &e) { + if best.as_ref().is_none_or(|b| distance < b.distance) { + best = Some(RewindHit { + id: e.id, + distance, + entity: e, + }); + } + } + } + best + } + + /// Every entity overlapping `query` at `time` (area effects). + pub fn overlaps(&self, time: Duration, query: &HitQuery) -> Vec { + let mut hits: Vec = self + .at_time(time) + .unwrap_or_default() + .into_iter() + .filter_map(|e| { + intersect(query, &e).map(|distance| RewindHit { + id: e.id, + distance, + entity: e, + }) + }) + .collect(); + hits.sort_by(|a, b| a.distance.total_cmp(&b.distance).then(a.id.cmp(&b.id))); + hits + } + + /// Resolve the client's view time (clamped) and hit-test there. + pub fn hit_test_shot( + &self, + timing: ShotTiming, + query: &HitQuery, + filter: impl FnMut(u32) -> bool, + ) -> Option<(RewindHit, ResolvedTime)> { + let resolved = self.resolve(timing)?; + self.hit_test(resolved.time, query, filter) + .map(|hit| (hit, resolved)) + } +} + +fn lerp_entity(a: &Historic, b: &Historic, t: f32) -> Historic { + Historic { + id: a.id, + pos: [ + lerp(a.pos[0], b.pos[0], t), + lerp(a.pos[1], b.pos[1], t), + lerp(a.pos[2], b.pos[2], t), + ], + shape: a.shape, + fields: a + .fields + .iter() + .enumerate() + .map(|(i, v)| b.fields.get(i).map_or(*v, |w| lerp(*v, *w, t))) + .collect(), + } +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +fn add(a: Vec3, b: Vec3) -> Vec3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn sub(a: Vec3, b: Vec3) -> Vec3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn scale(a: Vec3, s: f32) -> Vec3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: Vec3, b: Vec3) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn norm(a: Vec3) -> f32 { + dot(a, a).sqrt() +} + +/// Closest point to `p` on segment `a → b`. +fn closest_on_segment(p: Vec3, a: Vec3, b: Vec3) -> Vec3 { + let ab = sub(b, a); + let len2 = dot(ab, ab); + if len2 <= f32::EPSILON { + return a; + } + let t = (dot(sub(p, a), ab) / len2).clamp(0.0, 1.0); + add(a, scale(ab, t)) +} + +/// Entry distance of the ray `ro + t·rd` (`rd` unit) into a sphere, if any +/// with `t >= 0` (0 when starting inside). +fn ray_sphere(ro: Vec3, rd: Vec3, center: Vec3, r: f32) -> Option { + let oc = sub(ro, center); + let c = dot(oc, oc) - r * r; + if c <= 0.0 { + return Some(0.0); + } + let b = dot(oc, rd); + let h = b * b - c; + if h < 0.0 || b > 0.0 { + return None; + } + Some(-b - h.sqrt()) +} + +/// Entry distance of a ray into a capsule `pa–pb` of radius `r`. +fn ray_capsule(ro: Vec3, rd: Vec3, pa: Vec3, pb: Vec3, r: f32) -> Option { + let closest = closest_on_segment(ro, pa, pb); + if dot(sub(ro, closest), sub(ro, closest)) <= r * r { + return Some(0.0); + } + let ba = sub(pb, pa); + let oa = sub(ro, pa); + let baba = dot(ba, ba); + let bard = dot(ba, rd); + let baoa = dot(ba, oa); + let rdoa = dot(rd, oa); + let oaoa = dot(oa, oa); + let a = baba - bard * bard; + let mut best: Option = None; + if a.abs() > 1e-9 { + let b = baba * rdoa - baoa * bard; + let c = baba * oaoa - baoa * baoa - r * r * baba; + let h = b * b - a * c; + if h >= 0.0 { + let t = (-b - h.sqrt()) / a; + let y = baoa + t * bard; + if t >= 0.0 && y > 0.0 && y < baba { + best = Some(t); + } + } + } + for cap in [pa, pb] { + if let Some(t) = ray_sphere(ro, rd, cap, r) { + best = Some(best.map_or(t, |b: f32| b.min(t))); + } + } + best +} + +fn intersect(query: &HitQuery, e: &Historic) -> Option { + let r = e.shape.radius(); + let (pa, pb) = e.shape.segment(e.pos); + match *query { + HitQuery::Segment { from, to } => { + let d = sub(to, from); + let len = norm(d); + if len <= f32::EPSILON { + let c = closest_on_segment(from, pa, pb); + return (norm(sub(from, c)) <= r).then_some(0.0); + } + let rd = scale(d, 1.0 / len); + ray_capsule(from, rd, pa, pb, r).filter(|t| *t <= len) + } + HitQuery::Sphere { center, radius } => { + let c = closest_on_segment(center, pa, pb); + let d = norm(sub(center, c)); + (d <= r + radius).then_some((d - r).max(0.0)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MS: fn(u64) -> Duration = Duration::from_millis; + + /// 30 Hz history of a target moving +x at 10 u/s along y = 10. + fn history(config: RewindConfig, ticks: u64) -> Rewind { + let mut rw = Rewind::new(config, 30); + let dt = Duration::from_secs(1) / 30; + for tick in 1..=ticks { + let t = dt * tick as u32; + let x = t.as_secs_f32() * 10.0; + rw.record( + tick, + t, + vec![ + Historic::sphere(7, [x, 10.0, 0.0], 0.5).with_fields(vec![x]), + Historic::capsule(9, [-50.0, 0.0, 1.0], 0.8, 0.4), + ], + ); + } + rw + } + + #[test] + fn ring_buffer_is_bounded_by_max_rewind() { + let rw = history(RewindConfig::default(), 200); + // 500 ms at 30 Hz = 15 ticks + 2 slack. + assert_eq!(rw.capacity(), 17); + assert_eq!(rw.len(), 17); + assert_eq!(rw.latest().unwrap().tick(), 200); + assert_eq!(rw.oldest().unwrap().tick(), 184); + assert!(rw.at(183).is_none()); + assert_eq!(rw.at(190).unwrap().tick(), 190); + } + + #[test] + fn at_time_interpolates_positions_and_fields() { + let rw = history(RewindConfig::default(), 60); + // Halfway between tick 50 and 51. + let t = (Duration::from_secs(1) / 30) * 50 + Duration::from_secs(1) / 60; + let e = rw.entity_at(7, t).unwrap(); + let expected = t.as_secs_f32() * 10.0; + assert!( + (e.pos[0] - expected).abs() < 1e-3, + "{} vs {expected}", + e.pos[0] + ); + assert!((e.fields[0] - expected).abs() < 1e-3); + } + + #[test] + fn laggy_shot_misses_now_but_hits_at_view_time() { + let rw = history(RewindConfig::default(), 60); + let latest = rw.latest().unwrap().time(); + // Client saw tick 54 rendered 100 ms behind: view = t(54) - 100 ms. + let timing = ShotTiming { + client_tick: 54, + interp_delay: MS(100), + }; + let view = rw.resolve(timing).unwrap(); + assert!(!view.clamped); + let seen_x = view.time.as_secs_f32() * 10.0; + // Shoot straight up (+y) through where the target was on screen. + let ray = HitQuery::ray([seen_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + assert!( + rw.hit_test(latest, &ray, |_| true).is_none(), + "present-time target has moved on" + ); + let (hit, resolved) = rw.hit_test_shot(timing, &ray, |_| true).unwrap(); + assert_eq!(hit.id, 7); + assert!((hit.distance - 9.5).abs() < 1e-3, "{}", hit.distance); + assert_eq!(resolved, view); + } + + #[test] + fn rewind_beyond_max_is_clamped() { + let rw = history( + RewindConfig { + max_rewind: MS(250), + max_frames: 1024, + }, + 90, + ); + let latest = rw.latest().unwrap().time(); + // Cheater claims a 2 s old view to hit where the target was then. + let timing = ShotTiming { + client_tick: 90, + interp_delay: Duration::from_secs(2), + }; + let resolved = rw.resolve(timing).unwrap(); + assert!(resolved.clamped); + assert_eq!(resolved.age, MS(250)); + assert_eq!(resolved.requested_age, Duration::from_secs(2)); + let old_x = (latest - Duration::from_secs(2)).as_secs_f32() * 10.0; + let ray = HitQuery::ray([old_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + assert!(rw.hit_test_shot(timing, &ray, |_| true).is_none()); + // Within the clamp the same request style still works. + let ok_x = (latest - MS(200)).as_secs_f32() * 10.0; + let ray = HitQuery::ray([ok_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + let timing = ShotTiming { + client_tick: 90, + interp_delay: MS(200), + }; + assert_eq!(rw.hit_test_shot(timing, &ray, |_| true).unwrap().0.id, 7); + } + + #[test] + fn future_ticks_resolve_to_latest() { + let rw = history(RewindConfig::default(), 30); + let timing = ShotTiming { + client_tick: 40, + interp_delay: Duration::ZERO, + }; + let r = rw.resolve(timing).unwrap(); + assert_eq!(r.time, rw.latest().unwrap().time()); + assert_eq!(r.age, Duration::ZERO); + } + + #[test] + fn capsule_segment_and_point_queries() { + let rw = history(RewindConfig::default(), 5); + let now = rw.latest().unwrap().time(); + // Horizontal shot through the capsule's cylinder. + let shot = HitQuery::ray([-60.0, 0.0, 1.0], [1.0, 0.0, 0.0], 50.0); + let hit = rw.hit_test(now, &shot, |id| id == 9).unwrap(); + assert!( + (hit.distance - (10.0 - 0.4)).abs() < 1e-3, + "{}", + hit.distance + ); + // Through the upper cap: entry = 10 - sqrt(0.4² - 0.2²). + let cap = HitQuery::ray([-60.0, 0.0, 2.0], [1.0, 0.0, 0.0], 50.0); + let hit = rw.hit_test(now, &cap, |id| id == 9).unwrap(); + assert!((hit.distance - (10.0 - 0.12f32.sqrt())).abs() < 1e-3); + // Above the capsule (z = 2.3 > 1.8 + 0.4) misses. + let over = HitQuery::ray([-60.0, 0.0, 2.3], [1.0, 0.0, 0.0], 50.0); + assert!(rw.hit_test(now, &over, |id| id == 9).is_none()); + // Too short a segment misses. + let short = HitQuery::ray([-60.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + assert!(rw.hit_test(now, &short, |_| true).is_none()); + // Point-in-radius. + assert_eq!( + rw.overlaps(now, &HitQuery::point([-50.2, 0.0, 0.5], 0.0))[0].id, + 9 + ); + assert!(rw + .overlaps(now, &HitQuery::point([-49.0, 0.0, 0.5], 0.2)) + .is_empty()); + // Filter excludes the shooter. + assert!(rw.hit_test(now, &shot, |id| id != 9).is_none()); + } +} diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index 0a70726e1..ba4f9e4d4 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -14,6 +14,7 @@ use crate::facts::FactSettlement; use crate::host::Ctx; use crate::protocol::Role; use crate::replication::WorldView; +use crate::rewind::RewindFrame; use crate::schema::EntitySchema; use crate::timers::TimerId; @@ -190,6 +191,17 @@ pub trait Zone: Sized + Send + 'static { /// Describe replicated entities for this patch. fn replicate(&self, out: &mut WorldView); + /// Record hit volumes for lag compensation after each tick + /// ([`Ctx::rewind`](crate::Ctx::rewind)). Default: nothing recorded. + fn record_rewind(&self, _frame: &mut RewindFrame) {} + + /// Digest of the authoritative state for record/replay + /// ([`replay`](mod@crate::replay)). `None` hashes the replicated + /// [`WorldView`] instead, which misses unreplicated state. + fn state_hash(&self) -> Option { + None + } + /// The zone is being destroyed; timers are cleared afterwards. fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) {} } diff --git a/distributed_game/tests/netcode/main.rs b/distributed_game/tests/netcode/main.rs new file mode 100644 index 000000000..de3e464d5 --- /dev/null +++ b/distributed_game/tests/netcode/main.rs @@ -0,0 +1,362 @@ +//! P8 netcode: lag compensation through `Ctx::rewind`, and deterministic +//! record/replay with divergence detection. + +#[path = "../zone_runtime/arena.rs"] +mod arena; + +use std::sync::Arc; +use std::time::Duration; + +use arena::{Arena, ArenaConfig}; +use distributed_game::replay::{replay, DivergenceKind, Event, JoinResult, Recorder, Recording}; +use distributed_game::rewind::{Historic, HitQuery, RewindConfig, RewindFrame, ShotTiming}; +use distributed_game::{ + fact_channel, spawn_fact_worker, ClientMirror, ConsumePolicy, Ctx, EntitySchema, EntityState, + FieldType, FieldValue, HostConfig, KindDef, ManualClock, MemoryFactSink, Outbound, PlayerId, + RetryPolicy, Role, ServerMessage, TicketClaims, WorldView, Zone, ZoneHost, ZoneRng, +}; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + } +} + +// ---------------------------------------------------------------- rewind + +const TARGET: u32 = 100; +const SPEED: f32 = 10.0; + +#[derive(Debug, Clone, PartialEq)] +struct ShotResult { + rewound: Option, + present: Option, + clamped: bool, + age: Duration, +} + +/// A target crosses the map along y = 10 at 10 u/s; players shoot straight +/// up (+y) from (aim_x, 0) and report their interpolation delay in the +/// payload: `aim_x: f32 LE ‖ interp_ms: u16 LE`. +struct Range { + target_x: f32, + shots: Vec, +} + +impl Zone for Range { + type Config = (); + type Input = (f32, u16); + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "target").field("x", FieldType::F32)) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { + Range { + target_x: 0.0, + shots: Vec::new(), + } + } + + fn decode_input(&self, _p: PlayerId, b: &[u8]) -> Option<(f32, u16)> { + let b: &[u8; 6] = b.try_into().ok()?; + Some(( + f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + u16::from_le_bytes([b[4], b[5]]), + )) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + for p in players { + for input in ctx.take_inputs(p, ConsumePolicy::Drain) { + let (aim_x, interp_ms) = input.input; + let timing = ShotTiming { + client_tick: input.client_tick, + interp_delay: Duration::from_millis(u64::from(interp_ms)), + }; + let ray = HitQuery::ray([aim_x, 0.0, 0.0], [0.0, 1.0, 0.0], 50.0); + let rewind = ctx.rewind(); + let resolved = rewind.resolve(timing).expect("history"); + let present = rewind.latest().unwrap().time(); + self.shots.push(ShotResult { + rewound: rewind.hit_test(resolved.time, &ray, |_| true).map(|h| h.id), + present: rewind.hit_test(present, &ray, |_| true).map(|h| h.id), + clamped: resolved.clamped, + age: resolved.age, + }); + } + } + self.target_x += SPEED * ctx.dt_secs(); + } + + fn record_rewind(&self, frame: &mut RewindFrame) { + frame.push(Historic::sphere(TARGET, [self.target_x, 10.0, 0.0], 0.5)); + } + + fn replicate(&self, out: &mut WorldView) { + out.push(EntityState::new( + TARGET, + 1, + self.target_x, + 10.0, + vec![FieldValue::F(self.target_x)], + )); + } +} + +fn shot(aim_x: f32, interp_ms: u16) -> Vec { + let mut b = aim_x.to_le_bytes().to_vec(); + b.extend_from_slice(&interp_ms.to_le_bytes()); + b +} + +#[test] +fn ctx_rewind_hits_at_view_time_and_clamps_cheats() { + let clock = ManualClock::new(); + let config = HostConfig { + rewind: RewindConfig { + max_rewind: Duration::from_millis(300), + max_frames: 128, + }, + ..HostConfig::default() + }; + let mut h = ZoneHost::::new("range", config, Arc::new(clock.clone()), ()); + let joined = h.join(&claims("sniper", "range"), 0, "").unwrap(); + let step = Duration::from_secs(1) / 30; + for _ in 0..90 { + clock.advance(step); + h.advance(); + } + let latest = h.rewind().latest().unwrap().clone(); + assert!(h.rewind().len() <= h.rewind().capacity()); + + // The client was rendering tick latest-4 with a 100 ms interpolation + // delay and aimed exactly at the target as drawn (~233 ms in the past). + let client_tick = (latest.tick() - 4) as u32; + let view = h.rewind().time_of(client_tick).unwrap() - Duration::from_millis(100); + let seen_x = h.rewind().entity_at(TARGET, view).unwrap().pos[0]; + h.push_input(joined.client, 1, client_tick, &shot(seen_x, 100)); + + // A cheater claims a 2 s interpolation delay to hit an old position. + let old_x = (latest.time() - Duration::from_secs(2)).as_secs_f32() * SPEED; + h.push_input(joined.client, 2, latest.tick() as u32, &shot(old_x, 2000)); + + clock.advance(step); + h.advance(); + let shots = &h.zone().shots; + assert_eq!(shots.len(), 2); + assert_eq!( + shots[0].rewound, + Some(TARGET), + "laggy shot hits at view time" + ); + assert_eq!(shots[0].present, None, "same shot misses at present time"); + assert!(!shots[0].clamped); + assert!(shots[0].age > Duration::from_millis(200) && shots[0].age < Duration::from_millis(300)); + assert!(shots[1].clamped, "2 s rewind is clamped"); + assert_eq!(shots[1].age, Duration::from_millis(300)); + assert_eq!( + shots[1].rewound, None, + "clamped rewind cannot reach 2 s ago" + ); +} + +// ---------------------------------------------------------------- replay + +struct Session { + recording: Recording, + /// Final `ZoneHost::state_hash` of the live run. + final_hash: u64, +} + +fn reconnect_token(out: &[Outbound], client: u32) -> Option { + out.iter().rev().find_map(|o| match o { + Outbound::Frame { client: c, frame } if c.0 == client => { + match ClientMirror::new().apply(frame) { + Ok(ServerMessage::Welcome(w)) => Some(w.reconnect_token), + _ => None, + } + } + _ => None, + }) +} + +/// Four players move randomly over uneven clock steps; one drops and +/// reconnects with its token, one leaves; heartbeat facts settle through a +/// real async worker. +async fn record_session() -> Session { + let clock = ManualClock::new(); + let config = HostConfig { + world_seed: 0xdead_beef, + ..HostConfig::default() + }; + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let (queue, feed) = fact_channel(64, RetryPolicy::default()); + spawn_fact_worker(feed, MemoryFactSink::new()); + let mut rec = Recorder::::new("arena-1", config, Arc::new(clock.clone()), cfg, vec![]) + .with_facts(queue, 64); + let mut rng = ZoneRng::from_seed(42); + let mut clients = Vec::new(); + let mut seqs = [0u32; 4]; + let mut token = None; + for step in 0..120u32 { + if step < 4 * 5 && step % 5 == 0 { + let i = (step / 5) as usize; + let joined = rec + .join(&claims(&format!("p{i}"), "arena-1"), 0, "") + .unwrap(); + clients.push(joined.client); + let out = rec.drain_outbound(); + if i == 2 { + token = reconnect_token(&out, joined.client.0); + } + } + if step == 40 { + rec.disconnect(clients[2], false); + } + if step == 55 { + let joined = rec.reconnect(token.as_deref().unwrap(), 0).unwrap(); + clients[2] = joined.client; + } + if step == 90 { + rec.disconnect(clients[3], true); + } + for (i, client) in clients.iter().enumerate() { + if (step == 90 && i == 3) || step > 90 && i == 3 || (40..55).contains(&step) && i == 2 { + continue; + } + if rng.chance(0.7) { + seqs[i] += 1; + let dx = rng.range_u32(0, 3) as i8 - 1; + let dy = rng.range_u32(0, 3) as i8 - 1; + rec.push_input(*client, seqs[i], step, &[dx as u8, dy as u8]); + } + } + clock.advance(Duration::from_millis(u64::from(rng.range_u32(10, 70)))); + rec.advance(); + rec.drain_outbound(); + if step % 7 == 0 { + tokio::time::sleep(Duration::from_millis(1)).await; + } + } + // Let outstanding facts settle, then deliver them. + tokio::time::sleep(Duration::from_millis(20)).await; + clock.advance(Duration::from_millis(40)); + rec.advance(); + let final_hash = rec.host().state_hash(); + Session { + recording: rec.finish(), + final_hash, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn recorded_session_replays_identically() { + let session = record_session().await; + let rec = &session.recording; + let settled: usize = rec + .events + .iter() + .map(|e| match e { + Event::Advance { settled, .. } => settled.len(), + _ => 0, + }) + .sum(); + assert!(settled > 0, "facts settled during the recording"); + assert!(rec.events.iter().any(|e| matches!( + e, + Event::Reconnect { + result: JoinResult::Joined(_), + .. + } + ))); + assert!(rec.tick_count() > 120, "{}", rec.tick_count()); + + // Compact file round trip. + let bytes = rec.encode(); + let path = std::env::temp_dir().join(format!("dg-replay-{}.dgr", std::process::id())); + rec.save(&path).unwrap(); + let loaded = Recording::load(&path).unwrap(); + std::fs::remove_file(&path).ok(); + assert_eq!(&loaded, rec); + let per_tick = bytes.len() as f64 / rec.tick_count() as f64; + // ~3 inputs, one heartbeat settlement and an 8-byte hash per tick. + assert!(per_tick < 96.0, "{} bytes, {per_tick:.1}/tick", bytes.len()); + + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let summary = replay::(&loaded, cfg).unwrap_or_else(|d| panic!("{d}")); + assert_eq!(summary.ticks as usize, rec.tick_count()); + assert_eq!(summary.final_hash, session.final_hash); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mutated_input_diverges_at_the_consuming_tick() { + let mut rec = record_session().await.recording; + // Flip the x direction of a mid-session input from p0 (never drops). + let p0 = match &rec.events[0] { + Event::Join { + result: JoinResult::Joined(c), + .. + } => *c, + other => panic!("{other:?}"), + }; + let (index, seq) = rec + .events + .iter() + .enumerate() + .skip(rec.events.len() / 2) + .find_map(|(i, e)| match e { + Event::Input { + client, + payload, + seq, + .. + } if *client == p0 && payload[0] != 0 => Some((i, *seq)), + _ => None, + }) + .expect("an input to mutate"); + if let Event::Input { payload, .. } = &mut rec.events[index] { + payload[0] = (-(payload[0] as i8)) as u8; + } + let consuming_tick = rec.events[index..] + .iter() + .find_map(|e| match e { + Event::Advance { hashes, .. } => hashes.first().map(|(t, _)| *t), + _ => None, + }) + .unwrap(); + + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let divergence = replay::(&rec, cfg).expect_err("mutation must be detected"); + assert_eq!(divergence.tick, consuming_tick); + assert_eq!(divergence.last_good_tick, consuming_tick - 1); + assert!(matches!(divergence.kind, DivergenceKind::StateHash { .. })); + let report = divergence.to_string(); + println!("{report}"); + assert!( + report.contains(&format!("diverged at tick {consuming_tick}")), + "{report}" + ); + assert!( + report.contains(&format!("client {p0} seq {seq} ")), + "report names the suspect input:\n{report}" + ); +} From 5fafeb2232d2710e63a22e6955276d562c088bdd Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:20:28 -0500 Subject: [PATCH 129/484] feat(game): add per-zone metrics, /metrics and NetSim loss New dependency-free `metrics` feature (implied by `net`): an instance-scoped GameMetrics registry rendering Prometheus text for tick duration, ticks/dropped ticks, tier, players, observers, entities, inputs by outcome (incl. transport rate limiting), Delta bytes per frame and facts pending/settled. The zone label is bounded: only the first ServerConfig::metrics_zone_labels live zones are labelled, the rest fold into zone="_other", and stopped zones free their slot. GameServer serves it at GET /metrics. The core distributed::metrics registry stays untouched: it is a fixed, process-global framework set and distributed_game does not depend on distributed outside the `cell` feature. NetSim gains loss with WebSocket-correct semantics (a retransmission delay with head-of-line blocking, never a dropped or reordered frame) and NetSim::from_env for demos. [[tasks/gr-p8-netcode-ops]] --- distributed_game/Cargo.toml | 6 +- distributed_game/src/lib.rs | 2 + distributed_game/src/metrics.rs | 673 +++++++++++++++++++++++++ distributed_game/src/net/mod.rs | 154 +++++- distributed_game/tests/net_e2e/main.rs | 1 + 5 files changed, 824 insertions(+), 12 deletions(-) create mode 100644 distributed_game/src/metrics.rs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 920f0b5c4..1aae5a384 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -16,8 +16,10 @@ default = [] runtime = ["dep:tokio"] # Adapter that commits facts into a `distributed` AggregateCell. cell = ["dep:distributed", "dep:sha2"] -# axum WebSocket zone server with signed-ticket admission. -net = ["runtime", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros"] +# Per-zone Prometheus metrics (dependency-free text exposition). +metrics = [] +# axum WebSocket zone server with signed-ticket admission (+ /metrics). +net = ["runtime", "metrics", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros"] [dependencies] serde_json = "1" diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index c709c9b61..361ef8876 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -32,6 +32,8 @@ pub mod facts; pub mod host; pub mod input; pub mod interest; +#[cfg(feature = "metrics")] +pub mod metrics; #[cfg(feature = "net")] pub mod net; pub mod protocol; diff --git a/distributed_game/src/metrics.rs b/distributed_game/src/metrics.rs new file mode 100644 index 000000000..5490e32fb --- /dev/null +++ b/distributed_game/src/metrics.rs @@ -0,0 +1,673 @@ +//! Per-zone Prometheus metrics (`metrics` feature, no dependencies). +//! +//! Why not the core `distributed::metrics` registry: that registry is a +//! deliberately *fixed* set of framework families with typed keys behind a +//! process-global `OnceLock`, and `distributed_game` does not depend on +//! `distributed` at all outside the `cell` feature. Game metrics need an +//! instance-scoped registry (one per [`GameServer`](crate::net::GameServer), +//! parallel test servers) and a zone label, so this module renders its own +//! Prometheus text (exposition format 0.0.4). Both expositions can be served +//! side by side; family names are prefixed `distributed_game_`. +//! +//! **Cardinality guard.** Zone ids are unbounded, so only the first +//! [`GameMetrics::max_zone_labels`] live zones get their own `zone` label; +//! every other zone is folded into `zone="_other"` (counters and histograms +//! accumulate there, gauges are summed at render time). When a zone stops +//! ([`GameMetrics::forget_zone`]) its series are dropped and its label slot +//! is freed. Series count is therefore bounded by +//! `(max_zone_labels + 1) × families × fixed label values`. Other labels +//! (`tier`, `outcome`) have fixed value sets. Principals and player ids are +//! never labels. +//! +//! Families: +//! +//! | Name | Type | Labels | +//! |---|---|---| +//! | `distributed_game_zones` | gauge | – | +//! | `distributed_game_zone_tick_duration_seconds` | histogram | zone | +//! | `distributed_game_zone_ticks_total` | counter | zone | +//! | `distributed_game_zone_ticks_dropped_total` | counter | zone | +//! | `distributed_game_zone_tier` | gauge (one-hot) | zone, tier | +//! | `distributed_game_zone_players` / `_observers` / `_entities` | gauge | zone | +//! | `distributed_game_zone_inputs_total` | counter | zone, outcome | +//! | `distributed_game_zone_patches_total` | counter | zone | +//! | `distributed_game_zone_delta_bytes` | histogram (per Delta frame) | zone | +//! | `distributed_game_zone_delta_bytes_total` | counter | zone | +//! | `distributed_game_zone_delta_deferred_total` | counter | zone | +//! | `distributed_game_zone_facts_pending` | gauge | zone | +//! | `distributed_game_zone_facts_settled_total` | counter | zone, outcome | + +use crate::facts::FactOutcome; +use crate::host::{AdvanceReport, ZoneHost}; +use crate::input::PushOutcome; +use crate::zone::{Tier, Zone}; +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::sync::Mutex; + +/// Label for zones beyond the cardinality budget. +pub const OTHER_ZONE: &str = "_other"; + +const TICK_BUCKETS: [f64; 12] = [ + 0.000_05, 0.000_1, 0.000_25, 0.000_5, 0.001, 0.002_5, 0.005, 0.01, 0.016, 0.033, 0.05, 0.1, +]; +const BYTE_BUCKETS: [f64; 10] = [ + 16.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 16384.0, 65536.0, +]; + +/// Input outcome label values (fixed set). +pub const INPUT_OUTCOMES: [&str; 7] = [ + "accepted", + "dropped_oldest", + "duplicate", + "stale", + "rejected", + "unknown_client", + "rate_limited", +]; + +fn input_label(outcome: PushOutcome) -> &'static str { + match outcome { + PushOutcome::Accepted => "accepted", + PushOutcome::AcceptedDroppedOldest => "dropped_oldest", + PushOutcome::Duplicate => "duplicate", + PushOutcome::Stale => "stale", + PushOutcome::Rejected => "rejected", + PushOutcome::UnknownClient => "unknown_client", + } +} + +#[derive(Debug, Clone)] +struct Histogram { + bounds: &'static [f64], + counts: Vec, + sum: f64, + count: u64, +} + +impl Histogram { + fn new(bounds: &'static [f64]) -> Self { + Self { + bounds, + counts: vec![0; bounds.len()], + sum: 0.0, + count: 0, + } + } + + fn observe(&mut self, v: f64) { + for (bound, count) in self.bounds.iter().zip(self.counts.iter_mut()) { + if v <= *bound { + *count += 1; + } + } + self.sum += v; + self.count += 1; + } +} + +/// Monotonic per-zone series. +#[derive(Debug, Clone)] +struct Counters { + tick_duration: Histogram, + ticks: u64, + ticks_dropped: u64, + inputs: BTreeMap<&'static str, u64>, + patches: u64, + delta_bytes: Histogram, + delta_bytes_total: u64, + delta_deferred: u64, + facts_committed: u64, + facts_failed: u64, +} + +impl Default for Counters { + fn default() -> Self { + Self { + tick_duration: Histogram::new(&TICK_BUCKETS), + ticks: 0, + ticks_dropped: 0, + inputs: BTreeMap::new(), + patches: 0, + delta_bytes: Histogram::new(&BYTE_BUCKETS), + delta_bytes_total: 0, + delta_deferred: 0, + facts_committed: 0, + facts_failed: 0, + } + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct Gauges { + tier: Option, + players: usize, + observers: usize, + entities: usize, + facts_pending: usize, +} + +#[derive(Debug, Default)] +struct ZoneSeries { + labeled: bool, + counters: Counters, + gauges: Gauges, +} + +#[derive(Debug, Default)] +struct State { + zones: BTreeMap, + labeled: usize, + other: Counters, +} + +impl State { + fn zone(&mut self, zone: &str, max: usize) -> &mut ZoneSeries { + if !self.zones.contains_key(zone) { + let labeled = self.labeled < max; + if labeled { + self.labeled += 1; + } + self.zones.insert( + zone.to_string(), + ZoneSeries { + labeled, + ..ZoneSeries::default() + }, + ); + } + self.zones.get_mut(zone).expect("inserted") + } + + fn counters(&mut self, zone: &str, max: usize) -> &mut Counters { + if self.zone(zone, max).labeled { + &mut self.zones.get_mut(zone).expect("present").counters + } else { + &mut self.other + } + } +} + +/// Instance-scoped game metrics registry. +#[derive(Debug)] +pub struct GameMetrics { + max_zone_labels: usize, + state: Mutex, +} + +impl Default for GameMetrics { + fn default() -> Self { + Self::new(64) + } +} + +impl GameMetrics { + /// Registry giving at most `max_zone_labels` live zones their own label. + pub fn new(max_zone_labels: usize) -> Self { + Self { + max_zone_labels, + state: Mutex::new(State::default()), + } + } + + /// Cardinality budget for the `zone` label. + pub fn max_zone_labels(&self) -> usize { + self.max_zone_labels + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Record one [`ZoneHost::advance`] and the host's current gauges. + pub fn record_advance(&self, host: &ZoneHost, report: &AdvanceReport) { + let max = self.max_zone_labels; + let mut state = self.lock(); + let series = state.zone(host.zone_id(), max); + series.gauges = Gauges { + tier: Some(host.tier()), + players: host.player_count(), + observers: host.observer_count(), + entities: report.entities.unwrap_or(series.gauges.entities), + facts_pending: host.facts_in_flight(), + }; + let c = state.counters(host.zone_id(), max); + for d in &report.tick_durations { + c.tick_duration.observe(d.as_secs_f64()); + } + c.ticks += u64::from(report.ticks); + c.ticks_dropped += u64::from(report.dropped_ticks); + if report.patched { + c.patches += 1; + } + for frame in &report.frames { + c.delta_bytes.observe(frame.bytes as f64); + c.delta_bytes_total += frame.bytes as u64; + c.delta_deferred += frame.stats.deferred as u64; + } + for (_, s) in &report.settled { + match s.outcome { + FactOutcome::Committed(_) => c.facts_committed += 1, + FactOutcome::Failed { .. } => c.facts_failed += 1, + } + } + } + + /// Record an input offer outcome. + pub fn record_input(&self, zone: &str, outcome: PushOutcome) { + self.record_input_label(zone, input_label(outcome)); + } + + /// Record an input dropped by the transport's rate limiter. + pub fn record_rate_limited(&self, zone: &str) { + self.record_input_label(zone, "rate_limited"); + } + + fn record_input_label(&self, zone: &str, label: &'static str) { + let max = self.max_zone_labels; + *self + .lock() + .counters(zone, max) + .inputs + .entry(label) + .or_insert(0) += 1; + } + + /// A zone stopped: drop its series and free its label slot. + pub fn forget_zone(&self, zone: &str) { + let mut state = self.lock(); + if let Some(series) = state.zones.remove(zone) { + if series.labeled { + state.labeled -= 1; + } + } + } + + /// Zones currently tracked. + pub fn zone_count(&self) -> usize { + self.lock().zones.len() + } + + /// Prometheus text exposition (format 0.0.4). + pub fn render(&self) -> String { + let state = self.lock(); + let mut out = String::new(); + let labeled: Vec<(&str, &ZoneSeries)> = state + .zones + .iter() + .filter(|(_, s)| s.labeled) + .map(|(z, s)| (z.as_str(), s)) + .collect(); + let overflow: Vec<&ZoneSeries> = state.zones.values().filter(|s| !s.labeled).collect(); + let mut counter_rows: Vec<(&str, &Counters)> = + labeled.iter().map(|(z, s)| (*z, &s.counters)).collect(); + if !overflow.is_empty() + || state.other.ticks > 0 + || !state.other.inputs.is_empty() + || state.other.patches > 0 + { + counter_rows.push((OTHER_ZONE, &state.other)); + } + let mut gauge_rows: Vec<(&str, Gauges, [u64; 3])> = labeled + .iter() + .map(|(z, s)| (*z, s.gauges, tier_hot(s.gauges.tier))) + .collect(); + if !overflow.is_empty() { + let mut sum = Gauges::default(); + let mut tiers = [0u64; 3]; + for s in &overflow { + sum.players += s.gauges.players; + sum.observers += s.gauges.observers; + sum.entities += s.gauges.entities; + sum.facts_pending += s.gauges.facts_pending; + for (t, v) in tiers.iter_mut().zip(tier_hot(s.gauges.tier)) { + *t += v; + } + } + gauge_rows.push((OTHER_ZONE, sum, tiers)); + } + + header(&mut out, "zones", "gauge", "Zones currently hosted."); + let _ = writeln!(out, "distributed_game_zones {}", state.zones.len()); + + header( + &mut out, + "zone_tick_duration_seconds", + "histogram", + "Wall time of one fixed simulation step.", + ); + for (zone, c) in &counter_rows { + histogram( + &mut out, + "zone_tick_duration_seconds", + zone, + &c.tick_duration, + ); + } + counter( + &mut out, + "zone_ticks_total", + "Fixed steps simulated.", + &counter_rows, + |c| c.ticks, + ); + counter( + &mut out, + "zone_ticks_dropped_total", + "Fixed steps dropped by the catch-up cap.", + &counter_rows, + |c| c.ticks_dropped, + ); + + header( + &mut out, + "zone_tier", + "gauge", + "Activity tier (one-hot; summed for _other).", + ); + for (zone, _, tiers) in &gauge_rows { + for (name, v) in ["hot", "idle", "dormant"].iter().zip(tiers) { + let _ = writeln!( + out, + "distributed_game_zone_tier{{zone=\"{}\",tier=\"{name}\"}} {v}", + escape(zone) + ); + } + } + gauge( + &mut out, + "zone_players", + "Players (incl. reconnect grace).", + &gauge_rows, + |g| g.players, + ); + gauge(&mut out, "zone_observers", "Observers.", &gauge_rows, |g| { + g.observers + }); + gauge( + &mut out, + "zone_entities", + "Replicated entities at the last patch.", + &gauge_rows, + |g| g.entities, + ); + gauge( + &mut out, + "zone_facts_pending", + "Unsettled facts.", + &gauge_rows, + |g| g.facts_pending, + ); + + header( + &mut out, + "zone_inputs_total", + "counter", + "Input offers by outcome.", + ); + for (zone, c) in &counter_rows { + for (label, v) in &c.inputs { + let _ = writeln!( + out, + "distributed_game_zone_inputs_total{{zone=\"{}\",outcome=\"{label}\"}} {v}", + escape(zone) + ); + } + } + counter( + &mut out, + "zone_patches_total", + "Patches (Delta rounds).", + &counter_rows, + |c| c.patches, + ); + header( + &mut out, + "zone_delta_bytes", + "histogram", + "Encoded size of one Delta frame.", + ); + for (zone, c) in &counter_rows { + histogram(&mut out, "zone_delta_bytes", zone, &c.delta_bytes); + } + counter( + &mut out, + "zone_delta_bytes_total", + "Delta bytes produced.", + &counter_rows, + |c| c.delta_bytes_total, + ); + counter( + &mut out, + "zone_delta_deferred_total", + "Entity changes deferred by the byte budget.", + &counter_rows, + |c| c.delta_deferred, + ); + header( + &mut out, + "zone_facts_settled_total", + "counter", + "Fact settlements delivered to zones by outcome.", + ); + for (zone, c) in &counter_rows { + for (label, v) in [("committed", c.facts_committed), ("failed", c.facts_failed)] { + let _ = writeln!( + out, + "distributed_game_zone_facts_settled_total{{zone=\"{}\",outcome=\"{label}\"}} {v}", + escape(zone) + ); + } + } + out + } +} + +fn tier_hot(tier: Option) -> [u64; 3] { + match tier { + Some(Tier::Hot) => [1, 0, 0], + Some(Tier::Idle) => [0, 1, 0], + Some(Tier::Dormant) => [0, 0, 1], + None => [0, 0, 0], + } +} + +fn escape(v: &str) -> String { + v.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") +} + +fn header(out: &mut String, name: &str, kind: &str, help: &str) { + let _ = writeln!(out, "# HELP distributed_game_{name} {help}"); + let _ = writeln!(out, "# TYPE distributed_game_{name} {kind}"); +} + +fn counter( + out: &mut String, + name: &str, + help: &str, + rows: &[(&str, &Counters)], + value: impl Fn(&Counters) -> u64, +) { + header(out, name, "counter", help); + for (zone, c) in rows { + let _ = writeln!( + out, + "distributed_game_{name}{{zone=\"{}\"}} {}", + escape(zone), + value(c) + ); + } +} + +fn gauge( + out: &mut String, + name: &str, + help: &str, + rows: &[(&str, Gauges, [u64; 3])], + value: impl Fn(&Gauges) -> usize, +) { + header(out, name, "gauge", help); + for (zone, g, _) in rows { + let _ = writeln!( + out, + "distributed_game_{name}{{zone=\"{}\"}} {}", + escape(zone), + value(g) + ); + } +} + +fn histogram(out: &mut String, name: &str, zone: &str, h: &Histogram) { + let zone = escape(zone); + for (bound, count) in h.bounds.iter().zip(&h.counts) { + let _ = writeln!( + out, + "distributed_game_{name}_bucket{{zone=\"{zone}\",le=\"{bound}\"}} {count}" + ); + } + let _ = writeln!( + out, + "distributed_game_{name}_bucket{{zone=\"{zone}\",le=\"+Inf\"}} {}", + h.count + ); + let _ = writeln!( + out, + "distributed_game_{name}_sum{{zone=\"{zone}\"}} {}", + h.sum + ); + let _ = writeln!( + out, + "distributed_game_{name}_count{{zone=\"{zone}\"}} {}", + h.count + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + ClientMirror, EntitySchema, EntityState, FieldType, FieldValue, KindDef, ManualClock, Role, + TicketClaims, WorldView, Zone, ZoneHost, + }; + use std::sync::Arc; + use std::time::Duration; + + struct Dots; + + impl Zone for Dots { + type Config = (); + type Input = u8; + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "dot").field("v", FieldType::U8)) + } + + fn on_create(_ctx: &mut crate::Ctx<'_, Self>, _: ()) -> Self { + Dots + } + + fn decode_input(&self, _p: crate::PlayerId, b: &[u8]) -> Option { + b.first().copied() + } + + fn on_tick(&mut self, _ctx: &mut crate::Ctx<'_, Self>) {} + + fn replicate(&self, out: &mut WorldView) { + for i in 0..3 { + out.push(EntityState::new(i, 1, 0.0, 0.0, vec![FieldValue::U(i)])); + } + } + } + + fn host(zone: &str, clock: &ManualClock) -> ZoneHost { + ZoneHost::new(zone, Default::default(), Arc::new(clock.clone()), ()) + } + + #[test] + fn records_zone_metrics_and_renders_prometheus() { + let metrics = GameMetrics::new(8); + let clock = ManualClock::new(); + let mut h = host("z1", &clock); + let claims = TicketClaims { + principal: "a".into(), + zone: "z1".into(), + expires_at: u64::MAX, + nonce: "n".into(), + role: Role::Player, + }; + let joined = h.join(&claims, 0, "").unwrap(); + metrics.record_input("z1", h.push_input(joined.client, 1, 0, &[1])); + metrics.record_input("z1", h.push_input(joined.client, 1, 0, &[1])); + metrics.record_rate_limited("z1"); + clock.advance(Duration::from_millis(100)); + let report = h.advance(); + assert_eq!(report.frames.len(), 1); + let mut mirror = ClientMirror::new(); + for o in h.drain_outbound() { + if let crate::Outbound::Frame { frame, .. } = o { + mirror.apply(&frame).unwrap(); + } + } + assert_eq!(mirror.entities.len(), 3); + metrics.record_advance(&h, &report); + let text = metrics.render(); + assert!(text.contains("distributed_game_zones 1"), "{text}"); + assert!( + text.contains("distributed_game_zone_ticks_total{zone=\"z1\"} 3"), + "{text}" + ); + assert!(text.contains("distributed_game_zone_tier{zone=\"z1\",tier=\"hot\"} 1")); + assert!(text.contains("distributed_game_zone_players{zone=\"z1\"} 1")); + assert!(text.contains("distributed_game_zone_entities{zone=\"z1\"} 3")); + assert!( + text.contains("distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"accepted\"} 1") + ); + assert!(text + .contains("distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"duplicate\"} 1")); + assert!(text.contains( + "distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"rate_limited\"} 1" + )); + assert!(text.contains("distributed_game_zone_delta_bytes_count{zone=\"z1\"} 1")); + assert!(text.contains("distributed_game_zone_tick_duration_seconds_count{zone=\"z1\"} 3")); + assert!(text.contains("# TYPE distributed_game_zone_delta_bytes histogram")); + } + + #[test] + fn zone_label_cardinality_is_bounded() { + let metrics = GameMetrics::new(2); + let clock = ManualClock::new(); + let mut hosts: Vec<_> = (0..5).map(|i| host(&format!("zone-{i}"), &clock)).collect(); + clock.advance(Duration::from_millis(100)); + for h in &mut hosts { + let r = h.advance(); + metrics.record_advance(h, &r); + } + let text = metrics.render(); + let zones: std::collections::BTreeSet<&str> = text + .lines() + .filter(|l| l.starts_with("distributed_game_zone_ticks_total{")) + .map(|l| l.split('"').nth(1).unwrap()) + .collect(); + assert_eq!( + zones.into_iter().collect::>(), + vec!["_other", "zone-0", "zone-1"] + ); + assert!( + text.contains("distributed_game_zone_ticks_total{zone=\"_other\"} 0"), + "{text}" + ); + assert!(text.contains("distributed_game_zone_tier{zone=\"_other\",tier=\"hot\"} 0")); + assert!(text.contains("distributed_game_zone_tier{zone=\"_other\",tier=\"idle\"} 3")); + // A labeled zone stopping frees its slot for the next new zone. + metrics.forget_zone("zone-0"); + let mut late = host("late", &clock); + clock.advance(Duration::from_millis(100)); + let r = late.advance(); + metrics.record_advance(&late, &r); + assert!(metrics.render().contains("zone=\"late\"")); + assert_eq!(metrics.zone_count(), 5); + } +} diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 5bb5cda46..a580d3efc 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -13,7 +13,9 @@ //! - Inputs are rate limited per connection with a token bucket; excess //! inputs are dropped (one `Error(RATE_LIMITED)` per second) and sustained //! abuse is kicked. -//! - [`NetSim`] adds latency/jitter in both directions for development. +//! - [`NetSim`] adds latency/jitter/loss in both directions for development +//! (configurable from the environment with [`NetSim::from_env`]). +//! - `GET /metrics` serves per-zone Prometheus metrics ([`crate::metrics`]). //! - [`GameServer::serve`] shuts down gracefully: every zone kicks its //! clients with `Kick(SHUTDOWN)`, runs `on_dispose`, and connections close. @@ -39,17 +41,86 @@ pub use ticket::{NonceCache, TicketError, TicketKey}; use crate::clock::{Clock, SystemClock}; use crate::facts::{fact_channel, spawn_fact_worker, FactQueue, FactSink, RetryPolicy}; use crate::host::{HostConfig, JoinError, Joined, Outbound, ZoneHost}; +use crate::metrics::GameMetrics; use crate::protocol::{error, kick, ClientMessage, ServerMessage, PROTOCOL_VERSION}; use crate::rng::ZoneRng; use crate::zone::{ClientId, Zone}; -/// Development latency/jitter simulation (applied to each direction). -#[derive(Debug, Clone, Copy, PartialEq)] +/// Development network simulation, applied independently to each direction +/// of every connection. +/// +/// Semantics over WebSocket (a reliable, ordered stream): a message is never +/// dropped or reordered, because Deltas are encoded against the previous +/// one. `loss` models what TCP does with a lost segment instead: with +/// probability `loss` a message is delayed by an extra `retransmit` (repeated +/// with the same probability, at most 3 times), and since order is preserved +/// every later message queues behind it (head-of-line blocking). Total +/// one-way delay = `latency + U[0, jitter] + k·retransmit`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct NetSim { /// Fixed one-way delay. pub latency: Duration, /// Extra uniform random delay in `[0, jitter]` (order is preserved). pub jitter: Duration, + /// Probability in `[0, 1]` that a message needs a retransmission. + pub loss: f32, + /// Delay added per simulated retransmission (TCP minimum RTO ≈ 200 ms). + pub retransmit: Duration, +} + +impl NetSim { + /// Latency + jitter, no loss. + pub fn new(latency: Duration, jitter: Duration) -> Self { + Self { + latency, + jitter, + loss: 0.0, + retransmit: Duration::from_millis(200), + } + } + + /// Add simulated loss (see the type docs for WebSocket semantics). + pub fn with_loss(mut self, loss: f32, retransmit: Duration) -> Self { + self.loss = loss.clamp(0.0, 1.0); + self.retransmit = retransmit; + self + } + + /// Read `DG_NET_LATENCY_MS`, `DG_NET_JITTER_MS`, `DG_NET_LOSS` (fraction, + /// e.g. `0.02`) and `DG_NET_RETRANSMIT_MS` (default 200). `None` when + /// none of the first three is set or all are zero. + pub fn from_env() -> Option { + Self::from_lookup(|key| std::env::var(key).ok()) + } + + /// [`from_env`](Self::from_env) over any key lookup. + pub fn from_lookup(lookup: impl Fn(&str) -> Option) -> Option { + let ms = |key: &str| { + lookup(key) + .and_then(|v| v.trim().parse::().ok()) + .map(Duration::from_millis) + }; + let latency = ms("DG_NET_LATENCY_MS").unwrap_or_default(); + let jitter = ms("DG_NET_JITTER_MS").unwrap_or_default(); + let loss = lookup("DG_NET_LOSS") + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0.0); + let retransmit = ms("DG_NET_RETRANSMIT_MS").unwrap_or(Duration::from_millis(200)); + (!latency.is_zero() || !jitter.is_zero() || loss > 0.0) + .then(|| Self::new(latency, jitter).with_loss(loss, retransmit)) + } + + /// One-way delay for one message. + fn delay(&self, rng: &mut ZoneRng) -> Duration { + let mut delay = self.latency + self.jitter.mul_f32(rng.next_f32()); + for _ in 0..3 { + if self.loss <= 0.0 || !rng.chance(self.loss) { + break; + } + delay += self.retransmit; + } + delay + } } /// Server settings. @@ -71,6 +142,8 @@ pub struct ServerConfig { pub max_frame_bytes: usize, /// Optional dev latency simulation. pub net_sim: Option, + /// Zones that get their own `zone` metrics label (see [`crate::metrics`]). + pub metrics_zone_labels: usize, } impl ServerConfig { @@ -85,6 +158,7 @@ impl ServerConfig { outbound_queue: 512, max_frame_bytes: 64 * 1024, net_sim: None, + metrics_zone_labels: 64, } } } @@ -133,6 +207,7 @@ struct Inner { tasks: Mutex>>, shutdown: watch::Sender, token_counter: AtomicU64, + metrics: Arc, } /// Multi-zone WebSocket game server. @@ -170,7 +245,6 @@ where let (shutdown, _) = watch::channel(false); Self { inner: Arc::new(Inner { - config, clock, factory: Box::new(factory), facts: None, @@ -179,6 +253,8 @@ where tasks: Mutex::new(Vec::new()), shutdown, token_counter: AtomicU64::new(0), + metrics: Arc::new(GameMetrics::new(config.metrics_zone_labels)), + config, }), } } @@ -201,13 +277,19 @@ where self } - /// axum router exposing `GET /zones/{zone_id}`. + /// axum router exposing `GET /zones/{zone_id}` and `GET /metrics`. pub fn router(&self) -> Router { Router::new() .route("/zones/{zone_id}", get(upgrade::)) + .route("/metrics", get(metrics_text::)) .with_state(self.inner.clone()) } + /// Per-zone metrics registry (also served at `GET /metrics`). + pub fn metrics(&self) -> &GameMetrics { + &self.inner.metrics + } + /// Ids of zones currently hosted. pub fn zone_ids(&self) -> Vec { let mut ids: Vec<_> = self @@ -280,6 +362,16 @@ where Some(tx) } +async fn metrics_text(State(inner): State>>) -> Response { + Response::builder() + .header( + axum::http::header::CONTENT_TYPE, + "text/plain; version=0.0.4; charset=utf-8", + ) + .body(axum::body::Body::from(inner.metrics.render())) + .expect("static response") +} + fn unix_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -322,6 +414,7 @@ async fn run_zone( let mut shutdown = inner.shutdown.subscribe(); loop { let report = host.advance(); + inner.metrics.record_advance(&host, &report); route(&mut host, &mut conns); let sleep_for = report .next_wake @@ -342,10 +435,10 @@ async fn run_zone( } cmd = rx.recv() => { let Some(cmd) = cmd else { break }; - handle_cmd(&mut host, &mut conns, cmd); + handle_cmd(&mut host, &mut conns, &inner.metrics, cmd); // Drain whatever else is queued before ticking again. while let Ok(cmd) = rx.try_recv() { - handle_cmd(&mut host, &mut conns, cmd); + handle_cmd(&mut host, &mut conns, &inner.metrics, cmd); } route(&mut host, &mut conns); } @@ -358,11 +451,13 @@ async fn run_zone( } } inner.zones.lock().expect("zones").remove(&zone_id); + inner.metrics.forget_zone(&zone_id); } fn handle_cmd( host: &mut ZoneHost, conns: &mut HashMap>, + metrics: &GameMetrics, cmd: ZoneCmd, ) { match cmd { @@ -397,7 +492,8 @@ fn handle_cmd( client_tick, payload, } => { - host.push_input(client, seq, client_tick, &payload); + let outcome = host.push_input(client, seq, client_tick, &payload); + metrics.record_input(host.zone_id(), outcome); } ZoneCmd::Disconnect { client, graceful } => { conns.remove(&client); @@ -482,8 +578,7 @@ impl DelayLine { let Some(sim) = self.sim else { return Some(item); }; - let jitter = sim.jitter.mul_f32(self.rng.next_f32()); - let at = (Instant::now() + sim.latency + jitter).max(self.last); + let at = (Instant::now() + sim.delay(&mut self.rng)).max(self.last); self.last = at; self.queue.push_back((at, item)); None @@ -671,6 +766,7 @@ where let item = match ClientMessage::decode(&bytes) { Ok(ClientMessage::Input { seq, client_tick, payload }) => { if !bucket.take() { + inner.metrics.record_rate_limited(&zone_id); if bucket.dropped_in_row as f64 > cfg.input_burst { let kick = ServerMessage::Kick { code: kick::RATE_LIMITED, message: "input flood".into() }; let _ = socket.send(Message::Binary(kick.encode(&()).expect("kick").into())).await; @@ -758,3 +854,41 @@ async fn forward_in( } } } + +#[cfg(test)] +mod netsim_tests { + use super::*; + + #[test] + fn netsim_from_env_and_loss_semantics() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |k: &str| { + pairs + .iter() + .find(|(key, _)| *key == k) + .map(|(_, v)| v.to_string()) + } + }; + assert_eq!(NetSim::from_lookup(env(&[])), None); + let sim = NetSim::from_lookup(env(&[ + ("DG_NET_LATENCY_MS", "40"), + ("DG_NET_JITTER_MS", "10"), + ("DG_NET_LOSS", "0.5"), + ])) + .unwrap(); + assert_eq!(sim.latency, Duration::from_millis(40)); + assert_eq!(sim.jitter, Duration::from_millis(10)); + assert_eq!(sim.retransmit, Duration::from_millis(200)); + let mut rng = ZoneRng::from_seed(7); + let delays: Vec = (0..2000).map(|_| sim.delay(&mut rng)).collect(); + let base_max = Duration::from_millis(50); + let retransmitted = delays.iter().filter(|d| **d > base_max).count(); + // P(at least one retransmit) = 0.5. + assert!((850..1150).contains(&retransmitted), "{retransmitted}"); + assert!(delays.iter().all(|d| *d >= sim.latency)); + assert!(delays.iter().all(|d| *d <= base_max + sim.retransmit * 3)); + // Without loss the delay is bounded by latency + jitter. + let clean = NetSim::new(Duration::from_millis(40), Duration::from_millis(10)); + assert!((0..500).all(|_| clean.delay(&mut rng) <= base_max)); + } +} diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs index 26873f33e..c0cac94ab 100644 --- a/distributed_game/tests/net_e2e/main.rs +++ b/distributed_game/tests/net_e2e/main.rs @@ -260,6 +260,7 @@ async fn latency_simulation_delays_but_preserves_order() { let sim = NetSim { latency: Duration::from_millis(40), jitter: Duration::from_millis(20), + ..NetSim::default() }; let (url, server, handle) = start(Some(sim)).await; let mut ws = connect(&url, "z9").await; From 12a09b14b5cdce184287130985dfec80741c58d6 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:20:29 -0500 Subject: [PATCH 130/484] feat(game): add load-test bots and game-bots binary New `bots` feature: a WebSocket bot library built on the reference ClientMirror. Bots mint signed tickets, join a zone, send inputs at a fixed rate from a pluggable Behaviour (random walk, circle), ping for RTT and count Deltas and bytes; run_bots returns a Summary with joined/failed counts, deltas per bot, bytes/s and RTT quantiles. The game-bots binary wraps it with flags/env for demos. A test runs 50 bots against an in-process server and scrapes /metrics. [[tasks/gr-p8-netcode-ops]] --- distributed_game/Cargo.toml | 14 + distributed_game/src/bin/game-bots.rs | 87 +++++ distributed_game/src/bots.rs | 470 ++++++++++++++++++++++++++ distributed_game/src/lib.rs | 2 + distributed_game/tests/bots/main.rs | 103 ++++++ 5 files changed, 676 insertions(+) create mode 100644 distributed_game/src/bin/game-bots.rs create mode 100644 distributed_game/src/bots.rs create mode 100644 distributed_game/tests/bots/main.rs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 1aae5a384..bd6b5b4cc 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -18,6 +18,8 @@ runtime = ["dep:tokio"] cell = ["dep:distributed", "dep:sha2"] # Per-zone Prometheus metrics (dependency-free text exposition). metrics = [] +# Load-test bots (library + `game-bots` binary). +bots = ["net", "dep:tokio-tungstenite", "dep:futures-util", "tokio/rt-multi-thread"] # axum WebSocket zone server with signed-ticket admission (+ /metrics). net = ["runtime", "metrics", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros"] @@ -29,6 +31,8 @@ axum = { version = "0.8", default-features = false, features = ["ws", "tokio", " hmac = { version = "0.12", optional = true } sha2 = { version = "0.10", optional = true } base64 = { version = "0.23", optional = true } +tokio-tungstenite = { version = "0.30", optional = true } +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"], optional = true } [dev-dependencies] tokio = { version = "1", features = ["full", "test-util"] } @@ -36,11 +40,21 @@ tokio-tungstenite = "0.30" futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } serde = { version = "1", features = ["derive"] } +[[bin]] +name = "game-bots" +path = "src/bin/game-bots.rs" +required-features = ["bots"] + [[test]] name = "netcode" path = "tests/netcode/main.rs" required-features = ["runtime"] +[[test]] +name = "bots" +path = "tests/bots/main.rs" +required-features = ["bots"] + [[test]] name = "net_e2e" path = "tests/net_e2e/main.rs" diff --git a/distributed_game/src/bin/game-bots.rs b/distributed_game/src/bin/game-bots.rs new file mode 100644 index 000000000..a088753e7 --- /dev/null +++ b/distributed_game/src/bin/game-bots.rs @@ -0,0 +1,87 @@ +//! Load-test bots against a running `distributed_game` server. +//! +//! ```sh +//! cargo run -p distributed_game --features bots --bin game-bots -- \ +//! --url ws://127.0.0.1:2567 --zone room-1 --bots 50 --rate 20 --secs 10 \ +//! --secret dev-secret --behaviour circle +//! ``` +//! +//! Flags fall back to `DG_BOTS_URL`, `DG_BOTS_ZONE`, `DG_BOTS_COUNT`, +//! `DG_BOTS_RATE`, `DG_BOTS_SECS`, `DG_TICKET_SECRET`, `DG_BOTS_BEHAVIOUR`. +//! Inputs are encoded as an `(i8, i8)` direction pair. + +use std::time::Duration; + +use distributed_game::bots::{run_bots, BehaviourKind, BotConfig}; +use distributed_game::net::TicketKey; + +const USAGE: &str = "usage: game-bots [--url ws://host:port] [--zone id] [--bots n] [--rate hz] \ +[--secs s] [--ramp-ms ms] [--secret s] [--behaviour random|circle] [--prefix p]"; + +fn main() { + let mut args = std::env::args().skip(1); + let env = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.to_string()); + let mut url = env("DG_BOTS_URL", "ws://127.0.0.1:2567"); + let mut zone = env("DG_BOTS_ZONE", "room-1"); + let mut bots = env("DG_BOTS_COUNT", "10"); + let mut rate = env("DG_BOTS_RATE", "20"); + let mut secs = env("DG_BOTS_SECS", "10"); + let mut ramp = String::from("0"); + let mut secret = env("DG_TICKET_SECRET", "dev-secret"); + let mut behaviour = env("DG_BOTS_BEHAVIOUR", "random"); + let mut prefix = String::from("bot"); + while let Some(flag) = args.next() { + let slot = match flag.as_str() { + "--url" => &mut url, + "--zone" => &mut zone, + "--bots" => &mut bots, + "--rate" => &mut rate, + "--secs" => &mut secs, + "--ramp-ms" => &mut ramp, + "--secret" => &mut secret, + "--behaviour" => &mut behaviour, + "--prefix" => &mut prefix, + _ => { + eprintln!("{USAGE}"); + std::process::exit(if flag == "--help" || flag == "-h" { + 0 + } else { + 2 + }); + } + }; + *slot = args.next().unwrap_or_else(|| { + eprintln!("{flag} needs a value\n{USAGE}"); + std::process::exit(2) + }); + } + let parse = |name: &str, v: &str| -> f64 { + v.parse().unwrap_or_else(|_| { + eprintln!("bad {name}: {v}"); + std::process::exit(2) + }) + }; + let kind = match behaviour.as_str() { + "random" => BehaviourKind::RandomWalk, + "circle" => BehaviourKind::Circle, + other => { + eprintln!("unknown behaviour {other}\n{USAGE}"); + std::process::exit(2) + } + }; + let mut config = BotConfig::new(url, zone, TicketKey::new(secret)); + config.bots = parse("bots", &bots) as usize; + config.input_rate = parse("rate", &rate); + config.duration = Duration::from_secs_f64(parse("secs", &secs)); + config.ramp_up = Duration::from_millis(parse("ramp-ms", &ramp) as u64); + config.principal_prefix = prefix; + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("tokio runtime"); + let summary = runtime.block_on(run_bots(config, move |i| kind.build(i))); + println!("{summary}"); + if summary.failed() > 0 { + std::process::exit(1); + } +} diff --git a/distributed_game/src/bots.rs b/distributed_game/src/bots.rs new file mode 100644 index 000000000..108cf642a --- /dev/null +++ b/distributed_game/src/bots.rs @@ -0,0 +1,470 @@ +//! Load-test bots (`bots` feature). +//! +//! Each bot is a real WebSocket client speaking the binary protocol through +//! the reference [`ClientMirror`]: it mints a signed ticket with the +//! server's [`TicketKey`] (dev/test only — production tickets come from the +//! auth service), joins a zone, sends inputs at a fixed rate from a pluggable +//! [`Behaviour`], pings for RTT and counts Deltas/bytes. [`run_bots`] runs N +//! of them concurrently and returns a [`Summary`]. +//! +//! Inputs are game-defined bytes: a [`Behaviour`] yields a 2D direction and +//! an [`Encoder`] turns it into the zone's input payload +//! ([`encode_i8_pair`] matches a `(dx, dy): (i8, i8)` input). +//! +//! The `game-bots` binary wraps this for demos: +//! `cargo run -p distributed_game --features bots --bin game-bots -- --help`. + +use std::fmt; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use futures_util::{SinkExt, StreamExt}; +use tokio::time::Instant; +use tokio_tungstenite::tungstenite::Message; + +use crate::net::TicketKey; +use crate::protocol::{ClientMessage, ClientMirror, Hello, Role, ServerMessage, PROTOCOL_VERSION}; +use crate::rng::ZoneRng; +use crate::zone::TicketClaims; + +/// Produces a movement direction each input tick. +pub trait Behaviour: Send { + /// Direction for the input sent at `elapsed` since the bot joined. + fn direction(&mut self, elapsed: Duration, rng: &mut ZoneRng) -> [f32; 2]; +} + +/// Keeps a heading and occasionally picks a new random one. +#[derive(Debug, Clone)] +pub struct RandomWalk { + /// Probability per input of turning. + pub turn_chance: f32, + heading: [f32; 2], +} + +impl RandomWalk { + /// Walker turning with probability `turn_chance` per input. + pub fn new(turn_chance: f32) -> Self { + Self { + turn_chance, + heading: [0.0, 0.0], + } + } +} + +impl Behaviour for RandomWalk { + fn direction(&mut self, _elapsed: Duration, rng: &mut ZoneRng) -> [f32; 2] { + if self.heading == [0.0, 0.0] || rng.chance(self.turn_chance) { + let a = rng.next_f32() * std::f32::consts::TAU; + self.heading = [a.cos(), a.sin()]; + } + self.heading + } +} + +/// Walks in a circle with a fixed period. +#[derive(Debug, Clone, Copy)] +pub struct Circle { + /// Time for one full turn. + pub period: Duration, + /// Starting angle (radians). + pub phase: f32, +} + +impl Behaviour for Circle { + fn direction(&mut self, elapsed: Duration, _rng: &mut ZoneRng) -> [f32; 2] { + let turns = elapsed.as_secs_f32() / self.period.as_secs_f32().max(1e-3); + let a = self.phase + turns * std::f32::consts::TAU; + [-a.sin(), a.cos()] + } +} + +/// Built-in behaviour selector (binary, quick tests). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BehaviourKind { + /// [`RandomWalk`] turning 10% of inputs. + RandomWalk, + /// [`Circle`] with a 4 s period, phase spread by bot index. + Circle, +} + +impl BehaviourKind { + /// Behaviour for bot `index`. + pub fn build(self, index: usize) -> Box { + match self { + Self::RandomWalk => Box::new(RandomWalk::new(0.1)), + Self::Circle => Box::new(Circle { + period: Duration::from_secs(4), + phase: index as f32 * 0.7, + }), + } + } +} + +/// Direction → input payload. +pub type Encoder = Arc Vec + Send + Sync>; + +/// Encode as two `i8` in `[-1, 1]` (rounded). +pub fn encode_i8_pair(dir: [f32; 2]) -> Vec { + dir.iter() + .map(|v| v.round().clamp(-1.0, 1.0) as i8 as u8) + .collect() +} + +/// Bot run settings. +#[derive(Clone)] +pub struct BotConfig { + /// Server base URL, e.g. `ws://127.0.0.1:2567` (`/zones/{zone}` is appended). + pub url: String, + /// Zone to join. + pub zone: String, + /// Number of bots. + pub bots: usize, + /// Inputs per second per bot. + pub input_rate: f64, + /// Ping cadence (RTT samples). + pub ping_interval: Duration, + /// How long each bot stays after joining. + pub duration: Duration, + /// Spread connects uniformly over this window. + pub ramp_up: Duration, + /// Signs tickets (must match the server's key). + pub ticket_key: TicketKey, + /// Principal prefix (`{prefix}-{index}`). + pub principal_prefix: String, + /// Hello content version. + pub content_version: String, + /// Seed for behaviours. + pub seed: u64, + /// Payload encoder. + pub encoder: Encoder, +} + +impl BotConfig { + /// Defaults: 20 inputs/s, ping every 500 ms, 10 s, random-walk friendly + /// `i8` pair encoding. + pub fn new(url: impl Into, zone: impl Into, ticket_key: TicketKey) -> Self { + Self { + url: url.into(), + zone: zone.into(), + bots: 10, + input_rate: 20.0, + ping_interval: Duration::from_millis(500), + duration: Duration::from_secs(10), + ramp_up: Duration::ZERO, + ticket_key, + principal_prefix: "bot".into(), + content_version: String::new(), + seed: 1, + encoder: Arc::new(encode_i8_pair), + } + } +} + +/// One bot's results. +#[derive(Debug, Clone, Default)] +pub struct BotStats { + /// Bot index. + pub index: usize, + /// Welcome received. + pub joined: bool, + /// Why it stopped early. + pub error: Option, + /// Deltas applied. + pub deltas: u64, + /// Delta bytes received. + pub delta_bytes: u64, + /// Inputs sent. + pub inputs_sent: u64, + /// Highest `ack_seq` seen. + pub last_ack: u32, + /// RTT samples. + pub rtts: Vec, + /// Entities in the mirror at the end. + pub entities: usize, + /// Time from Welcome to the end. + pub session: Duration, +} + +/// Aggregate of a run. +#[derive(Debug, Clone, Default)] +pub struct Summary { + /// Per-bot stats. + pub bots: Vec, + /// Wall time of the run. + pub elapsed: Duration, +} + +impl Summary { + /// Bots that received Welcome. + pub fn joined(&self) -> usize { + self.bots.iter().filter(|b| b.joined).count() + } + + /// Bots that stopped with an error. + pub fn failed(&self) -> usize { + self.bots.iter().filter(|b| b.error.is_some()).count() + } + + /// Fewest Deltas any bot received. + pub fn min_deltas(&self) -> u64 { + self.bots.iter().map(|b| b.deltas).min().unwrap_or(0) + } + + /// Total Deltas. + pub fn deltas(&self) -> u64 { + self.bots.iter().map(|b| b.deltas).sum() + } + + /// Total Delta bytes. + pub fn delta_bytes(&self) -> u64 { + self.bots.iter().map(|b| b.delta_bytes).sum() + } + + /// Delta bytes per second per bot (mean over bot sessions). + pub fn delta_bytes_per_sec_per_bot(&self) -> f64 { + let rates: Vec = self + .bots + .iter() + .filter(|b| !b.session.is_zero()) + .map(|b| b.delta_bytes as f64 / b.session.as_secs_f64()) + .collect(); + if rates.is_empty() { + 0.0 + } else { + rates.iter().sum::() / rates.len() as f64 + } + } + + /// RTT quantile `q` in `[0, 1]` over all samples. + pub fn rtt_quantile(&self, q: f64) -> Option { + let mut all: Vec = self.bots.iter().flat_map(|b| b.rtts.clone()).collect(); + if all.is_empty() { + return None; + } + all.sort(); + let i = ((all.len() - 1) as f64 * q.clamp(0.0, 1.0)).round() as usize; + Some(all[i]) + } + + /// Inputs sent. + pub fn inputs_sent(&self) -> u64 { + self.bots.iter().map(|b| b.inputs_sent).sum() + } +} + +impl fmt::Display for Summary { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ms = |d: Option| { + d.map_or("-".into(), |d| format!("{:.1}ms", d.as_secs_f64() * 1e3)) + }; + writeln!( + f, + "bots: {} joined, {} failed, {} total in {:.1}s", + self.joined(), + self.failed(), + self.bots.len(), + self.elapsed.as_secs_f64() + )?; + writeln!( + f, + "deltas: {} total, min/bot {}, {:.0} B/s/bot, {} bytes", + self.deltas(), + self.min_deltas(), + self.delta_bytes_per_sec_per_bot(), + self.delta_bytes() + )?; + writeln!(f, "inputs sent: {}", self.inputs_sent())?; + write!( + f, + "rtt: p50 {} p95 {} max {}", + ms(self.rtt_quantile(0.5)), + ms(self.rtt_quantile(0.95)), + ms(self.rtt_quantile(1.0)) + )?; + for b in self.bots.iter().filter(|b| b.error.is_some()).take(5) { + write!( + f, + "\n bot {}: {}", + b.index, + b.error.as_deref().unwrap_or("") + )?; + } + Ok(()) + } +} + +/// Run `config.bots` bots concurrently; `behaviour(index)` builds each one. +pub async fn run_bots( + config: BotConfig, + behaviour: impl Fn(usize) -> Box, +) -> Summary { + let started = Instant::now(); + let n = config.bots; + let config = Arc::new(config); + let mut tasks = Vec::with_capacity(n); + for index in 0..n { + let delay = if n > 1 { + config.ramp_up.mul_f64(index as f64 / (n - 1) as f64) + } else { + Duration::ZERO + }; + let behaviour = behaviour(index); + let config = config.clone(); + tasks.push(tokio::spawn(async move { + tokio::time::sleep(delay).await; + run_bot(&config, index, behaviour).await + })); + } + let mut bots = Vec::with_capacity(n); + for (index, task) in tasks.into_iter().enumerate() { + bots.push(task.await.unwrap_or_else(|e| BotStats { + index, + error: Some(format!("task: {e}")), + ..BotStats::default() + })); + } + Summary { + bots, + elapsed: started.elapsed(), + } +} + +/// Run one bot to completion. +pub async fn run_bot( + config: &BotConfig, + index: usize, + mut behaviour: Box, +) -> BotStats { + let mut stats = BotStats { + index, + ..BotStats::default() + }; + if let Err(e) = drive(config, index, behaviour.as_mut(), &mut stats).await { + stats.error = Some(e); + } + stats +} + +async fn drive( + config: &BotConfig, + index: usize, + behaviour: &mut dyn Behaviour, + stats: &mut BotStats, +) -> Result<(), String> { + let unix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let principal = format!("{}-{index}", config.principal_prefix); + let ticket = config.ticket_key.sign(&TicketClaims { + principal: principal.clone(), + zone: config.zone.clone(), + expires_at: unix + 3600, + nonce: format!("{principal}-{}-{}", config.seed, unix), + role: Role::Player, + }); + let url = format!("{}/zones/{}", config.url.trim_end_matches('/'), config.zone); + let (mut ws, _) = tokio_tungstenite::connect_async(url.as_str()) + .await + .map_err(|e| format!("connect: {e}"))?; + let hello = ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: config.content_version.clone(), + capabilities: 0, + ticket, + reconnect_token: String::new(), + }); + ws.send(Message::Binary(hello.encode().into())) + .await + .map_err(|e| format!("hello: {e}"))?; + + let mut mirror = ClientMirror::new(); + let mut rng = ZoneRng::for_zone(config.seed ^ index as u64, &config.zone); + let origin = Instant::now(); + let mut joined_at: Option = None; + let mut seq = 0u32; + let input_every = Duration::from_secs_f64(1.0 / config.input_rate.max(0.01)); + let mut next_input = Instant::now(); + let mut next_ping = Instant::now(); + let end_of = |joined: Instant| joined + config.duration; + let connect_deadline = origin + Duration::from_secs(10); + + loop { + let now = Instant::now(); + let deadline = joined_at.map_or(connect_deadline, end_of); + if now >= deadline { + if joined_at.is_none() { + return Err("no Welcome".into()); + } + break; + } + let wake = if joined_at.is_some() { + next_input.min(next_ping).min(deadline) + } else { + deadline + }; + tokio::select! { + msg = ws.next() => { + let bytes = match msg { + Some(Ok(Message::Binary(b))) => b, + Some(Ok(Message::Close(_))) | None => return Err("closed by server".into()), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(format!("recv: {e}")), + }; + match mirror.apply(&bytes).map_err(|e| format!("decode: {e}"))? { + ServerMessage::Welcome(_) => { + stats.joined = true; + let now = Instant::now(); + joined_at = Some(now); + next_input = now; + next_ping = now; + } + ServerMessage::Delta(d) => { + stats.deltas += 1; + stats.delta_bytes += bytes.len() as u64; + stats.last_ack = stats.last_ack.max(d.ack_seq); + } + ServerMessage::Pong { client_time, .. } => { + let now_ms = origin.elapsed().as_secs_f64() * 1e3; + stats.rtts.push(Duration::from_secs_f64(((now_ms - client_time) / 1e3).max(0.0))); + } + ServerMessage::Kick { code, message } => return Err(format!("kicked {code}: {message}")), + ServerMessage::Error { code, message } if !stats.joined => { + return Err(format!("refused {code}: {message}")); + } + _ => {} + } + } + _ = tokio::time::sleep_until(wake) => { + let Some(joined) = joined_at else { continue }; + let now = Instant::now(); + if now >= next_input { + seq += 1; + let dir = behaviour.direction(now - joined, &mut rng); + let input = ClientMessage::Input { + seq, + client_tick: mirror.server_tick, + payload: (config.encoder)(dir), + }; + ws.send(Message::Binary(input.encode().into())).await.map_err(|e| format!("send: {e}"))?; + stats.inputs_sent += 1; + next_input += input_every; + if next_input < now { + next_input = now + input_every; + } + } + if now >= next_ping { + let ping = ClientMessage::Ping { client_time: origin.elapsed().as_secs_f64() * 1e3 }; + ws.send(Message::Binary(ping.encode().into())).await.map_err(|e| format!("ping: {e}"))?; + next_ping = now + config.ping_interval; + } + } + } + } + stats.session = joined_at.map_or(Duration::ZERO, |j| j.elapsed()); + stats.entities = mirror.entities.len(); + let _ = ws + .send(Message::Binary(ClientMessage::Leave.encode().into())) + .await; + let _ = ws.close(None).await; + Ok(()) +} diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 361ef8876..c2d5d9e00 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -25,6 +25,8 @@ #![warn(missing_docs)] +#[cfg(feature = "bots")] +pub mod bots; #[cfg(feature = "cell")] pub mod cell; pub mod clock; diff --git a/distributed_game/tests/bots/main.rs b/distributed_game/tests/bots/main.rs new file mode 100644 index 000000000..e8543d42c --- /dev/null +++ b/distributed_game/tests/bots/main.rs @@ -0,0 +1,103 @@ +//! ~50 bots against an in-process server: every bot joins with a signed +//! ticket, sends inputs, receives Deltas and measures RTT; `/metrics` +//! reflects the load. + +#[path = "../zone_runtime/arena.rs"] +mod arena; + +use std::time::Duration; + +use arena::{Arena, ArenaConfig}; +use distributed_game::bots::{run_bots, BehaviourKind, BotConfig}; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +const SECRET: &str = "bots-secret"; + +async fn http_get(addr: std::net::SocketAddr, path: &str) -> String { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let request = format!("GET {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut body = String::new(); + stream.read_to_string(&mut body).await.unwrap(); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fifty_bots_join_play_and_receive_deltas() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + config.host.max_players = 64; + // Mild simulated network so RTT is measurable but the test stays fast. + config.net_sim = Some(NetSim::new( + Duration::from_millis(5), + Duration::from_millis(5), + )); + let server = GameServer::::new(config, |zone| { + zone.starts_with("load").then(ArenaConfig::default) + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + let mut bots = BotConfig::new(format!("ws://{addr}"), "load-1", TicketKey::new(SECRET)); + bots.bots = 50; + bots.input_rate = 20.0; + bots.ping_interval = Duration::from_millis(200); + bots.duration = Duration::from_millis(1200); + bots.ramp_up = Duration::from_millis(200); + + // Scrape while the bots are connected. + let scrape = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(900)).await; + http_get(addr, "/metrics").await + }); + let summary = run_bots(bots, |i| { + if i % 2 == 0 { + BehaviourKind::RandomWalk.build(i) + } else { + BehaviourKind::Circle.build(i) + } + }) + .await; + println!("{summary}"); + + assert_eq!(summary.joined(), 50, "{summary}"); + assert_eq!(summary.failed(), 0, "{summary}"); + assert!( + summary.min_deltas() > 5, + "every bot received deltas: {summary}" + ); + assert!( + summary.bots.iter().all(|b| b.last_ack > 0), + "inputs were acked" + ); + assert!(summary.bots.iter().all(|b| b.entities > 0)); + let p50 = summary.rtt_quantile(0.5).expect("rtt samples"); + assert!( + p50 >= Duration::from_millis(10), + "netsim adds 2x5ms: {p50:?}" + ); + assert!(summary.delta_bytes_per_sec_per_bot() > 0.0); + + let metrics = scrape.await.unwrap(); + assert!(metrics.starts_with("HTTP/1.1 200"), "{metrics}"); + assert!(metrics.contains("text/plain; version=0.0.4")); + assert!( + metrics.contains("distributed_game_zone_players{zone=\"load-1\"} 50"), + "{metrics}" + ); + assert!(metrics + .contains("distributed_game_zone_inputs_total{zone=\"load-1\",outcome=\"accepted\"}")); + assert!(metrics.contains("distributed_game_zone_delta_bytes_count{zone=\"load-1\"}")); + + server.shutdown(); + handle.await.unwrap(); +} From 71744b47144b5fc006d5c329489088441c32d652 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:20:29 -0500 Subject: [PATCH 131/484] docs(game): document netcode, metrics, bots and client_tick README gains a netcode/operations section (rewind, record/replay, metrics cardinality guard, bots, NetSim loss semantics and env vars). PROTOCOL.md clarifies the meaning of Input.client_tick for lag compensation; the encoding is unchanged. [[tasks/gr-p8-netcode-ops]] --- distributed_game/PROTOCOL.md | 6 ++++++ distributed_game/README.md | 39 +++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md index 7a490bca2..c7a277d3f 100644 --- a/distributed_game/PROTOCOL.md +++ b/distributed_game/PROTOCOL.md @@ -218,6 +218,12 @@ Leave := 0x04 (default 120/s, burst 240); excess inputs are dropped and the server sends `Error(RATE_LIMITED)` at most once per second; sustained abuse gets `Kick(RATE_LIMITED)`. Observers' inputs are ignored. + `client_tick` SHOULD be the latest `server_tick` the client has applied + (the tick its interpolated view is based on). Servers that do lag + compensation evaluate shots at `time(client_tick) - interp_delay`, where + `interp_delay` is game-defined and carried **inside `payload`**; the + server clamps the rewind to its configured maximum, so the value is + advisory and never trusted beyond that bound. - **Ping**: the server answers with Pong immediately. - **Leave**: graceful exit; the player is removed at once (no reconnect grace). diff --git a/distributed_game/README.md b/distributed_game/README.md index e0ab068f7..fa9418d31 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -15,7 +15,9 @@ Physics is out of scope: bring your own and step it in `on_tick`. | *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | | `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | | `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | -| `net` | `net::GameServer` (axum WebSocket), HMAC tickets | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | +| `net` | `net::GameServer` (axum WebSocket), HMAC tickets, `GET /metrics` (implies `metrics`) | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `bots` | `bots` load-test client library + `game-bots` binary | `net` + `tokio-tungstenite` | ## Minimal zone @@ -99,6 +101,41 @@ on a later tick. `cell::CellFactSink` dispatches into an `AggregateCell` with a deterministic command id per fact key, so retries replay instead of double-crediting. +## Netcode and operations + +- **Lag compensation** (`rewind`): implement `Zone::record_rewind` to push + hit volumes (sphere / vertical capsule + numeric fields) each tick; the + host keeps a ring buffer sized by `HostConfig::rewind.max_rewind` + (default 500 ms). In a hook, + `ctx.rewind().hit_test_shot(ShotTiming { client_tick, interp_delay }, &HitQuery::ray(o, d, range), |id| id != me)` + evaluates at the shooter's view time, clamped to `max_rewind` and the + stored history. The interpolation delay travels in the game's input + payload (no wire change). +- **Record/replay** (`replay`): drive a host through `Recorder` (same + methods as `ZoneHost`), save the compact `Recording` (`DGR1`), and + `replay::(&recording, config)` re-runs it on a `ManualClock`, + checking a per-tick state hash (`Zone::state_hash`, or the replicated + `WorldView`). A mismatch returns a `Divergence` naming the tick and the + stimuli applied since the last matching tick. Fact settlements are + replayed on the tick they were delivered. +- **Metrics** (`metrics`, served by `GameServer` at `GET /metrics`): + tick duration histogram, ticks/dropped ticks, tier, players, observers, + entities, inputs by outcome, Delta bytes per frame, facts pending/settled. + Only the first `ServerConfig::metrics_zone_labels` (default 64) live + zones get a `zone` label; the rest aggregate into `zone="_other"`. + `AdvanceReport` carries the raw numbers for custom drivers. +- **Bots** (`bots`): `run_bots(BotConfig, |i| behaviour)` connects N + WebSocket clients with signed tickets, sends inputs (random walk, + circle, or your own `Behaviour`), measures RTT and Delta bytes/s: + `cargo run -p distributed_game --features bots --bin game-bots -- --url ws://127.0.0.1:2567 --zone room-1 --bots 50`. +- **Network simulation** (`NetSim`, dev only): one-way latency + uniform + jitter + loss, per direction. WebSockets are reliable and ordered, so + loss is simulated as a TCP retransmission delay (`retransmit`, default + 200 ms, up to 3×) with head-of-line blocking, never as a dropped or + reordered message. `config.net_sim = NetSim::from_env()` reads + `DG_NET_LATENCY_MS`, `DG_NET_JITTER_MS`, `DG_NET_LOSS`, + `DG_NET_RETRANSMIT_MS`. + ## Protocol See [`PROTOCOL.md`](PROTOCOL.md) — binary, little-endian, varints, one From dc6582293ba0cff0b8e652f98c0b1707d0ccc983 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:22:57 -0500 Subject: [PATCH 132/484] feat(js): add durable offline command outbox to replica persistence IndexedDB persistence now advertises supportsOfflineCommandOutbox and offers commandOutbox(): a command-transport decorator that writes the exact prepared request before sending, keeps live callers waiting through outages, drains in enqueue order on reconnect or after a reload reusing the same command ids (server receipts dedupe resends) and surfaces rejections to the live caller and via onSettled. Durability is opt-in per command and fails closed for sensitive or unlisted commands; entries replay only under the same cache scope. Confirmed-only state persistence is unchanged. Also exports the ./game subpath in the pack-smoke contract and documents the game client and outbox in the package README. Refs [[tasks/gr-p4-client-sdk]] --- js/README.md | 57 +++ js/scripts/pack-smoke.mjs | 1 + js/src/replica/index.ts | 10 +- js/src/replica/persistence.ts | 8 + js/src/replica/persistence/idb.ts | 46 +- js/src/replica/persistence/implementation.ts | 1 + js/src/replica/persistence/index.ts | 8 + js/src/replica/persistence/outbox.ts | 424 +++++++++++++++++++ js/src/replica/persistence/state.ts | 3 +- js/src/replica/persistence/types.ts | 18 +- js/tests/fixtures/fake-indexeddb.mjs | 128 ++++++ js/tests/replica-command-outbox.test.mjs | 276 ++++++++++++ js/tests/replica-command-runtime.test.mjs | 65 +++ js/tests/replica-persistence.test.mjs | 5 +- 14 files changed, 1040 insertions(+), 10 deletions(-) create mode 100644 js/src/replica/persistence/outbox.ts create mode 100644 js/tests/fixtures/fake-indexeddb.mjs create mode 100644 js/tests/replica-command-outbox.test.mjs diff --git a/js/README.md b/js/README.md index 6aeff5244..e4dba2206 100644 --- a/js/README.md +++ b/js/README.md @@ -534,6 +534,26 @@ confirmed-state-only, and governed by generated/application model policy. Optimistic layers, command inputs, credentials, cache authority, and live connections are never persisted as replica data. +The same persistence object offers an opt-in durable command outbox for +offline use. It decorates the command transport: commands whose policy is +explicitly `{ durable: true, sensitive: false }` are written to IndexedDB +before they are sent and drained in order with their original command ids +(the server's receipts deduplicate resends). Rejections surface to the live +caller as `REPLICA_COMMAND_REJECTED` and, for commands replayed after a +reload, through `onSettled`. Only the prepared request is stored — never +optimistic state — and entries replay only under the same cache scope. + +```ts +const outbox = persistence.commandOutbox({ + transport, // the network command transport + scope: () => currentAuthoritativeScope, + policy: { commands: { 'todo.create': { durable: true, sensitive: false } } }, + onSettled: ({ commandId, outcome }) => console.info(commandId, outcome) +}); +const commands = createCommands(replica, outbox.transport); +addEventListener('online', () => void outbox.drain()); +``` + Diagnostics are also opt-in: ```ts @@ -553,6 +573,39 @@ credentials, trusted presets, raw command inputs, and cache scope. Revealing additional development detail requires an in-process capability plus an explicit redactor. +## Game zones + +`@hops-ops/distributed/game` speaks the `distributed_game` binary protocol +(golden-tested against the Rust fixtures). The app supplies tickets — a +function, so a fresh single-use ticket is fetched whenever a reconnect token +can no longer be used — and a pure `predict` for its own entity. + +```ts +import { GameClient } from '@hops-ops/distributed/game'; + +const game = new GameClient<{ dx: number; dy: number }>({ + url: (zone) => `wss://game.example/zones/${zone}`, + ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role), + prediction: { + encodeInput: ({ dx, dy }) => new Uint8Array([dx & 0xff, dy & 0xff]), + predict: (s, i, dt) => ({ x: s.x + i.dx * 10 * dt / 1000, y: s.y + i.dy * 10 * dt / 1000 }), + corrections: { avatar: { x: { mode: 'ease', durationMs: 120 }, hp: { mode: 'replace' } } } + } +}); +await game.connect('room-1'); +game.on('event', (zone, e) => { /* e.g. announce the controlled entity */ }); +game.setControlledEntity(myEntityId); +game.sendInput({ dx: 1, dy: 0 }); +requestAnimationFrame(function frame() { draw(game.render()); requestAnimationFrame(frame); }); +``` + +`render()` merges the authoritative zone and observed neighbours (`observe`) +sampled at `serverNow − interpolationDelay` (two patch intervals by default), +with the controlled entity at its predicted state. Reconciliation rebases on +every Delta's `ack_seq`; per-field `ease`, `snap` or `replace` resolves the +divergence. A server Handoff connects to the target zone with the transfer +ticket and swaps authority while the previous world keeps rendering. + ## Protocol and security boundaries Every accepted artifact and response is protocol v1 and carries an exact @@ -585,6 +638,10 @@ duplicated as decision documents in this package. - `@hops-ops/distributed/sveltekit/vite` — public Vite plugin, virtual module aliases, and GraphQL HTTP/WebSocket proxy helpers. - `@hops-ops/distributed/react` — provider and query hook over the same replica. +- `@hops-ops/distributed/game` — binary `distributed_game` zone protocol + client: codec, `GameConnection` (handshake, reconnect, clock sync), + interpolating `EntityReplica`, `Predictor` reconciliation and the + multi-zone `GameClient` with handoff. See `distributed_game/PROTOCOL.md`. All other subpaths are private and blocked by the package export map. diff --git a/js/scripts/pack-smoke.mjs b/js/scripts/pack-smoke.mjs index 8cd5771b1..8995d0057 100644 --- a/js/scripts/pack-smoke.mjs +++ b/js/scripts/pack-smoke.mjs @@ -79,6 +79,7 @@ function inspectPackageContract(packageJson) { assert.deepEqual(Object.keys(packageJson.exports).sort(), [ '.', './diagnostics', + './game', './package.json', './react', './replica', diff --git a/js/src/replica/index.ts b/js/src/replica/index.ts index 773296df3..c54b8a8d8 100644 --- a/js/src/replica/index.ts +++ b/js/src/replica/index.ts @@ -81,7 +81,15 @@ export type { ReplicaIndexedDbPersistence, ReplicaIndexedDbPersistenceOptions, ReplicaPersistenceModelPolicy, - ReplicaPersistencePolicy + ReplicaPersistencePolicy, + ReplicaCommandOutbox, + ReplicaCommandOutboxCommandPolicy, + ReplicaCommandOutboxDrainReport, + ReplicaCommandOutboxEntrySummary, + ReplicaCommandOutboxOptions, + ReplicaCommandOutboxOutcome, + ReplicaCommandOutboxPolicy, + ReplicaCommandOutboxSettlement } from './persistence.js'; export type { PrepareReplicaCommandOptions, diff --git a/js/src/replica/persistence.ts b/js/src/replica/persistence.ts index 35f3046d2..18c19f3b6 100644 --- a/js/src/replica/persistence.ts +++ b/js/src/replica/persistence.ts @@ -4,6 +4,14 @@ export { REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED } from './persistence/index.js'; export type { + ReplicaCommandOutbox, + ReplicaCommandOutboxCommandPolicy, + ReplicaCommandOutboxDrainReport, + ReplicaCommandOutboxEntrySummary, + ReplicaCommandOutboxOptions, + ReplicaCommandOutboxOutcome, + ReplicaCommandOutboxPolicy, + ReplicaCommandOutboxSettlement, ReplicaIndexedDbFactory, ReplicaIndexedDbPersistence, ReplicaIndexedDbPersistenceOptions, diff --git a/js/src/replica/persistence/idb.ts b/js/src/replica/persistence/idb.ts index 460358770..7411c59e6 100644 --- a/js/src/replica/persistence/idb.ts +++ b/js/src/replica/persistence/idb.ts @@ -7,6 +7,13 @@ import type { ReplicaIndexedDbPersistence, ReplicaIndexedDbPersistenceOptions } from './types.js'; +import { + OUTBOX_STORE_NAME, + ReplicaCommandOutboxImpl, + type ReplicaCommandOutbox, + type ReplicaCommandOutboxOptions, + type StoredOutboxEntry +} from './outbox.js'; import { DATABASE_VERSION, DEFAULT_DATABASE_NAME, @@ -25,7 +32,7 @@ import { export class IndexedDbConfirmedStatePersistence implements ReplicaIndexedDbPersistence { - readonly supportsOfflineCommandOutbox = false as const; + readonly supportsOfflineCommandOutbox = true as const; readonly #factory: ReplicaIndexedDbFactory; readonly #databaseName: string; readonly #policy: NormalizedPolicy; @@ -116,6 +123,33 @@ export class IndexedDbConfirmedStatePersistence ); } + commandOutbox(options: ReplicaCommandOutboxOptions): ReplicaCommandOutbox { + this.#assertOpen(); + const run = ( + mode: IDBTransactionMode, + operation: (store: IDBObjectStore) => Promise + ) => this.#transaction(mode, operation, OUTBOX_STORE_NAME); + return new ReplicaCommandOutboxImpl( + { + getAll: () => + run('readonly', (store) => requestResult(store.getAll() as IDBRequest)), + get: (commandId) => + run('readonly', (store) => requestResult(store.get(commandId) as IDBRequest)), + put: async (entry: StoredOutboxEntry) => { + await run('readwrite', async (store) => { + await requestResult(store.put(entry)); + }); + }, + delete: async (commandId) => { + await run('readwrite', async (store) => { + await requestResult(store.delete(commandId)); + }); + } + }, + options + ); + } + close(): void { if (this.#closed) return; this.#closed = true; @@ -148,14 +182,15 @@ export class IndexedDbConfirmedStatePersistence async #transaction( mode: IDBTransactionMode, - operation: (store: IDBObjectStore) => Promise + operation: (store: IDBObjectStore) => Promise, + storeName: string = STORE_NAME ): Promise { const database = await this.#database(); this.#assertOpen(); - const transaction = database.transaction(STORE_NAME, mode); + const transaction = database.transaction(storeName, mode); const completion = transactionResult(transaction); try { - const result = await operation(transaction.objectStore(STORE_NAME)); + const result = await operation(transaction.objectStore(storeName)); await completion; return result; } catch (error) { @@ -221,6 +256,9 @@ export function openDatabase( if (!database.objectStoreNames.contains(STORE_NAME)) { database.createObjectStore(STORE_NAME, { keyPath: 'identity' }); } + if (!database.objectStoreNames.contains(OUTBOX_STORE_NAME)) { + database.createObjectStore(OUTBOX_STORE_NAME, { keyPath: 'commandId' }); + } }; request.onsuccess = () => { if (settled) { diff --git a/js/src/replica/persistence/implementation.ts b/js/src/replica/persistence/implementation.ts index 54639d578..8421a898b 100644 --- a/js/src/replica/persistence/implementation.ts +++ b/js/src/replica/persistence/implementation.ts @@ -2,3 +2,4 @@ export * from './types.js'; export * from './state.js'; export * from './idb.js'; +export * from './outbox.js'; diff --git a/js/src/replica/persistence/index.ts b/js/src/replica/persistence/index.ts index 098782c56..8e5a909d7 100644 --- a/js/src/replica/persistence/index.ts +++ b/js/src/replica/persistence/index.ts @@ -3,6 +3,14 @@ export { REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED } from './implementation.js'; export type { + ReplicaCommandOutbox, + ReplicaCommandOutboxCommandPolicy, + ReplicaCommandOutboxDrainReport, + ReplicaCommandOutboxEntrySummary, + ReplicaCommandOutboxOptions, + ReplicaCommandOutboxOutcome, + ReplicaCommandOutboxPolicy, + ReplicaCommandOutboxSettlement, ReplicaIndexedDbFactory, ReplicaIndexedDbPersistence, ReplicaIndexedDbPersistenceOptions, diff --git a/js/src/replica/persistence/outbox.ts b/js/src/replica/persistence/outbox.ts new file mode 100644 index 000000000..24a5d54ac --- /dev/null +++ b/js/src/replica/persistence/outbox.ts @@ -0,0 +1,424 @@ +/** + * Durable offline command outbox. + * + * A transport decorator for the replica command runtime: an exact prepared + * command request is written to IndexedDB *before* it is sent, and removed + * only once the server returned a definitive answer. Entries that could not + * be sent (offline, network failure, 5xx, reload gate) stay durable and are + * drained strictly in enqueue order later — after a reconnect or a page + * reload — reusing the original command id, so the server's command + * receipts deduplicate any resend of a command it already processed. + * + * A live caller (the runtime's pending dispatch) keeps waiting until its + * command gets a definitive server answer, so the runtime's normal receipt, + * rejection and optimistic-layer handling apply unchanged; it can stop + * waiting through its AbortSignal. Commands replayed after a reload have no + * live caller and settle through `onSettled`. + * + * Only the immutable transport request is stored. Optimistic layers and + * unconfirmed cache state are never persisted (the confirmed-only policy is + * unchanged); after a reload the replica learns the effects of drained + * commands through normal revalidation. + * + * Durability is opt-in per command and fails closed like model policy: a + * command is written only when its policy is explicitly + * `{ durable: true, sensitive: false }`. Everything else passes straight + * through to the network transport. + */ +import { parseGraphqlResponseExtensions } from '../../protocol.js'; +import type { + ReplicaCommandTransport, + ReplicaCommandTransportRequest, + ReplicaCommandTransportResult +} from '../command-runtime/types.js'; +import type { ReplicaAuthoritativeScope } from '../types.js'; + +export type ReplicaCommandOutboxCommandPolicy = Readonly<{ + /** Persist and replay this command when it cannot be sent right away. */ + durable: boolean; + /** Sensitive command inputs are never written to durable storage. */ + sensitive: boolean; +}>; + +export type ReplicaCommandOutboxPolicy = Readonly<{ + /** Keyed by generated command name (`request.commandName`). */ + commands: Readonly>; +}>; + +export type ReplicaCommandOutboxOutcome = 'accepted' | 'rejected' | 'failed'; + +export type ReplicaCommandOutboxSettlement = Readonly<{ + commandId: string; + commandName: string; + /** + * `accepted`: the server holds a receipt (any non-rejected command state). + * `rejected`: the domain rejected it. `failed`: a non-retryable protocol + * or request error (malformed envelope, 4xx). + */ + outcome: ReplicaCommandOutboxOutcome; + result: ReplicaCommandTransportResult; + /** True when an in-memory caller was still awaiting this dispatch. */ + live: boolean; + /** Send attempts including this one. */ + attempts: number; +}>; + +export type ReplicaCommandOutboxDrainReport = Readonly<{ + settled: readonly ReplicaCommandOutboxSettlement[]; + /** Entries still queued for this scope (drain stops at the first unsendable). */ + remaining: number; + /** Why draining stopped early, if it did. */ + stoppedBy?: 'offline' | 'transport-error' | 'retryable-response'; +}>; + +export type ReplicaCommandOutboxEntrySummary = Readonly<{ + commandId: string; + commandName: string; + enqueuedAt: number; + attempts: number; +}>; + +export type ReplicaCommandOutboxOptions = Readonly<{ + /** The network transport the outbox decorates. */ + transport: ReplicaCommandTransport; + /** + * Current authoritative scope. Entries are bound to protocol version, + * schema hash and cache scope and only ever drained under the same + * values, so a queued command never replays for another principal or + * an incompatible schema. `undefined` disables durability. + */ + scope: () => ReplicaAuthoritativeScope | undefined; + policy: ReplicaCommandOutboxPolicy; + /** Defaults to `navigator.onLine` (true when unavailable). */ + isOnline?: () => boolean; + /** Every definitive outcome, including commands replayed after reload. */ + onSettled?: (settlement: ReplicaCommandOutboxSettlement) => void; +}>; + +export interface ReplicaCommandOutbox { + /** Pass to `createReplicaCommandRuntime` in place of the network transport. */ + readonly transport: ReplicaCommandTransport; + /** Send queued commands of the current scope in order. Call on reconnect. */ + drain(): Promise; + /** Queued commands of the current scope, oldest first. */ + pending(): Promise; + /** Remove one queued command without sending it (a live caller rejects). */ + discard(commandId: string): Promise; + /** Remove every queued command bound to `scope` (e.g. on sign-out). */ + discardScope(scope: ReplicaAuthoritativeScope): Promise; +} + +/** Storage seam (IndexedDB in production). */ +export interface ReplicaCommandOutboxStore { + getAll(): Promise; + get(commandId: string): Promise; + put(entry: StoredOutboxEntry): Promise; + delete(commandId: string): Promise; +} + +type StoredRequest = Omit; + +export type StoredOutboxEntry = Readonly<{ + formatVersion: 1; + commandId: string; + order: number; + scopeKey: string; + request: StoredRequest; + enqueuedAt: number; + attempts: number; +}>; + +export const OUTBOX_STORE_NAME = 'command-outbox'; + +type Waiter = { + resolve: (result: ReplicaCommandTransportResult) => void; + reject: (error: unknown) => void; +}; + +/** + * Outbox binding key. It deliberately excludes the authorization + * generation: a token refresh for the same cache scope must not strand + * queued commands, and the server binds the principal from the verified + * session at send time, never from the stored request. + */ +export function outboxScopeKey(scope: ReplicaAuthoritativeScope): string { + return JSON.stringify([ + 'distributed-command-outbox', + 1, + scope.protocolVersion, + scope.schemaHash, + scope.cacheScope + ]); +} + +function defaultIsOnline(): boolean { + const nav = (globalThis as { navigator?: { onLine?: boolean } }).navigator; + return nav?.onLine ?? true; +} + +function parseEntry(raw: unknown): StoredOutboxEntry | undefined { + if (raw === null || typeof raw !== 'object') return undefined; + const entry = raw as Record; + const request = entry.request as Record | null | undefined; + if ( + entry.formatVersion !== 1 || + typeof entry.commandId !== 'string' || + typeof entry.order !== 'number' || + typeof entry.scopeKey !== 'string' || + typeof entry.enqueuedAt !== 'number' || + typeof entry.attempts !== 'number' || + request === undefined || + request === null || + typeof request !== 'object' || + request.operation !== 'mutation' || + request.commandId !== entry.commandId || + typeof request.commandName !== 'string' || + typeof request.document !== 'string' || + typeof request.operationHash !== 'string' || + typeof request.mutationField !== 'string' + ) { + return undefined; + } + return entry as unknown as StoredOutboxEntry; +} + +/** + * Classify a transport result. `retry` keeps the command queued: the + * server took no durable decision (5xx, 408/429, reload gate, `unknown`). + */ +export function classifyOutboxResult( + result: ReplicaCommandTransportResult +): ReplicaCommandOutboxOutcome | 'retry' { + let state: string | undefined; + try { + state = parseGraphqlResponseExtensions(result.extensions)?.distributed?.command?.state; + } catch { + return 'failed'; + } + if (state !== undefined) { + if (state === 'rejected') return 'rejected'; + if (state === 'unknown') return 'retry'; + return 'accepted'; + } + const errors = result.errors ?? []; + if (errors.length > 0 && errors.every((e) => e.extensions?.code === 'REJECTED')) { + return 'rejected'; + } + if (result.status >= 500 || result.status === 408 || result.status === 429) return 'retry'; + if (errors.some((e) => e.extensions?.code === 'APPLICATION_RELOADING')) return 'retry'; + return 'failed'; +} + +export class ReplicaCommandOutboxImpl implements ReplicaCommandOutbox { + readonly transport: ReplicaCommandTransport; + readonly #store: ReplicaCommandOutboxStore; + readonly #options: ReplicaCommandOutboxOptions; + readonly #waiters = new Map(); + #lastOrder: number | undefined; + #queue: Promise = Promise.resolve(); + + constructor(store: ReplicaCommandOutboxStore, options: ReplicaCommandOutboxOptions) { + if (typeof options?.transport?.dispatch !== 'function') { + throw new TypeError('command outbox requires a transport'); + } + if (typeof options.scope !== 'function') { + throw new TypeError('command outbox requires a scope() provider'); + } + if (options.policy === undefined || typeof options.policy.commands !== 'object') { + throw new TypeError('command outbox requires an explicit command policy'); + } + this.#store = store; + this.#options = options; + const inner = options.transport; + this.transport = Object.freeze({ + dispatch: (request: ReplicaCommandTransportRequest) => this.#dispatch(request), + ...(inner.status === undefined ? {} : { status: inner.status.bind(inner) }) + }); + } + + drain(): Promise { + return this.#serialize(() => this.#drainNow()); + } + + async pending(): Promise { + const scope = this.#options.scope(); + if (scope === undefined) return []; + const entries = await this.#serialize(() => this.#entries(outboxScopeKey(scope))); + return entries.map((e) => ({ + commandId: e.commandId, + commandName: e.request.commandName, + enqueuedAt: e.enqueuedAt, + attempts: e.attempts + })); + } + + discard(commandId: string): Promise { + return this.#serialize(async () => { + await this.#store.delete(commandId); + this.#rejectWaiter(commandId, new Error('queued command discarded before delivery')); + }); + } + + discardScope(scope: ReplicaAuthoritativeScope): Promise { + return this.#serialize(async () => { + for (const entry of await this.#entries(outboxScopeKey(scope))) { + await this.#store.delete(entry.commandId); + this.#rejectWaiter(entry.commandId, new Error('queued command discarded with its scope')); + } + }); + } + + #rejectWaiter(commandId: string, error: unknown): void { + const waiter = this.#waiters.get(commandId); + if (waiter === undefined) return; + this.#waiters.delete(commandId); + waiter.reject(error); + } + + #durable(request: ReplicaCommandTransportRequest): boolean { + const policy = this.#options.policy.commands[request.commandName]; + return policy?.durable === true && policy.sensitive === false; + } + + #online(): boolean { + return (this.#options.isOnline ?? defaultIsOnline)(); + } + + async #dispatch(request: ReplicaCommandTransportRequest): Promise { + const scope = this.#options.scope(); + if (scope === undefined || !this.#durable(request)) { + return this.#options.transport.dispatch(request); + } + if (this.#waiters.has(request.commandId)) { + throw new Error(`command ${request.commandId} is already awaiting delivery`); + } + const result = new Promise((resolve, reject) => { + this.#waiters.set(request.commandId, { resolve, reject }); + }); + // Persist before any network attempt; a crash after this point + // replays the command on the next drain. + try { + await this.#serialize(() => this.#enqueue(request, outboxScopeKey(scope))); + } catch (error) { + this.#waiters.delete(request.commandId); + throw error; + } + const signal = request.signal; + if (signal !== undefined) { + const onAbort = () => { + void this.#serialize(async () => { + if (!this.#waiters.has(request.commandId)) return; // settled already + const stored = parseEntry(await this.#store.get(request.commandId)); + // Never sent: cancel it. Sent without an answer: the outcome + // is unknown, so keep it; a replay is deduplicated. + if (stored !== undefined && stored.attempts === 0) { + await this.#store.delete(request.commandId); + } + this.#rejectWaiter( + request.commandId, + signal.reason ?? new Error('command request aborted') + ); + }); + }; + if (signal.aborted) onAbort(); + else signal.addEventListener('abort', onAbort, { once: true }); + } + if (this.#online()) void this.drain().catch(() => undefined); + return result; + } + + async #enqueue(request: ReplicaCommandTransportRequest, scopeKey: string): Promise { + const existing = parseEntry(await this.#store.get(request.commandId)); + if (existing !== undefined) return; // runtime transport retry of the same command + if (this.#lastOrder === undefined) { + const all = await this.#store.getAll(); + this.#lastOrder = all.reduce((max, raw) => { + const entry = parseEntry(raw); + return entry === undefined ? max : Math.max(max, entry.order); + }, 0); + } + this.#lastOrder += 1; + const { signal: _signal, ...stored } = request; + await this.#store.put( + Object.freeze({ + formatVersion: 1 as const, + commandId: request.commandId, + order: this.#lastOrder, + scopeKey, + request: structuredClone(stored) as StoredRequest, + enqueuedAt: Date.now(), + attempts: 0 + }) + ); + } + + async #entries(scopeKey: string): Promise { + const out: StoredOutboxEntry[] = []; + for (const raw of await this.#store.getAll()) { + const entry = parseEntry(raw); + if (entry === undefined) { + // Corrupt entries are never replayed. + const id = (raw as { commandId?: unknown } | null)?.commandId; + if (typeof id === 'string') await this.#store.delete(id); + continue; + } + if (entry.scopeKey === scopeKey) out.push(entry); + } + return out.sort((a, b) => a.order - b.order); + } + + async #drainNow(): Promise { + const scope = this.#options.scope(); + if (scope === undefined) return { settled: [], remaining: 0 }; + const entries = await this.#entries(outboxScopeKey(scope)); + const settled: ReplicaCommandOutboxSettlement[] = []; + for (let index = 0; index < entries.length; index += 1) { + const remaining = entries.length - index; + if (!this.#online()) return { settled, remaining, stoppedBy: 'offline' }; + const entry = entries[index]; + const attempts = entry.attempts + 1; + // Record the attempt first: an abort after this point keeps the + // entry because the server may already have processed it. + await this.#store.put({ ...entry, attempts }); + let result: ReplicaCommandTransportResult; + try { + result = await this.#options.transport.dispatch(Object.freeze({ ...entry.request })); + } catch { + // Outcome unknown (offline, connection reset): keep it queued. + return { settled, remaining, stoppedBy: 'transport-error' }; + } + const outcome = classifyOutboxResult(result); + if (outcome === 'retry') { + // No durable server decision yet: keep it queued, in order. + return { settled, remaining, stoppedBy: 'retryable-response' }; + } + await this.#store.delete(entry.commandId); + const waiter = this.#waiters.get(entry.commandId); + this.#waiters.delete(entry.commandId); + const settlement: ReplicaCommandOutboxSettlement = Object.freeze({ + commandId: entry.commandId, + commandName: entry.request.commandName, + outcome, + result, + live: waiter !== undefined, + attempts + }); + settled.push(settlement); + // The live caller gets the exact result; the runtime turns a + // rejection into REPLICA_COMMAND_REJECTED and rolls back its layer. + waiter?.resolve(result); + try { + this.#options.onSettled?.(settlement); + } catch { + // Observer failures never stall the outbox. + } + } + return { settled, remaining: 0 }; + } + + #serialize(work: () => Promise): Promise { + const run = this.#queue.then(work, work); + this.#queue = run.catch(() => undefined); + return run; + } +} diff --git a/js/src/replica/persistence/state.ts b/js/src/replica/persistence/state.ts index 6f685b366..2b6a24143 100644 --- a/js/src/replica/persistence/state.ts +++ b/js/src/replica/persistence/state.ts @@ -17,7 +17,8 @@ import type { ReplicaPersistencePolicy } from './types.js'; -export const DATABASE_VERSION = 1; +/** v2 adds the durable command outbox store. */ +export const DATABASE_VERSION = 2; export const ENTRY_FORMAT_VERSION = 1; export const STORE_NAME = 'confirmed-replicas'; export const DEFAULT_DATABASE_NAME = '@hops-ops/distributed:replica'; diff --git a/js/src/replica/persistence/types.ts b/js/src/replica/persistence/types.ts index 1944040c6..9edf24fcc 100644 --- a/js/src/replica/persistence/types.ts +++ b/js/src/replica/persistence/types.ts @@ -3,7 +3,12 @@ import type { ReplicaDehydratedState } from '../types.js'; -export const REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED = false as const; +import type { + ReplicaCommandOutbox, + ReplicaCommandOutboxOptions +} from './outbox.js'; + +export const REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED = true as const; export type ReplicaPersistenceModelPolicy = { /** @@ -39,7 +44,16 @@ export type ReplicaIndexedDbPersistenceOptions = { }; export interface ReplicaIndexedDbPersistence { - readonly supportsOfflineCommandOutbox: false; + readonly supportsOfflineCommandOutbox: true; + + /** + * Durable offline command outbox in the same database. Wrap the network + * command transport with it; commands whose policy is explicitly + * `{ durable: true, sensitive: false }` are persisted before send and + * drained in order (same command ids) by `drain()` after reconnect. + * Confirmed-state policy is unaffected: optimistic state is never stored. + */ + commandOutbox(options: ReplicaCommandOutboxOptions): ReplicaCommandOutbox; /** * Validate, policy-filter, and persist one confirmed dehydration envelope. diff --git a/js/tests/fixtures/fake-indexeddb.mjs b/js/tests/fixtures/fake-indexeddb.mjs new file mode 100644 index 000000000..a9478f7b3 --- /dev/null +++ b/js/tests/fixtures/fake-indexeddb.mjs @@ -0,0 +1,128 @@ +/** + * Minimal in-memory IndexedDB (open/upgrade, multiple keyPath stores, get, + * getAll, put, delete, transaction completion) that persists across + * "reloads" — i.e. across persistence instances sharing one factory. + */ +export class FakeIndexedDb { + #databases = new Map(); + opens = 0; + + open(name, version) { + const request = fakeRequest(); + this.opens += 1; + queueMicrotask(() => { + let database = this.#databases.get(name); + const upgrade = database === undefined || database.version < version; + if (database === undefined) { + database = { version, stores: new Map() }; + this.#databases.set(name, database); + } + database.version = version; + request.result = new FakeDatabase(database); + if (upgrade) request.onupgradeneeded?.({ target: request }); + queueMicrotask(() => request.onsuccess?.({ target: request })); + }); + return request; + } + + /** Raw store contents (Map key → value). */ + store(name, storeName) { + return this.#databases.get(name)?.stores.get(storeName)?.entries ?? new Map(); + } +} + +class FakeDatabase { + constructor(state) { + this.state = state; + this.objectStoreNames = { contains: (name) => this.state.stores.has(name) }; + } + + createObjectStore(name, options = {}) { + const store = { keyPath: options.keyPath, entries: new Map() }; + this.state.stores.set(name, store); + return store; + } + + transaction(name) { + const store = this.state.stores.get(name); + if (store === undefined) throw new Error(`missing object store ${name}`); + return new FakeTransaction(store); + } + + close() {} +} + +class FakeTransaction { + #pending = 0; + completed = false; + error = null; + + constructor(store) { + this.store = store; + } + + objectStore() { + const { entries, keyPath } = this.store; + return { + get: (key) => this.#request(() => clone(entries.get(key))), + getAll: () => this.#request(() => [...entries.values()].map(clone)), + put: (value) => + this.#request(() => { + const copy = structuredClone(value); + entries.set(copy[keyPath], copy); + return copy[keyPath]; + }), + delete: (key) => + this.#request(() => { + entries.delete(key); + return undefined; + }) + }; + } + + abort() { + if (this.completed) throw new Error('transaction already completed'); + this.completed = true; + this.onabort?.({ target: this }); + } + + #request(work) { + const request = fakeRequest(); + this.#pending += 1; + queueMicrotask(() => { + if (this.completed) return; + try { + request.result = work(); + request.onsuccess?.({ target: request }); + } catch (error) { + request.error = error; + this.error = error; + request.onerror?.({ target: request }); + this.onerror?.({ target: this }); + return; + } + this.#pending -= 1; + queueMicrotask(() => { + if (this.completed || this.#pending > 0) return; + this.completed = true; + this.oncomplete?.({ target: this }); + }); + }); + return request; + } +} + +function clone(value) { + return value === undefined ? undefined : structuredClone(value); +} + +function fakeRequest() { + return { + result: undefined, + error: null, + onsuccess: null, + onerror: null, + onupgradeneeded: null, + onblocked: null + }; +} diff --git a/js/tests/replica-command-outbox.test.mjs b/js/tests/replica-command-outbox.test.mjs new file mode 100644 index 000000000..928865329 --- /dev/null +++ b/js/tests/replica-command-outbox.test.mjs @@ -0,0 +1,276 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + createReplicaIndexedDbPersistence, + REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED +} from '../dist/replica/persistence.js'; +import { classifyOutboxResult } from '../dist/replica/persistence/outbox.js'; +import { FakeIndexedDb } from './fixtures/fake-indexeddb.mjs'; +import { COMMAND_CONSISTENCY, commandReceipt } from './fixtures/command-protocol.mjs'; + +const DATABASE = 'outbox-test'; +const OUTBOX = 'command-outbox'; + +const scopeA = Object.freeze({ + protocolVersion: 1, + schemaHash: 'sha256:schema', + authorizationGeneration: 'auth-1', + cacheScope: 'scope:alice' +}); +const scopeB = Object.freeze({ ...scopeA, cacheScope: 'scope:bob' }); + +const POLICY = Object.freeze({ + commands: { + addTodo: { durable: true, sensitive: false }, + changePassword: { durable: true, sensitive: true }, + ephemeral: { durable: false, sensitive: false } + } +}); + +function request(commandName, commandId, variables = {}) { + return Object.freeze({ + operation: 'mutation', + commandName, + commandId, + mutationField: commandName, + document: `mutation ${commandName} { ${commandName} }`, + operationHash: 'sha256:op', + variables, + extensions: { distributed: { client: { schemaHash: 'sha256:schema' } } } + }); +} + +function accepted(req, state = 'succeeded_pending_projection') { + return { + status: 200, + data: { [req.mutationField]: { ok: true } }, + extensions: { + distributed: { + protocolVersion: 1, + schemaHash: 'sha256:schema', + authorizationGeneration: 'auth-1', + cacheScope: 'scope:alice', + operation: req.operationHash, + command: commandReceipt({ + commandId: req.commandId, + causationId: `cause:${req.commandId}`, + state, + consistency: COMMAND_CONSISTENCY.EVENTUAL + }) + } + } + }; +} + +function rejected(message = 'title taken') { + return { + status: 200, + data: null, + errors: [{ message, extensions: { code: 'REJECTED' } }] + }; +} + +/** A scripted network: `online` toggles, `answer(request)` decides. */ +function network(answer) { + const sent = []; + const net = { + online: true, + sent, + transport: { + async dispatch(req) { + sent.push(req.commandId); + if (!net.online) throw new TypeError('Failed to fetch'); + return answer(req); + } + } + }; + return net; +} + +function outboxFor(factory, net, options = {}) { + const persistence = createReplicaIndexedDbPersistence({ + indexedDB: factory, + databaseName: DATABASE + }); + const settled = []; + const outbox = persistence.commandOutbox({ + transport: net.transport, + scope: () => options.scope ?? scopeA, + policy: POLICY, + isOnline: () => net.online, + onSettled: (s) => settled.push(s) + }); + return { persistence, outbox, settled }; +} + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +test('offline outbox support is advertised by IndexedDB persistence', () => { + const persistence = createReplicaIndexedDbPersistence({ + indexedDB: new FakeIndexedDb(), + databaseName: DATABASE + }); + assert.equal(REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED, true); + assert.equal(persistence.supportsOfflineCommandOutbox, true); + assert.equal(typeof persistence.commandOutbox, 'function'); + persistence.close(); +}); + +test('commands persist before send and drain in order after a reload, reusing ids', async () => { + const factory = new FakeIndexedDb(); + const net = network((req) => (req.commandId === 'cmd-2' ? rejected() : accepted(req))); + net.online = false; + const first = outboxFor(factory, net); + + // Offline: durable commands are written, nothing reaches the network. + const live1 = first.outbox.transport.dispatch(request('addTodo', 'cmd-1', { title: 'a' })); + const live2 = first.outbox.transport.dispatch(request('addTodo', 'cmd-2', { title: 'b' })); + const live3 = first.outbox.transport.dispatch(request('addTodo', 'cmd-3', { title: 'c' })); + await tick(); + assert.deepEqual(net.sent, []); + const stored = [...factory.store(DATABASE, OUTBOX).values()].sort((a, b) => a.order - b.order); + assert.deepEqual(stored.map((e) => e.commandId), ['cmd-1', 'cmd-2', 'cmd-3']); + assert.deepEqual(stored[0].request.variables, { title: 'a' }); + assert.equal('signal' in stored[0].request, false); + assert.deepEqual((await first.outbox.pending()).map((p) => p.commandId), ['cmd-1', 'cmd-2', 'cmd-3']); + + // Non-durable and sensitive commands are never written; they go straight + // to the (offline) network and fail there. + await assert.rejects(first.outbox.transport.dispatch(request('changePassword', 'pw-1', { secret: 'x' }))); + await assert.rejects(first.outbox.transport.dispatch(request('ephemeral', 'e-1'))); + await assert.rejects(first.outbox.transport.dispatch(request('unlisted', 'u-1'))); + assert.equal(factory.store(DATABASE, OUTBOX).size, 3); + assert.equal( + JSON.stringify([...factory.store(DATABASE, OUTBOX).values()]).includes('secret'), + false + ); + + // "Reload": the live callers are gone; a fresh instance drains the queue. + void live1; + void live2; + void live3; + first.persistence.close(); + net.sent.length = 0; + net.online = true; + const second = outboxFor(factory, net); + const report = await second.outbox.drain(); + assert.deepEqual(net.sent, ['cmd-1', 'cmd-2', 'cmd-3'], 'same ids, enqueue order'); + assert.deepEqual( + report.settled.map((s) => [s.commandId, s.outcome, s.live]), + [ + ['cmd-1', 'accepted', false], + ['cmd-2', 'rejected', false], + ['cmd-3', 'accepted', false] + ] + ); + assert.equal(report.remaining, 0); + assert.deepEqual(second.settled.map((s) => s.outcome), ['accepted', 'rejected', 'accepted']); + assert.equal(factory.store(DATABASE, OUTBOX).size, 0); + second.persistence.close(); +}); + +test('a live caller waits through an outage and receives the deduplicated result', async () => { + const factory = new FakeIndexedDb(); + const processed = new Map(); + // The server dedupes on command id: a resend returns the first receipt. + const net = network((req) => { + if (!processed.has(req.commandId)) processed.set(req.commandId, accepted(req)); + return processed.get(req.commandId); + }); + const { outbox, persistence } = outboxFor(factory, net); + + // Online but the request dies in flight (server may have processed it). + net.online = true; + const original = net.transport.dispatch; + let failNext = true; + net.transport.dispatch = async (req) => { + const result = await original(req); + if (failNext) { + failNext = false; + throw new TypeError('connection reset after send'); + } + return result; + }; + let resolved; + const live = outbox.transport + .dispatch(request('addTodo', 'cmd-9')) + .then((r) => (resolved = r)); + await tick(); + await tick(); + assert.equal(resolved, undefined, 'outcome unknown: caller keeps waiting'); + const [entry] = factory.store(DATABASE, OUTBOX).values(); + assert.equal(entry.attempts, 1); + + // Reconnect: drain resends the same id, the server answers from its receipt. + const report = await outbox.drain(); + await live; + assert.deepEqual(net.sent, ['cmd-9', 'cmd-9']); + assert.equal(processed.size, 1); + assert.equal(resolved.extensions.distributed.command.commandId, 'cmd-9'); + assert.equal(report.settled[0].live, true); + assert.equal(report.settled[0].attempts, 2); + persistence.close(); +}); + +test('retryable responses keep order; aborting a never-sent command cancels it', async () => { + const factory = new FakeIndexedDb(); + let busy = true; + const net = network((req) => + busy ? { status: 503, data: null, errors: [{ message: 'busy' }] } : accepted(req) + ); + const { outbox, persistence } = outboxFor(factory, net); + const a = outbox.transport.dispatch(request('addTodo', 'a')); + await tick(); + await tick(); + assert.deepEqual(net.sent, ['a']); + net.online = false; + const controller = new AbortController(); + const b = outbox.transport.dispatch({ ...request('addTodo', 'b'), signal: controller.signal }); + await tick(); + controller.abort(new Error('user cancelled')); + await assert.rejects(b, /user cancelled/); + assert.deepEqual((await outbox.pending()).map((p) => p.commandId), ['a']); + + net.online = true; + busy = false; + const report = await outbox.drain(); + assert.deepEqual(report.settled.map((s) => s.commandId), ['a']); + assert.equal((await a).status, 200); + assert.deepEqual(net.sent, ['a', 'a']); + persistence.close(); +}); + +test('entries are bound to their scope and can be discarded on sign-out', async () => { + const factory = new FakeIndexedDb(); + const net = network((req) => accepted(req)); + net.online = false; + const alice = outboxFor(factory, net, { scope: scopeA }); + void alice.outbox.transport.dispatch(request('addTodo', 'alice-1')); + await tick(); + alice.persistence.close(); + + net.online = true; + const bob = outboxFor(factory, net, { scope: scopeB }); + const report = await bob.outbox.drain(); + assert.deepEqual(report.settled, [], 'never replayed for another principal'); + assert.deepEqual(net.sent, []); + await bob.outbox.discardScope(scopeA); + assert.equal(factory.store(DATABASE, OUTBOX).size, 0); + bob.persistence.close(); +}); + +test('result classification', () => { + const req = request('addTodo', 'x'); + assert.equal(classifyOutboxResult(accepted(req)), 'accepted'); + assert.equal(classifyOutboxResult(accepted(req, 'in_progress')), 'accepted'); + assert.equal(classifyOutboxResult(rejected()), 'rejected'); + assert.equal(classifyOutboxResult({ status: 502, data: null }), 'retry'); + assert.equal(classifyOutboxResult({ status: 429, data: null }), 'retry'); + assert.equal( + classifyOutboxResult({ status: 503, data: null, errors: [{ message: 'r', extensions: { code: 'APPLICATION_RELOADING' } }] }), + 'retry' + ); + assert.equal(classifyOutboxResult({ status: 400, data: null, errors: [{ message: 'bad' }] }), 'failed'); + assert.equal(classifyOutboxResult({ status: 200, extensions: { distributed: 'garbage' } }), 'failed'); +}); diff --git a/js/tests/replica-command-runtime.test.mjs b/js/tests/replica-command-runtime.test.mjs index 09348fd2e..4cee605d3 100644 --- a/js/tests/replica-command-runtime.test.mjs +++ b/js/tests/replica-command-runtime.test.mjs @@ -27,6 +27,8 @@ import { TodoModel, todoFrame } from './fixtures/adapter-conformance.mjs'; +import { createReplicaIndexedDbPersistence } from '../dist/replica/persistence.js'; +import { FakeIndexedDb } from './fixtures/fake-indexeddb.mjs'; const HASH_A = `sha256:${'a'.repeat(64)}`; const HASH_B = `sha256:${'b'.repeat(64)}`; @@ -3385,3 +3387,66 @@ test('calls made after preload cannot overtake earlier commands waiting for the assert.deepEqual(requests, [COMMAND_A, COMMAND_B, COMMAND_C]); runtime.dispose(); }); + +test('offline outbox: optimistic command waits offline, drains in order and surfaces rejection', async () => { + const replica = new TestReplica(); + const factory = new FakeIndexedDb(); + const persistence = createReplicaIndexedDbPersistence({ + indexedDB: factory, + databaseName: 'runtime-outbox' + }); + let online = false; + const sent = []; + const network = { + dispatch(request) { + sent.push(request.commandId); + if (!online) return Promise.reject(new TypeError('Failed to fetch')); + return Promise.resolve( + request.commandId === COMMAND_B + ? envelope(request, { state: 'rejected', projection: false, obligations: 0 }) + : envelope(request, { actualTitle: 'actual-a' }) + ); + } + }; + const settled = []; + const outbox = persistence.commandOutbox({ + transport: network, + scope: () => replica.scope, + policy: { commands: { 'todo.upsert': { durable: true, sensitive: false } } }, + isOnline: () => online, + onSettled: (s) => settled.push([s.commandId, s.outcome]) + }); + const runtime = createReplicaCommandRuntime(replica, outbox.transport, { + change: artifact() + }); + + const a = runtime.commands.change({ id: 'todo-1', title: 'preview-a' }, { commandId: COMMAND_A }); + const b = runtime.commands.change({ id: 'todo-1', title: 'preview-b' }, { commandId: COMMAND_B }); + const bRejected = assert.rejects(b, { code: 'REPLICA_COMMAND_REJECTED' }); + assert.equal(replica.record('todo-1').fields.title, 'preview-b', 'optimism applies offline'); + await tick(); + await tick(); + assert.deepEqual(sent, [], 'nothing was sent while offline'); + assert.deepEqual( + (await outbox.pending()).map((p) => p.commandId), + [COMMAND_A], + 'same-record dispatch order: B waits behind A inside the runtime' + ); + + online = true; + const first = await outbox.drain(); + assert.deepEqual(first.settled.map((s) => [s.commandId, s.outcome]), [[COMMAND_A, 'accepted']]); + const receipt = await a; + assert.equal(receipt.commandId, COMMAND_A); + // B is enqueued once A settles and drains automatically while online. + await bRejected; + assert.deepEqual(sent, [COMMAND_A, COMMAND_B]); + assert.deepEqual(settled, [ + [COMMAND_A, 'accepted'], + [COMMAND_B, 'rejected'] + ]); + assert.equal(replica.record('todo-1').fields.title, 'actual-a', 'rejected layer rolled back'); + assert.equal(factory.store('runtime-outbox', 'command-outbox').size, 0); + runtime.dispose(); + persistence.close(); +}); diff --git a/js/tests/replica-persistence.test.mjs b/js/tests/replica-persistence.test.mjs index 43fda4476..a59130300 100644 --- a/js/tests/replica-persistence.test.mjs +++ b/js/tests/replica-persistence.test.mjs @@ -219,8 +219,9 @@ test('persistence is explicit, IndexedDB-only, and fails closed without model po databaseName: DATABASE }); - assert.equal(REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED, false); - assert.equal(persistence.supportsOfflineCommandOutbox, false); + // The opt-in command outbox exists, but nothing is durable without policy. + assert.equal(REPLICA_OFFLINE_COMMAND_OUTBOX_SUPPORTED, true); + assert.equal(persistence.supportsOfflineCommandOutbox, true); assert.equal(await persistence.save(state()), false); assert.equal(factory.entries(DATABASE).size, 0); assert.equal('localStorage' in factory, false); From 93ae0b1b4b23b105c102d1318a1c8df5abe0bba4 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:23:54 -0500 Subject: [PATCH 133/484] feat(game): world directory, hibernation, handoff and barrier P5 world structure: ZoneDirectory (StaticDirectory, HashRing with virtual nodes) with Redirect on misrouted joins; fenced zone ownership (LocalOwnership, FencedLeaseOwnership over distributed::lease) renewed by every activation, lost claim stops the zone; dormant zones hibernate into a fenced ZoneStateStore (memory, native SQLite) and restore on the next activation; facts queued at dispose are still committed; signed single-use transfer tickets with carried state, reserve/confirm/release at the issuing host and return-to-source on refusal; zone hierarchy with tier-up ChildEvents routed across hosts. P7 freeze barrier: two-phase WorldCoordinator over local servers and admin-HTTP remote hosts (freeze + ack with timeout, apply, commit or abort to the old version), Zone::freeze_ready, inputs dropped and counted while frozen, version stamps, StalePolicy::SafeRoom gates with Kick(RELOAD) and rolling/hard modes. Wire (additive): 0x89 Redirect, Kick code 7 RELOAD; golden fixtures. Refs [[tasks/gr-p5-world-structure]] [[tasks/gr-p7-freeze-barrier]] --- distributed_game/Cargo.toml | 12 +- distributed_game/src/handoff.rs | 62 ++ distributed_game/src/host.rs | 383 ++++++- distributed_game/src/lib.rs | 15 +- distributed_game/src/net/mod.rs | 968 ++++++++++++++++-- distributed_game/src/net/peer.rs | 105 ++ distributed_game/src/net/ticket.rs | 139 ++- distributed_game/src/net/transfer.rs | 155 +++ distributed_game/src/net/world.rs | 495 +++++++++ distributed_game/src/protocol/messages.rs | 20 + distributed_game/src/world/barrier.rs | 52 + distributed_game/src/world/directory.rs | 275 +++++ distributed_game/src/world/mod.rs | 30 + distributed_game/src/world/ownership.rs | 274 +++++ distributed_game/src/world/state.rs | 261 +++++ distributed_game/src/world/topology.rs | 93 ++ distributed_game/src/zone.rs | 51 + distributed_game/tests/fixtures/messages.json | 20 + distributed_game/tests/golden/main.rs | 17 + distributed_game/tests/world/main.rs | 779 ++++++++++++++ distributed_game/tests/world/realm.rs | 183 ++++ distributed_game/tests/world_host/main.rs | 366 +++++++ 22 files changed, 4672 insertions(+), 83 deletions(-) create mode 100644 distributed_game/src/handoff.rs create mode 100644 distributed_game/src/net/peer.rs create mode 100644 distributed_game/src/net/transfer.rs create mode 100644 distributed_game/src/net/world.rs create mode 100644 distributed_game/src/world/barrier.rs create mode 100644 distributed_game/src/world/directory.rs create mode 100644 distributed_game/src/world/mod.rs create mode 100644 distributed_game/src/world/ownership.rs create mode 100644 distributed_game/src/world/state.rs create mode 100644 distributed_game/src/world/topology.rs create mode 100644 distributed_game/tests/world/main.rs create mode 100644 distributed_game/tests/world/realm.rs create mode 100644 distributed_game/tests/world_host/main.rs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 0519169df..14c6f6782 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -17,7 +17,11 @@ runtime = ["dep:tokio"] # Adapter that commits facts into a `distributed` AggregateCell. cell = ["dep:distributed", "dep:sha2"] # axum WebSocket zone server with signed-ticket admission. -net = ["runtime", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros"] +net = ["runtime", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros", "tokio/io-util"] +# `world::FencedLeaseOwnership`: zone ownership over `distributed::lease`. +lease = ["dep:distributed"] +# `world::SqliteZoneStateStore`: native SQLite hibernation snapshots. +sqlite = ["dep:rusqlite"] [dependencies] serde_json = "1" @@ -27,6 +31,7 @@ axum = { version = "0.8", default-features = false, features = ["ws", "tokio", " hmac = { version = "0.12", optional = true } sha2 = { version = "0.10", optional = true } base64 = { version = "0.23", optional = true } +rusqlite = { version = "0.39", features = ["bundled"], optional = true } [dev-dependencies] tokio = { version = "1", features = ["full", "test-util"] } @@ -43,3 +48,8 @@ required-features = ["net"] name = "cell_sink" path = "tests/cell_sink/main.rs" required-features = ["cell", "runtime"] + +[[test]] +name = "world" +path = "tests/world/main.rs" +required-features = ["net", "lease", "sqlite"] diff --git a/distributed_game/src/handoff.rs b/distributed_game/src/handoff.rs new file mode 100644 index 000000000..c1ac89a65 --- /dev/null +++ b/distributed_game/src/handoff.rs @@ -0,0 +1,62 @@ +//! Zone handoff types (transport-agnostic). +//! +//! A zone moves a player with [`Ctx::handoff`](crate::Ctx::handoff): the +//! host asks its transfer issuer (installed by the driver, e.g. the `net` +//! server signs an HS256 transfer ticket) for a ticket, removes the player +//! with [`LeaveReason::Handoff`](crate::LeaveReason::Handoff) after the hook +//! returns and sends `Handoff(target, ticket)`. The target admits the ticket +//! with [`ZoneHost::join_transfer`](crate::ZoneHost::join_transfer), which +//! calls [`Zone::on_handoff_join`](crate::Zone::on_handoff_join) with the +//! carried bytes. + +use crate::zone::TicketClaims; + +/// Largest carried state accepted in a handoff (it travels inside the +/// signed ticket, which travels inside Hello). +pub const MAX_CARRIED_BYTES: usize = 16 * 1024; + +/// What a zone asks the issuer to sign. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HandoffRequest { + /// Verified principal of the moving player. + pub principal: String, + /// Zone the player leaves. + pub source_zone: String, + /// Zone the player goes to. + pub target_zone: String, + /// Game state carried along (inventory, buffs, position hint...). + pub carried: Vec, +} + +/// Verified transfer ticket contents. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Transfer { + /// Principal, target zone (`claims.zone`), expiry and single-use nonce. + pub claims: TicketClaims, + /// Zone the player left. + pub source_zone: String, + /// Host id that issued the ticket (holds the transfer record). + pub issuer: String, + /// Source zone ownership token at issue time. + pub generation: u64, + /// Carried state. + pub carried: Vec, +} + +/// Why [`Ctx::handoff`](crate::Ctx::handoff) refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HandoffError { + /// No such player. + UnknownPlayer, + /// The host has no transfer issuer (no transport configured). + NoIssuer, + /// Carried state exceeds [`MAX_CARRIED_BYTES`]. + TooLarge, + /// Target equals the current zone. + SameZone, + /// The issuer refused (e.g. target unknown). + Refused, +} + +/// Transfer ticket issuer: `None` refuses the handoff. +pub type TransferIssuer = dyn FnMut(&HandoffRequest) -> Option + Send; diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 01eadb615..35cd7186e 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -32,6 +32,7 @@ use std::time::Duration; use crate::clock::Clock; use crate::facts::{EmitError, Fact, FactQueue}; +use crate::handoff::{HandoffError, HandoffRequest, Transfer, TransferIssuer, MAX_CARRIED_BYTES}; use crate::input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; use crate::interest::{InterestConfig, View}; use crate::protocol::{error, kick, Notice, Role, ServerMessage, Welcome}; @@ -41,6 +42,7 @@ use crate::schema::EntitySchema; use crate::stamp::FactStamp; use crate::timers::{TimerId, Timers}; use crate::timestep::{rate_to_step, FixedTimestep}; +use crate::world::{ChildEvent, FreezeState, StalePolicy}; use crate::zone::{ Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, Tier, Viewer, Zone, @@ -77,6 +79,9 @@ pub struct HostConfig { pub content_version: String, /// World seed; the zone RNG derives from it and the zone id. pub world_seed: u64, + /// Admission of clients whose content version differs from + /// `content_version` (see [`StalePolicy`]). + pub stale_policy: StalePolicy, } impl Default for HostConfig { @@ -96,6 +101,7 @@ impl Default for HostConfig { interest: InterestConfig::default(), content_version: String::new(), world_seed: 0, + stale_policy: StalePolicy::Strict, } } } @@ -168,6 +174,7 @@ struct PlayerSlot { grace_until: Option, reconnect_token: String, session_id: String, + content_version: String, } struct ObserverSlot { @@ -198,6 +205,11 @@ pub(crate) struct Core { outbound: Vec, facts: Option, pending_kicks: Vec<(PlayerId, String)>, + transfer_issuer: Option>, + pending_handoffs: Vec<(PlayerId, ServerMessage)>, + upward: Vec, + child_inbox: Vec, + dropped_frozen: u64, } impl Core { @@ -396,6 +408,88 @@ impl Ctx<'_, Z> { pub fn kick(&mut self, player: PlayerId, message: impl Into) { self.core.pending_kicks.push((player, message.into())); } + + /// Provenance of anything produced now (zone, tick, content version); + /// embed it in events so clients and logs can tell which content + /// version produced them. + pub fn stamp(&self) -> FactStamp { + FactStamp { + zone_id: self.core.zone_id.clone(), + tick: self.core.tick, + content_version: self.core.config.content_version.clone(), + } + } + + /// Move `player` to `target_zone` with `carried` state. A signed + /// transfer ticket is issued now; after the current hook returns the + /// player is removed (`LeaveReason::Handoff`) and its client is told + /// `Handoff(target, ticket)`. The player can never be in both zones: it + /// leaves this one before the ticket is usable, and the ticket is + /// single-use. + pub fn handoff( + &mut self, + player: PlayerId, + target_zone: &str, + carried: Vec, + ) -> Result<(), HandoffError> { + if target_zone == self.core.zone_id { + return Err(HandoffError::SameZone); + } + if carried.len() > MAX_CARRIED_BYTES { + return Err(HandoffError::TooLarge); + } + let principal = self + .core + .players + .get(&player) + .map(|slot| slot.info.principal.clone()) + .ok_or(HandoffError::UnknownPlayer)?; + if self + .core + .pending_handoffs + .iter() + .any(|(queued, _)| *queued == player) + { + return Err(HandoffError::Refused); + } + let request = HandoffRequest { + principal, + source_zone: self.core.zone_id.clone(), + target_zone: target_zone.to_string(), + carried, + }; + let issuer = self + .core + .transfer_issuer + .as_mut() + .ok_or(HandoffError::NoIssuer)?; + let ticket = issuer(&request).ok_or(HandoffError::Refused)?; + self.core.pending_handoffs.push(( + player, + ServerMessage::Handoff { + target_zone: request.target_zone, + transfer_ticket: ticket, + }, + )); + Ok(()) + } + + /// Send a tier-up event to the parent zone (and, while `levels` remain, + /// further up). Delivered asynchronously on a later tick of the parent. + pub fn emit_upward(&mut self, kind: impl Into, payload: Vec, levels: u8) { + if levels == 0 { + return; + } + self.core.upward.push(ChildEvent { + origin_zone: self.core.zone_id.clone(), + from_zone: self.core.zone_id.clone(), + kind: kind.into(), + payload, + origin_tick: self.core.tick, + content_version: self.core.config.content_version.clone(), + levels, + }); + } } /// Runs one zone. See the module docs. @@ -410,6 +504,7 @@ pub struct ZoneHost { next_patch: Duration, transitions: Vec<(Tier, Tier)>, frozen: bool, + freeze_request: Option, disposed: bool, token_source: Box String + Send>, } @@ -446,6 +541,11 @@ impl ZoneHost { outbound: Vec::new(), facts: None, pending_kicks: Vec::new(), + transfer_issuer: None, + pending_handoffs: Vec::new(), + upward: Vec::new(), + child_inbox: Vec::new(), + dropped_frozen: 0, config, }; let zone = Z::on_create(&mut Ctx { core: &mut core }, zone_config); @@ -465,6 +565,7 @@ impl ZoneHost { next_patch: now, transitions: Vec::new(), frozen: false, + freeze_request: None, disposed: false, token_source: Box::new(default_token), }; @@ -484,6 +585,27 @@ impl ZoneHost { self } + /// Install the transfer-ticket issuer used by [`Ctx::handoff`]. + pub fn with_transfer_issuer( + mut self, + issuer: impl FnMut(&HandoffRequest) -> Option + Send + 'static, + ) -> Self { + self.core.transfer_issuer = Some(Box::new(issuer)); + self + } + + /// Hand a hibernated snapshot to the zone ([`Zone::on_restore`]); call + /// right after construction. + pub fn restore(&mut self, state: &[u8], saved_version: &str) { + hook!(self.on_restore(state, saved_version)); + self.process_kicks(); + } + + /// Durable snapshot for hibernation ([`Zone::hibernate`]). + pub fn hibernate_state(&self) -> Option> { + self.zone.hibernate() + } + /// Zone id. pub fn zone_id(&self) -> &str { &self.core.zone_id @@ -565,6 +687,39 @@ impl ZoneHost { claims: &TicketClaims, capabilities: u32, content_version: &str, + ) -> Result { + self.admit(claims, capabilities, content_version, None) + } + + /// Admit a player arriving with a verified transfer ticket; the zone + /// sees [`Zone::on_handoff_join`] with the carried state (also when the + /// principal is still present, e.g. inside its reconnect grace). + pub fn join_transfer( + &mut self, + transfer: &Transfer, + capabilities: u32, + content_version: &str, + ) -> Result { + if transfer.claims.role != Role::Player { + return Err(JoinError::new( + error::UNAUTHORIZED, + "transfers are for players", + )); + } + self.admit( + &transfer.claims, + capabilities, + content_version, + Some((transfer.source_zone.as_str(), transfer.carried.clone())), + ) + } + + fn admit( + &mut self, + claims: &TicketClaims, + capabilities: u32, + content_version: &str, + handoff: Option<(&str, Vec)>, ) -> Result { if self.disposed { return Err(JoinError::new(error::NOT_FOUND, "zone disposed")); @@ -576,11 +731,22 @@ impl ZoneHost { )); } let expected = &self.core.config.content_version; + let mut reload = false; if !expected.is_empty() && content_version != expected { - return Err(JoinError::new( - error::VERSION_MISMATCH, - format!("content version {content_version} != {expected}"), - )); + let allowed = match self.core.config.stale_policy { + StalePolicy::Strict => false, + StalePolicy::SafeRoom { roam } => { + let gate = self.zone.is_gate(); + reload = gate; + handoff.is_some() && claims.role == Role::Player && (gate || roam) + } + }; + if !allowed { + return Err(JoinError::new( + error::VERSION_MISMATCH, + format!("content version {content_version} != {expected}: reload"), + )); + } } let existing = self .core @@ -608,9 +774,13 @@ impl ZoneHost { } self.wake(); let client = ClientId(self.core.next_id()); + let mut handoff = handoff; let joined = match (claims.role, existing) { (Role::Player, Some(player)) => { self.bind_player(player, client, capabilities); + if let Some((from, carried)) = handoff.take() { + hook!(self.on_handoff_join(player, from, carried)); + } Joined { client, viewer: Viewer::Player(player), @@ -635,10 +805,14 @@ impl ZoneHost { grace_until: None, reconnect_token: String::new(), session_id: (self.token_source)(), + content_version: content_version.to_string(), }, ); self.bind_player(player, client, capabilities); - hook!(self.on_join(player)); + match handoff.take() { + Some((from, carried)) => hook!(self.on_handoff_join(player, from, carried)), + None => hook!(self.on_join(player)), + } Joined { client, viewer: Viewer::Player(player), @@ -663,12 +837,43 @@ impl ZoneHost { } } }; + if let Viewer::Player(player) = joined.viewer { + if let Some(slot) = self.core.players.get_mut(&player) { + slot.content_version = content_version.to_string(); + } + if reload { + self.reload_player(player); + } + } self.process_kicks(); Ok(joined) } /// Resume a player's session with the token from its last Welcome. pub fn reconnect(&mut self, token: &str, capabilities: u32) -> Result { + self.reconnect_as(token, capabilities, None) + } + + /// [`reconnect`](Self::reconnect) presenting the client's (possibly + /// reloaded) content version. Under [`StalePolicy::Strict`] a stale + /// version is refused; under `SafeRoom` it is admitted to this zone + /// (the one the player is in), and told `Kick(RELOAD)` again if this + /// zone is a gate. + pub fn reconnect_with_version( + &mut self, + token: &str, + capabilities: u32, + content_version: &str, + ) -> Result { + self.reconnect_as(token, capabilities, Some(content_version)) + } + + fn reconnect_as( + &mut self, + token: &str, + capabilities: u32, + content_version: Option<&str>, + ) -> Result { let player = (!token.is_empty() && !self.disposed) .then(|| { self.core @@ -679,15 +884,120 @@ impl ZoneHost { }) .flatten() .ok_or_else(|| JoinError::new(error::RECONNECT_FAILED, "unknown or expired token"))?; + let expected = self.core.config.content_version.clone(); + let mut reload = false; + if let Some(version) = content_version { + if !expected.is_empty() && version != expected { + if self.core.config.stale_policy == StalePolicy::Strict { + return Err(JoinError::new( + error::VERSION_MISMATCH, + format!("content version {version} != {expected}: reload"), + )); + } + reload = self.zone.is_gate(); + } + } self.wake(); let client = ClientId(self.core.next_id()); self.bind_player(player, client, capabilities); + if let Some(version) = content_version { + if let Some(slot) = self.core.players.get_mut(&player) { + slot.content_version = version.to_string(); + } + } + if reload { + self.reload_player(player); + } Ok(Joined { client, viewer: Viewer::Player(player), }) } + /// Tell a connected player to reload its content (`Kick(RELOAD)`) and + /// keep it in the reconnect grace window so it can reconnect with its + /// last Welcome's token after reloading. + pub fn reload_player(&mut self, player: PlayerId) { + let now = self.core.clock.now(); + let grace = self.core.config.reconnect_grace; + let message = ServerMessage::Kick { + code: kick::RELOAD, + message: format!("content {} required", self.core.config.content_version), + }; + let Some(slot) = self.core.players.get_mut(&player) else { + return; + }; + let client = slot.client.take(); + slot.info.connected = false; + slot.inputs.clear(); + slot.grace_until = Some(now + grace); + if let Some(client) = client { + self.core.clients.remove(&client); + self.core.server_message(client, &message); + self.core.outbound.push(Outbound::Close { client }); + } + } + + /// [`reload_player`](Self::reload_player) every connected player whose + /// content version differs from the zone's (hard rollout). Returns the + /// number reloaded. + pub fn reload_stale_players(&mut self) -> usize { + let expected = self.core.config.content_version.clone(); + if expected.is_empty() { + return 0; + } + let stale: Vec<_> = self + .core + .players + .values() + .filter(|slot| slot.client.is_some() && slot.content_version != expected) + .map(|slot| slot.info.id) + .collect(); + for player in &stale { + self.reload_player(*player); + } + stale.len() + } + + /// Content version a player's client reported. + pub fn player_content_version(&self, player: PlayerId) -> Option<&str> { + self.core + .players + .get(&player) + .map(|slot| slot.content_version.as_str()) + } + + /// Switch the zone to a new content version + /// ([`Zone::on_content_version_changed`]); facts and stamps produced + /// afterwards carry it. + pub fn set_content_version(&mut self, version: impl Into) { + let version = version.into(); + if version == self.core.config.content_version { + return; + } + let previous = std::mem::replace(&mut self.core.config.content_version, version.clone()); + hook!(self.on_content_version_changed(&previous, &version)); + self.process_kicks(); + } + + /// Queue a tier-up event from a child zone; delivered to + /// [`Zone::on_child_event`] on a later tick (or the next `advance` when + /// the zone is not ticking), never while frozen. + pub fn deliver_child_event(&mut self, event: ChildEvent) { + self.core.child_inbox.push(event); + } + + /// Tier-up events emitted (or forwarded) by this zone since the last + /// call; the driver routes them to the parent zone. + pub fn drain_upward(&mut self) -> Vec { + std::mem::take(&mut self.core.upward) + } + + /// Inputs dropped because the zone was frozen. + pub fn inputs_dropped_frozen(&self) -> u64 { + self.core.dropped_frozen + } + fn attach_client(&mut self, client: ClientId, viewer: Viewer) { self.core.clients.insert( client, @@ -775,6 +1085,7 @@ impl ZoneHost { return PushOutcome::UnknownClient; }; if self.frozen { + self.core.dropped_frozen += 1; return PushOutcome::Rejected; } let Some(slot) = self.core.players.get(&player) else { @@ -815,12 +1126,52 @@ impl ZoneHost { /// Freeze: ticks stop and inputs are rejected; clients get Freeze. pub fn freeze(&mut self, notice: Notice) { + self.freeze_request = None; self.frozen = true; self.broadcast(&ServerMessage::Freeze(notice)); } + /// Barrier phase 1: freeze as soon as [`Zone::freeze_ready`] allows (now, + /// or at the end of a later `advance`; the zone keeps ticking until + /// then). Returns the resulting state. + pub fn request_freeze(&mut self, notice: Notice) -> FreezeState { + if !self.frozen { + self.freeze_request = Some(notice); + self.try_freeze(); + } + self.freeze_state() + } + + /// Abort a barrier: drop a pending freeze request, and resume with + /// `notice` if already frozen. + pub fn cancel_freeze(&mut self, notice: Notice) { + self.freeze_request = None; + if self.frozen { + self.resume(notice); + } + } + + /// Freeze progress. + pub fn freeze_state(&self) -> FreezeState { + if self.frozen { + FreezeState::Frozen + } else if self.freeze_request.is_some() { + FreezeState::Freezing + } else { + FreezeState::Running + } + } + + fn try_freeze(&mut self) { + if self.freeze_request.is_some() && !self.disposed && self.zone.freeze_ready() { + let notice = self.freeze_request.take().expect("checked"); + self.freeze(notice); + } + } + /// Resume after [`freeze`](Self::freeze); the frozen backlog is not simulated. pub fn resume(&mut self, notice: Notice) { + self.freeze_request = None; self.frozen = false; self.hot.reset(); if let Some(idle) = &mut self.idle { @@ -898,6 +1249,9 @@ impl ZoneHost { } fn process_kicks(&mut self) { + while let Some((player, message)) = self.core.pending_handoffs.pop() { + self.remove_player(player, LeaveReason::Handoff, Some(message)); + } while let Some((player, message)) = self.core.pending_kicks.pop() { let kick = ServerMessage::Kick { code: kick::BY_ZONE, @@ -963,11 +1317,28 @@ impl ZoneHost { self.process_kicks(); } + fn deliver_child_events(&mut self) { + if self.frozen || self.core.child_inbox.is_empty() { + return; + } + for event in std::mem::take(&mut self.core.child_inbox) { + hook!(self.on_child_event(&event)); + if event.levels > 1 { + let mut forward = event; + forward.levels -= 1; + forward.from_zone = self.core.zone_id.clone(); + self.core.upward.push(forward); + } + } + self.process_kicks(); + } + fn tick_once(&mut self, dt: Duration) { self.core.tick += 1; self.core.sim_time += dt; self.core.dt = dt; self.deliver_settlements(); + self.deliver_child_events(); let due = self.core.timers.due(self.core.sim_time); for (id, timer) in due { hook!(self.on_timer(id, timer)); @@ -1052,7 +1423,9 @@ impl ZoneHost { } if report.ticks == 0 { self.deliver_settlements(); + self.deliver_child_events(); } + self.try_freeze(); let patch_interval = rate_to_step(self.core.config.patch_rate); if self.core.tier == Tier::Hot && !self.core.clients.is_empty() && now >= self.next_patch { diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 6f998e0bc..bdcb5eefa 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -16,12 +16,13 @@ //! //! Physics is out of scope: games bring their own and run it in `on_tick`. //! +//! - World structure ([`world`]): zone directory and consistent-hash ring, +//! fenced ownership, hibernation snapshots, zone hierarchy with tier-up +//! events, handoff with carried state ([`handoff`]) and the content +//! barrier / safe-room policy. +//! //! # Extension seams (later phases) -//! Hibernation reads [`Tier::Dormant`]; directory/placement wraps -//! [`ZoneHost::new`] / [`ZoneHost::dispose`]; handoff sagas start from -//! [`ZoneHost::handoff`] + [`LeaveReason::Handoff`]; content barriers use -//! [`ZoneHost::freeze`] / [`ZoneHost::resume`]; metrics hook -//! [`AdvanceReport`] and [`replication::DeltaStats`]. +//! Metrics hook [`AdvanceReport`] and [`replication::DeltaStats`]. #![warn(missing_docs)] @@ -29,6 +30,7 @@ pub mod cell; pub mod clock; pub mod facts; +pub mod handoff; pub mod host; pub mod input; pub mod interest; @@ -41,6 +43,7 @@ pub mod schema; pub mod stamp; pub mod timers; pub mod timestep; +pub mod world; pub mod zone; pub use clock::{Clock, ManualClock, SystemClock}; @@ -50,6 +53,7 @@ pub use facts::{ fact_channel, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, }; +pub use handoff::{HandoffError, HandoffRequest, Transfer}; pub use host::{AdvanceReport, Ctx, HostConfig, JoinError, Joined, Outbound, ZoneHost}; pub use input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; pub use interest::{InterestConfig, View}; @@ -60,6 +64,7 @@ pub use schema::{EntitySchema, FieldType, FieldValue, KindDef}; pub use stamp::{stamp_metadata, FactStamp}; pub use timers::TimerId; pub use timestep::FixedTimestep; +pub use world::{BarrierMode, ChildEvent, FreezeState, StalePolicy}; pub use zone::{ Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, Tier, Viewer, Zone, diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 5bb5cda46..31e46dd44 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -16,9 +16,32 @@ //! - [`NetSim`] adds latency/jitter in both directions for development. //! - [`GameServer::serve`] shuts down gracefully: every zone kicks its //! clients with `Kick(SHUTDOWN)`, runs `on_dispose`, and connections close. +//! +//! World structure (see [`world`] and `crate::world`): +//! +//! - **Placement**: with a [`ZoneDirectory`], a Hello for a zone owned by +//! another host gets `Redirect(zone, url)` (ticket not consumed). +//! - **Ownership**: every activation acquires a fenced claim +//! ([`ZoneOwnership`], default [`LocalOwnership`]) and renews it; losing +//! it disposes the zone without persisting anything. +//! - **Activate on demand / hibernate**: zones are created on first use; +//! one that stays Dormant for `hibernate_after` is snapshotted +//! ([`Zone::hibernate`]) into the [`ZoneStateStore`] under its fencing +//! token, disposed, and restored on its next activation. +//! - **Handoff**: [`Ctx::handoff`](crate::Ctx::handoff) issues a signed +//! transfer ticket; the target reserves/confirms it with the issuing host +//! (single use), a refused transfer may return to its source. +//! - **Tier-up events** are routed to the parent zone, locally or through +//! the admin endpoint of the host that owns it. +//! - **Barrier**: [`GameServer::prepare_barrier`] / `commit_barrier` / +//! `abort_barrier`, driven by a [`world::WorldCoordinator`]. +pub mod peer; pub mod ticket; +pub mod transfer; +pub mod world; +use std::any::Any; use std::collections::{HashMap, VecDeque}; use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; @@ -28,20 +51,29 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use axum::extract::{Path, State}; use axum::response::Response; -use axum::routing::get; +use axum::routing::{get, post}; use axum::Router; +use serde_json::json; use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::JoinHandle; use tokio::time::Instant; -pub use ticket::{NonceCache, TicketError, TicketKey}; +pub use ticket::{NonceCache, TicketError, TicketKey, VerifiedTicket}; +pub use transfer::{TransferOp, TransferRegistry}; +pub use world::{BarrierParticipant, RemoteHost, RolloutError, RolloutReport, WorldCoordinator}; use crate::clock::{Clock, SystemClock}; use crate::facts::{fact_channel, spawn_fact_worker, FactQueue, FactSink, RetryPolicy}; +use crate::handoff::{HandoffRequest, Transfer}; use crate::host::{HostConfig, JoinError, Joined, Outbound, ZoneHost}; -use crate::protocol::{error, kick, ClientMessage, ServerMessage, PROTOCOL_VERSION}; +use crate::protocol::Role; +use crate::protocol::{error, kick, ClientMessage, Notice, ServerMessage, PROTOCOL_VERSION}; use crate::rng::ZoneRng; -use crate::zone::{ClientId, Zone}; +use crate::world::{ + BarrierMode, ChildEvent, DottedTopology, FreezeState, HostAddr, LocalOwnership, OwnershipError, + StoredZoneState, ZoneClaim, ZoneDirectory, ZoneOwnership, ZoneStateStore, ZoneTopology, +}; +use crate::zone::{ClientId, TicketClaims, Tier, Zone}; /// Development latency/jitter simulation (applied to each direction). #[derive(Debug, Clone, Copy, PartialEq)] @@ -71,6 +103,24 @@ pub struct ServerConfig { pub max_frame_bytes: usize, /// Optional dev latency simulation. pub net_sim: Option, + /// Hibernate a zone after it has been Dormant this long (None = never). + pub hibernate_after: Option, + /// Zone ownership claim TTL. + pub ownership_ttl: Duration, + /// Claim renewal period (well below `ownership_ttl`). + pub ownership_renew_every: Duration, + /// How long an activation waits for a held claim (e.g. the previous + /// activation still saving its snapshot) before refusing. + pub activation_timeout: Duration, + /// Transfer ticket lifetime (and target reservation bound). + pub transfer_ttl: Duration, + /// After a zone is disposed, how long to wait for its fact worker to + /// commit the facts still queued. + pub settle_timeout: Duration, + /// Shared secret enabling the `/admin/*` routes and peer calls. + pub admin_secret: Option, + /// Peer (host-to-host) request timeout. + pub peer_timeout: Duration, } impl ServerConfig { @@ -85,13 +135,24 @@ impl ServerConfig { outbound_queue: 512, max_frame_bytes: 64 * 1024, net_sim: None, + hibernate_after: None, + ownership_ttl: Duration::from_secs(15), + ownership_renew_every: Duration::from_secs(5), + activation_timeout: Duration::from_secs(5), + transfer_ttl: Duration::from_secs(30), + settle_timeout: Duration::from_secs(2), + admin_secret: None, + peer_timeout: Duration::from_secs(3), } } } +type Inspector = Box; + enum ZoneCmd { Join { - claims: crate::zone::TicketClaims, + claims: TicketClaims, + transfer: Option, capabilities: u32, content_version: String, out: mpsc::Sender, @@ -100,9 +161,24 @@ enum ZoneCmd { Reconnect { token: String, capabilities: u32, + content_version: String, out: mpsc::Sender, reply: oneshot::Sender>, }, + ChildEvent(ChildEvent), + Freeze { + notice: Notice, + ack: oneshot::Sender<()>, + }, + Commit { + version: String, + notes: String, + mode: BarrierMode, + }, + Abort { + notice: Notice, + }, + Inspect(Inspector), Input { client: ClientId, seq: u32, @@ -121,7 +197,20 @@ enum ConnOut { } type ConfigFactory = dyn Fn(&str) -> Option<::Config> + Send + Sync; -type FactsFactory = dyn Fn(&str) -> Option + Send + Sync; +type FactsFactory = dyn Fn(&str) -> Option<(FactQueue, JoinHandle<()>)> + Send + Sync; + +struct ZoneEntry { + tx: mpsc::Sender, + activation: u64, +} + +/// World-wide content state of this server. +#[derive(Debug, Clone, Default)] +struct WorldState { + version: String, + /// Barrier in progress: zones activated now start frozen. + barrier: Option<(u64, Notice)>, +} struct Inner { config: ServerConfig, @@ -129,10 +218,19 @@ struct Inner { factory: Box>, facts: Option>, nonces: Mutex, - zones: Mutex>>, + zones: Mutex>, tasks: Mutex>>, shutdown: watch::Sender, token_counter: AtomicU64, + host_id: String, + directory: Option>, + ownership: Arc, + state_store: Option>, + topology: Arc, + transfers: Mutex, + /// Lock order: `zones` before `world`. + world: Mutex, + activations: AtomicU64, } /// Multi-zone WebSocket game server. @@ -168,6 +266,7 @@ where factory: impl Fn(&str) -> Option + Send + Sync + 'static, ) -> Self { let (shutdown, _) = watch::channel(false); + let version = config.host.content_version.clone(); Self { inner: Arc::new(Inner { config, @@ -179,10 +278,200 @@ where tasks: Mutex::new(Vec::new()), shutdown, token_counter: AtomicU64::new(0), + host_id: "local".into(), + directory: None, + ownership: Arc::new(LocalOwnership::new()), + state_store: None, + topology: Arc::new(DottedTopology), + transfers: Mutex::new(TransferRegistry::default()), + world: Mutex::new(WorldState { + version, + barrier: None, + }), + activations: AtomicU64::new(0), }), } } + fn configure(mut self, f: impl FnOnce(&mut Inner)) -> Self { + f(Arc::get_mut(&mut self.inner).expect("configure before sharing the server")); + self + } + + /// This host's id (directory entry, ownership holder prefix, transfer + /// issuer). Default `"local"`. + pub fn with_host_id(self, host_id: impl Into) -> Self { + let host_id = host_id.into(); + self.configure(|inner| inner.host_id = host_id) + } + + /// Route zones owned by other hosts (Redirect, peer calls). + pub fn with_directory(self, directory: Arc) -> Self { + self.configure(|inner| inner.directory = Some(directory)) + } + + /// Fenced zone ownership shared by every host of the world. + pub fn with_ownership(self, ownership: Arc) -> Self { + self.configure(|inner| inner.ownership = ownership) + } + + /// Where hibernated zone snapshots go. + pub fn with_state_store(self, store: Arc) -> Self { + self.configure(|inner| inner.state_store = Some(store)) + } + + /// Zone hierarchy for tier-up events (default [`DottedTopology`]). + pub fn with_topology(self, topology: Arc) -> Self { + self.configure(|inner| inner.topology = topology) + } + + /// Host id. + pub fn host_id(&self) -> &str { + &self.inner.host_id + } + + /// The world content version this server runs. + pub fn content_version(&self) -> String { + self.inner.world.lock().expect("world").version.clone() + } + + /// True when `zone_id` is active on this server. + pub fn is_active(&self, zone_id: &str) -> bool { + self.inner + .zones + .lock() + .expect("zones") + .get(zone_id) + .is_some_and(|e| !e.tx.is_closed()) + } + + /// Run `f` against an **active** zone's host (ops tooling and tests). + /// None when the zone is not active here. + pub async fn inspect( + &self, + zone_id: &str, + f: impl FnOnce(&ZoneHost) -> R + Send + 'static, + ) -> Option { + let tx = { + let zones = self.inner.zones.lock().expect("zones"); + zones.get(zone_id)?.tx.clone() + }; + let (reply, rx) = oneshot::channel(); + let inspector: Inspector = Box::new(move |any: &dyn Any| { + if let Some(host) = any.downcast_ref::>() { + let _ = reply.send(f(host)); + } + }); + tx.send(ZoneCmd::Inspect(inspector)).await.ok()?; + rx.await.ok() + } + + /// Activate `zone_id` locally (as if a client asked for it). + pub fn activate(&self, zone_id: &str) -> bool { + activate_local(&self.inner, zone_id).is_some() + } + + /// Barrier phase 1 on this server: freeze every active zone (and every + /// zone activated until commit/abort) with `notice`, then wait up to + /// `timeout` for all to acknowledge. `Err` lists zones that did not. + pub async fn prepare_barrier( + &self, + barrier: u64, + notice: Notice, + timeout: Duration, + ) -> Result<(), Vec> { + let targets: Vec<(String, mpsc::Sender)> = { + let zones = self.inner.zones.lock().expect("zones"); + self.inner.world.lock().expect("world").barrier = Some((barrier, notice.clone())); + zones + .iter() + .map(|(id, e)| (id.clone(), e.tx.clone())) + .collect() + }; + let deadline = Instant::now() + timeout; + let mut waiting = Vec::new(); + for (zone_id, tx) in targets { + let (ack, rx) = oneshot::channel(); + let cmd = ZoneCmd::Freeze { + notice: notice.clone(), + ack, + }; + match tokio::time::timeout_at(deadline, tx.send(cmd)).await { + Ok(Ok(())) => waiting.push((zone_id, tx, rx)), + // Zone task gone (hibernated / stopped): nothing to freeze. + Ok(Err(_)) => {} + Err(_) => waiting.push((zone_id, tx, oneshot::channel().1)), + } + } + let mut missing = Vec::new(); + for (zone_id, tx, rx) in waiting { + match tokio::time::timeout_at(deadline, rx).await { + Ok(Ok(())) => {} + Ok(Err(_)) if tx.is_closed() => {} + _ => missing.push(zone_id), + } + } + if missing.is_empty() { + Ok(()) + } else { + missing.sort(); + Err(missing) + } + } + + /// Barrier phase 2: switch every zone to `version` and resume it + /// (`Resume{version, notes}`); `BarrierMode::Hard` also reloads stale + /// clients. + pub async fn commit_barrier( + &self, + _barrier: u64, + version: &str, + notes: &str, + mode: BarrierMode, + ) { + let targets: Vec> = { + let zones = self.inner.zones.lock().expect("zones"); + let mut world = self.inner.world.lock().expect("world"); + world.version = version.to_string(); + world.barrier = None; + zones.values().map(|e| e.tx.clone()).collect() + }; + for tx in targets { + let _ = tx + .send(ZoneCmd::Commit { + version: version.to_string(), + notes: notes.to_string(), + mode, + }) + .await; + } + } + + /// Abort a barrier: every zone resumes on the old version. + pub async fn abort_barrier(&self, _barrier: u64, notes: &str) { + let (targets, version): (Vec>, String) = { + let zones = self.inner.zones.lock().expect("zones"); + let mut world = self.inner.world.lock().expect("world"); + world.barrier = None; + ( + zones.values().map(|e| e.tx.clone()).collect(), + world.version.clone(), + ) + }; + let notice = Notice { + reason: "content_update_aborted".into(), + version, + notes: notes.to_string(), + }; + for tx in targets { + let _ = tx + .send(ZoneCmd::Abort { + notice: notice.clone(), + }) + .await; + } + } + /// Commit every zone's facts through `sink` (one worker per zone). /// Must be called before the server is cloned or served. pub fn with_fact_sink( @@ -195,17 +484,23 @@ where let inner = Arc::get_mut(&mut self.inner).expect("configure before sharing the server"); inner.facts = Some(Box::new(move |_zone: &str| { let (queue, feed) = fact_channel(capacity, policy); - spawn_fact_worker(feed, sink.clone()); - Some(queue) + let worker = spawn_fact_worker(feed, sink.clone()); + Some((queue, worker)) })); self } - /// axum router exposing `GET /zones/{zone_id}`. + /// axum router exposing `GET /zones/{zone_id}` and, when + /// `admin_secret` is set, the `/admin/*` peer routes. pub fn router(&self) -> Router { - Router::new() - .route("/zones/{zone_id}", get(upgrade::)) - .with_state(self.inner.clone()) + let mut router = Router::new().route("/zones/{zone_id}", get(upgrade::)); + if self.inner.config.admin_secret.is_some() { + router = router + .route("/admin/transfer", post(world::admin_transfer::)) + .route("/admin/child-event", post(world::admin_child_event::)) + .route("/admin/barrier/{phase}", post(world::admin_barrier::)); + } + router.with_state(self.inner.clone()) } /// Ids of zones currently hosted. @@ -215,8 +510,9 @@ where .zones .lock() .expect("zones") - .keys() - .cloned() + .iter() + .filter(|(_, e)| !e.tx.is_closed()) + .map(|(id, _)| id.clone()) .collect(); ids.sort(); ids @@ -253,7 +549,34 @@ where } } -fn zone_sender(inner: &Arc>, zone_id: &str) -> Option> +enum ZoneRoute { + Local(mpsc::Sender), + Remote(HostAddr), + NotFound, +} + +/// Where `zone_id` lives: here (activating it on demand) or on another host. +fn route_zone(inner: &Arc>, zone_id: &str) -> ZoneRoute +where + Z: Zone, + Z::Config: Send, +{ + if let Some(host) = inner + .directory + .as_ref() + .and_then(|d| d.locate(zone_id)) + .filter(|h| h.id != inner.host_id) + { + return ZoneRoute::Remote(host); + } + match activate_local(inner, zone_id) { + Some(tx) => ZoneRoute::Local(tx), + None => ZoneRoute::NotFound, + } +} + +/// Sender of the local activation of `zone_id`, creating it on demand. +fn activate_local(inner: &Arc>, zone_id: &str) -> Option> where Z: Zone, Z::Config: Send, @@ -262,12 +585,20 @@ where return None; } let mut zones = inner.zones.lock().expect("zones"); - if let Some(tx) = zones.get(zone_id).filter(|tx| !tx.is_closed()) { - return Some(tx.clone()); + if let Some(entry) = zones.get(zone_id).filter(|e| !e.tx.is_closed()) { + return Some(entry.tx.clone()); } let zone_config = (inner.factory)(zone_id)?; let (tx, rx) = mpsc::channel(1024); - zones.insert(zone_id.to_string(), tx.clone()); + let activation = inner.activations.fetch_add(1, Ordering::Relaxed) + 1; + let world = inner.world.lock().expect("world").clone(); + zones.insert( + zone_id.to_string(), + ZoneEntry { + tx: tx.clone(), + activation, + }, + ); let facts = inner.facts.as_ref().and_then(|f| f(zone_id)); let task = tokio::spawn(run_zone::( inner.clone(), @@ -275,8 +606,12 @@ where zone_config, facts, rx, + activation, + world, )); - inner.tasks.lock().expect("tasks").push(task); + let mut tasks = inner.tasks.lock().expect("tasks"); + tasks.retain(|t| !t.is_finished()); + tasks.push(task); Some(tx) } @@ -286,46 +621,327 @@ fn unix_now() -> u64 { .map_or(0, |d| d.as_secs()) } -async fn run_zone( +fn random_token(inner: &Inner, label: &str) -> String { + let n = inner.token_counter.fetch_add(1, Ordering::Relaxed); + let seed = format!( + "{label}|{}|{n}|{}", + inner.host_id, + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + ); + inner.config.ticket_key.hmac(seed.as_bytes())[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Apply a transfer-record operation at the issuing host (local or peer). +async fn transfer_op( + inner: &Arc>, + issuer: &str, + op: TransferOp, + nonce: &str, +) -> Result<(), String> { + let reserve_for = inner.config.transfer_ttl.as_secs().max(1); + if issuer == inner.host_id { + return inner + .transfers + .lock() + .expect("transfers") + .apply(op, nonce, unix_now(), reserve_for) + .map_err(str::to_string); + } + let host = inner + .directory + .as_ref() + .and_then(|d| d.host(issuer)) + .ok_or_else(|| format!("unknown issuing host {issuer}"))?; + let secret = inner + .config + .admin_secret + .as_deref() + .ok_or("no admin secret for peer calls")?; + let body = json!({ "op": op.as_str(), "nonce": nonce }); + match peer::post_json( + &host.admin_url, + "/admin/transfer", + secret, + &body, + inner.config.peer_timeout, + ) + .await? + { + (200, _) => Ok(()), + (_, reply) => Err(reply + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("transfer refused") + .to_string()), + } +} + +/// Route a tier-up event to `parent` (local activation or peer host). +fn deliver_child(inner: &Arc>, parent: String, event: ChildEvent) +where + Z: Zone, + Z::Config: Send, +{ + match route_zone(inner, &parent) { + ZoneRoute::Local(tx) => { + if let Err(mpsc::error::TrySendError::Full(cmd)) = + tx.try_send(ZoneCmd::ChildEvent(event)) + { + tokio::spawn(async move { + let _ = tx.send(cmd).await; + }); + } + } + ZoneRoute::Remote(host) => { + let Some(secret) = inner.config.admin_secret.clone() else { + return; + }; + let timeout = inner.config.peer_timeout; + let body = json!({ "zone": parent, "event": world::child_event_json(&event) }); + tokio::spawn(async move { + let _ = peer::post_json( + &host.admin_url, + "/admin/child-event", + &secret, + &body, + timeout, + ) + .await; + }); + } + ZoneRoute::NotFound => {} + } +} + +enum Exit { + Hibernate(Vec), + Shutdown, + Lost, +} + +async fn acquire_claim( + inner: &Arc>, + zone_id: &str, + holder: &str, +) -> Result { + let deadline = Instant::now() + inner.config.activation_timeout; + loop { + let error = match inner + .ownership + .acquire(zone_id, holder, inner.config.ownership_ttl) + .await + { + Ok(claim) => return Ok(claim), + Err(OwnershipError::Held { holder }) => format!("zone is owned by {holder}"), + Err(e) => format!("{e:?}"), + }; + if Instant::now() >= deadline { + return Err(error); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// Activation failed: answer everything queued and unregister. +fn refuse_activation( + inner: &Arc>, + zone_id: &str, + activation: u64, + mut rx: mpsc::Receiver, + message: &str, +) { + { + let mut zones = inner.zones.lock().expect("zones"); + if zones + .get(zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(zone_id); + } + rx.close(); + } + while let Ok(cmd) = rx.try_recv() { + match cmd { + ZoneCmd::Join { reply, .. } | ZoneCmd::Reconnect { reply, .. } => { + let _ = reply.send(Err(JoinError { + code: error::NOT_FOUND, + message: message.to_string(), + })); + } + // Nothing runs here, so nothing to freeze. + ZoneCmd::Freeze { ack, .. } => { + let _ = ack.send(()); + } + _ => {} + } + } +} + +async fn renew_claim( + ownership: Arc, + current: Arc>, + every: Duration, + ttl: Duration, + lost: oneshot::Sender<()>, +) { + loop { + tokio::time::sleep(every).await; + let claim = current.lock().expect("claim").clone(); + match ownership.renew(&claim, ttl).await { + Ok(renewed) => *current.lock().expect("claim") = renewed, + Err(OwnershipError::Backend(_)) => continue, + Err(_) => { + let _ = lost.send(()); + return; + } + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn run_zone( inner: Arc>, zone_id: String, zone_config: Z::Config, - facts: Option, + facts: Option<(FactQueue, JoinHandle<()>)>, mut rx: mpsc::Receiver, -) { - let key = inner.config.ticket_key.clone(); + activation: u64, + world: WorldState, +) where + Z: Zone, + Z::Config: Send, +{ + // 1. Fenced ownership. + let holder = format!("{}#{activation}", inner.host_id); + let claim = match acquire_claim(&inner, &zone_id, &holder).await { + Ok(claim) => claim, + Err(message) => return refuse_activation(&inner, &zone_id, activation, rx, &message), + }; + // 2. Restore the hibernated snapshot, if any. + let saved = match &inner.state_store { + Some(store) => { + let store = store.clone(); + let id = zone_id.clone(); + match tokio::task::spawn_blocking(move || store.load(&id)).await { + Ok(Ok(saved)) => saved, + _ => { + inner.ownership.release(&claim).await; + return refuse_activation( + &inner, + &zone_id, + activation, + rx, + "zone state unavailable", + ); + } + } + } + None => None, + }; + let mut host_config = inner.config.host.clone(); + host_config.content_version = world.version.clone(); let token_inner = inner.clone(); - let token_zone = zone_id.clone(); + let issuer_inner = inner.clone(); + let generation = claim.token; let mut host = ZoneHost::::new( zone_id.clone(), - inner.config.host.clone(), + host_config, inner.clock.clone(), zone_config, ) - .with_token_source(move || { - let n = token_inner.token_counter.fetch_add(1, Ordering::Relaxed); - let seed = format!( - "token|{token_zone}|{n}|{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_nanos()) - ); - key.hmac(seed.as_bytes())[..16] - .iter() - .map(|b| format!("{b:02x}")) - .collect() + .with_token_source(move || random_token(&token_inner, "token")) + .with_transfer_issuer(move |request: &HandoffRequest| { + let inner = &issuer_inner; + let expires_at = unix_now() + inner.config.transfer_ttl.as_secs().max(1); + let nonce = random_token(inner, "transfer"); + inner + .transfers + .lock() + .expect("transfers") + .issue(&nonce, expires_at); + Some(inner.config.ticket_key.sign_transfer(&Transfer { + claims: TicketClaims { + principal: request.principal.clone(), + zone: request.target_zone.clone(), + expires_at, + nonce, + role: Role::Player, + }, + source_zone: request.source_zone.clone(), + issuer: inner.host_id.clone(), + generation, + carried: request.carried.clone(), + })) }); - if let Some(queue) = facts { - host = host.with_facts(queue); + if let Some(saved) = &saved { + host.restore(&saved.state, &saved.content_version); + } + let fact_worker = match facts { + Some((queue, worker)) => { + host = host.with_facts(queue); + Some(worker) + } + None => None, + }; + if let Some((_, notice)) = world.barrier { + host.request_freeze(notice); } + + // 3. Keep the claim alive. + let current = Arc::new(Mutex::new(claim)); + let (lost_tx, mut lost_rx) = oneshot::channel(); + let renewer = tokio::spawn(renew_claim( + inner.ownership.clone(), + current.clone(), + inner.config.ownership_renew_every, + inner.config.ownership_ttl, + lost_tx, + )); + let mut conns: HashMap> = HashMap::new(); + let mut freeze_acks: Vec> = Vec::new(); + let mut dormant_since: Option = None; let mut shutdown = inner.shutdown.subscribe(); - loop { + let exit = loop { let report = host.advance(); route(&mut host, &mut conns); - let sleep_for = report - .next_wake - .map(|at| at.saturating_sub(inner.clock.now())); + forward_upward(&inner, &zone_id, &mut host); + if host.is_frozen() { + for ack in freeze_acks.drain(..) { + let _ = ack.send(()); + } + } + let now = inner.clock.now(); + if host.tier() == Tier::Dormant { + dormant_since.get_or_insert(now); + } else { + dormant_since = None; + } + let hibernate_at = match (inner.config.hibernate_after, dormant_since) { + (Some(after), Some(since)) + if conns.is_empty() + && host.freeze_state() == FreezeState::Running + && host.facts_in_flight() == 0 => + { + Some(since + after) + } + _ => None, + }; + if hibernate_at.is_some_and(|at| now >= at) { + if let Some(leftovers) = begin_hibernation(&inner, &zone_id, activation, &mut rx) { + break Exit::Hibernate(leftovers); + } + } + let wake = match (report.next_wake, hibernate_at) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let sleep_for = wake.map(|at| at.saturating_sub(now)); tokio::select! { biased; _ = shutdown.wait_for(|stop| *stop) => { @@ -338,14 +954,24 @@ async fn run_zone( conns.clear(); host.dispose(); host.drain_outbound(); - break; + break Exit::Shutdown; + } + _ = &mut lost_rx => { + // Someone else owns the zone now: stop without persisting. + host.dispose(); + route(&mut host, &mut conns); + break Exit::Lost; } cmd = rx.recv() => { - let Some(cmd) = cmd else { break }; - handle_cmd(&mut host, &mut conns, cmd); + let Some(cmd) = cmd else { + host.dispose(); + route(&mut host, &mut conns); + break Exit::Shutdown; + }; + handle_cmd(&mut host, &mut conns, &mut freeze_acks, cmd); // Drain whatever else is queued before ticking again. while let Ok(cmd) = rx.try_recv() { - handle_cmd(&mut host, &mut conns, cmd); + handle_cmd(&mut host, &mut conns, &mut freeze_acks, cmd); } route(&mut host, &mut conns); } @@ -356,24 +982,122 @@ async fn run_zone( } } => {} } + }; + renewer.abort(); + let claim = current.lock().expect("claim").clone(); + match exit { + Exit::Hibernate(leftovers) => { + let snapshot = host.hibernate_state(); + let content_version = host.config().content_version.clone(); + host.dispose(); + host.drain_outbound(); + forward_upward(&inner, &zone_id, &mut host); + if let (Some(state), Some(store)) = (snapshot, inner.state_store.clone()) { + let id = zone_id.clone(); + let stored = StoredZoneState { + token: claim.token, + content_version, + state, + }; + // A stale token means a newer owner saved already: drop ours. + let _ = tokio::task::spawn_blocking(move || store.save(&id, &stored)).await; + } + inner.ownership.release(&claim).await; + drop(host); + for cmd in leftovers { + if matches!(cmd, ZoneCmd::Input { .. } | ZoneCmd::Disconnect { .. }) { + continue; + } + if let Some(tx) = activate_local(&inner, &zone_id) { + let _ = tx.send(cmd).await; + } + } + } + Exit::Shutdown => { + inner.ownership.release(&claim).await; + drop(host); + } + Exit::Lost => drop(host), + } + // The fact worker commits everything still queued once the queue is + // dropped; give it a bounded moment so nothing is lost on dispose. + if let Some(worker) = fact_worker { + let _ = tokio::time::timeout(inner.config.settle_timeout, worker).await; + } + let mut zones = inner.zones.lock().expect("zones"); + if zones + .get(&zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(&zone_id); + } +} + +/// Unregister the zone and close its inbox atomically; None when commands +/// are pending (hibernation is retried later). +fn begin_hibernation( + inner: &Arc>, + zone_id: &str, + activation: u64, + rx: &mut mpsc::Receiver, +) -> Option> { + let mut zones = inner.zones.lock().expect("zones"); + if !rx.is_empty() { + return None; + } + if zones + .get(zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(zone_id); + } + rx.close(); + drop(zones); + // Commands sent between the check and the close are re-routed to the + // next activation (which waits for our claim release). + let mut leftovers = Vec::new(); + while let Ok(cmd) = rx.try_recv() { + leftovers.push(cmd); + } + Some(leftovers) +} + +fn forward_upward(inner: &Arc>, zone_id: &str, host: &mut ZoneHost) +where + Z: Zone, + Z::Config: Send, +{ + let events = host.drain_upward(); + if events.is_empty() { + return; + } + let Some(parent) = inner.topology.parent(zone_id) else { + return; + }; + for event in events { + deliver_child(inner, parent.clone(), event); } - inner.zones.lock().expect("zones").remove(&zone_id); } fn handle_cmd( host: &mut ZoneHost, conns: &mut HashMap>, + freeze_acks: &mut Vec>, cmd: ZoneCmd, ) { match cmd { ZoneCmd::Join { claims, + transfer, capabilities, content_version, out, reply, } => { - let result = host.join(&claims, capabilities, &content_version); + let result = match &transfer { + Some(transfer) => host.join_transfer(transfer, capabilities, &content_version), + None => host.join(&claims, capabilities, &content_version), + }; if let Ok(joined) = &result { conns.insert(joined.client, out); } @@ -382,10 +1106,11 @@ fn handle_cmd( ZoneCmd::Reconnect { token, capabilities, + content_version, out, reply, } => { - let result = host.reconnect(&token, capabilities); + let result = host.reconnect_with_version(&token, capabilities, &content_version); if let Ok(joined) = &result { conns.insert(joined.client, out); } @@ -403,6 +1128,37 @@ fn handle_cmd( conns.remove(&client); host.disconnect(client, graceful); } + ZoneCmd::ChildEvent(event) => host.deliver_child_event(event), + ZoneCmd::Freeze { notice, ack } => { + if host.request_freeze(notice) == FreezeState::Frozen { + let _ = ack.send(()); + } else { + freeze_acks.push(ack); + } + } + ZoneCmd::Commit { + version, + notes, + mode, + } => { + host.set_content_version(version.clone()); + if host.freeze_state() != FreezeState::Running { + host.resume(Notice { + reason: "content_update".into(), + version, + notes, + }); + } + if mode == BarrierMode::Hard { + host.reload_stale_players(); + } + freeze_acks.clear(); + } + ZoneCmd::Abort { notice } => { + host.cancel_freeze(notice); + freeze_acks.clear(); + } + ZoneCmd::Inspect(f) => f(&*host as &dyn Any), } } @@ -568,30 +1324,80 @@ where ) .await; } - let Some(zone) = zone_sender(&inner, &zone_id) else { - return reject(socket, error::NOT_FOUND, "unknown zone").await; - }; + // Placement: another host owns this zone -> Redirect (ticket untouched). + let first_route = route_zone(&inner, &zone_id); + match &first_route { + ZoneRoute::Remote(host) => { + let redirect = ServerMessage::Redirect { + zone_id: zone_id.clone(), + url: host.zone_url(&zone_id), + } + .encode(&()) + .expect("redirect encodes"); + let _ = socket.send(Message::Binary(redirect.into())).await; + let _ = socket.send(Message::Close(None)).await; + return; + } + ZoneRoute::NotFound => return reject(socket, error::NOT_FOUND, "unknown zone").await, + ZoneRoute::Local(_) => {} + } let (out_tx, mut out_rx) = mpsc::channel(cfg.outbound_queue.max(1)); let (reply_tx, reply_rx) = oneshot::channel(); + // Transfer record to settle once the zone answered: (issuer, nonce). + let mut reserved: Option<(String, String)> = None; let cmd = if hello.reconnect_token.is_empty() { let now = unix_now(); - let claims = match cfg.ticket_key.verify(&hello.ticket, now) { - Ok(claims) => claims, + let verified = match cfg.ticket_key.verify_ticket(&hello.ticket, now) { + Ok(verified) => verified, Err(e) => return reject(socket, error::UNAUTHORIZED, format!("{e:?}")).await, }; - if claims.zone != zone_id { - return reject(socket, error::UNAUTHORIZED, "ticket is for another zone").await; - } + let (claims, transfer) = match verified { + VerifiedTicket::Join(claims) => { + if claims.zone != zone_id { + return reject(socket, error::UNAUTHORIZED, "ticket is for another zone").await; + } + (claims, None) + } + VerifiedTicket::Transfer(mut transfer) => { + let nonce = transfer.claims.nonce.clone(); + if transfer.claims.zone == zone_id { + // Arrival at the target: reserve with the issuer first. + if let Err(e) = + transfer_op(&inner, &transfer.issuer, TransferOp::Reserve, &nonce).await + { + return reject(socket, error::UNAUTHORIZED, e).await; + } + reserved = Some((transfer.issuer.clone(), nonce)); + } else if transfer.source_zone == zone_id { + // Failed handoff returning to its source. + if let Err(e) = + transfer_op(&inner, &transfer.issuer, TransferOp::Return, &nonce).await + { + return reject(socket, error::UNAUTHORIZED, e).await; + } + let never_reached = + std::mem::replace(&mut transfer.claims.zone, zone_id.clone()); + transfer.source_zone = never_reached; + } else { + return reject(socket, error::UNAUTHORIZED, "ticket is for another zone").await; + } + (transfer.claims.clone(), Some(transfer)) + } + }; let replay = inner.nonces.lock().expect("nonces").check_and_insert( &claims.nonce, claims.expires_at, now, ); if let Err(e) = replay { + if let Some((issuer, nonce)) = reserved.take() { + let _ = transfer_op(&inner, &issuer, TransferOp::Release, &nonce).await; + } return reject(socket, error::UNAUTHORIZED, format!("{e:?}")).await; } ZoneCmd::Join { claims, + transfer, capabilities: hello.capabilities, content_version: hello.content_version, out: out_tx, @@ -601,14 +1407,52 @@ where ZoneCmd::Reconnect { token: hello.reconnect_token, capabilities: hello.capabilities, + content_version: hello.content_version, out: out_tx, reply: reply_tx, } }; - if zone.send(cmd).await.is_err() { - return reject(socket, error::NOT_FOUND, "zone stopped").await; + // A zone that just hibernated closes its inbox; retry on the next + // activation (which restores the snapshot first). + let mut zone = match first_route { + ZoneRoute::Local(tx) => tx, + _ => unreachable!("handled above"), + }; + let mut pending = cmd; + let mut attempts = 0; + loop { + match zone.send(pending).await { + Ok(()) => break, + Err(mpsc::error::SendError(cmd)) => { + attempts += 1; + match activate_local(&inner, &zone_id) { + Some(tx) if attempts < 4 => { + zone = tx; + pending = cmd; + } + _ => { + if let Some((issuer, nonce)) = reserved.take() { + let _ = transfer_op(&inner, &issuer, TransferOp::Release, &nonce).await; + } + return reject(socket, error::NOT_FOUND, "zone stopped").await; + } + } + } + } + } + let result = reply_rx.await; + if let Some((issuer, nonce)) = reserved.take() { + let op = if matches!(result, Ok(Ok(_))) { + TransferOp::Confirm + } else { + TransferOp::Release + }; + let inner = inner.clone(); + tokio::spawn(async move { + let _ = transfer_op(&inner, &issuer, op, &nonce).await; + }); } - let client = match reply_rx.await { + let client = match result { Ok(Ok(joined)) => joined.client, Ok(Err(e)) => return reject(socket, e.code, e.message).await, Err(_) => return reject(socket, error::NOT_FOUND, "zone stopped").await, diff --git a/distributed_game/src/net/peer.rs b/distributed_game/src/net/peer.rs new file mode 100644 index 000000000..4afdc447b --- /dev/null +++ b/distributed_game/src/net/peer.rs @@ -0,0 +1,105 @@ +//! Minimal HTTP/1.1 JSON client for host-to-host admin calls (child events, +//! transfer records, barrier phases). One request per connection; every +//! request carries the shared admin secret header. + +use std::time::Duration; + +use serde_json::Value; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +/// Header carrying the shared admin secret. +pub const ADMIN_SECRET_HEADER: &str = "x-game-admin-secret"; + +/// Constant-time byte comparison. +pub(crate) fn secret_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// POST `body` to `{admin_url}{path}`; returns status and JSON body. +pub async fn post_json( + admin_url: &str, + path: &str, + secret: &str, + body: &Value, + timeout: Duration, +) -> Result<(u16, Value), String> { + tokio::time::timeout(timeout, post_inner(admin_url, path, secret, body)) + .await + .map_err(|_| format!("peer {admin_url} timed out"))? +} + +async fn post_inner( + admin_url: &str, + path: &str, + secret: &str, + body: &Value, +) -> Result<(u16, Value), String> { + let authority = admin_url + .strip_prefix("http://") + .ok_or_else(|| format!("unsupported admin url {admin_url}"))? + .trim_end_matches('/'); + let mut stream = tokio::net::TcpStream::connect(authority) + .await + .map_err(|e| e.to_string())?; + let payload = body.to_string(); + let request = format!( + "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n{ADMIN_SECRET_HEADER}: {secret}\r\nConnection: close\r\n\r\n{payload}", + payload.len() + ); + stream + .write_all(request.as_bytes()) + .await + .map_err(|e| e.to_string())?; + let mut response = Vec::new(); + stream + .read_to_end(&mut response) + .await + .map_err(|e| e.to_string())?; + let split = response + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("malformed response")?; + let head = String::from_utf8_lossy(&response[..split]); + let status = head + .split_whitespace() + .nth(1) + .and_then(|s| s.parse::().ok()) + .ok_or("malformed status")?; + let body = &response[split + 4..]; + let chunked = head.lines().any(|l| { + l.to_ascii_lowercase() + .starts_with("transfer-encoding: chunked") + }); + let body = if chunked { + dechunk(body) + } else { + body.to_vec() + }; + let value = if body.is_empty() { + Value::Null + } else { + serde_json::from_slice(&body).map_err(|e| e.to_string())? + }; + Ok((status, value)) +} + +fn dechunk(mut body: &[u8]) -> Vec { + let mut out = Vec::new(); + while let Some(line_end) = body.windows(2).position(|w| w == b"\r\n") { + let size = std::str::from_utf8(&body[..line_end]) + .ok() + .and_then(|s| usize::from_str_radix(s.trim(), 16).ok()) + .unwrap_or(0); + body = &body[line_end + 2..]; + if size == 0 || body.len() < size { + break; + } + out.extend_from_slice(&body[..size]); + body = body.get(size + 2..).unwrap_or_default(); + } + out +} diff --git a/distributed_game/src/net/ticket.rs b/distributed_game/src/net/ticket.rs index 10ff8da5c..75db96a01 100644 --- a/distributed_game/src/net/ticket.rs +++ b/distributed_game/src/net/ticket.rs @@ -6,6 +6,12 @@ //! `{"sub","zone","exp","nonce","role"?}` where `exp` is Unix seconds and //! `role` is `"player"` (default) or `"observer"`. Any HS256 JWT library can //! mint them. The principal is taken **only** from a verified `sub`. +//! +//! **Transfer tickets** (zone handoff) are the same format with +//! `"kind":"transfer"` plus `src` (source zone), `iss` (issuing host id), +//! `gen` (source ownership token) and `carry` (base64url carried state). +//! [`TicketKey::verify`] rejects them ([`TicketError::WrongKind`]); use +//! [`TicketKey::verify_ticket`] to accept either kind. use std::collections::HashMap; @@ -15,6 +21,7 @@ use hmac::{Hmac, Mac}; use serde_json::{json, Value}; use sha2::Sha256; +use crate::handoff::Transfer; use crate::protocol::Role; use crate::zone::TicketClaims; @@ -35,6 +42,17 @@ pub enum TicketError { Expired, /// Nonce already used. Replayed, + /// A transfer ticket where a join ticket was expected (or vice versa). + WrongKind, +} + +/// A verified ticket of either kind. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VerifiedTicket { + /// Lobby-issued admission ticket. + Join(TicketClaims), + /// Server-issued handoff transfer ticket. + Transfer(Transfer), } /// Shared HMAC key. @@ -71,7 +89,6 @@ impl TicketKey { /// Mint a ticket (dev tooling and tests; production issuers can use any /// HS256 JWT library). pub fn sign(&self, claims: &TicketClaims) -> String { - let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT"}"#); let body = json!({ "sub": claims.principal, "zone": claims.zone, @@ -79,15 +96,91 @@ impl TicketKey { "nonce": claims.nonce, "role": match claims.role { Role::Player => "player", Role::Observer => "observer" }, }); + self.sign_body(&body) + } + + /// Mint a transfer ticket for a handoff. + pub fn sign_transfer(&self, transfer: &Transfer) -> String { + let claims = &transfer.claims; + let body = json!({ + "sub": claims.principal, + "zone": claims.zone, + "exp": claims.expires_at, + "nonce": claims.nonce, + "role": "player", + "kind": "transfer", + "src": transfer.source_zone, + "iss": transfer.issuer, + "gen": transfer.generation, + "carry": URL_SAFE_NO_PAD.encode(&transfer.carried), + }); + self.sign_body(&body) + } + + fn sign_body(&self, body: &Value) -> String { + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT"}"#); let payload = URL_SAFE_NO_PAD.encode(body.to_string()); let signing_input = format!("{header}.{payload}"); let sig = URL_SAFE_NO_PAD.encode(self.hmac(signing_input.as_bytes())); format!("{signing_input}.{sig}") } - /// Verify signature and expiry (`now_unix` seconds). Nonce reuse is - /// checked separately with a [`NonceCache`]. + /// Verify a join or transfer ticket (signature, expiry, claims). + pub fn verify_ticket( + &self, + ticket: &str, + now_unix: u64, + ) -> Result { + let (claims, body) = self.verify_inner(ticket, now_unix)?; + match body.get("kind").and_then(Value::as_str) { + None | Some("join") => Ok(VerifiedTicket::Join(claims)), + Some("transfer") => { + let text = |name: &'static str| { + body.get(name) + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string) + .ok_or(TicketError::MissingClaim(name)) + }; + let carried = URL_SAFE_NO_PAD + .decode( + body.get("carry") + .and_then(Value::as_str) + .ok_or(TicketError::MissingClaim("carry"))?, + ) + .map_err(|_| TicketError::MissingClaim("carry"))?; + if claims.role != Role::Player { + return Err(TicketError::MissingClaim("role")); + } + Ok(VerifiedTicket::Transfer(Transfer { + source_zone: text("src")?, + issuer: text("iss")?, + generation: body + .get("gen") + .and_then(Value::as_u64) + .ok_or(TicketError::MissingClaim("gen"))?, + carried, + claims, + })) + } + Some(_) => Err(TicketError::WrongKind), + } + } + + /// Verify signature and expiry (`now_unix` seconds) of a **join** + /// ticket. Nonce reuse is checked separately with a [`NonceCache`]. pub fn verify(&self, ticket: &str, now_unix: u64) -> Result { + match self.verify_ticket(ticket, now_unix)? { + VerifiedTicket::Join(claims) => Ok(claims), + VerifiedTicket::Transfer(_) => Err(TicketError::WrongKind), + } + } + + fn verify_inner( + &self, + ticket: &str, + now_unix: u64, + ) -> Result<(TicketClaims, Value), TicketError> { let mut parts = ticket.split('.'); let (Some(h), Some(p), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) @@ -128,13 +221,16 @@ impl TicketKey { Some("observer") => Role::Observer, Some(_) => return Err(TicketError::MissingClaim("role")), }; - Ok(TicketClaims { - principal: text("sub")?, - zone: text("zone")?, - expires_at, - nonce: text("nonce")?, - role, - }) + Ok(( + TicketClaims { + principal: text("sub")?, + zone: text("zone")?, + expires_at, + nonce: text("nonce")?, + role, + }, + claims, + )) } } @@ -209,6 +305,29 @@ mod tests { assert_eq!(key.verify(&forged, 1_000), Err(TicketError::BadSignature)); } + #[test] + fn transfer_tickets_round_trip_and_are_not_join_tickets() { + let key = TicketKey::new("secret"); + let transfer = Transfer { + claims: claims(), + source_zone: "z0".into(), + issuer: "h1".into(), + generation: 9, + carried: vec![1, 2, 3], + }; + let ticket = key.sign_transfer(&transfer); + assert_eq!( + key.verify_ticket(&ticket, 1_000).unwrap(), + VerifiedTicket::Transfer(transfer) + ); + assert_eq!(key.verify(&ticket, 1_000), Err(TicketError::WrongKind)); + let join = key.sign(&claims()); + assert_eq!( + key.verify_ticket(&join, 1_000).unwrap(), + VerifiedTicket::Join(claims()) + ); + } + #[test] fn nonce_is_single_use() { let mut cache = NonceCache::default(); diff --git a/distributed_game/src/net/transfer.rs b/distributed_game/src/net/transfer.rs new file mode 100644 index 000000000..eb1ab37a9 --- /dev/null +++ b/distributed_game/src/net/transfer.rs @@ -0,0 +1,155 @@ +//! Issued-transfer records: make every transfer ticket single-use across +//! hosts, and let a failed handoff return to its source. +//! +//! The host that issues a transfer ticket (the source zone's host) keeps a +//! record per nonce: +//! +//! ```text +//! Pending ──reserve(target)──► Reserved ──confirm──► Consumed +//! │ │ └──release (target refused)──► Pending +//! │ └──(reservation expires)──► Consumed +//! └──return(source)──► Consumed +//! ``` +//! +//! The target reserves before admitting and confirms after; the source +//! accepts the same ticket back ("return") only while Pending. A reservation +//! that is never confirmed or released counts as consumed: if in doubt the +//! player is *not* let back into the source (never in two zones; worst +//! case it needs a fresh lobby ticket). + +use std::collections::HashMap; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + Pending, + Reserved { until: u64 }, + Consumed, +} + +/// Registry operation (also the admin wire name). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TransferOp { + /// Target is about to admit. + Reserve, + /// Target admitted. + Confirm, + /// Target refused; the ticket may be used again (e.g. to return). + Release, + /// Source re-admits the player. + Return, +} + +impl TransferOp { + /// Wire name. + pub fn as_str(self) -> &'static str { + match self { + Self::Reserve => "reserve", + Self::Confirm => "confirm", + Self::Release => "release", + Self::Return => "return", + } + } + + /// Parse a wire name. + pub fn parse(name: &str) -> Option { + Some(match name { + "reserve" => Self::Reserve, + "confirm" => Self::Confirm, + "release" => Self::Release, + "return" => Self::Return, + _ => return None, + }) + } +} + +/// Transfer records of the tickets this host issued. +#[derive(Debug, Default)] +pub struct TransferRegistry { + entries: HashMap, +} + +impl TransferRegistry { + /// Record a newly issued ticket (`expires_at` Unix seconds). + pub fn issue(&mut self, nonce: &str, expires_at: u64) { + self.entries + .insert(nonce.to_string(), (State::Pending, expires_at)); + } + + /// Apply `op` at `now` (Unix seconds); `reserve_for` bounds a reservation. + pub fn apply( + &mut self, + op: TransferOp, + nonce: &str, + now: u64, + reserve_for: u64, + ) -> Result<(), &'static str> { + if self.entries.len() > 4096 { + self.entries.retain(|_, (_, exp)| *exp + reserve_for > now); + } + let Some((state, expires_at)) = self.entries.get_mut(nonce) else { + return Err("unknown transfer"); + }; + if let State::Reserved { until } = *state { + if until <= now { + *state = State::Consumed; + } + } + match (op, *state) { + (TransferOp::Reserve, State::Pending) if *expires_at > now => { + *state = State::Reserved { + until: now + reserve_for, + }; + Ok(()) + } + (TransferOp::Confirm, State::Reserved { .. }) => { + *state = State::Consumed; + Ok(()) + } + (TransferOp::Release, State::Reserved { .. }) => { + *state = State::Pending; + Ok(()) + } + (TransferOp::Return, State::Pending) if *expires_at > now => { + *state = State::Consumed; + Ok(()) + } + (_, State::Reserved { .. }) => Err("transfer in progress"), + (_, State::Consumed) => Err("transfer already used"), + _ => Err("transfer expired"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_use_with_release_and_return() { + let mut r = TransferRegistry::default(); + r.issue("n", 100); + r.apply(TransferOp::Reserve, "n", 10, 5).unwrap(); + assert!(r.apply(TransferOp::Return, "n", 11, 5).is_err()); + r.apply(TransferOp::Release, "n", 11, 5).unwrap(); + r.apply(TransferOp::Return, "n", 12, 5).unwrap(); + assert!(r.apply(TransferOp::Reserve, "n", 13, 5).is_err()); + + r.issue("m", 100); + r.apply(TransferOp::Reserve, "m", 10, 5).unwrap(); + r.apply(TransferOp::Confirm, "m", 11, 5).unwrap(); + assert!(r.apply(TransferOp::Return, "m", 12, 5).is_err()); + + // An unconfirmed reservation that lapses counts as used. + r.issue("k", 100); + r.apply(TransferOp::Reserve, "k", 10, 5).unwrap(); + assert_eq!( + r.apply(TransferOp::Return, "k", 20, 5), + Err("transfer already used") + ); + r.issue("e", 15); + assert_eq!( + r.apply(TransferOp::Reserve, "e", 20, 5), + Err("transfer expired") + ); + } +} diff --git a/distributed_game/src/net/world.rs b/distributed_game/src/net/world.rs new file mode 100644 index 000000000..b17be9b9a --- /dev/null +++ b/distributed_game/src/net/world.rs @@ -0,0 +1,495 @@ +//! Admin peer routes and the world barrier coordinator. +//! +//! # Admin routes (`ServerConfig::admin_secret`) +//! +//! `POST` with header `x-game-admin-secret: ` and a JSON body: +//! +//! | Route | Body | Effect | +//! |---|---|---| +//! | `/admin/transfer` | `{op: reserve\|confirm\|release\|return, nonce}` | transfer record at the issuing host | +//! | `/admin/child-event` | `{zone, event}` | deliver a tier-up event to a local zone | +//! | `/admin/barrier/prepare` | `{barrier, reason, version, notes, timeout_ms}` | freeze all zones, wait for acks (409 + `missing`) | +//! | `/admin/barrier/commit` | `{barrier, version, notes, mode: rolling\|hard}` | apply version, resume | +//! | `/admin/barrier/abort` | `{barrier, notes}` | resume on the old version | +//! +//! # Barrier +//! +//! [`WorldCoordinator::rollout`] runs a two-phase barrier over every +//! participant (local [`GameServer`]s and [`RemoteHost`]s): +//! +//! 1. **prepare**: each host freezes all its zones (`Freeze{reason, +//! version}`) and acknowledges once every zone is frozen (a zone may +//! delay with [`Zone::freeze_ready`]). Zones +//! activated during the barrier start frozen. +//! 2. if every host acknowledged within the timeout, the `apply` callback +//! installs the new content; then **commit**: every zone switches to the +//! new version and resumes (`Resume{version, notes}`). +//! +//! Any missing ack (or a failed `apply`) **aborts**: every zone resumes on +//! the old version. No zone ever simulates the new version while another +//! still simulates the old one outside the barrier: nothing resumes before +//! every zone is frozen. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Bytes; +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode}; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use serde_json::{json, Value}; + +use super::peer::{post_json, secret_eq, ADMIN_SECRET_HEADER}; +use super::{activate_local, transfer_op, unix_now, GameServer, Inner, TransferOp, ZoneCmd}; +use crate::facts::BoxFuture; +use crate::protocol::Notice; +use crate::world::{BarrierMode, ChildEvent, HostAddr}; +use crate::zone::Zone; + +type Reply = (StatusCode, String); + +fn reply(status: StatusCode, body: Value) -> Reply { + (status, body.to_string()) +} + +fn authorize(inner: &Inner, headers: &HeaderMap, body: &[u8]) -> Result { + let expected = inner.config.admin_secret.as_deref().unwrap_or_default(); + let presented = headers + .get(ADMIN_SECRET_HEADER) + .map(|v| v.as_bytes()) + .unwrap_or_default(); + if expected.is_empty() || !secret_eq(expected.as_bytes(), presented) { + return Err(reply( + StatusCode::UNAUTHORIZED, + json!({"ok": false, "error": "unauthorized"}), + )); + } + serde_json::from_slice(body).map_err(|e| { + reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": e.to_string()}), + ) + }) +} + +fn text(body: &Value, name: &str) -> String { + body.get(name) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() +} + +pub(super) fn child_event_json(event: &ChildEvent) -> Value { + json!({ + "origin_zone": event.origin_zone, + "from_zone": event.from_zone, + "kind": event.kind, + "payload": URL_SAFE_NO_PAD.encode(&event.payload), + "origin_tick": event.origin_tick, + "content_version": event.content_version, + "levels": event.levels, + }) +} + +fn child_event_from_json(v: &Value) -> Option { + Some(ChildEvent { + origin_zone: v.get("origin_zone")?.as_str()?.to_string(), + from_zone: v.get("from_zone")?.as_str()?.to_string(), + kind: v.get("kind")?.as_str()?.to_string(), + payload: URL_SAFE_NO_PAD.decode(v.get("payload")?.as_str()?).ok()?, + origin_tick: v.get("origin_tick")?.as_u64()?, + content_version: v.get("content_version")?.as_str()?.to_string(), + levels: u8::try_from(v.get("levels")?.as_u64()?).ok()?, + }) +} + +pub(super) async fn admin_transfer( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let Some(op) = TransferOp::parse(&text(&body, "op")) else { + return reply(StatusCode::BAD_REQUEST, json!({"ok": false, "error": "op"})); + }; + let host_id = inner.host_id.clone(); + match transfer_op(&inner, &host_id, op, &text(&body, "nonce")).await { + Ok(()) => reply(StatusCode::OK, json!({"ok": true})), + Err(e) => reply(StatusCode::CONFLICT, json!({"ok": false, "error": e})), + } +} + +pub(super) async fn admin_child_event( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let Some(event) = body.get("event").and_then(child_event_from_json) else { + return reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": "event"}), + ); + }; + // Deliver here only (never re-forward): a peer sent it because its + // directory says we own the zone. + match activate_local(&inner, &text(&body, "zone")) { + Some(tx) => { + let _ = tx.send(ZoneCmd::ChildEvent(event)).await; + reply(StatusCode::OK, json!({"ok": true})) + } + None => reply( + StatusCode::NOT_FOUND, + json!({"ok": false, "error": "unknown zone"}), + ), + } +} + +pub(super) async fn admin_barrier( + State(inner): State>>, + Path(phase): Path, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let server = GameServer { inner }; + let barrier = body.get("barrier").and_then(Value::as_u64).unwrap_or(0); + match phase.as_str() { + "prepare" => { + let notice = Notice { + reason: text(&body, "reason"), + version: text(&body, "version"), + notes: text(&body, "notes"), + }; + let timeout = Duration::from_millis( + body.get("timeout_ms") + .and_then(Value::as_u64) + .unwrap_or(5_000), + ); + match server.prepare_barrier(barrier, notice, timeout).await { + Ok(()) => reply(StatusCode::OK, json!({"ok": true})), + Err(missing) => reply( + StatusCode::CONFLICT, + json!({"ok": false, "missing": missing}), + ), + } + } + "commit" => { + let mode = match text(&body, "mode").as_str() { + "hard" => BarrierMode::Hard, + _ => BarrierMode::Rolling, + }; + server + .commit_barrier( + barrier, + &text(&body, "version"), + &text(&body, "notes"), + mode, + ) + .await; + reply(StatusCode::OK, json!({"ok": true})) + } + "abort" => { + server.abort_barrier(barrier, &text(&body, "notes")).await; + reply(StatusCode::OK, json!({"ok": true})) + } + _ => reply(StatusCode::NOT_FOUND, json!({"ok": false})), + } +} + +/// One host taking part in a world barrier. +pub trait BarrierParticipant: Send + Sync + 'static { + /// Display name (host id). + fn name(&self) -> String; + + /// Freeze everything; `Err` names what did not acknowledge in time. + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>>; + + /// Switch to `version` and resume. + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>>; + + /// Resume on the old version. + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>>; +} + +impl BarrierParticipant for GameServer +where + Z: Zone, + Z::Config: Send, +{ + fn name(&self) -> String { + self.inner.host_id.clone() + } + + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>> { + Box::pin(async move { + let host = self.inner.host_id.clone(); + self.prepare_barrier(barrier, notice.clone(), timeout) + .await + .map_err(|missing| missing.into_iter().map(|z| format!("{host}/{z}")).collect()) + }) + } + + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + self.commit_barrier(barrier, version, notes, mode).await; + Ok(()) + }) + } + + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + self.abort_barrier(barrier, notes).await; + Ok(()) + }) + } +} + +/// A host reached through its admin endpoint. +#[derive(Debug, Clone)] +pub struct RemoteHost { + host: HostAddr, + secret: String, + /// Extra time allowed on top of the barrier timeout for the HTTP call. + slack: Duration, +} + +impl RemoteHost { + /// Remote participant using the shared admin secret. + pub fn new(host: HostAddr, secret: impl Into) -> Self { + Self { + host, + secret: secret.into(), + slack: Duration::from_secs(2), + } + } + + async fn call(&self, path: &str, body: Value, timeout: Duration) -> Result { + match post_json(&self.host.admin_url, path, &self.secret, &body, timeout).await? { + (200, reply) => Ok(reply), + (status, reply) => Err(format!("{} {status}: {reply}", self.host.id)), + } + } +} + +impl BarrierParticipant for RemoteHost { + fn name(&self) -> String { + self.host.id.clone() + } + + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>> { + Box::pin(async move { + let body = json!({ + "barrier": barrier, "reason": notice.reason, "version": notice.version, + "notes": notice.notes, "timeout_ms": timeout.as_millis() as u64, + }); + match post_json( + &self.host.admin_url, + "/admin/barrier/prepare", + &self.secret, + &body, + timeout + self.slack, + ) + .await + { + Ok((200, _)) => Ok(()), + Ok((_, reply)) => Err(reply + .get("missing") + .and_then(Value::as_array) + .map(|zones| { + zones + .iter() + .filter_map(Value::as_str) + .map(|z| format!("{}/{z}", self.host.id)) + .collect() + }) + .unwrap_or_else(|| vec![self.host.id.clone()])), + Err(_) => Err(vec![self.host.id.clone()]), + } + }) + } + + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let mode = match mode { + BarrierMode::Rolling => "rolling", + BarrierMode::Hard => "hard", + }; + let body = + json!({"barrier": barrier, "version": version, "notes": notes, "mode": mode}); + self.call("/admin/barrier/commit", body, self.slack * 2) + .await + .map(|_| ()) + }) + } + + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let body = json!({"barrier": barrier, "notes": notes}); + self.call("/admin/barrier/abort", body, self.slack * 2) + .await + .map(|_| ()) + }) + } +} + +/// Successful rollout. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RolloutReport { + /// Barrier id. + pub barrier: u64, + /// Version now running everywhere. + pub version: String, + /// Commit calls that failed (the host must catch up out of band). + pub commit_errors: Vec, +} + +/// Failed (aborted) rollout: every zone resumed on the old version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RolloutError { + /// Zones/hosts that did not acknowledge the freeze in time. + NotAcked(Vec), + /// The apply callback failed. + ApplyFailed(String), +} + +/// Runs content-version barriers across every participant of one world. +pub struct WorldCoordinator { + participants: Vec>, + ack_timeout: Duration, + next: AtomicU64, +} + +impl WorldCoordinator { + /// Coordinator waiting `ack_timeout` for freeze acknowledgements. + pub fn new(ack_timeout: Duration) -> Self { + Self { + participants: Vec::new(), + ack_timeout, + next: AtomicU64::new(1), + } + } + + /// Add a participant. + pub fn participant(mut self, participant: Arc) -> Self { + self.participants.push(participant); + self + } + + /// Freeze everything, `apply(version)`, resume everything on `version`; + /// abort (resume on the old version) if any zone fails to acknowledge + /// or `apply` fails. + pub async fn rollout( + &self, + version: &str, + notes: &str, + mode: BarrierMode, + apply: impl FnOnce(&str) -> Result<(), String>, + ) -> Result { + let barrier = (unix_now() << 20) ^ self.next.fetch_add(1, Ordering::Relaxed); + let notice = Notice { + reason: "content_update".into(), + version: version.to_string(), + notes: notes.to_string(), + }; + let mut prepares = tokio::task::JoinSet::new(); + for p in &self.participants { + let p = p.clone(); + let notice = notice.clone(); + let timeout = self.ack_timeout; + prepares.spawn(async move { p.prepare(barrier, ¬ice, timeout).await }); + } + let mut missing = Vec::new(); + while let Some(result) = prepares.join_next().await { + match result { + Ok(Ok(())) => {} + Ok(Err(zones)) => missing.extend(zones), + Err(e) => missing.push(e.to_string()), + } + } + if !missing.is_empty() { + missing.sort(); + self.abort_all(barrier, "rollout aborted: freeze not acknowledged") + .await; + return Err(RolloutError::NotAcked(missing)); + } + if let Err(e) = apply(version) { + self.abort_all(barrier, "rollout aborted: apply failed") + .await; + return Err(RolloutError::ApplyFailed(e)); + } + let mut commit_errors = Vec::new(); + for p in &self.participants { + if let Err(e) = p.commit(barrier, version, notes, mode).await { + commit_errors.push(e); + } + } + Ok(RolloutReport { + barrier, + version: version.to_string(), + commit_errors, + }) + } + + async fn abort_all(&self, barrier: u64, notes: &str) { + for p in &self.participants { + let _ = p.abort(barrier, notes).await; + } + } +} diff --git a/distributed_game/src/protocol/messages.rs b/distributed_game/src/protocol/messages.rs index 2c153fbd7..61561f82d 100644 --- a/distributed_game/src/protocol/messages.rs +++ b/distributed_game/src/protocol/messages.rs @@ -36,6 +36,8 @@ pub mod tag { pub const KICK: u8 = 0x87; /// Server → client Error. pub const ERROR: u8 = 0x88; + /// Server → client Redirect (zone owned by another host). + pub const REDIRECT: u8 = 0x89; } /// Kick reason codes. @@ -52,6 +54,9 @@ pub mod kick { pub const ZONE_DISPOSED: u32 = 5; /// Outbound queue overflow (client too slow). pub const SLOW_CONSUMER: u32 = 6; + /// Client content is stale: reload, then reconnect with the last + /// Welcome's reconnect token inside the grace window. + pub const RELOAD: u32 = 7; } /// Error codes. @@ -300,6 +305,14 @@ pub enum ServerMessage { /// Text. message: String, }, + /// This host does not own `zone_id`: reconnect to `url` and send the + /// same Hello again (the ticket was not consumed). Followed by close. + Redirect { + /// Zone the client asked for. + zone_id: String, + /// Full WebSocket URL of the owning host's zone endpoint. + url: String, + }, } /// What a Delta decoder/encoder needs to know about the client's view. @@ -386,6 +399,9 @@ impl ServerMessage { Self::Error { code, message } => { w.u8(tag::ERROR).varuint(*code).string(message); } + Self::Redirect { zone_id, url } => { + w.u8(tag::REDIRECT).string(zone_id).string(url); + } } Ok(w.into_bytes()) } @@ -443,6 +459,10 @@ impl ServerMessage { code: r.varuint()?, message: r.string()?, }, + tag::REDIRECT => Self::Redirect { + zone_id: r.string()?, + url: r.string()?, + }, other => return Err(DecodeError::UnknownMessage(other)), }; r.finish()?; diff --git a/distributed_game/src/world/barrier.rs b/distributed_game/src/world/barrier.rs new file mode 100644 index 000000000..2481d9231 --- /dev/null +++ b/distributed_game/src/world/barrier.rs @@ -0,0 +1,52 @@ +//! Content-version policy shared by [`ZoneHost`](crate::ZoneHost) and the +//! world barrier (`net::WorldCoordinator`). +//! +//! A world runs one content version at a time. A rollout is a two-phase +//! barrier: every zone freezes (and acknowledges), the new version is +//! applied, every zone resumes on it. What happens to clients still running +//! the *old* client build is the [`StalePolicy`] plus the [`BarrierMode`]. + +/// What a host does with a client whose Hello content version differs from +/// the zone's current content version. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum StalePolicy { + /// Reject every admission with a different version + /// (`Error(VERSION_MISMATCH)`). Matches the pre-barrier behavior. + #[default] + Strict, + /// "Keep playing until a safe room": a stale client already in the world + /// keeps its current zone (reconnects are allowed) and may only be + /// handed off into a gate zone ([`Zone::is_gate`](crate::Zone::is_gate)) + /// unless `roam` is true. On entering a gate it is admitted, then told + /// `Kick(RELOAD)` and kept in the reconnect grace window, so the reloaded + /// client reconnects with its token and the new version. A fresh join + /// with a stale version is rejected (`VERSION_MISMATCH`, "reload"). + SafeRoom { + /// Also allow stale clients to be handed off into non-gate zones. + roam: bool, + }, +} + +/// How a committed rollout treats connected clients. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BarrierMode { + /// Zones resume on the new version; stale clients keep playing under the + /// [`StalePolicy`] until they reach a gate (or reconnect). + #[default] + Rolling, + /// Zones resume on the new version and every stale client is sent + /// `Kick(RELOAD)` immediately (kept in the reconnect grace window). + Hard, +} + +/// Freeze progress of one zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FreezeState { + /// Simulating. + Running, + /// A freeze was requested; the zone is not ready yet + /// ([`Zone::freeze_ready`](crate::Zone::freeze_ready)) and still ticks. + Freezing, + /// Frozen: no ticks, inputs dropped and counted. + Frozen, +} diff --git a/distributed_game/src/world/directory.rs b/distributed_game/src/world/directory.rs new file mode 100644 index 000000000..9d31cf8c7 --- /dev/null +++ b/distributed_game/src/world/directory.rs @@ -0,0 +1,275 @@ +//! Zone placement: which host owns a zone. +//! +//! A [`ZoneDirectory`] answers `locate(zone_id)` with the owning +//! [`HostAddr`]. It is advisory routing: actual ownership is enforced by a +//! fenced claim ([`ZoneOwnership`](super::ZoneOwnership)) when the zone is +//! activated, so a stale directory can at worst send a client to the wrong +//! host, which redirects it or refuses — it can never make two hosts run the +//! same zone. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::RwLock; + +use crate::rng::Fnv64; + +/// A host in the world. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct HostAddr { + /// Stable host id (also the ownership holder prefix). + pub id: String, + /// WebSocket base URL, e.g. `ws://10.0.0.2:2567` (clients connect to + /// `{ws_url}/zones/{zone_id}`). + pub ws_url: String, + /// Admin HTTP base URL, e.g. `http://10.0.0.2:2567` (peer calls). + pub admin_url: String, +} + +impl HostAddr { + /// Host listening on `addr` (`host:port`) for both WebSocket and admin. + pub fn new(id: impl Into, addr: impl AsRef) -> Self { + let addr = addr.as_ref(); + Self { + id: id.into(), + ws_url: format!("ws://{addr}"), + admin_url: format!("http://{addr}"), + } + } + + /// Client URL of `zone_id` on this host. + pub fn zone_url(&self, zone_id: &str) -> String { + format!("{}/zones/{zone_id}", self.ws_url) + } +} + +/// Zone → owning host lookup. +pub trait ZoneDirectory: Send + Sync + 'static { + /// Host that should own `zone_id` (None = unknown / not served). + fn locate(&self, zone_id: &str) -> Option; + + /// Host by id. + fn host(&self, host_id: &str) -> Option; + + /// Every known host. + fn hosts(&self) -> Vec; +} + +/// Explicit zone → host assignments with an optional fallback host. +#[derive(Debug, Default)] +pub struct StaticDirectory { + inner: RwLock, +} + +#[derive(Debug, Default)] +struct StaticInner { + hosts: BTreeMap, + zones: HashMap, + fallback: Option, +} + +impl StaticDirectory { + /// Empty directory. + pub fn new() -> Self { + Self::default() + } + + /// Register a host. + pub fn add_host(&self, host: HostAddr) -> &Self { + let mut inner = self.inner.write().expect("directory"); + inner.hosts.insert(host.id.clone(), host); + self + } + + /// Assign `zone_id` to `host_id` (also used to move a zone). + pub fn assign(&self, zone_id: impl Into, host_id: impl Into) -> &Self { + let mut inner = self.inner.write().expect("directory"); + inner.zones.insert(zone_id.into(), host_id.into()); + self + } + + /// Host for zones without an explicit assignment. + pub fn fallback(&self, host_id: impl Into) -> &Self { + self.inner.write().expect("directory").fallback = Some(host_id.into()); + self + } +} + +impl ZoneDirectory for StaticDirectory { + fn locate(&self, zone_id: &str) -> Option { + let inner = self.inner.read().expect("directory"); + let id = inner.zones.get(zone_id).or(inner.fallback.as_ref())?; + inner.hosts.get(id).cloned() + } + + fn host(&self, host_id: &str) -> Option { + self.inner + .read() + .expect("directory") + .hosts + .get(host_id) + .cloned() + } + + fn hosts(&self) -> Vec { + self.inner + .read() + .expect("directory") + .hosts + .values() + .cloned() + .collect() + } +} + +/// Consistent-hash ring over hosts with virtual nodes. +/// +/// Each host owns `vnodes` points on a 64-bit ring; a zone belongs to the +/// first point clockwise from its hash. Adding or removing one of N hosts +/// moves only ~1/N of the zones (those whose nearest point changed); every +/// other zone keeps its owner. +#[derive(Debug)] +pub struct HashRing { + vnodes: u32, + inner: RwLock, +} + +#[derive(Debug, Default)] +struct RingInner { + hosts: BTreeMap, + ring: BTreeMap, +} + +fn ring_hash(bytes: &[u8]) -> u64 { + // FNV-1a then a SplitMix64 finalizer for avalanche. + let mut z = Fnv64::new().write(bytes).finish(); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +impl HashRing { + /// Empty ring with `vnodes` virtual nodes per host (>= 1; 64–256 typical). + pub fn new(vnodes: u32) -> Self { + Self { + vnodes: vnodes.max(1), + inner: RwLock::default(), + } + } + + /// Ring over `hosts`. + pub fn with_hosts(vnodes: u32, hosts: impl IntoIterator) -> Self { + let ring = Self::new(vnodes); + for host in hosts { + ring.add_host(host); + } + ring + } + + /// Add (or replace) a host. + pub fn add_host(&self, host: HostAddr) { + let mut inner = self.inner.write().expect("ring"); + for v in 0..self.vnodes { + let point = ring_hash(format!("{}#{v}", host.id).as_bytes()); + inner.ring.insert(point, host.id.clone()); + } + inner.hosts.insert(host.id.clone(), host); + } + + /// Remove a host; its zones move to their next points. + pub fn remove_host(&self, host_id: &str) { + let mut inner = self.inner.write().expect("ring"); + inner.hosts.remove(host_id); + inner.ring.retain(|_, id| id != host_id); + } + + /// Owning host id of `zone_id`. + pub fn owner_id(&self, zone_id: &str) -> Option { + let inner = self.inner.read().expect("ring"); + let h = ring_hash(zone_id.as_bytes()); + inner + .ring + .range(h..) + .next() + .or_else(|| inner.ring.iter().next()) + .map(|(_, id)| id.clone()) + } +} + +impl ZoneDirectory for HashRing { + fn locate(&self, zone_id: &str) -> Option { + let id = self.owner_id(zone_id)?; + self.host(&id) + } + + fn host(&self, host_id: &str) -> Option { + self.inner.read().expect("ring").hosts.get(host_id).cloned() + } + + fn hosts(&self) -> Vec { + self.inner + .read() + .expect("ring") + .hosts + .values() + .cloned() + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host(i: usize) -> HostAddr { + HostAddr::new(format!("h{i}"), format!("10.0.0.{i}:2567")) + } + + fn owners(ring: &HashRing, zones: &[String]) -> Vec { + zones.iter().map(|z| ring.owner_id(z).unwrap()).collect() + } + + #[test] + fn ring_is_balanced_and_stable_under_add_and_remove() { + let ring = HashRing::with_hosts(128, (0..4).map(host)); + let zones: Vec = (0..4000).map(|i| format!("zone-{i}")).collect(); + let before = owners(&ring, &zones); + let mut counts: HashMap<&str, usize> = HashMap::new(); + for o in &before { + *counts.entry(o.as_str()).or_default() += 1; + } + for (_, n) in counts { + assert!((600..=1400).contains(&n), "unbalanced: {n}"); + } + + ring.add_host(host(4)); + let after = owners(&ring, &zones); + let moved = before.iter().zip(&after).filter(|(a, b)| a != b).count(); + // Ideal is 1/5 = 800; every moved zone moved to the new host. + assert!(moved > 400 && moved < 1300, "moved {moved}"); + assert!(before.iter().zip(&after).all(|(a, b)| a == b || b == "h4")); + + ring.remove_host("h4"); + assert_eq!(owners(&ring, &zones), before); + + ring.remove_host("h1"); + let without = owners(&ring, &zones); + assert!(before + .iter() + .zip(&without) + .all(|(a, b)| a == b || a == "h1")); + assert!(ring.locate("zone-1").is_some()); + assert_eq!(ring.hosts().len(), 3); + } + + #[test] + fn static_directory_assigns_with_fallback() { + let dir = StaticDirectory::new(); + dir.add_host(host(1)).add_host(host(2)); + dir.assign("realm.west", "h2").fallback("h1"); + assert_eq!(dir.locate("realm.west").unwrap().id, "h2"); + assert_eq!(dir.locate("anything").unwrap().id, "h1"); + assert_eq!( + dir.locate("realm.west").unwrap().zone_url("realm.west"), + "ws://10.0.0.2:2567/zones/realm.west" + ); + } +} diff --git a/distributed_game/src/world/mod.rs b/distributed_game/src/world/mod.rs new file mode 100644 index 000000000..c95d4fa30 --- /dev/null +++ b/distributed_game/src/world/mod.rs @@ -0,0 +1,30 @@ +//! World structure: where zones live, how they nest, how their durable state +//! survives hibernation and how ownership is fenced. +//! +//! - [`directory`]: [`ZoneDirectory`] maps a zone id to its owning host +//! ([`StaticDirectory`], consistent-hash [`HashRing`]). +//! - [`ownership`]: [`ZoneOwnership`] fenced claims so two hosts never run +//! the same zone ([`LocalOwnership`]; `FencedLeaseOwnership` over +//! `distributed::lease` with the `lease` feature). +//! - [`state`]: [`ZoneStateStore`] for hibernated zone state +//! ([`MemoryZoneStateStore`]; `SqliteZoneStateStore` with `sqlite`). +//! - [`topology`]: [`ZoneTopology`] parent links (province > city > borough +//! > neighborhood) and [`ChildEvent`] tier-up propagation. +//! - [`barrier`]: content-version policy types shared by the host and the +//! world barrier ([`StalePolicy`], [`BarrierMode`]). + +pub mod barrier; +pub mod directory; +pub mod ownership; +pub mod state; +pub mod topology; + +pub use barrier::{BarrierMode, FreezeState, StalePolicy}; +pub use directory::{HashRing, HostAddr, StaticDirectory, ZoneDirectory}; +#[cfg(feature = "lease")] +pub use ownership::FencedLeaseOwnership; +pub use ownership::{LocalOwnership, OwnershipError, ZoneClaim, ZoneOwnership}; +#[cfg(feature = "sqlite")] +pub use state::SqliteZoneStateStore; +pub use state::{MemoryZoneStateStore, StateError, StoredZoneState, ZoneStateStore}; +pub use topology::{ChildEvent, DottedTopology, FlatTopology, ZoneTopology}; diff --git a/distributed_game/src/world/ownership.rs b/distributed_game/src/world/ownership.rs new file mode 100644 index 000000000..499f0645e --- /dev/null +++ b/distributed_game/src/world/ownership.rs @@ -0,0 +1,274 @@ +//! Fenced zone ownership: at most one host runs a zone. +//! +//! A host activating a zone first acquires a claim on it +//! ([`ZoneOwnership::acquire`]) and keeps renewing it while the zone runs. +//! Every acquisition carries a fencing token strictly greater than any +//! earlier one for that zone, so writes made under an old claim (e.g. a +//! hibernation snapshot from a paused host) are rejected by fenced stores +//! ([`ZoneStateStore::save`](super::ZoneStateStore::save)). A host whose +//! renewal fails ([`OwnershipError::Lost`]) must stop the zone immediately +//! without persisting anything. +//! +//! Holders are `"{host_id}#{activation}"`, so a re-activation on the same +//! host (after hibernation) waits for the previous activation to release. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, SystemTime}; + +use crate::facts::BoxFuture; + +/// A held claim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneClaim { + /// Zone id. + pub zone_id: String, + /// Holder (`host#activation`). + pub holder: String, + /// Monotonic fencing token. + pub token: u64, + /// Expiry as seen by the ownership store (`UNIX_EPOCH` = no TTL). + pub expires_at: SystemTime, +} + +/// Ownership failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OwnershipError { + /// Someone else holds a live claim. + Held { + /// Current holder. + holder: String, + }, + /// The claim expired or was superseded: stop the zone. + Lost, + /// Transient backend failure. + Backend(String), +} + +/// Store of fenced zone claims. +pub trait ZoneOwnership: Send + Sync + 'static { + /// Acquire `zone_id` for `holder` for `ttl`. + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result>; + + /// Extend a live claim (keeps its token). + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result>; + + /// Release a claim early. + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()>; +} + +/// Process-local ownership without TTLs (single host / tests). Tokens are +/// monotonic per zone and survive release. +#[derive(Debug, Default)] +pub struct LocalOwnership { + claims: Mutex, u64)>>, +} + +impl LocalOwnership { + /// Empty. + pub fn new() -> Self { + Self::default() + } +} + +impl ZoneOwnership for LocalOwnership { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let mut claims = self.claims.lock().expect("claims"); + let entry = claims.entry(zone_id.to_string()).or_insert((None, 0)); + match &entry.0 { + Some(current) if current != holder => Err(OwnershipError::Held { + holder: current.clone(), + }), + Some(_) => Ok(entry.1), + None => { + entry.0 = Some(holder.to_string()); + entry.1 += 1; + Ok(entry.1) + } + } + .map(|token| ZoneClaim { + zone_id: zone_id.to_string(), + holder: holder.to_string(), + token, + expires_at: SystemTime::UNIX_EPOCH, + }) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let claims = self.claims.lock().expect("claims"); + match claims.get(&claim.zone_id) { + Some((Some(holder), token)) if *holder == claim.holder && *token == claim.token => { + Ok(claim.clone()) + } + _ => Err(OwnershipError::Lost), + } + }) + } + + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let mut claims = self.claims.lock().expect("claims"); + if let Some(entry) = claims.get_mut(&claim.zone_id) { + if entry.0.as_deref() == Some(claim.holder.as_str()) && entry.1 == claim.token { + entry.0 = None; + } + } + }) + } +} + +/// Zone ownership over any `distributed::lease::LeaseStore` (in-memory, +/// SQLite or Postgres): key `zone:{zone_id}`, the lease's fencing token is +/// the claim token. +#[cfg(feature = "lease")] +#[derive(Debug, Clone)] +pub struct FencedLeaseOwnership { + store: S, +} + +#[cfg(feature = "lease")] +impl FencedLeaseOwnership { + /// Wrap a lease store. + pub fn new(store: S) -> Self { + Self { store } + } + + /// The lease store. + pub fn store(&self) -> &S { + &self.store + } +} + +#[cfg(feature = "lease")] +fn lease_key(zone_id: &str) -> String { + format!("zone:{zone_id}") +} + +#[cfg(feature = "lease")] +fn map_lease_error(error: distributed::lease::LeaseError) -> OwnershipError { + use distributed::lease::LeaseError; + match error { + LeaseError::Held { holder, .. } => OwnershipError::Held { holder }, + LeaseError::Lost { .. } | LeaseError::StaleFence { .. } => OwnershipError::Lost, + other => OwnershipError::Backend(other.to_string()), + } +} + +#[cfg(feature = "lease")] +fn claim_of(zone_id: &str, lease: distributed::lease::Lease) -> ZoneClaim { + ZoneClaim { + zone_id: zone_id.to_string(), + holder: lease.holder, + token: lease.token.get(), + expires_at: lease.expires_at, + } +} + +#[cfg(feature = "lease")] +impl ZoneOwnership for FencedLeaseOwnership +where + S: distributed::lease::LeaseStore + 'static, +{ + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let key = lease_key(zone_id); + self.store + .acquire(&key, holder, ttl) + .await + .map(|lease| claim_of(zone_id, lease)) + .map_err(map_lease_error) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let lease = distributed::lease::Lease { + key: lease_key(&claim.zone_id), + holder: claim.holder.clone(), + token: distributed::lease::FencingToken::new(claim.token), + expires_at: claim.expires_at, + }; + self.store + .renew(&lease, ttl) + .await + .map(|lease| claim_of(&claim.zone_id, lease)) + .map_err(map_lease_error) + }) + } + + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let lease = distributed::lease::Lease { + key: lease_key(&claim.zone_id), + holder: claim.holder.clone(), + token: distributed::lease::FencingToken::new(claim.token), + expires_at: claim.expires_at, + }; + let _ = self.store.release(&lease).await; + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(f: impl std::future::Future) -> T { + // The local store never awaits anything; poll once. + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + match f.as_mut().poll(&mut cx) { + std::task::Poll::Ready(v) => v, + std::task::Poll::Pending => panic!("local ownership must not pend"), + } + } + + #[test] + fn local_claims_are_exclusive_and_tokens_monotonic() { + let own = LocalOwnership::new(); + let ttl = Duration::from_secs(1); + let a = block(own.acquire("z", "h1#1", ttl)).unwrap(); + assert_eq!( + block(own.acquire("z", "h2#1", ttl)), + Err(OwnershipError::Held { + holder: "h1#1".into() + }) + ); + assert_eq!(block(own.acquire("z", "h1#1", ttl)).unwrap(), a); + block(own.release(&a)); + assert_eq!(block(own.renew(&a, ttl)), Err(OwnershipError::Lost)); + let b = block(own.acquire("z", "h2#1", ttl)).unwrap(); + assert!(b.token > a.token); + } +} diff --git a/distributed_game/src/world/state.rs b/distributed_game/src/world/state.rs new file mode 100644 index 000000000..ef7e6fad1 --- /dev/null +++ b/distributed_game/src/world/state.rs @@ -0,0 +1,261 @@ +//! Durable zone state for hibernation. +//! +//! When a zone hibernates, the host asks it for a snapshot +//! ([`Zone::hibernate`](crate::Zone::hibernate)) and stores it here under +//! the zone's ownership token; the next activation (on any host) loads it +//! and hands it to [`Zone::on_restore`](crate::Zone::on_restore). +//! +//! Writes are **fenced**: `save` with a token older than the stored one +//! fails with [`StateError::Stale`], so a host that lost ownership while +//! paused can never overwrite the state written by its successor. +//! +//! The trait is synchronous (snapshots are small and rare); async drivers +//! call it on a blocking thread. +//! +//! Why not an `AggregateCell`: a hibernation snapshot is a whole-value +//! overwrite keyed by zone, not a stream of domain events; storing it as +//! events would grow without bound and buy nothing. Durable *outcomes* (XP, +//! loot) go through facts into cells; the snapshot only holds ephemeral +//! simulation state worth keeping across a cold start. + +use std::collections::HashMap; +use std::sync::Mutex; + +/// A stored snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredZoneState { + /// Ownership token it was written under. + pub token: u64, + /// Content version the zone was running. + pub content_version: String, + /// Opaque zone bytes. + pub state: Vec, +} + +/// Store failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StateError { + /// Write fenced off: a newer owner already saved. + Stale { + /// Presented token. + presented: u64, + /// Stored token. + current: u64, + }, + /// Backend failure. + Backend(String), +} + +impl std::fmt::Display for StateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Stale { presented, current } => { + write!(f, "stale zone-state token {presented} (current {current})") + } + Self::Backend(e) => write!(f, "zone-state backend: {e}"), + } + } +} + +impl std::error::Error for StateError {} + +/// Fenced snapshot store. +pub trait ZoneStateStore: Send + Sync + 'static { + /// Latest snapshot of `zone_id`. + fn load(&self, zone_id: &str) -> Result, StateError>; + + /// Store a snapshot if `state.token` >= the stored token. + fn save(&self, zone_id: &str, state: &StoredZoneState) -> Result<(), StateError>; +} + +/// In-memory store (tests / single process). +#[derive(Debug, Default)] +pub struct MemoryZoneStateStore { + states: Mutex>, +} + +impl MemoryZoneStateStore { + /// Empty. + pub fn new() -> Self { + Self::default() + } +} + +impl ZoneStateStore for MemoryZoneStateStore { + fn load(&self, zone_id: &str) -> Result, StateError> { + Ok(self.states.lock().expect("states").get(zone_id).cloned()) + } + + fn save(&self, zone_id: &str, state: &StoredZoneState) -> Result<(), StateError> { + let mut states = self.states.lock().expect("states"); + if let Some(current) = states.get(zone_id) { + if current.token > state.token { + return Err(StateError::Stale { + presented: state.token, + current: current.token, + }); + } + } + states.insert(zone_id.to_string(), state.clone()); + Ok(()) + } +} + +/// Native SQLite store (feature `sqlite`): one table, one fenced upsert. +#[cfg(feature = "sqlite")] +pub struct SqliteZoneStateStore { + conn: Mutex, +} + +#[cfg(feature = "sqlite")] +impl std::fmt::Debug for SqliteZoneStateStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("SqliteZoneStateStore") + } +} + +#[cfg(feature = "sqlite")] +fn backend(e: rusqlite::Error) -> StateError { + StateError::Backend(e.to_string()) +} + +#[cfg(feature = "sqlite")] +impl SqliteZoneStateStore { + /// Open (or create) the database file. + pub fn open(path: impl AsRef) -> Result { + Self::from_connection(rusqlite::Connection::open(path).map_err(backend)?) + } + + /// In-memory database. + pub fn open_in_memory() -> Result { + Self::from_connection(rusqlite::Connection::open_in_memory().map_err(backend)?) + } + + fn from_connection(conn: rusqlite::Connection) -> Result { + conn.execute_batch( + "PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS game_zone_state ( + zone_id TEXT PRIMARY KEY, + token INTEGER NOT NULL, + content_version TEXT NOT NULL, + state BLOB NOT NULL + );", + ) + .map_err(backend)?; + Ok(Self { + conn: Mutex::new(conn), + }) + } +} + +#[cfg(feature = "sqlite")] +impl ZoneStateStore for SqliteZoneStateStore { + fn load(&self, zone_id: &str) -> Result, StateError> { + use rusqlite::OptionalExtension; + let conn = self.conn.lock().expect("sqlite"); + conn.query_row( + "SELECT token, content_version, state FROM game_zone_state WHERE zone_id = ?1", + [zone_id], + |row| { + Ok(StoredZoneState { + token: row.get::<_, i64>(0)? as u64, + content_version: row.get(1)?, + state: row.get(2)?, + }) + }, + ) + .optional() + .map_err(backend) + } + + fn save(&self, zone_id: &str, state: &StoredZoneState) -> Result<(), StateError> { + let conn = self.conn.lock().expect("sqlite"); + let token = i64::try_from(state.token).map_err(|_| StateError::Backend("token".into()))?; + let changed = conn + .execute( + "INSERT INTO game_zone_state (zone_id, token, content_version, state) + VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(zone_id) DO UPDATE SET + token = excluded.token, + content_version = excluded.content_version, + state = excluded.state + WHERE excluded.token >= game_zone_state.token", + rusqlite::params![zone_id, token, state.content_version, state.state], + ) + .map_err(backend)?; + if changed == 0 { + let current: i64 = conn + .query_row( + "SELECT token FROM game_zone_state WHERE zone_id = ?1", + [zone_id], + |row| row.get(0), + ) + .map_err(backend)?; + return Err(StateError::Stale { + presented: state.token, + current: current as u64, + }); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn snap(token: u64, bytes: &[u8]) -> StoredZoneState { + StoredZoneState { + token, + content_version: "c1".into(), + state: bytes.to_vec(), + } + } + + fn exercise(store: &dyn ZoneStateStore) { + assert_eq!(store.load("z").unwrap(), None); + store.save("z", &snap(2, b"a")).unwrap(); + store.save("z", &snap(2, b"b")).unwrap(); + assert_eq!( + store.save("z", &snap(1, b"old")), + Err(StateError::Stale { + presented: 1, + current: 2 + }) + ); + store.save("z", &snap(3, b"c")).unwrap(); + assert_eq!(store.load("z").unwrap(), Some(snap(3, b"c"))); + } + + #[test] + fn memory_store_is_fenced() { + exercise(&MemoryZoneStateStore::new()); + } + + #[cfg(feature = "sqlite")] + #[test] + fn sqlite_store_is_fenced_and_durable() { + exercise(&SqliteZoneStateStore::open_in_memory().unwrap()); + let path = std::env::temp_dir().join(format!( + "dg-zone-state-{}-{}.sqlite3", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + { + let store = SqliteZoneStateStore::open(&path).unwrap(); + store.save("realm.east", &snap(7, b"boss:dead")).unwrap(); + } + let reopened = SqliteZoneStateStore::open(&path).unwrap(); + assert_eq!( + reopened.load("realm.east").unwrap(), + Some(snap(7, b"boss:dead")) + ); + drop(reopened); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + } +} diff --git a/distributed_game/src/world/topology.rs b/distributed_game/src/world/topology.rs new file mode 100644 index 000000000..307801539 --- /dev/null +++ b/distributed_game/src/world/topology.rs @@ -0,0 +1,93 @@ +//! Zone hierarchy and tier-up event propagation. +//! +//! Zones can nest (province > city > borough > neighborhood). A +//! [`ZoneTopology`] names each zone's parent. A zone emits a tier-up event +//! with [`Ctx::emit_upward`](crate::Ctx::emit_upward); the driver +//! (`net::GameServer`) routes it to the parent — activating the parent on +//! demand, on another host through the directory if needed — and the +//! parent's host delivers it to [`Zone::on_child_event`](crate::Zone::on_child_event) +//! on a later tick. Nothing blocks: the child's tick only enqueues. +//! +//! After delivering, the parent's host forwards the event further up while +//! `levels` remain (`levels = 1` reaches only the parent; the default +//! reaches the root). + +/// Parent links between zones. +pub trait ZoneTopology: Send + Sync + 'static { + /// Parent zone id, None for a root. + fn parent(&self, zone_id: &str) -> Option; +} + +/// `"eldoria.port.docks"` → parent `"eldoria.port"` → `"eldoria"` → root. +#[derive(Debug, Clone, Copy, Default)] +pub struct DottedTopology; + +impl ZoneTopology for DottedTopology { + fn parent(&self, zone_id: &str) -> Option { + zone_id + .rsplit_once('.') + .map(|(parent, _)| parent.to_string()) + .filter(|p| !p.is_empty()) + } +} + +/// No hierarchy. +#[derive(Debug, Clone, Copy, Default)] +pub struct FlatTopology; + +impl ZoneTopology for FlatTopology { + fn parent(&self, _zone_id: &str) -> Option { + None + } +} + +impl ZoneTopology for F +where + F: Fn(&str) -> Option + Send + Sync + 'static, +{ + fn parent(&self, zone_id: &str) -> Option { + self(zone_id) + } +} + +/// A tier-up event travelling from a child zone towards the root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChildEvent { + /// Zone that emitted it originally. + pub origin_zone: String, + /// Zone it was forwarded from (the direct child of the receiver). + pub from_zone: String, + /// Game-defined kind, e.g. `"boss_defeated"`. + pub kind: String, + /// Game-defined payload. + pub payload: Vec, + /// Origin tick. + pub origin_tick: u64, + /// Content version of the origin zone when emitted. + pub content_version: String, + /// Remaining levels to travel (>= 1 while in flight). + pub levels: u8, +} + +impl ChildEvent { + /// Levels value that reaches the root. + pub const TO_ROOT: u8 = u8::MAX; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dotted_parents() { + let t = DottedTopology; + assert_eq!( + t.parent("eldoria.port.docks").as_deref(), + Some("eldoria.port") + ); + assert_eq!(t.parent("eldoria.port").as_deref(), Some("eldoria")); + assert_eq!(t.parent("eldoria"), None); + let f = |z: &str| (z == "a").then(|| "b".to_string()); + assert_eq!(f.parent("a").as_deref(), Some("b")); + } +} diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index 0a70726e1..bd62f03b6 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -16,6 +16,7 @@ use crate::protocol::Role; use crate::replication::WorldView; use crate::schema::EntitySchema; use crate::timers::TimerId; +use crate::world::ChildEvent; /// Stable id of a player within a zone (survives reconnects). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -192,4 +193,54 @@ pub trait Zone: Sized + Send + 'static { /// The zone is being destroyed; timers are cleared afterwards. fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + // ---- World structure (all optional) ---- + + /// Durable snapshot taken when the zone hibernates (Dormant long + /// enough); `None` = nothing worth keeping. Stored in a + /// [`ZoneStateStore`](crate::world::ZoneStateStore) and handed to + /// [`on_restore`](Self::on_restore) on the next activation. + fn hibernate(&self) -> Option> { + None + } + + /// Restore a snapshot written by [`hibernate`](Self::hibernate) (called + /// right after `on_create`). `saved_version` is the content version it + /// was written under. + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, _state: &[u8], _saved_version: &str) {} + + /// A player arrived through a handoff from `from_zone` with `carried` + /// state (instead of `on_join`). Also called when the principal was + /// still present (reconnect grace), and for a handoff that failed and + /// returned to its source (`from_zone` is then the zone it never + /// reached). Defaults to `on_join`. + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + _from_zone: &str, + _carried: Vec, + ) { + self.on_join(ctx, player); + } + + /// A tier-up event from a descendant zone (see + /// [`world::topology`](crate::world::topology)). + fn on_child_event(&mut self, _ctx: &mut Ctx<'_, Self>, _event: &ChildEvent) {} + + /// True marks a safe-room gate: stale clients are told to reload here + /// (see [`StalePolicy`](crate::world::StalePolicy)). + fn is_gate(&self) -> bool { + false + } + + /// Barrier readiness: while false a requested freeze waits (the zone + /// keeps ticking), e.g. to finish a boss phase. A world barrier aborts + /// if a zone is not ready within its timeout. + fn freeze_ready(&self) -> bool { + true + } + + /// The content version changed (world barrier commit). + fn on_content_version_changed(&mut self, _ctx: &mut Ctx<'_, Self>, _from: &str, _to: &str) {} } diff --git a/distributed_game/tests/fixtures/messages.json b/distributed_game/tests/fixtures/messages.json index 323b09e16..ca36cf342 100644 --- a/distributed_game/tests/fixtures/messages.json +++ b/distributed_game/tests/fixtures/messages.json @@ -506,6 +506,26 @@ "direction": "server_to_client", "hex": "88020745787069726564", "name": "error" + }, + { + "decoded": { + "code": 7, + "message": "content c2 required", + "type": "Kick" + }, + "direction": "server_to_client", + "hex": "870713636f6e74656e74206332207265717569726564", + "name": "kick_reload" + }, + { + "decoded": { + "type": "Redirect", + "url": "ws://10.0.0.2:2567/zones/realm.west", + "zone_id": "realm.west" + }, + "direction": "server_to_client", + "hex": "890a7265616c6d2e776573742377733a2f2f31302e302e302e323a323536372f7a6f6e65732f7265616c6d2e77657374", + "name": "redirect" } ] } diff --git a/distributed_game/tests/golden/main.rs b/distributed_game/tests/golden/main.rs index ee7a8767d..5ecb5acfc 100644 --- a/distributed_game/tests/golden/main.rs +++ b/distributed_game/tests/golden/main.rs @@ -154,6 +154,9 @@ fn server_json(m: &ServerMessage) -> Value { ServerMessage::Error { code, message } => { json!({ "type": "Error", "code": code, "message": message }) } + ServerMessage::Redirect { zone_id, url } => { + json!({ "type": "Redirect", "zone_id": zone_id, "url": url }) + } } } @@ -480,6 +483,20 @@ fn messages() { message: "Expired".into(), }, ), + ( + "kick_reload", + ServerMessage::Kick { + code: kick::RELOAD, + message: "content c2 required".into(), + }, + ), + ( + "redirect", + ServerMessage::Redirect { + zone_id: "realm.west".into(), + url: "ws://10.0.0.2:2567/zones/realm.west".into(), + }, + ), ]; for (name, msg) in server { let bytes = msg.encode(&ctx).unwrap(); diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs new file mode 100644 index 000000000..19db43535 --- /dev/null +++ b/distributed_game/tests/world/main.rs @@ -0,0 +1,779 @@ +//! Two GameServers in one process on different ports: cross-host handoff +//! with a real WebSocket client, tier-up events across hosts, hibernation, +//! fenced ownership and the world content barrier. + +mod realm; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed::lease::InMemoryLeaseStore; +use distributed_game::net::{ + GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, WorldCoordinator, +}; +use distributed_game::protocol::{error, kick, Hello, Notice}; +use distributed_game::world::{ + FencedLeaseOwnership, HostAddr, LocalOwnership, SqliteZoneStateStore, StaticDirectory, + ZoneDirectory, ZoneOwnership, ZoneStateStore, +}; +use distributed_game::*; +use futures_util::{SinkExt, StreamExt}; +use realm::*; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +type Ws = WebSocketStream>; + +const SECRET: &str = "world-secret"; +const ADMIN: &str = "admin-secret"; + +fn ticket(principal: &str, zone: &str, nonce: &str) -> String { + TicketKey::new(SECRET).sign(&TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role: Role::Player, + }) +} + +struct Node { + server: GameServer, + addr: HostAddr, + sink: MemoryFactSink, +} + +type Factory = Arc Option + Send + Sync>; + +fn base_config() -> ServerConfig { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.patch_rate = 10; + config.admin_secret = Some(ADMIN.into()); + config +} + +async fn listen() -> (tokio::net::TcpListener, String) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + (listener, addr) +} + +fn serve(server: &GameServer, listener: tokio::net::TcpListener) { + let serving = server.clone(); + tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); +} + +/// Start two hosts "A" and "B" sharing a directory and ownership. +async fn two_hosts( + config: impl Fn() -> ServerConfig, + assign: &[(&str, &str)], + factory: Factory, + ownership: Arc, +) -> (Node, Node, Arc) { + let (la, a_addr) = listen().await; + let (lb, b_addr) = listen().await; + let a = HostAddr::new("A", &a_addr); + let b = HostAddr::new("B", &b_addr); + let dir = Arc::new(StaticDirectory::new()); + dir.add_host(a.clone()).add_host(b.clone()); + for (zone, host) in assign { + dir.assign(*zone, *host); + } + dir.fallback("A"); + let mut nodes = Vec::new(); + for (host, listener) in [(a, la), (b, lb)] { + let sink = MemoryFactSink::new(); + let f = factory.clone(); + let server = GameServer::::new(config(), move |zone| f(zone)) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()) + .with_host_id(host.id.clone()) + .with_directory(dir.clone()) + .with_ownership(ownership.clone()); + serve(&server, listener); + nodes.push(Node { + server, + addr: host, + sink, + }); + } + let b = nodes.pop().unwrap(); + let a = nodes.pop().unwrap(); + (a, b, dir) +} + +async fn send(ws: &mut Ws, msg: ClientMessage) { + ws.send(Message::Binary(msg.encode().into())).await.unwrap(); +} + +async fn hello(ws: &mut Ws, ticket: &str, token: &str, version: &str) { + send( + ws, + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: version.into(), + capabilities: 0, + ticket: ticket.into(), + reconnect_token: token.into(), + }), + ) + .await; +} + +async fn next(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + let frame = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("server message within 5s")?; + match frame { + Ok(Message::Binary(bytes)) => return Some(mirror.apply(&bytes).unwrap()), + Ok(Message::Close(_)) | Err(_) => return None, + Ok(_) => continue, + } + } +} + +/// Next message that is not a Delta. +async fn next_control(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + match next(ws, mirror).await? { + ServerMessage::Delta(_) => continue, + other => return Some(other), + } + } +} + +async fn connect(url: &str) -> Ws { + connect_async(url).await.unwrap().0 +} + +struct Client { + ws: Ws, + mirror: ClientMirror, + welcome: protocol::Welcome, +} + +/// Connect to `url` (a zone URL), following Redirects, and expect Welcome. +#[allow(clippy::result_large_err)] +async fn join_url(url: &str, ticket: &str, version: &str) -> Result { + let mut url = url.to_string(); + for _ in 0..3 { + let mut ws = connect(&url).await; + hello(&mut ws, ticket, "", version).await; + let mut mirror = ClientMirror::new(); + match next_control(&mut ws, &mut mirror).await.expect("reply") { + ServerMessage::Welcome(welcome) => { + return Ok(Client { + ws, + mirror, + welcome, + }) + } + ServerMessage::Redirect { url: to, .. } => url = to, + other => return Err(other), + } + } + panic!("redirect loop") +} + +async fn control(client: &mut Client) -> Option { + next_control(&mut client.ws, &mut client.mirror).await +} + +/// Next Freeze/Resume/Kick/Error (skips Deltas and game Events). +async fn next_notice(client: &mut Client) -> Option { + loop { + match control(client).await? { + ServerMessage::Event { .. } => continue, + other => return Some(other), + } + } +} + +async fn input(client: &mut Client, seq: u32, cmd: u8) { + send( + &mut client.ws, + ClientMessage::Input { + seq, + client_tick: 0, + payload: vec![cmd], + }, + ) + .await; +} + +async fn eventually(what: &str, mut check: F) +where + F: FnMut() -> Fut, + Fut: std::future::Future, +{ + for _ in 0..200 { + if check().await { + return; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("timed out waiting for {what}"); +} + +fn realm_factory( + neighbours: &[(&'static str, &'static str)], + rejecting: &'static [&'static str], +) -> Factory { + let neighbours: Vec<(String, String)> = neighbours + .iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect(); + Arc::new(move |zone: &str| { + if !zone.starts_with("realm") && !zone.starts_with('z') { + return None; + } + Some(RealmConfig { + neighbour: neighbours + .iter() + .find(|(from, _)| from == zone) + .map(|(_, to)| to.clone()), + reject_all: rejecting.contains(&zone), + gate: zone.ends_with(".inn"), + freeze_ready: !zone.ends_with(".stuck"), + }) + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn cross_host_handoff_follows_redirect_and_ticket_is_single_use() { + let (a, b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "B")], + realm_factory(&[("realm.east", "realm.west")], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + + // Asking B for an A zone redirects without consuming the ticket. + let t = ticket("ana", "realm.east", "n1"); + let mut ana = join_url(&b.addr.zone_url("realm.east"), &t, "") + .await + .unwrap(); + assert_eq!(ana.welcome.zone_id, "realm.east"); + assert!(a.server.is_active("realm.east")); + assert!(!b.server.is_active("realm.east")); + + for seq in 1..=2 { + input(&mut ana, seq, CMD_COUNT).await; + } + input(&mut ana, 3, CMD_HANDOFF).await; + let (target, transfer) = loop { + match control(&mut ana).await { + Some(ServerMessage::Handoff { + target_zone, + transfer_ticket, + }) => break (target_zone, transfer_ticket), + Some(_) => continue, + None => panic!("closed before Handoff"), + } + }; + assert_eq!(target, "realm.west"); + // The source fenced the player out before the ticket was usable. + assert_eq!( + a.server.inspect("realm.east", |h| h.player_count()).await, + Some(0) + ); + + // Client follows: same host first (Redirect to B), then B admits. + let mut west = join_url(&a.addr.zone_url(&target), &transfer, "") + .await + .unwrap(); + assert_eq!(west.welcome.zone_id, "realm.west"); + let arrived = loop { + match control(&mut west).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_ARRIVED => break payload, + _ => continue, + } + }; + assert_eq!(arrived, b"ana:gold=2|realm.east"); + let arrivals = b + .server + .inspect("realm.west", |h| h.zone().arrivals.clone()) + .await + .unwrap(); + assert_eq!(arrivals[0].principal, "ana"); + + // Single use: neither the target nor the source accepts it again. + match join_url(&b.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::UNAUTHORIZED), + other => panic!("replay admitted: {:?}", other.map(|c| c.welcome)), + } + match join_url(&a.addr.zone_url("realm.east"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::UNAUTHORIZED), + other => panic!( + "return after arrival admitted: {:?}", + other.map(|c| c.welcome) + ), + } + // A forged transfer (wrong key) is refused. + let forged = TicketKey::new("nope").sign(&TicketClaims { + principal: "mallory".into(), + zone: "realm.west".into(), + expires_at: 4_000_000_000, + nonce: "x".into(), + role: Role::Player, + }); + assert!(join_url(&b.addr.zone_url("realm.west"), &forged, "") + .await + .is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn refused_handoff_returns_to_source_with_carried_state() { + let (a, b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "B")], + realm_factory(&[("realm.east", "realm.west")], &["realm.west"]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &a.addr.zone_url("realm.east"), + &ticket("ana", "realm.east", "r1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_COUNT).await; + input(&mut ana, 2, CMD_HANDOFF).await; + let transfer = loop { + if let Some(ServerMessage::Handoff { + transfer_ticket, .. + }) = control(&mut ana).await + { + break transfer_ticket; + } + }; + // Target refuses (zone closed) -> policy: return to the source. + match join_url(&b.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::REJECTED), + other => panic!("expected rejection: {:?}", other.map(|c| c.welcome)), + } + let mut back = join_url(&a.addr.zone_url("realm.east"), &transfer, "") + .await + .unwrap(); + let arrived = loop { + match control(&mut back).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_ARRIVED => break payload, + _ => continue, + } + }; + // Carried state comes back; `from` is the zone it never reached. + assert_eq!(arrived, b"ana:gold=1|realm.west"); + // Once returned, the ticket is dead at the target too. + assert!(join_url(&b.addr.zone_url("realm.west"), &transfer, "") + .await + .is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn boss_defeat_tiers_up_to_parent_and_grandparent_across_hosts() { + let (a, b, _dir) = two_hosts( + base_config, + &[ + ("realm", "A"), + ("realm.east", "A"), + ("realm.east.keep", "B"), + ], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &b.addr.zone_url("realm.east.keep"), + &ticket("ana", "realm.east.keep", "b1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_BOSS).await; + for zone in ["realm.east", "realm"] { + let server = a.server.clone(); + eventually(zone, || { + let server = server.clone(); + async move { + server + .inspect(zone, |h| { + h.zone().child_events.iter().any(|e| { + e.kind == "boss_defeated" && e.origin_zone == "realm.east.keep" + }) + }) + .await + .unwrap_or(false) + } + }) + .await; + } + let grand = a + .server + .inspect("realm", |h| h.zone().child_events.clone()) + .await + .unwrap(); + assert_eq!(grand.len(), 1); + assert_eq!(grand[0].from_zone, "realm.east"); + assert_eq!(grand[0].payload, b"realm.east.keep"); + // Parents were activated on demand on their owning host only. + assert!(!b.server.is_active("realm.east")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn dormant_zone_hibernates_to_sqlite_and_restores() { + let path = std::env::temp_dir().join(format!( + "dg-world-hibernate-{}-{}.sqlite3", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let store = Arc::new(SqliteZoneStateStore::open(&path).unwrap()); + let mut config = base_config(); + config.host.idle_tick_rate = None; + config.host.dormant_after = Duration::from_millis(50); + config.hibernate_after = Some(Duration::from_millis(100)); + let sink = MemoryFactSink::new(); + let (listener, addr) = listen().await; + let factory = realm_factory(&[], &[]); + let server = GameServer::::new(config, move |z| factory(z)) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()) + .with_state_store(store.clone()); + serve(&server, listener); + let url = format!("ws://{addr}/zones/realm.vault"); + + let mut ana = join_url(&url, &ticket("ana", "realm.vault", "h1"), "") + .await + .unwrap(); + for seq in 1..=3 { + input(&mut ana, seq, CMD_COUNT).await; + } + eventually("three counts", || { + let server = server.clone(); + async move { server.inspect("realm.vault", |h| h.zone().counter).await == Some(3) } + }) + .await; + send(&mut ana.ws, ClientMessage::Leave).await; + eventually("hibernation", || { + let server = server.clone(); + async move { !server.is_active("realm.vault") } + }) + .await; + let saved = store.load("realm.vault").unwrap().expect("snapshot stored"); + assert_eq!(saved.state, 3u32.to_le_bytes()); + // Facts emitted while disposing were still committed. + eventually("dispose fact", || { + let sink = sink.clone(); + async move { + sink.committed() + .iter() + .any(|f| f.key() == "dispose:realm.vault:3") + } + }) + .await; + assert_eq!( + sink.committed() + .iter() + .filter(|f| f.command() == "realm.count") + .count(), + 3 + ); + + // Next activation restores it. + let mut again = join_url(&url, &ticket("ana", "realm.vault", "h2"), "") + .await + .unwrap(); + let counter = loop { + match control(&mut again).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_JOINED => { + break u32::from_le_bytes(payload.try_into().unwrap()) + } + _ => continue, + } + }; + assert_eq!(counter, 3); + drop(store); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fenced_lease_keeps_zone_on_one_host_and_loss_stops_it() { + let clock = distributed::ManualClock::starting_now(); + let leases = InMemoryLeaseStore::with_clock(clock.clone()); + let ownership: Arc = Arc::new(FencedLeaseOwnership::new(leases)); + let config = || { + let mut c = base_config(); + c.ownership_ttl = Duration::from_secs(10); + c.ownership_renew_every = Duration::from_millis(50); + c.activation_timeout = Duration::from_millis(200); + c + }; + // No directory: both hosts would happily serve any zone. + let mut nodes = Vec::new(); + for id in ["A", "B"] { + let (listener, addr) = listen().await; + let f = realm_factory(&[], &[]); + let server = GameServer::::new(config(), move |z| f(z)) + .with_host_id(id) + .with_ownership(ownership.clone()); + serve(&server, listener); + nodes.push((server, addr)); + } + let url = |i: usize| format!("ws://{}/zones/zboss", nodes[i].1); + + let mut ana = join_url(&url(0), &ticket("ana", "zboss", "l1"), "") + .await + .unwrap(); + match join_url(&url(1), &ticket("bo", "zboss", "l2"), "").await { + Err(ServerMessage::Error { code, message }) => { + assert_eq!(code, error::NOT_FOUND); + assert!(message.contains("owned by A#"), "{message}"); + } + other => panic!("second host ran the zone: {:?}", other.map(|c| c.welcome)), + } + + // A stalls past its TTL (e.g. paused); its next renewal fails and the + // zone stops there. + clock.advance(Duration::from_secs(11)); + let kicked = loop { + match control(&mut ana).await { + Some(ServerMessage::Kick { code, .. }) => break code, + Some(_) => continue, + None => panic!("closed without Kick"), + } + }; + assert_eq!(kicked, kick::ZONE_DISPOSED); + let a = nodes[0].0.clone(); + eventually("A stops", || { + let a = a.clone(); + async move { !a.is_active("zboss") } + }) + .await; + // Now B may own it. + let bo = join_url(&url(1), &ticket("bo", "zboss", "l3"), "") + .await + .unwrap(); + assert_eq!(bo.welcome.zone_id, "zboss"); +} + +fn versioned(version: &'static str) -> impl Fn() -> ServerConfig { + move || { + let mut c = base_config(); + c.host.content_version = version.into(); + c + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn world_barrier_freezes_applies_and_resumes_across_hosts() { + let (a, b, _dir) = two_hosts( + versioned("v1"), + &[("realm.a1", "A"), ("realm.a2", "A"), ("realm.b1", "B")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut clients = Vec::new(); + for (i, zone) in ["realm.a1", "realm.a2", "realm.b1"].into_iter().enumerate() { + let host = if zone.ends_with("b1") { &b } else { &a }; + let c = join_url( + &host.addr.zone_url(zone), + &ticket(&format!("p{i}"), zone, &format!("w{i}")), + "v1", + ) + .await + .unwrap(); + clients.push(c); + } + + // Prepare only on A: frozen zones drop (and count) inputs. + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + a.server + .prepare_barrier(1, notice.clone(), Duration::from_secs(2)) + .await + .unwrap(); + assert!(matches!( + next_notice(&mut clients[0]).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + input(&mut clients[0], 1, CMD_COUNT).await; + let server = a.server.clone(); + eventually("dropped input counted", || { + let server = server.clone(); + async move { + server + .inspect("realm.a1", |h| h.inputs_dropped_frozen()) + .await + .unwrap_or(0) + >= 1 + } + }) + .await; + a.server.abort_barrier(1, "test").await; + assert!(matches!( + next_notice(&mut clients[0]).await, + Some(ServerMessage::Resume(n)) if n.version == "v1" + )); + assert_eq!( + a.server.inspect("realm.a1", |h| h.zone().counter).await, + Some(0), + "input sent while frozen was not simulated" + ); + // realm.a2 (also on A) went through the same aborted barrier. + assert!(matches!( + next_notice(&mut clients[1]).await, + Some(ServerMessage::Freeze(_)) + )); + assert!( + matches!(next_notice(&mut clients[1]).await, Some(ServerMessage::Resume(n)) if n.version == "v1") + ); + + // Full rollout through the coordinator: A local, B over admin HTTP. + let applied = Arc::new(Mutex::new(Vec::new())); + let log = applied.clone(); + let coordinator = WorldCoordinator::new(Duration::from_secs(2)) + .participant(Arc::new(a.server.clone())) + .participant(Arc::new(RemoteHost::new(b.addr.clone(), ADMIN))); + let report = coordinator + .rollout("v2", "new loot tables", BarrierMode::Rolling, |v| { + log.lock().unwrap().push(v.to_string()); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(report.version, "v2"); + assert_eq!(*applied.lock().unwrap(), vec!["v2".to_string()]); + for c in &mut clients { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + let resumed = next_notice(c).await; + assert!( + matches!( + &resumed, + Some(ServerMessage::Resume(n)) if n.version == "v2" && n.notes == "new loot tables" + ), + "{resumed:?}" + ); + } + assert_eq!(a.server.content_version(), "v2"); + assert_eq!(b.server.content_version(), "v2"); + // Rolling: v1 clients keep playing; facts now carry v2. + input(&mut clients[2], 2, CMD_COUNT).await; + let sink = b.sink.clone(); + eventually("v2 fact", || { + let sink = sink.clone(); + async move { + sink.committed() + .iter() + .any(|f| f.command() == "realm.count" && f.stamp().content_version == "v2") + } + }) + .await; + // New zones activate on v2: a v1 fresh join is told to reload. + match join_url( + &a.addr.zone_url("realm.a3"), + &ticket("late", "realm.a3", "w9"), + "v1", + ) + .await + { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::VERSION_MISMATCH), + other => panic!("stale join admitted: {:?}", other.map(|c| c.welcome)), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn barrier_aborts_and_resumes_old_version_when_a_zone_never_acks() { + let (a, b, _dir) = two_hosts( + versioned("v1"), + &[("realm.ok", "A"), ("realm.stuck", "B")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ok = join_url( + &a.addr.zone_url("realm.ok"), + &ticket("p1", "realm.ok", "s1"), + "v1", + ) + .await + .unwrap(); + let mut stuck = join_url( + &b.addr.zone_url("realm.stuck"), + &ticket("p2", "realm.stuck", "s2"), + "v1", + ) + .await + .unwrap(); + let coordinator = WorldCoordinator::new(Duration::from_millis(300)) + .participant(Arc::new(a.server.clone())) + .participant(Arc::new(RemoteHost::new(b.addr.clone(), ADMIN))); + let mut applied = false; + let err = coordinator + .rollout("v2", "", BarrierMode::Hard, |_| { + applied = true; + Ok(()) + }) + .await + .unwrap_err(); + assert_eq!(err, RolloutError::NotAcked(vec!["B/realm.stuck".into()])); + assert!(!applied); + assert!(matches!( + next_notice(&mut ok).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + assert!(matches!( + next_notice(&mut ok).await, + Some(ServerMessage::Resume(n)) if n.version == "v1" + )); + assert_eq!(a.server.content_version(), "v1"); + assert_eq!(b.server.content_version(), "v1"); + // The stuck zone never froze, so its client saw nothing; it keeps + // simulating on v1. + input(&mut stuck, 1, CMD_COUNT).await; + let server = b.server.clone(); + eventually("stuck zone still runs", || { + let server = server.clone(); + async move { + server + .inspect("realm.stuck", |h| (h.zone().counter, h.freeze_state())) + .await + == Some((1, FreezeState::Running)) + } + }) + .await; + // A wrong admin secret is refused. + let wrong = WorldCoordinator::new(Duration::from_millis(300)) + .participant(Arc::new(RemoteHost::new(b.addr.clone(), "wrong"))); + assert!(matches!( + wrong + .rollout("v3", "", BarrierMode::Rolling, |_| Ok(())) + .await, + Err(RolloutError::NotAcked(_)) + )); + assert_eq!(b.server.content_version(), "v1"); +} + +#[test] +fn directory_types_are_object_safe() { + let dir: Arc = Arc::new(StaticDirectory::new()); + assert!(dir.locate("x").is_none()); +} diff --git a/distributed_game/tests/world/realm.rs b/distributed_game/tests/world/realm.rs new file mode 100644 index 000000000..0ec711f33 --- /dev/null +++ b/distributed_game/tests/world/realm.rs @@ -0,0 +1,183 @@ +//! Test zone for world-structure tests: handoff, tier-up events, +//! hibernation, gates and freeze readiness. + +#![allow(dead_code)] + +use distributed_game::*; + +/// Input commands (first payload byte). +pub const CMD_HANDOFF: u8 = 1; +pub const CMD_BOSS: u8 = 2; +pub const CMD_COUNT: u8 = 3; + +/// Event type ids sent to players. +pub const EV_JOINED: u32 = 1; +pub const EV_ARRIVED: u32 = 2; + +#[derive(Debug, Clone, Default)] +pub struct RealmConfig { + pub gate: bool, + pub freeze_ready: bool, + pub neighbour: Option, + pub reject_all: bool, +} + +impl RealmConfig { + pub fn new() -> Self { + Self { + freeze_ready: true, + ..Self::default() + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Arrival { + pub principal: String, + pub from: String, + pub carried: Vec, +} + +pub struct Realm { + pub cfg: RealmConfig, + pub counter: u32, + pub restored_from: Option, + pub arrivals: Vec, + pub child_events: Vec, + pub left: Vec<(PlayerId, LeaveReason)>, + pub versions: Vec<(String, String)>, + pub handoff_errors: Vec, +} + +impl Zone for Realm { + type Config = RealmConfig; + type Input = u8; + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "realm").field("counter", FieldType::U32)) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, cfg: RealmConfig) -> Self { + Self { + cfg, + counter: 0, + restored_from: None, + arrivals: Vec::new(), + child_events: Vec::new(), + left: Vec::new(), + versions: Vec::new(), + handoff_errors: Vec::new(), + } + } + + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, _req: &JoinRequest<'_>) -> Admission { + if self.cfg.reject_all { + Admission::Reject("closed for repairs".into()) + } else { + Admission::Admit + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send_event(player, EV_JOINED, self.counter.to_le_bytes().to_vec()); + } + + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + from_zone: &str, + carried: Vec, + ) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let mut payload = carried.clone(); + payload.extend_from_slice(b"|"); + payload.extend_from_slice(from_zone.as_bytes()); + ctx.send_event(player, EV_ARRIVED, payload); + self.arrivals.push(Arrival { + principal, + from: from_zone.to_string(), + carried, + }); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, reason: LeaveReason) { + self.left.push((player, reason)); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| (p.id, p.principal.clone())).collect(); + for (player, principal) in players { + for input in ctx.take_inputs(player, ConsumePolicy::Drain) { + match input.input { + CMD_HANDOFF => { + let Some(target) = self.cfg.neighbour.clone() else { + continue; + }; + let carried = format!("{principal}:gold={}", self.counter).into_bytes(); + if let Err(e) = ctx.handoff(player, &target, carried) { + self.handoff_errors.push(e); + } + } + CMD_BOSS => { + let zone = ctx.zone_id().to_string(); + ctx.emit_upward("boss_defeated", zone.into_bytes(), ChildEvent::TO_ROOT); + } + CMD_COUNT => { + self.counter += 1; + let key = format!("count:{}:{}", ctx.zone_id(), self.counter); + let _ = ctx.emit_fact_for( + player, + Fact::new(key, "realm.count", serde_json::json!({"n": self.counter})), + ); + } + _ => {} + } + } + } + } + + fn replicate(&self, out: &mut WorldView) { + out.push(EntityState::new(1, 1, 0.0, 0.0, vec![FieldValue::U(self.counter)]).global()); + } + + fn on_dispose(&mut self, ctx: &mut Ctx<'_, Self>) { + let key = format!("dispose:{}:{}", ctx.zone_id(), self.counter); + let _ = ctx.emit_fact(Fact::new(key, "realm.disposed", serde_json::json!({}))); + } + + fn hibernate(&self) -> Option> { + Some(self.counter.to_le_bytes().to_vec()) + } + + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], saved_version: &str) { + if let Ok(bytes) = <[u8; 4]>::try_from(state) { + self.counter = u32::from_le_bytes(bytes); + self.restored_from = Some(saved_version.to_string()); + } + } + + fn on_child_event(&mut self, _ctx: &mut Ctx<'_, Self>, event: &ChildEvent) { + self.child_events.push(event.clone()); + } + + fn is_gate(&self) -> bool { + self.cfg.gate + } + + fn freeze_ready(&self) -> bool { + self.cfg.freeze_ready + } + + fn on_content_version_changed(&mut self, _ctx: &mut Ctx<'_, Self>, from: &str, to: &str) { + self.versions.push((from.to_string(), to.to_string())); + } +} diff --git a/distributed_game/tests/world_host/main.rs b/distributed_game/tests/world_host/main.rs new file mode 100644 index 000000000..f3b03d3a4 --- /dev/null +++ b/distributed_game/tests/world_host/main.rs @@ -0,0 +1,366 @@ +//! Host-level world features without a transport: safe-room version +//! policy, handoff issuance, freeze readiness, tier-up forwarding, +//! hibernate/restore hooks and version stamping. + +#[path = "../world/realm.rs"] +mod realm; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed_game::protocol::{error, kick, Notice}; +use distributed_game::*; +use realm::*; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + } +} + +fn host(zone: &str, config: HostConfig, clock: &ManualClock, cfg: RealmConfig) -> ZoneHost { + ZoneHost::new(zone, config, Arc::new(clock.clone()), cfg) +} + +fn messages(out: &[Outbound], client: ClientId) -> Vec { + out.iter() + .filter_map(|o| match o { + Outbound::Frame { client: c, frame } if *c == client => { + ServerMessage::decode(frame, &()).ok() + } + _ => None, + }) + .collect() +} + +fn closed(out: &[Outbound], client: ClientId) -> bool { + out.iter() + .any(|o| matches!(o, Outbound::Close { client: c } if *c == client)) +} + +fn safe_room(version: &str) -> HostConfig { + HostConfig { + content_version: version.into(), + stale_policy: StalePolicy::SafeRoom { roam: false }, + ..HostConfig::default() + } +} + +fn transfer(principal: &str, from: &str, to: &str) -> Transfer { + Transfer { + claims: claims(principal, to), + source_zone: from.into(), + issuer: "h1".into(), + generation: 1, + carried: b"gold=7".to_vec(), + } +} + +#[test] +fn safe_room_policy_admits_stale_clients_only_where_allowed() { + let clock = ManualClock::new(); + let mut field = host("realm.field", safe_room("v2"), &clock, RealmConfig::new()); + let mut gate = host( + "realm.inn", + safe_room("v2"), + &clock, + RealmConfig { + gate: true, + ..RealmConfig::new() + }, + ); + + // Fresh joins with stale content are told to reload. + let err = field + .join(&claims("ana", "realm.field"), 0, "v1") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + assert!(err.message.contains("reload")); + // Stale players may not roam into non-gate zones... + let err = field + .join_transfer(&transfer("ana", "realm.inn", "realm.field"), 0, "v1") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + // ...but up-to-date ones may. + field + .join_transfer(&transfer("bo", "realm.inn", "realm.field"), 0, "v2") + .unwrap(); + + // Entering a gate: admitted, then Kick(RELOAD), kept for reconnect. + let joined = gate + .join_transfer(&transfer("ana", "realm.field", "realm.inn"), 0, "v1") + .unwrap(); + let out = gate.drain_outbound(); + let msgs = messages(&out, joined.client); + let ServerMessage::Welcome(welcome) = &msgs[0] else { + panic!("welcome first: {msgs:?}") + }; + assert!(matches!( + msgs.last(), + Some(ServerMessage::Kick { code, .. }) if *code == kick::RELOAD + )); + assert!(closed(&out, joined.client)); + assert_eq!(gate.player_count(), 1, "kept in the reconnect grace window"); + assert_eq!(gate.zone().arrivals.len(), 1); + + // Reconnecting still stale at a gate -> reload again; reloaded -> in. + let again = gate + .reconnect_with_version(&welcome.reconnect_token, 0, "v1") + .unwrap(); + let out = gate.drain_outbound(); + let msgs = messages(&out, again.client); + let ServerMessage::Welcome(welcome) = &msgs[0] else { + panic!() + }; + assert!(closed(&out, again.client)); + let ok = gate + .reconnect_with_version(&welcome.reconnect_token, 0, "v2") + .unwrap(); + let out = gate.drain_outbound(); + assert!(!closed(&out, ok.client)); + let Viewer::Player(player) = ok.viewer else { + panic!() + }; + assert_eq!(gate.player_content_version(player), Some("v2")); +} + +#[test] +fn strict_policy_rejects_stale_reconnects_and_hard_mode_reloads() { + let clock = ManualClock::new(); + let config = HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }; + let mut h = host("z", config, &clock, RealmConfig::new()); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + let out = h.drain_outbound(); + let ServerMessage::Welcome(welcome) = &messages(&out, joined.client)[0] else { + panic!() + }; + h.disconnect(joined.client, false); + let err = h + .reconnect_with_version(&welcome.reconnect_token, 0, "v0") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + let joined = h + .reconnect_with_version(&welcome.reconnect_token, 0, "v1") + .unwrap(); + h.drain_outbound(); + + // Barrier commit to v2 in hard mode: the v1 client is reloaded. + h.set_content_version("v2"); + assert_eq!(h.zone().versions, vec![("v1".into(), "v2".into())]); + assert_eq!(h.reload_stale_players(), 1); + let out = h.drain_outbound(); + assert!(messages(&out, joined.client) + .iter() + .any(|m| matches!(m, ServerMessage::Kick { code, .. } if *code == kick::RELOAD))); + assert_eq!(h.player_count(), 1); +} + +#[test] +fn handoff_issues_ticket_and_removes_player_first() { + let clock = ManualClock::new(); + let requests: Arc>> = Arc::default(); + let seen = requests.clone(); + let mut h = host( + "realm.east", + HostConfig::default(), + &clock, + RealmConfig { + neighbour: Some("realm.west".into()), + ..RealmConfig::new() + }, + ) + .with_transfer_issuer(move |r: &HandoffRequest| { + seen.lock().unwrap().push(r.clone()); + Some("signed-transfer".into()) + }); + let joined = h.join(&claims("ana", "realm.east"), 0, "").unwrap(); + h.drain_outbound(); + h.push_input(joined.client, 1, 0, &[CMD_HANDOFF]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let out = h.drain_outbound(); + let msgs = messages(&out, joined.client); + assert!(msgs.contains(&ServerMessage::Handoff { + target_zone: "realm.west".into(), + transfer_ticket: "signed-transfer".into(), + })); + assert!(closed(&out, joined.client)); + assert_eq!(h.player_count(), 0); + assert_eq!(h.zone().left[0].1, LeaveReason::Handoff); + let r = &requests.lock().unwrap()[0]; + assert_eq!( + ( + r.principal.as_str(), + r.source_zone.as_str(), + r.target_zone.as_str() + ), + ("ana", "realm.east", "realm.west") + ); + assert_eq!(r.carried, b"ana:gold=0"); + + // Without an issuer the zone gets an error and the player stays. + let mut lone = host( + "solo", + HostConfig::default(), + &clock, + RealmConfig { + neighbour: Some("x".into()), + ..RealmConfig::new() + }, + ); + let joined = lone.join(&claims("bo", "solo"), 0, "").unwrap(); + lone.push_input(joined.client, 1, 0, &[CMD_HANDOFF]); + clock.advance(Duration::from_millis(40)); + lone.advance(); + assert_eq!(lone.zone().handoff_errors, vec![HandoffError::NoIssuer]); + assert_eq!(lone.player_count(), 1); +} + +#[test] +fn freeze_waits_for_readiness_and_counts_dropped_inputs() { + let clock = ManualClock::new(); + let mut h = host( + "z", + HostConfig::default(), + &clock, + RealmConfig { + freeze_ready: false, + ..RealmConfig::new() + }, + ); + let joined = h.join(&claims("ana", "z"), 0, "").unwrap(); + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + assert_eq!(h.request_freeze(notice.clone()), FreezeState::Freezing); + clock.advance(Duration::from_millis(100)); + assert!(h.advance().ticks > 0, "still ticking while not ready"); + h.zone_mut().cfg.freeze_ready = true; + clock.advance(Duration::from_millis(100)); + h.advance(); + assert_eq!(h.freeze_state(), FreezeState::Frozen); + let out = h.drain_outbound(); + assert!(messages(&out, joined.client).contains(&ServerMessage::Freeze(notice))); + let before = h.tick(); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + h.push_input(joined.client, 2, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(100)); + assert_eq!(h.advance().ticks, 0); + assert_eq!(h.tick(), before); + assert_eq!(h.inputs_dropped_frozen(), 2); + + let resume = Notice { + reason: "content_update_aborted".into(), + version: String::new(), + notes: String::new(), + }; + h.cancel_freeze(resume.clone()); + assert_eq!(h.freeze_state(), FreezeState::Running); + assert!(messages(&h.drain_outbound(), joined.client).contains(&ServerMessage::Resume(resume))); +} + +#[test] +fn child_events_are_delivered_later_and_forwarded_up() { + let clock = ManualClock::new(); + let mut h = host( + "realm.east", + HostConfig::default(), + &clock, + RealmConfig::new(), + ); + let event = ChildEvent { + origin_zone: "realm.east.keep".into(), + from_zone: "realm.east.keep".into(), + kind: "boss_defeated".into(), + payload: b"hydra".to_vec(), + origin_tick: 9, + content_version: String::new(), + levels: 3, + }; + h.deliver_child_event(event.clone()); + assert!(h.zone().child_events.is_empty(), "not synchronous"); + clock.advance(Duration::from_millis(40)); + h.advance(); + assert_eq!(h.zone().child_events, vec![event.clone()]); + let up = h.drain_upward(); + assert_eq!(up.len(), 1); + assert_eq!(up[0].from_zone, "realm.east"); + assert_eq!(up[0].origin_zone, "realm.east.keep"); + assert_eq!(up[0].levels, 2); + + // A zone's own upward event. + let joined = h.join(&claims("ana", "realm.east"), 0, "").unwrap(); + h.push_input(joined.client, 1, 0, &[CMD_BOSS]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let up = h.drain_upward(); + assert_eq!(up[0].origin_zone, "realm.east"); + assert_eq!(up[0].levels, ChildEvent::TO_ROOT); +} + +#[test] +fn hibernate_restore_and_version_stamps() { + let clock = ManualClock::new(); + let (queue, _feed) = fact_channel(16, RetryPolicy::default()); + let mut h = host( + "z", + HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }, + &clock, + RealmConfig::new(), + ) + .with_facts(queue); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let saved = h.hibernate_state().unwrap(); + + let mut restored = host("z", HostConfig::default(), &clock, RealmConfig::new()); + restored.restore(&saved, "v1"); + assert_eq!(restored.zone().counter, 1); + assert_eq!(restored.zone().restored_from.as_deref(), Some("v1")); + + // Facts emitted after a version switch carry the new version. + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let sink = MemoryFactSink::new(); + let mut h = host( + "z", + HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }, + &clock, + RealmConfig::new(), + ) + .with_facts(queue); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + h.set_content_version("v2"); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + h.advance(); + drop(h); + futures_executor(feed.run(sink.clone(), |_| async {})); + let committed = sink.committed(); + assert_eq!(committed[0].stamp().content_version, "v2"); +} + +/// Minimal executor for the fact feed (no runtime needed: the memory sink +/// never pends). +fn futures_executor(f: impl std::future::Future) { + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + while f.as_mut().poll(&mut cx).is_pending() {} +} From 87b914e7e18ee0587bd620c709155737ea84f273 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:23:54 -0500 Subject: [PATCH 134/484] docs(game): document world structure, handoff and barrier PROTOCOL.md: Redirect message, Kick RELOAD, transfer tickets and the client handoff/return procedure, content-version policies. README: world features, hibernation fact policy, saga sketch for durable player relocation, admin routes. Refs [[tasks/gr-p5-world-structure]] [[tasks/gr-p7-freeze-barrier]] --- distributed_game/PROTOCOL.md | 100 ++++++++++++++++++++++++++++++++--- distributed_game/README.md | 82 ++++++++++++++++++++++++++-- 2 files changed, 170 insertions(+), 12 deletions(-) diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md index 7a490bca2..537eacde2 100644 --- a/distributed_game/PROTOCOL.md +++ b/distributed_game/PROTOCOL.md @@ -15,7 +15,12 @@ Key words MUST / MUST NOT / SHOULD / MAY are used as in RFC 2119. ### 1.1 WebSocket (normative transport) - Endpoint: `GET /zones/{zone_id}` upgraded to a WebSocket. The path - selects the zone; the zone in the admission ticket MUST equal it. + selects the zone; the zone in the admission ticket MUST equal it + (transfer tickets: §8.1). +- A host that does not own the zone answers the Hello with + `Redirect(zone_id, url)` and closes; the client MUST reconnect to `url` + and send the **same** Hello (the ticket was not consumed). Clients + SHOULD follow at most 3 redirects in a row. - Every protocol message is exactly **one binary WebSocket message**. There is no additional length prefix inside a WebSocket message. - Text messages are a protocol violation: the server replies @@ -192,6 +197,7 @@ replication priorities are not transmitted. | `0x86` | S→C | Handoff | | `0x87` | S→C | Kick | | `0x88` | S→C | Error | +| `0x89` | S→C | Redirect | Unknown type bytes and trailing bytes after a complete message are decode errors. @@ -251,6 +257,7 @@ Resume := 0x85, string reason, string version, string notes Handoff := 0x86, string target_zone, string transfer_ticket Kick := 0x87, varuint code, string message Error := 0x88, varuint code, string message +Redirect := 0x89, string zone_id, string url ``` - **Welcome**: `role` `0` = player, `1` = observer. `session_id` is stable @@ -262,14 +269,31 @@ Error := 0x88, varuint code, string message are queued when emitted and may arrive before the Delta of the tick that produced them. - **Pong**: echoes `client_time`; `server_time` is the server clock. -- **Freeze**: the zone stops simulating; inputs are rejected until - **Resume**. Used for content rollouts (`version`) and maintenance. +- **Freeze**: the zone stops simulating; inputs are dropped (and counted) + until **Resume**. For a content rollout `reason` is `content_update` and + `version` is the **target** content version. Clients SHOULD stop + sending inputs and show `notes`. +- **Resume**: simulation continues. `version` is the content version the + zone now runs: the new one after a committed rollout + (`reason = content_update`), the old one after an aborted rollout + (`reason = content_update_aborted`). Events and facts after Resume are + produced by `version`. A client whose own content differs MAY keep + playing until told to reload (§8.2). - **Handoff**: the player has been removed from this zone; connect to - `target_zone` and present `transfer_ticket` as the Hello ticket. The - server closes the socket. + `/zones/{target_zone}` (on the current host; follow any Redirect) and + present `transfer_ticket` as the Hello `ticket` (empty + `reconnect_token`). The server closes the socket. See §8.1. - **Kick**: the session is over; the server closes the socket. Codes: `1` BY_ZONE, `2` REPLACED (same principal connected again), - `3` SHUTDOWN, `4` RATE_LIMITED, `5` ZONE_DISPOSED, `6` SLOW_CONSUMER. + `3` SHUTDOWN, `4` RATE_LIMITED, `5` ZONE_DISPOSED, `6` SLOW_CONSUMER, + `7` RELOAD. **RELOAD** is the exception to "session over": the player + is kept for the reconnect grace window; the client MUST reload its + content to the zone's current version (`Resume.version` / Welcome + `content_version`) and reconnect with the token from its last Welcome + and the new `content_version` in Hello. +- **Redirect**: this host does not own `zone_id`; reconnect to `url` (a + full `ws://` / `wss://` URL including `/zones/{zone_id}`) with the same + Hello. The server closes the socket. - **Error**: codes `1` BAD_MESSAGE, `2` UNAUTHORIZED, `3` REJECTED, `4` ZONE_FULL, `5` VERSION_MISMATCH, `6` RATE_LIMITED, `7` NOT_FOUND, `8` RECONNECT_FAILED. Errors during the handshake are followed by close; @@ -306,6 +330,11 @@ schema of `fixtures/messages.json`): 01 78 06 00000000 00008042 0c "x" quant_f32 min 0 max 64 bits 12 ``` +Redirect (`fixtures/messages.json` → `redirect`): +`89 0a 7265616c6d2e77657374 23 77733a2f2f31302e302e302e323a323536372f7a6f6e65732f7265616c6d2e77657374` += zone `"realm.west"`, url `"ws://10.0.0.2:2567/zones/realm.west"`. +Kick RELOAD (`kick_reload`): `87 07 13 "content c2 required"`. + ## 7. Delta ### 7.1 Encoding @@ -414,6 +443,55 @@ unpadded base64url). Any HS256 JWT library can mint one. inputs. - Failures produce `Error(UNAUTHORIZED)` and close. +### 8.1 Transfer tickets and handoff + +A zone hands a player to another zone (possibly on another host) with a +**transfer ticket**: the same HS256 JWT format, minted by the source host, +with extra claims — `kind: "transfer"`, `src` (source zone), `iss` +(issuing host id), `gen` (source zone ownership token), `carry` +(base64url carried game state, <= 16 KiB). Clients treat it as opaque. + +Procedure (client side): + +1. Receive `Handoff(target_zone, transfer_ticket)`; the socket closes. + The player is already removed from the source zone. +2. Connect to `/zones/{target_zone}`; follow `Redirect` if any; send + Hello with `ticket = transfer_ticket`. +3. Welcome → in the target zone (the zone received the carried state). +4. If the target refuses (any `Error` before Welcome, or no Welcome + within ~10 s): connect to `/zones/{source_zone}` (the zone the client + just left) and send the **same** Hello; the source re-admits the player + with its carried state. If that also fails, fall back to the lobby for + a fresh admission ticket. + +Server guarantees: a transfer ticket is single use across hosts — the +target reserves it with the issuing host before admitting, confirms on +success and releases on refusal; the source accepts it back only while it +is neither reserved nor used. In doubt (an unconfirmed reservation that +lapsed) the ticket counts as used: a player is never in two zones. +Tickets expire after 30 s by default. + +### 8.2 Content versions (barrier and safe rooms) + +A world runs one content version. A rollout freezes every zone +(`Freeze{version: target}`), applies the new content, then resumes every +zone (`Resume{version: target}`); if any zone fails to freeze in time +all zones resume on the old version (`Resume{reason: +content_update_aborted}`). Servers pin a version per policy: + +- **Strict** (default): Hello `content_version` MUST equal the server's + for joins and reconnects; otherwise `Error(VERSION_MISMATCH)`. +- **SafeRoom** ("keep playing until a safe room"): after a *rolling* + rollout, clients on the old version keep playing in the zone they are + in (reconnects allowed). They may only be handed off into *gate* zones + (safe rooms) unless the server allows roaming; on entering a gate they + get Welcome and then `Kick(RELOAD)`. A fresh join with an old version + gets `Error(VERSION_MISMATCH)` (message ends with `reload`). +- A *hard* rollout sends `Kick(RELOAD)` to every stale client right after + Resume. + +### 8.3 Reconnect + Reconnect: after an abrupt disconnect the player stays in the zone for the reconnect grace window (default 15 s). A Hello with the last Welcome's `reconnect_token` rebinds the same player (same `session_id`, new token, @@ -448,5 +526,13 @@ JSON conventions in `decoded`: ## 10. Versioning `protocol_version` changes on any incompatible wire change. Message type -bytes `0x05..0x7f` and `0x89..0xff`, and field type tags `10..255`, are +bytes `0x05..0x7f` and `0x8a..0xff`, and field type tags `10..255`, are reserved for future versions. + +Additive changes within version 1 (clients SHOULD ignore unknown kick and +error codes and treat them as "session over" / "request failed"): + +- `0x89 Redirect` (server → client). +- Kick code `7` RELOAD. +- Transfer tickets (§8.1) and content-version policies (§8.2); `Handoff` + and `Freeze`/`Resume` encodings are unchanged. diff --git a/distributed_game/README.md b/distributed_game/README.md index e0ab068f7..38dbaa494 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -15,7 +15,9 @@ Physics is out of scope: bring your own and step it in `on_tick`. | *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | | `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | | `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | -| `net` | `net::GameServer` (axum WebSocket), HMAC tickets | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `net` | `net::GameServer` (axum WebSocket), HMAC tickets, handoff, admin peer routes, `WorldCoordinator` | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `lease` | `world::FencedLeaseOwnership` over `distributed::lease` | `distributed` | +| `sqlite` | `world::SqliteZoneStateStore` (hibernation snapshots) | `rusqlite` (bundled) | ## Minimal zone @@ -99,6 +101,80 @@ on a later tick. `cell::CellFactSink` dispatches into an `AggregateCell` with a deterministic command id per fact key, so retries replay instead of double-crediting. +## World structure + +`world` (no feature needed for the traits and in-memory impls): + +| Piece | Purpose | +|---|---| +| `ZoneDirectory` (`StaticDirectory`, `HashRing`) | zone → owning `HostAddr`. `HashRing` uses virtual nodes; adding/removing one of N hosts moves ~1/N of the zones. A Hello for a zone owned elsewhere gets `Redirect(zone, url)`. | +| `ZoneOwnership` (`LocalOwnership`, `FencedLeaseOwnership`) | every activation acquires a fenced claim (`host#activation`) and renews it; a failed renewal disposes the zone **without** saving. Two hosts never run the same zone. | +| `ZoneStateStore` (`MemoryZoneStateStore`, `SqliteZoneStateStore`) | hibernation snapshots, written under the claim's fencing token (stale writers get `StateError::Stale`). | +| `ZoneTopology` (`DottedTopology` default: `eldoria.port.docks` → `eldoria.port` → `eldoria`) | parent links for tier-up events. | + +**Activate on demand / hibernate.** `GameServer` creates a zone on first +join (or tier-up event). With `ServerConfig::hibernate_after = Some(d)` a +zone that stays Dormant for `d` (no clients, no in-flight facts, not +frozen) is hibernated: unregistered atomically (later joins start a new +activation, which waits for this one's claim), `Zone::hibernate()` is +stored, `on_dispose` runs, the claim is released. The next activation +calls `Zone::on_restore`. + +*Facts on dispose:* a zone only becomes Dormant with zero unsettled +facts, so hibernation never strands a settlement. Facts emitted during +disposal (e.g. in `on_dispose`) are still committed: the fact worker +drains its queue after the zone drops it, and the zone task waits up to +`settle_timeout` for it. We chose "settle, then dispose" over a durable +fact outbox because the zone-side queue is already bounded and +idempotent; a crash-durable outbox belongs to the sink (e.g. the cell +adapter commits the fact atomically with its own outbox row). + +**Handoff.** In a hook: `ctx.handoff(player, "realm.west", carried_bytes)?`. +The host signs a transfer ticket (principal, source, target, issuer host, +ownership generation, carried state, nonce, 30 s expiry), removes the +player (`LeaveReason::Handoff`) and sends `Handoff(target, ticket)`. The +target reserves the ticket with the issuing host (locally or via +`/admin/transfer`), admits it with `Zone::on_handoff_join(player, from, +carried)` and confirms; a refused transfer is released and the client may +present the same ticket back to the source (PROTOCOL.md §8.1). The +realtime path never waits on storage. When the player's **durable** +record must move too (home zone, inventory cell), emit a fact from the +handoff hook and let a `distributed::saga` drive it, off the tick: + +```rust,ignore +// zone hook: non-blocking +ctx.emit_fact_for(player, Fact::new(format!("move:{nonce}"), "player.relocate", + json!({"from": from, "to": to})))?; +// fact sink → SagaRunner::<_, Relocate>::start(nonce, data): +// step "detach" → source cell (compensate: "reattach") +// step "attach" → target cell (compensate: "detach_again") +// timeouts compensate; the game keeps playing on carried state meanwhile. +``` + +**Tier-up events.** `ctx.emit_upward("boss_defeated", payload, +ChildEvent::TO_ROOT)`; the server routes it to the parent (activating it, +on its owning host via `/admin/child-event`), whose host delivers +`Zone::on_child_event` on a later tick and forwards it further up while +`levels` remain. + +**Content barrier.** `net::WorldCoordinator::rollout(version, notes, mode, +apply)` over `GameServer`s and `RemoteHost`s (admin HTTP, shared secret): +freeze all zones (`Freeze{version}`; `Zone::freeze_ready` may delay), +wait for every ack within the timeout, `apply(version)`, then commit +(`Resume{version, notes}`; facts/`ctx.stamp()` carry the new version). +A missing ack or failed `apply` aborts: everyone resumes on the old +version. Inputs while frozen are dropped and counted +(`ZoneHost::inputs_dropped_frozen`). `HostConfig::stale_policy = +StalePolicy::SafeRoom { roam }` lets old clients keep playing after a +`BarrierMode::Rolling` commit until they reach a gate zone +(`Zone::is_gate`), where they get `Kick(RELOAD)` and reconnect with their +token after reloading; `BarrierMode::Hard` reloads every stale client at +once. + +Admin routes (enabled by `ServerConfig::admin_secret`, header +`x-game-admin-secret`): `POST /admin/transfer`, `/admin/child-event`, +`/admin/barrier/{prepare,commit,abort}` — see `net::world`. + ## Protocol See [`PROTOCOL.md`](PROTOCOL.md) — binary, little-endian, varints, one @@ -115,10 +191,6 @@ UPDATE_GOLDEN=1 cargo test -p distributed_game --test golden # accept wire cha ## Extension seams (later phases) -- Hibernation / directory: `Tier::Dormant`, `ZoneHost::dispose`, zone - factory in `GameServer`. -- Handoff saga: `ZoneHost::handoff` + `LeaveReason::Handoff` + Handoff message. -- Content barrier: `ZoneHost::freeze` / `resume`. - Metrics: `AdvanceReport`, `replication::DeltaStats`, `PushOutcome`. - Rewind/lag compensation: `SequencedInput::client_tick`, deterministic `ZoneRng` and `ManualClock`. From 5f83e5fb255c81485c31c08597964fd548fef267 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:24:48 -0500 Subject: [PATCH 135/484] test(game): add echo_arena example and opt-in JS e2e test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tiny `net` WebSocket zone server example that the JS suite spawns via cargo when DISTRIBUTED_GAME_E2E=1. The test mints HS256 tickets per PROTOCOL.md §8, joins, predicts and reconciles against real acks, checks clock sync, resumes after an abrupt drop with the reconnect token and opens an observer connection to a neighbouring zone. Refs [[tasks/gr-p4-client-sdk]] --- distributed_game/Cargo.toml | 5 + distributed_game/examples/echo_arena.rs | 126 ++++++++++++++++++++ js/tests/game-e2e.test.mjs | 149 ++++++++++++++++++++++++ 3 files changed, 280 insertions(+) create mode 100644 distributed_game/examples/echo_arena.rs create mode 100644 js/tests/game-e2e.test.mjs diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 0519169df..14fe3405b 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -43,3 +43,8 @@ required-features = ["net"] name = "cell_sink" path = "tests/cell_sink/main.rs" required-features = ["cell", "runtime"] + +[[example]] +name = "echo_arena" +path = "examples/echo_arena.rs" +required-features = ["net"] diff --git a/distributed_game/examples/echo_arena.rs b/distributed_game/examples/echo_arena.rs new file mode 100644 index 000000000..3da2662d9 --- /dev/null +++ b/distributed_game/examples/echo_arena.rs @@ -0,0 +1,126 @@ +//! Tiny WebSocket zone server for client end-to-end tests (feature `net`). +//! +//! Every player owns one avatar moved by 2-byte inputs `[dx, dy]` (i8, +//! clamped to -1..=1) at 10 units/s. On join the player receives Event type +//! 1 carrying its avatar entity id (u32 LE) so a client can bind prediction. +//! Zones `arena-*` are created on demand; tickets are HS256 with the secret +//! from `DISTRIBUTED_GAME_SECRET` (default `dev-secret`). +//! +//! Prints `LISTENING ws://127.0.0.1:` once bound, then serves until +//! stdin closes (so a parent test process can stop it by exiting). +//! +//! ```sh +//! cargo run -p distributed_game --features net --example echo_arena +//! ``` + +use std::collections::BTreeMap; +use std::io::{BufRead, Write}; + +use distributed_game::net::{GameServer, ServerConfig, TicketKey}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + PlayerId, View, WorldView, Zone, +}; + +const AVATAR: u16 = 1; +const SPEED: f32 = 10.0; + +struct EchoArena { + avatars: BTreeMap, +} + +impl Zone for EchoArena { + type Config = (); + type Input = (i8, i8); + type Timer = (); + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -500.0, + max: 500.0, + bits: 20, + }; + EntitySchema::new().kind( + KindDef::new(AVATAR, "avatar") + .field("x", pos) + .field("y", pos) + .field("seq_hint", FieldType::U32), + ) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self { + avatars: BTreeMap::new(), + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let entity = 100 + player.0; + self.avatars.insert(player, (entity, 0.0, 0.0)); + ctx.set_view(player, View::new(0.0, 0.0, 1000.0)); + ctx.send_event(player, 1, entity.to_le_bytes().to_vec()); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.avatars.remove(&player); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option<(i8, i8)> { + match payload { + [dx, dy] => Some(((*dx as i8).clamp(-1, 1), (*dy as i8).clamp(-1, 1))), + _ => None, + } + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + let players: Vec = self.avatars.keys().copied().collect(); + for player in players { + let inputs = ctx.take_inputs(player, ConsumePolicy::Drain); + if let Some(avatar) = self.avatars.get_mut(&player) { + for input in inputs { + avatar.1 += f32::from(input.input.0) * SPEED * dt; + avatar.2 += f32::from(input.input.1) * SPEED * dt; + } + } + } + } + + fn replicate(&self, out: &mut WorldView) { + for (entity, x, y) in self.avatars.values() { + out.push(EntityState::new( + *entity, + AVATAR, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::U(0)], + )); + } + } +} + +#[tokio::main] +async fn main() -> std::io::Result<()> { + let secret = std::env::var("DISTRIBUTED_GAME_SECRET").unwrap_or_else(|_| "dev-secret".into()); + let mut config = ServerConfig::new(TicketKey::new(secret)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + let server = + GameServer::::new(config, |zone| zone.starts_with("arena-").then_some(())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let addr = listener.local_addr()?; + println!("LISTENING ws://{addr}"); + std::io::stdout().flush()?; + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + std::thread::spawn(move || { + // Stop when the parent closes our stdin (or sends a line). + let mut line = String::new(); + let _ = std::io::stdin().lock().read_line(&mut line); + let _ = stop_tx.send(()); + }); + server + .serve(listener, async move { + let _ = stop_rx.await; + }) + .await +} diff --git a/js/tests/game-e2e.test.mjs b/js/tests/game-e2e.test.mjs new file mode 100644 index 000000000..06c159856 --- /dev/null +++ b/js/tests/game-e2e.test.mjs @@ -0,0 +1,149 @@ +/** + * End-to-end against the real Rust zone server + * (`distributed_game/examples/echo_arena.rs`, feature `net`). + * + * Opt-in: `DISTRIBUTED_GAME_E2E=1 npm test` (spawns `cargo run`, which may + * compile on first use). Skipped otherwise. + */ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { createHmac, randomUUID } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +import { GameClient } from '@hops-ops/distributed/game'; + +const ENABLED = process.env.DISTRIBUTED_GAME_E2E === '1'; +const SECRET = 'e2e-secret'; +const REPO = fileURLToPath(new URL('../../', import.meta.url)); + +const b64url = (value) => Buffer.from(value).toString('base64url'); + +/** HS256 admission ticket exactly as PROTOCOL.md §8 specifies. */ +function mintTicket(principal, zone, role = 'player') { + const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })); + const claims = b64url( + JSON.stringify({ + sub: principal, + zone, + exp: Math.floor(Date.now() / 1000) + 300, + nonce: randomUUID(), + role + }) + ); + const signature = createHmac('sha256', SECRET).update(`${header}.${claims}`).digest('base64url'); + return `${header}.${claims}.${signature}`; +} + +function startServer() { + const child = spawn( + 'cargo', + ['run', '-q', '-p', 'distributed_game', '--features', 'net', '--example', 'echo_arena'], + { cwd: REPO, env: { ...process.env, DISTRIBUTED_GAME_SECRET: SECRET }, stdio: ['pipe', 'pipe', 'inherit'] } + ); + const url = new Promise((resolve, reject) => { + let buffered = ''; + child.stdout.on('data', (chunk) => { + buffered += chunk; + const match = /LISTENING (ws:\/\/\S+)/.exec(buffered); + if (match) resolve(match[1]); + }); + child.on('exit', (code) => reject(new Error(`echo_arena exited with ${code}`))); + }); + return { child, url }; +} + +async function until(predicate, timeoutMs = 10_000, what = 'condition') { + const start = Date.now(); + while (!predicate()) { + if (Date.now() - start > timeoutMs) throw new Error(`timed out waiting for ${what}`); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +test('game client against the real Rust zone server', { skip: !ENABLED, timeout: 600_000 }, async () => { + const server = startServer(); + try { + const base = await server.url; + const DT = 1000 / 30; // server applies each input over one 30 Hz tick + const client = new GameClient({ + url: (zone) => `${base}/zones/${zone}`, + ticket: ({ zoneId, role }) => mintTicket('alice', zoneId, role), + pingIntervalMs: 200, + inputDtMs: DT, + prediction: { + encodeInput: ({ dx, dy }) => new Uint8Array([dx & 0xff, dy & 0xff]), + predict: (s, i, dt) => ({ + x: s.x + (i.dx * 10 * dt) / 1000, + y: s.y + (i.dy * 10 * dt) / 1000 + }), + corrections: { avatar: { x: { mode: 'snap' }, y: { mode: 'snap' } } } + } + }); + let controlled; + client.on('event', (_zone, event) => { + if (event.typeId === 1) { + controlled = new DataView(event.payload.buffer, event.payload.byteOffset).getUint32(0, true); + client.setControlledEntity(controlled); + } + }); + const welcome = await client.connect('arena-1'); + assert.equal(welcome.role, 'player'); + assert.equal(welcome.schema.kinds[0].name, 'avatar'); + await until(() => controlled !== undefined && client.predictor.active, 10_000, 'avatar'); + + // Prediction: inputs apply locally at once and agree with the server. + for (let i = 0; i < 10; i += 1) { + assert.equal(client.sendInput({ dx: 1, dy: 0 }), i + 1); + await sleep(40); + } + const predictedNow = client.predictor.predicted().x; + assert.ok(Math.abs(predictedNow - (10 * 10) / 30) < 0.01, `predicted ${predictedNow}`); + await until(() => client.predictor.lastAck >= 10 && client.predictor.pending.length === 0, 10_000, 'acks'); + const authoritative = client.authority.replica.get(controlled).fields.x; + assert.ok(Math.abs(authoritative - (10 * 10) / 30) < 0.01, `server x ${authoritative}`); + assert.ok(Math.abs(client.predictor.predicted().x - authoritative) < 1e-6); + + // Clock sync converged on a real socket. + const connection = client.authority.connection; + await until(() => connection.clock.synced, 5_000, 'clock sync'); + assert.ok(connection.clock.rtt >= 0 && connection.clock.rtt < 1000); + + // Abrupt drop → resume with the reconnect token (same session). + const session = connection.sessionId; + const resumed = new Promise((resolve) => + connection.on('welcome', (w, info) => resolve({ w, info })) + ); + connection.dropTransport(); + const { w, info } = await resumed; + assert.equal(info.resumed, true); + assert.equal(w.sessionId, session); + await until(() => client.authority.replica.has(controlled), 5_000, 'recreate'); + assert.equal(client.sendInput({ dx: 0, dy: 1 }), 1, 'sequence restarted on the new socket'); + await until(() => client.predictor.lastAck >= 1 && client.predictor.pending.length === 0, 5_000, 'ack after resume'); + + // Observer connection to a neighbouring zone, merged by zone tag. + const observed = await client.observe('arena-2'); + assert.equal(observed.role, 'observer'); + await sleep(150); + const rendered = client.render(); + const mine = rendered.find((e) => e.key === `arena-1:${controlled}`); + assert.ok(mine?.predicted, 'own avatar rendered from prediction'); + assert.ok(rendered.every((e) => e.zoneId === 'arena-1' || e.zoneId === 'arena-2')); + client.close(); + } finally { + server.child.stdin.end(); + await new Promise((resolve) => { + const timer = setTimeout(() => { + server.child.kill('SIGKILL'); + resolve(); + }, 5_000); + server.child.on('exit', () => { + clearTimeout(timer); + resolve(); + }); + }); + } +}); From 565cd126a3676318dc835eb37bb8ec7573c9156a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:27:56 -0500 Subject: [PATCH 136/484] feat(js): support game Redirect, RELOAD and handoff return path Tracks the additive protocol v1 changes from the world/barrier phase: Redirect (0x89) resends the same Hello to the owning host (max 3 hops), Kick RELOAD and handshake VERSION_MISMATCH enter reload-required and rejoin with the new content version (token within grace, else fresh ticket), Resume.version is remembered as the reload target, and a refused or silent handoff target sends the same Hello back to the source zone before falling back to a fresh ticket. Interpolation delay and view tick are exposed to encodeInput and the replica for lag compensation. Golden tests include the kick_reload and redirect fixtures copied from the world branch. Refs [[tasks/gr-p4-client-sdk]] --- js/README.md | 9 +- js/src/game/client.ts | 110 ++++++++- js/src/game/connection.ts | 173 ++++++++++++-- js/src/game/index.ts | 3 + js/src/game/messages.ts | 18 +- js/src/game/replica.ts | 7 + js/tests/fixtures/game-world-messages.json | 25 ++ js/tests/game-codec.test.mjs | 21 +- js/tests/game-world.test.mjs | 251 +++++++++++++++++++++ 9 files changed, 582 insertions(+), 35 deletions(-) create mode 100644 js/tests/fixtures/game-world-messages.json create mode 100644 js/tests/game-world.test.mjs diff --git a/js/README.md b/js/README.md index e4dba2206..93a6b2fe3 100644 --- a/js/README.md +++ b/js/README.md @@ -604,7 +604,14 @@ sampled at `serverNow − interpolationDelay` (two patch intervals by default), with the controlled entity at its predicted state. Reconciliation rebases on every Delta's `ack_seq`; per-field `ease`, `snap` or `replace` resolves the divergence. A server Handoff connects to the target zone with the transfer -ticket and swaps authority while the previous world keeps rendering. +ticket (following `Redirect`s) and swaps authority while the previous world +keeps rendering; if the target refuses or stays silent the same Hello goes +back to the source zone, then a fresh ticket. `Kick(RELOAD)` and handshake +`VERSION_MISMATCH` emit `reloadRequired`; supply `reloadContent` (or call +`connection.resumeAfterReload(version)`) to rejoin with the new content. +`encodeInput(input, ctx)` receives the interpolation delay and view tick for +server-side lag compensation (`replica.interpolationDelayMs`, +`client.inputContext()`). ## Protocol and security boundaries diff --git a/js/src/game/client.ts b/js/src/game/client.ts index 292ce49ac..accaaade9 100644 --- a/js/src/game/client.ts +++ b/js/src/game/client.ts @@ -65,8 +65,12 @@ export type ControlledEntityResolver = ( export type GamePredictionOptions = PredictorOptions & Readonly<{ - /** Encode an input to its game-defined payload bytes. */ - encodeInput(input: TInput): Uint8Array; + /** + * Encode an input to its game-defined payload bytes. `context` + * carries the interpolation delay / view tick the player is looking + * at, for server-side lag compensation. + */ + encodeInput(input: TInput, context: GameInputContext): Uint8Array; /** * Which entity the player controls in a zone. Re-evaluated on every * authoritative Delta until it returns an id; `setControlledEntity` @@ -75,6 +79,17 @@ export type GamePredictionOptions = PredictorOptions & controlledEntity?: ControlledEntityResolver; }>; +/** What the player sees when an input is sampled (lag compensation). */ +export type GameInputContext = Readonly<{ + zoneId: string; + /** Render delay behind the server clock (ms). */ + interpolationDelayMs: number; + /** Server tick of the interpolated world being rendered. */ + viewTick: number; + /** Estimated current server tick (also sent as Input.client_tick). */ + clientTick: number; +}>; + export type GameClientOptions = Readonly<{ /** WebSocket URL for a zone, e.g. `(z) => \`wss://game.example/zones/${z}\``. */ url: (zoneId: string) => string; @@ -97,6 +112,10 @@ export type GameClientOptions = Readonly<{ staleGraceMs?: number; historyMs?: number; prediction?: GamePredictionOptions; + /** Give up on a handoff target without a Welcome after this long (default 10000 ms). */ + handoffTimeoutMs?: number; + /** Called on content reload requests from any zone (see GameConnection). */ + reloadContent?: GameConnectionOptions['reloadContent']; /** After a handoff, keep the previous zone rendered this long once the target delivered its first Delta. Default 500 ms. */ handoffRetainMs?: number; /** Default input dt (ms) when `sendInput` omits it. Default: 1000 / tickRate. */ @@ -115,6 +134,8 @@ export type GameClientEvents = { error: [string, ErrorMessage]; handoff: [{ from: string; to: string; message: HandoffMessage }]; handoffComplete: [{ from: string; to: string }]; + handoffFailed: [{ from: string; to: string; stage: 'target' | 'return'; reason: string }]; + reloadRequired: [string, import('./connection.js').GameReloadRequest]; correction: [Correction]; zoneClosed: [string, GameCloseInfo]; }; @@ -217,13 +238,27 @@ export class GameClient { if (authority === undefined || prediction === undefined) return undefined; const connection = authority.connection; if (!connection.canSendInput()) return undefined; - const seq = connection.sendInput(prediction.encodeInput(input)); + const context = this.inputContext(authority)!; + const seq = connection.sendInput(prediction.encodeInput(input, context), context.clientTick); if (seq === undefined) return undefined; const tickRate = connection.welcome?.tickRate || 30; this.#predictor!.record(seq, input, dtMs ?? this.#options.inputDtMs ?? 1000 / tickRate); return seq; } + /** Interpolation delay and view tick for inputs sampled now. */ + inputContext(zone: GameZoneView | undefined = this.#authority): GameInputContext | undefined { + if (zone === undefined) return undefined; + const delay = this.interpolationDelay(zone); + const serverNow = zone.connection.serverNow(); + return { + zoneId: zone.zoneId, + interpolationDelayMs: delay, + viewTick: zone.connection.tickAt(serverNow - delay), + clientTick: zone.connection.tickAt(serverNow) + }; + } + /** Send raw input bytes (no prediction). */ sendRawInput(payload: Uint8Array): number | undefined { return this.#authority?.connection.sendInput(payload); @@ -250,7 +285,9 @@ export class GameClient { const controlled = predictor?.active === true && this.#authority !== undefined ? predictor.entityId : undefined; for (const zone of this.zones()) { - const renderTime = zone.connection.serverNow() - this.interpolationDelay(zone); + const delay = this.interpolationDelay(zone); + zone.replica.interpolationDelayMs = delay; + const renderTime = zone.connection.serverNow() - delay; const authoritative = zone === this.#authority; for (const entity of zone.replica.sample(renderTime)) { const isControlled = authoritative && entity.id === controlled && !entity.stale; @@ -292,6 +329,7 @@ export class GameClient { scheduler: this.#scheduler, reconnect: o.reconnect, pingIntervalMs: o.pingIntervalMs, + reloadContent: o.reloadContent, onListenerError: o.onListenerError }; } @@ -335,6 +373,7 @@ export class GameClient { zone.offs.push( c.on('welcome', (welcome) => { zone.replica.reset(welcome.schema, c.serverNow()); + zone.replica.interpolationDelayMs = this.interpolationDelay(zone); zone.firstDeltaSeen = false; if (zone === this.#authority) { this.#predictor?.resetSession(); @@ -350,6 +389,7 @@ export class GameClient { c.on('kick', (m) => this.#emitter.emit('kick', zone.zoneId, m)), c.on('error', (m) => this.#emitter.emit('error', zone.zoneId, m)), c.on('handoff', (m) => this.#onHandoff(zone, m)), + c.on('reloadRequired', (r) => this.#emitter.emit('reloadRequired', zone.zoneId, r)), c.on('close', (info) => { this.#emitter.emit('zoneClosed', zone.zoneId, info); }) @@ -412,15 +452,63 @@ export class GameClient { this.#emitter.emit('handoff', { from, to, message }); this.#controlledOverride = undefined; this.#predictor?.bind(undefined); - const target = this.#adopt(to, 'authority', message.transferTicket); - this.#authority = target; // Keep rendering the old zone until the new authority has content. this.#retire(zone, true); - const off = target.connection.on('delta', () => { - off(); - this.#emitter.emit('handoffComplete', { from, to }); - }); - void target.connection.connect().catch(() => undefined); + this.#attemptHandoff(from, to, message.transferTicket, 'target'); + } + + /** + * Connect to `zoneId` as authority presenting the transfer ticket. If the + * target refuses (Error before Welcome, close, or timeout) send the same + * Hello back to the source zone (§8.1 return path); if that fails too, + * rejoin the source with a fresh ticket from the app. + */ + #attemptHandoff(from: string, to: string, ticket: string, stage: 'target' | 'return'): void { + const zoneId = stage === 'target' ? to : from; + const target = this.#adopt(zoneId, 'authority', ticket); + this.#authority = target; + const connection = target.connection; + let done = false; + const offs: (() => void)[] = []; + const finish = () => { + done = true; + this.#scheduler.clearTimeout(timer); + for (const off of offs) off(); + }; + const fail = (reason: string) => { + if (done) return; + finish(); + if (this.#closed || this.#authority !== target) return; + this.#emitter.emit('handoffFailed', { from, to, stage, reason }); + connection.close({ leave: false }); + // Keep the zone's replica rendering while the next attempt runs. + this.#retire(target, true); + if (stage === 'target') { + this.#attemptHandoff(from, to, ticket, 'return'); + } else { + this.#authority = this.#adopt(from, 'authority'); + void this.#authority.connection.connect().catch(() => undefined); + } + }; + const timer = this.#scheduler.setTimeout( + () => fail('timeout'), + this.#options.handoffTimeoutMs ?? 10_000 + ); + offs.push( + connection.on('welcome', () => { + if (done) return; + finish(); + const off = connection.on('delta', () => { + off(); + this.#emitter.emit('handoffComplete', { from, to: zoneId }); + }); + }), + connection.on('error', (error) => { + if (connection.welcome === undefined) fail(`error ${error.code}: ${error.message}`); + }), + connection.on('close', (info) => fail(`closed: ${info.reason}`)) + ); + void connection.connect().catch(() => undefined); } #retire(zone: Zone, keepRendering: boolean): void { diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts index b46cf9288..53d5e1148 100644 --- a/js/src/game/connection.ts +++ b/js/src/game/connection.ts @@ -13,6 +13,7 @@ import { GAME_PROTOCOL_VERSION, GameClientMirror, GameErrorCode, + GameKickCode, type DeltaMessage, type ErrorMessage, type EventMessage, @@ -22,6 +23,7 @@ import { type GameServerMessage, type HandoffMessage, type KickMessage, + type RedirectMessage, type ResumeMessage, type WelcomeMessage } from './messages.js'; @@ -94,10 +96,37 @@ export type GameConnectionOptions = Readonly<{ /** Ping cadence while open (default 1000 ms; first ping right after Welcome). */ pingIntervalMs?: number; clock?: ClockSyncOptions; + /** Consecutive Redirects followed before giving up (default 3). */ + maxRedirects?: number; + /** + * Called when the server requires a content reload (`Kick(RELOAD)` or a + * handshake `Error(VERSION_MISMATCH)`). Load content for `version` and + * return the content version now running; the connection then resumes + * (reconnect token within the grace window, else a fresh ticket). Without + * it the connection waits in `reload-required` until + * `resumeAfterReload()` is called. + */ + reloadContent?: (request: GameReloadRequest) => string | Promise; onListenerError?: (error: unknown) => void; }>; -export type GameConnectionState = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'; +export type GameReloadRequest = Readonly<{ + /** + * Content version to load: the last Resume's version, else the last + * Welcome's `content_version` (undefined if never welcomed). + */ + version: string | undefined; + reason: 'kick' | 'version-mismatch'; + message: string; +}>; + +export type GameConnectionState = + | 'idle' + | 'connecting' + | 'open' + | 'reconnecting' + | 'reload-required' + | 'closed'; export type GameCloseReason = | 'client' @@ -105,6 +134,7 @@ export type GameCloseReason = | 'handoff' | 'rejected' | 'reconnect-exhausted' + | 'too-many-redirects' | 'connect-failed'; export type GameCloseInfo = Readonly<{ @@ -129,6 +159,8 @@ export type GameConnectionEvents = { handoff: [HandoffMessage]; kick: [KickMessage]; error: [ErrorMessage]; + redirect: [RedirectMessage]; + reloadRequired: [GameReloadRequest]; pong: [{ rtt: number; offset: number; jitter: number }]; state: [GameConnectionState]; disconnect: [{ code?: number; reason?: string }]; @@ -136,13 +168,20 @@ export type GameConnectionEvents = { close: [GameCloseInfo]; }; -type Attempt = { socket: GameSocket; mode: 'fresh' | 'resume'; welcomed: boolean }; +type Attempt = { + socket: GameSocket; + mode: 'fresh' | 'resume'; + welcomed: boolean; + ticket: string; + token: string; + redirect?: string; + reload?: GameReloadRequest; +}; const defaultBackoff = (attempt: number): number => Math.min(5000, 250 * 2 ** (attempt - 1)); export class GameConnection { readonly zoneId: string; - readonly url: string; readonly clock: ClockSync; readonly mirror = new GameClientMirror(); @@ -154,6 +193,11 @@ export class GameConnection { readonly #pingIntervalMs: number; #state: GameConnectionState = 'idle'; + readonly #baseUrl: string; + #url: string; + #contentVersion: string; + #redirects = 0; + #lastResumeVersion: string | undefined; #attempt: Attempt | undefined; #initialTicket: string | undefined; #reconnectToken = ''; @@ -171,7 +215,9 @@ export class GameConnection { constructor(options: GameConnectionOptions) { this.#options = options; this.zoneId = options.zoneId; - this.url = options.url; + this.#baseUrl = options.url; + this.#url = options.url; + this.#contentVersion = options.contentVersion ?? ''; this.#initialTicket = options.initialTicket; this.#scheduler = options.scheduler ?? defaultScheduler; const factory = @@ -195,6 +241,16 @@ export class GameConnection { this.clock = new ClockSync(options.clock); } + /** URL of the current (possibly redirected) zone host. */ + get url(): string { + return this.#url; + } + + /** Content version sent in Hello. */ + get contentVersion(): string { + return this.#contentVersion; + } + get state(): GameConnectionState { return this.#state; } @@ -256,6 +312,14 @@ export class GameConnection { return w.serverTime + (diff * 1000) / w.tickRate; } + /** Server tick (u32, wrapping) whose state belongs to server time `serverTime`. */ + tickAt(serverTime: number): number { + const w = this.mirror.welcome; + if (w === undefined) return 0; + const ticks = Math.floor(((serverTime - w.serverTime) * w.tickRate) / 1000); + return (w.serverTick + ticks) >>> 0; + } + /** Estimated server tick at the current server time (wraps at 2^32). */ estimatedServerTick(): number { const w = this.mirror.welcome; @@ -315,6 +379,18 @@ export class GameConnection { this.#finish({ reason: 'client' }); } + /** + * Continue after a content reload (state `reload-required`): sends the + * new `contentVersion` in Hello, with the reconnect token while the grace + * window lasts, else with a fresh ticket. + */ + resumeAfterReload(contentVersion: string): void { + if (this.#state !== 'reload-required') return; + this.#contentVersion = contentVersion; + this.#setState(this.#welcomes === 0 ? 'connecting' : 'reconnecting'); + void this.#open(this.#withinGrace() ? 'resume' : 'fresh'); + } + /** Simulate an abrupt transport loss (tests, "airplane mode" toggles). */ dropTransport(): void { this.#attempt?.socket.close(4000, 'dropped by client'); @@ -336,13 +412,16 @@ export class GameConnection { } } - async #open(mode: 'fresh' | 'resume'): Promise { - let ticket = ''; - if (mode === 'fresh') { + async #open( + mode: 'fresh' | 'resume', + reuse?: { ticket: string; token: string } + ): Promise { + let ticket = reuse?.ticket ?? ''; + if (mode === 'fresh' && reuse === undefined) { try { if (this.#initialTicket !== undefined) { + // Kept until a Welcome: an unanswered Hello did not consume it. ticket = this.#initialTicket; - this.#initialTicket = undefined; } else { ticket = await this.#options.ticket({ zoneId: this.zoneId, @@ -357,15 +436,16 @@ export class GameConnection { } if (this.#state === 'closed') return; } - const token = mode === 'resume' ? this.#reconnectToken : ''; + const token = reuse?.token ?? (mode === 'resume' ? this.#reconnectToken : ''); + if (reuse === undefined && mode === 'fresh') this.#url = this.#baseUrl; let socket: GameSocket; try { - socket = this.#socketFactory(this.url); + socket = this.#socketFactory(this.#url); } catch (error) { this.#attemptFailed(error); return; } - const attempt: Attempt = { socket, mode, welcomed: false }; + const attempt: Attempt = { socket, mode, welcomed: false, ticket, token }; this.#attempt = attempt; try { socket.binaryType = 'arraybuffer'; @@ -377,7 +457,7 @@ export class GameConnection { this.#send({ type: 'Hello', protocolVersion: GAME_PROTOCOL_VERSION, - contentVersion: this.#options.contentVersion ?? '', + contentVersion: this.#contentVersion, capabilities: this.#options.capabilities ?? 0, ticket, reconnectToken: token @@ -439,6 +519,7 @@ export class GameConnection { break; case 'Resume': this.#frozen = false; + this.#lastResumeVersion = message.version; this.#emitter.emit('resume', message); break; case 'Handoff': @@ -446,9 +527,22 @@ export class GameConnection { this.#emitter.emit('handoff', message); break; case 'Kick': - this.#terminal = { reason: 'kick', code: message.code, message: message.message }; + if (message.code === GameKickCode.RELOAD) { + // Not session-terminal: the player is held for the grace window. + attempt.reload = { + version: this.#lastResumeVersion ?? this.mirror.welcome?.contentVersion, + reason: 'kick', + message: message.message + }; + } else { + this.#terminal = { reason: 'kick', code: message.code, message: message.message }; + } this.#emitter.emit('kick', message); break; + case 'Redirect': + attempt.redirect = message.url; + this.#emitter.emit('redirect', message); + break; case 'Error': this.#onError(attempt, message); break; @@ -459,6 +553,9 @@ export class GameConnection { const reconnected = this.#welcomes > 0; this.#welcomes += 1; attempt.welcomed = true; + this.#redirects = 0; + this.#initialTicket = undefined; + this.#lastResumeVersion = undefined; this.#failedAttempts = 0; this.#disconnectedAt = undefined; this.#reconnectToken = welcome.reconnectToken; @@ -484,6 +581,14 @@ export class GameConnection { this.#reconnectToken = ''; return; } + if (error.code === GameErrorCode.VERSION_MISMATCH) { + attempt.reload = { + version: this.#lastResumeVersion ?? this.mirror.welcome?.contentVersion, + reason: 'version-mismatch', + message: error.message + }; + return; + } this.#terminal = { reason: 'rejected', code: error.code, message: error.message }; } @@ -499,6 +604,21 @@ export class GameConnection { this.#disconnectedAt = this.#scheduler.now(); this.#failedAttempts = 0; } + if (attempt.redirect !== undefined) { + this.#redirects += 1; + if (this.#redirects > (this.#options.maxRedirects ?? 3)) { + this.#finish({ reason: 'too-many-redirects', message: attempt.redirect }); + return; + } + this.#url = attempt.redirect; + // Same Hello: the ticket was not consumed by the redirecting host. + void this.#open(attempt.mode, { ticket: attempt.ticket, token: attempt.token }); + return; + } + if (attempt.reload !== undefined) { + this.#awaitReload(attempt.reload); + return; + } if (this.#welcomes === 0 && this.#reconnect === undefined) { this.#finish({ reason: 'connect-failed', code, message: reason }); return; @@ -528,14 +648,31 @@ export class GameConnection { this.#retryTimer = this.#scheduler.setTimeout(() => { this.#retryTimer = undefined; if (this.#state === 'closed') return; - const withinGrace = - this.#reconnectToken !== '' && - this.#disconnectedAt !== undefined && - this.#scheduler.now() - this.#disconnectedAt < this.#reconnect!.graceMs; - void this.#open(withinGrace ? 'resume' : 'fresh'); + void this.#open(this.#withinGrace() ? 'resume' : 'fresh'); }, delay); } + #withinGrace(): boolean { + return ( + this.#reconnectToken !== '' && + this.#disconnectedAt !== undefined && + this.#scheduler.now() - this.#disconnectedAt < (this.#reconnect?.graceMs ?? 15000) + ); + } + + #awaitReload(request: GameReloadRequest): void { + this.#setState('reload-required'); + this.#emitter.emit('reloadRequired', request); + const reload = this.#options.reloadContent; + if (reload === undefined) return; + Promise.resolve() + .then(() => reload(request)) + .then( + (version) => this.resumeAfterReload(version), + (error) => this.#finish({ reason: 'connect-failed', message: `reload failed: ${String(error)}` }) + ); + } + #startPing(): void { this.#stopPing(); this.ping(); diff --git a/js/src/game/index.ts b/js/src/game/index.ts index ed248fbe1..ab744e32b 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -67,6 +67,7 @@ export { type NoticeFields, type PingMessage, type PongMessage, + type RedirectMessage, type ResumeMessage, type WelcomeMessage } from './messages.js'; @@ -81,6 +82,7 @@ export { type GameConnectionOptions, type GameConnectionState, type GameReconnectOptions, + type GameReloadRequest, type GameScheduler, type GameSocket, type GameSocketFactory, @@ -114,6 +116,7 @@ export { type ControlledEntityResolver, type GameClientEvents, type GameClientOptions, + type GameInputContext, type GamePredictionOptions, type GameZoneView, type RenderedEntity, diff --git a/js/src/game/messages.ts b/js/src/game/messages.ts index d05628d12..032c8b58c 100644 --- a/js/src/game/messages.ts +++ b/js/src/game/messages.ts @@ -29,7 +29,8 @@ export const GameMessageTag = Object.freeze({ RESUME: 0x85, HANDOFF: 0x86, KICK: 0x87, - ERROR: 0x88 + ERROR: 0x88, + REDIRECT: 0x89 }); /** Kick codes. */ @@ -39,7 +40,9 @@ export const GameKickCode = Object.freeze({ SHUTDOWN: 3, RATE_LIMITED: 4, ZONE_DISPOSED: 5, - SLOW_CONSUMER: 6 + SLOW_CONSUMER: 6, + /** Not session-terminal: reload content, then reconnect with the token. */ + RELOAD: 7 }); /** Error codes. */ @@ -117,6 +120,8 @@ export type HandoffMessage = Readonly<{ }>; export type KickMessage = Readonly<{ type: 'Kick'; code: number; message: string }>; export type ErrorMessage = Readonly<{ type: 'Error'; code: number; message: string }>; +/** This host does not own `zoneId`; resend the same Hello to `url`. */ +export type RedirectMessage = Readonly<{ type: 'Redirect'; zoneId: string; url: string }>; export type GameServerMessage = | WelcomeMessage | DeltaMessage @@ -126,7 +131,8 @@ export type GameServerMessage = | ResumeMessage | HandoffMessage | KickMessage - | ErrorMessage; + | ErrorMessage + | RedirectMessage; /** What the Delta codec needs: the Welcome schema and the kind of each known id. */ export type EntityKinds = Readonly<{ @@ -241,6 +247,9 @@ export function encodeServerMessage( case 'Error': w.u8(GameMessageTag.ERROR).varuint(message.code).string(message.message); break; + case 'Redirect': + w.u8(GameMessageTag.REDIRECT).string(message.zoneId).string(message.url); + break; } return w.finish(); } @@ -301,6 +310,9 @@ export function decodeServerMessage( case GameMessageTag.ERROR: message = { type: 'Error', code: r.varuint(), message: r.string() }; break; + case GameMessageTag.REDIRECT: + message = { type: 'Redirect', zoneId: r.string(), url: r.string() }; + break; default: throw new GameDecodeError('UNKNOWN_MESSAGE', `message type 0x${tag.toString(16)}`); } diff --git a/js/src/game/replica.ts b/js/src/game/replica.ts index d5037c413..a70cfca29 100644 --- a/js/src/game/replica.ts +++ b/js/src/game/replica.ts @@ -106,6 +106,13 @@ export class EntityReplica { }; } + /** + * Render delay (ms) behind the server clock this replica is sampled at. + * Maintained by `GameClient`; games include it (or the matching view + * tick) in input payloads so the server can lag-compensate. + */ + interpolationDelayMs: number | undefined; + get schema(): GameSchema | undefined { return this.#schema; } diff --git a/js/tests/fixtures/game-world-messages.json b/js/tests/fixtures/game-world-messages.json new file mode 100644 index 000000000..9566bc876 --- /dev/null +++ b/js/tests/fixtures/game-world-messages.json @@ -0,0 +1,25 @@ +{ + "source": "feat/v5-game-world:distributed_game/tests/fixtures/messages.json (additive v1 messages; drop once merged)", + "messages": [ + { + "decoded": { + "code": 7, + "message": "content c2 required", + "type": "Kick" + }, + "direction": "server_to_client", + "hex": "870713636f6e74656e74206332207265717569726564", + "name": "kick_reload" + }, + { + "decoded": { + "type": "Redirect", + "url": "ws://10.0.0.2:2567/zones/realm.west", + "zone_id": "realm.west" + }, + "direction": "server_to_client", + "hex": "890a7265616c6d2e776573742377733a2f2f31302e302e302e323a323536372f7a6f6e65732f7265616c6d2e77657374", + "name": "redirect" + } + ] +} diff --git a/js/tests/game-codec.test.mjs b/js/tests/game-codec.test.mjs index efa848331..3619d0cad 100644 --- a/js/tests/game-codec.test.mjs +++ b/js/tests/game-codec.test.mjs @@ -196,6 +196,8 @@ function messageFromJson(decoded, schema) { case 'Kick': case 'Error': return { type: decoded.type, code: decoded.code, message: decoded.message }; + case 'Redirect': + return { type: 'Redirect', zoneId: decoded.zone_id, url: decoded.url }; } throw new Error(`unhandled ${decoded.type} (${schema})`); } @@ -276,6 +278,8 @@ function messageToJson(message, kinds) { case 'Kick': case 'Error': return { code: message.code, message: message.message, type: message.type }; + case 'Redirect': + return { type: 'Redirect', url: message.url, zone_id: message.zoneId }; } } @@ -361,10 +365,23 @@ test('quantization reproduces the Rust integers and binary32 results exactly', ( } }); -test('every message fixture encodes and decodes byte-exactly', () => { +/** + * Rust fixtures plus the additive v1 messages (Redirect, Kick RELOAD) copied + * from the world branch until it is merged; the Rust file wins once present. + */ +function allMessages() { const { messages } = fixture('messages.json'); + const extra = JSON.parse( + readFileSync(new URL('./fixtures/game-world-messages.json', import.meta.url), 'utf8') + ).messages; + const names = new Set(messages.map((m) => m.name)); + return [...messages, ...extra.filter((m) => !names.has(m.name))]; +} + +test('every message fixture encodes and decodes byte-exactly', () => { + const messages = allMessages(); const names = messages.map((m) => m.name); - for (const required of ['hello', 'hello_reconnect', 'input', 'ping', 'leave', 'welcome', 'delta', 'delta_empty', 'event', 'pong', 'freeze', 'resume', 'handoff', 'kick', 'error']) { + for (const required of ['hello', 'hello_reconnect', 'input', 'ping', 'leave', 'welcome', 'delta', 'delta_empty', 'event', 'pong', 'freeze', 'resume', 'handoff', 'kick', 'error', 'kick_reload', 'redirect']) { assert.ok(names.includes(required), `fixture ${required}`); } for (const entry of messages) { diff --git a/js/tests/game-world.test.mjs b/js/tests/game-world.test.mjs new file mode 100644 index 000000000..eb362bb23 --- /dev/null +++ b/js/tests/game-world.test.mjs @@ -0,0 +1,251 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + GameClient, + GameConnection, + GameErrorCode, + GameKickCode +} from '@hops-ops/distributed/game'; + +import { FakeNetwork, FakeScheduler, avatar, delta, flush, welcome } from './fixtures/game-harness.mjs'; + +const host = (conn) => new URL(conn.url).host; + +test('Redirect resends the same Hello to the owning host, at most 3 times', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, message) => { + if (message.type !== 'Hello') return; + if (host(conn) === 'lobby.test') { + conn.send({ type: 'Redirect', zoneId: 'z1', url: 'ws://h2.test/zones/z1' }); + conn.close(); + } else if (host(conn) === 'h2.test') { + conn.send(welcome()); + } + }; + let tickets = 0; + const conn = new GameConnection({ + url: 'ws://lobby.test/zones/z1', + zoneId: 'z1', + ticket: () => `ticket-${++tickets}`, + socket: network.factory, + scheduler + }); + const redirects = []; + conn.on('redirect', (r) => redirects.push(r.url)); + await conn.connect(); + assert.deepEqual(redirects, ['ws://h2.test/zones/z1']); + assert.equal(conn.url, 'ws://h2.test/zones/z1'); + const [first, second] = network.connections; + assert.deepEqual(second.lastHello, first.lastHello, 'identical Hello after redirect'); + assert.equal(tickets, 1, 'ticket not re-fetched'); + conn.close(); + + // A redirect loop gives up after 3 hops. + const loop = new FakeNetwork(); + loop.onMessage = (c, m) => { + if (m.type === 'Hello') { + c.send({ type: 'Redirect', zoneId: 'z1', url: `ws://h${loop.connections.length}.test/zones/z1` }); + c.close(); + } + }; + const looping = new GameConnection({ + url: 'ws://h0.test/zones/z1', + zoneId: 'z1', + ticket: () => 't', + socket: loop.factory, + scheduler + }); + await assert.rejects(looping.connect(), (e) => e.info.reason === 'too-many-redirects'); + assert.equal(loop.connections.length, 4); +}); + +test('Kick(RELOAD) waits for the app to reload, then resumes with the token and new version', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + let issued = 0; + network.onMessage = (conn, m) => { + if (m.type !== 'Hello') return; + if (m.contentVersion !== 'c1' && m.contentVersion !== 'c2') { + conn.send({ type: 'Error', code: GameErrorCode.VERSION_MISMATCH, message: 'content c2 required: reload' }); + conn.close(1008); + return; + } + issued += 1; + conn.send(welcome({ reconnectToken: `rt-${issued}`, contentVersion: m.contentVersion })); + }; + const reloads = []; + const conn = new GameConnection({ + url: 'ws://game.test/zones/z1', + zoneId: 'z1', + ticket: () => 'fresh', + contentVersion: 'c1', + socket: network.factory, + scheduler, + reloadContent: async (request) => { + reloads.push(request); + return request.version ?? 'c2'; + } + }); + const closes = []; + conn.on('close', (i) => closes.push(i)); + await conn.connect(); + const server = network.last(); + server.send({ type: 'Freeze', reason: 'content_update', version: 'c2', notes: 'patching' }); + server.send({ type: 'Resume', reason: 'content_update', version: 'c2', notes: '' }); + server.send({ type: 'Kick', code: GameKickCode.RELOAD, message: 'content c2 required' }); + server.close(); + await scheduler.advance(10); + assert.deepEqual(reloads, [{ version: 'c2', reason: 'kick', message: 'content c2 required' }]); + const hello = network.last().lastHello; + assert.equal(hello.contentVersion, 'c2'); + assert.equal(hello.reconnectToken, 'rt-1', 'player held for the grace window'); + assert.equal(hello.ticket, ''); + assert.equal(conn.state, 'open'); + assert.deepEqual(closes, [], 'RELOAD is not session-terminal'); + conn.close(); +}); + +test('a stale fresh join gets VERSION_MISMATCH and rejoins after a manual reload', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type !== 'Hello') return; + if (m.contentVersion !== 'c2') { + conn.send({ type: 'Error', code: GameErrorCode.VERSION_MISMATCH, message: 'stale content: reload' }); + conn.close(1008); + return; + } + conn.send(welcome({ contentVersion: 'c2' })); + }; + const conn = new GameConnection({ + url: 'ws://game.test/zones/z1', + zoneId: 'z1', + ticket: () => 'join-ticket', + initialTicket: 'join-ticket', + contentVersion: 'c1', + socket: network.factory, + scheduler + }); + const required = []; + conn.on('reloadRequired', (r) => required.push(r.reason)); + const joined = conn.connect(); + await scheduler.advance(10); + assert.equal(conn.state, 'reload-required'); + assert.deepEqual(required, ['version-mismatch']); + conn.resumeAfterReload('c2'); + const w = await joined; + assert.equal(w.contentVersion, 'c2'); + assert.equal(network.last().lastHello.ticket, 'join-ticket', 'unconsumed ticket reused'); + conn.close(); +}); + +function handoffClient(network, scheduler) { + return new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: ({ zoneId }) => `fresh:${zoneId}`, + socket: network.factory, + scheduler, + pingIntervalMs: 60_000, + handoffRetainMs: 100, + handoffTimeoutMs: 2000, + prediction: { + encodeInput: (dx, ctx) => new Uint8Array([dx & 0xff, ctx.interpolationDelayMs]), + predict: (s, dx, dt) => ({ x: s.x + (dx * dt) / 1000 }), + controlledEntity: () => 1 + } + }); +} + +test('refused handoff returns to the source with the same Hello, then falls back to a fresh ticket', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + let sourceAcceptsReturn = true; + network.onMessage = (conn, m) => { + if (m.type !== 'Hello') return; + if (conn.zoneId === 'z2') { + conn.send({ type: 'Error', code: GameErrorCode.ZONE_FULL, message: 'full' }); + conn.close(1008); + } else if (m.ticket === 'transfer:t1' && !sourceAcceptsReturn) { + conn.send({ type: 'Error', code: GameErrorCode.UNAUTHORIZED, message: 'used' }); + conn.close(1008); + } else { + conn.send(welcome({ zoneId: conn.zoneId })); + } + }; + const client = handoffClient(network, scheduler); + const failures = []; + client.on('handoffFailed', (f) => failures.push([f.stage, f.to])); + await client.connect('z1'); + network.last('z1').send(delta({ creates: [avatar(1, 5)] })); + + network.last('z1').send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:t1' }); + network.last('z1').close(); + await scheduler.advance(10); + assert.equal(network.last('z2').lastHello.ticket, 'transfer:t1'); + assert.equal(network.last('z1').lastHello.ticket, 'transfer:t1', 'same Hello back to the source'); + assert.deepEqual(failures, [['target', 'z2']]); + assert.equal(client.authority.zoneId, 'z1'); + assert.equal(client.authority.connection.state, 'open'); + assert.ok(client.render().some((e) => e.key === 'z1:1'), 'world kept rendering'); + client.close(); + + // Source refuses the return too → fresh ticket from the app. + sourceAcceptsReturn = false; + const net2 = new FakeNetwork(); + net2.onMessage = network.onMessage; + const client2 = handoffClient(net2, scheduler); + const failures2 = []; + client2.on('handoffFailed', (f) => failures2.push(f.stage)); + await client2.connect('z1'); + net2.last('z1').send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:t1' }); + net2.last('z1').close(); + await scheduler.advance(10); + assert.deepEqual(failures2, ['target', 'return']); + assert.equal(net2.last('z1').lastHello.ticket, 'fresh:z1'); + assert.equal(client2.authority.connection.state, 'open'); + client2.close(); +}); + +test('a silent handoff target times out into the return path', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type === 'Hello' && conn.zoneId !== 'z2') conn.send(welcome({ zoneId: conn.zoneId })); + }; + const client = handoffClient(network, scheduler); + const failures = []; + client.on('handoffFailed', (f) => failures.push(f.reason)); + await client.connect('z1'); + network.last('z1').send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:t9' }); + network.last('z1').close(); + await scheduler.advance(1000); + assert.deepEqual(failures, []); + await scheduler.advance(1500); + assert.deepEqual(failures, ['timeout']); + assert.equal(network.last('z2').closed, true); + assert.equal(client.authority.zoneId, 'z1'); + assert.equal(network.last('z1').lastHello.ticket, 'transfer:t9'); + client.close(); +}); + +test('interpolation delay and view tick are exposed for lag compensation', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type === 'Hello') conn.send(welcome({ serverTime: 10_000 })); + }; + const client = handoffClient(network, scheduler); + await client.connect('z1'); + assert.equal(client.authority.replica.interpolationDelayMs, 100, '2 patches at 20 Hz'); + network.last('z1').send(delta({ creates: [avatar(1, 0)] })); + scheduler.time = 1000; // serverNow = 11000 → tick 100 + 30 + const ctx = client.inputContext(); + assert.deepEqual(ctx, { zoneId: 'z1', interpolationDelayMs: 100, viewTick: 127, clientTick: 130 }); + client.sendInput(1); + const [input] = network.last('z1').inputs(); + assert.equal(input.clientTick, 130); + assert.deepEqual([...input.payload], [1, 100], 'encodeInput received the context'); + client.close(); +}); From 39ca3670a343bc479318b64880ab1b85cd568ef6 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:29:58 -0500 Subject: [PATCH 137/484] test(js): read world message fixtures from Rust golden file The temporary copy of the Redirect and Kick RELOAD fixtures is no longer needed after merging the world branch. [[tasks/gr-p4-client-sdk]] --- js/tests/game-codec.test.mjs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/js/tests/game-codec.test.mjs b/js/tests/game-codec.test.mjs index 3619d0cad..39c96776e 100644 --- a/js/tests/game-codec.test.mjs +++ b/js/tests/game-codec.test.mjs @@ -365,17 +365,9 @@ test('quantization reproduces the Rust integers and binary32 results exactly', ( } }); -/** - * Rust fixtures plus the additive v1 messages (Redirect, Kick RELOAD) copied - * from the world branch until it is merged; the Rust file wins once present. - */ +/** Rust message fixtures, including the additive v1 Redirect and Kick RELOAD. */ function allMessages() { - const { messages } = fixture('messages.json'); - const extra = JSON.parse( - readFileSync(new URL('./fixtures/game-world-messages.json', import.meta.url), 'utf8') - ).messages; - const names = new Set(messages.map((m) => m.name)); - return [...messages, ...extra.filter((m) => !names.has(m.name))]; + return fixture('messages.json').messages; } test('every message fixture encodes and decodes byte-exactly', () => { From 963914fea68896d264e19552648cd5b2a3c2d0b7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:34:34 -0500 Subject: [PATCH 138/484] feat(game): change NetSim at runtime with GameServer::set_net_sim Dev network simulation was fixed at ServerConfig time, so demos could not offer a live latency/jitter/loss control. GameServer now holds the simulation in a watch channel that every connection reads per message. Switching it off while messages are still delayed keeps them ordered. Refs [[tasks/gr-p10-demos]] --- distributed_game/README.md | 3 +- distributed_game/src/net/mod.rs | 61 ++++++++++++++++++++++++++++----- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index 22988282e..5a5e5aa67 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -141,7 +141,8 @@ double-crediting. 200 ms, up to 3×) with head-of-line blocking, never as a dropped or reordered message. `config.net_sim = NetSim::from_env()` reads `DG_NET_LATENCY_MS`, `DG_NET_JITTER_MS`, `DG_NET_LOSS`, - `DG_NET_RETRANSMIT_MS`. + `DG_NET_RETRANSMIT_MS`. `GameServer::set_net_sim(Some(sim) | None)` + changes it at runtime for every connection (order is preserved). ## World structure diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 6d1a2fee4..0e217e2d9 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -172,7 +172,8 @@ pub struct ServerConfig { pub outbound_queue: usize, /// Largest accepted inbound frame. pub max_frame_bytes: usize, - /// Optional dev latency simulation. + /// Optional dev latency simulation (initial value; change it at runtime + /// with [`GameServer::set_net_sim`]). pub net_sim: Option, /// Zones that get their own `zone` metrics label (see [`crate::metrics`]). pub metrics_zone_labels: usize, @@ -306,6 +307,8 @@ struct Inner { /// Lock order: `zones` before `world`. world: Mutex, activations: AtomicU64, + /// Live dev network simulation, read by every connection per message. + net_sim: watch::Sender>, } /// Multi-zone WebSocket game server. @@ -341,6 +344,7 @@ where factory: impl Fn(&str) -> Option + Send + Sync + 'static, ) -> Self { let (shutdown, _) = watch::channel(false); + let (net_sim, _) = watch::channel(config.net_sim); let version = config.host.content_version.clone(); Self { inner: Arc::new(Inner { @@ -365,6 +369,7 @@ where barrier: None, }), activations: AtomicU64::new(0), + net_sim, }), } } @@ -581,6 +586,19 @@ where router.with_state(self.inner.clone()) } + /// Replace the dev network simulation at runtime (`None` disables it). + /// Applies to every message sent or received from now on, on existing + /// and new connections; messages already delayed keep their schedule + /// and order is always preserved. + pub fn set_net_sim(&self, sim: Option) { + self.inner.net_sim.send_replace(sim); + } + + /// Network simulation currently in effect. + pub fn net_sim(&self) -> Option { + *self.inner.net_sim.borrow() + } + /// Per-zone metrics registry (also served at `GET /metrics`). pub fn metrics(&self) -> &GameMetrics { &self.inner.metrics @@ -1322,14 +1340,14 @@ async fn reject(mut socket: WebSocket, code: u32, message: impl Into) { /// Order-preserving delay line for [`NetSim`]. struct DelayLine { - sim: Option, + sim: watch::Receiver>, rng: ZoneRng, queue: VecDeque<(Instant, T)>, last: Instant, } impl DelayLine { - fn new(sim: Option, seed: u64) -> Self { + fn new(sim: watch::Receiver>, seed: u64) -> Self { Self { sim, rng: ZoneRng::from_seed(seed), @@ -1338,12 +1356,17 @@ impl DelayLine { } } - /// Returns the item immediately when no simulation is configured. + /// Returns the item immediately when no simulation is in effect and + /// nothing is still queued (order is preserved when the simulation is + /// switched off while messages are in flight). fn push(&mut self, item: T) -> Option { - let Some(sim) = self.sim else { - return Some(item); + let sim = *self.sim.borrow(); + let delay = match sim { + Some(sim) => sim.delay(&mut self.rng), + None if self.queue.is_empty() => return Some(item), + None => Duration::ZERO, }; - let at = (Instant::now() + sim.delay(&mut self.rng)).max(self.last); + let at = (Instant::now() + delay).max(self.last); self.last = at; self.queue.push_back((at, item)); None @@ -1564,8 +1587,8 @@ where // 2. Session loop. let seed = u64::from(client.0) ^ unix_now(); - let mut outbound: DelayLine = DelayLine::new(cfg.net_sim, seed); - let mut inbound: DelayLine = DelayLine::new(cfg.net_sim, !seed); + let mut outbound: DelayLine = DelayLine::new(inner.net_sim.subscribe(), seed); + let mut inbound: DelayLine = DelayLine::new(inner.net_sim.subscribe(), !seed); let mut bucket = Bucket { tokens: cfg.input_burst, rate: cfg.input_rate, @@ -1744,4 +1767,24 @@ mod netsim_tests { let clean = NetSim::new(Duration::from_millis(40), Duration::from_millis(10)); assert!((0..500).all(|_| clean.delay(&mut rng) <= base_max)); } + + #[test] + fn live_net_sim_changes_preserve_order() { + let (tx, rx) = watch::channel(None); + let mut line = DelayLine::new(rx, 1); + assert_eq!(line.push(1), Some(1), "no simulation: immediate"); + tx.send_replace(Some(NetSim::new( + Duration::from_millis(200), + Duration::ZERO, + ))); + assert_eq!(line.push(2), None, "simulation switched on: delayed"); + let due = line.next_due().expect("queued"); + tx.send_replace(None); + assert_eq!(line.push(3), None, "switched off: queues behind 2"); + assert_eq!(line.pop_due(), None); + assert_eq!(line.queue.len(), 2); + assert!(line.queue.back().unwrap().0 >= due); + line.queue.clear(); + assert_eq!(line.push(4), Some(4), "queue drained: immediate again"); + } } From 943cab17f761196b430df3deb9961200c1e8b2f2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:35:06 -0500 Subject: [PATCH 139/484] feat(js): expose GameConnection.stats byte and message counters HUDs and bandwidth graphs need Delta bytes/s, which the connection did not surface. Count bytes and messages in both directions (Delta bytes separately) across every socket of the connection. Refs [[tasks/gr-p10-demos]] --- js/README.md | 2 ++ js/src/game/connection.ts | 31 ++++++++++++++++++++++++++++++- js/src/game/index.ts | 1 + js/tests/game-connection.test.mjs | 6 ++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/js/README.md b/js/README.md index 93a6b2fe3..4dc9ae74b 100644 --- a/js/README.md +++ b/js/README.md @@ -612,6 +612,8 @@ back to the source zone, then a fresh ticket. `Kick(RELOAD)` and handshake `encodeInput(input, ctx)` receives the interpolation delay and view tick for server-side lag compensation (`replica.interpolationDelayMs`, `client.inputContext()`). +`connection.stats` exposes cumulative bytes/messages in and out (Delta bytes +separately) for bandwidth HUDs. ## Protocol and security boundaries diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts index 53d5e1148..f6d0fa6b7 100644 --- a/js/src/game/connection.ts +++ b/js/src/game/connection.ts @@ -143,6 +143,19 @@ export type GameCloseInfo = Readonly<{ message?: string; }>; +/** Cumulative transport counters of one connection (all sockets). */ +export type GameConnectionStats = Readonly<{ + /** Server → client bytes / messages. */ + bytesIn: number; + messagesIn: number; + /** Bytes / count of Delta messages (replication traffic). */ + deltaBytesIn: number; + deltasIn: number; + /** Client → server bytes / messages. */ + bytesOut: number; + messagesOut: number; +}>; + export type GameWelcomeInfo = Readonly<{ /** True when this Welcome resumed the session with a reconnect token. */ resumed: boolean; @@ -210,6 +223,7 @@ export class GameConnection { #terminal: GameCloseInfo | undefined; #seq = 0; #frozen = false; + #stats = { bytesIn: 0, messagesIn: 0, deltaBytesIn: 0, deltasIn: 0, bytesOut: 0, messagesOut: 0 }; #connectWaiters: { resolve: (w: WelcomeMessage) => void; reject: (e: unknown) => void }[] = []; constructor(options: GameConnectionOptions) { @@ -282,6 +296,14 @@ export class GameConnection { return this.#seq; } + /** + * Cumulative byte/message counters (HUDs, bandwidth graphs). Sample it + * periodically and diff for rates. + */ + get stats(): GameConnectionStats { + return { ...this.#stats }; + } + get scheduler(): GameScheduler { return this.#scheduler; } @@ -406,7 +428,10 @@ export class GameConnection { const socket = this.#attempt?.socket; if (socket === undefined) return; try { - socket.send(encodeClientMessage(message)); + const bytes = encodeClientMessage(message); + socket.send(bytes); + this.#stats.bytesOut += bytes.byteLength; + this.#stats.messagesOut += 1; } catch { // A failing send surfaces as a close; reconnect logic handles it. } @@ -467,6 +492,8 @@ export class GameConnection { if (this.#attempt !== attempt) return; const bytes = toBytes(event.data); if (bytes === undefined) return; + this.#stats.bytesIn += bytes.byteLength; + this.#stats.messagesIn += 1; this.#receive(attempt, bytes); }; socket.onerror = () => undefined; @@ -493,6 +520,8 @@ export class GameConnection { this.#onWelcome(attempt, message); break; case 'Delta': + this.#stats.deltaBytesIn += bytes.byteLength; + this.#stats.deltasIn += 1; this.#emitter.emit('delta', message); break; case 'Event': diff --git a/js/src/game/index.ts b/js/src/game/index.ts index ab744e32b..3d56c4e23 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -80,6 +80,7 @@ export { type GameCloseReason, type GameConnectionEvents, type GameConnectionOptions, + type GameConnectionStats, type GameConnectionState, type GameReconnectOptions, type GameReloadRequest, diff --git a/js/tests/game-connection.test.mjs b/js/tests/game-connection.test.mjs index 956c97bc9..7da338af4 100644 --- a/js/tests/game-connection.test.mjs +++ b/js/tests/game-connection.test.mjs @@ -147,6 +147,12 @@ test('typed events surface Event/Freeze/Resume/Error and inputs are sequenced', server.send(delta({ creates: [avatar(1, 3)] })); assert.equal(conn.state, 'open', 'post-join errors are advisory'); assert.deepEqual(seen, ['Freeze', 'Resume', 'Event', 'Error', 'Delta']); + const stats = conn.stats; + assert.equal(stats.deltasIn, 1); + assert.ok(stats.deltaBytesIn > 0 && stats.deltaBytesIn < stats.bytesIn); + assert.equal(stats.messagesIn, 7, 'Welcome, Pong, Freeze, Resume, Event, Error, Delta'); + assert.equal(stats.messagesOut, 4, 'Hello, Ping and two inputs'); + assert.ok(stats.bytesOut > 0); assert.deepEqual( server.inputs().map((i) => [i.seq, i.clientTick, [...i.payload]]), [ From bdd3d6e530f5d249f497f99e6789e42cdbac6e55 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:36:35 -0500 Subject: [PATCH 140/484] feat(game): add GameServer::serve_with for extra app routes Apps that host a lobby, health or dev endpoint next to the zones had to re-implement serve() to merge routes, losing the wait for zone tasks on shutdown. serve_with merges an extra Router and keeps the graceful shutdown (kick, dispose, join zone tasks). serve() delegates to it. Refs [[tasks/gr-p10-demos]] --- distributed_game/README.md | 2 + distributed_game/src/net/mod.rs | 15 +++++- distributed_game/tests/net_e2e/main.rs | 66 ++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index 5a5e5aa67..a3696604d 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -86,6 +86,8 @@ let server = GameServer::::new(ServerConfig::new(TicketKey::new(secret)), zone_id.starts_with("room-").then_some(()) }); server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_signal).await?; +// or merge app routes (lobby, health, dev tools) with the same graceful shutdown: +// server.serve_with(listener, axum::Router::new().route("/healthz", get(ok)), signal).await?; ``` ## Durable facts diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 0e217e2d9..96b2c28ed 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -630,10 +630,23 @@ where self, listener: tokio::net::TcpListener, signal: impl Future + Send + 'static, + ) -> std::io::Result<()> { + self.serve_with(listener, Router::new(), signal).await + } + + /// [`serve`](Self::serve) with additional application routes merged + /// into [`router`](Self::router) (lobby, dev or health endpoints), keeping + /// the same graceful shutdown: zones kick their clients and every zone + /// task finishes before this returns. + pub async fn serve_with( + self, + listener: tokio::net::TcpListener, + extra: Router, + signal: impl Future + Send + 'static, ) -> std::io::Result<()> { let server = self.clone(); let mut stopped = self.inner.shutdown.subscribe(); - axum::serve(listener, self.router()) + axum::serve(listener, self.router().merge(extra)) .with_graceful_shutdown(async move { tokio::select! { _ = signal => {} diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs index c0cac94ab..a2be9c956 100644 --- a/distributed_game/tests/net_e2e/main.rs +++ b/distributed_game/tests/net_e2e/main.rs @@ -295,3 +295,69 @@ async fn latency_simulation_delays_but_preserves_order() { server.shutdown(); let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; } + +/// Raw HTTP/1.1 GET returning the whole response text. +async fn http_get(addr: std::net::SocketAddr, path: &str) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut stream = TcpStream::connect(addr).await.unwrap(); + let request = format!("GET {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + response +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn serve_with_merges_extra_routes_and_shuts_down_gracefully() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + let server = GameServer::::new(config, |zone_id| { + zone_id.starts_with('z').then(ArenaConfig::default) + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let extra = axum::Router::new().route("/hello", axum::routing::get(|| async { "hi" })); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let handle = tokio::spawn(server.clone().serve_with(listener, extra, async move { + let _ = stopped.await; + })); + let hello = http_get(addr, "/hello").await; + assert!( + hello.starts_with("HTTP/1.1 200") && hello.ends_with("hi"), + "{hello}" + ); + assert!(http_get(addr, "/metrics").await.starts_with("HTTP/1.1 200")); + + // A joined player is kicked with SHUTDOWN when the signal fires. + let url = format!("ws://{addr}"); + let mut ws = connect(&url, "z1").await; + hello_join(&mut ws, "z1").await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next(&mut ws, &mut mirror).await, + Some(ServerMessage::Welcome(_)) + )); + stop.send(()).unwrap(); + let mut kicked = false; + while let Some(msg) = next(&mut ws, &mut mirror).await { + if let ServerMessage::Kick { code, .. } = msg { + assert_eq!(code, kick::SHUTDOWN); + kicked = true; + } + } + assert!(kicked, "shutdown kick delivered"); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("serve_with returns after shutdown") + .unwrap() + .unwrap(); +} + +async fn hello_join(ws: &mut Ws, zone: &str) { + hello( + ws, + ticket("serve-with", zone, "n-serve-with", Role::Player), + String::new(), + ) + .await; +} From e04db0a9318e927c19a330b71da892c2e1cedace Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:40:46 -0500 Subject: [PATCH 141/484] feat(game): add FieldType::quant_centered for exact-zero quantization A symmetric quant_f32 range has 2^bits - 1 intervals, so 0 is not on the grid: a server that canonicalizes its state each tick (to make client prediction exact) stores a resting velocity as half a step and entities creep. quant_centered(range, bits) shifts max by one step so 0 encodes exactly at q = 2^(bits-1). No wire change; PROTOCOL.md notes it. Refs [[tasks/gr-p10-demos]] --- distributed_game/PROTOCOL.md | 6 +++++ distributed_game/src/schema.rs | 47 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md index 0521371c0..904e76916 100644 --- a/distributed_game/PROTOCOL.md +++ b/distributed_game/PROTOCOL.md @@ -137,6 +137,12 @@ Worked example (`min=-100, max=100, bits=16`, from `fixtures/quantization.json`) `80 80 02`; decodes to `fround(-100 + (32768/65535) * 200) = 0.0015259022` (bits `3ac800c8`). `v = 250` clamps to `q = 65535` (`ff ff 03`) → `100.0`. +*Informative:* a symmetric range (`min = -max`) has `2^bits - 1` intervals, +so `0` is not on the grid (the example above decodes `0.0` as +`0.0015259022`). Signed quantities that must rest at exactly zero use +`max = -min · (1 - 2^-(bits-1))` (Rust: `FieldType::quant_centered`), which +puts `0` at `q = 2^(bits-1)`. + ### 4.2 `angle {bits}` ``` diff --git a/distributed_game/src/schema.rs b/distributed_game/src/schema.rs index 24c774bfb..ccdfeafe9 100644 --- a/distributed_game/src/schema.rs +++ b/distributed_game/src/schema.rs @@ -87,6 +87,22 @@ impl FieldValue { } impl FieldType { + /// `QuantF32` over `[-range, range - range / 2^(bits-1)]`: the grid step + /// is `range / 2^(bits-1)` and **zero is exactly representable**. + /// + /// A symmetric `[-r, r]` range has an odd number of intervals + /// (`2^bits - 1`), so 0 falls between two grid points: a velocity of 0 + /// decodes as ±half a step and a resting entity creeps. Use this for + /// signed quantities (velocities, offsets). `bits` must be 1..=32. + pub const fn quant_centered(range: f32, bits: u8) -> Self { + let half = (1u64 << (bits - 1)) as f32; + Self::QuantF32 { + min: -range, + max: range - range / half, + bits, + } + } + /// Clamped linear quantization (`PROTOCOL.md` §4.1). pub fn quantize_linear(v: f32, min: f32, max: f32, bits: u8) -> u32 { let maxq = max_q(bits); @@ -428,6 +444,37 @@ impl EntitySchema { mod tests { use super::*; + #[test] + fn centered_quantization_represents_zero_exactly() { + for (range, bits) in [ + (16.0, 12), + (16.0, 14), + (20.0, 18), + (8.0, 12), + (64.0, 16), + (1.0, 2), + ] { + let ty = FieldType::quant_centered(range, bits); + assert_eq!(ty.canonicalize(&FieldValue::F(0.0)), FieldValue::F(0.0)); + assert_eq!( + ty.canonicalize(&FieldValue::F(-range)), + FieldValue::F(-range) + ); + let step = range / (1u64 << (bits - 1)) as f32; + assert_eq!(ty.canonicalize(&FieldValue::F(step)), FieldValue::F(step)); + } + // The symmetric range cannot: 0 lands half a step off. + let symmetric = FieldType::QuantF32 { + min: -16.0, + max: 16.0, + bits: 12, + }; + assert_ne!( + symmetric.canonicalize(&FieldValue::F(0.0)), + FieldValue::F(0.0) + ); + } + #[test] fn linear_quantization_rounds_half_up_and_clamps() { let q = |v| FieldType::quantize_linear(v, -10.0, 10.0, 8); From b9fdbb4c92caf041d423bcf077cfb5063399f2b8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 15:51:59 -0500 Subject: [PATCH 142/484] feat(examples): add game demo scaffolding and the Arena demo examples/game hosts the distributed_game demos: a `game-demos` binary (own cargo workspace) with one subcommand per demo, a Vite + Babylon.js client using the local SDK, and run.sh for one-command dev and smoke. Shared scaffolding: common::Demo trait, spawn/run, dev-only /dev/ticket (server-generated guest principals, signed guest tokens) and /dev/netsim (live NetSim), JSON events; client hud, input, scene, dev-api and events modules. Arena: 30 Hz zone with capsules, dash, pillars, 30 interpolated drones and a 14 m interest radius. Movement is shared by Rust and TypeScript and bit-exact (fixture replayed by a node test); smoke tests run 20 bots in-process and a headless SDK client against the real binary. Refs [[tasks/gr-p10-demos]] --- Cargo.toml | 2 +- examples/game/README.md | 119 ++ examples/game/client/.gitignore | 2 + examples/game/client/arena/index.html | 13 + examples/game/client/index.html | 18 + examples/game/client/package-lock.json | 1233 +++++++++++++++++ examples/game/client/package.json | 24 + examples/game/client/src/arena/client.ts | 64 + examples/game/client/src/arena/main.ts | 207 +++ examples/game/client/src/arena/movement.ts | 189 +++ examples/game/client/src/shared/dev-api.ts | 106 ++ examples/game/client/src/shared/events.ts | 18 + examples/game/client/src/shared/hud.ts | 191 +++ examples/game/client/src/shared/input.ts | 140 ++ examples/game/client/src/shared/scene.ts | 215 +++ examples/game/client/src/shared/style.css | 116 ++ .../game/client/tests/arena-headless.test.mjs | 98 ++ .../game/client/tests/helpers/demo-server.mjs | 57 + .../client/tests/movement-parity.test.mjs | 58 + examples/game/client/tsconfig.json | 18 + examples/game/client/vite.config.ts | 32 + examples/game/fixtures/arena-movement.json | 364 +++++ examples/game/run.sh | 104 ++ examples/game/server/.gitignore | 1 + examples/game/server/Cargo.lock | 1017 ++++++++++++++ examples/game/server/Cargo.toml | 33 + examples/game/server/src/arena/mod.rs | 316 +++++ examples/game/server/src/arena/movement.rs | 356 +++++ examples/game/server/src/common/dev.rs | 194 +++ examples/game/server/src/common/guests.rs | 114 ++ examples/game/server/src/common/mod.rs | 201 +++ examples/game/server/src/lib.rs | 10 + examples/game/server/src/main.rs | 28 + examples/game/server/tests/arena_smoke.rs | 196 +++ .../game/server/tests/movement_fixture.rs | 110 ++ 35 files changed, 5963 insertions(+), 1 deletion(-) create mode 100644 examples/game/README.md create mode 100644 examples/game/client/.gitignore create mode 100644 examples/game/client/arena/index.html create mode 100644 examples/game/client/index.html create mode 100644 examples/game/client/package-lock.json create mode 100644 examples/game/client/package.json create mode 100644 examples/game/client/src/arena/client.ts create mode 100644 examples/game/client/src/arena/main.ts create mode 100644 examples/game/client/src/arena/movement.ts create mode 100644 examples/game/client/src/shared/dev-api.ts create mode 100644 examples/game/client/src/shared/events.ts create mode 100644 examples/game/client/src/shared/hud.ts create mode 100644 examples/game/client/src/shared/input.ts create mode 100644 examples/game/client/src/shared/scene.ts create mode 100644 examples/game/client/src/shared/style.css create mode 100644 examples/game/client/tests/arena-headless.test.mjs create mode 100644 examples/game/client/tests/helpers/demo-server.mjs create mode 100644 examples/game/client/tests/movement-parity.test.mjs create mode 100644 examples/game/client/tsconfig.json create mode 100644 examples/game/client/vite.config.ts create mode 100644 examples/game/fixtures/arena-movement.json create mode 100755 examples/game/run.sh create mode 100644 examples/game/server/.gitignore create mode 100644 examples/game/server/Cargo.lock create mode 100644 examples/game/server/Cargo.toml create mode 100644 examples/game/server/src/arena/mod.rs create mode 100644 examples/game/server/src/arena/movement.rs create mode 100644 examples/game/server/src/common/dev.rs create mode 100644 examples/game/server/src/common/guests.rs create mode 100644 examples/game/server/src/common/mod.rs create mode 100644 examples/game/server/src/lib.rs create mode 100644 examples/game/server/src/main.rs create mode 100644 examples/game/server/tests/arena_smoke.rs create mode 100644 examples/game/server/tests/movement_fixture.rs diff --git a/Cargo.toml b/Cargo.toml index 90fbff273..4e3959a8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] members = ["distributed_macros", "distributed_cli", "distributed_game"] -exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker"] +exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker", "examples/game/server"] resolver = "2" [workspace.package] diff --git a/examples/game/README.md b/examples/game/README.md new file mode 100644 index 000000000..2b3828194 --- /dev/null +++ b/examples/game/README.md @@ -0,0 +1,119 @@ +# distributed_game demos + +Small playable demos of the authoritative game runtime +([`distributed_game`](../../distributed_game/README.md)) and its browser SDK +([`@hops-ops/distributed/game`](../../js/README.md#game-zones)), each focused +on one mechanic. **Dev only**: the demo server mints tickets for anonymous +guests and lets any page change the network simulation. + +| Demo | Run | Mechanic it demonstrates | +|---|---|---| +| **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | + +`./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. + +Requirements: Rust (stable), Node ≥ 22.18 (runs `.ts` test imports natively). + +## Run + +```sh +examples/game/run.sh arena +# → open http://localhost:5173/arena/ (?name=Ana&zone=arena-2 optional) +``` + +The script builds the JS SDK if `js/dist` is stale, runs `npm ci` for the +client, builds `game-demos`, starts it on `127.0.0.1:2567` with `--dev`, then +runs Vite (which proxies `/zones` (WebSocket), `/dev` and `/metrics` to the +server). Ports: `GAME_DEMOS_PORT`, `GAME_DEMOS_CLIENT_PORT`. Open a second tab +to see another player interpolated. Server metrics: `/metrics`. + +Arena controls: WASD / arrows / left stick to move (camera-relative, drag to +orbit), Space / Shift / gamepad A to dash. **P** toggles client prediction +(off = your capsule is drawn like everyone else's, one RTT + 100 ms behind +your keys), **G** the wireframe ghost at the latest server position. The +NetSim sliders change the server's simulated one-way latency (applied in +both directions), jitter and loss (a TCP-like retransmit delay) for every +connection. + +## Architecture + +``` + browser (Vite dev server :5173) game-demos --dev (:2567) + ┌──────────────────────────────────┐ ┌─────────────────────────────────────┐ + │ src//main.ts Babylon scene │ │ common::run / spawn │ + │ └ src//client.ts │ POST /dev/ticket │ ├ dev::routes /dev/ticket │ + │ GameClient (SDK) │ ───────────────► │ │ guest principal (server-made) │ + │ ├ GameConnection ws ───────┼─ /zones/{zone} ─►│ │ /dev/netsim → set_net_sim │ + │ ├ EntityReplica (interp.) │ ◄─ Welcome/Delta │ └ GameServer::serve_with │ + │ └ Predictor ── movement.ts ═╪═ parity fixture ═╪══► ZoneHost 30 Hz │ + │ src/shared/ hud · input · scene │ │ └ arena::movement (twin) │ + │ dev-api · events │ GET /metrics │ GET /metrics (Prometheus) │ + └──────────────────────────────────┘ └─────────────────────────────────────┘ +``` + +Prediction is exact because (1) every input is one command frame of exactly +one tick, consumed one per tick with a small credit bank +(`arena::MAX_CREDITS`), (2) the step uses binary32 arithmetic only +(`Math.fround` in TS) without trig, and (3) the server snaps its state to the +wire quantization after each step, so the client rebases on exactly what the +server holds. `fixtures/arena-movement.json` (written by Rust) is replayed by +the TS step in `client/tests/movement-parity.test.mjs`. + +## Layout + +``` +examples/game/ + run.sh one-command dev + smoke runner + fixtures/ cross-language golden data (Rust writes, TS checks) + server/ Rust crate `game_demos`, its own cargo workspace + src/main.rs `game-demos ` subcommands + src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events + src/arena/ Arena zone + movement.rs (twin of client movement.ts) + tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs + client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) + index.html, /index.html + src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css + src/arena/ client.ts (headless), main.ts (Babylon), movement.ts + tests/ movement-parity, arena-headless (+ helpers/demo-server.mjs) +``` + +The server crate is excluded from the root workspace (`Cargo.toml` +`exclude`), depends on `../../../distributed_game` by path and keeps its own +`Cargo.lock`; the client depends on the SDK via `file:../../../js` (the built +`dist`). + +## Adding a demo + +1. **Server** — `server/src//mod.rs`: the zone plus a unit struct + implementing `common::Demo` (`NAME`, `DEFAULT_ZONE`, `hosts_zone`, + `server(config, guests)`); add `pub mod ;` to `lib.rs` and one + variant to `DemoCommand` in `main.rs`. You get `/dev/ticket`, + `/dev/netsim`, `/metrics`, `--port/--dev/--secret`, graceful shutdown. + - Display names: `guests.name(&ctx.player(p)?.principal)` in `on_join`. + - Low-rate events: `common::send_json_event` / `broadcast_json_event`. + - Signed quantities that must rest at zero: `FieldType::quant_centered`. +2. **Smoke test** — `server/tests/_smoke.rs`: `common::spawn::` + on `127.0.0.1:0` with `DemoOptions::dev(secret)` and + `distributed_game::bots::run_bots` (custom `encoder` for your input). +3. **Client** — `client//index.html` + `src//main.ts`, add the + name to `DEMOS` in `vite.config.ts` and a link in `index.html`. Keep + networking in `src//client.ts` (no Babylon) so Node can test it. + Reuse `DevApi` + `zoneUrl` (tickets), `Hud` (status/RTT/jitter/tick/ + delta B/s/entities + NetSim sliders + `row`/`toggle`), `InputSampler`, + `FixedRate`, `cameraRelative`, `toAxis`, `createStage`/`toWorld`/ + `material`/`createRing`/`LabelLayer`, `onJsonEvent`. +4. **Headless test** — `client/tests/-headless.test.mjs` with + `startDemo('')` from `tests/helpers/demo-server.mjs`. +5. Register the demo in `run.sh` (`DEMOS=(…)`) and in the table above. + +## Security notes (why this is dev only) + +- `--dev` (or `DG_DEMO_DEV=1`) mounts `/dev/*`; without it only `/zones` and + `/metrics` exist. `run.sh` binds `127.0.0.1` and always sets it. +- `/dev/ticket` never accepts an identity: the principal is generated by the + server (`guest-`); the caller may pass a display name (sanitized, + ≤ 16 chars) and a server-signed guest token from an earlier response to + stay the same guest. Unknown fields (e.g. `principal`) are rejected. +- `/dev/netsim` changes the simulation for every connection on the server. +- The ticket secret is random per process unless `DISTRIBUTED_GAME_SECRET` + is set (needed to point `game-bots` at a running demo). diff --git a/examples/game/client/.gitignore b/examples/game/client/.gitignore new file mode 100644 index 000000000..b94707787 --- /dev/null +++ b/examples/game/client/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/examples/game/client/arena/index.html b/examples/game/client/arena/index.html new file mode 100644 index 000000000..1b3276c8a --- /dev/null +++ b/examples/game/client/arena/index.html @@ -0,0 +1,13 @@ + + + + + + Arena Demo + + + +

+ + + diff --git a/examples/game/client/index.html b/examples/game/client/index.html new file mode 100644 index 000000000..8cca69766 --- /dev/null +++ b/examples/game/client/index.html @@ -0,0 +1,18 @@ + + + + + + Game Demos + + + +
+

distributed_game demos

+

Each demo runs its own server: examples/game/run.sh <demo>. The page for the running demo works; the others need their server.

+
    +
  • Arena — fixed tick, binary deltas, interest management, prediction + reconciliation, interpolation.
  • +
+
+ + diff --git a/examples/game/client/package-lock.json b/examples/game/client/package-lock.json new file mode 100644 index 000000000..1d1850627 --- /dev/null +++ b/examples/game/client/package-lock.json @@ -0,0 +1,1233 @@ +{ + "name": "game-demos-client", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "game-demos-client", + "version": "0.0.0", + "dependencies": { + "@babylonjs/core": "9.30.0", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "typescript": "5.9.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } + }, + "../../../js": { + "name": "@hops-ops/distributed", + "version": "0.1.0", + "license": "UNLICENSED", + "dependencies": { + "@graphql-typed-document-node/core": "^3.2.0", + "graphql": "^16.14.0", + "wasm-pack": "0.15.0" + }, + "devDependencies": { + "@apollo/client": "^4.2.7", + "@types/node": "^20.0.0", + "@types/react": "19.2.18", + "esbuild": "^0.28.0", + "publint": "^0.3.22", + "react": "19.2.8", + "react-dom": "19.2.8", + "react-test-renderer": "19.2.8", + "svelte": "5.56.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=20.3.0" + }, + "peerDependencies": { + "react": "^18.2.0 || ^19.0.0", + "svelte": "^5.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "svelte": { + "optional": true + } + } + }, + "node_modules/@babylonjs/core": { + "version": "9.30.0", + "resolved": "https://registry.npmjs.org/@babylonjs/core/-/core-9.30.0.tgz", + "integrity": "sha512-rV+kc7B9oEtREaWh0YYNinoqYshRbHLHj7t4s4woDjDXFXWKHu1d8S914CNfs3KTOI8V8DvoVKLe2yDHZXfZEA==", + "license": "Apache-2.0" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hops-ops/distributed": { + "resolved": "../../../js", + "link": true + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.10.tgz", + "integrity": "sha512-oJ9ZfVIZjSjts0ZIYA48+5T0vurE5fQfX/Liad2U52Y6EN99x/OCdjGGuKMDP6jSk2i2lY6jwwA3X0drEc4PBg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.10.tgz", + "integrity": "sha512-LylBINgYYwgHNz8OMCy5+Y0w/LEgRYE0PcAIZfEuTuLNMf0S40GSLX6SFwqZsBLplS7RIHHy4zOAbl8Y5cQEvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.10.tgz", + "integrity": "sha512-vbuT3VT1GBI2fAOoUJUrsHVoOg9nbrFXTM7e3DSnb9PYf4n6jZCN8v4Vo8O6x4u5B67+/c803b8BtCZe2nIeqA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.10.tgz", + "integrity": "sha512-qYUp/qYvM3T4cF+VWalPl+przBUESILxi+qZ1m1MVRHpg06vS+jHaxXubjCaRpXjLJPDFdXzOZ0FABDghHOhNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.10.tgz", + "integrity": "sha512-v9NRQG+JztbP4DP/0yuhSyDcEJk047lYbqeNnqIgbXITcVDjGDS7OpkW5nadSY3tJ7MY8W1qIMMqP4Q3Q8BDjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.10.tgz", + "integrity": "sha512-CHc9LBHdxhn6/NXfb9IegXCWoz5VlvcDOx9QrzZ9q+XYhFlfzwymSWJjOlZcEMMtC1zgMV7qxDe6U18AI1SG0A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.10.tgz", + "integrity": "sha512-ble2WR7kWfzZFJUd3ODMGCJn1XDszptfRC0QvWc0h9/EA6MxnrQ1mvbjPZifEdgHyfHhDrwWeKeJONDITcrHSg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.10.tgz", + "integrity": "sha512-DMCYegihxBMKvLpODdk4OsvIgxtHTi+Oddf1Pm3d6wMVNjcBiG2pqyXjMPy55HgG1gCdEFr9VfhB1CmvuKn1lw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.10.tgz", + "integrity": "sha512-HQ6HuVH9TmhvPWIas7MA/KeAROgdwqH3REpUU6hZq47NW7m1b1QCrHgM+M3+N/B8DfMt88x1/z79ppRc9RflCQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.10.tgz", + "integrity": "sha512-avBhxba1DdctX0kxKkN3JWdTSg72QsxSn6FdfhZ9MkL3TTYDOXqxY1GqbC7VNttlgviK7tCe2No5btfRkFgeIg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.10.tgz", + "integrity": "sha512-UtQMex7fiXq0W/GqcWRpy6XKqUbXgQeGKB+Bd5rJngmHzpI+3kjwpWFLAhKg02onFsIMSh+Zx0zp9JIMQ7/05A==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.10.tgz", + "integrity": "sha512-0Aum2pUsCSuOopi6oka+nR1DTj/nfvc1xjL979lvh6kXUjNa30TCX7sKFjyMsrX7bK3bNVs0FsJwQcE2HCWX1Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.10.tgz", + "integrity": "sha512-4dgsouKal3qfMFORgtNigLPt7K3HXiO6jTr7+nFJv1GWu1OkZx0kvQIXbK4sjrIGnaLBk0s80eQCQ9hPIelLrw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.10.tgz", + "integrity": "sha512-d7NE89try3jisYzBD7J9M5iwfgcrXYC4dwHEjQ3HIWBftvwch1U/cy3iZ26SthtUOyClKiu7iqYiFjQEwiOlqQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.10.tgz", + "integrity": "sha512-dqB5ChSBp91JWXxpCKAS5ZVAE38esKQvdfyqANm0lF5JPiQrXnYwgG3oVBQmuNRcQ1WHkA3j5qYLsrl2CtfhCA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.10.tgz", + "integrity": "sha512-7GMf3vbQQslorWLmfsbi5fdt9RVnglk205XpOMFvW6UY5jE5oJc6JLieQJPHtsYlZ2EO0PtC06nY9Hz/IG8guw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.10.tgz", + "integrity": "sha512-tuKbkB23DKc5LG+irPSUnZZztRHqC3CNmyxeWloueBteHB+i+1HkRCMzAE41lseLDlarybeLhqfibFitKOxKMg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.10.tgz", + "integrity": "sha512-ntHtQOMw7oIshHRF1swV3vyBw+beQt9PeZ04O3D32EeDZUMoHMJuZKp4/fDllH/+xogeK0GUCONVfjjKusqKLg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.10.tgz", + "integrity": "sha512-Dlh8q8r145aYgh+N3gNIG1dz35Fz/FCxe5hs/43orDsffjP8S1P4Xz5I4FpSJsDS4LpQw1QmswZkQlUbkCldjQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.10.tgz", + "integrity": "sha512-VBJhHWz/55u45CWFv9OmfSRDgJDVENESgFxSAn13gIKJpTuFJbP4/7ymMZhDfeKFx1zGn1XBsLnNB7Ryy71qww==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.10.tgz", + "integrity": "sha512-Vjcazg+EEzUfIz+LcaxS6YtbQHo+sv0sCD+5VbwhY504bCKNW4OOreVgKq61pHT2esRQ/+AXYVPStDwxSvAOdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.10.tgz", + "integrity": "sha512-jJAaP4El+HWxYkM0jeJghASaFgfnluY0FRHhyHXxU6STs/nBhKMIxIMDrJEFg2ftKz6orX9WAo4diVan5NugNA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.10.tgz", + "integrity": "sha512-bXXdRUfRx9PaHCToKt8R/7wjDV6Tbk/hmSHK0uQBKmD3rj4jkuYndct8uGX77ZuZsePrVkQbWUgPR2jJhCTMpQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.10.tgz", + "integrity": "sha512-57Idx+VkEOQeG6Ys6sZOBFT7FfbeyxGv9A3k1m+Lf/z2SwqT40rNWbAINzjPHSMoCCBvY7Fnb9RGZWQin/HHAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.10.tgz", + "integrity": "sha512-vrvuasIpm/xf+BpZbzgirku0WnrQZMAc+H2Ai26jzqBxYEmQQE4DdJb7h8erkJMfRRipx0ma2Cty8jJwUm9ocQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.10.tgz", + "integrity": "sha512-8N52YH1B5JzBP+B1rkcBERG7rfRTGAM0RmUpyd76yyRfTljuG452GCNbVm6MPzs1+gXBha6Rw5/oHRFohOpfDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.10", + "@rollup/rollup-android-arm64": "4.64.10", + "@rollup/rollup-darwin-arm64": "4.64.10", + "@rollup/rollup-darwin-x64": "4.64.10", + "@rollup/rollup-freebsd-arm64": "4.64.10", + "@rollup/rollup-freebsd-x64": "4.64.10", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.10", + "@rollup/rollup-linux-arm-musleabihf": "4.64.10", + "@rollup/rollup-linux-arm64-gnu": "4.64.10", + "@rollup/rollup-linux-arm64-musl": "4.64.10", + "@rollup/rollup-linux-loong64-gnu": "4.64.10", + "@rollup/rollup-linux-loong64-musl": "4.64.10", + "@rollup/rollup-linux-ppc64-gnu": "4.64.10", + "@rollup/rollup-linux-ppc64-musl": "4.64.10", + "@rollup/rollup-linux-riscv64-gnu": "4.64.10", + "@rollup/rollup-linux-riscv64-musl": "4.64.10", + "@rollup/rollup-linux-s390x-gnu": "4.64.10", + "@rollup/rollup-linux-x64-gnu": "4.64.10", + "@rollup/rollup-linux-x64-musl": "4.64.10", + "@rollup/rollup-openbsd-x64": "4.64.10", + "@rollup/rollup-openharmony-arm64": "4.64.10", + "@rollup/rollup-win32-arm64-msvc": "4.64.10", + "@rollup/rollup-win32-ia32-msvc": "4.64.10", + "@rollup/rollup-win32-x64-gnu": "4.64.10", + "@rollup/rollup-win32-x64-msvc": "4.64.10", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/examples/game/client/package.json b/examples/game/client/package.json new file mode 100644 index 000000000..28ff9aaad --- /dev/null +++ b/examples/game/client/package.json @@ -0,0 +1,24 @@ +{ + "name": "game-demos-client", + "private": true, + "version": "0.0.0", + "description": "Babylon.js clients for the distributed_game demos (dev only)", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "check": "tsc --noEmit", + "test": "node --test tests/*.test.mjs" + }, + "dependencies": { + "@babylonjs/core": "9.30.0", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "typescript": "5.9.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } +} diff --git a/examples/game/client/src/arena/client.ts b/examples/game/client/src/arena/client.ts new file mode 100644 index 000000000..29b030e4b --- /dev/null +++ b/examples/game/client/src/arena/client.ts @@ -0,0 +1,64 @@ +/** + * Arena networking without rendering: builds the `GameClient` with + * prediction for the own capsule and binds it from the zone's hello event. + * Used by `main.ts` (Babylon) and by the headless Node test. + */ +import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; + +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; +import { encodeMoveInput, predictPlayer, type MoveInput } from './movement.ts'; + +export const DEFAULT_ZONE = 'arena-1'; +/** Event type ids (server `arena::EVENT_*`). */ +export const EVENT_HELLO = 1; +/** Replicated kind names. */ +export const KIND = { player: 'player', drone: 'drone', pillar: 'pillar' } as const; + +export type ArenaHello = Readonly<{ entity: number; viewRadius: number; half: number }>; + +export type ArenaClient = Readonly<{ + client: GameClient; + /** Latest hello (own entity id, view radius); undefined until joined. */ + hello(): ArenaHello | undefined; + /** Resolves on the first hello. */ + ready: Promise; +}>; + +export type ArenaClientOptions = Readonly<{ + api: DevApi; + /** HTTP origin of the server (Node); default: the page origin. */ + base?: string; + socket?: GameSocketFactory; + /** Ease duration for position corrections (ms). */ + easeMs?: number; +}>; + +export function createArenaClient(options: ArenaClientOptions): ArenaClient { + const ease = { mode: 'ease', durationMs: options.easeMs ?? 150 } as const; + const snap = { mode: 'snap' } as const; + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 500, + // One input = one 30 Hz command frame on the server. + inputDtMs: 1000 / 30, + prediction: { + encodeInput: (input) => encodeMoveInput(input), + predict: (fields, input) => predictPlayer(fields, input), + corrections: { + [KIND.player]: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } + } + } + }); + let hello: ArenaHello | undefined; + let resolveReady: (h: ArenaHello) => void = () => undefined; + const ready = new Promise((resolve) => (resolveReady = resolve)); + onJsonEvent(client, EVENT_HELLO, (value) => { + hello = value; + client.setControlledEntity(value.entity); + resolveReady(value); + }); + return { client, hello: () => hello, ready }; +} diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts new file mode 100644 index 000000000..91387829f --- /dev/null +++ b/examples/game/client/src/arena/main.ts @@ -0,0 +1,207 @@ +/** + * Arena demo page: Babylon scene over `createArenaClient`. + * + * - own capsule: predicted (inputs apply immediately), corrections eased; + * toggle prediction off (P) to see raw input latency (RTT + interpolation + * delay); the ghost (G) shows the latest authoritative server position; + * - other players and drones: interpolated ~100 ms in the past; + * - interest ring: entities beyond it are removed by the server (drones pop + * in/out at the edge); pillars are global entities. + */ +import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { Vector3 } from '@babylonjs/core/Maths/math.vector'; +import { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import type { Scene } from '@babylonjs/core/scene'; +import type { RenderedEntity } from '@hops-ops/distributed/game'; + +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; +import { createArenaClient, DEFAULT_ZONE, KIND } from './client.ts'; +import { BUTTON_DASH, DASH_COOLDOWN, HALF, PLAYER_RADIUS, type MoveInput } from './movement.ts'; + +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const storedName = (() => { + try { + return localStorage.getItem('game-demos.name') ?? undefined; + } catch { + return undefined; + } +})(); +const name = params.get('name') ?? storedName; + +const api = new DevApi({ name: () => name }); +const arena = createArenaClient({ api }); +const { client } = arena; + +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: HALF }); +const { scene } = stage; + +let predictionOn = true; +let ghostOn = true; +let corrections = 0; +let lastCorrection = 0; +client.on('correction', (c) => { + corrections += 1; + lastCorrection = Math.hypot(c.errors.x ?? 0, c.errors.y ?? 0); +}); + +const hud = new Hud({ + title: 'Arena', + hint: 'WASD / stick to move, Space / A to dash. P: prediction, G: ghost. Drag to orbit.', + client, + devApi: api +}); +hud.toggle('Client prediction', true, (on) => (predictionOn = on), 'p'); +hud.toggle('Server ghost', true, (on) => (ghostOn = on), 'g'); + +// ---- meshes ---- +const mats = { + me: material(scene, 'me', '#6cc4ff'), + other: material(scene, 'other', '#f2a65a'), + ghost: material(scene, 'ghost', '#ffffff', 0.25), + drone: material(scene, 'drone', '#9ad16b'), + pillar: material(scene, 'pillar', '#7b8798') +}; +mats.ghost.wireframe = true; + +function capsule(id: string, mat: StandardMaterial): Mesh { + const mesh = MeshBuilder.CreateCapsule(id, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + mesh.material = mat; + return mesh; +} + +const droneTemplate = (() => { + const body = MeshBuilder.CreateSphere('drone-body', { diameter: 0.7, segments: 8 }, scene); + body.scaling.y = 0.45; + const nose = MeshBuilder.CreateBox('drone-nose', { width: 0.5, height: 0.12, depth: 0.12 }, scene); + nose.position.x = 0.35; + const merged = Mesh.MergeMeshes([body, nose], true)!; + merged.material = mats.drone; + merged.setEnabled(false); + return merged; +})(); + +type Visual = { mesh: Mesh | ReturnType; kind: string }; +const visuals = new Map(); +const ghost = capsule('ghost', mats.ghost); +const ring = createRing(scene, 14, '#6cc4ff'); +ring.setEnabled(false); + +function visualFor(entity: RenderedEntity, mine: boolean): Visual { + let visual = visuals.get(entity.key); + if (visual !== undefined) return visual; + switch (entity.kindName) { + case KIND.drone: + visual = { mesh: droneTemplate.createInstance(entity.key), kind: KIND.drone }; + break; + case KIND.pillar: { + const r = num(entity, 'r'); + const mesh = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2, tessellation: 24 }, scene); + mesh.material = mats.pillar; + visual = { mesh, kind: KIND.pillar }; + break; + } + default: + visual = { mesh: capsule(entity.key, mine ? mats.me : mats.other), kind: KIND.player }; + } + visuals.set(entity.key, visual); + return visual; +} + +function num(entity: RenderedEntity | { fields: RenderedEntity['fields'] }, field: string): number { + const v = entity.fields[field]; + return typeof v === 'number' ? v : 0; +} + +// ---- input: one command frame per 30 Hz tick ---- +const sampler = new InputSampler(); +const commandFrames = new FixedRate(30); +let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; + +function sendCommandFrame(): void { + const s = sampler.sample(); + const move = cameraRelative(s, stage.cameraForward()); + lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON_DASH : 0 }; + client.sendInput(lastInput); +} + +// ---- frame ---- +stage.onFrame((now, dtMs) => { + commandFrames.advance(now, sendCommandFrame); + const hello = arena.hello(); + const authority = client.authority; + const rendered = client.render(); + const seen = new Set(); + let me: { x: number; y: number } | undefined; + for (const entity of rendered) { + const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; + let fields = entity.fields; + if (mine && !predictionOn && authority !== undefined) { + // Prediction off: show the own capsule like everyone else, interpolated in the past. + const renderTime = authority.connection.serverNow() - client.interpolationDelay(authority); + fields = authority.replica.sampleEntity(entity.id, renderTime)?.fields ?? fields; + } + const visual = visualFor(entity, mine); + const x = num({ fields }, 'x'); + const y = num({ fields }, 'y'); + seen.add(entity.key); + if (visual.kind === KIND.drone) { + visual.mesh.position.copyFrom(toWorld(x, y, 1.3)); + visual.mesh.rotation.y = -num(entity, 'yaw'); + } else if (visual.kind === KIND.pillar) { + visual.mesh.position.copyFrom(toWorld(x, y, 1)); + } else { + visual.mesh.position.copyFrom(toWorld(x, y, 0.9)); + const dashing = num({ fields }, 'dash') > 0; + visual.mesh.scaling.copyFromFloats(dashing ? 1.25 : 1, 1, dashing ? 1.25 : 1); + const label = String(fields.name ?? ''); + stage.labels.set(entity.key, visual.mesh as Mesh, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); + if (mine) me = { x, y }; + } + visual.mesh.setEnabled(!entity.stale || visual.kind === KIND.pillar); + } + for (const [key, visual] of visuals) { + if (seen.has(key)) continue; + visual.mesh.dispose(); + stage.labels.delete(key); + visuals.delete(key); + } + + const authoritative = client.predictor?.authoritative(); + ghost.setEnabled(ghostOn && authoritative !== undefined); + if (authoritative !== undefined) ghost.position.copyFrom(toWorld(num({ fields: authoritative }, 'x'), num({ fields: authoritative }, 'y'), 0.9)); + if (me !== undefined) { + stage.follow(me.x, me.y, dtMs); + ring.setEnabled(true); + ring.position = new Vector3(me.x, 0, me.y); + if (hello !== undefined && ring.metadata !== hello.viewRadius) { + ring.scaling.setAll(hello.viewRadius / 14); + ring.metadata = hello.viewRadius; + } + } + + hud.frame({ entities: rendered.length }); + const predictor = client.predictor; + const cd = authoritative === undefined ? 0 : num({ fields: authoritative }, 'cd'); + hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); + hud.row('Pending inputs', String(predictor?.pending.length ?? 0)); + hud.row('Ack seq', String(predictor?.lastAck ?? 0)); + hud.row('Corrections', `${corrections} (last ${lastCorrection.toFixed(3)} m)`); + hud.row('Dash', cd > 0 ? `cooldown ${((cd / DASH_COOLDOWN) * 1.5).toFixed(1)} s` : 'ready'); + hud.row('Stick', `${lastInput.mx}, ${lastInput.my}`); +}); + +declare global { + interface Window { + /** Debug handle (console). */ + arena?: unknown; + } +} +window.arena = { client, api, scene: scene as Scene }; + +client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/arena/movement.ts b/examples/game/client/src/arena/movement.ts new file mode 100644 index 000000000..c8e7aaaa7 --- /dev/null +++ b/examples/game/client/src/arena/movement.ts @@ -0,0 +1,189 @@ +/** + * Shared deterministic movement step for the Arena demo. + * + * **Twin of `examples/game/server/src/arena/movement.rs`** — the server runs + * that one, the client predicts its own capsule with this one. They must + * produce identical numbers: every operation is rounded to binary32 with + * `f()` (= `Math.fround`), only `+ - * /` and `sqrt` are used, one input is + * one command frame of exactly `DT`, and positions/velocities are snapped + * to their wire quantization at the end of each step. + * + * `tests/movement-parity.test.mjs` replays the Rust-generated fixture + * `examples/game/fixtures/arena-movement.json` through this file. + * + * No imports except the SDK quantizers so Node can run it directly. + */ +import { dequantizeLinear, quantizeLinear, type EntityFields } from '@hops-ops/distributed/game'; + +const f = Math.fround; + +export const DT = f(1 / 30); +export const HALF = 20; +export const PLAYER_RADIUS = 0.5; +export const MAX_SPEED = 5; +export const ACCEL = 40; +export const DASH_SPEED = 14; +export const DASH_FRAMES = 6; +export const DASH_COOLDOWN = 45; +export const BUTTON_DASH = 1; + +/** Static circular pillars `[x, y, radius]`. */ +export const PILLARS: readonly (readonly [number, number, number])[] = [ + [0, 0, 2.5], + [-9, -9, 1.5], + [9, -9, 1.5], + [-9, 9, 1.5], + [9, 9, 1.5], + [0, -14, 1], + [0, 14, 1], + [-14, 0, 1], + [14, 0, 1] +]; + +export type Quant = Readonly<{ min: number; max: number; bits: number }>; + +/** `FieldType::quant_centered(range, bits)`: zero is on the grid. */ +export function quantCentered(range: number, bits: number): Quant { + return { min: -range, max: f(range - range / 2 ** (bits - 1)), bits }; +} + +/** Wire quantization of `x`/`y` and `vx`/`vy` (must match the Rust schema). */ +export const POS = quantCentered(HALF, 18); +export const VEL = quantCentered(16, 12); + +/** One command frame: stick per axis in [-127, 127] and button bits. */ +export type MoveInput = Readonly<{ mx: number; my: number; buttons: number }>; + +export type MoveState = Readonly<{ + x: number; + y: number; + vx: number; + vy: number; + dash: number; + cooldown: number; +}>; + +/** Wire payload `[mx, my, buttons]` (as the server decodes it). */ +export function encodeMoveInput(input: MoveInput): Uint8Array { + return new Uint8Array([input.mx & 0xff, input.my & 0xff, input.buttons & 0xff]); +} + +/** The server's sanitization: -128 → -127, unknown buttons cleared. */ +export function sanitizeMoveInput(input: MoveInput): MoveInput { + const axis = (v: number) => Math.max(-127, Math.min(127, Math.trunc(v))); + return { mx: axis(input.mx), my: axis(input.my), buttons: input.buttons & BUTTON_DASH }; +} + +function snap(q: Quant, v: number): number { + return dequantizeLinear(quantizeLinear(v, q.min, q.max, q.bits), q.min, q.max, q.bits); +} + +/** Advance one command frame (see the module docs). */ +export function step(state: MoveState, raw: MoveInput): MoveState { + const input = sanitizeMoveInput(raw); + let { x, y, vx, vy, dash, cooldown } = state; + let dx = f(input.mx / 127); + let dy = f(input.my / 127); + const l2 = f(f(dx * dx) + f(dy * dy)); + if (l2 > 1) { + const inv = f(1 / f(Math.sqrt(l2))); + dx = f(dx * inv); + dy = f(dy * inv); + } + + cooldown = Math.max(0, cooldown - 1); + if ((input.buttons & BUTTON_DASH) !== 0 && cooldown === 0 && dash === 0) { + const v2 = f(f(vx * vx) + f(vy * vy)); + let dir: [number, number] | undefined; + if (l2 > f(0.01)) { + const l = f(Math.sqrt(f(f(dx * dx) + f(dy * dy)))); + dir = [f(dx / l), f(dy / l)]; + } else if (v2 > f(0.01)) { + const l = f(Math.sqrt(v2)); + dir = [f(vx / l), f(vy / l)]; + } + if (dir !== undefined) { + vx = f(dir[0] * DASH_SPEED); + vy = f(dir[1] * DASH_SPEED); + dash = DASH_FRAMES; + cooldown = DASH_COOLDOWN; + } + } + + if (dash > 0) { + dash -= 1; + } else { + const ex = f(f(dx * MAX_SPEED) - vx); + const ey = f(f(dy * MAX_SPEED) - vy); + const e2 = f(f(ex * ex) + f(ey * ey)); + const maxDv = f(ACCEL * DT); + if (e2 > f(maxDv * maxDv)) { + const k = f(maxDv / f(Math.sqrt(e2))); + vx = f(vx + f(ex * k)); + vy = f(vy + f(ey * k)); + } else { + vx = f(vx + ex); + vy = f(vy + ey); + } + } + + x = f(x + f(vx * DT)); + y = f(y + f(vy * DT)); + + for (const [px, py, pr] of PILLARS) { + const ox = f(x - px); + const oy = f(y - py); + const d2 = f(f(ox * ox) + f(oy * oy)); + const min = f(PLAYER_RADIUS + pr); + if (d2 < f(min * min)) { + const d = f(Math.sqrt(d2)); + const [nx, ny] = d > f(1e-6) ? [f(ox / d), f(oy / d)] : [1, 0]; + x = f(px + f(nx * min)); + y = f(py + f(ny * min)); + const vn = f(f(vx * nx) + f(vy * ny)); + if (vn < 0) { + vx = f(vx - f(vn * nx)); + vy = f(vy - f(vn * ny)); + } + } + } + + const lim = f(HALF - PLAYER_RADIUS); + if (x < -lim) { + x = -lim; + vx = Math.max(vx, 0); + } else if (x > lim) { + x = lim; + vx = Math.min(vx, 0); + } + if (y < -lim) { + y = -lim; + vy = Math.max(vy, 0); + } else if (y > lim) { + y = lim; + vy = Math.min(vy, 0); + } + return { + x: snap(POS, x), + y: snap(POS, y), + vx: snap(VEL, vx), + vy: snap(VEL, vy), + dash, + cooldown + }; +} + +/** Replicated `player` fields → state. */ +export function stateFromFields(fields: EntityFields): MoveState { + const n = (name: string) => { + const v = fields[name]; + return typeof v === 'number' ? v : 0; + }; + return { x: n('x'), y: n('y'), vx: n('vx'), vy: n('vy'), dash: n('dash'), cooldown: n('cd') }; +} + +/** `Predictor` `predict` function for the `player` kind. */ +export function predictPlayer(fields: EntityFields, input: MoveInput): Record { + const s = step(stateFromFields(fields), input); + return { x: s.x, y: s.y, vx: s.vx, vy: s.vy, dash: s.dash, cd: s.cooldown }; +} diff --git a/examples/game/client/src/shared/dev-api.ts b/examples/game/client/src/shared/dev-api.ts new file mode 100644 index 000000000..5d2ddb88f --- /dev/null +++ b/examples/game/client/src/shared/dev-api.ts @@ -0,0 +1,106 @@ +/** + * Client side of the demo server's **dev-only** routes (`/dev/ticket`, + * `/dev/netsim`, see `server/src/common/dev.rs`) plus zone URLs. + * + * A real game gets admission tickets from its authenticated lobby; the dev + * route mints one for a server-generated guest. We keep the server-signed + * guest token (localStorage when available) so a page reload stays the same + * player. Works in browsers (relative URLs) and in Node tests (`base`). + */ +import type { GameTicketSource } from '@hops-ops/distributed/game'; + +export type DevTicket = Readonly<{ + ticket: string; + principal: string; + name: string; + guest: string; + zone: string; + expiresAt: number; +}>; + +export type NetSimSettings = Readonly<{ latencyMs: number; jitterMs: number; loss: number }>; + +export type DevApiOptions = Readonly<{ + /** HTTP origin of the demo server; '' = same origin (Vite proxy). */ + base?: string; + /** Display name for new tickets (read on every request). */ + name?: () => string | undefined; + /** Where the guest token lives between reloads (default localStorage when present). */ + storage?: Pick; +}>; + +const GUEST_KEY = 'game-demos.guest'; + +function defaultStorage(): Pick | undefined { + try { + return globalThis.localStorage ?? undefined; + } catch { + return undefined; + } +} + +export class DevApi { + readonly base: string; + readonly #name: () => string | undefined; + readonly #storage: Pick | undefined; + #guest: string | undefined; + /** Last ticket response (principal and display name in effect). */ + last: DevTicket | undefined; + + constructor(options: DevApiOptions = {}) { + this.base = options.base ?? ''; + this.#name = options.name ?? (() => undefined); + this.#storage = options.storage ?? defaultStorage(); + this.#guest = this.#storage?.getItem(GUEST_KEY) ?? undefined; + } + + /** Mint a single-use admission ticket for `zone`. */ + async ticket(zone: string, role: 'player' | 'observer' = 'player'): Promise { + const response = await this.#json('/dev/ticket', { + zone, + role, + name: this.#name(), + guest: this.#guest + }); + const ticket = response as DevTicket; + this.#guest = ticket.guest; + this.#storage?.setItem(GUEST_KEY, ticket.guest); + this.last = ticket; + return ticket; + } + + /** `GameClient` / `GameConnection` ticket source backed by `ticket()`. */ + ticketSource(): GameTicketSource { + return async ({ zoneId, role }) => (await this.ticket(zoneId, role)).ticket; + } + + async getNetSim(): Promise { + return (await this.#json('/dev/netsim')) as NetSimSettings; + } + + /** Server-wide: affects every connected client (dev only). */ + async setNetSim(settings: NetSimSettings): Promise { + return (await this.#json('/dev/netsim', settings)) as NetSimSettings; + } + + async #json(path: string, body?: unknown): Promise { + const response = await fetch(`${this.base}${path}`, { + method: body === undefined ? 'GET' : 'POST', + headers: body === undefined ? undefined : { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body) + }); + if (!response.ok) { + throw new Error(`${path}: HTTP ${response.status} ${await response.text()}`); + } + return response.json(); + } +} + +/** + * WebSocket URL of a zone. `base` is an http(s) origin (Node tests); in the + * browser the page's own origin is used (Vite proxies `/zones`). + */ +export function zoneUrl(zone: string, base?: string): string { + const origin = base ?? globalThis.location.origin; + return `${origin.replace(/^http/, 'ws')}/zones/${encodeURIComponent(zone)}`; +} diff --git a/examples/game/client/src/shared/events.ts b/examples/game/client/src/shared/events.ts new file mode 100644 index 000000000..908213f16 --- /dev/null +++ b/examples/game/client/src/shared/events.ts @@ -0,0 +1,18 @@ +/** + * Demos send low-rate events as UTF-8 JSON (`common::send_json_event` on the + * server). Subscribe by type id; returns the unsubscribe function. + */ +import type { GameClient } from '@hops-ops/distributed/game'; + +const decoder = new TextDecoder(); + +export function onJsonEvent( + client: Pick, 'on'>, + typeId: number, + handler: (value: T, zoneId: string) => void +): () => void { + return client.on('event', (zoneId, event) => { + if (event.typeId !== typeId) return; + handler(JSON.parse(decoder.decode(event.payload)) as T, zoneId); + }); +} diff --git a/examples/game/client/src/shared/hud.ts b/examples/game/client/src/shared/hud.ts new file mode 100644 index 000000000..50cd10586 --- /dev/null +++ b/examples/game/client/src/shared/hud.ts @@ -0,0 +1,191 @@ +/** + * Shared HUD: connection status, RTT/jitter, server tick, delta bytes/s and + * entity count for the authoritative zone of a `GameClient`, plus demo rows, + * toggles and the server-side NetSim controls (`/dev/netsim`). + * + * ```ts + * const hud = new Hud({ title: 'Arena', client, devApi }); + * hud.toggle('Prediction', true, (on) => (predict = on)); + * stage.onFrame(() => hud.frame({ entities: rendered.length })); + * hud.row('Pending inputs', String(n)); + * ``` + */ +import type { GameClient } from '@hops-ops/distributed/game'; + +import type { DevApi, NetSimSettings } from './dev-api.ts'; + +export type HudOptions = Readonly<{ + title: string; + /** One-line description of what to try. */ + hint?: string; + client: GameClient; + /** Shows NetSim sliders when given. */ + devApi?: DevApi; + /** Mount point (default document.body). */ + parent?: HTMLElement; +}>; + +const STAT_INTERVAL_MS = 250; + +export class Hud { + readonly root: HTMLElement; + readonly #client: GameClient; + readonly #rows = new Map(); + readonly #table: HTMLElement; + #lastSample: { at: number; deltaBytes: number; connection: unknown } | undefined; + #deltaRate = 0; + #lastStatAt = 0; + + constructor(options: HudOptions) { + this.#client = options.client; + this.root = el('aside', 'hud'); + const title = el('h1', '', options.title); + this.root.append(title); + if (options.hint !== undefined) this.root.append(el('p', 'hint', options.hint)); + this.#table = el('dl', 'stats'); + this.root.append(this.#table); + for (const name of ['Status', 'Zone', 'RTT', 'Jitter', 'Server tick', 'Delta in', 'Entities']) { + this.row(name, '—'); + } + if (options.devApi !== undefined) this.root.append(netSimPanel(options.devApi)); + (options.parent ?? document.body).append(this.root); + } + + /** Set (or add) a stat row. */ + row(name: string, value: string): void { + let dd = this.#rows.get(name); + if (dd === undefined) { + const dt = el('dt', '', name); + dd = el('dd'); + this.#table.append(dt, dd); + this.#rows.set(name, dd); + } + if (dd.textContent !== value) dd.textContent = value; + } + + /** Add a checkbox toggle. */ + toggle(label: string, initial: boolean, onChange: (on: boolean) => void, key?: string): void { + const wrap = el('label', 'toggle'); + const input = document.createElement('input'); + input.type = 'checkbox'; + input.checked = initial; + input.addEventListener('change', () => onChange(input.checked)); + wrap.append(input, document.createTextNode(` ${label}`)); + if (key !== undefined) wrap.title = `key: ${key}`; + this.root.append(wrap); + if (key !== undefined) { + window.addEventListener('keydown', (e) => { + if (e.key.toLowerCase() === key.toLowerCase() && !e.repeat) { + input.checked = !input.checked; + onChange(input.checked); + } + }); + } + } + + /** Call every frame; refreshes the standard rows a few times a second. */ + frame(extra: Readonly<{ entities?: number }> = {}): void { + const now = performance.now(); + if (now - this.#lastStatAt < STAT_INTERVAL_MS) return; + this.#lastStatAt = now; + const zone = this.#client.authority; + if (zone === undefined) { + this.row('Status', 'not connected'); + return; + } + const connection = zone.connection; + const stats = connection.stats; + const sample = this.#lastSample; + if (sample !== undefined && sample.connection === connection && now > sample.at) { + const rate = ((stats.deltaBytesIn - sample.deltaBytes) * 1000) / (now - sample.at); + this.#deltaRate = this.#deltaRate === 0 ? rate : this.#deltaRate * 0.7 + rate * 0.3; + } + this.#lastSample = { at: now, deltaBytes: stats.deltaBytesIn, connection }; + const clock = connection.clock; + this.row('Status', connection.frozen ? 'frozen' : connection.state); + this.row('Zone', zone.zoneId); + this.row('RTT', clock.synced ? `${clock.rtt.toFixed(0)} ms` : '—'); + this.row('Jitter', clock.synced ? `${clock.jitter.toFixed(1)} ms` : '—'); + this.row('Server tick', String(zone.replica.serverTick)); + this.row('Delta in', `${formatBytes(this.#deltaRate)}/s · ${stats.deltasIn} deltas`); + this.row('Entities', String(extra.entities ?? zone.replica.size)); + } +} + +function netSimPanel(api: DevApi): HTMLElement { + const box = el('fieldset', 'netsim'); + box.append(el('legend', '', 'Network simulation (server, all clients)')); + const settings = { latencyMs: 0, jitterMs: 0, loss: 0 }; + const sliders: Record = { + latencyMs: slider(box, 'Latency (one way)', 0, 300, 5, (v) => `${v} ms`), + jitterMs: slider(box, 'Jitter', 0, 100, 1, (v) => `${v} ms`), + loss: slider(box, 'Loss (retransmit)', 0, 0.2, 0.01, (v) => `${Math.round(v * 100)}%`) + }; + let timer: ReturnType | undefined; + const status = el('small', 'netsim-status', ''); + box.append(status); + const push = () => { + clearTimeout(timer); + timer = setTimeout(() => { + api + .setNetSim(settings) + .then(() => (status.textContent = 'applied')) + .catch((e: unknown) => (status.textContent = `failed: ${String(e)}`)); + }, 150); + }; + for (const key of Object.keys(sliders) as (keyof NetSimSettings)[]) { + sliders[key].addEventListener('input', () => { + settings[key] = Number(sliders[key].value); + push(); + }); + } + api + .getNetSim() + .then((current) => { + for (const key of Object.keys(sliders) as (keyof NetSimSettings)[]) { + settings[key] = current[key]; + sliders[key].value = String(current[key]); + sliders[key].dispatchEvent(new Event('sync')); + } + }) + .catch(() => (status.textContent = 'dev routes unavailable (start with --dev)')); + return box; +} + +function slider( + parent: HTMLElement, + label: string, + min: number, + max: number, + step: number, + format: (v: number) => string +): HTMLInputElement { + const row = el('label', 'slider'); + const name = el('span', '', label); + const value = el('output'); + const input = document.createElement('input'); + input.type = 'range'; + input.min = String(min); + input.max = String(max); + input.step = String(step); + input.value = String(min); + const show = () => (value.textContent = format(Number(input.value))); + input.addEventListener('input', show); + input.addEventListener('sync', show); + show(); + row.append(name, input, value); + parent.append(row); + return input; +} + +function el(tag: string, className = '', text?: string): HTMLElement { + const node = document.createElement(tag); + if (className !== '') node.className = className; + if (text !== undefined) node.textContent = text; + return node; +} + +export function formatBytes(n: number): string { + if (n < 1024) return `${n.toFixed(0)} B`; + return `${(n / 1024).toFixed(1)} KiB`; +} diff --git a/examples/game/client/src/shared/input.ts b/examples/game/client/src/shared/input.ts new file mode 100644 index 000000000..27f2c5f20 --- /dev/null +++ b/examples/game/client/src/shared/input.ts @@ -0,0 +1,140 @@ +/** + * Keyboard + gamepad sampling and a fixed-rate input loop. + * + * `InputSampler.sample()` returns a stick in [-1, 1]² (+x right, +y forward, + * length ≤ 1) and named buttons. `FixedRate` turns render frames into + * command frames at the server tick rate: each command frame is one input + * the server simulates for exactly one tick, which is what makes client + * prediction line up with the authoritative simulation. + */ + +export type Sample = Readonly<{ + x: number; + y: number; + /** Primary action (dash, fire …): Space / Shift / gamepad A or RB. */ + action: boolean; + /** Secondary action: E / F / gamepad B or LB. */ + alt: boolean; +}>; + +const UP = ['KeyW', 'ArrowUp']; +const DOWN = ['KeyS', 'ArrowDown']; +const LEFT = ['KeyA', 'ArrowLeft']; +const RIGHT = ['KeyD', 'ArrowRight']; +const ACTION = ['Space', 'ShiftLeft', 'ShiftRight']; +const ALT = ['KeyE', 'KeyF']; +const DEADZONE = 0.15; + +export class InputSampler { + readonly #down = new Set(); + readonly #dispose: () => void; + + constructor(target: Window = window) { + const down = (e: KeyboardEvent) => { + if (isTyping(e)) return; + this.#down.add(e.code); + if ([...UP, ...DOWN, ...LEFT, ...RIGHT, 'Space'].includes(e.code)) e.preventDefault(); + }; + const up = (e: KeyboardEvent) => this.#down.delete(e.code); + const blur = () => this.#down.clear(); + target.addEventListener('keydown', down); + target.addEventListener('keyup', up); + target.addEventListener('blur', blur); + this.#dispose = () => { + target.removeEventListener('keydown', down); + target.removeEventListener('keyup', up); + target.removeEventListener('blur', blur); + }; + } + + #any(codes: readonly string[]): boolean { + return codes.some((c) => this.#down.has(c)); + } + + sample(): Sample { + let x = (this.#any(RIGHT) ? 1 : 0) - (this.#any(LEFT) ? 1 : 0); + let y = (this.#any(UP) ? 1 : 0) - (this.#any(DOWN) ? 1 : 0); + let action = this.#any(ACTION); + let alt = this.#any(ALT); + const pad = firstGamepad(); + if (pad !== undefined) { + const gx = pad.axes[0] ?? 0; + const gy = -(pad.axes[1] ?? 0); + if (Math.hypot(gx, gy) > DEADZONE) { + x = gx; + y = gy; + } + action ||= pad.buttons[0]?.pressed === true || pad.buttons[5]?.pressed === true; + alt ||= pad.buttons[1]?.pressed === true || pad.buttons[4]?.pressed === true; + } + const length = Math.hypot(x, y); + if (length > 1) { + x /= length; + y /= length; + } + return { x, y, action, alt }; + } + + dispose(): void { + this.#dispose(); + } +} + +function firstGamepad(): Gamepad | undefined { + const pads = globalThis.navigator?.getGamepads?.() ?? []; + for (const pad of pads) if (pad?.connected) return pad; + return undefined; +} + +function isTyping(e: KeyboardEvent): boolean { + const t = e.target as HTMLElement | null; + return t !== null && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable); +} + +/** Rotate a stick by the camera so "forward" is away from the camera. */ +export function cameraRelative( + stick: Readonly<{ x: number; y: number }>, + forward: Readonly<{ x: number; y: number }> +): { x: number; y: number } { + const l = Math.hypot(forward.x, forward.y) || 1; + const fx = forward.x / l; + const fy = forward.y / l; + // right = forward rotated -90° on the ground plane. + return { x: fy * stick.x + fx * stick.y, y: -fx * stick.x + fy * stick.y }; +} + +/** Map [-1, 1] to an i8 axis in [-127, 127]. */ +export function toAxis(v: number): number { + return Math.round(Math.max(-1, Math.min(1, v)) * 127); +} + +/** + * Accumulates frame time and fires `step` once per `1000 / hz` ms. Backlog + * is capped (a hidden tab must not burst dozens of inputs on return). + */ +export class FixedRate { + readonly intervalMs: number; + readonly #maxSteps: number; + #acc = 0; + #last: number | undefined; + + constructor(hz: number, maxStepsPerFrame = 4) { + this.intervalMs = 1000 / hz; + this.#maxSteps = maxStepsPerFrame; + } + + /** Call every frame with a monotonic time; returns steps fired. */ + advance(now: number, step: () => void): number { + if (this.#last === undefined) this.#last = now; + this.#acc += now - this.#last; + this.#last = now; + let steps = 0; + while (this.#acc >= this.intervalMs && steps < this.#maxSteps) { + this.#acc -= this.intervalMs; + step(); + steps += 1; + } + if (steps === this.#maxSteps) this.#acc = Math.min(this.#acc, this.intervalMs); + return steps; + } +} diff --git a/examples/game/client/src/shared/scene.ts b/examples/game/client/src/shared/scene.ts new file mode 100644 index 000000000..11f2b569d --- /dev/null +++ b/examples/game/client/src/shared/scene.ts @@ -0,0 +1,215 @@ +/** + * Babylon.js stage shared by the demos: engine + scene + light, a gridded + * floor, a third-person follow camera, DOM name labels and helpers. + * + * Coordinates: the server's 2D plane (x, y) maps to Babylon (x, 0, z = y), + * Y up. Use `toWorld(x, y, height)`. + */ +// Deep imports keep the bundle small (the package root pulls in everything). +import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera'; +import { Engine } from '@babylonjs/core/Engines/engine'; +import { DirectionalLight } from '@babylonjs/core/Lights/directionalLight'; +import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight'; +import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture'; +import { Color3, Color4 } from '@babylonjs/core/Maths/math.color'; +import { Matrix, Vector3 } from '@babylonjs/core/Maths/math.vector'; +import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; +import type { LinesMesh } from '@babylonjs/core/Meshes/linesMesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import { Scene } from '@babylonjs/core/scene'; +// Side effect: Mesh.prototype.createInstance. +import '@babylonjs/core/Meshes/instancedMesh'; + +export type Stage = Readonly<{ + engine: Engine; + scene: Scene; + camera: ArcRotateCamera; + labels: LabelLayer; + /** Ground-plane direction the camera looks along (game x/y), for camera-relative input. */ + cameraForward(): { x: number; y: number }; + /** Ease the camera target toward a game position. */ + follow(x: number, y: number, dtMs: number): void; + /** Register a per-frame callback (after input, before render). */ + onFrame(callback: (now: number, dtMs: number) => void): void; +}>; + +export type StageOptions = Readonly<{ + /** Floor half extent (m). */ + half: number; + /** Grid line spacing (m). */ + gridStep?: number; + background?: string; +}>; + +export function toWorld(x: number, y: number, height = 0): Vector3 { + return new Vector3(x, height, y); +} + +export function material(scene: Scene, name: string, color: string, alpha = 1): StandardMaterial { + const m = new StandardMaterial(name, scene); + m.diffuseColor = Color3.FromHexString(color); + m.specularColor = new Color3(0.1, 0.1, 0.1); + m.alpha = alpha; + return m; +} + +export function createStage(canvas: HTMLCanvasElement, options: StageOptions): Stage { + const engine = new Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); + const scene = new Scene(engine); + scene.clearColor = Color4.FromHexString(`${options.background ?? '#0e1116'}ff`); + + const hemi = new HemisphericLight('sky', new Vector3(0, 1, 0), scene); + hemi.intensity = 0.65; + const sun = new DirectionalLight('sun', new Vector3(-0.4, -1, 0.3), scene); + sun.intensity = 0.6; + + const camera = new ArcRotateCamera('camera', -Math.PI / 2, 0.95, 20, Vector3.Zero(), scene); + camera.lowerRadiusLimit = 6; + camera.upperRadiusLimit = 60; + camera.upperBetaLimit = 1.45; + camera.wheelDeltaPercentage = 0.02; + camera.attachControl(canvas, true); + // Arrow keys move the player, not the camera. + camera.inputs.removeByType('ArcRotateCameraKeyboardMoveInput'); + + createFloor(scene, options.half, options.gridStep ?? 1); + + const labels = new LabelLayer(canvas, scene, camera); + const frameCallbacks: ((now: number, dtMs: number) => void)[] = []; + let last = performance.now(); + engine.runRenderLoop(() => { + const now = performance.now(); + const dt = now - last; + last = now; + for (const callback of frameCallbacks) callback(now, dt); + scene.render(); + labels.update(); + }); + window.addEventListener('resize', () => engine.resize()); + + return { + engine, + scene, + camera, + labels, + cameraForward() { + return { x: -Math.cos(camera.alpha), y: -Math.sin(camera.alpha) }; + }, + follow(x, y, dtMs) { + const k = 1 - Math.exp(-dtMs / 120); + const t = camera.target; + camera.setTarget(new Vector3(t.x + (x - t.x) * k, 0, t.z + (y - t.z) * k)); + }, + onFrame(callback) { + frameCallbacks.push(callback); + } + }; +} + +function createFloor(scene: Scene, half: number, step: number): void { + const size = half * 2; + const ground = MeshBuilder.CreateGround('floor', { width: size, height: size }, scene); + const px = 2048; + const texture = new DynamicTexture('grid', { width: px, height: px }, scene, true); + const ctx = texture.getContext() as CanvasRenderingContext2D; + ctx.fillStyle = '#1a1f27'; + ctx.fillRect(0, 0, px, px); + const lines = Math.round(size / step); + for (let i = 0; i <= lines; i += 1) { + const p = (i / lines) * px; + const major = i % 5 === 0; + ctx.strokeStyle = major ? '#3a4556' : '#262d38'; + ctx.lineWidth = major ? 3 : 1.5; + ctx.beginPath(); + ctx.moveTo(p, 0); + ctx.lineTo(p, px); + ctx.moveTo(0, p); + ctx.lineTo(px, p); + ctx.stroke(); + } + texture.update(); + const m = new StandardMaterial('floor', scene); + m.diffuseTexture = texture; + m.specularColor = Color3.Black(); + ground.material = m; + + // Low walls on the border. + const wall = material(scene, 'wall', '#4b5668'); + const h = 0.6; + const t = 0.3; + for (const [x, z, w, d] of [ + [0, half + t / 2, size + 2 * t, t], + [0, -half - t / 2, size + 2 * t, t], + [half + t / 2, 0, t, size], + [-half - t / 2, 0, t, size] + ] as const) { + const box = MeshBuilder.CreateBox('wall', { width: w, depth: d, height: h }, scene); + box.position = new Vector3(x, h / 2, z); + box.material = wall; + } +} + +/** A flat ring (e.g. an interest radius) on the floor; move it with `.position`. */ +export function createRing(scene: Scene, radius: number, color: string): LinesMesh { + const points: Vector3[] = []; + for (let i = 0; i <= 96; i += 1) { + const a = (i / 96) * Math.PI * 2; + points.push(new Vector3(Math.cos(a) * radius, 0.03, Math.sin(a) * radius)); + } + const ring = MeshBuilder.CreateLines('ring', { points }, scene); + ring.color = Color3.FromHexString(color); + return ring; +} + +/** HTML labels that follow meshes (cheap, crisp, no GUI dependency). */ +export class LabelLayer { + readonly #root: HTMLDivElement; + readonly #labels = new Map(); + readonly #scene: Scene; + readonly #camera: ArcRotateCamera; + + constructor(canvas: HTMLCanvasElement, scene: Scene, camera: ArcRotateCamera) { + this.#scene = scene; + this.#camera = camera; + this.#root = document.createElement('div'); + this.#root.className = 'labels'; + canvas.parentElement?.appendChild(this.#root); + } + + set(key: string, mesh: AbstractMesh, text: string, offset = 2.2, className = ''): void { + let label = this.#labels.get(key); + if (label === undefined) { + const el = document.createElement('div'); + this.#root.appendChild(el); + label = { el, mesh, offset }; + this.#labels.set(key, label); + } + label.mesh = mesh; + label.offset = offset; + if (label.el.textContent !== text) label.el.textContent = text; + const cls = `label ${className}`.trim(); + if (label.el.className !== cls) label.el.className = cls; + } + + delete(key: string): void { + this.#labels.get(key)?.el.remove(); + this.#labels.delete(key); + } + + update(): void { + const engine = this.#scene.getEngine(); + const width = engine.getRenderWidth(); + const height = engine.getRenderHeight(); + const scale = engine.getHardwareScalingLevel(); + const viewport = this.#camera.viewport.toGlobal(width, height); + const transform = this.#scene.getTransformMatrix(); + for (const { el, mesh, offset } of this.#labels.values()) { + const world = mesh.getAbsolutePosition().add(new Vector3(0, offset, 0)); + const p = Vector3.Project(world, Matrix.IdentityReadOnly, transform, viewport); + const visible = p.z > 0 && p.z < 1 && mesh.isEnabled(); + el.style.display = visible ? '' : 'none'; + if (visible) el.style.transform = `translate(${p.x * scale}px, ${p.y * scale}px) translate(-50%, -100%)`; + } + } +} diff --git a/examples/game/client/src/shared/style.css b/examples/game/client/src/shared/style.css new file mode 100644 index 000000000..ef9b11f88 --- /dev/null +++ b/examples/game/client/src/shared/style.css @@ -0,0 +1,116 @@ +:root { + color-scheme: dark; + --bg: #0e1116; + --panel: rgba(16, 20, 27, 0.86); + --text: #d7dde8; + --muted: #8793a6; + --accent: #6cc4ff; + font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; +} +html, +body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + overflow: hidden; +} +.stage { + position: fixed; + inset: 0; +} +.stage canvas { + width: 100%; + height: 100%; + display: block; + outline: none; + touch-action: none; +} +.labels { + position: absolute; + inset: 0; + pointer-events: none; + overflow: hidden; +} +.label { + position: absolute; + left: 0; + top: 0; + padding: 1px 6px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.55); + white-space: nowrap; + font-size: 12px; +} +.label.me { + color: var(--accent); +} +.hud { + position: fixed; + top: 12px; + left: 12px; + width: 300px; + max-height: calc(100% - 24px); + overflow: auto; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.hud h1 { + margin: 0 0 4px; + font-size: 15px; +} +.hud .hint { + margin: 0 0 8px; + color: var(--muted); +} +.hud dl { + display: grid; + grid-template-columns: auto 1fr; + gap: 2px 10px; + margin: 0 0 8px; +} +.hud dt { + color: var(--muted); +} +.hud dd { + margin: 0; + text-align: right; +} +.hud .toggle { + display: block; + margin: 4px 0; + cursor: pointer; +} +.hud fieldset { + margin: 8px 0 0; + border: 1px solid #2a3240; + border-radius: 6px; +} +.hud .slider { + display: grid; + grid-template-columns: 1fr; + margin: 4px 0; +} +.hud .slider output { + color: var(--accent); +} +.hud small { + color: var(--muted); +} +.index { + max-width: 760px; + margin: 40px auto; + padding: 0 16px; + overflow: auto; +} +.index a { + color: var(--accent); +} +@media (max-width: 640px) { + .hud { + width: calc(100% - 24px); + max-height: 45%; + } +} diff --git a/examples/game/client/tests/arena-headless.test.mjs b/examples/game/client/tests/arena-headless.test.mjs new file mode 100644 index 000000000..67ad215ed --- /dev/null +++ b/examples/game/client/tests/arena-headless.test.mjs @@ -0,0 +1,98 @@ +/** + * Headless Arena client (Node, no browser): dev ticket → join → move with + * prediction; the server agrees with the predicted position; NetSim control + * changes the measured RTT. Starts the real `game-demos arena` binary. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createArenaClient } from '../src/arena/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { stateFromFields, step } from '../src/arena/movement.ts'; +import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; + +test('headless client joins the arena and moves with exact prediction', { timeout: 600_000 }, async () => { + const server = await startDemo('arena'); + const clients = []; + try { + const api = new DevApi({ base: server.httpUrl, name: () => 'Headless', storage: memoryStorage() }); + const arena = createArenaClient({ api, base: server.httpUrl }); + clients.push(arena.client); + const { client } = arena; + const welcome = await client.connect('arena-1'); + assert.equal(welcome.tickRate, 30); + assert.deepEqual(welcome.schema.kinds.map((k) => k.name), ['player', 'drone', 'pillar']); + const hello = await arena.ready; + assert.equal(hello.viewRadius, 14); + assert.ok(api.last.principal.startsWith('guest-'), 'server-generated principal'); + await until(() => client.predictor.active, 5_000, 'own entity bound'); + const start = stateFromFields(client.predictor.predicted()); + + // 30 command frames forward + right at the server's tick rate. + const input = { mx: 90, my: 90, buttons: 0 }; + let expected = start; + for (let i = 0; i < 30; i += 1) { + client.sendInput(input); + expected = step(expected, input); + await sleep(1000 / 30); + } + const predicted = stateFromFields(client.predictor.predicted()); + assert.deepEqual(predicted, expected, 'prediction applies the shared step immediately'); + await until(() => client.predictor.lastAck >= 30 && client.predictor.pending.length === 0, 5_000, 'acks'); + const server_ = stateFromFields(client.authority.replica.get(hello.entity).fields); + assert.deepEqual(server_, expected, 'authoritative state equals the prediction bit for bit'); + assert.ok(Math.hypot(server_.x - start.x, server_.y - start.y) > 3, 'moved'); + + // Interpolated world: name label, drones and global pillars are visible. + await sleep(150); + const rendered = client.render(); + const me = rendered.find((e) => e.id === hello.entity); + assert.equal(me.fields.name, 'Headless'); + assert.ok(me.predicted); + assert.equal(rendered.filter((e) => e.kindName === 'pillar').length, 9); + assert.ok(rendered.some((e) => e.kindName === 'drone')); + const stats = client.authority.connection.stats; + assert.ok(stats.deltasIn > 10 && stats.deltaBytesIn > 0); + + // Server-side NetSim raises the RTT the clock measures. + const connection = client.authority.connection; + await until(() => connection.clock.synced, 5_000, 'clock'); + const base = connection.clock.rtt; + await api.setNetSim({ latencyMs: 60, jitterMs: 0, loss: 0 }); + await until(() => connection.clock.samples.at(-1)?.rtt >= 110, 10_000, 'rtt with netsim'); + assert.ok(connection.clock.samples.at(-1).rtt > base + 100); + await api.setNetSim({ latencyMs: 0, jitterMs: 0, loss: 0 }); + assert.deepEqual(await api.getNetSim(), { latencyMs: 0, jitterMs: 0, loss: 0 }); + + // A second guest: interest management hides the first one while it is + // beyond the view radius; walking toward it makes it appear, + // interpolated (not predicted) with its display name. + const other = createArenaClient({ + api: new DevApi({ base: server.httpUrl, name: () => 'Other', storage: memoryStorage() }), + base: server.httpUrl + }); + clients.push(other.client); + await other.client.connect('arena-1'); + const otherHello = await other.ready; + await until(() => other.client.predictor.active, 5_000, 'second entity bound'); + const sees = () => + other.client.render().some((e) => e.id === hello.entity && !e.predicted && e.fields.name === 'Headless'); + const deadline = Date.now() + 10_000; + while (!sees() && Date.now() < deadline) { + const at = stateFromFields(other.client.predictor.predicted()); + const dx = server_.x - at.x; + const dy = server_.y - at.y; + const d = Math.hypot(dx, dy); + if (d > otherHello.viewRadius + 2) { + assert.ok(!other.client.authority.replica.has(hello.entity), 'out of view radius: not replicated'); + } + const k = d > 1 ? 127 / d : 0; + other.client.sendInput({ mx: Math.round(dx * k), my: Math.round(dy * k), buttons: 0 }); + await sleep(1000 / 30); + } + assert.ok(sees(), 'remote player visible once within the view radius'); + } finally { + for (const c of clients) c.close(); + await server.stop(); + } +}); diff --git a/examples/game/client/tests/helpers/demo-server.mjs b/examples/game/client/tests/helpers/demo-server.mjs new file mode 100644 index 000000000..051e51897 --- /dev/null +++ b/examples/game/client/tests/helpers/demo-server.mjs @@ -0,0 +1,57 @@ +/** + * Start a `game-demos ` server for a Node test (port 0, dev routes on) + * and stop it afterwards. Uses GAME_DEMOS_BIN when set (run.sh builds it), + * else `cargo run` in ../server (compiles on first use). + */ +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const SERVER_DIR = fileURLToPath(new URL('../../../server/', import.meta.url)); + +export async function startDemo(demo, { env = {} } = {}) { + const bin = process.env.GAME_DEMOS_BIN; + const args = [demo, '--port', '0', '--dev']; + const child = bin + ? spawn(bin, args, { env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'inherit'] }) + : spawn('cargo', ['run', '-q', '--', ...args], { + cwd: SERVER_DIR, + env: { ...process.env, ...env }, + stdio: ['ignore', 'pipe', 'inherit'] + }); + const httpUrl = await new Promise((resolve, reject) => { + let buffered = ''; + child.stdout.on('data', (chunk) => { + buffered += chunk; + const match = /LISTENING (http:\/\/\S+)/.exec(buffered); + if (match) resolve(match[1]); + }); + child.on('exit', (code) => reject(new Error(`game-demos ${demo} exited with ${code}`))); + }); + return { + httpUrl, + async stop() { + if (child.exitCode !== null) return; + const exited = new Promise((resolve) => child.on('exit', resolve)); + child.kill('SIGTERM'); + const timer = setTimeout(() => child.kill('SIGKILL'), 5000); + await exited; + clearTimeout(timer); + } + }; +} + +export async function until(predicate, timeoutMs = 10_000, what = 'condition') { + const start = Date.now(); + while (!predicate()) { + if (Date.now() - start > timeoutMs) throw new Error(`timed out waiting for ${what}`); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + +export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** In-memory Storage for DevApi in Node. */ +export function memoryStorage() { + const map = new Map(); + return { getItem: (k) => map.get(k) ?? null, setItem: (k, v) => map.set(k, String(v)) }; +} diff --git a/examples/game/client/tests/movement-parity.test.mjs b/examples/game/client/tests/movement-parity.test.mjs new file mode 100644 index 000000000..476ef7b4d --- /dev/null +++ b/examples/game/client/tests/movement-parity.test.mjs @@ -0,0 +1,58 @@ +/** + * Rust ↔ TypeScript parity of the Arena movement step: replays the fixture + * written by `server/tests/movement_fixture.rs` through `src/arena/movement.ts` + * (Node strips the types). Prediction is only exact if this passes. + */ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +import * as movement from '../src/arena/movement.ts'; + +const fixture = JSON.parse( + readFileSync(new URL('../../fixtures/arena-movement.json', import.meta.url), 'utf8') +); +const EPSILON = 1e-4; + +test('constants and wire quantization match the Rust side', () => { + const c = fixture.constants; + assert.equal(Math.fround(c.dt), movement.DT); + assert.equal(c.half, movement.HALF); + assert.equal(c.playerRadius, movement.PLAYER_RADIUS); + assert.equal(c.maxSpeed, movement.MAX_SPEED); + assert.equal(c.accel, movement.ACCEL); + assert.equal(c.dashSpeed, movement.DASH_SPEED); + assert.equal(c.dashFrames, movement.DASH_FRAMES); + assert.equal(c.dashCooldown, movement.DASH_COOLDOWN); + assert.deepEqual(c.pillars, movement.PILLARS.map((p) => [...p])); + const byName = Object.fromEntries(fixture.fields.map((field) => [field.name, field])); + for (const [name, quant] of [['x', movement.POS], ['y', movement.POS], ['vx', movement.VEL], ['vy', movement.VEL]]) { + assert.deepEqual( + { min: byName[name].min, max: byName[name].max, bits: byName[name].bits }, + { ...quant }, + name + ); + } +}); + +test('the TypeScript step reproduces every Rust state', () => { + const toState = (s) => ({ x: s.x, y: s.y, vx: s.vx, vy: s.vy, dash: s.dash, cooldown: s.cd }); + let state = toState(fixture.start); + let exact = 0; + let maxError = 0; + fixture.steps.forEach(({ input, state: expected }, i) => { + state = movement.step(state, { mx: input[0], my: input[1], buttons: input[2] }); + const want = toState(expected); + for (const key of ['x', 'y', 'vx', 'vy']) { + const error = Math.abs(state[key] - Math.fround(want[key])); + maxError = Math.max(maxError, error); + assert.ok(error <= EPSILON, `step ${i} ${key}: ts ${state[key]} rust ${want[key]}`); + } + assert.equal(state.dash, want.dash, `step ${i} dash`); + assert.equal(state.cooldown, want.cooldown, `step ${i} cooldown`); + if (['x', 'y', 'vx', 'vy'].every((k) => state[k] === Math.fround(want[k]))) exact += 1; + }); + assert.ok(fixture.steps.length > 300); + // Binary32 discipline makes the twins bit-identical, not just close. + assert.equal(exact, fixture.steps.length, `bit-exact ${exact}/${fixture.steps.length}, max error ${maxError}`); +}); diff --git a/examples/game/client/tsconfig.json b/examples/game/client/tsconfig.json new file mode 100644 index 000000000..7362d1d85 --- /dev/null +++ b/examples/game/client/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": [], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src/**/*.ts"] +} diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts new file mode 100644 index 000000000..62082e6cb --- /dev/null +++ b/examples/game/client/vite.config.ts @@ -0,0 +1,32 @@ +// Multi-page Vite app: `/` lists the demos, `//` is one demo. +// Add a demo: create `/index.html` + `src//main.ts` and list it +// in DEMOS. In dev, game traffic is proxied to the Rust `game-demos` server +// (GAME_DEMOS_SERVER, default http://127.0.0.1:2567). +import { resolve } from 'node:path'; +import { defineConfig } from 'vite'; + +const DEMOS = ['arena']; +const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; + +export default defineConfig({ + server: { + port: Number(process.env.GAME_DEMOS_CLIENT_PORT ?? 5173), + strictPort: true, + proxy: { + '/zones': { target: server, ws: true }, + '/dev': server, + '/metrics': server + }, + // The SDK is a symlinked local package (file:../../../js). + fs: { allow: [resolve(__dirname, '..'), resolve(__dirname, '../../../js')] } + }, + build: { + chunkSizeWarningLimit: 2000, + rollupOptions: { + input: Object.fromEntries([ + ['index', resolve(__dirname, 'index.html')], + ...DEMOS.map((demo) => [demo, resolve(__dirname, `${demo}/index.html`)]) + ]) + } + } +}); diff --git a/examples/game/fixtures/arena-movement.json b/examples/game/fixtures/arena-movement.json new file mode 100644 index 000000000..1c10b51c0 --- /dev/null +++ b/examples/game/fixtures/arena-movement.json @@ -0,0 +1,364 @@ +{ + "description": "Arena movement parity: Rust movement::step vs client/src/arena/movement.ts", + "constants": {"accel":40.0,"dashCooldown":45,"dashFrames":6,"dashSpeed":14.0,"dt":0.03333333507180214,"half":20.0,"maxSpeed":5.0,"pillars":[[0.0,0.0,2.5],[-9.0,-9.0,1.5],[9.0,-9.0,1.5],[-9.0,9.0,1.5],[9.0,9.0,1.5],[0.0,-14.0,1.0],[0.0,14.0,1.0],[-14.0,0.0,1.0],[14.0,0.0,1.0]],"playerRadius":0.5}, + "fields": [{"bits":18,"max":19.999847412109375,"min":-20.0,"name":"x","type":"quant_f32"},{"bits":18,"max":19.999847412109375,"min":-20.0,"name":"y","type":"quant_f32"},{"bits":12,"max":15.9921875,"min":-16.0,"name":"vx","type":"quant_f32"},{"bits":12,"max":15.9921875,"min":-16.0,"name":"vy","type":"quant_f32"}], + "start": {"cd":0,"dash":0,"vx":0.0,"vy":0.0,"x":-5.0,"y":-5.0}, + "steps": [ + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":1.3359375,"vy":0.0,"x":-4.955596923828125,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":2.671875,"vy":0.0,"x":-4.86663818359375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":4.0078125,"vy":0.0,"x":-4.733123779296875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.566497802734375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.399871826171875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.233245849609375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.066619873046875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.899993896484375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.733367919921875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.566741943359375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.400115966796875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.233489990234375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.066864013671875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.900238037109375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.733612060546875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.566986083984375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.400360107421875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.233734130859375,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.067108154296875,"y":-5.0}}, + {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-1.900482177734375,"y":-5.0}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":4.4921875,"vy":1.234375,"x":-1.75079345703125,"y":-4.958953857421875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.9765625,"vy":2.46875,"x":-1.6180419921875,"y":-4.876708984375}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.500244140625,"y":-4.7589111328125}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.3824462890625,"y":-4.64111328125}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.2646484375,"y":-4.5233154296875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.1468505859375,"y":-4.405517578125}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.029052734375,"y":-4.2877197265625}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.9112548828125,"y":-4.169921875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.79345703125,"y":-4.0521240234375}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.6756591796875,"y":-3.934326171875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.557861328125,"y":-3.8165283203125}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.4400634765625,"y":-3.69873046875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.322265625,"y":-3.5809326171875}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.2044677734375,"y":-3.463134765625}}, + {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.086669921875,"y":-3.3453369140625}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":3.0546875,"vy":2.296875,"x":0.015106201171875,"y":-3.26873779296875}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":2.5703125,"vy":1.0546875,"x":0.100860595703125,"y":-3.233642578125}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":2.0859375,"vy":-0.1875,"x":0.170440673828125,"y":-3.239898681640625}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.6015625,"vy":-1.4296875,"x":0.223846435546875,"y":-3.28765869140625}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.263214111328125,"y":-3.37158203125}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.302581787109375,"y":-3.45550537109375}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.341949462890625,"y":-3.5394287109375}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.381317138671875,"y":-3.62335205078125}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.420684814453125,"y":-3.707275390625}}, + {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.460052490234375,"y":-3.79119873046875}}, + {"input":[0,0,1],"state":{"cd":45,"dash":5,"vx":5.9296875,"vy":-12.6796875,"x":0.65765380859375,"y":-4.214019775390625}}, + {"input":[0,0,0],"state":{"cd":44,"dash":4,"vx":5.9296875,"vy":-12.6796875,"x":0.855255126953125,"y":-4.636688232421875}}, + {"input":[0,0,0],"state":{"cd":43,"dash":3,"vx":5.9296875,"vy":-12.6796875,"x":1.0528564453125,"y":-5.059356689453125}}, + {"input":[0,0,0],"state":{"cd":42,"dash":2,"vx":5.9296875,"vy":-12.6796875,"x":1.250457763671875,"y":-5.482025146484375}}, + {"input":[0,0,0],"state":{"cd":41,"dash":1,"vx":5.9296875,"vy":-12.6796875,"x":1.44805908203125,"y":-5.904693603515625}}, + {"input":[0,0,0],"state":{"cd":40,"dash":0,"vx":5.9296875,"vy":-12.6796875,"x":1.645660400390625,"y":-6.327362060546875}}, + {"input":[0,0,0],"state":{"cd":39,"dash":0,"vx":5.3671875,"vy":-11.46875,"x":1.824493408203125,"y":-6.709747314453125}}, + {"input":[0,0,0],"state":{"cd":38,"dash":0,"vx":4.8046875,"vy":-10.2578125,"x":1.98455810546875,"y":-7.051849365234375}}, + {"input":[0,0,0],"state":{"cd":37,"dash":0,"vx":4.2421875,"vy":-9.046875,"x":2.1258544921875,"y":-7.353515625}}, + {"input":[0,0,0],"state":{"cd":36,"dash":0,"vx":3.6796875,"vy":-7.8359375,"x":2.248382568359375,"y":-7.614898681640625}}, + {"input":[0,0,0],"state":{"cd":35,"dash":0,"vx":3.109375,"vy":-6.6328125,"x":2.352142333984375,"y":-7.835845947265625}}, + {"input":[0,0,0],"state":{"cd":34,"dash":0,"vx":2.546875,"vy":-5.421875,"x":2.436981201171875,"y":-8.01666259765625}}, + {"input":[0,0,0],"state":{"cd":33,"dash":0,"vx":1.9765625,"vy":-4.21875,"x":2.5030517578125,"y":-8.157196044921875}}, + {"input":[-127,0,1],"state":{"cd":32,"dash":0,"vx":0.8359375,"vy":-3.53125,"x":2.530975341796875,"y":-8.27484130859375}}, + {"input":[-127,0,1],"state":{"cd":31,"dash":0,"vx":-0.3046875,"vy":-2.84375,"x":2.520751953125,"y":-8.369598388671875}}, + {"input":[-127,0,1],"state":{"cd":30,"dash":0,"vx":-1.4453125,"vy":-2.15625,"x":2.4725341796875,"y":-8.441314697265625}}, + {"input":[-127,0,1],"state":{"cd":29,"dash":0,"vx":-2.5859375,"vy":-1.4609375,"x":2.386322021484375,"y":-8.490142822265625}}, + {"input":[-127,0,1],"state":{"cd":28,"dash":0,"vx":-3.7265625,"vy":-0.7734375,"x":2.262115478515625,"y":-8.515777587890625}}, + {"input":[-127,0,1],"state":{"cd":27,"dash":0,"vx":-4.8671875,"vy":-0.078125,"x":2.09991455078125,"y":-8.518524169921875}}, + {"input":[-127,0,1],"state":{"cd":26,"dash":0,"vx":-5.0,"vy":0.0,"x":1.93328857421875,"y":-8.518524169921875}}, + {"input":[-127,0,1],"state":{"cd":25,"dash":0,"vx":-5.0,"vy":0.0,"x":1.76666259765625,"y":-8.518524169921875}}, + {"input":[-128,5,0],"state":{"cd":24,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.600189208984375,"y":-8.511962890625}}, + {"input":[-128,5,0],"state":{"cd":23,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.4337158203125,"y":-8.505401611328125}}, + {"input":[-128,5,0],"state":{"cd":22,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.267242431640625,"y":-8.49884033203125}}, + {"input":[-128,5,0],"state":{"cd":21,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.10076904296875,"y":-8.492279052734375}}, + {"input":[-128,5,0],"state":{"cd":20,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.934295654296875,"y":-8.4857177734375}}, + {"input":[-128,5,0],"state":{"cd":19,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.767822265625,"y":-8.479156494140625}}, + {"input":[-128,5,0],"state":{"cd":18,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.601348876953125,"y":-8.47259521484375}}, + {"input":[-128,5,0],"state":{"cd":17,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.43487548828125,"y":-8.466033935546875}}, + {"input":[-128,5,0],"state":{"cd":16,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.268402099609375,"y":-8.45947265625}}, + {"input":[-128,5,0],"state":{"cd":15,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.1019287109375,"y":-8.452911376953125}}, + {"input":[-128,5,0],"state":{"cd":14,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.064544677734375,"y":-8.44635009765625}}, + {"input":[-128,5,0],"state":{"cd":13,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.23101806640625,"y":-8.439788818359375}}, + {"input":[-128,5,0],"state":{"cd":12,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.397491455078125,"y":-8.4332275390625}}, + {"input":[-128,5,0],"state":{"cd":11,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.56396484375,"y":-8.426666259765625}}, + {"input":[-128,5,0],"state":{"cd":10,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.730438232421875,"y":-8.42010498046875}}, + {"input":[-128,5,0],"state":{"cd":9,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.89691162109375,"y":-8.413543701171875}}, + {"input":[-128,5,0],"state":{"cd":8,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.063385009765625,"y":-8.406982421875}}, + {"input":[-128,5,0],"state":{"cd":7,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.2298583984375,"y":-8.400421142578125}}, + {"input":[-128,5,0],"state":{"cd":6,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.396331787109375,"y":-8.39385986328125}}, + {"input":[-128,5,0],"state":{"cd":5,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.56280517578125,"y":-8.387298583984375}}, + {"input":[-128,5,0],"state":{"cd":4,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.729278564453125,"y":-8.3807373046875}}, + {"input":[-128,5,0],"state":{"cd":3,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.895751953125,"y":-8.374176025390625}}, + {"input":[-128,5,0],"state":{"cd":2,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.062225341796875,"y":-8.36761474609375}}, + {"input":[-128,5,0],"state":{"cd":1,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.22869873046875,"y":-8.361053466796875}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.395172119140625,"y":-8.3544921875}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.5616455078125,"y":-8.347930908203125}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.728118896484375,"y":-8.34136962890625}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.89459228515625,"y":-8.334808349609375}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.061065673828125,"y":-8.3282470703125}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.2275390625,"y":-8.321685791015625}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.394012451171875,"y":-8.31512451171875}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.56048583984375,"y":-8.308563232421875}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.726959228515625,"y":-8.302001953125}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.8934326171875,"y":-8.295440673828125}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.059906005859375,"y":-8.28887939453125}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.22637939453125,"y":-8.282318115234375}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.392852783203125,"y":-8.2757568359375}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.559326171875,"y":-8.269195556640625}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.725799560546875,"y":-8.26263427734375}}, + {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.89227294921875,"y":-8.256072998046875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-3.7578125,"vy":0.6796875,"x":-5.017547607421875,"y":-8.23333740234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-2.515625,"vy":1.1640625,"x":-5.101470947265625,"y":-8.194427490234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-1.2734375,"vy":1.6484375,"x":-5.143890380859375,"y":-8.13934326171875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-0.03125,"vy":2.1328125,"x":-5.14495849609375,"y":-8.068084716796875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":1.2109375,"vy":2.6171875,"x":-5.10467529296875,"y":-7.98065185546875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":2.453125,"vy":3.109375,"x":-5.023040771484375,"y":-7.877044677734375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.905242919921875,"y":-7.759246826171875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.787445068359375,"y":-7.641448974609375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.669647216796875,"y":-7.523651123046875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.551849365234375,"y":-7.405853271484375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.434051513671875,"y":-7.288055419921875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.316253662109375,"y":-7.170257568359375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.198455810546875,"y":-7.052459716796875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.080657958984375,"y":-6.934661865234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.962860107421875,"y":-6.816864013671875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.845062255859375,"y":-6.699066162109375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.727264404296875,"y":-6.581268310546875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.609466552734375,"y":-6.463470458984375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.491668701171875,"y":-6.345672607421875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.373870849609375,"y":-6.227874755859375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.256072998046875,"y":-6.110076904296875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.138275146484375,"y":-5.992279052734375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.020477294921875,"y":-5.874481201171875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.902679443359375,"y":-5.756683349609375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.784881591796875,"y":-5.638885498046875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.667083740234375,"y":-5.521087646484375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.549285888671875,"y":-5.403289794921875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.431488037109375,"y":-5.285491943359375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.313690185546875,"y":-5.167694091796875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.195892333984375,"y":-5.049896240234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.078094482421875,"y":-4.932098388671875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.960296630859375,"y":-4.814300537109375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.842498779296875,"y":-4.696502685546875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.724700927734375,"y":-4.578704833984375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.606903076171875,"y":-4.460906982421875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.489105224609375,"y":-4.343109130859375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.371307373046875,"y":-4.225311279296875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.253509521484375,"y":-4.107513427734375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.135711669921875,"y":-3.989715576171875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.017913818359375,"y":-3.871917724609375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.900115966796875,"y":-3.754119873046875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.782318115234375,"y":-3.636322021484375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.664520263671875,"y":-3.518524169921875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.546722412109375,"y":-3.400726318359375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.428924560546875,"y":-3.282928466796875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.311126708984375,"y":-3.165130615234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.193328857421875,"y":-3.047332763671875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.4453125,"vy":-0.0859375,"x":-0.07720947265625,"y":-2.99896240234375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.4921875,"vy":0.046875,"x":0.03936767578125,"y":-2.999725341796875}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5703125,"vy":0.1875,"x":0.158538818359375,"y":-2.995758056640625}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.6640625,"vy":0.34375,"x":0.28106689453125,"y":-2.98675537109375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.765625,"vy":0.515625,"x":0.4071044921875,"y":-2.972259521484375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.875,"vy":0.703125,"x":0.536651611328125,"y":-2.95166015625}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.96875,"vy":0.90625,"x":0.669708251953125,"y":-2.924346923828125}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.0546875,"vy":1.1328125,"x":0.805816650390625,"y":-2.88970947265625}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.125,"vy":1.3671875,"x":0.94451904296875,"y":-2.847442626953125}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1796875,"vy":1.6171875,"x":1.085052490234375,"y":-2.79693603515625}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.203125,"vy":1.8828125,"x":1.226654052734375,"y":-2.73773193359375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1953125,"vy":2.15625,"x":1.368560791015625,"y":-2.669677734375}}, + {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1640625,"vy":2.421875,"x":1.509552001953125,"y":-2.592620849609375}}, + {"input":[0,127,1],"state":{"cd":45,"dash":5,"vx":6.609375,"vy":4.6953125,"x":1.736907958984375,"y":-2.446136474609375}}, + {"input":[0,127,1],"state":{"cd":44,"dash":4,"vx":6.609375,"vy":4.6953125,"x":1.957244873046875,"y":-2.289581298828125}}, + {"input":[0,127,1],"state":{"cd":43,"dash":3,"vx":6.609375,"vy":4.6953125,"x":2.177581787109375,"y":-2.133026123046875}}, + {"input":[0,127,1],"state":{"cd":42,"dash":2,"vx":6.609375,"vy":4.6953125,"x":2.397918701171875,"y":-1.976470947265625}}, + {"input":[0,127,1],"state":{"cd":41,"dash":1,"vx":6.609375,"vy":4.6953125,"x":2.618255615234375,"y":-1.819915771484375}}, + {"input":[0,127,1],"state":{"cd":40,"dash":0,"vx":6.609375,"vy":4.6953125,"x":2.838592529296875,"y":-1.663360595703125}}, + {"input":[0,127,1],"state":{"cd":39,"dash":0,"vx":5.28125,"vy":4.7578125,"x":3.0145263671875,"y":-1.50482177734375}}, + {"input":[0,127,1],"state":{"cd":38,"dash":0,"vx":3.953125,"vy":4.8203125,"x":3.146209716796875,"y":-1.344146728515625}}, + {"input":[0,127,1],"state":{"cd":37,"dash":0,"vx":2.625,"vy":4.8828125,"x":3.233642578125,"y":-1.181488037109375}}, + {"input":[0,127,1],"state":{"cd":36,"dash":0,"vx":1.296875,"vy":4.9453125,"x":3.27667236328125,"y":-1.016693115234375}}, + {"input":[0,127,1],"state":{"cd":35,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.850067138671875}}, + {"input":[0,127,1],"state":{"cd":34,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.683441162109375}}, + {"input":[0,127,1],"state":{"cd":33,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.516815185546875}}, + {"input":[0,127,1],"state":{"cd":32,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.350189208984375}}, + {"input":[0,127,1],"state":{"cd":31,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.183563232421875}}, + {"input":[0,127,1],"state":{"cd":30,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.016937255859375}}, + {"input":[0,127,1],"state":{"cd":29,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.149688720703125}}, + {"input":[0,127,1],"state":{"cd":28,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.316314697265625}}, + {"input":[0,127,1],"state":{"cd":27,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.482940673828125}}, + {"input":[0,127,1],"state":{"cd":26,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.649566650390625}}, + {"input":[0,127,1],"state":{"cd":25,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.816192626953125}}, + {"input":[0,127,1],"state":{"cd":24,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.982818603515625}}, + {"input":[0,127,1],"state":{"cd":23,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.149444580078125}}, + {"input":[0,127,1],"state":{"cd":22,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.316070556640625}}, + {"input":[0,127,1],"state":{"cd":21,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.482696533203125}}, + {"input":[0,127,1],"state":{"cd":20,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.649322509765625}}, + {"input":[0,127,1],"state":{"cd":19,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.815948486328125}}, + {"input":[0,127,1],"state":{"cd":18,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.982574462890625}}, + {"input":[0,127,1],"state":{"cd":17,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.149200439453125}}, + {"input":[0,127,1],"state":{"cd":16,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.315826416015625}}, + {"input":[0,127,1],"state":{"cd":15,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.482452392578125}}, + {"input":[0,127,1],"state":{"cd":14,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.649078369140625}}, + {"input":[0,127,1],"state":{"cd":13,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.815704345703125}}, + {"input":[0,127,1],"state":{"cd":12,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.982330322265625}}, + {"input":[0,127,1],"state":{"cd":11,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.148956298828125}}, + {"input":[0,127,1],"state":{"cd":10,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.315582275390625}}, + {"input":[0,127,1],"state":{"cd":9,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.482208251953125}}, + {"input":[0,127,1],"state":{"cd":8,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.648834228515625}}, + {"input":[0,127,1],"state":{"cd":7,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.815460205078125}}, + {"input":[0,127,1],"state":{"cd":6,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.982086181640625}}, + {"input":[0,127,1],"state":{"cd":5,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.148712158203125}}, + {"input":[0,127,1],"state":{"cd":4,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.315338134765625}}, + {"input":[0,127,1],"state":{"cd":3,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.481964111328125}}, + {"input":[0,127,1],"state":{"cd":2,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.648590087890625}}, + {"input":[0,127,1],"state":{"cd":1,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.815216064453125}}, + {"input":[0,127,1],"state":{"cd":45,"dash":5,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":5.281829833984375}}, + {"input":[0,127,1],"state":{"cd":44,"dash":4,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":5.748443603515625}}, + {"input":[0,127,1],"state":{"cd":43,"dash":3,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":6.215057373046875}}, + {"input":[0,127,1],"state":{"cd":42,"dash":2,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":6.681671142578125}}, + {"input":[0,127,1],"state":{"cd":41,"dash":1,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":7.148284912109375}}, + {"input":[0,127,1],"state":{"cd":40,"dash":0,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":7.614898681640625}}, + {"input":[0,127,1],"state":{"cd":39,"dash":0,"vx":0.0,"vy":12.6640625,"x":3.27667236328125,"y":8.037109375}}, + {"input":[0,127,1],"state":{"cd":38,"dash":0,"vx":0.0,"vy":11.328125,"x":3.27667236328125,"y":8.414764404296875}}, + {"input":[0,127,1],"state":{"cd":37,"dash":0,"vx":0.0,"vy":9.9921875,"x":3.27667236328125,"y":8.74786376953125}}, + {"input":[0,127,1],"state":{"cd":36,"dash":0,"vx":0.0,"vy":8.65625,"x":3.27667236328125,"y":9.03656005859375}}, + {"input":[0,127,1],"state":{"cd":35,"dash":0,"vx":0.0,"vy":7.3203125,"x":3.27667236328125,"y":9.28070068359375}}, + {"input":[0,127,1],"state":{"cd":34,"dash":0,"vx":0.0,"vy":5.984375,"x":3.27667236328125,"y":9.48028564453125}}, + {"input":[0,127,1],"state":{"cd":33,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.64691162109375}}, + {"input":[0,127,1],"state":{"cd":32,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.81353759765625}}, + {"input":[0,127,1],"state":{"cd":31,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.98016357421875}}, + {"input":[0,127,1],"state":{"cd":30,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.14678955078125}}, + {"input":[0,127,1],"state":{"cd":29,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.31341552734375}}, + {"input":[0,127,1],"state":{"cd":28,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.48004150390625}}, + {"input":[0,127,1],"state":{"cd":27,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.64666748046875}}, + {"input":[0,127,1],"state":{"cd":26,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.81329345703125}}, + {"input":[0,127,1],"state":{"cd":25,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.97991943359375}}, + {"input":[0,127,1],"state":{"cd":24,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.14654541015625}}, + {"input":[0,127,1],"state":{"cd":23,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.31317138671875}}, + {"input":[0,127,1],"state":{"cd":22,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.47979736328125}}, + {"input":[0,127,1],"state":{"cd":21,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.64642333984375}}, + {"input":[0,-127,0],"state":{"cd":20,"dash":0,"vx":0.0,"vy":3.6640625,"x":3.27667236328125,"y":11.768646240234375}}, + {"input":[0,-127,0],"state":{"cd":19,"dash":0,"vx":0.0,"vy":2.328125,"x":3.27667236328125,"y":11.8463134765625}}, + {"input":[0,-127,0],"state":{"cd":18,"dash":0,"vx":0.0,"vy":0.9921875,"x":3.27667236328125,"y":11.879425048828125}}, + {"input":[0,-127,0],"state":{"cd":17,"dash":0,"vx":0.0,"vy":-0.34375,"x":3.27667236328125,"y":11.86798095703125}}, + {"input":[0,-127,0],"state":{"cd":16,"dash":0,"vx":0.0,"vy":-1.6796875,"x":3.27667236328125,"y":11.8121337890625}}, + {"input":[0,-127,0],"state":{"cd":15,"dash":0,"vx":0.0,"vy":-3.015625,"x":3.27667236328125,"y":11.71173095703125}}, + {"input":[0,-127,0],"state":{"cd":14,"dash":0,"vx":0.0,"vy":-4.3515625,"x":3.27667236328125,"y":11.5667724609375}}, + {"input":[0,-127,0],"state":{"cd":13,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.400146484375}}, + {"input":[0,-127,0],"state":{"cd":12,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.2335205078125}}, + {"input":[0,-127,0],"state":{"cd":11,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.06689453125}}, + {"input":[0,-127,0],"state":{"cd":10,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.9002685546875}}, + {"input":[0,-127,0],"state":{"cd":9,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.733642578125}}, + {"input":[0,-127,0],"state":{"cd":8,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.5670166015625}}, + {"input":[0,-127,0],"state":{"cd":7,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.400390625}}, + {"input":[0,-127,0],"state":{"cd":6,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.2337646484375}}, + {"input":[0,-127,0],"state":{"cd":5,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.067138671875}}, + {"input":[0,-127,0],"state":{"cd":4,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.9005126953125}}, + {"input":[0,-127,0],"state":{"cd":3,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.73388671875}}, + {"input":[0,-127,0],"state":{"cd":2,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.5672607421875}}, + {"input":[0,-127,0],"state":{"cd":1,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.400634765625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.2340087890625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.0673828125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.9007568359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.734130859375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.5675048828125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.40087890625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.2342529296875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.067626953125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.9010009765625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.734375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.5677490234375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.401123046875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.2344970703125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.06787109375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.9012451171875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.734619140625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.5679931640625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.4013671875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.2347412109375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.068115234375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.9014892578125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.73486328125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.5682373046875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.401611328125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.2349853515625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.068359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.9017333984375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.735107421875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.5684814453125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.40185546875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.2352294921875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.068603515625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.9019775390625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.7353515625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.5687255859375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.402099609375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.2354736328125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.06884765625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.9022216796875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.735595703125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.5689697265625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.40234375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.2357177734375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.069091796875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.9024658203125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.73583984375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.5692138671875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.402587890625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.2359619140625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.0693359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.9027099609375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.736083984375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.5694580078125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.40283203125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.2362060546875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.069580078125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.0970458984375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.263671875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.4302978515625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.596923828125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.7635498046875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.93017578125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.0968017578125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.263427734375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.4300537109375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.5966796875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.7633056640625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.929931640625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.0965576171875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.26318359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.4298095703125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.596435546875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.7630615234375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.9296875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.0963134765625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.262939453125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.4295654296875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.59619140625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.7628173828125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.929443359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.0960693359375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.2626953125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.4293212890625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.595947265625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.7625732421875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.92919921875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.0958251953125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.262451171875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.4290771484375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.595703125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.7623291015625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.928955078125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.0955810546875}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.26220703125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.4288330078125}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.595458984375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.7620849609375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.9287109375}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-7.0953369140625}}, + {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-7.261962890625}} + ] +} diff --git a/examples/game/run.sh b/examples/game/run.sh new file mode 100755 index 000000000..770a5e4b5 --- /dev/null +++ b/examples/game/run.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# distributed_game demos — one command per demo (dev only). +# +# ./run.sh arena build what is needed, start the arena server +# (dev routes on) + Vite, print the URL +# ./run.sh smoke every demo's smoke tests (Rust bots + headless JS) +# ./run.sh list demos this script knows +# +# Env: GAME_DEMOS_PORT (server, default 2567), GAME_DEMOS_CLIENT_PORT (Vite, +# default 5173), DG_NET_LATENCY_MS / DG_NET_JITTER_MS / DG_NET_LOSS (initial +# server NetSim; the HUD sliders change it live). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO="$(cd "$HERE/../.." && pwd)" +SERVER="$HERE/server" +CLIENT="$HERE/client" +BIN="$SERVER/target/debug/game-demos" +DEMOS=(arena) + +log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } + +ensure_sdk() { + # The client depends on the local SDK build (file:../../../js). + if [[ ! -d "$REPO/js/node_modules" ]]; then + log "installing js SDK dependencies" + (cd "$REPO/js" && npm ci --no-audit --no-fund) + fi + local marker="$REPO/js/dist/game/index.js" + if [[ ! -f "$marker" ]] || [[ -n "$(find "$REPO/js/src" -newer "$marker" -name '*.ts' -print -quit)" ]]; then + log "building js SDK" + (cd "$REPO/js" && npm run build >/dev/null) + fi +} + +ensure_client() { + local stamp="$CLIENT/node_modules/.package-lock.json" + if [[ ! -f "$stamp" ]] || [[ "$CLIENT/package-lock.json" -nt "$stamp" ]]; then + log "installing client dependencies (npm ci)" + (cd "$CLIENT" && npm ci --no-audit --no-fund) + fi +} + +ensure_server() { + log "building game-demos server" + cargo build --quiet --manifest-path "$SERVER/Cargo.toml" +} + +run_demo() { + local demo="$1" + local port="${GAME_DEMOS_PORT:-2567}" + local client_port="${GAME_DEMOS_CLIENT_PORT:-5173}" + ensure_sdk + ensure_client + ensure_server + + local log_file + log_file="$(mktemp -t game-demos.XXXXXX)" + "$BIN" "$demo" --dev --port "$port" >"$log_file" 2>&1 & + local server_pid=$! + trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; rm -f "$log_file"' EXIT INT TERM + for _ in $(seq 1 100); do + grep -q '^LISTENING' "$log_file" && break + if ! kill -0 "$server_pid" 2>/dev/null; then + cat "$log_file" + echo "game-demos $demo failed to start" >&2 + exit 1 + fi + sleep 0.1 + done + sed -n '2p' "$log_file" + echo + log "open http://localhost:$client_port/$demo/ (server :$port, dev routes ON — local only)" + echo + cd "$CLIENT" + GAME_DEMOS_SERVER="http://127.0.0.1:$port" GAME_DEMOS_CLIENT_PORT="$client_port" npx vite +} + +smoke() { + ensure_sdk + ensure_client + log "server: fmt, clippy, tests (bots smoke + movement fixture)" + cargo fmt --manifest-path "$SERVER/Cargo.toml" --check + cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --all-targets -- -D warnings + cargo test --quiet --manifest-path "$SERVER/Cargo.toml" + cargo build --quiet --manifest-path "$SERVER/Cargo.toml" + log "client: type-check, build, tests (movement parity + headless SDK)" + (cd "$CLIENT" && npm run --silent check && npx vite build --logLevel warn && GAME_DEMOS_BIN="$BIN" npm test --silent) + log "smoke OK" +} + +case "${1:-}" in + smoke) smoke ;; + list) printf '%s\n' "${DEMOS[@]}" ;; + "" | -h | --help | help) sed -n '2,13p' "$0" ;; + *) + if [[ " ${DEMOS[*]} " == *" $1 "* ]]; then + run_demo "$1" + else + echo "unknown demo '$1' (known: ${DEMOS[*]})" >&2 + exit 2 + fi + ;; +esac diff --git a/examples/game/server/.gitignore b/examples/game/server/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/examples/game/server/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock new file mode 100644 index 000000000..22830fbd1 --- /dev/null +++ b/examples/game/server/Cargo.lock @@ -0,0 +1,1017 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "distributed_game" +version = "0.1.0" +dependencies = [ + "axum", + "base64 0.23.1", + "futures-util", + "hmac", + "serde_json", + "sha2", + "tokio", + "tokio-tungstenite 0.30.0", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "game_demos" +version = "0.1.0" +dependencies = [ + "axum", + "clap", + "distributed_game", + "http-body-util", + "serde", + "serde_json", + "tokio", + "tower", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1 0.10.7", + "thiserror", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.3", + "sha1 0.11.0", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml new file mode 100644 index 000000000..9d745c0d9 --- /dev/null +++ b/examples/game/server/Cargo.toml @@ -0,0 +1,33 @@ +# Framework game demos: one binary, one subcommand per demo. +# Own workspace (like tests/gateway-native) so demo-only dependencies never +# reach the framework's lockfile; excluded from the root workspace. +[workspace] +members = ["."] +resolver = "2" + +[package] +name = "game_demos" +version = "0.1.0" +edition = "2021" +publish = false +description = "Playable demos of the distributed_game authoritative runtime (dev only)" + +[lib] +path = "src/lib.rs" + +[[bin]] +name = "game-demos" +path = "src/main.rs" + +[dependencies] +distributed_game = { path = "../../../distributed_game", features = ["net"] } +axum = { version = "0.8", default-features = false, features = ["json", "tokio", "http1"] } +clap = { version = "4", features = ["derive", "env"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "time", "sync"] } + +[dev-dependencies] +distributed_game = { path = "../../../distributed_game", features = ["net", "bots"] } +tower = { version = "0.5", features = ["util"] } +http-body-util = "0.1" diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs new file mode 100644 index 000000000..311c17358 --- /dev/null +++ b/examples/game/server/src/arena/mod.rs @@ -0,0 +1,316 @@ +//! **Arena** — the baseline netcode demo. +//! +//! Mechanics on display: fixed 30 Hz tick / 20 Hz patches, binary deltas, +//! interest management (14 m view radius on a 40×40 m floor: far drones pop +//! in and out at the ring's edge), client prediction + reconciliation of the +//! own capsule ([`movement`] is shared with the TypeScript client) and +//! interpolation of everything else (players, ~30 wandering drones). +//! +//! Entities: +//! +//! | kind | ids | fields | notes | +//! |---|---|---|---| +//! | 1 `player` | 1000 + player | x y vx vy dash cd name | full [`MoveState`] so clients can rebase | +//! | 2 `drone` | 1..=30 | x y yaw | wander between random targets | +//! | 3 `pillar` | 100 + i | x y r | global (visible everywhere) | +//! +//! Event [`EVENT_HELLO`] (JSON) tells a joining player its entity and the +//! view radius. Inputs are 3 bytes ([`MoveInput`]); each input is one +//! command frame. A player earns one frame credit per tick (max +//! [`MAX_CREDITS`]), so a client cannot move faster than real time by +//! sending more inputs, but jitter bursts are absorbed. + +pub mod movement; + +use std::collections::BTreeMap; + +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + PlayerId, View, WorldView, Zone, +}; +use serde_json::json; + +use crate::common::{send_json_event, Demo, Guests}; +pub use movement::{MoveInput, MoveState}; + +/// Player kind. +pub const KIND_PLAYER: u16 = 1; +/// Drone kind. +pub const KIND_DRONE: u16 = 2; +/// Pillar kind. +pub const KIND_PILLAR: u16 = 3; +/// Event type: `{"entity": u32, "viewRadius": f32, "half": f32}` (JSON). +pub const EVENT_HELLO: u32 = 1; +/// Interest radius (m). +pub const VIEW_RADIUS: f32 = 14.0; +/// Wandering drones. +pub const DRONES: u32 = 30; +/// Most command frames a player may bank (absorbs input jitter). +pub const MAX_CREDITS: u8 = 4; +const DRONE_SPEED: f32 = 2.5; + +struct Player { + entity: u32, + name: String, + state: MoveState, + credits: u8, +} + +struct Drone { + id: u32, + x: f32, + y: f32, + tx: f32, + ty: f32, + yaw: f32, +} + +/// Zone construction parameters. +#[derive(Clone, Default)] +pub struct ArenaConfig { + /// Display names registered by the dev ticket endpoint. + pub guests: Guests, +} + +/// The Arena zone. +pub struct Arena { + guests: Guests, + players: BTreeMap, + drones: Vec, +} + +/// Spawn points on a ring between the pillars. +fn spawn_point(player: PlayerId) -> (f32, f32) { + const SPOTS: [(f32, f32); 8] = [ + (-5.0, -5.0), + (5.0, -5.0), + (5.0, 5.0), + (-5.0, 5.0), + (0.0, -7.0), + (7.0, 0.0), + (0.0, 7.0), + (-7.0, 0.0), + ]; + SPOTS[player.0 as usize % SPOTS.len()] +} + +fn free_point(ctx: &mut Ctx<'_, Arena>) -> (f32, f32) { + loop { + let x = (ctx.rng().next_f32() * 2.0 - 1.0) * (movement::HALF - 1.0); + let y = (ctx.rng().next_f32() * 2.0 - 1.0) * (movement::HALF - 1.0); + let clear = movement::PILLARS + .iter() + .all(|(px, py, pr)| (x - px).powi(2) + (y - py).powi(2) > (pr + 1.0).powi(2)); + if clear { + return (x, y); + } + } +} + +impl Zone for Arena { + type Config = ArenaConfig; + type Input = MoveInput; + type Timer = (); + + fn schema() -> EntitySchema { + let small = FieldType::QuantF32 { + min: -movement::HALF, + max: movement::HALF, + bits: 14, + }; + EntitySchema::new() + .kind( + KindDef::new(KIND_PLAYER, "player") + .field("x", movement::POS) + .field("y", movement::POS) + .field("vx", movement::VEL) + .field("vy", movement::VEL) + .field("dash", FieldType::U8) + .field("cd", FieldType::U8) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .priority(2.0), + ) + .kind( + KindDef::new(KIND_DRONE, "drone") + .field("x", small) + .field("y", small) + .field("yaw", FieldType::Angle { bits: 8 }), + ) + .kind( + KindDef::new(KIND_PILLAR, "pillar") + .field("x", FieldType::F32) + .field("y", FieldType::F32) + .field("r", FieldType::F32), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, config: ArenaConfig) -> Self { + let mut arena = Self { + guests: config.guests, + players: BTreeMap::new(), + drones: Vec::new(), + }; + for id in 1..=DRONES { + let (x, y) = free_point(ctx); + let (tx, ty) = free_point(ctx); + arena.drones.push(Drone { + id, + x, + y, + tx, + ty, + yaw: 0.0, + }); + } + arena + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self.guests.name(&principal).unwrap_or(principal); + let (x, y) = spawn_point(player); + let entity = 1000 + player.0; + self.players.insert( + player, + Player { + entity, + name, + state: MoveState { + x, + y, + ..MoveState::default() + }, + credits: MAX_CREDITS, + }, + ); + ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); + send_json_event( + ctx, + player, + EVENT_HELLO, + &json!({ "entity": entity, "viewRadius": VIEW_RADIUS, "half": movement::HALF }), + ); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.players.remove(&player); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + MoveInput::decode(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + for (id, player) in &mut self.players { + player.credits = (player.credits + 1).min(MAX_CREDITS); + while player.credits > 0 { + let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { + break; + }; + player.state = movement::step(player.state, input.input); + player.credits -= 1; + } + ctx.set_view(*id, View::new(player.state.x, player.state.y, VIEW_RADIUS)); + } + let dt = ctx.dt_secs(); + for i in 0..self.drones.len() { + let d = &self.drones[i]; + let (ox, oy) = (d.tx - d.x, d.ty - d.y); + let dist = (ox * ox + oy * oy).sqrt(); + if dist < 0.3 { + let (tx, ty) = free_point(ctx); + let d = &mut self.drones[i]; + d.tx = tx; + d.ty = ty; + continue; + } + let d = &mut self.drones[i]; + let stride = (DRONE_SPEED * dt).min(dist); + d.x += ox / dist * stride; + d.y += oy / dist * stride; + d.yaw = oy.atan2(ox); + } + } + + fn replicate(&self, out: &mut WorldView) { + for p in self.players.values() { + let s = p.state; + out.push(EntityState::new( + p.entity, + KIND_PLAYER, + s.x, + s.y, + vec![ + FieldValue::F(s.x), + FieldValue::F(s.y), + FieldValue::F(s.vx), + FieldValue::F(s.vy), + FieldValue::U(s.dash.into()), + FieldValue::U(s.cooldown.into()), + FieldValue::Str(p.name.clone()), + ], + )); + } + for d in &self.drones { + out.push( + EntityState::new( + d.id, + KIND_DRONE, + d.x, + d.y, + vec![FieldValue::F(d.x), FieldValue::F(d.y), FieldValue::F(d.yaw)], + ) + .priority(0.5), + ); + } + for (i, (x, y, r)) in movement::PILLARS.iter().enumerate() { + out.push( + EntityState::new( + 100 + i as u32, + KIND_PILLAR, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::F(*r)], + ) + .global(), + ); + } + } +} + +/// Bot payload for `distributed_game::bots`: direction → [`MoveInput`]. +pub fn encode_bot_input(dir: [f32; 2]) -> Vec { + let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; + MoveInput { + mx: axis(dir[0]), + my: axis(dir[1]), + buttons: 0, + } + .encode() + .to_vec() +} + +/// Demo registration (`game-demos arena`). +pub struct ArenaDemo; + +impl Demo for ArenaDemo { + type Zone = Arena; + const NAME: &'static str = "arena"; + const DEFAULT_ZONE: &'static str = "arena-1"; + + fn hosts_zone(zone_id: &str) -> bool { + zone_id.starts_with("arena-") + } + + fn server(config: ServerConfig, guests: Guests) -> GameServer { + GameServer::new(config, move |zone_id| { + Self::hosts_zone(zone_id).then(|| ArenaConfig { + guests: guests.clone(), + }) + }) + } +} diff --git a/examples/game/server/src/arena/movement.rs b/examples/game/server/src/arena/movement.rs new file mode 100644 index 000000000..99250e8de --- /dev/null +++ b/examples/game/server/src/arena/movement.rs @@ -0,0 +1,356 @@ +//! Shared deterministic movement step for the Arena demo. +//! +//! **This file has a twin:** `examples/game/client/src/arena/movement.ts`. +//! The client predicts its own capsule with the same step, so both must +//! produce the same numbers for the same inputs. Rules that keep them equal: +//! +//! - all state and arithmetic is binary32 (`f32` here, `Math.fround` after +//! every operation in TypeScript); only `+ - * /` and `sqrt` are used +//! (correctly rounded in both languages; no trig, no `powf`); +//! - one input = one command frame of exactly [`DT`] seconds, independent +//! of the server's measured tick length; +//! - after every step the replicated fields are snapped to their wire +//! quantization ([`canonicalize`]), so the server's state is exactly what +//! clients decode and a rebase never introduces error. +//! +//! `tests/movement_fixture.rs` writes `examples/game/fixtures/arena-movement.json` +//! (inputs → states) and the client's `tests/movement-parity.test.mjs` replays +//! it through the TypeScript step. Change both files together, then +//! regenerate with `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. + +use distributed_game::FieldType; + +/// Command frame length (s): the 30 Hz tick. +pub const DT: f32 = 1.0 / 30.0; +/// Arena half extent (the floor spans -20..20 m on both axes). +pub const HALF: f32 = 20.0; +/// Capsule radius. +pub const PLAYER_RADIUS: f32 = 0.5; +/// Walking speed (m/s). +pub const MAX_SPEED: f32 = 5.0; +/// Acceleration toward the stick velocity (m/s²). +pub const ACCEL: f32 = 40.0; +/// Dash velocity (m/s). +pub const DASH_SPEED: f32 = 14.0; +/// Dash duration in command frames. +pub const DASH_FRAMES: u8 = 6; +/// Dash cooldown in command frames (1.5 s). +pub const DASH_COOLDOWN: u8 = 45; +/// Input bit: dash. +pub const BUTTON_DASH: u8 = 1; + +/// Static circular pillars `(x, y, radius)`. +pub const PILLARS: [(f32, f32, f32); 9] = [ + (0.0, 0.0, 2.5), + (-9.0, -9.0, 1.5), + (9.0, -9.0, 1.5), + (-9.0, 9.0, 1.5), + (9.0, 9.0, 1.5), + (0.0, -14.0, 1.0), + (0.0, 14.0, 1.0), + (-14.0, 0.0, 1.0), + (14.0, 0.0, 1.0), +]; + +/// Wire type of `x`/`y`: 20/2^17 m ≈ 0.15 mm steps, 0 exact. +pub const POS: FieldType = FieldType::quant_centered(HALF, 18); +/// Wire type of `vx`/`vy`: 1/128 m/s steps, 0 exact (a resting capsule +/// must have velocity exactly 0 or it creeps). +pub const VEL: FieldType = FieldType::quant_centered(16.0, 12); + +/// One command frame from the client: stick in `[-127, 127]` per axis +/// (+x right, +y forward) and button bits. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MoveInput { + /// Stick x. + pub mx: i8, + /// Stick y. + pub my: i8, + /// [`BUTTON_DASH`] … + pub buttons: u8, +} + +impl MoveInput { + /// Wire payload: `[mx, my, buttons]`. + pub fn encode(self) -> [u8; 3] { + [self.mx as u8, self.my as u8, self.buttons] + } + + /// Parse and sanitize a payload (`-128` clamps to `-127`, unknown + /// buttons are cleared). `None` for a wrong length. + pub fn decode(payload: &[u8]) -> Option { + let [mx, my, buttons] = payload else { + return None; + }; + Some(Self { + mx: (*mx as i8).max(-127), + my: (*my as i8).max(-127), + buttons: buttons & BUTTON_DASH, + }) + } +} + +/// Everything the step reads. Every field is replicated, so a client can +/// rebase its prediction on the authoritative copy. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct MoveState { + /// Position x. + pub x: f32, + /// Position y. + pub y: f32, + /// Velocity x. + pub vx: f32, + /// Velocity y. + pub vy: f32, + /// Remaining dash frames. + pub dash: u8, + /// Remaining cooldown frames. + pub cooldown: u8, +} + +/// Advance one command frame. +pub fn step(s: MoveState, input: MoveInput) -> MoveState { + let mut s = s; + // Stick direction, length clamped to 1. + let mut dx = f32::from(input.mx) / 127.0; + let mut dy = f32::from(input.my) / 127.0; + let l2 = dx * dx + dy * dy; + if l2 > 1.0 { + let inv = 1.0 / l2.sqrt(); + dx *= inv; + dy *= inv; + } + + s.cooldown = s.cooldown.saturating_sub(1); + if input.buttons & BUTTON_DASH != 0 && s.cooldown == 0 && s.dash == 0 { + // Dash along the stick, else along the current velocity. + let v2 = s.vx * s.vx + s.vy * s.vy; + let dir = if l2 > 0.01 { + let l = (dx * dx + dy * dy).sqrt(); + Some((dx / l, dy / l)) + } else if v2 > 0.01 { + let l = v2.sqrt(); + Some((s.vx / l, s.vy / l)) + } else { + None + }; + if let Some((nx, ny)) = dir { + s.vx = nx * DASH_SPEED; + s.vy = ny * DASH_SPEED; + s.dash = DASH_FRAMES; + s.cooldown = DASH_COOLDOWN; + } + } + + if s.dash > 0 { + s.dash -= 1; + } else { + let ex = dx * MAX_SPEED - s.vx; + let ey = dy * MAX_SPEED - s.vy; + let e2 = ex * ex + ey * ey; + let max_dv = ACCEL * DT; + if e2 > max_dv * max_dv { + let k = max_dv / e2.sqrt(); + s.vx += ex * k; + s.vy += ey * k; + } else { + s.vx += ex; + s.vy += ey; + } + } + + s.x += s.vx * DT; + s.y += s.vy * DT; + + for (px, py, pr) in PILLARS { + let ox = s.x - px; + let oy = s.y - py; + let d2 = ox * ox + oy * oy; + let min = PLAYER_RADIUS + pr; + if d2 < min * min { + let d = d2.sqrt(); + let (nx, ny) = if d > 1e-6 { + (ox / d, oy / d) + } else { + (1.0, 0.0) + }; + s.x = px + nx * min; + s.y = py + ny * min; + let vn = s.vx * nx + s.vy * ny; + if vn < 0.0 { + s.vx -= vn * nx; + s.vy -= vn * ny; + } + } + } + + let lim = HALF - PLAYER_RADIUS; + if s.x < -lim { + s.x = -lim; + s.vx = s.vx.max(0.0); + } else if s.x > lim { + s.x = lim; + s.vx = s.vx.min(0.0); + } + if s.y < -lim { + s.y = -lim; + s.vy = s.vy.max(0.0); + } else if s.y > lim { + s.y = lim; + s.vy = s.vy.min(0.0); + } + canonicalize(s) +} + +fn snap(ty: FieldType, v: f32) -> f32 { + match ty { + FieldType::QuantF32 { min, max, bits } => FieldType::dequantize_linear( + FieldType::quantize_linear(v, min, max, bits), + min, + max, + bits, + ), + _ => v, + } +} + +/// Snap to the replicated precision (see the module docs). +pub fn canonicalize(s: MoveState) -> MoveState { + MoveState { + x: snap(POS, s.x), + y: snap(POS, s.y), + vx: snap(VEL, s.vx), + vy: snap(VEL, s.vy), + ..s + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(mut s: MoveState, input: MoveInput, frames: usize) -> MoveState { + for _ in 0..frames { + s = step(s, input); + } + s + } + + const START: MoveState = MoveState { + x: -5.0, + y: -5.0, + vx: 0.0, + vy: 0.0, + dash: 0, + cooldown: 0, + }; + + #[test] + fn walks_at_max_speed_after_accelerating() { + let s = run( + START, + MoveInput { + mx: 127, + my: 0, + buttons: 0, + }, + 30, + ); + assert!((s.vx - MAX_SPEED).abs() < 0.01, "{s:?}"); + // 1 s of walking minus the acceleration phase (~0.06 m lost). + assert!(s.x > -5.0 + 4.6 && s.x < 0.0, "{s:?}"); + } + + #[test] + fn diagonal_stick_is_not_faster() { + let open = MoveState { + x: -15.0, + y: 5.0, + ..START + }; + let s = run( + open, + MoveInput { + mx: 127, + my: 127, + buttons: 0, + }, + 20, + ); + let speed = (s.vx * s.vx + s.vy * s.vy).sqrt(); + assert!((speed - MAX_SPEED).abs() < 0.02, "{speed}"); + } + + #[test] + fn pillars_and_walls_block() { + // Walk right into the central pillar from the left. + let at = MoveState { + x: -6.0, + y: 0.0, + ..START + }; + let s = run( + at, + MoveInput { + mx: 127, + my: 0, + buttons: 0, + }, + 90, + ); + assert!(s.x <= -(2.5 + PLAYER_RADIUS) + 1e-3, "{s:?}"); + let s = run( + START, + MoveInput { + mx: -127, + my: 0, + buttons: 0, + }, + 200, + ); + assert!((s.x + (HALF - PLAYER_RADIUS)).abs() < 1e-3, "{s:?}"); + assert_eq!(s.vx, 0.0); + } + + #[test] + fn dash_bursts_then_cools_down() { + let dash = MoveInput { + mx: 0, + my: 127, + buttons: BUTTON_DASH, + }; + let s = step(START, dash); + assert_eq!((s.dash, s.cooldown), (DASH_FRAMES - 1, DASH_COOLDOWN)); + assert!(s.vy > 13.9); + let s = run(s, dash, 14); + assert!( + s.vy <= MAX_SPEED + 0.01, + "dash over, back to walking: {s:?}" + ); + assert!( + s.cooldown > 0 && s.dash == 0, + "held button does not re-dash" + ); + let s = run(s, MoveInput::default(), 31); + assert_eq!(s.cooldown, 0); + } + + #[test] + fn input_round_trips_and_sanitizes() { + let i = MoveInput { + mx: -127, + my: 5, + buttons: BUTTON_DASH, + }; + assert_eq!(MoveInput::decode(&i.encode()), Some(i)); + assert_eq!( + MoveInput::decode(&[0x80, 0, 0xff]), + Some(MoveInput { + mx: -127, + my: 0, + buttons: BUTTON_DASH + }) + ); + assert_eq!(MoveInput::decode(&[1, 2]), None); + } +} diff --git a/examples/game/server/src/common/dev.rs b/examples/game/server/src/common/dev.rs new file mode 100644 index 000000000..c57e7d05c --- /dev/null +++ b/examples/game/server/src/common/dev.rs @@ -0,0 +1,194 @@ +//! **Dev-only** HTTP routes, mounted only with `--dev` / `DG_DEMO_DEV=1`. +//! +//! - `POST /dev/ticket` `{zone, name?, role?, guest?}` → +//! `{ticket, principal, name, guest, zone, expiresAt}`. Mints a single-use +//! HS256 admission ticket for a **server-generated** guest principal. The +//! caller chooses only a display name; `guest` (a token from an earlier +//! response, HMAC-signed by this server) keeps the same principal across +//! page reloads. A real game gets tickets from its authenticated lobby. +//! - `GET /dev/netsim` / `POST /dev/netsim` `{latencyMs, jitterMs, loss}` — +//! read / replace the server-side network simulation for **every** +//! connection (one-way latency applied in both directions, so RTT grows by +//! 2 × latency; loss is a TCP-retransmit delay, see `NetSim`). + +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::extract::State; +use axum::http::StatusCode; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use distributed_game::net::{GameServer, NetSim, TicketKey}; +use distributed_game::{Role, TicketClaims}; +use serde::{Deserialize, Serialize}; +use std::time::Duration; + +use super::guests::{self, Guests}; +use super::Demo; + +/// Ticket lifetime: long enough to connect, short because it is single use. +pub const TICKET_TTL_SECS: u64 = 120; + +struct DevState { + server: GameServer, + key: TicketKey, + guests: Guests, +} + +impl Clone for DevState { + fn clone(&self) -> Self { + Self { + server: self.server.clone(), + key: self.key.clone(), + guests: self.guests.clone(), + } + } +} + +/// `POST /dev/ticket` body. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TicketRequest { + /// Zone to join (must be hosted by the demo). + pub zone: String, + /// Display name (sanitized; identity is never taken from it). + #[serde(default)] + pub name: Option, + /// `"player"` (default) or `"observer"`. + #[serde(default)] + pub role: Option, + /// Guest token from an earlier response. + #[serde(default)] + pub guest: Option, +} + +/// `POST /dev/ticket` response. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TicketResponse { + /// HS256 admission ticket for Hello. + pub ticket: String, + /// Server-generated principal. + pub principal: String, + /// Display name in effect. + pub name: String, + /// Present this as `guest` next time to keep the principal. + pub guest: String, + /// Zone the ticket admits to. + pub zone: String, + /// Unix seconds. + pub expires_at: u64, +} + +/// NetSim as JSON (milliseconds, loss as a fraction). +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct NetSimJson { + /// One-way latency. + pub latency_ms: u64, + /// Uniform extra delay in `[0, jitter]`. + pub jitter_ms: u64, + /// Fraction of messages delayed by a simulated retransmit. + pub loss: f32, +} + +impl NetSimJson { + fn from_sim(sim: Option) -> Self { + sim.map_or_else(Self::default, |s| Self { + latency_ms: s.latency.as_millis() as u64, + jitter_ms: s.jitter.as_millis() as u64, + loss: s.loss, + }) + } + + fn to_sim(self) -> Option { + let latency = Duration::from_millis(self.latency_ms.min(1000)); + let jitter = Duration::from_millis(self.jitter_ms.min(500)); + let loss = if self.loss.is_finite() { + self.loss.clamp(0.0, 0.5) + } else { + 0.0 + }; + (!latency.is_zero() || !jitter.is_zero() || loss > 0.0) + .then(|| NetSim::new(latency, jitter).with_loss(loss, Duration::from_millis(200))) + } +} + +/// The dev router for demo `D`. +pub fn routes(server: GameServer, key: TicketKey, guests: Guests) -> Router { + Router::new() + .route("/dev/ticket", post(ticket::)) + .route("/dev/netsim", get(get_netsim::).post(set_netsim::)) + .with_state(DevState:: { + server, + key, + guests, + }) +} + +type ApiError = (StatusCode, Json); + +fn bad_request(message: &str) -> ApiError { + ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": message })), + ) +} + +async fn ticket( + State(state): State>, + Json(request): Json, +) -> Result, ApiError> { + if !D::hosts_zone(&request.zone) { + return Err(bad_request("zone is not hosted by this demo")); + } + let role = match request.role.as_deref() { + None | Some("player") => Role::Player, + Some("observer") => Role::Observer, + Some(_) => return Err(bad_request("role must be player or observer")), + }; + // Identity: a verified guest token, else a brand-new principal. + let principal = request + .guest + .as_deref() + .and_then(|token| guests::verify_guest_token(&state.key, token)) + .unwrap_or_else(guests::new_principal); + let name = request + .name + .as_deref() + .map(guests::sanitize_name) + .filter(|n| !n.is_empty()) + .or_else(|| state.guests.name(&principal)) + .unwrap_or_else(|| format!("Guest {}", principal.get(6..10).unwrap_or(""))); + state.guests.set_name(&principal, name.clone()); + let expires_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) + + TICKET_TTL_SECS; + let ticket = state.key.sign(&TicketClaims { + principal: principal.clone(), + zone: request.zone.clone(), + expires_at, + nonce: guests::random_hex(24), + role, + }); + Ok(Json(TicketResponse { + ticket, + guest: guests::guest_token(&state.key, &principal), + principal, + name, + zone: request.zone, + expires_at, + })) +} + +async fn get_netsim(State(state): State>) -> Json { + Json(NetSimJson::from_sim(state.server.net_sim())) +} + +async fn set_netsim( + State(state): State>, + Json(body): Json, +) -> Json { + state.server.set_net_sim(body.to_sim()); + Json(NetSimJson::from_sim(state.server.net_sim())) +} diff --git a/examples/game/server/src/common/guests.rs b/examples/game/server/src/common/guests.rs new file mode 100644 index 000000000..3ac84a2bb --- /dev/null +++ b/examples/game/server/src/common/guests.rs @@ -0,0 +1,114 @@ +//! Guest principals and display names (dev ticket endpoint only). +//! +//! The principal is always server-generated (`guest-`); a caller can +//! only choose a display name, which zones look up by the verified principal +//! from the ticket. A returning browser presents the server-signed guest +//! token it got earlier to keep the same principal (so a reconnect after the +//! grace window is the same player), never a raw principal. + +use std::collections::hash_map::RandomState; +use std::collections::HashMap; +use std::hash::{BuildHasher, Hasher}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use distributed_game::net::TicketKey; + +/// Longest display name (characters). +pub const MAX_NAME: usize = 16; + +/// principal → display name, shared by the dev routes and the zones. +#[derive(Clone, Default)] +pub struct Guests { + names: Arc>>, +} + +impl Guests { + /// Display name registered for `principal`. + pub fn name(&self, principal: &str) -> Option { + self.names.lock().expect("guests").get(principal).cloned() + } + + /// Register (or rename) a guest. + pub fn set_name(&self, principal: &str, name: String) { + self.names + .lock() + .expect("guests") + .insert(principal.to_string(), name); + } + + /// Number of known guests. + pub fn len(&self) -> usize { + self.names.lock().expect("guests").len() + } + + /// True when nobody registered. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// Keep letters, digits, space, `-` and `_`; trim; at most [`MAX_NAME`] chars. +pub fn sanitize_name(raw: &str) -> String { + raw.chars() + .filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')) + .take(MAX_NAME) + .collect::() + .trim() + .to_string() +} + +/// A fresh server-generated principal. +pub fn new_principal() -> String { + format!("guest-{}", random_hex(8)) +} + +/// `principal "." mac` — proves the server issued this principal. +pub fn guest_token(key: &TicketKey, principal: &str) -> String { + format!("{principal}.{}", mac_hex(key, principal)) +} + +/// The principal inside a valid guest token. +pub fn verify_guest_token(key: &TicketKey, token: &str) -> Option { + let (principal, mac) = token.rsplit_once('.')?; + (principal.starts_with("guest-") && mac == mac_hex(key, principal)) + .then(|| principal.to_string()) +} + +fn mac_hex(key: &TicketKey, principal: &str) -> String { + key.hmac(format!("demo-guest|{principal}").as_bytes())[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// `len` random hex characters (OS-seeded SipHash keys; dev quality). +pub fn random_hex(len: usize) -> String { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let mut out = String::with_capacity(len + 16); + while out.len() < len { + let mut h = RandomState::new().build_hasher(); + h.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed)); + out.push_str(&format!("{:016x}", h.finish())); + } + out.truncate(len); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_sanitized_and_tokens_verify() { + assert_eq!(sanitize_name(" Ana!! "), "bAnab"); + assert_eq!(sanitize_name(&"x".repeat(40)).len(), MAX_NAME); + let key = TicketKey::new("k"); + let principal = new_principal(); + let token = guest_token(&key, &principal); + assert_eq!(verify_guest_token(&key, &token), Some(principal.clone())); + assert_eq!(verify_guest_token(&TicketKey::new("other"), &token), None); + assert_eq!(verify_guest_token(&key, "admin.deadbeef"), None); + assert_ne!(new_principal(), principal); + } +} diff --git a/examples/game/server/src/common/mod.rs b/examples/game/server/src/common/mod.rs new file mode 100644 index 000000000..02b779124 --- /dev/null +++ b/examples/game/server/src/common/mod.rs @@ -0,0 +1,201 @@ +//! Shared plumbing for every demo: CLI options, the [`Demo`] trait, server +//! startup ([`spawn`] / [`run`]), the dev-only routes ([`dev`]), guest display +//! names ([`Guests`]) and small zone helpers ([`send_json_event`]). +//! +//! A new demo implements [`Demo`] in its own module and adds one subcommand +//! line in `main.rs`; everything else (ticket endpoint, NetSim control, +//! `/metrics`, graceful shutdown) comes from here. + +pub mod dev; +mod guests; + +use std::future::Future; +use std::net::SocketAddr; + +use axum::Router; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; +use distributed_game::{Ctx, Viewer, Zone}; + +pub use guests::Guests; + +/// One playable demo hosted by `game-demos `. +pub trait Demo: 'static { + /// The zone type. + type Zone: Zone; + /// Subcommand / URL path name (`arena` → `/arena/`). + const NAME: &'static str; + /// Zone the client joins by default. + const DEFAULT_ZONE: &'static str; + + /// Zones this demo creates on demand (the dev ticket endpoint refuses + /// others). + fn hosts_zone(zone_id: &str) -> bool; + + /// Build the server. `config` already carries the ticket key, 30 Hz + /// ticks, 20 Hz patches and any `DG_NET_*` simulation; adjust as needed. + fn server(config: ServerConfig, guests: Guests) -> GameServer; +} + +/// Options shared by every demo subcommand. +#[derive(Debug, Clone, clap::Args)] +pub struct DemoArgs { + /// Interface to bind (demos are local-only by default). + #[arg(long, default_value = "127.0.0.1")] + pub host: String, + /// Port (0 = any free port; the bound address is printed). + #[arg(long, env = "GAME_DEMOS_PORT", default_value_t = 2567)] + pub port: u16, + /// Enable the dev-only routes (`/dev/ticket`, `/dev/netsim`). Never in + /// production: anyone who can reach the port gets a guest ticket. + #[arg(long, env = "DG_DEMO_DEV")] + pub dev: bool, + /// HS256 ticket secret. Default: random per process. + #[arg(long, env = "DISTRIBUTED_GAME_SECRET", hide_env_values = true)] + pub secret: Option, +} + +/// In-process startup options (tests and [`run`]). +#[derive(Clone)] +pub struct DemoOptions { + /// Ticket signing key. + pub key: TicketKey, + /// Mount the dev routes. + pub dev: bool, + /// Initial network simulation. + pub net_sim: Option, +} + +impl DemoOptions { + /// Dev routes on, the given secret, no simulation. + pub fn dev(secret: &str) -> Self { + Self { + key: TicketKey::new(secret), + dev: true, + net_sim: None, + } + } +} + +/// A demo server running on a Tokio task. +pub struct RunningDemo { + /// Bound address. + pub addr: SocketAddr, + /// The game server (inspect zones, change NetSim, shut down). + pub server: GameServer, + /// Display names registered through `/dev/ticket`. + pub guests: Guests, + /// Resolves when the server stopped. + pub task: tokio::task::JoinHandle>, +} + +impl RunningDemo { + /// `ws://addr` (append `/zones/{zone}`). + pub fn ws_url(&self) -> String { + format!("ws://{}", self.addr) + } + + /// `http://addr`. + pub fn http_url(&self) -> String { + format!("http://{}", self.addr) + } +} + +/// Server config every demo starts from. +pub fn server_config(key: TicketKey, net_sim: Option) -> ServerConfig { + let mut config = ServerConfig::new(key); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + config.net_sim = net_sim; + config +} + +/// Start demo `D` on `listener` until `signal` resolves. +pub fn spawn( + listener: tokio::net::TcpListener, + options: DemoOptions, + signal: impl Future + Send + 'static, +) -> std::io::Result> { + let addr = listener.local_addr()?; + let guests = Guests::default(); + let server = D::server( + server_config(options.key.clone(), options.net_sim), + guests.clone(), + ); + let extra = if options.dev { + dev::routes::(server.clone(), options.key, guests.clone()) + } else { + Router::new() + }; + let task = tokio::spawn(server.clone().serve_with(listener, extra, signal)); + Ok(RunningDemo { + addr, + server, + guests, + task, + }) +} + +/// CLI entry: bind, print the address, serve until Ctrl-C / SIGTERM. +pub async fn run(args: DemoArgs) -> std::io::Result<()> { + let listener = tokio::net::TcpListener::bind((args.host.as_str(), args.port)).await?; + let secret = args.secret.unwrap_or_else(|| guests::random_hex(32)); + let options = DemoOptions { + key: TicketKey::new(secret), + dev: args.dev, + net_sim: NetSim::from_env(), + }; + let running = spawn::(listener, options, shutdown_signal())?; + // Parsed by run.sh and the client tests: keep the format. + println!("LISTENING http://{}", running.addr); + println!( + "demo {} · zone {} · ws {}/zones/{} · dev routes {}", + D::NAME, + D::DEFAULT_ZONE, + running.ws_url(), + D::DEFAULT_ZONE, + if args.dev { "ON" } else { "off" } + ); + running.task.await.map_err(std::io::Error::other)? +} + +async fn shutdown_signal() { + let ctrl_c = async { + let _ = tokio::signal::ctrl_c().await; + }; + #[cfg(unix)] + let term = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut s) => { + s.recv().await; + } + Err(_) => std::future::pending().await, + } + }; + #[cfg(not(unix))] + let term = std::future::pending::<()>(); + tokio::select! { + _ = ctrl_c => {} + _ = term => {} + } +} + +/// Send a JSON-encoded Event (`type_id`, UTF-8 JSON payload). Demos use JSON +/// for low-rate events so clients can `JSON.parse` them; hot data belongs in +/// replicated fields. +pub fn send_json_event( + ctx: &mut Ctx<'_, Z>, + to: impl Into, + type_id: u32, + value: &serde_json::Value, +) { + ctx.send_event(to, type_id, value.to_string().into_bytes()); +} + +/// Broadcast a JSON-encoded Event to every connection of the zone. +pub fn broadcast_json_event( + ctx: &mut Ctx<'_, Z>, + type_id: u32, + value: &serde_json::Value, +) { + ctx.broadcast_event(type_id, value.to_string().into_bytes()); +} diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs new file mode 100644 index 000000000..7bfa7546f --- /dev/null +++ b/examples/game/server/src/lib.rs @@ -0,0 +1,10 @@ +//! Playable demos of the `distributed_game` runtime (dev only). +//! +//! - [`common`]: what every demo shares — the [`common::Demo`] trait, +//! startup, dev ticket / NetSim routes, guest names, JSON events. +//! - One module per demo ([`arena`], …), each implementing `Demo`. +//! +//! See `examples/game/README.md`. + +pub mod arena; +pub mod common; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs new file mode 100644 index 000000000..7fde2d462 --- /dev/null +++ b/examples/game/server/src/main.rs @@ -0,0 +1,28 @@ +//! `game-demos [--port N] [--dev]` — one subcommand per demo. + +use clap::{Parser, Subcommand}; +use game_demos::arena::ArenaDemo; +use game_demos::common::{run, DemoArgs}; + +#[derive(Parser)] +#[command( + name = "game-demos", + about = "distributed_game demo servers (dev only)" +)] +struct Cli { + #[command(subcommand)] + demo: DemoCommand, +} + +#[derive(Subcommand)] +enum DemoCommand { + /// Prediction, reconciliation, interpolation and interest management. + Arena(DemoArgs), +} + +#[tokio::main] +async fn main() -> std::io::Result<()> { + match Cli::parse().demo { + DemoCommand::Arena(args) => run::(args).await, + } +} diff --git a/examples/game/server/tests/arena_smoke.rs b/examples/game/server/tests/arena_smoke.rs new file mode 100644 index 000000000..316d725bd --- /dev/null +++ b/examples/game/server/tests/arena_smoke.rs @@ -0,0 +1,196 @@ +//! Arena smoke tests: the real server in-process, dev routes over HTTP and +//! 20 WebSocket bots (`distributed_game::bots`). + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use distributed_game::bots::{run_bots, BotConfig, RandomWalk}; +use distributed_game::net::TicketKey; +use game_demos::arena::{self, ArenaDemo}; +use game_demos::common::{spawn, DemoOptions, RunningDemo}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +const SECRET: &str = "smoke-secret"; + +async fn start(options: DemoOptions) -> (RunningDemo, tokio::sync::oneshot::Sender<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let running = spawn::(listener, options, async move { + let _ = stopped.await; + }) + .unwrap(); + (running, stop) +} + +/// Minimal HTTP/1.1 client: `(status, JSON body or Null)`. +async fn http(addr: SocketAddr, method: &str, path: &str, body: Option) -> (u16, Value) { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + let status = response[9..12].parse().unwrap(); + let json = response + .split_once("\r\n\r\n") + .and_then(|(_, b)| serde_json::from_str(b).ok()) + .unwrap_or(Value::Null); + (status, json) +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dev_ticket_binds_a_server_generated_guest() { + let (demo, stop) = start(DemoOptions::dev(SECRET)).await; + let key = TicketKey::new(SECRET); + + let (status, first) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "arena-1", "name": " Ana " })), + ) + .await; + assert_eq!(status, 200, "{first}"); + let principal = first["principal"].as_str().unwrap().to_string(); + assert!(principal.starts_with("guest-")); + assert_eq!(first["name"], "bAnab"); + let claims = key + .verify(first["ticket"].as_str().unwrap(), now()) + .unwrap(); + assert_eq!(claims.principal, principal); + assert_eq!(claims.zone, "arena-1"); + assert_eq!(demo.guests.name(&principal).as_deref(), Some("bAnab")); + + // The signed guest token keeps the principal; a caller identity never does. + let (_, again) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "arena-1", "guest": first["guest"] })), + ) + .await; + assert_eq!(again["principal"], principal.as_str()); + assert_eq!(again["name"], "bAnab", "name remembered"); + let (_, forged) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "arena-1", "guest": "guest-admin.00" })), + ) + .await; + assert_ne!(forged["principal"], "guest-admin"); + let (status, _) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "arena-1", "principal": "admin" })), + ) + .await; + assert_eq!( + status, 422, + "unknown fields (a caller identity) are rejected" + ); + let (status, _) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "pit-1" })), + ) + .await; + assert_eq!(status, 400, "zones of other demos are refused"); + + // Live NetSim control. + let (status, sim) = http( + demo.addr, + "POST", + "/dev/netsim", + Some(json!({ "latencyMs": 40, "jitterMs": 10, "loss": 0.9 })), + ) + .await; + assert_eq!(status, 200); + assert_eq!(sim, json!({ "latencyMs": 40, "jitterMs": 10, "loss": 0.5 })); + assert_eq!( + demo.server.net_sim().unwrap().latency, + Duration::from_millis(40) + ); + let (_, off) = http(demo.addr, "POST", "/dev/netsim", Some(json!({}))).await; + assert_eq!(off, json!({ "latencyMs": 0, "jitterMs": 0, "loss": 0.0 })); + assert_eq!(demo.server.net_sim(), None); + + stop.send(()).unwrap(); + demo.task.await.unwrap().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dev_routes_are_off_by_default() { + let options = DemoOptions { + dev: false, + ..DemoOptions::dev(SECRET) + }; + let (demo, stop) = start(options).await; + let (status, _) = http( + demo.addr, + "POST", + "/dev/ticket", + Some(json!({ "zone": "arena-1" })), + ) + .await; + assert_eq!(status, 404); + let (status, _) = http(demo.addr, "GET", "/metrics", None).await; + assert_eq!(status, 200, "metrics are always served"); + stop.send(()).unwrap(); + demo.task.await.unwrap().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn twenty_bots_get_deltas_and_acks() { + let (demo, stop) = start(DemoOptions::dev(SECRET)).await; + let mut config = BotConfig::new(demo.ws_url(), "arena-1", TicketKey::new(SECRET)); + config.bots = 20; + config.input_rate = 30.0; + config.duration = Duration::from_secs(2); + config.encoder = Arc::new(arena::encode_bot_input); + let server = demo.server.clone(); + let (summary, players) = tokio::join!( + run_bots(config, |_| Box::new(RandomWalk::new(0.1))), + async move { + tokio::time::sleep(Duration::from_millis(1200)).await; + server.inspect("arena-1", |host| host.player_count()).await + } + ); + assert_eq!(players, Some(20), "all bots are players mid-run"); + assert_eq!( + summary.joined(), + 20, + "{:?}", + summary.bots.iter().find(|b| b.error.is_some()) + ); + assert_eq!(summary.failed(), 0); + for bot in &summary.bots { + assert!( + bot.deltas >= 20, + "bot {} got {} deltas", + bot.index, + bot.deltas + ); + assert!(bot.last_ack >= 20, "bot {} ack {}", bot.index, bot.last_ack); + assert!(bot.entities >= 9, "pillars are global: {}", bot.entities); + } + assert!(summary.delta_bytes() > 0); + let metrics = demo.server.metrics().render(); + assert!(metrics.contains("arena-1"), "per-zone metrics"); + stop.send(()).unwrap(); + demo.task.await.unwrap().unwrap(); +} diff --git a/examples/game/server/tests/movement_fixture.rs b/examples/game/server/tests/movement_fixture.rs new file mode 100644 index 000000000..b9f806b07 --- /dev/null +++ b/examples/game/server/tests/movement_fixture.rs @@ -0,0 +1,110 @@ +//! Golden fixture for the shared Arena movement step. +//! +//! Writes/compares `examples/game/fixtures/arena-movement.json`, which the +//! TypeScript client replays in `client/tests/movement-parity.test.mjs`. +//! Regenerate after an intended change to BOTH implementations: +//! `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. + +use std::path::PathBuf; + +use game_demos::arena::movement::{self, MoveInput, MoveState, BUTTON_DASH}; +use serde_json::{json, Value}; + +/// A scripted input sequence covering acceleration, diagonals, partial +/// stick, dash (stick and velocity direction), held dash, pillar and wall +/// contact. +fn script() -> Vec { + let i = |mx: i8, my: i8, buttons: u8| MoveInput { mx, my, buttons }; + let mut out = Vec::new(); + let mut push = |input: MoveInput, n: usize| out.extend(std::iter::repeat_n(input, n)); + push(i(127, 0, 0), 20); // accelerate right + push(i(90, 90, 0), 15); // diagonal (clamped length) + push(i(30, -64, 0), 10); // partial stick + push(i(0, 0, BUTTON_DASH), 1); // dash along velocity + push(i(0, 0, 0), 12); // decelerate + push(i(-127, 0, BUTTON_DASH), 8); // dash along stick, held + push(i(-128, 5, 0), 40); // into the left pillars / wall (-128 sanitizes) + push(i(127, 127, 0), 60); // towards the centre pillar + push(i(0, 127, BUTTON_DASH), 70); // repeated dashes after cooldown + push(i(0, -127, 0), 120); // across the floor into the far wall + out +} + +fn state_json(s: &MoveState) -> Value { + json!({ "x": s.x, "y": s.y, "vx": s.vx, "vy": s.vy, "dash": s.dash, "cd": s.cooldown }) +} + +fn field_json(name: &str, ty: distributed_game::FieldType) -> Value { + match ty { + distributed_game::FieldType::QuantF32 { min, max, bits } => { + json!({ "name": name, "type": "quant_f32", "min": min, "max": max, "bits": bits }) + } + _ => unreachable!(), + } +} + +fn build() -> Value { + let start = movement::canonicalize(MoveState { + x: -5.0, + y: -5.0, + ..MoveState::default() + }); + let mut s = start; + let mut steps = Vec::new(); + for input in script() { + // The server decodes the wire payload, so the fixture does too. + let decoded = MoveInput::decode(&input.encode()).unwrap(); + s = movement::step(s, decoded); + steps.push(json!({ + "input": [input.mx, input.my, input.buttons], + "state": state_json(&s), + })); + } + json!({ + "description": "Arena movement parity: Rust movement::step vs client/src/arena/movement.ts", + "constants": { + "dt": movement::DT, "half": movement::HALF, "playerRadius": movement::PLAYER_RADIUS, + "maxSpeed": movement::MAX_SPEED, "accel": movement::ACCEL, "dashSpeed": movement::DASH_SPEED, + "dashFrames": movement::DASH_FRAMES, "dashCooldown": movement::DASH_COOLDOWN, + "pillars": movement::PILLARS.iter().map(|(x, y, r)| json!([x, y, r])).collect::>(), + }, + "fields": [ + field_json("x", movement::POS), field_json("y", movement::POS), + field_json("vx", movement::VEL), field_json("vy", movement::VEL), + ], + "start": state_json(&start), + "steps": steps, + }) +} + +/// Stable, diff-friendly text: one step per line. Compared as text because +/// floats are written as the exact f64 widening of each f32. +fn render(v: &Value) -> String { + let mut out = String::from("{\n"); + for key in ["description", "constants", "fields", "start"] { + out += &format!(" \"{key}\": {},\n", v[key]); + } + out += " \"steps\": [\n"; + let steps = v["steps"].as_array().unwrap(); + for (i, step) in steps.iter().enumerate() { + let sep = if i + 1 == steps.len() { "" } else { "," }; + out += &format!(" {step}{sep}\n"); + } + out + " ]\n}\n" +} + +#[test] +fn movement_fixture_is_current() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/arena-movement.json"); + let fresh = render(&build()); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + std::fs::write(&path, fresh).unwrap(); + return; + } + let stored = + std::fs::read_to_string(&path).expect("fixture exists (UPDATE_GOLDEN=1 to create)"); + assert!( + stored == fresh, + "movement changed: update client/src/arena/movement.ts too, then UPDATE_GOLDEN=1" + ); +} From da44c1898a2d5d3ed0ab2099953f546f89527141 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:25:29 -0500 Subject: [PATCH 143/484] feat(game): add GameServer::with_host_config per-zone settings Zones of one server shared a single HostConfig, so a hierarchy could not run a slow province clock next to hot neighborhoods. The hook adjusts each activation's HostConfig; the world content version is applied afterwards and cannot be overridden. Refs [[tasks/gr-p10-demos]] --- distributed_game/README.md | 5 ++++ distributed_game/src/net/mod.rs | 18 +++++++++++++++ distributed_game/tests/net_e2e/main.rs | 32 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/distributed_game/README.md b/distributed_game/README.md index a3696604d..e19a186e0 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -157,6 +157,11 @@ double-crediting. | `ZoneStateStore` (`MemoryZoneStateStore`, `SqliteZoneStateStore`) | hibernation snapshots, written under the claim's fencing token (stale writers get `StateError::Stale`). | | `ZoneTopology` (`DottedTopology` default: `eldoria.port.docks` → `eldoria.port` → `eldoria`) | parent links for tier-up events. | +**Per-zone host settings.** `GameServer::with_host_config(|zone_id, host| +…)` adjusts the `HostConfig` of each activation (e.g. a province ticking at +2 Hz while its neighborhoods run at 30 Hz); the world content version is +applied afterwards. + **Activate on demand / hibernate.** `GameServer` creates a zone on first join (or tier-up event). With `ServerConfig::hibernate_after = Some(d)` a zone that stays Dormant for `d` (no clients, no in-flight facts, not diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 96b2c28ed..3dc4891c9 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -273,6 +273,7 @@ enum ConnOut { type ConfigFactory = dyn Fn(&str) -> Option<::Config> + Send + Sync; type FactsFactory = dyn Fn(&str) -> Option<(FactQueue, JoinHandle<()>)> + Send + Sync; +type HostConfigFn = dyn Fn(&str, &mut HostConfig) + Send + Sync; struct ZoneEntry { tx: mpsc::Sender, @@ -292,6 +293,8 @@ struct Inner { clock: Arc, factory: Box>, facts: Option>, + /// Per-zone adjustments of `config.host` (tick rates, capacity …). + host_config: Option>, nonces: Mutex, zones: Mutex>, tasks: Mutex>>, @@ -351,6 +354,7 @@ where clock, factory: Box::new(factory), facts: None, + host_config: None, nonces: Mutex::new(NonceCache::default()), zones: Mutex::new(HashMap::new()), tasks: Mutex::new(Vec::new()), @@ -401,6 +405,17 @@ where self.configure(|inner| inner.state_store = Some(store)) } + /// Adjust the [`HostConfig`] of each zone at activation, e.g. a slow + /// tick rate for a province and a hot one for its neighborhoods. `f` + /// receives the zone id and a copy of `config.host`; the world content + /// version is applied afterwards and cannot be changed here. + pub fn with_host_config( + self, + f: impl Fn(&str, &mut HostConfig) + Send + Sync + 'static, + ) -> Self { + self.configure(|inner| inner.host_config = Some(Box::new(f))) + } + /// Zone hierarchy for tier-up events (default [`DottedTopology`]). pub fn with_topology(self, topology: Arc) -> Self { self.configure(|inner| inner.topology = topology) @@ -968,6 +983,9 @@ async fn run_zone( None => None, }; let mut host_config = inner.config.host.clone(); + if let Some(adjust) = &inner.host_config { + adjust(&zone_id, &mut host_config); + } host_config.content_version = world.version.clone(); let token_inner = inner.clone(); let issuer_inner = inner.clone(); diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs index a2be9c956..75769a280 100644 --- a/distributed_game/tests/net_e2e/main.rs +++ b/distributed_game/tests/net_e2e/main.rs @@ -361,3 +361,35 @@ async fn hello_join(ws: &mut Ws, zone: &str) { ) .await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn host_config_hook_sets_per_zone_rates() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.content_version = "c1".into(); + let server = GameServer::::new(config, |zone_id| { + zone_id.starts_with('z').then(ArenaConfig::default) + }) + .with_host_config(|zone_id, host| { + if zone_id == "z-slow" { + host.tick_rate = 5; + host.patch_rate = 2; + host.content_version = "ignored".into(); + } + }); + assert!(server.activate("z-slow")); + assert!(server.activate("z-hot")); + let slow = server + .inspect("z-slow", |h| { + ( + h.config().tick_rate, + h.config().patch_rate, + h.config().content_version.clone(), + ) + }) + .await; + assert_eq!(slow, Some((5, 2, "c1".to_string())), "world version wins"); + let hot = server.inspect("z-hot", |h| h.config().tick_rate).await; + assert_eq!(hot, Some(30)); + server.shutdown(); +} From c9ff4722903696754bb4cf4a8c5bb1c42ee2d6ec Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:26:02 -0500 Subject: [PATCH 144/484] fix(js): present reloaded content version on later game connections GameClient built every new connection (handoff target, observer, rejoin) from options.contentVersion, so after a Kick(RELOAD) the next handoff presented the stale version and was refused. The client now tracks the version its authority presented after a reload and exposes setContentVersion() for clients that patch content live. Refs [[tasks/gr-p10-demos]] --- js/README.md | 3 +++ js/src/game/client.ts | 31 +++++++++++++++++++++++++++- js/src/game/connection.ts | 10 +++++++++ js/tests/game-world.test.mjs | 40 ++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) diff --git a/js/README.md b/js/README.md index 4dc9ae74b..d5703b9d6 100644 --- a/js/README.md +++ b/js/README.md @@ -609,6 +609,9 @@ keeps rendering; if the target refuses or stays silent the same Hello goes back to the source zone, then a fresh ticket. `Kick(RELOAD)` and handshake `VERSION_MISMATCH` emit `reloadRequired`; supply `reloadContent` (or call `connection.resumeAfterReload(version)`) to rejoin with the new content. +`client.contentVersion` follows the reload, so later handoff targets and +observers present the new version; a client that patches content live +(e.g. on a `resume` with a new version) calls `client.setContentVersion(v)`. `encodeInput(input, ctx)` receives the interpolation delay and view tick for server-side lag compensation (`replica.interpolationDelayMs`, `client.inputContext()`). diff --git a/js/src/game/client.ts b/js/src/game/client.ts index accaaade9..f663cb774 100644 --- a/js/src/game/client.ts +++ b/js/src/game/client.ts @@ -162,9 +162,11 @@ export class GameClient { #authority: Zone | undefined; #controlledOverride: number | undefined; #closed = false; + #contentVersion: string; constructor(options: GameClientOptions) { this.#options = options; + this.#contentVersion = options.contentVersion ?? ''; this.#scheduler = options.scheduler ?? defaultScheduler; this.#emitter = new Emitter(options.onListenerError); this.#predictor = @@ -178,6 +180,28 @@ export class GameClient { return this.#emitter.on(type, listener); } + /** + * Content version this client runs: `options.contentVersion`, then the + * version the authoritative connection presented after a reload, or the + * one set with `setContentVersion`. Every new connection (handoff + * target, observer, rejoin) presents it in Hello. + */ + get contentVersion(): string { + return this.#contentVersion; + } + + /** + * The app patched its content live to `version` (no reload round-trip): + * present it on every new connection and on reconnects of the current + * ones. + */ + setContentVersion(version: string): void { + this.#contentVersion = version; + for (const zone of [...this.#zones.values(), ...this.#retired.values(), ...this.#priors]) { + zone.connection.setContentVersion(version); + } + } + /** The authoritative zone, if any. */ get authority(): GameZoneView | undefined { return this.#authority; @@ -323,7 +347,7 @@ export class GameClient { role: role === 'authority' ? 'player' : 'observer', ticket: role === 'authority' ? o.ticket : observerTicket, initialTicket, - contentVersion: o.contentVersion, + contentVersion: this.#contentVersion, capabilities: o.capabilities, socket: o.socket, scheduler: this.#scheduler, @@ -372,6 +396,11 @@ export class GameClient { const c = zone.connection; zone.offs.push( c.on('welcome', (welcome) => { + // A reload (Kick(RELOAD) / VERSION_MISMATCH) changed what this + // connection presents: later connections must present it too. + if (zone === this.#authority && c.contentVersion !== this.#contentVersion) { + this.setContentVersion(c.contentVersion); + } zone.replica.reset(welcome.schema, c.serverNow()); zone.replica.interpolationDelayMs = this.interpolationDelay(zone); zone.firstDeltaSeen = false; diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts index f6d0fa6b7..bd7c79ac6 100644 --- a/js/src/game/connection.ts +++ b/js/src/game/connection.ts @@ -401,6 +401,16 @@ export class GameConnection { this.#finish({ reason: 'client' }); } + /** + * Content version presented in the next Hello (reconnects, reloads). + * For clients that patch content live (e.g. after a Resume with a new + * version) without a reload round-trip; the server learns it on the + * next Hello. + */ + setContentVersion(contentVersion: string): void { + this.#contentVersion = contentVersion; + } + /** * Continue after a content reload (state `reload-required`): sends the * new `contentVersion` in Hello, with the reconnect token while the grace diff --git a/js/tests/game-world.test.mjs b/js/tests/game-world.test.mjs index eb362bb23..c436815a7 100644 --- a/js/tests/game-world.test.mjs +++ b/js/tests/game-world.test.mjs @@ -249,3 +249,43 @@ test('interpolation delay and view tick are exposed for lag compensation', async assert.deepEqual([...input.payload], [1, 100], 'encodeInput received the context'); client.close(); }); + +test('a reloaded content version is presented on later handoffs; setContentVersion patches live', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type === 'Hello') conn.send(welcome({ zoneId: conn.zoneId, contentVersion: 'c2' })); + }; + const client = new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: ({ zoneId }) => `fresh:${zoneId}`, + contentVersion: 'c1', + socket: network.factory, + scheduler, + pingIntervalMs: 60_000, + reloadContent: async (request) => request.version ?? 'c2' + }); + await client.connect('hub'); + assert.equal(client.contentVersion, 'c1'); + network.last('hub').send({ type: 'Kick', code: GameKickCode.RELOAD, message: 'content c2 required' }); + network.last('hub').close(); + await scheduler.advance(10); + assert.equal(network.last('hub').lastHello.contentVersion, 'c2', 'reloaded connection resumes on c2'); + assert.equal(client.contentVersion, 'c2', 'client learns the reloaded version'); + + // The next zone (handoff target) must not present the stale option value. + network.last('hub').send({ type: 'Handoff', targetZone: 'field', transferTicket: 'transfer:t1' }); + network.last('hub').close(); + await scheduler.advance(10); + assert.equal(network.last('field').lastHello.contentVersion, 'c2'); + + // Live patch: reconnects of the current connection and new ones present c3. + client.setContentVersion('c3'); + assert.equal(client.authority.connection.contentVersion, 'c3'); + await client.observe('meadow'); + assert.equal(network.last('meadow').lastHello.contentVersion, 'c3'); + client.authority.connection.dropTransport(); + await scheduler.advance(10); + assert.equal(network.last('field').lastHello.contentVersion, 'c3'); + client.close(); +}); From bf248ee40fb4b051fb2dfd3d16e6887bc9476421 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:33:12 -0500 Subject: [PATCH 145/484] feat(examples): add the Shooting Gallery lag-compensation demo Targets race on rails and circles; shooters fire hitscan rays from fixed stations. The zone resolves each shot with the rewind history at the shooter's exact view time (client_tick plus the delay to the rendered instant), clamped to 500 ms, or at the present when compensation is off. The client adapts its interpolation delay to the measured latency and compares predicted with confirmed hits. Refs [[tasks/gr-p10-demos]] --- examples/game/README.md | 15 + examples/game/client/gallery/index.html | 13 + examples/game/client/index.html | 1 + examples/game/client/src/gallery/client.ts | 295 ++++++++++ examples/game/client/src/gallery/gallery.css | 47 ++ examples/game/client/src/gallery/main.ts | 270 +++++++++ .../client/tests/gallery-headless.test.mjs | 104 ++++ examples/game/client/vite.config.ts | 2 +- examples/game/run.sh | 2 +- examples/game/server/src/gallery/mod.rs | 529 ++++++++++++++++++ examples/game/server/src/lib.rs | 1 + examples/game/server/src/main.rs | 4 + examples/game/server/tests/gallery_smoke.rs | 152 +++++ 13 files changed, 1433 insertions(+), 2 deletions(-) create mode 100644 examples/game/client/gallery/index.html create mode 100644 examples/game/client/src/gallery/client.ts create mode 100644 examples/game/client/src/gallery/gallery.css create mode 100644 examples/game/client/src/gallery/main.ts create mode 100644 examples/game/client/tests/gallery-headless.test.mjs create mode 100644 examples/game/server/src/gallery/mod.rs create mode 100644 examples/game/server/tests/gallery_smoke.rs diff --git a/examples/game/README.md b/examples/game/README.md index 2b3828194..c8e8fab96 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -9,6 +9,7 @@ guests and lets any page change the network simulation. | Demo | Run | Mechanic it demonstrates | |---|---|---| | **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | +| **Shooting Gallery** | `./run.sh gallery` | Lag compensation: hitscan shots resolved with `ctx.rewind().hit_test_shot` at the shooter's view time (`client_tick` + interpolation delay in the payload), `max_rewind` clamp, per-shot compensation on/off, predicted vs confirmed hits | `./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. @@ -35,6 +36,18 @@ NetSim sliders change the server's simulated one-way latency (applied in both directions), jitter and loss (a TCP-like retransmit delay) for every connection. +Shooting Gallery controls: click a target (or Space / gamepad A through the +crosshair), drag to look. **C** toggles lag compensation (sent with every +shot), **G** wireframe ghosts at the newest received target state. Set the +NetSim latency to 150–250 ms: with compensation the confirmed hits match the +predicted ones (yellow marker → green); without it most turn red. The +client's interpolation delay adapts to `rtt / 2 + 2 patches + 2 × jitter` +(the SDK clock estimates the server's *present*, so a fixed 100 ms would ask +for states not yet received); each shot carries `delay = tickTime(client_tick) +- renderTime`, so the server rewinds to exactly what was on screen. Beyond +`gallery::MAX_REWIND_MS` (500 ms of view age, ≈ 200 ms one way) shots are +clamped and reported as such. + ## Architecture ``` @@ -69,11 +82,13 @@ examples/game/ src/main.rs `game-demos ` subcommands src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events src/arena/ Arena zone + movement.rs (twin of client movement.ts) + src/gallery/ Shooting Gallery zone (targets, rewind hit tests); tests/gallery_smoke.rs tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css src/arena/ client.ts (headless), main.ts (Babylon), movement.ts + src/gallery/ client.ts (shots, adaptive delay), main.ts; tests/gallery-headless tests/ movement-parity, arena-headless (+ helpers/demo-server.mjs) ``` diff --git a/examples/game/client/gallery/index.html b/examples/game/client/gallery/index.html new file mode 100644 index 000000000..fd203adb5 --- /dev/null +++ b/examples/game/client/gallery/index.html @@ -0,0 +1,13 @@ + + + + + + Shooting Gallery Demo + + + +
+ + + diff --git a/examples/game/client/index.html b/examples/game/client/index.html index 8cca69766..9b40d817b 100644 --- a/examples/game/client/index.html +++ b/examples/game/client/index.html @@ -12,6 +12,7 @@

distributed_game demos

Each demo runs its own server: examples/game/run.sh <demo>. The page for the running demo works; the others need their server.

  • Arena — fixed tick, binary deltas, interest management, prediction + reconciliation, interpolation.
  • +
  • Shooting Gallery — lag compensation: hitscan shots rewound to the shooter's view time, max-rewind clamp, compensation on/off.
diff --git a/examples/game/client/src/gallery/client.ts b/examples/game/client/src/gallery/client.ts new file mode 100644 index 000000000..e315618db --- /dev/null +++ b/examples/game/client/src/gallery/client.ts @@ -0,0 +1,295 @@ +/** + * Shooting Gallery networking without rendering (Node-testable). + * + * - Targets are interpolated like any remote entity, but with an adaptive + * delay (`AdaptiveDelay`): the SDK's clock estimates the server's + * *present*, so a fixed 100 ms delay would ask for states that have not + * arrived yet once one-way latency exceeds it; the delay follows + * `rtt / 2 + 2 patch intervals + 2 × jitter`, slewed slowly. + * - `shoot(dir)` ray-tests the rendered targets locally (client-predicted + * hit marker) and sends one shot input carrying the exact view time: + * `client_tick` (input header) plus `delay = tickTime(client_tick) - + * renderTime` in the payload, so the server's `hit_test_shot` rewinds to + * precisely the instant that was on screen (clamped to `maxRewindMs`). + * - The server answers every shot with a verdict event; `stats` compares + * predicted and confirmed hits. + */ +import { GameClient, type GameSocketFactory, type GameZoneView, type RenderedEntity } from '@hops-ops/distributed/game'; + +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; + +export const DEFAULT_ZONE = 'gallery-1'; +/** Event type ids (server `gallery::EVENT_*`). */ +export const EVENT_HELLO = 1; +export const EVENT_SHOT = 2; +export const FLAG_FIRE = 1; +export const FLAG_NO_COMP = 2; +export const KIND = { shooter: 'shooter', target: 'target' } as const; + +export type Vec3 = [number, number, number]; + +export type GalleryHello = Readonly<{ entity: number; eye: Vec3; maxRewindMs: number; range: number; half: number }>; + +export type ShotVerdict = Readonly<{ + shot: number; + hit: number | null; + compensated: boolean; + ageMs: number; + requestedAgeMs: number; + clamped: boolean; + tick: number; +}>; + +export type ShotRecord = { + id: number; + dir: Vec3; + compensated: boolean; + /** Target the client saw the ray hit (undefined = predicted miss). */ + predicted: number | undefined; + /** Where the ray met the predicted target (for markers). */ + point: Vec3 | undefined; + delayMs: number; + sentAt: number; + verdict?: ShotVerdict; +}; + +export type GalleryStats = { + shots: number; + predictedHits: number; + confirmedHits: number; + /** Shots where client and server agree (hit/miss and target). */ + agreed: number; + /** Verdicts received. */ + resolved: number; + clamped: number; + /** Mean rewind age of compensated verdicts (ms). */ + meanAgeMs: number; + lastAgeMs: number; +}; + +/** Interpolation delay that follows the measured one-way latency. */ +export class AdaptiveDelay { + readonly minMs: number; + readonly maxMs: number; + /** Largest change per 100 ms of wall time (keeps the timeline smooth). */ + readonly slewMs: number; + #value: number; + #at: number | undefined; + + constructor(options: Readonly<{ minMs?: number; maxMs?: number; slewMs?: number }> = {}) { + this.minMs = options.minMs ?? 100; + this.maxMs = options.maxMs ?? 800; + this.slewMs = options.slewMs ?? 25; + this.#value = this.minMs; + } + + get value(): number { + return this.#value; + } + + /** Target delay for a zone right now. */ + target(zone: GameZoneView): number { + const clock = zone.connection.clock; + const patchMs = 1000 / (zone.connection.welcome?.patchRate || 20); + const wanted = clock.synced ? clock.rtt / 2 + 2 * patchMs + 2 * clock.jitter : 2 * patchMs; + return Math.min(this.maxMs, Math.max(this.minMs, wanted)); + } + + /** Current delay, moved toward `target(zone)` by at most `slewMs` / 100 ms. */ + sample(zone: GameZoneView, now: number): number { + const last = this.#at ?? now; + this.#at = now; + const budget = (this.slewMs * Math.max(0, now - last)) / 100; + const delta = this.target(zone) - this.#value; + this.#value += Math.max(-budget, Math.min(budget, delta)); + return this.#value; + } + + /** True when within `toleranceMs` of the target. */ + settled(zone: GameZoneView, toleranceMs = 5): boolean { + return Math.abs(this.target(zone) - this.#value) <= toleranceMs; + } +} + +export function encodeShot(flags: number, shot: number, delayMs: number, dir: Vec3): Uint8Array { + const bytes = new Uint8Array(11); + const view = new DataView(bytes.buffer); + view.setUint8(0, flags); + view.setUint16(1, shot & 0xffff, true); + view.setUint16(3, Math.max(0, Math.min(0xffff, Math.round(delayMs))), true); + const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; + for (let i = 0; i < 3; i += 1) { + view.setInt16(5 + i * 2, Math.round(Math.max(-1, Math.min(1, dir[i] / len)) * 32767), true); + } + return bytes; +} + +/** Entry distance of a ray (unit `dir`) into a sphere, if hit in front. */ +export function raySphere(origin: Vec3, dir: Vec3, center: Vec3, radius: number): number | undefined { + const oc: Vec3 = [origin[0] - center[0], origin[1] - center[1], origin[2] - center[2]]; + const c = oc[0] ** 2 + oc[1] ** 2 + oc[2] ** 2 - radius * radius; + if (c <= 0) return 0; + const b = oc[0] * dir[0] + oc[1] * dir[1] + oc[2] * dir[2]; + const h = b * b - c; + if (h < 0 || b > 0) return undefined; + return -b - Math.sqrt(h); +} + +export function targetPosition(entity: Pick): Vec3 { + const f = entity.fields; + return [Number(f.x ?? 0), Number(f.y ?? 0), Number(f.z ?? 0)]; +} + +export type GalleryClient = Readonly<{ + client: GameClient; + delay: AdaptiveDelay; + hello(): GalleryHello | undefined; + ready: Promise; + stats: GalleryStats; + shots: Map; + /** Targets as rendered now. */ + targets(): RenderedEntity[]; + /** Nearest rendered target on the ray from the eye along `dir`. */ + predict(dir: Vec3): { target: number | undefined; point: Vec3 | undefined }; + /** Fire along `dir` (game coordinates, z up) from the eye; undefined if not sent. */ + shoot(dir: Vec3, options?: { compensated?: boolean }): ShotRecord | undefined; + /** Resolves with the verdict of shot `id`. */ + verdict(id: number): Promise; + onVerdict(listener: (shot: ShotRecord) => void): () => void; +}>; + +export type GalleryClientOptions = Readonly<{ + api: DevApi; + base?: string; + socket?: GameSocketFactory; + delay?: AdaptiveDelay; +}>; + +export function createGalleryClient(options: GalleryClientOptions): GalleryClient { + const delay = options.delay ?? new AdaptiveDelay(); + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 250, + interpolationDelayMs: (zone) => delay.sample(zone, zone.connection.now()) + }); + let hello: GalleryHello | undefined; + let resolveReady: (h: GalleryHello) => void = () => undefined; + const ready = new Promise((resolve) => (resolveReady = resolve)); + onJsonEvent(client, EVENT_HELLO, (value) => { + hello = value; + resolveReady(value); + }); + + const stats: GalleryStats = { + shots: 0, + predictedHits: 0, + confirmedHits: 0, + agreed: 0, + resolved: 0, + clamped: 0, + meanAgeMs: 0, + lastAgeMs: 0 + }; + const shots = new Map(); + const waiters = new Map void>(); + const listeners = new Set<(shot: ShotRecord) => void>(); + let next = 0; + let compensatedVerdicts = 0; + + onJsonEvent(client, EVENT_SHOT, (verdict) => { + const shot = shots.get(verdict.shot); + if (shot === undefined || shot.verdict !== undefined) return; + shot.verdict = verdict; + stats.resolved += 1; + if (verdict.hit !== null) stats.confirmedHits += 1; + if ((verdict.hit ?? undefined) === shot.predicted) stats.agreed += 1; + if (verdict.clamped) stats.clamped += 1; + if (verdict.compensated) { + compensatedVerdicts += 1; + stats.meanAgeMs += (verdict.ageMs - stats.meanAgeMs) / compensatedVerdicts; + stats.lastAgeMs = verdict.ageMs; + } + waiters.get(verdict.shot)?.(verdict); + waiters.delete(verdict.shot); + for (const listener of listeners) listener(shot); + }); + + const targets = () => client.render().filter((e) => e.kindName === KIND.target && !e.stale); + + function predict(dir: Vec3): { target: number | undefined; point: Vec3 | undefined } { + const eye = hello?.eye; + if (eye === undefined) return { target: undefined, point: undefined }; + const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; + const unit: Vec3 = [dir[0] / len, dir[1] / len, dir[2] / len]; + let target: number | undefined; + let point: Vec3 | undefined; + let best = Infinity; + for (const entity of targets()) { + const d = raySphere(eye, unit, targetPosition(entity), Number(entity.fields.r ?? 0.5)); + if (d !== undefined && d < best && d <= (hello?.range ?? 80)) { + best = d; + target = entity.id; + point = [eye[0] + unit[0] * d, eye[1] + unit[1] * d, eye[2] + unit[2] * d]; + } + } + return { target, point }; + } + + function shoot(dir: Vec3, opts: { compensated?: boolean } = {}): ShotRecord | undefined { + const zone = client.authority; + const eye = hello?.eye; + if (zone === undefined || eye === undefined || !zone.connection.canSendInput()) return undefined; + const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; + const unit: Vec3 = [dir[0] / len, dir[1] / len, dir[2] / len]; + // Exact view time: the delay is measured from client_tick's time to + // the instant render() samples, so the server rewinds to what is drawn. + const context = client.inputContext(zone)!; + const renderTime = zone.connection.serverNow() - context.interpolationDelayMs; + const delayMs = Math.max(0, zone.connection.tickTime(context.clientTick) - renderTime); + const { target: predicted, point } = predict(unit); + const compensated = opts.compensated ?? true; + next = (next + 1) & 0xffff; + const id = next; + const flags = FLAG_FIRE | (compensated ? 0 : FLAG_NO_COMP); + const seq = zone.connection.sendInput(encodeShot(flags, id, delayMs, unit), context.clientTick); + if (seq === undefined) return undefined; + const record: ShotRecord = { + id, + dir: unit, + compensated, + predicted, + point, + delayMs, + sentAt: zone.connection.now() + }; + shots.set(id, record); + if (shots.size > 512) shots.delete(shots.keys().next().value!); + stats.shots += 1; + if (predicted !== undefined) stats.predictedHits += 1; + return record; + } + + return { + client, + delay, + hello: () => hello, + ready, + stats, + shots, + targets, + predict, + shoot, + verdict(id) { + const known = shots.get(id)?.verdict; + if (known !== undefined) return Promise.resolve(known); + return new Promise((resolve) => waiters.set(id, resolve)); + }, + onVerdict(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + } + }; +} diff --git a/examples/game/client/src/gallery/gallery.css b/examples/game/client/src/gallery/gallery.css new file mode 100644 index 000000000..cafaa140a --- /dev/null +++ b/examples/game/client/src/gallery/gallery.css @@ -0,0 +1,47 @@ +.crosshair { + position: fixed; + left: 50%; + top: 50%; + width: 18px; + height: 18px; + margin: -9px 0 0 -9px; + pointer-events: none; + border: 2px solid rgba(255, 255, 255, 0.75); + border-radius: 50%; + box-sizing: border-box; +} +.crosshair.kick { + animation: kick 120ms ease-out; +} +@keyframes kick { + from { + transform: scale(1.6); + border-color: #ffd84a; + } +} +.shot-feed { + position: fixed; + right: 12px; + bottom: 12px; + width: 340px; + margin: 0; + padding: 8px 12px 8px 28px; + border-radius: 8px; + background: var(--panel); + pointer-events: none; +} +.shot-feed:empty { + display: none; +} +.shot-feed .ok { + color: #59e08c; +} +.shot-feed .bad { + color: #ff5d5d; +} +@media (max-width: 640px) { + .shot-feed { + width: calc(100% - 24px); + box-sizing: border-box; + } +} diff --git a/examples/game/client/src/gallery/main.ts b/examples/game/client/src/gallery/main.ts new file mode 100644 index 000000000..3cbd94f8e --- /dev/null +++ b/examples/game/client/src/gallery/main.ts @@ -0,0 +1,270 @@ +/** + * Shooting Gallery page: first-person view from the player's station over + * `createGalleryClient`. + * + * - Click (or Space / gamepad A through the crosshair) fires a hitscan ray. + * A yellow marker shows the client-predicted hit immediately; when the + * server's verdict arrives it turns green (confirmed) or red (rejected). + * - C toggles lag compensation (sent per shot). Raise the NetSim latency to + * 150–250 ms: with compensation the confirmed hits keep up with the + * predicted ones, without it most "hits" are rejected. + * - G shows wireframe ghosts at the newest received target state (what the + * server had a one-way latency ago), next to the interpolated targets you + * aim at. + */ +import { Color3 } from '@babylonjs/core/Maths/math.color'; +import { Matrix, Vector3 } from '@babylonjs/core/Maths/math.vector'; +import type { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import type { Scene } from '@babylonjs/core/scene'; + +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { InputSampler } from '../shared/input.ts'; +import { createStage, material, toWorld } from '../shared/scene.ts'; +import { createGalleryClient, DEFAULT_ZONE, KIND, targetPosition, type ShotRecord, type Vec3 } from './client.ts'; +import './gallery.css'; + +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const name = params.get('name') ?? undefined; + +const api = new DevApi({ name: () => name }); +const gallery = createGalleryClient({ api }); +const { client } = gallery; + +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: 20, background: '#0b0f14' }); +const { scene, camera } = stage; + +// First person: an ArcRotateCamera orbiting a point 5 cm away is a look-around camera. +camera.lowerRadiusLimit = 0.05; +camera.upperRadiusLimit = 0.05; +camera.radius = 0.05; +camera.lowerBetaLimit = 1.2; +camera.upperBetaLimit = 1.85; +camera.beta = Math.PI / 2 - 0.05; +camera.alpha = -Math.PI / 2; +camera.angularSensibilityX = 2500; +camera.angularSensibilityY = 2500; +camera.fov = 0.9; +camera.minZ = 0.02; + +let compensation = true; +let ghostsOn = true; + +const hud = new Hud({ + title: 'Shooting Gallery', + hint: 'Click a target (or Space/A through the crosshair). Drag to look. C: lag compensation, G: server ghosts.', + client, + devApi: api +}); +hud.toggle('Lag compensation', true, (on) => (compensation = on), 'c'); +hud.toggle('Ghosts at newest server state', true, (on) => (ghostsOn = on), 'g'); + +const crosshair = document.createElement('div'); +crosshair.className = 'crosshair'; +document.body.append(crosshair); +const feed = document.createElement('ol'); +feed.className = 'shot-feed'; +document.body.append(feed); + +// ---- meshes ---- +const mats = { + target: material(scene, 'target', '#ff8a3d'), + flash: material(scene, 'flash', '#ffffff'), + ghost: material(scene, 'ghost', '#9ad1ff', 0.35), + station: material(scene, 'station', '#3a4556'), + me: material(scene, 'me-station', '#6cc4ff'), + rail: material(scene, 'rail', '#2b3442'), + predicted: material(scene, 'predicted', '#ffd84a'), + confirmed: material(scene, 'confirmed', '#59e08c'), + rejected: material(scene, 'rejected', '#ff5d5d') +}; +mats.ghost.wireframe = true; +for (const m of [mats.predicted, mats.confirmed, mats.rejected, mats.flash]) m.emissiveColor = m.diffuseColor.clone(); + +// Rails / circles (decor matching the server course) and the firing line. +for (const [y, half] of [ + [2, 12], + [6, 14], + [16, 16], + [-2, 10] +] as const) { + const rail = MeshBuilder.CreateBox('rail', { width: half * 2, height: 0.05, depth: 0.1 }, scene); + rail.position = toWorld(0, y, 0.03); + rail.material = mats.rail; +} +for (const [x, y, r] of [ + [-7, 11, 4], + [7, 11, 3] +] as const) { + const ring = MeshBuilder.CreateTorus('loop', { diameter: r * 2, thickness: 0.08, tessellation: 48 }, scene); + ring.position = toWorld(x, y, 0.04); + ring.material = mats.rail; +} +const line = MeshBuilder.CreateBox('firing-line', { width: 18, height: 0.04, depth: 0.15 }, scene); +line.position = toWorld(0, -13.2, 0.02); +line.material = mats.station; + +type TargetVisual = { mesh: Mesh; ghost: Mesh; flash: number; flashUntil: number }; +const targets = new Map(); +const shooters = new Map(); + +function targetVisual(key: string, r: number): TargetVisual { + let v = targets.get(key); + if (v === undefined) { + const mesh = MeshBuilder.CreateSphere(key, { diameter: r * 2, segments: 16 }, scene); + mesh.material = mats.target; + const ghost = MeshBuilder.CreateSphere(`${key}-ghost`, { diameter: r * 2, segments: 8 }, scene); + ghost.material = mats.ghost; + v = { mesh, ghost, flash: -1, flashUntil: 0 }; + targets.set(key, v); + } + return v; +} + +// ---- shot markers ---- +type Marker = { mesh: Mesh; until: number }; +const markers: Marker[] = []; + +function marker(at: Vec3, mat: StandardMaterial, size: number, ttl: number): Mesh { + const mesh = MeshBuilder.CreateSphere('marker', { diameter: size, segments: 6 }, scene); + mesh.position = toWorld(at[0], at[1], at[2]); + mesh.material = mat; + markers.push({ mesh, until: performance.now() + ttl }); + return mesh; +} + +const pending = new Map(); + +function fire(dir: Vec3): void { + const shot = gallery.shoot(dir, { compensated: compensation }); + if (shot === undefined) return; + if (shot.point !== undefined) pending.set(shot.id, marker(shot.point, mats.predicted, 0.35, 4000)); + crosshair.classList.remove('kick'); + void crosshair.offsetWidth; + crosshair.classList.add('kick'); +} + +gallery.onVerdict((shot: ShotRecord) => { + const v = shot.verdict!; + const predictedMarker = pending.get(shot.id); + pending.delete(shot.id); + const confirmed = v.hit !== null; + if (predictedMarker !== undefined) predictedMarker.material = confirmed && v.hit === shot.predicted ? mats.confirmed : mats.rejected; + else if (confirmed) { + const target = gallery.targets().find((t) => t.id === v.hit); + if (target !== undefined) marker(targetPosition(target), mats.confirmed, 0.3, 1500); + } + const li = document.createElement('li'); + const verdict = confirmed ? (shot.predicted === v.hit ? 'CONFIRMED' : `HIT #${v.hit} (unexpected)`) : shot.predicted === undefined ? 'miss' : 'REJECTED'; + li.className = confirmed ? 'ok' : shot.predicted === undefined ? '' : 'bad'; + li.textContent = `#${shot.id} ${verdict} · ${v.compensated ? `rewind ${v.ageMs.toFixed(0)} ms${v.clamped ? ` (clamped from ${v.requestedAgeMs.toFixed(0)})` : ''}` : 'no compensation'}`; + feed.prepend(li); + while (feed.children.length > 8) feed.lastChild?.remove(); +}); + +// ---- input ---- +const sampler = new InputSampler(); +let down: { x: number; y: number } | undefined; +canvas.addEventListener('pointerdown', (e) => (down = { x: e.clientX, y: e.clientY })); +canvas.addEventListener('pointerup', (e) => { + if (down === undefined) return; + const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y); + down = undefined; + if (moved > 6) return; // a drag looks around + const rect = canvas.getBoundingClientRect(); + const scale = stage.engine.getHardwareScalingLevel(); + const ray = scene.createPickingRay((e.clientX - rect.left) / scale, (e.clientY - rect.top) / scale, Matrix.Identity(), camera); + fire([ray.direction.x, ray.direction.z, ray.direction.y]); +}); +let actionWasDown = false; + +// ---- frame ---- +stage.onFrame((now) => { + const hello = gallery.hello(); + if (hello !== undefined) { + const eye = toWorld(hello.eye[0], hello.eye[1], hello.eye[2]); + if (!camera.target.equals(eye)) camera.setTarget(eye); + } + const s = sampler.sample(); + if (s.action && !actionWasDown) { + const forward = camera.getForwardRay(1).direction; + fire([forward.x, forward.z, forward.y]); + } + actionWasDown = s.action; + + const rendered = client.render(); + const authority = client.authority; + const seen = new Set(); + for (const entity of rendered) { + seen.add(entity.key); + if (entity.kindName === KIND.target) { + const v = targetVisual(entity.key, Number(entity.fields.r ?? 0.5)); + const p = targetPosition(entity); + v.mesh.position.copyFrom(toWorld(p[0], p[1], p[2])); + const flash = Number(entity.fields.flash ?? 0); + if (v.flash >= 0 && flash !== v.flash) v.flashUntil = now + 150; + v.flash = flash; + v.mesh.material = now < v.flashUntil ? mats.flash : mats.target; + const newest = authority?.replica.get(entity.id); + v.ghost.setEnabled(ghostsOn && newest !== undefined); + if (newest !== undefined) { + const f = newest.fields; + v.ghost.position.copyFrom(toWorld(Number(f.x), Number(f.y), Number(f.z))); + } + } else if (entity.kindName === KIND.shooter) { + let mesh = shooters.get(entity.key); + const mine = entity.id === hello?.entity; + if (mesh === undefined) { + mesh = MeshBuilder.CreateCylinder(entity.key, { diameter: 0.9, height: 0.15, tessellation: 24 }, scene); + mesh.material = mine ? mats.me : mats.station; + shooters.set(entity.key, mesh); + } + mesh.position.copyFrom(toWorld(Number(entity.fields.x), Number(entity.fields.y), 0.08)); + if (!mine) stage.labels.set(entity.key, mesh, `${String(entity.fields.name)} · ${entity.fields.hits}/${entity.fields.shots}`, 1.9); + } + } + for (const [key, v] of targets) { + if (seen.has(key)) continue; + v.mesh.dispose(); + v.ghost.dispose(); + targets.delete(key); + } + for (const [key, mesh] of shooters) { + if (seen.has(key)) continue; + mesh.dispose(); + stage.labels.delete(key); + shooters.delete(key); + } + for (let i = markers.length - 1; i >= 0; i -= 1) { + if (now > markers[i].until) { + markers[i].mesh.dispose(); + markers.splice(i, 1); + } + } + + hud.frame({ entities: rendered.length }); + const st = gallery.stats; + const pct = (n: number, d: number) => (d === 0 ? '—' : `${Math.round((100 * n) / d)}%`); + hud.row('Interp delay', authority === undefined ? '—' : `${gallery.delay.value.toFixed(0)} ms (target ${gallery.delay.target(authority).toFixed(0)})`); + hud.row('Compensation', compensation ? `ON (max ${hello?.maxRewindMs ?? '—'} ms)` : 'OFF'); + hud.row('Shots', String(st.shots)); + hud.row('Predicted hits', `${st.predictedHits} (${pct(st.predictedHits, st.shots)})`); + hud.row('Confirmed hits', `${st.confirmedHits} (${pct(st.confirmedHits, st.resolved)})`); + hud.row('Client = server', `${st.agreed}/${st.resolved} (${pct(st.agreed, st.resolved)})`); + hud.row('Rewind age', st.lastAgeMs === 0 ? '—' : `last ${st.lastAgeMs.toFixed(0)} · mean ${st.meanAgeMs.toFixed(0)} ms`); + hud.row('Clamped shots', String(st.clamped)); +}); + +declare global { + interface Window { + /** Debug handle (console). */ + gallery?: unknown; + } +} +window.gallery = { gallery, client, api, scene: scene as Scene, Vector3, Color3 }; + +client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/tests/gallery-headless.test.mjs b/examples/game/client/tests/gallery-headless.test.mjs new file mode 100644 index 000000000..2fa1e810c --- /dev/null +++ b/examples/game/client/tests/gallery-headless.test.mjs @@ -0,0 +1,104 @@ +/** + * Headless Shooting Gallery client against the real `game-demos gallery` + * binary: a scripted shooter aims at the fastest target *as rendered* + * under simulated latency. With lag compensation the server confirms the + * hits; without it the same aim mostly misses; beyond the max rewind the + * shots are clamped. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createGalleryClient, encodeShot, raySphere, targetPosition } from '../src/gallery/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; + +const FAST_TARGET = 5; // 12 m/s rail + +/** Fire `n` shots at the rendered fast target, wait for every verdict. */ +async function volley(gallery, n, compensated) { + const records = []; + while (records.length < n) { + await sleep(80); + const eye = gallery.hello().eye; + const target = gallery.targets().find((t) => t.id === FAST_TARGET); + const at = targetPosition(target); + const dir = [at[0] - eye[0], at[1] - eye[1], at[2] - eye[2]]; + // Another target in the line of fire: wait for a clear shot. + if (gallery.predict(dir).target !== FAST_TARGET) continue; + const shot = gallery.shoot(dir, { compensated }); + assert.ok(shot, 'shot sent'); + assert.equal(shot.predicted, FAST_TARGET, 'aimed at what is rendered'); + records.push(shot); + } + const verdicts = await Promise.all(records.map((r) => gallery.verdict(r.id))); + return { + hits: verdicts.filter((v) => v.hit === FAST_TARGET).length, + clamped: verdicts.filter((v) => v.clamped).length, + ages: verdicts.map((v) => v.ageMs), + requested: verdicts.map((v) => v.requestedAgeMs) + }; +} + +test('shot payload and local ray test', () => { + const bytes = encodeShot(3, 0x1234, 287.4, [0, 2, 0]); + assert.deepEqual([...bytes.slice(0, 5)], [3, 0x34, 0x12, 31, 1]); + assert.equal(new DataView(bytes.buffer).getInt16(7, true), 32767); + assert.equal(raySphere([0, 0, 0], [0, 1, 0], [0, 10, 0], 1), 9); + assert.equal(raySphere([0, 0, 0], [0, 1, 0], [0, -10, 0], 1), undefined, 'behind'); + assert.equal(raySphere([0, 0, 0], [0, 1, 0], [2, 10, 0], 1), undefined, 'beside'); +}); + +test('lag compensation confirms what the shooter saw; off misses; beyond max rewind clamps', { timeout: 600_000 }, async (t) => { + const server = await startDemo('gallery'); + const api = new DevApi({ base: server.httpUrl, name: () => 'Sharpshooter', storage: memoryStorage() }); + const gallery = createGalleryClient({ api, base: server.httpUrl }); + try { + await gallery.client.connect('gallery-1'); + const hello = await gallery.ready; + assert.equal(hello.maxRewindMs, 500); + await until(() => gallery.targets().length === 6, 5_000, 'targets'); + + // 100 ms one way (RTT ≈ 200 ms): the client draws targets ~300 ms in the past. + await api.setNetSim({ latencyMs: 100, jitterMs: 0, loss: 0 }); + const zone = gallery.client.authority; + await until(() => zone.connection.clock.rtt > 180, 10_000, 'rtt with latency'); + await until(() => gallery.targets() && gallery.delay.settled(zone, 10), 15_000, 'adaptive delay'); + assert.ok(gallery.delay.value > 190, `delay ${gallery.delay.value}`); + + const on = await volley(gallery, 20, true); + assert.ok(on.hits >= 18, `compensated hits ${on.hits}/20`); + assert.equal(on.clamped, 0); + const meanAge = on.ages.reduce((a, b) => a + b, 0) / on.ages.length; + assert.ok(meanAge > 250 && meanAge < 500, `rewind age ${meanAge}`); + + const off = await volley(gallery, 20, false); + assert.ok(off.hits <= 6, `uncompensated hits ${off.hits}/20`); + assert.ok(off.ages.every((a) => a === 0), 'no rewind without compensation'); + + // 300 ms one way: the view is ~700 ms old, more than the 500 ms clamp. + await api.setNetSim({ latencyMs: 300, jitterMs: 0, loss: 0 }); + await until(() => zone.connection.clock.rtt > 550, 15_000, 'rtt 600'); + await until(() => gallery.targets() && gallery.delay.settled(zone, 10), 20_000, 'adaptive delay 2'); + const far = await volley(gallery, 10, true); + t.diagnostic( + `comp on ${on.hits}/20 (mean rewind ${meanAge.toFixed(0)} ms) · off ${off.hits}/20 · 300 ms: clamped ${far.clamped}/10, hits ${far.hits}/10` + ); + assert.ok(far.clamped >= 9, `clamped ${far.clamped}/10`); + assert.ok(far.requested.every((r) => r > 520), `requested ${far.requested}`); + assert.ok(far.ages.every((a) => a <= 501), `ages ${far.ages}`); + + assert.equal(gallery.stats.resolved, 50); + assert.equal(gallery.stats.predictedHits, 50); + const me = gallery.client.render().find((e) => e.id === hello.entity); + await until( + () => gallery.client.render().find((e) => e.id === hello.entity)?.fields.shots === 50, + 5_000, + 'replicated shot counter' + ); + assert.equal(me.fields.name, 'Sharpshooter'); + } finally { + await api.setNetSim({ latencyMs: 0, jitterMs: 0, loss: 0 }).catch(() => undefined); + gallery.client.close(); + await server.stop(); + } +}); diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts index 62082e6cb..5565cd286 100644 --- a/examples/game/client/vite.config.ts +++ b/examples/game/client/vite.config.ts @@ -5,7 +5,7 @@ import { resolve } from 'node:path'; import { defineConfig } from 'vite'; -const DEMOS = ['arena']; +const DEMOS = ['arena', 'gallery']; const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; export default defineConfig({ diff --git a/examples/game/run.sh b/examples/game/run.sh index 770a5e4b5..4cbdf556b 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -16,7 +16,7 @@ REPO="$(cd "$HERE/../.." && pwd)" SERVER="$HERE/server" CLIENT="$HERE/client" BIN="$SERVER/target/debug/game-demos" -DEMOS=(arena) +DEMOS=(arena gallery) log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } diff --git a/examples/game/server/src/gallery/mod.rs b/examples/game/server/src/gallery/mod.rs new file mode 100644 index 000000000..fcb888a44 --- /dev/null +++ b/examples/game/server/src/gallery/mod.rs @@ -0,0 +1,529 @@ +//! **Shooting Gallery** — lag compensation by rewinding hit volumes. +//! +//! Targets race along rails and circles downrange; players stand at fixed +//! stations on the firing line and fire a hitscan ray from their eye. A +//! client renders targets ~one-way latency + two patch intervals in the past +//! (interpolation), so what it aimed at is not where the target is on the +//! server when the shot arrives. With **compensation on** the zone resolves +//! the shot with `ctx.rewind().hit_test_shot` at the shooter's view time +//! (input `client_tick` minus the interpolation delay carried in the +//! payload), clamped to [`MAX_REWIND_MS`]; with it **off** the shot is tested +//! against the latest state. +//! +//! Entities: +//! +//! | kind | ids | fields | +//! |---|---|---| +//! | 1 `shooter` | 1000 + player | x y name shots hits | +//! | 2 `target` | 1..=[`TARGETS`] | x y z r flash | +//! +//! Inputs are shots only ([`ShotInput`], 11 bytes). The shooter gets one +//! [`EVENT_SHOT`] (JSON) per shot with the verdict and the rewind used. + +use std::collections::BTreeMap; +use std::time::Duration; + +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::rewind::{Historic, HitQuery, RewindFrame, ShotTiming, Vec3}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + PlayerId, View, WorldView, Zone, +}; +use serde_json::json; + +use crate::common::{send_json_event, Demo, Guests}; + +/// Shooter kind. +pub const KIND_SHOOTER: u16 = 1; +/// Target kind. +pub const KIND_TARGET: u16 = 2; +/// Event: `{"entity", "eye": [x, y, z], "maxRewindMs", "range"}` (JSON). +pub const EVENT_HELLO: u32 = 1; +/// Event: shot verdict (JSON, see [`ShotVerdict`]). +pub const EVENT_SHOT: u32 = 2; +/// Floor half extent (m). +pub const HALF: f32 = 20.0; +/// Firing line (m, game y). +pub const FIRING_LINE: f32 = -14.0; +/// Eye height (m). +pub const EYE: f32 = 1.6; +/// Station spacing along the firing line (m). +pub const STATION_SPACING: f32 = 3.0; +/// Stations on the firing line. +pub const STATIONS: u32 = 5; +/// Furthest a shot is rewound (anti-cheat clamp). +pub const MAX_REWIND_MS: u64 = 500; +/// Hitscan range (m). +pub const RANGE: f32 = 80.0; +/// Number of targets. +pub const TARGETS: u32 = 6; +/// Input flag: this input is a shot. +pub const FLAG_FIRE: u8 = 1; +/// Input flag: evaluate without lag compensation. +pub const FLAG_NO_COMP: u8 = 2; + +const POS: FieldType = FieldType::quant_centered(HALF, 18); + +/// How a target moves. +#[derive(Debug, Clone, Copy)] +enum Path { + /// Ping-pong along x at `y` between `x0..x1` at `speed` m/s. + Rail { + y: f32, + x0: f32, + x1: f32, + speed: f32, + }, + /// Circle around `(cx, cy)` with radius `r` at `speed` m/s. + Circle { + cx: f32, + cy: f32, + r: f32, + speed: f32, + }, +} + +/// `(path, height, radius)` of every target. +const COURSE: [(Path, f32, f32); TARGETS as usize] = [ + ( + Path::Rail { + y: 2.0, + x0: -12.0, + x1: 12.0, + speed: 3.0, + }, + 1.4, + 0.7, + ), + ( + Path::Rail { + y: 6.0, + x0: -14.0, + x1: 14.0, + speed: 7.0, + }, + 1.8, + 0.6, + ), + ( + Path::Circle { + cx: -7.0, + cy: 11.0, + r: 4.0, + speed: 8.0, + }, + 2.2, + 0.6, + ), + ( + Path::Circle { + cx: 7.0, + cy: 11.0, + r: 3.0, + speed: 6.0, + }, + 1.2, + 0.6, + ), + ( + Path::Rail { + y: 16.0, + x0: -16.0, + x1: 16.0, + speed: 12.0, + }, + 2.6, + 0.6, + ), + ( + Path::Rail { + y: -2.0, + x0: -10.0, + x1: 10.0, + speed: 10.0, + }, + 1.0, + 0.5, + ), +]; + +/// Target position at simulation time `t` (seconds). +pub fn target_position(index: usize, t: f64) -> Vec3 { + let (path, z, _) = COURSE[index]; + match path { + Path::Rail { y, x0, x1, speed } => { + let len = f64::from(x1 - x0); + let d = (t * f64::from(speed)).rem_euclid(2.0 * len); + let along = if d <= len { d } else { 2.0 * len - d }; + [x0 + along as f32, y, z] + } + Path::Circle { cx, cy, r, speed } => { + let a = (t * f64::from(speed) / f64::from(r)).rem_euclid(std::f64::consts::TAU); + [cx + r * a.cos() as f32, cy + r * a.sin() as f32, z] + } + } +} + +/// Radius of target `index` (0-based). +pub fn target_radius(index: usize) -> f32 { + COURSE[index].2 +} + +/// Speed of target `index` (m/s). +pub fn target_speed(index: usize) -> f32 { + match COURSE[index].0 { + Path::Rail { speed, .. } | Path::Circle { speed, .. } => speed, + } +} + +/// One shot: `[flags, shot u16, delay_ms u16, dx i16, dy i16, dz i16]` +/// (little endian; the direction is a unit vector × 32767). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ShotInput { + /// [`FLAG_FIRE`] | [`FLAG_NO_COMP`]. + pub flags: u8, + /// Client shot id (echoed in the verdict). + pub shot: u16, + /// Interpolation delay behind `client_tick` the shooter was rendering (ms). + pub delay_ms: u16, + /// Unit aim direction (game x, y, z-up). + pub dir: Vec3, +} + +impl ShotInput { + /// Wire payload. + pub fn encode(&self) -> Vec { + let mut out = vec![self.flags]; + out.extend_from_slice(&self.shot.to_le_bytes()); + out.extend_from_slice(&self.delay_ms.to_le_bytes()); + for v in self.dir { + out.extend_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()); + } + out + } + + /// Parse a payload; `None` for a wrong length or a zero direction. + pub fn decode(bytes: &[u8]) -> Option { + if bytes.len() != 11 { + return None; + } + let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]); + let axis = |i: usize| f32::from(u16_at(i) as i16) / 32767.0; + let dir = [axis(5), axis(7), axis(9)]; + let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt(); + (len > 0.5).then(|| Self { + flags: bytes[0] & (FLAG_FIRE | FLAG_NO_COMP), + shot: u16_at(1), + delay_ms: u16_at(3), + dir: [dir[0] / len, dir[1] / len, dir[2] / len], + }) + } +} + +/// Per-shooter counters (server truth). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ShooterStats { + /// Shots resolved. + pub shots: u32, + /// Shots that hit. + pub hits: u32, + /// Shots whose requested rewind exceeded the clamp. + pub clamped: u32, +} + +/// The verdict sent to the shooter. +#[derive(Debug, Clone, PartialEq)] +pub struct ShotVerdict { + /// Client shot id. + pub shot: u16, + /// Target hit. + pub hit: Option, + /// Lag compensation used. + pub compensated: bool, + /// Rewind applied (0 without compensation). + pub age: Duration, + /// Rewind the client asked for. + pub requested_age: Duration, + /// Limited by [`MAX_REWIND_MS`] / the stored history. + pub clamped: bool, +} + +struct Shooter { + entity: u32, + name: String, + station: u32, + stats: ShooterStats, +} + +impl Shooter { + fn eye(&self) -> Vec3 { + let (x, y) = station_position(self.station); + [x, y, EYE] + } +} + +/// Station `i` position on the firing line. +pub fn station_position(station: u32) -> (f32, f32) { + let offset = station as f32 - (STATIONS - 1) as f32 / 2.0; + (offset * STATION_SPACING, FIRING_LINE) +} + +/// Zone construction parameters. +#[derive(Clone, Default)] +pub struct GalleryConfig { + /// Display names registered by the dev ticket endpoint. + pub guests: Guests, +} + +/// The Shooting Gallery zone. +pub struct Gallery { + guests: Guests, + shooters: BTreeMap, + targets: Vec, + flash: Vec, +} + +impl Gallery { + /// Server-side counters of a player. + pub fn stats(&self, player: PlayerId) -> Option { + self.shooters.get(&player).map(|s| s.stats) + } + + /// Current target positions. + pub fn targets(&self) -> &[Vec3] { + &self.targets + } + + fn free_station(&self) -> u32 { + (0..STATIONS) + .find(|i| self.shooters.values().all(|s| s.station != *i)) + .unwrap_or(self.shooters.len() as u32 % STATIONS) + } + + /// Resolve one shot of `player` (compensated or not). + pub fn resolve_shot( + &self, + ctx: &Ctx<'_, Self>, + player: PlayerId, + client_tick: u32, + shot: &ShotInput, + ) -> Option { + let shooter = self.shooters.get(&player)?; + let query = HitQuery::ray(shooter.eye(), shot.dir, RANGE); + let rewind = ctx.rewind(); + let latest = rewind.latest()?.time(); + let compensated = shot.flags & FLAG_NO_COMP == 0; + let timing = ShotTiming { + client_tick, + interp_delay: Duration::from_millis(shot.delay_ms.into()), + }; + let resolved = rewind.resolve(timing)?; + let (time, age) = if compensated { + (resolved.time, resolved.age) + } else { + (latest, Duration::ZERO) + }; + let hit = rewind + .hit_test(time, &query, |id| (1..=TARGETS).contains(&id)) + .map(|h| h.id); + Some(ShotVerdict { + shot: shot.shot, + hit, + compensated, + age, + requested_age: resolved.requested_age, + clamped: compensated && resolved.clamped, + }) + } +} + +impl Zone for Gallery { + type Config = GalleryConfig; + type Input = ShotInput; + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new() + .kind( + KindDef::new(KIND_SHOOTER, "shooter") + .field("x", POS) + .field("y", POS) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .field("shots", FieldType::U32) + .field("hits", FieldType::U32) + .priority(0.5), + ) + .kind( + KindDef::new(KIND_TARGET, "target") + .field("x", POS) + .field("y", POS) + .field( + "z", + FieldType::QuantF32 { + min: 0.0, + max: 4.0, + bits: 12, + }, + ) + .field("r", FieldType::F32) + .field("flash", FieldType::U8) + .priority(2.0), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, config: GalleryConfig) -> Self { + let t = ctx.sim_time().as_secs_f64(); + Self { + guests: config.guests, + shooters: BTreeMap::new(), + targets: (0..TARGETS as usize) + .map(|i| target_position(i, t)) + .collect(), + flash: vec![0; TARGETS as usize], + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self.guests.name(&principal).unwrap_or(principal); + let station = self.free_station(); + let shooter = Shooter { + entity: 1000 + player.0, + name, + station, + stats: ShooterStats::default(), + }; + let eye = shooter.eye(); + let entity = shooter.entity; + self.shooters.insert(player, shooter); + ctx.set_view(player, View::new(0.0, 0.0, 100.0)); + send_json_event( + ctx, + player, + EVENT_HELLO, + &json!({ + "entity": entity, + "eye": eye, + "maxRewindMs": MAX_REWIND_MS, + "range": RANGE, + "half": HALF, + }), + ); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.shooters.remove(&player); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + ShotInput::decode(payload).filter(|s| s.flags & FLAG_FIRE != 0) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + // Shots first, against the history up to the previous tick (what + // every client has been sent so far). + let players: Vec = self.shooters.keys().copied().collect(); + for player in players { + for input in ctx.take_inputs(player, ConsumePolicy::Drain) { + let Some(verdict) = self.resolve_shot(ctx, player, input.client_tick, &input.input) + else { + continue; + }; + let shooter = self.shooters.get_mut(&player).expect("present"); + shooter.stats.shots += 1; + shooter.stats.clamped += u32::from(verdict.clamped); + if let Some(id) = verdict.hit { + shooter.stats.hits += 1; + let flash = &mut self.flash[(id - 1) as usize]; + *flash = flash.wrapping_add(1); + } + send_json_event( + ctx, + player, + EVENT_SHOT, + &json!({ + "shot": verdict.shot, + "hit": verdict.hit, + "compensated": verdict.compensated, + "ageMs": verdict.age.as_secs_f64() * 1000.0, + "requestedAgeMs": verdict.requested_age.as_secs_f64() * 1000.0, + "clamped": verdict.clamped, + "tick": ctx.tick(), + }), + ); + } + } + let t = ctx.sim_time().as_secs_f64(); + for (i, pos) in self.targets.iter_mut().enumerate() { + *pos = target_position(i, t); + } + } + + fn record_rewind(&self, frame: &mut RewindFrame) { + for (i, pos) in self.targets.iter().enumerate() { + frame.push(Historic::sphere(i as u32 + 1, *pos, target_radius(i))); + } + } + + fn replicate(&self, out: &mut WorldView) { + for s in self.shooters.values() { + let (x, y) = station_position(s.station); + out.push(EntityState::new( + s.entity, + KIND_SHOOTER, + x, + y, + vec![ + FieldValue::F(x), + FieldValue::F(y), + FieldValue::Str(s.name.clone()), + FieldValue::U(s.stats.shots), + FieldValue::U(s.stats.hits), + ], + )); + } + for (i, p) in self.targets.iter().enumerate() { + out.push( + EntityState::new( + i as u32 + 1, + KIND_TARGET, + p[0], + p[1], + vec![ + FieldValue::F(p[0]), + FieldValue::F(p[1]), + FieldValue::F(p[2]), + FieldValue::F(target_radius(i)), + FieldValue::U(self.flash[i].into()), + ], + ) + .global(), + ); + } + } +} + +/// Demo registration (`game-demos gallery`). +pub struct GalleryDemo; + +impl Demo for GalleryDemo { + type Zone = Gallery; + const NAME: &'static str = "gallery"; + const DEFAULT_ZONE: &'static str = "gallery-1"; + + fn hosts_zone(zone_id: &str) -> bool { + zone_id.starts_with("gallery-") + } + + fn server(mut config: ServerConfig, guests: Guests) -> GameServer { + config.host.rewind.max_rewind = Duration::from_millis(MAX_REWIND_MS); + GameServer::new(config, move |zone_id| { + Self::hosts_zone(zone_id).then(|| GalleryConfig { + guests: guests.clone(), + }) + }) + } +} diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index 7bfa7546f..e3e199265 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -8,3 +8,4 @@ pub mod arena; pub mod common; +pub mod gallery; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs index 7fde2d462..075de470b 100644 --- a/examples/game/server/src/main.rs +++ b/examples/game/server/src/main.rs @@ -3,6 +3,7 @@ use clap::{Parser, Subcommand}; use game_demos::arena::ArenaDemo; use game_demos::common::{run, DemoArgs}; +use game_demos::gallery::GalleryDemo; #[derive(Parser)] #[command( @@ -18,11 +19,14 @@ struct Cli { enum DemoCommand { /// Prediction, reconciliation, interpolation and interest management. Arena(DemoArgs), + /// Lag compensation: hitscan shots rewound to the shooter's view time. + Gallery(DemoArgs), } #[tokio::main] async fn main() -> std::io::Result<()> { match Cli::parse().demo { DemoCommand::Arena(args) => run::(args).await, + DemoCommand::Gallery(args) => run::(args).await, } } diff --git a/examples/game/server/tests/gallery_smoke.rs b/examples/game/server/tests/gallery_smoke.rs new file mode 100644 index 000000000..5a2af3fd1 --- /dev/null +++ b/examples/game/server/tests/gallery_smoke.rs @@ -0,0 +1,152 @@ +//! Shooting Gallery: deterministic lag-compensation checks on a +//! `ZoneHost` driven by a `ManualClock` (the end-to-end run under simulated +//! latency is `client/tests/gallery-headless.test.mjs`). + +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::{HostConfig, ManualClock, Role, TicketClaims, Viewer, ZoneHost}; +use game_demos::gallery::{ + self, Gallery, GalleryConfig, ShotInput, FLAG_FIRE, FLAG_NO_COMP, MAX_REWIND_MS, +}; + +const DT: Duration = Duration::from_nanos(33_333_333); + +struct Rig { + clock: ManualClock, + host: ZoneHost, + client: distributed_game::ClientId, + player: distributed_game::PlayerId, + seq: u32, +} + +impl Rig { + fn new() -> Self { + let clock = ManualClock::new(); + let mut config = HostConfig::default(); + config.rewind.max_rewind = Duration::from_millis(MAX_REWIND_MS); + let mut host = ZoneHost::::new( + "gallery-1", + config, + Arc::new(clock.clone()), + GalleryConfig::default(), + ); + let joined = host + .join( + &TicketClaims { + principal: "guest-test".into(), + zone: "gallery-1".into(), + expires_at: u64::MAX, + nonce: "n1".into(), + role: Role::Player, + }, + 0, + "", + ) + .unwrap(); + let Viewer::Player(player) = joined.viewer else { + panic!("player") + }; + let mut rig = Self { + clock, + host, + client: joined.client, + player, + seq: 0, + }; + rig.ticks(60); + rig + } + + fn ticks(&mut self, n: u32) { + for _ in 0..n { + self.clock.advance(DT); + self.host.advance(); + } + self.host.drain_outbound(); + } + + /// Aim from station 0's eye at target `id` as it was `ago` ticks + /// before the latest recorded tick; claim `delay_ms` of interpolation. + fn shoot(&mut self, id: u32, ago: u64, delay_ms: u16, flags: u8) -> gallery::ShooterStats { + let latest = self.host.rewind().latest().unwrap().tick(); + let seen = self + .host + .rewind() + .at(latest - ago) + .and_then(|f| f.get(id)) + .unwrap() + .pos; + let (x, y) = gallery::station_position(0); + let d = [seen[0] - x, seen[1] - y, seen[2] - gallery::EYE]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + self.seq += 1; + let shot = ShotInput { + flags: FLAG_FIRE | flags, + shot: self.seq as u16, + delay_ms, + dir: [d[0] / len, d[1] / len, d[2] / len], + }; + self.host + .push_input(self.client, self.seq, latest as u32, &shot.encode()); + self.ticks(1); + self.host.zone().stats(self.player).unwrap() + } +} + +#[test] +fn shot_payload_round_trips() { + let shot = ShotInput { + flags: FLAG_FIRE | FLAG_NO_COMP, + shot: 513, + delay_ms: 287, + dir: [0.6, 0.8, 0.0], + }; + let back = ShotInput::decode(&shot.encode()).unwrap(); + assert_eq!((back.flags, back.shot, back.delay_ms), (3, 513, 287)); + assert!((back.dir[0] - 0.6).abs() < 1e-4 && (back.dir[1] - 0.8).abs() < 1e-4); + assert_eq!(ShotInput::decode(&[1, 0, 0]), None, "wrong length"); + assert_eq!(ShotInput::decode(&[1; 10]), None); + assert_eq!( + ShotInput::decode(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + None, + "zero direction" + ); +} + +#[test] +fn rewound_shots_hit_what_the_shooter_saw() { + let mut rig = Rig::new(); + // Fast rail target (id 5, 12 m/s) as rendered 300 ms ago: 9 ticks. + let s = rig.shoot(5, 9, 300, 0); + assert_eq!((s.shots, s.hits, s.clamped), (1, 1, 0), "compensated hit"); + // Same aim without compensation: the target moved ~3.6 m. + let s = rig.shoot(5, 9, 300, FLAG_NO_COMP); + assert_eq!((s.shots, s.hits), (2, 1), "uncompensated miss"); + // Uncompensated shots hit only when aimed at the present. + let s = rig.shoot(5, 0, 0, FLAG_NO_COMP); + assert_eq!(s.hits, 2); + // Claiming 2 s of delay is clamped to MAX_REWIND_MS: aiming 2 s back + // misses, aiming at the clamp (15 ticks = 500 ms) still hits. + let s = rig.shoot(5, 15, 2000, 0); + assert_eq!((s.shots, s.hits, s.clamped), (4, 3, 1)); + let s = rig.shoot(2, 15, 2000, 0); + assert_eq!((s.shots, s.clamped), (5, 2)); +} + +#[test] +fn targets_move_deterministically() { + let a = gallery::target_position(4, 1.0); + let b = gallery::target_position(4, 1.0 + 1.0 / 30.0); + let step = ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt(); + assert!( + (step - gallery::target_speed(4) / 30.0).abs() < 1e-3, + "{step}" + ); + for i in 0..gallery::TARGETS as usize { + for k in 0..300 { + let p = gallery::target_position(i, f64::from(k) * 0.1); + assert!(p[0].abs() < gallery::HALF && p[1].abs() < gallery::HALF); + } + } +} From 1541208aec96882cb80b05b6b1188adc6ecf3839 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:45:10 -0500 Subject: [PATCH 146/484] feat(examples): add Endless Grid and Boss Ripple servers Two multi-host demos on a shared cluster module (--host-id, --peer, admin secret derived from the ticket secret, epoch-based fenced claims, SQLite snapshots, guest names shared with peers): - grid: procedural 32 m cells as zones on a hash ring, handoff across borders and hosts, hibernation of critters and markers, world map dev route; Rust/TS parity fixture for terrain, props and movement. - ripple: realm > city > borough > hood with per-tier tick rates, bosses whose defeats cascade upward as tier-up events, every hop on a different host. Refs [[tasks/gr-p10-demos]] --- examples/game/fixtures/grid-world.json | 13 + examples/game/server/Cargo.lock | 200 ++++++ examples/game/server/Cargo.toml | 4 +- examples/game/server/src/cluster.rs | 521 ++++++++++++++ examples/game/server/src/grid/dev.rs | 186 +++++ examples/game/server/src/grid/mod.rs | 657 +++++++++++++++++ examples/game/server/src/grid/world.rs | 435 ++++++++++++ examples/game/server/src/lib.rs | 3 + examples/game/server/src/main.rs | 9 + examples/game/server/src/ripple/mod.rs | 788 +++++++++++++++++++++ examples/game/server/tests/grid_fixture.rs | 156 ++++ examples/game/server/tests/grid_smoke.rs | 305 ++++++++ examples/game/server/tests/ripple_smoke.rs | 196 +++++ examples/game/server/tests/support/mod.rs | 304 ++++++++ 14 files changed, 3776 insertions(+), 1 deletion(-) create mode 100644 examples/game/fixtures/grid-world.json create mode 100644 examples/game/server/src/cluster.rs create mode 100644 examples/game/server/src/grid/dev.rs create mode 100644 examples/game/server/src/grid/mod.rs create mode 100644 examples/game/server/src/grid/world.rs create mode 100644 examples/game/server/src/ripple/mod.rs create mode 100644 examples/game/server/tests/grid_fixture.rs create mode 100644 examples/game/server/tests/grid_smoke.rs create mode 100644 examples/game/server/tests/ripple_smoke.rs create mode 100644 examples/game/server/tests/support/mod.rs diff --git a/examples/game/fixtures/grid-world.json b/examples/game/fixtures/grid-world.json new file mode 100644 index 000000000..bcd3ef763 --- /dev/null +++ b/examples/game/fixtures/grid-world.json @@ -0,0 +1,13 @@ +{ + "description": "Endless Grid parity: Rust grid::world vs client/src/grid/world.ts", + "constants": {"cell":32.0,"contentVersion":1,"hashes":[0,1753845952,3861431939,1734902346],"hysteresis":0.5,"mix":[81375972,3890567552],"playerRadius":0.44999998807907104,"propMargin":2.0,"seed":12648430,"sprint":10.0,"walk":6.0}, + "cells": [ + {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[0,0],"heights":[0.5932726860046387,0.6191548109054565,0.6287701725959778,0.5684976577758789,0.506608247756958,0.476431667804718,0.4526447653770447,0.40599799156188965,0.3470003008842468,0.5986464619636536,0.6271780133247375,0.6407992243766785,0.5713481307029724,0.499041885137558,0.48792269825935364,0.4807089567184448,0.43712469935417175,0.38371312618255615,0.6058180928230286,0.6377806663513184,0.6576048135757446,0.583746075630188,0.504568338394165,0.50711590051651,0.5085848569869995,0.4628223776817322,0.41231948137283325,0.612625241279602,0.6260185837745667,0.6300536394119263,0.5916079878807068,0.5455343723297119,0.5089141130447388,0.46644169092178345,0.44517818093299866,0.42410480976104736,0.6159852743148804,0.6130355596542358,0.6021124720573425,0.5914559960365295,0.5723928809165955,0.5054858326911926,0.43087658286094666,0.43410351872444153,0.4395725727081299,0.6654882431030273,0.6511151790618896,0.6289829611778259,0.6039171814918518,0.5709450244903564,0.5380295515060425,0.5008229613304138,0.4601622223854065,0.4185706079006195,0.7117636203765869,0.6877931356430054,0.6561192870140076,0.6189549565315247,0.5746230483055115,0.5735785961151123,0.5749499797821045,0.5053251385688782,0.4283277094364166,0.6724258065223694,0.6588683128356934,0.6377082467079163,0.6132182478904724,0.5823083519935608,0.5772964954376221,0.5812021493911743,0.5429924130439758,0.4911908209323883,0.6354392170906067,0.6307666897773743,0.6188353896141052,0.6054155230522156,0.5861055254936218,0.5758660435676575,0.5773574709892273,0.5610383749008179,0.5286053419113159],"moisture":[0.9225814342498779,0.9209369421005249,0.9161432385444641,0.9084103107452393,0.897948145866394,0.8849667310714722,0.8696759343147278,0.8522856831550598,0.833005964756012,0.9203137755393982,0.9186764359474182,0.9139037132263184,0.9062045812606812,0.8957881927490234,0.882863461971283,0.8676395416259766,0.8503252863883972,0.8311298489570618,0.9141969680786133,0.9125790596008301,0.9078628420829773,0.9002548456192017,0.889961838722229,0.8771901726722717,0.8621464371681213,0.8450372815132141,0.8260691165924072,0.9044886827468872,0.9029015302658081,0.8982750177383423,0.8908117413520813,0.880714476108551,0.8681857585906982,0.8534281849861145,0.8366444110870361,0.8180370330810547,0.8914466500282288,0.889900803565979,0.885394811630249,0.8781259655952454,0.8682916760444641,0.8560892343521118,0.8417160511016846,0.8253694176673889,0.8072466850280762,0.8753284811973572,0.8738337755203247,0.8694766759872437,0.8624480366706848,0.8529387712478638,0.8411396741867065,0.8272415399551392,0.8114351630210876,0.7939113974571228,0.8563919067382812,0.8549572229385376,0.8507750630378723,0.8440287113189697,0.8349013328552246,0.8235759735107422,0.8102359771728516,0.7950643301010132,0.7782442569732666,0.834894597530365,0.8335280418395996,0.8295445442199707,0.8231185674667358,0.8144246935844421,0.8036372661590576,0.7909308075904846,0.7764797210693359,0.7604585289955139,0.8110942840576172,0.8098031282424927,0.8060395121574402,0.7999683022499084,0.7917543649673462,0.7815624475479126,0.7695574164390564,0.7559041380882263,0.7407673597335815],"props":[[0,2.6997311115264893,3.5492422580718994,0.5242127180099487,true,19],[0,20.319786071777344,2.439387321472168,0.6280530691146851,true,104],[0,29.571075439453125,4.204550266265869,0.5941054821014404,true,77],[0,28.727685928344727,12.843689918518066,0.5227029919624329,true,18],[2,2.6637513637542725,20.259355545043945,0.5979864001274109,false,100],[0,10.334222793579102,21.184724807739258,0.7090258598327637,true,171],[0,21.481861114501953,20.544662475585938,0.6859129667282104,true,152],[2,27.356979370117188,19.172718048095703,0.7472004294395447,false,253],[0,4.534152030944824,26.57033920288086,0.6718509793281555,true,140],[0,10.943948745727539,27.216060638427734,0.6537189483642578,true,125],[0,21.012920379638672,26.721946716308594,0.7434372901916504,true,199]]}, + {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,2,2],"cell":[-1,0],"heights":[0.4879056513309479,0.5361763834953308,0.5719524621963501,0.5911566615104675,0.617572546005249,0.6191596984863281,0.6134335398674011,0.607620894908905,0.5932726860046387,0.4937855303287506,0.5281368494033813,0.5436740517616272,0.5619687438011169,0.5938694477081299,0.6191307902336121,0.6376091241836548,0.6225482821464539,0.5986464619636536,0.5442072153091431,0.559651255607605,0.5435690879821777,0.5464216470718384,0.5757881999015808,0.6204748153686523,0.659502387046814,0.6373487114906311,0.6058180928230286,0.6223092079162598,0.6223706603050232,0.578648030757904,0.555199384689331,0.5708223581314087,0.6146619319915771,0.6540663242340088,0.6381969451904297,0.612625241279602,0.6648482084274292,0.6553021669387817,0.5970399975776672,0.5603602528572083,0.5680696964263916,0.6101231575012207,0.6485512256622314,0.6369460225105286,0.6159852743148804,0.6821573376655579,0.6640446186065674,0.6098151803016663,0.6010086536407471,0.6244459748268127,0.6555972099304199,0.6784183979034424,0.6735973358154297,0.6654882431030273,0.6619725227355957,0.6480416059494019,0.6232592463493347,0.6636747717857361,0.7115744948387146,0.7276552319526672,0.7254219651222229,0.7144866585731506,0.7117636203765869,0.6366078853607178,0.6480674147605896,0.6731057167053223,0.7349919676780701,0.7804715633392334,0.7645105123519897,0.720649778842926,0.6868299841880798,0.6724258065223694,0.6471416354179382,0.6704965233802795,0.7175806760787964,0.7777050733566284,0.8118277192115784,0.7723835110664368,0.701501190662384,0.6561596989631653,0.6354392170906067],"moisture":[0.8806808590888977,0.8896992802619934,0.8978338837623596,0.9049864411354065,0.9110587239265442,0.9159526228904724,0.9195698499679565,0.921812117099762,0.9225814342498779,0.8787924647331238,0.887729287147522,0.8957902789115906,0.9028780460357666,0.9088953733444214,0.9137449860572815,0.9173294305801392,0.919551432132721,0.9203137755393982,0.8736987709999084,0.8824153542518616,0.8902777433395386,0.8971908688545227,0.9030599594116211,0.9077900052070618,0.9112861752510071,0.9134534597396851,0.9141969680786133,0.8656143546104431,0.8739814162254333,0.8815285563468933,0.8881644606590271,0.8937982320785522,0.8983386158943176,0.9016945958137512,0.9037749767303467,0.9044886827468872,0.8547537326812744,0.8626512885093689,0.8697749376296997,0.8760384917259216,0.8813560605049133,0.8856416940689087,0.888809323310852,0.8907729983329773,0.8914466500282288,0.8413316011428833,0.8486488461494446,0.8552490472793579,0.861052393913269,0.8659793138504028,0.8699500560760498,0.87288498878479,0.8747043013572693,0.8753284811973572,0.8255624175071716,0.8321979641914368,0.8381832242012024,0.843445897102356,0.8479138016700745,0.8515145778656006,0.8541760444641113,0.8558259010314941,0.8563919067382812,0.8076608180999756,0.813522458076477,0.8188096284866333,0.8234584927558899,0.8274052739143372,0.8305861353874207,0.8329371809959412,0.8343945741653442,0.834894597530365,0.7878413796424866,0.7928462028503418,0.7973605394363403,0.8013298511505127,0.8046996593475342,0.8074155449867249,0.8094229698181152,0.8106673359870911,0.8110942840576172],"props":[[0,19.097110748291016,5.61630916595459,0.6776201128959656,true,145],[0,26.24727439880371,5.479523658752441,0.6100752949714661,true,90],[0,5.130196571350098,11.272446632385254,0.6444254517555237,true,118],[0,19.86644744873047,12.887415885925293,0.5775140523910522,true,63],[0,29.14185333251953,11.574310302734375,0.7816622257232666,true,230],[0,4.698641777038574,18.850263595581055,0.7559527158737183,true,209],[2,11.599629402160645,20.818233489990234,0.6331537365913391,false,136],[1,27.429126739501953,21.335290908813477,0.8450204133987427,true,150],[0,4.095309257507324,27.893505096435547,0.5584002733230591,true,47],[1,21.594541549682617,29.985082626342773,0.9263221025466919,true,205]]}, + {"biomes":[2,2,2,2,2,2,3,3,3,2,2,2,2,2,2,2,3,3,2,2,2,2,2,2,2,3,3,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[1,-1],"heights":[0.42138075828552246,0.40141475200653076,0.39124739170074463,0.41956472396850586,0.43916285037994385,0.432271271944046,0.4294608235359192,0.4508451819419861,0.47138655185699463,0.45944392681121826,0.4243382215499878,0.3924155831336975,0.38853707909584045,0.3834754526615143,0.36564576625823975,0.35151854157447815,0.37482354044914246,0.400425523519516,0.5155394673347473,0.4601888060569763,0.39446061849594116,0.348171204328537,0.31514886021614075,0.2859475314617157,0.25848180055618286,0.27967092394828796,0.3077928423881531,0.5293982625007629,0.47131720185279846,0.38974568247795105,0.3340299427509308,0.3055242598056793,0.25335049629211426,0.20097412168979645,0.20033006370067596,0.21104685962200165,0.5239297151565552,0.4678651988506317,0.3830241858959198,0.32936185598373413,0.30893680453300476,0.23856870830059052,0.16770951449871063,0.15107545256614685,0.14831487834453583,0.4844319522380829,0.4264620542526245,0.34375059604644775,0.2833406329154968,0.252756804227829,0.2121821790933609,0.17443953454494476,0.16420844197273254,0.1663990318775177,0.42037874460220337,0.3649688959121704,0.29274648427963257,0.23549142479896545,0.2006106972694397,0.18751025199890137,0.1829589456319809,0.18365724384784698,0.19249162077903748,0.3685966432094574,0.3160467743873596,0.25430747866630554,0.22343163192272186,0.20760875940322876,0.18155789375305176,0.16938230395317078,0.17390522360801697,0.1821434199810028,0.3470003008842468,0.2953859865665436,0.2377258837223053,0.22395597398281097,0.22219297289848328,0.18450671434402466,0.16285213828086853,0.16717854142189026,0.17335659265518188],"moisture":[0.7218424081802368,0.7066196203231812,0.6903294324874878,0.6731244325637817,0.6551569700241089,0.6365795135498047,0.6175447106361389,0.5982049107551575,0.5787125825881958,0.7459695339202881,0.7295016646385193,0.7118791341781616,0.6932669878005981,0.673829972743988,0.6537331342697144,0.6331414580345154,0.6122198700904846,0.5911333560943604,0.7677018642425537,0.7501124739646912,0.7312898635864258,0.7114101648330688,0.6906495094299316,0.6691840887069702,0.6471900939941406,0.6248437762260437,0.602321207523346,0.7867749929428101,0.7682013511657715,0.7483254671096802,0.7273334264755249,0.7054109573364258,0.6827444434165955,0.6595197916030884,0.6359229683876038,0.6121401786804199,0.802924633026123,0.7835177183151245,0.7627500295639038,0.7408159971237183,0.7179099321365356,0.6942263841629028,0.6699596047401428,0.6453040838241577,0.6204540729522705,0.8158867359161377,0.795810878276825,0.7743273973464966,0.75163733959198,0.7279418706893921,0.7034419775009155,0.6783388257026672,0.6528334617614746,0.6271270513534546,0.8253968954086304,0.8048302531242371,0.7828216552734375,0.7595769166946411,0.735302209854126,0.7102034091949463,0.6844866275787354,0.6583577394485474,0.6320229172706604,0.831190824508667,0.8103252649307251,0.7879966497421265,0.7644140720367432,0.7397863864898682,0.7143227458000183,0.6882320642471313,0.6617233753204346,0.6350056529045105,0.833005964756012,0.8120467066764832,0.7896178960800171,0.7659293413162231,0.7411910891532898,0.7156131267547607,0.6894053220748901,0.6627776026725769,0.6359399557113647],"props":[[2,2.6364169120788574,5.466867446899414,0.5331394672393799,false,33],[0,18.785797119140625,5.822574138641357,0.6876273155212402,true,153],[0,2.7611401081085205,10.10028076171875,0.5881384611129761,true,72],[2,11.367517471313477,13.671693801879883,0.5278894901275635,false,28],[0,18.445932388305664,13.27216911315918,0.6055808663368225,true,86],[0,11.479331016540527,20.873830795288086,0.617036759853363,true,95],[0,18.60265350341797,18.293407440185547,0.7304015159606934,true,188],[0,29.521440505981445,19.42812156677246,0.6016110777854919,true,83],[0,4.589646339416504,29.109691619873047,0.5978066921234131,true,80],[0,13.470664978027344,28.999820709228516,0.6673028469085693,true,137],[0,18.913860321044922,29.154817581176758,0.7499248385429382,true,204],[0,29.176136016845703,27.976917266845703,0.7947177886962891,true,241]]}, + {"biomes":[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],"cell":[3,-7],"heights":[0.44168463349342346,0.4462580978870392,0.4758754372596741,0.5119243860244751,0.5240926146507263,0.5060517191886902,0.47019070386886597,0.4644808769226074,0.48008018732070923,0.43155404925346375,0.47093355655670166,0.5339734554290771,0.5748621821403503,0.5923664569854736,0.5602777600288391,0.5095936059951782,0.48983877897262573,0.48950710892677307,0.42734962701797485,0.4953855872154236,0.5845286846160889,0.627734899520874,0.6492524147033691,0.6065821051597595,0.5449163913726807,0.5144485235214233,0.5012316703796387,0.4742732644081116,0.5199416875839233,0.5842570066452026,0.618760347366333,0.6332355737686157,0.6235742568969727,0.5945666432380676,0.557242214679718,0.5351199507713318,0.5101231336593628,0.5382350087165833,0.5838687419891357,0.6132137775421143,0.6229410171508789,0.6408824920654297,0.6388668417930603,0.5955400466918945,0.5658830404281616,0.49519073963165283,0.5091087818145752,0.5367494225502014,0.5691434144973755,0.5851179361343384,0.6196902394294739,0.6370555758476257,0.6121094822883606,0.5962793827056885,0.45497655868530273,0.4533257484436035,0.457935631275177,0.484584242105484,0.5018151998519897,0.5534920692443848,0.5944374203681946,0.5922531485557556,0.5913298726081848,0.36176007986068726,0.3889848589897156,0.4152972102165222,0.4129660129547119,0.40809959173202515,0.47236132621765137,0.532341718673706,0.5400242209434509,0.5416451692581177,0.30415835976600647,0.3565188944339752,0.40500175952911377,0.3831290006637573,0.3615923523902893,0.43301910161972046,0.5028873085975647,0.5131760239601135,0.5143986940383911],"moisture":[0.5350773930549622,0.5283440351486206,0.5222705602645874,0.5169302821159363,0.5123965740203857,0.5087426900863647,0.5060420036315918,0.5043678283691406,0.503793478012085,0.5299458503723145,0.5241599678993225,0.5189410448074341,0.5143522024154663,0.510456383228302,0.5073166489601135,0.5049960017204285,0.5035573840141296,0.5030638575553894,0.5244593024253845,0.5196864604949951,0.5153812170028687,0.5115957856178284,0.5083820819854736,0.5057920217514038,0.5038776993751526,0.5026909112930298,0.5022838115692139,0.518669068813324,0.5149652361869812,0.5116243362426758,0.5086867809295654,0.5061928629875183,0.5041829943656921,0.5026974081993103,0.5017764568328857,0.5014605522155762,0.5126261711120605,0.5100380778312683,0.5077035427093506,0.5056508779525757,0.5039082169532776,0.5025037527084351,0.5014656782150269,0.500822126865387,0.5006013512611389,0.5063818693161011,0.5049466490745544,0.503652036190033,0.5025137066841125,0.5015473365783691,0.5007684826850891,0.5001928210258484,0.4998359680175781,0.4997135400772095,0.49998724460601807,0.4997326731681824,0.4995030164718628,0.49930107593536377,0.49912965297698975,0.4989914894104004,0.49888938665390015,0.4988260567188263,0.49880436062812805,0.4934934973716736,0.4944378733634949,0.49528968334198,0.49603864550590515,0.49667447805404663,0.49718692898750305,0.49756571650505066,0.4978005290031433,0.49788105487823486,0.4869517982006073,0.4891039729118347,0.491045206785202,0.4927521049976349,0.4942012131214142,0.4953690767288208,0.4962323009967804,0.49676740169525146,0.4969509541988373],"props":[[0,26.579748153686523,4.767230987548828,0.7743046283721924,true,224],[2,3.260620594024658,10.087486267089844,0.6818166971206665,false,186],[1,28.662282943725586,11.022789001464844,0.74249666929245,true,80],[0,26.725576400756836,18.9808406829834,0.5057967305183411,true,4]]}, + {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3],"cell":[-12,5],"heights":[0.5121973752975464,0.4823082387447357,0.46220675110816956,0.5112564563751221,0.5501552820205688,0.4872822165489197,0.38883817195892334,0.31799912452697754,0.28261008858680725,0.4805338978767395,0.44521087408065796,0.4195011556148529,0.47392895817756653,0.5189605951309204,0.4671037197113037,0.39131978154182434,0.3571542799472809,0.3469882309436798,0.41997605562210083,0.37975943088531494,0.3484508991241455,0.4063468873500824,0.45611312985420227,0.42487290501594543,0.3929973244667053,0.4145159125328064,0.43692919611930847,0.3330213129520416,0.31364208459854126,0.3024783134460449,0.3571169674396515,0.40484189987182617,0.38624680042266846,0.38952183723449707,0.4628981053829193,0.5148381590843201,0.2848259508609772,0.2832028865814209,0.2896556258201599,0.3422389626502991,0.38851577043533325,0.3728458285331726,0.388386994600296,0.4877353012561798,0.5564621090888977,0.2816266715526581,0.2867536246776581,0.2998877167701721,0.3233092427253723,0.34088629484176636,0.35961490869522095,0.4112788140773773,0.5053136944770813,0.5671341419219971,0.2767845094203949,0.28718429803848267,0.3051665127277374,0.303689569234848,0.29709380865097046,0.34592780470848083,0.4310455322265625,0.5240169763565063,0.5815257430076599,0.3178563117980957,0.3185093402862549,0.32627564668655396,0.3392178416252136,0.3477005958557129,0.3815544545650482,0.45490309596061707,0.5379451513290405,0.582377016544342,0.35266175866127014,0.3454577326774597,0.34513136744499207,0.3703245520591736,0.3913551867008209,0.41152533888816833,0.47250428795814514,0.5445654988288879,0.576723039150238],"moisture":[0.8263142704963684,0.825194776058197,0.8219315409660339,0.8166675567626953,0.809545636177063,0.8007087707519531,0.7902998328208923,0.778461754322052,0.7653374671936035,0.8096745014190674,0.8085733652114868,0.805363655090332,0.8001859188079834,0.7931808233261108,0.7844889163970947,0.7742506861686707,0.7626067399978638,0.7496976852416992,0.7918837666511536,0.7908022403717041,0.7876497507095337,0.7825644016265869,0.7756841778755188,0.7671471834182739,0.7570914626121521,0.7456550598144531,0.7329761981964111,0.7731080055236816,0.772047221660614,0.7689551115036011,0.7639671564102173,0.7572187185287476,0.7488452792167664,0.7389822006225586,0.7277648448944092,0.7153288125991821,0.7535130977630615,0.7524739503860474,0.749444842338562,0.744558572769165,0.7379477024078369,0.7297449111938477,0.7200828194618225,0.7090941667556763,0.6969115734100342,0.7332649827003479,0.7322481870651245,0.7292842268943787,0.7245029807090759,0.7180342078208923,0.7100077867507935,0.7005534172058105,0.6898009777069092,0.6778803467750549,0.7125295400619507,0.7115355730056763,0.7086383104324341,0.7039646506309509,0.6976414918899536,0.6897956132888794,0.6805540323257446,0.6700435280799866,0.6583910584449768,0.6914726495742798,0.6905019283294678,0.6876724362373352,0.6831079721450806,0.6769325733184814,0.6692701578140259,0.6602445840835571,0.6499797701835632,0.638599693775177,0.6702602505683899,0.6693129539489746,0.6665516495704651,0.6620972752571106,0.6560707688331604,0.6485930681228638,0.63978511095047,0.6297678351402283,0.6186621189117432],"props":[[0,2.650817632675171,4.8241119384765625,0.6354243159294128,true,110],[2,11.57477855682373,4.872535705566406,0.7331044673919678,false,238],[0,28.03809928894043,4.916660308837891,0.578079342842102,true,63],[2,4.669862270355225,11.890331268310547,0.5852758288383484,false,87],[0,10.483098983764648,11.758493423461914,0.564202606678009,true,52],[0,19.052648544311523,11.650245666503906,0.6284025311470032,true,105],[0,28.663318634033203,11.259580612182617,0.7930710315704346,true,240],[0,5.82761287689209,19.1566104888916,0.5523130893707275,true,42],[0,10.243107795715332,19.25455093383789,0.6117123365402222,true,91],[0,2.6146390438079834,29.77297592163086,0.5455815196037292,true,37],[0,12.799676895141602,28.633228302001953,0.6608912348747253,true,131],[0,19.269079208374023,28.336078643798828,0.5150197744369507,true,12]]}, + {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[999999,-1000000],"heights":[0.5270935297012329,0.5743997693061829,0.5953944325447083,0.5239696502685547,0.4753807783126831,0.5279929041862488,0.5514862537384033,0.5003933310508728,0.4679919481277466,0.5375649333000183,0.572934091091156,0.5820469260215759,0.5309256315231323,0.5026796460151672,0.5419862866401672,0.5614850521087646,0.513027548789978,0.474234402179718,0.5374559164047241,0.5614643096923828,0.5593416094779968,0.5240475535392761,0.5117505788803101,0.5481477379798889,0.5835541486740112,0.5567929744720459,0.5216204524040222,0.5208446979522705,0.5216416120529175,0.49646323919296265,0.46929264068603516,0.4653409719467163,0.5247509479522705,0.6015294790267944,0.6190511584281921,0.6109352111816406,0.5109962224960327,0.49113374948501587,0.44546449184417725,0.42380237579345703,0.42567700147628784,0.49693557620048523,0.5935209393501282,0.6337533593177795,0.6418488621711731,0.4949389100074768,0.4840001165866852,0.45257842540740967,0.4334706664085388,0.4331486225128174,0.4797436594963074,0.5479856133460999,0.6027395725250244,0.6307550072669983,0.4766243100166321,0.47689566016197205,0.4672740697860718,0.46044427156448364,0.46244776248931885,0.48313599824905396,0.5174170732498169,0.5744072794914246,0.6146253943443298,0.4837564527988434,0.4784761071205139,0.4735533893108368,0.498298704624176,0.5223067998886108,0.5017102360725403,0.4870026409626007,0.5422952175140381,0.5905597805976868,0.49135950207710266,0.4768757224082947,0.4670783579349518,0.5093743205070496,0.5473048686981201,0.4947369694709778,0.44537153840065,0.5052690505981445,0.5629271864891052],"moisture":[0.8571391701698303,0.8770757913589478,0.8950584530830383,0.9108702540397644,0.9242939352989197,0.9351125359535217,0.943108856678009,0.9480658769607544,0.9497664570808411,0.8566534519195557,0.8765634298324585,0.8945221900939941,0.9103129506111145,0.9237187504768372,0.9345229268074036,0.9425086379051208,0.9474590420722961,0.9491572976112366,0.8553431630134583,0.8751815557479858,0.893075704574585,0.9088096022605896,0.922167181968689,0.9329325556755066,0.9408894777297974,0.9458220601081848,0.9475142955780029,0.8532635569572449,0.8729882836341858,0.8907799124717712,0.9064236283302307,0.9197046756744385,0.9304082989692688,0.9383196830749512,0.9432240128517151,0.9449065327644348,0.8504698276519775,0.8700418472290039,0.8876957297325134,0.9032183289527893,0.9163965582847595,0.927017331123352,0.9348674416542053,0.9397338032722473,0.9414032697677612,0.847017228603363,0.8664004802703857,0.883884072303772,0.8992570638656616,0.9123081564903259,0.9228265285491943,0.9306009411811829,0.9354203343391418,0.9370737075805664,0.8429608345031738,0.8621223568916321,0.8794059753417969,0.8946030735969543,0.9075048565864563,0.9179028868675232,0.9255883693695068,0.9303526878356934,0.9319871068000793,0.8383559584617615,0.8572657108306885,0.8743222951889038,0.8893197178840637,0.9020520448684692,0.9123134613037109,0.9198979735374451,0.9245997071266174,0.9262126684188843,0.8332576751708984,0.8518888354301453,0.868694007396698,0.8834704160690308,0.8960150480270386,0.9061252474784851,0.9135980010032654,0.918230414390564,0.9198196530342102],"props":[[0,3.1682724952697754,2.740854263305664,0.7206481695175171,true,180],[0,10.771486282348633,2.1860263347625732,0.5887128710746765,true,72],[0,21.956050872802734,3.2204477787017822,0.779129147529602,true,228],[0,13.399469375610352,10.174410820007324,0.5151387453079224,true,12],[0,21.344093322753906,10.719156265258789,0.5965613126754761,true,79],[0,29.304264068603516,11.698976516723633,0.7484042644500732,true,203],[0,2.3951516151428223,26.584388732910156,0.7904362678527832,true,237],[0,18.772125244140625,28.845848083496094,0.5168313980102539,true,13],[0,27.48282241821289,26.896862030029297,0.5896564722061157,true,73]]} + ], + "walk": {"cell":[6,2],"start":[16.0,16.0],"steps":[{"input":[79,-128,1],"x":16.176055908203125,"y":15.717009544372559},{"input":[79,-128,1],"x":16.352205276489258,"y":15.433927536010742},{"input":[79,-128,1],"x":16.528352737426758,"y":15.150845527648926},{"input":[80,-128,1],"x":16.705965042114258,"y":14.868861198425293},{"input":[80,-128,1],"x":16.88357925415039,"y":14.586877822875977},{"input":[80,-128,1],"x":17.06119155883789,"y":14.30489444732666},{"input":[80,-128,1],"x":17.23880386352539,"y":14.022911071777344},{"input":[81,-128,1],"x":17.418066024780273,"y":13.741843223571777},{"input":[81,-128,1],"x":17.597326278686523,"y":13.460775375366211},{"input":[81,-128,1],"x":17.776588439941406,"y":13.179707527160645},{"input":[82,-128,1],"x":17.957313537597656,"y":12.899738311767578},{"input":[82,-128,1],"x":18.138038635253906,"y":12.619768142700195},{"input":[82,-128,1],"x":18.31876564025879,"y":12.339798927307129},{"input":[83,-128,1],"x":18.50113868713379,"y":12.060745239257812},{"input":[83,-128,1],"x":18.68351173400879,"y":11.781691551208496},{"input":[83,-128,1],"x":18.865886688232422,"y":11.50263786315918},{"input":[84,-128,1],"x":19.049724578857422,"y":11.224682807922363},{"input":[84,-128,1],"x":19.233562469482422,"y":10.946727752685547},{"input":[85,-128,1],"x":19.419050216674805,"y":10.66968822479248},{"input":[85,-128,1],"x":19.604536056518555,"y":10.392648696899414},{"input":[86,-128,1],"x":19.791488647460938,"y":10.116706848144531},{"input":[86,-128,1],"x":19.978439331054688,"y":9.840765953063965},{"input":[87,-128,1],"x":20.166854858398438,"y":9.565740585327148},{"input":[87,-128,1],"x":20.35527229309082,"y":9.290715217590332},{"input":[88,-128,1],"x":20.54515266418457,"y":9.016788482666016},{"input":[88,-128,1],"x":20.73503303527832,"y":8.7428617477417},{"input":[89,-128,1],"x":20.926380157470703,"y":8.469850540161133},{"input":[90,-128,1],"x":21.119190216064453,"y":8.197937965393066},{"input":[91,-128,1],"x":21.313283920288086,"y":7.926940441131592},{"input":[91,-128,1],"x":21.507375717163086,"y":7.655943393707275},{"input":[92,-128,1],"x":21.702932357788086,"y":7.386044979095459},{"input":[93,-128,1],"x":21.89995574951172,"y":7.117062091827393},{"input":[94,-128,1],"x":22.09825897216797,"y":6.849177837371826},{"input":[95,-128,1],"x":22.2978458404541,"y":6.58220911026001},{"input":[96,-128,1],"x":22.4988956451416,"y":6.316339015960693},{"input":[98,-128,1],"x":22.7025089263916,"y":6.052482604980469},{"input":[99,-128,1],"x":22.907405853271484,"y":5.789542198181152},{"input":[101,-128,1],"x":23.114864349365234,"y":5.528615951538086},{"input":[102,-128,1],"x":23.323606491088867,"y":5.2687883377075195},{"input":[104,-128,1],"x":23.534727096557617,"y":5.010974884033203},{"input":[106,-128,1],"x":23.748228073120117,"y":4.754992485046387},{"input":[109,-128,1],"x":23.96539306640625,"y":4.50212287902832},{"input":[111,-128,1],"x":24.18475341796875,"y":4.251084327697754},{"input":[115,-128,1],"x":24.408510208129883,"y":4.0040740966796875},{"input":[118,-128,1],"x":24.635377883911133,"y":3.759810447692871},{"input":[122,-128,1],"x":24.745058059692383,"y":3.535871744155884},{"input":[125,-128,1],"x":24.734071731567383,"y":3.2868473529815674},{"input":[126,-128,1],"x":24.778202056884766,"y":2.999919891357422},{"input":[122,-128,1],"x":24.896854400634766,"y":2.6990764141082764},{"input":[111,-128,1],"x":25.090946197509766,"y":2.42514967918396},{"input":[93,-128,1],"x":25.2879695892334,"y":2.1561665534973145},{"input":[71,-128,1],"x":25.4505672454834,"y":1.865211009979248},{"input":[51,-128,1],"x":25.5747127532959,"y":1.5559446811676025},{"input":[36,-128,1],"x":25.6655330657959,"y":1.235325813293457},{"input":[25,-128,1],"x":25.7299861907959,"y":0.908298134803772},{"input":[19,-128,1],"x":25.77924346923828,"y":0.5787070393562317},{"input":[14,-128,1],"x":25.81568145751953,"y":0.2474679797887802},{"input":[11,-128,1],"x":25.84442901611328,"y":-0.08468659967184067},{"input":[9,-128,1],"x":25.86804962158203,"y":-0.41720739006996155},{"input":[8,-128,1],"x":25.88892364501953,"y":-0.7499113082885742},{"input":[-94,84,0],"x":25.7409725189209,"y":-0.617708683013916},{"input":[-94,84,0],"x":25.5930233001709,"y":-0.48550599813461304},{"input":[-94,84,0],"x":25.4450740814209,"y":-0.35330334305763245},{"input":[-94,84,0],"x":25.2971248626709,"y":-0.22110070288181305},{"input":[-94,84,0],"x":25.149173736572266,"y":-0.08889804780483246},{"input":[-94,84,0],"x":25.001224517822266,"y":0.04330460727214813},{"input":[-94,84,0],"x":24.853275299072266,"y":0.17550726234912872},{"input":[-94,84,0],"x":24.705324172973633,"y":0.3077099025249481},{"input":[-94,84,0],"x":24.557374954223633,"y":0.4399125576019287},{"input":[-94,84,0],"x":24.409425735473633,"y":0.5721152424812317},{"input":[-94,84,0],"x":24.261476516723633,"y":0.7043178677558899},{"input":[-94,84,0],"x":24.113525390625,"y":0.8365205526351929},{"input":[-94,84,0],"x":23.965576171875,"y":0.9687231779098511},{"input":[-94,84,0],"x":23.817626953125,"y":1.1009258031845093},{"input":[-94,84,0],"x":23.669675827026367,"y":1.2331284284591675},{"input":[-94,84,0],"x":23.521726608276367,"y":1.3653311729431152},{"input":[-94,84,0],"x":23.373777389526367,"y":1.4975337982177734},{"input":[-94,84,0],"x":23.225826263427734,"y":1.6297364234924316},{"input":[-94,84,0],"x":23.077877044677734,"y":1.7619390487670898},{"input":[-94,84,0],"x":22.929927825927734,"y":1.8941417932510376},{"input":[-94,84,0],"x":22.781978607177734,"y":2.0263442993164062},{"input":[-94,84,0],"x":22.6340274810791,"y":2.1585471630096436},{"input":[-94,84,0],"x":22.4860782623291,"y":2.2907497882843018},{"input":[-94,84,0],"x":22.3381290435791,"y":2.42295241355896},{"input":[-94,84,0],"x":22.19017791748047,"y":2.555155038833618},{"input":[-94,84,0],"x":22.04222869873047,"y":2.6873576641082764},{"input":[-94,84,0],"x":21.89427947998047,"y":2.8195602893829346},{"input":[-94,84,0],"x":21.746328353881836,"y":2.9517629146575928},{"input":[-94,84,0],"x":21.598379135131836,"y":3.083965539932251},{"input":[-94,84,0],"x":21.450429916381836,"y":3.216168165206909},{"input":[-94,84,0],"x":21.302480697631836,"y":3.3483710289001465},{"input":[-94,84,0],"x":21.154529571533203,"y":3.4805736541748047},{"input":[-94,84,0],"x":21.006580352783203,"y":3.612776279449463},{"input":[-94,84,0],"x":20.858631134033203,"y":3.744978904724121},{"input":[-94,84,0],"x":20.71068000793457,"y":3.8771815299987793},{"input":[-94,84,0],"x":20.56273078918457,"y":4.0093841552734375},{"input":[-94,84,0],"x":20.41478157043457,"y":4.141586780548096},{"input":[-94,84,0],"x":20.26683235168457,"y":4.273789405822754},{"input":[-94,84,0],"x":20.118881225585938,"y":4.405992031097412},{"input":[-94,84,0],"x":19.970932006835938,"y":4.53819465637207},{"input":[-94,84,0],"x":19.822982788085938,"y":4.6703972816467285},{"input":[-94,84,0],"x":19.675031661987305,"y":4.802599906921387},{"input":[-94,84,0],"x":19.527082443237305,"y":4.934802532196045},{"input":[-94,84,0],"x":19.379133224487305,"y":5.067005634307861},{"input":[-94,84,0],"x":19.231182098388672,"y":5.1992082595825195},{"input":[-94,84,0],"x":19.083232879638672,"y":5.331410884857178},{"input":[-94,84,0],"x":18.935283660888672,"y":5.463613510131836},{"input":[-94,84,0],"x":18.787334442138672,"y":5.595816135406494},{"input":[-94,84,0],"x":18.63938331604004,"y":5.728018760681152},{"input":[-94,84,0],"x":18.49143409729004,"y":5.8602213859558105},{"input":[-94,84,0],"x":18.34348487854004,"y":5.992424011230469},{"input":[-94,84,0],"x":18.195533752441406,"y":6.124626636505127},{"input":[-94,84,0],"x":18.047584533691406,"y":6.256829261779785},{"input":[-94,84,0],"x":17.899635314941406,"y":6.389031887054443},{"input":[-94,84,0],"x":17.751686096191406,"y":6.521234512329102},{"input":[-94,84,0],"x":17.603734970092773,"y":6.65343713760376},{"input":[-94,84,0],"x":17.455785751342773,"y":6.785639762878418},{"input":[-94,84,0],"x":17.307836532592773,"y":6.917842388153076},{"input":[-94,84,0],"x":17.15988540649414,"y":7.050045013427734},{"input":[-94,84,0],"x":17.01193618774414,"y":7.182247638702393},{"input":[112,59,1],"x":17.305822372436523,"y":7.337155818939209},{"input":[112,59,1],"x":17.599706649780273,"y":7.492063522338867},{"input":[112,59,1],"x":17.893592834472656,"y":7.646971225738525},{"input":[112,59,1],"x":18.187477111816406,"y":7.801878929138184},{"input":[112,59,1],"x":18.48136329650879,"y":7.956787109375},{"input":[112,59,1],"x":18.775249481201172,"y":8.1116943359375},{"input":[112,59,1],"x":19.069133758544922,"y":8.266602516174316},{"input":[112,59,1],"x":19.363019943237305,"y":8.421510696411133},{"input":[112,59,1],"x":19.656904220581055,"y":8.576417922973633},{"input":[112,59,1],"x":19.950790405273438,"y":8.73132610321045},{"input":[112,59,1],"x":20.244674682617188,"y":8.886234283447266},{"input":[112,59,1],"x":20.53856086730957,"y":9.041141510009766},{"input":[112,59,1],"x":20.832447052001953,"y":9.196049690246582},{"input":[112,59,1],"x":21.126331329345703,"y":9.350956916809082},{"input":[112,59,1],"x":21.420217514038086,"y":9.505865097045898},{"input":[112,59,1],"x":21.714101791381836,"y":9.660773277282715},{"input":[112,59,1],"x":22.00798797607422,"y":9.815680503845215},{"input":[112,59,1],"x":22.3018741607666,"y":9.970588684082031},{"input":[112,59,1],"x":22.59575843811035,"y":10.125496864318848},{"input":[112,59,1],"x":22.889644622802734,"y":10.280404090881348},{"input":[112,59,1],"x":23.183528900146484,"y":10.435312271118164},{"input":[112,59,1],"x":23.477415084838867,"y":10.590219497680664},{"input":[112,59,1],"x":23.77130126953125,"y":10.74512767791748},{"input":[112,59,1],"x":24.065185546875,"y":10.900035858154297},{"input":[112,59,1],"x":24.359071731567383,"y":11.054943084716797},{"input":[112,59,1],"x":24.652956008911133,"y":11.209851264953613},{"input":[111,59,1],"x":24.944278717041016,"y":11.364758491516113},{"input":[111,59,1],"x":25.235599517822266,"y":11.51966667175293},{"input":[111,59,1],"x":25.52692222595215,"y":11.674574851989746},{"input":[111,59,1],"x":25.81824493408203,"y":11.829482078552246},{"input":[111,59,1],"x":26.10956573486328,"y":11.984390258789062},{"input":[111,60,1],"x":26.400888442993164,"y":12.141861915588379},{"input":[111,59,1],"x":26.692209243774414,"y":12.296769142150879},{"input":[111,60,1],"x":26.983531951904297,"y":12.454240798950195},{"input":[111,59,1],"x":27.198131561279297,"y":12.567949295043945},{"input":[111,60,1],"x":27.197582244873047,"y":12.569047927856445},{"input":[111,59,1],"x":27.198314666748047,"y":12.567766189575195},{"input":[111,60,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[-121,-128,0],"x":27.060436248779297,"y":12.422746658325195},{"input":[-121,-128,0],"x":26.922557830810547,"y":12.277909278869629},{"input":[-121,-128,0],"x":26.784679412841797,"y":12.133072853088379},{"input":[-121,-128,0],"x":26.646799087524414,"y":11.988235473632812},{"input":[-120,-128,0],"x":26.509469985961914,"y":11.842848777770996},{"input":[-120,-128,0],"x":26.372140884399414,"y":11.697463035583496},{"input":[-120,-128,0],"x":26.23480987548828,"y":11.55207633972168},{"input":[-119,-128,0],"x":26.09803009033203,"y":11.40614128112793},{"input":[-119,-128,0],"x":25.96125030517578,"y":11.260205268859863},{"input":[-119,-128,0],"x":25.82447052001953,"y":11.114269256591797},{"input":[-118,-128,0],"x":25.68842124938965,"y":10.967784881591797},{"input":[-118,-128,0],"x":25.5523738861084,"y":10.82129955291748},{"input":[-118,-128,0],"x":25.41632652282715,"y":10.67481517791748},{"input":[-117,-128,0],"x":25.28082847595215,"y":10.527780532836914},{"input":[-117,-128,0],"x":25.145328521728516,"y":10.380746841430664},{"input":[-116,-128,0],"x":25.010379791259766,"y":10.233162879943848},{"input":[-116,-128,0],"x":24.875431060791016,"y":10.085578918457031},{"input":[-116,-128,0],"x":24.740480422973633,"y":9.937995910644531},{"input":[-115,-128,0],"x":24.606264114379883,"y":9.789679527282715},{"input":[-115,-128,0],"x":24.472047805786133,"y":9.641364097595215},{"input":[-114,-128,0],"x":24.338380813598633,"y":9.492498397827148},{"input":[-114,-128,0],"x":24.2047119140625,"y":9.343632698059082},{"input":[-113,-128,0],"x":24.07177734375,"y":9.194218635559082},{"input":[-113,-128,0],"x":23.9388427734375,"y":9.044803619384766},{"input":[-112,-128,0],"x":23.806640625,"y":8.894840240478516},{"input":[-112,-128,0],"x":23.674436569213867,"y":8.74487590789795},{"input":[-111,-128,0],"x":23.542783737182617,"y":8.594362258911133},{"input":[-111,-128,0],"x":23.411130905151367,"y":8.443849563598633},{"input":[-110,-128,0],"x":23.280210494995117,"y":8.292603492736816},{"input":[-110,-128,0],"x":23.149288177490234,"y":8.141358375549316},{"input":[-109,-128,0],"x":23.019100189208984,"y":7.98956298828125},{"input":[-109,-128,0],"x":22.888912200927734,"y":7.837768077850342},{"input":[-108,-128,0],"x":22.759273529052734,"y":7.685423374176025},{"input":[-107,-128,0],"x":22.6303653717041,"y":7.532529830932617},{"input":[-107,-128,0],"x":22.5014591217041,"y":7.379636287689209},{"input":[-106,-128,0],"x":22.3732852935791,"y":7.226010322570801},{"input":[-106,-128,0],"x":22.24510955810547,"y":7.072384357452393},{"input":[-105,-128,0],"x":22.11766815185547,"y":6.918208599090576},{"input":[-104,-128,0],"x":21.99095916748047,"y":6.763484001159668},{"input":[-104,-128,0],"x":21.86425018310547,"y":6.60875940322876},{"input":[-103,-128,0],"x":21.738271713256836,"y":6.453485488891602},{"input":[-102,-128,0],"x":21.613027572631836,"y":6.297478675842285},{"input":[-102,-128,0],"x":21.487783432006836,"y":6.141472339630127},{"input":[-101,-128,0],"x":21.363271713256836,"y":5.984916687011719},{"input":[-100,-128,0],"x":21.239490509033203,"y":5.8278117179870605},{"input":[-100,-128,0],"x":21.115711212158203,"y":5.670706272125244},{"input":[-99,-128,0],"x":20.992664337158203,"y":5.513051986694336},{"input":[-98,-128,0],"x":20.870532989501953,"y":5.354665279388428},{"input":[-97,-128,0],"x":20.74913215637207,"y":5.1957292556762695},{"input":[-97,-128,0],"x":20.62773323059082,"y":5.036792755126953},{"input":[-96,-128,0],"x":20.50706672668457,"y":4.877307415008545},{"input":[-95,-128,0],"x":20.38731575012207,"y":4.717089653015137},{"input":[-94,-128,0],"x":20.26829719543457,"y":4.55632209777832},{"input":[-94,-128,0],"x":20.149276733398438,"y":4.395555019378662},{"input":[-93,-128,0],"x":20.031173706054688,"y":4.234238624572754},{"input":[-92,-128,0],"x":19.913803100585938,"y":4.072189807891846},{"input":[-91,-128,0],"x":19.797348022460938,"y":3.9095914363861084},{"input":[-91,-128,0],"x":19.680891036987305,"y":3.746993064880371},{"input":[-90,-128,0],"x":19.565168380737305,"y":3.583845376968384},{"input":[-89,-128,0],"x":19.450361251831055,"y":3.4201486110687256},{"input":[35,121,1],"x":19.542280197143555,"y":3.737654685974121},{"input":[35,121,1],"x":19.634199142456055,"y":4.0551605224609375},{"input":[35,121,1],"x":19.726118087768555,"y":4.372666835784912},{"input":[35,121,1],"x":19.818038940429688,"y":4.690173149108887},{"input":[35,121,1],"x":19.909957885742188,"y":5.007678985595703},{"input":[35,121,1],"x":20.001876831054688,"y":5.325185298919678},{"input":[35,121,1],"x":20.093795776367188,"y":5.642691135406494},{"input":[35,121,1],"x":20.185714721679688,"y":5.960197448730469},{"input":[35,121,1],"x":20.27763557434082,"y":6.277703285217285},{"input":[35,121,1],"x":20.36955451965332,"y":6.59520959854126},{"input":[35,121,1],"x":20.46147346496582,"y":6.912715435028076},{"input":[35,121,1],"x":20.55339241027832,"y":7.230221748352051},{"input":[35,121,1],"x":20.64531135559082,"y":7.547727584838867},{"input":[35,121,1],"x":20.73723030090332,"y":7.865233898162842},{"input":[35,121,1],"x":20.829151153564453,"y":8.182740211486816},{"input":[35,121,1],"x":20.921070098876953,"y":8.500246047973633},{"input":[35,121,1],"x":21.012989044189453,"y":8.81775188446045},{"input":[35,121,1],"x":21.104907989501953,"y":9.135258674621582},{"input":[35,121,1],"x":21.196826934814453,"y":9.452764511108398},{"input":[35,121,1],"x":21.288747787475586,"y":9.770270347595215},{"input":[35,121,1],"x":21.380666732788086,"y":10.087776184082031},{"input":[35,121,1],"x":21.472585678100586,"y":10.405282974243164},{"input":[35,121,1],"x":21.564504623413086,"y":10.72278881072998},{"input":[35,121,1],"x":21.656423568725586,"y":11.040294647216797},{"input":[35,121,1],"x":21.748342514038086,"y":11.357800483703613},{"input":[35,121,1],"x":21.84026336669922,"y":11.675307273864746},{"input":[35,121,1],"x":21.93218231201172,"y":11.992813110351562},{"input":[35,121,1],"x":22.02410125732422,"y":12.310318946838379},{"input":[35,121,1],"x":22.11602020263672,"y":12.627825736999512},{"input":[35,121,1],"x":22.20793914794922,"y":12.945331573486328},{"input":[35,121,1],"x":22.29986000061035,"y":13.262837409973145},{"input":[35,121,1],"x":22.39177894592285,"y":13.580343246459961},{"input":[35,121,1],"x":22.48369789123535,"y":13.897850036621094},{"input":[35,121,1],"x":22.57561683654785,"y":14.21535587310791},{"input":[35,121,1],"x":22.66753578186035,"y":14.532861709594727},{"input":[35,121,1],"x":22.759456634521484,"y":14.850367546081543},{"input":[35,121,1],"x":22.851375579833984,"y":15.167874336242676},{"input":[35,121,1],"x":22.943294525146484,"y":15.485380172729492},{"input":[35,121,1],"x":23.035213470458984,"y":15.802886009216309},{"input":[35,121,1],"x":23.127132415771484,"y":16.120391845703125},{"input":[35,121,1],"x":23.219051361083984,"y":16.437898635864258},{"input":[35,121,1],"x":23.310972213745117,"y":16.75540542602539},{"input":[35,121,1],"x":23.402891159057617,"y":17.07291030883789},{"input":[35,121,1],"x":23.494810104370117,"y":17.390417098999023},{"input":[35,121,1],"x":23.586729049682617,"y":17.707921981811523},{"input":[35,121,1],"x":23.678647994995117,"y":18.025428771972656},{"input":[35,121,1],"x":23.77056884765625,"y":18.34293556213379},{"input":[35,121,1],"x":23.86248779296875,"y":18.66044044494629},{"input":[35,121,1],"x":23.95440673828125,"y":18.977947235107422},{"input":[35,121,1],"x":24.04632568359375,"y":19.295454025268555},{"input":[35,121,1],"x":24.13824462890625,"y":19.612958908081055},{"input":[35,121,1],"x":24.23016357421875,"y":19.930465698242188},{"input":[35,121,1],"x":24.322084426879883,"y":20.247970581054688},{"input":[35,121,1],"x":24.414003372192383,"y":20.56547737121582},{"input":[35,121,1],"x":24.505922317504883,"y":20.882984161376953},{"input":[35,121,1],"x":24.597841262817383,"y":21.200489044189453},{"input":[35,121,1],"x":24.689760208129883,"y":21.517995834350586},{"input":[35,121,1],"x":24.781681060791016,"y":21.83550262451172},{"input":[35,121,1],"x":24.873600006103516,"y":22.15300750732422},{"input":[35,121,1],"x":24.965518951416016,"y":22.47051429748535},{"input":[116,-50,0],"x":25.148258209228516,"y":22.39177894592285},{"input":[116,-50,0],"x":25.33099937438965,"y":22.31304359436035},{"input":[116,-50,0],"x":25.51373863220215,"y":22.23430633544922},{"input":[116,-50,0],"x":25.69647789001465,"y":22.15557098388672},{"input":[116,-50,0],"x":25.87921905517578,"y":22.07683563232422},{"input":[116,-50,0],"x":26.06195831298828,"y":21.99810028076172},{"input":[116,-50,0],"x":26.24469757080078,"y":21.91936492919922},{"input":[116,-50,0],"x":26.427438735961914,"y":21.84062957763672},{"input":[116,-50,0],"x":26.610177993774414,"y":21.76189422607422},{"input":[116,-50,0],"x":26.792919158935547,"y":21.683156967163086},{"input":[116,-50,0],"x":26.975658416748047,"y":21.604421615600586},{"input":[116,-50,0],"x":27.158397674560547,"y":21.525686264038086},{"input":[116,-50,0],"x":27.34113883972168,"y":21.446950912475586},{"input":[116,-50,0],"x":27.52387809753418,"y":21.368215560913086},{"input":[116,-50,0],"x":27.70661735534668,"y":21.289480209350586},{"input":[116,-50,0],"x":27.889358520507812,"y":21.210742950439453},{"input":[116,-50,0],"x":28.072097778320312,"y":21.132007598876953},{"input":[116,-50,0],"x":28.254838943481445,"y":21.053272247314453},{"input":[116,-50,0],"x":28.437578201293945,"y":20.974536895751953},{"input":[116,-50,0],"x":28.620317459106445,"y":20.895801544189453},{"input":[116,-50,0],"x":28.803058624267578,"y":20.817066192626953},{"input":[116,-50,0],"x":28.985797882080078,"y":20.73832893371582},{"input":[116,-50,0],"x":29.168537139892578,"y":20.65959358215332},{"input":[116,-50,0],"x":29.35127830505371,"y":20.58085823059082},{"input":[116,-50,0],"x":29.53401756286621,"y":20.50212287902832},{"input":[116,-50,0],"x":29.71675682067871,"y":20.42338752746582},{"input":[116,-50,0],"x":29.899497985839844,"y":20.34465217590332},{"input":[116,-50,0],"x":30.082237243652344,"y":20.26591682434082},{"input":[116,-50,0],"x":30.264978408813477,"y":20.187179565429688},{"input":[116,-50,0],"x":30.447717666625977,"y":20.108444213867188},{"input":[116,-50,0],"x":30.630456924438477,"y":20.029708862304688},{"input":[116,-50,0],"x":30.81319808959961,"y":19.950973510742188},{"input":[116,-50,0],"x":30.99593734741211,"y":19.872238159179688},{"input":[116,-50,0],"x":31.17867660522461,"y":19.793502807617188},{"input":[116,-50,0],"x":31.361417770385742,"y":19.714765548706055},{"input":[116,-50,0],"x":31.544157028198242,"y":19.636030197143555},{"input":[116,-50,0],"x":31.726896286010742,"y":19.557294845581055},{"input":[116,-50,0],"x":31.909637451171875,"y":19.478559494018555},{"input":[116,-50,0],"x":32.092376708984375,"y":19.399824142456055},{"input":[116,-50,0],"x":32.275115966796875,"y":19.321088790893555},{"input":[116,-50,0],"x":32.457855224609375,"y":19.242351531982422},{"input":[116,-50,0],"x":32.64059829711914,"y":19.163616180419922},{"input":[116,-50,0],"x":32.82333755493164,"y":19.084880828857422},{"input":[116,-50,0],"x":33.00607681274414,"y":19.006145477294922},{"input":[116,-50,0],"x":33.18881607055664,"y":18.927410125732422},{"input":[116,-50,0],"x":33.37155532836914,"y":18.848674774169922},{"input":[116,-50,0],"x":33.554298400878906,"y":18.769939422607422},{"input":[116,-50,0],"x":33.737037658691406,"y":18.69120216369629},{"input":[116,-50,0],"x":33.919776916503906,"y":18.61246681213379},{"input":[116,-50,0],"x":33.999977111816406,"y":18.53373146057129},{"input":[116,-49,0],"x":33.999977111816406,"y":18.45664405822754},{"input":[117,-48,0],"x":33.999977111816406,"y":18.38102149963379},{"input":[118,-46,0],"x":33.999977111816406,"y":18.30851173400879},{"input":[118,-45,0],"x":33.999977111816406,"y":18.237648010253906},{"input":[118,-44,0],"x":33.999977111816406,"y":18.168434143066406},{"input":[119,-43,0],"x":33.999977111816406,"y":18.100685119628906},{"input":[119,-41,0],"x":33.999977111816406,"y":18.036048889160156},{"input":[120,-40,0],"x":33.999977111816406,"y":17.973060607910156},{"input":[120,-39,0],"x":33.999977111816406,"y":17.911720275878906},{"input":[121,-38,0],"x":33.999977111816406,"y":17.851844787597656},{"input":[-78,-128,1],"x":33.825477600097656,"y":17.567846298217773},{"input":[-78,-128,1],"x":33.650978088378906,"y":17.283849716186523},{"input":[-78,-128,1],"x":33.47647476196289,"y":16.99985122680664},{"input":[-78,-128,1],"x":33.30197525024414,"y":16.715852737426758},{"input":[-79,-128,1],"x":33.12582778930664,"y":16.432771682739258},{"input":[-79,-128,1],"x":32.94968032836914,"y":16.149688720703125},{"input":[-79,-128,1],"x":32.77353286743164,"y":15.866606712341309},{"input":[-79,-128,1],"x":32.59738540649414,"y":15.583524703979492},{"input":[-79,-128,1],"x":32.421234130859375,"y":15.300442695617676},{"input":[-79,-128,1],"x":32.245086669921875,"y":15.01736068725586},{"input":[-80,-128,1],"x":32.067474365234375,"y":14.735377311706543},{"input":[-80,-128,1],"x":31.889862060546875,"y":14.453393936157227},{"input":[-80,-128,1],"x":31.712247848510742,"y":14.17141056060791},{"input":[-80,-128,1],"x":31.534635543823242,"y":13.889427185058594},{"input":[-80,-128,1],"x":31.357023239135742,"y":13.607442855834961},{"input":[-80,-128,1],"x":31.17940902709961,"y":13.325459480285645},{"input":[-81,-128,1],"x":31.00014877319336,"y":13.044391632080078},{"input":[-81,-128,1],"x":30.82088851928711,"y":12.763323783874512},{"input":[-81,-128,1],"x":30.641626358032227,"y":12.482255935668945},{"input":[-81,-128,1],"x":30.462366104125977,"y":12.201188087463379},{"input":[-81,-128,1],"x":30.283105850219727,"y":11.920120239257812},{"input":[-81,-128,1],"x":30.103843688964844,"y":11.639052391052246},{"input":[-82,-128,1],"x":29.923118591308594,"y":11.359082221984863},{"input":[-82,-128,1],"x":29.74239158630371,"y":11.079113006591797},{"input":[-82,-128,1],"x":29.56166648864746,"y":10.79914379119873},{"input":[-82,-128,1],"x":29.38094139099121,"y":10.519174575805664},{"input":[-82,-128,1],"x":29.200214385986328,"y":10.239205360412598},{"input":[-83,-128,1],"x":29.017841339111328,"y":9.960151672363281},{"input":[-83,-128,1],"x":28.835468292236328,"y":9.681097984313965},{"input":[-83,-128,1],"x":28.653093338012695,"y":9.402044296264648},{"input":[-83,-128,1],"x":28.470720291137695,"y":9.122989654541016},{"input":[-84,-128,1],"x":28.286882400512695,"y":8.8450345993042},{"input":[-84,-128,1],"x":28.103042602539062,"y":8.567079544067383},{"input":[-84,-128,1],"x":27.919204711914062,"y":8.289124488830566},{"input":[-84,-128,1],"x":27.73536491394043,"y":8.01116943359375},{"input":[-85,-128,1],"x":27.54987907409668,"y":7.734129905700684},{"input":[-85,-128,1],"x":27.36439323425293,"y":7.457090377807617},{"input":[-85,-128,1],"x":27.178905487060547,"y":7.180050373077393},{"input":[-85,-128,1],"x":26.993419647216797,"y":6.903010845184326},{"input":[-86,-128,1],"x":26.806468963623047,"y":6.62706995010376},{"input":[-86,-128,1],"x":26.619516372680664,"y":6.351129055023193},{"input":[-86,-128,1],"x":26.432565689086914,"y":6.075188159942627},{"input":[-87,-128,1],"x":26.24414825439453,"y":5.800162315368652},{"input":[-87,-128,1],"x":26.05573272705078,"y":5.525136947631836},{"input":[-87,-128,1],"x":25.86731719970703,"y":5.2501115798950195},{"input":[-88,-128,1],"x":25.67743492126465,"y":4.976184844970703},{"input":[-88,-128,1],"x":25.4875545501709,"y":4.702258110046387},{"input":[-88,-128,1],"x":25.2813777923584,"y":4.44993782043457},{"input":[-88,-128,1],"x":25.040225982666016,"y":4.217576026916504},{"input":[-88,-128,1],"x":24.850345611572266,"y":3.9436490535736084},{"input":[-89,-128,1],"x":24.658998489379883,"y":3.670637845993042},{"input":[-89,-128,1],"x":24.467653274536133,"y":3.3976263999938965},{"input":[-90,-128,1],"x":24.274843215942383,"y":3.12571382522583},{"input":[-90,-128,1],"x":24.08203125,"y":2.8538012504577637},{"input":[-91,-128,1],"x":23.887939453125,"y":2.582803964614868},{"input":[-91,-128,1],"x":23.693845748901367,"y":2.3118069171905518},{"input":[-92,-128,1],"x":23.498289108276367,"y":2.0419085025787354},{"input":[-92,-128,1],"x":23.302732467651367,"y":1.7720099687576294},{"input":[-93,-128,1],"x":23.105709075927734,"y":1.5030269622802734},{"input":[-93,-128,1],"x":22.908687591552734,"y":1.2340439558029175}]} +} diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index 22830fbd1..23b81876c 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -121,6 +121,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.10.4" @@ -139,12 +145,28 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -287,6 +309,7 @@ dependencies = [ "base64 0.23.1", "futures-util", "hmac", + "rusqlite", "serde_json", "sha2", "tokio", @@ -303,6 +326,30 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "futures-core" version = "0.3.34" @@ -341,10 +388,12 @@ dependencies = [ "axum", "clap", "distributed_game", + "futures-util", "http-body-util", "serde", "serde_json", "tokio", + "tokio-tungstenite 0.30.0", "tower", ] @@ -382,6 +431,24 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown", +] + [[package]] name = "heck" version = "0.5.0" @@ -497,12 +564,33 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libsqlite3-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "log" version = "0.4.34" @@ -538,6 +626,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -556,6 +650,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -641,6 +741,37 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "serde" version = "1.0.229" @@ -728,6 +859,12 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -760,6 +897,18 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + [[package]] name = "strsim" version = "0.11.1" @@ -948,6 +1097,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -969,6 +1124,51 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index 9d745c0d9..2d60136ce 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -20,7 +20,7 @@ name = "game-demos" path = "src/main.rs" [dependencies] -distributed_game = { path = "../../../distributed_game", features = ["net"] } +distributed_game = { path = "../../../distributed_game", features = ["net", "sqlite"] } axum = { version = "0.8", default-features = false, features = ["json", "tokio", "http1"] } clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } @@ -31,3 +31,5 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal distributed_game = { path = "../../../distributed_game", features = ["net", "bots"] } tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" +tokio-tungstenite = "0.30" +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } diff --git a/examples/game/server/src/cluster.rs b/examples/game/server/src/cluster.rs new file mode 100644 index 000000000..b39c25af6 --- /dev/null +++ b/examples/game/server/src/cluster.rs @@ -0,0 +1,521 @@ +//! Multi-host plumbing for the world demos ([`crate::grid`], +//! [`crate::ripple`]): each host is its own `game-demos ` process with +//! `--host-id` and one `--peer ID=HOST:PORT` per other host. +//! +//! What a host gets on top of [`crate::common`]: +//! +//! - a [`ZoneDirectory`] over every host (the demo chooses: consistent hash, +//! placement by tier …): a Hello for a zone owned elsewhere gets +//! `Redirect`, handoffs and tier-up events cross hosts over the admin +//! routes (`/admin/transfer`, `/admin/child-event`); +//! - the admin secret, derived from the shared ticket secret (all hosts of +//! a world must be started with the same `--secret`); +//! - fenced zone claims ([`EpochOwnership`]) and SQLite hibernation +//! snapshots ([`SqliteZoneStateStore`], one file per host under +//! `--state-dir`, in-memory without it); +//! - guest display names shared with every peer: `/dev/ticket` on any host +//! forwards the new `principal → name` to the others before it answers, +//! so a zone on another host greets the player by name. +//! +//! **Dev only**, like everything under `/dev`. + +use std::future::Future; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use axum::routing::post; +use axum::{Json, Router}; +use distributed_game::facts::BoxFuture; +use distributed_game::net::peer::{post_json, ADMIN_SECRET_HEADER}; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; +use distributed_game::world::{ + HostAddr, LocalOwnership, OwnershipError, SqliteZoneStateStore, ZoneClaim, ZoneDirectory, + ZoneOwnership, ZoneStateStore, +}; +use serde_json::{json, Value}; + +use crate::common::{dev, server_config, Demo, DemoArgs, DemoOptions, Guests, RunningDemo}; + +/// CLI options of a multi-host demo. +#[derive(Debug, Clone, clap::Args)] +pub struct ClusterArgs { + #[command(flatten)] + #[allow(missing_docs)] + pub demo: DemoArgs, + /// This host's id (directory entry, ownership holder prefix). + #[arg(long, default_value = "A")] + pub host_id: String, + /// Another host of the same world, `ID=HOST:PORT` (repeatable). Every + /// host must list every other host. + #[arg(long = "peer", value_name = "ID=HOST:PORT")] + pub peers: Vec, + /// Directory for SQLite hibernation snapshots (`-.sqlite3`). + /// Default: in-memory (lost when the process exits). + #[arg(long)] + pub state_dir: Option, + /// Hibernate a zone after it has been Dormant this long (ms); it turns + /// Dormant after half of this without clients. + #[arg(long, default_value_t = 4000)] + pub hibernate_after_ms: u64, +} + +/// In-process cluster options (tests and [`run_cluster`]). +#[derive(Debug, Clone)] +pub struct ClusterOptions { + /// This host's id. + pub host_id: String, + /// Every other host. + pub peers: Vec, + /// Snapshot directory (None = in-memory SQLite). + pub state_dir: Option, + /// Dormant time before hibernation. + pub hibernate_after: Duration, +} + +impl ClusterOptions { + /// A lone host `id` (no peers, in-memory snapshots). + pub fn single(id: &str, hibernate_after: Duration) -> Self { + Self { + host_id: id.into(), + peers: Vec::new(), + state_dir: None, + hibernate_after, + } + } +} + +/// Parse `ID=HOST:PORT`. +pub fn parse_peer(spec: &str) -> Result { + let (id, addr) = spec + .split_once('=') + .ok_or_else(|| format!("peer {spec:?}: expected ID=HOST:PORT"))?; + if id.is_empty() || addr.is_empty() { + return Err(format!("peer {spec:?}: expected ID=HOST:PORT")); + } + Ok(HostAddr::new(id, addr)) +} + +/// What a running host knows about its world. +pub struct World { + /// This host. + pub host: HostAddr, + /// Every host, sorted by id (this one included). + pub hosts: Vec, + /// Zone placement. + pub directory: Arc, + /// Hibernation snapshots of the zones this host ran. + pub state: Arc, + /// Shared admin secret (peer calls). + pub admin_secret: String, + /// Display names (shared with peers by `/dev/ticket`). + pub guests: Guests, + /// Dormant time before hibernation. + pub hibernate_after: Duration, +} + +impl World { + /// A world of one host that is not serving (`Demo::server`). + pub fn standalone(options: &ClusterOptions, guests: Guests) -> Self { + let host = HostAddr::new(options.host_id.clone(), "127.0.0.1:0"); + let hosts = vec![host.clone()]; + Self { + directory: D::directory(&hosts), + host, + hosts, + state: Arc::new(SqliteZoneStateStore::open_in_memory().expect("in-memory SQLite")), + admin_secret: String::new(), + guests, + hibernate_after: options.hibernate_after, + } + } + + /// Hosts other than this one. + pub fn peers(&self) -> impl Iterator + '_ { + self.hosts.iter().filter(|h| h.id != self.host.id) + } + + /// Owner host id of `zone_id` (this host when the directory is silent). + pub fn owner(&self, zone_id: &str) -> String { + self.directory + .locate(zone_id) + .map_or_else(|| self.host.id.clone(), |h| h.id) + } + + /// True when the request carries the admin secret. + pub fn authorized(&self, headers: &HeaderMap) -> bool { + headers + .get(ADMIN_SECRET_HEADER) + .is_some_and(|v| v.as_bytes() == self.admin_secret.as_bytes()) + } + + /// POST `body` to `path` on every peer; `(host id, reply)` per answer. + pub async fn ask_peers(&self, path: &str, body: &Value) -> Vec<(String, Value)> { + let mut out = Vec::new(); + for peer in self.peers() { + let reply = post_json( + &peer.admin_url, + path, + &self.admin_secret, + body, + Duration::from_millis(800), + ) + .await; + if let Ok((200, value)) = reply { + out.push((peer.id.clone(), value)); + } + } + out + } +} + +/// A demo that runs as one host of a multi-host world. +pub trait ClusterDemo: Demo { + /// Zone placement over `hosts` (sorted by id). Must give the same answer + /// on every host. + fn directory(hosts: &[HostAddr]) -> Arc; + + /// Build this host's server (`config` already has the admin secret and + /// `hibernate_after`). Host id, directory, ownership and the state store + /// are attached afterwards; do not clone the server here. + fn cluster_server(config: ServerConfig, world: &World) -> GameServer; + + /// Extra dev routes (mounted with `--dev` only). + fn cluster_routes(_server: GameServer, _world: Arc) -> Router { + Router::new() + } +} + +/// A started host. +pub struct RunningHost { + /// The server, its address and guests. + pub demo: RunningDemo, + /// What the host knows about its world. + pub world: Arc, +} + +/// Admin secret every host of a world derives from the shared ticket key. +pub fn admin_secret(key: &TicketKey) -> String { + key.hmac(b"game-demos|admin")[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Start host `cluster.host_id` of demo `D` on `listener`. +pub fn spawn_cluster( + listener: tokio::net::TcpListener, + options: DemoOptions, + cluster: ClusterOptions, + signal: impl Future + Send + 'static, +) -> std::io::Result> { + let addr: SocketAddr = listener.local_addr()?; + let host = HostAddr::new(cluster.host_id.clone(), addr.to_string()); + let mut hosts: Vec = cluster + .peers + .iter() + .filter(|p| p.id != host.id) + .cloned() + .collect(); + hosts.push(host.clone()); + hosts.sort(); + let directory = D::directory(&hosts); + let state = match &cluster.state_dir { + Some(dir) => { + std::fs::create_dir_all(dir)?; + SqliteZoneStateStore::open(dir.join(format!("{}-{}.sqlite3", D::NAME, host.id))) + } + None => SqliteZoneStateStore::open_in_memory(), + } + .map_err(std::io::Error::other)?; + let guests = Guests::default(); + let world = Arc::new(World { + host, + hosts, + directory: directory.clone(), + state: Arc::new(state), + admin_secret: admin_secret(&options.key), + guests: guests.clone(), + hibernate_after: cluster.hibernate_after, + }); + + let mut config = server_config(options.key.clone(), options.net_sim); + config.admin_secret = Some(world.admin_secret.clone()); + config.hibernate_after = Some(cluster.hibernate_after); + config.host.dormant_after = cluster.hibernate_after / 2; + let server = D::cluster_server(config, &world) + .with_host_id(world.host.id.clone()) + .with_directory(directory) + .with_ownership(Arc::new(EpochOwnership::new())) + .with_state_store(world.state.clone() as Arc); + + let extra = if options.dev { + let tickets = dev::routes::(server.clone(), options.key, guests.clone()).layer( + middleware::from_fn_with_state(world.clone(), share_guest_names), + ); + tickets + .merge( + Router::new() + .route("/dev/cluster/guest", post(receive_guest)) + .with_state(world.clone()), + ) + .merge(D::cluster_routes(server.clone(), world.clone())) + } else { + Router::new() + }; + let task = tokio::spawn(server.clone().serve_with(listener, extra, signal)); + Ok(RunningHost { + demo: RunningDemo { + addr, + server, + guests, + task, + }, + world, + }) +} + +/// CLI entry: bind, print the address, serve until Ctrl-C / SIGTERM. +pub async fn run_cluster(args: ClusterArgs) -> std::io::Result<()> { + let demo = args.demo; + let listener = tokio::net::TcpListener::bind((demo.host.as_str(), demo.port)).await?; + let secret = demo.secret.unwrap_or_else(random_secret); + let peers = args + .peers + .iter() + .map(|p| parse_peer(p)) + .collect::, _>>() + .map_err(std::io::Error::other)?; + let options = DemoOptions { + key: TicketKey::new(secret), + dev: demo.dev, + net_sim: NetSim::from_env(), + }; + let cluster = ClusterOptions { + host_id: args.host_id, + peers, + state_dir: args.state_dir, + hibernate_after: Duration::from_millis(args.hibernate_after_ms.max(100)), + }; + let running = spawn_cluster::(listener, options, cluster, shutdown_signal())?; + // Parsed by run.sh and the client tests: keep the format. + println!("LISTENING http://{}", running.demo.addr); + let hosts: Vec = running + .world + .hosts + .iter() + .map(|h| format!("{}={}", h.id, h.ws_url)) + .collect(); + println!( + "demo {} · host {} of [{}] · zone {} · dev routes {}", + D::NAME, + running.world.host.id, + hosts.join(", "), + D::DEFAULT_ZONE, + if demo.dev { "ON" } else { "off" } + ); + running.demo.task.await.map_err(std::io::Error::other)? +} + +/// After a successful `/dev/ticket`, tell every peer the guest's display +/// name (awaited, so a redirected Hello finds it on the owning host). +async fn share_guest_names( + State(world): State>, + request: Request, + next: Next, +) -> Response { + let is_ticket = request.uri().path() == "/dev/ticket"; + let response = next.run(request).await; + if !is_ticket || !response.status().is_success() || world.peers().next().is_none() { + return response; + } + let (parts, body) = response.into_parts(); + let bytes = axum::body::to_bytes(body, 64 * 1024) + .await + .unwrap_or_default(); + if let Ok(ticket) = serde_json::from_slice::(&bytes) { + let body = json!({ "principal": ticket["principal"], "name": ticket["name"] }); + world.ask_peers("/dev/cluster/guest", &body).await; + } + Response::from_parts(parts, Body::from(bytes)) +} + +/// `POST /dev/cluster/guest {principal, name}` (admin secret): a peer +/// registered a guest. +async fn receive_guest( + State(world): State>, + headers: HeaderMap, + Json(body): Json, +) -> StatusCode { + if !world.authorized(&headers) { + return StatusCode::UNAUTHORIZED; + } + let (Some(principal), Some(name)) = (body["principal"].as_str(), body["name"].as_str()) else { + return StatusCode::BAD_REQUEST; + }; + if !principal.starts_with("guest-") { + return StatusCode::BAD_REQUEST; + } + world.guests.set_name(principal, sanitize_name(name)); + StatusCode::OK +} + +/// Same rules as the dev ticket endpoint (letters, digits, ` -_`, ≤ 16). +fn sanitize_name(raw: &str) -> String { + raw.chars() + .filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')) + .take(16) + .collect::() + .trim() + .to_string() +} + +/// 64 random hex characters (OS-seeded SipHash keys; dev quality). +fn random_secret() -> String { + use std::hash::{BuildHasher, Hasher}; + (0..4u64) + .map(|i| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(i); + format!("{:016x}", h.finish()) + }) + .collect() +} + +async fn shutdown_signal() { + let ctrl_c = async { + let _ = tokio::signal::ctrl_c().await; + }; + #[cfg(unix)] + let term = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut s) => { + s.recv().await; + } + Err(_) => std::future::pending().await, + } + }; + #[cfg(not(unix))] + let term = std::future::pending::<()>(); + tokio::select! { + _ = ctrl_c => {} + _ = term => {} + } +} + +/// Process-local fenced claims whose tokens start at the process start time +/// (ms) so they stay monotonic across restarts of a host against the same +/// snapshot file (plain [`LocalOwnership`] restarts at 1 and every later +/// save would be fenced off as stale). +/// +/// Exclusivity across hosts comes from the directory: every host computes +/// the same owner, and a Hello or tier-up event for a foreign zone is +/// forwarded instead of activated. A production world uses +/// `FencedLeaseOwnership` over a shared lease store instead. +pub struct EpochOwnership { + local: LocalOwnership, + base: u64, +} + +impl EpochOwnership { + /// Tokens based on the current time. + pub fn new() -> Self { + let ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + Self { + local: LocalOwnership::new(), + base: ms << 20, + } + } + + fn outer(&self, mut claim: ZoneClaim) -> ZoneClaim { + claim.token += self.base; + claim + } + + fn inner(&self, claim: &ZoneClaim) -> ZoneClaim { + let mut claim = claim.clone(); + claim.token -= self.base; + claim + } +} + +impl Default for EpochOwnership { + fn default() -> Self { + Self::new() + } +} + +impl ZoneOwnership for EpochOwnership { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.local + .acquire(zone_id, holder, ttl) + .await + .map(|c| self.outer(c)) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let inner = self.inner(claim); + self.local.renew(&inner, ttl).await.map(|c| self.outer(c)) + }) + } + + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let inner = self.inner(claim); + self.local.release(&inner).await; + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn epoch_tokens_grow_across_instances() { + let first = EpochOwnership::new(); + let a = first + .acquire("z", "h#1", Duration::from_secs(1)) + .await + .unwrap(); + assert!(first.renew(&a, Duration::from_secs(1)).await.is_ok()); + first.release(&a).await; + tokio::time::sleep(Duration::from_millis(2)).await; + let restarted = EpochOwnership::new(); + let b = restarted + .acquire("z", "h#1", Duration::from_secs(1)) + .await + .unwrap(); + assert!(b.token > a.token, "a restarted host can still save"); + assert!(i64::try_from(b.token).is_ok(), "fits the SQLite column"); + } + + #[test] + fn peers_parse() { + let peer = parse_peer("B=127.0.0.1:2702").unwrap(); + assert_eq!(peer.id, "B"); + assert_eq!(peer.ws_url, "ws://127.0.0.1:2702"); + assert!(parse_peer("127.0.0.1:2702").is_err()); + assert!(parse_peer("=x").is_err()); + } +} diff --git a/examples/game/server/src/grid/dev.rs b/examples/game/server/src/grid/dev.rs new file mode 100644 index 000000000..a02c9d450 --- /dev/null +++ b/examples/game/server/src/grid/dev.rs @@ -0,0 +1,186 @@ +//! **Dev-only** world map routes of the grid (mounted with `--dev`). +//! +//! - `GET /dev/grid/map?x=0&y=0&r=4` (any host): every cell within `r` +//! (≤ 8) of `(x, y)` with its owning host and state — `active` (with +//! tier, players, observers), `hibernated` (a snapshot is stored) or +//! `cold` (never ran, or ran without being hibernated). Cells owned by +//! a peer are answered by that peer (`/dev/grid/local`). +//! - `POST /dev/grid/local {zones: [...]}` (admin secret, host to host): +//! the same facts for this host's cells. + +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode, Uri}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use distributed_game::net::GameServer; +use distributed_game::world::ZoneStateStore; +use distributed_game::Tier; +use serde_json::{json, Value}; + +use super::{world, GridZone}; +use crate::cluster::World; + +/// Largest map radius (cells). +pub const MAX_RADIUS: i32 = 8; + +#[derive(Clone)] +struct MapState { + server: GameServer, + world: Arc, +} + +/// The router. +pub fn routes(server: GameServer, world: Arc) -> Router { + Router::new() + .route("/dev/grid/map", get(map)) + .route("/dev/grid/local", post(local)) + .with_state(MapState { server, world }) +} + +fn query_i32(uri: &Uri, key: &str, default: i32) -> i32 { + uri.query() + .unwrap_or_default() + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(k, _)| *k == key) + .and_then(|(_, v)| v.parse().ok()) + .unwrap_or(default) +} + +fn tier_name(tier: Tier) -> &'static str { + match tier { + Tier::Hot => "hot", + Tier::Idle => "idle", + Tier::Dormant => "dormant", + } +} + +/// Facts about this host's cells among `zones`, keyed by zone id. +async fn local_cells(state: &MapState, zones: &[String]) -> serde_json::Map { + let mut out = serde_json::Map::new(); + for zone in zones { + if state.world.owner(zone) != state.world.host.id || world::parse_zone(zone).is_none() { + continue; + } + let live = if state.server.is_active(zone) { + let inspect = state.server.inspect(zone, |h| { + (tier_name(h.tier()), h.player_count(), h.observer_count()) + }); + tokio::time::timeout(Duration::from_millis(300), inspect) + .await + .ok() + .flatten() + } else { + None + }; + let value = match live { + Some((tier, players, observers)) => json!({ + "state": "active", "tier": tier, "players": players, "observers": observers + }), + None => { + let stored = state.world.state.load(zone).ok().flatten(); + json!({ "state": if stored.is_some() { "hibernated" } else { "cold" } }) + } + }; + out.insert(zone.clone(), value); + } + out +} + +async fn map(State(state): State, uri: Uri) -> Json { + let x = query_i32(&uri, "x", 0).clamp(-world::MAX_CELL, world::MAX_CELL); + let y = query_i32(&uri, "y", 0).clamp(-world::MAX_CELL, world::MAX_CELL); + let r = query_i32(&uri, "r", 4).clamp(0, MAX_RADIUS); + let mut cells = Vec::new(); + for cy in (y - r)..=(y + r) { + for cx in (x - r)..=(x + r) { + if cx.abs() <= world::MAX_CELL && cy.abs() <= world::MAX_CELL { + cells.push((cx, cy, world::zone_id((cx, cy)))); + } + } + } + let zones: Vec = cells.iter().map(|(_, _, z)| z.clone()).collect(); + let mut facts = local_cells(&state, &zones).await; + let mut totals = serde_json::Map::new(); + totals.insert( + state.world.host.id.clone(), + json!(state.server.zone_ids().len()), + ); + for (peer, reply) in state + .world + .ask_peers("/dev/grid/local", &json!({ "zones": zones })) + .await + { + if let Some(cells) = reply["cells"].as_object() { + facts.extend(cells.clone()); + } + totals.insert(peer, reply["activeTotal"].clone()); + } + let count = |host: &str, wanted: &str| { + zones + .iter() + .filter(|z| { + state.world.owner(z) == host + && facts.get(*z).and_then(|f| f["state"].as_str()) == Some(wanted) + }) + .count() + }; + let hosts: Vec = state + .world + .hosts + .iter() + .map(|host| { + json!({ + "id": host.id, + "wsUrl": host.ws_url, + "reachable": totals.contains_key(&host.id), + "activeTotal": totals.get(&host.id).cloned().unwrap_or(Value::Null), + "active": count(&host.id, "active"), + "hibernated": count(&host.id, "hibernated"), + }) + }) + .collect(); + let cells: Vec = cells + .iter() + .map(|(cx, cy, zone)| { + let mut cell = facts + .get(zone) + .cloned() + .unwrap_or_else(|| json!({ "state": "unknown" })); + cell["x"] = json!(cx); + cell["y"] = json!(cy); + cell["zone"] = json!(zone); + cell["owner"] = json!(state.world.owner(zone)); + cell + }) + .collect(); + Json(json!({ "host": state.world.host.id, "hosts": hosts, "cells": cells })) +} + +async fn local( + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Result, StatusCode> { + if !state.world.authorized(&headers) { + return Err(StatusCode::UNAUTHORIZED); + } + let zones: Vec = body["zones"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|z| z.as_str().map(str::to_string)) + .take(((2 * MAX_RADIUS + 1) * (2 * MAX_RADIUS + 1)) as usize) + .collect() + }) + .unwrap_or_default(); + let cells = local_cells(&state, &zones).await; + Ok(Json(json!({ + "host": state.world.host.id, + "activeTotal": state.server.zone_ids().len(), + "cells": cells, + }))) +} diff --git a/examples/game/server/src/grid/mod.rs b/examples/game/server/src/grid/mod.rs new file mode 100644 index 000000000..6000005f9 --- /dev/null +++ b/examples/game/server/src/grid/mod.rs @@ -0,0 +1,657 @@ +//! **Endless Grid** — an unbounded world of square cells, one zone per cell. +//! +//! Mechanics on display: +//! +//! - **Seeded procedural content** ([`world`]): terrain, biomes and props of +//! a cell are a pure function of `(seed, cell, CONTENT_VERSION)`, +//! generated identically by the server (collision) and the client +//! (rendering); nothing static is replicated. +//! - **Spatial cells as zones**: zone `grid..` simulates the walkers +//! in its 32 m square plus a few wandering critters. Walking past a +//! border (with [`world::HYSTERESIS`]) hands the walker off to the +//! neighbour (`ctx.handoff`, carrying its position in the target's +//! frame and its name); the client follows the Handoff. +//! - **Interest across borders**: clients observe the 8 neighbouring zones +//! (observer connections), so critters and walkers across a border are +//! visible before you cross. +//! - **Cross-host handoff**: zones are placed on hosts by a consistent-hash +//! ring ([`HashRing`]); a Hello for a foreign zone gets `Redirect`, a +//! handoff into it reserves the transfer ticket with the issuing host. +//! - **Hibernation**: a zone nobody is in or observing turns Dormant, then +//! hibernates into SQLite (critter positions and dropped markers) and +//! restores on the next activation; its hello says `restored`. +//! +//! Zone ids: `grid..` with canonical integers, |x|, |y| ≤ 1 000 000. +//! The dots are not a hierarchy: the server uses `FlatTopology` (the +//! default `DottedTopology` would make `grid.3` the parent of `grid.3.5`). +//! The ring hashes the full id, so neighbouring cells land on either host. +//! +//! | kind | ids | fields | notes | +//! |---|---|---|---| +//! | 1 `walker` | 1000 + player | x y name hue | local coordinates | +//! | 2 `critter` | 1.. | x y yaw hue | wander, persisted on hibernation | +//! | 3 `marker` | 500.. | x y label hue | dropped with E, persisted | +//! +//! Every entity is global within its zone (a cell is small); interest +//! between zones is the client's choice of observed neighbours. + +pub mod dev; +pub mod world; + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::world::{FlatTopology, HashRing, HostAddr, ZoneDirectory}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + ObserverId, PlayerId, WorldView, Zone, +}; +use serde::{Deserialize, Serialize}; + +use crate::cluster::{ClusterDemo, ClusterOptions, World}; +use crate::common::{send_json_event, Demo, Guests}; +use world::{MoveInput, Prop, CELL, POS}; + +/// Walker kind. +pub const KIND_WALKER: u16 = 1; +/// Critter kind. +pub const KIND_CRITTER: u16 = 2; +/// Marker kind. +pub const KIND_MARKER: u16 = 3; +/// Event type (JSON) sent to every joining player and observer, see [`GridHello`]. +pub const EVENT_HELLO: u32 = 1; +/// Most markers a cell keeps (oldest dropped first). +pub const MAX_MARKERS: usize = 12; +/// Most command frames a walker may bank. +pub const MAX_CREDITS: u8 = 4; +const CRITTER_SPEED: f32 = 1.6; +const CRITTER_RADIUS: f32 = 0.3; +const MARK_COOLDOWN: u8 = 15; + +/// What a zone tells each player / observer on arrival (JSON, camelCase). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct GridHello { + /// Zone id. + pub zone: String, + /// Cell coordinates. + pub cell: [i32; 2], + /// Host running the zone. + pub host: String, + /// World seed (the client generates the same content). + pub seed: u32, + /// Generation version. + pub content_version: u32, + /// Cell edge (m). + pub cell_size: f32, + /// The player's own walker entity (players only). + pub entity: Option, + /// This activation restored a hibernation snapshot. + pub restored: bool, + /// Times this cell was restored (persisted). + pub restores: u32, + /// How long the snapshot slept (ms), when restored. + pub hibernated_for_ms: Option, + /// Critters / markers in the restored snapshot. + pub restored_critters: u32, + /// Markers in the restored snapshot. + pub restored_markers: u32, + /// Activation start (Unix ms): identifies this activation. + pub activated_at: u64, +} + +struct Walker { + entity: u32, + name: String, + hue: u8, + x: f32, + y: f32, + credits: u8, + mark_cooldown: u8, + leaving: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +struct Critter { + id: u32, + x: f32, + y: f32, + tx: f32, + ty: f32, + yaw: f32, + hue: u8, + rest: u16, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +struct Marker { + id: u32, + x: f32, + y: f32, + label: String, + hue: u8, +} + +/// Hibernation snapshot (JSON). +#[derive(Debug, Serialize, Deserialize)] +struct Snapshot { + critters: Vec, + markers: Vec, + next_marker: u32, + restores: u32, + saved_at_ms: u64, +} + +/// Zone construction parameters. +#[derive(Clone)] +pub struct GridConfig { + /// Display names. + pub guests: Guests, + /// Host running the zone (shown to clients). + pub host_id: String, + /// World seed. + pub seed: u32, + /// The cell. + pub cell: (i32, i32), +} + +/// One cell of the grid. +pub struct GridZone { + config: GridConfig, + props: Vec, + walkers: BTreeMap, + critters: Vec, + markers: Vec, + next_marker: u32, + restores: u32, + restored: Option<(u64, u32, u32)>, + activated_at: u64, +} + +fn unix_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) +} + +fn hue_of(principal: &str) -> u8 { + let h = principal.bytes().fold(0x811c_9dc5u32, |h, b| { + (h ^ u32::from(b)).wrapping_mul(0x0100_0193) + }); + (world::hash32(h) >> 24) as u8 +} + +impl GridZone { + /// Walkers as `(name, x, y)` (ops tooling and tests). + pub fn walkers(&self) -> Vec<(String, f32, f32)> { + self.walkers + .values() + .map(|w| (w.name.clone(), w.x, w.y)) + .collect() + } + + /// Dropped markers. + pub fn marker_count(&self) -> usize { + self.markers.len() + } + + fn free_point(&self, ctx: &mut Ctx<'_, Self>, margin: f32) -> (f32, f32) { + for _ in 0..32 { + let x = 1.0 + ctx.rng().next_f32() * (CELL - 2.0); + let y = 1.0 + ctx.rng().next_f32() * (CELL - 2.0); + let clear = self + .props + .iter() + .filter(|p| p.solid) + .all(|p| (x - p.x).powi(2) + (y - p.y).powi(2) > (p.r + margin).powi(2)); + if clear { + return (x, y); + } + } + // Sub-cell corners are always free. + (CELL / 2.0, CELL / 2.0) + } + + fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> serde_json::Value { + let hello = GridHello { + zone: ctx.zone_id().to_string(), + cell: [self.config.cell.0, self.config.cell.1], + host: self.config.host_id.clone(), + seed: self.config.seed, + content_version: world::CONTENT_VERSION, + cell_size: CELL, + entity, + restored: self.restored.is_some(), + restores: self.restores, + hibernated_for_ms: self.restored.map(|(ms, _, _)| ms), + restored_critters: self.restored.map_or(0, |(_, c, _)| c), + restored_markers: self.restored.map_or(0, |(_, _, m)| m), + activated_at: self.activated_at, + }; + serde_json::to_value(hello).unwrap_or_default() + } + + fn admit( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + at: (f32, f32), + name: Option, + ) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self + .config + .guests + .name(&principal) + .or(name) + .unwrap_or_else(|| format!("Guest {}", principal.get(6..10).unwrap_or(""))); + let entity = 1000 + player.0; + self.walkers.insert( + player, + Walker { + entity, + name, + hue: hue_of(&principal), + x: world::snap(at.0), + y: world::snap(at.1), + credits: MAX_CREDITS, + mark_cooldown: 0, + leaving: false, + }, + ); + let hello = self.hello(ctx, Some(entity)); + send_json_event(ctx, player, EVENT_HELLO, &hello); + } + + fn drop_marker(&mut self, x: f32, y: f32, label: String, hue: u8) { + if self.markers.len() >= MAX_MARKERS { + self.markers.remove(0); + } + let id = 500 + self.next_marker % 400; + self.next_marker = self.next_marker.wrapping_add(1); + self.markers.push(Marker { + id, + x, + y, + label, + hue, + }); + } + + fn wander(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + for i in 0..self.critters.len() { + let c = &self.critters[i]; + if c.rest > 0 { + self.critters[i].rest -= 1; + continue; + } + let (ox, oy) = (c.tx - c.x, c.ty - c.y); + let dist = (ox * ox + oy * oy).sqrt(); + if dist < 0.2 { + let (tx, ty) = self.free_point(ctx, 0.8); + let rest = 10 + (ctx.rng().next_f32() * 50.0) as u16; + let c = &mut self.critters[i]; + (c.tx, c.ty, c.rest) = (tx, ty, rest); + continue; + } + let stride = (CRITTER_SPEED * dt).min(dist); + let (x, y) = world::collide( + c.x + ox / dist * stride, + c.y + oy / dist * stride, + CRITTER_RADIUS, + &self.props, + ); + let c = &mut self.critters[i]; + c.yaw = oy.atan2(ox); + (c.x, c.y) = ( + world::snap(x.clamp(0.3, CELL - 0.3)), + world::snap(y.clamp(0.3, CELL - 0.3)), + ); + } + } +} + +/// Carried state of a handoff: position in the target frame and the name. +pub fn encode_carried(x: f32, y: f32, name: &str) -> Vec { + let mut out = Vec::with_capacity(8 + name.len()); + out.extend_from_slice(&x.to_le_bytes()); + out.extend_from_slice(&y.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out +} + +/// Inverse of [`encode_carried`]; None for a malformed or out-of-range payload. +pub fn decode_carried(carried: &[u8]) -> Option<(f32, f32, String)> { + let x = f32::from_le_bytes(carried.get(0..4)?.try_into().ok()?); + let y = f32::from_le_bytes(carried.get(4..8)?.try_into().ok()?); + let range = -world::OUTSIDE_LIMIT..=CELL + world::OUTSIDE_LIMIT; + if !range.contains(&x) || !range.contains(&y) { + return None; + } + let name = std::str::from_utf8(carried.get(8..)?).ok()?; + Some((x, y, name.chars().take(16).collect())) +} + +impl Zone for GridZone { + type Config = GridConfig; + type Input = MoveInput; + type Timer = (); + + fn schema() -> EntitySchema { + EntitySchema::new() + .kind( + KindDef::new(KIND_WALKER, "walker") + .field("x", POS) + .field("y", POS) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .field("hue", FieldType::U8) + .priority(2.0), + ) + .kind( + KindDef::new(KIND_CRITTER, "critter") + .field("x", POS) + .field("y", POS) + .field("yaw", FieldType::Angle { bits: 8 }) + .field("hue", FieldType::U8), + ) + .kind( + KindDef::new(KIND_MARKER, "marker") + .field("x", POS) + .field("y", POS) + .field("label", FieldType::ShortStr) + .field("hue", FieldType::U8), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, config: GridConfig) -> Self { + let props = world::cell_props(config.seed, config.cell); + let count = 2 + world::mix(config.seed, 9, config.cell.0, config.cell.1) % 3; + let mut zone = Self { + config, + props, + walkers: BTreeMap::new(), + critters: Vec::new(), + markers: Vec::new(), + next_marker: 0, + restores: 0, + restored: None, + activated_at: unix_ms(), + }; + for id in 1..=count { + let (x, y) = zone.free_point(ctx, 0.8); + let (tx, ty) = zone.free_point(ctx, 0.8); + let hue = (ctx.rng().next_f32() * 255.0) as u8; + zone.critters.push(Critter { + id, + x: world::snap(x), + y: world::snap(y), + tx, + ty, + yaw: 0.0, + hue, + rest: 0, + }); + } + zone + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + // Sub-cell corners are always free of props. + self.admit(ctx, player, (CELL / 2.0, CELL / 2.0), None); + } + + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + _from: &str, + carried: Vec, + ) { + match decode_carried(&carried) { + Some((x, y, name)) => self.admit(ctx, player, (x, y), Some(name)), + None => self.admit(ctx, player, (CELL / 2.0, CELL / 2.0), None), + } + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.walkers.remove(&player); + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + let hello = self.hello(ctx, None); + send_json_event(ctx, observer, EVENT_HELLO, &hello); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + MoveInput::decode(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let ids: Vec = self.walkers.keys().copied().collect(); + for id in ids { + let mut marks = Vec::new(); + { + let Some(w) = self.walkers.get_mut(&id) else { + continue; + }; + if w.leaving { + continue; + } + w.credits = (w.credits + 1).min(MAX_CREDITS); + w.mark_cooldown = w.mark_cooldown.saturating_sub(1); + while w.credits > 0 { + let Some(input) = ctx.take_inputs(id, ConsumePolicy::Next).pop() else { + break; + }; + let input = input.input; + (w.x, w.y) = world::step(w.x, w.y, input, &self.props); + w.credits -= 1; + if input.buttons & world::BUTTON_MARK != 0 && w.mark_cooldown == 0 { + w.mark_cooldown = MARK_COOLDOWN; + marks.push((w.x, w.y, w.name.clone(), w.hue)); + } + if world::crossing(w.x, w.y).is_some() { + break; + } + } + } + for (x, y, label, hue) in marks { + self.drop_marker(x, y, label, hue); + } + let w = &self.walkers[&id]; + let Some((dx, dy)) = world::crossing(w.x, w.y) else { + continue; + }; + let (cx, cy) = (self.config.cell.0 + dx, self.config.cell.1 + dy); + let target = world::zone_id((cx, cy)); + let carried = encode_carried(w.x - dx as f32 * CELL, w.y - dy as f32 * CELL, &w.name); + let inside = cx.abs() <= world::MAX_CELL && cy.abs() <= world::MAX_CELL; + let handed = inside && ctx.handoff(id, &target, carried).is_ok(); + let w = self.walkers.get_mut(&id).expect("walker"); + if handed { + w.leaving = true; + } else { + // Edge of the world (or no issuer): stay inside. + w.x = w.x.clamp(-world::HYSTERESIS, CELL + world::HYSTERESIS); + w.y = w.y.clamp(-world::HYSTERESIS, CELL + world::HYSTERESIS); + } + } + self.wander(ctx); + } + + fn replicate(&self, out: &mut WorldView) { + for w in self.walkers.values() { + out.push( + EntityState::new( + w.entity, + KIND_WALKER, + w.x, + w.y, + vec![ + FieldValue::F(w.x), + FieldValue::F(w.y), + FieldValue::Str(w.name.clone()), + FieldValue::U(w.hue.into()), + ], + ) + .global(), + ); + } + for c in &self.critters { + out.push( + EntityState::new( + c.id, + KIND_CRITTER, + c.x, + c.y, + vec![ + FieldValue::F(c.x), + FieldValue::F(c.y), + FieldValue::F(c.yaw), + FieldValue::U(c.hue.into()), + ], + ) + .global() + .priority(0.5), + ); + } + for m in &self.markers { + out.push( + EntityState::new( + m.id, + KIND_MARKER, + m.x, + m.y, + vec![ + FieldValue::F(m.x), + FieldValue::F(m.y), + FieldValue::Str(m.label.clone()), + FieldValue::U(m.hue.into()), + ], + ) + .global() + .priority(0.3), + ); + } + } + + fn hibernate(&self) -> Option> { + serde_json::to_vec(&Snapshot { + critters: self.critters.clone(), + markers: self.markers.clone(), + next_marker: self.next_marker, + restores: self.restores, + saved_at_ms: unix_ms(), + }) + .ok() + } + + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { + let Ok(snapshot) = serde_json::from_slice::(state) else { + return; + }; + self.restored = Some(( + unix_ms().saturating_sub(snapshot.saved_at_ms), + snapshot.critters.len() as u32, + snapshot.markers.len() as u32, + )); + self.critters = snapshot.critters; + self.markers = snapshot.markers; + self.next_marker = snapshot.next_marker; + self.restores = snapshot.restores + 1; + } +} + +/// Bot payload: direction → sprinting [`MoveInput`]. +pub fn encode_bot_input(dir: [f32; 2]) -> Vec { + let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; + MoveInput { + mx: axis(dir[0]), + my: axis(dir[1]), + buttons: world::BUTTON_SPRINT, + } + .encode() + .to_vec() +} + +/// World seed: `DG_GRID_SEED` (decimal or 0x-hex) or [`world::DEFAULT_SEED`]. +pub fn seed_from_env() -> u32 { + std::env::var("DG_GRID_SEED") + .ok() + .and_then(|v| { + let v = v.trim(); + match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + } + }) + .unwrap_or(world::DEFAULT_SEED) +} + +/// Demo registration (`game-demos grid`). +pub struct GridDemo; + +impl Demo for GridDemo { + type Zone = GridZone; + const NAME: &'static str = "grid"; + const DEFAULT_ZONE: &'static str = "grid.0.0"; + + fn hosts_zone(zone_id: &str) -> bool { + world::parse_zone(zone_id).is_some() + } + + /// Single host (used by `common::spawn`); `game-demos grid` runs + /// [`crate::cluster::run_cluster`] instead. + fn server(config: ServerConfig, guests: Guests) -> GameServer { + let options = ClusterOptions::single("local", std::time::Duration::from_secs(4)); + let world = crate::cluster::World::standalone::(&options, guests); + Self::cluster_server(config, &world) + } +} + +impl ClusterDemo for GridDemo { + fn directory(hosts: &[HostAddr]) -> Arc { + Arc::new(HashRing::with_hosts(64, hosts.iter().cloned())) + } + + fn cluster_server(mut config: ServerConfig, world: &World) -> GameServer { + let seed = seed_from_env(); + config.host.world_seed = u64::from(seed); + config.host.idle_tick_rate = Some(2); + config.host.max_observers = 64; + let guests = world.guests.clone(); + let host_id = world.host.id.clone(); + GameServer::new(config, move |zone_id| { + world::parse_zone(zone_id).map(|cell| GridConfig { + guests: guests.clone(), + host_id: host_id.clone(), + seed, + cell, + }) + }) + .with_topology(Arc::new(FlatTopology)) + } + + fn cluster_routes(server: GameServer, world: Arc) -> axum::Router { + dev::routes(server, world) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn carried_state_round_trips_and_is_bounded() { + let bytes = encode_carried(0.5, 31.0, "Ana"); + assert_eq!(decode_carried(&bytes), Some((0.5, 31.0, "Ana".into()))); + assert_eq!(decode_carried(&encode_carried(99.0, 1.0, "x")), None); + assert_eq!(decode_carried(&[1, 2, 3]), None); + } +} diff --git a/examples/game/server/src/grid/world.rs b/examples/game/server/src/grid/world.rs new file mode 100644 index 000000000..289e66ec4 --- /dev/null +++ b/examples/game/server/src/grid/world.rs @@ -0,0 +1,435 @@ +//! Procedural world and movement of the Endless Grid. +//! +//! **This file has a twin:** `examples/game/client/src/grid/world.ts`. The +//! static content of a cell (terrain height, biome, props) is a pure +//! function of `(world seed, cell x, cell y, CONTENT_VERSION)`; the server +//! uses it for collision and the client for rendering, and **nothing +//! static is replicated**. The movement step is shared too, so the client +//! predicts its own walker exactly. +//! +//! Rules that keep both sides bit-identical (as in the Arena movement): +//! integer hashing on `u32` only (`Math.imul` / `>>> 0` in TypeScript); +//! floats are binary32 (`Math.fround` after every operation) using only +//! `+ - * /`, `sqrt` and `floor`; constants are dyadic where it matters. +//! `tests/grid_fixture.rs` writes `examples/game/fixtures/grid-world.json`, +//! replayed by the client's `tests/grid-world-parity.test.mjs`. Change both +//! files together, then `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. +//! +//! Layout: a cell is [`CELL`] m square with local coordinates `0..CELL` on +//! both axes; cell `(cx, cy)` covers world `cx*CELL .. (cx+1)*CELL`. Each +//! cell is split into 4×4 sub-cells of 8 m holding at most one prop, kept +//! [`PROP_MARGIN`] m away from the sub-cell edges: every line where x or y +//! is a multiple of 8 m is a free path ("trail"), and props never reach +//! across a cell border. + +use distributed_game::{FieldType, FieldValue}; + +/// Cell edge length (m). +pub const CELL: f32 = 32.0; +/// Bumped whenever generation changes (part of every hash). +pub const CONTENT_VERSION: u32 = 1; +/// Default world seed. +pub const DEFAULT_SEED: u32 = 0x00C0_FFEE; +/// Sub-cells per cell axis. +pub const SUB: i32 = 4; +/// Sub-cell edge length (m). +pub const SUB_SIZE: f32 = 8.0; +/// Prop distance from sub-cell edges (m). +pub const PROP_MARGIN: f32 = 2.0; +/// Prop placement span inside a sub-cell: `SUB_SIZE - 2 * PROP_MARGIN`. +pub const PROP_SPAN: f32 = 4.0; +/// Handoff hysteresis (m): a walker belongs to the neighbour once it is +/// this far past the border, and arrives this far inside it. +pub const HYSTERESIS: f32 = 0.5; +/// Walker radius (m). +pub const PLAYER_RADIUS: f32 = 0.45; +/// Walking speed (m/s). +pub const WALK_SPEED: f32 = 6.0; +/// Sprint speed (m/s). +pub const SPRINT_SPEED: f32 = 10.0; +/// Command frame length (s): the 30 Hz tick. +pub const DT: f32 = 1.0 / 30.0; +/// How far outside its cell a walker may be before it is clamped (m). +pub const OUTSIDE_LIMIT: f32 = 2.0; +/// Input bit: sprint. +pub const BUTTON_SPRINT: u8 = 1; +/// Input bit: drop a marker. +pub const BUTTON_MARK: u8 = 2; +/// Wire type of local positions (covers the walker's slack outside the cell). +pub const POS: FieldType = FieldType::QuantF32 { + min: -8.0, + max: 40.0, + bits: 18, +}; + +/// Biomes, by index. +pub const BIOMES: [&str; 4] = ["highlands", "steppe", "forest", "meadow"]; +const PROP_DENSITY: [f32; 4] = [0.4375, 0.1875, 0.75, 0.3125]; +const SALT_HEIGHT: [u32; 3] = [1, 2, 3]; +const SALT_MOISTURE: u32 = 7; +const SALT_PROP: u32 = 100; + +/// Prop kinds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PropKind { + /// Solid trunk, big canopy (cosmetic). + Tree = 0, + /// Solid boulder. + Rock = 1, + /// Walk-through shrub. + Bush = 2, +} + +/// One static prop in cell-local coordinates. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Prop { + /// Kind. + pub kind: PropKind, + /// Local x. + pub x: f32, + /// Local y. + pub y: f32, + /// Collision (trunk / boulder) radius. + pub r: f32, + /// Blocks walkers. + pub solid: bool, + /// Cosmetic variation (0..=255). + pub variant: u8, +} + +/// lowbias32 integer hash. +pub fn hash32(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^= x >> 16; + x +} + +/// Hash of `(seed, salt, a, b)` including [`CONTENT_VERSION`]. +pub fn mix(seed: u32, salt: u32, a: i32, b: i32) -> u32 { + let mut h = hash32(seed ^ hash32(salt.wrapping_add(CONTENT_VERSION.wrapping_mul(0x9e37_79b9)))); + h = hash32(h ^ a as u32); + hash32(h.wrapping_add((b as u32).wrapping_mul(0x85eb_ca6b))) +} + +/// Top 24 bits as an exact binary32 in `[0, 1)`. +pub fn unit(h: u32) -> f32 { + (h >> 8) as f32 * (1.0 / 16_777_216.0) +} + +/// Lattice index and fraction along one axis for local coordinate `l` +/// (`0..=CELL`) of cell `c` and lattice `spacing` (divides 32 or is a +/// multiple of 32). Integer-based so a cell border samples identically +/// from both sides. +fn lattice(c: i32, l: f32, spacing: i32) -> (i32, f32) { + let s = spacing as f32; + if spacing <= CELL as i32 { + let per = CELL as i32 / spacing; + let k = ((l / s).floor() as i32).clamp(0, per); + let frac = (l - (k * spacing) as f32) / s; + (c.wrapping_mul(per).wrapping_add(k), frac) + } else { + let n = spacing / CELL as i32; + let mut i = c.div_euclid(n); + let mut off = (c - i * n) as f32 * CELL + l; + if off >= s { + // The far border is the next lattice point at fraction 0. + i = i.wrapping_add(1); + off -= s; + } + (i, off / s) + } +} + +fn smooth(t: f32) -> f32 { + t * t * (3.0 - 2.0 * t) +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +/// Value noise in `[0, 1)` with lattice `spacing` (m). +pub fn noise(seed: u32, salt: u32, cell: (i32, i32), l: (f32, f32), spacing: i32) -> f32 { + let (ix, fx) = lattice(cell.0, l.0, spacing); + let (iy, fy) = lattice(cell.1, l.1, spacing); + let v = |dx: i32, dy: i32| unit(mix(seed, salt, ix.wrapping_add(dx), iy.wrapping_add(dy))); + let (sx, sy) = (smooth(fx), smooth(fy)); + lerp(lerp(v(0, 0), v(1, 0), sx), lerp(v(0, 1), v(1, 1), sx), sy) +} + +/// Terrain height in `[0, 1)` (three octaves; the client draws `4 m × h`). +pub fn height(seed: u32, cell: (i32, i32), l: (f32, f32)) -> f32 { + noise(seed, SALT_HEIGHT[0], cell, l, 64) * 0.5625 + + noise(seed, SALT_HEIGHT[1], cell, l, 16) * 0.3125 + + noise(seed, SALT_HEIGHT[2], cell, l, 8) * 0.125 +} + +/// Moisture in `[0, 1)` (one broad octave). +pub fn moisture(seed: u32, cell: (i32, i32), l: (f32, f32)) -> f32 { + noise(seed, SALT_MOISTURE, cell, l, 128) +} + +/// Biome index into [`BIOMES`]. +pub fn biome(seed: u32, cell: (i32, i32), l: (f32, f32)) -> u8 { + let h = height(seed, cell, l); + let m = moisture(seed, cell, l); + if h > 0.6875 { + 0 + } else if m < 0.375 { + 1 + } else if m > 0.625 { + 2 + } else { + 3 + } +} + +/// The props of a cell, sub-cell by sub-cell (row-major). +pub fn cell_props(seed: u32, cell: (i32, i32)) -> Vec { + let mut props = Vec::new(); + for j in 0..SUB { + for i in 0..SUB { + let gx = cell.0.wrapping_mul(SUB).wrapping_add(i); + let gy = cell.1.wrapping_mul(SUB).wrapping_add(j); + let h0 = mix(seed, SALT_PROP, gx, gy); + let center = ( + i as f32 * SUB_SIZE + SUB_SIZE / 2.0, + j as f32 * SUB_SIZE + SUB_SIZE / 2.0, + ); + let b = biome(seed, cell, center); + if unit(h0) >= PROP_DENSITY[b as usize] { + continue; + } + let h1 = hash32(h0 ^ 0x68e3_1da4); + let h2 = hash32(h1 ^ 0xb529_7a4d); + let h3 = hash32(h2 ^ 0x1b56_c4e9); + let h4 = hash32(h3 ^ 0x2545_f491); + let x = i as f32 * SUB_SIZE + PROP_MARGIN + unit(h1) * PROP_SPAN; + let y = j as f32 * SUB_SIZE + PROP_MARGIN + unit(h2) * PROP_SPAN; + let k = unit(h3); + let kind = match b { + 0 if k < 0.8125 => PropKind::Rock, + 0 => PropKind::Tree, + 1 if k < 0.5 => PropKind::Rock, + 1 => PropKind::Bush, + 2 if k < 0.8125 => PropKind::Tree, + 2 if k < 0.875 => PropKind::Rock, + 2 => PropKind::Bush, + _ if k < 0.375 => PropKind::Tree, + _ if k < 0.5625 => PropKind::Rock, + _ => PropKind::Bush, + }; + let u = unit(h4); + let r = match kind { + PropKind::Tree => 0.5 + u * 0.3125, + PropKind::Rock => 0.625 + u * 0.375, + PropKind::Bush => 0.5 + u * 0.25, + }; + props.push(Prop { + kind, + x, + y, + r, + solid: kind != PropKind::Bush, + variant: (h4 >> 24) as u8, + }); + } + } + props +} + +/// One command frame: stick per axis in `[-127, 127]` and button bits. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MoveInput { + /// Stick x (+east). + pub mx: i8, + /// Stick y (+north). + pub my: i8, + /// [`BUTTON_SPRINT`] | [`BUTTON_MARK`]. + pub buttons: u8, +} + +impl MoveInput { + /// Wire payload `[mx, my, buttons]`. + pub fn encode(self) -> [u8; 3] { + [self.mx as u8, self.my as u8, self.buttons] + } + + /// Parse and sanitize (`-128` → `-127`, unknown buttons cleared). + pub fn decode(payload: &[u8]) -> Option { + let [mx, my, buttons] = payload else { + return None; + }; + Some(Self { + mx: (*mx as i8).max(-127), + my: (*my as i8).max(-127), + buttons: buttons & (BUTTON_SPRINT | BUTTON_MARK), + }) + } +} + +/// Snap to the wire quantization so the server holds exactly what clients decode. +pub fn snap(v: f32) -> f32 { + match POS.canonicalize(&FieldValue::F(v)) { + FieldValue::F(v) => v, + _ => v, + } +} + +/// Push a circle of radius `radius` at `(x, y)` out of every solid prop. +pub fn collide(mut x: f32, mut y: f32, radius: f32, props: &[Prop]) -> (f32, f32) { + for p in props.iter().filter(|p| p.solid) { + let ox = x - p.x; + let oy = y - p.y; + let d2 = ox * ox + oy * oy; + let min = radius + p.r; + if d2 < min * min { + let d = d2.sqrt(); + let (nx, ny) = if d > 1e-6 { + (ox / d, oy / d) + } else { + (1.0, 0.0) + }; + x = p.x + nx * min; + y = p.y + ny * min; + } + } + (x, y) +} + +/// Advance a walker one command frame inside its cell (`props` = the +/// cell's props). Positions may leave `0..CELL` by up to +/// [`OUTSIDE_LIMIT`]; the zone hands the walker off past [`HYSTERESIS`]. +pub fn step(x: f32, y: f32, input: MoveInput, props: &[Prop]) -> (f32, f32) { + let mut dx = f32::from(input.mx) / 127.0; + let mut dy = f32::from(input.my) / 127.0; + let l2 = dx * dx + dy * dy; + if l2 > 1.0 { + let inv = 1.0 / l2.sqrt(); + dx *= inv; + dy *= inv; + } + let speed = if input.buttons & BUTTON_SPRINT != 0 { + SPRINT_SPEED + } else { + WALK_SPEED + }; + let x = x + dx * speed * DT; + let y = y + dy * speed * DT; + let (x, y) = collide(x, y, PLAYER_RADIUS, props); + let lo = -OUTSIDE_LIMIT; + let hi = CELL + OUTSIDE_LIMIT; + (snap(x.clamp(lo, hi)), snap(y.clamp(lo, hi))) +} + +/// Neighbour a walker at `(x, y)` belongs to, as a cell offset, or None +/// while inside (with hysteresis). X first, then y. +pub fn crossing(x: f32, y: f32) -> Option<(i32, i32)> { + if x < -HYSTERESIS { + Some((-1, 0)) + } else if x > CELL + HYSTERESIS { + Some((1, 0)) + } else if y < -HYSTERESIS { + Some((0, -1)) + } else if y > CELL + HYSTERESIS { + Some((0, 1)) + } else { + None + } +} + +/// `grid..`; coordinates are limited to ±1 000 000. +pub fn zone_id(cell: (i32, i32)) -> String { + format!("grid.{}.{}", cell.0, cell.1) +} + +/// Largest |cell coordinate|. +pub const MAX_CELL: i32 = 1_000_000; + +/// Parse `grid..` (canonical integers only). +pub fn parse_zone(zone_id: &str) -> Option<(i32, i32)> { + let rest = zone_id.strip_prefix("grid.")?; + let (x, y) = rest.split_once('.')?; + let parse = |s: &str| -> Option { + let v: i32 = s.parse().ok()?; + (v.to_string() == s && v.abs() <= MAX_CELL).then_some(v) + }; + Some((parse(x)?, parse(y)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zone_ids_round_trip() { + assert_eq!(parse_zone("grid.0.0"), Some((0, 0))); + assert_eq!(parse_zone("grid.-3.12"), Some((-3, 12))); + assert_eq!(parse_zone(&zone_id((-7, 9))), Some((-7, 9))); + for bad in [ + "grid.1", + "grid.01.2", + "grid.+1.2", + "grid.1.2.3", + "grid.2000000.0", + "arena-1", + ] { + assert_eq!(parse_zone(bad), None, "{bad}"); + } + } + + #[test] + fn borders_match_and_trails_stay_free() { + let seed = DEFAULT_SEED; + for cx in -3..3 { + for cy in -3..3 { + // The shared edge samples the same lattice from both cells. + for k in 0..=16 { + let l = k as f32 * 2.0; + assert_eq!( + height(seed, (cx, cy), (32.0, l)), + height(seed, (cx + 1, cy), (0.0, l)) + ); + assert_eq!( + height(seed, (cx, cy), (l, 32.0)), + height(seed, (cx, cy + 1), (l, 0.0)) + ); + } + for p in cell_props(seed, (cx, cy)) { + let reach = if p.solid { p.r + PLAYER_RADIUS } else { 0.0 }; + for line in [0.0, 8.0, 16.0, 24.0, 32.0] { + assert!((p.x - line).abs() > reach && (p.y - line).abs() > reach); + } + // A walker up to HYSTERESIS past the border (still + // owned by this cell) never overlaps a neighbour's prop. + let clear = HYSTERESIS + PLAYER_RADIUS; + assert!(p.x - p.r >= clear && p.x + p.r <= CELL - clear); + assert!(p.y - p.r >= clear && p.y + p.r <= CELL - clear); + } + } + } + } + + #[test] + fn walking_a_trail_crosses_the_cell() { + let props = cell_props(DEFAULT_SEED, (0, 0)); + let (mut x, mut y) = (16.0, 16.0); + let east = MoveInput { + mx: 127, + my: 0, + buttons: BUTTON_SPRINT, + }; + let mut frames = 0; + while crossing(x, y).is_none() { + (x, y) = step(x, y, east, &props); + frames += 1; + assert!(frames < 200, "stuck at {x},{y}"); + } + assert_eq!(crossing(x, y), Some((1, 0))); + assert!((y - 16.0).abs() < 1e-3); + } +} diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index 7bfa7546f..d892f80b1 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -7,4 +7,7 @@ //! See `examples/game/README.md`. pub mod arena; +pub mod cluster; pub mod common; +pub mod grid; +pub mod ripple; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs index 7fde2d462..211106026 100644 --- a/examples/game/server/src/main.rs +++ b/examples/game/server/src/main.rs @@ -2,7 +2,10 @@ use clap::{Parser, Subcommand}; use game_demos::arena::ArenaDemo; +use game_demos::cluster::{run_cluster, ClusterArgs}; use game_demos::common::{run, DemoArgs}; +use game_demos::grid::GridDemo; +use game_demos::ripple::RippleDemo; #[derive(Parser)] #[command( @@ -18,11 +21,17 @@ struct Cli { enum DemoCommand { /// Prediction, reconciliation, interpolation and interest management. Arena(DemoArgs), + /// Endless Grid: procedural cells as zones, handoff across hosts, hibernation. + Grid(ClusterArgs), + /// Boss Ripple: realm > city > borough > hood, tier-up events across hosts. + Ripple(ClusterArgs), } #[tokio::main] async fn main() -> std::io::Result<()> { match Cli::parse().demo { DemoCommand::Arena(args) => run::(args).await, + DemoCommand::Grid(args) => run_cluster::(args).await, + DemoCommand::Ripple(args) => run_cluster::(args).await, } } diff --git a/examples/game/server/src/ripple/mod.rs b/examples/game/server/src/ripple/mod.rs new file mode 100644 index 000000000..7db89698b --- /dev/null +++ b/examples/game/server/src/ripple/mod.rs @@ -0,0 +1,788 @@ +//! **Boss Ripple** — hierarchical zones and tier-up event propagation. +//! +//! ```text +//! realm (2 Hz, idle background clock) +//! └ realm.city (5 Hz) +//! ├ realm.city.borough-1 (10 Hz) +//! │ ├ realm.city.borough-1.hood-1 (30 Hz, a boss + players) +//! │ ├ … hood-2, hood-3 +//! └ realm.city.borough-2 … +//! ``` +//! +//! Every neighborhood has a boss players can fight (E near it) or smite +//! (demo button). The boss **stays in its zone**; only its effects travel +//! up as tier-up events (`ctx.emit_upward`, routed by the server through +//! `DottedTopology`, across hosts via `/admin/child-event`): +//! +//! 1. hood: boss falls → `boss_defeated` (to the root); +//! 2. borough: tallies its hoods; when all fell it unlocks and emits +//! `borough_cleared` (to the root); +//! 3. city: weather follows the remaining bosses (storm → rain → clearing +//! → clear) and is broadcast to everyone observing the city — the +//! players in its neighborhoods observe it, so the weather reaches +//! them; with every borough cleared it emits `city_liberated`; +//! 4. realm: counts everything and shows a global banner. +//! +//! A defeated boss respawns after [`RESPAWN`] (`boss_respawned`, which +//! re-locks the borough and darkens the sky again). Tiers tick at +//! different rates (`GameServer::with_host_config`): realm 2 Hz, city +//! 5 Hz, borough 10 Hz, hood 30 Hz. With two hosts, placement alternates +//! by depth (hoods and the city on the first host, boroughs and the realm +//! on the second), so every hop of the ripple crosses hosts. Each tier's +//! state survives hibernation. +//! +//! Entities: 1 `tier` (id 1, every zone), 2 `boss` (id 2, hoods), 3 +//! `player` (1000 + player, hoods; Arena movement fields so the client +//! predicts with the Arena step — the boss stands on its central pillar). + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::world::{HostAddr, ZoneDirectory}; +use distributed_game::{ + ChildEvent, ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, + LeaveReason, ObserverId, PlayerId, TimerId, WorldView, Zone, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::arena::movement::{self, MoveInput, MoveState}; +use crate::cluster::{ClusterDemo, ClusterOptions, World}; +use crate::common::{broadcast_json_event, send_json_event, Demo, Guests}; + +/// Root zone. +pub const REALM: &str = "realm"; +/// The city. +pub const CITY: &str = "realm.city"; +/// Boroughs of the city. +pub const BOROUGHS: [&str; 2] = ["realm.city.borough-1", "realm.city.borough-2"]; +/// Neighborhoods per borough. +pub const HOODS_PER_BOROUGH: usize = 3; +/// Boss hit points. +pub const BOSS_HP: u32 = 240; +/// Damage per hit. +pub const HIT_DAMAGE: u32 = 12; +/// Reach from the boss center (pillar radius + player radius + 1.5 m). +pub const REACH: f32 = 4.5; +/// A defeated boss returns after this long (simulation time of its hood). +pub const RESPAWN: Duration = Duration::from_secs(60); + +/// Kind: tier state (every zone). +pub const KIND_TIER: u16 = 1; +/// Kind: the boss (hoods). +pub const KIND_BOSS: u16 = 2; +/// Kind: a player (hoods). +pub const KIND_PLAYER: u16 = 3; +/// Event: `{zone, tier, parent, children, host, tickRate, entity?}` on join/observe. +pub const EVENT_HELLO: u32 = 1; +/// Event: a tier received a child event `{at, kind, from, origin, originTick}`. +pub const EVENT_RIPPLE: u32 = 2; +/// Event (city): `{weather, remaining}`. +pub const EVENT_WEATHER: u32 = 3; +/// Event (realm): `{text}`. +pub const EVENT_BANNER: u32 = 4; +/// Event (hood): `{kind: "defeated" | "respawned", by?}`. +pub const EVENT_BOSS: u32 = 5; +/// Input action bit: attack (needs [`REACH`]). +pub const ACTION_ATTACK: u8 = 1; +/// Input action bit: smite (demo shortcut: defeats the boss from anywhere). +pub const ACTION_SMITE: u8 = 2; +const ATTACK_COOLDOWN: u8 = 8; +const MAX_CREDITS: u8 = 4; +/// Weather names by index (city). +pub const WEATHER: [&str; 4] = ["storm", "rain", "clearing", "clear"]; + +/// Tier of a zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TierKind { + /// Province / root. + Realm, + /// City. + City, + /// Borough. + Borough, + /// Neighborhood (has a boss). + Hood, +} + +impl TierKind { + /// Depth in the hierarchy (realm = 1). + pub fn depth(self) -> usize { + match self { + Self::Realm => 1, + Self::City => 2, + Self::Borough => 3, + Self::Hood => 4, + } + } + + /// Lowercase name. + pub fn name(self) -> &'static str { + match self { + Self::Realm => "realm", + Self::City => "city", + Self::Borough => "borough", + Self::Hood => "hood", + } + } + + /// (tick, patch, idle) rates. + pub fn rates(self) -> (u32, u32, Option) { + match self { + Self::Realm => (2, 2, Some(1)), + Self::City => (5, 5, Some(1)), + Self::Borough => (10, 10, Some(1)), + Self::Hood => (30, 20, Some(2)), + } + } +} + +/// Neighborhoods of a borough. +pub fn hoods(borough: &str) -> Vec { + (1..=HOODS_PER_BOROUGH) + .map(|i| format!("{borough}.hood-{i}")) + .collect() +} + +/// Every zone of the hierarchy, root first. +pub fn all_zones() -> Vec { + let mut zones = vec![REALM.to_string(), CITY.to_string()]; + for b in BOROUGHS { + zones.push(b.to_string()); + zones.extend(hoods(b)); + } + zones +} + +/// Total bosses. +pub fn total_bosses() -> usize { + BOROUGHS.len() * HOODS_PER_BOROUGH +} + +/// Tier of a known zone id. +pub fn tier_of(zone_id: &str) -> Option { + match zone_id { + REALM => Some(TierKind::Realm), + CITY => Some(TierKind::City), + z if BOROUGHS.contains(&z) => Some(TierKind::Borough), + z => BOROUGHS + .iter() + .any(|b| hoods(b).iter().any(|h| h == z)) + .then_some(TierKind::Hood), + } +} + +fn children(zone_id: &str) -> Vec { + match tier_of(zone_id) { + Some(TierKind::Realm) => vec![CITY.into()], + Some(TierKind::City) => BOROUGHS.iter().map(|b| b.to_string()).collect(), + Some(TierKind::Borough) => hoods(zone_id), + _ => Vec::new(), + } +} + +/// Placement: depth-alternating over the sorted hosts (hood → hosts[0], +/// borough → hosts[1], city → hosts[0], realm → hosts[1] with two hosts). +pub struct TierPlacement { + hosts: Vec, +} + +impl TierPlacement { + /// Over `hosts` (sorted by id). + pub fn new(hosts: &[HostAddr]) -> Self { + Self { + hosts: hosts.to_vec(), + } + } +} + +impl ZoneDirectory for TierPlacement { + fn locate(&self, zone_id: &str) -> Option { + let n = self.hosts.len(); + if n == 0 { + return None; + } + let depth = tier_of(zone_id).map_or(4, TierKind::depth); + self.hosts.get((4 - depth) % n).cloned() + } + + fn host(&self, host_id: &str) -> Option { + self.hosts.iter().find(|h| h.id == host_id).cloned() + } + + fn hosts(&self) -> Vec { + self.hosts.clone() + } +} + +/// Hood input: Arena movement + action bits. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct HoodInput { + /// Movement (Arena step). + pub movement: MoveInput, + /// [`ACTION_ATTACK`] | [`ACTION_SMITE`]. + pub action: u8, +} + +impl HoodInput { + /// Wire payload `[mx, my, buttons, action]`. + pub fn encode(self) -> [u8; 4] { + let [mx, my, buttons] = self.movement.encode(); + [mx, my, buttons, self.action] + } + + /// Parse and sanitize. + pub fn decode(payload: &[u8]) -> Option { + let (movement, action) = payload.split_at_checked(3)?; + let [action] = action else { + return None; + }; + Some(Self { + movement: MoveInput::decode(movement)?, + action: action & (ACTION_ATTACK | ACTION_SMITE), + }) + } +} + +/// Timers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RippleTimer { + /// The boss comes back. + Respawn, +} + +struct Fighter { + entity: u32, + name: String, + state: MoveState, + credits: u8, + cooldown: u8, +} + +/// Persistent tier state (also the hibernation snapshot). +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub struct TierState { + /// Boss hit points (hoods). + pub hp: u32, + /// Who landed the last blow (hoods, while defeated). + pub defeated_by: Option, + /// Hoods whose boss is down, as seen by this tier. + pub defeated: BTreeSet, + /// Boroughs cleared, as seen by this tier (city, realm). + pub cleared: BTreeSet, + /// City liberated (city, realm). + pub liberated: bool, + /// Times the city was liberated (realm). + pub liberations: u32, + /// Child events received. + pub events: u32, + /// Realm banner. + pub banner: String, +} + +/// Zone construction parameters. +#[derive(Clone)] +pub struct RippleConfig { + /// Display names. + pub guests: Guests, + /// Host running the zone. + pub host_id: String, + /// Tier. + pub tier: TierKind, +} + +/// One zone of the hierarchy (every tier). +pub struct Ripple { + config: RippleConfig, + state: TierState, + fighters: BTreeMap, + respawn: Option, + /// Ticks simulated by this activation (the tier's clock). + ticks: u32, +} + +impl Ripple { + /// Persistent state (tests, tooling). + pub fn state(&self) -> &TierState { + &self.state + } + + /// Tier. + pub fn tier(&self) -> TierKind { + self.config.tier + } + + fn weather(&self) -> usize { + let remaining = total_bosses() - self.state.defeated.len().min(total_bosses()); + match remaining { + 0 => 3, + 1 | 2 => 2, + 3 | 4 => 1, + _ => 0, + } + } + + fn weather_json(&self) -> Value { + json!({ + "weather": WEATHER[self.weather()], + "remaining": total_bosses() - self.state.defeated.len().min(total_bosses()), + }) + } + + fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> Value { + let tier = self.config.tier; + json!({ + "zone": ctx.zone_id(), + "tier": tier.name(), + "parent": ctx.zone_id().rsplit_once('.').map(|(p, _)| p), + "children": children(ctx.zone_id()), + "host": self.config.host_id, + "tickRate": tier.rates().0, + "entity": entity, + "weather": (tier == TierKind::City).then(|| self.weather_json()), + "banner": self.state.banner, + }) + } + + fn greet(&self, ctx: &mut Ctx<'_, Self>, to: distributed_game::Viewer, entity: Option) { + let hello = self.hello(ctx, entity); + send_json_event(ctx, to, EVENT_HELLO, &hello); + } + + fn defeat(&mut self, ctx: &mut Ctx<'_, Self>, by: String) { + self.state.hp = 0; + self.state.defeated_by = Some(by.clone()); + self.state.defeated.insert(ctx.zone_id().to_string()); + let payload = json!({ "hood": ctx.zone_id(), "by": by }); + ctx.emit_upward( + "boss_defeated", + payload.to_string().into_bytes(), + ChildEvent::TO_ROOT, + ); + broadcast_json_event(ctx, EVENT_BOSS, &json!({ "kind": "defeated", "by": by })); + self.respawn = Some(ctx.set_timeout(RESPAWN, RippleTimer::Respawn)); + } + + fn hood_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let mut blows: Vec<(u32, String)> = Vec::new(); + for (id, f) in &mut self.fighters { + f.credits = (f.credits + 1).min(MAX_CREDITS); + f.cooldown = f.cooldown.saturating_sub(1); + while f.credits > 0 { + let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { + break; + }; + let input = input.input; + f.state = movement::step(f.state, input.movement); + f.credits -= 1; + if input.action & ACTION_SMITE != 0 { + blows.push((u32::MAX, f.name.clone())); + } else if input.action & ACTION_ATTACK != 0 && f.cooldown == 0 { + let d = (f.state.x * f.state.x + f.state.y * f.state.y).sqrt(); + if d <= REACH { + f.cooldown = ATTACK_COOLDOWN; + blows.push((HIT_DAMAGE, f.name.clone())); + } + } + } + } + for (damage, by) in blows { + if self.state.hp == 0 { + break; + } + self.state.hp = self.state.hp.saturating_sub(damage); + if self.state.hp == 0 { + self.defeat(ctx, by); + } + } + } + + fn on_child(&mut self, ctx: &mut Ctx<'_, Self>, event: &ChildEvent) { + let origin = event.origin_zone.clone(); + let tier = self.config.tier; + let weather_before = self.weather(); + match event.kind.as_str() { + "boss_defeated" => { + self.state.defeated.insert(origin.clone()); + } + "boss_respawned" => { + self.state.defeated.remove(&origin); + } + "borough_cleared" => { + self.state.cleared.insert(origin.clone()); + } + "borough_lost" => { + self.state.cleared.remove(&origin); + } + _ => {} + } + match tier { + TierKind::Borough => { + let all = hoods(ctx.zone_id()) + .iter() + .all(|h| self.state.defeated.contains(h)); + let was = self.state.cleared.contains(ctx.zone_id()); + let me = ctx.zone_id().to_string(); + if all && !was { + self.state.cleared.insert(me.clone()); + let payload = json!({ "borough": me }).to_string().into_bytes(); + ctx.emit_upward("borough_cleared", payload, ChildEvent::TO_ROOT); + } else if !all && was { + self.state.cleared.remove(&me); + let payload = json!({ "borough": me }).to_string().into_bytes(); + ctx.emit_upward("borough_lost", payload, ChildEvent::TO_ROOT); + } + } + TierKind::City => { + let liberated = BOROUGHS.iter().all(|b| self.state.cleared.contains(*b)); + if liberated != self.state.liberated { + self.state.liberated = liberated; + let kind = if liberated { + "city_liberated" + } else { + "city_fallen" + }; + let payload = json!({ "city": ctx.zone_id() }).to_string().into_bytes(); + ctx.emit_upward(kind, payload, 1); + } + if self.weather() != weather_before { + let weather = self.weather_json(); + broadcast_json_event(ctx, EVENT_WEATHER, &weather); + } + } + TierKind::Realm => { + let banner = match event.kind.as_str() { + "city_liberated" => { + self.state.liberated = true; + self.state.liberations += 1; + Some(format!( + "The city is liberated! (liberation #{})", + self.state.liberations + )) + } + "city_fallen" => { + self.state.liberated = false; + Some("Darkness returns to the city".to_string()) + } + _ => None, + }; + if let Some(text) = banner { + self.state.banner = text.clone(); + broadcast_json_event(ctx, EVENT_BANNER, &json!({ "text": text })); + } + } + TierKind::Hood => {} + } + self.state.events += 1; + let ripple = json!({ + "at": ctx.zone_id(), + "kind": event.kind, + "from": event.from_zone, + "origin": event.origin_zone, + "originTick": event.origin_tick, + "tick": ctx.tick(), + }); + broadcast_json_event(ctx, EVENT_RIPPLE, &ripple); + } +} + +impl Zone for Ripple { + type Config = RippleConfig; + type Input = HoodInput; + type Timer = RippleTimer; + + fn schema() -> EntitySchema { + EntitySchema::new() + .kind( + KindDef::new(KIND_TIER, "tier") + .field("defeated", FieldType::U8) + .field("total", FieldType::U8) + .field("cleared", FieldType::U8) + .field("liberated", FieldType::Bool) + .field("weather", FieldType::U8) + .field("clock", FieldType::U32) + .field("events", FieldType::U32), + ) + .kind( + KindDef::new(KIND_BOSS, "boss") + .field("hp", FieldType::U16) + .field("max", FieldType::U16) + .field("by", FieldType::ShortStr), + ) + .kind( + KindDef::new(KIND_PLAYER, "player") + .field("x", movement::POS) + .field("y", movement::POS) + .field("vx", movement::VEL) + .field("vy", movement::VEL) + .field("dash", FieldType::U8) + .field("cd", FieldType::U8) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .priority(2.0), + ) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, config: RippleConfig) -> Self { + Self { + config, + state: TierState { + hp: BOSS_HP, + ..TierState::default() + }, + fighters: BTreeMap::new(), + respawn: None, + ticks: 0, + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self + .config + .guests + .name(&principal) + .unwrap_or_else(|| format!("Guest {}", principal.get(6..10).unwrap_or(""))); + let entity = 1000 + player.0; + if self.config.tier == TierKind::Hood { + const SPOTS: [(f32, f32); 4] = [(-6.0, -6.0), (6.0, -6.0), (6.0, 6.0), (-6.0, 6.0)]; + let (x, y) = SPOTS[player.0 as usize % SPOTS.len()]; + self.fighters.insert( + player, + Fighter { + entity, + name, + state: movement::canonicalize(MoveState { + x, + y, + ..MoveState::default() + }), + credits: MAX_CREDITS, + cooldown: 0, + }, + ); + } + let entity = (self.config.tier == TierKind::Hood).then_some(entity); + self.greet(ctx, player.into(), entity); + } + + fn on_auth( + &mut self, + _ctx: &mut Ctx<'_, Self>, + request: &distributed_game::JoinRequest<'_>, + ) -> distributed_game::Admission { + // Only neighborhoods are playable; upper tiers are observed. + if self.config.tier != TierKind::Hood + && request.claims.role == distributed_game::Role::Player + { + return distributed_game::Admission::Reject("observe this tier".into()); + } + distributed_game::Admission::Admit + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.fighters.remove(&player); + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + self.greet(ctx, observer.into(), None); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + HoodInput::decode(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.ticks = self.ticks.wrapping_add(1); + if self.config.tier == TierKind::Hood { + self.hood_tick(ctx); + } + } + + fn on_timer(&mut self, ctx: &mut Ctx<'_, Self>, _id: TimerId, timer: RippleTimer) { + match timer { + RippleTimer::Respawn => { + self.respawn = None; + self.state.hp = BOSS_HP; + self.state.defeated_by = None; + self.state.defeated.remove(ctx.zone_id()); + let payload = json!({ "hood": ctx.zone_id() }).to_string().into_bytes(); + ctx.emit_upward("boss_respawned", payload, ChildEvent::TO_ROOT); + broadcast_json_event(ctx, EVENT_BOSS, &json!({ "kind": "respawned" })); + } + } + } + + fn on_child_event(&mut self, ctx: &mut Ctx<'_, Self>, event: &ChildEvent) { + self.on_child(ctx, event); + } + + fn wants_background(&self) -> bool { + // The realm keeps its slow clock running with nobody watching. + self.config.tier == TierKind::Realm + } + + fn replicate(&self, out: &mut WorldView) { + let s = &self.state; + out.push( + EntityState::new( + 1, + KIND_TIER, + 0.0, + 0.0, + vec![ + FieldValue::U(s.defeated.len() as u32), + FieldValue::U(total_bosses() as u32), + FieldValue::U(s.cleared.len() as u32), + FieldValue::Bool(s.liberated), + FieldValue::U(self.weather() as u32), + FieldValue::U(self.ticks), + FieldValue::U(s.events), + ], + ) + .global(), + ); + if self.config.tier != TierKind::Hood { + return; + } + out.push( + EntityState::new( + 2, + KIND_BOSS, + 0.0, + 0.0, + vec![ + FieldValue::U(s.hp), + FieldValue::U(BOSS_HP), + FieldValue::Str(s.defeated_by.clone().unwrap_or_default()), + ], + ) + .global(), + ); + for f in self.fighters.values() { + let m = f.state; + out.push( + EntityState::new( + f.entity, + KIND_PLAYER, + m.x, + m.y, + vec![ + FieldValue::F(m.x), + FieldValue::F(m.y), + FieldValue::F(m.vx), + FieldValue::F(m.vy), + FieldValue::U(m.dash.into()), + FieldValue::U(m.cooldown.into()), + FieldValue::Str(f.name.clone()), + ], + ) + .global(), + ); + } + } + + fn hibernate(&self) -> Option> { + serde_json::to_vec(&self.state).ok() + } + + fn on_restore(&mut self, ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { + if let Ok(state) = serde_json::from_slice::(state) { + self.state = state; + } + if self.config.tier == TierKind::Hood && self.state.hp == 0 { + self.respawn = Some(ctx.set_timeout(RESPAWN, RippleTimer::Respawn)); + } + } +} + +/// Bot / test payload. +pub fn encode_input(mx: i8, my: i8, action: u8) -> Vec { + HoodInput { + movement: MoveInput { mx, my, buttons: 0 }, + action, + } + .encode() + .to_vec() +} + +/// Demo registration (`game-demos ripple`). +pub struct RippleDemo; + +impl Demo for RippleDemo { + type Zone = Ripple; + const NAME: &'static str = "ripple"; + const DEFAULT_ZONE: &'static str = "realm.city.borough-1.hood-1"; + + fn hosts_zone(zone_id: &str) -> bool { + tier_of(zone_id).is_some() + } + + fn server(config: ServerConfig, guests: Guests) -> GameServer { + let options = ClusterOptions::single("local", Duration::from_secs(20)); + let world = World::standalone::(&options, guests); + Self::cluster_server(config, &world) + } +} + +impl ClusterDemo for RippleDemo { + fn directory(hosts: &[HostAddr]) -> Arc { + Arc::new(TierPlacement::new(hosts)) + } + + fn cluster_server(mut config: ServerConfig, world: &World) -> GameServer { + config.host.max_observers = 64; + let guests = world.guests.clone(); + let host_id = world.host.id.clone(); + GameServer::new(config, move |zone_id| { + tier_of(zone_id).map(|tier| RippleConfig { + guests: guests.clone(), + host_id: host_id.clone(), + tier, + }) + }) + .with_host_config(|zone_id, host| { + if let Some(tier) = tier_of(zone_id) { + let (tick, patch, idle) = tier.rates(); + host.tick_rate = tick; + host.patch_rate = patch; + host.idle_tick_rate = idle; + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hierarchy_and_placement() { + assert_eq!(all_zones().len(), 2 + 2 + 6); + assert_eq!(tier_of("realm.city.borough-2.hood-3"), Some(TierKind::Hood)); + assert_eq!(tier_of("realm.city.borough-3"), None); + let hosts = [HostAddr::new("A", "a:1"), HostAddr::new("B", "b:1")]; + let place = TierPlacement::new(&hosts); + let owner = |z: &str| place.locate(z).unwrap().id; + assert_eq!(owner("realm.city.borough-1.hood-1"), "A"); + assert_eq!(owner("realm.city.borough-1"), "B"); + assert_eq!(owner(CITY), "A"); + assert_eq!(owner(REALM), "B"); + let one = TierPlacement::new(&hosts[..1]); + assert!(all_zones().iter().all(|z| one.locate(z).unwrap().id == "A")); + } + + #[test] + fn input_round_trips() { + let bytes = encode_input(-128, 5, 0xff); + let input = HoodInput::decode(&bytes).unwrap(); + assert_eq!(input.movement.mx, -127); + assert_eq!(input.action, ACTION_ATTACK | ACTION_SMITE); + assert_eq!(HoodInput::decode(&bytes[..3]), None); + } +} diff --git a/examples/game/server/tests/grid_fixture.rs b/examples/game/server/tests/grid_fixture.rs new file mode 100644 index 000000000..4d51d2d1a --- /dev/null +++ b/examples/game/server/tests/grid_fixture.rs @@ -0,0 +1,156 @@ +//! Golden fixture for the Endless Grid's procedural world and movement. +//! +//! Writes/compares `examples/game/fixtures/grid-world.json`, which the +//! TypeScript client replays in `client/tests/grid-world-parity.test.mjs` +//! (bit-exact). Regenerate after an intended change to BOTH +//! `server/src/grid/world.rs` and `client/src/grid/world.ts`: +//! `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. + +use std::path::PathBuf; + +use game_demos::grid::world::{self, MoveInput, BUTTON_SPRINT, DEFAULT_SEED}; +use serde_json::{json, Value}; + +const CELLS: [(i32, i32); 6] = [ + (0, 0), + (-1, 0), + (1, -1), + (3, -7), + (-12, 5), + (999_999, -1_000_000), +]; + +fn cell_json(seed: u32, cell: (i32, i32)) -> Value { + let props: Vec = world::cell_props(seed, cell) + .iter() + .map(|p| json!([p.kind as u8, p.x, p.y, p.r, p.solid, p.variant])) + .collect(); + let mut heights = Vec::new(); + let mut moisture = Vec::new(); + let mut biomes = Vec::new(); + for j in 0..=8 { + for i in 0..=8 { + let l = (i as f32 * 4.0, j as f32 * 4.0 + 0.25); + heights.push(json!(world::height(seed, cell, l))); + moisture.push(json!(world::moisture(seed, cell, l))); + biomes.push(json!(world::biome(seed, cell, l))); + } + } + json!({ "cell": [cell.0, cell.1], "props": props, "heights": heights, "moisture": moisture, "biomes": biomes }) +} + +/// The densest of a few cells, so the walk bumps into props. +fn busy_cell(seed: u32) -> (i32, i32) { + (0..12) + .map(|i| (i, 2)) + .max_by_key(|c| { + world::cell_props(seed, *c) + .iter() + .filter(|p| p.solid) + .count() + }) + .unwrap() +} + +fn walk(seed: u32) -> Value { + let cell = busy_cell(seed); + let props = world::cell_props(seed, cell); + // Head for each solid prop in turn (pushing into it), then wander off. + let (mut x, mut y) = (16.0f32, 16.0f32); + let mut steps = Vec::new(); + let targets: Vec<(f32, f32)> = props + .iter() + .filter(|p| p.solid) + .map(|p| (p.x, p.y)) + .chain([(40.0, 16.0), (16.0, -5.0)]) + .collect(); + for (k, (tx, ty)) in targets.iter().enumerate() { + for _ in 0..60 { + let (dx, dy) = (tx - x, ty - y); + let l = (dx * dx + dy * dy).sqrt().max(1e-3); + let input = MoveInput { + mx: (dx / l * 127.0) as i8, + my: if k % 3 == 0 { + -128 + } else { + (dy / l * 127.0) as i8 + }, + buttons: if k % 2 == 0 { BUTTON_SPRINT } else { 0 }, + }; + let decoded = MoveInput::decode(&input.encode()).unwrap(); + (x, y) = world::step(x, y, decoded, &props); + steps.push(json!({ "input": [input.mx, input.my, input.buttons], "x": x, "y": y })); + } + } + json!({ "cell": [cell.0, cell.1], "start": [16.0, 16.0], "steps": steps }) +} + +fn build() -> Value { + let seed = DEFAULT_SEED; + let hashes = [0u32, 1, 0xdead_beef, u32::MAX].map(world::hash32); + let mixes = [ + world::mix(seed, 3, -5, 7), + world::mix(0, 0, i32::MIN, i32::MAX), + ]; + json!({ + "description": "Endless Grid parity: Rust grid::world vs client/src/grid/world.ts", + "constants": { + "seed": seed, "contentVersion": world::CONTENT_VERSION, "cell": world::CELL, + "propMargin": world::PROP_MARGIN, "hysteresis": world::HYSTERESIS, + "playerRadius": world::PLAYER_RADIUS, "walk": world::WALK_SPEED, "sprint": world::SPRINT_SPEED, + "hashes": hashes, + "mix": mixes, + }, + "cells": CELLS.iter().map(|c| cell_json(seed, *c)).collect::>(), + "walk": walk(seed), + }) +} + +fn render(v: &Value) -> String { + let mut out = String::from("{\n"); + for key in ["description", "constants"] { + out += &format!(" \"{key}\": {},\n", v[key]); + } + out += " \"cells\": [\n"; + let cells = v["cells"].as_array().unwrap(); + for (i, cell) in cells.iter().enumerate() { + let sep = if i + 1 == cells.len() { "" } else { "," }; + out += &format!(" {cell}{sep}\n"); + } + out += &format!(" ],\n \"walk\": {}\n}}\n", v["walk"]); + out +} + +#[test] +fn grid_world_fixture_is_current() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/grid-world.json"); + let fresh = render(&build()); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + std::fs::write(&path, fresh).unwrap(); + return; + } + let stored = + std::fs::read_to_string(&path).expect("fixture exists (UPDATE_GOLDEN=1 to create)"); + assert!( + stored == fresh, + "grid world changed: update client/src/grid/world.ts too, then UPDATE_GOLDEN=1" + ); +} + +#[test] +fn biomes_and_props_vary() { + let mut biomes = [0usize; 4]; + let mut props = 0; + for cx in -10..10 { + for cy in -10..10 { + biomes[world::biome(DEFAULT_SEED, (cx, cy), (16.0, 16.0)) as usize] += 1; + props += world::cell_props(DEFAULT_SEED, (cx, cy)).len(); + } + } + eprintln!("biomes {biomes:?}, props/cell {}", props as f32 / 400.0); + assert!( + biomes.iter().all(|n| *n > 10), + "every biome appears: {biomes:?}" + ); + assert!((3..12).contains(&(props / 400)), "props per cell"); +} diff --git a/examples/game/server/tests/grid_smoke.rs b/examples/game/server/tests/grid_smoke.rs new file mode 100644 index 000000000..02e5b4f53 --- /dev/null +++ b/examples/game/server/tests/grid_smoke.rs @@ -0,0 +1,305 @@ +//! Endless Grid smoke tests: two in-process hosts (A, B) on a hash ring. +//! +//! - a walker crosses several cell borders, at least one of them between +//! hosts, following every Handoff (and Redirect) without losing its +//! session, and ends in the right zone; +//! - a cell hibernates into SQLite and restores critters and markers; +//! - dev routes: world map across hosts, names shared with peers. + +mod support; + +use std::time::Duration; + +use distributed_game::world::ZoneStateStore; +use distributed_game::{FieldValue, Role, ServerMessage}; +use game_demos::grid::world::{self, MoveInput, BUTTON_MARK, BUTTON_SPRINT}; +use game_demos::grid::{GridDemo, EVENT_HELLO, KIND_CRITTER, KIND_MARKER}; +use serde_json::{json, Value}; +use support::{eventually, http, join, start_cluster, ticket, Client}; + +fn east(buttons: u8) -> Vec { + MoveInput { + mx: 127, + my: 0, + buttons: BUTTON_SPRINT | buttons, + } + .encode() + .to_vec() +} + +fn f(fields: &[FieldValue], i: usize) -> f32 { + match fields[i] { + FieldValue::F(v) => v, + _ => f32::NAN, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn walker_crosses_borders_and_hosts_without_losing_its_session() { + let cluster = start_cluster::(&["A", "B"], Duration::from_secs(4)).await; + let world = &cluster.hosts[0].world; + // Walk east along the y = 16 trail until we crossed a host boundary. + let owner = |x: i32| world.owner(&world::zone_id((x, 0))); + let last = (1..=16) + .find(|k| (0..*k).any(|i| owner(i) != owner(i + 1)) && *k >= 2) + .expect("a cross-host border within 16 cells"); + let base = cluster.host("A").demo.ws_url(); + + // Interest across the border: an observer of the east neighbour sees its critters. + let mut observer = join( + &base, + "grid.1.0", + &ticket("guest-eye", "grid.1.0", Role::Observer), + ) + .await + .unwrap(); + let hello = observer.json_event(EVENT_HELLO).await; + assert_eq!(hello["host"], owner(1).as_str()); + assert!(hello["entity"].is_null(), "observers control nothing"); + observer + .until("critters replicated to the observer", |c| { + c.count(KIND_CRITTER) >= 2 + }) + .await; + + let mut client = join( + &base, + "grid.0.0", + &ticket("guest-walker", "grid.0.0", Role::Player), + ) + .await + .unwrap(); + let hello = client.json_event(EVENT_HELLO).await; + let name = format!("Guest {}", &"guest-walker"[6..10]); + assert_eq!(hello["cell"], json!([0, 0])); + assert!(hello["entity"].as_u64().is_some()); + + let mut zone = "grid.0.0".to_string(); + let mut handoffs = 0; + let mut cross_host = 0; + let deadline = tokio::time::Instant::now() + Duration::from_secs(45); + let target = world::zone_id((last, 0)); + loop { + assert!( + tokio::time::Instant::now() < deadline, + "walk timed out in {zone}" + ); + client.input(east(0)).await; + let mut handoff = None; + while let Some(msg) = client.next(Duration::from_millis(30)).await { + match msg { + ServerMessage::Handoff { + target_zone, + transfer_ticket, + } => { + handoff = Some((target_zone, transfer_ticket)); + break; + } + ServerMessage::Error { code, message } => panic!("error {code}: {message}"), + ServerMessage::Kick { message, .. } => panic!("kicked: {message}"), + _ => {} + } + } + if let Some((to, transfer)) = handoff { + let from_owner = world.owner(&zone); + let to_owner = world.owner(&to); + let mut next: Client = join(&base, &to, &transfer).await.expect("target admits"); + let hello = next.json_event(EVENT_HELLO).await; + assert_eq!(hello["zone"], to.as_str()); + assert_eq!(hello["host"], to_owner.as_str()); + assert_eq!( + next.redirects > 0, + to_owner != "A", + "redirected to the owner" + ); + handoffs += 1; + if from_owner != to_owner { + cross_host += 1; + } + zone = to; + client = next; + continue; + } + if zone == target { + let owner = cluster.owner(&zone); + let walkers = owner + .demo + .server + .inspect(&zone, |h| h.zone().walkers()) + .await + .unwrap(); + if walkers.first().is_some_and(|(_, x, _)| *x > 4.0) { + assert_eq!(walkers.len(), 1); + assert_eq!(walkers[0].0, name, "same walker, name carried across hosts"); + assert!((walkers[0].2 - 16.0).abs() < 0.01, "stayed on the trail"); + break; + } + } + } + assert_eq!(handoffs, last, "one handoff per border"); + assert!(cross_host >= 1, "crossed between hosts"); + for x in 0..last { + let id = world::zone_id((x, 0)); + let walkers = cluster + .owner(&id) + .demo + .server + .inspect(&id, |h| h.zone().walkers().len()) + .await; + assert!( + matches!(walkers, Some(0) | None), + "{id} released the walker" + ); + } + cluster.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn empty_cell_hibernates_and_restores_critters_and_markers() { + let cluster = start_cluster::(&["A", "B"], Duration::from_millis(300)).await; + let zone = "grid.5.5"; + let owner = cluster.owner(zone); + let base = cluster.host("A").demo.ws_url(); + + let mut client = join(&base, zone, &ticket("guest-marker", zone, Role::Player)) + .await + .unwrap(); + let hello = client.json_event(EVENT_HELLO).await; + assert_eq!(hello["restored"], false); + client.input(east(BUTTON_MARK)).await; + client + .until("marker replicated", |c| c.count(KIND_MARKER) == 1) + .await; + client.leave().await; + drop(client); + + eventually("hibernation", || { + let server = owner.demo.server.clone(); + async move { !server.is_active(zone) } + }) + .await; + let saved = owner + .world + .state + .load(zone) + .unwrap() + .expect("snapshot stored"); + let snapshot: Value = serde_json::from_slice(&saved.state).unwrap(); + assert_eq!(snapshot["markers"].as_array().unwrap().len(), 1); + let critters = snapshot["critters"].as_array().unwrap().clone(); + assert!(critters.len() >= 2); + + // The world map shows it hibernated (asked on the other host too). + let other = if owner.world.host.id == "A" { "B" } else { "A" }; + let (status, map) = http( + cluster.host(other).demo.addr, + "GET", + "/dev/grid/map?x=5&y=5&r=0", + None, + ) + .await; + assert_eq!(status, 200, "{map}"); + assert_eq!(map["cells"][0]["state"], "hibernated", "{map}"); + assert_eq!(map["cells"][0]["owner"], owner.world.host.id.as_str()); + + let mut again = join(&base, zone, &ticket("guest-marker", zone, Role::Player)) + .await + .unwrap(); + let hello = again.json_event(EVENT_HELLO).await; + assert_eq!(hello["restored"], true); + assert_eq!(hello["restores"], 1); + assert_eq!(hello["restoredMarkers"], 1); + assert_eq!(hello["restoredCritters"], critters.len()); + let n = critters.len(); + again + .until("restored entities replicated", |c| { + c.count(KIND_CRITTER) == n && c.count(KIND_MARKER) == 1 + }) + .await; + // Critters resume exactly where they slept (first delta after restore). + for c in &critters { + let id = c["id"].as_u64().unwrap() as u32; + let fields = &again.mirror.entities[&id].fields; + let (x, y) = ( + c["x"].as_f64().unwrap() as f32, + c["y"].as_f64().unwrap() as f32, + ); + assert!( + (f(fields, 0) - x).abs() < 0.2 && (f(fields, 1) - y).abs() < 0.2, + "critter {id}" + ); + } + cluster.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn dev_routes_share_names_and_map_both_hosts() { + let cluster = start_cluster::(&["A", "B"], Duration::from_secs(4)).await; + let world = &cluster.hosts[0].world; + let on_b = (0..64) + .map(|x| world::zone_id((x, 3))) + .find(|z| world.owner(z) == "B") + .unwrap(); + let a = cluster.host("A").demo.addr; + let (status, ticket) = http( + a, + "POST", + "/dev/ticket", + Some(json!({ "zone": on_b, "name": "Ana" })), + ) + .await; + assert_eq!(status, 200, "{ticket}"); + let principal = ticket["principal"].as_str().unwrap(); + assert_eq!( + cluster.host("B").demo.guests.name(principal).as_deref(), + Some("Ana") + ); + + // The ticket from A works on B (shared secret) and B greets by name. + let mut client = join( + &cluster.host("A").demo.ws_url(), + &on_b, + ticket["ticket"].as_str().unwrap(), + ) + .await + .unwrap(); + assert_eq!(client.redirects, 1); + client.json_event(EVENT_HELLO).await; + let walkers = cluster + .host("B") + .demo + .server + .inspect(&on_b, |h| h.zone().walkers()) + .await + .unwrap(); + assert_eq!(walkers[0].0, "Ana"); + + let (status, map) = http(a, "GET", "/dev/grid/map?x=0&y=3&r=2", None).await; + assert_eq!(status, 200); + let cells = map["cells"].as_array().unwrap(); + assert_eq!(cells.len(), 25); + let owners: std::collections::BTreeSet<&str> = + cells.iter().filter_map(|c| c["owner"].as_str()).collect(); + assert_eq!(owners.len(), 2, "both hosts own cells nearby: {owners:?}"); + let mine = cells.iter().find(|c| c["zone"] == on_b.as_str()); + if let Some(cell) = mine { + assert_eq!(cell["state"], "active"); + assert_eq!(cell["players"], 1); + } + assert!(map["hosts"] + .as_array() + .unwrap() + .iter() + .all(|h| h["reachable"] == true)); + + // The peer route needs the admin secret. + let (status, _) = http( + cluster.host("B").demo.addr, + "POST", + "/dev/grid/local", + Some(json!({ "zones": [] })), + ) + .await; + assert_eq!(status, 401); + cluster.stop().await; +} diff --git a/examples/game/server/tests/ripple_smoke.rs b/examples/game/server/tests/ripple_smoke.rs new file mode 100644 index 000000000..6f907c261 --- /dev/null +++ b/examples/game/server/tests/ripple_smoke.rs @@ -0,0 +1,196 @@ +//! Boss Ripple smoke test: two in-process hosts, placement alternating by +//! depth so every tier-up hop crosses hosts. Defeating bosses must cascade +//! hood → borough → city → realm with the right state at every tier. + +mod support; + +use std::time::Duration; + +use distributed_game::{FieldValue, Role, ServerMessage}; +use game_demos::ripple::{ + self, encode_input, RippleDemo, ACTION_ATTACK, ACTION_SMITE, BOROUGHS, CITY, EVENT_BANNER, + EVENT_BOSS, EVENT_HELLO, EVENT_RIPPLE, EVENT_WEATHER, REALM, +}; +use serde_json::Value; +use support::{eventually, join, start_cluster, ticket, Client}; + +/// Field `i` of the tier entity (id 1) as u32. +fn tier_field(client: &Client, i: usize) -> u32 { + match client.mirror.entities.get(&1).map(|e| &e.fields[i]) { + Some(FieldValue::U(v)) => *v, + Some(FieldValue::Bool(b)) => u32::from(*b), + _ => u32::MAX, + } +} + +async fn observe(base: &str, zone: &str) -> Client { + let mut c = join(base, zone, &ticket("guest-watch", zone, Role::Observer)) + .await + .unwrap(); + let hello = c.json_event(EVENT_HELLO).await; + assert_eq!(hello["zone"], zone); + c.until("tier entity", |c| c.mirror.entities.contains_key(&1)) + .await; + c +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn boss_defeats_ripple_up_every_tier_across_hosts() { + let cluster = start_cluster::(&["A", "B"], Duration::from_secs(20)).await; + let world = &cluster.hosts[0].world; + assert_eq!(world.owner("realm.city.borough-1.hood-1"), "A"); + assert_eq!(world.owner(BOROUGHS[0]), "B"); + assert_eq!(world.owner(CITY), "A"); + assert_eq!(world.owner(REALM), "B"); + let base = cluster.host("A").demo.ws_url(); + + let mut realm = observe(&base, REALM).await; + let mut city = observe(&base, CITY).await; + let mut borough = observe(&base, BOROUGHS[0]).await; + assert_eq!(realm.redirects, 1, "realm lives on B"); + assert_eq!(realm.welcome.tick_rate, 2, "slow realm clock"); + assert_eq!(city.welcome.tick_rate, 5); + assert_eq!(borough.welcome.tick_rate, 10); + // Upper tiers are observed, never joined. + let refused = join(&base, CITY, &ticket("guest-x", CITY, Role::Player)).await; + assert!(matches!(refused, Err(ServerMessage::Error { .. }))); + + // Fight the first boss by hand: walk to it and attack. + let hood1 = "realm.city.borough-1.hood-1"; + let mut fighter = join(&base, hood1, &ticket("guest-fighter", hood1, Role::Player)) + .await + .unwrap(); + assert_eq!(fighter.welcome.tick_rate, 30, "hot neighborhood"); + let hello = fighter.json_event(EVENT_HELLO).await; + assert_eq!(hello["tier"], "hood"); + assert!(hello["entity"].as_u64().is_some()); + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + let mut defeated = None; + while defeated.is_none() { + assert!(tokio::time::Instant::now() < deadline, "boss not defeated"); + // Steer toward the boss at the center, attacking once in reach. + let me = hello["entity"].as_u64().unwrap() as u32; + let (x, y) = match fighter + .mirror + .entities + .get(&me) + .map(|e| (&e.fields[0], &e.fields[1])) + { + Some((FieldValue::F(x), FieldValue::F(y))) => (*x, *y), + _ => (0.0, 0.0), + }; + let d = (x * x + y * y).sqrt().max(1e-3); + let k = if d > 3.5 { 127.0 / d } else { 0.0 }; + fighter + .input(encode_input((-x * k) as i8, (-y * k) as i8, ACTION_ATTACK)) + .await; + while let Some(msg) = fighter.next(Duration::from_millis(33)).await { + if let ServerMessage::Event { type_id, payload } = msg { + if type_id == EVENT_BOSS { + defeated = Some(serde_json::from_slice::(&payload).unwrap()); + } + } + } + } + assert_eq!(defeated.unwrap()["kind"], "defeated"); + + // The rest of borough-1 by smiting. + for hood in &ripple::hoods(BOROUGHS[0])[1..] { + let mut c = join(&base, hood, &ticket("guest-smiter", hood, Role::Player)) + .await + .unwrap(); + c.json_event(EVENT_HELLO).await; + c.input(encode_input(0, 0, ACTION_SMITE)).await; + assert_eq!(c.json_event(EVENT_BOSS).await["kind"], "defeated"); + let state = cluster + .host("A") + .demo + .server + .inspect(hood, |h| h.zone().state().hp) + .await; + assert_eq!(state, Some(0)); + } + borough + .until("borough tallied all three", |c| { + tier_field(c, 0) == 3 && tier_field(c, 2) == 1 + }) + .await; + let ripples = borough.seen(EVENT_RIPPLE); + city.until("city saw the borough cleared", |c| { + tier_field(c, 2) == 1 && tier_field(c, 0) == 3 + }) + .await; + assert_eq!(tier_field(&city, 4), 1, "weather: rain with 3 bosses left"); + realm + .until("realm counted", |c| { + tier_field(c, 0) == 3 && tier_field(c, 2) == 1 + }) + .await; + assert_eq!(tier_field(&realm, 3), 0, "city not liberated yet"); + + // Borough-2 falls too: the city is liberated and the realm says so. + for hood in ripple::hoods(BOROUGHS[1]) { + let mut c = join(&base, &hood, &ticket("guest-smiter", &hood, Role::Player)) + .await + .unwrap(); + c.json_event(EVENT_HELLO).await; + c.input(encode_input(0, 0, ACTION_SMITE)).await; + c.json_event(EVENT_BOSS).await; + } + let banner = realm.json_event(EVENT_BANNER).await; + assert!( + banner["text"].as_str().unwrap().contains("liberated"), + "{banner}" + ); + realm + .until("realm state", |c| { + tier_field(c, 0) == 6 && tier_field(c, 2) == 2 && tier_field(c, 3) == 1 + }) + .await; + city.until("city liberated", |c| { + tier_field(c, 3) == 1 && tier_field(c, 4) == 3 + }) + .await; + let weather: Vec = city + .seen(EVENT_WEATHER) + .iter() + .map(|w| w["weather"].as_str().unwrap().to_string()) + .collect(); + assert_eq!( + weather.last().map(String::as_str), + Some("clear"), + "{weather:?}" + ); + assert!(weather.iter().any(|w| w == "rain"), "{weather:?}"); + + // Borough-1's ripple events name each hood as origin and the borough as receiver. + let origins: std::collections::BTreeSet = ripples + .iter() + .filter(|r| r["kind"] == "boss_defeated") + .map(|r| r["origin"].as_str().unwrap().to_string()) + .collect(); + assert!(origins.len() >= 2, "{ripples:?}"); + assert!(ripples.iter().all(|r| r["at"] == BOROUGHS[0])); + + // The cascade's state lives where each tier runs. + let city_state = cluster + .host("A") + .demo + .server + .inspect(CITY, |h| h.zone().state().clone()) + .await + .unwrap(); + assert!(city_state.liberated); + assert_eq!(city_state.cleared.len(), 2); + eventually("realm state on B", || { + let server = cluster.host("B").demo.server.clone(); + async move { + server + .inspect(REALM, |h| h.zone().state().liberations) + .await + == Some(1) + } + }) + .await; + cluster.stop().await; +} diff --git a/examples/game/server/tests/support/mod.rs b/examples/game/server/tests/support/mod.rs new file mode 100644 index 000000000..222aa2232 --- /dev/null +++ b/examples/game/server/tests/support/mod.rs @@ -0,0 +1,304 @@ +//! Shared helpers for the multi-host smoke tests: start N in-process hosts +//! of a cluster demo on ephemeral ports and a minimal protocol client that +//! follows Redirects. +#![allow(dead_code)] + +use std::net::SocketAddr; +use std::time::Duration; + +use distributed_game::net::TicketKey; +use distributed_game::protocol::{Hello, Welcome}; +use distributed_game::world::HostAddr; +use distributed_game::{ + ClientMessage, ClientMirror, Role, ServerMessage, TicketClaims, PROTOCOL_VERSION, +}; +use futures_util::{SinkExt, StreamExt}; +use game_demos::cluster::{spawn_cluster, ClusterDemo, ClusterOptions, RunningHost}; +use game_demos::common::DemoOptions; +use serde_json::Value; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +pub const SECRET: &str = "cluster-smoke-secret"; + +pub type Ws = WebSocketStream>; + +pub struct Cluster { + pub hosts: Vec>, + stops: Vec>, + pub state_dir: std::path::PathBuf, +} + +impl Cluster { + /// Host by id. + pub fn host(&self, id: &str) -> &RunningHost { + self.hosts + .iter() + .find(|h| h.world.host.id == id) + .expect("host") + } + + /// The host owning `zone`. + pub fn owner(&self, zone: &str) -> &RunningHost { + self.host(&self.hosts[0].world.owner(zone)) + } + + pub async fn stop(self) { + for stop in self.stops { + let _ = stop.send(()); + } + for host in self.hosts { + let _ = host.demo.task.await; + } + let _ = std::fs::remove_dir_all(&self.state_dir); + } +} + +/// Start hosts `ids` (all peers of each other) on 127.0.0.1:0. +pub async fn start_cluster(ids: &[&str], hibernate_after: Duration) -> Cluster { + let mut listeners = Vec::new(); + for id in ids { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + listeners.push((id.to_string(), addr, listener)); + } + let all: Vec = listeners + .iter() + .map(|(id, addr, _)| HostAddr::new(id.clone(), addr.to_string())) + .collect(); + let state_dir = std::env::temp_dir().join(format!( + "game-demos-{}-{}-{}", + D::NAME, + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut hosts = Vec::new(); + let mut stops = Vec::new(); + for (id, _, listener) in listeners { + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let options = ClusterOptions { + host_id: id, + peers: all.clone(), + state_dir: Some(state_dir.clone()), + hibernate_after, + }; + let host = spawn_cluster::(listener, DemoOptions::dev(SECRET), options, async move { + let _ = stopped.await; + }) + .unwrap(); + hosts.push(host); + stops.push(stop); + } + Cluster { + hosts, + stops, + state_dir, + } +} + +pub fn ticket(principal: &str, zone: &str, role: Role) -> String { + static NONCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NONCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TicketKey::new(SECRET).sign(&TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: format!("n-{principal}-{n}"), + role, + }) +} + +/// A connected protocol client. +pub struct Client { + pub ws: Ws, + pub mirror: ClientMirror, + pub welcome: Welcome, + /// URL that finally accepted the Hello. + pub url: String, + /// Redirects followed to get there. + pub redirects: u32, + pub seq: u32, + /// Messages received after Welcome but not yet consumed. + pub backlog: Vec, + /// Every game Event received (type id, payload), in order. + pub events: Vec<(u32, Vec)>, +} + +async fn hello(ws: &mut Ws, ticket: &str) { + let msg = ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: String::new(), + capabilities: 0, + ticket: ticket.to_string(), + reconnect_token: String::new(), + }); + ws.send(Message::Binary(msg.encode().into())).await.unwrap(); +} + +/// Next decoded server message, None on close / timeout. +pub async fn next(ws: &mut Ws, mirror: &mut ClientMirror, wait: Duration) -> Option { + loop { + let frame = tokio::time::timeout(wait, ws.next()).await.ok()??; + match frame { + Ok(Message::Binary(bytes)) => return Some(mirror.apply(&bytes).unwrap()), + Ok(Message::Close(_)) | Err(_) => return None, + Ok(_) => continue, + } + } +} + +/// Connect to `base/zones/zone`, following Redirects, until Welcome. +#[allow(clippy::result_large_err)] +pub async fn join(base: &str, zone: &str, ticket: &str) -> Result { + let mut url = format!("{base}/zones/{zone}"); + let mut redirects = 0; + for _ in 0..4 { + let (mut ws, _) = connect_async(&url).await.unwrap(); + hello(&mut ws, ticket).await; + let mut mirror = ClientMirror::new(); + loop { + match next(&mut ws, &mut mirror, Duration::from_secs(5)) + .await + .expect("reply to Hello") + { + ServerMessage::Welcome(welcome) => { + return Ok(Client { + ws, + mirror, + welcome, + url, + redirects, + seq: 0, + backlog: Vec::new(), + events: Vec::new(), + }) + } + ServerMessage::Redirect { url: to, .. } => { + url = to; + redirects += 1; + break; + } + ServerMessage::Pong { .. } => continue, + other => return Err(other), + } + } + } + panic!("redirect loop") +} + +impl Client { + pub async fn input(&mut self, payload: Vec) { + self.seq += 1; + let msg = ClientMessage::Input { + seq: self.seq, + client_tick: 0, + payload, + }; + self.ws + .send(Message::Binary(msg.encode().into())) + .await + .unwrap(); + } + + pub async fn leave(&mut self) { + let _ = self + .ws + .send(Message::Binary(ClientMessage::Leave.encode().into())) + .await; + } + + /// Next message (backlog first). + pub async fn next(&mut self, wait: Duration) -> Option { + if !self.backlog.is_empty() { + return Some(self.backlog.remove(0)); + } + let msg = next(&mut self.ws, &mut self.mirror, wait).await; + if let Some(ServerMessage::Event { type_id, payload }) = &msg { + self.events.push((*type_id, payload.clone())); + } + msg + } + + /// JSON events of `type_id` received so far. + pub fn seen(&self, type_id: u32) -> Vec { + self.events + .iter() + .filter(|(t, _)| *t == type_id) + .filter_map(|(_, p)| serde_json::from_slice(p).ok()) + .collect() + } + + /// Wait for the first JSON event of `type_id`. + pub async fn json_event(&mut self, type_id: u32) -> Value { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + match self.next(left).await.expect("event within 5 s") { + ServerMessage::Event { + type_id: t, + payload, + } if t == type_id => return serde_json::from_slice(&payload).unwrap(), + _ => continue, + } + } + } + + /// Read messages until `pred` holds (10 s). + pub async fn until(&mut self, what: &str, pred: impl Fn(&Client) -> bool) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while !pred(self) { + assert!(tokio::time::Instant::now() < deadline, "timed out: {what}"); + if let Some(ServerMessage::Error { code, message }) = + self.next(Duration::from_millis(100)).await + { + panic!("{what}: error {code}: {message}"); + } + } + } + + /// Entities of `kind` currently mirrored. + pub fn count(&self, kind: u16) -> usize { + self.mirror + .entities + .values() + .filter(|e| e.kind == kind) + .count() + } +} + +/// Minimal HTTP/1.1 client: `(status, JSON body or Null)`. +pub async fn http(addr: SocketAddr, method: &str, path: &str, body: Option) -> (u16, Value) { + let mut stream = TcpStream::connect(addr).await.unwrap(); + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + let status = response[9..12].parse().unwrap(); + let json = response + .split_once("\r\n\r\n") + .and_then(|(_, b)| serde_json::from_str(b).ok()) + .unwrap_or(Value::Null); + (status, json) +} + +/// Poll `check` until true (10 s). +pub async fn eventually(what: &str, mut check: F) +where + F: FnMut() -> Fut, + Fut: std::future::Future, +{ + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while !check().await { + assert!(tokio::time::Instant::now() < deadline, "timed out: {what}"); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} From 8ad5d8faffaab152abe0cc55e400838cbfd5d881 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:47:39 -0500 Subject: [PATCH 147/484] feat(examples): let game demos build server and dev routes together common::spawn_with / run_with take a builder returning the GameServer plus demo-specific dev routes, so a demo can share state (a durable store, a leaderboard) between its zones and its routes. spawn/run delegate to them unchanged; random_hex is re-exported. Refs [[tasks/gr-p10-demos]] --- examples/game/server/src/common/mod.rs | 36 +++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/examples/game/server/src/common/mod.rs b/examples/game/server/src/common/mod.rs index 02b779124..9b7180b57 100644 --- a/examples/game/server/src/common/mod.rs +++ b/examples/game/server/src/common/mod.rs @@ -16,7 +16,7 @@ use axum::Router; use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; use distributed_game::{Ctx, Viewer, Zone}; -pub use guests::Guests; +pub use guests::{random_hex, Guests}; /// One playable demo hosted by `game-demos `. pub trait Demo: 'static { @@ -114,15 +114,32 @@ pub fn spawn( listener: tokio::net::TcpListener, options: DemoOptions, signal: impl Future + Send + 'static, +) -> std::io::Result> { + spawn_with::( + listener, + options, + |config, guests| (D::server(config, guests), Router::new()), + signal, + ) +} + +/// Like [`spawn`], but `build` makes the server and the demo's own dev +/// routes (merged next to `/dev/ticket`, only with `--dev`). For demos whose +/// zones and routes share state (e.g. a durable store) built by the caller. +pub fn spawn_with( + listener: tokio::net::TcpListener, + options: DemoOptions, + build: impl FnOnce(ServerConfig, Guests) -> (GameServer, Router), + signal: impl Future + Send + 'static, ) -> std::io::Result> { let addr = listener.local_addr()?; let guests = Guests::default(); - let server = D::server( + let (server, demo_routes) = build( server_config(options.key.clone(), options.net_sim), guests.clone(), ); let extra = if options.dev { - dev::routes::(server.clone(), options.key, guests.clone()) + dev::routes::(server.clone(), options.key, guests.clone()).merge(demo_routes) } else { Router::new() }; @@ -137,6 +154,17 @@ pub fn spawn( /// CLI entry: bind, print the address, serve until Ctrl-C / SIGTERM. pub async fn run(args: DemoArgs) -> std::io::Result<()> { + run_with::(args, |config, guests| { + (D::server(config, guests), Router::new()) + }) + .await +} + +/// [`run`] with a caller-built server and dev routes (see [`spawn_with`]). +pub async fn run_with( + args: DemoArgs, + build: impl FnOnce(ServerConfig, Guests) -> (GameServer, Router), +) -> std::io::Result<()> { let listener = tokio::net::TcpListener::bind((args.host.as_str(), args.port)).await?; let secret = args.secret.unwrap_or_else(|| guests::random_hex(32)); let options = DemoOptions { @@ -144,7 +172,7 @@ pub async fn run(args: DemoArgs) -> std::io::Result<()> { dev: args.dev, net_sim: NetSim::from_env(), }; - let running = spawn::(listener, options, shutdown_signal())?; + let running = spawn_with::(listener, options, build, shutdown_signal())?; // Parsed by run.sh and the client tests: keep the format. println!("LISTENING http://{}", running.addr); println!( From 5e6ba51e11ff4e7b549e932f0a9142abd9c84883 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:47:40 -0500 Subject: [PATCH 148/484] feat(examples): add Mob Pit and Leaderboard demo servers Mob Pit: 30 Hz melee zone with 12 telegraphing mobs. Kills emit non-blocking facts committed into per-player Crawler aggregates in native SQLite cells (cell-sqlite) via CellFactSink; XP is decided by the cell from the mob tier, the principal comes from the verified ticket. A dev "slow storage" knob delays commits; the tick stays flat. The ticket secret persists in the data dir for crash-recovery runs. Leaderboard: kills/XP boards (in-memory or Redis) fed fire-and-forget through BackgroundLeaderboard with deterministic occurrence ids, so live updates, ledger replays and rebuilds from cell event history never double count. Top 10 is pushed as a zone event. Smoke tests cover exactly-once commits, slow storage, kill -9 restart on the same data dir with replay of a pre-crash fact key, and boards matching the cells. Refs [[tasks/gr-p10-demos]] --- examples/game/server/Cargo.lock | 817 +++++++++++++++++ examples/game/server/Cargo.toml | 9 +- examples/game/server/src/lib.rs | 1 + examples/game/server/src/main.rs | 6 + examples/game/server/src/mobpit/board.rs | 414 +++++++++ examples/game/server/src/mobpit/crawler.rs | 220 +++++ examples/game/server/src/mobpit/mod.rs | 144 +++ examples/game/server/src/mobpit/routes.rs | 104 +++ examples/game/server/src/mobpit/store.rs | 310 +++++++ examples/game/server/src/mobpit/world.rs | 181 ++++ examples/game/server/src/mobpit/zone.rs | 967 +++++++++++++++++++++ examples/game/server/tests/mobpit_smoke.rs | 544 ++++++++++++ 12 files changed, 3714 insertions(+), 3 deletions(-) create mode 100644 examples/game/server/src/mobpit/board.rs create mode 100644 examples/game/server/src/mobpit/crawler.rs create mode 100644 examples/game/server/src/mobpit/mod.rs create mode 100644 examples/game/server/src/mobpit/routes.rs create mode 100644 examples/game/server/src/mobpit/store.rs create mode 100644 examples/game/server/src/mobpit/world.rs create mode 100644 examples/game/server/src/mobpit/zone.rs create mode 100644 examples/game/server/tests/mobpit_smoke.rs diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index 22830fbd1..505178b4d 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -52,6 +52,49 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arcstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -67,6 +110,7 @@ dependencies = [ "axum-core", "base64 0.22.1", "bytes", + "form_urlencoded", "futures-util", "http", "http-body", @@ -82,6 +126,7 @@ dependencies = [ "serde_core", "serde_json", "serde_path_to_error", + "serde_urlencoded", "sha1 0.10.7", "sync_wrapper", "tokio", @@ -109,6 +154,15 @@ dependencies = [ "tower-service", ] +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", +] + [[package]] name = "base64" version = "0.22.1" @@ -121,6 +175,36 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitcode" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6ed1b54d8dc333e7be604d00fa9262f4635485ffea923647b6521a5fff045d" +dependencies = [ + "arrayvec", + "bitcode_derive", + "bytemuck", + "glam", + "serde", +] + +[[package]] +name = "bitcode_derive" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238b90427dfad9da4a9abd60f3ec1cdee6b80454bde49ed37f1781dd8e9dc7f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.10.4" @@ -139,12 +223,34 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -208,6 +314,20 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + [[package]] name = "const-oid" version = "0.10.2" @@ -279,12 +399,44 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "distributed" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64 0.23.1", + "bitcode", + "distributed_macros", + "futures-util", + "js-sys", + "redis", + "rusqlite", + "serde", + "serde_json", + "sha2", + "tokio", + "tonic-build", + "uuid", +] + [[package]] name = "distributed_game" version = "0.1.0" dependencies = [ "axum", "base64 0.23.1", + "distributed", "futures-util", "hmac", "serde_json", @@ -293,6 +445,23 @@ dependencies = [ "tokio-tungstenite 0.30.0", ] +[[package]] +name = "distributed_macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "sha2", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -303,6 +472,74 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -340,6 +577,7 @@ version = "0.1.0" dependencies = [ "axum", "clap", + "distributed", "distributed_game", "http-body-util", "serde", @@ -382,6 +620,36 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "glam" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc148d4ddd3930c52f9e5ae79b89805c6f07e9ff417e7b083e0348cea60a5aba" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown 0.16.1", +] + [[package]] name = "heck" version = "0.5.0" @@ -485,6 +753,120 @@ dependencies = [ "tower-service", ] +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -497,12 +879,40 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libsqlite3-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "log" version = "0.4.34" @@ -538,12 +948,24 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -556,6 +978,21 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -565,6 +1002,25 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -641,6 +1097,70 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "redis" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5b98ae99461e02895c3a96a25dbe4d852a3d5e5b815d31d5d9e4b5344d99e9" +dependencies = [ + "arc-swap", + "arcstr", + "async-lock", + "backon", + "bytes", + "cfg-if", + "combine", + "futures-channel", + "futures-util", + "itoa", + "percent-encoding", + "pin-project-lite", + "ryu", + "sha1_smol", + "socket2", + "tokio", + "tokio-util", + "url", + "xxhash-rust", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "serde" version = "1.0.229" @@ -695,6 +1215,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -717,6 +1249,12 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.9" @@ -728,6 +1266,12 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -760,6 +1304,24 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" @@ -800,6 +1362,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -820,6 +1393,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tokio" version = "1.53.3" @@ -871,6 +1454,62 @@ dependencies = [ "tungstenite 0.30.0", ] +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tower" version = "0.5.3" @@ -942,12 +1581,47 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -969,6 +1643,51 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -984,12 +1703,56 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -1010,6 +1773,60 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index 9d745c0d9..d751e9a29 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -20,14 +20,17 @@ name = "game-demos" path = "src/main.rs" [dependencies] -distributed_game = { path = "../../../distributed_game", features = ["net"] } -axum = { version = "0.8", default-features = false, features = ["json", "tokio", "http1"] } +distributed_game = { path = "../../../distributed_game", features = ["net", "cell"] } +# Mob Pit: native durable SQLite cells + sorted-set leaderboards (Redis optional at runtime). +distributed = { path = "../../..", features = ["cell-sqlite", "redis"] } +axum = { version = "0.8", default-features = false, features = ["json", "query", "tokio", "http1"] } clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "time", "sync"] } [dev-dependencies] -distributed_game = { path = "../../../distributed_game", features = ["net", "bots"] } +distributed_game = { path = "../../../distributed_game", features = ["net", "cell", "bots"] } +tokio = { version = "1", features = ["process", "io-util"] } tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index 7bfa7546f..c1598688a 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -8,3 +8,4 @@ pub mod arena; pub mod common; +pub mod mobpit; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs index 7fde2d462..56ff642c6 100644 --- a/examples/game/server/src/main.rs +++ b/examples/game/server/src/main.rs @@ -3,6 +3,7 @@ use clap::{Parser, Subcommand}; use game_demos::arena::ArenaDemo; use game_demos::common::{run, DemoArgs}; +use game_demos::mobpit::{self, MobPitArgs}; #[derive(Parser)] #[command( @@ -18,11 +19,16 @@ struct Cli { enum DemoCommand { /// Prediction, reconciliation, interpolation and interest management. Arena(DemoArgs), + /// Non-blocking durable facts, crash recovery, authoritative combat. + Mobpit(MobPitArgs), + /// Kills/XP leaderboards (same server as `mobpit`). + Leaderboard(MobPitArgs), } #[tokio::main] async fn main() -> std::io::Result<()> { match Cli::parse().demo { DemoCommand::Arena(args) => run::(args).await, + DemoCommand::Mobpit(args) | DemoCommand::Leaderboard(args) => mobpit::run(args).await, } } diff --git a/examples/game/server/src/mobpit/board.rs b/examples/game/server/src/mobpit/board.rs new file mode 100644 index 000000000..d57442a2b --- /dev/null +++ b/examples/game/server/src/mobpit/board.rs @@ -0,0 +1,414 @@ +//! **Leaderboard**: kills and XP boards projected from the Crawler cells. +//! +//! - Store: `InMemoryLeaderboard`, or `RedisLeaderboard` when `REDIS_URL` +//! is set (sorted sets; every idempotent write is one Lua script). +//! - Live path (fire-and-forget): after a kill commits, the fact sink calls +//! [`Leaderboards::submit_kill`], which enqueues one occurrence on a +//! `BackgroundLeaderboard` and returns immediately. A full queue or a Redis +//! outage drops the update (counted); a rebuild heals it. +//! - Idempotency: every kill becomes a `DomainEventOccurrence` whose id is +//! derived from `(producer, "Crawler:{principal}", event sequence, +//! "mob_killed")` — the same id whether it comes from the live receipt, a +//! ledger replay of the same fact, or the cell's event history. The +//! projector's apply keys (`"{id}#{change}"`) make every repeat a no-op. +//! - Rebuild ([`Leaderboards::rebuild`]): read every cell's durable event +//! history, project it into the *staging* boards and atomically promote +//! them. Runs at startup too (the in-memory board starts empty). + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, UNIX_EPOCH}; + +use distributed::leaderboard::{ + BackgroundLeaderboard, BackgroundLeaderboardOptions, Board, InMemoryLeaderboard, + LeaderboardChange, LeaderboardEntry, LeaderboardError, LeaderboardProjection, + LeaderboardProjector, LeaderboardStore, RedisLeaderboard, ScorePolicy, ScoreSubmission, +}; +use distributed::{DomainEventOccurrence, ExternalEventSource}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::crawler::{KillReceipt, MobKilledArgs, AGGREGATE_TYPE, MOB_KILLED_EVENT}; +use super::store::CrawlerCells; + +/// Kills board. +pub const KILLS_BOARD: &str = "mobpit.kills"; +/// XP board. +pub const XP_BOARD: &str = "mobpit.xp"; +/// Producer of kill occurrences. +pub const PRODUCER: &str = "mobpit.crawler-cell"; +/// Rows pushed to clients. +pub const TOP_N: usize = 10; + +/// Leaderboard projection input: one committed kill. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] +#[domain_event(name = "mobpit.mob_killed", version = 1)] +pub struct MobKilled { + /// Principal credited. + pub crawler: String, + /// Mob instance. + pub mob: String, + /// Mob tier. + pub tier: u8, + /// XP credited. + pub xp: u32, +} + +/// The occurrence of the kill recorded at `sequence` in `principal`'s cell. +/// Deterministic: same inputs → same id → deduplicated by the projector. +pub fn kill_occurrence( + principal: &str, + sequence: u64, + at_ms: u64, + body: &MobKilled, +) -> Result { + DomainEventOccurrence::capture_external( + ExternalEventSource { + producer: PRODUCER.into(), + stream: format!("{AGGREGATE_TYPE}:{principal}"), + position: sequence, + key: "mob_killed".into(), + }, + UNIX_EPOCH + Duration::from_millis(at_ms), + Default::default(), + body, + ) + .map_err(|e| format!("capture kill occurrence: {e:?}")) +} + +/// kills += 1, xp += xp. +pub struct KillProjection { + kills: Board, + xp: Board, +} + +impl KillProjection { + fn new() -> Self { + Self { + kills: Board::high_first(KILLS_BOARD).expect("board name"), + xp: Board::high_first(XP_BOARD).expect("board name"), + } + } +} + +impl LeaderboardProjection for KillProjection { + fn handles(&self, event_name: &str) -> bool { + event_name == ::DESCRIPTOR.name + } + + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError> { + let kill: MobKilled = event + .decode_body() + .map_err(|e| LeaderboardError::invalid(format!("mob_killed body: {e:?}")))?; + Ok(vec![ + LeaderboardChange::new( + self.kills.clone(), + ScoreSubmission::new(&kill.crawler, 1.0, ScorePolicy::Increment), + ), + LeaderboardChange::new( + self.xp.clone(), + ScoreSubmission::new(&kill.crawler, f64::from(kill.xp), ScorePolicy::Increment), + ), + ]) + } +} + +type Projector = LeaderboardProjector; + +/// Leaderboard service shared by the zone, the fact sink and the routes. +pub struct Leaderboards { + store: Arc, + projector: Projector, + background: BackgroundLeaderboard, + backend: &'static str, + kills: Board, + xp: Board, + names: Mutex>, + snapshot: Mutex>, + version: AtomicU64, + dirty: AtomicBool, + last_rebuild: Mutex>, + rebuilding: tokio::sync::Mutex<()>, +} + +impl Leaderboards { + /// Redis when `redis_url` is given, else in memory. Must run inside a + /// Tokio runtime (spawns the background applier and the refresher). + pub fn open(redis_url: Option<&str>, redis_prefix: &str) -> Result, String> { + let (store, backend): (Arc, _) = match redis_url { + Some(url) => ( + Arc::new( + RedisLeaderboard::connect(url) + .map_err(|e| e.to_string())? + .with_prefix(redis_prefix), + ), + "redis", + ), + None => (Arc::new(InMemoryLeaderboard::new()), "memory"), + }; + let projection = Arc::new(KillProjection::new()); + let projector: Projector = LeaderboardProjector::new(store.clone(), projection); + let background = BackgroundLeaderboard::spawn( + projector.clone(), + BackgroundLeaderboardOptions::default(), + ); + let boards = Arc::new(Self { + store, + projector, + background, + backend, + kills: Board::high_first(KILLS_BOARD).expect("board name"), + xp: Board::high_first(XP_BOARD).expect("board name"), + names: Mutex::new(HashMap::new()), + snapshot: Mutex::new(Arc::new(json!({ "version": 0, "kills": [], "xp": [] }))), + version: AtomicU64::new(0), + dirty: AtomicBool::new(true), + last_rebuild: Mutex::new(None), + rebuilding: tokio::sync::Mutex::new(()), + }); + tokio::spawn(refresh_loop(Arc::downgrade(&boards))); + Ok(boards) + } + + /// `"memory"` or `"redis"`. + pub fn backend(&self) -> &'static str { + self.backend + } + + /// The store (tests read scores directly). + pub fn store(&self) -> &Arc { + &self.store + } + + /// The live projector (tests replay occurrences through it). + pub fn projector(&self) -> &Projector { + &self.projector + } + + /// Board handles `(kills, xp)`. + pub fn boards(&self) -> (&Board, &Board) { + (&self.kills, &self.xp) + } + + /// Fire-and-forget live update for a committed (or replayed) kill. + pub fn submit_kill(&self, kill: &KillReceipt) { + self.remember_name(&kill.crawler, &kill.name); + match kill_occurrence( + &kill.crawler, + kill.sequence, + kill.at_ms, + &MobKilled { + crawler: kill.crawler.clone(), + mob: kill.mob.clone(), + tier: kill.tier, + xp: kill.xp, + }, + ) { + Ok(occurrence) => { + self.background.submit(occurrence); + } + Err(error) => eprintln!("mobpit: leaderboard update skipped: {error}"), + } + } + + fn remember_name(&self, principal: &str, name: &str) { + if !name.is_empty() { + self.names + .lock() + .expect("names") + .insert(principal.to_string(), name.to_string()); + } + } + + fn name_of(&self, principal: &str) -> String { + self.names + .lock() + .expect("names") + .get(principal) + .cloned() + .unwrap_or_else(|| principal.to_string()) + } + + /// Version of the pushed snapshot (bumps when it changes). + pub fn version(&self) -> u64 { + self.version.load(Ordering::Acquire) + } + + /// Latest top-N snapshot (JSON pushed as `EVENT_BOARD`). + pub fn snapshot(&self) -> Arc { + self.snapshot.lock().expect("snapshot").clone() + } + + /// Force a snapshot refresh on the next refresher pass. + pub fn mark_dirty(&self) { + self.dirty.store(true, Ordering::Release); + } + + fn rows(&self, entries: Vec) -> Value { + Value::Array( + entries + .into_iter() + .map(|e| { + json!({ + "rank": e.rank + 1, + "member": e.member, + "name": self.name_of(&e.member), + "score": e.score, + }) + }) + .collect(), + ) + } + + async fn top_rows(&self) -> Result<(Value, Value, u64), LeaderboardError> { + let kills = self.store.top(&self.kills, TOP_N).await?; + let xp = self.store.top(&self.xp, TOP_N).await?; + let members = self.store.len(&self.kills).await?; + Ok((self.rows(kills), self.rows(xp), members)) + } + + async fn refresh(&self) -> Result<(), LeaderboardError> { + let (kills, xp, members) = self.top_rows().await?; + let stats = self.background.stats(); + let mut body = json!({ + "backend": self.backend, + "members": members, + "kills": kills, + "xp": xp, + "background": { + "enqueued": stats.enqueued, + "applied": stats.applied, + "dropped": stats.dropped, + "failed": stats.failed, + }, + "lastRebuild": *self.last_rebuild.lock().expect("rebuild"), + }); + let mut snapshot = self.snapshot.lock().expect("snapshot"); + let mut current = (**snapshot).clone(); + if let Some(map) = current.as_object_mut() { + map.remove("version"); + } + if current != body { + let version = self.version.load(Ordering::Acquire) + 1; + body["version"] = json!(version); + *snapshot = Arc::new(body); + self.version.store(version, Ordering::Release); + } + Ok(()) + } + + /// Rank, score and neighbours of `member` on both boards. + pub async fn around(&self, member: &str, radius: usize) -> Result { + let mut out = serde_json::Map::new(); + for (key, board) in [("kills", &self.kills), ("xp", &self.xp)] { + let rank = self.store.rank(board, member).await?; + let score = self.store.score(board, member).await?; + let around = self.store.around(board, member, radius).await?; + out.insert( + key.into(), + json!({ "rank": rank.map(|r| r + 1), "score": score, "around": self.rows(around) }), + ); + } + Ok(Value::Object(out)) + } + + /// Score of `member` on (kills, xp). + pub async fn scores(&self, member: &str) -> Result<(f64, f64), LeaderboardError> { + Ok(( + self.store.score(&self.kills, member).await?.unwrap_or(0.0), + self.store.score(&self.xp, member).await?.unwrap_or(0.0), + )) + } + + /// Rebuild both boards from every cell's durable event history and check + /// the result against the cells' current state. + pub async fn rebuild(&self, cells: &CrawlerCells) -> Result { + let _one_at_a_time = self.rebuilding.lock().await; + let started = Instant::now(); + let before = self.top_rows().await.map_err(|e| e.to_string())?; + let mut occurrences = Vec::new(); + let mut expected: BTreeMap = BTreeMap::new(); + let principals = cells.principals(); + for principal in &principals { + let cell = cells.get(principal).map_err(|e| e.to_string())?; + for record in cell.history().await.map_err(|e| e.to_string())? { + if record.event_name != MOB_KILLED_EVENT { + continue; + } + let (crawler, name, mob, tier, xp): MobKilledArgs = + record.decode().map_err(|e| e.to_string())?; + self.remember_name(&crawler, &name); + let at_ms = record + .timestamp + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + occurrences.push(kill_occurrence( + principal, + record.sequence, + at_ms, + &MobKilled { + crawler, + mob, + tier, + xp, + }, + )?); + } + if let Some(state) = cell.load().await.map_err(|e| e.to_string())? { + expected.insert(principal.clone(), (state.kills, state.xp)); + } + } + let report = self + .projector + .rebuild(&[self.kills.clone(), self.xp.clone()], &occurrences) + .await + .map_err(|e| e.to_string())?; + let after = self.top_rows().await.map_err(|e| e.to_string())?; + let mut mismatches = Vec::new(); + for (principal, (kills, xp)) in &expected { + let (k, x) = self.scores(principal).await.map_err(|e| e.to_string())?; + if k != f64::from(*kills) || x != *xp as f64 { + mismatches.push(json!({ + "member": principal, "cell": { "kills": kills, "xp": xp }, "board": { "kills": k, "xp": x } + })); + } + } + let result = json!({ + "backend": self.backend, + "crawlers": principals.len(), + "events": occurrences.len(), + "applied": report.applied, + "duplicates": report.duplicates, + "identicalTop": before.0 == after.0 && before.1 == after.1, + "matchesCells": mismatches.is_empty(), + "mismatches": mismatches, + "tookMs": started.elapsed().as_secs_f64() * 1000.0, + }); + *self.last_rebuild.lock().expect("rebuild") = Some(result.clone()); + self.mark_dirty(); + let _ = self.refresh().await; + Ok(result) + } +} + +async fn refresh_loop(boards: std::sync::Weak) { + let mut last_applied = u64::MAX; + loop { + tokio::time::sleep(Duration::from_millis(150)).await; + let Some(boards) = boards.upgrade() else { + return; + }; + let applied = boards.background.stats().applied; + if applied != last_applied || boards.dirty.swap(false, Ordering::AcqRel) { + if boards.refresh().await.is_ok() { + last_applied = applied; + } else { + boards.mark_dirty(); + } + } + } +} diff --git a/examples/game/server/src/mobpit/crawler.rs b/examples/game/server/src/mobpit/crawler.rs new file mode 100644 index 000000000..dd7bde43b --- /dev/null +++ b/examples/game/server/src/mobpit/crawler.rs @@ -0,0 +1,220 @@ +//! The durable side of Mob Pit: one `Crawler` aggregate per player, each in +//! its own native SQLite cell (`distributed` feature `cell-sqlite`). +//! +//! The only command is [`RECORD_KILL`]. It is dispatched by the zone's fact +//! worker through `distributed_game::cell::CellFactSink`, never by a client: +//! +//! - the **principal** comes from the trusted server-built session +//! (`x-user-id`, bound by the host from the player's verified ticket); the +//! input has no identity field and unknown fields are rejected; +//! - the **XP amount** is decided here from the mob tier ([`xp_for_tier`]); +//! the zone only reports which mob died; +//! - the command id is derived from the fact key, so a retry or re-emission +//! replays the stored receipt through the cell's command ledger instead of +//! crediting twice. + +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; +use std::time::UNIX_EPOCH; + +/// Aggregate type (cell instance names are `Crawler:{principal}`). +pub const AGGREGATE_TYPE: &str = "Crawler"; +/// Command dispatched for every `MobKilled` fact. +pub const RECORD_KILL: &str = "crawler.record_kill"; +/// Event recorded by [`RECORD_KILL`]. +pub const MOB_KILLED_EVENT: &str = "crawler.mob_killed"; + +/// XP per mob tier — server-side game rules, never client input. +pub fn xp_for_tier(tier: u8) -> Option { + match tier { + 1 => Some(10), + 2 => Some(25), + 3 => Some(60), + _ => None, + } +} + +/// Level for a total XP: level `n` starts at `40 · (n − 1)²` XP. +pub fn level_for(xp: u64) -> u32 { + let mut level = 1u32; + while level_floor(level + 1) <= xp { + level += 1; + } + level +} + +/// First XP of `level`. +pub fn level_floor(level: u32) -> u64 { + let n = u64::from(level.saturating_sub(1)); + 40 * n * n +} + +/// One player's durable progress. +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct Crawler { + entity: Entity, + /// Last display name seen with a kill (cosmetic; identity is the id). + pub name: String, + /// Total XP. + pub xp: u64, + /// Mobs killed. + pub kills: u32, + /// Derived from `xp`. + pub level: u32, +} + +#[sourced(entity, aggregate_type = "Crawler", events = "CrawlerEvent")] +impl Crawler { + #[event("crawler.mob_killed", version = 1)] + fn mob_killed(&mut self, id: String, name: String, mob: String, tier: u8, xp: u32) { + let _ = (mob, tier); + self.entity.set_id(id); + self.name = name; + self.xp += u64::from(xp); + self.kills += 1; + self.level = level_for(self.xp); + } +} + +impl Crawler { + /// Principal (stream id). + pub fn id(&self) -> &str { + self.entity.id() + } + + /// Committed stream version. + pub fn version(&self) -> u64 { + self.entity.version() + } +} + +/// Arguments of a recorded `crawler.mob_killed` event, in declaration order +/// (`EventRecord::decode` of the stored payload). +pub type MobKilledArgs = (String, String, String, u8, u32); + +/// [`RECORD_KILL`] input. No principal, no XP: both are server-decided. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandInput)] +pub struct RecordKillInput { + /// Mob instance (`{zone}/m{id}`). + pub mob: String, + /// Mob tier (1..=3); XP comes from [`xp_for_tier`]. + pub tier: u8, + /// Display name at the time of the kill (server-sanitized). + pub name: String, +} + +/// [`RECORD_KILL`] result, replayed verbatim for a repeated fact key. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandOutput)] +pub struct KillReceipt { + /// Principal credited. + pub crawler: String, + /// Display name recorded. + pub name: String, + /// Mob instance. + pub mob: String, + /// Mob tier. + pub tier: u8, + /// XP credited by this kill. + pub xp: u32, + /// Total XP after it. + pub total_xp: u64, + /// Total kills after it. + pub kills: u32, + /// Level after it. + pub level: u32, + /// Stream sequence of the recorded event (leaderboard occurrence position). + pub sequence: u64, + /// Event time (Unix ms). + pub at_ms: u64, +} + +/// Mounts [`RECORD_KILL`] on a `Crawler` cell. +pub struct RecordKill; + +impl PortableCommand for RecordKill +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + RECORD_KILL, + )) + .guarded( + |ctx: &CausalCommandContext<'_, Crawler>| ctx.session().user_id().is_some(), + handle_record_kill, + ) + } +} + +async fn handle_record_kill( + ctx: &CausalCommandContext<'_, Crawler>, + input: RecordKillInput, +) -> Result>, HandlerError> { + // Identity: the trusted session only. The cell is the principal's own + // shard, so a mismatched principal cannot load it either. + let principal = ctx.session().user_id().unwrap_or_default().to_string(); + let xp = xp_for_tier(input.tier) + .ok_or_else(|| HandlerError::Rejected(format!("unknown mob tier {}", input.tier)))?; + let name: String = input.name.chars().take(16).collect(); + let repo = ctx.repo(); + let mut crawler = match repo.get(&principal).await? { + Some(crawler) => crawler, + None => repo.create(), + }; + crawler + .mob_killed( + principal.clone(), + name.clone(), + input.mob.clone(), + input.tier, + xp, + ) + .map_err(|e| HandlerError::Rejected(e.to_string()))?; + let (sequence, at_ms) = crawler + .entity + .events() + .last() + .map(|record| { + let at = record + .timestamp + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + (record.sequence, at) + }) + .unwrap_or_default(); + let receipt = KillReceipt { + crawler: principal, + name, + mob: input.mob, + tier: input.tier, + xp, + total_xp: crawler.xp, + kills: crawler.kills, + level: crawler.level, + sequence, + at_ms, + }; + repo.commit(crawler)?.succeeded(receipt) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_follow_the_quadratic_curve() { + assert_eq!(level_for(0), 1); + assert_eq!(level_for(39), 1); + assert_eq!(level_for(40), 2); + assert_eq!(level_for(159), 2); + assert_eq!(level_for(160), 3); + assert_eq!(level_floor(3), 160); + assert_eq!(xp_for_tier(0), None); + assert_eq!(xp_for_tier(3), Some(60)); + } +} diff --git a/examples/game/server/src/mobpit/mod.rs b/examples/game/server/src/mobpit/mod.rs new file mode 100644 index 000000000..8aab74d6a --- /dev/null +++ b/examples/game/server/src/mobpit/mod.rs @@ -0,0 +1,144 @@ +//! **Mob Pit** (+ **Leaderboard**) — non-blocking durable facts, crash +//! recovery and authoritative combat; kills projected into sorted-set +//! leaderboards. +//! +//! - [`zone`]: the 30 Hz zone (players, 12 mobs with a telegraphed attack +//! state machine, melee cones). A kill emits a fact and keeps ticking. +//! - [`crawler`]: the per-player `Crawler` aggregate and its one command; +//! XP is decided there, the principal comes from the trusted session. +//! - [`store`]: one native SQLite cell per player + the `FactSink` (with the +//! "slow storage" latency knob) that routes facts into them via +//! `distributed_game::cell::CellFactSink`. +//! - [`board`]: kills/XP leaderboards (in-memory or Redis), fire-and-forget +//! live updates, idempotent apply keys, rebuild from the cells' events. +//! - [`routes`]: dev routes (`/dev/mobpit/*`). +//! +//! `game-demos mobpit` and `game-demos leaderboard` start the same server +//! (one process hosts the pit and the boards); they differ only in the page +//! `run.sh` opens. Data lives in `--data-dir` / `MOBPIT_DATA_DIR`; the +//! ticket secret is persisted there too so guests keep their identity across +//! a restart (crash-recovery demo). + +pub mod board; +pub mod crawler; +pub mod routes; +pub mod store; +pub mod world; +pub mod zone; + +use std::future::Future; +use std::path::PathBuf; +use std::sync::Arc; + +use distributed_game::net::{GameServer, ServerConfig}; + +use crate::common::{self, random_hex, Demo, DemoArgs, DemoOptions, Guests, RunningDemo}; +pub use world::{MobPitWorld, WorldOptions}; +pub use zone::{encode_bot_input, MobPit}; + +/// `game-demos mobpit|leaderboard` options. +#[derive(Debug, Clone, clap::Args)] +pub struct MobPitArgs { + /// Shared demo options. + #[command(flatten)] + pub common: DemoArgs, + /// Directory of the per-player SQLite cells (and the persisted dev + /// ticket secret). Default: `$TMPDIR/game-demos-mobpit`. + #[arg(long, env = "MOBPIT_DATA_DIR")] + pub data_dir: Option, + /// Redis for the leaderboard (`redis://127.0.0.1:6379`); default in memory. + #[arg(long, env = "REDIS_URL")] + pub redis_url: Option, + /// Start with this artificial storage latency (ms). + #[arg(long, env = "MOBPIT_STORAGE_LATENCY_MS", default_value_t = 0)] + pub storage_latency_ms: u64, +} + +/// Demo registration. +pub struct MobPitDemo; + +impl Demo for MobPitDemo { + type Zone = MobPit; + const NAME: &'static str = "mobpit"; + const DEFAULT_ZONE: &'static str = "pit-1"; + + fn hosts_zone(zone_id: &str) -> bool { + zone_id.starts_with("pit-") + } + + /// Plain `common::spawn` gets a throwaway world (temp dir, in-memory + /// board, no dev routes of its own); use [`spawn`] / [`run`] instead. + fn server(config: ServerConfig, guests: Guests) -> GameServer { + let world = MobPitWorld::open(WorldOptions::temporary()) + .expect("mobpit world (needs a Tokio runtime)"); + world.server(config, guests).0 + } +} + +/// Start Mob Pit over `world` (tests; dev routes need `options.dev`). +pub fn spawn( + listener: tokio::net::TcpListener, + options: DemoOptions, + world: Arc, + signal: impl Future + Send + 'static, +) -> std::io::Result> { + common::spawn_with::( + listener, + options, + move |config, guests| world.server(config, guests), + signal, + ) +} + +/// Dev ticket secret kept in the data dir, so guest tokens (and therefore +/// principals) survive a server restart. +fn persisted_secret(dir: &std::path::Path) -> std::io::Result { + let path = dir.join("dev-ticket-secret"); + if let Ok(secret) = std::fs::read_to_string(&path) { + let secret = secret.trim().to_string(); + if secret.len() >= 32 { + return Ok(secret); + } + } + let secret = random_hex(64); + std::fs::write(&path, &secret)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; + } + Ok(secret) +} + +/// CLI entry: open the cells, rebuild the board from them, serve. +pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { + let data_dir = args + .data_dir + .clone() + .unwrap_or_else(|| std::env::temp_dir().join("game-demos-mobpit")); + let mut options = WorldOptions::new(&data_dir); + options.redis_url = args.redis_url.clone(); + let world = MobPitWorld::open(options).map_err(std::io::Error::other)?; + world + .sink_state() + .set_latency(std::time::Duration::from_millis(args.storage_latency_ms)); + if args.common.secret.is_none() { + args.common.secret = Some(persisted_secret(&data_dir)?); + } + // Board = projection of the cells: rebuild it before accepting players + // (the in-memory board starts empty; Redis may have missed updates). + match world.rebuild_board().await { + Ok(report) => eprintln!("mobpit: leaderboard rebuilt from cells: {report}"), + Err(error) => eprintln!("mobpit: leaderboard rebuild failed (serving anyway): {error}"), + } + eprintln!( + "mobpit: data dir {} · boot {} · leaderboard {}", + data_dir.display(), + world.boot(), + world.board().backend() + ); + common::run_with::(args.common, move |config, guests| { + world.server(config, guests) + }) + .await +} diff --git a/examples/game/server/src/mobpit/routes.rs b/examples/game/server/src/mobpit/routes.rs new file mode 100644 index 000000000..0e4917a0d --- /dev/null +++ b/examples/game/server/src/mobpit/routes.rs @@ -0,0 +1,104 @@ +//! **Dev-only** Mob Pit routes (mounted with `--dev`, next to `/dev/ticket`). +//! None of them takes an identity or a reward from the caller. +//! +//! - `GET /dev/mobpit/storage`, `POST /dev/mobpit/storage {latencyMs}` — +//! artificial latency in front of every cell commit ("slow storage"). +//! - `GET /dev/mobpit/stats` — boot id, sink counters, pending facts, recent +//! commits (key, exact input, receipt). +//! - `GET /dev/mobpit/crawlers` — every Crawler cell on disk (read path). +//! - `GET /dev/mobpit/leaderboard[?member=principal]` — the pushed top-N +//! snapshot, plus rank / neighbours of `member` on both boards. +//! - `POST /dev/mobpit/leaderboard/rebuild` — rebuild both boards from the +//! cells' event history; reports whether the result matches the cells. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use super::world::MobPitWorld; + +type ApiResult = Result, (StatusCode, Json)>; + +fn internal(error: impl std::fmt::Display) -> (StatusCode, Json) { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": error.to_string() })), + ) +} + +/// The router. +pub fn routes(world: Arc) -> Router { + Router::new() + .route("/dev/mobpit/storage", get(get_storage).post(set_storage)) + .route("/dev/mobpit/stats", get(stats)) + .route("/dev/mobpit/crawlers", get(crawlers)) + .route("/dev/mobpit/leaderboard", get(leaderboard)) + .route("/dev/mobpit/leaderboard/rebuild", post(rebuild)) + .with_state(world) +} + +/// `POST /dev/mobpit/storage` body. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StorageBody { + latency_ms: u64, +} + +fn storage_json(world: &MobPitWorld) -> Value { + json!({ "latencyMs": world.sink_state().latency().as_millis() as u64 }) +} + +async fn get_storage(State(world): State>) -> Json { + Json(storage_json(&world)) +} + +async fn set_storage( + State(world): State>, + Json(body): Json, +) -> Json { + world + .sink_state() + .set_latency(Duration::from_millis(body.latency_ms)); + Json(storage_json(&world)) +} + +async fn stats(State(world): State>) -> Json { + Json(json!({ + "boot": world.boot(), + "dataDir": world.data_dir().display().to_string(), + "latencyMs": world.sink_state().latency().as_millis() as u64, + "pending": world.zone_pending(), + "sink": world.sink_state().stats(), + "recent": world.sink_state().recent(), + "board": world.board().backend(), + })) +} + +async fn crawlers(State(world): State>) -> ApiResult { + Ok(Json( + json!({ "crawlers": world.crawlers().await.map_err(internal)? }), + )) +} + +async fn leaderboard( + State(world): State>, + Query(query): Query>, +) -> ApiResult { + let snapshot = (*world.board().snapshot()).clone(); + let me = match query.get("member").filter(|m| !m.is_empty()) { + Some(member) => world.board().around(member, 2).await.map_err(internal)?, + None => Value::Null, + }; + Ok(Json(json!({ "snapshot": snapshot, "me": me }))) +} + +async fn rebuild(State(world): State>) -> ApiResult { + Ok(Json(world.rebuild_board().await.map_err(internal)?)) +} diff --git a/examples/game/server/src/mobpit/store.rs b/examples/game/server/src/mobpit/store.rs new file mode 100644 index 000000000..947d85b08 --- /dev/null +++ b/examples/game/server/src/mobpit/store.rs @@ -0,0 +1,310 @@ +//! Per-player durable cells and the fact sink that routes into them. +//! +//! [`CrawlerCells`] keeps one native SQLite cell per principal under a data +//! directory (`Crawler%3A{principal}.sqlite3`, see `CellSqlitePath`). Every +//! command commits its event, the command-ledger receipt and snapshot rows in +//! one SQLite transaction with `synchronous=FULL`, so an acknowledged fact +//! survives `kill -9` (and power loss), and a half-applied one cannot exist. +//! +//! [`CrawlerFactSink`] is the game's `FactSink`: optional artificial latency +//! (the "slow storage" toggle), then `CellFactSink::commit` into the killer's +//! cell, then a fire-and-forget leaderboard update. + +use std::collections::{BTreeMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed::cell_host::{AggregateCell, CellSqlitePath, CellStreamStore}; +use distributed::entity::EventRecord; +use distributed::{GetStream, RepositoryError, StreamIdentity}; +use distributed_game::cell::CellFactSink; +use distributed_game::facts::BoxFuture; +use distributed_game::{Fact, FactError, FactReceipt, FactSink}; +use serde::Serialize; + +use super::board::Leaderboards; +use super::crawler::{Crawler, KillReceipt, RecordKill, AGGREGATE_TYPE, RECORD_KILL}; + +/// Command-ledger service id for game facts. +pub const SERVICE_ID: &str = "mobpit"; +/// Principal for facts without a player (none are emitted today). +pub const SYSTEM_PRINCIPAL: &str = "mobpit-zone"; +const FILE_PREFIX: &str = "Crawler%3A"; + +/// One player's open cell. +pub struct CrawlerCell { + principal: String, + cell: Arc>, + store: CellStreamStore, + sink: CellFactSink, +} + +impl CrawlerCell { + /// Current state (`None` before the first kill). + pub async fn load(&self) -> Result, RepositoryError> { + self.cell.load().await + } + + /// The full durable event history of this cell, oldest first. + pub async fn history(&self) -> Result, RepositoryError> { + let identity = StreamIdentity::new(AGGREGATE_TYPE, self.principal.clone())?; + Ok(GetStream::get_stream(&self.store, &identity) + .await? + .map(|entity| entity.events().to_vec()) + .unwrap_or_default()) + } + + /// The cell (tests dispatch into it directly). + pub fn cell(&self) -> &Arc> { + &self.cell + } +} + +/// Lazily opened `Crawler` cells under one directory. +pub struct CrawlerCells { + root: PathBuf, + open: Mutex>>, +} + +impl CrawlerCells { + /// Cells under `root` (created on first write). + pub fn new(root: impl Into) -> Self { + Self { + root: root.into(), + open: Mutex::new(BTreeMap::new()), + } + } + + /// Data directory. + pub fn root(&self) -> &Path { + &self.root + } + + /// Open (once per process) the cell of `principal`. Opening the same file + /// twice in one process would give two connections; the cache prevents it. + pub fn get(&self, principal: &str) -> Result, RepositoryError> { + let mut open = self.open.lock().expect("cells lock"); + if let Some(cell) = open.get(principal) { + return Ok(cell.clone()); + } + let identity = StreamIdentity::new(AGGREGATE_TYPE, principal.to_string())?; + let store = CellStreamStore::open_sqlite(&CellSqlitePath::root(&self.root), identity)?; + let cell = Arc::new(AggregateCell::from_store(store.clone())?.mount(RecordKill)); + let entry = Arc::new(CrawlerCell { + principal: principal.to_string(), + sink: CellFactSink::new(cell.clone(), SERVICE_ID, SYSTEM_PRINCIPAL), + cell, + store, + }); + open.insert(principal.to_string(), entry.clone()); + Ok(entry) + } + + /// Whether `principal` already has a cell file (reads never create one). + pub fn exists(&self, principal: &str) -> bool { + CellSqlitePath::root(&self.root) + .resolve(&format!("{AGGREGATE_TYPE}:{principal}")) + .exists() + } + + /// Principals with a cell file on disk (sorted). + pub fn principals(&self) -> Vec { + let Ok(dir) = std::fs::read_dir(&self.root) else { + return Vec::new(); + }; + let suffix = format!(".{}", distributed::cell_host::NATIVE_CELL_SQLITE_EXTENSION); + let mut out: Vec = dir + .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) + .filter_map(|name| { + let stem = name.strip_prefix(FILE_PREFIX)?.strip_suffix(&suffix)?; + // Long names are hashed (`~`) and cannot be inverted; guest + // and bot principals never are. + percent_decode(stem) + }) + .collect(); + out.sort(); + out.dedup(); + out + } +} + +fn percent_decode(stem: &str) -> Option { + let bytes = stem.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + let hex = stem.get(i + 1..i + 3)?; + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else if bytes[i] == b'~' { + return None; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +/// A committed kill as the dev routes report it. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CommittedFact { + /// Fact idempotency key. + pub key: String, + /// Command input as committed (needed to replay the exact command). + pub input: serde_json::Value, + /// Receipt. + pub receipt: KillReceipt, + /// True when the ledger replayed an earlier commit. + pub replayed: bool, +} + +/// Counters of the fact sink. +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SinkStats { + /// Commit attempts started. + pub attempts: u64, + /// First-time commits. + pub committed: u64, + /// Ledger replays (same key seen again). + pub replayed: u64, + /// Failed attempts (retryable or permanent). + pub errors: u64, + /// Facts currently inside `commit` (incl. the artificial latency). + pub in_sink: u64, +} + +/// Shared sink state (lives in the world). +#[derive(Default)] +pub struct SinkState { + latency_ms: AtomicU64, + stats: Mutex, + recent: Mutex>, +} + +impl SinkState { + /// Artificial storage latency. + pub fn latency(&self) -> Duration { + Duration::from_millis(self.latency_ms.load(Ordering::Relaxed)) + } + + /// Set the artificial storage latency (clamped to 5 s). + pub fn set_latency(&self, latency: Duration) -> Duration { + let ms = latency.as_millis().min(5_000) as u64; + self.latency_ms.store(ms, Ordering::Relaxed); + Duration::from_millis(ms) + } + + /// Counter snapshot. + pub fn stats(&self) -> SinkStats { + self.stats.lock().expect("stats").clone() + } + + /// Most recent commits, newest last (at most 64). + pub fn recent(&self) -> Vec { + self.recent + .lock() + .expect("recent") + .iter() + .cloned() + .collect() + } + + fn update(&self, f: impl FnOnce(&mut SinkStats)) { + f(&mut self.stats.lock().expect("stats")); + } +} + +/// The game's fact sink (cloned into every zone's fact worker). +#[derive(Clone)] +pub struct CrawlerFactSink { + cells: Arc, + state: Arc, + board: Arc, +} + +impl CrawlerFactSink { + /// Sink over `cells`, reporting into `state`, feeding `board`. + pub fn new(cells: Arc, state: Arc, board: Arc) -> Self { + Self { + cells, + state, + board, + } + } + + async fn commit_inner(&self, fact: &Fact) -> Result { + let latency = self.state.latency(); + if !latency.is_zero() { + tokio::time::sleep(latency).await; + } + let principal = fact + .principal() + .ok_or_else(|| FactError::Permanent("kill facts need a player principal".into()))?; + let cell = self + .cells + .get(principal) + .map_err(|e| FactError::Retryable(format!("open cell: {e}")))?; + let receipt = cell.sink.commit(fact).await?; + if fact.command() == RECORD_KILL { + if let Ok(kill) = serde_json::from_value::(receipt.payload.clone()) { + // Fire-and-forget: never awaits the leaderboard store. + self.board.submit_kill(&kill); + let mut recent = self.state.recent.lock().expect("recent"); + if recent.len() == 64 { + recent.pop_front(); + } + recent.push_back(CommittedFact { + key: fact.key().to_string(), + input: fact.input().clone(), + receipt: kill, + replayed: receipt.replayed, + }); + } + } + Ok(receipt) + } +} + +impl FactSink for CrawlerFactSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.state.update(|s| { + s.attempts += 1; + s.in_sink += 1; + }); + let result = self.commit_inner(fact).await; + self.state.update(|s| { + s.in_sink -= 1; + match &result { + Ok(r) if r.replayed => s.replayed += 1, + Ok(_) => s.committed += 1, + Err(_) => s.errors += 1, + } + }); + result + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_names_round_trip_to_principals() { + let dir = + std::env::temp_dir().join(format!("mobpit-cells-{}", crate::common::random_hex(12))); + let cells = CrawlerCells::new(&dir); + for p in ["guest-0a1b", "bot-3", "odd:name"] { + cells.get(p).unwrap(); + } + assert_eq!(cells.principals(), vec!["bot-3", "guest-0a1b", "odd:name"]); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs new file mode 100644 index 000000000..98d998ffb --- /dev/null +++ b/examples/game/server/src/mobpit/world.rs @@ -0,0 +1,181 @@ +//! Process-wide Mob Pit state shared by the zones, the fact worker and the +//! dev routes: the durable cells, the sink's latency/counters and the +//! leaderboards. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use axum::Router; +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::RetryPolicy; +use serde_json::{json, Value}; + +use super::board::Leaderboards; +use super::store::{CrawlerCells, CrawlerFactSink, SinkState}; +use super::zone::{MobPit, MobPitConfig}; +use super::{routes, MobPitDemo}; +use crate::common::{random_hex, Demo, Guests}; + +/// Unsettled facts one zone may hold before `emit_fact` reports backpressure. +pub const FACT_CAPACITY: usize = 256; + +/// How to open the world. +#[derive(Debug, Clone)] +pub struct WorldOptions { + /// Directory of the per-player cell files. + pub data_dir: PathBuf, + /// `redis://…` for a Redis leaderboard; None = in memory. + pub redis_url: Option, + /// Redis key prefix (tests isolate themselves with it). + pub redis_prefix: String, +} + +impl WorldOptions { + /// Cells in `data_dir`, in-memory leaderboard. + pub fn new(data_dir: impl Into) -> Self { + Self { + data_dir: data_dir.into(), + redis_url: None, + redis_prefix: "mobpit".into(), + } + } + + /// A fresh directory under the system temp dir. + pub fn temporary() -> Self { + Self::new(std::env::temp_dir().join(format!("game-demos-mobpit-{}", random_hex(12)))) + } +} + +/// A loaded profile: principal and `(xp, level, kills)` (None = no cell yet). +pub type LoadedProfile = (String, Option<(u64, u32, u32)>); + +/// See the module docs. +pub struct MobPitWorld { + boot: String, + cells: Arc, + sink: Arc, + board: Arc, + zone_pending: AtomicUsize, + profiles: Arc>>, +} + +impl MobPitWorld { + /// Open the cells directory and the leaderboard. Must be called inside a + /// Tokio runtime. Does not rebuild the board: call [`Self::rebuild_board`]. + pub fn open(options: WorldOptions) -> Result, String> { + std::fs::create_dir_all(&options.data_dir) + .map_err(|e| format!("create {}: {e}", options.data_dir.display()))?; + let board = Leaderboards::open(options.redis_url.as_deref(), &options.redis_prefix)?; + Ok(Arc::new(Self { + boot: random_hex(8), + cells: Arc::new(CrawlerCells::new(options.data_dir)), + sink: Arc::new(SinkState::default()), + board, + zone_pending: AtomicUsize::new(0), + profiles: Arc::default(), + })) + } + + /// Random id of this server process (part of every fact key). + pub fn boot(&self) -> &str { + &self.boot + } + + /// Cell files directory. + pub fn data_dir(&self) -> &Path { + self.cells.root() + } + + /// The cells. + pub fn cells(&self) -> &Arc { + &self.cells + } + + /// Sink latency and counters. + pub fn sink_state(&self) -> &Arc { + &self.sink + } + + /// Leaderboards. + pub fn board(&self) -> &Arc { + &self.board + } + + /// The game's fact sink. + pub fn fact_sink(&self) -> CrawlerFactSink { + CrawlerFactSink::new(self.cells.clone(), self.sink.clone(), self.board.clone()) + } + + pub(crate) fn set_zone_pending(&self, n: usize) { + self.zone_pending.store(n, Ordering::Relaxed); + } + + /// Facts emitted by the zone and not yet settled (incl. backpressure backlog). + pub fn zone_pending(&self) -> usize { + self.zone_pending.load(Ordering::Relaxed) + } + + /// Load `principal`'s cell on a background task; the zone picks the + /// result up with [`Self::take_loaded_profiles`] on a later tick. + pub fn request_profile(&self, principal: &str) { + let cells = self.cells.clone(); + let profiles = self.profiles.clone(); + let principal = principal.to_string(); + let Ok(handle) = tokio::runtime::Handle::try_current() else { + return; + }; + handle.spawn(async move { + // A first-time player has no cell yet; do not create one to read. + let state = match cells.exists(&principal).then(|| cells.get(&principal)) { + Some(Ok(cell)) => cell.load().await.ok().flatten(), + _ => None, + }; + profiles + .lock() + .expect("profiles") + .push((principal, state.map(|c| (c.xp, c.level, c.kills)))); + }); + } + + pub(crate) fn take_loaded_profiles(&self) -> Vec { + std::mem::take(&mut *self.profiles.lock().expect("profiles")) + } + + /// Rebuild the leaderboards from the cells' event history. + pub async fn rebuild_board(&self) -> Result { + self.board.rebuild(&self.cells).await + } + + /// Every crawler on disk: `{principal, name, xp, kills, level, version}`. + pub async fn crawlers(&self) -> Result, String> { + let mut out = Vec::new(); + for principal in self.cells.principals() { + let cell = self.cells.get(&principal).map_err(|e| e.to_string())?; + if let Some(c) = cell.load().await.map_err(|e| e.to_string())? { + out.push(json!({ + "principal": principal, "name": c.name, "xp": c.xp, + "kills": c.kills, "level": c.level, "version": c.version(), + })); + } + } + Ok(out) + } + + /// Game server for `config` plus the Mob Pit dev routes. + pub fn server( + self: &Arc, + config: ServerConfig, + guests: Guests, + ) -> (GameServer, Router) { + let world = self.clone(); + let server = GameServer::new(config, move |zone_id| { + MobPitDemo::hosts_zone(zone_id).then(|| MobPitConfig { + guests: guests.clone(), + world: world.clone(), + }) + }) + .with_fact_sink(self.fact_sink(), FACT_CAPACITY, RetryPolicy::default()); + (server, routes::routes(self.clone())) + } +} diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs new file mode 100644 index 000000000..85ca2424a --- /dev/null +++ b/examples/game/server/src/mobpit/zone.rs @@ -0,0 +1,967 @@ +//! The Mob Pit zone: authoritative melee combat at 30 Hz. +//! +//! Movement reuses the Arena's predicted step ([`crate::arena::movement`], +//! same floor and pillars) so the own capsule is client-predicted; combat is +//! server-only. Entities: +//! +//! | kind | ids | fields | +//! |---|---|---| +//! | 1 `player` | 1000 + player | x y vx vy dash cd (predicted) · name hp face swing level dead | +//! | 2 `mob` | 1..=12 | x y face tier hp state tele | +//! | 3 `pillar` | 100 + i | x y r (global) | +//! | 4 `pit` | 900 | pending slowMs tickMs tickMaxMs workUs committed backlog (global) | +//! +//! Mob state machine (deterministic, zone RNG only for wander targets): +//! `idle` (wander near home) → `chase` (living player within aggro radius or +//! hit by one) → `windup` (in reach: stand still, telegraph ring for 0.8 s) → +//! damage everyone inside the ring → `recover` (0.6 s) → `chase`; beyond the +//! leash or target dead → `return` home → `idle`. Dead mobs respawn after 4 s +//! with a new generation. +//! +//! A kill emits a fact **without awaiting storage**: +//! `Fact::new("kill:{boot}:{zone}:{mob}:{generation}", "crawler.record_kill", +//! {mob, tier, name})` via `ctx.emit_fact_for(killer)` — the host binds the +//! killer's verified principal. `boot` is random per server process, so keys +//! never collide with an earlier run's facts (zone ticks restart at 0). The +//! settlement arrives in [`Zone::on_fact_settled`] on a later tick and is +//! pushed to the killer as [`EVENT_SAVED`] + [`EVENT_PROFILE`]. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::sync::Arc; +use std::time::Instant; + +use distributed_game::{ + ConsumePolicy, Ctx, EmitError, EntitySchema, EntityState, Fact, FactOutcome, FactSettlement, + FieldType, FieldValue, KindDef, LeaveReason, ObserverId, PlayerId, View, WorldView, Zone, +}; +use serde_json::{json, Value}; + +use super::crawler::{level_floor, KillReceipt, RECORD_KILL}; +use super::world::MobPitWorld; +use crate::arena::movement::{self, MoveInput, MoveState, PILLARS, PLAYER_RADIUS}; +use crate::common::{broadcast_json_event, send_json_event, Guests}; + +/// Player kind. +pub const KIND_PLAYER: u16 = 1; +/// Mob kind. +pub const KIND_MOB: u16 = 2; +/// Pillar kind. +pub const KIND_PILLAR: u16 = 3; +/// Zone stats kind. +pub const KIND_PIT: u16 = 4; +/// Entity id of the stats entity. +pub const PIT_ENTITY: u32 = 900; + +/// `{entity, half, boot, attackRange, attackArcCos}` to a joining player. +pub const EVENT_HELLO: u32 = 1; +/// `{xp, level, kills, levelXp, nextLevelXp, source}` — from the cell on +/// join (`source: "cell"`), after each settlement (`"settled"`). +pub const EVENT_PROFILE: u32 = 2; +/// Broadcast `{key, mob, tier, x, y, killer, killerName}` the tick a mob dies. +pub const EVENT_KILL: u32 = 3; +/// To the killer: `{key, ok, replayed, xp, totalXp, kills, level, waitedMs, x, y, error?}`. +pub const EVENT_SAVED: u32 = 4; +/// Broadcast leaderboard snapshot (see `board::Leaderboards::snapshot`). +pub const EVENT_BOARD: u32 = 5; +/// To a player that died: `{respawnMs}`. +pub const EVENT_DIED: u32 = 6; + +/// Input bit: attack (bit 0 is the Arena's dash). +pub const BUTTON_ATTACK: u8 = 2; +/// Melee reach (m, from the player's centre to the mob's edge). +pub const ATTACK_RANGE: f32 = 2.2; +/// Cosine of the half cone angle (60°). +pub const ATTACK_ARC_COS: f32 = 0.5; +/// Damage per swing. +pub const ATTACK_DAMAGE: i32 = 10; +/// Swing cooldown (ticks). +pub const SWING_COOLDOWN: u8 = 13; +/// Swing animation length (ticks). +const SWING_FRAMES: u8 = 6; +/// Player max HP. +pub const PLAYER_HP: i32 = 100; +/// Number of mobs. +pub const MOBS: usize = 12; +const MAX_CREDITS: u8 = 4; +const VIEW_RADIUS: f32 = 40.0; +const AGGRO: f32 = 7.0; +const LEASH: f32 = 15.0; +const WINDUP_TICKS: u16 = 24; +const RECOVER_TICKS: u16 = 18; +const RESPAWN_TICKS: u64 = 120; +const PLAYER_RESPAWN_TICKS: u64 = 90; + +/// Mob tier stats: (max hp, speed m/s, damage, radius, telegraph radius). +fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { + match tier { + 3 => (100, 3.3, 24, 0.8, 2.6), + 2 => (60, 2.4, 16, 0.7, 2.2), + _ => (30, 3.0, 9, 0.5, 1.8), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MobState { + Idle = 0, + Chase = 1, + Windup = 2, + Recover = 3, + Return = 4, + Dead = 5, +} + +struct Mob { + id: u32, + tier: u8, + home: (f32, f32), + x: f32, + y: f32, + face: f32, + hp: i32, + state: MobState, + timer: u16, + target: Option, + generation: u32, + respawn_at: u64, + wander: (f32, f32), +} + +struct Player { + entity: u32, + principal: String, + name: String, + state: MoveState, + credits: u8, + hp: i32, + face: f32, + swing_cd: u8, + swing_anim: u8, + dead_until: Option, + level: u32, + regen: u8, +} + +struct PendingKill { + principal: String, + x: f32, + y: f32, + emitted: Instant, +} + +/// Zone construction parameters. +#[derive(Clone)] +pub struct MobPitConfig { + /// Display names from the dev ticket endpoint. + pub guests: Guests, + /// Durable cells, fact sink state and leaderboards. + pub world: Arc, +} + +/// The Mob Pit zone. +pub struct MobPit { + guests: Guests, + world: Arc, + players: BTreeMap, + mobs: Vec, + pending: HashMap, + /// Facts refused by backpressure, retried each tick (oldest first). + backlog: VecDeque<(PlayerId, Fact, f32, f32)>, + board_version: u64, + last_tick: Option, + tick_ms: f32, + tick_max_ms: f32, + tick_max_window: f32, + window_ticks: u32, + work_us: f32, + committed: u32, +} + +/// Mob homes on two rings between the pillars, tiers by index. +fn mob_layout() -> Vec<(u8, (f32, f32))> { + let mut out = Vec::with_capacity(MOBS); + for i in 0..MOBS { + let ring = if i % 2 == 0 { 11.5 } else { 16.0 }; + let a = (i as f32 + 0.5) / MOBS as f32 * std::f32::consts::TAU; + let tier = match i { + 0 => 3, + 3 | 6 | 9 | 11 => 2, + _ => 1, + }; + out.push((tier, (ring * a.cos(), ring * a.sin()))); + } + out +} + +fn spawn_point(player: PlayerId) -> (f32, f32) { + const SPOTS: [(f32, f32); 6] = [ + (-4.5, -4.5), + (4.5, -4.5), + (4.5, 4.5), + (-4.5, 4.5), + (0.0, -5.5), + (0.0, 5.5), + ]; + SPOTS[player.0 as usize % SPOTS.len()] +} + +fn push_out_of_pillars(x: &mut f32, y: &mut f32, radius: f32) { + for (px, py, pr) in PILLARS { + let (ox, oy) = (*x - px, *y - py); + let d2 = ox * ox + oy * oy; + let min = radius + pr; + if d2 < min * min { + let d = d2.sqrt().max(1e-4); + *x = px + ox / d * min; + *y = py + oy / d * min; + } + } + let lim = movement::HALF - radius; + *x = x.clamp(-lim, lim); + *y = y.clamp(-lim, lim); +} + +fn step_toward(x: &mut f32, y: &mut f32, tx: f32, ty: f32, stride: f32) -> f32 { + let (dx, dy) = (tx - *x, ty - *y); + let d = (dx * dx + dy * dy).sqrt(); + if d > 1e-4 { + let s = stride.min(d); + *x += dx / d * s; + *y += dy / d * s; + } + dy.atan2(dx) +} + +fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { + ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() +} + +/// Player input: the Arena's 3-byte frame plus [`BUTTON_ATTACK`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PitInput { + /// Movement part (dash bit only). + pub movement: MoveInput, + /// Attack held. + pub attack: bool, +} + +impl MobPit { + fn profile_event(xp: u64, level: u32, kills: u32, source: &str) -> Value { + json!({ + "xp": xp, + "level": level, + "kills": kills, + "levelXp": level_floor(level), + "nextLevelXp": level_floor(level + 1), + "source": source, + }) + } + + fn player_by_principal(&self, principal: &str) -> Option { + self.players + .iter() + .find(|(_, p)| p.principal == principal) + .map(|(id, _)| *id) + } + + fn emit_kill(&mut self, ctx: &mut Ctx<'_, Self>, killer: PlayerId, mob: usize) { + let m = &self.mobs[mob]; + let zone = ctx.zone_id().to_string(); + let key = format!( + "kill:{}:{zone}:m{}:{}", + self.world.boot(), + m.id, + m.generation + ); + let (x, y, tier, id) = (m.x, m.y, m.tier, m.id); + let Some(player) = self.players.get(&killer) else { + return; + }; + let fact = Fact::new( + key.clone(), + RECORD_KILL, + json!({ "mob": format!("{zone}/m{id}"), "tier": tier, "name": player.name }), + ); + broadcast_json_event( + ctx, + EVENT_KILL, + &json!({ + "key": key, "mob": id, "tier": tier, "x": x, "y": y, + "killer": player.entity, "killerName": player.name, + }), + ); + self.backlog.push_back((killer, fact, x, y)); + self.flush_backlog(ctx); + } + + /// Hand queued facts to the host; never blocks. Backpressure keeps the + /// rest for the next tick. + fn flush_backlog(&mut self, ctx: &mut Ctx<'_, Self>) { + while let Some((player, fact, x, y)) = self.backlog.pop_front() { + let key = fact.key().to_string(); + match ctx.emit_fact_for(player, fact.clone()) { + Ok(()) => { + let principal = self + .players + .get(&player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + self.pending.insert( + key, + PendingKill { + principal, + x, + y, + emitted: Instant::now(), + }, + ); + } + Err(EmitError::Backpressure) => { + self.backlog.push_front((player, fact, x, y)); + return; + } + // The killer left before the fact could be queued, or the key + // is already in flight: nothing durable to do. + Err(_) => {} + } + } + } + + fn step_players(&mut self, ctx: &mut Ctx<'_, Self>) -> Vec<(PlayerId, f32, f32, f32)> { + let tick = ctx.tick(); + let mut swings = Vec::new(); + for (id, p) in &mut self.players { + p.credits = (p.credits + 1).min(MAX_CREDITS); + p.swing_cd = p.swing_cd.saturating_sub(1); + p.swing_anim = p.swing_anim.saturating_sub(1); + if let Some(until) = p.dead_until { + // Dead: inputs are consumed but ignored. + let _ = ctx.take_inputs(*id, ConsumePolicy::Drain); + if tick >= until { + let (x, y) = spawn_point(*id); + p.state = MoveState { + x, + y, + ..MoveState::default() + }; + p.hp = PLAYER_HP; + p.dead_until = None; + } + continue; + } + while p.credits > 0 { + let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { + break; + }; + let input = input.input; + p.state = movement::step(p.state, input.movement); + p.credits -= 1; + let (sx, sy) = (f32::from(input.movement.mx), f32::from(input.movement.my)); + if sx * sx + sy * sy > 20.0 * 20.0 { + p.face = sy.atan2(sx); + } + if input.attack && p.swing_cd == 0 { + p.swing_cd = SWING_COOLDOWN; + p.swing_anim = SWING_FRAMES; + swings.push((*id, p.state.x, p.state.y, p.face)); + } + } + p.regen = p.regen.wrapping_add(1); + if p.regen % 15 == 0 && p.hp < PLAYER_HP { + p.hp += 1; + } + ctx.set_view(*id, View::new(p.state.x, p.state.y, VIEW_RADIUS)); + } + swings + } + + fn resolve_swings(&mut self, ctx: &mut Ctx<'_, Self>, swings: Vec<(PlayerId, f32, f32, f32)>) { + for (player, x, y, face) in swings { + let (fx, fy) = (face.cos(), face.sin()); + for i in 0..self.mobs.len() { + let m = &mut self.mobs[i]; + if m.state == MobState::Dead { + continue; + } + let (_, _, _, radius, _) = tier_stats(m.tier); + let (dx, dy) = (m.x - x, m.y - y); + let d = (dx * dx + dy * dy).sqrt(); + if d > ATTACK_RANGE + radius { + continue; + } + let cos = if d < 1e-3 { + 1.0 + } else { + (dx * fx + dy * fy) / d + }; + if cos < ATTACK_ARC_COS && d > radius + PLAYER_RADIUS { + continue; + } + m.hp -= ATTACK_DAMAGE; + if matches!(m.state, MobState::Idle | MobState::Return) { + m.state = MobState::Chase; + m.target = Some(player); + } + if m.hp <= 0 { + m.hp = 0; + m.state = MobState::Dead; + m.respawn_at = ctx.tick() + RESPAWN_TICKS; + m.target = None; + self.emit_kill(ctx, player, i); + } + } + } + } + + fn step_mobs(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + let tick = ctx.tick(); + let living: Vec<(PlayerId, f32, f32)> = self + .players + .iter() + .filter(|(_, p)| p.dead_until.is_none()) + .map(|(id, p)| (*id, p.state.x, p.state.y)) + .collect(); + let mut hits: Vec<(PlayerId, i32)> = Vec::new(); + for i in 0..self.mobs.len() { + let (max_hp, speed, damage, radius, tele) = tier_stats(self.mobs[i].tier); + let target_pos = |t: Option| { + t.and_then(|t| living.iter().find(|(id, _, _)| *id == t)) + .map(|(_, x, y)| (*x, *y)) + }; + let m = &mut self.mobs[i]; + match m.state { + MobState::Dead => { + if tick >= m.respawn_at { + m.generation += 1; + m.hp = max_hp; + (m.x, m.y) = m.home; + m.state = MobState::Idle; + } + continue; + } + MobState::Idle => { + let nearest = living + .iter() + .map(|(id, x, y)| (*id, dist((m.x, m.y), (*x, *y)))) + .filter(|(_, d)| *d < AGGRO) + .min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((id, _)) = nearest { + m.state = MobState::Chase; + m.target = Some(id); + } else if dist((m.x, m.y), m.wander) < 0.3 { + let a = ctx.rng().next_f32() * std::f32::consts::TAU; + let r = ctx.rng().next_f32() * 2.5; + let m = &mut self.mobs[i]; + m.wander = (m.home.0 + r * a.cos(), m.home.1 + r * a.sin()); + } else { + let (wx, wy) = m.wander; + m.face = step_toward(&mut m.x, &mut m.y, wx, wy, 1.0 * dt); + } + } + MobState::Chase => match target_pos(m.target) { + Some((tx, ty)) if dist(m.home, (m.x, m.y)) < LEASH => { + let reach = radius + PLAYER_RADIUS + 0.6; + if dist((m.x, m.y), (tx, ty)) <= reach { + m.state = MobState::Windup; + m.timer = WINDUP_TICKS; + m.face = (ty - m.y).atan2(tx - m.x); + } else { + m.face = step_toward(&mut m.x, &mut m.y, tx, ty, speed * dt); + } + } + _ => { + m.state = MobState::Return; + m.target = None; + } + }, + MobState::Windup => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + for (id, x, y) in &living { + if dist((m.x, m.y), (*x, *y)) <= tele + PLAYER_RADIUS * 0.5 { + hits.push((*id, damage)); + } + } + m.state = MobState::Recover; + m.timer = RECOVER_TICKS; + } + } + MobState::Recover => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + m.state = MobState::Chase; + } + } + MobState::Return => { + let (hx, hy) = m.home; + m.face = step_toward(&mut m.x, &mut m.y, hx, hy, speed * 1.3 * dt); + m.hp = (m.hp + 1).min(max_hp); + if dist((m.x, m.y), m.home) < 0.3 { + m.state = MobState::Idle; + m.wander = m.home; + } + } + } + let m = &mut self.mobs[i]; + push_out_of_pillars(&mut m.x, &mut m.y, radius); + } + // Light separation so a pack does not stack on one spot. + for i in 0..self.mobs.len() { + for j in (i + 1)..self.mobs.len() { + let (a, b) = (&self.mobs[i], &self.mobs[j]); + if a.state == MobState::Dead || b.state == MobState::Dead { + continue; + } + let min = tier_stats(a.tier).3 + tier_stats(b.tier).3; + let (dx, dy) = (b.x - a.x, b.y - a.y); + let d = (dx * dx + dy * dy).sqrt(); + if d < min && d > 1e-4 { + let push = (min - d) * 0.5; + let (nx, ny) = (dx / d * push, dy / d * push); + self.mobs[i].x -= nx; + self.mobs[i].y -= ny; + self.mobs[j].x += nx; + self.mobs[j].y += ny; + } + } + } + for (id, damage) in hits { + let Some(p) = self.players.get_mut(&id) else { + continue; + }; + if p.dead_until.is_some() { + continue; + } + p.hp -= damage; + if p.hp <= 0 { + p.hp = 0; + p.state.vx = 0.0; + p.state.vy = 0.0; + p.dead_until = Some(tick + PLAYER_RESPAWN_TICKS); + for m in &mut self.mobs { + if m.target == Some(id) { + m.target = None; + } + } + send_json_event( + ctx, + id, + EVENT_DIED, + &json!({ "respawnMs": PLAYER_RESPAWN_TICKS * 1000 / 30 }), + ); + } + } + } + + fn deliver_profiles(&mut self, ctx: &mut Ctx<'_, Self>) { + for (principal, crawler) in self.world.take_loaded_profiles() { + let Some(id) = self.player_by_principal(&principal) else { + continue; + }; + let (xp, level, kills) = crawler.unwrap_or((0, 1, 0)); + if let Some(p) = self.players.get_mut(&id) { + p.level = level; + } + send_json_event( + ctx, + id, + EVENT_PROFILE, + &Self::profile_event(xp, level, kills, "cell"), + ); + } + } + + fn push_board(&mut self, ctx: &mut Ctx<'_, Self>) { + let version = self.world.board().version(); + if version != self.board_version { + self.board_version = version; + let snapshot = self.world.board().snapshot(); + broadcast_json_event(ctx, EVENT_BOARD, &snapshot); + } + } + + fn measure_tick(&mut self) { + let now = Instant::now(); + if let Some(last) = self.last_tick { + let ms = now.duration_since(last).as_secs_f32() * 1000.0; + self.tick_ms = if self.tick_ms == 0.0 { + ms + } else { + self.tick_ms * 0.9 + ms * 0.1 + }; + self.tick_max_window = self.tick_max_window.max(ms); + self.window_ticks += 1; + if self.window_ticks >= 30 { + self.tick_max_ms = self.tick_max_window; + self.tick_max_window = 0.0; + self.window_ticks = 0; + } + } + self.last_tick = Some(now); + } +} + +impl Zone for MobPit { + type Config = MobPitConfig; + type Input = PitInput; + type Timer = (); + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -movement::HALF, + max: movement::HALF, + bits: 14, + }; + EntitySchema::new() + .kind( + KindDef::new(KIND_PLAYER, "player") + .field("x", movement::POS) + .field("y", movement::POS) + .field("vx", movement::VEL) + .field("vy", movement::VEL) + .field("dash", FieldType::U8) + .field("cd", FieldType::U8) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .field("hp", FieldType::U8) + .field("face", FieldType::Angle { bits: 8 }) + .field("swing", FieldType::U8) + .field("level", FieldType::U16) + .field("dead", FieldType::Bool) + .priority(2.0), + ) + .kind( + KindDef::new(KIND_MOB, "mob") + .field("x", pos) + .field("y", pos) + .field("face", FieldType::Angle { bits: 8 }) + .field("tier", FieldType::U8) + .field("hp", FieldType::U8) + .field("state", FieldType::U8) + .field("tele", FieldType::U8), + ) + .kind( + KindDef::new(KIND_PILLAR, "pillar") + .field("x", FieldType::F32) + .field("y", FieldType::F32) + .field("r", FieldType::F32), + ) + .kind( + KindDef::new(KIND_PIT, "pit") + .field("pending", FieldType::U16) + .field("slowMs", FieldType::U16) + .field("tickMs", FieldType::F32) + .field("tickMaxMs", FieldType::F32) + .field("workUs", FieldType::U32) + .field("committed", FieldType::U32) + .field("backlog", FieldType::U16), + ) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, config: MobPitConfig) -> Self { + let mobs = mob_layout() + .into_iter() + .enumerate() + .map(|(i, (tier, home))| Mob { + id: i as u32 + 1, + tier, + home, + x: home.0, + y: home.1, + face: 0.0, + hp: tier_stats(tier).0, + state: MobState::Idle, + timer: 0, + target: None, + generation: 0, + respawn_at: 0, + wander: home, + }) + .collect(); + Self { + guests: config.guests, + world: config.world, + players: BTreeMap::new(), + mobs, + pending: HashMap::new(), + backlog: VecDeque::new(), + board_version: u64::MAX, + last_tick: None, + tick_ms: 0.0, + tick_max_ms: 0.0, + tick_max_window: 0.0, + window_ticks: 0, + work_us: 0.0, + committed: 0, + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self + .guests + .name(&principal) + .unwrap_or_else(|| principal.clone()); + let (x, y) = spawn_point(player); + let entity = 1000 + player.0; + self.players.insert( + player, + Player { + entity, + principal: principal.clone(), + name, + state: MoveState { + x, + y, + ..MoveState::default() + }, + credits: MAX_CREDITS, + hp: PLAYER_HP, + face: 0.0, + swing_cd: 0, + swing_anim: 0, + dead_until: None, + level: 1, + regen: 0, + }, + ); + ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); + send_json_event( + ctx, + player, + EVENT_HELLO, + &json!({ + "entity": entity, "half": movement::HALF, "boot": self.world.boot(), + "attackRange": ATTACK_RANGE, "attackArcCos": ATTACK_ARC_COS, + }), + ); + send_json_event(ctx, player, EVENT_BOARD, &self.world.board().snapshot()); + // Read path: load the durable cell off the tick; delivered later. + self.world.request_profile(&principal); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.players.remove(&player); + for m in &mut self.mobs { + if m.target == Some(player) { + m.target = None; + } + } + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); + send_json_event(ctx, observer, EVENT_BOARD, &self.world.board().snapshot()); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + let movement = MoveInput::decode(payload)?; + Some(PitInput { + movement, + attack: payload[2] & BUTTON_ATTACK != 0, + }) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.measure_tick(); + let work = Instant::now(); + self.deliver_profiles(ctx); + let swings = self.step_players(ctx); + self.resolve_swings(ctx, swings); + self.step_mobs(ctx); + self.flush_backlog(ctx); + self.push_board(ctx); + self.world + .set_zone_pending(ctx.facts_in_flight() + self.backlog.len()); + let us = work.elapsed().as_secs_f32() * 1e6; + self.work_us = if self.work_us == 0.0 { + us + } else { + self.work_us * 0.9 + us * 0.1 + }; + } + + fn on_fact_settled(&mut self, ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + let pending = self.pending.remove(&settlement.key); + let (principal, x, y, waited_ms) = match &pending { + Some(p) => ( + p.principal.clone(), + p.x, + p.y, + p.emitted.elapsed().as_millis() as u64, + ), + None => (String::new(), 0.0, 0.0, 0), + }; + let player = self.player_by_principal(&principal); + match settlement.outcome { + FactOutcome::Committed(receipt) => { + self.committed += 1; + let Ok(kill) = serde_json::from_value::(receipt.payload) else { + return; + }; + let Some(player) = player else { return }; + if let Some(p) = self.players.get_mut(&player) { + p.level = kill.level; + } + send_json_event( + ctx, + player, + EVENT_SAVED, + &json!({ + "key": settlement.key, "ok": true, "replayed": receipt.replayed, + "xp": kill.xp, "totalXp": kill.total_xp, "kills": kill.kills, + "level": kill.level, "waitedMs": waited_ms, "x": x, "y": y, + }), + ); + send_json_event( + ctx, + player, + EVENT_PROFILE, + &Self::profile_event(kill.total_xp, kill.level, kill.kills, "settled"), + ); + } + FactOutcome::Failed { error, attempts } => { + if let Some(player) = player { + send_json_event( + ctx, + player, + EVENT_SAVED, + &json!({ + "key": settlement.key, "ok": false, "error": format!("{error:?}"), + "attempts": attempts, "waitedMs": waited_ms, "x": x, "y": y, + }), + ); + } + } + } + } + + fn has_pending_work(&self) -> bool { + !self.backlog.is_empty() + } + + fn replicate(&self, out: &mut WorldView) { + for p in self.players.values() { + let s = p.state; + out.push(EntityState::new( + p.entity, + KIND_PLAYER, + s.x, + s.y, + vec![ + FieldValue::F(s.x), + FieldValue::F(s.y), + FieldValue::F(s.vx), + FieldValue::F(s.vy), + FieldValue::U(s.dash.into()), + FieldValue::U(s.cooldown.into()), + FieldValue::Str(p.name.clone()), + FieldValue::U(p.hp.max(0) as u32), + FieldValue::F(p.face), + FieldValue::U(p.swing_anim.into()), + FieldValue::U(p.level), + FieldValue::Bool(p.dead_until.is_some()), + ], + )); + } + for m in &self.mobs { + if m.state == MobState::Dead { + continue; + } + let max_hp = tier_stats(m.tier).0; + let tele = if m.state == MobState::Windup { + 255 - (u32::from(m.timer) * 255 / u32::from(WINDUP_TICKS)) + } else { + 0 + }; + out.push(EntityState::new( + m.id, + KIND_MOB, + m.x, + m.y, + vec![ + FieldValue::F(m.x), + FieldValue::F(m.y), + FieldValue::F(m.face), + FieldValue::U(m.tier.into()), + FieldValue::U((m.hp.max(0) * 100 / max_hp) as u32), + FieldValue::U(m.state as u32), + FieldValue::U(tele), + ], + )); + } + for (i, (x, y, r)) in PILLARS.iter().enumerate() { + out.push( + EntityState::new( + 100 + i as u32, + KIND_PILLAR, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::F(*r)], + ) + .global(), + ); + } + out.push( + EntityState::new( + PIT_ENTITY, + KIND_PIT, + 0.0, + 0.0, + vec![ + FieldValue::U(self.pending.len().min(65_535) as u32), + FieldValue::U(self.world.sink_state().latency().as_millis().min(65_535) as u32), + FieldValue::F(self.tick_ms), + FieldValue::F(self.tick_max_ms), + FieldValue::U(self.work_us as u32), + FieldValue::U(self.committed), + FieldValue::U(self.backlog.len().min(65_535) as u32), + ], + ) + .global(), + ); + } +} + +/// Zone numbers for tests and tooling (`GameServer::inspect`). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct PitStats { + /// Facts emitted and not yet settled (incl. backpressure backlog). + pub pending: usize, + /// Tick interval EMA (ms). + pub tick_ms: f32, + /// Longest tick interval of the last 30 ticks (ms). + pub tick_max_ms: f32, + /// Settlements received. + pub committed: u32, + /// Living mobs. + pub mobs_alive: usize, + /// Players. + pub players: usize, +} + +impl MobPit { + /// Current numbers. + pub fn stats(&self) -> PitStats { + PitStats { + pending: self.pending.len() + self.backlog.len(), + tick_ms: self.tick_ms, + tick_max_ms: self.tick_max_ms, + committed: self.committed, + mobs_alive: self + .mobs + .iter() + .filter(|m| m.state != MobState::Dead) + .count(), + players: self.players.len(), + } + } +} + +/// Bot payload: the direction as a move plus attack always held. +pub fn encode_bot_input(dir: [f32; 2]) -> Vec { + let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; + vec![axis(dir[0]) as u8, axis(dir[1]) as u8, BUTTON_ATTACK] +} diff --git a/examples/game/server/tests/mobpit_smoke.rs b/examples/game/server/tests/mobpit_smoke.rs new file mode 100644 index 000000000..a210121c9 --- /dev/null +++ b/examples/game/server/tests/mobpit_smoke.rs @@ -0,0 +1,544 @@ +//! Mob Pit + Leaderboard smoke tests. +//! +//! 1. Facts → native SQLite cells exactly once (ledger replay), server-side +//! XP, trusted principal; leaderboard occurrences have the same ids live +//! and from history, so rebuild + replay never double count. +//! 2. Bots fight in-process; with 1.5 s of storage latency the tick stays +//! flat while pending facts climb, then everything settles and the +//! boards equal the cells (and a rebuild changes nothing). +//! 3. Crash recovery with the real binary: `kill -9` mid-fight with facts in +//! flight, restart on the same data dir, verify the cells and that a +//! replayed pre-crash fact key does not double-credit. + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use distributed::leaderboard::LeaderboardStore; +use distributed_game::bots::{run_bots, Behaviour, BotConfig}; +use distributed_game::net::TicketKey; +use distributed_game::{Fact, FactError, FactSink, FactStamp, ZoneRng}; +use game_demos::common::{random_hex, DemoOptions, RunningDemo}; +use game_demos::mobpit::board::{kill_occurrence, MobKilled}; +use game_demos::mobpit::crawler::RECORD_KILL; +use game_demos::mobpit::{self, encode_bot_input, MobPitDemo, MobPitWorld, WorldOptions}; +use serde_json::{json, Value}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; + +const SECRET: &str = "mobpit-smoke-secret-0123456789abcdef"; + +/// Walk slowly while turning: the swing cone sweeps around, chasing mobs get hit. +struct Spin { + period: Duration, + phase: f32, +} + +impl Behaviour for Spin { + fn direction(&mut self, elapsed: Duration, _rng: &mut ZoneRng) -> [f32; 2] { + let a = + self.phase + elapsed.as_secs_f32() / self.period.as_secs_f32() * std::f32::consts::TAU; + [0.35 * a.cos(), 0.35 * a.sin()] + } +} + +fn temp_dir(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!("mobpit-{tag}-{}", random_hex(10))) +} + +async fn http(addr: SocketAddr, method: &str, path: &str, body: Option) -> (u16, Value) { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + let status = response[9..12].parse().unwrap(); + let json = response + .split_once("\r\n\r\n") + .and_then(|(_, b)| serde_json::from_str(b).ok()) + .unwrap_or(Value::Null); + (status, json) +} + +async fn eventually>( + what: &str, + timeout: Duration, + mut check: impl FnMut() -> F, +) { + let start = Instant::now(); + while !check().await { + assert!(start.elapsed() < timeout, "timed out waiting for {what}"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +fn kill_fact(key: &str, principal: &str, input: Value) -> Fact { + Fact::trusted( + key, + RECORD_KILL, + input, + Some(principal.into()), + FactStamp::default(), + ) +} + +/// Every cell's (kills, xp) equals both boards' scores. +async fn assert_board_matches_cells(world: &MobPitWorld) -> u64 { + let mut total = 0; + for c in world.crawlers().await.unwrap() { + let principal = c["principal"].as_str().unwrap(); + let (kills, xp) = world.board().scores(principal).await.unwrap(); + assert_eq!(kills, c["kills"].as_f64().unwrap(), "kills of {principal}"); + assert_eq!(xp, c["xp"].as_f64().unwrap(), "xp of {principal}"); + total += c["kills"].as_u64().unwrap(); + } + total +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn facts_commit_once_and_board_rebuilds_identically() { + let dir = temp_dir("unit"); + let world = MobPitWorld::open(WorldOptions::new(&dir)).unwrap(); + let sink = world.fact_sink(); + let input = json!({ "mob": "pit-1/m3", "tier": 2, "name": "Ana" }); + + let first = sink + .commit(&kill_fact("kill:t:pit-1:m3:0", "guest-ana", input.clone())) + .await + .unwrap(); + assert!(!first.replayed); + assert_eq!( + first.payload["xp"], 25, + "XP decided by the cell from the tier" + ); + assert_eq!( + first.payload["crawler"], "guest-ana", + "principal from the session" + ); + let replay = sink + .commit(&kill_fact("kill:t:pit-1:m3:0", "guest-ana", input.clone())) + .await + .unwrap(); + assert!(replay.replayed, "same key replays the receipt"); + assert_eq!(replay.payload, first.payload); + + // Inputs cannot carry identity or rewards; facts need a principal. + let forged = sink + .commit(&kill_fact( + "kill:t:pit-1:m4:0", + "guest-ana", + json!({ "mob": "pit-1/m4", "tier": 1, "name": "Ana", "xp": 9999 }), + )) + .await; + assert!(matches!(forged, Err(FactError::Permanent(_))), "{forged:?}"); + let bad_tier = sink + .commit(&kill_fact( + "kill:t:pit-1:m5:0", + "guest-ana", + json!({ "mob": "pit-1/m5", "tier": 9, "name": "Ana" }), + )) + .await; + assert!(matches!(bad_tier, Err(FactError::Permanent(_)))); + let anonymous = Fact::trusted("k", RECORD_KILL, input.clone(), None, FactStamp::default()); + assert!(matches!( + sink.commit(&anonymous).await, + Err(FactError::Permanent(_)) + )); + sink.commit(&kill_fact( + "kill:t:pit-1:m6:0", + "guest-bo", + json!({ "mob": "pit-1/m6", "tier": 3, "name": "Bo" }), + )) + .await + .unwrap(); + + let cell = world.cells().get("guest-ana").unwrap(); + let ana = cell.load().await.unwrap().unwrap(); + assert_eq!((ana.kills, ana.xp, ana.level), (1, 25, 1), "credited once"); + let history = cell.history().await.unwrap(); + assert_eq!(history.len(), 1); + assert_eq!( + history[0].sequence, + first.payload["sequence"].as_u64().unwrap() + ); + + // Live updates are fire-and-forget; the replay was deduplicated. + eventually("live board", Duration::from_secs(5), || async { + world.board().scores("guest-bo").await.unwrap() == (1.0, 60.0) + }) + .await; + assert_eq!( + world.board().scores("guest-ana").await.unwrap(), + (1.0, 25.0) + ); + assert_eq!(assert_board_matches_cells(&world).await, 2); + + let report = world.rebuild_board().await.unwrap(); + assert_eq!(report["events"], 2); + assert_eq!(report["applied"], 4, "two boards per kill"); + assert_eq!(report["matchesCells"], true, "{report}"); + assert_eq!(report["identicalTop"], true, "{report}"); + + // The live occurrence id equals the history one: replaying it after the + // rebuild is a duplicate on both boards. + let occurrence = kill_occurrence( + "guest-ana", + first.payload["sequence"].as_u64().unwrap(), + first.payload["at_ms"].as_u64().unwrap(), + &MobKilled { + crawler: "guest-ana".into(), + mob: "pit-1/m3".into(), + tier: 2, + xp: 25, + }, + ) + .unwrap(); + let again = world + .board() + .projector() + .apply_event(&occurrence) + .await + .unwrap(); + assert_eq!((again.applied, again.duplicates), (0, 2)); + assert_eq!( + world.board().scores("guest-ana").await.unwrap(), + (1.0, 25.0) + ); + let (kills, _) = world.board().boards(); + assert_eq!(world.board().store().len(kills).await.unwrap(), 2); + let _ = std::fs::remove_dir_all(dir); +} + +async fn start( + world: Arc, +) -> (RunningDemo, tokio::sync::oneshot::Sender<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let running = mobpit::spawn(listener, DemoOptions::dev(SECRET), world, async move { + let _ = stopped.await; + }) + .unwrap(); + (running, stop) +} + +fn bot_config(ws: String, bots: usize, duration: Duration) -> BotConfig { + let mut config = BotConfig::new(ws, "pit-1", TicketKey::new(SECRET)); + config.bots = bots; + config.input_rate = 30.0; + config.duration = duration; + config.encoder = Arc::new(encode_bot_input); + config +} + +fn spin(i: usize) -> Box { + Box::new(Spin { + period: Duration::from_millis(900 + 150 * i as u64), + phase: i as f32, + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn bots_fight_slow_storage_keeps_the_tick_flat_and_boards_match_cells() { + let dir = temp_dir("bots"); + let world = MobPitWorld::open(WorldOptions::new(&dir)).unwrap(); + let (demo, stop) = start(world.clone()).await; + + // Unknown fields (e.g. an identity) are rejected on the dev routes too. + let (status, _) = http( + demo.addr, + "POST", + "/dev/mobpit/storage", + Some(json!({ "latencyMs": 1, "principal": "x" })), + ) + .await; + assert_eq!(status, 422); + + let server = demo.server.clone(); + let addr = demo.addr; + let probe = async move { + // Fight at full speed first, then make storage slow. + tokio::time::sleep(Duration::from_secs(4)).await; + let (_, storage) = http( + addr, + "POST", + "/dev/mobpit/storage", + Some(json!({ "latencyMs": 1500 })), + ) + .await; + assert_eq!(storage["latencyMs"], 1500); + let mut max_pending = 0; + let mut max_tick: f32 = 0.0; + let until = Instant::now() + Duration::from_secs(6); + while Instant::now() < until { + tokio::time::sleep(Duration::from_millis(250)).await; + if let Some(s) = server.inspect("pit-1", |h| h.zone().stats()).await { + max_pending = max_pending.max(s.pending); + if s.tick_max_ms > 0.0 { + max_tick = max_tick.max(s.tick_max_ms); + } + } + } + (max_pending, max_tick) + }; + let (summary, (max_pending, max_tick)) = tokio::join!( + run_bots(bot_config(demo.ws_url(), 8, Duration::from_secs(11)), spin), + probe + ); + assert_eq!( + summary.joined(), + 8, + "{:?}", + summary.bots.iter().find(|b| b.error.is_some()) + ); + eprintln!("slow storage: max pending {max_pending}, max tick interval {max_tick:.1} ms"); + assert!( + max_pending >= 1, + "slow storage: facts wait (max {max_pending})" + ); + assert!( + max_tick < 120.0, + "the 30 Hz tick never waits for storage (max interval {max_tick} ms)" + ); + + // Back to fast storage: everything settles. + http( + demo.addr, + "POST", + "/dev/mobpit/storage", + Some(json!({ "latencyMs": 0 })), + ) + .await; + let w = world.clone(); + eventually("facts settled", Duration::from_secs(60), || { + let w = w.clone(); + async move { w.zone_pending() == 0 && w.sink_state().stats().in_sink == 0 } + }) + .await; + let stats = world.sink_state().stats(); + assert!(stats.committed >= 3, "bots killed mobs: {stats:?}"); + assert_eq!(stats.errors, 0, "{stats:?}"); + + // Boards = cells (fire-and-forget updates have drained), rebuild = same. + let w = world.clone(); + eventually("board caught up", Duration::from_secs(10), || { + let w = w.clone(); + async move { + let mut ok = true; + for c in w.crawlers().await.unwrap() { + let (k, _) = w + .board() + .scores(c["principal"].as_str().unwrap()) + .await + .unwrap(); + ok &= k == c["kills"].as_f64().unwrap(); + } + ok + } + }) + .await; + let total = assert_board_matches_cells(&world).await; + eprintln!("bots: {stats:?}, kills on disk {total}"); + assert_eq!(total, stats.committed, "one kill per committed fact"); + let (_, rebuild) = http(demo.addr, "POST", "/dev/mobpit/leaderboard/rebuild", None).await; + assert_eq!(rebuild["matchesCells"], true, "{rebuild}"); + assert_eq!(rebuild["identicalTop"], true, "{rebuild}"); + assert_eq!(rebuild["events"].as_u64(), Some(total)); + + // Read routes. + let (_, board) = http( + demo.addr, + "GET", + "/dev/mobpit/leaderboard?member=bot-0", + None, + ) + .await; + assert_eq!(board["snapshot"]["backend"], "memory"); + assert!(!board["snapshot"]["kills"].as_array().unwrap().is_empty()); + let (_, crawlers) = http(demo.addr, "GET", "/dev/mobpit/crawlers", None).await; + assert_eq!( + crawlers["crawlers"] + .as_array() + .unwrap() + .iter() + .map(|c| c["kills"].as_u64().unwrap()) + .sum::(), + total + ); + + stop.send(()).unwrap(); + demo.task.await.unwrap().unwrap(); + let _ = std::fs::remove_dir_all(dir); +} + +struct Binary { + child: Child, + addr: SocketAddr, +} + +async fn start_binary(dir: &Path) -> Binary { + let mut child = Command::new(env!("CARGO_BIN_EXE_game-demos")) + .args([ + "mobpit", + "--port", + "0", + "--dev", + "--secret", + SECRET, + "--data-dir", + ]) + .arg(dir) + .env_remove("REDIS_URL") + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn game-demos"); + let stdout = child.stdout.take().unwrap(); + let mut lines = + tokio::io::BufReader::new(tokio::process::ChildStdout::from_std(stdout).unwrap()).lines(); + let addr = loop { + let line = tokio::time::timeout(Duration::from_secs(60), lines.next_line()) + .await + .expect("server start") + .unwrap() + .expect("server exited"); + if let Some(url) = line.strip_prefix("LISTENING http://") { + break url.parse().unwrap(); + } + }; + // Keep draining stdout so the child never blocks on a full pipe. + tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} }); + Binary { child, addr } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn kill_dash_nine_mid_fight_keeps_settled_facts_exactly_once() { + let dir = temp_dir("crash"); + let mut first = start_binary(&dir).await; + let ws = format!("ws://{}", first.addr); + // Settle some kills at full speed, then slow storage so facts are in + // flight at the moment of the crash. + let addr = first.addr; + let fight = tokio::spawn(run_bots(bot_config(ws, 5, Duration::from_secs(30)), spin)); + let start = Instant::now(); + let before = loop { + tokio::time::sleep(Duration::from_millis(200)).await; + let (_, stats) = http(addr, "GET", "/dev/mobpit/stats", None).await; + if stats["sink"]["committed"].as_u64().unwrap_or(0) >= 3 { + break stats; + } + assert!( + start.elapsed() < Duration::from_secs(25), + "no kills: {stats}" + ); + }; + http( + addr, + "POST", + "/dev/mobpit/storage", + Some(json!({ "latencyMs": 1500 })), + ) + .await; + let start = Instant::now(); + let at_crash = loop { + tokio::time::sleep(Duration::from_millis(100)).await; + let (_, stats) = http(addr, "GET", "/dev/mobpit/stats", None).await; + if stats["sink"]["inSink"].as_u64().unwrap_or(0) >= 1 + || start.elapsed() > Duration::from_secs(10) + { + break stats; + } + }; + first.child.kill().unwrap(); // SIGKILL: no graceful drain + first.child.wait().unwrap(); + fight.abort(); + let settled_before = at_crash["sink"]["committed"].as_u64().unwrap(); + let in_flight = at_crash["pending"].as_u64().unwrap(); + assert!(settled_before >= before["sink"]["committed"].as_u64().unwrap()); + + // Restart on the same directory: the settled facts are all there; of the + // in-flight ones each either committed atomically or not at all. + let mut second = start_binary(&dir).await; + let (_, crawlers) = http(second.addr, "GET", "/dev/mobpit/crawlers", None).await; + let total: u64 = crawlers["crawlers"] + .as_array() + .unwrap() + .iter() + .map(|c| c["kills"].as_u64().unwrap()) + .sum(); + eprintln!( + "crash: settled {settled_before}, in flight {in_flight}, durable after restart {total}" + ); + assert!( + total >= settled_before && total <= settled_before + in_flight, + "settled {settled_before} ≤ durable {total} ≤ settled + in flight ({in_flight})" + ); + // The board was rebuilt from the cells at boot. + let (_, board) = http(second.addr, "GET", "/dev/mobpit/leaderboard", None).await; + let board_kills: f64 = board["snapshot"]["kills"] + .as_array() + .unwrap() + .iter() + .map(|r| r["score"].as_f64().unwrap()) + .sum(); + assert_eq!(board_kills as u64, total, "{board}"); + second.child.kill().unwrap(); + second.child.wait().unwrap(); + + // Replay a pre-crash fact (same key, same input) against the files: the + // command ledger replays it, nothing is credited twice. + let recent = &before["recent"].as_array().unwrap()[0]; + let key = recent["key"].as_str().unwrap(); + let principal = recent["receipt"]["crawler"].as_str().unwrap(); + let world = MobPitWorld::open(WorldOptions::new(&dir)).unwrap(); + let cell = world.cells().get(principal).unwrap(); + let kills_before = cell.load().await.unwrap().unwrap().kills; + let replay = world + .fact_sink() + .commit(&kill_fact(key, principal, recent["input"].clone())) + .await + .unwrap(); + assert!(replay.replayed, "pre-crash key replays after the restart"); + assert_eq!(replay.payload, recent["receipt"], "original receipt"); + assert_eq!(cell.load().await.unwrap().unwrap().kills, kills_before); + let _ = std::fs::remove_dir_all(dir); +} + +/// Same projection on Redis sorted sets. Skipped unless `REDIS_URL` is set +/// (`docker compose up -d redis`, then `REDIS_URL=redis://127.0.0.1:6379`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn redis_board_projects_and_rebuilds_when_redis_url_is_set() { + let Ok(url) = std::env::var("REDIS_URL") else { + eprintln!("REDIS_URL unset: skipping the Redis leaderboard test"); + return; + }; + let dir = temp_dir("redis"); + let mut options = WorldOptions::new(&dir); + options.redis_url = Some(url); + options.redis_prefix = format!("mobpit-test-{}", random_hex(8)); + let world = MobPitWorld::open(options).unwrap(); + assert_eq!(world.board().backend(), "redis"); + let sink = world.fact_sink(); + for (i, tier) in [1u8, 3].into_iter().enumerate() { + let input = json!({ "mob": format!("pit-1/m{i}"), "tier": tier, "name": "Rae" }); + let fact = kill_fact(&format!("kill:r:pit-1:m{i}:0"), "guest-rae", input); + sink.commit(&fact).await.unwrap(); + assert!(sink.commit(&fact).await.unwrap().replayed); + } + eventually("redis board", Duration::from_secs(10), || async { + world.board().scores("guest-rae").await.unwrap() == (2.0, 70.0) + }) + .await; + let report = world.rebuild_board().await.unwrap(); + assert_eq!(report["matchesCells"], true, "{report}"); + assert_eq!(report["identicalTop"], true, "{report}"); + let (kills, xp) = world.board().boards(); + for board in [kills, xp] { + world.board().store().reset(board).await.unwrap(); + } + let _ = std::fs::remove_dir_all(dir); +} From 0626e5f4c7356d6434bbd10012ee54f3d4ebee2a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:47:40 -0500 Subject: [PATCH 149/484] feat(examples): add Mob Pit and Leaderboard browser clients Mob Pit page (Babylon): mobs with HP bars and filling telegraph rings, blade swing and cone, kill popups that turn into "+XP saved" when the fact settles, XP bar from the cell, pending-facts vs tick-interval graph and a slow-storage toggle. Leaderboard page (DOM) observes the pit zone for pushed top-10 snapshots, shows your rank and neighbours and triggers a rebuild from cell events. Headless Node tests drive both against the real binary, including a restart on the same data. Refs [[tasks/gr-p10-demos]] --- examples/game/client/index.html | 2 + examples/game/client/leaderboard/index.html | 39 ++ examples/game/client/mobpit/index.html | 14 + examples/game/client/src/leaderboard/main.ts | 146 ++++++ .../game/client/src/leaderboard/style.css | 92 ++++ examples/game/client/src/mobpit/client.ts | 258 +++++++++++ examples/game/client/src/mobpit/main.ts | 419 ++++++++++++++++++ examples/game/client/src/mobpit/style.css | 120 +++++ examples/game/client/tests/helpers/mobpit.mjs | 39 ++ .../tests/leaderboard-headless.test.mjs | 63 +++ .../client/tests/mobpit-headless.test.mjs | 88 ++++ examples/game/client/vite.config.ts | 2 +- 12 files changed, 1281 insertions(+), 1 deletion(-) create mode 100644 examples/game/client/leaderboard/index.html create mode 100644 examples/game/client/mobpit/index.html create mode 100644 examples/game/client/src/leaderboard/main.ts create mode 100644 examples/game/client/src/leaderboard/style.css create mode 100644 examples/game/client/src/mobpit/client.ts create mode 100644 examples/game/client/src/mobpit/main.ts create mode 100644 examples/game/client/src/mobpit/style.css create mode 100644 examples/game/client/tests/helpers/mobpit.mjs create mode 100644 examples/game/client/tests/leaderboard-headless.test.mjs create mode 100644 examples/game/client/tests/mobpit-headless.test.mjs diff --git a/examples/game/client/index.html b/examples/game/client/index.html index 8cca69766..d1254c6d6 100644 --- a/examples/game/client/index.html +++ b/examples/game/client/index.html @@ -12,6 +12,8 @@

distributed_game demos

Each demo runs its own server: examples/game/run.sh <demo>. The page for the running demo works; the others need their server.

  • Arena — fixed tick, binary deltas, interest management, prediction + reconciliation, interpolation.
  • +
  • Mob Pit — authoritative combat, non-blocking durable facts into SQLite cells, slow storage, crash recovery.
  • +
  • Leaderboard — kills/XP sorted-set boards projected from the cells, pushed live, rebuilt from events (runs with Mob Pit).
diff --git a/examples/game/client/leaderboard/index.html b/examples/game/client/leaderboard/index.html new file mode 100644 index 000000000..05d404dbd --- /dev/null +++ b/examples/game/client/leaderboard/index.html @@ -0,0 +1,39 @@ + + + + + + Leaderboard Demo + + + + +
+
+

Mob Pit leaderboard

+

+ Kill facts committed to the Crawler cells are projected into two sorted-set boards (fire-and-forget, + idempotent apply keys). The top 10 is pushed over the zone connection (observer); your rank is read on each push. + Play the pit ↗ +

+
+
connecting…
+
+

Kills

+

XP

+
+

You

+
—
+

Live pit

+ +
+
+
+ + Throws the boards away and replays every Crawler cell's durable event history into staging boards, then promotes them atomically. +

+			
+
+ + + diff --git a/examples/game/client/mobpit/index.html b/examples/game/client/mobpit/index.html new file mode 100644 index 000000000..f7f53dac3 --- /dev/null +++ b/examples/game/client/mobpit/index.html @@ -0,0 +1,14 @@ + + + + + + Mob Pit Demo + + + + +
+ + + diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts new file mode 100644 index 000000000..f81e66e64 --- /dev/null +++ b/examples/game/client/src/leaderboard/main.ts @@ -0,0 +1,146 @@ +/** + * Leaderboard page: observes the pit zone (no avatar), renders the pushed + * top-10 snapshots, reads your rank and neighbours on every push, and + * triggers a rebuild from the cells' event history. + */ +import { HALF } from '../arena/movement.ts'; +import { DevApi } from '../shared/dev-api.ts'; +import { + createBoardWatcher, + DEFAULT_ZONE, + KIND, + MobPitApi, + TIERS, + type BoardPosition, + type BoardRow, + type BoardSnapshot +} from '../mobpit/client.ts'; + +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const api = new DevApi(); +const pitApi = new MobPitApi(); +const watcher = createBoardWatcher({ api }); +const { client } = watcher; + +const $ = (k: string) => document.querySelector(`[data-k="${k}"]`) as HTMLElement; +const status = $('status'); +let pushes = 0; + +function table(el: HTMLElement, rows: readonly BoardRow[], unit: string, me: string | undefined): void { + if (rows.length === 0) { + el.innerHTML = 'No kills yet — go to the pit.'; + return; + } + el.replaceChildren( + ...rows.map((row) => { + const tr = document.createElement('tr'); + if (row.member === me) tr.className = 'me'; + for (const [text, cls] of [ + [`#${row.rank}`, 'num'], + [row.name, ''], + [`${row.score} ${unit}`, 'num'] + ] as const) { + const td = document.createElement('td'); + td.textContent = text; + if (cls !== '') td.className = cls; + tr.append(td); + } + return tr; + }) + ); +} + +function position(label: string, unit: string, p: BoardPosition | undefined, me: string): string { + if (p === undefined || p.rank === null) return `
${label}: not ranked yet
`; + const around = p.around + .map((r) => `${r.member === me ? '' : ''}#${r.rank} ${escape(r.name)} ${r.score}${r.member === me ? '' : ''}`) + .join('
'); + return `
${label}: #${p.rank} (${p.score} ${unit})
${around}
`; +} + +function escape(text: string): string { + return text.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`); +} + +async function render(board: BoardSnapshot): Promise { + pushes += 1; + const me = api.last?.principal; + table($('kills'), board.kills, 'kills', me); + table($('xp'), board.xp, 'XP', me); + const bg = board.background; + status.textContent = + `push #${pushes} · version ${board.version} · store ${board.backend ?? '?'} · ${board.members ?? 0} ranked` + + (bg === undefined ? '' : ` · background updates: ${bg.applied} applied, ${bg.dropped} dropped, ${bg.failed} failed`); + status.classList.add('flash'); + setTimeout(() => status.classList.remove('flash'), 120); + if (me === undefined) return; + try { + const { me: mine } = await pitApi.leaderboard(me); + $('me').innerHTML = + `
${escape(api.last?.name ?? me)}
` + + position('Kills', 'kills', mine?.kills, me) + + position('XP', 'XP', mine?.xp, me); + } catch (error) { + $('me').textContent = `rank lookup failed: ${String(error)}`; + } +} + +watcher.on((board) => void render(board)); + +$('rebuild').addEventListener('click', async () => { + const button = $('rebuild') as HTMLButtonElement; + button.disabled = true; + $('report').textContent = 'rebuilding…'; + try { + const r = await pitApi.rebuild(); + $('report').textContent = + `${r.events} kill events from ${r.crawlers} cells → ${r.applied} board changes in ${r.tookMs.toFixed(1)} ms (${r.backend})\n` + + `top 10 identical to before: ${r.identicalTop ? 'yes ✓' : 'no (live board had drifted — now healed)'}\n` + + `every cell's kills/XP equal its board scores: ${r.matchesCells ? 'yes ✓' : `NO: ${JSON.stringify(r.mismatches)}`}`; + } catch (error) { + $('report').textContent = `rebuild failed: ${String(error)}`; + } finally { + button.disabled = false; + } +}); + +// ---- live minimap of the observed zone ---- +const map = $('map') as HTMLCanvasElement; +function drawMap(): void { + const ctx = map.getContext('2d'); + if (ctx !== null) { + const s = map.width / (HALF * 2); + const px = (v: number) => (v + HALF) * s; + ctx.clearRect(0, 0, map.width, map.height); + for (const e of client.render()) { + const x = Number(e.fields.x ?? 0); + const y = Number(e.fields.y ?? 0); + if (e.kindName === KIND.pillar) { + ctx.fillStyle = '#5d5566'; + ctx.beginPath(); + ctx.arc(px(x), map.height - px(y), Number(e.fields.r ?? 1) * s, 0, Math.PI * 2); + ctx.fill(); + } else if (e.kindName === KIND.mob) { + ctx.fillStyle = TIERS[Number(e.fields.tier ?? 1)]?.color ?? '#9ad16b'; + ctx.fillRect(px(x) - 3, map.height - px(y) - 3, 6, 6); + } else if (e.kindName === KIND.player) { + ctx.fillStyle = e.fields.dead ? '#555' : '#f2a65a'; + ctx.beginPath(); + ctx.arc(px(x), map.height - px(y), 4, 0, Math.PI * 2); + ctx.fill(); + } + } + } + requestAnimationFrame(drawMap); +} +requestAnimationFrame(drawMap); + +declare global { + interface Window { + leaderboard?: unknown; + } +} +window.leaderboard = { client, api, pitApi, watcher }; + +client.observe(zone).catch((error: unknown) => (status.textContent = `failed: ${String(error)}`)); diff --git a/examples/game/client/src/leaderboard/style.css b/examples/game/client/src/leaderboard/style.css new file mode 100644 index 000000000..5aec51a9c --- /dev/null +++ b/examples/game/client/src/leaderboard/style.css @@ -0,0 +1,92 @@ +/* Leaderboard page (DOM only). */ +.lb { + max-width: 1100px; + margin: 0 auto; + padding: 16px; + box-sizing: border-box; +} +.lb h1 { + margin: 0 0 4px; + font-size: 18px; +} +.lb h2 { + margin: 0 0 6px; + font-size: 14px; +} +.lb a { + color: var(--accent); +} +.lb-hint { + color: var(--muted); +} +.lb-status { + margin: 10px 0; + padding: 6px 10px; + border-radius: 6px; + background: var(--panel); + transition: background 0.4s ease; +} +.lb-status.flash { + background: #1f3a2a; + transition: none; +} +.lb-grid { + display: grid; + grid-template-columns: 1fr 1fr 260px; + gap: 12px; +} +.lb-grid section { + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); +} +.lb table { + width: 100%; + border-collapse: collapse; +} +.lb td { + padding: 3px 4px; + border-bottom: 1px solid #222a35; +} +.lb td.num { + text-align: right; +} +.lb tr.me td { + color: var(--accent); + font-weight: bold; +} +.lb-me canvas { + width: 100%; + max-width: 240px; + aspect-ratio: 1; + background: #0b0d12; + border-radius: 6px; +} +.lb-me .pos { + margin-bottom: 8px; +} +.lb-rebuild { + margin-top: 12px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); +} +.lb-rebuild button { + font: inherit; + padding: 6px 12px; + margin-right: 8px; + border: 1px solid #3a4556; + border-radius: 6px; + background: #1a2230; + color: var(--text); + cursor: pointer; +} +.lb-rebuild pre { + margin: 8px 0 0; + white-space: pre-wrap; +} +@media (max-width: 860px) { + .lb-grid { + grid-template-columns: 1fr; + } +} diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts new file mode 100644 index 000000000..f72b3ecbf --- /dev/null +++ b/examples/game/client/src/mobpit/client.ts @@ -0,0 +1,258 @@ +/** + * Mob Pit networking without rendering (Node-testable): the `GameClient` + * with the Arena's predicted movement for the own capsule, the zone's JSON + * events folded into a small state object, and the `/dev/mobpit/*` routes. + * + * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the + * fact is only *queued*) → `saved` (to the killer, when the durable cell + * commit settled; `waitedMs` shows the storage latency) → `profile`. + */ +import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; + +import { encodeMoveInput, predictPlayer, type MoveInput } from '../arena/movement.ts'; +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; + +export const DEFAULT_ZONE = 'pit-1'; +/** Event type ids (server `mobpit::zone::EVENT_*`). */ +export const EVENT = { hello: 1, profile: 2, kill: 3, saved: 4, board: 5, died: 6 } as const; +/** Input bits: the Arena's dash (1) plus attack. */ +export const BUTTON_DASH = 1; +export const BUTTON_ATTACK = 2; +export const KIND = { player: 'player', mob: 'mob', pillar: 'pillar', pit: 'pit' } as const; +export const MOB_STATE = ['idle', 'chase', 'windup', 'recover', 'return'] as const; +/** Per tier: display name, body radius, telegraph radius (server `tier_stats`). */ +export const TIERS: Readonly> = { + 1: { name: 'Grunt', radius: 0.5, tele: 1.8, color: '#9ad16b' }, + 2: { name: 'Brute', radius: 0.7, tele: 2.2, color: '#b48cf2' }, + 3: { name: 'Elite', radius: 0.8, tele: 2.6, color: '#ff6b6b' } +}; + +export type PitHello = Readonly<{ entity: number; half: number; boot: string; attackRange: number; attackArcCos: number }>; +export type Profile = Readonly<{ + xp: number; + level: number; + kills: number; + levelXp: number; + nextLevelXp: number; + source: 'cell' | 'settled'; +}>; +export type KillEvent = Readonly<{ key: string; mob: number; tier: number; x: number; y: number; killer: number; killerName: string }>; +export type SavedEvent = Readonly<{ + key: string; + ok: boolean; + replayed?: boolean; + xp?: number; + totalXp?: number; + kills?: number; + level?: number; + waitedMs: number; + x: number; + y: number; + error?: string; +}>; +export type BoardRow = Readonly<{ rank: number; member: string; name: string; score: number }>; +export type BoardSnapshot = Readonly<{ + version: number; + backend?: 'memory' | 'redis'; + members?: number; + kills: BoardRow[]; + xp: BoardRow[]; + background?: Readonly<{ enqueued: number; applied: number; dropped: number; failed: number }>; + lastRebuild?: RebuildReport | null; +}>; +export type RebuildReport = Readonly<{ + backend: string; + crawlers: number; + events: number; + applied: number; + duplicates: number; + identicalTop: boolean; + matchesCells: boolean; + mismatches: unknown[]; + tookMs: number; +}>; +export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: BoardRow[] }>; + +export type MobPitEvents = { + hello: PitHello; + profile: Profile; + kill: KillEvent; + saved: SavedEvent; + board: BoardSnapshot; + died: { respawnMs: number }; +}; + +export type MobPitClient = Readonly<{ + client: GameClient; + hello(): PitHello | undefined; + profile(): Profile | undefined; + board(): BoardSnapshot | undefined; + /** Kills by me whose fact has not settled yet (key → event). */ + unsaved: ReadonlyMap; + /** Resolves on the first hello. */ + ready: Promise; + on(type: K, handler: (value: MobPitEvents[K]) => void): () => void; +}>; + +export type MobPitClientOptions = Readonly<{ + api: DevApi; + base?: string; + socket?: GameSocketFactory; +}>; + +export function createMobPitClient(options: MobPitClientOptions): MobPitClient { + const ease = { mode: 'ease', durationMs: 150 } as const; + const snap = { mode: 'snap' } as const; + const replace = { mode: 'replace' } as const; + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 500, + inputDtMs: 1000 / 30, + prediction: { + encodeInput: (input) => encodeMoveInput(input), + predict: (fields, input) => predictPlayer(fields, input), + corrections: { + [KIND.player]: { + x: ease, + y: ease, + vx: snap, + vy: snap, + dash: snap, + cd: snap, + name: replace, + hp: replace, + face: replace, + swing: replace, + level: replace, + dead: replace + } + } + } + }); + const listeners = new Map void>>(); + const emit = (type: string, value: unknown) => { + for (const handler of listeners.get(type) ?? []) handler(value); + }; + let hello: PitHello | undefined; + let profile: Profile | undefined; + let board: BoardSnapshot | undefined; + const unsaved = new Map(); + let resolveReady: (h: PitHello) => void = () => undefined; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + onJsonEvent(client, EVENT.hello, (value) => { + hello = value; + client.setControlledEntity(value.entity); + resolveReady(value); + emit('hello', value); + }); + onJsonEvent(client, EVENT.profile, (value) => { + profile = value; + emit('profile', value); + }); + onJsonEvent(client, EVENT.kill, (value) => { + if (hello !== undefined && value.killer === hello.entity) unsaved.set(value.key, value); + emit('kill', value); + }); + onJsonEvent(client, EVENT.saved, (value) => { + unsaved.delete(value.key); + emit('saved', value); + }); + onJsonEvent(client, EVENT.board, (value) => { + board = value; + emit('board', value); + }); + onJsonEvent<{ respawnMs: number }>(client, EVENT.died, (value) => emit('died', value)); + + return { + client, + hello: () => hello, + profile: () => profile, + board: () => board, + unsaved, + ready, + on(type, handler) { + let set = listeners.get(type); + if (set === undefined) listeners.set(type, (set = new Set())); + const h = handler as (value: unknown) => void; + set.add(h); + return () => set.delete(h); + } + }; +} + +/** Observer-only client for the leaderboard page (no prediction, no inputs). */ +export function createBoardWatcher(options: MobPitClientOptions): Readonly<{ + client: GameClient; + board(): BoardSnapshot | undefined; + on(handler: (value: BoardSnapshot) => void): () => void; +}> { + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 1000 + }); + let board: BoardSnapshot | undefined; + const handlers = new Set<(value: BoardSnapshot) => void>(); + onJsonEvent(client, EVENT.board, (value) => { + board = value; + for (const h of handlers) h(value); + }); + return { + client, + board: () => board, + on(handler) { + handlers.add(handler); + return () => handlers.delete(handler); + } + }; +} + +/** `/dev/mobpit/*` (dev only; none of these take an identity or a reward). */ +export class MobPitApi { + readonly base: string; + + constructor(base = '') { + this.base = base; + } + + storage(): Promise<{ latencyMs: number }> { + return this.#json('/dev/mobpit/storage'); + } + + /** Artificial latency in front of every durable commit (server-wide). */ + setStorage(latencyMs: number): Promise<{ latencyMs: number }> { + return this.#json('/dev/mobpit/storage', { latencyMs }); + } + + stats(): Promise> { + return this.#json('/dev/mobpit/stats'); + } + + crawlers(): Promise<{ crawlers: { principal: string; name: string; xp: number; kills: number; level: number }[] }> { + return this.#json('/dev/mobpit/crawlers'); + } + + leaderboard(member?: string): Promise<{ snapshot: BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { + const query = member === undefined ? '' : `?member=${encodeURIComponent(member)}`; + return this.#json(`/dev/mobpit/leaderboard${query}`); + } + + rebuild(): Promise { + return this.#json('/dev/mobpit/leaderboard/rebuild', {}); + } + + async #json(path: string, body?: unknown): Promise { + const response = await fetch(`${this.base}${path}`, { + method: body === undefined ? 'GET' : 'POST', + headers: body === undefined ? undefined : { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body) + }); + if (!response.ok) throw new Error(`${path}: HTTP ${response.status} ${await response.text()}`); + return (await response.json()) as T; + } +} diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts new file mode 100644 index 000000000..4089a1503 --- /dev/null +++ b/examples/game/client/src/mobpit/main.ts @@ -0,0 +1,419 @@ +/** + * Mob Pit page: Babylon scene over `createMobPitClient`. + * + * What to look at: kill a mob (Space) and watch the grey "saving…" popup + * turn into "+XP saved ✓" when the durable cell commit settles. Toggle + * *Slow storage* (L): every commit now takes 1.5 s — the pending-facts graph + * climbs while the tick graph stays flat at ~33 ms, because the zone never + * waits for storage. Kill the server (`kill -9`), restart it, reload: your + * XP and kills come back from the cell. + */ +import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { Color3 } from '@babylonjs/core/Maths/math.color'; +import { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import type { RenderedEntity } from '@hops-ops/distributed/game'; + +import { HALF, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { createStage, material, toWorld } from '../shared/scene.ts'; +import { + BUTTON_ATTACK, + BUTTON_DASH, + createMobPitClient, + DEFAULT_ZONE, + KIND, + MobPitApi, + TIERS, + type BoardSnapshot, + type KillEvent +} from './client.ts'; + +const SLOW_MS = 1500; +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const storedName = (() => { + try { + return localStorage.getItem('game-demos.name') ?? undefined; + } catch { + return undefined; + } +})(); +const name = params.get('name') ?? storedName; + +const api = new DevApi({ name: () => name }); +const pitApi = new MobPitApi(); +const pit = createMobPitClient({ api }); +const { client } = pit; + +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: HALF, background: '#120f14' }); +const { scene } = stage; + +const hud = new Hud({ + title: 'Mob Pit', + hint: 'WASD move · Space attack · E dash · L slow storage. Kills are durable facts; the tick never waits for them.', + client, + devApi: api +}); +let slow = false; +hud.toggle(`Slow storage (${SLOW_MS} ms per commit)`, false, (on) => { + slow = on; + pitApi.setStorage(on ? SLOW_MS : 0).catch((e: unknown) => hud.row('Storage', `failed: ${String(e)}`)); +}, 'l'); +pitApi + .storage() + .then((s) => (slow = s.latencyMs > 0)) + .catch(() => undefined); + +// ---- side panels: XP bar, durable facts graph, mini leaderboard ---- +const xpPanel = div('pit-xp', document.body); +const xpLabel = div('pit-xp-label', xpPanel); +const xpBar = div('pit-xp-bar', xpPanel); +const xpFill = div('pit-xp-fill', xpBar); +const factsPanel = div('pit-facts', document.body); +factsPanel.innerHTML = `

Durable facts

+
0 pending 0 saved ✓
+ +
■ pending facts ■ tick interval (ms)
+
+

Leaderboard open ↗

+
    `; +const graph = factsPanel.querySelector('canvas') as HTMLCanvasElement; +const field = (k: string) => factsPanel.querySelector(`[data-k="${k}"]`) as HTMLElement; +const deathBanner = div('pit-death', document.body); +deathBanner.style.display = 'none'; + +function div(className: string, parent: HTMLElement): HTMLDivElement { + const d = document.createElement('div'); + d.className = className; + parent.append(d); + return d; +} + +// ---- materials and templates ---- +const mats = { + me: material(scene, 'me', '#6cc4ff'), + other: material(scene, 'other', '#f2a65a'), + dead: material(scene, 'dead', '#555555', 0.4), + pillar: material(scene, 'pillar', '#5d5566'), + blade: material(scene, 'blade', '#e8eef7'), + swing: material(scene, 'swing', '#ffffff', 0.18), + hpBack: material(scene, 'hp-back', '#1b1b1b'), + hpFill: material(scene, 'hp-fill', '#e04848'), + tele: material(scene, 'tele', '#ff3b3b', 0.25), + teleFill: material(scene, 'tele-fill', '#ff3b3b', 0.45) +}; +for (const m of [mats.swing, mats.tele, mats.teleFill, mats.hpFill]) m.emissiveColor = m.diffuseColor.clone(); +mats.blade.emissiveColor = new Color3(0.6, 0.6, 0.7); +const tierMats = new Map(); +for (const [tier, t] of Object.entries(TIERS)) tierMats.set(Number(tier), material(scene, `mob-${tier}`, t.color)); + +type PlayerVisual = { kind: 'player'; body: Mesh; blade: Mesh; arc: Mesh; nose: Mesh }; +type MobVisual = { kind: 'mob'; body: Mesh; hpBack: Mesh; hpFill: Mesh; ring: Mesh; fill: Mesh; tier: number }; +type PillarVisual = { kind: 'pillar'; body: Mesh }; +type Visual = PlayerVisual | MobVisual | PillarVisual; +const visuals = new Map(); + +function flatDisc(id: string, radius: number, mat: StandardMaterial, arc = 1): Mesh { + const disc = MeshBuilder.CreateDisc(id, { radius, arc, tessellation: 48, sideOrientation: Mesh.DOUBLESIDE }, scene); + disc.rotation.x = Math.PI / 2; + disc.material = mat; + disc.isPickable = false; + return disc; +} + +function createPlayer(entity: RenderedEntity, mine: boolean): PlayerVisual { + const body = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + body.material = mine ? mats.me : mats.other; + const nose = MeshBuilder.CreateBox(`${entity.key}-nose`, { width: 0.35, height: 0.15, depth: 0.2 }, scene); + nose.material = mats.blade; + const blade = MeshBuilder.CreateBox(`${entity.key}-blade`, { width: 1.6, height: 0.08, depth: 0.14 }, scene); + blade.material = mats.blade; + // Swing wedge: 120° (the server's cone), flat on the floor. + const arc = flatDisc(`${entity.key}-arc`, 2.2 + PLAYER_RADIUS, mats.swing, 1 / 3); + return { kind: 'player', body, blade, arc, nose }; +} + +function createMob(entity: RenderedEntity): MobVisual { + const tier = num(entity, 'tier') || 1; + const t = TIERS[tier] ?? TIERS[1]!; + const body = + tier === 3 + ? MeshBuilder.CreateCylinder(entity.key, { diameterTop: 0, diameterBottom: t.radius * 2, height: 2, tessellation: 6 }, scene) + : MeshBuilder.CreateBox(entity.key, { width: t.radius * 2, depth: t.radius * 2, height: tier === 2 ? 1.5 : 0.9 }, scene); + body.material = tierMats.get(tier) ?? mats.other; + const hpBack = MeshBuilder.CreatePlane(`${entity.key}-hpb`, { width: 1.2, height: 0.14 }, scene); + hpBack.material = mats.hpBack; + hpBack.billboardMode = Mesh.BILLBOARDMODE_ALL; + const hpFill = MeshBuilder.CreatePlane(`${entity.key}-hpf`, { width: 1.16, height: 0.1 }, scene); + hpFill.material = mats.hpFill; + hpFill.billboardMode = Mesh.BILLBOARDMODE_ALL; + const ring = flatDisc(`${entity.key}-tele`, t.tele, mats.tele); + const fill = flatDisc(`${entity.key}-tele-fill`, t.tele, mats.teleFill); + return { kind: 'mob', body, hpBack, hpFill, ring, fill, tier }; +} + +function visualFor(entity: RenderedEntity, mine: boolean): Visual { + let visual = visuals.get(entity.key); + if (visual !== undefined) return visual; + switch (entity.kindName) { + case KIND.mob: + visual = createMob(entity); + break; + case KIND.pillar: { + const r = num(entity, 'r'); + const body = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2.4, tessellation: 24 }, scene); + body.material = mats.pillar; + visual = { kind: 'pillar', body }; + break; + } + default: + visual = createPlayer(entity, mine); + } + visuals.set(entity.key, visual); + return visual; +} + +function dispose(visual: Visual): void { + for (const mesh of Object.values(visual)) if (mesh instanceof Mesh) mesh.dispose(); +} + +function num(entity: RenderedEntity | { fields: RenderedEntity['fields'] }, f: string): number { + const v = entity.fields[f]; + return typeof v === 'number' ? v : typeof v === 'boolean' ? Number(v) : 0; +} + +// ---- kill / saved popups (DOM labels anchored to invisible meshes) ---- +type Popup = { mesh: Mesh; until: number }; +const popups = new Map(); +let popupSeq = 0; + +function popup(key: string, x: number, y: number, text: string, className: string, ttlMs: number): void { + let p = popups.get(key); + if (p === undefined) { + const mesh = MeshBuilder.CreateBox(`popup-${popupSeq++}`, { size: 0.01 }, scene); + mesh.isVisible = false; + mesh.position.copyFrom(toWorld(x, y, 1.2)); + p = { mesh, until: 0 }; + popups.set(key, p); + } + p.until = performance.now() + ttlMs; + stage.labels.set(`popup:${key}`, p.mesh, text, 0.6, `pit-pop ${className}`); +} + +pit.on('kill', (kill: KillEvent) => { + const mine = kill.killer === pit.hello()?.entity; + const tier = TIERS[kill.tier]?.name ?? 'Mob'; + if (mine) popup(kill.key, kill.x, kill.y, `${tier} slain · saving…`, 'pending', 60_000); + else popup(kill.key, kill.x, kill.y, `${kill.killerName} slew a ${tier}`, 'other', 2000); +}); +let savedCount = 0; +pit.on('saved', (saved) => { + if (saved.ok) { + savedCount += 1; + const waited = saved.waitedMs >= 200 ? ` (${(saved.waitedMs / 1000).toFixed(1)} s)` : ''; + popup(saved.key, saved.x, saved.y, `+${saved.xp} XP saved ✓${waited}`, 'saved', 2500); + } else { + popup(saved.key, saved.x, saved.y, `save failed: ${saved.error ?? '?'}`, 'failed', 4000); + } +}); +pit.on('died', (d) => { + deathBanner.textContent = 'You died — respawning…'; + deathBanner.style.display = ''; + setTimeout(() => (deathBanner.style.display = 'none'), d.respawnMs); +}); +pit.on('board', (board) => renderBoard(board)); + +function renderBoard(board: BoardSnapshot): void { + const me = api.last?.principal; + const list = field('board'); + list.replaceChildren( + ...board.kills.slice(0, 5).map((row) => { + const li = document.createElement('li'); + li.textContent = `${row.name} — ${row.score} kills`; + if (row.member === me) li.className = 'me'; + return li; + }) + ); +} + +// ---- durable-facts graph ---- +type Sample = { pending: number; tick: number }; +const samples: Sample[] = []; +let lastSampleAt = 0; + +function drawGraph(): void { + const ctx = graph.getContext('2d'); + if (ctx === null) return; + const { width, height } = graph; + ctx.clearRect(0, 0, width, height); + ctx.strokeStyle = '#2a3240'; + ctx.beginPath(); + ctx.moveTo(0, height - 0.5); + ctx.lineTo(width, height - 0.5); + ctx.stroke(); + const maxPending = Math.max(4, ...samples.map((s) => s.pending)); + const series = (pick: (s: Sample) => number, max: number, color: string) => { + ctx.strokeStyle = color; + ctx.lineWidth = 2; + ctx.beginPath(); + samples.forEach((s, i) => { + const x = (i / 119) * width; + const y = height - 2 - (Math.min(pick(s), max) / max) * (height - 6); + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); + ctx.stroke(); + }; + series((s) => s.tick, 100, '#6cc4ff'); + series((s) => s.pending, maxPending, '#f2a65a'); + ctx.fillStyle = '#8793a6'; + ctx.font = '10px monospace'; + ctx.fillText(`pending max ${maxPending}`, 4, 10); + ctx.fillText('tick 0–100 ms', width - 80, 10); +} + +// ---- input ---- +const sampler = new InputSampler(); +const commandFrames = new FixedRate(30); + +function sendCommandFrame(): void { + const s = sampler.sample(); + const move = cameraRelative(s, stage.cameraForward()); + const input: MoveInput = { + mx: toAxis(move.x), + my: toAxis(move.y), + buttons: (s.action ? BUTTON_ATTACK : 0) | (s.alt ? BUTTON_DASH : 0) + }; + client.sendInput(input); +} + +// ---- frame ---- +stage.onFrame((now, dtMs) => { + commandFrames.advance(now, sendCommandFrame); + const hello = pit.hello(); + const authority = client.authority; + const rendered = client.render(); + const seen = new Set(); + let me: { x: number; y: number; hp: number; dead: boolean } | undefined; + let stats: RenderedEntity | undefined; + for (const entity of rendered) { + if (entity.kindName === KIND.pit) { + stats = entity; + continue; + } + const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; + const visual = visualFor(entity, mine); + const x = num(entity, 'x'); + const y = num(entity, 'y'); + seen.add(entity.key); + const visible = !entity.stale || visual.kind === 'pillar'; + if (visual.kind === 'pillar') { + visual.body.position.copyFrom(toWorld(x, y, 1.2)); + } else if (visual.kind === 'mob') { + const height = visual.tier === 3 ? 1 : visual.tier === 2 ? 0.75 : 0.45; + visual.body.position.copyFrom(toWorld(x, y, height)); + visual.body.rotation.y = -num(entity, 'face'); + const hp = num(entity, 'hp') / 100; + const top = height * 2 + 0.35; + visual.hpBack.position.copyFrom(toWorld(x, y, top)); + visual.hpFill.position.copyFrom(toWorld(x, y, top)); + visual.hpFill.scaling.x = Math.max(0.001, hp); + const tele = num(entity, 'tele') / 255; + const winding = num(entity, 'state') === 2; + visual.ring.setEnabled(visible && winding); + visual.fill.setEnabled(visible && winding); + if (winding) { + visual.ring.position.copyFrom(toWorld(x, y, 0.03)); + visual.fill.position.copyFrom(toWorld(x, y, 0.04)); + visual.fill.scaling.setAll(Math.max(0.05, tele)); + } + visual.body.scaling.setAll(winding ? 1 + 0.15 * tele : 1); + for (const m of [visual.body, visual.hpBack, visual.hpFill]) m.setEnabled(visible); + } else { + const dead = num(entity, 'dead') > 0; + const face = num(entity, 'face'); + const swing = num(entity, 'swing'); + visual.body.position.copyFrom(toWorld(x, y, 0.9)); + visual.body.material = dead ? mats.dead : mine ? mats.me : mats.other; + visual.nose.position.copyFrom(toWorld(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3)); + visual.nose.rotation.y = -face; + // Blade sweeps through the 120° cone while `swing` counts down (6 → 0). + const sweep = swing > 0 ? ((6 - swing) / 6) * (Math.PI * 2 / 3) - Math.PI / 3 : -Math.PI / 2.5; + const a = face + sweep; + visual.blade.position.copyFrom(toWorld(x + Math.cos(a) * 0.8, y + Math.sin(a) * 0.8, 1.0)); + visual.blade.rotation.y = -a; + visual.blade.setEnabled(visible && !dead); + visual.arc.setEnabled(visible && swing > 0); + if (swing > 0) { + visual.arc.position.copyFrom(toWorld(x, y, 0.05)); + // Disc arcs start at +x and run counter-clockwise; centre it on `face`. + visual.arc.rotation.y = -(face - Math.PI / 3); + } + const label = `${String(entity.fields.name ?? '')} · L${num(entity, 'level')} · ${num(entity, 'hp')} HP`; + stage.labels.set(entity.key, visual.body, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); + visual.body.setEnabled(visible); + visual.nose.setEnabled(visible && !dead); + if (mine) me = { x, y, hp: num(entity, 'hp'), dead }; + } + } + for (const [key, visual] of visuals) { + if (seen.has(key)) continue; + dispose(visual); + stage.labels.delete(key); + visuals.delete(key); + } + for (const [key, p] of popups) { + if (now < p.until) continue; + p.mesh.dispose(); + stage.labels.delete(`popup:${key}`); + popups.delete(key); + } + if (me !== undefined) stage.follow(me.x, me.y, dtMs); + + // ---- HUD ---- + hud.frame({ entities: rendered.length }); + const pending = stats === undefined ? 0 : num(stats, 'pending'); + const tickMs = stats === undefined ? 0 : num(stats, 'tickMs'); + const tickMax = stats === undefined ? 0 : num(stats, 'tickMaxMs'); + const slowMs = stats === undefined ? 0 : num(stats, 'slowMs'); + hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); + hud.row('HP', me === undefined ? '—' : me.dead ? 'dead' : String(me.hp)); + hud.row('Facts pending (zone)', String(pending)); + hud.row('Facts saved (zone)', String(stats === undefined ? 0 : num(stats, 'committed'))); + hud.row('My unsaved kills', String(pit.unsaved.size)); + hud.row('Storage latency', slowMs > 0 ? `${slowMs} ms (slow)` : 'normal'); + hud.row('Server tick interval', `${tickMs.toFixed(1)} ms avg · ${tickMax.toFixed(1)} max`); + hud.row('Tick work', `${stats === undefined ? 0 : num(stats, 'workUs')} µs`); + const profile = pit.profile(); + if (profile !== undefined) { + const span = Math.max(1, profile.nextLevelXp - profile.levelXp); + xpFill.style.width = `${Math.min(100, ((profile.xp - profile.levelXp) / span) * 100).toFixed(1)}%`; + xpLabel.textContent = `Level ${profile.level} · ${profile.xp} XP · ${profile.kills} kills · next level at ${profile.nextLevelXp} XP (${profile.source === 'cell' ? 'loaded from cell' : 'saved'})`; + } else { + xpLabel.textContent = 'Loading your Crawler cell…'; + } + field('pending').textContent = String(pending); + field('saved').textContent = String(savedCount); + field('note').textContent = slow || slowMs > 0 + ? `Storage is slow: each commit waits ${slowMs} ms. Pending climbs, the tick does not.` + : 'Storage is fast: facts settle within a tick or two.'; + if (now - lastSampleAt > 250) { + lastSampleAt = now; + samples.push({ pending, tick: tickMs }); + if (samples.length > 120) samples.shift(); + drawGraph(); + } +}); + +declare global { + interface Window { + mobpit?: unknown; + } +} +window.mobpit = { client, api, pitApi, pit, scene }; + +client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/mobpit/style.css b/examples/game/client/src/mobpit/style.css new file mode 100644 index 000000000..31836839c --- /dev/null +++ b/examples/game/client/src/mobpit/style.css @@ -0,0 +1,120 @@ +/* Mob Pit panels (layered over the shared HUD/stage styles). */ +.pit-xp { + position: fixed; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + width: min(560px, calc(100% - 32px)); + padding: 8px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-xp-label { + margin-bottom: 4px; + color: var(--muted); +} +.pit-xp-bar { + height: 10px; + border-radius: 5px; + background: #2a3240; + overflow: hidden; +} +.pit-xp-fill { + height: 100%; + width: 0; + background: linear-gradient(90deg, #f2c94c, #f2a65a); + transition: width 0.3s ease; +} +.pit-facts { + position: fixed; + top: 12px; + right: 12px; + width: 284px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-facts h2 { + margin: 0 0 6px; + font-size: 13px; +} +.pit-facts h2 a { + float: right; + font-weight: normal; + color: var(--accent); +} +.pit-facts canvas { + width: 100%; + height: 90px; + display: block; +} +.pit-big { + margin-bottom: 6px; +} +.pit-big span { + font-size: 22px; +} +.pit-big span[data-k='pending'] { + color: #f2a65a; +} +.pit-big span[data-k='saved'] { + color: #7ee787; + margin-left: 8px; +} +.pit-legend { + margin: 4px 0; + font-size: 11px; +} +.c-pending { + color: #f2a65a; +} +.c-tick { + color: #6cc4ff; +} +.pit-note { + margin: 4px 0 10px; + color: var(--muted); +} +.pit-facts ol { + margin: 0; + padding-left: 20px; +} +.pit-facts li.me { + color: var(--accent); +} +.pit-death { + position: fixed; + top: 40%; + left: 50%; + transform: translate(-50%, -50%); + padding: 12px 20px; + border-radius: 8px; + background: rgba(120, 20, 20, 0.85); + font-size: 18px; +} +.label.pit-pop { + font-weight: bold; +} +.label.pit-pop.pending { + color: #b9c0cc; +} +.label.pit-pop.saved { + color: #7ee787; + background: rgba(10, 40, 16, 0.75); +} +.label.pit-pop.failed { + color: #ff7b72; +} +.label.pit-pop.other { + color: var(--muted); + font-weight: normal; +} +@media (max-width: 900px) { + .pit-facts { + top: auto; + bottom: 72px; + width: 220px; + } +} diff --git a/examples/game/client/tests/helpers/mobpit.mjs b/examples/game/client/tests/helpers/mobpit.mjs new file mode 100644 index 000000000..919ef00ca --- /dev/null +++ b/examples/game/client/tests/helpers/mobpit.mjs @@ -0,0 +1,39 @@ +/** + * Headless Mob Pit helpers: a throwaway data dir and a scripted hunter that + * walks to the nearest mob, faces it and swings until `done()` is true. + */ +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { BUTTON_ATTACK } from '../../src/mobpit/client.ts'; +import { sleep } from './demo-server.mjs'; + +export function tempDataDir() { + return mkdtempSync(join(tmpdir(), 'mobpit-js-')); +} + +/** Hunt mobs (one command frame per 30 Hz tick) until `done()` or timeout. */ +export async function hunt(pit, done, timeoutMs = 45_000) { + const { client } = pit; + const deadline = Date.now() + timeoutMs; + while (!done()) { + if (Date.now() > deadline) throw new Error('hunt timed out'); + const rendered = client.render(); + const me = rendered.find((e) => e.id === pit.hello()?.entity && e.kindName === 'player'); + const mobs = rendered.filter((e) => e.kindName === 'mob' && !e.stale); + let input = { mx: 0, my: 0, buttons: 0 }; + if (me !== undefined && mobs.length > 0 && !me.fields.dead) { + const target = mobs + .map((m) => ({ m, d: Math.hypot(m.fields.x - me.fields.x, m.fields.y - me.fields.y) })) + .sort((a, b) => a.d - b.d)[0]; + const dx = target.m.fields.x - me.fields.x; + const dy = target.m.fields.y - me.fields.y; + const near = target.d < 1.9; + const k = (near ? 40 : 127) / Math.max(target.d, 1e-3); + input = { mx: Math.round(dx * k), my: Math.round(dy * k), buttons: near ? BUTTON_ATTACK : 0 }; + } + client.sendInput(input); + await sleep(1000 / 30); + } +} diff --git a/examples/game/client/tests/leaderboard-headless.test.mjs b/examples/game/client/tests/leaderboard-headless.test.mjs new file mode 100644 index 000000000..e1588f13d --- /dev/null +++ b/examples/game/client/tests/leaderboard-headless.test.mjs @@ -0,0 +1,63 @@ +/** + * Headless Leaderboard: a hunter scores kills in the pit, an observer + * receives pushed board snapshots whose scores equal the Crawler cells; + * rebuilding from the cells' events yields the identical board. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createBoardWatcher, createMobPitClient, MobPitApi } from '../src/mobpit/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { memoryStorage, startDemo, until } from './helpers/demo-server.mjs'; +import { hunt, tempDataDir } from './helpers/mobpit.mjs'; + +test('board pushes match the cells and rebuild is identical', { timeout: 600_000 }, async () => { + const server = await startDemo('leaderboard', { env: { MOBPIT_DATA_DIR: tempDataDir() } }); + const clients = []; + try { + const storage = memoryStorage(); + const api = new DevApi({ base: server.httpUrl, name: () => 'Ranker', storage }); + const pitApi = new MobPitApi(server.httpUrl); + + // Observer page first: it gets the current (empty) snapshot on observe. + const watcher = createBoardWatcher({ api: new DevApi({ base: server.httpUrl, storage }), base: server.httpUrl }); + clients.push(watcher.client); + const pushes = []; + watcher.on((b) => pushes.push(b)); + await watcher.client.observe('pit-1'); + await until(() => pushes.length >= 1, 5_000, 'initial board push'); + assert.equal(watcher.board().backend, 'memory'); + + const pit = createMobPitClient({ api, base: server.httpUrl }); + clients.push(pit.client); + await pit.client.connect('pit-1'); + await pit.ready; + const me = api.last.principal; + await hunt(pit, () => (pit.profile()?.kills ?? 0) >= 2); + const profile = pit.profile(); + + // Pushed, not polled: the observer sees my kills without asking. + const row = (b, board) => b[board].find((r) => r.member === me); + await until(() => row(watcher.board(), 'kills')?.score === profile.kills, 10_000, 'pushed kills'); + assert.equal(row(watcher.board(), 'kills').name, 'Ranker'); + assert.equal(row(watcher.board(), 'xp').score, profile.xp); + const { crawlers } = await pitApi.crawlers(); + assert.deepEqual(crawlers.map((c) => [c.principal, c.kills, c.xp]), [[me, profile.kills, profile.xp]]); + + const { me: mine } = await pitApi.leaderboard(me); + assert.equal(mine.kills.rank, 1); + assert.equal(mine.kills.around[0].member, me); + + const top = JSON.stringify([watcher.board().kills, watcher.board().xp]); + const report = await pitApi.rebuild(); + assert.equal(report.events, profile.kills); + assert.equal(report.matchesCells, true); + assert.equal(report.identicalTop, true); + const after = (await pitApi.leaderboard()).snapshot; + assert.equal(JSON.stringify([after.kills, after.xp]), top, 'rebuild from events = live board'); + await until(() => watcher.board().lastRebuild?.events === profile.kills, 5_000, 'rebuild pushed'); + } finally { + for (const c of clients) c.close(); + await server.stop(); + } +}); diff --git a/examples/game/client/tests/mobpit-headless.test.mjs b/examples/game/client/tests/mobpit-headless.test.mjs new file mode 100644 index 000000000..59dec60f5 --- /dev/null +++ b/examples/game/client/tests/mobpit-headless.test.mjs @@ -0,0 +1,88 @@ +/** + * Headless Mob Pit (Node, real `game-demos mobpit` binary): join → profile + * read from the Crawler cell → kill a mob → the fact settles ("saved") with + * server-decided XP → slow storage makes the settlement wait while the tick + * stays flat → restart the server on the same data dir → XP is still there. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createMobPitClient, MobPitApi } from '../src/mobpit/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { memoryStorage, startDemo, until } from './helpers/demo-server.mjs'; +import { hunt, tempDataDir } from './helpers/mobpit.mjs'; + +const XP = new Set([10, 25, 60]); + +test('kills become durable facts without stalling the tick, and survive a restart', { timeout: 600_000 }, async () => { + const dataDir = tempDataDir(); + const env = { MOBPIT_DATA_DIR: dataDir }; + const storage = memoryStorage(); + let server = await startDemo('mobpit', { env }); + const clients = []; + try { + const api = new DevApi({ base: server.httpUrl, name: () => 'Hunter', storage }); + const pitApi = new MobPitApi(server.httpUrl); + const pit = createMobPitClient({ api, base: server.httpUrl }); + clients.push(pit.client); + const welcome = await pit.client.connect('pit-1'); + assert.deepEqual(welcome.schema.kinds.map((k) => k.name), ['player', 'mob', 'pillar', 'pit']); + await pit.ready; + await until(() => pit.profile() !== undefined, 5_000, 'profile from the cell'); + assert.equal(pit.profile().source, 'cell'); + assert.equal(pit.profile().kills, 0); + + // First kill at normal speed. + const saved = []; + const kills = []; + pit.on('saved', (s) => saved.push(s)); + pit.on('kill', (k) => k.killer === pit.hello().entity && kills.push(k)); + await hunt(pit, () => saved.length >= 1); + assert.ok(saved[0].ok && XP.has(saved[0].xp), JSON.stringify(saved[0])); + assert.equal(saved[0].key, kills[0].key); + assert.match(saved[0].key, /^kill:[0-9a-f]+:pit-1:m\d+:\d+$/); + // One swing can kill several mobs: wait until every own kill settled. + await until(() => pit.unsaved.size === 0 && saved.length === kills.length, 5_000, 'settlements'); + await until(() => pit.profile().source === 'settled' && pit.profile().kills === kills.length, 5_000, `profile after settlement ${JSON.stringify(pit.profile())}`); + + // Slow storage: the next kill stays unsaved for ~1.5 s, the tick does not slow down. + assert.equal((await pitApi.setStorage(1500)).latencyMs, 1500); + const pitStats = () => pit.client.render().find((e) => e.kindName === 'pit')?.fields; + const fastKills = kills.length; + await hunt(pit, () => kills.length > fastKills); + await until(() => (pitStats()?.pending ?? 0) >= 1, 2_000, 'pending fact replicated'); + assert.ok(pit.unsaved.size >= 1, 'kill not yet saved'); + const ticks = []; + const sampleUntil = Date.now() + 900; + while (Date.now() < sampleUntil) { + ticks.push(pitStats()?.tickMaxMs ?? 0); + await new Promise((r) => setTimeout(r, 100)); + } + assert.ok(Math.max(...ticks) < 80, `tick interval stays ~33 ms while storage is slow: ${ticks}`); + await until(() => saved.length === kills.length, 15_000, 'slow settlements'); + assert.ok(saved[fastKills].waitedMs >= 1400, `waited ${saved[fastKills].waitedMs} ms`); + await pitApi.setStorage(0); + await until(() => pit.profile().kills === kills.length, 5_000, 'profile'); + const before = pit.profile(); + + // Graceful restart on the same data dir (the smoke test covers kill -9): + // the guest token stays valid (secret persisted in the data dir) and + // the profile is read back from the cell. + pit.client.close(); + await server.stop(); + server = await startDemo('mobpit', { env }); + const again = createMobPitClient({ api: new DevApi({ base: server.httpUrl, storage }), base: server.httpUrl }); + clients.push(again.client); + await again.client.connect('pit-1'); + await until(() => again.profile() !== undefined, 5_000, 'profile after restart'); + assert.equal(again.profile().source, 'cell'); + assert.equal(again.profile().kills, before.kills); + assert.equal(again.profile().xp, before.xp); + const crawlers = (await new MobPitApi(server.httpUrl).crawlers()).crawlers; + assert.equal(crawlers.length, 1); + assert.equal(crawlers[0].kills, kills.length); + } finally { + for (const c of clients) c.close(); + await server.stop(); + } +}); diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts index 62082e6cb..866f663ff 100644 --- a/examples/game/client/vite.config.ts +++ b/examples/game/client/vite.config.ts @@ -5,7 +5,7 @@ import { resolve } from 'node:path'; import { defineConfig } from 'vite'; -const DEMOS = ['arena']; +const DEMOS = ['arena', 'mobpit', 'leaderboard']; const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; export default defineConfig({ From abe6edd652141c5d886819751be21d73fc8f7e3e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:47:41 -0500 Subject: [PATCH 150/484] docs(examples): document Mob Pit, Leaderboard and crash recovery Register both demos in run.sh (MOBPIT_DATA_DIR defaults to examples/game/.data/mobpit, ignored) and explain the fact flow, slow storage, the kill -9 exactly-once story and the leaderboard design. Refs [[tasks/gr-p10-demos]] --- examples/game/.gitignore | 2 + examples/game/README.md | 127 ++++++++++++++++++++++++++++++++++++++- examples/game/run.sh | 10 ++- 3 files changed, 134 insertions(+), 5 deletions(-) create mode 100644 examples/game/.gitignore diff --git a/examples/game/.gitignore b/examples/game/.gitignore new file mode 100644 index 000000000..fdd3cf487 --- /dev/null +++ b/examples/game/.gitignore @@ -0,0 +1,2 @@ +# Mob Pit / Leaderboard durable cells (run.sh default MOBPIT_DATA_DIR). +/.data/ diff --git a/examples/game/README.md b/examples/game/README.md index 2b3828194..ed42db29f 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -9,6 +9,8 @@ guests and lets any page change the network simulation. | Demo | Run | Mechanic it demonstrates | |---|---|---| | **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | +| **Mob Pit** | `./run.sh mobpit` | Authoritative melee combat vs. 12 telegraphing mobs; kills are **non-blocking durable facts** committed exactly once into per-player native SQLite cells (`cell-sqlite`); "slow storage" toggle (tick stays flat, pending facts climb); `kill -9` crash recovery | +| **Leaderboard** | `./run.sh leaderboard` | Same server as Mob Pit: kills/XP sorted-set boards (in-memory or Redis) fed fire-and-forget with idempotent apply keys, top 10 pushed live, your rank + neighbours, rebuild from the cells' event history | `./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. @@ -69,12 +71,17 @@ examples/game/ src/main.rs `game-demos ` subcommands src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events src/arena/ Arena zone + movement.rs (twin of client movement.ts) - tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs + src/mobpit/ Mob Pit zone, Crawler cell aggregate, fact sink, leaderboards, dev routes + tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs, + mobpit_smoke.rs (facts, slow storage, kill -9 recovery, boards) client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css src/arena/ client.ts (headless), main.ts (Babylon), movement.ts - tests/ movement-parity, arena-headless (+ helpers/demo-server.mjs) + src/mobpit/ client.ts (headless + /dev/mobpit API), main.ts (Babylon), style.css + src/leaderboard/ main.ts (DOM page over the observer connection), style.css + tests/ movement-parity, arena-headless, mobpit-headless, + leaderboard-headless (+ helpers/demo-server.mjs, helpers/mobpit.mjs) ``` The server crate is excluded from the root workspace (`Cargo.toml` @@ -82,6 +89,119 @@ The server crate is excluded from the root workspace (`Cargo.toml` `Cargo.lock`; the client depends on the SDK via `file:../../../js` (the built `dist`). +## Mob Pit + +```sh +examples/game/run.sh mobpit # → http://localhost:5173/mobpit/ +examples/game/run.sh leaderboard # same server → http://localhost:5173/leaderboard/ +``` + +Controls: WASD / stick move (the Arena's predicted step, same floor and +pillars), **Space** attack (120° cone, 2.2 m), **E** dash, **L** slow +storage. Mobs wander near home, aggro within 7 m, chase, stop and show a red +**telegraph ring** that fills for 0.8 s, then hit everyone inside it. Grunts +(green, 10 XP), brutes (purple, 25 XP) and the elite (red, 60 XP) respawn 4 s +after dying. Level `n` starts at `40·(n−1)²` XP. + +**One kill, end to end** (`server/src/mobpit/`): + +1. `zone.rs`, tick N: the mob's HP reaches 0. The zone calls + `ctx.emit_fact_for(killer, Fact::new("kill:{boot}:{zone}:m{id}:{gen}", + "crawler.record_kill", {mob, tier, name}))` and broadcasts a `kill` event. + `emit_fact_for` only enqueues: the host binds the killer's **verified + ticket principal**; the zone never awaits storage. Backpressure (256 + unsettled facts) parks facts in a backlog retried next tick. +2. The zone's fact worker (`GameServer::with_fact_sink`) runs + `store::CrawlerFactSink`: optional artificial latency, then + `CellFactSink::commit` into the killer's own cell + (`$MOBPIT_DATA_DIR/Crawler%3A{principal}.sqlite3`, `AggregateCell::from_store` + over `CellStreamStore::open_sqlite`). The command id is + `sha256(service ‖ fact key)`, so the cell's command ledger turns any repeat + of the key into a replay of the stored receipt. +3. `crawler.rs`: `crawler.record_kill` takes the principal from the trusted + session (`x-user-id`) and **decides the XP from the tier**; the input has + no identity or XP field and unknown fields are rejected. Event, ledger + receipt and snapshot commit in one SQLite transaction (`synchronous=FULL`). +4. Tick N+k: `Zone::on_fact_settled` sends the killer `saved` (with + `waitedMs`) and `profile`; the popup turns from "saving…" to + "+XP saved ✓". The sink also hands the kill to the leaderboard + (fire-and-forget). + +The read path: on join the zone asks a background task to load the player's +cell and sends `profile` (`source: "cell"`) a few ticks later. + +**Slow storage.** The *Slow storage* toggle (`POST /dev/mobpit/storage +{latencyMs: 1500}`) delays every commit by 1.5 s. Facts commit in order per +zone, so pending climbs when you kill faster than one per 1.5 s; the top-right +graph shows pending (orange) rising and settling while the tick interval +(blue, `pit` entity `tickMs`/`tickMaxMs`) stays at ~33 ms and the HUD's tick +work stays in microseconds. This is the fix for a world that froze while +awaiting durable commits: the tick only enqueues. + +**Crash recovery** (`kill -9`): + +```sh +examples/game/run.sh mobpit # play, get some kills, toggle slow storage, kill more +kill -9 $(lsof -t -iTCP:2567 -sTCP:LISTEN) # in another terminal, mid-fight +examples/game/run.sh mobpit # restart (same .data/mobpit), reload the page +``` + +The ticket secret is persisted in the data dir (`dev-ticket-secret`), so the +page's guest token still maps to the same principal, and the profile comes +back from the cell. What survives: + +- **Settled facts** (you saw "saved ✓"): durable. The commit was acknowledged + only after the SQLite transaction (event + ledger receipt) was fsynced. +- **Facts in flight** at the crash: each is either fully committed (the + transaction finished; you just never saw the settlement) or not at all + (rolled back with the WAL) — never half-applied, never twice. The zone's + in-memory state (mob HP, positions, the fact queue) dies with the process, + so an uncommitted kill is lost like any other unsaved world state; there is + no zone-side outbox (see `distributed_game` README, *Facts on dispose*). +- **Retries and replays** of the same key (the worker's retry after a + timeout, or a re-emitted fact) replay the stored receipt through the + ledger: `replayed: true`, nothing credited twice. Fact keys contain a + per-process `boot` id because zone ticks and mob generations restart at 0. + +`tests/mobpit_smoke.rs` proves it with the real binary: bots fight, storage is +made slow, the server gets `SIGKILL` with facts in flight, restarts on the +same directory; then `settled ≤ durable kills ≤ settled + in flight`, the +board (rebuilt at boot) equals the cells, and re-committing a pre-crash fact +(same key and input) against the files returns the original receipt with +`replayed: true` and unchanged kills. + +## Leaderboard + +`server/src/mobpit/board.rs`. Kills project into two boards, +`mobpit.kills` (+1) and `mobpit.xp` (+xp), through `LeaderboardProjector`. + +- **Store**: `InMemoryLeaderboard` by default; `RedisLeaderboard` when + `REDIS_URL` is set (`docker compose up -d redis` at the repo root, then + `REDIS_URL=redis://127.0.0.1:6379 examples/game/run.sh leaderboard`). +- **Fire-and-forget**: after a commit the sink calls + `BackgroundLeaderboard::submit`, which never awaits the store; a full queue + or a Redis outage drops (and counts) the update. +- **Idempotent**: each kill becomes a `DomainEventOccurrence` + (`capture_external`, source `mobpit.crawler-cell` / `Crawler:{principal}` / + event sequence / `mob_killed`). The id is identical whether it comes from + the live receipt, a ledger replay of the fact, or the cell's event history, + and the store applies `"{id}#{change}"` at most once per board. +- **Rebuild** (button, `POST /dev/mobpit/leaderboard/rebuild`, and at every + server start): read every cell's durable event stream, project it into the + staging boards, promote atomically, then compare each cell's kills/XP with + its scores (`matchesCells`) and the top 10 with the previous one + (`identicalTop`). Dropped live updates are healed here. +- **Push**: the zone broadcasts the top-10 snapshot (`board` event) whenever + it changes; the leaderboard page joins the pit as an **observer** (no + avatar) and renders those pushes; on each push it reads your rank and + neighbours from `GET /dev/mobpit/leaderboard?member=…` (ranks are public; + the page knows its principal from its own ticket). + +Dev routes (`--dev` only, none takes an identity or a reward): +`GET|POST /dev/mobpit/storage`, `GET /dev/mobpit/stats` (sink counters, +pending, recent commits), `GET /dev/mobpit/crawlers` (every cell on disk), +`GET /dev/mobpit/leaderboard[?member=]`, `POST /dev/mobpit/leaderboard/rebuild`. + ## Adding a demo 1. **Server** — `server/src//mod.rs`: the zone plus a unit struct @@ -92,6 +212,9 @@ The server crate is excluded from the root workspace (`Cargo.toml` - Display names: `guests.name(&ctx.player(p)?.principal)` in `on_join`. - Low-rate events: `common::send_json_event` / `broadcast_json_event`. - Signed quantities that must rest at zero: `FieldType::quant_centered`. + - State shared by the zones and demo-specific dev routes (a durable + store, a leaderboard): build both in `common::spawn_with` / + `common::run_with` (see `mobpit::spawn` / `mobpit::run`). 2. **Smoke test** — `server/tests/_smoke.rs`: `common::spawn::` on `127.0.0.1:0` with `DemoOptions::dev(secret)` and `distributed_game::bots::run_bots` (custom `encoder` for your input). diff --git a/examples/game/run.sh b/examples/game/run.sh index 770a5e4b5..22bdceb3d 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -3,12 +3,15 @@ # # ./run.sh arena build what is needed, start the arena server # (dev routes on) + Vite, print the URL +# ./run.sh mobpit same for Mob Pit; `leaderboard` = same server, board page # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS) # ./run.sh list demos this script knows # # Env: GAME_DEMOS_PORT (server, default 2567), GAME_DEMOS_CLIENT_PORT (Vite, # default 5173), DG_NET_LATENCY_MS / DG_NET_JITTER_MS / DG_NET_LOSS (initial -# server NetSim; the HUD sliders change it live). +# server NetSim; the HUD sliders change it live), MOBPIT_DATA_DIR (Mob Pit / +# Leaderboard cells, default examples/game/.data/mobpit), REDIS_URL (Redis +# leaderboard instead of in-memory). set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -16,7 +19,8 @@ REPO="$(cd "$HERE/../.." && pwd)" SERVER="$HERE/server" CLIENT="$HERE/client" BIN="$SERVER/target/debug/game-demos" -DEMOS=(arena) +DEMOS=(arena mobpit leaderboard) +export MOBPIT_DATA_DIR="${MOBPIT_DATA_DIR:-$HERE/.data/mobpit}" log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } @@ -92,7 +96,7 @@ smoke() { case "${1:-}" in smoke) smoke ;; list) printf '%s\n' "${DEMOS[@]}" ;; - "" | -h | --help | help) sed -n '2,13p' "$0" ;; + "" | -h | --help | help) sed -n '2,14p' "$0" ;; *) if [[ " ${DEMOS[*]} " == *" $1 "* ]]; then run_demo "$1" From 6faa0a400653032c6044d1b734ab232ea7a13066 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:51:45 -0500 Subject: [PATCH 151/484] fix(game): admit a handoff return when source and target share a host The return path re-presents the transfer ticket to the source zone. When the refusing target ran on the same host, its nonce replay cache had already recorded the nonce, so the return failed with Replayed and the player fell back to a fresh join. The issuer's transfer registry keeps the return single use, so it now gets its own replay key. Refs [[tasks/gr-p10-demos]] --- distributed_game/src/net/mod.rs | 12 ++++++++- distributed_game/tests/world/main.rs | 39 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 96b2c28ed..0cfb6ae7e 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -1485,6 +1485,10 @@ where let (reply_tx, reply_rx) = oneshot::channel(); // Transfer record to settle once the zone answered: (issuer, nonce). let mut reserved: Option<(String, String)> = None; + // A failed handoff returning to its source presents a ticket whose nonce + // the target may have recorded on this same host; the issuer's transfer + // registry (`Return`) keeps it single use, so it gets its own replay key. + let mut returning = false; let cmd = if hello.reconnect_token.is_empty() { let now = unix_now(); let verified = match cfg.ticket_key.verify_ticket(&hello.ticket, now) { @@ -1515,6 +1519,7 @@ where { return reject(socket, error::UNAUTHORIZED, e).await; } + returning = true; let never_reached = std::mem::replace(&mut transfer.claims.zone, zone_id.clone()); transfer.source_zone = never_reached; @@ -1524,8 +1529,13 @@ where (transfer.claims.clone(), Some(transfer)) } }; + let replay_key = if returning { + format!("return:{}", claims.nonce) + } else { + claims.nonce.clone() + }; let replay = inner.nonces.lock().expect("nonces").check_and_insert( - &claims.nonce, + &replay_key, claims.expires_at, now, ); diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index 09d04e353..94fffd53b 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -378,6 +378,45 @@ async fn refused_handoff_returns_to_source_with_carried_state() { .is_err()); } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn refused_handoff_returns_to_a_source_on_the_same_host() { + // Source and target share a host (and its nonce replay cache): the + // target saw the ticket first, the return must still be admitted once. + let (a, _b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "A")], + realm_factory(&[("realm.east", "realm.west")], &["realm.west"]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &a.addr.zone_url("realm.east"), + &ticket("ana", "realm.east", "s1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_HANDOFF).await; + let transfer = loop { + if let Some(ServerMessage::Handoff { + transfer_ticket, .. + }) = control(&mut ana).await + { + break transfer_ticket; + } + }; + match join_url(&a.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::REJECTED), + other => panic!("expected rejection: {:?}", other.map(|c| c.welcome)), + } + let back = join_url(&a.addr.zone_url("realm.east"), &transfer, "").await; + assert!(back.is_ok(), "return admitted: {:?}", back.err()); + // The return is single use. + assert!(join_url(&a.addr.zone_url("realm.east"), &transfer, "") + .await + .is_err()); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn boss_defeat_tiers_up_to_parent_and_grandparent_across_hosts() { let (a, b, _dir) = two_hosts( From c9a45dc7099eacf27347feba1b352fd872fb9163 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:53:17 -0500 Subject: [PATCH 152/484] fix(examples): aim the gallery camera and raise its max rewind createPickingRay needs Babylon's Ray side-effect import, and setTarget on the first-person ArcRotateCamera recomputed its radius; keep alpha, beta and radius instead. The 600 ms clamp keeps compensation working up to ~250 ms one-way latency so the on/off contrast shows on the sliders. Refs [[tasks/gr-p10-demos]] --- examples/game/README.md | 2 +- examples/game/client/src/gallery/main.ts | 3 ++- examples/game/client/tests/gallery-headless.test.mjs | 10 +++++----- examples/game/server/src/gallery/mod.rs | 2 +- examples/game/server/tests/gallery_smoke.rs | 6 +++--- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/examples/game/README.md b/examples/game/README.md index c8e8fab96..44672e570 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -45,7 +45,7 @@ client's interpolation delay adapts to `rtt / 2 + 2 patches + 2 × jitter` (the SDK clock estimates the server's *present*, so a fixed 100 ms would ask for states not yet received); each shot carries `delay = tickTime(client_tick) - renderTime`, so the server rewinds to exactly what was on screen. Beyond -`gallery::MAX_REWIND_MS` (500 ms of view age, ≈ 200 ms one way) shots are +`gallery::MAX_REWIND_MS` (600 ms of view age, ≈ 250 ms one way) shots are clamped and reported as such. ## Architecture diff --git a/examples/game/client/src/gallery/main.ts b/examples/game/client/src/gallery/main.ts index 3cbd94f8e..6b851d9ab 100644 --- a/examples/game/client/src/gallery/main.ts +++ b/examples/game/client/src/gallery/main.ts @@ -24,6 +24,7 @@ import { Hud } from '../shared/hud.ts'; import { InputSampler } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; import { createGalleryClient, DEFAULT_ZONE, KIND, targetPosition, type ShotRecord, type Vec3 } from './client.ts'; +import '@babylonjs/core/Culling/ray'; // side effect: scene.createPickingRay import './gallery.css'; const params = new URLSearchParams(location.search); @@ -187,7 +188,7 @@ stage.onFrame((now) => { const hello = gallery.hello(); if (hello !== undefined) { const eye = toWorld(hello.eye[0], hello.eye[1], hello.eye[2]); - if (!camera.target.equals(eye)) camera.setTarget(eye); + if (!camera.target.equals(eye)) camera.setTarget(eye, false, false, true); // keep alpha/beta/radius } const s = sampler.sample(); if (s.action && !actionWasDown) { diff --git a/examples/game/client/tests/gallery-headless.test.mjs b/examples/game/client/tests/gallery-headless.test.mjs index 2fa1e810c..d7ff9bc36 100644 --- a/examples/game/client/tests/gallery-headless.test.mjs +++ b/examples/game/client/tests/gallery-headless.test.mjs @@ -55,7 +55,7 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew try { await gallery.client.connect('gallery-1'); const hello = await gallery.ready; - assert.equal(hello.maxRewindMs, 500); + assert.equal(hello.maxRewindMs, 600); await until(() => gallery.targets().length === 6, 5_000, 'targets'); // 100 ms one way (RTT ≈ 200 ms): the client draws targets ~300 ms in the past. @@ -69,13 +69,13 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew assert.ok(on.hits >= 18, `compensated hits ${on.hits}/20`); assert.equal(on.clamped, 0); const meanAge = on.ages.reduce((a, b) => a + b, 0) / on.ages.length; - assert.ok(meanAge > 250 && meanAge < 500, `rewind age ${meanAge}`); + assert.ok(meanAge > 250 && meanAge < 600, `rewind age ${meanAge}`); const off = await volley(gallery, 20, false); assert.ok(off.hits <= 6, `uncompensated hits ${off.hits}/20`); assert.ok(off.ages.every((a) => a === 0), 'no rewind without compensation'); - // 300 ms one way: the view is ~700 ms old, more than the 500 ms clamp. + // 300 ms one way: the view is ~700 ms old, more than the 600 ms clamp. await api.setNetSim({ latencyMs: 300, jitterMs: 0, loss: 0 }); await until(() => zone.connection.clock.rtt > 550, 15_000, 'rtt 600'); await until(() => gallery.targets() && gallery.delay.settled(zone, 10), 20_000, 'adaptive delay 2'); @@ -84,8 +84,8 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew `comp on ${on.hits}/20 (mean rewind ${meanAge.toFixed(0)} ms) · off ${off.hits}/20 · 300 ms: clamped ${far.clamped}/10, hits ${far.hits}/10` ); assert.ok(far.clamped >= 9, `clamped ${far.clamped}/10`); - assert.ok(far.requested.every((r) => r > 520), `requested ${far.requested}`); - assert.ok(far.ages.every((a) => a <= 501), `ages ${far.ages}`); + assert.ok(far.requested.every((r) => r > 620), `requested ${far.requested}`); + assert.ok(far.ages.every((a) => a <= 601), `ages ${far.ages}`); assert.equal(gallery.stats.resolved, 50); assert.equal(gallery.stats.predictedHits, 50); diff --git a/examples/game/server/src/gallery/mod.rs b/examples/game/server/src/gallery/mod.rs index fcb888a44..a33250675 100644 --- a/examples/game/server/src/gallery/mod.rs +++ b/examples/game/server/src/gallery/mod.rs @@ -52,7 +52,7 @@ pub const STATION_SPACING: f32 = 3.0; /// Stations on the firing line. pub const STATIONS: u32 = 5; /// Furthest a shot is rewound (anti-cheat clamp). -pub const MAX_REWIND_MS: u64 = 500; +pub const MAX_REWIND_MS: u64 = 600; /// Hitscan range (m). pub const RANGE: f32 = 80.0; /// Number of targets. diff --git a/examples/game/server/tests/gallery_smoke.rs b/examples/game/server/tests/gallery_smoke.rs index 5a2af3fd1..2dcc2b812 100644 --- a/examples/game/server/tests/gallery_smoke.rs +++ b/examples/game/server/tests/gallery_smoke.rs @@ -127,10 +127,10 @@ fn rewound_shots_hit_what_the_shooter_saw() { let s = rig.shoot(5, 0, 0, FLAG_NO_COMP); assert_eq!(s.hits, 2); // Claiming 2 s of delay is clamped to MAX_REWIND_MS: aiming 2 s back - // misses, aiming at the clamp (15 ticks = 500 ms) still hits. - let s = rig.shoot(5, 15, 2000, 0); + // misses, aiming at the clamp (18 ticks = 600 ms) still hits. + let s = rig.shoot(5, 18, 2000, 0); assert_eq!((s.shots, s.hits, s.clamped), (4, 3, 1)); - let s = rig.shoot(2, 15, 2000, 0); + let s = rig.shoot(2, 18, 2000, 0); assert_eq!((s.shots, s.clamped), (5, 2)); } From 07572680e435e6836b77e10da1ea64a2e50c06f1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 16:55:00 -0500 Subject: [PATCH 153/484] feat(examples): add The Freeze world-version barrier demo Three zones on two server processes (the primary spawns the second host) share data-driven content packs per version. An admin route runs WorldCoordinator::rollout: every zone freezes behind a diegetic SYSTEM overlay, inputs are dropped and counted, the pack is staged, and zones resume with change notes. Hard mode reloads every client; safe-room mode lets a pinned old client play on until it enters the hub gate; a ritual makes a zone refuse freeze_ready and the rollout aborts. Refs [[tasks/gr-p10-demos]] --- examples/game/README.md | 38 + examples/game/client/freeze/index.html | 13 + examples/game/client/index.html | 1 + examples/game/client/src/freeze/client.ts | 309 ++++++++ examples/game/client/src/freeze/freeze.css | 161 ++++ examples/game/client/src/freeze/main.ts | 379 +++++++++ .../client/tests/freeze-headless.test.mjs | 166 ++++ examples/game/client/vite.config.ts | 2 +- examples/game/run.sh | 2 +- examples/game/server/src/freeze/content.rs | 324 ++++++++ examples/game/server/src/freeze/mod.rs | 548 +++++++++++++ examples/game/server/src/freeze/world.rs | 738 ++++++++++++++++++ examples/game/server/src/lib.rs | 1 + examples/game/server/src/main.rs | 4 + examples/game/server/tests/freeze_smoke.rs | 241 ++++++ 15 files changed, 2925 insertions(+), 2 deletions(-) create mode 100644 examples/game/client/freeze/index.html create mode 100644 examples/game/client/src/freeze/client.ts create mode 100644 examples/game/client/src/freeze/freeze.css create mode 100644 examples/game/client/src/freeze/main.ts create mode 100644 examples/game/client/tests/freeze-headless.test.mjs create mode 100644 examples/game/server/src/freeze/content.rs create mode 100644 examples/game/server/src/freeze/mod.rs create mode 100644 examples/game/server/src/freeze/world.rs create mode 100644 examples/game/server/tests/freeze_smoke.rs diff --git a/examples/game/README.md b/examples/game/README.md index 44672e570..3757ee454 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -10,6 +10,7 @@ guests and lets any page change the network simulation. |---|---|---| | **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | | **Shooting Gallery** | `./run.sh gallery` | Lag compensation: hitscan shots resolved with `ctx.rewind().hit_test_shot` at the shooter's view time (`client_tick` + interpolation delay in the payload), `max_rewind` clamp, per-shot compensation on/off, predicted vs confirmed hits | +| **The Freeze** | `./run.sh freeze` | World-version barrier (`WorldCoordinator::rollout`) across **two server processes** as an in-world "admin update": freeze → apply → resume with change notes, inputs dropped while frozen, Hard reload vs safe-room gating (`StalePolicy::SafeRoom`, `Zone::is_gate`) of old clients, aborted rollout (`freeze_ready` → `NotAcked`), facts/events stamped with the content version | `./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. @@ -48,6 +49,41 @@ for states not yet received); each shot carries `delay = tickTime(client_tick) `gallery::MAX_REWIND_MS` (600 ms of view age, ≈ 250 ms one way) shots are clamped and reported as such. +The Freeze: the server prints an **admin secret** (`./run.sh freeze` shows +it; set `DG_DEMO_ADMIN_SECRET` to choose one) — open +`/freeze/?admin=` (add `&old=1` in a second tab for an old client). +`game-demos freeze` hosts the Town Hub (safe-room gate) and Whisper Meadow +and starts a second process of itself for Ember Fields (`beta`, shared +ticket + admin secrets, exits with its parent); portals hand players off +between them (`Redirect` + `/admin/transfer` across processes). Content is +data-driven per version (`freeze::content`: v1 lava pools that burn, v2 +"lava is now ice", v3 back to lava; slime speed/size/color, crystals, gem +value) and served by `GET /dev/freeze/content/{version}`; the client derives +the scene from *its own* pack. + +- **Roll out update (Hard)**: every zone on both hosts freezes (SYSTEM + overlay, inputs dropped and counted — client side, plus any in flight on + the server), the "content CDN" stages the pack (`DG_FREEZE_STAGE_MS`, + default 2.5 s), every zone resumes on the next version with the notes, + and every client reloads (`Kick(RELOAD)` → `reloadContent` → reconnect + with the token). +- **Roll out (Safe room)**: rolling commit. Normal clients patch live + (`client.setContentVersion`); an old client (**O** / `&old=1`) keeps its + old pack in the field — the server already runs the new rules — until it + walks through a portal into the Town Hub, where it gets `RELOAD`. + (An old client that is *already* in the hub when the update lands is + refused by the field it walks into next — `VERSION_MISMATCH` — returns to + the hub with its transfer ticket and is reloaded there.) +- **Ritual in Ember Fields**: that zone's `freeze_ready()` is false; the + next rollout times out (`NotAcked: beta/freeze-ember`) and every zone + resumes on the old version with "update aborted". + +Each zone switch emits a `freeze.content_applied` fact and a stamped event; +gems emit `freeze.gem_collected` facts — the admin panel lists them with +their stamp. Display names live on the primary host: a player joining Ember +Fields directly (`&zone=freeze-ember`) shows as a guest there, names carry +over portals. + ## Architecture ``` @@ -83,12 +119,14 @@ examples/game/ src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events src/arena/ Arena zone + movement.rs (twin of client movement.ts) src/gallery/ Shooting Gallery zone (targets, rewind hit tests); tests/gallery_smoke.rs + src/freeze/ The Freeze zone, content packs, two-host world + admin routes; tests/freeze_smoke.rs tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css src/arena/ client.ts (headless), main.ts (Babylon), movement.ts src/gallery/ client.ts (shots, adaptive delay), main.ts; tests/gallery-headless + src/freeze/ client.ts (content packs, live patch / reload, admin API), main.ts; tests/freeze-headless tests/ movement-parity, arena-headless (+ helpers/demo-server.mjs) ``` diff --git a/examples/game/client/freeze/index.html b/examples/game/client/freeze/index.html new file mode 100644 index 000000000..9d602545e --- /dev/null +++ b/examples/game/client/freeze/index.html @@ -0,0 +1,13 @@ + + + + + + The Freeze Demo + + + +
    + + + diff --git a/examples/game/client/index.html b/examples/game/client/index.html index 9b40d817b..a28fd7d3c 100644 --- a/examples/game/client/index.html +++ b/examples/game/client/index.html @@ -13,6 +13,7 @@

    distributed_game demos

    • Arena — fixed tick, binary deltas, interest management, prediction + reconciliation, interpolation.
    • Shooting Gallery — lag compensation: hitscan shots rewound to the shooter's view time, max-rewind clamp, compensation on/off.
    • +
    • The Freeze — world-version barrier across two server processes as a story beat: hard reload, safe-room gating of old clients, aborted rollout.
    diff --git a/examples/game/client/src/freeze/client.ts b/examples/game/client/src/freeze/client.ts new file mode 100644 index 000000000..a7effeb3f --- /dev/null +++ b/examples/game/client/src/freeze/client.ts @@ -0,0 +1,309 @@ +/** + * The Freeze networking without rendering (Node-testable). + * + * The client "build" runs one content pack (`pack()`), fetched from the + * demo's content CDN (`GET /dev/freeze/content/{version}`). What happens + * at a world barrier: + * + * - `Freeze`: `frozen()` holds the notice; inputs are not sent and are + * counted in `droppedWhileFrozen` (the server also drops and counts any + * that were in flight). + * - `Resume` with a new version: a normal client patches live (fetches the + * pack, `client.setContentVersion`); a **pinned** client (simulated old + * build) keeps its pack and is `stale()` until the server makes it + * reload — at once in a Hard rollout, or when it enters the hub gate in a + * Rolling (safe-room) rollout. + * - `Kick(RELOAD)` / `VERSION_MISMATCH`: `reloadContent` fetches the + * required pack; the SDK reconnects with the reconnect token. + * - `Resume` with reason `content_update_aborted`: `lastResume().aborted`. + */ +import { + GameClient, + type GameSocketFactory, + type ResumeMessage, + type FreezeMessage +} from '@hops-ops/distributed/game'; + +import { encodeMoveInput, predictPlayer, type MoveInput } from '../arena/movement.ts'; +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; + +export const ZONES = { hub: 'freeze-hub', meadow: 'freeze-meadow', ember: 'freeze-ember' } as const; +export const DEFAULT_ZONE = ZONES.hub; +/** Event type ids (server `freeze::EVENT_*`). */ +export const EVENT_HELLO = 1; +export const EVENT_GEM = 2; +export const EVENT_BURNED = 3; +export const EVENT_CONTENT = 4; +export const KIND = { player: 'player', slime: 'slime', gem: 'gem', ritual: 'ritual' } as const; + +export type Stamp = Readonly<{ zone: string; tick: number; contentVersion: string }>; + +export type ZoneLayout = Readonly<{ + title: string; + gate: boolean; + portals: readonly Readonly<{ x: number; y: number; to: string; title: string }>[]; + pools: readonly Readonly<{ x: number; y: number; r: number }>[]; + ritual: Readonly<{ x: number; y: number }>; +}>; + +export type Pack = Readonly<{ + version: string; + name: string; + notes: readonly string[]; + hazard: 'lava' | 'ice'; + slimeSpeed: number; + slimeColor: string; + slimeScale: number; + crystalColor: string; + crystalLayout: number; + gemValue: number; + zones: Readonly> & { crystals: readonly (readonly [number, number])[][] }; +}>; + +export type FreezeHello = Readonly<{ + entity: number; + zone: string; + title: string; + gate: boolean; + host: string; + half: number; + contentVersion: string; +}>; + +export type LogEntry = Readonly<{ at: number; zone: string; kind: string; text: string; stamp?: Stamp }>; + +export type ResumeInfo = Readonly<{ + version: string; + notes: string[]; + aborted: boolean; + /** Applied live (normal client) vs ignored (pinned client). */ + patched: boolean; + zone: string; +}>; + +/** The content CDN (any version up to the world's current one). */ +export async function fetchPack(base: string, version: string): Promise { + const response = await fetch(`${base}/dev/freeze/content/${encodeURIComponent(version)}`); + if (!response.ok) throw new Error(`content ${version}: HTTP ${response.status}`); + return (await response.json()) as Pack; +} + +/** Admin side of the demo (`x-game-admin-secret`). */ +export class FreezeAdmin { + readonly base: string; + secret: string; + + constructor(base: string, secret: string) { + this.base = base; + this.secret = secret; + } + + rollout(mode: 'hard' | 'rolling'): Promise> { + return this.#post('/dev/freeze/rollout', { mode }); + } + + setStuck(zone: string, stuck: boolean): Promise> { + return this.#post('/dev/freeze/stuck', { zone, stuck }); + } + + async world(): Promise { + const response = await fetch(`${this.base}/dev/freeze/world`); + if (!response.ok) throw new Error(`world: HTTP ${response.status}`); + return (await response.json()) as WorldStatus; + } + + async #post(path: string, body: unknown): Promise> { + const response = await fetch(`${this.base}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-game-admin-secret': this.secret }, + body: JSON.stringify(body) + }); + const json = (await response.json().catch(() => ({}))) as Record; + if (!response.ok) throw new Error(`${path}: HTTP ${response.status} ${String(json.error ?? '')}`); + return json; + } +} + +export type ZoneStatus = Readonly<{ + zone: string; + title: string; + state: 'running' | 'freezing' | 'frozen'; + players: number; + droppedFrozen: number; + contentVersion: string; + pack: string; + stuck: boolean; +}>; + +export type WorldStatus = Readonly<{ + version: string; + hosts: readonly Readonly<{ + host: string; + version?: string; + zones?: readonly ZoneStatus[]; + facts?: readonly Readonly<{ command: string; key: string; stamp: Stamp; input: unknown }>[]; + error?: string; + }>[]; + rollouts: readonly Record[]; +}>; + +export type FreezeClient = Readonly<{ + client: GameClient; + /** Content pack the client renders. */ + pack(): Pack; + hello(): FreezeHello | undefined; + /** Resolves on the next hello (each zone sends one). */ + nextHello(): Promise; + /** Freeze notice while frozen. */ + frozen(): FreezeMessage | undefined; + lastResume(): ResumeInfo | undefined; + /** World content version (last Welcome / Resume of the authority). */ + worldVersion(): string | undefined; + /** Running older content than the world. */ + stale(): boolean; + /** Inputs not sent because the zone was frozen. */ + droppedWhileFrozen(): number; + /** Content reloads forced by the server (zone, version). */ + reloads: { zone: string; version: string }[]; + log: LogEntry[]; + /** Send one command frame (counted when frozen). */ + sendInput(input: MoveInput): number | undefined; + onChange(listener: (what: string) => void): () => void; +}>; + +export type FreezeClientOptions = Readonly<{ + api: DevApi; + /** HTTP origin (Node); '' = the page origin. */ + base?: string; + socket?: GameSocketFactory; + /** Simulate an old client: never patch content live. */ + pinned?: () => boolean; +}>; + +export async function createFreezeClient(options: FreezeClientOptions): Promise { + const base = options.base ?? ''; + const pinned = options.pinned ?? (() => false); + let pack = await fetchPack(base, 'current'); + const listeners = new Set<(what: string) => void>(); + const changed = (what: string) => { + for (const listener of listeners) listener(what); + }; + const reloads: { zone: string; version: string }[] = []; + const log: LogEntry[] = []; + const note = (zone: string, kind: string, text: string, stamp?: Stamp) => { + log.push({ at: Date.now(), zone, kind, text, stamp }); + if (log.length > 50) log.shift(); + changed('log'); + }; + const ease = { mode: 'ease', durationMs: 150 } as const; + const snap = { mode: 'snap' } as const; + let reloadingZone = ''; + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 500, + inputDtMs: 1000 / 30, + contentVersion: pack.version, + reloadContent: async (request) => { + pack = await fetchPack(base, request.version ?? 'current'); + reloads.push({ zone: reloadingZone, version: pack.version }); + note(reloadingZone, 'reload', `server required content ${pack.version}: reloaded "${pack.name}"`); + changed('pack'); + return pack.version; + }, + prediction: { + encodeInput: (input) => encodeMoveInput(input), + predict: (fields, input) => predictPlayer(fields, input), + corrections: { + player: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } + } + } + }); + client.on('reloadRequired', (zone) => (reloadingZone = zone)); + + let hello: FreezeHello | undefined; + let helloWaiters: ((h: FreezeHello) => void)[] = []; + let frozen: FreezeMessage | undefined; + let lastResume: ResumeInfo | undefined; + let worldVersion: string | undefined; + let dropped = 0; + + onJsonEvent(client, EVENT_HELLO, (value) => { + hello = value; + client.setControlledEntity(value.entity); + const waiters = helloWaiters; + helloWaiters = []; + for (const w of waiters) w(value); + changed('hello'); + }); + client.on('authority', (_zone, welcome) => { + worldVersion = welcome.contentVersion; + frozen = undefined; + changed('welcome'); + }); + client.on('freeze', (zone, message) => { + if (zone !== client.authority?.zoneId) return; + frozen = message; + note(zone, 'freeze', `world paused for update ${message.version}`); + changed('freeze'); + }); + client.on('resume', (zone, message: ResumeMessage) => { + if (zone !== client.authority?.zoneId) return; + frozen = undefined; + const aborted = message.reason === 'content_update_aborted'; + const notes = message.notes.split('\n').filter((l) => l.length > 0); + worldVersion = message.version; + const update = !aborted && message.version !== client.contentVersion; + const patched = update && !pinned(); + lastResume = { version: message.version, notes, aborted, patched, zone }; + note(zone, aborted ? 'aborted' : 'resume', aborted ? `update aborted (${notes.join(' ')}); still ${message.version}` : `resumed on ${message.version}`); + changed('resume'); + if (patched) { + // A client that can patch live: load the pack, present it from now on. + fetchPack(base, message.version) + .then((next) => { + pack = next; + client.setContentVersion(next.version); + note(zone, 'patch', `patched live to ${next.version} "${next.name}"`); + changed('pack'); + }) + .catch((error: unknown) => note(zone, 'error', String(error))); + } + }); + onJsonEvent<{ by: string; value: number; stamp: Stamp }>(client, EVENT_GEM, (v, zone) => + note(zone, 'gem', `${v.by} collected a gem (+${v.value})`, v.stamp) + ); + onJsonEvent<{ name: string; stamp: Stamp }>(client, EVENT_BURNED, (v, zone) => + note(zone, 'burned', `${v.name} stepped into lava`, v.stamp) + ); + onJsonEvent<{ from: string; to: string; name: string; stamp: Stamp }>(client, EVENT_CONTENT, (v, zone) => + note(zone, 'content', `zone switched ${v.from} → ${v.to} "${v.name}"`, v.stamp) + ); + + return { + client, + pack: () => pack, + hello: () => hello, + nextHello: () => new Promise((resolve) => helloWaiters.push(resolve)), + frozen: () => frozen, + lastResume: () => lastResume, + worldVersion: () => worldVersion, + stale: () => worldVersion !== undefined && worldVersion !== client.contentVersion, + droppedWhileFrozen: () => dropped, + reloads, + log, + sendInput(input) { + if (client.authority?.connection.frozen === true) { + dropped += 1; + return undefined; + } + return client.sendInput(input); + }, + onChange(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + } + }; +} diff --git a/examples/game/client/src/freeze/freeze.css b/examples/game/client/src/freeze/freeze.css new file mode 100644 index 000000000..777719a1b --- /dev/null +++ b/examples/game/client/src/freeze/freeze.css @@ -0,0 +1,161 @@ +.zone-badge { + position: fixed; + top: 12px; + left: 50%; + transform: translateX(-50%); + padding: 4px 12px; + border-radius: 6px; + background: var(--panel); + pointer-events: none; + white-space: nowrap; +} +.freeze-overlay { + position: fixed; + inset: 0; + display: none; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 6px; + background: rgba(8, 14, 24, 0.72); + backdrop-filter: grayscale(1) blur(1px); + color: #cfe8ff; + text-align: center; + pointer-events: none; +} +.freeze-overlay.show { + display: flex; +} +.freeze-overlay .system { + font-size: 22px; + letter-spacing: 0.3em; + color: #7fd1ff; +} +.freeze-overlay .line { + font-size: 16px; +} +.freeze-overlay .spinner { + width: 28px; + height: 28px; + margin: 8px; + border: 3px solid #2d4a63; + border-top-color: #7fd1ff; + border-radius: 50%; + animation: freeze-spin 0.9s linear infinite; +} +@keyframes freeze-spin { + to { + transform: rotate(360deg); + } +} +.freeze-toast { + position: fixed; + top: 48px; + left: 50%; + transform: translateX(-50%); + max-width: min(560px, calc(100% - 24px)); + padding: 10px 14px; + border-radius: 8px; + background: var(--panel); + border-left: 4px solid #59e08c; + display: none; + pointer-events: none; +} +.freeze-toast.show { + display: block; +} +.freeze-toast.aborted { + border-left-color: #ff5d5d; +} +.freeze-toast.stale { + border-left-color: #ffd84a; +} +.stale-banner { + position: fixed; + bottom: 12px; + left: 50%; + transform: translateX(-50%); + max-width: min(620px, calc(100% - 24px)); + padding: 8px 12px; + border-radius: 8px; + background: rgba(90, 70, 10, 0.9); + color: #ffe9a8; + display: none; + pointer-events: none; +} +.stale-banner.show { + display: block; +} +.freeze-log { + position: fixed; + right: 12px; + top: 48px; + width: 320px; + margin: 0; + padding: 8px 12px 8px 26px; + border-radius: 8px; + background: var(--panel); + font-size: 12px; + pointer-events: none; +} +.freeze-log:empty { + display: none; +} +.freeze-log .aborted, +.freeze-log .burned { + color: #ff8a8a; +} +.freeze-log .reload, +.freeze-log .patch { + color: #7fd1ff; +} +.freeze-log .gem { + color: #fff27a; +} +.hud .admin input.secret { + width: 100%; + box-sizing: border-box; + margin: 4px 0; +} +.hud .admin .buttons { + display: flex; + gap: 6px; + flex-wrap: wrap; +} +.hud .admin button { + font: inherit; + padding: 3px 8px; + cursor: pointer; +} +.hud .admin .result { + display: block; + margin: 4px 0; +} +.hud .admin .zone-row.frozen { + color: #7fd1ff; +} +.hud .admin .zone-row.freezing { + color: #ffd84a; +} +.label.portal { + color: #d7c2ff; +} +.label.ritual { + color: #ff8aa0; +} +.fatal { + position: fixed; + inset: 40px; + color: #ff8a8a; +} +@media (max-width: 640px) { + .freeze-log { + display: none; + } + .zone-badge { + top: auto; + bottom: 52px; + white-space: normal; + max-width: calc(100% - 24px); + } +} diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts new file mode 100644 index 000000000..6214e85dc --- /dev/null +++ b/examples/game/client/src/freeze/main.ts @@ -0,0 +1,379 @@ +/** + * The Freeze page: Babylon scene over `createFreezeClient`, plus a dev + * admin panel (needs the admin secret printed by the server; `?admin=`). + * + * Everything that depends on content (pool look, slime color/size, + * crystals, gem value) is derived from the client's *own* pack, so a + * pinned old client visibly keeps the old world while the server already + * runs the new rules. + */ +import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { Color3 } from '@babylonjs/core/Maths/math.color'; +import type { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import type { RenderedEntity } from '@hops-ops/distributed/game'; + +import { BUTTON_DASH, HALF, PILLARS, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; +import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, KIND, ZONES, type Pack, type WorldStatus } from './client.ts'; +import './freeze.css'; + +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const name = params.get('name') ?? undefined; +let pinned = params.get('old') === '1'; + +function stored(key: string): string | undefined { + try { + return localStorage.getItem(key) ?? undefined; + } catch { + return undefined; + } +} +function store(key: string, value: string): void { + try { + localStorage.setItem(key, value); + } catch { + // private mode + } +} + +const el = (tag: K, className = '', text?: string): HTMLElementTagNameMap[K] => { + const node = document.createElement(tag); + if (className !== '') node.className = className; + if (text !== undefined) node.textContent = text; + return node; +}; + +declare global { + interface Window { + /** Debug handle (console). */ + freeze?: unknown; + } +} + +async function main(): Promise { + const api = new DevApi({ name: () => name }); + const freeze = await createFreezeClient({ api, pinned: () => pinned }); + const { client } = freeze; + + const canvas = document.getElementById('stage') as HTMLCanvasElement; + const stage = createStage(canvas, { half: HALF, background: '#0d1013' }); + const { scene } = stage; + + const hud = new Hud({ + title: 'The Freeze', + hint: 'WASD to move, Space to dash. Walk through portals. Roll out updates in the admin panel; O: simulate an old client.', + client + }); + hud.toggle('Simulate old client (no live patch)', pinned, (on) => (pinned = on), 'o'); + + // ---- DOM overlays ---- + const badge = el('div', 'zone-badge'); + const overlay = el('div', 'freeze-overlay'); + const toast = el('div', 'freeze-toast'); + const banner = el('div', 'stale-banner'); + const logBox = el('ol', 'freeze-log'); + document.body.append(badge, overlay, toast, banner, logBox); + let toastTimer: ReturnType | undefined; + + function showToast(title: string, lines: readonly string[], kind: string): void { + toast.replaceChildren(el('strong', '', title), ...lines.map((l) => el('div', '', `• ${l}`))); + toast.className = `freeze-toast show ${kind}`; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => (toast.className = 'freeze-toast'), 7000); + } + + freeze.onChange((what) => { + if (what === 'resume') { + const r = freeze.lastResume()!; + if (r.aborted) showToast(`SYSTEM: update aborted — the world stays on ${r.version}`, r.notes, 'aborted'); + else if (r.patched || !pinned) showToast(`SYSTEM: update ${r.version} applied. Here's what changed:`, r.notes.slice(1), 'applied'); + else showToast(`SYSTEM: the world now runs ${r.version}`, ['Your old client keeps its content until you enter the Town Hub.', ...r.notes.slice(1)], 'stale'); + } + if (what === 'pack' && freeze.reloads.length > 0 && freeze.reloads.at(-1)!.version === freeze.pack().version) { + const p = freeze.pack(); + showToast(`SYSTEM: content reloaded — ${p.name} (${p.version})`, p.notes, 'applied'); + } + if (what === 'log') { + const e = freeze.log.at(-1)!; + const li = el('li', e.kind, `${e.text}${e.stamp === undefined ? '' : ` · ${e.stamp.zone}#${e.stamp.tick} @${e.stamp.contentVersion}`}`); + logBox.prepend(li); + while (logBox.children.length > 8) logBox.lastChild?.remove(); + } + }); + + // ---- admin panel ---- + const admin = new FreezeAdmin('', params.get('admin') ?? stored('game-demos.freeze.admin') ?? ''); + const panel = el('fieldset', 'admin'); + panel.append(el('legend', '', 'World admin (dev, admin secret)')); + const secret = el('input', 'secret'); + secret.type = 'password'; + secret.placeholder = 'admin secret (printed by the server)'; + secret.value = admin.secret; + secret.addEventListener('change', () => { + admin.secret = secret.value.trim(); + store('game-demos.freeze.admin', admin.secret); + }); + const buttons = el('div', 'buttons'); + const hardButton = el('button', '', 'Roll out update (Hard)'); + const rollingButton = el('button', '', 'Roll out (Safe room)'); + buttons.append(hardButton, rollingButton); + const ritualLabel = el('label', 'toggle'); + const ritual = el('input'); + ritual.type = 'checkbox'; + ritualLabel.append(ritual, document.createTextNode(' Ritual in Ember Fields (zone refuses to freeze)')); + const result = el('small', 'result', ''); + const status = el('div', 'world-status'); + panel.append(secret, buttons, ritualLabel, result, status); + hud.root.append(panel); + + async function roll(mode: 'hard' | 'rolling'): Promise { + hardButton.disabled = rollingButton.disabled = true; + result.textContent = `rolling out (${mode})…`; + try { + const r = await admin.rollout(mode); + result.textContent = r.ok + ? `✓ ${String(r.from)} → ${String(r.version)} "${String(r.name)}" in ${String(r.tookMs)} ms` + : `✗ aborted (${String(r.error)}: ${(r.missing as string[] | undefined)?.join(', ') ?? ''}) — still ${String(r.version)}`; + } catch (error) { + result.textContent = String(error); + } finally { + hardButton.disabled = rollingButton.disabled = false; + } + } + hardButton.addEventListener('click', () => void roll('hard')); + rollingButton.addEventListener('click', () => void roll('rolling')); + ritual.addEventListener('change', () => { + admin.setStuck(ZONES.ember, ritual.checked).then( + () => (result.textContent = ritual.checked ? 'Ember Fields will refuse the next freeze' : 'ritual ended'), + (error: unknown) => { + result.textContent = String(error); + ritual.checked = !ritual.checked; + } + ); + }); + + let world: WorldStatus | undefined; + async function pollWorld(): Promise { + try { + world = await admin.world(); + status.replaceChildren( + ...world.hosts.flatMap((h) => + (h.zones ?? []).map((z) => + el( + 'div', + `zone-row ${z.state}`, + `${h.host} · ${z.title.replace(' (safe room)', '')}: ${z.state} ${z.contentVersion} · ${z.players}p · dropped ${z.droppedFrozen}${z.stuck ? ' · RITUAL' : ''}` + ) + ) + ) + ); + ritual.checked = world.hosts.some((h) => h.zones?.some((z) => z.zone === ZONES.ember && z.stuck)); + } catch { + status.textContent = 'world status unavailable'; + } + } + setInterval(() => void pollWorld(), 1000); + void pollWorld(); + + // ---- content-derived scenery ---- + const mats = { + me: material(scene, 'me', '#6cc4ff'), + other: material(scene, 'other', '#f2a65a'), + pillar: material(scene, 'pillar', '#7b8798'), + portal: material(scene, 'portal', '#b48cff'), + gem: material(scene, 'gem', '#fff27a') + }; + mats.portal.emissiveColor = Color3.FromHexString('#5b3fa8'); + mats.gem.emissiveColor = Color3.FromHexString('#8a7d1e'); + for (const [x, y, r] of PILLARS) { + const p = MeshBuilder.CreateCylinder('pillar', { diameter: r * 2, height: 2, tessellation: 24 }, scene); + p.position = toWorld(x, y, 1); + p.material = mats.pillar; + } + let scenery: Mesh[] = []; + let sceneryKey = ''; + let slimeMat: StandardMaterial = material(scene, 'slime', '#7ed957'); + + function buildScenery(pack: Pack, zoneId: string): void { + for (const m of scenery) m.dispose(); + for (const key of [...portalLabels]) stage.labels.delete(key); + portalLabels.clear(); + scenery = []; + const layout = pack.zones[zoneId]; + if (layout === undefined) return; + const lava = pack.hazard === 'lava'; + const pool = material(scene, `pool-${pack.version}`, lava ? '#ff5a1f' : '#bfe9ff', lava ? 1 : 0.85); + pool.emissiveColor = Color3.FromHexString(lava ? '#a8320c' : '#3d6f8a'); + for (const p of layout.pools) { + const disc = MeshBuilder.CreateDisc('pool', { radius: p.r, tessellation: 40 }, scene); + disc.rotation.x = Math.PI / 2; + disc.position = toWorld(p.x, p.y, 0.02); + disc.material = pool; + scenery.push(disc); + } + for (const p of layout.portals) { + const ring = MeshBuilder.CreateTorus('portal', { diameter: 2.4, thickness: 0.25, tessellation: 32 }, scene); + ring.rotation.z = Math.PI / 2; + ring.position = toWorld(p.x, p.y, 1.3); + ring.material = mats.portal; + scenery.push(ring); + const key = `portal:${p.to}`; + portalLabels.add(key); + stage.labels.set(key, ring, `→ ${p.title}`, 1.6, 'portal'); + } + const crystal = material(scene, `crystal-${pack.version}`, pack.crystalColor); + crystal.emissiveColor = Color3.FromHexString(pack.crystalColor).scale(0.35); + for (const [x, y] of pack.zones.crystals[pack.crystalLayout] ?? []) { + const c = MeshBuilder.CreateCylinder('crystal', { diameterTop: 0, diameterBottom: 1.1, height: 2.6, tessellation: 5 }, scene); + c.position = toWorld(x, y, 1.3); + c.material = crystal; + scenery.push(c); + } + slimeMat = material(scene, `slime-${pack.version}`, pack.slimeColor); + for (const v of visuals.values()) if (v.kind === KIND.slime) v.mesh.material = slimeMat; + } + const portalLabels = new Set(); + + // ---- entities ---- + type Visual = { mesh: Mesh; kind: string }; + const visuals = new Map(); + const ritualRing = createRing(scene, 2, '#ff4d6d'); + ritualRing.setEnabled(false); + + function visualFor(entity: RenderedEntity, mine: boolean): Visual { + let v = visuals.get(entity.key); + if (v !== undefined) return v; + let mesh: Mesh; + switch (entity.kindName) { + case KIND.slime: + mesh = MeshBuilder.CreateSphere(entity.key, { diameter: 0.9, segments: 10 }, scene); + mesh.scaling.y = 0.6; + mesh.material = slimeMat; + break; + case KIND.gem: + mesh = MeshBuilder.CreatePolyhedron(entity.key, { type: 1, size: 0.35 }, scene); + mesh.material = mats.gem; + break; + case KIND.ritual: + mesh = MeshBuilder.CreateBox(entity.key, { size: 0.01 }, scene); + mesh.isVisible = false; + break; + default: + mesh = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + mesh.material = mine ? mats.me : mats.other; + } + v = { mesh, kind: entity.kindName }; + visuals.set(entity.key, v); + return v; + } + + // ---- input ---- + const sampler = new InputSampler(); + const frames = new FixedRate(30); + let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; + const sendFrame = () => { + const s = sampler.sample(); + const move = cameraRelative(s, stage.cameraForward()); + lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON_DASH : 0 }; + freeze.sendInput(lastInput); + }; + + stage.onFrame((now, dtMs) => { + frames.advance(now, sendFrame); + const hello = freeze.hello(); + const pack = freeze.pack(); + const authority = client.authority; + const zoneId = hello?.zone ?? authority?.zoneId ?? zone; + if (sceneryKey !== `${pack.version}:${zoneId}`) { + sceneryKey = `${pack.version}:${zoneId}`; + buildScenery(pack, zoneId); + } + const rendered = client.render(); + const seen = new Set(); + let me: { x: number; y: number } | undefined; + let ritualStuck = false; + for (const entity of rendered) { + if (authority !== undefined && entity.zoneId !== authority.zoneId) continue; + const mine = hello !== undefined && entity.id === hello.entity; + const v = visualFor(entity, mine); + seen.add(entity.key); + const x = Number(entity.fields.x ?? 0); + const y = Number(entity.fields.y ?? 0); + switch (v.kind) { + case KIND.slime: + v.mesh.position.copyFrom(toWorld(x, y, 0.3 * pack.slimeScale)); + v.mesh.scaling.set(pack.slimeScale, 0.6 * pack.slimeScale, pack.slimeScale); + break; + case KIND.gem: + v.mesh.position.copyFrom(toWorld(x, y, 0.8 + 0.15 * Math.sin(now / 300))); + v.mesh.rotation.y = now / 600; + break; + case KIND.ritual: + v.mesh.position.copyFrom(toWorld(x, y, 0)); + ritualStuck = Number(entity.fields.stuck ?? 0) === 1; + ritualRing.position.copyFrom(toWorld(x, y, 0)); + if (ritualStuck) stage.labels.set('ritual', v.mesh, 'RITUAL IN PROGRESS — this zone cannot pause', 0.6, 'ritual'); + else stage.labels.delete('ritual'); + break; + default: + v.mesh.position.copyFrom(toWorld(x, y, 0.9)); + stage.labels.set(entity.key, v.mesh, mine ? `${String(entity.fields.name)} (you)` : String(entity.fields.name ?? ''), 1.4, mine ? 'me' : ''); + if (mine) me = { x, y }; + } + v.mesh.setEnabled(!entity.stale); + } + ritualRing.setEnabled(ritualStuck); + ritualRing.scaling.setAll(1 + 0.08 * Math.sin(now / 150)); + for (const [key, v] of visuals) { + if (seen.has(key)) continue; + v.mesh.dispose(); + stage.labels.delete(key); + visuals.delete(key); + } + if (me !== undefined) stage.follow(me.x, me.y, dtMs); + + // Overlays. + const frozen = freeze.frozen(); + overlay.classList.toggle('show', frozen !== undefined); + if (frozen !== undefined) { + const title = frozen.notes.split('\n')[0] ?? ''; + overlay.replaceChildren( + el('div', 'system', 'SYSTEM'), + el('div', 'line', 'An administrator has paused the world…'), + el('div', 'line', `applying update ${frozen.version}${title === '' ? '' : ` — ${title}`}`), + el('div', 'spinner'), + el('small', '', `inputs dropped while frozen: ${freeze.droppedWhileFrozen()}`) + ); + } + const stale = freeze.stale() && pinned; + banner.classList.toggle('show', stale); + if (stale) { + banner.textContent = hello?.gate + ? `Your client runs ${client.contentVersion}; the world runs ${freeze.worldVersion()}. Leave and re-enter the hub to update.` + : `Your client runs ${client.contentVersion} (old build); the world runs ${freeze.worldVersion()}. Keep playing — walk into the Town Hub (safe room) to update.`; + } + badge.textContent = hello === undefined ? 'connecting…' : `${hello.title} · host ${hello.host} · content ${client.contentVersion} "${pack.name}"`; + + hud.frame({ entities: rendered.length }); + const serverDropped = world?.hosts.reduce((n, h) => n + (h.zones ?? []).reduce((m, z) => m + z.droppedFrozen, 0), 0); + hud.row('You', api.last === undefined ? '—' : api.last.name); + hud.row('Client content', `${client.contentVersion} ${pinned ? '(pinned old client)' : '(live patching)'}`); + hud.row('World content', freeze.worldVersion() ?? '—'); + hud.row('Pools', pack.hazard === 'lava' ? 'lava (burns)' : 'ice (safe)'); + hud.row('Inputs dropped', `client ${freeze.droppedWhileFrozen()} · server ${serverDropped ?? '—'}`); + hud.row('Reloads', freeze.reloads.map((r) => `${r.version}@${r.zone.replace('freeze-', '')}`).join(', ') || '—'); + }); + + window.freeze = { freeze, client, api, admin, scene }; + + await client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); +} + +main().catch((error: unknown) => { + document.body.append(el('pre', 'fatal', `The Freeze failed to start: ${String(error)}\n(is the server running? ./run.sh freeze)`)); +}); diff --git a/examples/game/client/tests/freeze-headless.test.mjs b/examples/game/client/tests/freeze-headless.test.mjs new file mode 100644 index 000000000..fd5a5537c --- /dev/null +++ b/examples/game/client/tests/freeze-headless.test.mjs @@ -0,0 +1,166 @@ +/** + * Headless run of The Freeze against the real `game-demos freeze` binary + * (primary process + the second host it spawns). Two players in Ember + * Fields (second host): Ana patches content live, Bo is a pinned old + * client. + * + * 1. Rolling rollout v1 → v2 across both hosts: Ana patches, Bo keeps + * playing v1 in the field and reloads only when it walks into the hub + * gate (Ana walks in without a reload). + * 2. Hard rollout v2 → v3: inputs during the freeze are dropped and + * counted, every client reloads at once. + * 3. A stuck zone (ritual in Ember Fields) aborts the next rollout: + * everyone resumes on v3 with "update aborted". + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { stateFromFields } from '../src/arena/movement.ts'; +import { createFreezeClient, FreezeAdmin, ZONES } from '../src/freeze/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; + +const ADMIN = 'freeze-test-admin'; + +async function player(base, name, pinned) { + const api = new DevApi({ base, name: () => name, storage: memoryStorage() }); + return createFreezeClient({ api, base, pinned: () => pinned }); +} + +/** Steer with command frames toward (x, y) until `done()`. */ +async function walk(p, [x, y], done, timeoutMs = 15_000) { + const deadline = Date.now() + timeoutMs; + while (!done()) { + assert.ok(Date.now() < deadline, `walk to ${x},${y} timed out`); + const fields = p.client.predictor?.active ? p.client.predictor.predicted() : undefined; + if (fields !== undefined) { + const at = stateFromFields(fields); + const dx = x - at.x; + const dy = y - at.y; + const d = Math.hypot(dx, dy); + const k = d > 0.01 ? 127 / d : 0; + p.sendInput({ mx: Math.round(dx * k), my: Math.round(dy * k), buttons: 0 }); + } + await sleep(1000 / 30); + } +} + +test('world barrier across two hosts: rolling + safe room, hard reload, aborted rollout', { timeout: 600_000 }, async (t) => { + const server = await startDemo('freeze', { env: { DG_DEMO_ADMIN_SECRET: ADMIN, DG_FREEZE_STAGE_MS: '700' } }); + const base = server.httpUrl; + const admin = new FreezeAdmin(base, ADMIN); + const players = []; + try { + const ana = await player(base, 'Ana', false); + const bo = await player(base, 'Bo', true); + players.push(ana, bo); + assert.equal(ana.pack().version, 'v1'); + assert.equal(ana.pack().hazard, 'lava'); + for (const p of [ana, bo]) { + const hello = p.nextHello(); + await p.client.connect(ZONES.ember); + const h = await hello; + assert.equal(h.host, 'beta', 'Ember Fields runs on the second process'); + assert.equal(h.contentVersion, 'v1'); + await until(() => p.client.predictor.active, 5_000, 'bound'); + } + assert.match(bo.client.authority.connection.url, /\/zones\/freeze-ember$/); + assert.notEqual(new URL(bo.client.authority.connection.url).port, new URL(base).port, 'redirected to beta'); + await assert.rejects(new FreezeAdmin(base, 'wrong').rollout('hard'), /401/); + + // ---- 1. Rolling (safe room) v1 → v2 ---- + const rolling = await admin.rollout('rolling'); + assert.equal(rolling.ok, true, JSON.stringify(rolling)); + assert.equal(rolling.version, 'v2'); + await until(() => ana.lastResume()?.version === 'v2' && bo.lastResume()?.version === 'v2', 5_000, 'resume v2'); + assert.ok(ana.lastResume().notes.some((n) => n.includes('Lava is now ice'))); + await until(() => ana.client.contentVersion === 'v2' && ana.pack().hazard === 'ice', 5_000, 'ana patched'); + assert.equal(ana.lastResume().patched, true); + assert.equal(bo.lastResume().patched, false); + assert.equal(bo.client.contentVersion, 'v1', 'pinned client keeps its build'); + assert.equal(bo.pack().hazard, 'lava'); + assert.ok(bo.stale()); + assert.deepEqual([ana.reloads.length, bo.reloads.length], [0, 0], 'nobody reloaded in the field'); + // The stale client keeps playing in the field zone: inputs are acked. + const ack = bo.client.predictor.lastAck; + for (let i = 0; i < 10; i += 1) { + bo.sendInput({ mx: 0, my: 40, buttons: 0 }); + await sleep(1000 / 30); + } + await until(() => bo.client.predictor.lastAck >= ack + 10, 5_000, 'stale inputs acked'); + assert.equal(bo.client.authority.zoneId, ZONES.ember); + + // Both walk west into the hub gate (cross-host handoff beta → alpha). + const portal = [-16.5, 5]; + await Promise.all( + [ana, bo].map((p) => walk(p, portal, () => p.hello()?.zone === ZONES.hub && p.client.authority?.connection.state === 'open')) + ); + await until(() => bo.reloads.length === 1 && bo.client.contentVersion === 'v2', 10_000, 'bo reloaded at the gate'); + assert.deepEqual(bo.reloads, [{ zone: ZONES.hub, version: 'v2' }], 'reload happened at the hub'); + await until(() => bo.client.authority.connection.state === 'open' && !bo.stale(), 10_000, 'bo back'); + assert.equal(bo.pack().hazard, 'ice'); + assert.equal(ana.reloads.length, 0, 'an up-to-date client enters the gate without reloading'); + assert.equal(bo.hello().host, 'alpha'); + + // ---- 2. Hard v2 → v3: inputs during the freeze are dropped ---- + const hard = admin.rollout('hard'); + await until(() => ana.frozen() !== undefined && bo.frozen() !== undefined, 5_000, 'frozen'); + assert.equal(ana.frozen().version, 'v3'); + assert.equal(ana.client.authority.connection.canSendInput(), false); + for (let i = 0; i < 5; i += 1) { + assert.equal(ana.sendInput({ mx: 127, my: 0, buttons: 0 }), undefined); + await sleep(20); + } + assert.ok(ana.droppedWhileFrozen() >= 5); + const hardResult = await hard; + assert.equal(hardResult.ok, true, JSON.stringify(hardResult)); + assert.equal(hardResult.version, 'v3'); + await until( + () => [ana, bo].every((p) => p.client.contentVersion === 'v3' && p.client.authority?.connection.state === 'open'), + 10_000, + 'everyone reloaded to v3' + ); + assert.deepEqual(ana.reloads, [{ zone: ZONES.hub, version: 'v3' }]); + assert.deepEqual(bo.reloads.at(-1), { zone: ZONES.hub, version: 'v3' }); + assert.equal(ana.pack().name, 'Bloom Update'); + + // Facts on both hosts carry the version they were produced under. + const world = await admin.world(); + assert.equal(world.version, 'v3'); + const facts = world.hosts.flatMap((h) => (h.facts ?? []).map((f) => ({ host: h.host, ...f }))); + for (const [host, zone] of [ + ['alpha', ZONES.hub], + ['beta', ZONES.ember] + ]) { + for (const version of ['v2', 'v3']) { + assert.ok( + facts.some( + (f) => f.host === host && f.command === 'freeze.content_applied' && f.stamp.zone === zone && f.stamp.contentVersion === version + ), + `${host}/${zone} ${version} fact: ${JSON.stringify(facts)}` + ); + } + } + assert.ok(world.hosts.every((h) => h.version === 'v3' && h.zones.every((z) => z.state === 'running'))); + assert.ok(ana.log.some((e) => e.kind === 'content' && e.stamp?.contentVersion === 'v3'), 'stamped content event'); + + // ---- 3. Stuck zone → aborted rollout, everyone stays on v3 ---- + const stuck = await admin.setStuck(ZONES.ember, true); + assert.equal(stuck.host, 'beta'); + const aborted = await admin.rollout('hard'); + assert.equal(aborted.ok, false); + assert.equal(aborted.error, 'not_acked'); + assert.deepEqual(aborted.missing, [`beta/${ZONES.ember}`]); + await until(() => ana.lastResume()?.aborted === true && bo.lastResume()?.aborted === true, 5_000, 'abort notice'); + assert.equal(ana.lastResume().version, 'v3'); + assert.equal(ana.client.contentVersion, 'v3'); + assert.equal(ana.reloads.length, 1, 'no reload on abort'); + const after = await admin.world(); + assert.ok(after.hosts.every((h) => h.version === 'v3')); + await admin.setStuck(ZONES.ember, false); + t.diagnostic(`dropped while frozen: ana ${ana.droppedWhileFrozen()} · rollouts ${after.rollouts.map((r) => `${r.version}${r.ok ? '' : ' (aborted)'}`).join(', ')}`); + } finally { + for (const p of players) p.client.close(); + await server.stop(); + } +}); diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts index 5565cd286..ae54080a2 100644 --- a/examples/game/client/vite.config.ts +++ b/examples/game/client/vite.config.ts @@ -5,7 +5,7 @@ import { resolve } from 'node:path'; import { defineConfig } from 'vite'; -const DEMOS = ['arena', 'gallery']; +const DEMOS = ['arena', 'gallery', 'freeze']; const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; export default defineConfig({ diff --git a/examples/game/run.sh b/examples/game/run.sh index 4cbdf556b..56d1bf2a1 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -16,7 +16,7 @@ REPO="$(cd "$HERE/../.." && pwd)" SERVER="$HERE/server" CLIENT="$HERE/client" BIN="$SERVER/target/debug/game-demos" -DEMOS=(arena gallery) +DEMOS=(arena gallery freeze) log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } diff --git a/examples/game/server/src/freeze/content.rs b/examples/game/server/src/freeze/content.rs new file mode 100644 index 000000000..7002fc25a --- /dev/null +++ b/examples/game/server/src/freeze/content.rs @@ -0,0 +1,324 @@ +//! Data-driven content of **The Freeze**: one pack per content version. +//! +//! Version `v{n}` uses pack `(n - 1) % 3`, so the admin can keep rolling +//! out "new" versions. The server derives its rules (hazard, slime speed, +//! gem value) from the pack of the zone's content version; clients fetch +//! the same pack as JSON (`GET /dev/freeze/content/{version}`, the demo's +//! stand-in for a content CDN) and derive colors, props and labels from +//! it. A client pinned to an old version keeps rendering its old pack. +//! +//! The zone layout (portals, pools, gem spots) is version independent and +//! shipped inside every pack so the client needs nothing else. + +use serde::Serialize; +use serde_json::{json, Value}; + +/// What standing in a pool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Hazard { + /// Burns: the player is sent back to a spawn point. + Lava, + /// Safe to cross. + Ice, +} + +/// One content pack. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Pack { + /// `v{n}`. + pub version: String, + /// Display name of the update. + pub name: String, + /// "Here's what changed" bullet points (relative to the previous pack). + pub notes: Vec, + /// Pool behaviour. + pub hazard: Hazard, + /// Slime wander speed (m/s). + pub slime_speed: f32, + /// Slime color (hex). + pub slime_color: String, + /// Slime scale. + pub slime_scale: f32, + /// Crystal prop color (hex). + pub crystal_color: String, + /// Crystal props `(x, y)` per field zone (mirrored per pack). + pub crystal_layout: u8, + /// Value of a collected gem. + pub gem_value: u32, +} + +/// Number of distinct packs. +pub const PACKS: u32 = 3; + +/// Version number of `version` (`"v7"` → 7). +pub fn version_number(version: &str) -> Option { + version + .strip_prefix('v')? + .parse() + .ok() + .filter(|n: &u32| *n >= 1) +} + +/// `"v{n}"`. +pub fn version_name(n: u32) -> String { + format!("v{n}") +} + +/// The pack of `version` (`None` for a malformed version). +pub fn pack(version: &str) -> Option { + let n = version_number(version)?; + let (name, notes, hazard, speed, color, scale, crystal, layout, gem) = match (n - 1) % PACKS { + 0 => ( + "Ember Season", + vec![ + "The thaw is over: the pools are molten lava again (they burn).", + "Slimes are back to a calm 2.0 m/s and green.", + "Crystals glow orange; gems are worth 1.", + ], + Hazard::Lava, + 2.0, + "#7ed957", + 1.0, + "#ff9d3c", + 0, + 1, + ), + 1 => ( + "Frostfall Patch", + vec![ + "Lava is now ice: the pools are safe to cross.", + "Slimes are faster (2.0 → 3.5 m/s), bigger and blue.", + "Crystals moved and turned cyan; gems are worth 2.", + ], + Hazard::Ice, + 3.5, + "#5ab8ff", + 1.35, + "#7ff3ff", + 1, + 2, + ), + _ => ( + "Bloom Update", + vec![ + "Spring thaw: the ice melted back into lava (it burns again).", + "Slimes are slow (1.2 m/s), tiny and pink.", + "Crystals bloomed magenta; gems are worth 3.", + ], + Hazard::Lava, + 1.2, + "#ff7ad9", + 0.7, + "#d77bff", + 2, + 3, + ), + }; + Some(Pack { + version: version_name(n), + name: name.into(), + notes: notes.into_iter().map(String::from).collect(), + hazard, + slime_speed: speed, + slime_color: color.into(), + slime_scale: scale, + crystal_color: crystal.into(), + crystal_layout: layout, + gem_value: gem, + }) +} + +impl Pack { + /// Notes for the barrier's `Resume{notes}`: the name, then one line per + /// change. + pub fn resume_notes(&self) -> String { + let mut out = format!("{} ({})", self.name, self.version); + for note in &self.notes { + out.push('\n'); + out.push_str(note); + } + out + } + + /// Pack plus the world layout, as served to clients. + pub fn to_json(&self) -> Value { + let mut v = serde_json::to_value(self).expect("pack serializes"); + v["zones"] = layout_json(); + v + } +} + +/// Kind of zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ZoneKind { + /// Town hub: the safe room (gate). + Hub, + /// Field zone on the primary host. + Meadow, + /// Field zone on the second host. + Ember, +} + +/// Zone ids of the world. +pub const HUB: &str = "freeze-hub"; +/// Meadow zone id. +pub const MEADOW: &str = "freeze-meadow"; +/// Ember Fields zone id. +pub const EMBER: &str = "freeze-ember"; +/// Every zone (activated at startup so the barrier reaches them all). +pub const ZONES: [&str; 3] = [HUB, MEADOW, EMBER]; + +impl ZoneKind { + /// Kind of a zone id. + pub fn of(zone_id: &str) -> Option { + match zone_id { + HUB => Some(Self::Hub), + MEADOW => Some(Self::Meadow), + EMBER => Some(Self::Ember), + _ => None, + } + } + + /// Display title. + pub fn title(self) -> &'static str { + match self { + Self::Hub => "Town Hub (safe room)", + Self::Meadow => "Whisper Meadow", + Self::Ember => "Ember Fields", + } + } + + /// Portals `(x, y, target zone)`. + pub fn portals(self) -> &'static [(f32, f32, &'static str)] { + match self { + Self::Hub => &[(-16.5, 5.0, MEADOW), (16.5, 5.0, EMBER)], + Self::Meadow => &[(16.5, 5.0, HUB)], + Self::Ember => &[(-16.5, 5.0, HUB)], + } + } + + /// Pools `(x, y, radius)`. + pub fn pools(self) -> &'static [(f32, f32, f32)] { + match self { + Self::Hub => &[], + Self::Meadow => &[(-6.0, 6.0, 2.2), (6.0, -5.0, 2.5)], + Self::Ember => &[(-5.0, -5.0, 2.5), (6.0, 5.0, 3.0), (-4.0, 12.0, 2.0)], + } + } + + /// Gem spots. + pub fn gem_spots(self) -> &'static [(f32, f32)] { + match self { + Self::Hub => &[], + Self::Meadow | Self::Ember => &[ + (-12.0, -12.0), + (12.0, -12.0), + (12.0, 12.0), + (-12.0, 12.0), + (-3.0, -16.0), + (3.0, 16.0), + ], + } + } + + /// Wandering slimes. + pub fn slimes(self) -> u32 { + match self { + Self::Hub => 0, + Self::Meadow => 6, + Self::Ember => 8, + } + } + + /// Where a "ritual" can hold the zone (the stuck-zone toggle). + pub fn ritual(self) -> (f32, f32) { + (0.0, -10.0) + } +} + +/// Fresh-join spawn points (clear of pools and pillars). +pub const SPAWNS: [(f32, f32); 4] = [(0.0, -6.0), (0.0, 6.0), (-6.0, 0.0), (6.0, 0.0)]; + +/// Crystal props for a layout id (decor, no collision). +pub fn crystals(layout: u8) -> Vec<(f32, f32)> { + let base = [ + (-17.0, -17.0), + (-11.0, -17.5), + (17.0, -16.0), + (17.5, 11.0), + (-17.5, 15.0), + (-8.0, 17.0), + (10.0, 17.5), + ]; + base.iter() + .map(|&(x, y)| match layout { + 0 => (x, y), + 1 => (-x, y), + _ => (y, x), + }) + .collect() +} + +fn layout_json() -> Value { + let zone = |kind: ZoneKind| { + json!({ + "title": kind.title(), + "gate": kind == ZoneKind::Hub, + "portals": kind.portals().iter().map(|(x, y, to)| json!({"x": x, "y": y, "to": to, "title": ZoneKind::of(to).map(ZoneKind::title)})).collect::>(), + "pools": kind.pools().iter().map(|(x, y, r)| json!({"x": x, "y": y, "r": r})).collect::>(), + "ritual": { "x": kind.ritual().0, "y": kind.ritual().1 }, + }) + }; + json!({ + HUB: zone(ZoneKind::Hub), + MEADOW: zone(ZoneKind::Meadow), + EMBER: zone(ZoneKind::Ember), + "crystals": [crystals(0), crystals(1), crystals(2)], + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions_cycle_through_packs() { + assert_eq!(version_number("v12"), Some(12)); + assert_eq!(version_number("v0"), None); + assert_eq!(version_number("x1"), None); + assert_eq!(pack("v1").unwrap().hazard, Hazard::Lava); + assert_eq!(pack("v2").unwrap().hazard, Hazard::Ice); + assert_eq!(pack("v4").unwrap().name, pack("v1").unwrap().name); + assert_eq!(pack("v4").unwrap().version, "v4"); + let json = pack("v2").unwrap().to_json(); + assert_eq!(json["hazard"], "ice"); + assert_eq!(json["zones"][EMBER]["portals"][0]["to"], HUB); + assert!(pack("v2") + .unwrap() + .resume_notes() + .starts_with("Frostfall Patch (v2)\n")); + } + + #[test] + fn layout_is_clear_of_pillars() { + use crate::arena::movement::PILLARS; + for kind in [ZoneKind::Hub, ZoneKind::Meadow, ZoneKind::Ember] { + let points = kind + .portals() + .iter() + .map(|p| (p.0, p.1)) + .chain(kind.gem_spots().iter().copied()) + .chain(SPAWNS); + for (x, y) in points { + for (px, py, pr) in PILLARS { + assert!(((x - px).powi(2) + (y - py).powi(2)).sqrt() > pr + 1.0); + } + for (qx, qy, qr) in kind.pools() { + assert!(((x - qx).powi(2) + (y - qy).powi(2)).sqrt() > qr + 1.0); + } + } + } + } +} diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs new file mode 100644 index 000000000..e7e2c001b --- /dev/null +++ b/examples/game/server/src/freeze/mod.rs @@ -0,0 +1,548 @@ +//! **The Freeze** — a world-version barrier as an in-world story beat. +//! +//! Three zones on two server processes: the **Town Hub** (a safe room, +//! [`Zone::is_gate`]) and **Whisper Meadow** on the primary host, **Ember +//! Fields** on the second host. Their rules come from the content pack of +//! the zone's content version ([`content`]): lava pools that burn (or ice +//! that does not), slime speed, gem value. An administrator rolls out the +//! next version with [`world`]'s `/dev/freeze/rollout` (admin secret): +//! `WorldCoordinator::rollout` freezes every zone on both hosts (clients +//! show "SYSTEM: an administrator has paused the world…", inputs are +//! dropped and counted), the update is applied, every zone resumes on the +//! new version with the change notes. +//! +//! - **Hard**: every client is told `Kick(RELOAD)`, reloads the pack and +//! reconnects with its token. +//! - **Rolling + SafeRoom** (`StalePolicy::SafeRoom { roam: false }`): +//! clients that patch content live keep going; an old client (the page's +//! "simulate old client") keeps playing its old pack in a field zone and is +//! only reloaded when it walks through a portal into the hub gate. +//! - **Abort**: a zone with a ritual in progress refuses +//! [`Zone::freeze_ready`]; the barrier times out (`NotAcked`) and every +//! zone resumes on the old version ("update aborted"). +//! +//! Movement is the Arena's shared step ([`crate::arena::movement`], predicted +//! by the client with the same TypeScript twin). +//! +//! Entities: 1 `player` (Arena fields), 2 `slime` (x y yaw), 3 `gem` (x y), +//! 4 `ritual` (global: x y stuck). Events (JSON): [`EVENT_HELLO`], +//! [`EVENT_GEM`], [`EVENT_BURNED`], [`EVENT_CONTENT`]; gameplay events carry +//! `ctx.stamp()` (zone, tick, content version). Gems and content switches are +//! also durable facts stamped by the host. + +pub mod content; +pub mod world; + +use std::collections::{BTreeMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, KindDef, + LeaveReason, PlayerId, StalePolicy, View, WorldView, Zone, +}; +use serde_json::{json, Value}; + +use crate::arena::movement::{self, MoveInput, MoveState}; +use crate::common::{broadcast_json_event, send_json_event, Demo, Guests}; +use content::{Hazard, Pack, ZoneKind}; + +/// Player kind (Arena fields: the client predicts it with Arena's step). +pub const KIND_PLAYER: u16 = 1; +/// Slime kind. +pub const KIND_SLIME: u16 = 2; +/// Gem kind. +pub const KIND_GEM: u16 = 3; +/// Ritual circle (global; `stuck` = 1 while it holds the zone). +pub const KIND_RITUAL: u16 = 4; +/// `{"entity", "zone", "title", "gate", "host", "half", "contentVersion"}`. +pub const EVENT_HELLO: u32 = 1; +/// `{"by", "value", "stamp"}` — someone collected a gem. +pub const EVENT_GEM: u32 = 2; +/// `{"name", "stamp"}` — someone stepped into lava. +pub const EVENT_BURNED: u32 = 3; +/// `{"from", "to", "name", "stamp"}` — the zone switched content. +pub const EVENT_CONTENT: u32 = 4; +/// Content version every host starts on. +pub const INITIAL_VERSION: &str = "v1"; +const VIEW_RADIUS: f32 = 40.0; +const PORTAL_RADIUS: f32 = 1.2; +const GEM_RADIUS: f32 = 0.9; +const GEM_RESPAWN: Duration = Duration::from_secs(4); +const RITUAL_ID: u32 = 900; + +/// Zones whose ritual blocks a freeze (the "stuck zone" toggle), shared by +/// a host's zones and its dev routes. +#[derive(Clone, Default)] +pub struct Rituals(Arc>>); + +impl Rituals { + /// Start / stop the ritual of `zone`. + pub fn set(&self, zone: &str, stuck: bool) { + let mut set = self.0.lock().expect("rituals"); + if stuck { + set.insert(zone.to_string()); + } else { + set.remove(zone); + } + } + + /// True while `zone` refuses to freeze. + pub fn is_stuck(&self, zone: &str) -> bool { + self.0.lock().expect("rituals").contains(zone) + } + + /// Stuck zones. + pub fn list(&self) -> Vec { + let mut v: Vec<_> = self.0.lock().expect("rituals").iter().cloned().collect(); + v.sort(); + v + } +} + +/// Zone construction parameters. +#[derive(Clone)] +pub struct FreezeConfig { + /// Which zone this is. + pub kind: ZoneKind, + /// Display names registered by the dev ticket endpoint (primary host). + pub guests: Guests, + /// Stuck-zone toggles of this host. + pub rituals: Rituals, + /// Host id shown to players (`alpha` / `beta`). + pub host: String, +} + +struct Player { + entity: u32, + name: String, + state: MoveState, + credits: u8, + /// Just arrived through a portal: ignore portals until it stepped off. + on_portal: bool, +} + +struct Slime { + x: f32, + y: f32, + tx: f32, + ty: f32, + yaw: f32, +} + +struct Gem { + spot: usize, + /// Simulation time it respawns at (None = present). + respawn_at: Option, +} + +/// One zone of The Freeze. +pub struct FreezeZone { + config: FreezeConfig, + zone_id: String, + pack: Pack, + players: BTreeMap, + slimes: Vec, + gems: Vec, + collected: u64, +} + +impl FreezeZone { + /// Content pack in effect. + pub fn pack(&self) -> &Pack { + &self.pack + } + + /// Player position. + pub fn player_position(&self, player: PlayerId) -> Option<(f32, f32)> { + self.players.get(&player).map(|p| (p.state.x, p.state.y)) + } + + fn stamp_json(stamp: &FactStamp) -> Value { + json!({ "zone": stamp.zone_id, "tick": stamp.tick, "contentVersion": stamp.content_version }) + } + + fn arrival_point(&self, from_zone: &str) -> (f32, f32) { + self.config + .kind + .portals() + .iter() + .find(|(_, _, to)| *to == from_zone) + .map(|(x, y, _)| (*x - x.signum() * 3.0, *y)) + .unwrap_or(content::SPAWNS[0]) + } + + fn add_player( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + name: String, + at: (f32, f32), + ) { + let entity = 1000 + player.0; + self.players.insert( + player, + Player { + entity, + name, + state: MoveState { + x: at.0, + y: at.1, + ..MoveState::default() + }, + credits: crate::arena::MAX_CREDITS, + on_portal: false, + }, + ); + ctx.set_view(player, View::new(at.0, at.1, VIEW_RADIUS)); + send_json_event( + ctx, + player, + EVENT_HELLO, + &json!({ + "entity": entity, + "zone": self.zone_id, + "title": self.config.kind.title(), + "gate": self.config.kind == ZoneKind::Hub, + "host": self.config.host, + "half": movement::HALF, + "contentVersion": ctx.content_version(), + }), + ); + } + + fn random_point(ctx: &mut Ctx<'_, Self>) -> (f32, f32) { + loop { + let x = (ctx.rng().next_f32() * 2.0 - 1.0) * (movement::HALF - 2.0); + let y = (ctx.rng().next_f32() * 2.0 - 1.0) * (movement::HALF - 2.0); + if movement::PILLARS + .iter() + .all(|(px, py, pr)| (x - px).powi(2) + (y - py).powi(2) > (pr + 1.0).powi(2)) + { + return (x, y); + } + } + } +} + +impl Zone for FreezeZone { + type Config = FreezeConfig; + type Input = MoveInput; + type Timer = (); + + fn schema() -> EntitySchema { + let small = FieldType::QuantF32 { + min: -movement::HALF, + max: movement::HALF, + bits: 14, + }; + EntitySchema::new() + .kind( + KindDef::new(KIND_PLAYER, "player") + .field("x", movement::POS) + .field("y", movement::POS) + .field("vx", movement::VEL) + .field("vy", movement::VEL) + .field("dash", FieldType::U8) + .field("cd", FieldType::U8) + .field_with_priority("name", FieldType::ShortStr, 0.2) + .priority(2.0), + ) + .kind( + KindDef::new(KIND_SLIME, "slime") + .field("x", small) + .field("y", small) + .field("yaw", FieldType::Angle { bits: 8 }), + ) + .kind( + KindDef::new(KIND_GEM, "gem") + .field("x", small) + .field("y", small), + ) + .kind( + KindDef::new(KIND_RITUAL, "ritual") + .field("x", small) + .field("y", small) + .field("stuck", FieldType::U8), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, config: FreezeConfig) -> Self { + let pack = content::pack(ctx.content_version()) + .unwrap_or_else(|| content::pack(INITIAL_VERSION).expect("v1")); + let kind = config.kind; + let mut slimes = Vec::new(); + for _ in 0..kind.slimes() { + let (x, y) = Self::random_point(ctx); + let (tx, ty) = Self::random_point(ctx); + slimes.push(Slime { + x, + y, + tx, + ty, + yaw: 0.0, + }); + } + Self { + zone_id: ctx.zone_id().to_string(), + config, + pack, + players: BTreeMap::new(), + slimes, + gems: (0..kind.gem_spots().len()) + .map(|spot| Gem { + spot, + respawn_at: None, + }) + .collect(), + collected: 0, + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + let name = self + .config + .guests + .name(&principal) + .unwrap_or_else(|| format!("Guest {}", principal.get(6..10).unwrap_or(""))); + let at = content::SPAWNS[player.0 as usize % content::SPAWNS.len()]; + self.add_player(ctx, player, name, at); + } + + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + from_zone: &str, + carried: Vec, + ) { + // Carried: the display name (the second host has no guest registry). + let name = String::from_utf8(carried) + .ok() + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| "Traveller".into()); + let at = self.arrival_point(from_zone); + self.add_player(ctx, player, name, at); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.players.remove(&player); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + MoveInput::decode(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let kind = self.config.kind; + let now = ctx.sim_time(); + let ids: Vec = self.players.keys().copied().collect(); + for id in ids { + let player = self.players.get_mut(&id).expect("present"); + player.credits = (player.credits + 1).min(crate::arena::MAX_CREDITS); + while player.credits > 0 { + let Some(input) = ctx.take_inputs(id, ConsumePolicy::Next).pop() else { + break; + }; + player.state = movement::step(player.state, input.input); + player.credits -= 1; + } + let (x, y) = (player.state.x, player.state.y); + // Lava burns (ice is safe): back to a spawn point. + if self.pack.hazard == Hazard::Lava + && kind + .pools() + .iter() + .any(|(px, py, pr)| (x - px).powi(2) + (y - py).powi(2) < (pr - 0.3).powi(2)) + { + let (sx, sy) = content::SPAWNS[id.0 as usize % content::SPAWNS.len()]; + player.state = MoveState { + x: sx, + y: sy, + ..MoveState::default() + }; + let event = json!({ "name": player.name, "stamp": Self::stamp_json(&ctx.stamp()) }); + broadcast_json_event(ctx, EVENT_BURNED, &event); + } + let player = self.players.get_mut(&id).expect("present"); + let (x, y) = (player.state.x, player.state.y); + ctx.set_view(id, View::new(x, y, VIEW_RADIUS)); + // Gems. + for gem in &mut self.gems { + let (gx, gy) = kind.gem_spots()[gem.spot]; + if gem.respawn_at.is_none() + && (x - gx).powi(2) + (y - gy).powi(2) < GEM_RADIUS.powi(2) + { + gem.respawn_at = Some(now + GEM_RESPAWN); + self.collected += 1; + let value = self.pack.gem_value; + let key = format!("gem:{}:{}:{}", self.zone_id, ctx.tick(), gem.spot); + let _ = ctx.emit_fact_for( + id, + Fact::new(key, "freeze.gem_collected", json!({ "value": value })), + ); + let event = json!({ + "by": player.name, "value": value, "stamp": Self::stamp_json(&ctx.stamp()), + }); + broadcast_json_event(ctx, EVENT_GEM, &event); + } + } + // Portals. + let portal = kind + .portals() + .iter() + .find(|(px, py, _)| (x - px).powi(2) + (y - py).powi(2) < PORTAL_RADIUS.powi(2)); + match portal { + Some((_, _, target)) if !player.on_portal => { + player.on_portal = true; + let _ = ctx.handoff(id, target, player.name.clone().into_bytes()); + } + Some(_) => {} + None => player.on_portal = false, + } + } + for gem in &mut self.gems { + if gem.respawn_at.is_some_and(|at| now >= at) { + gem.respawn_at = None; + } + } + let dt = ctx.dt_secs(); + let speed = self.pack.slime_speed; + for i in 0..self.slimes.len() { + let s = &self.slimes[i]; + let (ox, oy) = (s.tx - s.x, s.ty - s.y); + let dist = (ox * ox + oy * oy).sqrt(); + if dist < 0.3 { + let (tx, ty) = Self::random_point(ctx); + self.slimes[i].tx = tx; + self.slimes[i].ty = ty; + continue; + } + let s = &mut self.slimes[i]; + let stride = (speed * dt).min(dist); + s.x += ox / dist * stride; + s.y += oy / dist * stride; + s.yaw = oy.atan2(ox); + } + } + + fn replicate(&self, out: &mut WorldView) { + for p in self.players.values() { + let s = p.state; + out.push(EntityState::new( + p.entity, + KIND_PLAYER, + s.x, + s.y, + vec![ + FieldValue::F(s.x), + FieldValue::F(s.y), + FieldValue::F(s.vx), + FieldValue::F(s.vy), + FieldValue::U(s.dash.into()), + FieldValue::U(s.cooldown.into()), + FieldValue::Str(p.name.clone()), + ], + )); + } + for (i, s) in self.slimes.iter().enumerate() { + out.push(EntityState::new( + 1 + i as u32, + KIND_SLIME, + s.x, + s.y, + vec![FieldValue::F(s.x), FieldValue::F(s.y), FieldValue::F(s.yaw)], + )); + } + let spots = self.config.kind.gem_spots(); + for gem in self.gems.iter().filter(|g| g.respawn_at.is_none()) { + let (x, y) = spots[gem.spot]; + out.push( + EntityState::new( + 100 + gem.spot as u32, + KIND_GEM, + x, + y, + vec![FieldValue::F(x), FieldValue::F(y)], + ) + .global(), + ); + } + let (rx, ry) = self.config.kind.ritual(); + out.push( + EntityState::new( + RITUAL_ID, + KIND_RITUAL, + rx, + ry, + vec![ + FieldValue::F(rx), + FieldValue::F(ry), + FieldValue::U(self.config.rituals.is_stuck(&self.zone_id).into()), + ], + ) + .global(), + ); + } + + fn is_gate(&self) -> bool { + self.config.kind == ZoneKind::Hub + } + + fn freeze_ready(&self) -> bool { + !self.config.rituals.is_stuck(&self.zone_id) + } + + fn on_content_version_changed(&mut self, ctx: &mut Ctx<'_, Self>, from: &str, to: &str) { + if let Some(pack) = content::pack(to) { + self.pack = pack; + } + // A meaningful world transition: persisted (stamped with `to`). + let key = format!("content:{}:{to}", self.zone_id); + let _ = ctx.emit_fact(Fact::new( + key, + "freeze.content_applied", + json!({ "from": from, "to": to }), + )); + let event = json!({ + "from": from, "to": to, "name": self.pack.name, "stamp": Self::stamp_json(&ctx.stamp()), + }); + broadcast_json_event(ctx, EVENT_CONTENT, &event); + } + + fn has_pending_work(&self) -> bool { + false + } +} + +/// Host settings every Freeze server uses: content version `v1`, safe-room +/// stale policy. +pub fn freeze_config(mut config: ServerConfig) -> ServerConfig { + config.host.content_version = INITIAL_VERSION.into(); + config.host.stale_policy = StalePolicy::SafeRoom { roam: false }; + config +} + +/// Demo registration (`game-demos freeze`). [`Demo::server`] builds a +/// single-host world (every zone local); `game-demos freeze` runs the +/// two-host world of [`world`]. +pub struct FreezeDemo; + +impl Demo for FreezeDemo { + type Zone = FreezeZone; + const NAME: &'static str = "freeze"; + const DEFAULT_ZONE: &'static str = content::HUB; + + fn hosts_zone(zone_id: &str) -> bool { + ZoneKind::of(zone_id).is_some() + } + + fn server(config: ServerConfig, guests: Guests) -> GameServer { + world::zone_server(freeze_config(config), guests, Rituals::default(), "local") + } +} diff --git a/examples/game/server/src/freeze/world.rs b/examples/game/server/src/freeze/world.rs new file mode 100644 index 000000000..6fd25fe88 --- /dev/null +++ b/examples/game/server/src/freeze/world.rs @@ -0,0 +1,738 @@ +//! The two-host world of **The Freeze** and its dev / admin routes. +//! +//! `game-demos freeze --dev` is the **primary** host (`alpha`: hub + +//! meadow). It starts a **second process** of itself for `beta` (Ember +//! Fields) with `--peer alpha=`, sharing the ticket secret and the +//! admin secret through the environment; the child exits when the +//! primary's pipe closes. Both hosts share a `StaticDirectory`, so a Hello +//! for a zone on the other host is redirected and handoffs reserve their +//! transfer with the issuing host over `/admin/transfer`. +//! +//! Routes (dev only, mounted with `--dev`; the mutating ones require the +//! `x-game-admin-secret` header): +//! +//! | Route | Effect | +//! |---|---| +//! | `GET /dev/freeze/content/{version}` | content pack JSON (`current` = the world's version; future versions 404) | +//! | `GET /dev/freeze/world` | status of every host's zones (freeze state, players, inputs dropped while frozen, recent facts) | +//! | `POST /dev/freeze/rollout` `{mode: hard\|rolling}` | **admin** — primary only: `WorldCoordinator::rollout` to the next version | +//! | `POST /dev/freeze/stuck` `{zone, stuck}` | **admin** — start/stop a zone's ritual (forwarded to the owning host) | +//! | `POST /dev/freeze/host-status` | **admin** — this host's status (peer call) | + +use std::future::Future; +use std::io::{BufRead, BufReader}; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use distributed_game::facts::BoxFuture; +use distributed_game::net::peer::{post_json, ADMIN_SECRET_HEADER}; +use distributed_game::net::{ + BarrierParticipant, GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, + WorldCoordinator, +}; +use distributed_game::protocol::Notice; +use distributed_game::world::{HostAddr, StaticDirectory}; +use distributed_game::{BarrierMode, FreezeState, MemoryFactSink, RetryPolicy}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use super::content::{self, ZoneKind, EMBER, HUB, MEADOW}; +use super::{freeze_config, FreezeConfig, FreezeDemo, FreezeZone, Rituals}; +use crate::common::{dev, server_config, DemoArgs, Guests}; + +/// Default time the "content CDN" takes to stage an update while the world +/// is frozen (makes the pause visible). +pub const STAGE_MS: u64 = 2500; +/// How long the coordinator waits for every zone to freeze. +pub const ACK_TIMEOUT: Duration = Duration::from_secs(3); + +/// `game-demos freeze` options. +#[derive(Debug, Clone, clap::Args)] +pub struct FreezeArgs { + #[command(flatten)] + pub demo: DemoArgs, + /// Shared admin secret (barrier, transfers, `/dev/freeze/*` admin + /// routes). Default: random, printed at startup. + #[arg(long, env = "DG_DEMO_ADMIN_SECRET", hide_env_values = true)] + pub admin_secret: Option, + /// This host's id. + #[arg(long, default_value = "alpha")] + pub host_id: String, + /// Run as the second host of `id=host:port` (set by the primary). + #[arg(long)] + pub peer: Option, + /// Simulated content staging time during the freeze (ms). + #[arg(long, env = "DG_FREEZE_STAGE_MS", default_value_t = STAGE_MS)] + pub stage_ms: u64, +} + +/// Everything one host needs. +pub struct HostSpec { + /// This host. + pub me: HostAddr, + /// The other hosts. + pub peers: Vec, + /// Zone → host id. + pub assignment: Vec<(String, String)>, + /// Ticket key shared by every host. + pub key: TicketKey, + /// Admin secret shared by every host. + pub admin_secret: String, + /// Mount the dev routes. + pub dev: bool, + /// Content staging delay inside the barrier. + pub stage: Duration, + /// Barrier acknowledgement timeout. + pub ack_timeout: Duration, +} + +/// A running Freeze host. +pub struct WorldHost { + /// Bound address. + pub addr: SocketAddr, + /// The game server. + pub server: GameServer, + /// Facts committed by this host's zones. + pub sink: MemoryFactSink, + /// Stuck-zone toggles. + pub rituals: Rituals, + /// Resolves when the server stopped. + pub task: tokio::task::JoinHandle>, +} + +/// The Freeze game server for one host (no routes, no directory). +pub fn zone_server( + config: ServerConfig, + guests: Guests, + rituals: Rituals, + host: &str, +) -> GameServer { + zone_server_with_sink(config, guests, rituals, host, MemoryFactSink::new()) +} + +fn zone_server_with_sink( + config: ServerConfig, + guests: Guests, + rituals: Rituals, + host: &str, + sink: MemoryFactSink, +) -> GameServer { + let host = host.to_string(); + GameServer::new(config, move |zone_id| { + ZoneKind::of(zone_id).map(|kind| FreezeConfig { + kind, + guests: guests.clone(), + rituals: rituals.clone(), + host: host.clone(), + }) + }) + .with_fact_sink(sink, 256, RetryPolicy::default()) +} + +/// The default assignment: hub + meadow on `primary`, ember on `secondary`. +pub fn assignment(primary: &str, secondary: &str) -> Vec<(String, String)> { + vec![ + (HUB.into(), primary.into()), + (MEADOW.into(), primary.into()), + (EMBER.into(), secondary.into()), + ] +} + +/// Start one host on `listener` until `signal` resolves; activates its +/// zones so the barrier reaches them before anyone joined. +pub fn start_host( + listener: tokio::net::TcpListener, + spec: HostSpec, + signal: impl Future + Send + 'static, +) -> std::io::Result { + let addr = listener.local_addr()?; + let directory = Arc::new(StaticDirectory::new()); + directory.add_host(spec.me.clone()); + for peer in &spec.peers { + directory.add_host(peer.clone()); + } + for (zone, host) in &spec.assignment { + directory.assign(zone.clone(), host.clone()); + } + let mut config = freeze_config(server_config(spec.key.clone(), None)); + config.admin_secret = Some(spec.admin_secret.clone()); + let guests = Guests::default(); + let rituals = Rituals::default(); + let sink = MemoryFactSink::new(); + let server = zone_server_with_sink( + config, + guests.clone(), + rituals.clone(), + &spec.me.id, + sink.clone(), + ) + .with_host_id(spec.me.id.clone()) + .with_directory(directory); + let local: Vec = spec + .assignment + .iter() + .filter(|(_, h)| *h == spec.me.id) + .map(|(z, _)| z.clone()) + .collect(); + let extra = if spec.dev { + dev::routes::(server.clone(), spec.key.clone(), guests).merge(routes( + FreezeRoutes { + server: server.clone(), + sink: sink.clone(), + rituals: rituals.clone(), + admin_secret: spec.admin_secret.clone(), + me: spec.me.clone(), + peers: spec.peers.clone(), + local: local.clone(), + assignment: spec.assignment.clone(), + stage: spec.stage, + ack_timeout: spec.ack_timeout, + primary: spec + .assignment + .iter() + .any(|(z, h)| z == HUB && *h == spec.me.id), + rollout: Arc::new(tokio::sync::Mutex::new(())), + history: Arc::new(Mutex::new(Vec::new())), + }, + )) + } else { + Router::new() + }; + let task = tokio::spawn(server.clone().serve_with(listener, extra, signal)); + for zone in &local { + server.activate(zone); + } + Ok(WorldHost { + addr, + server, + sink, + rituals, + task, + }) +} + +// ---------------------------------------------------------------- routes + +#[derive(Clone)] +struct FreezeRoutes { + server: GameServer, + sink: MemoryFactSink, + rituals: Rituals, + admin_secret: String, + me: HostAddr, + peers: Vec, + local: Vec, + assignment: Vec<(String, String)>, + stage: Duration, + ack_timeout: Duration, + primary: bool, + rollout: Arc>, + history: Arc>>, +} + +type Reply = (StatusCode, Json); + +fn reply(status: StatusCode, body: Value) -> Reply { + (status, Json(body)) +} + +fn authorized(state: &FreezeRoutes, headers: &HeaderMap) -> Result<(), Reply> { + let presented = headers + .get(ADMIN_SECRET_HEADER) + .map(|v| v.as_bytes()) + .unwrap_or_default(); + let expected = state.admin_secret.as_bytes(); + let same = presented.len() == expected.len() + && presented + .iter() + .zip(expected) + .fold(0u8, |acc, (a, b)| acc | (a ^ b)) + == 0; + if same && !expected.is_empty() { + Ok(()) + } else { + Err(reply( + StatusCode::UNAUTHORIZED, + json!({ "ok": false, "error": "admin secret required (x-game-admin-secret)" }), + )) + } +} + +fn routes(state: FreezeRoutes) -> Router { + Router::new() + .route("/dev/freeze/content/{version}", get(content_pack)) + .route("/dev/freeze/world", get(world_status)) + .route("/dev/freeze/host-status", post(host_status)) + .route("/dev/freeze/rollout", post(rollout)) + .route("/dev/freeze/stuck", post(stuck)) + .with_state(state) +} + +async fn content_pack(State(state): State, Path(version): Path) -> Reply { + let current = state.server.content_version(); + let wanted = if version == "current" { + current.clone() + } else { + version + }; + let published = content::version_number(&wanted) + .zip(content::version_number(¤t)) + .is_some_and(|(w, c)| w <= c); + match content::pack(&wanted).filter(|_| published) { + Some(pack) => reply(StatusCode::OK, pack.to_json()), + None => reply( + StatusCode::NOT_FOUND, + json!({ "error": format!("content {wanted} is not published (world runs {current})") }), + ), + } +} + +async fn local_status(state: &FreezeRoutes) -> Value { + let mut zones = Vec::new(); + for zone in &state.local { + let info = state + .server + .inspect(zone, |h| { + ( + h.freeze_state(), + h.player_count(), + h.inputs_dropped_frozen(), + h.config().content_version.clone(), + h.zone().pack().name.clone(), + ) + }) + .await; + if let Some((freeze, players, dropped, version, pack)) = info { + zones.push(json!({ + "zone": zone, + "title": ZoneKind::of(zone).map(ZoneKind::title), + "state": match freeze { + FreezeState::Running => "running", + FreezeState::Freezing => "freezing", + FreezeState::Frozen => "frozen", + }, + "players": players, + "droppedFrozen": dropped, + "contentVersion": version, + "pack": pack, + "stuck": state.rituals.is_stuck(zone), + })); + } + } + let facts: Vec = state + .sink + .committed() + .iter() + .rev() + .take(8) + .map(|f| { + json!({ + "command": f.command(), + "key": f.key(), + "principal": f.principal(), + "input": f.input(), + "stamp": { + "zone": f.stamp().zone_id, + "tick": f.stamp().tick, + "contentVersion": f.stamp().content_version, + }, + }) + }) + .collect(); + json!({ + "host": state.me.id, + "version": state.server.content_version(), + "zones": zones, + "facts": facts, + }) +} + +async fn host_status(State(state): State, headers: HeaderMap) -> Reply { + if let Err(r) = authorized(&state, &headers) { + return r; + } + reply(StatusCode::OK, local_status(&state).await) +} + +async fn world_status(State(state): State) -> Reply { + let mut hosts = vec![local_status(&state).await]; + for peer in &state.peers { + match post_json( + &peer.admin_url, + "/dev/freeze/host-status", + &state.admin_secret, + &json!({}), + Duration::from_secs(2), + ) + .await + { + Ok((200, status)) => hosts.push(status), + other => hosts.push(json!({ "host": peer.id, "error": format!("{other:?}") })), + } + } + let history = state.history.lock().expect("history").clone(); + reply( + StatusCode::OK, + json!({ "version": state.server.content_version(), "hosts": hosts, "rollouts": history }), + ) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RolloutRequest { + /// `hard` or `rolling` (safe room). + mode: String, +} + +async fn rollout( + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Reply { + if let Err(r) = authorized(&state, &headers) { + return r; + } + if !state.primary { + return reply( + StatusCode::BAD_REQUEST, + json!({ "ok": false, "error": "roll out from the primary host" }), + ); + } + let mode = match body.mode.as_str() { + "hard" => BarrierMode::Hard, + "rolling" => BarrierMode::Rolling, + _ => { + return reply( + StatusCode::BAD_REQUEST, + json!({ "ok": false, "error": "mode must be hard or rolling" }), + ) + } + }; + let Ok(_running) = state.rollout.try_lock() else { + return reply( + StatusCode::CONFLICT, + json!({ "ok": false, "error": "a rollout is in progress" }), + ); + }; + let current = state.server.content_version(); + let next = content::version_name(content::version_number(¤t).unwrap_or(1) + 1); + let pack = content::pack(&next).expect("valid version"); + let notes = pack.resume_notes(); + let mut coordinator = WorldCoordinator::new(state.ack_timeout) + .participant(Arc::new(state.server.clone())) + .participant(Arc::new(ContentStage { delay: state.stage })); + for peer in &state.peers { + coordinator = coordinator.participant(Arc::new(RemoteHost::new( + peer.clone(), + state.admin_secret.clone(), + ))); + } + let started = Instant::now(); + let result = coordinator.rollout(&next, ¬es, mode, |_| Ok(())).await; + let took_ms = started.elapsed().as_millis() as u64; + let mode_name = body.mode; + let outcome = match result { + Ok(report) => json!({ + "ok": true, "from": current, "version": report.version, "mode": mode_name, + "name": pack.name, "notes": pack.notes, "commitErrors": report.commit_errors, + "tookMs": took_ms, + }), + Err(RolloutError::NotAcked(missing)) => json!({ + "ok": false, "error": "not_acked", "missing": missing, "attempted": next, + "version": current, "mode": mode_name, "tookMs": took_ms, + }), + Err(RolloutError::ApplyFailed(e)) => json!({ + "ok": false, "error": "apply_failed", "detail": e, "attempted": next, + "version": current, "mode": mode_name, "tookMs": took_ms, + }), + }; + let mut history = state.history.lock().expect("history"); + history.push(outcome.clone()); + if history.len() > 10 { + history.remove(0); + } + reply(StatusCode::OK, outcome) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StuckRequest { + zone: String, + stuck: bool, +} + +async fn stuck( + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Reply { + if let Err(r) = authorized(&state, &headers) { + return r; + } + let Some(owner) = state + .assignment + .iter() + .find(|(z, _)| *z == body.zone) + .map(|(_, h)| h.clone()) + else { + return reply( + StatusCode::BAD_REQUEST, + json!({ "ok": false, "error": "unknown zone" }), + ); + }; + if owner == state.me.id { + state.rituals.set(&body.zone, body.stuck); + return reply( + StatusCode::OK, + json!({ "ok": true, "host": owner, "stuck": state.rituals.list() }), + ); + } + let Some(peer) = state.peers.iter().find(|p| p.id == owner) else { + return reply( + StatusCode::BAD_GATEWAY, + json!({ "ok": false, "error": "owner unknown" }), + ); + }; + match post_json( + &peer.admin_url, + "/dev/freeze/stuck", + &state.admin_secret, + &json!({ "zone": body.zone, "stuck": body.stuck }), + Duration::from_secs(2), + ) + .await + { + Ok((status, value)) => reply( + StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY), + value, + ), + Err(e) => reply(StatusCode::BAD_GATEWAY, json!({ "ok": false, "error": e })), + } +} + +/// The content CDN as a barrier participant: staging the pack takes +/// `delay` while the world is frozen (nothing to undo on abort). +struct ContentStage { + delay: Duration, +} + +impl BarrierParticipant for ContentStage { + fn name(&self) -> String { + "content-cdn".into() + } + + fn prepare<'a>( + &'a self, + _barrier: u64, + _notice: &'a Notice, + _timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>> { + Box::pin(async move { + tokio::time::sleep(self.delay).await; + Ok(()) + }) + } + + fn commit<'a>( + &'a self, + _barrier: u64, + _version: &'a str, + _notes: &'a str, + _mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async { Ok(()) }) + } + + fn abort<'a>(&'a self, _barrier: u64, _notes: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async { Ok(()) }) + } +} + +// ---------------------------------------------------------------- CLI + +fn parse_peer(spec: &str) -> std::io::Result { + let (id, addr) = spec + .split_once('=') + .ok_or_else(|| std::io::Error::other("--peer must be id=host:port"))?; + Ok(HostAddr::new(id, addr)) +} + +/// Spawn the second host (this binary, `--peer`), wait for its address. +fn spawn_secondary( + args: &FreezeArgs, + primary: &HostAddr, + secret: &str, + admin: &str, +) -> std::io::Result<(std::process::Child, HostAddr)> { + let exe = std::env::current_exe()?; + let mut command = std::process::Command::new(exe); + command + .arg("freeze") + .args([ + "--host", + &args.demo.host, + "--port", + "0", + "--host-id", + "beta", + ]) + .arg("--peer") + .arg(format!( + "{}={}", + primary.id, + primary.admin_url.trim_start_matches("http://") + )) + .args(["--stage-ms", &args.stage_ms.to_string()]) + .env("DISTRIBUTED_GAME_SECRET", secret) + .env("DG_DEMO_ADMIN_SECRET", admin) + .env_remove("GAME_DEMOS_PORT") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::inherit()); + if args.demo.dev { + command.arg("--dev"); + } + let mut child = command.spawn()?; + let stdout = child.stdout.take().expect("piped"); + let mut lines = BufReader::new(stdout).lines(); + let addr = loop { + match lines.next() { + Some(Ok(line)) => { + if let Some(url) = line.strip_prefix("LISTENING http://") { + break url.trim().to_string(); + } + } + _ => { + let _ = child.kill(); + let _ = child.wait(); + return Err(std::io::Error::other("second host failed to start")); + } + } + }; + // Keep draining so the child never blocks on a full pipe. + std::thread::spawn(move || for _ in lines.by_ref() {}); + Ok((child, HostAddr::new("beta", addr))) +} + +async fn shutdown_signal(watch_stdin: bool) { + let ctrl_c = async { + let _ = tokio::signal::ctrl_c().await; + }; + #[cfg(unix)] + let term = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut s) => { + s.recv().await; + } + Err(_) => std::future::pending().await, + } + }; + #[cfg(not(unix))] + let term = std::future::pending::<()>(); + // The secondary exits when the primary (which holds its stdin) is gone. + let (orphaned_tx, orphaned) = tokio::sync::oneshot::channel::<()>(); + if watch_stdin { + std::thread::spawn(move || { + let mut sink = Vec::new(); + let _ = std::io::Read::read_to_end(&mut std::io::stdin(), &mut sink); + let _ = orphaned_tx.send(()); + }); + } else { + std::mem::forget(orphaned_tx); + } + tokio::select! { + _ = ctrl_c => {} + _ = term => {} + _ = orphaned => {} + } +} + +/// `game-demos freeze`: the primary host (spawns the secondary) or, with +/// `--peer`, the secondary. +pub async fn run(args: FreezeArgs) -> std::io::Result<()> { + let listener = tokio::net::TcpListener::bind((args.demo.host.as_str(), args.demo.port)).await?; + let addr = listener.local_addr()?; + let secret = args + .demo + .secret + .clone() + .unwrap_or_else(|| random_secret(32)); + let admin = args + .admin_secret + .clone() + .unwrap_or_else(|| random_secret(24)); + let me = HostAddr::new(args.host_id.clone(), addr.to_string()); + let secondary = args.peer.is_some(); + let (peers, child) = match &args.peer { + Some(spec) => (vec![parse_peer(spec)?], None), + None => { + let (child, beta) = spawn_secondary(&args, &me, &secret, &admin)?; + (vec![beta], Some(child)) + } + }; + let (primary_id, secondary_id) = if secondary { + (peers[0].id.clone(), me.id.clone()) + } else { + (me.id.clone(), peers[0].id.clone()) + }; + let spec = HostSpec { + me: me.clone(), + peers: peers.clone(), + assignment: assignment(&primary_id, &secondary_id), + key: TicketKey::new(secret), + admin_secret: admin.clone(), + dev: args.demo.dev, + stage: Duration::from_millis(args.stage_ms), + ack_timeout: ACK_TIMEOUT, + }; + let host = start_host(listener, spec, shutdown_signal(secondary))?; + // Parsed by run.sh and the client tests: keep the format. + println!("LISTENING http://{}", host.addr); + if secondary { + println!("freeze host {} (Ember Fields)", me.id); + } else { + println!( + "demo freeze · zones {HUB} {MEADOW} @{} + {EMBER} @{} (second process) · admin secret {admin} (admin panel: /freeze/?admin={admin}) · dev routes {}", + me.id, + peers[0].admin_url, + if args.demo.dev { "ON" } else { "off" } + ); + } + let result = host.task.await.map_err(std::io::Error::other)?; + if let Some(mut child) = child { + // Closing its stdin is the shutdown signal; kill as a fallback. + drop(child.stdin.take()); + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if child.try_wait()?.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + if child.try_wait()?.is_none() { + let _ = child.kill(); + let _ = child.wait(); + } + } + result +} + +/// `len` random hex characters (OS-seeded SipHash; dev quality). +fn random_secret(len: usize) -> String { + use std::hash::{BuildHasher, Hasher}; + let mut out = String::new(); + let mut n = 0u64; + while out.len() < len { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(n); + n += 1; + out.push_str(&format!("{:016x}", h.finish())); + } + out.truncate(len); + out +} diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index e3e199265..7d353f702 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -8,4 +8,5 @@ pub mod arena; pub mod common; +pub mod freeze; pub mod gallery; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs index 075de470b..5699dc1e4 100644 --- a/examples/game/server/src/main.rs +++ b/examples/game/server/src/main.rs @@ -3,6 +3,7 @@ use clap::{Parser, Subcommand}; use game_demos::arena::ArenaDemo; use game_demos::common::{run, DemoArgs}; +use game_demos::freeze::world::FreezeArgs; use game_demos::gallery::GalleryDemo; #[derive(Parser)] @@ -21,6 +22,8 @@ enum DemoCommand { Arena(DemoArgs), /// Lag compensation: hitscan shots rewound to the shooter's view time. Gallery(DemoArgs), + /// World-version barrier across two server processes, safe-room reloads. + Freeze(FreezeArgs), } #[tokio::main] @@ -28,5 +31,6 @@ async fn main() -> std::io::Result<()> { match Cli::parse().demo { DemoCommand::Arena(args) => run::(args).await, DemoCommand::Gallery(args) => run::(args).await, + DemoCommand::Freeze(args) => game_demos::freeze::world::run(args).await, } } diff --git a/examples/game/server/tests/freeze_smoke.rs b/examples/game/server/tests/freeze_smoke.rs new file mode 100644 index 000000000..3039acd53 --- /dev/null +++ b/examples/game/server/tests/freeze_smoke.rs @@ -0,0 +1,241 @@ +//! The Freeze: two in-process hosts talking over their admin HTTP routes +//! (the binary runs the second host as a separate process; the client's +//! `freeze-headless` test covers that, handoffs and safe-room reloads). + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::bots::{run_bots, BotConfig, RandomWalk}; +use distributed_game::net::TicketKey; +use distributed_game::world::HostAddr; +use distributed_game::FreezeState; +use game_demos::arena; +use game_demos::freeze::content::{EMBER, HUB, MEADOW}; +use game_demos::freeze::world::{assignment, start_host, HostSpec, WorldHost}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +const SECRET: &str = "freeze-smoke-secret"; +const ADMIN: &str = "freeze-smoke-admin"; + +async fn world() -> (WorldHost, WorldHost, Vec>) { + let la = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let lb = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = HostAddr::new("alpha", la.local_addr().unwrap().to_string()); + let b = HostAddr::new("beta", lb.local_addr().unwrap().to_string()); + let mut stops = Vec::new(); + let mut hosts = Vec::new(); + for (me, peer, listener) in [(a.clone(), b.clone(), la), (b, a, lb)] { + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + stops.push(stop); + let spec = HostSpec { + me, + peers: vec![peer], + assignment: assignment("alpha", "beta"), + key: TicketKey::new(SECRET), + admin_secret: ADMIN.into(), + dev: true, + stage: Duration::from_millis(600), + ack_timeout: Duration::from_millis(800), + }; + hosts.push( + start_host(listener, spec, async move { + let _ = stopped.await; + }) + .unwrap(), + ); + } + let b = hosts.pop().unwrap(); + let a = hosts.pop().unwrap(); + (a, b, stops) +} + +/// Minimal HTTP/1.1 client: `(status, JSON body or Null)`. +async fn http( + addr: SocketAddr, + method: &str, + path: &str, + body: Option, + admin: bool, +) -> (u16, Value) { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let secret = if admin { + format!("x-game-admin-secret: {ADMIN}\r\n") + } else { + String::new() + }; + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n{secret}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + let status = response[9..12].parse().unwrap(); + let json = response + .split_once("\r\n\r\n") + .and_then(|(_, b)| serde_json::from_str(b).ok()) + .unwrap_or(Value::Null); + (status, json) +} + +fn bots(url: String, zone: &str) -> BotConfig { + let mut config = BotConfig::new(url, zone, TicketKey::new(SECRET)); + config.bots = 2; + config.input_rate = 30.0; + config.duration = Duration::from_millis(2600); + config.content_version = "v1".into(); + config.principal_prefix = format!("bot-{zone}"); + config.encoder = Arc::new(arena::encode_bot_input); + config +} + +async fn dropped(host: &WorldHost, zone: &str) -> u64 { + host.server + .inspect(zone, |h| h.inputs_dropped_frozen()) + .await + .unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn rollout_spans_both_hosts_drops_frozen_inputs_and_stamps_the_new_version() { + let (a, b, stops) = world().await; + let ws_a = format!("ws://{}", a.addr); + let ws_b = format!("ws://{}", b.addr); + + // Admin routes need the secret; content of the future is not published. + let (status, _) = http( + a.addr, + "POST", + "/dev/freeze/rollout", + Some(json!({"mode": "hard"})), + false, + ) + .await; + assert_eq!(status, 401); + let (status, _) = http(a.addr, "GET", "/dev/freeze/content/v2", None, false).await; + assert_eq!(status, 404); + let (status, pack) = http(a.addr, "GET", "/dev/freeze/content/current", None, false).await; + assert_eq!((status, pack["version"].as_str()), (200, Some("v1"))); + + // Bots keep sending inputs through the freeze on both hosts. + let addr = a.addr; + let (meadow, ember, rollout) = tokio::join!( + run_bots(bots(ws_a, MEADOW), |_| Box::new(RandomWalk::new(0.1))), + run_bots(bots(ws_b, EMBER), |_| Box::new(RandomWalk::new(0.1))), + async move { + tokio::time::sleep(Duration::from_millis(700)).await; + http( + addr, + "POST", + "/dev/freeze/rollout", + Some(json!({"mode": "rolling"})), + true, + ) + .await + } + ); + assert_eq!(rollout.0, 200); + assert_eq!(rollout.1["ok"], true, "{}", rollout.1); + assert_eq!(rollout.1["version"], "v2"); + for summary in [&meadow, &ember] { + assert_eq!(summary.joined(), 2, "{:?}", summary.bots); + assert_eq!(summary.failed(), 0, "{:?}", summary.bots); + assert!(summary.bots.iter().all(|bot| bot.last_ack > 10)); + } + assert!( + dropped(&a, MEADOW).await > 0, + "frozen inputs counted on alpha" + ); + assert!( + dropped(&b, EMBER).await > 0, + "frozen inputs counted on beta (remote barrier)" + ); + + assert_eq!(a.server.content_version(), "v2"); + assert_eq!(b.server.content_version(), "v2"); + for (host, zone) in [(&a, HUB), (&a, MEADOW), (&b, EMBER)] { + let (version, pack) = host + .server + .inspect(zone, |h| { + ( + h.config().content_version.clone(), + h.zone().pack().name.clone(), + ) + }) + .await + .unwrap(); + assert_eq!((version.as_str(), pack.as_str()), ("v2", "Frostfall Patch")); + assert!(host + .sink + .committed() + .iter() + .any(|f| f.command() == "freeze.content_applied" + && f.stamp().zone_id == zone + && f.stamp().content_version == "v2")); + } + let (_, pack) = http(a.addr, "GET", "/dev/freeze/content/current", None, false).await; + assert_eq!(pack["hazard"], "ice"); + let (_, status) = http(a.addr, "GET", "/dev/freeze/world", None, false).await; + assert_eq!(status["hosts"][1]["host"], "beta"); + assert_eq!(status["hosts"][1]["zones"][0]["contentVersion"], "v2"); + for stop in stops { + let _ = stop.send(()); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_stuck_zone_aborts_and_everyone_resumes_on_the_old_version() { + let (a, b, stops) = world().await; + // The stuck toggle is forwarded to the host owning the zone. + let (status, reply) = http( + a.addr, + "POST", + "/dev/freeze/stuck", + Some(json!({"zone": EMBER, "stuck": true})), + true, + ) + .await; + assert_eq!((status, reply["host"].as_str()), (200, Some("beta"))); + assert!(b.rituals.is_stuck(EMBER)); + let (_, result) = http( + a.addr, + "POST", + "/dev/freeze/rollout", + Some(json!({"mode": "hard"})), + true, + ) + .await; + assert_eq!(result["ok"], false, "{result}"); + assert_eq!(result["missing"], json!([format!("beta/{EMBER}")])); + assert_eq!(a.server.content_version(), "v1"); + assert_eq!(b.server.content_version(), "v1"); + for (host, zone) in [(&a, HUB), (&a, MEADOW), (&b, EMBER)] { + let state = host.server.inspect(zone, |h| h.freeze_state()).await; + assert_eq!(state, Some(FreezeState::Running), "{zone}"); + } + // Unstuck: the next rollout goes through. + http( + a.addr, + "POST", + "/dev/freeze/stuck", + Some(json!({"zone": EMBER, "stuck": false})), + true, + ) + .await; + let (_, result) = http( + a.addr, + "POST", + "/dev/freeze/rollout", + Some(json!({"mode": "hard"})), + true, + ) + .await; + assert_eq!(result["version"], "v2", "{result}"); + assert_eq!(b.server.content_version(), "v2"); + for stop in stops { + let _ = stop.send(()); + } +} From 166ad5ebff92ad7bf1ab8024938e5d81dafb9013 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:07:02 -0500 Subject: [PATCH 154/484] feat(examples): add Endless Grid and Boss Ripple clients Babylon pages and Node-testable networking for both multi-host demos, wired into Vite, the demo index, run.sh (two hosts per demo) and the README: - grid: terrain/props generated locally from the seed (parity test against the Rust fixture), prediction with the shared step, observer connections to the 8 neighbours, handoff across hosts, host-tinted borders, minimap of active/hibernated cells, restore toasts. - ripple: playable neighborhood plus a live hierarchy tree with per-tier host, tick rate and clock, animated tier-up hops, city weather and realm banner. Headless tests start both hosts on ephemeral ports. Refs [[tasks/gr-p10-demos]] --- examples/game/README.md | 85 +++- examples/game/client/grid/index.html | 13 + examples/game/client/index.html | 2 + examples/game/client/ripple/index.html | 13 + examples/game/client/src/grid/client.ts | 216 ++++++++ examples/game/client/src/grid/grid.css | 71 +++ examples/game/client/src/grid/main.ts | 469 ++++++++++++++++++ examples/game/client/src/grid/world.ts | 245 +++++++++ examples/game/client/src/ripple/client.ts | 215 ++++++++ examples/game/client/src/ripple/main.ts | 325 ++++++++++++ examples/game/client/src/ripple/ripple.css | 148 ++++++ .../game/client/tests/grid-headless.test.mjs | 113 +++++ .../client/tests/grid-world-parity.test.mjs | 75 +++ .../game/client/tests/helpers/cluster.mjs | 93 ++++ .../client/tests/ripple-headless.test.mjs | 57 +++ examples/game/client/vite.config.ts | 2 +- examples/game/run.sh | 57 ++- 17 files changed, 2193 insertions(+), 6 deletions(-) create mode 100644 examples/game/client/grid/index.html create mode 100644 examples/game/client/ripple/index.html create mode 100644 examples/game/client/src/grid/client.ts create mode 100644 examples/game/client/src/grid/grid.css create mode 100644 examples/game/client/src/grid/main.ts create mode 100644 examples/game/client/src/grid/world.ts create mode 100644 examples/game/client/src/ripple/client.ts create mode 100644 examples/game/client/src/ripple/main.ts create mode 100644 examples/game/client/src/ripple/ripple.css create mode 100644 examples/game/client/tests/grid-headless.test.mjs create mode 100644 examples/game/client/tests/grid-world-parity.test.mjs create mode 100644 examples/game/client/tests/helpers/cluster.mjs create mode 100644 examples/game/client/tests/ripple-headless.test.mjs diff --git a/examples/game/README.md b/examples/game/README.md index 2b3828194..41a0dec54 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -9,6 +9,8 @@ guests and lets any page change the network simulation. | Demo | Run | Mechanic it demonstrates | |---|---|---| | **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | +| **Endless Grid** | `./run.sh grid` | Seeded procedural world (terrain/biomes/props generated bit-identically in Rust and TS, nothing static replicated), 32 m cells as zones, observer connections to the 8 neighbours, handoff across borders **and hosts** (2 processes, hash ring, Redirect + transfer tickets), hibernation to SQLite and restore | +| **Boss Ripple** | `./run.sh ripple` | Zone hierarchy realm › city › borough › hood (`DottedTopology`), per-tier tick rates (2/5/10/30 Hz), boss defeats propagating up as tier-up events (each hop on another host), parent broadcasts reaching players through observer connections | `./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. @@ -35,6 +37,72 @@ NetSim sliders change the server's simulated one-way latency (applied in both directions), jitter and loss (a TCP-like retransmit delay) for every connection. +## Endless Grid + +```sh +examples/game/run.sh grid +# → http://localhost:5173/grid/ (?zone=grid.4.-2&name=Ana optional) +``` + +Two `game-demos grid` processes: host **A** on `GAME_DEMOS_PORT` (Vite +proxies to it) and **B** on the next port, each listing the other with +`--peer`, sharing one ticket secret (the admin secret for host-to-host calls +is derived from it) and keeping hibernation snapshots under one +`--state-dir` (`grid-A.sqlite3`, `grid-B.sqlite3`). + +- **World.** Cell `(x, y)` is zone `grid..` (canonical integers, + |x|,|y| ≤ 10⁶; the server uses `FlatTopology`, the dots are not a + hierarchy). Its terrain height, biome and props are a pure function of + `(seed, x, y, CONTENT_VERSION)` in `server/src/grid/world.rs` and its twin + `client/src/grid/world.ts` (u32 hashing + binary32 value noise; checked + bit-for-bit by `fixtures/grid-world.json`). Props sit inside 8 m + sub-cells 2 m from their edges, so lines every 8 m are free trails and no + prop reaches across a border. Seed: `DG_GRID_SEED`. +- **Zones.** A cell simulates walkers (predicted with the shared step, + colliding with the cell's props) and 2–4 critters. Past a border by + 0.5 m the walker is handed off with its position in the neighbour's + frame (`ctx.handoff`); the SDK follows the Handoff — through a Redirect + when the neighbour lives on the other host (`HashRing`, 64 vnodes). +- **Interest across borders.** The client observes the 8 neighbours and + re-syncs on every authority change; entities are drawn at + `cell × 32 + local` around a floating origin. +- **Hibernation.** Nobody inside or observing → Idle → Dormant after 2 s → + hibernated after 4 s more (`--hibernate-after-ms`): critters and markers + (E) go to SQLite and come back on the next activation; its hello says + `restored` and the page toasts. The minimap (`GET /dev/grid/map`, which + asks the peer for its cells) shows active / hibernated / cold cells per + host; borders are tinted by owning host. + +Controls: WASD / stick, Space/Shift sprint, E drops a marker. + +## Boss Ripple + +```sh +examples/game/run.sh ripple +# → http://localhost:5173/ripple/ (?hood=realm.city.borough-2.hood-3 optional) +``` + +`realm` › `realm.city` › `realm.city.borough-{1,2}` › +`….hood-{1,2,3}`. Placement alternates by depth over the two hosts (hoods +and the city on A, boroughs and the realm on B), so every hop is a +`/admin/child-event` call between processes. Tick rates per tier come from +`GameServer::with_host_config`: realm 2 Hz (keeps an idle background +clock), city 5, borough 10, hood 30. Upper tiers refuse players; they are +observed. + +1. A hood's boss falls (E near it, or "Smite") → `boss_defeated` to the root. +2. The borough tallies its hoods; all down → `borough_cleared` (unlocked). +3. The city's weather follows the remaining bosses (storm → rain → + clearing → clear) and is broadcast to its observers — every player + observes the city, so the sky over their hood changes; both boroughs + cleared → `city_liberated`. +4. The realm counts everything and broadcasts a banner. + +Bosses respawn after 60 s (`boss_respawned` re-locks the borough). Every +tier's state is its hibernation snapshot. The page shows the tree with +each tier's host, rate and clock, animates each hop, and lets you click a +hood to fight there. + ## Architecture ``` @@ -68,13 +136,20 @@ examples/game/ server/ Rust crate `game_demos`, its own cargo workspace src/main.rs `game-demos ` subcommands src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events + src/cluster.rs multi-host demos: --host-id/--peer, directory, ownership, snapshots src/arena/ Arena zone + movement.rs (twin of client movement.ts) - tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs + src/grid/ Endless Grid zone, world.rs (twin of world.ts), dev map routes + src/ripple/ Boss Ripple tiers and placement + tests/ arena_smoke.rs, movement_fixture.rs, grid_smoke.rs, + grid_fixture.rs, ripple_smoke.rs (+ support/ for two hosts) client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css src/arena/ client.ts (headless), main.ts (Babylon), movement.ts - tests/ movement-parity, arena-headless (+ helpers/demo-server.mjs) + src/grid/, src/ripple/ client.ts (headless), main.ts (Babylon); grid/world.ts + tests/ movement-parity, arena-headless, grid-world-parity, + grid-headless, ripple-headless (+ helpers/demo-server.mjs, + helpers/cluster.mjs for multi-host demos) ``` The server crate is excluded from the root workspace (`Cargo.toml` @@ -106,6 +181,12 @@ The server crate is excluded from the root workspace (`Cargo.toml` `startDemo('')` from `tests/helpers/demo-server.mjs`. 5. Register the demo in `run.sh` (`DEMOS=(…)`) and in the table above. +A **multi-host** demo also implements `cluster::ClusterDemo` (`directory` +over the hosts, `cluster_server`, optional dev routes), uses +`DemoCommand::X(ClusterArgs)` → `run_cluster::`, is listed in +`CLUSTER_DEMOS` in `run.sh`, and tests with `tests/support` (Rust) / +`startCluster` (Node). + ## Security notes (why this is dev only) - `--dev` (or `DG_DEMO_DEV=1`) mounts `/dev/*`; without it only `/zones` and diff --git a/examples/game/client/grid/index.html b/examples/game/client/grid/index.html new file mode 100644 index 000000000..baf66d5b0 --- /dev/null +++ b/examples/game/client/grid/index.html @@ -0,0 +1,13 @@ + + + + + + Endless Grid Demo + + + +
    + + + diff --git a/examples/game/client/index.html b/examples/game/client/index.html index 8cca69766..ca6c3b78f 100644 --- a/examples/game/client/index.html +++ b/examples/game/client/index.html @@ -12,6 +12,8 @@

    distributed_game demos

    Each demo runs its own server: examples/game/run.sh <demo>. The page for the running demo works; the others need their server.

    • Arena — fixed tick, binary deltas, interest management, prediction + reconciliation, interpolation.
    • +
    • Endless Grid — seeded procedural cells as zones, observer connections across borders, handoff across two hosts, hibernation.
    • +
    • Boss Ripple — realm › city › borough › hood, per-tier tick rates, boss defeats rippling up as tier-up events across hosts.
    diff --git a/examples/game/client/ripple/index.html b/examples/game/client/ripple/index.html new file mode 100644 index 000000000..f98f2f69d --- /dev/null +++ b/examples/game/client/ripple/index.html @@ -0,0 +1,13 @@ + + + + + + Boss Ripple Demo + + + +
    + + + diff --git a/examples/game/client/src/grid/client.ts b/examples/game/client/src/grid/client.ts new file mode 100644 index 000000000..dbf528e07 --- /dev/null +++ b/examples/game/client/src/grid/client.ts @@ -0,0 +1,216 @@ +/** + * Endless Grid networking without rendering (Node-testable): + * + * - one `GameClient` whose authority is the cell the walker is in; it + * follows every Handoff (and the Redirect when the next cell lives on + * another host) — the SDK keeps rendering the old cell until the new one + * has content; + * - observer connections to the 8 neighbouring cells, re-synced whenever + * the authority changes, so what is across a border is visible before + * crossing; + * - prediction of the own walker with the shared step (`world.ts`) against + * the props of the current cell; + * - per-zone hello info (host, restored-from-hibernation …) and the + * `/dev/grid/map` world map. + */ +import { GameClient, type GameSocketFactory, type RenderedEntity } from '@hops-ops/distributed/game'; + +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; +import { + cellProps, + encodeMoveInput, + parseZone, + step, + zoneId, + CELL, + DEFAULT_SEED, + type Cell, + type MoveInput, + type Prop +} from './world.ts'; + +export const DEFAULT_ZONE = 'grid.0.0'; +/** Event type ids (server `grid::EVENT_*`). */ +export const EVENT_HELLO = 1; +export const KIND = { walker: 'walker', critter: 'critter', marker: 'marker' } as const; + +export type GridHello = Readonly<{ + zone: string; + cell: [number, number]; + host: string; + seed: number; + contentVersion: number; + cellSize: number; + entity: number | null; + restored: boolean; + restores: number; + hibernatedForMs: number | null; + restoredCritters: number; + restoredMarkers: number; + activatedAt: number; +}>; + +export type MapCell = Readonly<{ + x: number; + y: number; + zone: string; + owner: string; + state: 'active' | 'hibernated' | 'cold' | 'unknown'; + tier?: string; + players?: number; + observers?: number; +}>; + +export type WorldMap = Readonly<{ + host: string; + hosts: readonly Readonly<{ id: string; wsUrl: string; reachable: boolean; activeTotal: number | null; active: number; hibernated: number }>[]; + cells: readonly MapCell[]; +}>; + +export type GridClientOptions = Readonly<{ + api: DevApi; + /** HTTP origin of the first host (Node); default: the page origin. */ + base?: string; + socket?: GameSocketFactory; + /** Observe the 8 neighbours (default true). */ + neighbours?: boolean; +}>; + +export type GridClient = Readonly<{ + client: GameClient; + /** Cell of the authoritative zone. */ + cell(): Cell | undefined; + /** Latest hello per zone. */ + info(zone: string): GridHello | undefined; + /** Seed announced by the zones (falls back to the default). */ + seed(): number; + /** Props of a cell (memoized). */ + props(cell: Cell): readonly Prop[]; + /** World position (m) of a rendered entity. */ + worldOf(entity: RenderedEntity): { x: number; y: number } | undefined; + /** Handoffs completed so far. */ + handoffs(): number; + /** Resolves on the first hello with an own entity. */ + ready: Promise; + /** Called once per restored activation of any zone we see. */ + onRestored(listener: (hello: GridHello) => void): () => void; + /** Fetch the world map around a cell (`/dev/grid/map`). */ + map(center: Cell, radius: number): Promise; + close(): void; +}>; + +export function neighbours(cell: Cell): string[] { + const out: string[] = []; + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) { + if (dx !== 0 || dy !== 0) out.push(zoneId([cell[0] + dx, cell[1] + dy])); + } + } + return out; +} + +export function createGridClient(options: GridClientOptions): GridClient { + const infos = new Map(); + const propsCache = new Map(); + let seed = DEFAULT_SEED; + let authorityCell: Cell | undefined; + let handoffs = 0; + const restoredSeen = new Set(); + const restoredListeners = new Set<(hello: GridHello) => void>(); + + const props = (cell: Cell): readonly Prop[] => { + const key = `${seed}:${cell[0]}:${cell[1]}`; + let list = propsCache.get(key); + if (list === undefined) { + list = cellProps(seed, cell); + if (propsCache.size > 256) propsCache.clear(); + propsCache.set(key, list); + } + return list; + }; + const num = (v: unknown) => (typeof v === 'number' ? v : 0); + const ease = { mode: 'ease', durationMs: 120 } as const; + + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 1000, + inputDtMs: 1000 / 30, + prediction: { + encodeInput: (input) => encodeMoveInput(input), + predict: (fields, input) => { + const cell = authorityCell ?? [0, 0]; + const [x, y] = step(num(fields.x), num(fields.y), input, props(cell)); + return { x, y }; + }, + corrections: { [KIND.walker]: { x: ease, y: ease, name: { mode: 'replace' }, hue: { mode: 'replace' } } } + } + }); + + let resolveReady: (h: GridHello) => void = () => undefined; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + const syncNeighbours = () => { + if (options.neighbours === false || authorityCell === undefined) return; + const authority = client.authority?.zoneId; + const wanted = new Set(neighbours(authorityCell)); + for (const zone of client.zones()) { + if (zone.role === 'observer' && !wanted.has(zone.zoneId)) client.unobserve(zone.zoneId); + } + for (const zone of wanted) { + if (zone === authority) continue; + const existing = client.zone(zone); + if (existing?.role === 'observer') continue; + client.observe(zone).catch(() => undefined); + } + }; + + client.on('authority', (zone) => { + authorityCell = parseZone(zone); + syncNeighbours(); + }); + client.on('handoffComplete', () => { + handoffs += 1; + }); + onJsonEvent(client, EVENT_HELLO, (hello, zone) => { + infos.set(zone, hello); + seed = hello.seed; + if (hello.entity !== null && zone === client.authority?.zoneId) { + client.setControlledEntity(hello.entity); + resolveReady(hello); + } + const key = `${zone}@${hello.activatedAt}`; + if (hello.restored && !restoredSeen.has(key)) { + restoredSeen.add(key); + for (const listener of restoredListeners) listener(hello); + } + }); + + return { + client, + cell: () => authorityCell, + info: (zone) => infos.get(zone), + seed: () => seed, + props, + worldOf(entity) { + const cell = parseZone(entity.zoneId); + if (cell === undefined) return undefined; + return { x: cell[0] * CELL + num(entity.fields.x), y: cell[1] * CELL + num(entity.fields.y) }; + }, + handoffs: () => handoffs, + ready, + onRestored(listener) { + restoredListeners.add(listener); + return () => restoredListeners.delete(listener); + }, + async map(center, radius) { + const base = options.base ?? ''; + const response = await fetch(`${base}/dev/grid/map?x=${center[0]}&y=${center[1]}&r=${radius}`); + if (!response.ok) throw new Error(`/dev/grid/map: HTTP ${response.status}`); + return (await response.json()) as WorldMap; + }, + close: () => client.close() + }; +} diff --git a/examples/game/client/src/grid/grid.css b/examples/game/client/src/grid/grid.css new file mode 100644 index 000000000..0c190f7ca --- /dev/null +++ b/examples/game/client/src/grid/grid.css @@ -0,0 +1,71 @@ +.grid-toasts { + position: fixed; + top: 14px; + left: 50%; + transform: translateX(-50%); + display: flex; + flex-direction: column; + gap: 6px; + align-items: center; + pointer-events: none; + z-index: 5; + max-width: calc(100% - 32px); +} +.grid-toast { + padding: 7px 12px; + border-radius: 6px; + background: var(--panel); + border: 1px solid #2a3240; + transition: opacity 0.5s, transform 0.5s; +} +.grid-toast.restored { + border-color: #8fd3ff; + color: #cfeeff; +} +.grid-toast.host { + border-color: #ffb36b; +} +.grid-toast.error { + border-color: #ff6b6b; +} +.grid-toast.out { + opacity: 0; + transform: translateY(-6px); +} +.grid-map { + position: fixed; + right: 12px; + bottom: 12px; + padding: 8px; + border-radius: 8px; + background: var(--panel); +} +.grid-map canvas { + display: block; + width: 195px; + height: 195px; + image-rendering: pixelated; +} +.grid-legend { + margin-top: 6px; + font-size: 11px; + max-width: 195px; +} +.grid-legend .swatch { + display: inline-block; + width: 9px; + height: 9px; + margin-right: 5px; + border-radius: 2px; +} +.grid-legend small { + display: block; + margin-top: 3px; + color: var(--muted); +} +@media (max-width: 640px) { + .grid-map canvas { + width: 130px; + height: 130px; + } +} diff --git a/examples/game/client/src/grid/main.ts b/examples/game/client/src/grid/main.ts new file mode 100644 index 000000000..95f2c9828 --- /dev/null +++ b/examples/game/client/src/grid/main.ts @@ -0,0 +1,469 @@ +/** + * Endless Grid page: Babylon scene over `createGridClient`. + * + * - terrain, biomes and props of the 5×5 cells around you are generated + * locally from the seed (`world.ts`, bit-identical to the server) — + * nothing static comes over the wire; + * - cell borders are tinted by the host that runs the cell; the minimap + * (`/dev/grid/map`) shows active / hibernated / cold cells per host; + * - your walker is predicted; everything else (critters, other walkers, + * markers) is interpolated, from your cell and the 8 observed neighbours; + * - crossing a border hands you off (maybe to the other host); entering a + * cell that was hibernated shows a "restored from hibernation" toast. + * + * Rendering uses a floating origin at your current cell so coordinates stay + * small however far you walk. + */ +import { VertexBuffer } from '@babylonjs/core/Buffers/buffer'; +import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { Color3, Color4 } from '@babylonjs/core/Maths/math.color'; +import { Matrix, Vector3 } from '@babylonjs/core/Maths/math.vector'; +import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; +import type { InstancedMesh } from '@babylonjs/core/Meshes/instancedMesh'; +import type { LinesMesh } from '@babylonjs/core/Meshes/linesMesh'; +import { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { VertexData } from '@babylonjs/core/Meshes/mesh.vertexData'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import { Scene } from '@babylonjs/core/scene'; +import type { RenderedEntity } from '@hops-ops/distributed/game'; + +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { createStage, material } from '../shared/scene.ts'; +import { createGridClient, DEFAULT_ZONE, KIND, type GridHello, type MapCell, type WorldMap } from './client.ts'; +import { + BIOMES, + BUTTON_MARK, + BUTTON_SPRINT, + CELL, + PLAYER_RADIUS, + PROP_BUSH, + PROP_ROCK, + PROP_TREE, + biomeOf, + height, + moisture, + parseZone, + zoneId, + type Cell, + type MoveInput +} from './world.ts'; +import './grid.css'; + +const params = new URLSearchParams(location.search); +const startZone = params.get('zone') ?? DEFAULT_ZONE; +const name = params.get('name') ?? undefined; +const VIEW_CELLS = 2; +const RELIEF = 4; +const HOST_COLORS = ['#4ea1ff', '#ff9f43', '#b48cff', '#5fd39a']; + +const api = new DevApi({ name: () => name }); +const grid = createGridClient({ api }); +const { client } = grid; + +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: 1, background: '#a9c7e6' }); +const { scene, camera } = stage; +for (const mesh of [...scene.meshes]) if (mesh.name === 'floor' || mesh.name === 'wall') mesh.dispose(); +camera.radius = 26; +camera.upperRadiusLimit = 70; +scene.fogMode = Scene.FOGMODE_EXP2; +scene.fogDensity = 0.011; +scene.fogColor = Color3.FromHexString('#a9c7e6'); +scene.clearColor = Color4.FromHexString('#a9c7e6ff'); + +// ---- hosts ---- +const hostOrder: string[] = []; +function hostColor(host: string | undefined): string { + if (host === undefined) return '#8a8f99'; + if (!hostOrder.includes(host)) { + hostOrder.push(host); + hostOrder.sort(); + } + return HOST_COLORS[hostOrder.indexOf(host) % HOST_COLORS.length]!; +} +const owners = new Map(); + +// ---- floating origin ---- +let origin: Cell = parseZone(startZone) ?? [0, 0]; +function local(cell: Cell, x: number, y: number, up = 0): Vector3 { + return new Vector3((cell[0] - origin[0]) * CELL + x, terrain(cell, x, y) + up, (cell[1] - origin[1]) * CELL + y); +} +function terrain(cell: Cell, x: number, y: number): number { + const cx = Math.min(CELL, Math.max(0, x)); + const cy = Math.min(CELL, Math.max(0, y)); + return height(grid.seed(), cell, cx, cy) * RELIEF; +} + +// ---- terrain chunks ---- +const groundMat = new StandardMaterial('ground', scene); +groundMat.specularColor = Color3.Black(); +const BIOME_COLORS = [ + Color3.FromHexString('#8c8579'), + Color3.FromHexString('#c9b36b'), + Color3.FromHexString('#3d7638'), + Color3.FromHexString('#7cae4c') +]; + +/** Instancing templates; a tree is two instances (trunk + canopy). */ +const templates = (() => { + const trunk = MeshBuilder.CreateCylinder('trunk', { diameter: 0.5, height: 2.2, tessellation: 8 }, scene); + trunk.position.y = 1.1; + trunk.bakeCurrentTransformIntoVertices(); + trunk.material = material(scene, 'bark', '#6b4a2f'); + const canopy = MeshBuilder.CreateCylinder('canopy', { diameterTop: 0, diameterBottom: 3, height: 3.6, tessellation: 9 }, scene); + canopy.position.y = 3.6; + canopy.bakeCurrentTransformIntoVertices(); + canopy.material = material(scene, 'leaves', '#2f6b34'); + const rock = MeshBuilder.CreateIcoSphere('rock', { radius: 1, subdivisions: 1, flat: true }, scene); + rock.scaling.y = 0.6; + rock.bakeCurrentTransformIntoVertices(); + rock.material = material(scene, 'stone', '#6f737a'); + const bush = MeshBuilder.CreateSphere('bush', { diameter: 2, segments: 6 }, scene); + bush.scaling.y = 0.55; + bush.bakeCurrentTransformIntoVertices(); + bush.material = material(scene, 'shrub', '#4f8f3a'); + for (const m of [trunk, canopy, rock, bush]) m.setEnabled(false); + return { [PROP_TREE]: [trunk, canopy], [PROP_ROCK]: [rock], [PROP_BUSH]: [bush] } as Record; +})(); + +// Props are not parented to the ground: instanced children of a moved +// parent rendered fully fogged (white) here, so they are placed directly. +type Chunk = { cell: Cell; ground: Mesh; props: { mesh: InstancedMesh; at: Vector3 }[]; border: LinesMesh; owner?: string }; +const chunks = new Map(); + +function chunkColors(cell: Cell, ground: Mesh, owner: string | undefined): void { + const positions = ground.getVerticesData(VertexBuffer.PositionKind)!; + const colors = new Float32Array((positions.length / 3) * 4); + const tint = owner === undefined ? undefined : Color3.FromHexString(hostColor(owner)); + const seed = grid.seed(); + for (let i = 0; i < positions.length / 3; i += 1) { + const lx = positions[i * 3]! + CELL / 2; + const ly = positions[i * 3 + 2]! + CELL / 2; + const h = height(seed, cell, lx, ly); + const b = biomeOf(h, moisture(seed, cell, lx, ly)); + let c = BIOME_COLORS[b]!.scale(0.72 + h * 0.55); + if (lx % 8 === 0 || ly % 8 === 0) c = Color3.Lerp(c, Color3.FromHexString('#d9c9a3'), 0.28); // trails + if (tint !== undefined) c = Color3.Lerp(c, tint, 0.1); + colors.set([c.r, c.g, c.b, 1], i * 4); + } + ground.setVerticesData(VertexBuffer.ColorKind, colors); +} + +function createChunk(cell: Cell): Chunk { + const key = zoneId(cell); + const ground = MeshBuilder.CreateGround(`ground-${key}`, { width: CELL, height: CELL, subdivisions: 16, updatable: true }, scene); + const positions = ground.getVerticesData(VertexBuffer.PositionKind)!; + for (let i = 0; i < positions.length / 3; i += 1) { + positions[i * 3 + 1] = height(grid.seed(), cell, positions[i * 3]! + CELL / 2, positions[i * 3 + 2]! + CELL / 2) * RELIEF; + } + const normals: number[] = []; + VertexData.ComputeNormals(positions, ground.getIndices()!, normals); + ground.updateVerticesData(VertexBuffer.PositionKind, positions); + ground.updateVerticesData(VertexBuffer.NormalKind, normals); + ground.material = groundMat; + const owner = owners.get(key); + chunkColors(cell, ground, owner); + + const props: Chunk['props'] = []; + for (const [i, p] of grid.props(cell).entries()) { + for (const [j, template] of templates[p.kind]!.entries()) { + const inst = template.createInstance(`prop-${key}-${i}-${j}`); + inst.scaling.setAll(p.kind === PROP_TREE ? p.r / 0.55 : p.r); + inst.rotation.y = (p.variant / 255) * Math.PI * 2; + props.push({ mesh: inst, at: new Vector3(p.x - CELL / 2, terrain(cell, p.x, p.y) - 0.1, p.y - CELL / 2) }); + } + } + + const edge: Vector3[] = []; + const at = (x: number, y: number) => new Vector3(x - CELL / 2, terrain(cell, x, y) + 0.08, y - CELL / 2); + for (let k = 0; k <= 16; k += 1) edge.push(at(k * 2, 0)); + for (let k = 1; k <= 16; k += 1) edge.push(at(CELL, k * 2)); + for (let k = 15; k >= 0; k -= 1) edge.push(at(k * 2, CELL)); + for (let k = 15; k >= 0; k -= 1) edge.push(at(0, k * 2)); + const border = MeshBuilder.CreateLines(`border-${key}`, { points: edge }, scene); + border.parent = ground; + border.color = Color3.FromHexString(hostColor(owner)); + return { cell, ground, props, border, owner }; +} + +function syncChunks(): void { + const wanted = new Set(); + for (let dy = -VIEW_CELLS; dy <= VIEW_CELLS; dy += 1) { + for (let dx = -VIEW_CELLS; dx <= VIEW_CELLS; dx += 1) { + const cell: Cell = [origin[0] + dx, origin[1] + dy]; + const key = zoneId(cell); + wanted.add(key); + if (!chunks.has(key)) chunks.set(key, createChunk(cell)); + } + } + for (const [key, chunk] of chunks) { + if (!wanted.has(key)) { + for (const prop of chunk.props) prop.mesh.dispose(); + chunk.ground.dispose(false, true); + chunks.delete(key); + continue; + } + chunk.ground.position.set((chunk.cell[0] - origin[0]) * CELL + CELL / 2, 0, (chunk.cell[1] - origin[1]) * CELL + CELL / 2); + for (const prop of chunk.props) prop.mesh.position.copyFrom(chunk.ground.position.add(prop.at)); + const owner = owners.get(key); + if (owner !== chunk.owner) { + chunk.owner = owner; + chunk.border.color = Color3.FromHexString(hostColor(owner)); + chunkColors(chunk.cell, chunk.ground, owner); + } + } +} + +function moveOrigin(to: Cell): void { + if (to[0] === origin[0] && to[1] === origin[1]) return; + const shift = new Vector3((to[0] - origin[0]) * CELL, 0, (to[1] - origin[1]) * CELL); + origin = to; + camera.setTarget(camera.target.subtract(shift)); + syncChunks(); +} + +// ---- entities ---- +function hueColor(hue: number, s = 0.65, v = 0.95): Color3 { + const c = new Color3(); + Color3.HSVtoRGBToRef((hue / 255) * 360, s, v, c); + return c; +} +const mats = new Map(); +function hueMat(hue: number, kind: string): StandardMaterial { + const key = `${kind}-${hue}`; + let m = mats.get(key); + if (m === undefined) { + m = new StandardMaterial(key, scene); + m.diffuseColor = hueColor(hue, kind === 'critter' ? 0.45 : 0.7); + m.specularColor = new Color3(0.1, 0.1, 0.1); + mats.set(key, m); + } + return m; +} +const meMat = material(scene, 'me', '#ffffff'); +meMat.emissiveColor = Color3.FromHexString('#2a4c66'); + +type Visual = { mesh: AbstractMesh; kind: string }; +const visuals = new Map(); +function visualFor(entity: RenderedEntity, mine: boolean): Visual { + let visual = visuals.get(entity.key); + const hue = typeof entity.fields.hue === 'number' ? entity.fields.hue : 0; + if (visual !== undefined) return visual; + let mesh: AbstractMesh; + if (entity.kindName === KIND.critter) { + const body = MeshBuilder.CreateSphere(entity.key, { diameter: 0.7, segments: 8 }, scene); + body.scaling.set(1.2, 0.7, 0.8); + body.material = hueMat(hue, 'critter'); + mesh = body; + } else if (entity.kindName === KIND.marker) { + const pole = MeshBuilder.CreateCylinder(entity.key, { diameter: 0.08, height: 2.2 }, scene); + pole.bakeTransformIntoVertices(Matrix.Translation(0, 1.1, 0)); + const flag = MeshBuilder.CreateBox(`${entity.key}-flag`, { width: 0.8, height: 0.5, depth: 0.04 }, scene); + flag.parent = pole; + flag.position.set(0.42, 1.9, 0); + flag.material = hueMat(hue, 'marker'); + mesh = pole; + } else { + const capsule = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + capsule.material = mine ? meMat : hueMat(hue, 'walker'); + mesh = capsule; + } + visual = { mesh, kind: entity.kindName }; + visuals.set(entity.key, visual); + return visual; +} + +// ---- HUD, toasts, minimap ---- +const hud = new Hud({ + title: 'Endless Grid', + hint: 'WASD / stick to walk, Space/Shift to sprint, E to drop a marker. Trails (light lines) are always free.', + client, + devApi: api +}); +const toasts = document.createElement('div'); +toasts.className = 'grid-toasts'; +document.body.append(toasts); +function toast(text: string, kind = ''): void { + const el = document.createElement('div'); + el.className = `grid-toast ${kind}`.trim(); + el.textContent = text; + toasts.append(el); + setTimeout(() => el.classList.add('out'), 4200); + setTimeout(() => el.remove(), 4800); +} +// Restores arrive in bursts (walking back wakes a cell and its neighbours): +// one toast per burst. +let restoredBurst: GridHello[] = []; +grid.onRestored((hello) => { + restoredBurst.push(hello); + if (restoredBurst.length > 1) return; + setTimeout(() => { + const burst = restoredBurst; + restoredBurst = []; + const here = burst.find((h) => h.zone === client.authority?.zoneId) ?? burst[0]!; + const slept = here.hibernatedForMs === null ? '' : ` after ${(here.hibernatedForMs / 1000).toFixed(1)} s`; + const others = burst.length > 1 ? ` (+${burst.length - 1} neighbour${burst.length > 2 ? 's' : ''})` : ''; + toast( + `${here.zone} restored from hibernation${slept} on host ${here.host}: ${here.restoredCritters} critters, ${here.restoredMarkers} markers${others}`, + 'restored' + ); + }, 400); +}); +let lastHost: string | undefined; +client.on('handoffComplete', ({ to }) => { + const host = grid.info(to)?.host; + if (host !== undefined && lastHost !== undefined && host !== lastHost) toast(`Crossed into ${to} — now on host ${host}`, 'host'); + lastHost = host ?? lastHost; +}); +client.on('handoffFailed', ({ to, reason }) => toast(`Handoff to ${to} failed: ${reason}`, 'error')); + +const mapBox = document.createElement('div'); +mapBox.className = 'grid-map'; +const mapCanvas = document.createElement('canvas'); +const MAP_R = 6; +const MAP_PX = 15; +mapCanvas.width = mapCanvas.height = (MAP_R * 2 + 1) * MAP_PX; +const legend = document.createElement('div'); +legend.className = 'grid-legend'; +mapBox.append(mapCanvas, legend); +document.body.append(mapBox); +let worldMap: WorldMap | undefined; + +function drawMap(): void { + const ctx = mapCanvas.getContext('2d'); + if (ctx === null || worldMap === undefined) return; + const center = grid.cell() ?? origin; + ctx.clearRect(0, 0, mapCanvas.width, mapCanvas.height); + const observed = new Set(client.zones().filter((z) => z.role === 'observer').map((z) => z.zoneId)); + for (const cell of worldMap.cells as MapCell[]) { + const px = (cell.x - center[0] + MAP_R) * MAP_PX; + const py = (MAP_R - (cell.y - center[1])) * MAP_PX; + if (px < 0 || py < 0 || px >= mapCanvas.width || py >= mapCanvas.height) continue; + ctx.globalAlpha = cell.state === 'active' ? 0.9 : cell.state === 'hibernated' ? 0.4 : 0.1; + ctx.fillStyle = hostColor(cell.owner); + ctx.fillRect(px + 1, py + 1, MAP_PX - 2, MAP_PX - 2); + ctx.globalAlpha = 1; + if (cell.state === 'hibernated') { + ctx.fillStyle = '#e8f1ff'; + ctx.font = '10px ui-monospace, monospace'; + ctx.fillText('z', px + 4, py + 11); + } + if (observed.has(cell.zone)) { + ctx.strokeStyle = 'rgba(255,255,255,0.45)'; + ctx.strokeRect(px + 1.5, py + 1.5, MAP_PX - 3, MAP_PX - 3); + } + if (cell.x === center[0] && cell.y === center[1]) { + ctx.strokeStyle = '#ffffff'; + ctx.lineWidth = 2; + ctx.strokeRect(px + 1, py + 1, MAP_PX - 2, MAP_PX - 2); + ctx.lineWidth = 1; + } + } + legend.replaceChildren( + ...worldMap.hosts.map((h) => { + const row = document.createElement('div'); + const swatch = document.createElement('span'); + swatch.className = 'swatch'; + swatch.style.background = hostColor(h.id); + row.append(swatch, `host ${h.id}: ${h.active} active, ${h.hibernated} asleep${h.reachable ? '' : ' (unreachable)'}`); + return row; + }), + Object.assign(document.createElement('small'), { textContent: 'bright = active · dim z = hibernated · faint = cold' }) + ); +} + +async function pollMap(): Promise { + try { + worldMap = await grid.map(grid.cell() ?? origin, MAP_R); + for (const cell of worldMap.cells) owners.set(cell.zone, cell.owner); + drawMap(); + } catch { + legend.textContent = 'world map unavailable (dev routes off?)'; + } +} +setInterval(() => void pollMap(), 1000); +void pollMap(); + +// ---- input ---- +const sampler = new InputSampler(); +const commandFrames = new FixedRate(30); +let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; +function sendCommandFrame(): void { + const s = sampler.sample(); + const move = cameraRelative(s, stage.cameraForward()); + lastInput = { + mx: toAxis(move.x), + my: toAxis(move.y), + buttons: (s.action ? BUTTON_SPRINT : 0) | (s.alt ? BUTTON_MARK : 0) + }; + client.sendInput(lastInput); +} + +// ---- frame ---- +syncChunks(); +stage.onFrame((now, dtMs) => { + commandFrames.advance(now, sendCommandFrame); + const cell = grid.cell(); + if (cell !== undefined) moveOrigin(cell); + const rendered = client.render(); + const seen = new Set(); + const hello = cell === undefined ? undefined : grid.info(zoneId(cell)); + let me: Vector3 | undefined; + let markers = 0; + for (const entity of rendered) { + const ecell = parseZone(entity.zoneId); + if (ecell === undefined) continue; + const mine = entity.predicted || (entity.authoritative && hello?.entity === entity.id); + const visual = visualFor(entity, mine); + const x = Number(entity.fields.x ?? 0); + const y = Number(entity.fields.y ?? 0); + seen.add(entity.key); + if (visual.kind === KIND.critter) { + visual.mesh.position.copyFrom(local(ecell, x, y, 0.3)); + visual.mesh.rotation.y = -Number(entity.fields.yaw ?? 0); + } else if (visual.kind === KIND.marker) { + visual.mesh.position.copyFrom(local(ecell, x, y)); + stage.labels.set(entity.key, visual.mesh, `⚑ ${String(entity.fields.label ?? '')}`, 2.6); + if (entity.authoritative) markers += 1; + } else { + visual.mesh.position.copyFrom(local(ecell, x, y, 0.9)); + const label = String(entity.fields.name ?? ''); + stage.labels.set(entity.key, visual.mesh, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); + if (mine) me = visual.mesh.position; + } + visual.mesh.setEnabled(!entity.stale); + } + for (const [key, visual] of visuals) { + if (seen.has(key)) continue; + visual.mesh.dispose(false, true); + stage.labels.delete(key); + visuals.delete(key); + } + if (me !== undefined) stage.follow(me.x, me.z, dtMs); + + hud.frame({ entities: rendered.length }); + const observers = client.zones().filter((z) => z.role === 'observer'); + const predicted = client.predictor?.active === true ? client.predictor.predicted() : undefined; + const px = Number(predicted?.x ?? 16); + const py = Number(predicted?.y ?? 16); + hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); + hud.row('Cell', cell === undefined ? '—' : `${cell[0]}, ${cell[1]} · local ${px.toFixed(1)}, ${py.toFixed(1)}`); + hud.row('Host', hello?.host ?? '—'); + hud.row('Biome', cell === undefined ? '—' : BIOMES[biomeOf(height(grid.seed(), cell, px, py), moisture(grid.seed(), cell, px, py))]!); + hud.row('Neighbours', `${observers.filter((z) => z.connection.state === 'open').length}/8 observed`); + hud.row('Handoffs', String(grid.handoffs())); + hud.row('Markers here', String(markers)); + hud.row('Seed', `0x${grid.seed().toString(16)}`); +}); + +declare global { + interface Window { + /** Debug handle (console). */ + grid?: unknown; + } +} +window.grid = { grid, client, api, scene }; + +client.connect(startZone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/grid/world.ts b/examples/game/client/src/grid/world.ts new file mode 100644 index 000000000..e47c07edf --- /dev/null +++ b/examples/game/client/src/grid/world.ts @@ -0,0 +1,245 @@ +/** + * Procedural world and movement of the Endless Grid. + * + * **Twin of `examples/game/server/src/grid/world.rs`** — the server uses it + * for collision, the client for rendering and prediction; nothing static + * is replicated. Bit-identical by construction: `u32` hashing with + * `Math.imul` / `>>> 0`, binary32 arithmetic with `f()` (= `Math.fround`) + * after every operation, only `+ - * /`, `sqrt` and `floor`. + * `tests/grid-world-parity.test.mjs` replays the Rust-written fixture + * `examples/game/fixtures/grid-world.json`. + * + * No imports except the SDK quantizers so Node can run it directly. + */ +import { dequantizeLinear, quantizeLinear } from '@hops-ops/distributed/game'; + +const f = Math.fround; + +export const CELL = 32; +export const CONTENT_VERSION = 1; +export const DEFAULT_SEED = 0x00c0ffee; +export const SUB = 4; +export const SUB_SIZE = 8; +export const PROP_MARGIN = 2; +export const PROP_SPAN = 4; +export const HYSTERESIS = 0.5; +export const PLAYER_RADIUS = f(0.45); +export const WALK_SPEED = 6; +export const SPRINT_SPEED = 10; +export const DT = f(1 / 30); +export const OUTSIDE_LIMIT = 2; +export const BUTTON_SPRINT = 1; +export const BUTTON_MARK = 2; +/** Wire quantization of local positions (server `grid::world::POS`). */ +export const POS = { min: -8, max: 40, bits: 18 } as const; + +export const BIOMES = ['highlands', 'steppe', 'forest', 'meadow'] as const; +const PROP_DENSITY = [0.4375, 0.1875, 0.75, 0.3125]; +const SALT_HEIGHT = [1, 2, 3]; +const SALT_MOISTURE = 7; +const SALT_PROP = 100; + +export const PROP_TREE = 0; +export const PROP_ROCK = 1; +export const PROP_BUSH = 2; + +export type Prop = Readonly<{ kind: number; x: number; y: number; r: number; solid: boolean; variant: number }>; +export type Cell = readonly [number, number]; + +/** lowbias32. */ +export function hash32(v: number): number { + let x = v >>> 0; + x = (x ^ (x >>> 16)) >>> 0; + x = Math.imul(x, 0x7feb352d) >>> 0; + x = (x ^ (x >>> 15)) >>> 0; + x = Math.imul(x, 0x846ca68b) >>> 0; + x = (x ^ (x >>> 16)) >>> 0; + return x; +} + +export function mix(seed: number, salt: number, a: number, b: number): number { + const salted = ((salt >>> 0) + (Math.imul(CONTENT_VERSION, 0x9e3779b9) >>> 0)) >>> 0; + let h = hash32((seed ^ hash32(salted)) >>> 0); + h = hash32((h ^ (a >>> 0)) >>> 0); + return hash32((h + (Math.imul(b | 0, 0x85ebca6b) >>> 0)) >>> 0); +} + +/** Top 24 bits in [0, 1) (exact binary32). */ +export function unit(h: number): number { + return (h >>> 8) * (1 / 16777216); +} + +function lattice(c: number, l: number, spacing: number): [number, number] { + const s = spacing; + if (spacing <= CELL) { + const per = CELL / spacing; + const k = Math.max(0, Math.min(per, Math.floor(f(l / s)))); + const frac = f(f(l - k * spacing) / s); + return [(Math.imul(c, per) + k) | 0, frac]; + } + const n = spacing / CELL; + let i = Math.floor(c / n); + let off = f(f((c - i * n) * CELL) + l); + if (off >= s) { + i = (i + 1) | 0; + off = f(off - s); + } + return [i, f(off / s)]; +} + +function smooth(t: number): number { + return f(f(t * t) * f(3 - f(2 * t))); +} + +function lerp(a: number, b: number, t: number): number { + return f(a + f(f(b - a) * t)); +} + +/** Value noise in [0, 1) with lattice `spacing` (m). */ +export function noise(seed: number, salt: number, cell: Cell, lx: number, ly: number, spacing: number): number { + const [ix, fx] = lattice(cell[0], lx, spacing); + const [iy, fy] = lattice(cell[1], ly, spacing); + const v = (dx: number, dy: number) => unit(mix(seed, salt, (ix + dx) | 0, (iy + dy) | 0)); + const sx = smooth(fx); + const sy = smooth(fy); + return lerp(lerp(v(0, 0), v(1, 0), sx), lerp(v(0, 1), v(1, 1), sx), sy); +} + +/** Terrain height in [0, 1). */ +export function height(seed: number, cell: Cell, lx: number, ly: number): number { + const a = f(noise(seed, SALT_HEIGHT[0]!, cell, lx, ly, 64) * 0.5625); + const b = f(noise(seed, SALT_HEIGHT[1]!, cell, lx, ly, 16) * 0.3125); + const c = f(noise(seed, SALT_HEIGHT[2]!, cell, lx, ly, 8) * 0.125); + return f(f(a + b) + c); +} + +export function moisture(seed: number, cell: Cell, lx: number, ly: number): number { + return noise(seed, SALT_MOISTURE, cell, lx, ly, 128); +} + +/** Biome index into BIOMES (given height and moisture, or computed). */ +export function biome(seed: number, cell: Cell, lx: number, ly: number): number { + return biomeOf(height(seed, cell, lx, ly), moisture(seed, cell, lx, ly)); +} + +export function biomeOf(h: number, m: number): number { + if (h > 0.6875) return 0; + if (m < 0.375) return 1; + if (m > 0.625) return 2; + return 3; +} + +/** The props of a cell, sub-cell by sub-cell (row-major). */ +export function cellProps(seed: number, cell: Cell): Prop[] { + const props: Prop[] = []; + for (let j = 0; j < SUB; j += 1) { + for (let i = 0; i < SUB; i += 1) { + const gx = (Math.imul(cell[0], SUB) + i) | 0; + const gy = (Math.imul(cell[1], SUB) + j) | 0; + const h0 = mix(seed, SALT_PROP, gx, gy); + const b = biome(seed, cell, i * SUB_SIZE + SUB_SIZE / 2, j * SUB_SIZE + SUB_SIZE / 2); + if (unit(h0) >= PROP_DENSITY[b]!) continue; + const h1 = hash32((h0 ^ 0x68e31da4) >>> 0); + const h2 = hash32((h1 ^ 0xb5297a4d) >>> 0); + const h3 = hash32((h2 ^ 0x1b56c4e9) >>> 0); + const h4 = hash32((h3 ^ 0x2545f491) >>> 0); + const x = f(f(i * SUB_SIZE + PROP_MARGIN) + f(unit(h1) * PROP_SPAN)); + const y = f(f(j * SUB_SIZE + PROP_MARGIN) + f(unit(h2) * PROP_SPAN)); + const k = unit(h3); + let kind: number; + if (b === 0) kind = k < 0.8125 ? PROP_ROCK : PROP_TREE; + else if (b === 1) kind = k < 0.5 ? PROP_ROCK : PROP_BUSH; + else if (b === 2) kind = k < 0.8125 ? PROP_TREE : k < 0.875 ? PROP_ROCK : PROP_BUSH; + else kind = k < 0.375 ? PROP_TREE : k < 0.5625 ? PROP_ROCK : PROP_BUSH; + const u = unit(h4); + const r = + kind === PROP_TREE + ? f(0.5 + f(u * 0.3125)) + : kind === PROP_ROCK + ? f(0.625 + f(u * 0.375)) + : f(0.5 + f(u * 0.25)); + props.push({ kind, x, y, r, solid: kind !== PROP_BUSH, variant: h4 >>> 24 }); + } + } + return props; +} + +/** One command frame: stick per axis in [-127, 127] and button bits. */ +export type MoveInput = Readonly<{ mx: number; my: number; buttons: number }>; + +export function encodeMoveInput(input: MoveInput): Uint8Array { + return new Uint8Array([input.mx & 0xff, input.my & 0xff, input.buttons & 0xff]); +} + +/** The server's sanitization: -128 → -127, unknown buttons cleared. */ +export function sanitizeMoveInput(input: MoveInput): MoveInput { + const axis = (v: number) => Math.max(-127, Math.min(127, Math.trunc(v))); + return { mx: axis(input.mx), my: axis(input.my), buttons: input.buttons & (BUTTON_SPRINT | BUTTON_MARK) }; +} + +export function snap(v: number): number { + return dequantizeLinear(quantizeLinear(v, POS.min, POS.max, POS.bits), POS.min, POS.max, POS.bits); +} + +export function collide(x0: number, y0: number, radius: number, props: readonly Prop[]): [number, number] { + let x = x0; + let y = y0; + for (const p of props) { + if (!p.solid) continue; + const ox = f(x - p.x); + const oy = f(y - p.y); + const d2 = f(f(ox * ox) + f(oy * oy)); + const min = f(radius + p.r); + if (d2 < f(min * min)) { + const d = f(Math.sqrt(d2)); + const [nx, ny] = d > f(1e-6) ? [f(ox / d), f(oy / d)] : [1, 0]; + x = f(p.x + f(nx * min)); + y = f(p.y + f(ny * min)); + } + } + return [x, y]; +} + +/** Advance a walker one command frame inside its cell (see the Rust docs). */ +export function step(x: number, y: number, raw: MoveInput, props: readonly Prop[]): [number, number] { + const input = sanitizeMoveInput(raw); + let dx = f(input.mx / 127); + let dy = f(input.my / 127); + const l2 = f(f(dx * dx) + f(dy * dy)); + if (l2 > 1) { + const inv = f(1 / f(Math.sqrt(l2))); + dx = f(dx * inv); + dy = f(dy * inv); + } + const speed = (input.buttons & BUTTON_SPRINT) !== 0 ? SPRINT_SPEED : WALK_SPEED; + const nx = f(x + f(f(dx * speed) * DT)); + const ny = f(y + f(f(dy * speed) * DT)); + const [cx, cy] = collide(nx, ny, PLAYER_RADIUS, props); + const lo = -OUTSIDE_LIMIT; + const hi = CELL + OUTSIDE_LIMIT; + return [snap(Math.min(hi, Math.max(lo, cx))), snap(Math.min(hi, Math.max(lo, cy)))]; +} + +/** Neighbour offset a walker belongs to past the hysteresis (x first), or undefined. */ +export function crossing(x: number, y: number): [number, number] | undefined { + if (x < -HYSTERESIS) return [-1, 0]; + if (x > CELL + HYSTERESIS) return [1, 0]; + if (y < -HYSTERESIS) return [0, -1]; + if (y > CELL + HYSTERESIS) return [0, 1]; + return undefined; +} + +export const MAX_CELL = 1_000_000; + +export function zoneId(cell: Cell): string { + return `grid.${cell[0]}.${cell[1]}`; +} + +export function parseZone(zone: string): [number, number] | undefined { + const m = /^grid\.(-?\d+)\.(-?\d+)$/.exec(zone); + if (m === null) return undefined; + const x = Number(m[1]); + const y = Number(m[2]); + if (String(x) !== m[1] || String(y) !== m[2] || Math.abs(x) > MAX_CELL || Math.abs(y) > MAX_CELL) return undefined; + return [x, y]; +} diff --git a/examples/game/client/src/ripple/client.ts b/examples/game/client/src/ripple/client.ts new file mode 100644 index 000000000..4c197b66a --- /dev/null +++ b/examples/game/client/src/ripple/client.ts @@ -0,0 +1,215 @@ +/** + * Boss Ripple networking without rendering (Node-testable): + * + * - the player's authoritative zone is one neighborhood (predicted with + * the Arena movement step; the boss stands on the central pillar); + * - every other zone of the hierarchy is observed (realm, city, boroughs + * and the other hoods), so the page shows each tier's live state and + * receives what upper tiers broadcast: ripple events, the city's + * weather, the realm's banner. + */ +import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; + +import { encodeMoveInput, predictPlayer } from '../arena/movement.ts'; +import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import { onJsonEvent } from '../shared/events.ts'; + +export const REALM = 'realm'; +export const CITY = 'realm.city'; +export const BOROUGHS = ['realm.city.borough-1', 'realm.city.borough-2'] as const; +export const HOODS_PER_BOROUGH = 3; +export const DEFAULT_ZONE = 'realm.city.borough-1.hood-1'; +/** Event type ids (server `ripple::EVENT_*`). */ +export const EVENT = { hello: 1, ripple: 2, weather: 3, banner: 4, boss: 5 } as const; +export const ACTION_ATTACK = 1; +export const ACTION_SMITE = 2; +export const WEATHER = ['storm', 'rain', 'clearing', 'clear'] as const; + +export type HoodInput = Readonly<{ mx: number; my: number; buttons: number; action: number }>; +export type TierName = 'realm' | 'city' | 'borough' | 'hood'; + +export type RippleHello = Readonly<{ + zone: string; + tier: TierName; + parent: string | null; + children: string[]; + host: string; + tickRate: number; + entity: number | null; + weather: Readonly<{ weather: string; remaining: number }> | null; + banner: string; +}>; + +export type RippleEvent = Readonly<{ at: string; kind: string; from: string; origin: string; originTick: number; tick: number }>; + +/** Live state of one tier, from its replicated `tier` (and `boss`) entity. */ +export type TierView = Readonly<{ + zone: string; + hello: RippleHello | undefined; + connected: boolean; + defeated: number; + total: number; + cleared: number; + liberated: boolean; + weather: string; + clock: number; + events: number; + boss?: Readonly<{ hp: number; max: number; by: string }>; +}>; + +export function hoods(borough: string): string[] { + return Array.from({ length: HOODS_PER_BOROUGH }, (_, i) => `${borough}.hood-${i + 1}`); +} + +/** Every zone, root first (tree order). */ +export function allZones(): string[] { + const out = [REALM, CITY]; + for (const b of BOROUGHS) out.push(b, ...hoods(b)); + return out; +} + +export function tierOf(zone: string): TierName | undefined { + if (zone === REALM) return 'realm'; + if (zone === CITY) return 'city'; + if ((BOROUGHS as readonly string[]).includes(zone)) return 'borough'; + return BOROUGHS.some((b) => hoods(b).includes(zone)) ? 'hood' : undefined; +} + +export function encodeHoodInput(input: HoodInput): Uint8Array { + const move = encodeMoveInput(input); + return new Uint8Array([move[0]!, move[1]!, move[2]!, input.action & 0xff]); +} + +export type RippleClientOptions = Readonly<{ + api: DevApi; + base?: string; + socket?: GameSocketFactory; + /** Observe every other zone of the hierarchy (default true). */ + observeAll?: boolean; +}>; + +export type RippleClient = Readonly<{ + client: GameClient; + /** Resolves on the first hello of the player's hood. */ + ready: Promise; + tier(zone: string): TierView; + /** Ripple events received (newest last, bounded). */ + ripples(): readonly RippleEvent[]; + weather(): string | undefined; + banner(): string | undefined; + onRipple(listener: (event: RippleEvent) => void): () => void; + onBanner(listener: (text: string) => void): () => void; + onWeather(listener: (weather: string) => void): () => void; + onBoss(listener: (zone: string, event: { kind: string; by?: string }) => void): () => void; + /** Join `hood` as the player's zone (switches authority). */ + enter(hood: string): Promise; + /** One input with the smite bit (demo shortcut). */ + smite(): void; + close(): void; +}>; + +export function createRippleClient(options: RippleClientOptions): RippleClient { + const hellos = new Map(); + const ripples: RippleEvent[] = []; + let weather: string | undefined; + let banner: string | undefined; + const listeners = { + ripple: new Set<(e: RippleEvent) => void>(), + banner: new Set<(t: string) => void>(), + weather: new Set<(w: string) => void>(), + boss: new Set<(z: string, e: { kind: string; by?: string }) => void>() + }; + const ease = { mode: 'ease', durationMs: 150 } as const; + const snap = { mode: 'snap' } as const; + const client = new GameClient({ + url: (zone) => zoneUrl(zone, options.base), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 1000, + inputDtMs: 1000 / 30, + prediction: { + encodeInput: (input) => encodeHoodInput(input), + predict: (fields, input) => predictPlayer(fields, input), + corrections: { player: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } } + } + }); + let resolveReady: (h: RippleHello) => void = () => undefined; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + onJsonEvent(client, EVENT.hello, (hello, zone) => { + hellos.set(zone, hello); + if (hello.weather !== null) weather = hello.weather.weather; + if (hello.tier === 'realm' && hello.banner !== '') banner = hello.banner; + if (hello.entity !== null && zone === client.authority?.zoneId) { + client.setControlledEntity(hello.entity); + resolveReady(hello); + } + }); + onJsonEvent(client, EVENT.ripple, (event) => { + ripples.push(event); + if (ripples.length > 200) ripples.shift(); + for (const l of listeners.ripple) l(event); + }); + onJsonEvent<{ weather: string }>(client, EVENT.weather, (value) => { + weather = value.weather; + for (const l of listeners.weather) l(value.weather); + }); + onJsonEvent<{ text: string }>(client, EVENT.banner, (value) => { + banner = value.text; + for (const l of listeners.banner) l(value.text); + }); + onJsonEvent<{ kind: string; by?: string }>(client, EVENT.boss, (value, zone) => { + for (const l of listeners.boss) l(zone, value); + }); + + const observeOthers = () => { + if (options.observeAll === false) return; + const authority = client.authority?.zoneId; + for (const zone of allZones()) { + if (zone === authority || client.zone(zone)?.role === 'observer') continue; + client.observe(zone).catch(() => undefined); + } + }; + client.on('authority', observeOthers); + + const on = (set: Set, l: T) => { + set.add(l); + return () => set.delete(l); + }; + const n = (v: unknown) => (typeof v === 'number' ? v : typeof v === 'boolean' ? Number(v) : 0); + + return { + client, + ready, + tier(zone) { + const view = client.zone(zone); + const tier = view?.replica.get(1)?.fields ?? {}; + const boss = view?.replica.get(2)?.fields; + return { + zone, + hello: hellos.get(zone), + connected: view?.connection.state === 'open', + defeated: n(tier.defeated), + total: n(tier.total), + cleared: n(tier.cleared), + liberated: tier.liberated === true, + weather: WEATHER[n(tier.weather)] ?? 'storm', + clock: n(tier.clock), + events: n(tier.events), + boss: boss === undefined ? undefined : { hp: n(boss.hp), max: n(boss.max), by: String(boss.by ?? '') } + }; + }, + ripples: () => ripples, + weather: () => weather, + banner: () => banner, + onRipple: (l) => on(listeners.ripple, l), + onBanner: (l) => on(listeners.banner, l), + onWeather: (l) => on(listeners.weather, l), + onBoss: (l) => on(listeners.boss, l), + enter: (hood) => client.connect(hood), + smite() { + client.sendInput({ mx: 0, my: 0, buttons: 0, action: ACTION_SMITE }); + }, + close: () => client.close() + }; +} diff --git a/examples/game/client/src/ripple/main.ts b/examples/game/client/src/ripple/main.ts new file mode 100644 index 000000000..08ea55536 --- /dev/null +++ b/examples/game/client/src/ripple/main.ts @@ -0,0 +1,325 @@ +/** + * Boss Ripple page: a playable neighborhood (Babylon) next to the live + * hierarchy (DOM + SVG), both over `createRippleClient`. + * + * - fight the boss in your hood (E near it, or "Smite"); its defeat travels + * up as tier-up events — watch the pulse climb hood → borough → city → + * realm in the tree (each hop is a cross-host admin call with two hosts); + * - the borough unlocks when all its bosses fell, the city's weather + * follows the remaining bosses (it is broadcast to everyone observing + * the city — including you, so the sky over your hood changes), and the + * realm shows a banner when the city is liberated; + * - each tier shows its own tick rate and clock (realm 2 Hz … hood 30 Hz). + */ +import { Color3, Color4 } from '@babylonjs/core/Maths/math.color'; +import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import { Scene } from '@babylonjs/core/scene'; +import type { RenderedEntity } from '@hops-ops/distributed/game'; + +import { BUTTON_DASH, HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { createStage, material, toWorld } from '../shared/scene.ts'; +import { + ACTION_ATTACK, + ACTION_SMITE, + allZones, + createRippleClient, + DEFAULT_ZONE, + tierOf, + type HoodInput, + type RippleEvent +} from './client.ts'; +import './ripple.css'; + +const params = new URLSearchParams(location.search); +let hood = params.get('hood') ?? DEFAULT_ZONE; +if (tierOf(hood) !== 'hood') hood = DEFAULT_ZONE; +const name = params.get('name') ?? undefined; + +const api = new DevApi({ name: () => name }); +const ripple = createRippleClient({ api }); +const { client } = ripple; + +// ---- hood scene ---- +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: HALF }); +const { scene } = stage; +scene.fogMode = Scene.FOGMODE_EXP2; +const sky = { + storm: { clear: '#141821', fog: 0.035, light: 0.35 }, + rain: { clear: '#2a3442', fog: 0.022, light: 0.55 }, + clearing: { clear: '#56708c', fog: 0.012, light: 0.8 }, + clear: { clear: '#8fc3f0', fog: 0.004, light: 1.1 } +} as const; +let weather: keyof typeof sky = 'storm'; +const lights = scene.lights.map((l) => ({ light: l, base: l.intensity })); +function applySky(dtMs: number): void { + const target = sky[weather]; + const want = Color4.FromHexString(`${target.clear}ff`); + const k = 1 - Math.exp(-dtMs / 400); + scene.clearColor = Color4.Lerp(scene.clearColor, want, k); + scene.fogColor = new Color3(scene.clearColor.r, scene.clearColor.g, scene.clearColor.b); + scene.fogDensity += (target.fog - scene.fogDensity) * k; + const flash = weather === 'storm' && Math.random() < 0.004 ? 2.5 : 1; + for (const { light, base } of lights) light.intensity += (base * target.light * flash - light.intensity) * Math.min(1, k * (flash > 1 ? 20 : 1)); +} + +const mats = { + me: material(scene, 'me', '#6cc4ff'), + other: material(scene, 'other', '#f2a65a'), + pillar: material(scene, 'pillar', '#5d6675'), + boss: material(scene, 'boss', '#d0453b'), + down: material(scene, 'down', '#4a4a4a') +}; +mats.boss.emissiveColor = Color3.FromHexString('#3a0b08'); +for (const [i, [x, y, r]] of PILLARS.entries()) { + if (i === 0) continue; // the boss stands on the central pillar + const ruin = MeshBuilder.CreateCylinder(`ruin-${i}`, { diameter: r * 2, height: 1.2 + (i % 3) * 0.8, tessellation: 7 }, scene); + ruin.position = toWorld(x, y, ruin.getBoundingInfo().boundingBox.extendSize.y); + ruin.material = mats.pillar; +} +const boss = MeshBuilder.CreateSphere('boss', { diameter: PILLARS[0]![2] * 2, segments: 12 }, scene); +boss.scaling.y = 1.3; +boss.material = mats.boss; +boss.position = toWorld(0, 0, 2.2); + +const visuals = new Map(); +function capsule(entity: RenderedEntity, mine: boolean): AbstractMesh { + let mesh = visuals.get(entity.key); + if (mesh === undefined) { + mesh = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + mesh.material = mine ? mats.me : mats.other; + visuals.set(entity.key, mesh); + } + return mesh; +} + +// ---- HUD, banner ---- +const hud = new Hud({ + title: 'Boss Ripple', + hint: 'WASD to move, Space to dash, E near the boss to attack. Click a neighborhood in the tree to fight there.', + client, + devApi: api +}); +let smitePending = false; +const smite = document.createElement('button'); +smite.className = 'ripple-button'; +smite.textContent = 'Smite the boss (demo)'; +smite.addEventListener('click', () => (smitePending = true)); +hud.root.append(smite); + +const banner = document.createElement('div'); +banner.className = 'ripple-banner'; +document.body.append(banner); +function showBanner(text: string): void { + banner.textContent = text; + banner.classList.remove('show'); + void banner.offsetWidth; + banner.classList.add('show'); +} +ripple.onBanner(showBanner); +ripple.onWeather((w) => { + if (w in sky) weather = w as keyof typeof sky; +}); + +// ---- hierarchy tree ---- +const tree = document.createElement('aside'); +tree.className = 'ripple-tree'; +const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); +svg.classList.add('ripple-edges'); +tree.append(svg); +const nodes = new Map(); +for (const zone of allZones()) { + const tier = tierOf(zone)!; + const el = document.createElement('div'); + el.className = `ripple-node tier-${tier}`; + const title = document.createElement('div'); + title.className = 'title'; + title.textContent = zone.split('.').at(-1)!; + const meta = document.createElement('span'); + meta.className = 'meta'; + title.append(meta); + const state = document.createElement('div'); + state.className = 'state'; + el.append(title, state); + let bar: HTMLElement | undefined; + if (tier === 'hood') { + const track = document.createElement('div'); + track.className = 'hp'; + bar = document.createElement('div'); + track.append(bar); + el.append(track); + el.title = 'click to fight here'; + el.addEventListener('click', () => { + if (zone === hood) return; + hood = zone; + history.replaceState(null, '', `?hood=${encodeURIComponent(zone)}${name === undefined ? '' : `&name=${encodeURIComponent(name)}`}`); + ripple.enter(zone).catch(() => undefined); + }); + } + tree.append(el); + nodes.set(zone, { el, state, bar }); + meta.dataset.role = 'meta'; +} +const log = document.createElement('ol'); +log.className = 'ripple-log'; +tree.append(log); +document.body.append(tree); + +function center(zone: string): { x: number; y: number } | undefined { + const node = nodes.get(zone)?.el; + if (node === undefined) return undefined; + const box = tree.getBoundingClientRect(); + const r = node.getBoundingClientRect(); + return { x: r.left - box.left + 10, y: r.top - box.top + r.height / 2 + tree.scrollTop }; +} +function drawEdges(): void { + svg.setAttribute('width', String(tree.scrollWidth)); + svg.setAttribute('height', String(tree.scrollHeight)); + const lines: string[] = []; + for (const zone of allZones()) { + const parent = zone.includes('.') ? zone.slice(0, zone.lastIndexOf('.')) : undefined; + if (parent === undefined) continue; + const a = center(parent); + const b = center(zone); + if (a === undefined || b === undefined) continue; + lines.push(``); + } + svg.innerHTML = lines.join(''); +} +window.addEventListener('resize', drawEdges); +requestAnimationFrame(drawEdges); + +function pulse(event: RippleEvent): void { + const from = center(event.from); + const to = center(event.at); + nodes.get(event.at)?.el.classList.remove('pulse'); + void nodes.get(event.at)?.el.offsetWidth; + nodes.get(event.at)?.el.classList.add('pulse'); + const item = document.createElement('li'); + item.textContent = `${event.from.split('.').at(-1)} → ${event.at.split('.').at(-1)}: ${event.kind}`; + log.prepend(item); + while (log.children.length > 8) log.lastChild?.remove(); + if (from === undefined || to === undefined) return; + const dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); + dot.setAttribute('r', '5'); + dot.classList.add(event.kind.includes('respawn') || event.kind.includes('lost') || event.kind.includes('fallen') ? 'bad' : 'good'); + svg.append(dot); + const start = performance.now(); + const step = (now: number) => { + const t = Math.min(1, (now - start) / 600); + // Up the elbow: first along x back to the parent column, then up. + const [x, y] = t < 0.5 ? [from.x + (to.x - from.x) * t * 2, from.y] : [to.x, from.y + (to.y - from.y) * (t - 0.5) * 2]; + dot.setAttribute('cx', String(x)); + dot.setAttribute('cy', String(y)); + if (t < 1) requestAnimationFrame(step); + else dot.remove(); + }; + requestAnimationFrame(step); +} +ripple.onRipple(pulse); +ripple.onBoss((zone, event) => { + if (zone === hood && event.kind === 'defeated') showBanner(`Boss down! (${event.by ?? 'someone'})`); +}); + +function refreshTree(): void { + for (const zone of allZones()) { + const node = nodes.get(zone)!; + const view = ripple.tier(zone); + const hello = view.hello; + const meta = node.el.querySelector('[data-role="meta"]')!; + meta.textContent = hello === undefined ? ' · …' : ` · host ${hello.host} · ${hello.tickRate} Hz · t${view.clock}`; + node.el.classList.toggle('offline', !view.connected); + node.el.classList.toggle('here', zone === client.authority?.zoneId); + let text = ''; + switch (tierOf(zone)) { + case 'realm': + text = `bosses ${view.defeated}/${view.total} · boroughs ${view.cleared}/2 · ${view.liberated ? 'city free' : 'city occupied'}`; + break; + case 'city': + text = `${view.weather} · boroughs cleared ${view.cleared}/2${view.liberated ? ' · LIBERATED' : ''}`; + break; + case 'borough': + text = `bosses down ${view.defeated}/3 · ${view.cleared > 0 ? 'unlocked' : 'locked'}`; + node.el.classList.toggle('cleared', view.cleared > 0); + break; + default: { + const b = view.boss; + text = b === undefined ? '…' : b.hp === 0 ? `defeated by ${b.by || '?'}` : `boss ${b.hp}/${b.max}`; + if (node.bar !== undefined && b !== undefined) node.bar.style.width = `${(100 * b.hp) / Math.max(1, b.max)}%`; + node.el.classList.toggle('cleared', b?.hp === 0); + } + } + if (node.state.textContent !== text) node.state.textContent = text; + } +} + +// ---- input ---- +const sampler = new InputSampler(); +const frames = new FixedRate(30); +function sendFrame(): void { + const s = sampler.sample(); + const move = cameraRelative(s, stage.cameraForward()); + const input: HoodInput = { + mx: toAxis(move.x), + my: toAxis(move.y), + buttons: s.action ? BUTTON_DASH : 0, + action: (s.alt ? ACTION_ATTACK : 0) | (smitePending ? ACTION_SMITE : 0) + }; + if (client.sendInput(input) !== undefined) smitePending = false; +} + +let lastTree = 0; +stage.onFrame((now, dtMs) => { + frames.advance(now, sendFrame); + applySky(dtMs); + const authority = client.authority; + const view = authority === undefined ? undefined : ripple.tier(authority.zoneId); + const hp = view?.boss?.hp ?? 1; + boss.material = hp === 0 ? mats.down : mats.boss; + const s = hp === 0 ? 0.35 : 0.55 + 0.45 * (hp / Math.max(1, view?.boss?.max ?? 1)); + boss.scaling.set(s, 1.3 * s, s); + boss.position.y = 2.2 * s; + stage.labels.set('boss', boss, hp === 0 ? `defeated by ${view?.boss?.by ?? ''}` : `Boss ${hp}/${view?.boss?.max ?? ''}`, 2.2); + + const rendered = client.render().filter((e) => e.authoritative && e.kindName === 'player'); + const seen = new Set(); + for (const entity of rendered) { + const mine = entity.predicted; + const mesh = capsule(entity, mine); + const x = Number(entity.fields.x ?? 0); + const y = Number(entity.fields.y ?? 0); + mesh.position.copyFrom(toWorld(x, y, 0.9)); + mesh.setEnabled(!entity.stale); + stage.labels.set(entity.key, mesh, mine ? `${String(entity.fields.name ?? '')} (you)` : String(entity.fields.name ?? ''), 1.4, mine ? 'me' : ''); + if (mine) stage.follow(x, y, dtMs); + seen.add(entity.key); + } + for (const [key, mesh] of visuals) { + if (seen.has(key)) continue; + mesh.dispose(); + stage.labels.delete(key); + visuals.delete(key); + } + if (now - lastTree > 150) { + lastTree = now; + refreshTree(); + } + hud.frame({ entities: rendered.length }); + hud.row('Hood', authority?.zoneId ?? '—'); + hud.row('Weather', ripple.weather() ?? '—'); + hud.row('Realm banner', ripple.banner() ?? '—'); +}); + +declare global { + interface Window { + /** Debug handle (console). */ + ripple?: unknown; + } +} +window.ripple = { ripple, client, api, scene }; + +client.connect(hood).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/ripple/ripple.css b/examples/game/client/src/ripple/ripple.css new file mode 100644 index 000000000..80812c189 --- /dev/null +++ b/examples/game/client/src/ripple/ripple.css @@ -0,0 +1,148 @@ +.ripple-tree { + position: fixed; + top: 12px; + right: 12px; + width: 330px; + max-height: calc(100% - 24px); + overflow: auto; + padding: 10px 12px 10px 10px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.ripple-edges { + position: absolute; + left: 0; + top: 0; + pointer-events: none; + overflow: visible; +} +.ripple-edges path { + fill: none; + stroke: #3a4556; + stroke-width: 1.5; +} +.ripple-edges circle.good { + fill: #ffd25e; + filter: drop-shadow(0 0 4px #ffd25e); +} +.ripple-edges circle.bad { + fill: #ff6b6b; + filter: drop-shadow(0 0 4px #ff6b6b); +} +.ripple-node { + position: relative; + margin: 0 0 6px; + padding: 5px 8px; + border-radius: 6px; + border: 1px solid #2a3240; + background: #141922; +} +.ripple-node .title { + font-weight: 600; +} +.ripple-node .meta { + font-weight: 400; + color: var(--muted); + font-size: 11px; +} +.ripple-node .state { + color: var(--text); + font-size: 12px; +} +.ripple-node.tier-city { + margin-left: 16px; +} +.ripple-node.tier-borough { + margin-left: 32px; +} +.ripple-node.tier-hood { + margin-left: 48px; + cursor: pointer; +} +.ripple-node.here { + border-color: var(--accent); +} +.ripple-node.cleared { + border-color: #5fd39a; +} +.ripple-node.offline { + opacity: 0.5; +} +.ripple-node.pulse { + animation: ripple-pulse 0.9s ease-out; +} +@keyframes ripple-pulse { + 0% { + box-shadow: 0 0 0 0 rgba(255, 210, 94, 0.8); + } + 100% { + box-shadow: 0 0 0 12px rgba(255, 210, 94, 0); + } +} +.ripple-node .hp { + height: 4px; + margin-top: 4px; + border-radius: 2px; + background: #2a3240; + overflow: hidden; +} +.ripple-node .hp div { + height: 100%; + background: #d0453b; + transition: width 0.2s; +} +.ripple-log { + margin: 8px 0 0; + padding-left: 18px; + color: var(--muted); + font-size: 11px; +} +.ripple-button { + display: block; + width: 100%; + margin: 8px 0 0; + padding: 6px; + border: 1px solid #d0453b; + border-radius: 6px; + background: #2a1414; + color: #ffd7d2; + font: inherit; + cursor: pointer; +} +.ripple-banner { + position: fixed; + top: 18%; + left: 50%; + transform: translateX(-50%); + padding: 12px 22px; + border-radius: 10px; + background: rgba(16, 20, 27, 0.9); + border: 1px solid #ffd25e; + color: #ffe9a8; + font-size: 20px; + opacity: 0; + pointer-events: none; + max-width: calc(100% - 32px); + text-align: center; +} +.ripple-banner.show { + animation: ripple-banner 4s ease-out; +} +@keyframes ripple-banner { + 0%, + 80% { + opacity: 1; + } + 100% { + opacity: 0; + } +} +@media (max-width: 640px) { + .ripple-tree { + top: auto; + bottom: 12px; + width: calc(100% - 24px); + max-height: 40%; + } +} diff --git a/examples/game/client/tests/grid-headless.test.mjs b/examples/game/client/tests/grid-headless.test.mjs new file mode 100644 index 000000000..db72d5c89 --- /dev/null +++ b/examples/game/client/tests/grid-headless.test.mjs @@ -0,0 +1,113 @@ +/** + * Headless Endless Grid client (Node, no browser) against two real + * `game-demos grid` processes (hosts A and B on a hash ring): + * + * - joins grid.0.0 and observes its 8 neighbours (critters across the + * border are rendered before crossing); + * - walks east along a trail over several borders, at least one of them + * between hosts, following every Handoff/Redirect with the SDK — the + * session survives and the walker ends in the expected cell; + * - the cell left behind hibernates (world map) and a new visitor gets + * the "restored from hibernation" hello. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { createGridClient } from '../src/grid/client.ts'; +import { BUTTON_SPRINT, zoneId } from '../src/grid/world.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { startCluster } from './helpers/cluster.mjs'; +import { memoryStorage, sleep, until } from './helpers/demo-server.mjs'; + +test('grid walker crosses cells and hosts; empty cells hibernate and restore', { timeout: 600_000 }, async () => { + const cluster = await startCluster('grid', { hibernateAfterMs: 800 }); + const clients = []; + try { + const base = cluster.httpUrl; + const api = new DevApi({ base, name: () => 'Walker', storage: memoryStorage() }); + const grid = createGridClient({ api, base }); + clients.push(grid); + const { client } = grid; + let failed = 0; + client.on('handoffFailed', () => (failed += 1)); + + await client.connect('grid.0.0'); + const hello = await grid.ready; + assert.deepEqual(hello.cell, [0, 0]); + const principal = api.last.principal; + await until(() => client.predictor.active, 5_000, 'walker bound'); + await until( + () => client.zones().filter((z) => z.role === 'observer' && z.connection.welcome !== undefined).length === 8, + 10_000, + '8 neighbours observed' + ); + await until( + () => client.render().some((e) => e.kindName === 'critter' && e.zoneId === 'grid.1.0'), + 5_000, + 'critters across the east border' + ); + + // Pick a route east that crosses between hosts. + const map = await grid.map([0, 0], 8); + const owner = (x) => map.cells.find((c) => c.x === x && c.y === 0).owner; + assert.equal(owner(0), hello.host); + let last = 2; + while (![...Array(last).keys()].some((i) => owner(i) !== owner(i + 1))) last += 1; + assert.ok(last <= 8, 'a host border within 8 cells'); + const target = zoneId([last, 0]); + + const deadline = Date.now() + 60_000; + const hosts = new Set(); + while (!(client.authority?.zoneId === target && client.predictor.active && client.predictor.predicted().x > 4)) { + assert.ok(Date.now() < deadline, `walk timed out in ${client.authority?.zoneId}`); + client.sendInput({ mx: 127, my: 0, buttons: BUTTON_SPRINT }); + const zone = client.authority?.zoneId; + if (zone !== undefined && grid.info(zone) !== undefined) hosts.add(grid.info(zone).host); + await sleep(1000 / 30); + } + assert.equal(failed, 0, 'no failed handoff'); + assert.equal(grid.handoffs(), last, 'one handoff per border'); + assert.equal(grid.info(target).host, owner(last)); + assert.ok(hosts.size === 2, `visited both hosts: ${[...hosts]}`); + const ownerUrl = map.hosts.find((h) => h.id === owner(last)).wsUrl; + assert.ok(client.authority.connection.url.startsWith(ownerUrl), 'connected to the owning host'); + assert.equal(api.last.principal, principal, 'same guest throughout'); + await until(() => client.predictor.pending.length === 0, 5_000, 'acks'); + const me = client.authority.replica.get(grid.info(target).entity); + assert.equal(me.fields.name, 'Walker', 'name carried across hosts'); + assert.ok(Math.abs(me.fields.y - 16) < 0.01, 'stayed on the trail'); + assert.deepEqual(client.predictor.predicted().x, me.fields.x, 'prediction matches the server'); + // Neighbours follow the walker. + await until( + () => client.zones().filter((z) => z.role === 'observer').map((z) => z.zoneId).includes(zoneId([last + 1, 0])), + 5_000, + 'new east neighbour observed' + ); + + // grid.0.0 is no longer observed by anyone: Dormant, then hibernated. + let state = 'active'; + const hibernateDeadline = Date.now() + 15_000; + while (state !== 'hibernated') { + assert.ok(Date.now() < hibernateDeadline, `grid.0.0 stayed ${state}`); + await sleep(200); + state = (await grid.map([0, 0], 0)).cells[0].state; + } + + const visitor = createGridClient({ + api: new DevApi({ base, name: () => 'Visitor', storage: memoryStorage() }), + base, + neighbours: false + }); + clients.push(visitor); + const restored = new Promise((resolve) => visitor.onRestored(resolve)); + await visitor.client.connect('grid.0.0'); + const back = await restored; + assert.equal(back.zone, 'grid.0.0'); + assert.equal(back.restores, 1); + assert.ok(back.restoredCritters >= 2); + assert.ok(back.hibernatedForMs >= 0); + } finally { + for (const c of clients) c.close(); + await cluster.stop(); + } +}); diff --git a/examples/game/client/tests/grid-world-parity.test.mjs b/examples/game/client/tests/grid-world-parity.test.mjs new file mode 100644 index 000000000..6d7ad39f8 --- /dev/null +++ b/examples/game/client/tests/grid-world-parity.test.mjs @@ -0,0 +1,75 @@ +/** + * Rust ↔ TypeScript parity of the Endless Grid's procedural world and + * movement: replays `examples/game/fixtures/grid-world.json` (written by + * `server/tests/grid_fixture.rs`) through `src/grid/world.ts`. Every value + * must match bit for bit — the client renders and predicts with the same + * content the server collides against. + */ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +import * as world from '../src/grid/world.ts'; + +const fixture = JSON.parse(readFileSync(new URL('../../fixtures/grid-world.json', import.meta.url), 'utf8')); +const f = Math.fround; + +test('constants and hashes match', () => { + const c = fixture.constants; + assert.equal(c.seed, world.DEFAULT_SEED); + assert.equal(c.contentVersion, world.CONTENT_VERSION); + assert.equal(c.cell, world.CELL); + assert.equal(c.propMargin, world.PROP_MARGIN); + assert.equal(c.hysteresis, world.HYSTERESIS); + assert.equal(f(c.playerRadius), world.PLAYER_RADIUS); + assert.equal(c.walk, world.WALK_SPEED); + assert.equal(c.sprint, world.SPRINT_SPEED); + assert.deepEqual([0, 1, 0xdeadbeef, 0xffffffff].map(world.hash32), c.hashes); + assert.deepEqual([world.mix(c.seed, 3, -5, 7), world.mix(0, 0, -2147483648, 2147483647)], c.mix); +}); + +test('terrain, moisture, biomes and props are bit-identical', () => { + const seed = fixture.constants.seed; + let props = 0; + for (const expected of fixture.cells) { + const cell = expected.cell; + let k = 0; + for (let j = 0; j <= 8; j += 1) { + for (let i = 0; i <= 8; i += 1, k += 1) { + const lx = i * 4; + const ly = j * 4 + 0.25; + assert.equal(world.height(seed, cell, lx, ly), f(expected.heights[k]), `height ${cell} ${i},${j}`); + assert.equal(world.moisture(seed, cell, lx, ly), f(expected.moisture[k]), `moisture ${cell} ${i},${j}`); + assert.equal(world.biome(seed, cell, lx, ly), expected.biomes[k], `biome ${cell} ${i},${j}`); + } + } + const actual = world.cellProps(seed, cell).map((p) => [p.kind, p.x, p.y, p.r, p.solid, p.variant]); + const want = expected.props.map(([kind, x, y, r, solid, variant]) => [kind, f(x), f(y), f(r), solid, variant]); + assert.deepEqual(actual, want, `props of ${cell}`); + props += actual.length; + } + assert.ok(props > 10, 'fixture cells have props'); +}); + +test('the movement step reproduces every Rust position', () => { + const walk = fixture.walk; + const props = world.cellProps(fixture.constants.seed, walk.cell); + let [x, y] = walk.start; + let pushed = 0; + walk.steps.forEach(({ input, x: wx, y: wy }, i) => { + const free = world.step(x, y, { mx: input[0], my: input[1], buttons: input[2] }, []); + [x, y] = world.step(x, y, { mx: input[0], my: input[1], buttons: input[2] }, props); + if (free[0] !== x || free[1] !== y) pushed += 1; + assert.equal(x, f(wx), `step ${i} x`); + assert.equal(y, f(wy), `step ${i} y`); + }); + assert.ok(pushed > 0, 'the walk collides with props'); +}); + +test('zone ids round-trip', () => { + assert.deepEqual(world.parseZone('grid.-3.12'), [-3, 12]); + assert.equal(world.zoneId([4, -2]), 'grid.4.-2'); + for (const bad of ['grid.1', 'grid.01.2', 'grid.1.2.3', 'grid.2000000.0', 'arena-1']) { + assert.equal(world.parseZone(bad), undefined, bad); + } +}); diff --git a/examples/game/client/tests/helpers/cluster.mjs b/examples/game/client/tests/helpers/cluster.mjs new file mode 100644 index 000000000..8b72d948d --- /dev/null +++ b/examples/game/client/tests/helpers/cluster.mjs @@ -0,0 +1,93 @@ +/** + * Start a multi-host demo (`game-demos --host-id … --peer …`) for a + * Node test: one process per host on free ephemeral ports, a shared ticket + * secret, dev routes on. Uses GAME_DEMOS_BIN when set, else `cargo run`. + */ +import { spawn } from 'node:child_process'; +import { createServer, Socket } from 'node:net'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const SERVER_DIR = fileURLToPath(new URL('../../../server/', import.meta.url)); + +function freePort() { + return new Promise((resolve, reject) => { + const server = createServer(); + server.unref(); + server.on('error', reject); + server.listen(0, '127.0.0.1', () => { + const { port } = server.address(); + server.close(() => resolve(port)); + }); + }); +} + +/** + * @param {string} demo + * @param {{ hosts?: string[], hibernateAfterMs?: number, env?: Record }} options + */ +export async function startCluster(demo, { hosts = ['A', 'B'], hibernateAfterMs = 4000, env = {} } = {}) { + const ports = []; + for (const _ of hosts) ports.push(await freePort()); + const stateDir = mkdtempSync(join(tmpdir(), `game-demos-${demo}-`)); + const secret = `test-secret-${process.pid}-${Date.now()}`; + const bin = process.env.GAME_DEMOS_BIN; + const children = []; + const urls = {}; + try { + await Promise.all( + hosts.map(async (id, i) => { + const args = [demo, '--dev', '--port', String(ports[i]), '--host-id', id, '--secret', secret]; + args.push('--state-dir', stateDir, '--hibernate-after-ms', String(hibernateAfterMs)); + hosts.forEach((peer, j) => { + if (j !== i) args.push('--peer', `${peer}=127.0.0.1:${ports[j]}`); + }); + const options = { env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'inherit'] }; + const child = bin + ? spawn(bin, args, options) + : spawn('cargo', ['run', '-q', '--', ...args], { ...options, cwd: SERVER_DIR }); + children.push(child); + urls[id] = await new Promise((resolve, reject) => { + let buffered = ''; + child.stdout.on('data', (chunk) => { + buffered += chunk; + const match = /LISTENING (http:\/\/\S+)/.exec(buffered); + if (match) resolve(match[1]); + }); + child.on('exit', (code) => reject(new Error(`game-demos ${demo} host ${id} exited with ${code}`))); + }); + }) + ); + } catch (error) { + for (const child of children) child.kill('SIGKILL'); + rmSync(stateDir, { recursive: true, force: true }); + throw error; + } + return { + /** HTTP origin per host id. */ + urls, + /** First host (what the Vite proxy points at in `run.sh`). */ + httpUrl: urls[hosts[0]], + async stop() { + await Promise.all( + children.map(async (child) => { + if (child.exitCode !== null) return; + const exited = new Promise((resolve) => child.on('exit', resolve)); + child.kill('SIGTERM'); + const timer = setTimeout(() => child.kill('SIGKILL'), 5000); + await exited; + clearTimeout(timer); + }) + ); + rmSync(stateDir, { recursive: true, force: true }); + // Node's WebSocket (undici) keeps a socket whose closing handshake + // the server started (Redirect) paused until a ~60 s timeout, which + // would hold the test process open: drop what still points at us. + for (const handle of process._getActiveHandles()) { + if (handle instanceof Socket && ports.includes(handle.remotePort)) handle.destroy(); + } + } + }; +} diff --git a/examples/game/client/tests/ripple-headless.test.mjs b/examples/game/client/tests/ripple-headless.test.mjs new file mode 100644 index 000000000..ef43db758 --- /dev/null +++ b/examples/game/client/tests/ripple-headless.test.mjs @@ -0,0 +1,57 @@ +/** + * Headless Boss Ripple client against two real `game-demos ripple` + * processes (placement alternates by depth, so each hop crosses hosts): + * the client plays a neighborhood, observes every tier, smites the bosses + * of borough-1 and sees the cascade arrive at the borough, the city (rain) + * and the realm, each tier running its own tick rate. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { allZones, BOROUGHS, CITY, createRippleClient, hoods, REALM } from '../src/ripple/client.ts'; +import { DevApi } from '../src/shared/dev-api.ts'; +import { startCluster } from './helpers/cluster.mjs'; +import { memoryStorage, until } from './helpers/demo-server.mjs'; + +test('defeating a borough ripples up every tier across hosts', { timeout: 600_000 }, async () => { + const cluster = await startCluster('ripple'); + const base = cluster.httpUrl; + const ripple = createRippleClient({ api: new DevApi({ base, name: () => 'Hero', storage: memoryStorage() }), base }); + try { + const { client } = ripple; + const [first, ...rest] = hoods(BOROUGHS[0]); + await client.connect(first); + const hello = await ripple.ready; + assert.equal(hello.tier, 'hood'); + assert.equal(hello.tickRate, 30); + await until(() => allZones().every((z) => ripple.tier(z).connected && ripple.tier(z).hello !== undefined), 10_000, 'every tier observed'); + assert.equal(ripple.tier(REALM).hello.tickRate, 2); + assert.equal(ripple.tier(CITY).hello.tickRate, 5); + assert.equal(ripple.tier(BOROUGHS[0]).hello.tickRate, 10); + assert.notEqual(ripple.tier(BOROUGHS[0]).hello.host, hello.host, 'parent on another host'); + assert.equal(ripple.tier(first).boss.hp, ripple.tier(first).boss.max); + await until(() => ripple.weather() === 'storm', 5_000, 'stormy city'); + + const bosses = []; + ripple.onBoss((zone, event) => bosses.push([zone, event.kind])); + for (const hood of [first, ...rest]) { + if (hood !== first) await ripple.enter(hood); + await until(() => client.authority?.zoneId === hood && client.authority.connection.canSendInput(), 5_000, `in ${hood}`); + ripple.smite(); + await until(() => ripple.tier(hood).boss?.hp === 0, 5_000, `${hood} boss down`); + } + await until(() => ripple.tier(BOROUGHS[0]).cleared === 1, 10_000, 'borough cleared'); + await until(() => ripple.tier(CITY).cleared === 1 && ripple.tier(CITY).defeated === 3, 10_000, 'city tally'); + await until(() => ripple.tier(REALM).defeated === 3, 10_000, 'realm tally'); + await until(() => ripple.weather() === 'rain', 5_000, 'weather broadcast down to the players'); + const atBorough = ripple.ripples().filter((r) => r.at === BOROUGHS[0] && r.kind === 'boss_defeated'); + assert.deepEqual(new Set(atBorough.map((r) => r.origin)), new Set([first, ...rest])); + assert.ok(ripple.ripples().some((r) => r.at === CITY && r.kind === 'borough_cleared')); + assert.ok(ripple.ripples().some((r) => r.at === REALM && r.kind === 'borough_cleared' && r.from === CITY)); + assert.ok(bosses.filter(([, kind]) => kind === 'defeated').length >= 3); + assert.equal(ripple.tier(BOROUGHS[1]).cleared, 0, 'the other borough is untouched'); + } finally { + ripple.close(); + await cluster.stop(); + } +}); diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts index 62082e6cb..9fa283795 100644 --- a/examples/game/client/vite.config.ts +++ b/examples/game/client/vite.config.ts @@ -5,7 +5,7 @@ import { resolve } from 'node:path'; import { defineConfig } from 'vite'; -const DEMOS = ['arena']; +const DEMOS = ['arena', 'grid', 'ripple']; const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; export default defineConfig({ diff --git a/examples/game/run.sh b/examples/game/run.sh index 770a5e4b5..3c4713db2 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -3,6 +3,8 @@ # # ./run.sh arena build what is needed, start the arena server # (dev routes on) + Vite, print the URL +# ./run.sh grid|ripple same with TWO hosts (A on GAME_DEMOS_PORT, B on +# the next port), one process each # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS) # ./run.sh list demos this script knows # @@ -16,7 +18,9 @@ REPO="$(cd "$HERE/../.." && pwd)" SERVER="$HERE/server" CLIENT="$HERE/client" BIN="$SERVER/target/debug/game-demos" -DEMOS=(arena) +DEMOS=(arena grid ripple) +# Multi-host demos: `game-demos --host-id A|B --peer …`. +CLUSTER_DEMOS=(grid ripple) log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } @@ -76,6 +80,51 @@ run_demo() { GAME_DEMOS_SERVER="http://127.0.0.1:$port" GAME_DEMOS_CLIENT_PORT="$client_port" npx vite } +wait_listening() { + local log_file="$1" pid="$2" what="$3" + for _ in $(seq 1 100); do + grep -q '^LISTENING' "$log_file" && return 0 + if ! kill -0 "$pid" 2>/dev/null; then + cat "$log_file" + echo "$what failed to start" >&2 + exit 1 + fi + sleep 0.1 + done +} + +run_cluster() { + local demo="$1" + local port_a="${GAME_DEMOS_PORT:-2567}" + local port_b=$((port_a + 1)) + local client_port="${GAME_DEMOS_CLIENT_PORT:-5173}" + ensure_sdk + ensure_client + ensure_server + + local dir secret + dir="$(mktemp -d "${TMPDIR:-/tmp}/game-demos-$demo.XXXXXX")" + # Both hosts must share the ticket secret (and derive the admin secret). + secret="${DISTRIBUTED_GAME_SECRET:-$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')}" + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" "$demo" --dev --port "$port_a" --host-id A \ + --peer "B=127.0.0.1:$port_b" --state-dir "$dir" >"$dir/A.log" 2>&1 & + local pid_a=$! + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" "$demo" --dev --port "$port_b" --host-id B \ + --peer "A=127.0.0.1:$port_a" --state-dir "$dir" >"$dir/B.log" 2>&1 & + local pid_b=$! + trap 'kill "$pid_a" "$pid_b" 2>/dev/null || true; wait "$pid_a" "$pid_b" 2>/dev/null || true; rm -rf "$dir"' EXIT INT TERM + wait_listening "$dir/A.log" "$pid_a" "game-demos $demo host A" + wait_listening "$dir/B.log" "$pid_b" "game-demos $demo host B" + sed -n '2p' "$dir/A.log" + sed -n '2p' "$dir/B.log" + echo + log "open http://localhost:$client_port/$demo/ (hosts A :$port_a, B :$port_b, dev routes ON — local only)" + log "snapshots in $dir (removed on exit)" + echo + cd "$CLIENT" + GAME_DEMOS_SERVER="http://127.0.0.1:$port_a" GAME_DEMOS_CLIENT_PORT="$client_port" npx vite +} + smoke() { ensure_sdk ensure_client @@ -92,9 +141,11 @@ smoke() { case "${1:-}" in smoke) smoke ;; list) printf '%s\n' "${DEMOS[@]}" ;; - "" | -h | --help | help) sed -n '2,13p' "$0" ;; + "" | -h | --help | help) sed -n '2,15p' "$0" ;; *) - if [[ " ${DEMOS[*]} " == *" $1 "* ]]; then + if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then + run_cluster "$1" + elif [[ " ${DEMOS[*]} " == *" $1 "* ]]; then run_demo "$1" else echo "unknown demo '$1' (known: ${DEMOS[*]})" >&2 From deb75d0ffc1e92a966d27d31013d13b735afa35f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:14:29 -0500 Subject: [PATCH 155/484] feat(game): pluggable ticket verifier and observer principals - net::TicketVerifier (trait, closures, TicketKey as default) set with ServerConfig::with_ticket_verifier admits join tickets minted elsewhere (e.g. a web BFF's HS256 JWTs); the server still enforces route zone, expiry and single use via TicketClaims::replay_key. Transfer tickets stay on ticket_key. decode_hs256 / TicketKey::sign_json help custom formats; TicketError gains WrongZone and Invalid. - TicketClaims carries an optional display name (TicketClaims::new / with_name), exposed as PlayerInfo::name and carried through handoffs. - Observers: ObserverInfo (principal, name) via Ctx::observer / observers / observers_of, available during on_observe and on_unobserve; ZoneHost::players / observers for tooling. - Recording format bumped to DGR2 (claims include the name). Test: custom verifier for the BFF ticket shape (iss/aud/sub human_hex, principal, name, jti, exp <= 120 s, optional zoneRoute). Refs [[specs/framework/game-runtime/v1/index]] Refs [[tasks/zr-02-bff-ticket-admission]] --- distributed_game/PROTOCOL.md | 10 ++ distributed_game/README.md | 22 ++- distributed_game/src/bots.rs | 1 + distributed_game/src/handoff.rs | 2 + distributed_game/src/host.rs | 88 +++++++++-- distributed_game/src/lib.rs | 4 +- distributed_game/src/metrics.rs | 1 + distributed_game/src/net/mod.rs | 53 ++++++- distributed_game/src/net/ticket.rs | 133 +++++++++++++++- distributed_game/src/replay.rs | 42 ++--- distributed_game/src/zone.rs | 63 +++++++- distributed_game/tests/net_e2e/main.rs | 158 +++++++++++++++++++ distributed_game/tests/netcode/main.rs | 1 + distributed_game/tests/world/main.rs | 2 + distributed_game/tests/world_host/main.rs | 1 + distributed_game/tests/zone_runtime/arena.rs | 19 ++- distributed_game/tests/zone_runtime/main.rs | 18 ++- examples/game/server/src/common/dev.rs | 1 + examples/game/server/tests/gallery_smoke.rs | 1 + 19 files changed, 550 insertions(+), 70 deletions(-) diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md index 904e76916..a4b38a3af 100644 --- a/distributed_game/PROTOCOL.md +++ b/distributed_game/PROTOCOL.md @@ -453,8 +453,18 @@ unpadded base64url). Any HS256 JWT library can mint one. - `role` (string, optional) — `"player"` (default) or `"observer"`. Observers receive Deltas and Events but own no player and cannot send inputs. + - `name` (string, optional) — display name vouched for by the issuer + (never identity). Carried into transfer tickets. - Failures produce `Error(UNAUTHORIZED)` and close. +**Custom ticket formats.** A server MAY admit join tickets in another +format through a pluggable verifier (`ServerConfig::ticket_verifier`, e.g. +a web backend's own JWTs with `iss`/`aud`/`jti` and no `zone`/`nonce`). +The verifier maps the token to the same claims (principal, zone = route +zone, expiry, replay key, role, name); the server still rejects a zone +other than the route's, `exp <= now` and a reused replay key. Transfer +tickets (§8.1) always use the format above. + ### 8.1 Transfer tickets and handoff A zone hands a player to another zone (possibly on another host) with a diff --git a/distributed_game/README.md b/distributed_game/README.md index a3696604d..31e435c44 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -68,10 +68,7 @@ impl Zone for Room { let clock = ManualClock::new(); let mut host = ZoneHost::::new("room-1", HostConfig::default(), Arc::new(clock.clone()), ()); -let claims = TicketClaims { - principal: "alice".into(), zone: "room-1".into(), - expires_at: u64::MAX, nonce: "n".into(), role: Role::Player, -}; +let claims = TicketClaims::new("alice", "room-1", u64::MAX, "n", Role::Player); let joined = host.join(&claims, 0, "").unwrap(); host.push_input(joined.client, 1, 0, &[1]); clock.advance(Duration::from_millis(100)); @@ -107,6 +104,21 @@ double-crediting. ## Netcode and operations +- **Admission tickets** (`net`): by default join tickets are HS256 JWTs + signed with `ServerConfig::ticket_key` (PROTOCOL.md §8). To admit tickets + your web backend already mints, plug in a verifier — + `ServerConfig::new(key).with_ticket_verifier(|token: &str, zone: &str, now: u64| { … })` + (or implement `net::TicketVerifier`) — that checks your issuer, audience + and lifetime (`net::decode_hs256` verifies an HS256 signature and + returns the claims) and returns `TicketClaims` with `zone` = the route + zone and `nonce` = your replay key (e.g. `jti`). The server still + enforces route zone, expiry and single use; `TicketClaims::name` becomes + `PlayerInfo::name` / `ObserverInfo::name` and travels with handoffs. + Transfer tickets always use `ticket_key`. +- **Observers**: `Ctx::observer(id)` / `observers()` / `observers_of(principal)` + expose each observer's verified principal and name (also during + `on_unobserve`); `ctx.send_event(observer_id, …)` addresses one observer. + - **Lag compensation** (`rewind`): implement `Zone::record_rewind` to push hit volumes (sphere / vertical capsule + numeric fields) each tick; the host keeps a ring buffer sized by `HostConfig::rewind.max_rewind` @@ -116,7 +128,7 @@ double-crediting. stored history. The interpolation delay travels in the game's input payload (no wire change). - **Record/replay** (`replay`): drive a host through `Recorder` (same - methods as `ZoneHost`), save the compact `Recording` (`DGR1`), and + methods as `ZoneHost`), save the compact `Recording` (`DGR2`), and `replay::(&recording, config)` re-runs it on a `ManualClock`, checking a per-tick state hash (`Zone::state_hash`, or the replicated `WorldView`). A mismatch returns a `Divergence` naming the tick and the diff --git a/distributed_game/src/bots.rs b/distributed_game/src/bots.rs index 108cf642a..3cf03bce3 100644 --- a/distributed_game/src/bots.rs +++ b/distributed_game/src/bots.rs @@ -361,6 +361,7 @@ async fn drive( expires_at: unix + 3600, nonce: format!("{principal}-{}-{}", config.seed, unix), role: Role::Player, + name: None, }); let url = format!("{}/zones/{}", config.url.trim_end_matches('/'), config.zone); let (mut ws, _) = tokio_tungstenite::connect_async(url.as_str()) diff --git a/distributed_game/src/handoff.rs b/distributed_game/src/handoff.rs index c1ac89a65..e8f67d081 100644 --- a/distributed_game/src/handoff.rs +++ b/distributed_game/src/handoff.rs @@ -20,6 +20,8 @@ pub const MAX_CARRIED_BYTES: usize = 16 * 1024; pub struct HandoffRequest { /// Verified principal of the moving player. pub principal: String, + /// The player's display name (from its admission ticket), carried over. + pub name: Option, /// Zone the player leaves. pub source_zone: String, /// Zone the player goes to. diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 9285f6c6e..39bb77e2d 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -45,8 +45,8 @@ use crate::timers::{TimerId, Timers}; use crate::timestep::{rate_to_step, FixedTimestep}; use crate::world::{ChildEvent, FreezeState, StalePolicy}; use crate::zone::{ - Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, - Tier, Viewer, Zone, + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, ObserverInfo, PlayerId, PlayerInfo, + TicketClaims, Tier, Viewer, Zone, }; /// Host tuning. @@ -207,6 +207,7 @@ struct PlayerSlot { } struct ObserverSlot { + info: ObserverInfo, client: ClientId, view: View, } @@ -229,6 +230,8 @@ pub(crate) struct Core { tier: Tier, players: BTreeMap>, observers: BTreeMap, + /// Observer being removed while `on_unobserve` runs. + departing: Option, clients: BTreeMap, next_id: u32, outbound: Vec, @@ -351,6 +354,29 @@ impl Ctx<'_, Z> { self.core.players.get(&id).map(|slot| &slot.info) } + /// Observers currently subscribed. + pub fn observers(&self) -> impl Iterator + '_ { + self.core.observers.values().map(|slot| &slot.info) + } + + /// One observer (verified principal, display name). Also answers for + /// the observer leaving during [`Zone::on_unobserve`]. + pub fn observer(&self, id: ObserverId) -> Option<&ObserverInfo> { + self.core.observers.get(&id).map(|slot| &slot.info).or(self + .core + .departing + .as_ref() + .filter(|info| info.id == id)) + } + + /// Observers whose verified principal is `principal` (a principal may + /// observe through several connections). + pub fn observers_of<'p>(&'p self, principal: &'p str) -> impl Iterator + 'p { + self.observers() + .filter(move |info| info.principal == principal) + .map(|info| info.id) + } + /// Consume buffered inputs of `player`; advances its ack. pub fn take_inputs( &mut self, @@ -473,11 +499,11 @@ impl Ctx<'_, Z> { if carried.len() > MAX_CARRIED_BYTES { return Err(HandoffError::TooLarge); } - let principal = self + let (principal, name) = self .core .players .get(&player) - .map(|slot| slot.info.principal.clone()) + .map(|slot| (slot.info.principal.clone(), slot.info.name.clone())) .ok_or(HandoffError::UnknownPlayer)?; if self .core @@ -489,6 +515,7 @@ impl Ctx<'_, Z> { } let request = HandoffRequest { principal, + name, source_zone: self.core.zone_id.clone(), target_zone: target_zone.to_string(), carried, @@ -573,6 +600,7 @@ impl ZoneHost { tier: Tier::Hot, players: BTreeMap::new(), observers: BTreeMap::new(), + departing: None, clients: BTreeMap::new(), next_id: 0, outbound: Vec::new(), @@ -686,6 +714,16 @@ impl ZoneHost { self.core.players.len() } + /// Players (including those in the grace window). + pub fn players(&self) -> impl Iterator + '_ { + self.core.players.values().map(|slot| &slot.info) + } + + /// Observers. + pub fn observers(&self) -> impl Iterator + '_ { + self.core.observers.values().map(|slot| &slot.info) + } + /// Live connections. pub fn client_count(&self) -> usize { self.core.clients.len() @@ -850,6 +888,11 @@ impl ZoneHost { let mut handoff = handoff; let joined = match (claims.role, existing) { (Role::Player, Some(player)) => { + if let Some(slot) = self.core.players.get_mut(&player) { + if claims.name.is_some() { + slot.info.name = claims.name.clone(); + } + } self.bind_player(player, client, capabilities); if let Some((from, carried)) = handoff.take() { hook!(self.on_handoff_join(player, from, carried)); @@ -869,6 +912,7 @@ impl ZoneHost { info: PlayerInfo { id: player, principal: claims.principal.clone(), + name: claims.name.clone(), capabilities, connected: true, }, @@ -897,6 +941,12 @@ impl ZoneHost { self.core.observers.insert( observer, ObserverSlot { + info: ObserverInfo { + id: observer, + principal: claims.principal.clone(), + name: claims.name.clone(), + capabilities, + }, client, view: View::new(0.0, 0.0, self.core.config.default_view_radius), }, @@ -1138,10 +1188,7 @@ impl ZoneHost { p.grace_until = Some(self.core.clock.now() + self.core.config.reconnect_grace); } } - Viewer::Observer(observer) => { - self.core.observers.remove(&observer); - hook!(self.on_unobserve(observer)); - } + Viewer::Observer(observer) => self.remove_observer(observer, None), } self.process_kicks(); } @@ -1280,14 +1327,7 @@ impl ZoneHost { } let observers: Vec<_> = self.core.observers.keys().copied().collect(); for observer in observers { - if let Some(slot) = self.core.observers.remove(&observer) { - self.core.clients.remove(&slot.client); - self.core.server_message(slot.client, &bye); - self.core.outbound.push(Outbound::Close { - client: slot.client, - }); - } - hook!(self.on_unobserve(observer)); + self.remove_observer(observer, Some(&bye)); } hook!(self.on_dispose()); self.core.pending_kicks.clear(); @@ -1321,6 +1361,22 @@ impl ZoneHost { hook!(self.on_leave(player, reason)); } + fn remove_observer(&mut self, observer: ObserverId, last: Option<&ServerMessage>) { + let Some(slot) = self.core.observers.remove(&observer) else { + return; + }; + self.core.clients.remove(&slot.client); + if let Some(message) = last { + self.core.server_message(slot.client, message); + self.core.outbound.push(Outbound::Close { + client: slot.client, + }); + } + self.core.departing = Some(slot.info); + hook!(self.on_unobserve(observer)); + self.core.departing = None; + } + fn process_kicks(&mut self) { while let Some((player, message)) = self.core.pending_handoffs.pop() { self.remove_player(player, LeaveReason::Handoff, Some(message)); diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 9198ac6e4..554026541 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -74,8 +74,8 @@ pub use timers::TimerId; pub use timestep::FixedTimestep; pub use world::{BarrierMode, ChildEvent, FreezeState, StalePolicy}; pub use zone::{ - Admission, ClientId, JoinRequest, LeaveReason, ObserverId, PlayerId, PlayerInfo, TicketClaims, - Tier, Viewer, Zone, + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, ObserverInfo, PlayerId, PlayerInfo, + TicketClaims, Tier, Viewer, Zone, }; #[doc = include_str!("../README.md")] diff --git a/distributed_game/src/metrics.rs b/distributed_game/src/metrics.rs index df5e206c1..541a294ee 100644 --- a/distributed_game/src/metrics.rs +++ b/distributed_game/src/metrics.rs @@ -603,6 +603,7 @@ mod tests { expires_at: u64::MAX, nonce: "n".into(), role: Role::Player, + name: None, }; let joined = h.join(&claims, 0, "").unwrap(); metrics.record_input("z1", h.push_input(joined.client, 1, 0, &[1])); diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 0cfb6ae7e..00aebbe72 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -60,7 +60,10 @@ use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::JoinHandle; use tokio::time::Instant; -pub use ticket::{NonceCache, TicketError, TicketKey, VerifiedTicket}; +pub use ticket::{ + decode_hs256, NonceCache, SharedTicketVerifier, TicketError, TicketKey, TicketVerifier, + VerifiedTicket, +}; pub use transfer::{TransferOp, TransferRegistry}; pub use world::{BarrierParticipant, RemoteHost, RolloutError, RolloutReport, WorldCoordinator}; @@ -160,8 +163,13 @@ impl NetSim { pub struct ServerConfig { /// Settings for every hosted zone. pub host: HostConfig, - /// HMAC key for admission tickets. + /// HMAC key for transfer tickets and server tokens, and (unless + /// `ticket_verifier` is set) for admission tickets. pub ticket_key: TicketKey, + /// Custom verifier for **join** tickets (e.g. the game's web-BFF JWTs); + /// `None` = HS256 tickets signed with `ticket_key`. Expiry, route zone + /// and single use are enforced by the server either way. + pub ticket_verifier: Option, /// Deadline for the first (Hello) frame. pub hello_timeout: Duration, /// Sustained inputs per second per connection. @@ -198,11 +206,18 @@ pub struct ServerConfig { } impl ServerConfig { + /// Admit join tickets with `verifier` instead of `ticket_key`. + pub fn with_ticket_verifier(mut self, verifier: impl TicketVerifier) -> Self { + self.ticket_verifier = Some(SharedTicketVerifier::new(verifier)); + self + } + /// Defaults with the given ticket key. pub fn new(ticket_key: TicketKey) -> Self { Self { host: HostConfig::default(), ticket_key, + ticket_verifier: None, hello_timeout: Duration::from_secs(5), input_rate: 120.0, input_burst: 240.0, @@ -224,6 +239,7 @@ impl ServerConfig { type Inspector = Box; +#[allow(clippy::large_enum_variant)] // Join is rare; boxing buys nothing. enum ZoneCmd { Join { claims: TicketClaims, @@ -995,6 +1011,7 @@ async fn run_zone( expires_at, nonce, role: Role::Player, + name: request.name.clone(), }, source_zone: request.source_zone.clone(), issuer: inner.host_id.clone(), @@ -1491,7 +1508,7 @@ where let mut returning = false; let cmd = if hello.reconnect_token.is_empty() { let now = unix_now(); - let verified = match cfg.ticket_key.verify_ticket(&hello.ticket, now) { + let verified = match verify_hello_ticket(cfg, &hello.ticket, &zone_id, now) { Ok(verified) => verified, Err(e) => return reject(socket, error::UNAUTHORIZED, format!("{e:?}")).await, }; @@ -1706,6 +1723,36 @@ where let _ = socket.send(Message::Close(None)).await; } +/// Transfer tickets always use the server key; join tickets go through the +/// configured [`TicketVerifier`] and are then checked for zone, expiry and a +/// non-empty replay key. +fn verify_hello_ticket( + cfg: &ServerConfig, + ticket: &str, + zone_id: &str, + now: u64, +) -> Result { + let verified = match &cfg.ticket_verifier { + None => cfg.ticket_key.verify_ticket(ticket, now)?, + Some(custom) => match cfg.ticket_key.verify_ticket(ticket, now) { + Ok(VerifiedTicket::Transfer(transfer)) => VerifiedTicket::Transfer(transfer), + _ => VerifiedTicket::Join(custom.0.verify(ticket, zone_id, now)?), + }, + }; + if let VerifiedTicket::Join(claims) = &verified { + if claims.principal.is_empty() { + return Err(TicketError::MissingClaim("sub")); + } + if claims.replay_key().is_empty() { + return Err(TicketError::MissingClaim("nonce")); + } + if claims.expires_at <= now { + return Err(TicketError::Expired); + } + } + Ok(verified) +} + /// Ok(false) when the connection should end. async fn send_out(socket: &mut WebSocket, out: ConnOut) -> Result { match out { diff --git a/distributed_game/src/net/ticket.rs b/distributed_game/src/net/ticket.rs index 75db96a01..2122bdf31 100644 --- a/distributed_game/src/net/ticket.rs +++ b/distributed_game/src/net/ticket.rs @@ -12,6 +12,17 @@ //! `gen` (source ownership token) and `carry` (base64url carried state). //! [`TicketKey::verify`] rejects them ([`TicketError::WrongKind`]); use //! [`TicketKey::verify_ticket`] to accept either kind. +//! +//! **Custom admission tickets.** Join tickets go through a +//! [`TicketVerifier`] (`ServerConfig::ticket_verifier`); the default is the +//! `TicketKey` itself. A game whose web backend already mints its own tickets +//! (different claim names, issuer/audience checks, no `zone`/`nonce`) +//! implements `TicketVerifier` (or passes a closure) and maps them onto +//! [`TicketClaims`]: `zone` is the route zone the client asked for, `nonce` +//! the replay key (e.g. the `jti`). The server still enforces +//! `claims.zone == route zone`, expiry and single use. Transfer tickets are +//! always minted and verified by the server's own `TicketKey`. +//! [`decode_hs256`] helps verifiers of other HS256 JWTs. use std::collections::HashMap; @@ -44,6 +55,68 @@ pub enum TicketError { Replayed, /// A transfer ticket where a join ticket was expected (or vice versa). WrongKind, + /// Signed for another zone than the one requested. + WrongZone, + /// Refused by a custom [`TicketVerifier`] (issuer, audience, ...). + Invalid(String), +} + +/// Verifies **join** tickets presented in Hello. +/// +/// `zone` is the zone id of the route the client connected to and `now_unix` +/// the current Unix time in seconds. Return the verified claims (principal +/// only ever from the verified token); the server then checks +/// `claims.zone == zone`, `claims.expires_at > now_unix` and that +/// [`TicketClaims::replay_key`] was not used before. +/// +/// Implemented by [`TicketKey`] (the built-in HS256 format) and by any +/// `Fn(&str, &str, u64) -> Result` closure. +pub trait TicketVerifier: Send + Sync + 'static { + /// Verify `token` for `zone` at `now_unix`. + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result; +} + +impl TicketVerifier for TicketKey { + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result { + let claims = TicketKey::verify(self, token, now_unix)?; + if claims.zone != zone { + return Err(TicketError::WrongZone); + } + Ok(claims) + } +} + +impl TicketVerifier for F +where + F: Fn(&str, &str, u64) -> Result + Send + Sync + 'static, +{ + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result { + self(token, zone, now_unix) + } +} + +/// A shared [`TicketVerifier`] (`ServerConfig::ticket_verifier`). +#[derive(Clone)] +pub struct SharedTicketVerifier(pub std::sync::Arc); + +impl SharedTicketVerifier { + /// Wrap a verifier. + pub fn new(verifier: impl TicketVerifier) -> Self { + Self(std::sync::Arc::new(verifier)) + } +} + +impl std::fmt::Debug for SharedTicketVerifier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("SharedTicketVerifier(..)") + } +} + +/// Verify the signature of a compact HS256 JWT with `secret` and return its +/// claims object (no claim is interpreted, not even `exp`). For custom +/// [`TicketVerifier`]s over tickets minted elsewhere. +pub fn decode_hs256(token: &str, secret: &[u8]) -> Result { + TicketKey::new(secret).decode(token) } /// A verified ticket of either kind. @@ -96,7 +169,7 @@ impl TicketKey { "nonce": claims.nonce, "role": match claims.role { Role::Player => "player", Role::Observer => "observer" }, }); - self.sign_body(&body) + self.sign_body(&with_name(body, claims)) } /// Mint a transfer ticket for a handoff. @@ -114,7 +187,13 @@ impl TicketKey { "gen": transfer.generation, "carry": URL_SAFE_NO_PAD.encode(&transfer.carried), }); - self.sign_body(&body) + self.sign_body(&with_name(body, claims)) + } + + /// Sign an arbitrary JSON claims object as an HS256 JWT (tests and dev + /// tooling for custom [`TicketVerifier`] formats). + pub fn sign_json(&self, claims: &Value) -> String { + self.sign_body(claims) } fn sign_body(&self, body: &Value) -> String { @@ -176,11 +255,8 @@ impl TicketKey { } } - fn verify_inner( - &self, - ticket: &str, - now_unix: u64, - ) -> Result<(TicketClaims, Value), TicketError> { + /// Signature check only; returns the claims object. + fn decode(&self, ticket: &str) -> Result { let mut parts = ticket.split('.'); let (Some(h), Some(p), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) @@ -200,7 +276,15 @@ impl TicketKey { mac.update(p.as_bytes()); mac.verify_slice(&sig) .map_err(|_| TicketError::BadSignature)?; - let claims: Value = decode_json(p)?; + decode_json(p) + } + + fn verify_inner( + &self, + ticket: &str, + now_unix: u64, + ) -> Result<(TicketClaims, Value), TicketError> { + let claims = self.decode(ticket)?; let text = |name: &'static str| { claims .get(name) @@ -228,12 +312,24 @@ impl TicketKey { expires_at, nonce: text("nonce")?, role, + name: claims + .get("name") + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string), }, claims, )) } } +fn with_name(mut body: Value, claims: &TicketClaims) -> Value { + if let (Some(name), Some(object)) = (&claims.name, body.as_object_mut()) { + object.insert("name".into(), Value::String(name.clone())); + } + body +} + fn decode_json(segment: &str) -> Result { let bytes = URL_SAFE_NO_PAD .decode(segment) @@ -279,6 +375,7 @@ mod tests { expires_at: 2_000, nonce: "n1".into(), role: Role::Player, + name: None, } } @@ -328,6 +425,26 @@ mod tests { ); } + #[test] + fn names_round_trip_and_default_verifier_checks_zone() { + let key = TicketKey::new("secret"); + let named = claims().with_name("Ana"); + let ticket = key.sign(&named); + assert_eq!( + TicketVerifier::verify(&key, &ticket, "z1", 1_000), + Ok(named) + ); + assert_eq!( + TicketVerifier::verify(&key, &ticket, "z2", 1_000), + Err(TicketError::WrongZone) + ); + assert!(decode_hs256(&ticket, b"secret").is_ok()); + assert_eq!( + decode_hs256(&ticket, b"other"), + Err(TicketError::BadSignature) + ); + } + #[test] fn nonce_is_single_use() { let mut cache = NonceCache::default(); diff --git a/distributed_game/src/replay.rs b/distributed_game/src/replay.rs index 190da2f7b..d0d176947 100644 --- a/distributed_game/src/replay.rs +++ b/distributed_game/src/replay.rs @@ -50,7 +50,7 @@ use crate::schema::FieldValue; use crate::world::{ChildEvent, StalePolicy}; use crate::zone::{ClientId, PlayerId, TicketClaims, Zone}; -const MAGIC: &[u8; 4] = b"DGR1"; +const MAGIC: &[u8; 4] = b"DGR2"; /// FNV digest of a replicated world (entity order, ids, kinds, positions, /// priorities and field values). @@ -562,6 +562,10 @@ fn put_claims(w: &mut Writer, claims: &TicketClaims) { Role::Player => 0, Role::Observer => 1, }); + match &claims.name { + Some(name) => w.u8(1).string(name), + None => w.u8(0), + }; } fn get_claims(r: &mut Reader<'_>) -> Result { @@ -573,12 +577,17 @@ fn get_claims(r: &mut Reader<'_>) -> Result { 0 => Role::Player, _ => Role::Observer, }; + let name = match r.u8()? { + 0 => None, + _ => Some(r.string()?), + }; Ok(TicketClaims { principal, zone, expires_at, nonce, role, + name, }) } @@ -652,17 +661,9 @@ impl Recording { result, .. } => { - w.u8(0) - .string(&claims.principal) - .string(&claims.zone) - .string(&claims.nonce); - put_u64(&mut w, claims.expires_at); - w.u8(match claims.role { - Role::Player => 0, - Role::Observer => 1, - }) - .varuint(*capabilities) - .string(content_version); + w.u8(0); + put_claims(&mut w, claims); + w.varuint(*capabilities).string(content_version); put_join_result(&mut w, result); } Event::Reconnect { @@ -813,23 +814,10 @@ impl Recording { at += get_dur(&mut r)?; let event = match r.u8()? { 0 => { - let principal = r.string()?; - let zone = r.string()?; - let nonce = r.string()?; - let expires_at = get_u64(&mut r)?; - let role = match r.u8()? { - 0 => Role::Player, - _ => Role::Observer, - }; + let claims = get_claims(&mut r)?; Event::Join { at, - claims: TicketClaims { - principal, - zone, - expires_at, - nonce, - role, - }, + claims, capabilities: r.varuint()?, content_version: r.string()?, result: get_join_result(&mut r)?, diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index 3f31e2f69..9021986cd 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -54,6 +54,9 @@ impl From for Viewer { /// Claims from a **verified** admission ticket. The principal is the only /// identity the runtime trusts; nothing in client payloads can change it. +/// +/// Built by a `net::TicketVerifier` (the default HS256 `net::TicketKey`, or a +/// game's own verifier for tickets minted by its web backend). #[derive(Debug, Clone, PartialEq, Eq)] pub struct TicketClaims { /// Verified principal (`sub`). @@ -62,10 +65,46 @@ pub struct TicketClaims { pub zone: String, /// Expiry, Unix seconds. pub expires_at: u64, - /// Single-use nonce. + /// Single-use replay key (`nonce`, or a JWT `jti`): the server refuses + /// a second admission with the same key until `expires_at`. pub nonce: String, /// Player or observer. pub role: Role, + /// Optional display name vouched for by the ticket issuer (never + /// identity: use `principal` for that). Exposed as + /// [`PlayerInfo::name`] / [`ObserverInfo::name`]. + pub name: Option, +} + +impl TicketClaims { + /// Claims without a display name. + pub fn new( + principal: impl Into, + zone: impl Into, + expires_at: u64, + nonce: impl Into, + role: Role, + ) -> Self { + Self { + principal: principal.into(), + zone: zone.into(), + expires_at, + nonce: nonce.into(), + role, + name: None, + } + } + + /// Attach a display name. + pub fn with_name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } + + /// Key the server's replay cache records (the nonce / `jti`). + pub fn replay_key(&self) -> &str { + &self.nonce + } } /// Admission request seen by [`Zone::on_auth`]. @@ -110,12 +149,27 @@ pub struct PlayerInfo { pub id: PlayerId, /// Verified principal from the ticket. pub principal: String, + /// Display name from the ticket ([`TicketClaims::name`]), if any. + pub name: Option, /// Hello capabilities. pub capabilities: u32, /// False while inside the reconnect grace window. pub connected: bool, } +/// Observer as seen by the zone ([`Ctx::observer`](crate::Ctx::observer)). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ObserverInfo { + /// Observer id (address events with [`Ctx::send_event`](crate::Ctx::send_event)). + pub id: ObserverId, + /// Verified principal from the observer ticket. + pub principal: String, + /// Display name from the ticket, if any. + pub name: Option, + /// Hello capabilities. + pub capabilities: u32, +} + /// Activity tier of a zone. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Tier { @@ -153,10 +207,13 @@ pub trait Zone: Sized + Send + 'static { /// A player left for `reason` (not called on a disconnect still inside the grace window). fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId, _reason: LeaveReason) {} - /// An observer subscribed. + /// An observer subscribed. Its principal and name are available from + /// [`Ctx::observer`](crate::Ctx::observer); address it with + /// [`Ctx::send_event`](crate::Ctx::send_event)`(observer, ..)`. fn on_observe(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} - /// An observer left. + /// An observer left. [`Ctx::observer`](crate::Ctx::observer) still + /// returns it during this hook (it can no longer receive events). fn on_unobserve(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} /// Decode raw input bytes from the wire; `None` drops the input. diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs index a2be9c956..5e22b142e 100644 --- a/distributed_game/tests/net_e2e/main.rs +++ b/distributed_game/tests/net_e2e/main.rs @@ -29,6 +29,7 @@ fn ticket(principal: &str, zone: &str, nonce: &str, role: Role) -> String { expires_at: 4_000_000_000, nonce: nonce.into(), role, + name: None, }) } @@ -219,6 +220,7 @@ async fn client_joins_sends_inputs_receives_deltas_and_reconnects() { expires_at: 4_000_000_000, nonce: "n4".into(), role: Role::Player, + name: None, }); expect_error(&url, "z1", forged, error::UNAUTHORIZED).await; @@ -361,3 +363,159 @@ async fn hello_join(ws: &mut Ws, zone: &str) { ) .await; } + +// ---- Custom ticket verifier: a web BFF's own HS256 JWTs ---- + +const BFF_SECRET: &[u8] = b"bff-secret"; + +/// The downstream game's web-BFF ticket: HS256, `iss` +/// `dungeon-crawler-web`, `aud` `dungeon-crawler-zone`, `sub` +/// `human_`, `principal`, `name`, `jti`, `exp` at most 120 s out, +/// optional `zoneRoute`; no `zone` / `nonce` claims. +fn bff_verifier( + token: &str, + zone: &str, + now: u64, +) -> Result { + use distributed_game::net::{decode_hs256, TicketError}; + let claims = decode_hs256(token, BFF_SECRET)?; + let text = |name: &'static str| { + claims + .get(name) + .and_then(|v| v.as_str()) + .filter(|v| !v.is_empty()) + .ok_or(TicketError::MissingClaim(name)) + }; + if text("iss")? != "dungeon-crawler-web" || text("aud")? != "dungeon-crawler-zone" { + return Err(TicketError::Invalid("issuer/audience".into())); + } + let sub = text("sub")?; + let hex = sub + .strip_prefix("human_") + .filter(|h| !h.is_empty() && h.chars().all(|c| c.is_ascii_hexdigit())) + .ok_or(TicketError::Invalid("sub".into()))?; + if text("principal")? != sub { + return Err(TicketError::Invalid("principal".into())); + } + let exp = claims + .get("exp") + .and_then(|v| v.as_u64()) + .ok_or(TicketError::MissingClaim("exp"))?; + if exp > now + 120 { + return Err(TicketError::Invalid("lifetime over 120s".into())); + } + if let Some(route) = claims.get("zoneRoute").and_then(|v| v.as_str()) { + if route != zone { + return Err(TicketError::WrongZone); + } + } + let mut verified = TicketClaims::new( + format!("human_{hex}"), + zone, + exp, + text("jti")?, + Role::Player, + ); + verified.name = claims + .get("name") + .and_then(|v| v.as_str()) + .map(str::to_string); + Ok(verified) +} + +fn bff_ticket(jti: &str, exp_in: u64, zone_route: Option<&str>) -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut claims = serde_json::json!({ + "iss": "dungeon-crawler-web", "aud": "dungeon-crawler-zone", + "sub": "human_0a1b2c", "principal": "human_0a1b2c", "name": "Ana", + "jti": jti, "exp": now + exp_in, + }); + if let Some(route) = zone_route { + claims["zoneRoute"] = route.into(); + } + TicketKey::new(BFF_SECRET).sign_json(&claims) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn custom_verifier_admits_web_bff_tickets_with_replay_protection() { + let config = ServerConfig::new(TicketKey::new(SECRET)).with_ticket_verifier(bff_verifier); + let server = GameServer::::new(config, |zone_id| { + zone_id.starts_with('z').then(ArenaConfig::default) + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + let mut ws = connect(&url, "z1").await; + hello(&mut ws, bff_ticket("jti-1", 60, Some("z1")), String::new()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome") + }; + assert_eq!(welcome.zone_id, "z1"); + let players = server + .inspect("z1", |host| { + host.players() + .map(|p| (p.principal.clone(), p.name.clone())) + .collect::>() + }) + .await + .unwrap(); + assert_eq!( + players, + vec![("human_0a1b2c".to_string(), Some("Ana".to_string()))] + ); + + // Replay of the same jti, wrong route, overlong lifetime, built-in + // tickets (the custom verifier replaces them) and a forged signature. + expect_error( + &url, + "z1", + bff_ticket("jti-1", 60, Some("z1")), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z2", + bff_ticket("jti-2", 60, Some("z1")), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + bff_ticket("jti-3", 600, None), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + ticket("bob", "z1", "n-bob", Role::Player), + error::UNAUTHORIZED, + ) + .await; + let forged = TicketKey::new("nope").sign_json(&serde_json::json!({"sub": "human_ff"})); + expect_error(&url, "z1", forged, error::UNAUTHORIZED).await; + // No zoneRoute: admitted to the zone the client asked for. + let mut ws2 = connect(&url, "z2").await; + hello(&mut ws2, bff_ticket("jti-4", 60, None), String::new()).await; + let mut mirror2 = ClientMirror::new(); + assert!(matches!( + next(&mut ws2, &mut mirror2).await, + Some(ServerMessage::Welcome(_)) + )); + + server.shutdown(); + handle.await.unwrap(); +} diff --git a/distributed_game/tests/netcode/main.rs b/distributed_game/tests/netcode/main.rs index de3e464d5..5d3711f68 100644 --- a/distributed_game/tests/netcode/main.rs +++ b/distributed_game/tests/netcode/main.rs @@ -23,6 +23,7 @@ fn claims(principal: &str, zone: &str) -> TicketClaims { expires_at: u64::MAX, nonce: format!("n-{principal}"), role: Role::Player, + name: None, } } diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index 94fffd53b..b9ee3c63f 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -35,6 +35,7 @@ fn ticket(principal: &str, zone: &str, nonce: &str) -> String { expires_at: 4_000_000_000, nonce: nonce.into(), role: Role::Player, + name: None, }) } @@ -324,6 +325,7 @@ async fn cross_host_handoff_follows_redirect_and_ticket_is_single_use() { expires_at: 4_000_000_000, nonce: "x".into(), role: Role::Player, + name: None, }); assert!(join_url(&b.addr.zone_url("realm.west"), &forged, "") .await diff --git a/distributed_game/tests/world_host/main.rs b/distributed_game/tests/world_host/main.rs index bea2e28c8..1699da6bc 100644 --- a/distributed_game/tests/world_host/main.rs +++ b/distributed_game/tests/world_host/main.rs @@ -19,6 +19,7 @@ fn claims(principal: &str, zone: &str) -> TicketClaims { expires_at: u64::MAX, nonce: format!("n-{principal}"), role: Role::Player, + name: None, } } diff --git a/distributed_game/tests/zone_runtime/arena.rs b/distributed_game/tests/zone_runtime/arena.rs index c64fd01ba..d3805d52e 100644 --- a/distributed_game/tests/zone_runtime/arena.rs +++ b/distributed_game/tests/zone_runtime/arena.rs @@ -148,11 +148,24 @@ impl Zone for Arena { fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { ctx.set_view(observer, View::new(50.0, 50.0, 1000.0)); - self.log.push("observe".into()); + let info = ctx + .observer(observer) + .expect("observer known in on_observe"); + let line = format!( + "observe:{}:{}", + info.principal, + info.name.as_deref().unwrap_or("-") + ); + let mine: Vec<_> = ctx.observers_of(&info.principal.clone()).collect(); + assert_eq!(mine, vec![observer]); + ctx.send_event(observer, 7, line.clone().into_bytes()); + self.log.push(line); } - fn on_unobserve(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) { - self.log.push("unobserve".into()); + fn on_unobserve(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + let principal = ctx.observer(observer).map(|o| o.principal.clone()); + self.log + .push(format!("unobserve:{}", principal.as_deref().unwrap_or("?"))); } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option<(i8, i8)> { diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index bfd0e3e64..adc8dba26 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -24,6 +24,7 @@ fn claims(principal: &str, zone: &str) -> TicketClaims { expires_at: u64::MAX, nonce: format!("n-{principal}"), role: Role::Player, + name: None, } } @@ -493,9 +494,11 @@ fn observers_receive_deltas_without_owning_a_player() { let clock = ManualClock::new(); let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); h.join(&claims("alice", "z1"), 0, "").unwrap(); - let mut obs_claims = claims("watcher", "z1"); + let mut obs_claims = claims("watcher", "z1").with_name("Wat"); obs_claims.role = Role::Observer; let o = h.join(&obs_claims, 0, "").unwrap(); + assert!(h.zone().log.contains(&"observe:watcher:Wat".to_string())); + assert_eq!(h.observers().next().unwrap().principal, "watcher"); assert_eq!(h.player_count(), 1); assert_eq!( h.push_input(o.client, 1, 0, &[1, 0]), @@ -504,13 +507,22 @@ fn observers_receive_deltas_without_owning_a_player() { clock.advance(MS(100)); h.advance(); let mut mirror = ClientMirror::new(); + let mut events = Vec::new(); for frame in frames_for(&h.drain_outbound(), o.client) { - mirror.apply(&frame).unwrap(); + if let ServerMessage::Event { type_id, payload } = mirror.apply(&frame).unwrap() { + events.push((type_id, payload)); + } } assert_eq!(mirror.welcome.as_ref().unwrap().role, Role::Observer); assert_eq!(mirror.entities.len(), 1); + assert!( + events + .iter() + .any(|(t, p)| *t == 7 && p == b"observe:watcher:Wat"), + "event addressed to the observer" + ); h.disconnect(o.client, false); - assert!(h.zone().log.contains(&"unobserve".to_string())); + assert!(h.zone().log.contains(&"unobserve:watcher".to_string())); } #[test] diff --git a/examples/game/server/src/common/dev.rs b/examples/game/server/src/common/dev.rs index c57e7d05c..23c65cb07 100644 --- a/examples/game/server/src/common/dev.rs +++ b/examples/game/server/src/common/dev.rs @@ -170,6 +170,7 @@ async fn ticket( expires_at, nonce: guests::random_hex(24), role, + name: None, }); Ok(Json(TicketResponse { ticket, diff --git a/examples/game/server/tests/gallery_smoke.rs b/examples/game/server/tests/gallery_smoke.rs index 2dcc2b812..f5822fa6b 100644 --- a/examples/game/server/tests/gallery_smoke.rs +++ b/examples/game/server/tests/gallery_smoke.rs @@ -39,6 +39,7 @@ impl Rig { expires_at: u64::MAX, nonce: "n1".into(), role: Role::Player, + name: None, }, 0, "", From 3ec5b97acd24b3b028298041bd648cccfa66feda Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:15:10 -0500 Subject: [PATCH 156/484] feat(game): re-export BoxFuture for external FactSink impls BoxFuture is now exported from the crate root (and from world and net for ZoneOwnership / BarrierParticipant impls). A test implements FactSink with crate-root imports only, the way a downstream crate would. Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 5 +++- distributed_game/src/lib.rs | 4 +-- distributed_game/src/net/mod.rs | 1 + distributed_game/src/world/mod.rs | 1 + distributed_game/tests/zone_runtime/main.rs | 33 +++++++++++++++++++-- 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index 31e435c44..87d275f50 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -100,7 +100,10 @@ stamps zone/tick/content version. A `FactSink` commits facts on a worker with bounded retries/backoff; `Zone::on_fact_settled` receives the outcome on a later tick. `cell::CellFactSink` dispatches into an `AggregateCell` with a deterministic command id per fact key, so retries replay instead of -double-crediting. +double-crediting. A custom sink needs only crate-root imports: +`impl FactSink for MySink { fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { Box::pin(async move { … }) } }` +(`BoxFuture` is also re-exported from `world` and `net` for +`ZoneOwnership` / `BarrierParticipant` impls). ## Netcode and operations diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 554026541..c76ef0603 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -56,8 +56,8 @@ pub use clock::{Clock, ManualClock, SystemClock}; #[cfg(feature = "runtime")] pub use facts::spawn_fact_worker; pub use facts::{ - fact_channel, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, FactReceipt, - FactSettlement, FactSink, MemoryFactSink, RetryPolicy, SettlementScript, + fact_channel, BoxFuture, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, + FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, SettlementScript, }; pub use handoff::{HandoffError, HandoffRequest, Transfer}; pub use host::{AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, ZoneHost}; diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 00aebbe72..1d2cb9751 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -60,6 +60,7 @@ use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::JoinHandle; use tokio::time::Instant; +pub use crate::facts::BoxFuture; pub use ticket::{ decode_hs256, NonceCache, SharedTicketVerifier, TicketError, TicketKey, TicketVerifier, VerifiedTicket, diff --git a/distributed_game/src/world/mod.rs b/distributed_game/src/world/mod.rs index c95d4fa30..d325cccaa 100644 --- a/distributed_game/src/world/mod.rs +++ b/distributed_game/src/world/mod.rs @@ -19,6 +19,7 @@ pub mod ownership; pub mod state; pub mod topology; +pub use crate::facts::BoxFuture; pub use barrier::{BarrierMode, FreezeState, StalePolicy}; pub use directory::{HashRing, HostAddr, StaticDirectory, ZoneDirectory}; #[cfg(feature = "lease")] diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index adc8dba26..de715788c 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -299,6 +299,35 @@ fn same_seed_and_input_log_reproduce_state() { assert_ne!(run_scripted(7).0, first.0, "different seed diverges"); } +/// A sink written the way a downstream crate would: only crate-root +/// imports (`distributed_game::{BoxFuture, Fact, FactSink, ...}`). +mod external_sink { + use distributed_game::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; + + pub struct CountingSink(pub std::sync::atomic::AtomicUsize); + + impl FactSink for CountingSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(FactReceipt { + payload: serde_json::json!({ "key": fact.key() }), + replayed: false, + }) + }) + } + } +} + +#[tokio::test] +async fn facts_sink_implementable_from_crate_root_exports() { + let sink = external_sink::CountingSink(Default::default()); + let fact = Fact::new("k1", "cmd", serde_json::json!({})); + let receipt = sink.commit(&fact).await.unwrap(); + assert_eq!(receipt.payload["key"], "k1"); + assert_eq!(sink.0.load(Ordering::SeqCst), 1); +} + /// Sink that takes `delay` per commit (simulated slow storage). struct SlowSink { delay: Duration, @@ -309,7 +338,7 @@ impl FactSink for SlowSink { fn commit<'a>( &'a self, fact: &'a Fact, - ) -> distributed_game::facts::BoxFuture<'a, Result> { + ) -> distributed_game::BoxFuture<'a, Result> { Box::pin(async move { tokio::time::sleep(self.delay).await; self.inner.commit(fact).await @@ -386,7 +415,7 @@ impl FactSink for FlakySink { fn commit<'a>( &'a self, fact: &'a Fact, - ) -> distributed_game::facts::BoxFuture<'a, Result> { + ) -> distributed_game::BoxFuture<'a, Result> { Box::pin(async move { if fact.key() == self.permanent_key { return Err(FactError::Permanent("no such player".into())); From 9c8b3b290d5652af43d6bd9ae9fb9c7017244e34 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:19:36 -0500 Subject: [PATCH 157/484] fix(game): restart-safe ownership tokens and fact keys - LocalOwnership seeds every zone's first fencing token from its epoch (Unix micros at creation; LocalOwnership::with_epoch), so a restarted host outranks snapshots saved by its previous run. Before, tokens restarted at 1 and every hibernation save against an existing snapshot was rejected as Stale and silently dropped. - Hibernation saves are never swallowed: counted in distributed_game_hibernation_saves_total{outcome} and logged. - HostConfig::boot_epoch / Ctx::boot_epoch: unique per activation and growing across restarts (the net server uses the fencing token). Ctx::fact_key and facts::fact_key build restart-safe idempotency keys; README warns that tick/generation-only keys collide after a restart. Mob Pit uses ctx.fact_key. Recordings store the epoch. Test: restart a server on the same SqliteZoneStateStore after two activations; hibernation saves still succeed (fails without the fix). Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 16 ++++- distributed_game/src/facts.rs | 25 ++++++- distributed_game/src/host.rs | 40 +++++++++++ distributed_game/src/lib.rs | 5 +- distributed_game/src/metrics.rs | 37 ++++++++++ distributed_game/src/net/mod.rs | 23 +++++- distributed_game/src/replay.rs | 8 ++- distributed_game/src/world/ownership.rs | 51 ++++++++++++-- distributed_game/tests/world/main.rs | 78 +++++++++++++++++++++ distributed_game/tests/zone_runtime/main.rs | 28 ++++++++ examples/game/README.md | 8 ++- examples/game/server/src/mobpit/world.rs | 3 +- examples/game/server/src/mobpit/zone.rs | 14 ++-- 13 files changed, 308 insertions(+), 28 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index 87d275f50..d43019c16 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -92,9 +92,21 @@ server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_sign Zones never await storage. Emit a fact during a tick: ```rust,ignore -ctx.emit_fact_for(player, Fact::new(format!("kill:{zone}:{tick}:{enemy}"), "hero.credit_xp", json!({"amount": 25})))?; +let key = ctx.fact_key("kill", &[&enemy_id, &enemy_generation]); // "kill:{zone}:{boot_epoch}:…" +ctx.emit_fact_for(player, Fact::new(key, "hero.credit_xp", json!({"amount": 25})))?; ``` +> **Warning — restart-safe keys.** Ticks, entity ids and generations all +> restart from zero when a process restarts (or a zone is re-activated from +> a snapshot). A key derived only from them — `format!("kill:{zone}:{tick}")` +> — **collides with an earlier run's key**, and an idempotent sink then +> treats the new outcome as a replay of the old one: the XP is silently +> never credited. Always include `ctx.boot_epoch()` (unique per activation, +> increasing across restarts; the `net` server uses the activation's fencing +> token, a bare `ZoneHost` Unix microseconds, or `HostConfig::boot_epoch`) +> — `ctx.fact_key(prefix, parts)` / `fact_key(prefix, zone, epoch, parts)` +> do it for you. + The host binds the principal from the player's **verified ticket** and stamps zone/tick/content version. A `FactSink` commits facts on a worker with bounded retries/backoff; `Zone::on_fact_settled` receives the outcome @@ -169,7 +181,7 @@ double-crediting. A custom sink needs only crate-root imports: |---|---| | `ZoneDirectory` (`StaticDirectory`, `HashRing`) | zone → owning `HostAddr`. `HashRing` uses virtual nodes; adding/removing one of N hosts moves ~1/N of the zones. A Hello for a zone owned elsewhere gets `Redirect(zone, url)`. | | `ZoneOwnership` (`LocalOwnership`, `FencedLeaseOwnership`) | every activation acquires a fenced claim (`host#activation`) and renews it; a failed renewal disposes the zone **without** saving. Two hosts never run the same zone. | -| `ZoneStateStore` (`MemoryZoneStateStore`, `SqliteZoneStateStore`) | hibernation snapshots, written under the claim's fencing token (stale writers get `StateError::Stale`). | +| `ZoneStateStore` (`MemoryZoneStateStore`, `SqliteZoneStateStore`) | hibernation snapshots, written under the claim's fencing token (stale writers get `StateError::Stale`, counted in `distributed_game_hibernation_saves_total{outcome="stale"}` and logged to stderr, never silently dropped). `LocalOwnership` seeds its tokens from the Unix time (µs) at creation, so a restarted host still outranks the snapshots its previous run saved. | | `ZoneTopology` (`DottedTopology` default: `eldoria.port.docks` → `eldoria.port` → `eldoria`) | parent links for tier-up events. | **Activate on demand / hibernate.** `GameServer` creates a zone on first diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs index 522b8c6a3..b8a297bf8 100644 --- a/distributed_game/src/facts.rs +++ b/distributed_game/src/facts.rs @@ -35,6 +35,27 @@ use crate::stamp::FactStamp; /// Boxed `Send` future used by [`FactSink`]. pub type BoxFuture<'a, T> = Pin + Send + 'a>>; +/// Restart-safe idempotency key: `"{prefix}:{zone}:{epoch}:{part}:…"`. +/// +/// `epoch` must change between activations and grow across restarts +/// ([`Ctx::boot_epoch`](crate::Ctx::boot_epoch)). Keys derived only from the +/// tick or an entity generation **collide after a restart** — both counters +/// start again from zero — and an idempotent sink then treats the new +/// outcome as a replay of the old one (silently dropping it). +/// +/// ``` +/// use distributed_game::facts::fact_key; +/// assert_eq!(fact_key("kill", "pit-1", 7, &[&"mob-3", &42]), "kill:pit-1:7:mob-3:42"); +/// ``` +pub fn fact_key(prefix: &str, zone: &str, epoch: u64, parts: &[&dyn std::fmt::Display]) -> String { + use std::fmt::Write as _; + let mut key = format!("{prefix}:{zone}:{epoch}"); + for part in parts { + let _ = write!(key, ":{part}"); + } + key +} + /// A durable outcome to commit. #[derive(Debug, Clone, PartialEq)] pub struct Fact { @@ -46,7 +67,9 @@ pub struct Fact { } impl Fact { - /// `key` must be unique per logical outcome (e.g. `"kill:{zone}:{tick}:{enemy}"`); + /// `key` must be unique per logical outcome **across restarts**: build it + /// with [`Ctx::fact_key`](crate::Ctx::fact_key) / [`fact_key`] (zone + + /// boot epoch + your parts), never from the tick alone; /// `command` names the durable command; `input` is its payload. pub fn new(key: impl Into, command: impl Into, input: Value) -> Self { Self { diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 39bb77e2d..0ac439001 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -85,6 +85,12 @@ pub struct HostConfig { /// Admission of clients whose content version differs from /// `content_version` (see [`StalePolicy`]). pub stale_policy: StalePolicy, + /// Epoch of this activation of the zone ([`Ctx::boot_epoch`]): must + /// differ between activations and grow across restarts so fact keys + /// built from it never collide with an earlier run's. `0` (default) = + /// Unix time in microseconds when the host is created. The `net` server + /// sets it to the activation's fencing token. + pub boot_epoch: u64, } impl Default for HostConfig { @@ -106,6 +112,7 @@ impl Default for HostConfig { world_seed: 0, rewind: RewindConfig::default(), stale_policy: StalePolicy::Strict, + boot_epoch: 0, } } } @@ -322,6 +329,28 @@ impl Ctx<'_, Z> { &self.core.config.content_version } + /// Epoch of this zone activation ([`HostConfig::boot_epoch`]): unique + /// per activation and increasing across restarts and hibernation. + /// Tick counts and entity generations restart with the process, so a + /// fact key built only from them **collides after a restart** (and the + /// sink replays the old commit instead of recording the new outcome); + /// include this epoch, e.g. via [`fact_key`](Self::fact_key). + pub fn boot_epoch(&self) -> u64 { + self.core.config.boot_epoch + } + + /// Restart-safe fact idempotency key: + /// `"{prefix}:{zone}:{boot_epoch}:{part}:{part}…"` (see + /// [`fact_key`](crate::facts::fact_key)). + pub fn fact_key(&self, prefix: &str, parts: &[&dyn std::fmt::Display]) -> String { + crate::facts::fact_key( + prefix, + &self.core.zone_id, + self.core.config.boot_epoch, + parts, + ) + } + /// The zone's deterministic RNG. pub fn rng(&mut self) -> &mut ZoneRng { &mut self.core.rng @@ -589,6 +618,10 @@ impl ZoneHost { ) -> Self { let zone_id = zone_id.into(); let now = clock.now(); + let mut config = config; + if config.boot_epoch == 0 { + config.boot_epoch = unix_micros(); + } let mut core = Core { rng: ZoneRng::for_zone(config.world_seed, &zone_id), zone_id, @@ -1624,6 +1657,13 @@ impl ZoneHost { } } +fn unix_micros() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64) + .max(1) +} + pub(crate) fn default_token() -> String { use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hasher}; diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index c76ef0603..b62b3e5f1 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -56,8 +56,9 @@ pub use clock::{Clock, ManualClock, SystemClock}; #[cfg(feature = "runtime")] pub use facts::spawn_fact_worker; pub use facts::{ - fact_channel, BoxFuture, EmitError, Fact, FactError, FactFeed, FactOutcome, FactQueue, - FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, SettlementScript, + fact_channel, fact_key, BoxFuture, EmitError, Fact, FactError, FactFeed, FactOutcome, + FactQueue, FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, + SettlementScript, }; pub use handoff::{HandoffError, HandoffRequest, Transfer}; pub use host::{AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, ZoneHost}; diff --git a/distributed_game/src/metrics.rs b/distributed_game/src/metrics.rs index 541a294ee..00595189d 100644 --- a/distributed_game/src/metrics.rs +++ b/distributed_game/src/metrics.rs @@ -36,6 +36,7 @@ //! | `distributed_game_zone_delta_deferred_total` | counter | zone | //! | `distributed_game_zone_facts_pending` | gauge | zone | //! | `distributed_game_zone_facts_settled_total` | counter | zone, outcome | +//! | `distributed_game_hibernation_saves_total` | counter | outcome (`saved`, `stale`, `error`) | use crate::facts::FactOutcome; use crate::host::{AdvanceReport, ZoneHost}; @@ -160,8 +161,13 @@ struct State { zones: BTreeMap, labeled: usize, other: Counters, + /// Server-wide (zones are forgotten when they hibernate). + hibernation_saves: BTreeMap<&'static str, u64>, } +/// Hibernation snapshot save outcome label values (fixed set). +pub const HIBERNATION_OUTCOMES: [&str; 3] = ["saved", "stale", "error"]; + impl State { fn zone(&mut self, zone: &str, max: usize) -> &mut ZoneSeries { if !self.zones.contains_key(zone) { @@ -279,6 +285,24 @@ impl GameMetrics { .or_insert(0) += 1; } + /// Record a hibernation snapshot save: `"saved"`, `"stale"` (rejected by + /// the fenced store: a newer owner saved, or tokens went backwards) or + /// `"error"` (backend failure). Other labels are ignored. + pub fn record_hibernation_save(&self, outcome: &str) { + if let Some(label) = HIBERNATION_OUTCOMES.iter().find(|l| **l == outcome) { + *self.lock().hibernation_saves.entry(label).or_insert(0) += 1; + } + } + + /// Hibernation saves recorded with `outcome`. + pub fn hibernation_saves(&self, outcome: &str) -> u64 { + self.lock() + .hibernation_saves + .get(outcome) + .copied() + .unwrap_or(0) + } + /// A zone stopped: drop its series and free its label slot. pub fn forget_zone(&self, zone: &str) { let mut state = self.lock(); @@ -465,6 +489,19 @@ impl GameMetrics { ); } } + header( + &mut out, + "hibernation_saves_total", + "counter", + "Hibernation snapshot saves by outcome (stale = rejected by the fenced store).", + ); + for label in HIBERNATION_OUTCOMES { + let v = state.hibernation_saves.get(label).copied().unwrap_or(0); + let _ = writeln!( + out, + "distributed_game_hibernation_saves_total{{outcome=\"{label}\"}} {v}" + ); + } out } } diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 1d2cb9751..2c988ed01 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -78,7 +78,8 @@ use crate::protocol::{error, kick, ClientMessage, Notice, ServerMessage, PROTOCO use crate::rng::ZoneRng; use crate::world::{ BarrierMode, ChildEvent, DottedTopology, FreezeState, HostAddr, LocalOwnership, OwnershipError, - StoredZoneState, ZoneClaim, ZoneDirectory, ZoneOwnership, ZoneStateStore, ZoneTopology, + StateError, StoredZoneState, ZoneClaim, ZoneDirectory, ZoneOwnership, ZoneStateStore, + ZoneTopology, }; use crate::zone::{ClientId, TicketClaims, Tier, Zone}; @@ -986,6 +987,9 @@ async fn run_zone( }; let mut host_config = inner.config.host.clone(); host_config.content_version = world.version.clone(); + // Fencing tokens grow across activations and restarts: a restart-safe + // epoch for fact keys (`Ctx::boot_epoch`). + host_config.boot_epoch = claim.token; let token_inner = inner.clone(); let issuer_inner = inner.clone(); let generation = claim.token; @@ -1142,8 +1146,21 @@ async fn run_zone( content_version, state, }; - // A stale token means a newer owner saved already: drop ours. - let _ = tokio::task::spawn_blocking(move || store.save(&id, &stored)).await; + // A stale token means a newer owner saved already: ours is + // dropped, but never silently (metrics + stderr). + let saved = tokio::task::spawn_blocking(move || store.save(&id, &stored)).await; + let outcome = match &saved { + Ok(Ok(())) => "saved", + Ok(Err(StateError::Stale { .. })) => "stale", + _ => "error", + }; + inner.metrics.record_hibernation_save(outcome); + if outcome != "saved" { + eprintln!( + "distributed_game: hibernation snapshot of zone {zone_id} (token {}) not saved: {saved:?}", + claim.token + ); + } } inner.ownership.release(&claim).await; drop(host); diff --git a/distributed_game/src/replay.rs b/distributed_game/src/replay.rs index d0d176947..3caf4b262 100644 --- a/distributed_game/src/replay.rs +++ b/distributed_game/src/replay.rs @@ -375,7 +375,7 @@ pub struct Recording { /// File decode failure. #[derive(Debug, Clone, PartialEq, Eq)] pub enum RecordingError { - /// Not a `DGR1` file. + /// Not a `DGR2` file. BadMagic, /// Malformed content. Decode(String), @@ -551,6 +551,7 @@ fn put_config(w: &mut Writer, c: &HostConfig) { StalePolicy::SafeRoom { roam: false } => 1, StalePolicy::SafeRoom { roam: true } => 2, }); + put_u64(w, c.boot_epoch); } fn put_claims(w: &mut Writer, claims: &TicketClaims) { @@ -622,12 +623,13 @@ fn get_config(r: &mut Reader<'_>) -> Result { 1 => StalePolicy::SafeRoom { roam: false }, _ => StalePolicy::SafeRoom { roam: true }, }, + boot_epoch: get_u64(r)?, }) } impl Recording { /// Compact binary encoding: - /// `"DGR1" ‖ zone_id ‖ config ‖ created_at ‖ fact_capacity? ‖ zone_config ‖ + /// `"DGR2" ‖ zone_id ‖ config ‖ created_at ‖ fact_capacity? ‖ zone_config ‖ /// varuint(event count) ‖ events`. Integers are LEB128 varints, /// durations are nanosecond varints, clock readings are delta-coded /// against the previous event, hashes are 8 raw bytes. @@ -1003,6 +1005,8 @@ impl Recorder { token }); host.set_tick_hashing(true); + // The resolved boot epoch, so replayed fact keys match. + let config = host.config().clone(); Self { host, clock, diff --git a/distributed_game/src/world/ownership.rs b/distributed_game/src/world/ownership.rs index 499f0645e..719e9af1a 100644 --- a/distributed_game/src/world/ownership.rs +++ b/distributed_game/src/world/ownership.rs @@ -67,16 +67,44 @@ pub trait ZoneOwnership: Send + Sync + 'static { } /// Process-local ownership without TTLs (single host / tests). Tokens are -/// monotonic per zone and survive release. -#[derive(Debug, Default)] +/// monotonic per zone, survive release and **keep increasing across process +/// restarts**: the first token of every zone is the instance's epoch (Unix +/// time in microseconds at creation), so a restarted host's claims outrank +/// snapshots its previous run saved in a durable +/// [`ZoneStateStore`](super::ZoneStateStore). +#[derive(Debug)] pub struct LocalOwnership { + epoch: u64, claims: Mutex, u64)>>, } +impl Default for LocalOwnership { + fn default() -> Self { + Self::new() + } +} + impl LocalOwnership { - /// Empty. + /// Empty, epoch = now (Unix microseconds). pub fn new() -> Self { - Self::default() + let micros = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64); + Self::with_epoch(micros) + } + + /// Empty with an explicit epoch (first token of every zone; must exceed + /// every token a previous run used with the same state store). + pub fn with_epoch(epoch: u64) -> Self { + Self { + epoch: epoch.max(1), + claims: Mutex::new(HashMap::new()), + } + } + + /// First token handed out for each zone. + pub fn epoch(&self) -> u64 { + self.epoch } } @@ -97,7 +125,7 @@ impl ZoneOwnership for LocalOwnership { Some(_) => Ok(entry.1), None => { entry.0 = Some(holder.to_string()); - entry.1 += 1; + entry.1 = (entry.1 + 1).max(self.epoch); Ok(entry.1) } } @@ -271,4 +299,17 @@ mod tests { let b = block(own.acquire("z", "h2#1", ttl)).unwrap(); assert!(b.token > a.token); } + + #[test] + fn local_tokens_outrank_a_previous_process() { + let ttl = Duration::from_secs(1); + let before = LocalOwnership::with_epoch(100); + let old = block(before.acquire("z", "h#1", ttl)).unwrap(); + assert_eq!(old.token, 100); + // A restarted process starts from a later epoch. + let after = LocalOwnership::new(); + let new = block(after.acquire("z", "h#1", ttl)).unwrap(); + assert!(new.token > old.token); + assert_eq!(new.token, after.epoch()); + } } diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index b9ee3c63f..08a5812f3 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -549,6 +549,84 @@ async fn dormant_zone_hibernates_to_sqlite_and_restores() { } } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn hibernation_saves_succeed_after_a_host_restart_on_the_same_store() { + let path = std::env::temp_dir().join(format!( + "dg-world-restart-{}-{}.sqlite3", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let url_of = |addr: &str| format!("ws://{addr}/zones/realm.keep"); + let mut epochs = Vec::new(); + let mut count = 0u32; + for run in 1..=2 { + // A fresh process: new store handle, new (default) LocalOwnership. + let store = Arc::new(SqliteZoneStateStore::open(&path).unwrap()); + let mut config = base_config(); + config.host.idle_tick_rate = None; + config.host.dormant_after = Duration::from_millis(50); + config.hibernate_after = Some(Duration::from_millis(100)); + let (listener, addr) = listen().await; + let factory = realm_factory(&[], &[]); + let server = + GameServer::::new(config, move |z| factory(z)).with_state_store(store.clone()); + serve(&server, listener); + // Two activations per run, so the first run's last token exceeds + // the restarted run's first token unless tokens survive restarts. + for cycle in 1..=2u64 { + let nonce = format!("r{run}-{cycle}"); + let mut ana = join_url(&url_of(&addr), &ticket("ana", "realm.keep", &nonce), "") + .await + .unwrap(); + input(&mut ana, 1, CMD_COUNT).await; + count += 1; + let expected = count; + eventually("count", || { + let server = server.clone(); + async move { + server.inspect("realm.keep", |h| h.zone().counter).await == Some(expected) + } + }) + .await; + epochs.push( + server + .inspect("realm.keep", |h| h.config().boot_epoch) + .await + .unwrap(), + ); + send(&mut ana.ws, ClientMessage::Leave).await; + eventually("hibernation", || { + let server = server.clone(); + async move { !server.is_active("realm.keep") } + }) + .await; + assert_eq!(server.metrics().hibernation_saves("stale"), 0, "run {run}"); + assert_eq!( + server.metrics().hibernation_saves("saved"), + cycle, + "run {run}" + ); + let saved = store.load("realm.keep").unwrap().expect("snapshot"); + assert_eq!(saved.state, count.to_le_bytes(), "run {run} saved"); + } + assert!(server + .metrics() + .render() + .contains("distributed_game_hibernation_saves_total{outcome=\"saved\"} 2")); + server.shutdown(); + } + assert!( + epochs.windows(2).all(|w| w[1] > w[0]), + "epochs grow: {epochs:?}" + ); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn fenced_lease_keeps_zone_on_one_host_and_loss_stops_it() { let clock = distributed::ManualClock::starting_now(); diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index de715788c..317e0737e 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -566,3 +566,31 @@ fn same_principal_replaces_previous_connection() { assert!(out.contains(&Outbound::Close { client: a.client })); assert_eq!(h.zone().log, vec!["create", "join:alice"]); } + +#[test] +fn boot_epoch_defaults_to_wall_clock_and_can_be_pinned() { + let clock = ManualClock::new(); + let default = host(HostConfig::default(), &clock, ArenaConfig::default()); + assert!( + default.config().boot_epoch > 1_600_000_000_000_000, + "unix micros" + ); + let pinned = host( + HostConfig { + boot_epoch: 42, + ..HostConfig::default() + }, + &clock, + ArenaConfig::default(), + ); + assert_eq!(pinned.config().boot_epoch, 42); + assert_eq!( + distributed_game::fact_key( + "kill", + pinned.zone_id(), + pinned.config().boot_epoch, + &[&7, &"m"] + ), + "kill:z1:42:7:m" + ); +} diff --git a/examples/game/README.md b/examples/game/README.md index 49d46653c..5b810c612 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -160,7 +160,7 @@ after dying. Level `n` starts at `40·(n−1)²` XP. **One kill, end to end** (`server/src/mobpit/`): 1. `zone.rs`, tick N: the mob's HP reaches 0. The zone calls - `ctx.emit_fact_for(killer, Fact::new("kill:{boot}:{zone}:m{id}:{gen}", + `ctx.emit_fact_for(killer, Fact::new(ctx.fact_key("kill", &[m{id}, gen]), "crawler.record_kill", {mob, tier, name}))` and broadcasts a `kill` event. `emit_fact_for` only enqueues: the host binds the killer's **verified ticket principal**; the zone never awaits storage. Backpressure (256 @@ -214,8 +214,10 @@ back from the cell. What survives: no zone-side outbox (see `distributed_game` README, *Facts on dispose*). - **Retries and replays** of the same key (the worker's retry after a timeout, or a re-emitted fact) replay the stored receipt through the - ledger: `replayed: true`, nothing credited twice. Fact keys contain a - per-process `boot` id because zone ticks and mob generations restart at 0. + ledger: `replayed: true`, nothing credited twice. Fact keys + (`kill:{zone}:{boot_epoch}:m{id}:{gen}`) contain the activation's boot + epoch (`Ctx::boot_epoch`, grows across restarts) because zone ticks and + mob generations restart at 0. `tests/mobpit_smoke.rs` proves it with the real binary: bots fight, storage is made slow, the server gets `SIGKILL` with facts in flight, restarts on the diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs index 98d998ffb..1a10b0ef9 100644 --- a/examples/game/server/src/mobpit/world.rs +++ b/examples/game/server/src/mobpit/world.rs @@ -77,7 +77,8 @@ impl MobPitWorld { })) } - /// Random id of this server process (part of every fact key). + /// Random id of this server process (shown by clients to spot restarts; + /// fact keys use `Ctx::fact_key` / the boot epoch). pub fn boot(&self) -> &str { &self.boot } diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index 85ca2424a..f2c4224a2 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -19,10 +19,11 @@ //! with a new generation. //! //! A kill emits a fact **without awaiting storage**: -//! `Fact::new("kill:{boot}:{zone}:{mob}:{generation}", "crawler.record_kill", +//! `Fact::new(ctx.fact_key("kill", &[mob, generation]), "crawler.record_kill", //! {mob, tier, name})` via `ctx.emit_fact_for(killer)` — the host binds the -//! killer's verified principal. `boot` is random per server process, so keys -//! never collide with an earlier run's facts (zone ticks restart at 0). The +//! killer's verified principal. The key is `kill:{zone}:{boot_epoch}:m{mob}: +//! {generation}`: the boot epoch grows across restarts, so keys never collide +//! with an earlier run's facts (generations and ticks restart at 0). The //! settlement arrives in [`Zone::on_fact_settled`] on a later tick and is //! pushed to the killer as [`EVENT_SAVED`] + [`EVENT_PROFILE`]. @@ -266,12 +267,7 @@ impl MobPit { fn emit_kill(&mut self, ctx: &mut Ctx<'_, Self>, killer: PlayerId, mob: usize) { let m = &self.mobs[mob]; let zone = ctx.zone_id().to_string(); - let key = format!( - "kill:{}:{zone}:m{}:{}", - self.world.boot(), - m.id, - m.generation - ); + let key = ctx.fact_key("kill", &[&format_args!("m{}", m.id), &m.generation]); let (x, y, tier, id) = (m.x, m.y, m.tier, m.id); let Some(player) = self.players.get(&killer) else { return; From 13fe9c46f3c8a081702a1b44e45c2569bc0cfb20 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:21:22 -0500 Subject: [PATCH 158/484] feat(game): bounded concurrent fact commits in principal lanes FactFeed::with_max_concurrent_commits(n) / ServerConfig:: max_concurrent_commits (default 1 keeps strict emission order). Above 1, up to n commits overlap; facts of one principal (and zone facts without one) stay sequential in emission order, so per-key and per-principal order hold while a slow commit no longer blocks other players' facts. Ordering semantics documented in facts and README. Test: a slow commit delays every fact at n = 1; at n = 4 other principals overtake it and the same principal's next fact waits. Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 8 + distributed_game/src/facts.rs | 158 ++++++++++++++++++-- distributed_game/src/net/mod.rs | 8 + distributed_game/tests/zone_runtime/main.rs | 76 ++++++++++ 4 files changed, 234 insertions(+), 16 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index d43019c16..e171f80ad 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -117,6 +117,14 @@ double-crediting. A custom sink needs only crate-root imports: (`BoxFuture` is also re-exported from `world` and `net` for `ZoneOwnership` / `BarrierParticipant` impls). +**Throughput.** One worker per zone commits facts in emission order, one at +a time (a slow commit delays every later fact). Set +`ServerConfig::max_concurrent_commits` (or +`FactFeed::with_max_concurrent_commits`) above 1 to overlap commits in +**per-principal lanes**: a principal's facts (and, separately, zone facts +without a principal) stay sequential in emission order; different +principals commit concurrently; settlements arrive in completion order. + ## Netcode and operations - **Admission tickets** (`net`): by default join tickets are HS256 JWTs diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs index b8a297bf8..d8805336f 100644 --- a/distributed_game/src/facts.rs +++ b/distributed_game/src/facts.rs @@ -18,6 +18,16 @@ //! replay (the cell adapter maps it onto `dispatch_idempotent`). //! - Trusted identity: the principal is bound by the host from the player's //! verified ticket — zones and clients cannot set it. +//! +//! Ordering: by default (`max_concurrent_commits = 1`) one worker commits +//! facts strictly in emission order, one at a time, so a slow commit delays +//! every later fact. With [`FactFeed::with_max_concurrent_commits`]`(n > 1)` +//! up to `n` commits run at once, in **lanes by principal**: facts of the +//! same principal (and, separately, all zone/system facts without one) are +//! still committed one at a time in emission order, while facts of +//! different principals overlap. A key is never in flight twice (the queue +//! refuses duplicates), so per-key order always holds. Settlements arrive +//! in completion order. use std::collections::{HashSet, VecDeque}; use std::future::Future; @@ -249,6 +259,7 @@ pub struct FactFeed { shared: Arc, settlements: mpsc::Sender, policy: RetryPolicy, + max_concurrent: usize, } /// Create a queue allowing `capacity` unsettled facts. @@ -267,6 +278,7 @@ pub fn fact_channel(capacity: usize, policy: RetryPolicy) -> (FactQueue, FactFee shared, settlements: tx, policy, + max_concurrent: 1, }, ) } @@ -388,7 +400,21 @@ impl Future for NextFact<'_> { } impl FactFeed { - /// Commit facts in emission order until the queue is dropped and drained. + /// Allow up to `n` commits at once (default 1: strict emission order). + /// Facts of one principal stay sequential; see the module docs. + pub fn with_max_concurrent_commits(mut self, n: usize) -> Self { + self.max_concurrent = n.max(1); + self + } + + /// Commits allowed at once. + pub fn max_concurrent_commits(&self) -> usize { + self.max_concurrent + } + + /// Commit facts until the queue is dropped and drained: in emission + /// order, or with bounded concurrency in per-principal lanes + /// ([`with_max_concurrent_commits`](Self::with_max_concurrent_commits)). /// `sleep` provides the runtime's timer for backoff. pub async fn run(self, sink: S, sleep: F) where @@ -396,24 +422,124 @@ impl FactFeed { F: Fn(Duration) -> Fut, Fut: Future, { - while let Some(fact) = NextFact(&self.shared).await { - let mut attempts = 0; - let outcome = loop { - attempts += 1; - match sink.commit(&fact).await { - Ok(receipt) => break FactOutcome::Committed(receipt), - Err(FactError::Retryable(_)) if attempts < self.policy.max_attempts.max(1) => { - sleep(self.policy.backoff(attempts)).await; + let policy = self.policy; + if self.max_concurrent <= 1 { + while let Some(fact) = NextFact(&self.shared).await { + let settlement = commit_with_retries(&sink, fact, policy, &sleep).await; + let _ = self.settlements.send(settlement); + } + return; + } + let start = |fact: Fact| Box::pin(commit_with_retries(&sink, fact, policy, &sleep)); + Pump { + shared: &self.shared, + settlements: &self.settlements, + limit: self.max_concurrent, + start, + waiting: VecDeque::new(), + active: Vec::new(), + } + .await; + } +} + +async fn commit_with_retries( + sink: &S, + fact: Fact, + policy: RetryPolicy, + sleep: &F, +) -> FactSettlement +where + S: FactSink, + F: Fn(Duration) -> Fut, + Fut: Future, +{ + let mut attempts = 0; + let outcome = loop { + attempts += 1; + match sink.commit(&fact).await { + Ok(receipt) => break FactOutcome::Committed(receipt), + Err(FactError::Retryable(_)) if attempts < policy.max_attempts.max(1) => { + sleep(policy.backoff(attempts)).await; + } + Err(error) => break FactOutcome::Failed { error, attempts }, + } + }; + FactSettlement { + key: fact.key, + command: fact.command, + outcome, + } +} + +/// Concurrent commit driver: at most `limit` commits in flight, one per +/// principal lane, admitted in emission order. +struct Pump<'a, T, M> { + shared: &'a Shared, + settlements: &'a mpsc::Sender, + limit: usize, + start: M, + waiting: VecDeque, + active: Vec<(Option, Pin>)>, +} + +impl Future for Pump<'_, T, M> +where + T: Future, + M: FnMut(Fact) -> Pin> + Unpin, +{ + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + let this = self.get_mut(); + // Register before checking so a concurrent push cannot be missed. + *this.shared.waker.lock().expect("waker lock") = Some(cx.waker().clone()); + loop { + this.waiting + .extend(this.shared.queue.lock().expect("fact queue lock").drain(..)); + // Admit in order; a lane is blocked by an active commit or by an + // earlier waiting fact of the same lane. + let mut blocked: HashSet> = + this.active.iter().map(|(lane, _)| lane.clone()).collect(); + let mut i = 0; + while i < this.waiting.len() && this.active.len() < this.limit { + let lane = this.waiting[i].principal.clone(); + if blocked.contains(&lane) { + i += 1; + continue; + } + let fact = this.waiting.remove(i).expect("index in range"); + blocked.insert(lane.clone()); + this.active.push((lane, (this.start)(fact))); + } + let mut progressed = false; + let mut j = 0; + while j < this.active.len() { + match this.active[j].1.as_mut().poll(cx) { + Poll::Ready(settlement) => { + let _ = this.settlements.send(settlement); + this.active.remove(j); + progressed = true; } - Err(error) => break FactOutcome::Failed { error, attempts }, + Poll::Pending => j += 1, } - }; - let _ = self.settlements.send(FactSettlement { - key: fact.key, - command: fact.command, - outcome, - }); + } + if !progressed { + break; + } + } + let drained = this.active.is_empty() + && this.waiting.is_empty() + && this + .shared + .queue + .lock() + .expect("fact queue lock") + .is_empty(); + if drained && this.shared.closed.load(Ordering::SeqCst) { + return Poll::Ready(()); } + Poll::Pending } } diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 2c988ed01..8c30f7d85 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -205,6 +205,11 @@ pub struct ServerConfig { pub admin_secret: Option, /// Peer (host-to-host) request timeout. pub peer_timeout: Duration, + /// Fact commits each zone's worker may run at once (default 1 = strict + /// emission order). Above 1, facts of one principal stay sequential and + /// different principals overlap (see [`crate::facts`]). Read by + /// [`GameServer::with_fact_sink`]. + pub max_concurrent_commits: usize, } impl ServerConfig { @@ -235,6 +240,7 @@ impl ServerConfig { settle_timeout: Duration::from_secs(2), admin_secret: None, peer_timeout: Duration::from_secs(3), + max_concurrent_commits: 1, } } } @@ -581,8 +587,10 @@ where ) -> Self { let sink = Arc::new(sink); let inner = Arc::get_mut(&mut self.inner).expect("configure before sharing the server"); + let concurrency = inner.config.max_concurrent_commits; inner.facts = Some(Box::new(move |_zone: &str| { let (queue, feed) = fact_channel(capacity, policy); + let feed = feed.with_max_concurrent_commits(concurrency); let worker = spawn_fact_worker(feed, sink.clone()); Some((queue, worker)) })); diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index 317e0737e..4342d8b62 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -594,3 +594,79 @@ fn boot_epoch_defaults_to_wall_clock_and_can_be_pinned() { "kill:z1:42:7:m" ); } + +/// Sink where keys starting with `slow` take `delay`; records completion order. +struct LaggySink { + delay: Duration, + done: Arc>>, +} + +impl FactSink for LaggySink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::BoxFuture<'a, Result> { + Box::pin(async move { + if fact.key().starts_with("slow") { + tokio::time::sleep(self.delay).await; + } + self.done.lock().unwrap().push(fact.key().to_string()); + Ok(FactReceipt { + payload: serde_json::Value::Null, + replayed: false, + }) + }) + } +} + +async fn commit_order(concurrency: usize) -> Vec { + let done = Arc::new(std::sync::Mutex::new(Vec::new())); + let (mut queue, feed) = fact_channel(16, RetryPolicy::default()); + let worker = tokio::spawn(feed.with_max_concurrent_commits(concurrency).run( + LaggySink { + delay: MS(300), + done: done.clone(), + }, + tokio::time::sleep, + )); + let fact = |key: &str, principal: &str| { + Fact::trusted( + key, + "cmd", + serde_json::Value::Null, + Some(principal.into()), + Default::default(), + ) + }; + queue.try_send(fact("slow-a1", "alice")).unwrap(); + queue.try_send(fact("fast-a2", "alice")).unwrap(); + queue.try_send(fact("fast-b1", "bob")).unwrap(); + queue.try_send(fact("fast-c1", "carol")).unwrap(); + let started = Instant::now(); + while queue.in_flight() > 0 { + queue.drain(); + assert!(started.elapsed() < Duration::from_secs(5), "settles"); + tokio::time::sleep(MS(5)).await; + } + drop(queue); + worker.await.unwrap(); + let order = done.lock().unwrap().clone(); + order +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn concurrent_commits_do_not_block_other_principals_and_keep_lane_order() { + // Default: strict emission order, the slow commit blocks everyone. + assert_eq!( + commit_order(1).await, + vec!["slow-a1", "fast-a2", "fast-b1", "fast-c1"] + ); + // Concurrency: bob and carol overtake; alice's second fact waits for + // her first (same principal lane). + let order = commit_order(4).await; + assert_eq!(order.len(), 4); + let pos = |k: &str| order.iter().position(|o| o == k).unwrap(); + assert!(pos("fast-b1") < pos("slow-a1"), "{order:?}"); + assert!(pos("fast-c1") < pos("slow-a1"), "{order:?}"); + assert!(pos("slow-a1") < pos("fast-a2"), "{order:?}"); +} From 9de34dda256b85bb9eed47c2c11de1b269066eb7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:24:29 -0500 Subject: [PATCH 159/484] feat(cell-host): read stream history on native SQLite cells AggregateCell::history() and stream_events(identity) read a stream's durable events through the cell's store, so they work on the in-process reference host and on cell-sqlite cells (durable_events is a reference-host export and errors on SQLite cells). Foreign streams are rejected by the store's ownership check. Mob Pit drops its kept store handle and uses cell.history(). Tests: reference host history matches the export; a SQLite cell reads every event after reopen (with snapshots every event). Refs [[specs/framework/game-runtime/v1/index]] --- examples/game/server/src/mobpit/store.rs | 17 ++------ src/microsvc/cell_host/cell.rs | 31 +++++++++++++- src/microsvc/cell_host/tests.rs | 5 +++ src/microsvc/cell_host/tests/native_sqlite.rs | 40 +++++++++++++++++++ 4 files changed, 78 insertions(+), 15 deletions(-) diff --git a/examples/game/server/src/mobpit/store.rs b/examples/game/server/src/mobpit/store.rs index 947d85b08..f9d5df62c 100644 --- a/examples/game/server/src/mobpit/store.rs +++ b/examples/game/server/src/mobpit/store.rs @@ -18,10 +18,9 @@ use std::time::Duration; use distributed::cell_host::{AggregateCell, CellSqlitePath, CellStreamStore}; use distributed::entity::EventRecord; -use distributed::{GetStream, RepositoryError, StreamIdentity}; +use distributed::{RepositoryError, StreamIdentity}; use distributed_game::cell::CellFactSink; -use distributed_game::facts::BoxFuture; -use distributed_game::{Fact, FactError, FactReceipt, FactSink}; +use distributed_game::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; use serde::Serialize; use super::board::Leaderboards; @@ -35,9 +34,7 @@ const FILE_PREFIX: &str = "Crawler%3A"; /// One player's open cell. pub struct CrawlerCell { - principal: String, cell: Arc>, - store: CellStreamStore, sink: CellFactSink, } @@ -49,11 +46,7 @@ impl CrawlerCell { /// The full durable event history of this cell, oldest first. pub async fn history(&self) -> Result, RepositoryError> { - let identity = StreamIdentity::new(AGGREGATE_TYPE, self.principal.clone())?; - Ok(GetStream::get_stream(&self.store, &identity) - .await? - .map(|entity| entity.events().to_vec()) - .unwrap_or_default()) + self.cell.history().await } /// The cell (tests dispatch into it directly). @@ -91,12 +84,10 @@ impl CrawlerCells { } let identity = StreamIdentity::new(AGGREGATE_TYPE, principal.to_string())?; let store = CellStreamStore::open_sqlite(&CellSqlitePath::root(&self.root), identity)?; - let cell = Arc::new(AggregateCell::from_store(store.clone())?.mount(RecordKill)); + let cell = Arc::new(AggregateCell::from_store(store)?.mount(RecordKill)); let entry = Arc::new(CrawlerCell { - principal: principal.to_string(), sink: CellFactSink::new(cell.clone(), SERVICE_ID, SYSTEM_PRINCIPAL), cell, - store, }); open.insert(principal.to_string(), entry.clone()); Ok(entry) diff --git a/src/microsvc/cell_host/cell.rs b/src/microsvc/cell_host/cell.rs index 0b5181584..0eb92d796 100644 --- a/src/microsvc/cell_host/cell.rs +++ b/src/microsvc/cell_host/cell.rs @@ -13,11 +13,12 @@ use super::store::{ DurableAggregateCellState, DurableCellCommand, DurableCellEvents, DurableCellSnapshot, }; use crate::aggregate::{Aggregate, AggregateRepository}; +use crate::entity::EventRecord; use crate::microsvc::error::HandlerError; use crate::microsvc::service::{PortableCommand, Routes}; use crate::microsvc::session::Session; use crate::microsvc::HasOutboxStore; -use crate::repository::{RepositoryError, SnapshotStore, StreamIdentity}; +use crate::repository::{GetStream, RepositoryError, SnapshotStore, StreamIdentity}; use crate::snapshot::{SnapshotRecord, Snapshottable}; use crate::OutboxDispatcher; @@ -264,7 +265,33 @@ where self.routes.repo().get(self.shard.aggregate_id()).await } - /// Event log for Durable Object SQLite persistence. + /// Durable event history of one stream this cell owns, oldest first + /// (empty when the stream has no events). Reads the backing store, so it + /// works on the in-process reference host **and** on native SQLite + /// cells (`cell-sqlite`), unlike the whole-state + /// [`durable_events`](Self::durable_events) export. A stream the cell + /// does not own is rejected. + pub async fn stream_events( + &self, + identity: &StreamIdentity, + ) -> Result, RepositoryError> { + Ok(GetStream::get_stream(self.routes.repo().repo(), identity) + .await? + .map(|entity| entity.events().to_vec()) + .unwrap_or_default()) + } + + /// Durable event history of this cell's own aggregate stream + /// (`{aggregate_type}:{shard}`), oldest first. See + /// [`stream_events`](Self::stream_events). + pub async fn history(&self) -> Result, RepositoryError> { + self.stream_events(&self.shard).await + } + + /// Event log export of the in-process reference host (restart tests). + /// SQLite cells persist rows directly and return an error here; read + /// history with [`history`](Self::history) / + /// [`stream_events`](Self::stream_events) instead. #[cfg(not(all(feature = "workers-rs", target_arch = "wasm32")))] pub fn durable_events(&self) -> Result, RepositoryError> { self.routes.repo().repo().durable_events() diff --git a/src/microsvc/cell_host/tests.rs b/src/microsvc/cell_host/tests.rs index 99d893c9e..fe773cca8 100644 --- a/src/microsvc/cell_host/tests.rs +++ b/src/microsvc/cell_host/tests.rs @@ -223,6 +223,11 @@ async fn command_replay_retains_confirmation_evidence_without_outbox_history() { "replay must not republish" ); assert_eq!(reopened.durable_events().unwrap()[0].events.len(), 1); + // History reads the same log through the store. + let history = reopened.history().await.unwrap(); + assert_eq!(history, cell.durable_events().unwrap()[0].events); + let foreign = StreamIdentity::new("CellItem", "someone-else").unwrap(); + assert!(reopened.stream_events(&foreign).await.is_err()); } fn fn_send_sync(_: &T) {} diff --git a/src/microsvc/cell_host/tests/native_sqlite.rs b/src/microsvc/cell_host/tests/native_sqlite.rs index 8affe2094..830ef485f 100644 --- a/src/microsvc/cell_host/tests/native_sqlite.rs +++ b/src/microsvc/cell_host/tests/native_sqlite.rs @@ -207,6 +207,46 @@ async fn sqlite_cell_reopens_identically_and_replays_recorded_outcomes() { assert_eq!(dump(&location, "item-1").await, before, "replay re-applied"); } +#[tokio::test] +async fn sqlite_cell_history_reads_every_event_after_reopen() { + let root = TempRoot::new(); + let location = root.location(); + let cell = sqlite_cell(&location, "item-h"); + assert!(cell.history().await.unwrap().is_empty()); + assert!( + cell.durable_events().is_err(), + "whole-state export stays a reference-host API" + ); + cell.dispatch_idempotent( + "cell_item.create", + &identity("0190a000-0000-7000-8000-000000000601"), + json!({ "id": "item-h", "title": "ship" }), + owner_session(), + ) + .await + .unwrap(); + cell.dispatch_idempotent( + "cell_item.complete", + &identity("0190a000-0000-7000-8000-000000000602"), + json!({ "id": "item-h" }), + owner_session(), + ) + .await + .unwrap(); + let history = cell.history().await.unwrap(); + let names: Vec<_> = history.iter().map(|e| e.event_name.as_str()).collect(); + assert_eq!(names.len(), 2, "{names:?}"); + drop(cell); + + // A fresh handle (process restart) reads the same history, snapshots + // notwithstanding (snapshot every event here). + let reopened = sqlite_cell(&location, "item-h"); + assert_eq!(reopened.history().await.unwrap(), history); + let own = StreamIdentity::new("CellItem", "item-h").unwrap(); + assert_eq!(reopened.stream_events(&own).await.unwrap(), history); + assert_eq!(dump(&location, "item-h").await.events, history); +} + #[tokio::test] async fn sealed_row_reducer_failure_rolls_back_the_whole_command() { let root = TempRoot::new(); From 9c232db243486cb80ae8290f81ece2673aab8b7b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:26:24 -0500 Subject: [PATCH 160/484] feat(leaderboard): gate BackgroundLeaderboard on its own feature New leaderboard-background feature (tokio only) enables BackgroundLeaderboard over any LeaderboardStore, e.g. InMemoryLeaderboard, without pulling in redis. redis implies it, so existing users are unaffected. Verified: cargo tree with leaderboard-background has no redis; the background tests pass with only that feature and with redis. Refs [[specs/framework/game-runtime/v1/index]] --- Cargo.toml | 5 ++++- README.md | 3 ++- src/leaderboard/mod.rs | 12 +++++++----- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4e3959a8d..0903c0abd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,10 @@ nats = ["dep:async-nats", "dep:futures", "dep:tokio"] rabbitmq = ["dep:lapin", "dep:futures", "dep:tokio"] kafka = ["dep:rdkafka", "dep:tokio"] # Redis sorted-set leaderboards and the Redis Streams `MessagePublisher`. -redis = ["dep:redis", "dep:tokio"] +redis = ["dep:redis", "dep:tokio", "leaderboard-background"] +# `leaderboard::BackgroundLeaderboard` (fire-and-forget updates on a Tokio +# task) without Redis, e.g. over `InMemoryLeaderboard`. +leaderboard-background = ["dep:tokio"] workers-rs = ["dep:worker"] # Native durable aggregate cells: one synchronous SQLite file per cell, same # SQL store and one-transaction-per-command contract as Durable Object cells. diff --git a/README.md b/README.md index 6f2091843..baa4450bd 100644 --- a/README.md +++ b/README.md @@ -704,7 +704,8 @@ network servers. | `nats` | No | `NatsBus` (NATS JetStream source/publisher). | | `rabbitmq` | No | `RabbitBus` (RabbitMQ source/publisher). | | `kafka` | No | `KafkaBus` (Kafka source/publisher). | -| `redis` | No | `leaderboard::RedisLeaderboard` (sorted-set leaderboards, `BackgroundLeaderboard`) and `bus::RedisStreamPublisher` (Redis Streams `XADD`, id dedupe). The `leaderboard` module and `InMemoryLeaderboard` are always available. | +| `redis` | No | `leaderboard::RedisLeaderboard` (sorted-set leaderboards) and `bus::RedisStreamPublisher` (Redis Streams `XADD`, id dedupe); implies `leaderboard-background`. The `leaderboard` module and `InMemoryLeaderboard` are always available. | +| `leaderboard-background` | No | `leaderboard::BackgroundLeaderboard` (fire-and-forget updates on a Tokio task) over any `LeaderboardStore`, e.g. `InMemoryLeaderboard`, without pulling in Redis. | > The `InMemoryBus`, `PostgresBus`, and `SqliteBus` need no separate broker > feature. SQL-backed bus support comes from the matching `postgres` or `sqlite` diff --git a/src/leaderboard/mod.rs b/src/leaderboard/mod.rs index 72a7b9888..a055f95e3 100644 --- a/src/leaderboard/mod.rs +++ b/src/leaderboard/mod.rs @@ -40,9 +40,11 @@ //! permanent. Because gameplay commands only commit to the event store and //! outbox, a Redis blip delays the board but never blocks a command. //! 2. **In-process (best effort).** Hand committed occurrences to a -//! `BackgroundLeaderboard`, which applies them on a background task and -//! drops (and counts) updates when its queue is full or Redis stays down. -//! Dropped updates are healed by the next rebuild. +//! `BackgroundLeaderboard` (feature `leaderboard-background`, implied by +//! `redis`; needs Tokio, works over any store, e.g. the in-memory one), +//! which applies them on a background task and drops (and counts) +//! updates when its queue is full or the store stays down. Dropped +//! updates are healed by the next rebuild. //! //! # Idempotency //! @@ -75,7 +77,7 @@ mod in_memory; mod projector; -#[cfg(feature = "redis")] +#[cfg(feature = "leaderboard-background")] mod background; #[cfg(feature = "redis")] mod redis; @@ -90,7 +92,7 @@ pub use projector::{ ProjectionReport, }; -#[cfg(feature = "redis")] +#[cfg(feature = "leaderboard-background")] pub use background::{BackgroundLeaderboard, BackgroundLeaderboardOptions, BackgroundStats}; #[cfg(feature = "redis")] pub use redis::{RedisLeaderboard, DEFAULT_REDIS_LEADERBOARD_PREFIX}; From 32d2838d2d47fd597b8b732ac1e4a191bfc2d4de Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:27:31 -0500 Subject: [PATCH 161/484] feat(game): configurable public URLs for zone redirects Deployments behind a proxy can redirect clients to proxied URLs: ServerConfig::with_redirect_url(|owner, zone| url) maps every Redirect, and HostAddr::with_ws_url advertises a per-host public WebSocket URL in the directory while peer calls keep using admin_url. Default behaviour (raw ws://addr) is unchanged. Test: a Redirect from host B for an A zone carries the mapped URL. Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 2 +- distributed_game/src/net/mod.rs | 37 ++++++++++++++++++++++++- distributed_game/src/world/directory.rs | 12 ++++++-- distributed_game/tests/world/main.rs | 29 +++++++++++++++++++ 4 files changed, 76 insertions(+), 4 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index e171f80ad..8825c624d 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -187,7 +187,7 @@ principals commit concurrently; settlements arrive in completion order. | Piece | Purpose | |---|---| -| `ZoneDirectory` (`StaticDirectory`, `HashRing`) | zone → owning `HostAddr`. `HashRing` uses virtual nodes; adding/removing one of N hosts moves ~1/N of the zones. A Hello for a zone owned elsewhere gets `Redirect(zone, url)`. | +| `ZoneDirectory` (`StaticDirectory`, `HashRing`) | zone → owning `HostAddr`. `HashRing` uses virtual nodes; adding/removing one of N hosts moves ~1/N of the zones. A Hello for a zone owned elsewhere gets `Redirect(zone, url)`; `url` is the owner's `HostAddr::ws_url` (advertise a proxied public URL with `HostAddr::with_ws_url`) or `ServerConfig::with_redirect_url(\|host, zone\| …)`. | | `ZoneOwnership` (`LocalOwnership`, `FencedLeaseOwnership`) | every activation acquires a fenced claim (`host#activation`) and renews it; a failed renewal disposes the zone **without** saving. Two hosts never run the same zone. | | `ZoneStateStore` (`MemoryZoneStateStore`, `SqliteZoneStateStore`) | hibernation snapshots, written under the claim's fencing token (stale writers get `StateError::Stale`, counted in `distributed_game_hibernation_saves_total{outcome="stale"}` and logged to stderr, never silently dropped). `LocalOwnership` seeds its tokens from the Unix time (µs) at creation, so a restarted host still outranks the snapshots its previous run saved. | | `ZoneTopology` (`DottedTopology` default: `eldoria.port.docks` → `eldoria.port` → `eldoria`) | parent links for tier-up events. | diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 8c30f7d85..57c3199e1 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -205,6 +205,11 @@ pub struct ServerConfig { pub admin_secret: Option, /// Peer (host-to-host) request timeout. pub peer_timeout: Duration, + /// Public URL clients are redirected to for a zone owned by another + /// host (`None` = the directory's [`HostAddr::zone_url`]). For + /// deployments behind a proxy whose URLs differ from the hosts' raw + /// addresses; see [`ServerConfig::with_redirect_url`]. + pub redirect_url: Option, /// Fact commits each zone's worker may run at once (default 1 = strict /// emission order). Above 1, facts of one principal stay sequential and /// different principals overlap (see [`crate::facts`]). Read by @@ -212,7 +217,32 @@ pub struct ServerConfig { pub max_concurrent_commits: usize, } +/// `(owning host, zone id) -> Redirect URL`. +pub type RedirectUrlFn = dyn Fn(&HostAddr, &str) -> String + Send + Sync; + +/// Maps (owning host, zone id) to the URL sent in `Redirect`. +#[derive(Clone)] +pub struct RedirectUrl(pub Arc); + +impl std::fmt::Debug for RedirectUrl { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("RedirectUrl(..)") + } +} + impl ServerConfig { + /// Build `Redirect` URLs with `url(owner, zone_id)`, e.g. + /// `|host, zone| format!("wss://game.example/{}/zones/{zone}", host.id)`. + /// Alternatively advertise per-host public URLs in the directory with + /// [`HostAddr::with_ws_url`]. + pub fn with_redirect_url( + mut self, + url: impl Fn(&HostAddr, &str) -> String + Send + Sync + 'static, + ) -> Self { + self.redirect_url = Some(RedirectUrl(Arc::new(url))); + self + } + /// Admit join tickets with `verifier` instead of `ticket_key`. pub fn with_ticket_verifier(mut self, verifier: impl TicketVerifier) -> Self { self.ticket_verifier = Some(SharedTicketVerifier::new(verifier)); @@ -241,6 +271,7 @@ impl ServerConfig { admin_secret: None, peer_timeout: Duration::from_secs(3), max_concurrent_commits: 1, + redirect_url: None, } } } @@ -1511,9 +1542,13 @@ where let first_route = route_zone(&inner, &zone_id); match &first_route { ZoneRoute::Remote(host) => { + let url = match &inner.config.redirect_url { + Some(map) => (map.0)(host, &zone_id), + None => host.zone_url(&zone_id), + }; let redirect = ServerMessage::Redirect { zone_id: zone_id.clone(), - url: host.zone_url(&zone_id), + url, } .encode(&()) .expect("redirect encodes"); diff --git a/distributed_game/src/world/directory.rs b/distributed_game/src/world/directory.rs index 9d31cf8c7..2b0c0f47a 100644 --- a/distributed_game/src/world/directory.rs +++ b/distributed_game/src/world/directory.rs @@ -17,8 +17,9 @@ use crate::rng::Fnv64; pub struct HostAddr { /// Stable host id (also the ownership holder prefix). pub id: String, - /// WebSocket base URL, e.g. `ws://10.0.0.2:2567` (clients connect to - /// `{ws_url}/zones/{zone_id}`). + /// WebSocket base URL clients are redirected to, e.g. + /// `ws://10.0.0.2:2567` or, behind a proxy, `wss://game.example/h/a` + /// (clients connect to `{ws_url}/zones/{zone_id}`). Peers never use it. pub ws_url: String, /// Admin HTTP base URL, e.g. `http://10.0.0.2:2567` (peer calls). pub admin_url: String, @@ -35,6 +36,13 @@ impl HostAddr { } } + /// Advertise `ws_url` (e.g. the proxied public URL) instead of the raw + /// `ws://{addr}`; admin/peer calls keep using `admin_url`. + pub fn with_ws_url(mut self, ws_url: impl Into) -> Self { + self.ws_url = ws_url.into().trim_end_matches('/').to_string(); + self + } + /// Client URL of `zone_id` on this host. pub fn zone_url(&self, zone_id: &str) -> String { format!("{}/zones/{zone_id}", self.ws_url) diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index 08a5812f3..00e54d398 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -332,6 +332,35 @@ async fn cross_host_handoff_follows_redirect_and_ticket_is_single_use() { .is_err()); } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn redirects_use_the_configured_public_url() { + let (_a, b, _dir) = two_hosts( + || { + base_config().with_redirect_url(|host, zone| { + format!("wss://game.example/hosts/{}/zones/{zone}", host.id) + }) + }, + &[("realm.east", "A")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ws = connect(&b.addr.zone_url("realm.east")).await; + hello(&mut ws, &ticket("ana", "realm.east", "pub-1"), "", "").await; + let mut mirror = ClientMirror::new(); + match next_control(&mut ws, &mut mirror).await { + Some(ServerMessage::Redirect { zone_id, url }) => { + assert_eq!(zone_id, "realm.east"); + assert_eq!(url, "wss://game.example/hosts/A/zones/realm.east"); + } + other => panic!("expected Redirect, got {other:?}"), + } + // Per-host advertised URL in the directory (no mapping configured). + let proxied = HostAddr::new("A", "10.0.0.2:2567").with_ws_url("wss://game.example/a/"); + assert_eq!(proxied.zone_url("z"), "wss://game.example/a/zones/z"); + assert_eq!(proxied.admin_url, "http://10.0.0.2:2567"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn refused_handoff_returns_to_source_with_carried_state() { let (a, b, _dir) = two_hosts( From 1c4015f937a1e40b3310117af37ab98289106008 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:30:13 -0500 Subject: [PATCH 162/484] feat(game): async barrier apply, gate reloads and abort notes - WorldCoordinator::rollout_async awaits an async apply while every zone stays frozen; rollout keeps the sync convenience. - A rolling commit reloads stale clients already inside a safe-room gate (they would otherwise only reload at the next gate). - AbortNotes / with_abort_notes configure the Resume notes of aborted rollouts ({error} expands to the apply error). - The Freeze demo stages its content pack in the async apply and drops the extra ContentStage barrier participant. Test: failed async apply resumes with custom notes; zones are frozen during apply; a rolling commit reloads the gate client only, which reconnects on the new version. Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 13 ++- distributed_game/src/net/mod.rs | 14 ++- distributed_game/src/net/world.rs | 73 ++++++++++++++-- distributed_game/tests/world/main.rs | 105 ++++++++++++++++++++++- examples/game/README.md | 12 +-- examples/game/server/src/freeze/world.rs | 58 +++---------- 6 files changed, 206 insertions(+), 69 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index 8825c624d..f32dddad7 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -242,14 +242,19 @@ apply)` over `GameServer`s and `RemoteHost`s (admin HTTP, shared secret): freeze all zones (`Freeze{version}`; `Zone::freeze_ready` may delay), wait for every ack within the timeout, `apply(version)`, then commit (`Resume{version, notes}`; facts/`ctx.stamp()` carry the new version). -A missing ack or failed `apply` aborts: everyone resumes on the old -version. Inputs while frozen are dropped and counted +`rollout_async(…, |version| async { … })` awaits an async `apply` while +every zone stays frozen (a visible "applying update" pause, no extra +barrier participant needed). A missing ack or failed `apply` aborts: +everyone resumes on the old version with `AbortNotes` +(`WorldCoordinator::with_abort_notes`; `{error}` expands to the apply +error). Inputs while frozen are dropped and counted (`ZoneHost::inputs_dropped_frozen`). `HostConfig::stale_policy = StalePolicy::SafeRoom { roam }` lets old clients keep playing after a `BarrierMode::Rolling` commit until they reach a gate zone (`Zone::is_gate`), where they get `Kick(RELOAD)` and reconnect with their -token after reloading; `BarrierMode::Hard` reloads every stale client at -once. +token after reloading — stale clients already inside a gate when the +rolling commit lands are reloaded there at once; `BarrierMode::Hard` +reloads every stale client at once. Admin routes (enabled by `ServerConfig::admin_secret`, header `x-game-admin-secret`): `POST /admin/transfer`, `/admin/child-event`, diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 57c3199e1..7cda10fed 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -66,7 +66,9 @@ pub use ticket::{ VerifiedTicket, }; pub use transfer::{TransferOp, TransferRegistry}; -pub use world::{BarrierParticipant, RemoteHost, RolloutError, RolloutReport, WorldCoordinator}; +pub use world::{ + AbortNotes, BarrierParticipant, RemoteHost, RolloutError, RolloutReport, WorldCoordinator, +}; use crate::clock::{Clock, SystemClock}; use crate::facts::{fact_channel, spawn_fact_worker, FactQueue, FactSink, RetryPolicy}; @@ -78,8 +80,8 @@ use crate::protocol::{error, kick, ClientMessage, Notice, ServerMessage, PROTOCO use crate::rng::ZoneRng; use crate::world::{ BarrierMode, ChildEvent, DottedTopology, FreezeState, HostAddr, LocalOwnership, OwnershipError, - StateError, StoredZoneState, ZoneClaim, ZoneDirectory, ZoneOwnership, ZoneStateStore, - ZoneTopology, + StalePolicy, StateError, StoredZoneState, ZoneClaim, ZoneDirectory, ZoneOwnership, + ZoneStateStore, ZoneTopology, }; use crate::zone::{ClientId, TicketClaims, Tier, Zone}; @@ -1359,7 +1361,11 @@ fn handle_cmd( notes, }); } - if mode == BarrierMode::Hard { + // Hard reloads every stale client; Rolling reloads the ones + // already inside a safe-room gate (they will not walk into one). + let gate = host.zone().is_gate() + && matches!(host.config().stale_policy, StalePolicy::SafeRoom { .. }); + if mode == BarrierMode::Hard || gate { host.reload_stale_players(); } freeze_acks.clear(); diff --git a/distributed_game/src/net/world.rs b/distributed_game/src/net/world.rs index b17be9b9a..a0795d507 100644 --- a/distributed_game/src/net/world.rs +++ b/distributed_game/src/net/world.rs @@ -22,11 +22,16 @@ //! delay with [`Zone::freeze_ready`]). Zones //! activated during the barrier start frozen. //! 2. if every host acknowledged within the timeout, the `apply` callback -//! installs the new content; then **commit**: every zone switches to the -//! new version and resumes (`Resume{version, notes}`). +//! installs the new content (sync, or awaited with +//! [`WorldCoordinator::rollout_async`] — zones stay frozen meanwhile); +//! then **commit**: every zone switches to the new version and resumes +//! (`Resume{version, notes}`). A **rolling** commit also reloads stale +//! clients already inside a safe-room gate ([`Zone::is_gate`] under +//! `StalePolicy::SafeRoom`): they reached a safe point, so they reload +//! there instead of waiting to walk into another gate. //! //! Any missing ack (or a failed `apply`) **aborts**: every zone resumes on -//! the old version. No zone ever simulates the new version while another +//! the old version with [`AbortNotes`] ([`WorldCoordinator::with_abort_notes`]). No zone ever simulates the new version while another //! still simulates the old one outside the barrier: nothing resumes before //! every zone is frozen. @@ -409,11 +414,31 @@ pub enum RolloutError { ApplyFailed(String), } +/// Notes sent with `Resume` when a rollout aborts +/// ([`WorldCoordinator::with_abort_notes`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AbortNotes { + /// A zone or host did not acknowledge the freeze in time. + pub not_acked: String, + /// The `apply` callback failed; `{error}` is replaced by its message. + pub apply_failed: String, +} + +impl Default for AbortNotes { + fn default() -> Self { + Self { + not_acked: "rollout aborted: freeze not acknowledged".into(), + apply_failed: "rollout aborted: apply failed".into(), + } + } +} + /// Runs content-version barriers across every participant of one world. pub struct WorldCoordinator { participants: Vec>, ack_timeout: Duration, next: AtomicU64, + abort_notes: AbortNotes, } impl WorldCoordinator { @@ -423,9 +448,18 @@ impl WorldCoordinator { participants: Vec::new(), ack_timeout, next: AtomicU64::new(1), + abort_notes: AbortNotes::default(), } } + /// Notes clients see in `Resume(content_update_aborted)` when a rollout + /// aborts (defaults: "rollout aborted: freeze not acknowledged" / + /// "rollout aborted: apply failed"). + pub fn with_abort_notes(mut self, notes: AbortNotes) -> Self { + self.abort_notes = notes; + self + } + /// Add a participant. pub fn participant(mut self, participant: Arc) -> Self { self.participants.push(participant); @@ -434,7 +468,8 @@ impl WorldCoordinator { /// Freeze everything, `apply(version)`, resume everything on `version`; /// abort (resume on the old version) if any zone fails to acknowledge - /// or `apply` fails. + /// or `apply` fails. Synchronous `apply`; see + /// [`rollout_async`](Self::rollout_async) for one that awaits. pub async fn rollout( &self, version: &str, @@ -442,6 +477,27 @@ impl WorldCoordinator { mode: BarrierMode, apply: impl FnOnce(&str) -> Result<(), String>, ) -> Result { + self.rollout_async(version, notes, mode, |v: String| { + let result = apply(&v); + std::future::ready(result) + }) + .await + } + + /// [`rollout`](Self::rollout) with an async `apply(version)`, awaited + /// while every zone is frozen (e.g. staging a content pack, so clients + /// see an "applying update" pause). Nothing resumes before it returns. + pub async fn rollout_async( + &self, + version: &str, + notes: &str, + mode: BarrierMode, + apply: F, + ) -> Result + where + F: FnOnce(String) -> Fut, + Fut: std::future::Future>, + { let barrier = (unix_now() << 20) ^ self.next.fetch_add(1, Ordering::Relaxed); let notice = Notice { reason: "content_update".into(), @@ -465,13 +521,12 @@ impl WorldCoordinator { } if !missing.is_empty() { missing.sort(); - self.abort_all(barrier, "rollout aborted: freeze not acknowledged") - .await; + self.abort_all(barrier, &self.abort_notes.not_acked).await; return Err(RolloutError::NotAcked(missing)); } - if let Err(e) = apply(version) { - self.abort_all(barrier, "rollout aborted: apply failed") - .await; + if let Err(e) = apply(version.to_string()).await { + let notes = self.abort_notes.apply_failed.replace("{error}", &e); + self.abort_all(barrier, ¬es).await; return Err(RolloutError::ApplyFailed(e)); } let mut commit_errors = Vec::new(); diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index 00e54d398..f5c99a074 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -9,7 +9,7 @@ use std::time::Duration; use distributed::lease::InMemoryLeaseStore; use distributed_game::net::{ - GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, WorldCoordinator, + AbortNotes, GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, WorldCoordinator, }; use distributed_game::protocol::{error, kick, Hello, Notice}; use distributed_game::world::{ @@ -724,6 +724,109 @@ fn versioned(version: &'static str) -> impl Fn() -> ServerConfig { } } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn rolling_commit_reloads_stale_clients_in_gates_and_apply_may_await() { + let safe_room = || { + let mut c = base_config(); + c.host.content_version = "v1".into(); + c.host.stale_policy = StalePolicy::SafeRoom { roam: false }; + c + }; + let (a, _b, _dir) = two_hosts( + safe_room, + &[("realm.inn", "A"), ("realm.field", "A")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut inn = join_url( + &a.addr.zone_url("realm.inn"), + &ticket("ina", "realm.inn", "g1"), + "v1", + ) + .await + .unwrap(); + let mut field = join_url( + &a.addr.zone_url("realm.field"), + &ticket("fey", "realm.field", "g2"), + "v1", + ) + .await + .unwrap(); + let server = a.server.clone(); + let coordinator = WorldCoordinator::new(Duration::from_secs(2)) + .participant(Arc::new(a.server.clone())) + .with_abort_notes(AbortNotes { + not_acked: "the ritual held the world".into(), + apply_failed: "CDN said: {error}".into(), + }); + + // Async apply that fails: everyone resumes on v1 with the custom note. + let failed = coordinator + .rollout_async("v2", "", BarrierMode::Rolling, |_v| async { + tokio::time::sleep(Duration::from_millis(20)).await; + Err("pack missing".to_string()) + }) + .await; + assert_eq!( + failed, + Err(RolloutError::ApplyFailed("pack missing".into())) + ); + for c in [&mut inn, &mut field] { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(_)) + )); + let resumed = next_notice(c).await; + assert!( + matches!(&resumed, Some(ServerMessage::Resume(n)) + if n.version == "v1" && n.notes == "CDN said: pack missing"), + "{resumed:?}" + ); + } + + // Async apply observed while every zone is frozen, then a rolling commit. + let report = coordinator + .rollout_async("v2", "ice", BarrierMode::Rolling, |v| async move { + tokio::time::sleep(Duration::from_millis(100)).await; + let frozen = server.inspect("realm.inn", |h| h.is_frozen()).await; + assert_eq!(frozen, Some(true), "zones stay frozen while applying {v}"); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(report.version, "v2"); + for c in [&mut inn, &mut field] { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(_)) + )); + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Resume(n)) if n.version == "v2" + )); + } + // The stale client already inside the gate reloads there ... + match next_notice(&mut inn).await { + Some(ServerMessage::Kick { code, .. }) => assert_eq!(code, kick::RELOAD), + other => panic!("expected Kick(RELOAD), got {other:?}"), + } + // ... the one in the field keeps playing its old version. + let field_connected = a + .server + .inspect("realm.field", |h| h.players().all(|p| p.connected)) + .await; + assert_eq!(field_connected, Some(true)); + // The reloaded client reconnects with its token on v2. + let mut back = connect(&a.addr.zone_url("realm.inn")).await; + hello(&mut back, "", &inn.welcome.reconnect_token, "v2").await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next_control(&mut back, &mut mirror).await, + Some(ServerMessage::Welcome(w)) if w.content_version == "v2" + )); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn world_barrier_freezes_applies_and_resumes_across_hosts() { let (a, b, _dir) = two_hosts( diff --git a/examples/game/README.md b/examples/game/README.md index 5b810c612..9fb917c7d 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -65,17 +65,19 @@ the scene from *its own* pack. - **Roll out update (Hard)**: every zone on both hosts freezes (SYSTEM overlay, inputs dropped and counted — client side, plus any in flight on - the server), the "content CDN" stages the pack (`DG_FREEZE_STAGE_MS`, - default 2.5 s), every zone resumes on the next version with the notes, + the server), the "content CDN" stages the pack — an async `apply` + awaited by `WorldCoordinator::rollout_async` while everything stays + frozen (`DG_FREEZE_STAGE_MS`, default 2.5 s) — every zone resumes on the next version with the notes, and every client reloads (`Kick(RELOAD)` → `reloadContent` → reconnect with the token). - **Roll out (Safe room)**: rolling commit. Normal clients patch live (`client.setContentVersion`); an old client (**O** / `&old=1`) keeps its old pack in the field — the server already runs the new rules — until it walks through a portal into the Town Hub, where it gets `RELOAD`. - (An old client that is *already* in the hub when the update lands is - refused by the field it walks into next — `VERSION_MISMATCH` — returns to - the hub with its transfer ticket and is reloaded there.) + Every client already *in* the hub when the update lands is at a safe + point and reloads right there (a rolling commit reloads stale clients + inside gate zones); a live-patching client reports its new version on + that reconnect. - **Ritual in Ember Fields**: that zone's `freeze_ready()` is false; the next rollout times out (`NotAcked: beta/freeze-ember`) and every zone resumes on the old version with "update aborted". diff --git a/examples/game/server/src/freeze/world.rs b/examples/game/server/src/freeze/world.rs index 6fd25fe88..dcdc1398b 100644 --- a/examples/game/server/src/freeze/world.rs +++ b/examples/game/server/src/freeze/world.rs @@ -29,13 +29,10 @@ use axum::extract::{Path, State}; use axum::http::{HeaderMap, StatusCode}; use axum::routing::{get, post}; use axum::{Json, Router}; -use distributed_game::facts::BoxFuture; use distributed_game::net::peer::{post_json, ADMIN_SECRET_HEADER}; use distributed_game::net::{ - BarrierParticipant, GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, - WorldCoordinator, + GameServer, RemoteHost, RolloutError, ServerConfig, TicketKey, WorldCoordinator, }; -use distributed_game::protocol::Notice; use distributed_game::world::{HostAddr, StaticDirectory}; use distributed_game::{BarrierMode, FreezeState, MemoryFactSink, RetryPolicy}; use serde::Deserialize; @@ -423,9 +420,8 @@ async fn rollout( let next = content::version_name(content::version_number(¤t).unwrap_or(1) + 1); let pack = content::pack(&next).expect("valid version"); let notes = pack.resume_notes(); - let mut coordinator = WorldCoordinator::new(state.ack_timeout) - .participant(Arc::new(state.server.clone())) - .participant(Arc::new(ContentStage { delay: state.stage })); + let mut coordinator = + WorldCoordinator::new(state.ack_timeout).participant(Arc::new(state.server.clone())); for peer in &state.peers { coordinator = coordinator.participant(Arc::new(RemoteHost::new( peer.clone(), @@ -433,7 +429,15 @@ async fn rollout( ))); } let started = Instant::now(); - let result = coordinator.rollout(&next, ¬es, mode, |_| Ok(())).await; + // The "content CDN" stages the pack while every zone is frozen: an + // async apply, so clients see the SYSTEM "applying update" pause. + let stage = state.stage; + let result = coordinator + .rollout_async(&next, ¬es, mode, |_version| async move { + tokio::time::sleep(stage).await; + Ok(()) + }) + .await; let took_ms = started.elapsed().as_millis() as u64; let mode_name = body.mode; let outcome = match result { @@ -515,44 +519,6 @@ async fn stuck( } } -/// The content CDN as a barrier participant: staging the pack takes -/// `delay` while the world is frozen (nothing to undo on abort). -struct ContentStage { - delay: Duration, -} - -impl BarrierParticipant for ContentStage { - fn name(&self) -> String { - "content-cdn".into() - } - - fn prepare<'a>( - &'a self, - _barrier: u64, - _notice: &'a Notice, - _timeout: Duration, - ) -> BoxFuture<'a, Result<(), Vec>> { - Box::pin(async move { - tokio::time::sleep(self.delay).await; - Ok(()) - }) - } - - fn commit<'a>( - &'a self, - _barrier: u64, - _version: &'a str, - _notes: &'a str, - _mode: BarrierMode, - ) -> BoxFuture<'a, Result<(), String>> { - Box::pin(async { Ok(()) }) - } - - fn abort<'a>(&'a self, _barrier: u64, _notes: &'a str) -> BoxFuture<'a, Result<(), String>> { - Box::pin(async { Ok(()) }) - } -} - // ---------------------------------------------------------------- CLI fn parse_peer(spec: &str) -> std::io::Result { From 3a103f6059b63555f5345577cca90c1bab0588de Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:31:00 -0500 Subject: [PATCH 163/484] refactor(examples): share shutdown_signal and random_hex helpers common::shutdown_signal is public; the Freeze host wraps it with its stdin-orphan watch instead of duplicating the Ctrl-C / SIGTERM logic, and uses common::random_hex for its secrets instead of a private copy. Refs [[specs/framework/game-runtime/v1/index]] --- examples/game/server/src/common/mod.rs | 6 ++- examples/game/server/src/freeze/world.rs | 48 +++--------------------- 2 files changed, 10 insertions(+), 44 deletions(-) diff --git a/examples/game/server/src/common/mod.rs b/examples/game/server/src/common/mod.rs index 9b7180b57..8965d23f0 100644 --- a/examples/game/server/src/common/mod.rs +++ b/examples/game/server/src/common/mod.rs @@ -1,6 +1,7 @@ //! Shared plumbing for every demo: CLI options, the [`Demo`] trait, server //! startup ([`spawn`] / [`run`]), the dev-only routes ([`dev`]), guest display -//! names ([`Guests`]) and small zone helpers ([`send_json_event`]). +//! names ([`Guests`]), small zone helpers ([`send_json_event`]) and process +//! helpers ([`shutdown_signal`], [`random_hex`]). //! //! A new demo implements [`Demo`] in its own module and adds one subcommand //! line in `main.rs`; everything else (ticket endpoint, NetSim control, @@ -186,7 +187,8 @@ pub async fn run_with( running.task.await.map_err(std::io::Error::other)? } -async fn shutdown_signal() { +/// Resolves on Ctrl-C or SIGTERM (graceful shutdown for every demo binary). +pub async fn shutdown_signal() { let ctrl_c = async { let _ = tokio::signal::ctrl_c().await; }; diff --git a/examples/game/server/src/freeze/world.rs b/examples/game/server/src/freeze/world.rs index dcdc1398b..5885c89e7 100644 --- a/examples/game/server/src/freeze/world.rs +++ b/examples/game/server/src/freeze/world.rs @@ -40,7 +40,7 @@ use serde_json::{json, Value}; use super::content::{self, ZoneKind, EMBER, HUB, MEADOW}; use super::{freeze_config, FreezeConfig, FreezeDemo, FreezeZone, Rituals}; -use crate::common::{dev, server_config, DemoArgs, Guests}; +use crate::common::{self, dev, random_hex, server_config, DemoArgs, Guests}; /// Default time the "content CDN" takes to stage an update while the world /// is frozen (makes the pause visible). @@ -585,22 +585,9 @@ fn spawn_secondary( Ok((child, HostAddr::new("beta", addr))) } +/// [`common::shutdown_signal`], plus (secondary host) the primary going away: +/// the secondary exits when its stdin, held by the primary, closes. async fn shutdown_signal(watch_stdin: bool) { - let ctrl_c = async { - let _ = tokio::signal::ctrl_c().await; - }; - #[cfg(unix)] - let term = async { - match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { - Ok(mut s) => { - s.recv().await; - } - Err(_) => std::future::pending().await, - } - }; - #[cfg(not(unix))] - let term = std::future::pending::<()>(); - // The secondary exits when the primary (which holds its stdin) is gone. let (orphaned_tx, orphaned) = tokio::sync::oneshot::channel::<()>(); if watch_stdin { std::thread::spawn(move || { @@ -612,8 +599,7 @@ async fn shutdown_signal(watch_stdin: bool) { std::mem::forget(orphaned_tx); } tokio::select! { - _ = ctrl_c => {} - _ = term => {} + _ = common::shutdown_signal() => {} _ = orphaned => {} } } @@ -623,15 +609,8 @@ async fn shutdown_signal(watch_stdin: bool) { pub async fn run(args: FreezeArgs) -> std::io::Result<()> { let listener = tokio::net::TcpListener::bind((args.demo.host.as_str(), args.demo.port)).await?; let addr = listener.local_addr()?; - let secret = args - .demo - .secret - .clone() - .unwrap_or_else(|| random_secret(32)); - let admin = args - .admin_secret - .clone() - .unwrap_or_else(|| random_secret(24)); + let secret = args.demo.secret.clone().unwrap_or_else(|| random_hex(32)); + let admin = args.admin_secret.clone().unwrap_or_else(|| random_hex(24)); let me = HostAddr::new(args.host_id.clone(), addr.to_string()); let secondary = args.peer.is_some(); let (peers, child) = match &args.peer { @@ -687,18 +666,3 @@ pub async fn run(args: FreezeArgs) -> std::io::Result<()> { } result } - -/// `len` random hex characters (OS-seeded SipHash; dev quality). -fn random_secret(len: usize) -> String { - use std::hash::{BuildHasher, Hasher}; - let mut out = String::new(); - let mut n = 0u64; - while out.len() < len { - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(n); - n += 1; - out.push_str(&format!("{:016x}", h.finish())); - } - out.truncate(len); - out -} From 48716196130b5622799058a25db1de76049e9238 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:39:09 -0500 Subject: [PATCH 164/484] test(examples): match restart-safe Mob Pit fact keys Mob Pit kill keys are now kill:{zone}:{boot_epoch}:m{mob}:{generation} (Ctx::fact_key); the headless test checks that shape. Refs [[specs/framework/game-runtime/v1/index]] --- examples/game/client/tests/mobpit-headless.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/game/client/tests/mobpit-headless.test.mjs b/examples/game/client/tests/mobpit-headless.test.mjs index 59dec60f5..2ea553dfe 100644 --- a/examples/game/client/tests/mobpit-headless.test.mjs +++ b/examples/game/client/tests/mobpit-headless.test.mjs @@ -40,7 +40,7 @@ test('kills become durable facts without stalling the tick, and survive a restar await hunt(pit, () => saved.length >= 1); assert.ok(saved[0].ok && XP.has(saved[0].xp), JSON.stringify(saved[0])); assert.equal(saved[0].key, kills[0].key); - assert.match(saved[0].key, /^kill:[0-9a-f]+:pit-1:m\d+:\d+$/); + assert.match(saved[0].key, /^kill:pit-1:\d+:m\d+:\d+$/, "kill:{zone}:{boot_epoch}:m{mob}:{generation}"); // One swing can kill several mobs: wait until every own kill settled. await until(() => pit.unsaved.size === 0 && saved.length === kills.length, 5_000, 'settlements'); await until(() => pit.profile().source === 'settled' && pit.profile().kills === kills.length, 5_000, `profile after settlement ${JSON.stringify(pit.profile())}`); From 0e86e75ecd27e33396de24d5187d006b0f666ad9 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:39:24 -0500 Subject: [PATCH 165/484] feat(game): adaptive interpolation delay, prediction toggle, pacing JS SDK: - AdaptiveDelay (ported from the gallery): rtt/2 + 2 patch intervals + 2 x jitter, clamped to [2 patches, 800 ms] and slewed <= 25 ms per 100 ms. GameClient uses one per zone by default (tunable with adaptiveDelay, inspectable with client.adaptiveDelay(zone)); a fixed interpolationDelayMs or a function still works. - GameClient.setPredictionEnabled / predictionEnabled: render the controlled entity interpolated while inputs keep being reconciled. - InputPacer: one input per server tick from a render loop, catch-up capped. Rust: InputCredits caps consumed inputs per tick with a burst bank (the Arena scheme), exported from the crate root. Demos: the gallery uses the SDK delay; Arena's P key uses the SDK toggle; Arena, Mob Pit and The Freeze send through InputPacer (shared FixedRate removed); Arena and The Freeze consume via InputCredits. Tests: AdaptiveDelay target/slew/clamps, InputPacer at 120 Hz and after a stall, GameClient defaults and runtime toggle, InputCredits bursts. Refs [[specs/framework/game-runtime/v1/index]] --- distributed_game/README.md | 6 + distributed_game/src/input.rs | 69 +++++++ distributed_game/src/lib.rs | 2 +- distributed_game/tests/zone_runtime/main.rs | 55 ++++++ examples/game/README.md | 4 +- examples/game/client/src/arena/main.ts | 20 +-- examples/game/client/src/freeze/main.ts | 8 +- examples/game/client/src/gallery/client.ts | 69 ++----- examples/game/client/src/gallery/main.ts | 2 +- examples/game/client/src/mobpit/main.ts | 8 +- examples/game/client/src/shared/input.ts | 41 +---- .../client/tests/gallery-headless.test.mjs | 6 +- examples/game/server/src/arena/mod.rs | 19 +- examples/game/server/src/freeze/mod.rs | 14 +- js/README.md | 27 ++- js/src/game/client.ts | 53 +++++- js/src/game/index.ts | 12 +- js/src/game/pacing.ts | 169 ++++++++++++++++++ js/tests/game-pacing.test.mjs | 112 ++++++++++++ 19 files changed, 550 insertions(+), 146 deletions(-) create mode 100644 js/src/game/pacing.ts create mode 100644 js/tests/game-pacing.test.mjs diff --git a/distributed_game/README.md b/distributed_game/README.md index f32dddad7..e6953cc6c 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -138,6 +138,12 @@ principals commit concurrently; settlements arrive in completion order. enforces route zone, expiry and single use; `TicketClaims::name` becomes `PlayerInfo::name` / `ObserverInfo::name` and travels with handoffs. Transfer tickets always use `ticket_key`. +- **Input pacing**: `InputCredits::new(max)` gives each player one input + credit per tick (banking up to `max` for jitter bursts); + `credits.take(ctx, player)` consumes queued inputs while credits last, so + a client can never simulate faster than real time by flooding inputs. + Pair it with the JS SDK's `InputPacer` (one input per server tick from a + render loop). - **Observers**: `Ctx::observer(id)` / `observers()` / `observers_of(principal)` expose each observer's verified principal and name (also during `on_unobserve`); `ctx.send_event(observer_id, …)` addresses one observer. diff --git a/distributed_game/src/input.rs b/distributed_game/src/input.rs index f9454dab7..b07b82f86 100644 --- a/distributed_game/src/input.rs +++ b/distributed_game/src/input.rs @@ -153,6 +153,75 @@ impl InputBuffer { } } +/// Server-side input pacing: a player earns one input credit per tick (up +/// to `max`, the burst it may bank) and spends one per consumed input, so a +/// client can never simulate faster than real time by sending more inputs, +/// while jitter bursts (several inputs in one tick after a gap) are still +/// absorbed. Pair with a client sending one input per tick (the JS SDK's +/// `InputPacer`). New players start with a full bank. +/// +/// ```ignore +/// fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { +/// for player in self.players.keys().copied().collect::>() { +/// for input in self.credits.take(ctx, player) { /* step one command frame */ } +/// } +/// } +/// fn on_leave(&mut self, _: &mut Ctx<'_, Self>, player: PlayerId, _: LeaveReason) { +/// self.credits.remove(player); +/// } +/// ``` +#[derive(Debug, Clone)] +pub struct InputCredits { + max: u32, + bank: std::collections::BTreeMap, +} + +impl InputCredits { + /// Bank at most `max` (>= 1) credits per player. + pub fn new(max: u32) -> Self { + Self { + max: max.max(1), + bank: std::collections::BTreeMap::new(), + } + } + + /// Credit ceiling. + pub fn max(&self) -> u32 { + self.max + } + + /// Credits `player` has banked (a new player has `max`). + pub fn credits(&self, player: crate::PlayerId) -> u32 { + self.bank.get(&player).copied().unwrap_or(self.max) + } + + /// Earn this tick's credit, then consume queued inputs oldest first + /// while credits last. Call once per player per tick. + pub fn take( + &mut self, + ctx: &mut crate::Ctx<'_, Z>, + player: crate::PlayerId, + ) -> Vec> { + let max = self.max; + let credits = self.bank.entry(player).or_insert(max); + *credits = (*credits + 1).min(max); + let mut out = Vec::new(); + while *credits > 0 { + let Some(input) = ctx.take_inputs(player, ConsumePolicy::Next).pop() else { + break; + }; + out.push(input); + *credits -= 1; + } + out + } + + /// Forget a player (on leave). + pub fn remove(&mut self, player: crate::PlayerId) { + self.bank.remove(&player); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index b62b3e5f1..bbb1c1f11 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -62,7 +62,7 @@ pub use facts::{ }; pub use handoff::{HandoffError, HandoffRequest, Transfer}; pub use host::{AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, ZoneHost}; -pub use input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; +pub use input::{ConsumePolicy, InputBuffer, InputCredits, PushOutcome, SequencedInput}; pub use interest::{InterestConfig, View}; pub use protocol::{ClientMessage, ClientMirror, Role, ServerMessage, PROTOCOL_VERSION}; pub use replay::{replay, Recorder, Recording}; diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index 4342d8b62..97038be77 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -670,3 +670,58 @@ async fn concurrent_commits_do_not_block_other_principals_and_keep_lane_order() assert!(pos("fast-c1") < pos("slow-a1"), "{order:?}"); assert!(pos("slow-a1") < pos("fast-a2"), "{order:?}"); } + +/// Consumes inputs through `InputCredits` (bank of 3). +struct Paced { + credits: distributed_game::InputCredits, + consumed: Vec, +} + +impl distributed_game::Zone for Paced { + type Config = (); + type Input = u8; + type Timer = (); + + fn schema() -> distributed_game::EntitySchema { + distributed_game::EntitySchema::new() + } + + fn on_create(_ctx: &mut distributed_game::Ctx<'_, Self>, _config: ()) -> Self { + Self { + credits: distributed_game::InputCredits::new(3), + consumed: Vec::new(), + } + } + + fn decode_input(&self, _player: distributed_game::PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, ctx: &mut distributed_game::Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + let mut n = 0; + for player in players { + n += self.credits.take(ctx, player).len(); + } + self.consumed.push(n); + } + + fn replicate(&self, _out: &mut distributed_game::WorldView) {} +} + +#[test] +fn input_credits_cap_inputs_per_tick_and_absorb_bursts() { + let clock = ManualClock::new(); + let mut h: ZoneHost = + ZoneHost::new("z1", HostConfig::default(), Arc::new(clock.clone()), ()); + let joined = h.join(&claims("ana", "z1"), 0, "").unwrap(); + for seq in 1..=10 { + h.push_input(joined.client, seq, 0, &[1]); + } + for _ in 0..5 { + clock.advance(Duration::from_secs_f64(1.0 / 30.0) + MS(1)); + h.advance(); + } + // Full bank of 3 spent on the burst, then one input per tick. + assert_eq!(h.zone().consumed[..5], [3, 1, 1, 1, 1]); +} diff --git a/examples/game/README.md b/examples/game/README.md index 9fb917c7d..5750c4ff9 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -105,8 +105,8 @@ over portals. ``` Prediction is exact because (1) every input is one command frame of exactly -one tick, consumed one per tick with a small credit bank -(`arena::MAX_CREDITS`), (2) the step uses binary32 arithmetic only +one tick (sent by the SDK's `InputPacer`), consumed one per tick with a small +credit bank (`distributed_game::InputCredits`, `arena::MAX_CREDITS`), (2) the step uses binary32 arithmetic only (`Math.fround` in TS) without trig, and (3) the server snaps its state to the wire quantization after each step, so the client rebases on exactly what the server holds. `fixtures/arena-movement.json` (written by Rust) is replayed by diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 91387829f..78b50135c 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -13,11 +13,11 @@ import { Vector3 } from '@babylonjs/core/Maths/math.vector'; import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import type { Scene } from '@babylonjs/core/scene'; -import type { RenderedEntity } from '@hops-ops/distributed/game'; +import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; -import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { createArenaClient, DEFAULT_ZONE, KIND } from './client.ts'; import { BUTTON_DASH, DASH_COOLDOWN, HALF, PLAYER_RADIUS, type MoveInput } from './movement.ts'; @@ -41,7 +41,6 @@ const canvas = document.getElementById('stage') as HTMLCanvasElement; const stage = createStage(canvas, { half: HALF }); const { scene } = stage; -let predictionOn = true; let ghostOn = true; let corrections = 0; let lastCorrection = 0; @@ -56,7 +55,7 @@ const hud = new Hud({ client, devApi: api }); -hud.toggle('Client prediction', true, (on) => (predictionOn = on), 'p'); +hud.toggle('Client prediction', true, (on) => client.setPredictionEnabled(on), 'p'); hud.toggle('Server ghost', true, (on) => (ghostOn = on), 'g'); // ---- meshes ---- @@ -120,7 +119,7 @@ function num(entity: RenderedEntity | { fields: RenderedEntity['fields'] }, fiel // ---- input: one command frame per 30 Hz tick ---- const sampler = new InputSampler(); -const commandFrames = new FixedRate(30); +const commandFrames = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; function sendCommandFrame(): void { @@ -132,7 +131,7 @@ function sendCommandFrame(): void { // ---- frame ---- stage.onFrame((now, dtMs) => { - commandFrames.advance(now, sendCommandFrame); + commandFrames.update(now, sendCommandFrame); const hello = arena.hello(); const authority = client.authority; const rendered = client.render(); @@ -140,12 +139,9 @@ stage.onFrame((now, dtMs) => { let me: { x: number; y: number } | undefined; for (const entity of rendered) { const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; - let fields = entity.fields; - if (mine && !predictionOn && authority !== undefined) { - // Prediction off: show the own capsule like everyone else, interpolated in the past. - const renderTime = authority.connection.serverNow() - client.interpolationDelay(authority); - fields = authority.replica.sampleEntity(entity.id, renderTime)?.fields ?? fields; - } + // Prediction off (P): the SDK renders the own capsule like everyone + // else's, interpolated in the past. + const fields = entity.fields; const visual = visualFor(entity, mine); const x = num({ fields }, 'x'); const y = num({ fields }, 'y'); diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts index 6214e85dc..6b49ea62f 100644 --- a/examples/game/client/src/freeze/main.ts +++ b/examples/game/client/src/freeze/main.ts @@ -11,12 +11,12 @@ import type { StandardMaterial } from '@babylonjs/core/Materials/standardMateria import { Color3 } from '@babylonjs/core/Maths/math.color'; import type { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; -import type { RenderedEntity } from '@hops-ops/distributed/game'; +import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { BUTTON_DASH, HALF, PILLARS, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; -import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, KIND, ZONES, type Pack, type WorldStatus } from './client.ts'; import './freeze.css'; @@ -274,7 +274,7 @@ async function main(): Promise { // ---- input ---- const sampler = new InputSampler(); - const frames = new FixedRate(30); + const frames = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; const sendFrame = () => { const s = sampler.sample(); @@ -284,7 +284,7 @@ async function main(): Promise { }; stage.onFrame((now, dtMs) => { - frames.advance(now, sendFrame); + frames.update(now, sendFrame); const hello = freeze.hello(); const pack = freeze.pack(); const authority = client.authority; diff --git a/examples/game/client/src/gallery/client.ts b/examples/game/client/src/gallery/client.ts index e315618db..2b868c460 100644 --- a/examples/game/client/src/gallery/client.ts +++ b/examples/game/client/src/gallery/client.ts @@ -1,8 +1,8 @@ /** * Shooting Gallery networking without rendering (Node-testable). * - * - Targets are interpolated like any remote entity, but with an adaptive - * delay (`AdaptiveDelay`): the SDK's clock estimates the server's + * - Targets are interpolated like any remote entity with the SDK's default + * adaptive delay (`AdaptiveDelay`): the clock estimates the server's * *present*, so a fixed 100 ms delay would ask for states that have not * arrived yet once one-way latency exceeds it; the delay follows * `rtt / 2 + 2 patch intervals + 2 × jitter`, slewed slowly. @@ -14,7 +14,14 @@ * - The server answers every shot with a verdict event; `stats` compares * predicted and confirmed hits. */ -import { GameClient, type GameSocketFactory, type GameZoneView, type RenderedEntity } from '@hops-ops/distributed/game'; +import { + GameClient, + type AdaptiveDelay, + type AdaptiveDelayOptions, + type GameSocketFactory, + type GameZoneView, + type RenderedEntity +} from '@hops-ops/distributed/game'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; import { onJsonEvent } from '../shared/events.ts'; @@ -68,50 +75,6 @@ export type GalleryStats = { lastAgeMs: number; }; -/** Interpolation delay that follows the measured one-way latency. */ -export class AdaptiveDelay { - readonly minMs: number; - readonly maxMs: number; - /** Largest change per 100 ms of wall time (keeps the timeline smooth). */ - readonly slewMs: number; - #value: number; - #at: number | undefined; - - constructor(options: Readonly<{ minMs?: number; maxMs?: number; slewMs?: number }> = {}) { - this.minMs = options.minMs ?? 100; - this.maxMs = options.maxMs ?? 800; - this.slewMs = options.slewMs ?? 25; - this.#value = this.minMs; - } - - get value(): number { - return this.#value; - } - - /** Target delay for a zone right now. */ - target(zone: GameZoneView): number { - const clock = zone.connection.clock; - const patchMs = 1000 / (zone.connection.welcome?.patchRate || 20); - const wanted = clock.synced ? clock.rtt / 2 + 2 * patchMs + 2 * clock.jitter : 2 * patchMs; - return Math.min(this.maxMs, Math.max(this.minMs, wanted)); - } - - /** Current delay, moved toward `target(zone)` by at most `slewMs` / 100 ms. */ - sample(zone: GameZoneView, now: number): number { - const last = this.#at ?? now; - this.#at = now; - const budget = (this.slewMs * Math.max(0, now - last)) / 100; - const delta = this.target(zone) - this.#value; - this.#value += Math.max(-budget, Math.min(budget, delta)); - return this.#value; - } - - /** True when within `toleranceMs` of the target. */ - settled(zone: GameZoneView, toleranceMs = 5): boolean { - return Math.abs(this.target(zone) - this.#value) <= toleranceMs; - } -} - export function encodeShot(flags: number, shot: number, delayMs: number, dir: Vec3): Uint8Array { const bytes = new Uint8Array(11); const view = new DataView(bytes.buffer); @@ -143,7 +106,8 @@ export function targetPosition(entity: Pick): Vec3 { export type GalleryClient = Readonly<{ client: GameClient; - delay: AdaptiveDelay; + /** The SDK's adaptive interpolation delay of `zone` (default: the authority). */ + delay(zone?: GameZoneView): AdaptiveDelay; hello(): GalleryHello | undefined; ready: Promise; stats: GalleryStats; @@ -163,18 +127,21 @@ export type GalleryClientOptions = Readonly<{ api: DevApi; base?: string; socket?: GameSocketFactory; - delay?: AdaptiveDelay; + adaptiveDelay?: AdaptiveDelayOptions; }>; export function createGalleryClient(options: GalleryClientOptions): GalleryClient { - const delay = options.delay ?? new AdaptiveDelay(); const client = new GameClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 250, - interpolationDelayMs: (zone) => delay.sample(zone, zone.connection.now()) + adaptiveDelay: options.adaptiveDelay }); + const delay = (zone: GameZoneView | undefined = client.authority): AdaptiveDelay => { + if (zone === undefined) throw new Error('not joined'); + return client.adaptiveDelay(zone)!; + }; let hello: GalleryHello | undefined; let resolveReady: (h: GalleryHello) => void = () => undefined; const ready = new Promise((resolve) => (resolveReady = resolve)); diff --git a/examples/game/client/src/gallery/main.ts b/examples/game/client/src/gallery/main.ts index 6b851d9ab..7b9d95da7 100644 --- a/examples/game/client/src/gallery/main.ts +++ b/examples/game/client/src/gallery/main.ts @@ -250,7 +250,7 @@ stage.onFrame((now) => { hud.frame({ entities: rendered.length }); const st = gallery.stats; const pct = (n: number, d: number) => (d === 0 ? '—' : `${Math.round((100 * n) / d)}%`); - hud.row('Interp delay', authority === undefined ? '—' : `${gallery.delay.value.toFixed(0)} ms (target ${gallery.delay.target(authority).toFixed(0)})`); + hud.row('Interp delay', authority === undefined ? '—' : `${gallery.delay(authority).value.toFixed(0)} ms (target ${gallery.delay(authority).target(authority).toFixed(0)})`); hud.row('Compensation', compensation ? `ON (max ${hello?.maxRewindMs ?? '—'} ms)` : 'OFF'); hud.row('Shots', String(st.shots)); hud.row('Predicted hits', `${st.predictedHits} (${pct(st.predictedHits, st.shots)})`); diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index 4089a1503..b2b808631 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -12,12 +12,12 @@ import type { StandardMaterial } from '@babylonjs/core/Materials/standardMateria import { Color3 } from '@babylonjs/core/Maths/math.color'; import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; -import type { RenderedEntity } from '@hops-ops/distributed/game'; +import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { HALF, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; -import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; import { BUTTON_ATTACK, @@ -278,7 +278,7 @@ function drawGraph(): void { // ---- input ---- const sampler = new InputSampler(); -const commandFrames = new FixedRate(30); +const commandFrames = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); function sendCommandFrame(): void { const s = sampler.sample(); @@ -293,7 +293,7 @@ function sendCommandFrame(): void { // ---- frame ---- stage.onFrame((now, dtMs) => { - commandFrames.advance(now, sendCommandFrame); + commandFrames.update(now, sendCommandFrame); const hello = pit.hello(); const authority = client.authority; const rendered = client.render(); diff --git a/examples/game/client/src/shared/input.ts b/examples/game/client/src/shared/input.ts index 27f2c5f20..b4474df35 100644 --- a/examples/game/client/src/shared/input.ts +++ b/examples/game/client/src/shared/input.ts @@ -1,11 +1,11 @@ /** - * Keyboard + gamepad sampling and a fixed-rate input loop. + * Keyboard + gamepad sampling. * * `InputSampler.sample()` returns a stick in [-1, 1]² (+x right, +y forward, - * length ≤ 1) and named buttons. `FixedRate` turns render frames into - * command frames at the server tick rate: each command frame is one input - * the server simulates for exactly one tick, which is what makes client - * prediction line up with the authoritative simulation. + * length ≤ 1) and named buttons. The SDK's `InputPacer` turns render frames + * into command frames at the server tick rate: each command frame is one + * input the server simulates for exactly one tick (`InputCredits`), which is + * what makes client prediction line up with the authoritative simulation. */ export type Sample = Readonly<{ @@ -107,34 +107,3 @@ export function cameraRelative( export function toAxis(v: number): number { return Math.round(Math.max(-1, Math.min(1, v)) * 127); } - -/** - * Accumulates frame time and fires `step` once per `1000 / hz` ms. Backlog - * is capped (a hidden tab must not burst dozens of inputs on return). - */ -export class FixedRate { - readonly intervalMs: number; - readonly #maxSteps: number; - #acc = 0; - #last: number | undefined; - - constructor(hz: number, maxStepsPerFrame = 4) { - this.intervalMs = 1000 / hz; - this.#maxSteps = maxStepsPerFrame; - } - - /** Call every frame with a monotonic time; returns steps fired. */ - advance(now: number, step: () => void): number { - if (this.#last === undefined) this.#last = now; - this.#acc += now - this.#last; - this.#last = now; - let steps = 0; - while (this.#acc >= this.intervalMs && steps < this.#maxSteps) { - this.#acc -= this.intervalMs; - step(); - steps += 1; - } - if (steps === this.#maxSteps) this.#acc = Math.min(this.#acc, this.intervalMs); - return steps; - } -} diff --git a/examples/game/client/tests/gallery-headless.test.mjs b/examples/game/client/tests/gallery-headless.test.mjs index d7ff9bc36..db51b6c87 100644 --- a/examples/game/client/tests/gallery-headless.test.mjs +++ b/examples/game/client/tests/gallery-headless.test.mjs @@ -62,8 +62,8 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew await api.setNetSim({ latencyMs: 100, jitterMs: 0, loss: 0 }); const zone = gallery.client.authority; await until(() => zone.connection.clock.rtt > 180, 10_000, 'rtt with latency'); - await until(() => gallery.targets() && gallery.delay.settled(zone, 10), 15_000, 'adaptive delay'); - assert.ok(gallery.delay.value > 190, `delay ${gallery.delay.value}`); + await until(() => gallery.targets() && gallery.delay(zone).settled(zone, 10), 15_000, 'adaptive delay'); + assert.ok(gallery.delay().value > 190, `delay ${gallery.delay().value}`); const on = await volley(gallery, 20, true); assert.ok(on.hits >= 18, `compensated hits ${on.hits}/20`); @@ -78,7 +78,7 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew // 300 ms one way: the view is ~700 ms old, more than the 600 ms clamp. await api.setNetSim({ latencyMs: 300, jitterMs: 0, loss: 0 }); await until(() => zone.connection.clock.rtt > 550, 15_000, 'rtt 600'); - await until(() => gallery.targets() && gallery.delay.settled(zone, 10), 20_000, 'adaptive delay 2'); + await until(() => gallery.targets() && gallery.delay(zone).settled(zone, 10), 20_000, 'adaptive delay 2'); const far = await volley(gallery, 10, true); t.diagnostic( `comp on ${on.hits}/20 (mean rewind ${meanAge.toFixed(0)} ms) · off ${off.hits}/20 · 300 ms: clamped ${far.clamped}/10, hits ${far.hits}/10` diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index 311c17358..f35bb19e1 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -17,8 +17,9 @@ //! Event [`EVENT_HELLO`] (JSON) tells a joining player its entity and the //! view radius. Inputs are 3 bytes ([`MoveInput`]); each input is one //! command frame. A player earns one frame credit per tick (max -//! [`MAX_CREDITS`]), so a client cannot move faster than real time by -//! sending more inputs, but jitter bursts are absorbed. +//! [`MAX_CREDITS`], `distributed_game::InputCredits`), so a client cannot +//! move faster than real time by sending more inputs, but jitter bursts are +//! absorbed. pub mod movement; @@ -26,7 +27,7 @@ use std::collections::BTreeMap; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::{ - ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + Ctx, EntitySchema, EntityState, FieldType, FieldValue, InputCredits, KindDef, LeaveReason, PlayerId, View, WorldView, Zone, }; use serde_json::json; @@ -54,7 +55,6 @@ struct Player { entity: u32, name: String, state: MoveState, - credits: u8, } struct Drone { @@ -77,6 +77,7 @@ pub struct ArenaConfig { pub struct Arena { guests: Guests, players: BTreeMap, + credits: InputCredits, drones: Vec, } @@ -149,6 +150,7 @@ impl Zone for Arena { let mut arena = Self { guests: config.guests, players: BTreeMap::new(), + credits: InputCredits::new(u32::from(MAX_CREDITS)), drones: Vec::new(), }; for id in 1..=DRONES { @@ -184,7 +186,6 @@ impl Zone for Arena { y, ..MoveState::default() }, - credits: MAX_CREDITS, }, ); ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); @@ -198,6 +199,7 @@ impl Zone for Arena { fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { self.players.remove(&player); + self.credits.remove(player); } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { @@ -206,13 +208,8 @@ impl Zone for Arena { fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { for (id, player) in &mut self.players { - player.credits = (player.credits + 1).min(MAX_CREDITS); - while player.credits > 0 { - let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { - break; - }; + for input in self.credits.take(ctx, *id) { player.state = movement::step(player.state, input.input); - player.credits -= 1; } ctx.set_view(*id, View::new(player.state.x, player.state.y, VIEW_RADIUS)); } diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs index e7e2c001b..23a53e6fe 100644 --- a/examples/game/server/src/freeze/mod.rs +++ b/examples/game/server/src/freeze/mod.rs @@ -39,7 +39,7 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::{ - ConsumePolicy, Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, KindDef, + Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, InputCredits, KindDef, LeaveReason, PlayerId, StalePolicy, View, WorldView, Zone, }; use serde_json::{json, Value}; @@ -118,7 +118,6 @@ struct Player { entity: u32, name: String, state: MoveState, - credits: u8, /// Just arrived through a portal: ignore portals until it stepped off. on_portal: bool, } @@ -143,6 +142,7 @@ pub struct FreezeZone { zone_id: String, pack: Pack, players: BTreeMap, + credits: InputCredits, slimes: Vec, gems: Vec, collected: u64, @@ -191,7 +191,6 @@ impl FreezeZone { y: at.1, ..MoveState::default() }, - credits: crate::arena::MAX_CREDITS, on_portal: false, }, ); @@ -289,6 +288,7 @@ impl Zone for FreezeZone { config, pack, players: BTreeMap::new(), + credits: InputCredits::new(u32::from(crate::arena::MAX_CREDITS)), slimes, gems: (0..kind.gem_spots().len()) .map(|spot| Gem { @@ -332,6 +332,7 @@ impl Zone for FreezeZone { fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { self.players.remove(&player); + self.credits.remove(player); } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { @@ -344,13 +345,8 @@ impl Zone for FreezeZone { let ids: Vec = self.players.keys().copied().collect(); for id in ids { let player = self.players.get_mut(&id).expect("present"); - player.credits = (player.credits + 1).min(crate::arena::MAX_CREDITS); - while player.credits > 0 { - let Some(input) = ctx.take_inputs(id, ConsumePolicy::Next).pop() else { - break; - }; + for input in self.credits.take(ctx, id) { player.state = movement::step(player.state, input.input); - player.credits -= 1; } let (x, y) = (player.state.x, player.state.y); // Lava burns (ice is safe): back to a spawn point. diff --git a/js/README.md b/js/README.md index d5703b9d6..51a3957c9 100644 --- a/js/README.md +++ b/js/README.md @@ -581,7 +581,7 @@ function, so a fresh single-use ticket is fetched whenever a reconnect token can no longer be used — and a pure `predict` for its own entity. ```ts -import { GameClient } from '@hops-ops/distributed/game'; +import { GameClient, InputPacer } from '@hops-ops/distributed/game'; const game = new GameClient<{ dx: number; dy: number }>({ url: (zone) => `wss://game.example/zones/${zone}`, @@ -595,13 +595,27 @@ const game = new GameClient<{ dx: number; dy: number }>({ await game.connect('room-1'); game.on('event', (zone, e) => { /* e.g. announce the controlled entity */ }); game.setControlledEntity(myEntityId); -game.sendInput({ dx: 1, dy: 0 }); -requestAnimationFrame(function frame() { draw(game.render()); requestAnimationFrame(frame); }); +// One input per server tick, whatever the display refresh rate. +const pacer = new InputPacer({ tickRate: () => game.authority?.connection.welcome?.tickRate }); +requestAnimationFrame(function frame(now) { + pacer.update(now, (dtMs) => game.sendInput(readStick(), dtMs)); + draw(game.render()); + requestAnimationFrame(frame); +}); ``` `render()` merges the authoritative zone and observed neighbours (`observe`) -sampled at `serverNow − interpolationDelay` (two patch intervals by default), -with the controlled entity at its predicted state. Reconciliation rebases on +sampled at `serverNow − interpolationDelay`, with the controlled entity at +its predicted state. The delay is **adaptive** per zone by default +(`AdaptiveDelay`: `rtt / 2 + 2 patch intervals + 2 × jitter`, clamped to +`[2 patches, 800 ms]`, slewed ≤ 25 ms per 100 ms; tune with +`adaptiveDelay: { minMs, maxMs, slewMs, patchIntervals, jitterFactor }`, +inspect with `client.adaptiveDelay(zone)`): the clock estimates the +server's *present*, so a fixed delay below the one-way latency would ask +for states not yet received. A fixed `interpolationDelayMs: 100` (or a +function of the zone) is still accepted. `client.setPredictionEnabled(false)` +renders the controlled entity like any other (interpolated, one RTT behind +the keys) while inputs keep being recorded, so switching back is seamless. Reconciliation rebases on every Delta's `ack_seq`; per-field `ease`, `snap` or `replace` resolves the divergence. A server Handoff connects to the target zone with the transfer ticket (following `Redirect`s) and swaps authority while the previous world @@ -653,7 +667,8 @@ duplicated as decision documents in this package. - `@hops-ops/distributed/game` — binary `distributed_game` zone protocol client: codec, `GameConnection` (handshake, reconnect, clock sync), interpolating `EntityReplica`, `Predictor` reconciliation and the - multi-zone `GameClient` with handoff. See `distributed_game/PROTOCOL.md`. + multi-zone `GameClient` with handoff, `AdaptiveDelay` and `InputPacer`. + See `distributed_game/PROTOCOL.md`. All other subpaths are private and blocked by the package export map. diff --git a/js/src/game/client.ts b/js/src/game/client.ts index f663cb774..f5c62481c 100644 --- a/js/src/game/client.ts +++ b/js/src/game/client.ts @@ -26,6 +26,7 @@ import type { ResumeMessage, WelcomeMessage } from './messages.js'; +import { AdaptiveDelay, type AdaptiveDelayOptions } from './pacing.js'; import { Predictor, type Correction, type PredictorOptions } from './prediction.js'; import { EntityReplica, @@ -104,10 +105,17 @@ export type GameClientOptions = Readonly<{ reconnect?: false | GameReconnectOptions; pingIntervalMs?: number; /** - * Render delay behind the server clock. Default: two patch intervals of - * the zone (100 ms at 20 Hz). + * Render delay behind the server clock: a fixed number of ms, or a + * function of the zone. Default: adaptive per zone (`AdaptiveDelay`, + * `rtt / 2 + 2 patch intervals + 2 × jitter`, slewed slowly, tuned with + * `adaptiveDelay`), because the clock estimates the server's present and + * a fixed delay below the one-way latency renders states not yet received. */ interpolationDelayMs?: number | ((zone: GameZoneView) => number); + /** Tuning of the default adaptive interpolation delay. */ + adaptiveDelay?: AdaptiveDelayOptions; + /** Render the controlled entity predicted (default true); see `setPredictionEnabled`. */ + predictionEnabled?: boolean; interpolation?: InterpolationPolicy; staleGraceMs?: number; historyMs?: number; @@ -163,6 +171,9 @@ export class GameClient { #controlledOverride: number | undefined; #closed = false; #contentVersion: string; + #predictionEnabled: boolean; + /** Adaptive delay per zone, keyed by the replica (shared across a zone's connections). */ + readonly #delays = new WeakMap(); constructor(options: GameClientOptions) { this.#options = options; @@ -171,6 +182,22 @@ export class GameClient { this.#emitter = new Emitter(options.onListenerError); this.#predictor = options.prediction === undefined ? undefined : new Predictor(options.prediction); + this.#predictionEnabled = options.predictionEnabled ?? true; + } + + /** Whether `render` shows the controlled entity at its predicted state. */ + get predictionEnabled(): boolean { + return this.#predictionEnabled; + } + + /** + * Toggle prediction at runtime. Off, the controlled entity is rendered + * like every other entity (interpolated, one RTT + delay behind the + * keys). Inputs keep being recorded and reconciled either way, so + * switching back on is seamless. + */ + setPredictionEnabled(enabled: boolean): void { + this.#predictionEnabled = enabled; } on( @@ -293,8 +320,22 @@ export class GameClient { const configured = this.#options.interpolationDelayMs; if (typeof configured === 'number') return configured; if (typeof configured === 'function') return configured(zone); - const patchRate = zone.connection.welcome?.patchRate || 20; - return 2 * (1000 / patchRate); + return this.adaptiveDelay(zone)!.sample(zone, this.#scheduler.now()); + } + + /** + * The adaptive delay controller of a zone (undefined when a fixed + * `interpolationDelayMs` is configured): `value`, `target(zone)`, + * `settled(zone)` for HUDs and tests. + */ + adaptiveDelay(zone: GameZoneView): AdaptiveDelay | undefined { + if (this.#options.interpolationDelayMs !== undefined) return undefined; + let delay = this.#delays.get(zone.replica); + if (delay === undefined) { + delay = new AdaptiveDelay(this.#options.adaptiveDelay); + this.#delays.set(zone.replica, delay); + } + return delay; } /** @@ -307,7 +348,9 @@ export class GameClient { const now = this.#scheduler.now(); const predictor = this.#predictor; const controlled = - predictor?.active === true && this.#authority !== undefined ? predictor.entityId : undefined; + this.#predictionEnabled && predictor?.active === true && this.#authority !== undefined + ? predictor.entityId + : undefined; for (const zone of this.zones()) { const delay = this.interpolationDelay(zone); zone.replica.interpolationDelayMs = delay; diff --git a/js/src/game/index.ts b/js/src/game/index.ts index 3d56c4e23..4183adab6 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -5,7 +5,10 @@ * - `GameConnection`: one zone WebSocket — handshake, reconnect, clock sync. * - `EntityReplica`: schema-driven entity store with interpolation buffers. * - `Predictor`: client prediction + per-field reconciliation policies. - * - `GameClient`: authority + observer zones, merged render, handoff. + * - `GameClient`: authority + observer zones, merged render, handoff, + * adaptive interpolation delay, runtime prediction toggle. + * - `AdaptiveDelay` / `InputPacer`: network-following render delay and + * one-input-per-tick pacing for render loops. */ export { MAX_BLOB_LEN, @@ -112,6 +115,13 @@ export { type PredictFn, type PredictorOptions } from './prediction.js'; +export { + AdaptiveDelay, + InputPacer, + type AdaptiveDelayOptions, + type DelaySource, + type InputPacerOptions +} from './pacing.js'; export { GameClient, type ControlledEntityResolver, diff --git a/js/src/game/pacing.ts b/js/src/game/pacing.ts new file mode 100644 index 000000000..44c79dede --- /dev/null +++ b/js/src/game/pacing.ts @@ -0,0 +1,169 @@ +/** + * Timing helpers for game clients. + * + * - `AdaptiveDelay`: interpolation delay that follows the measured network. + * The clock estimates the server's *present*, so a fixed delay smaller + * than the one-way latency asks for states that have not arrived yet; + * the adaptive delay targets `rtt / 2 + patchIntervals × patch interval + + * jitterFactor × jitter`, clamped to `[minMs, maxMs]` and slewed slowly + * so the rendered timeline never jumps. `GameClient` uses one per zone by + * default. + * - `InputPacer`: sends one input per server tick from a render loop + * (accumulator with a catch-up cap), so inputs match the server's command + * frames instead of the display refresh rate. + */ + +/** What `AdaptiveDelay` reads from a zone (a `GameZoneView` fits). */ +export type DelaySource = Readonly<{ + connection: Readonly<{ + clock: Readonly<{ rtt: number; jitter: number; synced: boolean }>; + welcome?: Readonly<{ patchRate: number }>; + }>; +}>; + +export type AdaptiveDelayOptions = Readonly<{ + /** Lower bound (ms). Default: `patchIntervals` patch intervals of the zone. */ + minMs?: number; + /** Upper bound (ms). Default 800. */ + maxMs?: number; + /** Largest change per 100 ms of wall time (ms). Default 25. */ + slewMs?: number; + /** Patch intervals of buffer. Default 2. */ + patchIntervals?: number; + /** Jitter multiplier. Default 2. */ + jitterFactor?: number; +}>; + +/** Interpolation delay that follows the measured one-way latency. */ +export class AdaptiveDelay { + readonly maxMs: number; + readonly slewMs: number; + readonly #minMs: number | undefined; + readonly #patchIntervals: number; + readonly #jitterFactor: number; + #value: number | undefined; + #at: number | undefined; + + constructor(options: AdaptiveDelayOptions = {}) { + this.#minMs = options.minMs; + this.maxMs = options.maxMs ?? 800; + this.slewMs = options.slewMs ?? 25; + this.#patchIntervals = options.patchIntervals ?? 2; + this.#jitterFactor = options.jitterFactor ?? 2; + } + + /** Current delay (ms); before the first `sample`, the lower bound at 20 Hz. */ + get value(): number { + return this.#value ?? this.#minMs ?? this.#patchIntervals * 50; + } + + /** Lower bound for a zone. */ + minMs(zone: DelaySource): number { + return this.#minMs ?? this.#patchIntervals * patchMs(zone); + } + + /** Delay the zone's network calls for right now (before slewing). */ + target(zone: DelaySource): number { + const clock = zone.connection.clock; + const patch = patchMs(zone); + const wanted = clock.synced + ? clock.rtt / 2 + this.#patchIntervals * patch + this.#jitterFactor * clock.jitter + : this.#patchIntervals * patch; + const min = this.minMs(zone); + return Math.min(Math.max(min, this.maxMs), Math.max(min, wanted)); + } + + /** + * Delay to render with at local time `now`: starts at the target, then + * moves toward it by at most `slewMs` per 100 ms. Calling it several + * times with the same `now` returns the same value. + */ + sample(zone: DelaySource, now: number): number { + const target = this.target(zone); + if (this.#value === undefined || this.#at === undefined) { + this.#value = target; + this.#at = now; + return target; + } + const budget = (this.slewMs * Math.max(0, now - this.#at)) / 100; + this.#at = Math.max(this.#at, now); + const delta = target - this.#value; + this.#value += Math.max(-budget, Math.min(budget, delta)); + return this.#value; + } + + /** True when within `toleranceMs` of the target. */ + settled(zone: DelaySource, toleranceMs = 5): boolean { + return Math.abs(this.target(zone) - this.value) <= toleranceMs; + } + + /** Start over (next `sample` jumps to the target). */ + reset(): void { + this.#value = undefined; + this.#at = undefined; + } +} + +function patchMs(zone: DelaySource): number { + return 1000 / (zone.connection.welcome?.patchRate || 20); +} + +export type InputPacerOptions = Readonly<{ + /** Inputs per second. Default: `tickRate()` or 30. */ + rate?: number; + /** Current server tick rate (e.g. `() => client.authority?.connection.welcome?.tickRate`). */ + tickRate?: () => number | undefined; + /** Most inputs sent by one `update` (after a stall the backlog is dropped). Default 4. */ + maxPerUpdate?: number; +}>; + +/** + * Fires `send` once per input interval from a render loop: call + * `update(now, send)` every frame. One input per server tick is what an + * authoritative zone consumes (see the server's `InputCredits`); sending + * per display frame would overflow its input buffer at 120 Hz or starve + * it at 30 Hz. + */ +export class InputPacer { + readonly #rate: number | undefined; + readonly #tickRate: (() => number | undefined) | undefined; + readonly #maxPerUpdate: number; + #acc = 0; + #last: number | undefined; + + constructor(options: InputPacerOptions = {}) { + this.#rate = options.rate; + this.#tickRate = options.tickRate; + this.#maxPerUpdate = Math.max(1, options.maxPerUpdate ?? 4); + } + + /** Current input interval (ms). */ + get intervalMs(): number { + const rate = this.#rate ?? this.#tickRate?.() ?? 30; + return 1000 / (rate > 0 ? rate : 30); + } + + /** Call every frame with a monotonic time; returns the inputs sent. */ + update(now: number, send: (dtMs: number) => void): number { + if (this.#last === undefined) this.#last = now; + this.#acc += Math.max(0, now - this.#last); + this.#last = now; + const interval = this.intervalMs; + let sent = 0; + // Tolerate float drift from summing frame times. + while (this.#acc >= interval - 1e-6 && sent < this.#maxPerUpdate) { + this.#acc -= interval; + send(interval); + sent += 1; + } + if (sent === this.#maxPerUpdate) this.#acc = Math.min(this.#acc, interval); + this.#acc = Math.max(0, this.#acc); + return sent; + } + + /** Forget accumulated time (e.g. after a pause). */ + reset(): void { + this.#acc = 0; + this.#last = undefined; + } +} diff --git a/js/tests/game-pacing.test.mjs b/js/tests/game-pacing.test.mjs new file mode 100644 index 000000000..71d1c283d --- /dev/null +++ b/js/tests/game-pacing.test.mjs @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { AdaptiveDelay, GameClient, InputPacer } from '@hops-ops/distributed/game'; + +import { FakeNetwork, FakeScheduler, avatar, delta, welcome } from './fixtures/game-harness.mjs'; + +const zoneWith = (clock, patchRate = 20) => ({ connection: { clock, welcome: { patchRate } } }); + +test('AdaptiveDelay targets rtt/2 + 2 patches + 2 jitter, clamped and slewed', () => { + const delay = new AdaptiveDelay(); + const unsynced = zoneWith({ rtt: 0, jitter: 0, synced: false }); + assert.equal(delay.target(unsynced), 100, 'two 20 Hz patches before any Pong'); + assert.equal(delay.sample(unsynced, 0), 100, 'first sample jumps to the target'); + + const slow = zoneWith({ rtt: 400, jitter: 20, synced: true }); + assert.equal(delay.target(slow), 200 + 100 + 40); + assert.equal(delay.sample(slow, 100), 125, 'at most 25 ms per 100 ms'); + assert.equal(delay.sample(slow, 100), 125, 'same instant, same value'); + assert.equal(delay.settled(slow), false); + for (let t = 200; t <= 1_200; t += 100) delay.sample(slow, t); + assert.equal(delay.value, 340); + assert.equal(delay.settled(slow), true); + + // Clamped to maxMs and to the patch-based minimum. + assert.equal(delay.target(zoneWith({ rtt: 5_000, jitter: 0, synced: true })), 800); + assert.equal(delay.target(zoneWith({ rtt: 0, jitter: 0, synced: true }, 10)), 200); + const tuned = new AdaptiveDelay({ minMs: 50, maxMs: 300, patchIntervals: 1, jitterFactor: 0 }); + assert.equal(tuned.target(zoneWith({ rtt: 10, jitter: 99, synced: true })), 55); + assert.equal(tuned.target(zoneWith({ rtt: 1_000, jitter: 0, synced: true })), 300); +}); + +test('InputPacer sends one input per tick from any frame rate and caps catch-up', () => { + let tickRate = 30; + const pacer = new InputPacer({ tickRate: () => tickRate, maxPerUpdate: 3 }); + let sent = 0; + const send = (dt) => { + assert.ok(Math.abs(dt - 1000 / tickRate) < 1e-9); + sent += 1; + }; + // 120 Hz display for one second → 30 inputs. + for (let i = 0; i <= 120; i += 1) pacer.update((i * 1000) / 120, send); + assert.equal(sent, 30); + // A 2 s stall sends at most 3 and drops the rest of the backlog. + sent = 0; + assert.equal(pacer.update(3_000, send), 3); + assert.equal(pacer.update(3_001, send), 1, 'at most one interval carried over'); + // Rate follows the server tick rate. + tickRate = 60; + pacer.reset(); + sent = 0; + for (let i = 0; i <= 60; i += 1) pacer.update(10_000 + (i * 1000) / 60, send); + assert.equal(sent, 60); + assert.equal(new InputPacer({ rate: 10 }).intervalMs, 100); +}); + +test('GameClient: adaptive delay by default, fixed when configured, prediction toggles at runtime', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type === 'Hello') conn.send(welcome({ serverTime: 10_000 })); + }; + const client = new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: () => 't', + socket: network.factory, + scheduler, + pingIntervalMs: 60_000, + prediction: { + encodeInput: (dx) => new Uint8Array([dx & 0xff]), + predict: (s, dx, dt) => ({ x: s.x + (dx * dt) / 1000 }), + controlledEntity: () => 1 + } + }); + await client.connect('z1'); + const zone = client.authority; + const delay = client.adaptiveDelay(zone); + assert.ok(delay instanceof AdaptiveDelay); + assert.equal(client.interpolationDelay(zone), 100); + // A measured 300 ms RTT moves the delay up gradually. + zone.connection.clock.observe(0, 10_150, 300); + scheduler.time = 400; + const moved = client.interpolationDelay(zone); + assert.ok(moved > 100 && moved < delay.target(zone), `slewing: ${moved}`); + + network.last('z1').send(delta({ creates: [avatar(1, 0)] })); + await scheduler.advance(1); + client.sendInput(50, 1000); + const predicted = () => client.render().find((e) => e.id === 1); + assert.equal(predicted().predicted, true); + assert.ok(Math.abs(predicted().fields.x - 50) < 0.01, `${predicted().fields.x}`); + client.setPredictionEnabled(false); + assert.equal(client.predictionEnabled, false); + assert.equal(predicted().predicted, false); + assert.ok(Math.abs(predicted().fields.x) < 0.01, 'authoritative state when prediction is off'); + client.sendInput(50, 1000); + client.setPredictionEnabled(true); + assert.ok(Math.abs(predicted().fields.x - 100) < 0.01, 'inputs kept recording while off'); + client.close(); + + const fixed = new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: () => 't', + socket: network.factory, + scheduler, + interpolationDelayMs: 70 + }); + await fixed.connect('z1'); + assert.equal(fixed.interpolationDelay(fixed.authority), 70); + assert.equal(fixed.adaptiveDelay(fixed.authority), undefined); + fixed.close(); +}); From 9aef09f87229a6b33933aee9a6bd29698537f588 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:42:05 -0500 Subject: [PATCH 166/484] feat(examples): keep Arena players visible and add a minimap Players are global entities so everyone in the room stays visible; only drones are culled by the view radius. Drones shrink away near the ring edge, players outside the ring are dimmed and labelled, and a shared minimap shows all positions and the view ring. Feedback from manual review: idle players looked like they vanished when out of range. [[tasks/gr-p10-demos]] --- examples/game/client/src/arena/main.ts | 43 ++++++- examples/game/client/src/shared/minimap.ts | 109 ++++++++++++++++++ examples/game/client/src/shared/style.css | 29 +++++ .../game/client/tests/arena-headless.test.mjs | 33 +++--- examples/game/server/src/arena/mod.rs | 42 ++++--- 5 files changed, 216 insertions(+), 40 deletions(-) create mode 100644 examples/game/client/src/shared/minimap.ts diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 91387829f..e25913dbc 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -5,8 +5,10 @@ * toggle prediction off (P) to see raw input latency (RTT + interpolation * delay); the ghost (G) shows the latest authoritative server position; * - other players and drones: interpolated ~100 ms in the past; - * - interest ring: entities beyond it are removed by the server (drones pop - * in/out at the edge); pillars are global entities. + * - interest ring: drones beyond it are removed by the server (they shrink + * away over the last few metres before the edge); players and pillars are + * global, so everyone in the room stays visible (dimmed outside the ring); + * - minimap (top right): everyone's position and the view ring. */ import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; import { Vector3 } from '@babylonjs/core/Maths/math.vector'; @@ -18,6 +20,7 @@ import type { RenderedEntity } from '@hops-ops/distributed/game'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, FixedRate, InputSampler, toAxis } from '../shared/input.ts'; +import { Minimap, type MinimapDot } from '../shared/minimap.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { createArenaClient, DEFAULT_ZONE, KIND } from './client.ts'; import { BUTTON_DASH, DASH_COOLDOWN, HALF, PLAYER_RADIUS, type MoveInput } from './movement.ts'; @@ -63,6 +66,7 @@ hud.toggle('Server ghost', true, (on) => (ghostOn = on), 'g'); const mats = { me: material(scene, 'me', '#6cc4ff'), other: material(scene, 'other', '#f2a65a'), + otherFar: material(scene, 'other-far', '#f2a65a', 0.45), ghost: material(scene, 'ghost', '#ffffff', 0.25), drone: material(scene, 'drone', '#9ad16b'), pillar: material(scene, 'pillar', '#7b8798') @@ -92,6 +96,18 @@ const ghost = capsule('ghost', mats.ghost); const ring = createRing(scene, 14, '#6cc4ff'); ring.setEnabled(false); +/** Drones shrink away over this many metres inside the view-radius edge. */ +const FADE_BAND = 3; +const COLORS = { me: '#6cc4ff', other: '#f2a65a', drone: '#9ad16b', pillar: '#7b8798' }; +const minimap = new Minimap({ + half: HALF, + legend: [ + { color: COLORS.me, label: 'you' }, + { color: COLORS.other, label: 'players (global)' }, + { color: COLORS.drone, label: 'drones (in view only)' } + ] +}); + function visualFor(entity: RenderedEntity, mine: boolean): Visual { let visual = visuals.get(entity.key); if (visual !== undefined) return visual; @@ -137,9 +153,15 @@ stage.onFrame((now, dtMs) => { const authority = client.authority; const rendered = client.render(); const seen = new Set(); - let me: { x: number; y: number } | undefined; + const isMine = (entity: RenderedEntity) => + authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; + const mineEntity = rendered.find(isMine); + let me: { x: number; y: number } | undefined = + mineEntity === undefined ? undefined : { x: num(mineEntity, 'x'), y: num(mineEntity, 'y') }; + const viewRadius = hello?.viewRadius ?? 14; + const dots: MinimapDot[] = []; for (const entity of rendered) { - const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; + const mine = isMine(entity); let fields = entity.fields; if (mine && !predictionOn && authority !== undefined) { // Prediction off: show the own capsule like everyone else, interpolated in the past. @@ -150,18 +172,28 @@ stage.onFrame((now, dtMs) => { const x = num({ fields }, 'x'); const y = num({ fields }, 'y'); seen.add(entity.key); + const distance = me === undefined ? 0 : Math.hypot(x - me.x, y - me.y); if (visual.kind === KIND.drone) { + // Shrink toward the edge so culling at the ring reads as "out of view". + const s = Math.min(1, Math.max(0.2, (viewRadius - distance) / FADE_BAND)); visual.mesh.position.copyFrom(toWorld(x, y, 1.3)); visual.mesh.rotation.y = -num(entity, 'yaw'); + visual.mesh.scaling.setAll(s); + dots.push({ x, y, color: COLORS.drone, size: 2 }); } else if (visual.kind === KIND.pillar) { visual.mesh.position.copyFrom(toWorld(x, y, 1)); + dots.push({ x, y, color: COLORS.pillar, size: Math.max(2, num(entity, 'r') * 2), hollow: true }); } else { visual.mesh.position.copyFrom(toWorld(x, y, 0.9)); const dashing = num({ fields }, 'dash') > 0; visual.mesh.scaling.copyFromFloats(dashing ? 1.25 : 1, 1, dashing ? 1.25 : 1); const label = String(fields.name ?? ''); - stage.labels.set(entity.key, visual.mesh as Mesh, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); + const outside = !mine && distance > viewRadius; + if (!mine) (visual.mesh as Mesh).material = outside ? mats.otherFar : mats.other; + const text = mine ? `${label} (you)` : outside ? `${label} · outside view` : label; + stage.labels.set(entity.key, visual.mesh as Mesh, text, 1.4, mine ? 'me' : ''); if (mine) me = { x, y }; + dots.push({ x, y, color: mine ? COLORS.me : COLORS.other, size: mine ? 4 : 3.5 }); } visual.mesh.setEnabled(!entity.stale || visual.kind === KIND.pillar); } @@ -185,6 +217,7 @@ stage.onFrame((now, dtMs) => { } } + minimap.draw({ me, viewRadius, dots }); hud.frame({ entities: rendered.length }); const predictor = client.predictor; const cd = authoritative === undefined ? 0 : num({ fields: authoritative }, 'cd'); diff --git a/examples/game/client/src/shared/minimap.ts b/examples/game/client/src/shared/minimap.ts new file mode 100644 index 000000000..7957e8a2c --- /dev/null +++ b/examples/game/client/src/shared/minimap.ts @@ -0,0 +1,109 @@ +/** + * Top-down minimap overlay (2D canvas, top-right). Draws the floor bounds, + * the local view radius and a dot per entity, so it is obvious which + * entities the server culled by interest management and which are global. + */ + +export type MinimapDot = Readonly<{ + x: number; + y: number; + color: string; + /** Dot radius in CSS pixels (default 3). */ + size?: number; + /** Draw as an outlined ring instead of a filled dot. */ + hollow?: boolean; +}>; + +export type MinimapFrame = Readonly<{ + /** Local player position; the view ring is centred here. */ + me?: Readonly<{ x: number; y: number }>; + /** View radius in world metres (omit to hide the ring). */ + viewRadius?: number; + dots: readonly MinimapDot[]; +}>; + +export type MinimapOptions = Readonly<{ + /** Half the floor size in metres: the map shows [-half, half]². */ + half: number; + /** Canvas size in CSS pixels (default 180). */ + size?: number; + /** Legend entries shown under the map. */ + legend?: readonly Readonly<{ color: string; label: string }>[]; +}>; + +export class Minimap { + readonly #canvas: HTMLCanvasElement; + readonly #ctx: CanvasRenderingContext2D; + readonly #half: number; + readonly #size: number; + + constructor(options: MinimapOptions, parent: HTMLElement = document.body) { + this.#half = options.half; + this.#size = options.size ?? 180; + const root = document.createElement('div'); + root.className = 'minimap'; + this.#canvas = document.createElement('canvas'); + const dpr = globalThis.devicePixelRatio ?? 1; + this.#canvas.width = Math.round(this.#size * dpr); + this.#canvas.height = Math.round(this.#size * dpr); + this.#canvas.style.width = `${this.#size}px`; + this.#canvas.style.height = `${this.#size}px`; + root.append(this.#canvas); + if (options.legend !== undefined && options.legend.length > 0) { + const legend = document.createElement('ul'); + for (const entry of options.legend) { + const item = document.createElement('li'); + const swatch = document.createElement('span'); + swatch.style.background = entry.color; + item.append(swatch, entry.label); + legend.append(item); + } + root.append(legend); + } + parent.append(root); + const ctx = this.#canvas.getContext('2d'); + if (ctx === null) throw new Error('minimap: 2d context unavailable'); + ctx.scale(dpr, dpr); + this.#ctx = ctx; + } + + /** World metres → canvas pixels (north-up: +y is drawn upward). */ + #px(x: number, y: number): [number, number] { + const s = this.#size / (this.#half * 2); + return [(x + this.#half) * s, (this.#half - y) * s]; + } + + draw(frame: MinimapFrame): void { + const ctx = this.#ctx; + const size = this.#size; + ctx.clearRect(0, 0, size, size); + ctx.fillStyle = 'rgba(10, 14, 20, 0.75)'; + ctx.fillRect(0, 0, size, size); + ctx.strokeStyle = 'rgba(255, 255, 255, 0.25)'; + ctx.lineWidth = 1; + ctx.strokeRect(0.5, 0.5, size - 1, size - 1); + if (frame.me !== undefined && frame.viewRadius !== undefined) { + const [cx, cy] = this.#px(frame.me.x, frame.me.y); + const r = (frame.viewRadius / (this.#half * 2)) * size; + ctx.beginPath(); + ctx.arc(cx, cy, r, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(108, 196, 255, 0.08)'; + ctx.fill(); + ctx.strokeStyle = 'rgba(108, 196, 255, 0.6)'; + ctx.stroke(); + } + for (const dot of frame.dots) { + const [x, y] = this.#px(dot.x, dot.y); + ctx.beginPath(); + ctx.arc(x, y, dot.size ?? 3, 0, Math.PI * 2); + if (dot.hollow === true) { + ctx.strokeStyle = dot.color; + ctx.lineWidth = 1.5; + ctx.stroke(); + } else { + ctx.fillStyle = dot.color; + ctx.fill(); + } + } + } +} diff --git a/examples/game/client/src/shared/style.css b/examples/game/client/src/shared/style.css index ef9b11f88..eea417011 100644 --- a/examples/game/client/src/shared/style.css +++ b/examples/game/client/src/shared/style.css @@ -114,3 +114,32 @@ body { max-height: 45%; } } +.minimap { + position: fixed; + top: 12px; + right: 12px; + padding: 8px; + border-radius: 8px; + background: var(--panel); + font-size: 11px; +} +.minimap canvas { + display: block; + border-radius: 4px; +} +.minimap ul { + display: flex; + flex-wrap: wrap; + gap: 4px 10px; + max-width: 180px; + margin: 6px 0 0; + padding: 0; + list-style: none; +} +.minimap li span { + display: inline-block; + width: 8px; + height: 8px; + margin-right: 4px; + border-radius: 50%; +} diff --git a/examples/game/client/tests/arena-headless.test.mjs b/examples/game/client/tests/arena-headless.test.mjs index 67ad215ed..8b291b6ab 100644 --- a/examples/game/client/tests/arena-headless.test.mjs +++ b/examples/game/client/tests/arena-headless.test.mjs @@ -64,9 +64,9 @@ test('headless client joins the arena and moves with exact prediction', { timeou await api.setNetSim({ latencyMs: 0, jitterMs: 0, loss: 0 }); assert.deepEqual(await api.getNetSim(), { latencyMs: 0, jitterMs: 0, loss: 0 }); - // A second guest: interest management hides the first one while it is - // beyond the view radius; walking toward it makes it appear, - // interpolated (not predicted) with its display name. + // A second guest: players are global, so it sees the first one at any + // distance (interpolated, not predicted, with its display name), while + // drones stay culled by the view radius. const other = createArenaClient({ api: new DevApi({ base: server.httpUrl, name: () => 'Other', storage: memoryStorage() }), base: server.httpUrl @@ -77,20 +77,19 @@ test('headless client joins the arena and moves with exact prediction', { timeou await until(() => other.client.predictor.active, 5_000, 'second entity bound'); const sees = () => other.client.render().some((e) => e.id === hello.entity && !e.predicted && e.fields.name === 'Headless'); - const deadline = Date.now() + 10_000; - while (!sees() && Date.now() < deadline) { - const at = stateFromFields(other.client.predictor.predicted()); - const dx = server_.x - at.x; - const dy = server_.y - at.y; - const d = Math.hypot(dx, dy); - if (d > otherHello.viewRadius + 2) { - assert.ok(!other.client.authority.replica.has(hello.entity), 'out of view radius: not replicated'); - } - const k = d > 1 ? 127 / d : 0; - other.client.sendInput({ mx: Math.round(dx * k), my: Math.round(dy * k), buttons: 0 }); - await sleep(1000 / 30); - } - assert.ok(sees(), 'remote player visible once within the view radius'); + await until(sees, 5_000, 'remote player visible regardless of distance'); + await until( + () => { + const at = stateFromFields(other.client.predictor.predicted()); + const drones = other.client.render().filter((e) => e.kindName === 'drone' && !e.stale); + return ( + drones.length > 0 && + drones.every((d) => Math.hypot(d.fields.x - at.x, d.fields.y - at.y) <= otherHello.viewRadius * 1.25 + 1) + ); + }, + 5_000, + 'only drones near the view radius are replicated' + ); } finally { for (const c of clients) c.close(); await server.stop(); diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index 311c17358..d72c06475 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -1,8 +1,9 @@ //! **Arena** — the baseline netcode demo. //! //! Mechanics on display: fixed 30 Hz tick / 20 Hz patches, binary deltas, -//! interest management (14 m view radius on a 40×40 m floor: far drones pop -//! in and out at the ring's edge), client prediction + reconciliation of the +//! interest management (14 m view radius on a 40×40 m floor: far drones are +//! culled at the ring's edge; players are global so you always see everyone +//! in the room), client prediction + reconciliation of the //! own capsule ([`movement`] is shared with the TypeScript client) and //! interpolation of everything else (players, ~30 wandering drones). //! @@ -10,7 +11,7 @@ //! //! | kind | ids | fields | notes | //! |---|---|---|---| -//! | 1 `player` | 1000 + player | x y vx vy dash cd name | full [`MoveState`] so clients can rebase | +//! | 1 `player` | 1000 + player | x y vx vy dash cd name | global; full [`MoveState`] so clients can rebase | //! | 2 `drone` | 1..=30 | x y yaw | wander between random targets | //! | 3 `pillar` | 100 + i | x y r | global (visible everywhere) | //! @@ -239,21 +240,26 @@ impl Zone for Arena { fn replicate(&self, out: &mut WorldView) { for p in self.players.values() { let s = p.state; - out.push(EntityState::new( - p.entity, - KIND_PLAYER, - s.x, - s.y, - vec![ - FieldValue::F(s.x), - FieldValue::F(s.y), - FieldValue::F(s.vx), - FieldValue::F(s.vy), - FieldValue::U(s.dash.into()), - FieldValue::U(s.cooldown.into()), - FieldValue::Str(p.name.clone()), - ], - )); + out.push( + EntityState::new( + p.entity, + KIND_PLAYER, + s.x, + s.y, + vec![ + FieldValue::F(s.x), + FieldValue::F(s.y), + FieldValue::F(s.vx), + FieldValue::F(s.vy), + FieldValue::U(s.dash.into()), + FieldValue::U(s.cooldown.into()), + FieldValue::Str(p.name.clone()), + ], + ) + // Players are global: a small room shows everyone; only drones are + // culled by the view radius. + .global(), + ); } for d in &self.drones { out.push( From 1ddd5a859b2b36b997bc7d6c0cdf98a8f731d82c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 17:55:47 -0500 Subject: [PATCH 167/484] feat(examples): add a first-person view toggle to Arena The shared stage gains a first-person free camera (click for pointer lock, mouse to look) with camera-relative movement following the look direction; Arena toggles it with V and hides the own capsule, label and overlapping ghost. Requested in manual review. [[tasks/gr-p10-demos]] --- examples/game/client/src/arena/main.ts | 20 +++++-- examples/game/client/src/shared/scene.ts | 74 +++++++++++++++++++++--- 2 files changed, 80 insertions(+), 14 deletions(-) diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 4a31dd280..26692dd99 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -54,12 +54,13 @@ client.on('correction', (c) => { const hud = new Hud({ title: 'Arena', - hint: 'WASD / stick to move, Space / A to dash. P: prediction, G: ghost. Drag to orbit.', + hint: 'WASD / stick to move, Space / A to dash. P: prediction, G: ghost, V: first person (click to look). Drag to orbit.', client, devApi: api }); hud.toggle('Client prediction', true, (on) => client.setPredictionEnabled(on), 'p'); hud.toggle('Server ghost', true, (on) => (ghostOn = on), 'g'); +hud.toggle('First-person view', false, (on) => stage.setView(on ? 'first' : 'third'), 'v'); // ---- meshes ---- const mats = { @@ -187,11 +188,13 @@ stage.onFrame((now, dtMs) => { const outside = !mine && distance > viewRadius; if (!mine) (visual.mesh as Mesh).material = outside ? mats.otherFar : mats.other; const text = mine ? `${label} (you)` : outside ? `${label} · outside view` : label; - stage.labels.set(entity.key, visual.mesh as Mesh, text, 1.4, mine ? 'me' : ''); + // First person: the camera is the own capsule, so hide it and its label. + if (mine && stage.view() === 'first') stage.labels.delete(entity.key); + else stage.labels.set(entity.key, visual.mesh as Mesh, text, 1.4, mine ? 'me' : ''); if (mine) me = { x, y }; dots.push({ x, y, color: mine ? COLORS.me : COLORS.other, size: mine ? 4 : 3.5 }); } - visual.mesh.setEnabled(!entity.stale || visual.kind === KIND.pillar); + visual.mesh.setEnabled((!entity.stale || visual.kind === KIND.pillar) && !(mine && stage.view() === 'first')); } for (const [key, visual] of visuals) { if (seen.has(key)) continue; @@ -201,8 +204,15 @@ stage.onFrame((now, dtMs) => { } const authoritative = client.predictor?.authoritative(); - ghost.setEnabled(ghostOn && authoritative !== undefined); - if (authoritative !== undefined) ghost.position.copyFrom(toWorld(num({ fields: authoritative }, 'x'), num({ fields: authoritative }, 'y'), 0.9)); + let ghostVisible = ghostOn && authoritative !== undefined; + if (authoritative !== undefined) { + const gx = num({ fields: authoritative }, 'x'); + const gy = num({ fields: authoritative }, 'y'); + ghost.position.copyFrom(toWorld(gx, gy, 0.9)); + // First person: the eye sits inside the ghost; show it only once it lags visibly. + if (stage.view() === 'first' && me !== undefined && Math.hypot(gx - me.x, gy - me.y) < 0.8) ghostVisible = false; + } + ghost.setEnabled(ghostVisible); if (me !== undefined) { stage.follow(me.x, me.y, dtMs); ring.setEnabled(true); diff --git a/examples/game/client/src/shared/scene.ts b/examples/game/client/src/shared/scene.ts index 11f2b569d..1da7a4259 100644 --- a/examples/game/client/src/shared/scene.ts +++ b/examples/game/client/src/shared/scene.ts @@ -1,12 +1,15 @@ /** * Babylon.js stage shared by the demos: engine + scene + light, a gridded - * floor, a third-person follow camera, DOM name labels and helpers. + * floor, a third-person follow camera with an optional first-person view + * (click to lock the pointer, mouse to look), DOM name labels and helpers. * * Coordinates: the server's 2D plane (x, y) maps to Babylon (x, 0, z = y), * Y up. Use `toWorld(x, y, height)`. */ // Deep imports keep the bundle small (the package root pulls in everything). import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera'; +import type { Camera } from '@babylonjs/core/Cameras/camera'; +import { FreeCamera } from '@babylonjs/core/Cameras/freeCamera'; import { Engine } from '@babylonjs/core/Engines/engine'; import { DirectionalLight } from '@babylonjs/core/Lights/directionalLight'; import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight'; @@ -26,14 +29,24 @@ export type Stage = Readonly<{ scene: Scene; camera: ArcRotateCamera; labels: LabelLayer; + /** Current view: orbiting third person, or first person at the followed position. */ + view(): CameraView; + /** Switch view; first person keeps the current facing direction. */ + setView(view: CameraView): void; /** Ground-plane direction the camera looks along (game x/y), for camera-relative input. */ cameraForward(): { x: number; y: number }; - /** Ease the camera target toward a game position. */ + /** Ease the camera target toward a game position (first person: place the eye there). */ follow(x: number, y: number, dtMs: number): void; /** Register a per-frame callback (after input, before render). */ onFrame(callback: (now: number, dtMs: number) => void): void; }>; +export type CameraView = 'third' | 'first'; + +/** First-person eye height (m) and mouse-look sensitivity (rad per pixel). */ +const EYE_HEIGHT = 1.6; +const LOOK_SPEED = 0.0025; + export type StageOptions = Readonly<{ /** Floor half extent (m). */ half: number; @@ -73,9 +86,30 @@ export function createStage(canvas: HTMLCanvasElement, options: StageOptions): S // Arrow keys move the player, not the camera. camera.inputs.removeByType('ArcRotateCameraKeyboardMoveInput'); + // First person: a free camera with no built-in inputs; pointer lock + + // mouse movement drive yaw/pitch, the follow target places the eye. + const eye = new FreeCamera('eye', new Vector3(0, EYE_HEIGHT, 0), scene); + eye.inputs.clear(); + eye.minZ = 0.05; + eye.fov = 1.2; + let view: CameraView = 'third'; + let yaw = 0; + let pitch = 0; + canvas.addEventListener('click', () => { + if (view === 'first' && document.pointerLockElement !== canvas) void canvas.requestPointerLock?.(); + }); + document.addEventListener('mousemove', (e) => { + if (view !== 'first' || document.pointerLockElement !== canvas) return; + yaw += e.movementX * LOOK_SPEED; + pitch = Math.max(-1.3, Math.min(1.3, pitch + e.movementY * LOOK_SPEED)); + eye.rotation.set(pitch, yaw, 0); + }); + const forward = () => + view === 'first' ? { x: Math.sin(yaw), y: Math.cos(yaw) } : { x: -Math.cos(camera.alpha), y: -Math.sin(camera.alpha) }; + createFloor(scene, options.half, options.gridStep ?? 1); - const labels = new LabelLayer(canvas, scene, camera); + const labels = new LabelLayer(canvas, scene); const frameCallbacks: ((now: number, dtMs: number) => void)[] = []; let last = performance.now(); engine.runRenderLoop(() => { @@ -93,10 +127,32 @@ export function createStage(canvas: HTMLCanvasElement, options: StageOptions): S scene, camera, labels, - cameraForward() { - return { x: -Math.cos(camera.alpha), y: -Math.sin(camera.alpha) }; + view: () => view, + setView(next) { + if (next === view) return; + const f = forward(); + view = next; + if (next === 'first') { + yaw = Math.atan2(f.x, f.y); + pitch = 0; + eye.rotation.set(pitch, yaw, 0); + camera.detachControl(); + scene.activeCamera = eye; + } else { + if (document.pointerLockElement === canvas) document.exitPointerLock(); + camera.alpha = Math.atan2(-f.y, -f.x); + camera.attachControl(canvas, true); + scene.activeCamera = camera; + } }, + cameraForward: forward, follow(x, y, dtMs) { + if (view === 'first') { + eye.position.set(x, EYE_HEIGHT, y); + // Keep the orbit camera centred so switching back is seamless. + camera.setTarget(new Vector3(x, 0, y)); + return; + } const k = 1 - Math.exp(-dtMs / 120); const t = camera.target; camera.setTarget(new Vector3(t.x + (x - t.x) * k, 0, t.z + (y - t.z) * k)); @@ -167,11 +223,9 @@ export class LabelLayer { readonly #root: HTMLDivElement; readonly #labels = new Map(); readonly #scene: Scene; - readonly #camera: ArcRotateCamera; - constructor(canvas: HTMLCanvasElement, scene: Scene, camera: ArcRotateCamera) { + constructor(canvas: HTMLCanvasElement, scene: Scene) { this.#scene = scene; - this.#camera = camera; this.#root = document.createElement('div'); this.#root.className = 'labels'; canvas.parentElement?.appendChild(this.#root); @@ -202,7 +256,9 @@ export class LabelLayer { const width = engine.getRenderWidth(); const height = engine.getRenderHeight(); const scale = engine.getHardwareScalingLevel(); - const viewport = this.#camera.viewport.toGlobal(width, height); + const camera: Camera | null = this.#scene.activeCamera; + if (camera === null) return; + const viewport = camera.viewport.toGlobal(width, height); const transform = this.#scene.getTransformMatrix(); for (const { el, mesh, offset } of this.#labels.values()) { const world = mesh.getAbsolutePosition().add(new Vector3(0, offset, 0)); From 86e8beede03e067545e7da82d57fb1ded93979bc Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 18:00:54 -0500 Subject: [PATCH 168/484] feat(examples): look around with the gamepad right stick The shared stage reads the right stick every frame: it turns the eye in first person and orbits the follow camera in third person, so every demo gets it. Also imports Ray for scene picking and tolerates refused pointer lock. Requested in manual review. [[tasks/gr-p10-demos]] --- examples/game/client/src/arena/main.ts | 2 +- examples/game/client/src/shared/scene.ts | 39 ++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 26692dd99..45931b769 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -54,7 +54,7 @@ client.on('correction', (c) => { const hud = new Hud({ title: 'Arena', - hint: 'WASD / stick to move, Space / A to dash. P: prediction, G: ghost, V: first person (click to look). Drag to orbit.', + hint: 'WASD / stick to move, Space / A to dash. P: prediction, G: ghost, V: first person (click to look). Right stick / drag: camera.', client, devApi: api }); diff --git a/examples/game/client/src/shared/scene.ts b/examples/game/client/src/shared/scene.ts index 1da7a4259..49ed9fb4a 100644 --- a/examples/game/client/src/shared/scene.ts +++ b/examples/game/client/src/shared/scene.ts @@ -1,7 +1,8 @@ /** * Babylon.js stage shared by the demos: engine + scene + light, a gridded * floor, a third-person follow camera with an optional first-person view - * (click to lock the pointer, mouse to look), DOM name labels and helpers. + * (click to lock the pointer, mouse to look), gamepad right-stick look in + * both views, DOM name labels and helpers. * * Coordinates: the server's 2D plane (x, y) maps to Babylon (x, 0, z = y), * Y up. Use `toWorld(x, y, height)`. @@ -21,6 +22,8 @@ import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; import type { LinesMesh } from '@babylonjs/core/Meshes/linesMesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { Scene } from '@babylonjs/core/scene'; +// Side effect: scene picking (pointer events) needs Ray. +import '@babylonjs/core/Culling/ray'; // Side effect: Mesh.prototype.createInstance. import '@babylonjs/core/Meshes/instancedMesh'; @@ -46,6 +49,22 @@ export type CameraView = 'third' | 'first'; /** First-person eye height (m) and mouse-look sensitivity (rad per pixel). */ const EYE_HEIGHT = 1.6; const LOOK_SPEED = 0.0025; +/** Gamepad right-stick look rates (rad/s) and deadzone. */ +const STICK_YAW = 2.6; +const STICK_PITCH = 1.6; +const STICK_DEADZONE = 0.15; + +/** Right stick of the first connected gamepad: +x right, +y up. */ +function rightStick(): { x: number; y: number } { + const pads = globalThis.navigator?.getGamepads?.() ?? []; + for (const pad of pads) { + if (!pad?.connected) continue; + const x = pad.axes[2] ?? 0; + const y = -(pad.axes[3] ?? 0); + return { x: Math.abs(x) > STICK_DEADZONE ? x : 0, y: Math.abs(y) > STICK_DEADZONE ? y : 0 }; + } + return { x: 0, y: 0 }; +} export type StageOptions = Readonly<{ /** Floor half extent (m). */ @@ -96,7 +115,8 @@ export function createStage(canvas: HTMLCanvasElement, options: StageOptions): S let yaw = 0; let pitch = 0; canvas.addEventListener('click', () => { - if (view === 'first' && document.pointerLockElement !== canvas) void canvas.requestPointerLock?.(); + // Pointer lock can be refused (e.g. headless or unfocused); mouse look then waits for the next click. + if (view === 'first' && document.pointerLockElement !== canvas) Promise.resolve(canvas.requestPointerLock?.()).catch(() => {}); }); document.addEventListener('mousemove', (e) => { if (view !== 'first' || document.pointerLockElement !== canvas) return; @@ -116,6 +136,21 @@ export function createStage(canvas: HTMLCanvasElement, options: StageOptions): S const now = performance.now(); const dt = now - last; last = now; + // Right stick looks around: turns the eye in first person, orbits in third. + const stick = rightStick(); + if (stick.x !== 0 || stick.y !== 0) { + const s = Math.min(dt, 100) / 1000; + if (view === 'first') { + yaw += stick.x * STICK_YAW * s; + pitch = Math.max(-1.3, Math.min(1.3, pitch - stick.y * STICK_PITCH * s)); + eye.rotation.set(pitch, yaw, 0); + } else { + camera.alpha -= stick.x * STICK_YAW * s; + const lo = camera.lowerBetaLimit ?? 0.01; + const hi = camera.upperBetaLimit ?? Math.PI - 0.01; + camera.beta = Math.max(lo, Math.min(hi, camera.beta + stick.y * STICK_PITCH * s)); + } + } for (const callback of frameCallbacks) callback(now, dt); scene.render(); labels.update(); From f79c9d6d138e204c604bd54a5c7024cc94a0a596 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 18:19:08 -0500 Subject: [PATCH 169/484] fix(examples): read gamepads by layout and guard the right stick Prefer a pad with the standard layout, keep only the left stick on other layouts (their axes 2/3 can be triggers resting at -1, which spun the camera), ignore the right stick until seen at rest, and show the active pad and its axes in the Arena HUD. [[tasks/gr-p10-demos]] --- examples/game/client/src/arena/main.ts | 3 +- examples/game/client/src/shared/input.ts | 49 ++++++++++++++++++++++-- examples/game/client/src/shared/scene.ts | 14 +------ 3 files changed, 49 insertions(+), 17 deletions(-) diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 45931b769..ea1ad6e84 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -19,7 +19,7 @@ import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; -import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; +import { cameraRelative, describeGamepad, InputSampler, toAxis } from '../shared/input.ts'; import { Minimap, type MinimapDot } from '../shared/minimap.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { createArenaClient, DEFAULT_ZONE, KIND } from './client.ts'; @@ -233,6 +233,7 @@ stage.onFrame((now, dtMs) => { hud.row('Corrections', `${corrections} (last ${lastCorrection.toFixed(3)} m)`); hud.row('Dash', cd > 0 ? `cooldown ${((cd / DASH_COOLDOWN) * 1.5).toFixed(1)} s` : 'ready'); hud.row('Stick', `${lastInput.mx}, ${lastInput.my}`); + hud.row('Gamepad', describeGamepad()); }); declare global { diff --git a/examples/game/client/src/shared/input.ts b/examples/game/client/src/shared/input.ts index b4474df35..d53fc8ae9 100644 --- a/examples/game/client/src/shared/input.ts +++ b/examples/game/client/src/shared/input.ts @@ -80,10 +80,53 @@ export class InputSampler { } } -function firstGamepad(): Gamepad | undefined { +/** + * The gamepad to read: the first connected pad with the W3C `standard` + * layout, else the first connected pad (whose left stick is still axes 0/1 + * on every layout we know). Slots can be sparse, so scan them all. + */ +export function activeGamepad(): Gamepad | undefined { const pads = globalThis.navigator?.getGamepads?.() ?? []; - for (const pad of pads) if (pad?.connected) return pad; - return undefined; + let fallback: Gamepad | undefined; + for (const pad of pads) { + if (!pad?.connected) continue; + if (pad.mapping === 'standard') return pad; + fallback ??= pad; + } + return fallback; +} + +function firstGamepad(): Gamepad | undefined { + return activeGamepad(); +} + +const neutralSeen = new WeakMap(); + +/** + * Right stick (+x right, +y up) of a `standard` pad, with deadzone. Other + * layouts return zero: their axes 2/3 may be triggers that rest at -1 and + * would read as a stick held hard over. The stick is also ignored until it + * has been seen at rest once. + */ +export function rightStick(deadzone = DEADZONE): { x: number; y: number } { + const pad = activeGamepad(); + if (pad === undefined || pad.mapping !== 'standard') return { x: 0, y: 0 }; + const x = pad.axes[2] ?? 0; + const y = -(pad.axes[3] ?? 0); + if (!neutralSeen.get(pad)) { + if (Math.hypot(x, y) > deadzone) return { x: 0, y: 0 }; + neutralSeen.set(pad, true); + } + return { x: Math.abs(x) > deadzone ? x : 0, y: Math.abs(y) > deadzone ? y : 0 }; +} + +/** One-line description of the active pad for HUD diagnostics. */ +export function describeGamepad(): string { + const pad = activeGamepad(); + if (pad === undefined) return 'none (press a button)'; + const f = (v: number | undefined) => (v ?? 0).toFixed(2); + const name = pad.id.length > 28 ? `${pad.id.slice(0, 28)}…` : pad.id; + return `${name} · ${pad.mapping || 'non-standard'} · L ${f(pad.axes[0])},${f(pad.axes[1])} R ${f(pad.axes[2])},${f(pad.axes[3])}`; } function isTyping(e: KeyboardEvent): boolean { diff --git a/examples/game/client/src/shared/scene.ts b/examples/game/client/src/shared/scene.ts index 49ed9fb4a..ec310f243 100644 --- a/examples/game/client/src/shared/scene.ts +++ b/examples/game/client/src/shared/scene.ts @@ -22,6 +22,7 @@ import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; import type { LinesMesh } from '@babylonjs/core/Meshes/linesMesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { Scene } from '@babylonjs/core/scene'; +import { rightStick } from './input.ts'; // Side effect: scene picking (pointer events) needs Ray. import '@babylonjs/core/Culling/ray'; // Side effect: Mesh.prototype.createInstance. @@ -52,19 +53,6 @@ const LOOK_SPEED = 0.0025; /** Gamepad right-stick look rates (rad/s) and deadzone. */ const STICK_YAW = 2.6; const STICK_PITCH = 1.6; -const STICK_DEADZONE = 0.15; - -/** Right stick of the first connected gamepad: +x right, +y up. */ -function rightStick(): { x: number; y: number } { - const pads = globalThis.navigator?.getGamepads?.() ?? []; - for (const pad of pads) { - if (!pad?.connected) continue; - const x = pad.axes[2] ?? 0; - const y = -(pad.axes[3] ?? 0); - return { x: Math.abs(x) > STICK_DEADZONE ? x : 0, y: Math.abs(y) > STICK_DEADZONE ? y : 0 }; - } - return { x: 0, y: 0 }; -} export type StageOptions = Readonly<{ /** Floor half extent (m). */ From 489661d250cb1973e9c4951f5d1c3b32c3567488 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 18:26:30 -0500 Subject: [PATCH 170/484] fix(game): treat a fresh-ticket rejoin as a new client session A ticket for a principal already in the zone (page reload, second tab with the same identity) replaced the connection but kept the old input sequence, so the new client's inputs were all stale and never acked, and the zone never resent per-player state. Reset the sequence and call the new Zone::on_rejoin hook (default: on_leave(Rejoined) + on_join). Found in manual review of the Arena demo. [[specs/framework/game-runtime/v1/index]] --- distributed_game/src/host.rs | 7 +++++ distributed_game/src/input.rs | 7 +++++ distributed_game/src/zone.rs | 18 ++++++++++++ distributed_game/tests/zone_runtime/main.rs | 31 ++++++++++++++++++++- 4 files changed, 62 insertions(+), 1 deletion(-) diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 0ac439001..c2c685c7e 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -926,9 +926,16 @@ impl ZoneHost { slot.info.name = claims.name.clone(); } } + // A ticket (not a reconnect token) means a new client session: + // its input sequence restarts, so forget the old one. + if let Some(slot) = self.core.players.get_mut(&player) { + slot.inputs.reset_sequence(); + } self.bind_player(player, client, capabilities); if let Some((from, carried)) = handoff.take() { hook!(self.on_handoff_join(player, from, carried)); + } else { + hook!(self.on_rejoin(player)); } Joined { client, diff --git a/distributed_game/src/input.rs b/distributed_game/src/input.rs index b07b82f86..55f7b8429 100644 --- a/distributed_game/src/input.rs +++ b/distributed_game/src/input.rs @@ -151,6 +151,13 @@ impl InputBuffer { pub fn clear(&mut self) { self.queue.clear(); } + + /// Start a new sequence space (a new client session numbers its inputs + /// from 1 again): clears the queue and the last processed sequence. + pub fn reset_sequence(&mut self) { + self.queue.clear(); + self.last_processed = 0; + } } /// Server-side input pacing: a player earns one input credit per tick (up diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index 9021986cd..166a06ebc 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -140,6 +140,9 @@ pub enum LeaveReason { Handoff, /// Zone disposed. Disposed, + /// A fresh ticket for the same principal started a new client session in + /// this slot (e.g. a page reload); see [`Zone::on_rejoin`]. + Rejoined, } /// Player as seen by the zone. @@ -207,6 +210,21 @@ pub trait Zone: Sized + Send + 'static { /// A player left for `reason` (not called on a disconnect still inside the grace window). fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId, _reason: LeaveReason) {} + /// A fresh ticket (not a reconnect token) arrived for a principal that + /// already holds a player slot here, e.g. the page was reloaded or opened + /// in another tab with the same identity. The old connection was + /// replaced (`Kick(REPLACED)`) and the new one is a new client session: + /// its input sequence starts again and it knows nothing about per-player + /// state the zone sent on join (own entity id, hello events…). + /// + /// Defaults to `on_leave(Rejoined)` then `on_join`, i.e. a fresh join in + /// the same [`PlayerId`]. Override to keep in-zone state and only resend + /// what the client needs. + fn on_rejoin(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.on_leave(ctx, player, LeaveReason::Rejoined); + self.on_join(ctx, player); + } + /// An observer subscribed. Its principal and name are available from /// [`Ctx::observer`](crate::Ctx::observer); address it with /// [`Ctx::send_event`](crate::Ctx::send_event)`(observer, ..)`. diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index 97038be77..11f7ba50d 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -559,12 +559,41 @@ fn same_principal_replaces_previous_connection() { let clock = ManualClock::new(); let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + for seq in 1..=5 { + assert_eq!( + h.push_input(a.client, seq, 0, &[1, 0]), + PushOutcome::Accepted + ); + } + clock.advance(MS(200)); + h.advance(); + h.drain_outbound(); + + // A fresh ticket (e.g. page reload) replaces the connection and is a new + // client session: its inputs number from 1 again and must not be stale, + // and the zone sees on_rejoin (default: leave(Rejoined) + join) so it can + // resend per-player state. let b = h.join(&claims("alice", "z1"), 0, "").unwrap(); assert_eq!(a.viewer, b.viewer); assert_eq!(h.client_count(), 1); let out = h.drain_outbound(); assert!(out.contains(&Outbound::Close { client: a.client })); - assert_eq!(h.zone().log, vec!["create", "join:alice"]); + assert_eq!( + h.zone().log, + vec!["create", "join:alice", "leave:Rejoined", "join:alice"] + ); + assert_eq!(h.push_input(b.client, 1, 0, &[0, 1]), PushOutcome::Accepted); + clock.advance(MS(100)); + h.advance(); + let mut mirror = ClientMirror::new(); + let later = h.drain_outbound(); + for frame in frames_for(&out, b.client) + .into_iter() + .chain(frames_for(&later, b.client)) + { + mirror.apply(&frame).unwrap(); + } + assert_eq!(mirror.ack_seq, 1, "new session acked from its own sequence"); } #[test] From 3aa05be5ff999824a0f9cf4ab05f7edbe4b9312d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 18:26:31 -0500 Subject: [PATCH 171/484] fix(examples): keep one dev guest per tab Store the guest token in sessionStorage so a reload keeps the player and each tab is a separate player. [[tasks/gr-p10-demos]] --- examples/game/client/src/shared/dev-api.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/game/client/src/shared/dev-api.ts b/examples/game/client/src/shared/dev-api.ts index 5d2ddb88f..64ed40f5f 100644 --- a/examples/game/client/src/shared/dev-api.ts +++ b/examples/game/client/src/shared/dev-api.ts @@ -4,8 +4,8 @@ * * A real game gets admission tickets from its authenticated lobby; the dev * route mints one for a server-generated guest. We keep the server-signed - * guest token (localStorage when available) so a page reload stays the same - * player. Works in browsers (relative URLs) and in Node tests (`base`). + * guest token per tab (sessionStorage when available): a reload stays the + * same player, and each tab is its own player. Works in browsers (relative URLs) and in Node tests (`base`). */ import type { GameTicketSource } from '@hops-ops/distributed/game'; @@ -25,7 +25,7 @@ export type DevApiOptions = Readonly<{ base?: string; /** Display name for new tickets (read on every request). */ name?: () => string | undefined; - /** Where the guest token lives between reloads (default localStorage when present). */ + /** Where the guest token lives between reloads (default sessionStorage when present: one guest per tab). */ storage?: Pick; }>; @@ -33,7 +33,7 @@ const GUEST_KEY = 'game-demos.guest'; function defaultStorage(): Pick | undefined { try { - return globalThis.localStorage ?? undefined; + return globalThis.sessionStorage ?? undefined; } catch { return undefined; } From 14f5e4e42e4951e10858a703656ac6dbb138021d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 18:38:48 -0500 Subject: [PATCH 172/484] fix(examples): make right-stick camera look work in third person The neutral-stick guard was keyed on the Gamepad object, but browsers return a fresh snapshot per getGamepads() call, so the stick was always ignored; key it by pad index and id. The follow camera's setTarget also rebuilt alpha/beta from the last rendered position every frame, undoing stick orbit; keep the angles. [[tasks/gr-p10-demos]] --- examples/game/client/src/shared/input.ts | 12 +++++++++--- examples/game/client/src/shared/scene.ts | 6 ++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/examples/game/client/src/shared/input.ts b/examples/game/client/src/shared/input.ts index d53fc8ae9..8600cd519 100644 --- a/examples/game/client/src/shared/input.ts +++ b/examples/game/client/src/shared/input.ts @@ -100,7 +100,12 @@ function firstGamepad(): Gamepad | undefined { return activeGamepad(); } -const neutralSeen = new WeakMap(); +/** + * Pads whose right stick has been seen at rest, by `index:id`. Browsers return + * a fresh snapshot object from every `getGamepads()` call, so the pad object + * itself cannot be the key. + */ +const neutralSeen = new Set(); /** * Right stick (+x right, +y up) of a `standard` pad, with deadzone. Other @@ -113,9 +118,10 @@ export function rightStick(deadzone = DEADZONE): { x: number; y: number } { if (pad === undefined || pad.mapping !== 'standard') return { x: 0, y: 0 }; const x = pad.axes[2] ?? 0; const y = -(pad.axes[3] ?? 0); - if (!neutralSeen.get(pad)) { + const key = `${pad.index}:${pad.id}`; + if (!neutralSeen.has(key)) { if (Math.hypot(x, y) > deadzone) return { x: 0, y: 0 }; - neutralSeen.set(pad, true); + neutralSeen.add(key); } return { x: Math.abs(x) > deadzone ? x : 0, y: Math.abs(y) > deadzone ? y : 0 }; } diff --git a/examples/game/client/src/shared/scene.ts b/examples/game/client/src/shared/scene.ts index ec310f243..8d130149a 100644 --- a/examples/game/client/src/shared/scene.ts +++ b/examples/game/client/src/shared/scene.ts @@ -173,12 +173,14 @@ export function createStage(canvas: HTMLCanvasElement, options: StageOptions): S if (view === 'first') { eye.position.set(x, EYE_HEIGHT, y); // Keep the orbit camera centred so switching back is seamless. - camera.setTarget(new Vector3(x, 0, y)); + camera.setTarget(new Vector3(x, 0, y), false, false, true); return; } const k = 1 - Math.exp(-dtMs / 120); const t = camera.target; - camera.setTarget(new Vector3(t.x + (x - t.x) * k, 0, t.z + (y - t.z) * k)); + // cloneAlphaBetaRadius: keep the orbit angles; the default rebuilds + // them from the last rendered position, undoing stick look. + camera.setTarget(new Vector3(t.x + (x - t.x) * k, 0, t.z + (y - t.z) * k), false, false, true); }, onFrame(callback) { frameCallbacks.push(callback); From 9710277ffb55bdb9a6dd65fca59991bb0ebc44a2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 21:59:10 -0500 Subject: [PATCH 173/484] fix(game): restart input sequence on every welcome, incl. reconnect A resumed session (reconnect token, e.g. after Kick(RELOAD)) restarts the client's input sequence at 1, but the host kept the old one and dropped the first inputs as duplicates, freezing the player ~2.5 s. --- distributed_game/src/host.rs | 8 +++----- distributed_game/tests/zone_runtime/main.rs | 7 +++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index c2c685c7e..837397872 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -926,11 +926,6 @@ impl ZoneHost { slot.info.name = claims.name.clone(); } } - // A ticket (not a reconnect token) means a new client session: - // its input sequence restarts, so forget the old one. - if let Some(slot) = self.core.players.get_mut(&player) { - slot.inputs.reset_sequence(); - } self.bind_player(player, client, capabilities); if let Some((from, carried)) = handoff.take() { hook!(self.on_handoff_join(player, from, carried)); @@ -1179,6 +1174,9 @@ impl ZoneHost { slot.info.connected = true; slot.info.capabilities = capabilities; slot.reconnect_token = token.clone(); + // Every Welcome restarts the client's input sequence (ticket or + // reconnect token), so forget the previous connection's. + slot.inputs.reset_sequence(); let session_id = slot.session_id.clone(); if let Some(old) = previous { self.core.clients.remove(&old); diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index 11f7ba50d..60777d449 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -210,12 +210,19 @@ fn reconnect_within_grace_keeps_player_then_expires() { let token = mirror.welcome.as_ref().unwrap().reconnect_token.clone(); assert!(!token.is_empty()); + for seq in 1..=5 { + assert_eq!(h.push_input(a.client, seq, 0, &[1, 0]), PushOutcome::Accepted); + } + h.advance(); + h.disconnect(a.client, false); clock.advance(Duration::from_secs(1)); h.advance(); assert_eq!(h.player_count(), 1); let b = h.reconnect(&token, 0).unwrap(); assert_eq!(b.viewer, a.viewer, "same player after reconnect"); + // The resumed session restarts its input sequence at 1 (new Welcome). + assert_eq!(h.push_input(b.client, 1, 0, &[1, 0]), PushOutcome::Accepted); assert!(h.reconnect(&token, 0).is_err(), "tokens rotate on use"); assert_eq!(h.zone().log, vec!["create", "join:alice"]); From 81133303987e806ad5156dbcb5479bb12e818484 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 21:59:11 -0500 Subject: [PATCH 174/484] fix(examples): remember freeze admin secret, prompt when missing --- examples/game/client/src/freeze/main.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts index 6b49ea62f..54e34bbcc 100644 --- a/examples/game/client/src/freeze/main.ts +++ b/examples/game/client/src/freeze/main.ts @@ -107,14 +107,17 @@ async function main(): Promise { }); // ---- admin panel ---- - const admin = new FreezeAdmin('', params.get('admin') ?? stored('game-demos.freeze.admin') ?? ''); + // `?admin=` is remembered, so other tabs (e.g. `?old=1`) can roll out too. + const adminParam = params.get('admin'); + if (adminParam !== null) store('game-demos.freeze.admin', adminParam); + const admin = new FreezeAdmin('', adminParam ?? stored('game-demos.freeze.admin') ?? ''); const panel = el('fieldset', 'admin'); panel.append(el('legend', '', 'World admin (dev, admin secret)')); const secret = el('input', 'secret'); secret.type = 'password'; secret.placeholder = 'admin secret (printed by the server)'; secret.value = admin.secret; - secret.addEventListener('change', () => { + secret.addEventListener('input', () => { admin.secret = secret.value.trim(); store('game-demos.freeze.admin', admin.secret); }); @@ -131,7 +134,15 @@ async function main(): Promise { panel.append(secret, buttons, ritualLabel, result, status); hud.root.append(panel); + function needSecret(): boolean { + if (admin.secret !== '') return false; + result.textContent = 'Paste the admin secret printed by the server (or open /freeze/?admin=).'; + secret.focus(); + return true; + } + async function roll(mode: 'hard' | 'rolling'): Promise { + if (needSecret()) return; hardButton.disabled = rollingButton.disabled = true; result.textContent = `rolling out (${mode})…`; try { @@ -148,6 +159,10 @@ async function main(): Promise { hardButton.addEventListener('click', () => void roll('hard')); rollingButton.addEventListener('click', () => void roll('rolling')); ritual.addEventListener('change', () => { + if (needSecret()) { + ritual.checked = !ritual.checked; + return; + } admin.setStuck(ZONES.ember, ritual.checked).then( () => (result.textContent = ritual.checked ? 'Ember Fields will refuse the next freeze' : 'ritual ended'), (error: unknown) => { From e2b4b4758a30d3906f2be23d4136b65a70a196a7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 22:02:19 -0500 Subject: [PATCH 175/484] fix(examples): keep grid camera angle across floating-origin shifts --- examples/game/client/src/grid/main.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/game/client/src/grid/main.ts b/examples/game/client/src/grid/main.ts index 7a4c0f92e..a8f699b86 100644 --- a/examples/game/client/src/grid/main.ts +++ b/examples/game/client/src/grid/main.ts @@ -220,7 +220,7 @@ function moveOrigin(to: Cell): void { if (to[0] === origin[0] && to[1] === origin[1]) return; const shift = new Vector3((to[0] - origin[0]) * CELL, 0, (to[1] - origin[1]) * CELL); origin = to; - camera.setTarget(camera.target.subtract(shift)); + camera.setTarget(camera.target.subtract(shift), false, false, true); // keep the orbit angles syncChunks(); } From 865b337c89db6e0db2191494adc153df4bab1280 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 22:07:57 -0500 Subject: [PATCH 176/484] fix(game-sdk): hold predicted entity through a zone handoff Until the target zone binds the controlled entity, render it frozen at its last predicted state and never draw the source zone's interpolated copy, which sat ~100 ms behind and made the player flash back. --- js/src/game/client.ts | 43 ++++++++++++++++++++++++++++++++++-- js/tests/game-world.test.mjs | 27 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/js/src/game/client.ts b/js/src/game/client.ts index f5c62481c..4b945ffac 100644 --- a/js/src/game/client.ts +++ b/js/src/game/client.ts @@ -169,6 +169,16 @@ export class GameClient { readonly #predictor: Predictor | undefined; #authority: Zone | undefined; #controlledOverride: number | undefined; + /** Last rendered controlled entity (held through a handoff). */ + #lastControlled: RenderedEntity | undefined; + /** + * Handoff in flight: the controlled entity is drawn frozen at its last + * predicted state until the target zone binds it, instead of the source + * zone's interpolated (older) copy. + */ + #handoffBridge: RenderedEntity | undefined; + /** The source zone's copy of the handed-off entity: never drawn again. */ + #handedOff: Readonly<{ zoneId: string; id: number }> | undefined; #closed = false; #contentVersion: string; #predictionEnabled: boolean; @@ -351,18 +361,41 @@ export class GameClient { this.#predictionEnabled && predictor?.active === true && this.#authority !== undefined ? predictor.entityId : undefined; + if (controlled !== undefined) this.#handoffBridge = undefined; + const gone = this.#handedOff; + let goneSeen = false; + let mine: RenderedEntity | undefined; for (const zone of this.zones()) { const delay = this.interpolationDelay(zone); zone.replica.interpolationDelayMs = delay; const renderTime = zone.connection.serverNow() - delay; const authoritative = zone === this.#authority; for (const entity of zone.replica.sample(renderTime)) { + // (Unless a failed handoff returned control to the source zone.) + if ( + gone !== undefined && + zone.zoneId === gone.zoneId && + entity.id === gone.id && + !(authoritative && entity.id === controlled) + ) { + goneSeen = true; + continue; + } const isControlled = authoritative && entity.id === controlled && !entity.stale; - out.push( - rendered(zone.zoneId, entity, authoritative, isControlled, isControlled ? predictor!.current(now) : undefined) + const item = rendered( + zone.zoneId, + entity, + authoritative, + isControlled, + isControlled ? predictor!.current(now) : undefined ); + if (item.predicted) mine = item; + out.push(item); } } + if (gone !== undefined && !goneSeen) this.#handedOff = undefined; + if (this.#handoffBridge !== undefined) out.push(this.#handoffBridge); + this.#lastControlled = mine; return out; } @@ -522,6 +555,11 @@ export class GameClient { const from = zone.zoneId; const to = message.targetZone; this.#emitter.emit('handoff', { from, to, message }); + const last = this.#lastControlled; + if (last !== undefined && last.zoneId === from) { + this.#handoffBridge = { ...last, stale: false }; + this.#handedOff = { zoneId: from, id: last.id }; + } this.#controlledOverride = undefined; this.#predictor?.bind(undefined); // Keep rendering the old zone until the new authority has content. @@ -552,6 +590,7 @@ export class GameClient { finish(); if (this.#closed || this.#authority !== target) return; this.#emitter.emit('handoffFailed', { from, to, stage, reason }); + this.#handoffBridge = undefined; connection.close({ leave: false }); // Keep the zone's replica rendering while the next attempt runs. this.#retire(target, true); diff --git a/js/tests/game-world.test.mjs b/js/tests/game-world.test.mjs index c436815a7..4718c2e6f 100644 --- a/js/tests/game-world.test.mjs +++ b/js/tests/game-world.test.mjs @@ -208,6 +208,33 @@ test('refused handoff returns to the source with the same Hello, then falls back client2.close(); }); +test('handoff holds the predicted entity until the target binds it (no source copy)', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + network.onMessage = (conn, m) => { + if (m.type === 'Hello') conn.send(welcome({ zoneId: conn.zoneId })); + }; + const client = handoffClient(network, scheduler); + await client.connect('z1'); + network.last('z1').send(delta({ creates: [avatar(1, 5)] })); + const own = () => client.render().filter((e) => e.id === 1); + assert.deepEqual(own().map((e) => [e.key, e.predicted]), [['z1:1', true]]); + + network.last('z1').send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:t1' }); + await scheduler.advance(10); + assert.equal(client.authority.zoneId, 'z2'); + // Welcomed by z2 but no Delta yet: one frozen predicted copy, not the + // source's interpolated (older) one. + const held = own(); + assert.deepEqual(held.map((e) => [e.key, e.predicted, e.stale]), [['z1:1', true, false]]); + assert.ok(Math.abs(held[0].fields.x - 5) < 1e-3, 'held at the last predicted position'); + + network.last('z2').send(delta({ creates: [avatar(1, 5.5)] })); + network.last('z1').send(delta({ serverTick: 101, updates: [] })); + assert.deepEqual(own().map((e) => [e.key, e.predicted]), [['z2:1', true]]); + client.close(); +}); + test('a silent handoff target times out into the return path', async () => { const network = new FakeNetwork(); const scheduler = new FakeScheduler(); From 50c45c84a724796eb1e29065ed32aa9a2bf2400d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 22:43:28 -0500 Subject: [PATCH 177/484] docs(game): add a guide to the distributed_game README Overview, concepts, life of a tick, demos, a zone walkthrough, guides per system, design decisions and status, ahead of the API reference. Links the engine from the root README. --- README.md | 12 ++ distributed_game/README.md | 418 ++++++++++++++++++++++++++++++++++--- 2 files changed, 401 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index baa4450bd..ca528c63c 100644 --- a/README.md +++ b/README.md @@ -544,6 +544,18 @@ that scope the client replica. --- +## Multiplayer games + +`distributed_game` adds a server-authoritative realtime engine on top of +this framework: zones that tick at a fixed rate, binary delta replication +with interest management, client prediction (`@hops-ops/distributed/game`), +outcomes saved as idempotent commands on cells without ever pausing the +game, and zones spread across servers with handoff, hibernation and live +content updates. Start with **[`distributed_game/README.md`](distributed_game/README.md)**; +seven runnable demos are in [`examples/game`](examples/game/README.md). + +--- + ## See it run ### e2e-ui playground (`tests/e2e-ui`) diff --git a/distributed_game/README.md b/distributed_game/README.md index 854304862..f4d6fe2c4 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -1,27 +1,116 @@ # distributed_game -Authoritative multiplayer zone runtime for the `distributed` CQRS/ES -framework. A game implements [`Zone`]; [`ZoneHost`] runs it with a fixed -timestep, activity tiers, sequenced inputs, timers, seeded RNG, -non-blocking durable facts and interest-managed binary replication. The -optional `net` feature serves many zones over WebSockets. - -Physics is out of scope: bring your own and step it in `on_tick`. +A server-authoritative multiplayer game engine for the `distributed` +framework. You write the rules of a piece of your world (a **zone**) as a +plain Rust struct. The engine runs it at a fixed tick rate, takes player +input, sends each player only the changes they can see, saves important +outcomes without ever pausing the game, and spreads zones across as many +server processes as you need. A TypeScript client SDK +(`@hops-ops/distributed/game`) connects browsers to it, with prediction and +smoothing built in. + +It replaces the role a room server like Colyseus plays, but in Rust and on +the same event-sourced storage the rest of `distributed` uses. + +**It is:** the authoritative simulation loop, networking, replication, +persistence of outcomes, and world layout across servers. + +**It is not:** a renderer, a physics engine or a content pipeline. Bring +your own physics and step it inside `on_tick`. The demos use Babylon.js in +the browser, but the client SDK has no rendering dependency. + +## Contents + +- [The big picture](#the-big-picture) +- [Try it](#try-it) +- [Build a zone](#build-a-zone) +- [Guides](#guides): game loop · input · what clients see · the client SDK · + saving progress · scaling out · live updates · lag compensation · + testing and operations · security +- [Design decisions](#design-decisions) +- [Status and limits](#status-and-limits) +- [Reference](#reference) + +## The big picture + +```mermaid +flowchart LR + subgraph Browser + C[GameClient
    prediction + interpolation] + end + subgraph "Game server process (GameServer)" + H1[ZoneHost: town] --- Z1[your Zone code] + H2[ZoneHost: dungeon-1] --- Z2[your Zone code] + W[fact worker] + end + subgraph Storage + CELL[(player cells
    SQLite / Workers)] + SNAP[(hibernation
    snapshots)] + end + C -- "binary WebSocket: inputs" --> H1 + H1 -- "deltas, events" --> C + Z1 -- "facts (never awaited)" --> W + W -- "idempotent commands" --> CELL + H2 -. "sleep when empty" .-> SNAP +``` -## Features +The words used throughout: -| Feature | Adds | Deps | +| Term | Meaning | +|---|---| +| **Zone** | One piece of the world with its own rules and state: a room, an arena, a dungeon floor, a 32 m map cell. Your code implements the `Zone` trait. Zones are the unit of simulation, ownership and scaling. | +| **ZoneHost** | Runs one zone: the fixed-timestep loop, connected clients, input queues, timers, replication. Has no networking of its own, so it is easy to test with a `ManualClock`. | +| **GameServer** | (`net` feature) A WebSocket server hosting many zones, creating them on demand, routing players, and serving `/metrics` and admin routes. | +| **Tick** | One fixed simulation step (30 Hz by default). Separate from the **patch** rate (20 Hz by default), how often clients get updates. | +| **Player / Observer** | A *player* controls something and sends inputs. An *observer* only watches: a spectator, a leaderboard page, or a client looking into the zone next door. | +| **Entity** | Something clients can see. The zone describes its entities each patch; the engine works out what changed for each client. | +| **Schema** | The kinds of entity and their fields (with quantization). Sent to clients on connect, so clients need no generated code. | +| **Fact** | An outcome worth keeping ("Alice killed the elite, +60 XP"). The zone emits it and moves on; a background worker commits it to storage and reports back later. | +| **Cell** | Durable, event-sourced state in `distributed`, for example one player's profile. Facts usually end up as commands on a cell. | +| **Ticket** | A signed, single-use admission token naming the player (principal), the zone and a role. Identity always comes from the ticket, never from game input. | + +### The life of a tick + +1. Inputs arrive over the socket. Each is numbered; the host drops + duplicates and stale ones, decodes them with `Zone::decode_input`, and + checks them with `Zone::sanitize_input`. +2. The host calls `Zone::on_tick`. Your code reads inputs with + `ctx.take_inputs`, moves things, resolves combat, and may emit facts, + events, timers or a handoff. +3. On patch ticks the host calls `Zone::replicate`. For each client it + compares what you described with what that client last received, keeps + only what the client can see (interest), fits it into the client's byte + budget (most important first), and sends one binary **Delta** with the + number of the last input it processed. +4. The browser applies the Delta. Other entities are drawn slightly in the + past (interpolated) so they move smoothly. The player's own character is + predicted from their inputs and quietly corrected when the server + disagrees. +5. Meanwhile, emitted facts are committed by the fact worker. When one + settles, `Zone::on_fact_settled` runs on a later tick (to show + "saved ✓", for example). The tick never waits for storage. + +## Try it + +Seven runnable demos live in [`examples/game`](../examples/game/README.md), +each built to show one part of the engine: + +| Demo | Run | Shows | |---|---|---| -| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | -| `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | -| `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | -| `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | -| `net` | `net::GameServer` (axum WebSocket), HMAC tickets, `GET /metrics` (implies `metrics`), handoff, admin peer routes, `WorldCoordinator` | `axum`, `hmac`, `sha2`, `base64`, `tokio` | -| `bots` | `bots` load-test client library + `game-bots` binary | `net` + `tokio-tungstenite` | -| `lease` | `world::FencedLeaseOwnership` over `distributed::lease` | `distributed` | -| `sqlite` | `world::SqliteZoneStateStore` (hibernation snapshots) | `rusqlite` (bundled) | +| Arena | `examples/game/run.sh arena` | ticks, deltas, prediction on/off, interest radius vs. global entities, simulated latency | +| Mob Pit | `run.sh mobpit` | combat whose rewards are saved without stalling; "slow storage"; `kill -9` crash recovery | +| Leaderboard | `run.sh leaderboard` | a live ranking fed from saved kills, rebuilt from history | +| Shooting Gallery | `run.sh gallery` | lag compensation on/off under latency | +| The Freeze | `run.sh freeze` | pausing every zone on two servers, updating content, resuming; safe-room reloads | +| Endless Grid | `run.sh grid` | a generated world split into zones across two servers, seamless border crossings, zones sleeping and waking | +| Boss Ripple | `run.sh ripple` | nested zones (realm › city › borough › neighbourhood) with events travelling up | + +Then open `http://localhost:5173//`. Each page explains what to try. -## Minimal zone +## Build a zone + +A zone is a struct plus a few trait methods. This one is a dot that +players push left and right: ```rust use std::sync::Arc; @@ -35,6 +124,7 @@ impl Zone for Room { type Input = i8; // -1, 0, 1 type Timer = (); + // What clients can see: one kind, "dot", with a quantized x. fn schema() -> EntitySchema { EntitySchema::new().kind( KindDef::new(1, "dot") @@ -44,14 +134,15 @@ impl Zone for Room { fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { Room { x: 0.0 } } + // Bytes from the client → your input type. Never trust them: fn decode_input(&self, _p: PlayerId, bytes: &[u8]) -> Option { bytes.first().map(|b| *b as i8) } - fn sanitize_input(&self, _p: PlayerId, dx: i8) -> Option { (-1..=1).contains(&dx).then_some(dx) } + // The game rules, once per tick. fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { let players: Vec<_> = ctx.players().map(|p| p.id).collect(); for p in players { @@ -61,11 +152,13 @@ impl Zone for Room { } } + // Describe the world; the engine diffs it per client. fn replicate(&self, out: &mut WorldView) { out.push(EntityState::new(1, 1, self.x, 0.0, vec![FieldValue::F(self.x)])); } } +// Drive it directly (tests, tools) with a manual clock: let clock = ManualClock::new(); let mut host = ZoneHost::::new("room-1", HostConfig::default(), Arc::new(clock.clone()), ()); let claims = TicketClaims::new("alice", "room-1", u64::MAX, "n", Role::Player); @@ -73,20 +166,293 @@ let joined = host.join(&claims, 0, "").unwrap(); host.push_input(joined.client, 1, 0, &[1]); clock.advance(Duration::from_millis(100)); host.advance(); -for out in host.drain_outbound() { /* send Outbound::Frame bytes to the client */ } +for out in host.drain_outbound() { /* Outbound::Frame bytes go to the client */ } ``` -Serving it (`net`): +Serve it over WebSockets (`net` feature). The closure decides which zone +ids this server hosts and with what config: ```rust,ignore let server = GameServer::::new(ServerConfig::new(TicketKey::new(secret)), |zone_id| { zone_id.starts_with("room-").then_some(()) }); server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_signal).await?; -// or merge app routes (lobby, health, dev tools) with the same graceful shutdown: -// server.serve_with(listener, axum::Router::new().route("/healthz", get(ok)), signal).await?; ``` +Connect a browser: + +```ts +import { GameClient, InputPacer } from '@hops-ops/distributed/game'; + +const game = new GameClient({ + url: (zone) => `wss://game.example/zones/${zone}`, + ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role), // your backend signs these + prediction: { + encodeInput: (dx) => new Uint8Array([dx & 0xff]), + predict: (s, dx, dtMs) => ({ x: s.x + (dx * 5 * dtMs) / 1000 }), // same rule as on_tick + controlledEntity: () => 1 + } +}); +await game.connect('room-1'); +const pacer = new InputPacer({ tickRate: () => game.authority?.connection.welcome?.tickRate }); +requestAnimationFrame(function frame(now) { + pacer.update(now, (dtMs) => game.sendInput(readKeys(), dtMs)); // one input per server tick + draw(game.render()); // entities ready to draw + requestAnimationFrame(frame); +}); +``` + +The rest of `Zone` is optional hooks: `on_auth`, `on_join`, `on_leave`, +`on_rejoin`, `on_observe`, `on_timer`, `on_fact_settled`, +`on_tier_changed`, `on_dispose`, `hibernate` / `on_restore`, +`on_handoff_join`, `on_child_event`, `is_gate`, `freeze_ready`, +`on_content_version_changed`, `record_rewind`, `state_hash`. Each is +explained in the guide that uses it. + +## Guides + +### The game loop + +`ZoneHost::advance()` runs as many fixed steps as real time requires, +capped at `HostConfig::max_catch_up` (5) so a stalled process skips ahead +instead of fast-forwarding. `ctx.dt_secs()` is always the fixed step. + +A zone is in one of three **tiers**: + +- **Hot**: someone is connected; full `tick_rate` (30 Hz). +- **Idle**: empty; ticks at `idle_tick_rate` (1 Hz) so timers and + respawns keep going. Return `true` from `Zone::wants_background` to stay + Idle forever (a city clock, say) or from `has_pending_work` to stay Hot. +- **Dormant**: idle for `dormant_after` (30 s); no ticks. With + hibernation on, a Dormant zone is saved and unloaded (see + [Scaling out](#scaling-out-many-zones-many-servers)). + +`on_tier_changed` tells you about transitions. Timers +(`ctx.set_timeout(after, value)`, `ctx.set_interval(every, value)`, +`ctx.cancel_timer(id)`) fire `on_timer` on the tick they are due; +`ctx.rng()` is a seeded RNG derived from the world seed and zone id, so a +recorded session replays identically. + +### Input + +Clients number every input. The host keeps a bounded queue per player, +rejects duplicates and inputs older than the last processed one, and +reports the last processed number back in every Delta. The client uses +that to drop inputs the server has already applied when it reconciles. + +- `decode_input` turns bytes into your type; `sanitize_input` rejects or + clamps anything a cheater could send (speed hacks, out-of-range values). +- `ctx.take_inputs(player, ConsumePolicy::…)` reads them in `on_tick`. + `InputCredits` allows one input per tick per player (with a small bank + for network jitter), so flooding inputs cannot make anyone move faster. +- Every new connection (a fresh ticket, a reconnect token, or a reconnect + after a content reload) starts its numbering again from 1, and so does + the host. +- A player who reconnects with a fresh ticket while still in the zone + gets `on_rejoin`, by default `on_leave(Rejoined)` then `on_join`, so the + zone re-sends whatever a new client needs. +- While the world is frozen for an update, inputs are dropped and counted. + +### What each client sees + +Each patch, `replicate` describes every entity once, as `EntityState`s +with a position and the schema's fields. For each client the engine then +sends only the difference from what that client already has: + +- **Schema and quantization.** Fields are typed (`QuantF32`, integers, + booleans, strings, …). Floats are quantized to the precision you choose, + and a change too small to show up after quantization costs nothing. +- **Interest.** Each viewer has a `View` (centre and radius, set with + `ctx.set_view`). Entities outside it are not sent and are removed from + the client when they leave it. A spatial grid makes this cheap. Mark + entities that everyone must always see (players in a small room, a boss, + pillars) with `.global()`. +- **Bandwidth budget.** Each client has `byte_budget` bytes per Delta + (4 KiB). Creates and updates compete by priority (kind × entity × + field × nearness). Anything deferred builds up priority, so it is always + sent eventually. +- **Events** (`ctx.send_event(viewer, type_id, bytes)`, + `ctx.broadcast_event(type_id, bytes)`) carry one-off messages such as "kill", "saved" or "weather changed" next to the + Deltas. + +Wire details are in [`PROTOCOL.md`](PROTOCOL.md). + +### The client SDK + +`GameClient` (`@hops-ops/distributed/game`) handles the connection, +reconnection and clock sync, and gives you `render()`: a list of entities +ready to draw. + +- **Interpolation.** Other entities are drawn a little in the past, + between two received states, so movement is smooth whatever the network + does. The delay adapts to measured latency and jitter (`AdaptiveDelay`). +- **Prediction.** The player's own entity moves the moment they press a + key, using your `predict` function (the same rule as the server). Each + Delta, the client replays not-yet-acknowledged inputs on top of the + server's state; any difference is resolved per field (`ease`, `snap` or + `replace`). `setPredictionEnabled(false)` turns it off, to feel the raw + latency. +- **Neighbouring zones.** `observe(zone)` opens a watch-only connection, + so a player sees across a border before crossing it. +- **Crossing zones.** When the server hands the player to another zone + (possibly on another server), the client follows automatically. The + predicted character is held in place until the new zone takes over, and + if the new zone refuses, the client goes back. +- **Content reloads.** `reloadContent` is called when the server requires + a newer content version, and the client rejoins afterwards with the same + player. + +### Saving progress without pausing the game + +The rule: **the tick never waits for storage.** A slow disk or a busy +database must not freeze the world. Zones emit **facts** and continue: + +```rust,ignore +let key = ctx.fact_key("kill", &[&mob_id, &mob_generation]); +ctx.emit_fact_for(killer, Fact::new(key, "crawler.record_kill", json!({"mob": "elite"})))?; +``` + +- The host attaches the killer's **verified identity** from their ticket. + The zone cannot claim to be someone else, and the payload names no + reward amount; the storage side decides the XP from the facts it + trusts. +- A background worker commits facts with retries. + `cell::CellFactSink` turns each one into a command on that player's + cell, with a command id derived from the fact key. A retry or a + duplicate is therefore a harmless replay, never a double reward. +- `on_fact_settled` reports the outcome on a later tick. +- Keys must be unique across restarts; `ctx.fact_key` includes the + activation's boot epoch for you (see [Durable facts](#durable-facts)). +- If the process crashes, each in-flight fact is either fully saved or + not saved at all. Mob Pit shows this with `kill -9`. + +### Scaling out: many zones, many servers + +- **Placement.** A `ZoneDirectory` (`HashRing`) maps each zone id to a + host. A client that connects to the wrong host is told where to go + (`Redirect`) and follows automatically. +- **One owner at a time.** Each activation of a zone holds a fenced claim + (`ZoneOwnership`, with leases in production). Two servers never run the + same zone, and a server that loses its claim stops without saving. +- **On demand and asleep.** Zones start on first use. With + `hibernate_after`, an empty zone is saved (`Zone::hibernate`) and + unloaded, and restored (`on_restore`) the next time someone arrives. +- **Handoff.** `ctx.handoff(player, "next-zone", carried_bytes)` moves a + player to another zone, on any server, with a signed transfer ticket. + The target receives `on_handoff_join` with the carried state. When the + player's durable records must move too, emit a fact and let a + `distributed::saga` do it off the tick. +- **Hierarchy.** Zone ids like `realm.city.borough` form a tree + (`DottedTopology`). `ctx.emit_upward(…)` sends an event to the parent + zones, wherever they run, and each level can tick at its own rate + (`GameServer::with_host_config`). + +### Live content updates + +`WorldCoordinator::rollout` updates content across every server: + +1. **Freeze**: every zone pauses, shows the update notice, and drops + inputs. A zone can delay with `freeze_ready` (for example, mid-ritual). +2. **Apply**: your function switches the content version (it may be + async, a download for example). +3. **Resume**: everyone continues on the new version. Facts are stamped + with the version they happened under. + +If any zone does not acknowledge in time, the rollout is **aborted** and +everyone resumes on the old version. In `Hard` mode every client reloads +at once. In `Rolling` mode with `StalePolicy::SafeRoom`, clients that +cannot patch live keep playing until they walk into a gate zone +(`is_gate`), where they reload. + +### Lag compensation + +For hit-scan weapons, the server judges a shot against where targets were +**on the shooter's screen** when they fired, not where they are when the +shot arrives. `record_rewind` stores hit volumes each tick, and +`ctx.rewind().hit_test_shot(timing, ray, filter)` tests against that +moment, capped at `max_rewind` (500 ms by default) so lag cannot buy +unlimited rewind. + +### Testing and operations + +- **Deterministic tests**: drive `ZoneHost` with `ManualClock`; the RNG + is seeded. +- **Record and replay**: `Recorder` captures a session; `replay` re-runs + it and pinpoints the first tick that differs. +- **Metrics**: `GET /metrics` (Prometheus): tick time, players, entities, + inputs by outcome, bytes per Delta, facts pending and settled. +- **Load bots**: `game-bots` connects N WebSocket clients and reports + round-trip time and bandwidth. +- **Network simulation**: `NetSim` adds latency, jitter and loss in + development, and can be changed at runtime. + +### Security + +- Players are admitted only with a signed, single-use, expiring ticket. + Your web backend mints it; plug in your own verifier with + `with_ticket_verifier`. +- The ticket's principal is the only identity the zone sees, and the only + one attached to facts. Inputs are game data, never identity, owner or + reward amounts. +- Admin routes (transfers, tier events, rollout) need a separate shared + secret. + +## Design decisions + +- **Server-authoritative, not lockstep or peer-to-peer.** The server owns + the truth and clients predict. That tolerates cheaters and mixed + latencies, and needs only one simulation per zone. +- **Zones, not one global world loop.** A zone is the unit that ticks, + sleeps, moves between servers and is owned by exactly one process. + Actors live inside their zone. Only things that outlive a zone (a + player's profile, a match) get their own durable cell. +- **Facts, not per-tick persistence.** Movement and combat ticks are never + stored, only meaningful outcomes. The tick enqueues and moves on, so + storage speed never shows up as lag. +- **Idempotency through keys, not a zone-side outbox.** A fact key plus + the cell's command ledger make retries safe. An outbox on the zone + would add a second write per outcome for little gain, since the zone + state lost in a crash is lost either way. +- **Static world from a seed.** Terrain and props are a pure function of + seed and content version, generated identically on server and client. + Only things that change are replicated. +- **Binary protocol with the schema sent on connect.** Small, + diff-friendly frames, and any client can decode them without generated + code. +- **Reliable, ordered WebSockets.** Deltas are computed against what each + client last received, which only works because nothing is lost or + reordered. Loss shows up as delay, which the adaptive interpolation + absorbs. + +## Status and limits + +- Pre-release, on the unreleased v5 line. +- Covered by unit, integration and golden-wire tests, plus the demos' + smoke tests (bots and headless browsers). +- **Not yet verified here:** `FencedLeaseOwnership` on Postgres (Docker + was unavailable) and the Redis leaderboard against a real Redis (only a + fake). +- No production deployment or load testing beyond local bots. +- WebSocket only (no UDP or WebTransport). No built-in physics. Input + replay on the client assumes your `predict` matches `on_tick` exactly. + +--- + +# Reference + +## Features + +| Feature | Adds | Deps | +|---|---|---| +| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | +| `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | +| `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | +| `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | +| `net` | `net::GameServer` (axum WebSocket), HMAC tickets, `GET /metrics` (implies `metrics`), handoff, admin peer routes, `WorldCoordinator` | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `bots` | `bots` load-test client library + `game-bots` binary | `net` + `tokio-tungstenite` | +| `lease` | `world::FencedLeaseOwnership` over `distributed::lease` | `distributed` | +| `sqlite` | `world::SqliteZoneStateStore` (hibernation snapshots) | `rusqlite` (bundled) | + ## Durable facts Zones never await storage. Emit a fact during a tick: @@ -284,9 +650,3 @@ need no codegen. Golden fixtures for other implementations are in cargo test -p distributed_game --all-features UPDATE_GOLDEN=1 cargo test -p distributed_game --test golden # accept wire changes ``` - -## Extension seams (later phases) - -- Metrics: `AdvanceReport`, `replication::DeltaStats`, `PushOutcome`. -- Rewind/lag compensation: `SequencedInput::client_tick`, deterministic - `ZoneRng` and `ManualClock`. From c4c5daf056e2bcadd024446c0e8abe586b280a37 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:14:06 -0500 Subject: [PATCH 178/484] feat(game): add authoring derives and typed game surface Add the distributed_game_macros crate (Replicated, GameInput, GameEvent, GameRecord, FactCommand) re-exported from distributed_game, a shared typed payload codec whose scalars match entity field encodings, the versioned GameSurface manifest, typed Ctx send/broadcast and typed fact emission with restart-safe keys bound to the cell command name. --- Cargo.toml | 2 +- distributed_game/Cargo.toml | 3 + distributed_game/src/authoring.rs | 170 +++++ distributed_game/src/codec.rs | 538 ++++++++++++++ distributed_game/src/facts.rs | 55 ++ distributed_game/src/host.rs | 97 ++- distributed_game/src/lib.rs | 41 +- distributed_game/src/protocol/wire.rs | 37 + distributed_game/src/replication.rs | 4 + distributed_game/src/schema.rs | 34 + distributed_game/src/surface.rs | 258 +++++++ distributed_game/tests/authoring/main.rs | 690 ++++++++++++++++++ .../tests/fixtures/authoring.json | 545 ++++++++++++++ distributed_game/tests/zone_runtime/main.rs | 5 +- distributed_game_macros/Cargo.toml | 24 + distributed_game_macros/src/event.rs | 334 +++++++++ distributed_game_macros/src/fact.rs | 137 ++++ distributed_game_macros/src/input.rs | 145 ++++ distributed_game_macros/src/lib.rs | 85 +++ distributed_game_macros/src/replicated.rs | 194 +++++ distributed_game_macros/src/shared.rs | 405 ++++++++++ distributed_game_macros/tests/compile_fail.rs | 11 + .../tests/compile_fail/event_duplicate_id.rs | 11 + .../compile_fail/event_duplicate_id.stderr | 5 + .../tests/compile_fail/event_missing_id.rs | 10 + .../compile_fail/event_missing_id.stderr | 5 + .../tests/compile_fail/fact_identity_field.rs | 10 + .../compile_fail/fact_identity_field.stderr | 5 + .../compile_fail/fact_missing_command.rs | 8 + .../compile_fail/fact_missing_command.stderr | 5 + .../tests/compile_fail/fact_reward_field.rs | 11 + .../compile_fail/fact_reward_field.stderr | 5 + .../compile_fail/input_buttons_on_float.rs | 9 + .../input_buttons_on_float.stderr | 23 + .../compile_fail/input_unsupported_field.rs | 8 + .../input_unsupported_field.stderr | 20 + .../compile_fail/replicated_needs_kind.rs | 9 + .../compile_fail/replicated_needs_kind.stderr | 5 + .../compile_fail/replicated_needs_position.rs | 9 + .../replicated_needs_position.stderr | 5 + .../replicated_quant_on_integer.rs | 11 + .../replicated_quant_on_integer.stderr | 12 + .../replicated_unknown_correction.rs | 11 + .../replicated_unknown_correction.stderr | 5 + .../replicated_unsupported_type.rs | 11 + .../replicated_unsupported_type.stderr | 14 + 46 files changed, 4032 insertions(+), 9 deletions(-) create mode 100644 distributed_game/src/authoring.rs create mode 100644 distributed_game/src/codec.rs create mode 100644 distributed_game/src/surface.rs create mode 100644 distributed_game/tests/authoring/main.rs create mode 100644 distributed_game/tests/fixtures/authoring.json create mode 100644 distributed_game_macros/Cargo.toml create mode 100644 distributed_game_macros/src/event.rs create mode 100644 distributed_game_macros/src/fact.rs create mode 100644 distributed_game_macros/src/input.rs create mode 100644 distributed_game_macros/src/lib.rs create mode 100644 distributed_game_macros/src/replicated.rs create mode 100644 distributed_game_macros/src/shared.rs create mode 100644 distributed_game_macros/tests/compile_fail.rs create mode 100644 distributed_game_macros/tests/compile_fail/event_duplicate_id.rs create mode 100644 distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr create mode 100644 distributed_game_macros/tests/compile_fail/event_missing_id.rs create mode 100644 distributed_game_macros/tests/compile_fail/event_missing_id.stderr create mode 100644 distributed_game_macros/tests/compile_fail/fact_identity_field.rs create mode 100644 distributed_game_macros/tests/compile_fail/fact_identity_field.stderr create mode 100644 distributed_game_macros/tests/compile_fail/fact_missing_command.rs create mode 100644 distributed_game_macros/tests/compile_fail/fact_missing_command.stderr create mode 100644 distributed_game_macros/tests/compile_fail/fact_reward_field.rs create mode 100644 distributed_game_macros/tests/compile_fail/fact_reward_field.stderr create mode 100644 distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs create mode 100644 distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr create mode 100644 distributed_game_macros/tests/compile_fail/input_unsupported_field.rs create mode 100644 distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr create mode 100644 distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs create mode 100644 distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr create mode 100644 distributed_game_macros/tests/compile_fail/replicated_needs_position.rs create mode 100644 distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr create mode 100644 distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs create mode 100644 distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr create mode 100644 distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs create mode 100644 distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr create mode 100644 distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs create mode 100644 distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr diff --git a/Cargo.toml b/Cargo.toml index 0903c0abd..d6793212e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["distributed_macros", "distributed_cli", "distributed_game"] +members = ["distributed_macros", "distributed_cli", "distributed_game", "distributed_game_macros"] exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker", "examples/game/server"] resolver = "2" diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 817b10e47..e9665bb55 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -28,6 +28,8 @@ lease = ["dep:distributed"] sqlite = ["dep:rusqlite"] [dependencies] +distributed_game_macros = { version = "0.1.0", path = "../distributed_game_macros" } +serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", default-features = false, features = ["rt", "sync", "time"], optional = true } distributed = { path = "..", default-features = false, optional = true } @@ -40,6 +42,7 @@ futures-util = { version = "0.3", default-features = false, features = ["sink", rusqlite = { version = "0.39", features = ["bundled"], optional = true } [dev-dependencies] +trybuild = "=1.0.120" tokio = { version = "1", features = ["full", "test-util"] } tokio-tungstenite = "0.30" futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } diff --git a/distributed_game/src/authoring.rs b/distributed_game/src/authoring.rs new file mode 100644 index 000000000..95e89b0ac --- /dev/null +++ b/distributed_game/src/authoring.rs @@ -0,0 +1,170 @@ +//! Traits implemented by the authoring derives (`distributed_game_macros`, +//! re-exported from this crate): [`Replicated`] views, [`GameInput`] frames +//! and [`GameEvent`] messages. Implement them by hand only when a derive does +//! not fit; the derives keep the schema, the encoding and the surface in one +//! declaration so they cannot drift. + +use crate::codec::Wire; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::replication::{EntityState, WorldView}; +use crate::schema::{FieldValue, KindDef}; +use crate::surface::{EventSurface, InputSurface, RecordSurface}; + +/// A struct describing one replicated entity kind (`#[derive(Replicated)]`). +/// +/// The derive generates the [`KindDef`] and the field values from the same +/// field list, so the schema order and the encoding order cannot drift. +pub trait Replicated { + /// Kind id. + const KIND_ID: u16; + /// Kind name. + const KIND_NAME: &'static str; + /// Every entity of this kind is visible to every client by default. + const GLOBAL: bool; + + /// The kind definition (field names, wire types, priorities, client + /// correction defaults). + fn kind_def() -> KindDef; + + /// Interest-plane position (the `x` / `y` fields unless overridden). + fn position(&self) -> (f32, f32); + + /// Field values in schema order. + fn field_values(&self) -> Vec; + + /// The entity for a [`WorldView`]. + fn entity(&self, id: u32) -> EntityState { + let (x, y) = self.position(); + let mut entity = EntityState::new(id, Self::KIND_ID, x, y, self.field_values()); + entity.global = Self::GLOBAL; + entity + } +} + +/// Builds an [`EntitySchema`](crate::EntitySchema) from `Replicated` view +/// types, in order: `schema![PlayerView, DroneView]`. +#[macro_export] +macro_rules! schema { + ($($kind:ty),* $(,)?) => { + $crate::EntitySchema::new() + $(.kind(<$kind as $crate::Replicated>::kind_def()))* + }; +} + +/// Handle to an entity just pushed with [`WorldView::add`]. +#[derive(Debug)] +pub struct Pushed<'a>(&'a mut EntityState); + +impl Pushed<'_> { + /// Visible to every client regardless of view. + pub fn global(self) -> Self { + self.0.global = true; + self + } + + /// Only within views (overrides a `global` kind). + pub fn local(self) -> Self { + self.0.global = false; + self + } + + /// Priority multiplier for this entity. + pub fn priority(self, p: f32) -> Self { + self.0.priority = p; + self + } + + /// Interest-plane position override. + pub fn at(self, x: f32, y: f32) -> Self { + self.0.x = x; + self.0.y = y; + self + } +} + +impl WorldView { + /// Push entity `id` described by a `Replicated` view. + pub fn add(&mut self, id: u32, view: &R) -> Pushed<'_> { + self.push(view.entity(id)); + Pushed(self.last_mut().expect("just pushed")) + } +} + +/// A compact binary input frame (`#[derive(GameInput)]`). +/// +/// [`from_payload`](Self::from_payload) decodes **and sanitizes**, so a +/// zone's `decode_input` is a one-liner: +/// +/// ```ignore +/// fn decode_input(&self, _: PlayerId, payload: &[u8]) -> Option { +/// MoveInput::from_payload(payload) +/// } +/// ``` +pub trait GameInput: Sized { + /// Field layout (pushes any records it mentions). + fn input_surface(records: &mut Vec) -> InputSurface; + /// Append the raw encoding (no sanitizing). + fn encode_input(&self, w: &mut Writer); + /// Decode without sanitizing. + fn decode_input(r: &mut Reader<'_>) -> Result; + /// Clamp `#[range]` fields, clear unknown `#[buttons]` bits, reject + /// non-finite floats (`None` drops the input). + fn sanitize(self) -> Option; + + /// Encoded payload bytes. + fn to_payload(&self) -> Vec { + let mut w = Writer::new(); + self.encode_input(&mut w); + w.into_bytes() + } + + /// Decode exactly one frame (trailing bytes reject) and sanitize it. + fn from_payload(payload: &[u8]) -> Option { + let mut r = Reader::new(payload); + let input = Self::decode_input(&mut r).ok()?; + r.finish().ok()?; + input.sanitize() + } +} + +/// A reliable zone event with a stable type id (`#[derive(GameEvent)]` on a +/// struct, or on an enum whose variants are the zone's events). +/// +/// Send with [`Ctx::send`](crate::Ctx::send) / +/// [`Ctx::broadcast`](crate::Ctx::broadcast). +pub trait GameEvent: Sized { + /// Type id of this value. + fn event_id(&self) -> u32; + /// Append the payload encoding. + fn encode_payload(&self, w: &mut Writer); + /// Decode an Event message: `Ok(None)` when `type_id` is not one of + /// this type's events. + fn decode_event(type_id: u32, payload: &[u8]) -> Result, DecodeError>; + /// Every event this type declares (pushes any records they mention). + fn event_surfaces(records: &mut Vec) -> Vec; + + /// Encoded payload bytes. + fn to_payload(&self) -> Vec { + let mut w = Writer::new(); + self.encode_payload(&mut w); + w.into_bytes() + } +} + +/// Decode a whole event payload as `T` (generated code). +#[doc(hidden)] +pub fn decode_whole( + payload: &[u8], + decode: impl FnOnce(&mut Reader<'_>) -> Result, +) -> Result { + let mut r = Reader::new(payload); + let value = decode(&mut r)?; + r.finish()?; + Ok(value) +} + +/// Push `T`'s records (generated code). +#[doc(hidden)] +pub fn records_of(out: &mut Vec) { + T::records(out); +} diff --git a/distributed_game/src/codec.rs b/distributed_game/src/codec.rs new file mode 100644 index 000000000..f7c7bd963 --- /dev/null +++ b/distributed_game/src/codec.rs @@ -0,0 +1,538 @@ +//! Typed payload codec behind the authoring derives. +//! +//! Entity fields, inputs and events all use **one** value codec. Its scalar +//! encodings are exactly the entity [`FieldType`] encodings (`PROTOCOL.md` +//! §4), so a value means the same bytes whether it is replicated, sent as an +//! input or carried in an event. Payloads (inputs, events) may additionally +//! use types an entity field cannot: `i8`, `i16`, `u64`, `f64`, long +//! strings, lists, options and nested records. +//! +//! | Rust | [`WireType`] | bytes | +//! |---|---|---| +//! | `bool` | `bool` | `u8` 0/1 | +//! | `u8` / `i8` | `u8` / `i8` | one byte (two's complement for `i8`) | +//! | `u16` / `u32` | `u16` / `u32` | varuint (`u16` checked ≤ 65535) | +//! | `i16` / `i32` | `i16` / `i32` | zigzag varint (`i16` range-checked) | +//! | `u64` | `u64` | varuint up to `2^53 - 1` (saturating; exact in JS) | +//! | `f32` / `f64` | `f32` / `f64` | binary32 / binary64 LE | +//! | `f32` + `#[quant(..)]` | `quant` | varuint (§4.1) | +//! | `f32` + `#[angle(..)]` | `angle` | varuint (§4.2) | +//! | `String` | `short_str` | `u8` length + UTF-8 (truncated to 255 bytes) | +//! | `String` + `#[long]` | `str` | varuint length + UTF-8 | +//! | `Vec` | `bytes` | varuint length + bytes | +//! | `Vec` | `list` | varuint count + items | +//! | `Option` | `optional` | `u8` 0 (none) / 1 + value | +//! | `#[derive(GameRecord)]` struct | `record` | fields in declaration order | +//! +//! The derives in `distributed_game_macros` generate the calls; use this +//! module directly only for hand-written payloads. + +use serde::{Deserialize, Serialize}; + +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::schema::{FieldType, FieldValue}; +use crate::surface::RecordSurface; + +/// Wire type of one payload or entity field, as exported in the +/// [`GameSurface`](crate::surface::GameSurface). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum WireType { + /// `u8` 0/1. + Bool, + /// One byte. + U8, + /// One byte, two's complement. + I8, + /// varuint ≤ 65535. + U16, + /// zigzag varint in `i16` range. + I16, + /// varuint. + U32, + /// zigzag varint. + I32, + /// varuint up to `2^53 - 1`. + U64, + /// binary32 LE. + F32, + /// binary64 LE. + F64, + /// Clamped linear quantization (`FieldType::QuantF32`). + Quant { + /// Lower bound. + min: f32, + /// Upper bound. + max: f32, + /// Precision in bits (1..=32). + bits: u8, + }, + /// Wrapped angle quantization (`FieldType::Angle`). + Angle { + /// Precision in bits (1..=32). + bits: u8, + }, + /// `u8` length + UTF-8. + ShortStr, + /// varuint length + UTF-8. + Str, + /// varuint length + bytes. + Bytes, + /// varuint count + items. + List { + /// Item type. + item: Box, + }, + /// `u8` presence + value. + Optional { + /// Value type. + item: Box, + }, + /// A named record (see the surface's `records`). + Record { + /// Record name (the Rust type name). + name: String, + }, +} + +impl WireType { + /// The equivalent entity [`FieldType`], if this type can be replicated. + pub fn field_type(&self) -> Option { + Some(match self { + Self::Bool => FieldType::Bool, + Self::U8 => FieldType::U8, + Self::U16 => FieldType::U16, + Self::U32 => FieldType::U32, + Self::I32 => FieldType::I32, + Self::F32 => FieldType::F32, + Self::Quant { min, max, bits } => FieldType::QuantF32 { + min: *min, + max: *max, + bits: *bits, + }, + Self::Angle { bits } => FieldType::Angle { bits: *bits }, + Self::ShortStr => FieldType::ShortStr, + Self::Bytes => FieldType::Bytes, + _ => return None, + }) + } + + /// The payload type of an entity field type. + pub fn of_field(ty: FieldType) -> Self { + match ty { + FieldType::Bool => Self::Bool, + FieldType::U8 => Self::U8, + FieldType::U16 => Self::U16, + FieldType::U32 => Self::U32, + FieldType::I32 => Self::I32, + FieldType::F32 => Self::F32, + FieldType::QuantF32 { min, max, bits } => Self::Quant { min, max, bits }, + FieldType::Angle { bits } => Self::Angle { bits }, + FieldType::ShortStr => Self::ShortStr, + FieldType::Bytes => Self::Bytes, + } + } +} + +/// A Rust type with a default payload encoding (see the module table). +/// +/// Implemented for the scalar types, `String`, `Vec`, `Option`, and by +/// `#[derive(GameRecord)]` / `#[derive(GameEvent)]` for structs. +#[diagnostic::on_unimplemented( + message = "`{Self}` has no game payload encoding", + label = "unsupported payload field type", + note = "supported: bool, u8, i8, u16, i16, u32, i32, u64, f32, f64, String, Vec, Option and `#[derive(GameRecord)]` structs" +)] +pub trait Wire: Sized { + /// Wire type descriptor. + fn wire_type() -> WireType; + /// Append the encoding. + fn encode(&self, w: &mut Writer); + /// Decode one value. + fn decode(r: &mut Reader<'_>) -> Result; + /// Push the definitions of every record this type mentions (itself + /// included), depth first; duplicates are removed by the surface. + fn records(_out: &mut Vec) {} +} + +macro_rules! wire_scalar { + ($ty:ty, $wire:ident, |$w:ident, $v:ident| $enc:expr, |$r:ident| $dec:expr) => { + impl Wire for $ty { + fn wire_type() -> WireType { + WireType::$wire + } + fn encode(&self, $w: &mut Writer) { + let $v = *self; + $enc; + } + fn decode($r: &mut Reader<'_>) -> Result { + $dec + } + } + }; +} + +wire_scalar!(bool, Bool, |w, v| w.bool(v), |r| r.bool()); +wire_scalar!(u8, U8, |w, v| w.u8(v), |r| r.u8()); +wire_scalar!(i8, I8, |w, v| w.u8(v as u8), |r| Ok(r.u8()? as i8)); +wire_scalar!(u16, U16, |w, v| w.varuint(u32::from(v)), |r| { + u16::try_from(r.varuint()?).map_err(|_| DecodeError::Invalid("u16 out of range")) +}); +wire_scalar!(i16, I16, |w, v| w.varint(i32::from(v)), |r| { + i16::try_from(r.varint()?).map_err(|_| DecodeError::Invalid("i16 out of range")) +}); +wire_scalar!(u32, U32, |w, v| w.varuint(v), |r| r.varuint()); +wire_scalar!(i32, I32, |w, v| w.varint(v), |r| r.varint()); +wire_scalar!(u64, U64, |w, v| w.varuint64(v), |r| r.varuint64()); +wire_scalar!(f32, F32, |w, v| w.f32(v), |r| r.f32()); +wire_scalar!(f64, F64, |w, v| w.f64(v), |r| r.f64()); + +impl Wire for String { + fn wire_type() -> WireType { + WireType::ShortStr + } + fn encode(&self, w: &mut Writer) { + w.short_string(self); + } + fn decode(r: &mut Reader<'_>) -> Result { + r.short_string() + } +} + +impl Wire for Vec { + fn wire_type() -> WireType { + WireType::List { + item: Box::new(T::wire_type()), + } + } + fn encode(&self, w: &mut Writer) { + w.varuint(u32::try_from(self.len()).unwrap_or(u32::MAX)); + for item in self { + item.encode(w); + } + } + fn decode(r: &mut Reader<'_>) -> Result { + let count = r.varuint()? as usize; + // Every item takes at least one byte: bound the allocation. + if count > r.remaining() { + return Err(DecodeError::UnexpectedEof); + } + let mut out = Vec::with_capacity(count); + for _ in 0..count { + out.push(T::decode(r)?); + } + Ok(out) + } + fn records(out: &mut Vec) { + T::records(out); + } +} + +impl Wire for Option { + fn wire_type() -> WireType { + WireType::Optional { + item: Box::new(T::wire_type()), + } + } + fn encode(&self, w: &mut Writer) { + match self { + None => { + w.u8(0); + } + Some(value) => { + w.u8(1); + value.encode(w); + } + } + } + fn decode(r: &mut Reader<'_>) -> Result { + match r.u8()? { + 0 => Ok(None), + 1 => Ok(Some(T::decode(r)?)), + _ => Err(DecodeError::Invalid("option tag must be 0 or 1")), + } + } + fn records(out: &mut Vec) { + T::records(out); + } +} + +/// `#[quant(..)]` / `#[angle(..)]` / `#[long]` field encodings (used by the +/// generated code). +pub mod special { + use super::*; + + /// An `f32` encoded as entity field type `ty` (quantized or angle). + pub fn encode_f32(w: &mut Writer, ty: FieldType, v: f32) { + ty.encode(w, &FieldValue::F(v)); + } + + /// Inverse of [`encode_f32`] (range-checked). + pub fn decode_f32(r: &mut Reader<'_>, ty: FieldType) -> Result { + match ty.decode(r)? { + FieldValue::F(v) => Ok(v), + _ => Err(DecodeError::Invalid("expected a float field type")), + } + } + + /// varuint-length string (`#[long]`). + pub fn encode_long(w: &mut Writer, v: &str) { + w.string(v); + } + + /// Inverse of [`encode_long`]. + pub fn decode_long(r: &mut Reader<'_>) -> Result { + r.string() + } +} + +/// Encode a whole value into a fresh buffer. +pub fn to_bytes(value: &T) -> Vec { + let mut w = Writer::new(); + value.encode(&mut w); + w.into_bytes() +} + +/// Decode a whole value; trailing bytes are an error. +pub fn from_bytes(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let value = T::decode(&mut r)?; + r.finish()?; + Ok(value) +} + +/// A Rust type usable as a replicated entity field (`#[derive(Replicated)]`). +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be a replicated entity field", + label = "unsupported entity field type", + note = "supported: bool, u8, u16, u32, i32, f32 (optionally #[quant]/#[angle]), String (short_str) and Vec (bytes)" +)] +pub trait EntityField { + /// Default wire type (overridden by `#[quant]` / `#[angle]` on `f32`). + const FIELD_TYPE: FieldType; + /// This value as a [`FieldValue`]. + fn to_field_value(&self) -> FieldValue; +} + +macro_rules! entity_field { + ($ty:ty, $ft:expr, |$v:ident| $value:expr) => { + impl EntityField for $ty { + const FIELD_TYPE: FieldType = $ft; + fn to_field_value(&self) -> FieldValue { + let $v = self; + $value + } + } + }; +} + +entity_field!(bool, FieldType::Bool, |v| FieldValue::Bool(*v)); +entity_field!(u8, FieldType::U8, |v| FieldValue::U(u32::from(*v))); +entity_field!(u16, FieldType::U16, |v| FieldValue::U(u32::from(*v))); +entity_field!(u32, FieldType::U32, |v| FieldValue::U(*v)); +entity_field!(i32, FieldType::I32, |v| FieldValue::I(*v)); +entity_field!(f32, FieldType::F32, |v| FieldValue::F(*v)); +entity_field!(String, FieldType::ShortStr, |v| FieldValue::Str(v.clone())); +entity_field!(Vec, FieldType::Bytes, |v| FieldValue::Bytes(v.clone())); + +/// Marker: a field type that accepts `#[quant(..)]` / `#[angle(..)]`. +#[diagnostic::on_unimplemented( + message = "`#[quant]` / `#[angle]` need an `f32` field, not `{Self}`", + label = "quantize an f32" +)] +pub trait QuantizedF32 { + /// The value. + fn get(&self) -> f32; + /// From a decoded value. + fn from_f32(v: f32) -> Self; +} + +impl QuantizedF32 for f32 { + fn get(&self) -> f32 { + *self + } + fn from_f32(v: f32) -> Self { + v + } +} + +/// Marker: a field type that accepts `#[long]`. +#[diagnostic::on_unimplemented( + message = "`#[long]` needs a `String` field, not `{Self}`", + label = "long strings are Strings" +)] +pub trait LongString { + /// The text. + fn text(&self) -> &str; + /// From decoded text. + fn from_text(v: String) -> Self; +} + +impl LongString for String { + fn text(&self) -> &str { + self + } + fn from_text(v: String) -> Self { + v + } +} + +/// A scalar usable in a `#[derive(GameInput)]` struct, and how its +/// `#[range(..)]` clamps. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be a game input field", + label = "unsupported input field type", + note = "inputs are small fixed scalars: bool, u8, i8, u16, i16, u32, i32 or f32 (optionally #[quant]/#[angle])" +)] +pub trait InputField: Wire + Copy { + /// Clamp into `[min, max]` (given as `f64`); `None` rejects the input + /// (non-finite floats). + fn sanitize_range(self, min: f64, max: f64) -> Option; + /// Validity without a range (floats must be finite). + fn sanitize_plain(self) -> Option { + Some(self) + } +} + +macro_rules! input_int { + ($($ty:ty),*) => {$( + impl InputField for $ty { + fn sanitize_range(self, min: f64, max: f64) -> Option { + Some((self as f64).clamp(min, max) as $ty) + } + } + )*}; +} + +input_int!(u8, i8, u16, i16, u32, i32); + +impl InputField for bool { + fn sanitize_range(self, _min: f64, _max: f64) -> Option { + Some(self) + } +} + +impl InputField for f32 { + fn sanitize_range(self, min: f64, max: f64) -> Option { + self.is_finite() + .then(|| f64::from(self).clamp(min, max) as f32) + } + fn sanitize_plain(self) -> Option { + self.is_finite().then_some(self) + } +} + +/// A bit-flag field (`#[buttons(..)]`): unknown bits are cleared. +#[diagnostic::on_unimplemented( + message = "`#[buttons]` needs a u8, u16 or u32 field, not `{Self}`", + label = "button bits live in an unsigned integer" +)] +pub trait ButtonBits: Copy { + /// Keep only the bits of `mask`. + fn mask(self, mask: u32) -> Self; +} + +macro_rules! button_bits { + ($($ty:ty),*) => {$( + impl ButtonBits for $ty { + fn mask(self, mask: u32) -> Self { + (u32::from(self) & mask) as $ty + } + } + )*}; +} + +button_bits!(u8, u16, u32); + +#[cfg(test)] +mod tests { + use super::*; + + fn field_bytes(ty: FieldType, value: &FieldValue) -> Vec { + let mut w = Writer::new(); + ty.encode(&mut w, value); + w.into_bytes() + } + + #[test] + fn scalars_match_entity_field_encodings() { + for (bytes, field) in [ + ( + to_bytes(&true), + field_bytes(FieldType::Bool, &FieldValue::Bool(true)), + ), + ( + to_bytes(&200u8), + field_bytes(FieldType::U8, &FieldValue::U(200)), + ), + ( + to_bytes(&300u16), + field_bytes(FieldType::U16, &FieldValue::U(300)), + ), + ( + to_bytes(&70_000u32), + field_bytes(FieldType::U32, &FieldValue::U(70_000)), + ), + ( + to_bytes(&-5i32), + field_bytes(FieldType::I32, &FieldValue::I(-5)), + ), + ( + to_bytes(&1.5f32), + field_bytes(FieldType::F32, &FieldValue::F(1.5)), + ), + ( + to_bytes(&"hé".to_string()), + field_bytes(FieldType::ShortStr, &FieldValue::Str("hé".into())), + ), + ] { + assert_eq!(bytes, field); + } + } + + #[test] + fn composite_types_round_trip() { + let value: (Vec>, u64) = (vec![Some(-128), None, Some(127)], (1 << 53) - 1); + let mut w = Writer::new(); + value.0.encode(&mut w); + value.1.encode(&mut w); + let bytes = w.into_bytes(); + let mut r = Reader::new(&bytes); + assert_eq!(Vec::>::decode(&mut r).unwrap(), value.0); + assert_eq!(u64::decode(&mut r).unwrap(), value.1); + r.finish().unwrap(); + // u64 saturates at 2^53 - 1 so JavaScript decodes it exactly. + assert_eq!( + from_bytes::(&to_bytes(&u64::MAX)).unwrap(), + (1 << 53) - 1 + ); + assert!(from_bytes::(&to_bytes(&70_000u32)).is_err()); + assert!(from_bytes::>(&[2]).is_err()); + assert!(from_bytes::>(&[200]).is_err()); + } + + #[test] + fn input_ranges_clamp_and_floats_must_be_finite() { + assert_eq!((-128i8).sanitize_range(-127.0, 127.0), Some(-127)); + assert_eq!(9u8.sanitize_range(0.0, 4.0), Some(4)); + assert_eq!(f32::NAN.sanitize_range(-1.0, 1.0), None); + assert_eq!(f32::INFINITY.sanitize_plain(), None); + assert_eq!(2.5f32.sanitize_range(-1.0, 1.0), Some(1.0)); + assert_eq!(0b111u8.mask(0b101), 0b101); + } + + #[test] + fn wire_types_serialize_tagged() { + let ty = Vec::>::wire_type(); + let json = serde_json::to_value(&ty).unwrap(); + assert_eq!( + json, + serde_json::json!({"type": "list", "item": {"type": "optional", "item": {"type": "f32"}}}) + ); + assert_eq!(serde_json::from_value::(json).unwrap(), ty); + assert_eq!( + WireType::of_field(FieldType::quant_centered(16.0, 12)).field_type(), + Some(FieldType::quant_centered(16.0, 12)) + ); + } +} diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs index d8805336f..9855304dc 100644 --- a/distributed_game/src/facts.rs +++ b/distributed_game/src/facts.rs @@ -66,6 +66,32 @@ pub fn fact_key(prefix: &str, zone: &str, epoch: u64, parts: &[&dyn std::fmt::Di key } +/// A cell command input a zone may emit as a typed fact +/// (`#[derive(FactCommand)]`, or implement by hand). +/// +/// `COMMAND` names the durable command the input belongs to: point it at +/// the same constant the cell mounts it under (`typed_command::(NAME)` +/// or `#[command]`'s generated `_COMMAND_ID`), so the zone and the +/// handler cannot disagree. [`Ctx::emit`](crate::Ctx::emit) then builds the +/// restart-safe key (`"{COMMAND}:{zone}:{boot_epoch}:{parts…}"`) from +/// [`dedupe_parts`](Self::dedupe_parts), or from the tick and emission order +/// when it returns none. +/// +/// Trust rules (enforced by the host, not by this trait): the principal is +/// bound from the player's verified ticket, never from the input; the input +/// reports *what happened* (which mob died) and the command handler decides +/// any reward. The derive rejects identity- and reward-looking field names. +pub trait FactCommand: serde::Serialize { + /// Durable command name. + const COMMAND: &'static str; + + /// Parts that identify this logical outcome within one zone activation + /// (e.g. mob id + generation). Empty = use the tick and emission order. + fn dedupe_parts(&self) -> Vec { + Vec::new() + } +} + /// A durable outcome to commit. #[derive(Debug, Clone, PartialEq)] pub struct Fact { @@ -91,6 +117,19 @@ impl Fact { } } + /// Typed fact: `C::COMMAND` with `input` serialized as its payload. + pub fn typed( + key: impl Into, + input: &C, + ) -> Result { + Ok(Self::new(key, C::COMMAND, serde_json::to_value(input)?)) + } + + /// True when this fact is a `C` command. + pub fn is(&self) -> bool { + self.command == C::COMMAND + } + /// Idempotency key. pub fn key(&self) -> &str { &self.key @@ -153,6 +192,13 @@ pub struct FactReceipt { pub replayed: bool, } +impl FactReceipt { + /// The sink's result payload as a typed value (e.g. the command output). + pub fn payload_as(&self) -> Result { + T::deserialize(&self.payload) + } +} + /// Final outcome of one fact. #[derive(Debug, Clone, PartialEq)] pub enum FactOutcome { @@ -178,6 +224,13 @@ pub struct FactSettlement { pub outcome: FactOutcome, } +impl FactSettlement { + /// True when the settled fact was a `C` command. + pub fn is(&self) -> bool { + self.command == C::COMMAND + } +} + /// Durable commit target. pub trait FactSink: Send + Sync + 'static { /// Commit one fact. Must be idempotent per [`Fact::key`]. @@ -226,6 +279,8 @@ pub enum EmitError { NoSink, /// The player is unknown (cannot bind a principal). UnknownPlayer, + /// A typed fact input did not serialize. + Encode(String), } #[derive(Debug, Default)] diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 837397872..a68a42cdb 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -30,8 +30,9 @@ use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; +use crate::authoring::GameEvent; use crate::clock::Clock; -use crate::facts::{EmitError, Fact, FactQueue, FactSettlement}; +use crate::facts::{EmitError, Fact, FactCommand, FactQueue, FactSettlement}; use crate::handoff::{HandoffError, HandoffRequest, Transfer, TransferIssuer, MAX_CARRIED_BYTES}; use crate::input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; use crate::interest::{InterestConfig, View}; @@ -250,6 +251,8 @@ pub(crate) struct Core { upward: Vec, child_inbox: Vec, dropped_frozen: u64, + /// Typed facts keyed without dedupe parts this tick: `(tick, count)`. + fact_seq: (u64, u32), } impl Core { @@ -419,9 +422,78 @@ impl Ctx<'_, Z> { .unwrap_or_default() } + /// Typed fact for a cell command input, keyed restart-safely: + /// `"{C::COMMAND}:{zone}:{boot_epoch}:{parts…}"` with the input's + /// [`dedupe_parts`](FactCommand::dedupe_parts), or `t{tick}:{n}` (the + /// n-th such fact this tick) when it has none. Emit it with + /// [`emit_fact_for`](Self::emit_fact_for) (e.g. to keep it in a retry + /// backlog) or use [`emit`](Self::emit) directly. + pub fn fact(&mut self, input: &C) -> Result { + let parts = input.dedupe_parts(); + let key = if parts.is_empty() { + let tick = self.core.tick; + if self.core.fact_seq.0 != tick { + self.core.fact_seq = (tick, 0); + } + let n = self.core.fact_seq.1; + self.core.fact_seq.1 += 1; + self.fact_key(C::COMMAND, &[&format_args!("t{tick}"), &n]) + } else { + let parts: Vec<&dyn std::fmt::Display> = + parts.iter().map(|p| p as &dyn std::fmt::Display).collect(); + self.fact_key(C::COMMAND, &parts) + }; + Fact::typed(key, input).map_err(|e| EmitError::Encode(e.to_string())) + } + + /// [`fact`](Self::fact) with explicit dedupe parts (overriding the + /// input's own). + pub fn fact_with_key( + &self, + input: &C, + parts: &[&dyn std::fmt::Display], + ) -> Result { + Fact::typed(self.fact_key(C::COMMAND, parts), input) + .map_err(|e| EmitError::Encode(e.to_string())) + } + + /// Emit a typed cell command input on behalf of `player`: the principal + /// is bound from the player's verified ticket (the input carries no + /// identity), the key is derived as in [`fact`](Self::fact). Returns + /// the key. Never blocks. + pub fn emit( + &mut self, + player: PlayerId, + input: C, + ) -> Result { + let fact = self.fact(&input)?; + let key = fact.key().to_string(); + self.emit_fact_for(player, fact).map(|()| key) + } + + /// [`emit`](Self::emit) with explicit dedupe parts. + pub fn emit_keyed( + &mut self, + player: PlayerId, + input: C, + parts: &[&dyn std::fmt::Display], + ) -> Result { + let fact = self.fact_with_key(&input, parts)?; + let key = fact.key().to_string(); + self.emit_fact_for(player, fact).map(|()| key) + } + + /// Emit a typed zone/system fact (no principal; the sink's system + /// principal applies). Returns the key. + pub fn emit_zone(&mut self, input: C) -> Result { + let fact = self.fact(&input)?; + let key = fact.key().to_string(); + self.emit_fact(fact).map(|()| key) + } + /// Emit a zone/system fact (no principal). Never blocks. pub fn emit_fact(&mut self, fact: Fact) -> Result<(), EmitError> { - self.emit(fact, None) + self.emit_bound(fact, None) } /// Emit a fact on behalf of `player`; the principal is bound from the @@ -433,10 +505,10 @@ impl Ctx<'_, Z> { .get(&player) .map(|slot| slot.info.principal.clone()) .ok_or(EmitError::UnknownPlayer)?; - self.emit(fact, Some(principal)) + self.emit_bound(fact, Some(principal)) } - fn emit(&mut self, fact: Fact, principal: Option) -> Result<(), EmitError> { + fn emit_bound(&mut self, fact: Fact, principal: Option) -> Result<(), EmitError> { let stamp = FactStamp { zone_id: self.core.zone_id.clone(), tick: self.core.tick, @@ -478,6 +550,17 @@ impl Ctx<'_, Z> { } } + /// Typed reliable event to one viewer (dropped if it has no live + /// connection). + pub fn send(&mut self, to: impl Into, event: &E) { + self.send_event(to, event.event_id(), event.to_payload()); + } + + /// Typed reliable event to every connection. + pub fn broadcast(&mut self, event: &E) { + self.broadcast_event(event.event_id(), event.to_payload()); + } + /// Set a viewer's area of interest. pub fn set_view(&mut self, viewer: impl Into, view: View) { match viewer.into() { @@ -645,6 +728,7 @@ impl ZoneHost { upward: Vec::new(), child_inbox: Vec::new(), dropped_frozen: 0, + fact_seq: (0, 0), config, }; let zone = Z::on_create(&mut Ctx { core: &mut core }, zone_config); @@ -1276,6 +1360,11 @@ impl ZoneHost { .send_event(to, type_id, payload); } + /// Send a typed event now (see [`Ctx::send`]). + pub fn send(&mut self, to: Viewer, event: &E) { + self.send_event(to, event.event_id(), event.to_payload()); + } + /// Kick a player now. pub fn kick(&mut self, player: PlayerId, message: impl Into) { self.core.pending_kicks.push((player, message.into())); diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index bbb1c1f11..b47a14a78 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -14,6 +14,17 @@ //! - Transport (`net` feature): axum WebSocket server hosting many zones //! with HMAC-signed ticket admission ([`net`]). //! +//! - Authoring derives (re-exported from `distributed_game_macros`): +//! `#[derive(Replicated)]` views generate a kind's schema and field +//! encoding from one struct ([`schema!`], [`WorldView::add`]); +//! `#[derive(GameInput)]` generates the input codec and sanitize; +//! `#[derive(GameEvent)]` / `#[derive(GameRecord)]` give events stable ids +//! and typed binary payloads ([`Ctx::send`], [`Ctx::broadcast`]); +//! `#[derive(FactCommand)]` binds a cell command input to its command name +//! ([`Ctx::emit`]). The derives also describe the zone's +//! [`GameSurface`](surface::GameSurface), from which `distributed +//! game-client` generates typed TypeScript. +//! //! Physics is out of scope: games bring their own and run it in `on_tick`. //! //! - World structure ([`world`]): zone directory and consistent-hash ring, @@ -26,11 +37,13 @@ #![warn(missing_docs)] +pub mod authoring; #[cfg(feature = "bots")] pub mod bots; #[cfg(feature = "cell")] pub mod cell; pub mod clock; +pub mod codec; pub mod facts; pub mod handoff; pub mod host; @@ -47,17 +60,22 @@ pub mod rewind; pub mod rng; pub mod schema; pub mod stamp; +pub mod surface; pub mod timers; pub mod timestep; pub mod world; pub mod zone; +pub use authoring::{GameEvent, GameInput, Pushed, Replicated}; pub use clock::{Clock, ManualClock, SystemClock}; +pub use codec::{Wire, WireType}; +/// Authoring derives (see the crate docs and README). +pub use distributed_game_macros::{FactCommand, GameEvent, GameInput, GameRecord, Replicated}; #[cfg(feature = "runtime")] pub use facts::spawn_fact_worker; pub use facts::{ - fact_channel, fact_key, BoxFuture, EmitError, Fact, FactError, FactFeed, FactOutcome, - FactQueue, FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, + fact_channel, fact_key, BoxFuture, EmitError, Fact, FactCommand, FactError, FactFeed, + FactOutcome, FactQueue, FactReceipt, FactSettlement, FactSink, MemoryFactSink, RetryPolicy, SettlementScript, }; pub use handoff::{HandoffError, HandoffRequest, Transfer}; @@ -69,8 +87,9 @@ pub use replay::{replay, Recorder, Recording}; pub use replication::{EntityState, WorldView}; pub use rewind::{Historic, HitQuery, Rewind, RewindConfig, RewindFrame, ShotTiming}; pub use rng::{Fnv64, ZoneRng}; -pub use schema::{EntitySchema, FieldType, FieldValue, KindDef}; +pub use schema::{Correction, EntitySchema, FieldType, FieldValue, KindDef}; pub use stamp::{stamp_metadata, FactStamp}; +pub use surface::GameSurface; pub use timers::TimerId; pub use timestep::FixedTimestep; pub use world::{BarrierMode, ChildEvent, FreezeState, StalePolicy}; @@ -79,6 +98,22 @@ pub use zone::{ TicketClaims, Tier, Viewer, Zone, }; +/// Paths used by derive-generated code. Not public API. +#[doc(hidden)] +pub mod __private { + pub use crate::authoring::{decode_whole, records_of}; + pub use crate::codec::{ + special, ButtonBits, EntityField, InputField, LongString, QuantizedF32, Wire, WireType, + }; + pub use crate::protocol::wire::{DecodeError, Reader, Writer}; + pub use crate::schema::{Correction, FieldType, FieldValue, KindDef}; + pub use crate::surface::{ + EventPayload, EventSurface, InputSurface, PayloadField, RecordSurface, + }; + pub use serde; + pub use std; +} + #[doc = include_str!("../README.md")] #[cfg(doctest)] pub struct ReadmeDoctests; diff --git a/distributed_game/src/protocol/wire.rs b/distributed_game/src/protocol/wire.rs index b81f77346..7ddf472b5 100644 --- a/distributed_game/src/protocol/wire.rs +++ b/distributed_game/src/protocol/wire.rs @@ -11,6 +11,10 @@ use std::fmt; /// Largest `string`/`bytes` length accepted by decoders (1 MiB). pub const MAX_BLOB_LEN: usize = 1 << 20; +/// Largest value [`Writer::varuint64`] / [`Reader::varuint64`] carry: +/// `2^53 - 1`, the largest integer a JavaScript `number` holds exactly. +pub const MAX_SAFE_U64: u64 = (1 << 53) - 1; + /// Decoding failure. #[derive(Debug, Clone, PartialEq, Eq)] pub enum DecodeError { @@ -107,6 +111,22 @@ impl Writer { } } + /// Unsigned LEB128 of a `u64`, saturated to [`MAX_SAFE_U64`] so a + /// JavaScript `number` decodes it exactly. Only typed game payloads + /// ([`codec`](crate::codec)) use it; no protocol message does. + pub fn varuint64(&mut self, v: u64) -> &mut Self { + let mut v = v.min(MAX_SAFE_U64); + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + self.buf.push(byte); + return self; + } + self.buf.push(byte | 0x80); + } + } + /// Zigzag-mapped signed varint: `(v << 1) ^ (v >> 31)`. pub fn varint(&mut self, v: i32) -> &mut Self { self.varuint(((v << 1) ^ (v >> 31)) as u32) @@ -208,6 +228,23 @@ impl<'a> Reader<'a> { Err(DecodeError::VarintOverflow) } + /// Unsigned LEB128 up to [`MAX_SAFE_U64`] (`2^53 - 1`, exact in a + /// JavaScript `number`); longer or non-minimal-overflowing input is an error. + pub fn varuint64(&mut self) -> Result { + let mut value: u64 = 0; + for index in 0..8 { + let byte = self.u8()?; + value |= u64::from(byte & 0x7f) << (7 * index); + if byte & 0x80 == 0 { + if value > MAX_SAFE_U64 { + return Err(DecodeError::VarintOverflow); + } + return Ok(value); + } + } + Err(DecodeError::VarintOverflow) + } + /// Zigzag signed varint. pub fn varint(&mut self) -> Result { let raw = self.varuint()?; diff --git a/distributed_game/src/replication.rs b/distributed_game/src/replication.rs index 3b434daba..15f54ab21 100644 --- a/distributed_game/src/replication.rs +++ b/distributed_game/src/replication.rs @@ -86,6 +86,10 @@ impl WorldView { pub fn entities(&self) -> &[EntityState] { &self.entities } + + pub(crate) fn last_mut(&mut self) -> Option<&mut EntityState> { + self.entities.last_mut() + } } #[derive(Debug, Clone)] diff --git a/distributed_game/src/schema.rs b/distributed_game/src/schema.rs index ccdfeafe9..1c41aeed3 100644 --- a/distributed_game/src/schema.rs +++ b/distributed_game/src/schema.rs @@ -309,6 +309,25 @@ fn steps(bits: u8) -> f64 { (1u64 << bits.clamp(1, 32)) as f64 } +/// How a predicting client resolves a misprediction of one field (the JS +/// SDK's `CorrectionPolicy`). Client metadata only: never sent on the wire, +/// exported in the [`GameSurface`](crate::surface::GameSurface) so generated +/// clients get per-field defaults. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] +pub enum Correction { + /// Adopt the rebased value, easing the visual error out over `duration_ms`. + Ease { + /// Ease duration (ms). + #[serde(rename = "durationMs")] + duration_ms: u32, + }, + /// Adopt the rebased value immediately. + Snap, + /// Server-owned: show the authoritative value, never replay inputs over it. + Replace, +} + /// One component field of a kind. #[derive(Debug, Clone, PartialEq)] pub struct FieldDef { @@ -318,6 +337,8 @@ pub struct FieldDef { pub ty: FieldType, /// Server-side replication priority multiplier (not sent on the wire). pub priority: f32, + /// Client correction default (not sent on the wire; see [`Correction`]). + pub correction: Option, } /// An entity kind: id, name and ordered fields. @@ -359,10 +380,23 @@ impl KindDef { name: name.into(), ty, priority: p, + correction: None, }); self } + /// Set the client correction default of the last added field. + /// + /// # Panics + /// If the kind has no fields yet. + pub fn correct(mut self, correction: Correction) -> Self { + self.fields + .last_mut() + .expect("add a field before its correction") + .correction = Some(correction); + self + } + /// Set the kind priority multiplier. pub fn priority(mut self, p: f32) -> Self { self.priority = p; diff --git a/distributed_game/src/surface.rs b/distributed_game/src/surface.rs new file mode 100644 index 000000000..d51802cf3 --- /dev/null +++ b/distributed_game/src/surface.rs @@ -0,0 +1,258 @@ +//! The game surface manifest: everything a generated client needs to know +//! about one zone type, built from the authoring derives. +//! +//! A [`GameSurface`] lists the zone's replicated kinds (fields, wire types, +//! priorities, client correction defaults), its input layout, its events and +//! the records their payloads mention. It is versioned +//! ([`GAME_SURFACE_SCHEMA_VERSION`]) and serialized as JSON by an app export +//! function (conventionally `game_surface`), which `distributed +//! game-manifest` runs and `distributed game-client` turns into typed +//! TypeScript. +//! +//! ```ignore +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("arena").events::() +//! } +//! ``` +//! +//! It is deliberately separate from the strict GraphQL client manifest: game +//! clients speak the binary zone protocol (`PROTOCOL.md`), not GraphQL. + +use serde::{Deserialize, Serialize}; + +use crate::codec::WireType; +use crate::protocol::PROTOCOL_VERSION; +use crate::schema::{Correction, EntitySchema}; +use crate::{GameEvent, GameInput, Zone}; + +/// Version of the [`GameSurface`] JSON shape. +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 1; + +/// One zone type's client-facing surface. See the module docs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct GameSurface { + /// [`GAME_SURFACE_SCHEMA_VERSION`]. + pub schema_version: u32, + /// Surface name (generated TypeScript prefixes exports with it). + pub name: String, + /// Zone wire protocol version (`PROTOCOL_VERSION`). + pub protocol_version: u32, + /// Replicated kinds in schema order. + pub kinds: Vec, + /// Input layout, if the zone takes typed input. + pub input: Option, + /// Events by id. + pub events: Vec, + /// Records mentioned by inputs or events, by name. + pub records: Vec, +} + +/// One replicated kind. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct KindSurface { + /// Kind id. + pub id: u16, + /// Kind name. + pub name: String, + /// Server-side priority multiplier. + pub priority: f32, + /// Ordered fields. + pub fields: Vec, +} + +/// One entity field. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EntityFieldSurface { + /// Wire name (the key in `RenderedEntity.fields`). + pub name: String, + /// Wire type (always an entity field type). + #[serde(rename = "type")] + pub ty: WireType, + /// Server-side priority multiplier. + pub priority: f32, + /// Client correction default. + pub correction: Option, +} + +/// A payload field (input, event or record). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PayloadField { + /// Rust field name (generated TypeScript uses its camelCase form). + pub name: String, + /// Wire type. + #[serde(rename = "type")] + pub ty: WireType, + /// Input sanitize range `[min, max]` (inputs only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub range: Option<[f64; 2]>, + /// Button names, bit 0 first (input bit-flag fields only). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub buttons: Vec, +} + +impl PayloadField { + /// Plain field. + pub fn new(name: impl Into, ty: WireType) -> Self { + Self { + name: name.into(), + ty, + range: None, + buttons: Vec::new(), + } + } +} + +/// The input layout. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct InputSurface { + /// Rust type name. + pub name: String, + /// Fields in wire order. + pub fields: Vec, +} + +/// One event type. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EventSurface { + /// Stable type id (the Event message `type_id`). + pub id: u32, + /// Event name (snake_case). + pub name: String, + /// Payload: inline fields or one value. + pub payload: EventPayload, +} + +/// An event payload. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum EventPayload { + /// Named fields in wire order (struct events, struct-like variants). + Fields { + /// Fields. + fields: Vec, + }, + /// The payload is one value's encoding (`Variant(T)`), typically a + /// record shared with other code. + Value { + /// Value type. + #[serde(rename = "type")] + ty: WireType, + }, +} + +/// A named record (nested payload struct). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RecordSurface { + /// Rust type name. + pub name: String, + /// Fields in wire order. + pub fields: Vec, +} + +impl GameSurface { + /// Empty surface named `name`. + pub fn new(name: impl Into) -> Self { + Self { + schema_version: GAME_SURFACE_SCHEMA_VERSION, + name: name.into(), + protocol_version: PROTOCOL_VERSION, + kinds: Vec::new(), + input: None, + events: Vec::new(), + records: Vec::new(), + } + } + + /// Kinds from the zone's [`Zone::schema`] and its typed input. + pub fn for_zone(name: impl Into) -> Self + where + Z: Zone, + Z::Input: GameInput, + { + Self::new(name).schema(&Z::schema()).input::() + } + + /// Add every kind of `schema` (derived or hand-written). + pub fn schema(mut self, schema: &EntitySchema) -> Self { + for kind in schema.kinds() { + assert!( + self.kinds.iter().all(|k| k.id != kind.id), + "duplicate kind id {} in game surface {}", + kind.id, + self.name + ); + self.kinds.push(KindSurface { + id: kind.id, + name: kind.name.clone(), + priority: kind.priority, + fields: kind + .fields + .iter() + .map(|field| EntityFieldSurface { + name: field.name.clone(), + ty: WireType::of_field(field.ty), + priority: field.priority, + correction: field.correction, + }) + .collect(), + }); + } + self + } + + /// Set the input layout. + pub fn input(mut self) -> Self { + let mut records = Vec::new(); + self.input = Some(I::input_surface(&mut records)); + self.add_records(records); + self + } + + /// Add an event type (a `#[derive(GameEvent)]` enum adds all its + /// variants). Event ids and names must be unique across the surface. + pub fn events(mut self) -> Self { + let mut records = Vec::new(); + for event in E::event_surfaces(&mut records) { + assert!( + self.events + .iter() + .all(|e| e.id != event.id && e.name != event.name), + "duplicate event id {} / name {} in game surface {}", + event.id, + event.name, + self.name + ); + self.events.push(event); + } + self.events.sort_by_key(|e| e.id); + self.add_records(records); + self + } + + fn add_records(&mut self, records: Vec) { + for record in records { + match self.records.iter().find(|r| r.name == record.name) { + Some(existing) => assert_eq!( + existing, &record, + "two different records named {} in game surface {}", + record.name, self.name + ), + None => self.records.push(record), + } + } + self.records.sort_by(|a, b| a.name.cmp(&b.name)); + } + + /// Pretty JSON (deterministic: kinds in schema order, events by id, + /// records by name). + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).expect("game surface serializes") + } +} diff --git a/distributed_game/tests/authoring/main.rs b/distributed_game/tests/authoring/main.rs new file mode 100644 index 000000000..b354c6d98 --- /dev/null +++ b/distributed_game/tests/authoring/main.rs @@ -0,0 +1,690 @@ +//! Authoring derives: `Replicated`, `GameInput`, `GameEvent`, `GameRecord`, +//! `FactCommand`, the `GameSurface` they describe, and the typed `Ctx` +//! helpers. +//! +//! `fixtures/authoring.json` (sample surface + encoded samples) is the Rust +//! side of the generated-client round trip: `distributed_cli` generates +//! TypeScript from its surface (golden `js/tests/fixtures/game-generated/`) +//! and `js/tests/game-generated.test.mjs` encodes/decodes the samples with +//! it. Regenerate with `UPDATE_GOLDEN=1 cargo test -p distributed_game --test authoring`. + +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::protocol::{Reader, Writer}; +use distributed_game::surface::{EventPayload, GameSurface}; +use distributed_game::{ + fact_channel, schema, Correction, Ctx, EntitySchema, FactCommand, FactOutcome, FactSettlement, + FieldType, FieldValue, GameEvent, GameInput, GameRecord, HostConfig, ManualClock, + MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, Wire, WireType, + WorldView, Zone, ZoneHost, +}; +use serde::Serialize; +use serde_json::{json, Value}; + +// ---- sample surface ------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0)] +pub struct PlayerView { + #[quant(centered = 20.0, bits = 18)] + #[correct(ease = 150)] + pub x: f32, + #[quant(centered = 20.0, bits = 18)] + #[correct(ease = 150)] + pub y: f32, + #[quant(min = -16.0, max = 16.0, bits = 12)] + #[correct(snap)] + pub vx: f32, + #[angle(bits = 8)] + #[correct(replace)] + pub face: f32, + #[priority(0.2)] + #[correct(replace)] + pub name: String, + pub hp: u8, + pub level: u16, + pub dead: bool, + pub score: i32, + pub raw: f32, + pub blob: Vec, + pub kills: u32, +} + +const POS: FieldType = FieldType::quant_centered(64.0, 16); + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "marker", id = 2, x = px, y = py)] +pub struct MarkerView { + #[field_type(POS)] + pub px: f32, + #[field_type(POS)] + pub py: f32, + pub label: String, +} + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "stats", id = 4, global)] +pub struct StatsView { + pub slow_ms: u16, + pub tick_ms: f32, +} + +#[derive(Debug, Clone, Copy, PartialEq, GameInput)] +pub struct SampleInput { + #[range(min = -127, max = 127)] + pub mx: i8, + #[range(min = -127, max = 127)] + pub my: i8, + #[buttons(dash, attack)] + pub buttons: u8, + #[angle(bits = 10)] + pub aim: f32, + #[range(min = 0.0, max = 1.0)] + pub power: f32, + pub view_tick: u32, +} + +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +pub struct Row { + pub rank: u16, + pub name: String, + pub score: u64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +pub struct Board { + pub version: u32, + pub kills: Vec, + pub note: Option, + #[long] + pub motd: String, +} + +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum SampleEvent { + #[game_event(id = 1)] + Hello { + entity: u32, + view_radius: f32, + #[quant(min = 0.0, max = 64.0, bits = 10)] + half: f32, + }, + #[game_event(id = 2)] + Board(Board), + #[game_event(id = 3, name = "respawned")] + Respawn, + #[game_event(id = 4)] + Shot { + hit: bool, + target: Option, + offset: i16, + small: i8, + at_ms: f64, + tags: Vec, + bytes: Vec, + total: u64, + }, +} + +#[derive(Debug, Clone, PartialEq, GameEvent)] +#[game_event(id = 9)] +pub struct Ping { + pub seq: u32, +} + +/// The cell command name, as the cell would mount it. +pub const RECORD_KILL: &str = "sample.record_kill"; + +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = RECORD_KILL, key(mob, generation))] +pub struct RecordKill { + pub mob: u32, + pub generation: u32, + pub tier: u8, +} + +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = "sample.tick_note")] +pub struct TickNote { + pub note: String, +} + +pub fn sample_surface() -> GameSurface { + GameSurface::for_zone::("sample") + .events::() + .events::() +} + +// ---- a zone using all of it ---------------------------------------------- + +#[derive(Default)] +pub struct Sample { + players: Vec, + pub settled: Vec, + pub keys: Vec, + pub last_input: Option, + kills: u32, +} + +impl Zone for Sample { + type Config = (); + type Input = SampleInput; + type Timer = (); + + fn schema() -> EntitySchema { + schema![PlayerView, MarkerView, StatsView] + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self::default() + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.players.push(player); + ctx.send( + player, + &SampleEvent::Hello { + entity: 1000 + player.0, + view_radius: 14.0, + half: 20.0, + }, + ); + ctx.broadcast(&Ping { seq: player.0 }); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + SampleInput::from_payload(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + for player in self.players.clone() { + for input in ctx.take_inputs(player, distributed_game::ConsumePolicy::Drain) { + self.last_input = Some(input.input); + if input.input.buttons & SampleInput::ATTACK != 0 { + self.kills += 1; + let key = ctx + .emit( + player, + RecordKill { + mob: 7, + generation: self.kills, + tier: 2, + }, + ) + .unwrap(); + self.keys.push(key); + // Two keyless facts in one tick get distinct keys. + self.keys + .push(ctx.emit_zone(TickNote { note: "a".into() }).unwrap()); + self.keys + .push(ctx.emit_zone(TickNote { note: "b".into() }).unwrap()); + } + } + } + } + + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + self.settled.push(settlement); + } + + fn replicate(&self, out: &mut WorldView) { + for (i, player) in self.players.iter().enumerate() { + out.add(1000 + player.0, &sample_player(i as f32)); + } + out.add( + 50, + &MarkerView { + px: 3.0, + py: -2.0, + label: "spawn".into(), + }, + ) + .priority(0.5); + out.add( + 900, + &StatsView { + slow_ms: 12, + tick_ms: 33.3, + }, + ); + } +} + +fn sample_player(offset: f32) -> PlayerView { + PlayerView { + x: 1.25 + offset, + y: -3.5, + vx: 0.5, + face: 1.0, + name: "Ada".into(), + hp: 90, + level: 3, + dead: false, + score: -12, + raw: 0.1, + blob: vec![1, 2, 3], + kills: 70_000, + } +} + +// ---- derive behaviour ----------------------------------------------------- + +#[test] +fn replicated_kind_def_and_values_share_one_field_order() { + let kind = PlayerView::kind_def(); + assert_eq!( + (kind.id, kind.name.as_str(), kind.priority), + (1, "player", 2.0) + ); + let names: Vec<_> = kind.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!( + names, + ["x", "y", "vx", "face", "name", "hp", "level", "dead", "score", "raw", "blob", "kills"] + ); + assert_eq!(kind.fields[0].ty, FieldType::quant_centered(20.0, 18)); + assert_eq!( + kind.fields[0].correction, + Some(Correction::Ease { duration_ms: 150 }) + ); + assert_eq!(kind.fields[2].correction, Some(Correction::Snap)); + assert_eq!(kind.fields[3].ty, FieldType::Angle { bits: 8 }); + assert_eq!(kind.fields[4].priority, 0.2); + assert_eq!(kind.fields[5].ty, FieldType::U8); + assert_eq!(kind.fields[6].ty, FieldType::U16); + assert_eq!(kind.fields[10].ty, FieldType::Bytes); + let view = sample_player(0.0); + let values = view.field_values(); + assert_eq!(values.len(), kind.fields.len()); + assert_eq!(values[4], FieldValue::Str("Ada".into())); + assert_eq!(values[8], FieldValue::I(-12)); + assert_eq!(view.position(), (1.25, -3.5)); + const { assert!(!PlayerView::GLOBAL) }; + const { assert!(StatsView::GLOBAL) }; + assert_eq!( + MarkerView { + px: 3.0, + py: 4.0, + label: String::new() + } + .position(), + (3.0, 4.0) + ); + assert_eq!(MarkerView::kind_def().fields[0].ty, POS); + + let schema = Sample::schema(); + assert_eq!(schema.kinds().len(), 3); + let mut view = WorldView::default(); + view.add( + 5, + &StatsView { + slow_ms: 1, + tick_ms: 2.0, + }, + ) + .local() + .priority(3.0); + view.add(6, &sample_player(0.0)).global(); + assert!(!view.entities()[0].global); + assert_eq!(view.entities()[0].priority, 3.0); + assert!(view.entities()[1].global); + assert_eq!(view.entities()[1].kind, PlayerView::KIND_ID); +} + +#[test] +fn game_input_codec_and_sanitize() { + let input = SampleInput { + mx: -128, + my: 64, + buttons: 0b1111, + aim: 1.0, + power: 2.0, + view_tick: 300, + }; + let bytes = input.to_payload(); + // i8, i8, u8, angle varuint (10 bits), f32, varuint. + assert_eq!(bytes[..3], [0x80, 0x40, 0x0f]); + let decoded = SampleInput::from_payload(&bytes).expect("valid"); + assert_eq!(decoded.mx, -127, "range clamps"); + assert_eq!( + decoded.buttons, + SampleInput::DASH | SampleInput::ATTACK, + "unknown bits cleared" + ); + assert_eq!(decoded.power, 1.0); + assert_eq!((SampleInput::DASH, SampleInput::ATTACK), (1, 2)); + let mut long = bytes.clone(); + long.push(0); + assert_eq!( + SampleInput::from_payload(&long), + None, + "trailing bytes reject" + ); + assert_eq!( + SampleInput::from_payload(&bytes[..4]), + None, + "short frames reject" + ); + let nan = SampleInput { + power: f32::NAN, + ..input + }; + assert_eq!( + SampleInput::from_payload(&nan.to_payload()), + None, + "non-finite floats reject" + ); +} + +#[test] +fn events_have_stable_ids_and_round_trip() { + let events = sample_events(); + for event in &events { + let payload = event.to_payload(); + let back = SampleEvent::decode_event(event.event_id(), &payload).unwrap(); + assert_eq!(back.as_ref(), Some(event)); + assert_eq!( + Ping::decode_event(event.event_id(), &payload).unwrap(), + None + ); + } + assert_eq!(SampleEvent::HELLO, 1); + assert_eq!(SampleEvent::RESPAWN, 3); + assert_eq!(Ping::EVENT_ID, 9); + assert_eq!(SampleEvent::decode_event(77, &[]).unwrap(), None); + assert!(SampleEvent::decode_event(1, &[1]).is_err()); + let ping = Ping { seq: 5 }; + assert_eq!( + Ping::decode_event(9, &ping.to_payload()).unwrap(), + Some(ping) + ); +} + +#[test] +fn records_round_trip_through_the_value_codec() { + let board = sample_board(); + let mut w = Writer::new(); + board.encode(&mut w); + let mut r = Reader::new(w.as_bytes()); + assert_eq!(Board::decode(&mut r).unwrap(), board); + r.finish().unwrap(); + assert_eq!( + Board::wire_type(), + WireType::Record { + name: "Board".into() + } + ); +} + +#[test] +fn surface_describes_everything_once() { + let surface = sample_surface(); + assert_eq!(surface.schema_version, 1); + assert_eq!(surface.kinds.len(), 3); + assert_eq!( + surface.kinds[0].fields[0].correction, + Some(Correction::Ease { duration_ms: 150 }) + ); + let input = surface.input.as_ref().expect("typed input"); + assert_eq!(input.name, "SampleInput"); + assert_eq!(input.fields[0].range, Some([-127.0, 127.0])); + assert_eq!(input.fields[2].buttons, ["dash", "attack"]); + let ids: Vec<_> = surface + .events + .iter() + .map(|e| (e.id, e.name.as_str())) + .collect(); + assert_eq!( + ids, + [ + (1, "hello"), + (2, "board"), + (3, "respawned"), + (4, "shot"), + (9, "ping") + ] + ); + assert_eq!( + surface.events[1].payload, + EventPayload::Value { + ty: WireType::Record { + name: "Board".into() + } + } + ); + let records: Vec<_> = surface.records.iter().map(|r| r.name.as_str()).collect(); + assert_eq!(records, ["Board", "Row"]); + // JSON round trip (the CLI reads this shape). + let json = surface.to_json(); + let back: GameSurface = serde_json::from_str(&json).unwrap(); + assert_eq!(back, surface); +} + +#[test] +#[should_panic(expected = "duplicate event id")] +fn surface_rejects_duplicate_event_ids_across_types() { + #[derive(GameEvent)] + #[game_event(id = 1)] + struct Clash {} + let _ = sample_surface().events::(); +} + +// ---- typed facts through a real host ------------------------------------- + +fn claims(principal: &str) -> TicketClaims { + TicketClaims::new( + principal, + "z1", + u64::MAX, + format!("n-{principal}"), + Role::Player, + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn typed_facts_bind_the_principal_and_derive_restart_safe_keys() { + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(64, RetryPolicy::default()); + tokio::spawn(feed.run(sink.clone(), tokio::time::sleep)); + let clock = ManualClock::new(); + let config = HostConfig { + boot_epoch: 42, + ..HostConfig::default() + }; + let mut host = + ZoneHost::::new("z1", config, Arc::new(clock.clone()), ()).with_facts(queue); + let joined = host.join(&claims("alice"), 0, "").unwrap(); + let attack = SampleInput { + mx: 0, + my: 0, + buttons: SampleInput::ATTACK, + aim: 0.0, + power: 0.5, + view_tick: 0, + }; + host.push_input(joined.client, 1, 0, &attack.to_payload()); + clock.advance(Duration::from_millis(40)); + host.advance(); + let keys = host.zone().keys.clone(); + assert_eq!(keys[0], "sample.record_kill:z1:42:7:1"); + assert!( + keys[1].starts_with("sample.tick_note:z1:42:t"), + "{}", + keys[1] + ); + assert_ne!(keys[1], keys[2], "keyless facts are numbered within a tick"); + + for _ in 0..200 { + if sink.committed().len() == 3 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + let committed = sink.committed(); + let kill = committed + .iter() + .find(|f| f.is::()) + .expect("kill committed"); + assert_eq!( + kill.principal(), + Some("alice"), + "principal from the verified ticket" + ); + assert_eq!( + kill.input(), + &json!({ "mob": 7, "generation": 1, "tier": 2 }) + ); + let note = committed + .iter() + .find(|f| f.is::()) + .expect("zone fact"); + assert_eq!(note.principal(), None); + + for _ in 0..50 { + clock.advance(Duration::from_millis(40)); + host.advance(); + if host.zone().settled.len() == 3 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + let settled = &host.zone().settled; + assert!(settled.iter().any(|s| s.is::())); + assert!(settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + assert_eq!(RecordKill::COMMAND, RECORD_KILL); +} + +// ---- golden fixture for the generated TypeScript -------------------------- + +fn sample_board() -> Board { + Board { + version: 7, + kills: vec![ + Row { + rank: 1, + name: "Ada".into(), + score: 9_007_199_254_740_991, + }, + Row { + rank: 2, + name: "Bob ✓".into(), + score: 3, + }, + ], + note: None, + motd: "x".repeat(300), + } +} + +fn sample_events() -> Vec { + vec![ + SampleEvent::Hello { + entity: 1001, + view_radius: 14.0, + half: 64.0, + }, + SampleEvent::Board(sample_board()), + SampleEvent::Respawn, + SampleEvent::Shot { + hit: true, + target: Some(42), + offset: -300, + small: -5, + at_ms: 1234.5, + tags: vec!["a".into(), "".into()], + bytes: vec![0, 255], + total: 1 << 40, + }, + SampleEvent::Shot { + hit: false, + target: None, + offset: 0, + small: 0, + at_ms: 0.0, + tags: vec![], + bytes: vec![], + total: 0, + }, + ] +} + +/// The TypeScript-side value of each sample (camelCase keys). +fn sample_event_values() -> Vec { + let board = json!({ + "version": 7, + "kills": [ + {"rank": 1, "name": "Ada", "score": 9_007_199_254_740_991u64}, + {"rank": 2, "name": "Bob ✓", "score": 3} + ], + "note": null, + "motd": "x".repeat(300), + }); + vec![ + json!({"entity": 1001, "viewRadius": 14.0, "half": 64.0}), + board, + json!({}), + json!({"hit": true, "target": 42, "offset": -300, "small": -5, "atMs": 1234.5, "tags": ["a", ""], "bytes": [0, 255], "total": 1u64 << 40}), + json!({"hit": false, "target": null, "offset": 0, "small": 0, "atMs": 0.0, "tags": [], "bytes": [], "total": 0}), + ] +} + +fn f32_of(ty: FieldType, v: f32) -> f64 { + match ty.canonicalize(&FieldValue::F(v)) { + FieldValue::F(v) => f64::from(v), + _ => unreachable!(), + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[test] +fn golden_fixture_is_current() { + let input = SampleInput { + mx: -128, + my: 100, + buttons: 0b111, + aim: -1.0, + power: 0.25, + view_tick: 123_456, + }; + let sanitized = SampleInput::from_payload(&input.to_payload()).unwrap(); + let aim_wire = f32_of(FieldType::Angle { bits: 10 }, -1.0); + let events: Vec = sample_events() + .iter() + .zip(sample_event_values()) + .map(|(event, value)| { + let name = sample_surface() + .events + .into_iter() + .find(|e| e.id == event.event_id()) + .unwrap() + .name; + json!({ "id": event.event_id(), "name": name, "value": value, "hex": hex(&event.to_payload()) }) + }) + .collect(); + let fixture = json!({ + // Through `to_json` so floats keep their shortest binary32 form. + "surface": serde_json::from_str::(&sample_surface().to_json()).unwrap(), + "input": { + "value": {"mx": -128, "my": 100, "buttons": 7, "aim": -1.0, "power": 0.25, "viewTick": 123_456}, + "hex": hex(&input.to_payload()), + "decoded": {"mx": -128, "my": 100, "buttons": 7, "aim": aim_wire, "power": 0.25, "viewTick": 123_456}, + "sanitized": {"mx": sanitized.mx, "my": sanitized.my, "buttons": sanitized.buttons, "aim": aim_wire, "power": 0.25, "viewTick": 123_456}, + }, + "events": events, + }); + let text = serde_json::to_string_pretty(&fixture).unwrap() + "\n"; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/authoring.json"); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + std::fs::write(path, &text).unwrap(); + } + let current = std::fs::read_to_string(path).unwrap_or_default(); + assert_eq!( + current, text, + "run with UPDATE_GOLDEN=1 to regenerate {path}" + ); +} diff --git a/distributed_game/tests/fixtures/authoring.json b/distributed_game/tests/fixtures/authoring.json new file mode 100644 index 000000000..de7cc6e67 --- /dev/null +++ b/distributed_game/tests/fixtures/authoring.json @@ -0,0 +1,545 @@ +{ + "events": [ + { + "hex": "e90700006041ff07", + "id": 1, + "name": "hello", + "value": { + "entity": 1001, + "half": 64.0, + "viewRadius": 14.0 + } + }, + { + "hex": "07020103416461ffffffffffffff0f0207426f6220e29c930300ac02787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878", + "id": 2, + "name": "board", + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "hex": "", + "id": 3, + "name": "respawned", + "value": {} + }, + { + "hex": "01012ad704fb00000000004a9340020161000200ff808080808020", + "id": 4, + "name": "shot", + "value": { + "atMs": 1234.5, + "bytes": [ + 0, + 255 + ], + "hit": true, + "offset": -300, + "small": -5, + "tags": [ + "a", + "" + ], + "target": 42, + "total": 1099511627776 + } + }, + { + "hex": "000000000000000000000000000000", + "id": 4, + "name": "shot", + "value": { + "atMs": 0.0, + "bytes": [], + "hit": false, + "offset": 0, + "small": 0, + "tags": [], + "target": null, + "total": 0 + } + } + ], + "input": { + "decoded": { + "aim": 5.283030033111572, + "buttons": 7, + "mx": -128, + "my": 100, + "power": 0.25, + "viewTick": 123456 + }, + "hex": "806407dd060000803ec0c407", + "sanitized": { + "aim": 5.283030033111572, + "buttons": 3, + "mx": -127, + "my": 100, + "power": 0.25, + "viewTick": 123456 + }, + "value": { + "aim": -1.0, + "buttons": 7, + "mx": -128, + "my": 100, + "power": 0.25, + "viewTick": 123456 + } + }, + "surface": { + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "view_radius", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "Board", + "type": "record" + } + } + }, + { + "id": 3, + "name": "respawned", + "payload": { + "fields": [], + "kind": "fields" + } + }, + { + "id": 4, + "name": "shot", + "payload": { + "fields": [ + { + "name": "hit", + "type": { + "type": "bool" + } + }, + { + "name": "target", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "offset", + "type": { + "type": "i16" + } + }, + { + "name": "small", + "type": { + "type": "i8" + } + }, + { + "name": "at_ms", + "type": { + "type": "f64" + } + }, + { + "name": "tags", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "bytes", + "type": { + "type": "bytes" + } + }, + { + "name": "total", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + }, + { + "id": 9, + "name": "ping", + "payload": { + "fields": [ + { + "name": "seq", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + }, + { + "name": "aim", + "type": { + "bits": 10, + "type": "angle" + } + }, + { + "name": "power", + "range": [ + 0.0, + 1.0 + ], + "type": { + "type": "f32" + } + }, + { + "name": "view_tick", + "type": { + "type": "u32" + } + } + ], + "name": "SampleInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 16.0, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + }, + { + "correction": null, + "name": "score", + "priority": 1.0, + "type": { + "type": "i32" + } + }, + { + "correction": null, + "name": "raw", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "blob", + "priority": 1.0, + "type": { + "type": "bytes" + } + }, + { + "correction": null, + "name": "kills", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "px", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "py", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "label", + "priority": 1.0, + "type": { + "type": "short_str" + } + } + ], + "id": 2, + "name": "marker", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 4, + "name": "stats", + "priority": 1.0 + } + ], + "name": "sample", + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "version", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "note", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "motd", + "type": { + "type": "str" + } + } + ], + "name": "Board" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u16" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "u64" + } + } + ], + "name": "Row" + } + ], + "schemaVersion": 1 + } +} diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs index 60777d449..6bd1bd5c4 100644 --- a/distributed_game/tests/zone_runtime/main.rs +++ b/distributed_game/tests/zone_runtime/main.rs @@ -211,7 +211,10 @@ fn reconnect_within_grace_keeps_player_then_expires() { assert!(!token.is_empty()); for seq in 1..=5 { - assert_eq!(h.push_input(a.client, seq, 0, &[1, 0]), PushOutcome::Accepted); + assert_eq!( + h.push_input(a.client, seq, 0, &[1, 0]), + PushOutcome::Accepted + ); } h.advance(); diff --git a/distributed_game_macros/Cargo.toml b/distributed_game_macros/Cargo.toml new file mode 100644 index 000000000..3677a49b9 --- /dev/null +++ b/distributed_game_macros/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "distributed_game_macros" +version.workspace = true +edition.workspace = true +description = "Authoring derives for distributed_game: Replicated, GameInput, GameEvent, GameRecord, FactCommand" +license.workspace = true +repository.workspace = true + +[lib] +proc-macro = true + +[dependencies] +proc-macro-crate = "3.5" +proc-macro2 = "1.0" +quote = "1.0" +syn = { version = "2.0", features = ["full"] } + +[dev-dependencies] +# Compile-fail snapshots depend on trybuild's compiler-diagnostic normalization. +trybuild = "=1.0.120" +# Dev-only cycle (as in distributed_macros): fixtures need the runtime crate. +distributed_game = { path = "../distributed_game" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/distributed_game_macros/src/event.rs b/distributed_game_macros/src/event.rs new file mode 100644 index 000000000..710f309d2 --- /dev/null +++ b/distributed_game_macros/src/event.rs @@ -0,0 +1,334 @@ +//! `#[derive(GameEvent)]` and `#[derive(GameRecord)]`: typed payloads with +//! the shared value codec. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::spanned::Spanned; +use syn::{Data, DeriveInput, Field, Fields, Ident, LitInt, LitStr}; + +use crate::shared::{ + check_name, field_name, find_attr, named_fields, no_generics, parse_field_attrs, payload_codec, + reject, runtime, snake_case, +}; + +/// Encode/decode/surface tokens for a list of named fields read through +/// `access(ident)` (e.g. `&self.x` or a bound pattern variable). +struct FieldsCodec { + encodes: Vec, + decodes: Vec, + surfaces: Vec, + records: Vec, +} + +fn fields_codec( + fields: &[&Field], + derive: &str, + rt: &TokenStream, + access: impl Fn(&Ident) -> TokenStream, +) -> syn::Result { + let p = quote!(#rt::__private); + let mut out = FieldsCodec { + encodes: Vec::new(), + decodes: Vec::new(), + surfaces: Vec::new(), + records: Vec::new(), + }; + for field in fields { + let fid = field.ident.as_ref().expect("named"); + let fa = parse_field_attrs(field, rt)?; + reject(fa.priority.as_ref().map(|x| x.1), "#[priority]", derive)?; + reject(fa.correct.as_ref().map(|x| x.1), "#[correct]", derive)?; + reject(fa.range.as_ref().map(|x| x.2), "#[range]", derive)?; + reject(fa.buttons.as_ref().map(|x| x.1), "#[buttons]", derive)?; + let codec = payload_codec( + &field.ty, + access(fid), + fa.special.as_ref().map(|s| &s.0), + rt, + ); + let name = field_name(fid); + out.encodes.push(codec.encode); + let decode = codec.decode; + out.decodes.push(quote!(#fid: #decode)); + let wire_type = codec.wire_type; + out.surfaces + .push(quote!(#p::PayloadField::new(#name, #wire_type))); + out.records.push(codec.records); + } + Ok(out) +} + +pub(crate) fn expand_record(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameRecord")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let fields = named_fields(&input, "GameRecord")?; + let c = fields_codec(&fields, "GameRecord", &rt, |f| quote!(&self.#f))?; + let ident = &input.ident; + let name = ident.to_string(); + let (encodes, decodes, surfaces, records) = (c.encodes, c.decodes, c.surfaces, c.records); + Ok(quote! { + impl #p::Wire for #ident { + fn wire_type() -> #p::WireType { + #p::WireType::Record { name: #p::std::string::String::from(#name) } + } + + fn encode(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode(r: &mut #p::Reader<'_>) -> #p::std::result::Result { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + } + + fn records(records: &mut #p::std::vec::Vec<#p::RecordSurface>) { + if records.iter().any(|r| r.name == #name) { + return; + } + records.push(#p::RecordSurface { + name: #p::std::string::String::from(#name), + fields: #p::std::vec![#(#surfaces),*], + }); + #(#records)* + } + } + }) +} + +struct EventAttr { + id: u32, + id_span: proc_macro2::Span, + name: Option, +} + +fn parse_event_attr( + attrs: &[syn::Attribute], + span: proc_macro2::Span, + what: &str, +) -> syn::Result { + let Some(attr) = find_attr(attrs, "game_event") else { + return Err(syn::Error::new( + span, + format!("{what} needs #[game_event(id = N)] (a stable u32 type id)"), + )); + }; + let (mut id, mut name) = (None, None); + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("id") { + let lit: LitInt = meta.value()?.parse()?; + id = Some((lit.base10_parse::()?, lit.span())); + } else if meta.path.is_ident("name") { + name = Some(check_name(&meta.value()?.parse::()?)?); + } else { + return Err(meta.error("expected `id` or `name` in #[game_event(..)]")); + } + Ok(()) + })?; + let Some((id, id_span)) = id else { + return Err(syn::Error::new( + attr.path().span(), + "#[game_event(..)] needs a literal `id = N`", + )); + }; + Ok(EventAttr { id, id_span, name }) +} + +pub(crate) fn expand_event(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameEvent")?; + match &input.data { + Data::Struct(_) => expand_struct_event(&input), + Data::Enum(_) => expand_enum_event(&input), + Data::Union(_) => Err(syn::Error::new( + input.ident.span(), + "#[derive(GameEvent)] supports structs and enums", + )), + } +} + +fn expand_struct_event(input: &DeriveInput) -> syn::Result { + let rt = runtime()?; + let p = quote!(#rt::__private); + let attr = parse_event_attr(&input.attrs, input.ident.span(), "a struct event")?; + let fields = named_fields(input, "GameEvent")?; + let c = fields_codec(&fields, "GameEvent", &rt, |f| quote!(&self.#f))?; + let ident = &input.ident; + let id = attr.id; + let name = attr.name.unwrap_or_else(|| snake_case(&ident.to_string())); + let (encodes, decodes, surfaces, records) = (c.encodes, c.decodes, c.surfaces, c.records); + Ok(quote! { + impl #ident { + /// Stable event type id. + pub const EVENT_ID: u32 = #id; + } + + impl #rt::GameEvent for #ident { + fn event_id(&self) -> u32 { + #id + } + + fn encode_payload(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode_event( + type_id: u32, + payload: &[u8], + ) -> #p::std::result::Result<#p::std::option::Option, #p::DecodeError> { + if type_id != #id { + return #p::std::result::Result::Ok(#p::std::option::Option::None); + } + #p::decode_whole(payload, |r| { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + }) + .map(#p::std::option::Option::Some) + } + + fn event_surfaces( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::std::vec::Vec<#p::EventSurface> { + #(#records)* + let _ = &records; + #p::std::vec![#p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec![#(#surfaces),*] }, + }] + } + } + }) +} + +fn expand_enum_event(input: &DeriveInput) -> syn::Result { + let rt = runtime()?; + let p = quote!(#rt::__private); + let Data::Enum(data) = &input.data else { + unreachable!() + }; + if data.variants.is_empty() { + return Err(syn::Error::new( + input.ident.span(), + "an event enum needs at least one variant", + )); + } + let ident = &input.ident; + let mut seen: Vec<(u32, String)> = Vec::new(); + let (mut ids, mut encodes, mut decodes, mut surfaces, mut consts) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for variant in &data.variants { + let vid = &variant.ident; + let attr = parse_event_attr(&variant.attrs, vid.span(), "every event variant")?; + let id = attr.id; + let name = attr.name.unwrap_or_else(|| snake_case(&vid.to_string())); + if let Some((_, other)) = seen.iter().find(|(i, n)| *i == id || *n == name) { + return Err(syn::Error::new( + attr.id_span, + format!("event id {id} / name `{name}` already used by `{other}`"), + )); + } + seen.push((id, name.clone())); + let const_name = format_ident!("{}", snake_case(&vid.to_string()).to_uppercase()); + let doc = format!("Type id of [`{ident}::{vid}`]."); + consts.push(quote!(#[doc = #doc] pub const #const_name: u32 = #id;)); + match &variant.fields { + Fields::Unit => { + ids.push(quote!(Self::#vid => #id)); + encodes.push(quote!(Self::#vid => {})); + decodes.push(quote!(#id => #p::decode_whole(payload, |_| #p::std::result::Result::Ok(Self::#vid)))); + surfaces.push(quote! { + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec::Vec::new() }, + } + }); + } + Fields::Named(named) => { + let fields: Vec<&Field> = named.named.iter().collect(); + let bind: Vec<&Ident> = fields + .iter() + .map(|f| f.ident.as_ref().expect("named")) + .collect(); + let c = fields_codec(&fields, "GameEvent", &rt, |f| quote!(#f))?; + let (enc, dec, surf, recs) = (c.encodes, c.decodes, c.surfaces, c.records); + ids.push(quote!(Self::#vid { .. } => #id)); + encodes.push(quote!(Self::#vid { #(#bind),* } => { #(#enc)* })); + decodes.push(quote!(#id => #p::decode_whole(payload, |r| { + let _ = &r; + #p::std::result::Result::Ok(Self::#vid { #(#dec),* }) + }))); + surfaces.push(quote! {{ + #(#recs)* + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec![#(#surf),*] }, + } + }}); + } + Fields::Unnamed(unnamed) => { + if unnamed.unnamed.len() != 1 { + return Err(syn::Error::new( + variant.fields.span(), + "a tuple event variant carries exactly one value (use named fields for more)", + )); + } + let ty = &unnamed.unnamed[0].ty; + let codec = payload_codec(ty, quote!(value), None, &rt); + let (enc, dec, wt, recs) = + (codec.encode, codec.decode, codec.wire_type, codec.records); + ids.push(quote!(Self::#vid(..) => #id)); + encodes.push(quote!(Self::#vid(value) => { #enc })); + decodes.push(quote!(#id => #p::decode_whole(payload, |r| #p::std::result::Result::Ok(Self::#vid(#dec))))); + surfaces.push(quote! {{ + #recs + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Value { ty: #wt }, + } + }}); + } + } + } + Ok(quote! { + impl #ident { + #(#consts)* + } + + impl #rt::GameEvent for #ident { + fn event_id(&self) -> u32 { + match self { + #(#ids),* + } + } + + fn encode_payload(&self, w: &mut #p::Writer) { + let _ = &w; + match self { + #(#encodes)* + } + } + + fn decode_event( + type_id: u32, + payload: &[u8], + ) -> #p::std::result::Result<#p::std::option::Option, #p::DecodeError> { + match type_id { + #(#decodes.map(#p::std::option::Option::Some),)* + _ => #p::std::result::Result::Ok(#p::std::option::Option::None), + } + } + + fn event_surfaces( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::std::vec::Vec<#p::EventSurface> { + let _ = &records; + #p::std::vec![#(#surfaces),*] + } + } + }) +} diff --git a/distributed_game_macros/src/fact.rs b/distributed_game_macros/src/fact.rs new file mode 100644 index 000000000..09fa5516d --- /dev/null +++ b/distributed_game_macros/src/fact.rs @@ -0,0 +1,137 @@ +//! `#[derive(FactCommand)]`: bind a cell command input type to its command +//! name so a zone can `ctx.emit(player, input)`. + +use proc_macro2::TokenStream; +use quote::quote; +use syn::spanned::Spanned; +use syn::{DeriveInput, Expr, Ident, LitStr}; + +use crate::shared::{field_name, find_attr, named_fields, no_generics, runtime}; + +/// Field names a zone-emitted fact must never carry: identity is bound by +/// the host from the verified ticket, rewards are decided by the handler. +const FORBIDDEN: &[(&str, &str)] = &[ + ("principal", "identity"), + ("user", "identity"), + ("user_id", "identity"), + ("userid", "identity"), + ("owner", "identity"), + ("owner_id", "identity"), + ("account", "identity"), + ("account_id", "identity"), + ("subject", "identity"), + ("sub", "identity"), + ("xp", "a reward"), + ("experience", "a reward"), + ("reward", "a reward"), + ("rewards", "a reward"), +]; + +fn normalized(name: &str) -> String { + name.chars() + .filter(|c| *c != '_' && *c != '-') + .flat_map(char::to_lowercase) + .collect() +} + +fn forbidden(name: &str) -> Option<&'static str> { + let n = normalized(name); + FORBIDDEN + .iter() + .find(|(bad, _)| normalized(bad) == n) + .map(|(_, why)| *why) +} + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "FactCommand")?; + let rt = runtime()?; + let Some(attr) = find_attr(&input.attrs, "fact") else { + return Err(syn::Error::new( + input.ident.span(), + "#[derive(FactCommand)] needs #[fact(command = COMMAND_NAME)] (the constant the cell mounts the command under, or a string literal)", + )); + }; + let (mut command, mut key): (Option, Option>) = (None, None); + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("command") { + command = Some(meta.value()?.parse()?); + } else if meta.path.is_ident("key") { + let mut parts = Vec::new(); + meta.parse_nested_meta(|part| { + let Some(ident) = part.path.get_ident() else { + return Err(part.error("key parts are field names")); + }; + parts.push(ident.clone()); + Ok(()) + })?; + key = Some(parts); + } else { + return Err(meta.error("expected `command = ..` or `key(field, ..)` in #[fact(..)]")); + } + Ok(()) + })?; + let Some(command) = command else { + return Err(syn::Error::new( + attr.path().span(), + "#[fact(..)] needs `command = ..`", + )); + }; + + let fields = named_fields(&input, "FactCommand")?; + for field in &fields { + let ident = field.ident.as_ref().expect("named"); + let mut names = vec![(field_name(ident), ident.span())]; + // Serde renames change what the handler sees. + for a in field.attrs.iter().filter(|a| a.path().is_ident("serde")) { + let _ = a.parse_nested_meta(|meta| { + if meta.path.is_ident("rename") || meta.path.is_ident("alias") { + if let Ok(value) = meta.value() { + if let Ok(lit) = value.parse::() { + names.push((lit.value(), lit.span())); + } + } + } else if meta.input.peek(syn::Token![=]) { + let _ = meta.value()?.parse::(); + } else if meta.input.peek(syn::token::Paren) { + let _ = meta.parse_nested_meta(|_| Ok(())); + } + Ok(()) + }); + } + for (name, span) in names { + if let Some(why) = forbidden(&name) { + return Err(syn::Error::new( + span, + format!( + "fact input field `{name}` looks like {why}: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards" + ), + )); + } + } + } + + let parts = match &key { + None => quote!(::std::vec::Vec::new()), + Some(parts) => { + for part in parts { + if !fields.iter().any(|f| f.ident.as_ref() == Some(part)) { + return Err(syn::Error::new( + part.span(), + format!("no field `{part}` in this struct"), + )); + } + } + quote!(::std::vec![#(::std::string::ToString::to_string(&self.#parts)),*]) + } + }; + let ident = &input.ident; + Ok(quote! { + impl #rt::FactCommand for #ident { + const COMMAND: &'static str = #command; + + fn dedupe_parts(&self) -> ::std::vec::Vec<::std::string::String> { + #parts + } + } + }) +} diff --git a/distributed_game_macros/src/input.rs b/distributed_game_macros/src/input.rs new file mode 100644 index 000000000..f20a1d565 --- /dev/null +++ b/distributed_game_macros/src/input.rs @@ -0,0 +1,145 @@ +//! `#[derive(GameInput)]`: compact input codec + sanitize from one struct. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::DeriveInput; + +use crate::shared::{ + field_name, named_fields, no_generics, parse_field_attrs, payload_codec, reject, runtime, + Special, +}; + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameInput")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let fields = named_fields(&input, "GameInput")?; + let ident = &input.ident; + let type_name = ident.to_string(); + + let mut surfaces = Vec::new(); + let mut encodes = Vec::new(); + let mut decodes = Vec::new(); + let mut sanitizes = Vec::new(); + let mut consts = Vec::new(); + let mut const_names: Vec = Vec::new(); + for field in &fields { + let fid = field.ident.as_ref().expect("named"); + let name = field_name(fid); + let ty = &field.ty; + let span = ty.span(); + let fa = parse_field_attrs(field, &rt)?; + reject( + fa.priority.as_ref().map(|x| x.1), + "#[priority]", + "GameInput", + )?; + reject(fa.correct.as_ref().map(|x| x.1), "#[correct]", "GameInput")?; + if let Some((Special::Long, span)) = &fa.special { + return Err(syn::Error::new( + *span, + "inputs carry no strings; #[long] is not supported by #[derive(GameInput)]", + )); + } + let codec = payload_codec( + ty, + quote!(&self.#fid), + fa.special.as_ref().map(|s| &s.0), + &rt, + ); + encodes.push(codec.encode); + let decode = codec.decode; + decodes.push(quote!(#fid: #decode)); + + let range = match &fa.range { + Some((min, max, _)) => quote!(Some([(#min) as f64, (#max) as f64])), + None => quote!(None), + }; + let mut buttons = Vec::new(); + let sanitize = if let Some((names, bspan)) = &fa.buttons { + if fa.range.is_some() || fa.special.is_some() { + return Err(syn::Error::new( + *bspan, + "a #[buttons] field takes no #[range] / #[quant] / #[angle]", + )); + } + let mask: u64 = (1u64 << names.len()) - 1; + let mask = mask as u32; + for (bit, button) in names.iter().enumerate() { + let name = field_name(button); + buttons.push(quote!(#p::std::string::String::from(#name))); + let cname = format_ident!("{}", name.to_uppercase(), span = button.span()); + if const_names.iter().any(|c| c == &cname) { + return Err(syn::Error::new(button.span(), "duplicate button constant")); + } + const_names.push(cname.clone()); + let doc = format!("`{name}` bit of `{}`.", field_name(fid)); + let bit = bit as u32; + consts.push(quote_spanned!(span=> + #[doc = #doc] + pub const #cname: #ty = (1u32 << #bit) as #ty; + )); + } + quote_spanned!(span=> <#ty as #p::ButtonBits>::mask(self.#fid, #mask)) + } else if let Some((min, max, _)) = &fa.range { + quote_spanned!(span=> + <#ty as #p::InputField>::sanitize_range(self.#fid, (#min) as f64, (#max) as f64)? + ) + } else { + quote_spanned!(span=> <#ty as #p::InputField>::sanitize_plain(self.#fid)?) + }; + sanitizes.push(quote!(#fid: #sanitize)); + let wire_type = codec.wire_type; + let records = codec.records; + surfaces.push(quote! {{ + #records + #p::PayloadField { + name: #p::std::string::String::from(#name), + ty: #wire_type, + range: #range, + buttons: #p::std::vec![#(#buttons),*], + } + }}); + } + + let consts = if consts.is_empty() { + quote!() + } else { + quote! { + impl #ident { + #(#consts)* + } + } + }; + Ok(quote! { + #consts + + impl #rt::GameInput for #ident { + fn input_surface( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::InputSurface { + let _ = &records; + #p::InputSurface { + name: #p::std::string::String::from(#type_name), + fields: #p::std::vec![#(#surfaces),*], + } + } + + fn encode_input(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode_input(r: &mut #p::Reader<'_>) -> #p::std::result::Result { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + } + + #[allow(clippy::unnecessary_cast)] + fn sanitize(self) -> #p::std::option::Option { + #p::std::option::Option::Some(Self { #(#sanitizes),* }) + } + } + }) +} diff --git a/distributed_game_macros/src/lib.rs b/distributed_game_macros/src/lib.rs new file mode 100644 index 000000000..0a85fcd33 --- /dev/null +++ b/distributed_game_macros/src/lib.rs @@ -0,0 +1,85 @@ +//! Authoring derives for `distributed_game`. Use them through the runtime +//! crate's re-exports (`distributed_game::Replicated`, …); generated code +//! refers to `distributed_game` (renames are resolved). +//! +//! | derive | on | generates | +//! |---|---|---| +//! | [`Replicated`] | struct | `Replicated`: `KindDef` + field values from one field list | +//! | [`GameInput`] | struct | `GameInput`: compact codec, sanitize from `#[range]` / `#[buttons]` | +//! | [`GameEvent`] | struct / enum | `GameEvent`: stable ids, typed payload codec | +//! | [`GameRecord`] | struct | `Wire`: a nested payload record | +//! | [`FactCommand`] | struct | `FactCommand`: the cell command name of a fact input | +//! +//! Field attributes (where they apply): +//! +//! - `#[quant(min = A, max = B, bits = N)]` / `#[quant(centered = R, bits = N)]` +//! (zero exactly representable, `FieldType::quant_centered`) and +//! `#[angle(bits = N)]` on `f32` fields; `#[field_type(EXPR)]` uses any +//! `FieldType` expression (e.g. a shared `const POS: FieldType`). +//! - `#[long]` on a `String` payload field: varuint length instead of the +//! 255-byte short string. +//! - Replicated only: `#[priority(P)]`, `#[correct(ease = MS | ease | snap | replace)]`. +//! - GameInput only: `#[range(min = A, max = B)]` (clamp), `#[buttons(a, b, ..)]` +//! (bit flags, unknown bits cleared; also generates `Type::A`, `Type::B` consts). + +mod event; +mod fact; +mod input; +mod replicated; +mod shared; + +use proc_macro::TokenStream; +use syn::{parse_macro_input, DeriveInput}; + +fn finish(result: syn::Result) -> TokenStream { + result.unwrap_or_else(|e| e.to_compile_error()).into() +} + +/// One replicated entity kind: `#[replicated(kind = "mob", id = 2, +/// priority = 2.0, global, x = field, y = field)]` on a struct with named +/// fields (Rust type → wire type: `bool`, `u8`, `u16`, `u32`, `i32`, `f32`, +/// `String` → short_str, `Vec` → bytes). The interest position is the +/// `x`/`y` fields unless overridden; a kind without a position must be +/// `global`. +#[proc_macro_derive( + Replicated, + attributes(replicated, quant, angle, field_type, priority, correct) +)] +pub fn derive_replicated(input: TokenStream) -> TokenStream { + finish(replicated::expand(parse_macro_input!(input as DeriveInput))) +} + +/// A compact binary input frame. Fields are encoded in order with the +/// shared value codec; `#[range(..)]` clamps, `#[buttons(..)]` masks, +/// non-finite floats reject. +#[proc_macro_derive(GameInput, attributes(quant, angle, field_type, range, buttons))] +pub fn derive_game_input(input: TokenStream) -> TokenStream { + finish(input::expand(parse_macro_input!(input as DeriveInput))) +} + +/// Zone events with stable ids: `#[game_event(id = N, name = "..")]` on a +/// struct, or on every variant of an enum (unit, named fields, or one value +/// such as a `GameRecord`). +#[proc_macro_derive(GameEvent, attributes(game_event, quant, angle, field_type, long))] +pub fn derive_game_event(input: TokenStream) -> TokenStream { + finish(event::expand_event(parse_macro_input!( + input as DeriveInput + ))) +} + +/// A nested payload record (lists of rows, shared structs). +#[proc_macro_derive(GameRecord, attributes(quant, angle, field_type, long))] +pub fn derive_game_record(input: TokenStream) -> TokenStream { + finish(event::expand_record(parse_macro_input!( + input as DeriveInput + ))) +} + +/// Bind a cell command input to its command: +/// `#[fact(command = RECORD_KILL, key(mob, generation))]`. Requires +/// `serde::Serialize`. Identity- and reward-looking field names are +/// rejected. +#[proc_macro_derive(FactCommand, attributes(fact))] +pub fn derive_fact_command(input: TokenStream) -> TokenStream { + finish(fact::expand(parse_macro_input!(input as DeriveInput))) +} diff --git a/distributed_game_macros/src/replicated.rs b/distributed_game_macros/src/replicated.rs new file mode 100644 index 000000000..6bbc286c4 --- /dev/null +++ b/distributed_game_macros/src/replicated.rs @@ -0,0 +1,194 @@ +//! `#[derive(Replicated)]`: one struct = one kind's schema + field encoding. + +use proc_macro2::{Span, TokenStream}; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{DeriveInput, Expr, Ident, LitInt, LitStr}; + +use crate::shared::{ + check_name, field_name, find_attr, named_fields, no_generics, parse_field_attrs, reject, + runtime, Special, +}; + +const MAX_FIELDS: usize = 32; + +struct KindAttrs { + kind: String, + id: u16, + priority: Option, + global: bool, + x: Option, + y: Option, +} + +fn parse_kind_attrs(input: &DeriveInput) -> syn::Result { + let Some(attr) = find_attr(&input.attrs, "replicated") else { + return Err(syn::Error::new( + input.ident.span(), + "#[derive(Replicated)] needs #[replicated(kind = \"name\", id = N)]", + )); + }; + let (mut kind, mut id, mut priority, mut global, mut x, mut y) = + (None, None, None, false, None, None); + attr.parse_nested_meta(|meta| { + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + match key.as_str() { + "kind" => kind = Some(check_name(&meta.value()?.parse::()?)?), + "id" => { + let lit: LitInt = meta.value()?.parse()?; + id = Some(lit.base10_parse::()?); + } + "priority" => priority = Some(meta.value()?.parse::()?), + "global" => global = true, + "x" => x = Some(meta.value()?.parse::()?), + "y" => y = Some(meta.value()?.parse::()?), + _ => { + return Err(meta.error( + "expected `kind`, `id`, `priority`, `global`, `x` or `y` in #[replicated(..)]", + )) + } + } + Ok(()) + })?; + let span = attr.path().span(); + Ok(KindAttrs { + kind: kind + .ok_or_else(|| syn::Error::new(span, "#[replicated(..)] needs `kind = \"name\"`"))?, + id: id.ok_or_else(|| { + syn::Error::new(span, "#[replicated(..)] needs a literal `id = N` (u16)") + })?, + priority, + global, + x, + y, + }) +} + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "Replicated")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let attrs = parse_kind_attrs(&input)?; + let fields = named_fields(&input, "Replicated")?; + if fields.is_empty() { + return Err(syn::Error::new( + input.ident.span(), + "a replicated kind needs at least one field", + )); + } + if fields.len() > MAX_FIELDS { + return Err(syn::Error::new( + fields[MAX_FIELDS].span(), + "at most 32 fields per kind (update masks are 32-bit)", + )); + } + + let mut defs = Vec::new(); + let mut values = Vec::new(); + for field in &fields { + let ident = field.ident.as_ref().expect("named"); + let name = field_name(ident); + let ty = &field.ty; + let fa = parse_field_attrs(field, &rt)?; + reject(fa.range.as_ref().map(|r| r.2), "#[range]", "Replicated")?; + reject(fa.buttons.as_ref().map(|b| b.1), "#[buttons]", "Replicated")?; + let span = ty.span(); + let (field_type, value) = match fa.special.as_ref().map(|s| &s.0) { + None => ( + quote_spanned!(span=> <#ty as #p::EntityField>::FIELD_TYPE), + quote_spanned!(span=> <#ty as #p::EntityField>::to_field_value(&self.#ident)), + ), + Some(Special::FieldType(ft)) => ( + ft.clone(), + quote_spanned!(span=> #p::FieldValue::F(<#ty as #p::QuantizedF32>::get(&self.#ident))), + ), + Some(Special::Long) => return Err(syn::Error::new( + fa.special.as_ref().map_or(Span::call_site(), |s| s.1), + "#[long] strings cannot be replicated (entity strings are short_str, <= 255 bytes)", + )), + }; + let priority = fa + .priority + .as_ref() + .map(|(e, _)| quote!((#e) as f32)) + .unwrap_or(quote!(1.0)); + let correct = fa + .correct + .as_ref() + .map(|(c, _)| quote!(.correct(#c))) + .unwrap_or_default(); + defs.push(quote! { .field_with_priority(#name, #field_type, #priority) #correct }); + values.push(value); + } + + let has = |n: &str| { + fields + .iter() + .find(|f| f.ident.as_ref().is_some_and(|i| field_name(i) == n)) + .and_then(|f| f.ident.clone()) + }; + let check_named = |ident: &Ident| -> syn::Result<()> { + if fields.iter().any(|f| f.ident.as_ref() == Some(ident)) { + Ok(()) + } else { + Err(syn::Error::new( + ident.span(), + format!("no field `{ident}` in this struct"), + )) + } + }; + if let Some(x) = &attrs.x { + check_named(x)?; + } + if let Some(y) = &attrs.y { + check_named(y)?; + } + let pos_x = attrs.x.clone().or_else(|| has("x")); + let pos_y = attrs.y.clone().or_else(|| has("y")); + let position = match (pos_x, pos_y) { + (Some(x), Some(y)) => quote! { (self.#x as f32, self.#y as f32) }, + _ if attrs.global => quote! { (0.0, 0.0) }, + _ => { + return Err(syn::Error::new( + input.ident.span(), + "a non-global kind needs a position: name fields `x` and `y`, point at them with #[replicated(x = .., y = ..)], or mark the kind `global`", + )) + } + }; + + let ident = &input.ident; + let kind = &attrs.kind; + let id = attrs.id; + let global = attrs.global; + let kind_priority = attrs + .priority + .as_ref() + .map(|e| quote!(.priority((#e) as f32))) + .unwrap_or_default(); + Ok(quote! { + impl #rt::Replicated for #ident { + const KIND_ID: u16 = #id; + const KIND_NAME: &'static str = #kind; + const GLOBAL: bool = #global; + + fn kind_def() -> #p::KindDef { + #p::KindDef::new(#id, #kind) + #(#defs)* + #kind_priority + } + + #[allow(clippy::unnecessary_cast)] + fn position(&self) -> (f32, f32) { + #position + } + + fn field_values(&self) -> #p::std::vec::Vec<#p::FieldValue> { + #p::std::vec![#(#values),*] + } + } + }) +} diff --git a/distributed_game_macros/src/shared.rs b/distributed_game_macros/src/shared.rs new file mode 100644 index 000000000..8b7bb5597 --- /dev/null +++ b/distributed_game_macros/src/shared.rs @@ -0,0 +1,405 @@ +//! Attribute parsing and codegen helpers shared by the derives. + +use proc_macro2::{Span, TokenStream}; +use proc_macro_crate::{crate_name, FoundCrate}; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{Attribute, Data, DeriveInput, Expr, Field, Fields, Ident, LitStr, Type}; + +/// `distributed_game` as named by the consuming crate (renames and the +/// crate itself included). +pub(crate) fn runtime() -> syn::Result { + let root = match crate_name("distributed_game") { + Ok(FoundCrate::Itself) => quote!(crate), + Ok(FoundCrate::Name(name)) => { + let ident = Ident::new(&name, Span::call_site()); + quote!(::#ident) + } + Err(error) => { + let message = + format!("unable to resolve `distributed_game` for generated code: {error}"); + return Err(syn::Error::new(Span::call_site(), message)); + } + }; + Ok(root) +} + +/// Rust field name without a raw prefix. +pub(crate) fn field_name(ident: &Ident) -> String { + let name = ident.to_string(); + name.strip_prefix("r#").map(str::to_string).unwrap_or(name) +} + +/// `BoardSnapshot` → `board_snapshot`. +pub(crate) fn snake_case(name: &str) -> String { + let mut out = String::new(); + for (i, c) in name.chars().enumerate() { + if c.is_uppercase() { + if i > 0 { + out.push('_'); + } + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + out +} + +/// Named fields of a struct, or a spanned error naming the derive. +pub(crate) fn named_fields<'a>( + input: &'a DeriveInput, + derive: &str, +) -> syn::Result> { + match &input.data { + Data::Struct(data) => match &data.fields { + Fields::Named(fields) => Ok(fields.named.iter().collect()), + Fields::Unit => Ok(Vec::new()), + Fields::Unnamed(_) => Err(syn::Error::new( + input.ident.span(), + format!("#[derive({derive})] needs a struct with named fields"), + )), + }, + _ => Err(syn::Error::new( + input.ident.span(), + format!("#[derive({derive})] only supports structs"), + )), + } +} + +/// Reject generics (descriptors are per concrete type). +pub(crate) fn no_generics(input: &DeriveInput, derive: &str) -> syn::Result<()> { + if input.generics.params.is_empty() { + Ok(()) + } else { + Err(syn::Error::new( + input.generics.span(), + format!("#[derive({derive})] does not support generic types"), + )) + } +} + +/// Wire-level override of one field, from `#[quant]`, `#[angle]`, +/// `#[field_type]` or `#[long]`. +pub(crate) enum Special { + /// `#[quant(min, max, bits)]` / `#[quant(centered, bits)]` / `#[angle(bits)]` + /// / `#[field_type(EXPR)]`: an `f32` encoded as this `FieldType` expression. + FieldType(TokenStream), + /// `#[long]`: a varuint-length string. + Long, +} + +/// Every per-field attribute a derive may accept. Each derive rejects the +/// ones it does not support. +#[derive(Default)] +pub(crate) struct FieldAttrs { + pub special: Option<(Special, Span)>, + pub priority: Option<(Expr, Span)>, + pub correct: Option<(TokenStream, Span)>, + pub range: Option<(Expr, Expr, Span)>, + pub buttons: Option<(Vec, Span)>, +} + +const FIELD_ATTRS: &[&str] = &[ + "quant", + "angle", + "field_type", + "long", + "priority", + "correct", + "range", + "buttons", +]; + +fn set_special(attrs: &mut FieldAttrs, special: Special, span: Span) -> syn::Result<()> { + if attrs.special.is_some() { + return Err(syn::Error::new( + span, + "only one of #[quant], #[angle], #[field_type] or #[long] per field", + )); + } + attrs.special = Some((special, span)); + Ok(()) +} + +pub(crate) fn parse_field_attrs(field: &Field, rt: &TokenStream) -> syn::Result { + let mut out = FieldAttrs::default(); + for attr in &field.attrs { + let Some(name) = attr.path().get_ident().map(Ident::to_string) else { + continue; + }; + if !FIELD_ATTRS.contains(&name.as_str()) { + continue; + } + let span = attr.path().span(); + match name.as_str() { + "quant" => { + let (mut min, mut max, mut centered, mut bits) = (None, None, None, None); + attr.parse_nested_meta(|meta| { + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + let value: Expr = meta.value()?.parse()?; + match key.as_str() { + "min" => min = Some(value), + "max" => max = Some(value), + "centered" => centered = Some(value), + "bits" => bits = Some(value), + _ => { + return Err(meta.error( + "expected `min`, `max`, `bits` or `centered` in #[quant(..)]", + )) + } + } + Ok(()) + })?; + let Some(bits) = bits else { + return Err(syn::Error::new(span, "#[quant(..)] needs `bits = 1..=32`")); + }; + let ty = match (min, max, centered) { + (Some(min), Some(max), None) => quote! { + #rt::__private::FieldType::QuantF32 { + min: (#min) as f32, + max: (#max) as f32, + bits: (#bits) as u8, + } + }, + (None, None, Some(range)) => quote! { + #rt::__private::FieldType::quant_centered((#range) as f32, (#bits) as u8) + }, + _ => { + return Err(syn::Error::new( + span, + "#[quant(..)] needs either `min` and `max`, or `centered = RANGE` (zero exactly representable)", + )) + } + }; + set_special(&mut out, Special::FieldType(ty), span)?; + } + "angle" => { + let mut bits = None; + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("bits") { + bits = Some(meta.value()?.parse::()?); + Ok(()) + } else { + Err(meta.error("expected `bits` in #[angle(bits = ..)]")) + } + })?; + let Some(bits) = bits else { + return Err(syn::Error::new(span, "#[angle(..)] needs `bits = 1..=32`")); + }; + let ty = quote!(#rt::__private::FieldType::Angle { bits: (#bits) as u8 }); + set_special(&mut out, Special::FieldType(ty), span)?; + } + "field_type" => { + let expr: Expr = attr.parse_args()?; + set_special(&mut out, Special::FieldType(quote!((#expr))), span)?; + } + "long" => { + attr.meta.require_path_only()?; + set_special(&mut out, Special::Long, span)?; + } + "priority" => { + if out.priority.is_some() { + return Err(syn::Error::new(span, "duplicate #[priority]")); + } + out.priority = Some((attr.parse_args()?, span)); + } + "correct" => { + if out.correct.is_some() { + return Err(syn::Error::new(span, "duplicate #[correct]")); + } + let mut policy = None; + attr.parse_nested_meta(|meta| { + if policy.is_some() { + return Err(meta.error("#[correct(..)] takes one policy")); + } + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + policy = Some(match key.as_str() { + "ease" => { + let ms: Expr = if meta.input.peek(syn::Token![=]) { + meta.value()?.parse()? + } else { + syn::parse_quote!(100) + }; + quote!(#rt::__private::Correction::Ease { duration_ms: (#ms) as u32 }) + } + "snap" => quote!(#rt::__private::Correction::Snap), + "replace" => quote!(#rt::__private::Correction::Replace), + _ => return Err(meta.error( + "expected `ease`, `ease = MS`, `snap` or `replace` in #[correct(..)]", + )), + }); + Ok(()) + })?; + let Some(policy) = policy else { + return Err(syn::Error::new(span, "#[correct(..)] needs a policy")); + }; + out.correct = Some((policy, span)); + } + "range" => { + if out.range.is_some() { + return Err(syn::Error::new(span, "duplicate #[range]")); + } + let (mut min, mut max) = (None, None); + attr.parse_nested_meta(|meta| { + let value: Expr = meta.value()?.parse()?; + if meta.path.is_ident("min") { + min = Some(value); + } else if meta.path.is_ident("max") { + max = Some(value); + } else { + return Err(meta.error("expected `min` and `max` in #[range(..)]")); + } + Ok(()) + })?; + match (min, max) { + (Some(min), Some(max)) => out.range = Some((min, max, span)), + _ => { + return Err(syn::Error::new( + span, + "#[range(..)] needs both `min` and `max`", + )) + } + } + } + "buttons" => { + if out.buttons.is_some() { + return Err(syn::Error::new(span, "duplicate #[buttons]")); + } + let mut names = Vec::new(); + attr.parse_nested_meta(|meta| { + let Some(ident) = meta.path.get_ident() else { + return Err(meta.error("button names are identifiers")); + }; + if names.iter().any(|n: &Ident| n == ident) { + return Err(meta.error("duplicate button name")); + } + names.push(ident.clone()); + Ok(()) + })?; + if names.is_empty() || names.len() > 32 { + return Err(syn::Error::new(span, "#[buttons(..)] names 1..=32 bits")); + } + out.buttons = Some((names, span)); + } + _ => unreachable!(), + } + } + Ok(out) +} + +/// Error for an attribute a derive does not accept on fields. +pub(crate) fn reject(span: Option, what: &str, derive: &str) -> syn::Result<()> { + match span { + Some(span) => Err(syn::Error::new( + span, + format!("{what} is not supported by #[derive({derive})]"), + )), + None => Ok(()), + } +} + +/// One payload field's encode / decode / descriptor tokens (inputs, events, +/// records). +pub(crate) struct PayloadCodec { + pub encode: TokenStream, + pub decode: TokenStream, + pub wire_type: TokenStream, + pub records: TokenStream, +} + +/// Codec tokens for `value` (an expression of type `&ty`) of a payload field. +pub(crate) fn payload_codec( + ty: &Type, + value: TokenStream, + special: Option<&Special>, + rt: &TokenStream, +) -> PayloadCodec { + let p = quote!(#rt::__private); + let span = ty.span(); + match special { + // `Vec` encodes like any list of bytes (varuint count + bytes) — + // identical to `bytes` — but is described as `bytes` so generated + // clients get a `Uint8Array`. + None if is_byte_vec(ty) => PayloadCodec { + encode: quote_spanned!(span=> <#ty as #p::Wire>::encode(#value, w);), + decode: quote_spanned!(span=> <#ty as #p::Wire>::decode(r)?), + wire_type: quote!(#p::WireType::Bytes), + records: quote!(), + }, + None => PayloadCodec { + encode: quote_spanned!(span=> <#ty as #p::Wire>::encode(#value, w);), + decode: quote_spanned!(span=> <#ty as #p::Wire>::decode(r)?), + wire_type: quote_spanned!(span=> <#ty as #p::Wire>::wire_type()), + records: quote_spanned!(span=> <#ty as #p::Wire>::records(records);), + }, + Some(Special::FieldType(ft)) => PayloadCodec { + encode: quote_spanned!(span=> + #p::special::encode_f32(w, #ft, <#ty as #p::QuantizedF32>::get(#value)); + ), + decode: quote_spanned!(span=> + <#ty as #p::QuantizedF32>::from_f32(#p::special::decode_f32(r, #ft)?) + ), + wire_type: quote!(#p::WireType::of_field(#ft)), + records: quote!(), + }, + Some(Special::Long) => PayloadCodec { + encode: quote_spanned!(span=> + #p::special::encode_long(w, <#ty as #p::LongString>::text(#value)); + ), + decode: quote_spanned!(span=> + <#ty as #p::LongString>::from_text(#p::special::decode_long(r)?) + ), + wire_type: quote!(#p::WireType::Str), + records: quote!(), + }, + } +} + +/// `Vec` written as such (aliases are not seen). +fn is_byte_vec(ty: &Type) -> bool { + let Type::Path(path) = ty else { return false }; + let Some(last) = path.path.segments.last() else { + return false; + }; + if last.ident != "Vec" { + return false; + } + let syn::PathArguments::AngleBracketed(args) = &last.arguments else { + return false; + }; + matches!( + args.args.first(), + Some(syn::GenericArgument::Type(Type::Path(inner))) if inner.path.is_ident("u8") + ) && args.args.len() == 1 +} + +/// A `name = "..."` / `id = N` style container attribute. +pub(crate) fn find_attr<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attribute> { + attrs.iter().find(|a| a.path().is_ident(name)) +} + +/// Validate a wire name (non-empty, ASCII identifier-ish). +pub(crate) fn check_name(lit: &LitStr) -> syn::Result { + let value = lit.value(); + let ok = !value.is_empty() + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'); + if ok { + Ok(value) + } else { + Err(syn::Error::new( + lit.span(), + "names are non-empty ASCII letters, digits, `_` or `-`", + )) + } +} diff --git a/distributed_game_macros/tests/compile_fail.rs b/distributed_game_macros/tests/compile_fail.rs new file mode 100644 index 000000000..9d4502ad5 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail.rs @@ -0,0 +1,11 @@ +//! Compile-fail suite for `distributed_game_macros`. +//! +//! Each fixture in `tests/compile_fail/` must fail with a pointed, spanned +//! diagnostic; the `.stderr` snapshot pins it. Regenerate with +//! `TRYBUILD=overwrite cargo test -p distributed_game_macros`. + +#[test] +fn compile_fail() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile_fail/*.rs"); +} diff --git a/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs b/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs new file mode 100644 index 000000000..c19c0de16 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs @@ -0,0 +1,11 @@ +use distributed_game::GameEvent; + +#[derive(GameEvent)] +enum ZoneEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, + #[game_event(id = 1)] + Bye, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr b/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr new file mode 100644 index 000000000..0df9c0d7a --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr @@ -0,0 +1,5 @@ +error: event id 1 / name `bye` already used by `hello` + --> tests/compile_fail/event_duplicate_id.rs:7:23 + | +7 | #[game_event(id = 1)] + | ^ diff --git a/distributed_game_macros/tests/compile_fail/event_missing_id.rs b/distributed_game_macros/tests/compile_fail/event_missing_id.rs new file mode 100644 index 000000000..acbc006f9 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_missing_id.rs @@ -0,0 +1,10 @@ +use distributed_game::GameEvent; + +#[derive(GameEvent)] +enum ZoneEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, + Bye, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/event_missing_id.stderr b/distributed_game_macros/tests/compile_fail/event_missing_id.stderr new file mode 100644 index 000000000..8f2b82ea7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_missing_id.stderr @@ -0,0 +1,5 @@ +error: every event variant needs #[game_event(id = N)] (a stable u32 type id) + --> tests/compile_fail/event_missing_id.rs:7:5 + | +7 | Bye, + | ^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_field.rs b/distributed_game_macros/tests/compile_fail/fact_identity_field.rs new file mode 100644 index 000000000..6023b8b14 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_field.rs @@ -0,0 +1,10 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.record_kill")] +struct RecordKill { + mob: String, + principal: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr b/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr new file mode 100644 index 000000000..3707c3aac --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr @@ -0,0 +1,5 @@ +error: fact input field `principal` looks like identity: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards + --> tests/compile_fail/fact_identity_field.rs:7:5 + | +7 | principal: String, + | ^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_missing_command.rs b/distributed_game_macros/tests/compile_fail/fact_missing_command.rs new file mode 100644 index 000000000..21b24d8a1 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_missing_command.rs @@ -0,0 +1,8 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +struct RecordKill { + mob: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr b/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr new file mode 100644 index 000000000..2793042a3 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr @@ -0,0 +1,5 @@ +error: #[derive(FactCommand)] needs #[fact(command = COMMAND_NAME)] (the constant the cell mounts the command under, or a string literal) + --> tests/compile_fail/fact_missing_command.rs:4:8 + | +4 | struct RecordKill { + | ^^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_reward_field.rs b/distributed_game_macros/tests/compile_fail/fact_reward_field.rs new file mode 100644 index 000000000..20944d60b --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_reward_field.rs @@ -0,0 +1,11 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.record_kill")] +struct RecordKill { + mob: String, + #[serde(rename = "XP")] + amount: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr b/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr new file mode 100644 index 000000000..4bf6b46a6 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr @@ -0,0 +1,5 @@ +error: fact input field `XP` looks like a reward: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards + --> tests/compile_fail/fact_reward_field.rs:7:22 + | +7 | #[serde(rename = "XP")] + | ^^^^ diff --git a/distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs b/distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs new file mode 100644 index 000000000..ab9997be7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/input_buttons_on_float.rs @@ -0,0 +1,9 @@ +use distributed_game::GameInput; + +#[derive(GameInput)] +struct PadInput { + #[buttons(jump, duck)] + buttons: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr b/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr new file mode 100644 index 000000000..5ecf53ade --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/input_buttons_on_float.stderr @@ -0,0 +1,23 @@ +error[E0277]: `#[buttons]` needs a u8, u16 or u32 field, not `f32` + --> tests/compile_fail/input_buttons_on_float.rs:6:14 + | +6 | buttons: f32, + | ---------^^^ + | | | + | | button bits live in an unsigned integer + | `f32` doesn't satisfy the trait bound + | + = help: the trait `ButtonBits` is not implemented for `f32` +help: the following other types implement trait `ButtonBits` + --> $WORKSPACE/distributed_game/src/codec.rs + | + | impl ButtonBits for $ty { + | ^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `u16` + | `u32` + | `u8` +... + | button_bits!(u8, u16, u32); + | -------------------------- in this macro invocation + = note: this error originates in the macro `button_bits` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/distributed_game_macros/tests/compile_fail/input_unsupported_field.rs b/distributed_game_macros/tests/compile_fail/input_unsupported_field.rs new file mode 100644 index 000000000..6b56e28e7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/input_unsupported_field.rs @@ -0,0 +1,8 @@ +use distributed_game::GameInput; + +#[derive(GameInput)] +struct ChatInput { + text: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr b/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr new file mode 100644 index 000000000..38d6993b4 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/input_unsupported_field.stderr @@ -0,0 +1,20 @@ +error[E0277]: `String` cannot be a game input field + --> tests/compile_fail/input_unsupported_field.rs:5:11 + | +5 | text: String, + | ------^^^^^^ + | | | + | | unsupported input field type + | `String` doesn't satisfy the trait bound + | + = help: the trait `InputField` is not implemented for `String` + = note: inputs are small fixed scalars: bool, u8, i8, u16, i16, u32, i32 or f32 (optionally #[quant]/#[angle]) + = help: the following other types implement trait `InputField`: + bool + f32 + i16 + i32 + i8 + u16 + u32 + u8 diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs new file mode 100644 index 000000000..e4319b01e --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs @@ -0,0 +1,9 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +struct OrbView { + x: f32, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr new file mode 100644 index 000000000..703985edc --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr @@ -0,0 +1,5 @@ +error: #[derive(Replicated)] needs #[replicated(kind = "name", id = N)] + --> tests/compile_fail/replicated_needs_kind.rs:4:8 + | +4 | struct OrbView { + | ^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs b/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs new file mode 100644 index 000000000..bf2f16687 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs @@ -0,0 +1,9 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "score", id = 3)] +struct ScoreView { + points: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr b/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr new file mode 100644 index 000000000..f2d61d254 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr @@ -0,0 +1,5 @@ +error: a non-global kind needs a position: name fields `x` and `y`, point at them with #[replicated(x = .., y = ..)], or mark the kind `global` + --> tests/compile_fail/replicated_needs_position.rs:5:8 + | +5 | struct ScoreView { + | ^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs b/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs new file mode 100644 index 000000000..6ee2b99dc --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + #[quant(min = 0.0, max = 10.0, bits = 8)] + x: u8, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr b/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr new file mode 100644 index 000000000..025cf5611 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_quant_on_integer.stderr @@ -0,0 +1,12 @@ +error[E0277]: `#[quant]` / `#[angle]` need an `f32` field, not `u8` + --> tests/compile_fail/replicated_quant_on_integer.rs:7:8 + | +7 | x: u8, + | ^^ quantize an f32 + | + = help: the trait `QuantizedF32` is not implemented for `u8` +help: the trait `QuantizedF32` is implemented for `f32` + --> $WORKSPACE/distributed_game/src/codec.rs + | + | impl QuantizedF32 for f32 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs new file mode 100644 index 000000000..6bafa1254 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + #[correct(wobble)] + x: f32, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr new file mode 100644 index 000000000..4544bd728 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr @@ -0,0 +1,5 @@ +error: expected `ease`, `ease = MS`, `snap` or `replace` in #[correct(..)] + --> tests/compile_fail/replicated_unknown_correction.rs:6:15 + | +6 | #[correct(wobble)] + | ^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs b/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs new file mode 100644 index 000000000..6d58f301f --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + x: f32, + y: f32, + charge: i8, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr b/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr new file mode 100644 index 000000000..d44fa8440 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unsupported_type.stderr @@ -0,0 +1,14 @@ +error[E0277]: `i8` cannot be a replicated entity field + --> tests/compile_fail/replicated_unsupported_type.rs:8:13 + | +8 | charge: i8, + | ^^ unsupported entity field type + | + = help: the trait `EntityField` is not implemented for `i8` + = note: supported: bool, u8, u16, u32, i32, f32 (optionally #[quant]/#[angle]), String (short_str) and Vec (bytes) + = help: the following other types implement trait `EntityField`: + f32 + i32 + u16 + u32 + u8 From ee5acf3b2e7dd6a3285fa085e751edc203c4f994 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:24:04 -0500 Subject: [PATCH 179/484] feat(game-sdk): add typed payload codec and generated-client helpers Mirror distributed_game's payload codec (encodePayload, decodeValue, sanitizePayload, varuint53) and add typed event codecs, onGameEvent and entity field readers for clients generated from a game surface. A new test round-trips the generated golden client against Rust samples. --- js/.gitignore | 1 + js/src/game/codec.ts | 282 +++++++++++++++++++++++++++++++ js/src/game/index.ts | 28 +++ js/src/game/typed.ts | 90 ++++++++++ js/src/game/wire.ts | 37 ++++ js/tests/game-generated.test.mjs | 109 ++++++++++++ js/tsconfig.generated-tests.json | 27 ++- 7 files changed, 568 insertions(+), 6 deletions(-) create mode 100644 js/src/game/codec.ts create mode 100644 js/src/game/typed.ts create mode 100644 js/tests/game-generated.test.mjs diff --git a/js/.gitignore b/js/.gitignore index e72899590..9f38a2233 100644 --- a/js/.gitignore +++ b/js/.gitignore @@ -1,3 +1,4 @@ dist/ node_modules/ *.tgz +tests/.generated-*/ diff --git a/js/src/game/codec.ts b/js/src/game/codec.ts new file mode 100644 index 000000000..936c19206 --- /dev/null +++ b/js/src/game/codec.ts @@ -0,0 +1,282 @@ +/** + * Typed payload codec (`distributed_game::codec`): the value encoding of + * inputs, events and records described by a game surface. Scalar encodings + * are the entity field encodings (`PROTOCOL.md` §4), so one value means the + * same bytes everywhere. Code generated by `distributed game-client` drives + * it with layout constants; hand-written code may use it directly. + */ +import { GameDecodeError, WireReader, WireWriter } from './wire.js'; +import { dequantizeAngle, dequantizeLinear, quantizeAngle, quantizeLinear } from './schema.js'; + +export type WireType = + | Readonly<{ type: 'bool' }> + | Readonly<{ type: 'u8' }> + | Readonly<{ type: 'i8' }> + | Readonly<{ type: 'u16' }> + | Readonly<{ type: 'i16' }> + | Readonly<{ type: 'u32' }> + | Readonly<{ type: 'i32' }> + | Readonly<{ type: 'u64' }> + | Readonly<{ type: 'f32' }> + | Readonly<{ type: 'f64' }> + | Readonly<{ type: 'quant'; min: number; max: number; bits: number }> + | Readonly<{ type: 'angle'; bits: number }> + | Readonly<{ type: 'short_str' }> + | Readonly<{ type: 'str' }> + | Readonly<{ type: 'bytes' }> + | Readonly<{ type: 'list'; item: WireType }> + | Readonly<{ type: 'optional'; item: WireType }> + | Readonly<{ type: 'record'; fields: PayloadLayout }>; + +/** Ordered `[property, type]` pairs (property names are the TS names). */ +export type PayloadLayout = readonly (readonly [string, WireType])[]; + +const INT_RANGE: Readonly> = { + u8: [0, 255], + i8: [-128, 127], + u16: [0, 65535], + i16: [-32768, 32767], + u32: [0, 0xffff_ffff], + i32: [-0x8000_0000, 0x7fff_ffff], + u64: [0, Number.MAX_SAFE_INTEGER] +}; + +function num(value: unknown): number { + if (typeof value === 'number') return value; + if (typeof value === 'boolean') return value ? 1 : 0; + return 0; +} + +/** Rust `f64 as int` semantics: NaN → 0, saturating, truncating. */ +function saturate(n: number, lo: number, hi: number): number { + if (Number.isNaN(n)) return 0; + return Math.trunc(Math.min(Math.max(n, lo), hi)); +} + +const utf8 = new TextEncoder(); + +/** Append `value` as `type`, coercing numbers into the type's range. */ +export function writeWire(w: WireWriter, type: WireType, value: unknown): void { + switch (type.type) { + case 'bool': + w.bool(value === true || (typeof value === 'number' && value !== 0)); + return; + case 'u8': + w.u8(saturate(num(value), 0, 255)); + return; + case 'i8': + w.u8(saturate(num(value), -128, 127) & 0xff); + return; + case 'u16': + case 'u32': + w.varuint(saturate(num(value), ...INT_RANGE[type.type])); + return; + case 'i16': + case 'i32': + w.varint(saturate(num(value), ...INT_RANGE[type.type])); + return; + case 'u64': + w.varuint53(saturate(num(value), 0, Number.MAX_SAFE_INTEGER)); + return; + case 'f32': + w.f32(num(value)); + return; + case 'f64': + w.f64(num(value)); + return; + case 'quant': + w.varuint(quantizeLinear(num(value), type.min, type.max, type.bits)); + return; + case 'angle': + w.varuint(quantizeAngle(num(value), type.bits)); + return; + case 'short_str': + w.shortString(typeof value === 'string' ? value : ''); + return; + case 'str': + w.string(typeof value === 'string' ? value : ''); + return; + case 'bytes': + w.bytes( + value instanceof Uint8Array + ? value + : typeof value === 'string' + ? utf8.encode(value) + : Array.isArray(value) + ? Uint8Array.from(value as number[]) + : new Uint8Array(0) + ); + return; + case 'list': { + const items = Array.isArray(value) ? value : []; + w.varuint(items.length); + for (const item of items) writeWire(w, type.item, item); + return; + } + case 'optional': + if (value === undefined || value === null) { + w.u8(0); + } else { + w.u8(1); + writeWire(w, type.item, value); + } + return; + case 'record': { + const object = (value ?? {}) as Record; + for (const [name, field] of type.fields) writeWire(w, field, object[name]); + return; + } + } +} + +/** Read one value of `type` (optional `none` decodes as `undefined`). */ +export function readWire(r: WireReader, type: WireType): unknown { + switch (type.type) { + case 'bool': + return r.bool(); + case 'u8': + return r.u8(); + case 'i8': { + const byte = r.u8(); + return byte > 127 ? byte - 256 : byte; + } + case 'u16': { + const v = r.varuint(); + if (v > 65535) throw new GameDecodeError('INVALID', 'u16 out of range'); + return v; + } + case 'i16': { + const v = r.varint(); + if (v < -32768 || v > 32767) throw new GameDecodeError('INVALID', 'i16 out of range'); + return v; + } + case 'u32': + return r.varuint(); + case 'i32': + return r.varint(); + case 'u64': + return r.varuint53(); + case 'f32': + return r.f32(); + case 'f64': + return r.f64(); + case 'quant': { + const q = r.varuint(); + if (q > 2 ** type.bits - 1) { + throw new GameDecodeError('INVALID', 'quantized value out of range'); + } + return dequantizeLinear(q, type.min, type.max, type.bits); + } + case 'angle': { + const q = r.varuint(); + if (q >= 2 ** type.bits) throw new GameDecodeError('INVALID', 'angle out of range'); + return dequantizeAngle(q, type.bits); + } + case 'short_str': + return r.shortString(); + case 'str': + return r.string(); + case 'bytes': + return r.bytes(); + case 'list': { + const count = r.varuint(); + if (count > r.remaining) throw new GameDecodeError('UNEXPECTED_EOF', 'list longer than input'); + const out: unknown[] = []; + for (let i = 0; i < count; i += 1) out.push(readWire(r, type.item)); + return out; + } + case 'optional': { + const tag = r.u8(); + if (tag === 0) return undefined; + if (tag === 1) return readWire(r, type.item); + throw new GameDecodeError('INVALID', 'option tag must be 0 or 1'); + } + case 'record': + return readFields(r, type.fields); + } +} + +function readFields(r: WireReader, layout: PayloadLayout): Record { + const out: Record = {}; + for (const [name, type] of layout) out[name] = readWire(r, type); + return out; +} + +/** Encode an object field by field. */ +export function encodePayload(layout: PayloadLayout, value: object): Uint8Array { + const w = new WireWriter(); + const object = value as Record; + for (const [name, type] of layout) writeWire(w, type, object[name]); + return w.finish(); +} + +/** Decode a whole payload (trailing bytes are an error). */ +export function decodePayload(layout: PayloadLayout, payload: Uint8Array): Record { + const r = new WireReader(payload); + const out = readFields(r, layout); + r.finish(); + return out; +} + +/** Encode one value (a `Variant(T)` event payload). */ +export function encodeValue(type: WireType, value: unknown): Uint8Array { + const w = new WireWriter(); + writeWire(w, type, value); + return w.finish(); +} + +/** Decode one whole value. */ +export function decodeValue(type: WireType, payload: Uint8Array): unknown { + const r = new WireReader(payload); + const out = readWire(r, type); + r.finish(); + return out; +} + +/** What the receiver decodes for `value` (encode → decode). */ +export function canonicalWire(type: WireType, value: unknown): unknown { + return decodeValue(type, encodeValue(type, value)); +} + +/** One input field's server-side sanitize rule. */ +export type InputRule = + | Readonly<{ range: readonly [number, number] }> + | Readonly<{ buttons: number }> + | undefined; + +/** + * Mirror of the server's `GameInput::from_payload`: what the zone will + * simulate for `input` (wire coercion, then `#[range]` clamp, `#[buttons]` + * mask; a non-finite float rejects the whole input → `undefined`). + */ +export function sanitizePayload( + layout: PayloadLayout, + rules: readonly InputRule[], + input: T +): T | undefined { + const decoded = decodePayload(layout, encodePayload(layout, input)); + const object = input as Record; + for (let i = 0; i < layout.length; i += 1) { + const [name, type] = layout[i]; + const rule = rules[i]; + let v = decoded[name]; + if (type.type === 'f32' || type.type === 'f64') { + const raw = num(object[name]); + if (!Number.isFinite(raw)) return undefined; + } + if (typeof v === 'number' && rule !== undefined) { + if ('range' in rule) { + v = Math.min(Math.max(v, rule.range[0]), rule.range[1]); + if (type.type !== 'f32' && type.type !== 'f64' && type.type !== 'quant' && type.type !== 'angle') { + v = Math.trunc(v as number); + } else { + v = Math.fround(v as number); + } + } else { + v = (v & rule.buttons) >>> 0; + } + } + decoded[name] = v; + } + return decoded as T; +} diff --git a/js/src/game/index.ts b/js/src/game/index.ts index 4183adab6..a19174d30 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -9,6 +9,8 @@ * adaptive interpolation delay, runtime prediction toggle. * - `AdaptiveDelay` / `InputPacer`: network-following render delay and * one-input-per-tick pacing for render loops. + * - Typed payload codec (`encodePayload`, …) and helpers for clients + * generated by `distributed game-client` from a Rust game surface. */ export { MAX_BLOB_LEN, @@ -74,6 +76,32 @@ export { type ResumeMessage, type WelcomeMessage } from './messages.js'; +export { + canonicalWire, + decodePayload, + decodeValue, + encodePayload, + encodeValue, + readWire, + sanitizePayload, + writeWire, + type InputRule, + type PayloadLayout, + type WireType +} from './codec.js'; +export { + decodeGameEvent, + fieldBool, + fieldBytes, + fieldNumber, + fieldString, + mergeCorrections, + onGameEvent, + type DecodedGameEvent, + type GameEventCodec, + type GameEventCodecs, + type GameEventSource +} from './typed.js'; export { ClockSync, type ClockSample, type ClockSyncOptions } from './clock.js'; export { GameConnection, diff --git a/js/src/game/typed.ts b/js/src/game/typed.ts new file mode 100644 index 000000000..8514b2e43 --- /dev/null +++ b/js/src/game/typed.ts @@ -0,0 +1,90 @@ +/** + * Helpers for clients generated by `distributed game-client` from a Rust + * game surface: typed event codecs and subscriptions, typed reads of + * replicated entity fields, and correction-default merging. + */ +import type { GameClient } from './client.js'; +import type { EventMessage } from './messages.js'; +import type { CorrectionPolicies } from './prediction.js'; +import type { EntityFields } from './replica.js'; + +/** One event type: stable id, name and payload codec. */ +export type GameEventCodec = Readonly<{ + id: number; + name: string; + encode(value: T): Uint8Array; + decode(payload: Uint8Array): T; +}>; + +/** Codecs of a surface's events, keyed by event name. */ +export type GameEventCodecs = { readonly [K in keyof M]: GameEventCodec }; + +/** A decoded event: `{ name, value }` discriminated by name. */ +export type DecodedGameEvent = { [K in keyof M]: Readonly<{ name: K; value: M[K] }> }[keyof M]; + +/** Anything that emits `('event', zoneId, EventMessage)` (a `GameClient`). */ +export type GameEventSource = Pick, 'on'>; + +/** Decode an Event message; `undefined` for type ids not in `codecs`. */ +export function decodeGameEvent( + codecs: GameEventCodecs, + event: Pick +): DecodedGameEvent | undefined { + for (const name of Object.keys(codecs) as (keyof M)[]) { + const codec = codecs[name]; + if (codec.id === event.typeId) { + return { name, value: codec.decode(event.payload) } as DecodedGameEvent; + } + } + return undefined; +} + +/** Subscribe to one typed event of every zone of `client`; returns the unsubscribe. */ +export function onGameEvent( + client: GameEventSource, + codecs: GameEventCodecs, + name: K, + handler: (value: M[K], zoneId: string) => void +): () => void { + const codec = codecs[name]; + return (client as Pick, 'on'>).on('event', (zoneId, event) => { + if (event.typeId !== codec.id) return; + handler(codec.decode(event.payload), zoneId); + }); +} + +/** A replicated number field (0 when missing or not numeric). */ +export function fieldNumber(fields: EntityFields, name: string): number { + const v = fields[name]; + return typeof v === 'number' ? v : typeof v === 'boolean' ? (v ? 1 : 0) : 0; +} + +/** A replicated `bool` field. */ +export function fieldBool(fields: EntityFields, name: string): boolean { + const v = fields[name]; + return v === true || (typeof v === 'number' && v !== 0); +} + +/** A replicated `short_str` field. */ +export function fieldString(fields: EntityFields, name: string): string { + const v = fields[name]; + return typeof v === 'string' ? v : ''; +} + +/** A replicated `bytes` field. */ +export function fieldBytes(fields: EntityFields, name: string): Uint8Array { + const v = fields[name]; + return v instanceof Uint8Array ? v : new Uint8Array(0); +} + +/** `defaults` with `overrides` applied per kind and field. */ +export function mergeCorrections( + defaults: CorrectionPolicies, + overrides: CorrectionPolicies | undefined +): CorrectionPolicies { + if (overrides === undefined) return defaults; + const out: Record> = {}; + for (const [kind, fields] of Object.entries(defaults)) out[kind] = { ...fields }; + for (const [kind, fields] of Object.entries(overrides)) out[kind] = { ...out[kind], ...fields }; + return out; +} diff --git a/js/src/game/wire.ts b/js/src/game/wire.ts index 394e30e04..9af197691 100644 --- a/js/src/game/wire.ts +++ b/js/src/game/wire.ts @@ -110,6 +110,27 @@ export class WireWriter { } } + /** + * Unsigned LEB128 of an integer up to `2^53 - 1` (typed game payloads' + * `u64`; no protocol message uses it). + */ + varuint53(value: number): this { + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError(`varuint53 must be a safe unsigned integer, got ${value}`); + } + let v = value; + this.#reserve(8); + for (;;) { + const byte = v % 128; + v = Math.floor(v / 128); + if (v === 0) { + this.#buf[this.#len++] = byte; + return this; + } + this.#buf[this.#len++] = byte | 0x80; + } + } + /** Zigzag-mapped signed varint. */ varint(value: number): this { const v = assertI32(value, 'varint'); @@ -203,6 +224,22 @@ export class WireReader { throw new GameDecodeError('VARINT_OVERFLOW', 'varuint exceeds 32 bits'); } + /** Unsigned LEB128 up to `2^53 - 1` (see `WireWriter.varuint53`). */ + varuint53(): number { + let value = 0; + for (let index = 0; index < 8; index += 1) { + const byte = this.u8(); + value += (byte & 0x7f) * 2 ** (7 * index); + if ((byte & 0x80) === 0) { + if (value > Number.MAX_SAFE_INTEGER) { + throw new GameDecodeError('VARINT_OVERFLOW', 'varuint exceeds 2^53 - 1'); + } + return value; + } + } + throw new GameDecodeError('VARINT_OVERFLOW', 'varuint exceeds 2^53 - 1'); + } + varint(): number { const z = this.varuint(); return (z >>> 1) ^ -(z & 1); diff --git a/js/tests/game-generated.test.mjs b/js/tests/game-generated.test.mjs new file mode 100644 index 000000000..4bd33a1dc --- /dev/null +++ b/js/tests/game-generated.test.mjs @@ -0,0 +1,109 @@ +// Generated game clients (`distributed game-client`) against Rust. +// +// `distributed_game/tests/fixtures/authoring.json` holds a sample surface and +// payloads encoded by the Rust derives; the TypeScript generated from that +// surface is pinned in `distributed_cli/tests/fixtures/game-client/sample/`. +// This test loads the generated files (Node strips their types) and checks +// they encode and decode byte-for-byte like Rust. +import assert from 'node:assert/strict'; +import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { after, before, test } from 'node:test'; + +import { fromHex, toHex } from '@hops-ops/distributed/game'; + +const fixture = JSON.parse( + readFileSync(new URL('../../distributed_game/tests/fixtures/authoring.json', import.meta.url), 'utf8') +); +const GOLDEN = fileURLToPath(new URL('../../distributed_cli/tests/fixtures/game-client/sample/', import.meta.url)); + +let dir; +let gen; +before(async () => { + // Inside the package so `@hops-ops/distributed/game` resolves to this build. + dir = mkdtempSync(fileURLToPath(new URL('./.generated-', import.meta.url))); + cpSync(GOLDEN, dir, { recursive: true }); + gen = await import(pathToFileURL(`${dir}/index.ts`).href); +}); +after(() => rmSync(dir, { recursive: true, force: true })); + +const camel = (name) => name.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()); + +/** JSON fixture values → what the decoder returns (null → undefined, byte arrays). */ +function normalize(value) { + if (value instanceof Uint8Array) return [...value]; + if (value === null) return undefined; + if (Array.isArray(value)) return value.map(normalize); + if (typeof value === 'object') { + const out = {}; + for (const [k, v] of Object.entries(value)) out[k] = normalize(v); + return out; + } + return value; +} + +test('input encoder, decoder and sanitize match the Rust derive', () => { + const { value, hex, decoded, sanitized } = fixture.input; + assert.equal(toHex(gen.encodeInput(value)), hex); + assert.deepEqual(gen.decodeInput(fromHex(hex)), decoded); + assert.deepEqual(gen.sanitizeInput(value), sanitized); + assert.equal(gen.sanitizeInput({ ...value, power: Number.NaN }), undefined, 'non-finite floats reject'); + assert.deepEqual(gen.BUTTON, { dash: 1, attack: 2 }); +}); + +test('every event encodes and decodes like Rust', () => { + for (const sample of fixture.events) { + const codec = gen.EVENTS[camel(sample.name)]; + assert.equal(codec.id, sample.id); + const value = normalize(sample.value); + const bytes = codec.encode(sample.value); + assert.equal(toHex(bytes), sample.hex, `${sample.name} encodes`); + const decoded = codec.decode(fromHex(sample.hex)); + assert.deepEqual(normalize(decoded), value, `${sample.name} decodes`); + const any = gen.decodeEvent({ typeId: sample.id, payload: fromHex(sample.hex) }); + assert.equal(any.name, camel(sample.name)); + } + assert.equal(gen.decodeEvent({ typeId: 999, payload: new Uint8Array() }), undefined); + assert.throws(() => gen.EVENTS.hello.decode(fromHex('01'))); +}); + +test('kinds, typed field accessors and correction defaults follow the surface', () => { + const surface = fixture.surface; + for (const kind of surface.kinds) assert.equal(gen.KIND[camel(kind.name)], kind.id); + const fields = { x: 1.5, y: 2, vx: 0, face: 3, name: 'Ada', hp: 9, level: 2, dead: true, score: -1, raw: 0.5, blob: new Uint8Array([1]), kills: 4 }; + const player = gen.playerFields({ kind: 1, fields }); + assert.equal(player.name, 'Ada'); + assert.equal(player.dead, true); + assert.deepEqual([...player.blob], [1]); + assert.equal(gen.isPlayer({ kind: 1 }), true); + assert.equal(gen.isStats({ kind: 1 }), false); + assert.deepEqual(gen.statsFields({ fields: { slow_ms: 12, tick_ms: 33 } }), { slowMs: 12, tickMs: 33 }); + assert.deepEqual(gen.CORRECTIONS.player.x, { mode: 'ease', durationMs: 150 }); + assert.deepEqual(gen.CORRECTIONS.player.name, { mode: 'replace' }); + assert.deepEqual(gen.FIELD_TYPES.player.x, surface.kinds[0].fields[0].type); +}); + +test('typed subscriptions decode only their own event', () => { + const listeners = []; + const source = { on: (type, listener) => (listeners.push([type, listener]), () => undefined) }; + const seen = []; + gen.onEvent(source, 'ping', (value, zone) => seen.push([value, zone])); + const ping = fixture.events.find((e) => e.name === 'hello'); + for (const [type, listener] of listeners) { + assert.equal(type, 'event'); + listener('z1', { typeId: 9, payload: gen.EVENTS.ping.encode({ seq: 5 }) }); + listener('z1', { typeId: ping.id, payload: fromHex(ping.hex) }); + } + assert.deepEqual(seen, [[{ seq: 5 }, 'z1']]); +}); + +test('the client factory wires the encoder and merged corrections', () => { + const typed = gen.createSampleClient({ + url: () => 'ws://unused', + ticket: async () => 'unused', + prediction: { predict: (state) => state, corrections: { player: { y: { mode: 'snap' } } } } + }); + assert.equal(typeof typed.client.sendInput, 'function'); + assert.equal(typed.send({ mx: 0, my: 0, buttons: 0, aim: 0, power: 0, viewTick: 0 }), undefined, 'not connected'); + typed.client.close(); +}); diff --git a/js/tsconfig.generated-tests.json b/js/tsconfig.generated-tests.json index 3a19aed02..8cf891051 100644 --- a/js/tsconfig.generated-tests.json +++ b/js/tsconfig.generated-tests.json @@ -10,16 +10,31 @@ "noEmit": true, "outDir": "./dist-type-tests", "paths": { - "@hops-ops/distributed/replica": ["./src/replica/index.ts"], - "@hops-ops/distributed/replica/lazy": ["./src/replica/lazy.ts"], - "@hops-ops/distributed/react": ["./src/react/index.ts"], - "@hops-ops/distributed/sveltekit": ["./src/sveltekit/index.ts"], - "@hops-ops/distributed/sveltekit/vite": ["./src/sveltekit/vite.ts"] + "@hops-ops/distributed/replica": [ + "./src/replica/index.ts" + ], + "@hops-ops/distributed/replica/lazy": [ + "./src/replica/lazy.ts" + ], + "@hops-ops/distributed/react": [ + "./src/react/index.ts" + ], + "@hops-ops/distributed/sveltekit": [ + "./src/sveltekit/index.ts" + ], + "@hops-ops/distributed/sveltekit/vite": [ + "./src/sveltekit/vite.ts" + ], + "@hops-ops/distributed/game": [ + "./src/game/index.ts" + ] }, - "rootDir": ".." + "rootDir": "..", + "allowImportingTsExtensions": true }, "include": [ "../distributed_cli/tests/fixtures/generated-*.ts", + "../distributed_cli/tests/fixtures/game-client/**/*.ts", "type-tests/**/*.ts" ] } From e55e78bb9c108f6c2a6c3db4538d3de7f75c66e7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:24:05 -0500 Subject: [PATCH 180/484] feat(cli): add game-manifest and game-client commands game-manifest runs a crate's game_surface export through the manifest harness; game-client turns a GameSurface into deterministic typed TypeScript (kinds, accessors, input codec, events, client factory) with a --check mode. Golden output is type-checked by the JS package. --- distributed_cli/src/cli.rs | 195 +++ distributed_cli/src/game_client.rs | 1125 +++++++++++++++++ distributed_cli/src/lib.rs | 10 +- distributed_cli/src/manifest_harness.rs | 22 + distributed_cli/tests/cli_game_client.rs | 205 +++ .../fixtures/game-client/sample/client.ts | 49 + .../fixtures/game-client/sample/events.ts | 162 +++ .../fixtures/game-client/sample/index.ts | 7 + .../fixtures/game-client/sample/input.ts | 59 + .../fixtures/game-client/sample/schema.ts | 150 +++ .../fixtures/game-client/sample/surface.json | 440 +++++++ .../tests/fixtures/game-surface/Cargo.toml | 15 + .../tests/fixtures/game-surface/src/lib.rs | 62 + 13 files changed, 2497 insertions(+), 4 deletions(-) create mode 100644 distributed_cli/src/game_client.rs create mode 100644 distributed_cli/tests/cli_game_client.rs create mode 100644 distributed_cli/tests/fixtures/game-client/sample/client.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/events.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/index.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/input.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/schema.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/surface.json create mode 100644 distributed_cli/tests/fixtures/game-surface/Cargo.toml create mode 100644 distributed_cli/tests/fixtures/game-surface/src/lib.rs diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index edc3a0eed..8bc9a1a30 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -71,6 +71,10 @@ pub enum DistributedCommands { Client(ClientArgs), /// Compile the service's authorized client Surface manifest as JSON ClientManifest(ClientManifestArgs), + /// Print a distributed_game zone's GameSurface (kinds, input, events) as JSON + GameManifest(GameManifestArgs), + /// Generate typed TypeScript for a distributed_game zone from its GameSurface + GameClient(GameClientArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), /// Extract the embedded Distributed agent skills into a project @@ -122,6 +126,10 @@ pub enum ServiceCommands { Client(ClientArgs), /// Compile the service's authorized client Surface manifest as JSON ClientManifest(ClientManifestArgs), + /// Print a distributed_game zone's GameSurface (kinds, input, events) as JSON + GameManifest(GameManifestArgs), + /// Generate typed TypeScript for a distributed_game zone from its GameSurface + GameClient(GameClientArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), /// Extract the embedded Distributed agent skills into a project @@ -428,6 +436,58 @@ pub struct ClientManifestArgs { pub distributed_path: Option, } +#[derive(Args, Debug)] +pub struct GameManifestArgs { + /// Game crate directory. Defaults to the current directory. + #[arg(long, default_value = ".")] + pub path: PathBuf, + /// Cargo.toml of the game crate. Overrides --path. + #[arg(long)] + pub manifest_path: Option, + /// Cargo package to inspect when the manifest belongs to a workspace. + #[arg(long)] + pub package: Option, + /// Comma-delimited feature list for the game crate. + #[arg(long, value_delimiter = ',')] + pub features: Vec, + /// Disable default features on the game crate dependency. + #[arg(long)] + pub no_default_features: bool, + /// Surface export function returning `distributed_game::GameSurface`. + /// Defaults to `::game_surface`; e.g. `game_demos::arena::game_surface`. + #[arg(long)] + pub entrypoint: Option, + /// Write the JSON here instead of stdout. + #[arg(long)] + pub out: Option, +} + +#[derive(Clone, Copy, Debug, ValueEnum)] +pub enum GameImportExtension { + /// `./schema.ts` (Vite, Node type stripping, `allowImportingTsExtensions`) + Ts, + /// `./schema.js` (tsc NodeNext emit) + Js, + /// `./schema` (bundler resolution) + None, +} + +#[derive(Args, Debug)] +pub struct GameClientArgs { + /// GameSurface JSON (from `distributed game-manifest`). + #[arg(long)] + pub manifest: PathBuf, + /// Generated TypeScript directory (owned by the generator). + #[arg(long)] + pub out: PathBuf, + /// Verify the generated files are current without writing anything. + #[arg(long)] + pub check: bool, + /// Import specifier extension between generated files. + #[arg(long, value_enum, default_value = "ts")] + pub import_extension: GameImportExtension, +} + #[derive(Args, Debug)] #[command(group( ArgGroup::new("client_surface") @@ -633,6 +693,8 @@ pub fn run_distributed(args: &DistributedArgs) -> Result<(), Box> { DistributedCommands::Describe(describe) => run_describe(describe), DistributedCommands::Client(client) => run_client(client), DistributedCommands::ClientManifest(client) => run_client_manifest(client), + DistributedCommands::GameManifest(game) => run_game_manifest(game), + DistributedCommands::GameClient(game) => run_game_client(game), DistributedCommands::Schema(schema) => run_schema(schema), DistributedCommands::Skills(skills) => match &skills.command { SkillsCommands::Init(init) => run_skills_init(init), @@ -680,6 +742,8 @@ pub fn run(args: &ServiceArgs) -> Result<(), Box> { ServiceCommands::Describe(describe) => run_describe(describe), ServiceCommands::Client(client) => run_client(client), ServiceCommands::ClientManifest(client) => run_client_manifest(client), + ServiceCommands::GameManifest(game) => run_game_manifest(game), + ServiceCommands::GameClient(game) => run_game_client(game), ServiceCommands::Schema(schema) => run_schema(schema), ServiceCommands::Skills(skills) => match &skills.command { SkillsCommands::Init(init) => run_skills_init(init), @@ -2293,6 +2357,137 @@ fn run_client_manifest(args: &ClientManifestArgs) -> Result<(), Box> Ok(()) } +fn run_game_manifest(args: &GameManifestArgs) -> Result<(), Box> { + let json = run_manifest_harness( + &HarnessOptions { + path: args.path.clone(), + manifest_path: args.manifest_path.clone(), + package: args.package.clone(), + features: args.features.clone(), + no_default_features: args.no_default_features, + entrypoint: args.entrypoint.clone(), + distributed_path: None, + }, + HarnessMode::GameManifest, + )?; + crate::game_client::validate_game_surface(&json)?; + let value: serde_json::Value = serde_json::from_str(&json)?; + let pretty = serde_json::to_string_pretty(&value)? + "\n"; + match &args.out { + Some(path) => { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + fs::write(path, pretty) + .map_err(|error| format!("write game surface {}: {error}", path.display()))?; + } + None => print!("{pretty}"), + } + Ok(()) +} + +fn run_game_client(args: &GameClientArgs) -> Result<(), Box> { + let source = read_utf8_bounded(&args.manifest, MAX_CLIENT_MANIFEST_BYTES, "game surface")?; + let ext = match args.import_extension { + GameImportExtension::Ts => crate::game_client::ImportExtension::Ts, + GameImportExtension::Js => crate::game_client::ImportExtension::Js, + GameImportExtension::None => crate::game_client::ImportExtension::None, + }; + let files = crate::game_client::generate_game_client(&source, ext) + .map_err(|error| format!("{}: {error}", args.manifest.display()))?; + if args.check { + check_game_client(&args.out, &files)?; + println!( + "Game client for {} is current ({} files)", + args.manifest.display(), + files.len() + ); + } else { + write_game_client(&args.out, &files)?; + println!( + "Generated {} game client files at {}", + files.len(), + args.out.display() + ); + } + Ok(()) +} + +/// Files directly in `root` (the generator owns the directory). +fn game_client_dir_files(root: &Path) -> Result, Box> { + let mut out = BTreeSet::new(); + match fs::read_dir(root) { + Ok(entries) => { + for entry in entries { + let entry = entry?; + if entry.file_type()?.is_file() { + out.insert(entry.file_name().to_string_lossy().into_owned()); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("read {}: {error}", root.display()).into()), + } + Ok(out) +} + +fn check_game_client(root: &Path, files: &[GeneratedClientFile]) -> Result<(), Box> { + let mut drift = Vec::new(); + let existing = game_client_dir_files(root)?; + for file in files { + match fs::read_to_string(root.join(&file.path)) { + Ok(actual) if actual == file.contents => {} + Ok(_) => drift.push(format!("changed {}", file.path)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + drift.push(format!("missing {}", file.path)) + } + Err(error) => return Err(format!("read {}: {error}", file.path).into()), + } + } + for name in existing { + if !files.iter().any(|f| f.path == name) { + drift.push(format!("unexpected {name}")); + } + } + if drift.is_empty() { + return Ok(()); + } + Err(format!( + "generated game client at {} is stale:\n {}\nrun `distributed game-client` without --check to regenerate", + root.display(), + drift.join("\n ") + ) + .into()) +} + +fn write_game_client(root: &Path, files: &[GeneratedClientFile]) -> Result<(), Box> { + fs::create_dir_all(root)?; + for name in game_client_dir_files(root)? { + if files.iter().any(|f| f.path == name) { + continue; + } + let path = root.join(&name); + let owned = fs::read_to_string(&path) + .map(|text| text.starts_with("// @generated by `distributed game-client`")) + .unwrap_or(false); + if !owned { + return Err(format!( + "{} is not a generated game client file; refusing to overwrite the directory (move it out of {})", + path.display(), + root.display() + ) + .into()); + } + fs::remove_file(&path)?; + } + for file in files { + let path = root.join(&file.path); + fs::write(&path, &file.contents) + .map_err(|error| format!("write {}: {error}", path.display()))?; + } + Ok(()) +} + fn run_schema(args: &SchemaArgs) -> Result<(), Box> { let mode = match args.format { SchemaFormat::Graphql => HarnessMode::SchemaGraphql, diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs new file mode 100644 index 000000000..aeab807a1 --- /dev/null +++ b/distributed_cli/src/game_client.rs @@ -0,0 +1,1125 @@ +//! `distributed game-client`: typed TypeScript for one `distributed_game` +//! zone surface (`GameSurface` JSON, schema v1, from `distributed +//! game-manifest`). +//! +//! The generated files import only `@hops-ops/distributed/game` and are +//! deterministic (same surface → same bytes): +//! +//! | file | contents | +//! |---|---| +//! | `schema.ts` | `KIND` ids, per-kind field interfaces + accessors over rendered entities, field wire types, `CORRECTIONS` defaults | +//! | `input.ts` | the input interface, `BUTTON` bits, `encodeInput` / `decodeInput` / `sanitizeInput` | +//! | `events.ts` | record + event payload interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | +//! | `client.ts` | `createClient`: a `GameClient` with the input encoder and correction defaults wired in, plus typed `on` | +//! | `index.ts` | re-exports | +//! | `surface.json` | the surface it was generated from (so `--check` also catches manifest drift) | +//! +//! This is intentionally not the GraphQL client manifest: that contract is +//! strict (`deny_unknown_fields`, fingerprints) and describes a different +//! protocol. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write as _; + +use serde::Deserialize; + +use crate::client_compiler::GeneratedClientFile; + +/// The only surface schema version this generator understands. +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 1; + +const SDK: &str = "@hops-ops/distributed/game"; + +/// Import specifier style for imports between generated files. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ImportExtension { + /// `./schema.ts` (Node type stripping, Vite, `allowImportingTsExtensions`). + Ts, + /// `./schema.js` (tsc `NodeNext` emit). + Js, + /// `./schema` (bundler resolution). + None, +} + +impl ImportExtension { + fn suffix(self) -> &'static str { + match self { + Self::Ts => ".ts", + Self::Js => ".js", + Self::None => "", + } + } +} + +// ---- surface mirror (schema v1) ------------------------------------------- + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Surface { + schema_version: u32, + name: String, + protocol_version: u32, + kinds: Vec, + input: Option, + events: Vec, + records: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Kind { + id: u16, + name: String, + priority: f32, + fields: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EntityField { + name: String, + #[serde(rename = "type")] + ty: Wire, + priority: f32, + correction: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] +enum Correction { + Ease { + #[serde(rename = "durationMs")] + duration_ms: u32, + }, + Snap, + Replace, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Field { + name: String, + #[serde(rename = "type")] + ty: Wire, + #[serde(default)] + range: Option<[f64; 2]>, + #[serde(default)] + buttons: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Input { + name: String, + fields: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Event { + id: u32, + name: String, + payload: Payload, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +enum Payload { + Fields { + fields: Vec, + }, + Value { + #[serde(rename = "type")] + ty: Wire, + }, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Record { + name: String, + fields: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Wire { + Bool, + U8, + I8, + U16, + I16, + U32, + I32, + U64, + F32, + F64, + Quant { min: f32, max: f32, bits: u8 }, + Angle { bits: u8 }, + ShortStr, + Str, + Bytes, + List { item: Box }, + Optional { item: Box }, + Record { name: String }, +} + +impl Wire { + fn is_entity_type(&self) -> bool { + matches!( + self, + Self::Bool + | Self::U8 + | Self::U16 + | Self::U32 + | Self::I32 + | Self::F32 + | Self::Quant { .. } + | Self::Angle { .. } + | Self::ShortStr + | Self::Bytes + ) + } + + fn is_float(&self) -> bool { + matches!(self, Self::F32 | Self::F64) + } + + fn is_integer(&self) -> bool { + matches!( + self, + Self::U8 | Self::I8 | Self::U16 | Self::I16 | Self::U32 | Self::I32 | Self::U64 + ) + } +} + +// ---- naming --------------------------------------------------------------- + +fn words(name: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut prev_lower = false; + for c in name.chars() { + if c == '_' || c == '-' || c == ' ' { + if !current.is_empty() { + out.push(std::mem::take(&mut current)); + } + prev_lower = false; + continue; + } + if c.is_uppercase() && prev_lower && !current.is_empty() { + out.push(std::mem::take(&mut current)); + } + prev_lower = c.is_lowercase() || c.is_ascii_digit(); + current.push(c); + } + if !current.is_empty() { + out.push(current); + } + out +} + +fn capitalize(word: &str) -> String { + let mut chars = word.chars(); + match chars.next() { + Some(first) => first + .to_uppercase() + .chain(chars.flat_map(char::to_lowercase)) + .collect(), + None => String::new(), + } +} + +/// `view_radius` → `viewRadius`. +fn camel(name: &str) -> String { + let words = words(name); + let mut out = String::new(); + for (i, word) in words.iter().enumerate() { + if i == 0 { + out.push_str(&word.to_lowercase()); + } else { + out.push_str(&capitalize(word)); + } + } + out +} + +/// `board_snapshot` → `BoardSnapshot`. +fn pascal(name: &str) -> String { + words(name).iter().map(|w| capitalize(w)).collect() +} + +/// `slow_ms` → `SLOW_MS`. +fn constant(name: &str) -> String { + words(name) + .iter() + .map(|w| w.to_uppercase()) + .collect::>() + .join("_") +} + +fn is_identifier(name: &str) -> bool { + let mut chars = name.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') +} + +fn key(name: &str) -> String { + if is_identifier(name) { + name.to_string() + } else { + format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'")) + } +} + +/// Single-quoted TypeScript string literal. +fn string(value: &str) -> String { + let mut out = String::from("'"); + for c in value.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\'' => out.push_str("\\'"), + '\n' => out.push_str("\\n"), + c if c.is_control() => { + let _ = write!(out, "\\u{{{:x}}}", c as u32); + } + c => out.push(c), + } + } + out.push('\''); + out +} + +fn f32_literal(v: f32) -> String { + if v.is_finite() { + format!("{v}") + } else { + "Number.NaN".into() + } +} + +fn f64_literal(v: f64) -> String { + format!("{v}") +} + +// ---- generation ----------------------------------------------------------- + +struct Gen<'a> { + surface: &'a Surface, + records: BTreeMap<&'a str, &'a Record>, + ext: ImportExtension, +} + +type GenResult = Result; + +/// Generate the client files for a surface manifest (JSON text). +pub fn generate_game_client( + manifest_json: &str, + ext: ImportExtension, +) -> GenResult> { + let value: serde_json::Value = + serde_json::from_str(manifest_json).map_err(|e| format!("parse game surface: {e}"))?; + let version = value + .get("schemaVersion") + .and_then(serde_json::Value::as_u64); + if version != Some(u64::from(GAME_SURFACE_SCHEMA_VERSION)) { + return Err(format!( + "unsupported game surface schemaVersion {version:?}; this CLI generates schema version {GAME_SURFACE_SCHEMA_VERSION}" + )); + } + let surface: Surface = + serde_json::from_value(value.clone()).map_err(|e| format!("invalid game surface: {e}"))?; + let gen = Gen::new(&surface, ext)?; + let mut files = vec![ + file("schema.ts", gen.schema_ts()?), + file("input.ts", gen.input_ts()?), + file("events.ts", gen.events_ts()?), + file("client.ts", gen.client_ts()), + file("index.ts", gen.index_ts()), + file( + "surface.json", + serde_json::to_string_pretty(&value).expect("surface serializes") + "\n", + ), + ]; + files.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(files) +} + +/// Validate a manifest (as `game-manifest` prints it). +pub fn validate_game_surface(manifest_json: &str) -> GenResult<()> { + generate_game_client(manifest_json, ImportExtension::Ts).map(|_| ()) +} + +fn file(path: &str, contents: String) -> GeneratedClientFile { + GeneratedClientFile { + path: path.to_string(), + contents, + } +} + +impl<'a> Gen<'a> { + fn new(surface: &'a Surface, ext: ImportExtension) -> GenResult { + let _ = (surface.schema_version, surface.protocol_version); + if !surface + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + || surface.name.is_empty() + { + return Err(format!("invalid surface name {:?}", surface.name)); + } + let mut records = BTreeMap::new(); + for record in &surface.records { + if !is_identifier(&record.name) { + return Err(format!( + "record name {:?} is not an identifier", + record.name + )); + } + if records.insert(record.name.as_str(), record).is_some() { + return Err(format!("duplicate record {}", record.name)); + } + } + let gen = Self { + surface, + records, + ext, + }; + gen.validate()?; + Ok(gen) + } + + fn validate(&self) -> GenResult<()> { + let mut kind_ids = BTreeSet::new(); + let mut kind_names = BTreeSet::new(); + for kind in &self.surface.kinds { + if !kind_ids.insert(kind.id) { + return Err(format!("duplicate kind id {}", kind.id)); + } + if pascal(&kind.name).is_empty() || !kind_names.insert(pascal(&kind.name)) { + return Err(format!("duplicate or empty kind name {:?}", kind.name)); + } + let mut props = BTreeSet::new(); + for field in &kind.fields { + if !field.ty.is_entity_type() { + return Err(format!( + "kind {} field {} has a non-entity wire type", + kind.name, field.name + )); + } + if !props.insert(camel(&field.name)) { + return Err(format!( + "kind {} fields collide as `{}`", + kind.name, + camel(&field.name) + )); + } + } + } + let mut event_ids = BTreeSet::new(); + let mut event_names = BTreeSet::new(); + for event in &self.surface.events { + if !event_ids.insert(event.id) || !event_names.insert(camel(&event.name)) { + return Err(format!("duplicate event {} / {}", event.id, event.name)); + } + match &event.payload { + Payload::Fields { fields } => self.check_fields(fields, &event.name)?, + Payload::Value { ty } => self.check_type(ty, &event.name)?, + } + } + for record in &self.surface.records { + self.check_fields(&record.fields, &record.name)?; + } + if let Some(input) = &self.surface.input { + self.check_fields(&input.fields, &input.name)?; + let mut buttons = BTreeSet::new(); + for field in &input.fields { + for b in &field.buttons { + if !buttons.insert(camel(b)) { + return Err(format!("duplicate input button {b}")); + } + } + } + } + self.record_order()?; + self.check_exports() + } + + /// Every name the generated modules export, so `index.ts` re-exports + /// cannot collide. + fn check_exports(&self) -> GenResult<()> { + let prefix = pascal(&self.surface.name); + let mut names: Vec = [ + "KIND", + "KindName", + "FIELD_TYPES", + "CORRECTIONS", + "Input", + "EVENT", + "Events", + "EVENTS", + "AnyEvent", + "decodeEvent", + "onEvent", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + names.push(format!("create{prefix}Client")); + names.push(format!("{prefix}Client")); + names.push(format!("{prefix}ClientOptions")); + names.push(format!("{prefix}PredictionOptions")); + for kind in &self.surface.kinds { + names.push(format!("{}Fields", pascal(&kind.name))); + names.push(format!("is{}", pascal(&kind.name))); + names.push(format!("{}Fields", camel(&kind.name))); + } + if let Some(input) = &self.surface.input { + names.extend( + [ + "BUTTON", + "INPUT_LAYOUT", + "encodeInput", + "decodeInput", + "sanitizeInput", + ] + .map(String::from), + ); + names.push(input.name.clone()); + } + for record in &self.surface.records { + names.push(record.name.clone()); + } + for event in &self.surface.events { + names.push(format!("{}Event", pascal(&event.name))); + } + let mut seen = BTreeSet::new(); + for name in names { + if !seen.insert(name.clone()) { + return Err(format!( + "generated export `{name}` would be declared twice; rename the record, input, kind or event" + )); + } + } + Ok(()) + } + + fn check_fields(&self, fields: &[Field], owner: &str) -> GenResult<()> { + let mut props = BTreeSet::new(); + for field in fields { + if !props.insert(camel(&field.name)) || camel(&field.name).is_empty() { + return Err(format!( + "{owner}: field `{}` is empty or collides with another as `{}`", + field.name, + camel(&field.name) + )); + } + self.check_type(&field.ty, owner)?; + } + Ok(()) + } + + fn check_type(&self, ty: &Wire, owner: &str) -> GenResult<()> { + match ty { + Wire::List { item } | Wire::Optional { item } => self.check_type(item, owner), + Wire::Record { name } if !self.records.contains_key(name.as_str()) => { + Err(format!("{owner}: unknown record {name}")) + } + _ => Ok(()), + } + } + + /// Records in dependency order (a record after every record it uses). + fn record_order(&self) -> GenResult> { + fn deps(ty: &Wire, out: &mut Vec) { + match ty { + Wire::List { item } | Wire::Optional { item } => deps(item, out), + Wire::Record { name } => out.push(name.clone()), + _ => {} + } + } + let mut order = Vec::new(); + let mut done = BTreeSet::new(); + let mut visiting = BTreeSet::new(); + fn visit<'r>( + name: &str, + records: &BTreeMap<&'r str, &'r Record>, + done: &mut BTreeSet, + visiting: &mut BTreeSet, + order: &mut Vec<&'r Record>, + ) -> GenResult<()> { + if done.contains(name) { + return Ok(()); + } + if !visiting.insert(name.to_string()) { + return Err(format!( + "record {name} is recursive; recursive records are not supported" + )); + } + let record = records[name]; + let mut needs = Vec::new(); + for field in &record.fields { + deps(&field.ty, &mut needs); + } + for dep in needs { + visit(&dep, records, done, visiting, order)?; + } + visiting.remove(name); + done.insert(name.to_string()); + order.push(record); + Ok(()) + } + for name in self.records.keys() { + visit(name, &self.records, &mut done, &mut visiting, &mut order)?; + } + Ok(order) + } + + fn header(&self, what: &str) -> String { + format!( + "// @generated by `distributed game-client` from game surface `{}` (schema v{}, protocol v{}).\n// {what}\n// Do not edit: change the Rust definitions and regenerate.\n", + self.surface.name, + self.surface.schema_version, + self.surface.protocol_version + ) + } + + fn local(&self, module: &str) -> String { + format!("./{module}{}", self.ext.suffix()) + } + + fn ts_type(&self, ty: &Wire) -> String { + match ty { + Wire::Bool => "boolean".into(), + Wire::ShortStr | Wire::Str => "string".into(), + Wire::Bytes => "Uint8Array".into(), + Wire::List { item } => { + let inner = self.ts_type(item); + if inner.contains(' ') { + format!("readonly ({inner})[]") + } else { + format!("readonly {inner}[]") + } + } + Wire::Optional { item } => format!("{} | undefined", self.ts_type(item)), + Wire::Record { name } => name.clone(), + _ => "number".into(), + } + } + + /// A `WireType` literal; records refer to their `*_TYPE` constants. + fn wire_literal(&self, ty: &Wire) -> String { + match ty { + Wire::Quant { min, max, bits } => format!( + "{{ type: 'quant', min: {}, max: {}, bits: {bits} }}", + f32_literal(*min), + f32_literal(*max) + ), + Wire::Angle { bits } => format!("{{ type: 'angle', bits: {bits} }}"), + Wire::List { item } => format!("{{ type: 'list', item: {} }}", self.wire_literal(item)), + Wire::Optional { item } => { + format!("{{ type: 'optional', item: {} }}", self.wire_literal(item)) + } + Wire::Record { name } => format!("{}_TYPE", constant(name)), + other => format!("{{ type: '{}' }}", simple_tag(other)), + } + } + + fn layout(&self, fields: &[Field]) -> String { + if fields.is_empty() { + return "[]".into(); + } + let mut out = String::from("[\n"); + for field in fields { + let _ = writeln!( + out, + "\t[{}, {}],", + string(&camel(&field.name)), + self.wire_literal(&field.ty) + ); + } + out.push(']'); + out + } + + fn interface(&self, name: &str, doc: &str, fields: &[Field]) -> String { + let mut out = format!("/** {doc} */\nexport interface {name} {{\n"); + for field in fields { + let _ = writeln!( + out, + "\treadonly {}: {};", + key(&camel(&field.name)), + self.ts_type(&field.ty) + ); + } + out.push_str("}\n"); + out + } + + fn schema_ts(&self) -> GenResult { + let kinds = &self.surface.kinds; + let mut readers = BTreeSet::new(); + for kind in kinds { + for field in &kind.fields { + readers.insert(reader(&field.ty)); + } + } + let mut imports: Vec = readers.into_iter().map(str::to_string).collect(); + imports.push("type CorrectionPolicies".into()); + imports.push("type EntityFields".into()); + imports.push("type WireType".into()); + let mut out = + self.header("Replicated kinds: ids, typed fields, wire types, correction defaults."); + let _ = writeln!(out, "import {{ {} }} from '{SDK}';\n", imports.join(", ")); + + out.push_str("/** Replicated kind ids by name. */\nexport const KIND = {\n"); + for kind in kinds { + let _ = writeln!(out, "\t{}: {},", key(&camel(&kind.name)), kind.id); + } + out.push_str("} as const;\n\nexport type KindName = keyof typeof KIND;\n"); + + for kind in kinds { + let pascal_name = pascal(&kind.name); + let camel_name = camel(&kind.name); + let _ = write!( + out, + "\n/** `{}` (kind {}, priority {}). */\nexport interface {pascal_name}Fields {{\n", + kind.name, + kind.id, + f32_literal(kind.priority) + ); + for field in &kind.fields { + let doc = field_doc(&field.ty, field.priority); + let _ = writeln!( + out, + "\t/** {doc} */\n\treadonly {}: {};", + key(&camel(&field.name)), + self.ts_type(&field.ty) + ); + } + out.push_str("}\n\n"); + let _ = writeln!( + out, + "/** True for a `{}` entity. */\nexport function is{pascal_name}(entity: {{ readonly kind: number }}): boolean {{\n\treturn entity.kind === {};\n}}\n", + kind.name, kind.id + ); + let _ = writeln!( + out, + "/** Typed fields of a `{}` entity (rendered or replica). */\nexport function {camel_name}Fields(entity: {{ readonly fields: EntityFields }}): {pascal_name}Fields {{\n\tconst f = entity.fields;\n\treturn {{", + kind.name + ); + for field in &kind.fields { + let _ = writeln!( + out, + "\t\t{}: {}(f, {}),", + key(&camel(&field.name)), + reader(&field.ty), + string(&field.name) + ); + } + out.push_str("\t};\n}\n"); + } + + out.push_str("\n/** Wire type of every replicated field, by kind and wire field name. */\nexport const FIELD_TYPES = {\n"); + for kind in kinds { + let _ = writeln!(out, "\t{}: {{", key(&camel(&kind.name))); + for field in &kind.fields { + let _ = writeln!( + out, + "\t\t{}: {},", + key(&field.name), + self.wire_literal(&field.ty) + ); + } + out.push_str("\t},\n"); + } + out.push_str("} as const satisfies Record>;\n"); + + out.push_str("\n/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */\nexport const CORRECTIONS: CorrectionPolicies = {\n"); + for kind in kinds { + let corrected: Vec<_> = kind + .fields + .iter() + .filter_map(|f| f.correction.as_ref().map(|c| (f, c))) + .collect(); + if corrected.is_empty() { + continue; + } + let _ = writeln!(out, "\t{}: {{", key(&kind.name)); + for (field, correction) in corrected { + let policy = match correction { + Correction::Ease { duration_ms } => { + format!("{{ mode: 'ease', durationMs: {duration_ms} }}") + } + Correction::Snap => "{ mode: 'snap' }".into(), + Correction::Replace => "{ mode: 'replace' }".into(), + }; + let _ = writeln!(out, "\t\t{}: {policy},", key(&field.name)); + } + out.push_str("\t},\n"); + } + out.push_str("};\n"); + Ok(out) + } + + fn input_ts(&self) -> GenResult { + let mut out = + self.header("Input frame: interface, button bits, encoder, decoder, sanitize."); + let Some(input) = &self.surface.input else { + out.push_str("\n/** This zone takes no typed input. */\nexport type Input = never;\n"); + return Ok(out); + }; + let can_reject = input.fields.iter().any(|f| f.ty.is_float()); + let _ = writeln!( + out, + "import {{ decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout }} from '{SDK}';\n" + ); + out.push_str(&self.interface( + &input.name, + &format!("One `{}` input frame (`#[derive(GameInput)]`).", input.name), + &input.fields, + )); + let _ = writeln!(out, "\nexport type Input = {};", input.name); + let buttons: Vec<(String, u32)> = input + .fields + .iter() + .flat_map(|f| { + f.buttons + .iter() + .enumerate() + .map(|(bit, b)| (camel(b), 1u32 << bit)) + }) + .collect(); + if !buttons.is_empty() { + out.push_str("\n/** Button bits (`#[buttons(..)]`). */\nexport const BUTTON = {\n"); + for (name, bit) in &buttons { + let _ = writeln!(out, "\t{}: {bit},", key(name)); + } + out.push_str("} as const;\n"); + } + let _ = writeln!( + out, + "\n/** Wire layout, in field order. */\nexport const INPUT_LAYOUT: PayloadLayout = {};\n", + self.layout(&input.fields) + ); + out.push_str("const INPUT_RULES: readonly InputRule[] = [\n"); + for field in &input.fields { + let rule = if !field.buttons.is_empty() { + let mask: u64 = (1u64 << field.buttons.len()) - 1; + format!("{{ buttons: {mask} }}") + } else if let Some([min, max]) = field.range { + let (min, max) = if field.ty.is_integer() { + (min.trunc(), max.trunc()) + } else { + (min, max) + }; + format!("{{ range: [{}, {}] }}", f64_literal(min), f64_literal(max)) + } else { + "undefined".into() + }; + let _ = writeln!(out, "\t{rule},"); + } + out.push_str("];\n\n"); + let name = &input.name; + let _ = writeln!( + out, + "/** Payload bytes of one input frame. */\nexport function encodeInput(input: {name}): Uint8Array {{\n\treturn encodePayload(INPUT_LAYOUT, input);\n}}\n" + ); + let _ = writeln!( + out, + "/** Decode one input frame (no sanitizing). */\nexport function decodeInput(payload: Uint8Array): {name} {{\n\treturn decodePayload(INPUT_LAYOUT, payload) as unknown as {name};\n}}\n" + ); + if can_reject { + let _ = writeln!( + out, + "/**\n * What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks,\n * wire precision); `undefined` when the server would drop it (non-finite float).\n */\nexport function sanitizeInput(input: {name}): {name} | undefined {{\n\treturn sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input);\n}}" + ); + } else { + let _ = writeln!( + out, + "/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */\nexport function sanitizeInput(input: {name}): {name} {{\n\treturn sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!;\n}}" + ); + } + Ok(out) + } + + fn events_ts(&self) -> GenResult { + let mut out = self + .header("Events and records: payload interfaces, ids, codecs, typed subscriptions."); + let events = &self.surface.events; + let records = self.record_order()?; + let mut sdk = vec![ + "decodeGameEvent", + "onGameEvent", + "type DecodedGameEvent", + "type GameEventCodecs", + "type GameEventSource", + ]; + let uses_fields = events + .iter() + .any(|e| matches!(e.payload, Payload::Fields { .. })); + let uses_value = events + .iter() + .any(|e| matches!(e.payload, Payload::Value { .. })); + if uses_fields { + sdk.extend(["decodePayload", "encodePayload", "type PayloadLayout"]); + } + if uses_value { + sdk.extend(["decodeValue", "encodeValue"]); + } + if uses_value || !records.is_empty() { + sdk.push("type WireType"); + } + sdk.sort_by_key(|s| (s.starts_with("type "), s.to_string())); + let _ = writeln!(out, "import {{ {} }} from '{SDK}';", sdk.join(", ")); + + for record in &records { + out.push('\n'); + out.push_str(&self.interface( + &record.name, + &format!("Record `{}` (`#[derive(GameRecord)]`).", record.name), + &record.fields, + )); + let _ = writeln!( + out, + "\nconst {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};", + constant(&record.name), + indent(&self.layout(&record.fields)) + ); + } + + for event in events { + let type_name = format!("{}Event", pascal(&event.name)); + out.push('\n'); + match &event.payload { + Payload::Fields { fields } if fields.is_empty() => { + let _ = writeln!( + out, + "/** Event `{}` (id {}): no payload. */\nexport type {type_name} = Readonly>;", + event.name, event.id + ); + let _ = writeln!( + out, + "\nconst {}_LAYOUT: PayloadLayout = [];", + constant(&event.name) + ); + } + Payload::Fields { fields } => { + out.push_str(&self.interface( + &type_name, + &format!("Event `{}` (id {}).", event.name, event.id), + fields, + )); + let _ = writeln!( + out, + "\nconst {}_LAYOUT: PayloadLayout = {};", + constant(&event.name), + self.layout(fields) + ); + } + Payload::Value { ty } => { + let _ = writeln!( + out, + "/** Event `{}` (id {}). */\nexport type {type_name} = {};", + event.name, + event.id, + self.ts_type(ty) + ); + let _ = writeln!( + out, + "\nconst {}_PAYLOAD: WireType = {};", + constant(&event.name), + self.wire_literal(ty) + ); + } + } + } + + out.push_str("\n/** Event type ids by name. */\nexport const EVENT = {\n"); + for event in events { + let _ = writeln!(out, "\t{}: {},", key(&camel(&event.name)), event.id); + } + out.push_str( + "} as const;\n\n/** Event payload types by name. */\nexport interface Events {\n", + ); + for event in events { + let _ = writeln!( + out, + "\t{}: {}Event;", + key(&camel(&event.name)), + pascal(&event.name) + ); + } + out.push_str("}\n\n/** Codecs of every event. */\nexport const EVENTS: GameEventCodecs = {\n"); + for event in events { + let type_name = format!("{}Event", pascal(&event.name)); + let c = constant(&event.name); + let (encode, decode) = match &event.payload { + Payload::Fields { .. } => ( + format!("(value) => encodePayload({c}_LAYOUT, value)"), + format!( + "(payload) => decodePayload({c}_LAYOUT, payload) as unknown as {type_name}" + ), + ), + Payload::Value { .. } => ( + format!("(value) => encodeValue({c}_PAYLOAD, value)"), + format!("(payload) => decodeValue({c}_PAYLOAD, payload) as {type_name}"), + ), + }; + let _ = writeln!( + out, + "\t{}: {{\n\t\tid: {},\n\t\tname: {},\n\t\tencode: {encode},\n\t\tdecode: {decode}\n\t}},", + key(&camel(&event.name)), + event.id, + string(&event.name) + ); + } + out.push_str("};\n\n"); + out.push_str("/** A decoded event, discriminated by `name`. */\nexport type AnyEvent = DecodedGameEvent;\n\n"); + out.push_str("/** Decode an Event message (`undefined` for ids this surface does not declare). */\nexport function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined {\n\treturn decodeGameEvent(EVENTS, event);\n}\n\n"); + out.push_str("/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */\nexport function onEvent(\n\tclient: GameEventSource,\n\tname: K,\n\thandler: (value: Events[K], zoneId: string) => void\n): () => void {\n\treturn onGameEvent(client, EVENTS, name, handler);\n}\n"); + Ok(out) + } + + fn client_ts(&self) -> String { + let prefix = pascal(&self.surface.name); + let mut out = self.header("Typed client factory."); + let input = self.surface.input.as_ref().map(|i| i.name.as_str()); + match input { + Some(name) => { + let _ = writeln!( + out, + "import {{ GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\nimport {{ encodeInput, type {name} }} from '{}';\nimport {{ CORRECTIONS }} from '{}';\n", + self.local("events"), + self.local("input"), + self.local("schema") + ); + let _ = writeln!( + out, + "/** Prediction options; `encodeInput` and the correction defaults are filled in. */\nexport type {prefix}PredictionOptions = Omit, 'encodeInput'> &\n\tPartial, 'encodeInput'>>;\n\nexport type {prefix}ClientOptions = Omit, 'prediction'> &\n\tReadonly<{{ prediction?: {prefix}PredictionOptions }}>;\n" + ); + let _ = writeln!( + out, + "export type {prefix}Client = Readonly<{{\n\tclient: GameClient<{name}>;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n\t/** Send one input: predicted when prediction is configured, raw otherwise. */\n\tsend(input: {name}): number | undefined;\n}}>;\n" + ); + let _ = writeln!( + out, + "/** A `GameClient` for the `{surface}` surface with its input encoder and correction defaults. */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst prediction = options.prediction;\n\tconst client = new GameClient<{name}>({{\n\t\t...options,\n\t\tprediction:\n\t\t\tprediction === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {{\n\t\t\t\t\t\t...prediction,\n\t\t\t\t\t\tencodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)),\n\t\t\t\t\t\tcorrections: mergeCorrections(CORRECTIONS, prediction.corrections)\n\t\t\t\t\t}}\n\t}});\n\treturn {{\n\t\tclient,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}}),\n\t\tsend: (input) =>\n\t\t\tprediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input)\n\t}};\n}}", + surface = self.surface.name + ); + } + None => { + let _ = writeln!( + out, + "import {{ GameClient, type GameClientOptions }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\n", + self.local("events") + ); + let _ = writeln!( + out, + "export type {prefix}ClientOptions = Omit, 'prediction'>;\n\nexport type {prefix}Client = Readonly<{{\n\tclient: GameClient;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n}}>;\n" + ); + let _ = writeln!( + out, + "/** A `GameClient` for the `{surface}` surface (no typed input). */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst client = new GameClient(options);\n\treturn {{\n\t\tclient,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}})\n\t}};\n}}", + surface = self.surface.name + ); + } + } + out + } + + fn index_ts(&self) -> String { + let mut out = self.header("Everything generated for this surface."); + for module in ["client", "events", "input", "schema"] { + let _ = writeln!(out, "export * from '{}';", self.local(module)); + } + out + } +} + +fn simple_tag(ty: &Wire) -> &'static str { + match ty { + Wire::Bool => "bool", + Wire::U8 => "u8", + Wire::I8 => "i8", + Wire::U16 => "u16", + Wire::I16 => "i16", + Wire::U32 => "u32", + Wire::I32 => "i32", + Wire::U64 => "u64", + Wire::F32 => "f32", + Wire::F64 => "f64", + Wire::ShortStr => "short_str", + Wire::Str => "str", + Wire::Bytes => "bytes", + _ => unreachable!("composite types have their own literal"), + } +} + +fn reader(ty: &Wire) -> &'static str { + match ty { + Wire::Bool => "fieldBool", + Wire::ShortStr => "fieldString", + Wire::Bytes => "fieldBytes", + _ => "fieldNumber", + } +} + +fn field_doc(ty: &Wire, priority: f32) -> String { + let wire = match ty { + Wire::Quant { min, max, bits } => format!( + "quant [{}, {}] / {bits} bits", + f32_literal(*min), + f32_literal(*max) + ), + Wire::Angle { bits } => format!("angle / {bits} bits"), + other => simple_tag(other).to_string(), + }; + if priority == 1.0 { + format!("`{wire}`") + } else { + format!("`{wire}`, priority {}", f32_literal(priority)) + } +} + +fn indent(block: &str) -> String { + block.replace("\n\t", "\n\t\t").replace("\n]", "\n\t]") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_convert() { + assert_eq!(camel("view_radius"), "viewRadius"); + assert_eq!(camel("slowMs"), "slowMs"); + assert_eq!(camel("hp"), "hp"); + assert_eq!(pascal("board_snapshot"), "BoardSnapshot"); + assert_eq!(pascal("player"), "Player"); + assert_eq!(constant("BoardRow"), "BOARD_ROW"); + assert_eq!(constant("slow_ms"), "SLOW_MS"); + assert_eq!(key("type"), "type"); + assert_eq!(key("a-b"), "'a-b'"); + } + + #[test] + fn rejects_other_schema_versions_and_unknown_fields() { + let err = generate_game_client(r#"{"schemaVersion": 2}"#, ImportExtension::Ts).unwrap_err(); + assert!(err.contains("schemaVersion"), "{err}"); + let err = generate_game_client( + r#"{"schemaVersion":1,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, + ImportExtension::Ts, + ) + .unwrap_err(); + assert!(err.contains("unknown field"), "{err}"); + } + + #[test] + fn rejects_recursive_records() { + let json = r#"{"schemaVersion":1,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], + "records":[{"name":"Node","fields":[{"name":"next","type":{"type":"optional","item":{"type":"record","name":"Node"}}}]}]}"#; + let err = generate_game_client(json, ImportExtension::Ts).unwrap_err(); + assert!(err.contains("recursive"), "{err}"); + } +} diff --git a/distributed_cli/src/lib.rs b/distributed_cli/src/lib.rs index 3fde9d3df..cea0aadde 100644 --- a/distributed_cli/src/lib.rs +++ b/distributed_cli/src/lib.rs @@ -9,6 +9,7 @@ mod atlas; mod cli; mod client_compiler; pub mod contracts; +mod game_client; mod generate; mod js_framework; pub mod lifecycle; @@ -20,10 +21,10 @@ pub use atlas::{render_atlas_schema, AtlasDatabaseUrl, AtlasSchemaSpec}; pub use cli::{ run, run_distributed, AgentHarness, BuildArgs, Bus, ClientArgs, ClientManifestArgs, ContractsAcceptArgs, ContractsArgs, ContractsCheckArgs, ContractsCommands, ContractsOutput, - DescribeArgs, DevArgs, DistributedArgs, DistributedCommands, Framework, GitopsPromote, - JavascriptWatchArgs, LifecycleOutput, ManifestFormat, Metrics, ProbeArgs, ScaffoldArgs, - SchemaArgs, SchemaDialect, SchemaFormat, ServiceArgs, ServiceCommands, SkillsArgs, - SkillsCommands, SkillsInitArgs, Store, Transport, + DescribeArgs, DevArgs, DistributedArgs, DistributedCommands, Framework, GameClientArgs, + GameManifestArgs, GitopsPromote, JavascriptWatchArgs, LifecycleOutput, ManifestFormat, Metrics, + ProbeArgs, ScaffoldArgs, SchemaArgs, SchemaDialect, SchemaFormat, ServiceArgs, ServiceCommands, + SkillsArgs, SkillsCommands, SkillsInitArgs, Store, Transport, }; pub use client_compiler::{ compile_client, ClientCompileError, ClientCompileInput, ClientDocument, ClientSourceLocation, @@ -50,6 +51,7 @@ pub use contracts::{ MAX_SNAPSHOT_VALUE_BYTES, MIGRATION_INVENTORY_PATH, MIGRATION_INVENTORY_SCHEMA_VERSION, MIGRATION_OWNER, MIGRATION_SCOPE, }; +pub use game_client::{generate_game_client, validate_game_surface, ImportExtension}; pub use generate::{generate_service_scaffold, package_name}; pub use lifecycle::{ run_lifecycle_build, run_lifecycle_dev, ArtifactNodeReceipt, BuildDrift, diff --git a/distributed_cli/src/manifest_harness.rs b/distributed_cli/src/manifest_harness.rs index 391e779df..44fe0249c 100644 --- a/distributed_cli/src/manifest_harness.rs +++ b/distributed_cli/src/manifest_harness.rs @@ -32,6 +32,7 @@ pub(crate) enum HarnessMode { SchemaSql(SchemaDialect), SchemaGraphql, ClientManifest, + GameManifest, } impl HarnessMode { @@ -42,12 +43,14 @@ impl HarnessMode { HarnessMode::SchemaSql(SchemaDialect::Sqlite) => "schema-sqlite", HarnessMode::SchemaGraphql => "schema-graphql", HarnessMode::ClientManifest => "client-manifest", + HarnessMode::GameManifest => "game-manifest", } } fn default_entrypoint(self) -> &'static str { match self { HarnessMode::ClientManifest => "distributed_client_surface", + HarnessMode::GameManifest => "game_surface", HarnessMode::DescribeJson => "application_manifest", HarnessMode::SchemaSql(_) | HarnessMode::SchemaGraphql => "read_model_catalog", } @@ -226,6 +229,13 @@ fn harness_main_rs(entrypoint: &str, mode: HarnessMode) -> String { .expect("read-model GraphQL SDL should render"); print!("{{}}", sdl); }} +"# + ), + HarnessMode::GameManifest => format!( + r#"fn main() {{ + let surface = {entrypoint}(); + println!("{{}}", serde_json::to_string_pretty(&surface).expect("game surface should serialize")); +}} "# ), HarnessMode::ClientManifest => format!( @@ -423,6 +433,18 @@ mod tests { assert!(!main_rs.contains("build_surface")); } + #[test] + fn game_harness_prints_the_surface_export() { + assert_eq!( + HarnessMode::GameManifest.default_entrypoint(), + "game_surface" + ); + assert!(!HarnessMode::GameManifest.requires_distributed_dependency()); + let main_rs = harness_main_rs("game_demos::arena::game_surface", HarnessMode::GameManifest); + assert!(main_rs.contains("let surface = game_demos::arena::game_surface();")); + assert!(main_rs.contains("serde_json::to_string_pretty(&surface)")); + } + #[test] fn client_harness_does_not_add_a_second_framework_dependency() { assert!(!HarnessMode::ClientManifest.requires_distributed_dependency()); diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs new file mode 100644 index 000000000..0a7c9fe62 --- /dev/null +++ b/distributed_cli/tests/cli_game_client.rs @@ -0,0 +1,205 @@ +//! `distributed game-client` / `game-manifest`. +//! +//! The golden surface is the one `distributed_game`'s authoring test writes +//! (`distributed_game/tests/fixtures/authoring.json`); its generated +//! TypeScript is pinned in `tests/fixtures/game-client/sample/`, type-checked +//! by `js` (`npm run check:generated`) and round-tripped against the Rust +//! samples by `js/tests/game-generated.test.mjs`. Regenerate with +//! `UPDATE_GOLDEN=1 cargo test -p distributed_cli --test cli_game_client`. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use distributed_cli::{generate_game_client, ImportExtension}; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf() +} + +fn sample_surface() -> String { + let path = root().join("../distributed_game/tests/fixtures/authoring.json"); + let fixture: serde_json::Value = + serde_json::from_str(&fs::read_to_string(path).expect("authoring fixture")).unwrap(); + serde_json::to_string_pretty(&fixture["surface"]).unwrap() +} + +fn golden_dir() -> PathBuf { + root().join("tests/fixtures/game-client/sample") +} + +fn distributed(args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_distributed")) + .args(args) + .output() + .expect("distributed should run") +} + +#[test] +fn generated_typescript_matches_the_golden_files() { + let files = generate_game_client(&sample_surface(), ImportExtension::Ts).unwrap(); + let names: Vec<_> = files.iter().map(|f| f.path.as_str()).collect(); + assert_eq!( + names, + [ + "client.ts", + "events.ts", + "index.ts", + "input.ts", + "schema.ts", + "surface.json" + ] + ); + let dir = golden_dir(); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + fs::create_dir_all(&dir).unwrap(); + for file in &files { + fs::write(dir.join(&file.path), &file.contents).unwrap(); + } + } + for file in &files { + let golden = fs::read_to_string(dir.join(&file.path)).unwrap_or_default(); + assert_eq!( + golden, file.contents, + "{} drifted; regenerate with UPDATE_GOLDEN=1", + file.path + ); + } + // Deterministic: a second run is byte-identical. + assert_eq!( + generate_game_client(&sample_surface(), ImportExtension::Ts).unwrap(), + files + ); + // Only the SDK is imported from outside the directory. + for file in files.iter().filter(|f| f.path.ends_with(".ts")) { + for line in file + .contents + .lines() + .filter(|l| l.starts_with("import ") || l.starts_with("export * from")) + { + assert!( + line.contains("'@hops-ops/distributed/game'") || line.contains("'./"), + "{}: unexpected import {line}", + file.path + ); + } + } +} + +#[test] +fn import_extension_is_configurable() { + let js = generate_game_client(&sample_surface(), ImportExtension::Js).unwrap(); + let index = js.iter().find(|f| f.path == "index.ts").unwrap(); + assert!(index.contents.contains("export * from './schema.js';")); + let none = generate_game_client(&sample_surface(), ImportExtension::None).unwrap(); + let index = none.iter().find(|f| f.path == "index.ts").unwrap(); + assert!(index.contents.contains("export * from './schema';")); +} + +#[test] +fn check_mode_detects_drift_and_write_keeps_foreign_files() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, sample_surface()).unwrap(); + let out = tmp.path().join("gen"); + let (m, o) = (manifest.to_str().unwrap(), out.to_str().unwrap()); + + let check = distributed(&["game-client", "--manifest", m, "--out", o, "--check"]); + assert!(!check.status.success()); + assert!(String::from_utf8_lossy(&check.stderr).contains("missing schema.ts")); + + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert!( + distributed(&["game-client", "--manifest", m, "--out", o, "--check"]) + .status + .success() + ); + + fs::write(out.join("events.ts"), "// edited").unwrap(); + fs::write( + out.join("stale.ts"), + "// @generated by `distributed game-client` (old)", + ) + .unwrap(); + let check = distributed(&["game-client", "--manifest", m, "--out", o, "--check"]); + let stderr = String::from_utf8_lossy(&check.stderr); + assert!(!check.status.success()); + assert!(stderr.contains("changed events.ts"), "{stderr}"); + assert!(stderr.contains("unexpected stale.ts"), "{stderr}"); + + // Regenerating removes stale generated files... + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert!(!out.join("stale.ts").exists()); + // ...but refuses to delete files it did not generate. + fs::write(out.join("mine.ts"), "export const x = 1;").unwrap(); + let write = distributed(&["game-client", "--manifest", m, "--out", o]); + assert!(!write.status.success()); + assert!(out.join("mine.ts").exists()); +} + +#[test] +fn invalid_surfaces_are_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, r#"{"schemaVersion": 9}"#).unwrap(); + let out = tmp.path().join("gen"); + let run = distributed(&[ + "game-client", + "--manifest", + manifest.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ]); + assert!(!run.status.success()); + assert!(String::from_utf8_lossy(&run.stderr).contains("schemaVersion")); +} + +#[test] +#[ignore = "compiles the fixture via the manifest harness; run in the integration job"] +fn game_manifest_runs_the_surface_export() { + let manifest = root().join("tests/fixtures/game-surface/Cargo.toml"); + let tmp = tempfile::tempdir().unwrap(); + let out = tmp.path().join("orbs.json"); + let run = distributed(&[ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ]); + assert!( + run.status.success(), + "{}", + String::from_utf8_lossy(&run.stderr) + ); + let surface: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(surface["schemaVersion"], 1); + assert_eq!(surface["name"], "orbs"); + assert_eq!( + surface["kinds"][0]["fields"][0]["correction"]["durationMs"], + 80 + ); + assert_eq!(surface["input"]["fields"][1]["buttons"][0], "boost"); + assert_eq!(surface["events"][0]["name"], "hello"); + let gen = tmp.path().join("gen"); + let run = distributed(&[ + "game-client", + "--manifest", + out.to_str().unwrap(), + "--out", + gen.to_str().unwrap(), + ]); + assert!( + run.status.success(), + "{}", + String::from_utf8_lossy(&run.stderr) + ); + assert!(fs::read_to_string(gen.join("client.ts")) + .unwrap() + .contains("createOrbsClient")); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/client.ts b/distributed_cli/tests/fixtures/game-client/sample/client.ts new file mode 100644 index 000000000..81f139f22 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type SampleInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type SamplePredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type SampleClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: SamplePredictionOptions }>; + +export type SampleClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: SampleInput): number | undefined; +}>; + +/** A `GameClient` for the `sample` surface with its input encoder and correction defaults. */ +export function createSampleClient(options: SampleClientOptions): SampleClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/events.ts b/distributed_cli/tests/fixtures/game-client/sample/events.ts new file mode 100644 index 000000000..89260ef91 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/events.ts @@ -0,0 +1,162 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `Row` (`#[derive(GameRecord)]`). */ +export interface Row { + readonly rank: number; + readonly name: string; + readonly score: number; +} + +const ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u16' }], + ['name', { type: 'short_str' }], + ['score', { type: 'u64' }], + ] +}; + +/** Record `Board` (`#[derive(GameRecord)]`). */ +export interface Board { + readonly version: number; + readonly kills: readonly Row[]; + readonly note: string | undefined; + readonly motd: string; +} + +const BOARD_TYPE: WireType = { + type: 'record', + fields: [ + ['version', { type: 'u32' }], + ['kills', { type: 'list', item: ROW_TYPE }], + ['note', { type: 'optional', item: { type: 'short_str' } }], + ['motd', { type: 'str' }], + ] +}; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly viewRadius: number; + readonly half: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['viewRadius', { type: 'f32' }], + ['half', { type: 'quant', min: 0, max: 64, bits: 10 }], +]; + +/** Event `board` (id 2). */ +export type BoardEvent = Board; + +const BOARD_PAYLOAD: WireType = BOARD_TYPE; + +/** Event `respawned` (id 3): no payload. */ +export type RespawnedEvent = Readonly>; + +const RESPAWNED_LAYOUT: PayloadLayout = []; + +/** Event `shot` (id 4). */ +export interface ShotEvent { + readonly hit: boolean; + readonly target: number | undefined; + readonly offset: number; + readonly small: number; + readonly atMs: number; + readonly tags: readonly string[]; + readonly bytes: Uint8Array; + readonly total: number; +} + +const SHOT_LAYOUT: PayloadLayout = [ + ['hit', { type: 'bool' }], + ['target', { type: 'optional', item: { type: 'u32' } }], + ['offset', { type: 'i16' }], + ['small', { type: 'i8' }], + ['atMs', { type: 'f64' }], + ['tags', { type: 'list', item: { type: 'short_str' } }], + ['bytes', { type: 'bytes' }], + ['total', { type: 'u64' }], +]; + +/** Event `ping` (id 9). */ +export interface PingEvent { + readonly seq: number; +} + +const PING_LAYOUT: PayloadLayout = [ + ['seq', { type: 'u32' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + board: 2, + respawned: 3, + shot: 4, + ping: 9, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + board: BoardEvent; + respawned: RespawnedEvent; + shot: ShotEvent; + ping: PingEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + board: { + id: 2, + name: 'board', + encode: (value) => encodeValue(BOARD_PAYLOAD, value), + decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent + }, + respawned: { + id: 3, + name: 'respawned', + encode: (value) => encodePayload(RESPAWNED_LAYOUT, value), + decode: (payload) => decodePayload(RESPAWNED_LAYOUT, payload) as unknown as RespawnedEvent + }, + shot: { + id: 4, + name: 'shot', + encode: (value) => encodePayload(SHOT_LAYOUT, value), + decode: (payload) => decodePayload(SHOT_LAYOUT, payload) as unknown as ShotEvent + }, + ping: { + id: 9, + name: 'ping', + encode: (value) => encodePayload(PING_LAYOUT, value), + decode: (payload) => decodePayload(PING_LAYOUT, payload) as unknown as PingEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/index.ts b/distributed_cli/tests/fixtures/game-client/sample/index.ts new file mode 100644 index 000000000..87034da95 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/input.ts b/distributed_cli/tests/fixtures/game-client/sample/input.ts new file mode 100644 index 000000000..d0f65baab --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/input.ts @@ -0,0 +1,59 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `SampleInput` input frame (`#[derive(GameInput)]`). */ +export interface SampleInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; + readonly aim: number; + readonly power: number; + readonly viewTick: number; +} + +export type Input = SampleInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + dash: 1, + attack: 2, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], + ['aim', { type: 'angle', bits: 10 }], + ['power', { type: 'f32' }], + ['viewTick', { type: 'u32' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 3 }, + undefined, + { range: [0, 1] }, + undefined, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: SampleInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): SampleInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as SampleInput; +} + +/** + * What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, + * wire precision); `undefined` when the server would drop it (non-finite float). + */ +export function sanitizeInput(input: SampleInput): SampleInput | undefined { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/schema.ts b/distributed_cli/tests/fixtures/game-client/sample/schema.ts new file mode 100644 index 000000000..ad605c59b --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/schema.ts @@ -0,0 +1,150 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldBool, fieldBytes, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + marker: 2, + stats: 4, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 16] / 12 bits` */ + readonly vx: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u8` */ + readonly hp: number; + /** `u16` */ + readonly level: number; + /** `bool` */ + readonly dead: boolean; + /** `i32` */ + readonly score: number; + /** `f32` */ + readonly raw: number; + /** `bytes` */ + readonly blob: Uint8Array; + /** `u32` */ + readonly kills: number; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + face: fieldNumber(f, 'face'), + name: fieldString(f, 'name'), + hp: fieldNumber(f, 'hp'), + level: fieldNumber(f, 'level'), + dead: fieldBool(f, 'dead'), + score: fieldNumber(f, 'score'), + raw: fieldNumber(f, 'raw'), + blob: fieldBytes(f, 'blob'), + kills: fieldNumber(f, 'kills'), + }; +} + +/** `marker` (kind 2, priority 1). */ +export interface MarkerFields { + /** `quant [-64, 63.998047] / 16 bits` */ + readonly px: number; + /** `quant [-64, 63.998047] / 16 bits` */ + readonly py: number; + /** `short_str` */ + readonly label: string; +} + +/** True for a `marker` entity. */ +export function isMarker(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `marker` entity (rendered or replica). */ +export function markerFields(entity: { readonly fields: EntityFields }): MarkerFields { + const f = entity.fields; + return { + px: fieldNumber(f, 'px'), + py: fieldNumber(f, 'py'), + label: fieldString(f, 'label'), + }; +} + +/** `stats` (kind 4, priority 1). */ +export interface StatsFields { + /** `u16` */ + readonly slowMs: number; + /** `f32` */ + readonly tickMs: number; +} + +/** True for a `stats` entity. */ +export function isStats(entity: { readonly kind: number }): boolean { + return entity.kind === 4; +} + +/** Typed fields of a `stats` entity (rendered or replica). */ +export function statsFields(entity: { readonly fields: EntityFields }): StatsFields { + const f = entity.fields; + return { + slowMs: fieldNumber(f, 'slow_ms'), + tickMs: fieldNumber(f, 'tick_ms'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847, bits: 18 }, + vx: { type: 'quant', min: -16, max: 16, bits: 12 }, + face: { type: 'angle', bits: 8 }, + name: { type: 'short_str' }, + hp: { type: 'u8' }, + level: { type: 'u16' }, + dead: { type: 'bool' }, + score: { type: 'i32' }, + raw: { type: 'f32' }, + blob: { type: 'bytes' }, + kills: { type: 'u32' }, + }, + marker: { + px: { type: 'quant', min: -64, max: 63.998047, bits: 16 }, + py: { type: 'quant', min: -64, max: 63.998047, bits: 16 }, + label: { type: 'short_str' }, + }, + stats: { + slow_ms: { type: 'u16' }, + tick_ms: { type: 'f32' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + face: { mode: 'replace' }, + name: { mode: 'replace' }, + }, +}; diff --git a/distributed_cli/tests/fixtures/game-client/sample/surface.json b/distributed_cli/tests/fixtures/game-client/sample/surface.json new file mode 100644 index 000000000..63dab5de2 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/surface.json @@ -0,0 +1,440 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "view_radius", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "Board", + "type": "record" + } + } + }, + { + "id": 3, + "name": "respawned", + "payload": { + "fields": [], + "kind": "fields" + } + }, + { + "id": 4, + "name": "shot", + "payload": { + "fields": [ + { + "name": "hit", + "type": { + "type": "bool" + } + }, + { + "name": "target", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "offset", + "type": { + "type": "i16" + } + }, + { + "name": "small", + "type": { + "type": "i8" + } + }, + { + "name": "at_ms", + "type": { + "type": "f64" + } + }, + { + "name": "tags", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "bytes", + "type": { + "type": "bytes" + } + }, + { + "name": "total", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + }, + { + "id": 9, + "name": "ping", + "payload": { + "fields": [ + { + "name": "seq", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + }, + { + "name": "aim", + "type": { + "bits": 10, + "type": "angle" + } + }, + { + "name": "power", + "range": [ + 0.0, + 1.0 + ], + "type": { + "type": "f32" + } + }, + { + "name": "view_tick", + "type": { + "type": "u32" + } + } + ], + "name": "SampleInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 16.0, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + }, + { + "correction": null, + "name": "score", + "priority": 1.0, + "type": { + "type": "i32" + } + }, + { + "correction": null, + "name": "raw", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "blob", + "priority": 1.0, + "type": { + "type": "bytes" + } + }, + { + "correction": null, + "name": "kills", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "px", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "py", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "label", + "priority": 1.0, + "type": { + "type": "short_str" + } + } + ], + "id": 2, + "name": "marker", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 4, + "name": "stats", + "priority": 1.0 + } + ], + "name": "sample", + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "version", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "note", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "motd", + "type": { + "type": "str" + } + } + ], + "name": "Board" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u16" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "u64" + } + } + ], + "name": "Row" + } + ], + "schemaVersion": 1 +} diff --git a/distributed_cli/tests/fixtures/game-surface/Cargo.toml b/distributed_cli/tests/fixtures/game-surface/Cargo.toml new file mode 100644 index 000000000..330aa0e08 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-surface/Cargo.toml @@ -0,0 +1,15 @@ +# Standalone fixture compiled by `distributed game-manifest` in integration tests. +# Its own `[workspace]` decouples it from the repo workspace. +[package] +name = "game-surface-fixture" +version = "0.0.0" +edition = "2021" +publish = false + +[workspace] + +[lib] +path = "src/lib.rs" + +[dependencies] +distributed_game = { path = "../../../../distributed_game" } diff --git a/distributed_cli/tests/fixtures/game-surface/src/lib.rs b/distributed_cli/tests/fixtures/game-surface/src/lib.rs new file mode 100644 index 000000000..a609ee6c0 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-surface/src/lib.rs @@ -0,0 +1,62 @@ +//! A minimal zone surface for `distributed game-manifest` tests. + +use distributed_game::{ + schema, Ctx, EntitySchema, GameEvent, GameInput, GameSurface, PlayerId, Replicated, WorldView, + Zone, +}; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +pub struct OrbView { + #[quant(centered = 32.0, bits = 14)] + #[correct(ease = 80)] + pub x: f32, + #[quant(centered = 32.0, bits = 14)] + #[correct(ease = 80)] + pub y: f32, +} + +#[derive(Clone, Copy, GameInput)] +pub struct Steer { + #[range(min = -127, max = 127)] + pub turn: i8, + #[buttons(boost)] + pub buttons: u8, +} + +#[derive(GameEvent)] +pub enum OrbEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, +} + +pub struct Orbs; + +impl Zone for Orbs { + type Config = (); + type Input = Steer; + type Timer = (); + + fn schema() -> EntitySchema { + schema![OrbView] + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Orbs + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + Steer::from_payload(payload) + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + fn replicate(&self, out: &mut WorldView) { + out.add(1, &OrbView { x: 0.0, y: 0.0 }); + } +} + +/// The export `distributed game-manifest` runs by default. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("orbs").events::() +} From beb077bb23f5ecdee669e874dfabf58375d4443a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:31:46 -0500 Subject: [PATCH 181/484] fix(cli): emit exact binary32 quantization bounds in game clients --- distributed_cli/src/game_client.rs | 13 +++++++++++-- .../tests/fixtures/game-client/sample/schema.ts | 8 ++++---- js/tests/game-generated.test.mjs | 4 +++- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs index aeab807a1..380a60cf0 100644 --- a/distributed_cli/src/game_client.rs +++ b/distributed_cli/src/game_client.rs @@ -298,6 +298,15 @@ fn f32_literal(v: f32) -> String { } } +/// The exact binary32 value as a JS number (`Math.fround` of it is itself). +fn f32_exact(v: f32) -> String { + if v.is_finite() { + format!("{}", f64::from(v)) + } else { + "Number.NaN".into() + } +} + fn f64_literal(v: f64) -> String { format!("{v}") } @@ -612,8 +621,8 @@ impl<'a> Gen<'a> { match ty { Wire::Quant { min, max, bits } => format!( "{{ type: 'quant', min: {}, max: {}, bits: {bits} }}", - f32_literal(*min), - f32_literal(*max) + f32_exact(*min), + f32_exact(*max) ), Wire::Angle { bits } => format!("{{ type: 'angle', bits: {bits} }}"), Wire::List { item } => format!("{{ type: 'list', item: {} }}", self.wire_literal(item)), diff --git a/distributed_cli/tests/fixtures/game-client/sample/schema.ts b/distributed_cli/tests/fixtures/game-client/sample/schema.ts index ad605c59b..66b1efcc2 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/schema.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/schema.ts @@ -114,8 +114,8 @@ export function statsFields(entity: { readonly fields: EntityFields }): StatsFie /** Wire type of every replicated field, by kind and wire field name. */ export const FIELD_TYPES = { player: { - x: { type: 'quant', min: -20, max: 19.999847, bits: 18 }, - y: { type: 'quant', min: -20, max: 19.999847, bits: 18 }, + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, vx: { type: 'quant', min: -16, max: 16, bits: 12 }, face: { type: 'angle', bits: 8 }, name: { type: 'short_str' }, @@ -128,8 +128,8 @@ export const FIELD_TYPES = { kills: { type: 'u32' }, }, marker: { - px: { type: 'quant', min: -64, max: 63.998047, bits: 16 }, - py: { type: 'quant', min: -64, max: 63.998047, bits: 16 }, + px: { type: 'quant', min: -64, max: 63.998046875, bits: 16 }, + py: { type: 'quant', min: -64, max: 63.998046875, bits: 16 }, label: { type: 'short_str' }, }, stats: { diff --git a/js/tests/game-generated.test.mjs b/js/tests/game-generated.test.mjs index 4bd33a1dc..08712f874 100644 --- a/js/tests/game-generated.test.mjs +++ b/js/tests/game-generated.test.mjs @@ -80,7 +80,9 @@ test('kinds, typed field accessors and correction defaults follow the surface', assert.deepEqual(gen.statsFields({ fields: { slow_ms: 12, tick_ms: 33 } }), { slowMs: 12, tickMs: 33 }); assert.deepEqual(gen.CORRECTIONS.player.x, { mode: 'ease', durationMs: 150 }); assert.deepEqual(gen.CORRECTIONS.player.name, { mode: 'replace' }); - assert.deepEqual(gen.FIELD_TYPES.player.x, surface.kinds[0].fields[0].type); + // Generated bounds are the exact binary32 values (the surface JSON spells them shortest). + const x = surface.kinds[0].fields[0].type; + assert.deepEqual(gen.FIELD_TYPES.player.x, { ...x, min: Math.fround(x.min), max: Math.fround(x.max) }); }); test('typed subscriptions decode only their own event', () => { From b8f962f6c0d4c5c28f75ef9bcc63ff01b3798965 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:31:47 -0500 Subject: [PATCH 182/484] feat(examples): author the arena with derives and a generated client Arena kinds, input and hello event come from #[derive(Replicated)], #[derive(GameInput)] and #[derive(GameEvent)]; the browser client wraps the generated createArenaClient. run.sh gen regenerates clients and smoke checks them. --- examples/game/client/src/arena/client.ts | 62 ++--- examples/game/client/src/arena/main.ts | 73 +++--- examples/game/client/src/arena/movement.ts | 39 ++- .../game/client/src/generated/arena/client.ts | 49 ++++ .../game/client/src/generated/arena/events.ts | 54 ++++ .../game/client/src/generated/arena/index.ts | 7 + .../game/client/src/generated/arena/input.ts | 46 ++++ .../game/client/src/generated/arena/schema.ts | 136 +++++++++++ .../client/src/generated/arena/surface.json | 231 ++++++++++++++++++ examples/game/client/src/shared/latest.ts | 29 +++ .../client/tests/movement-parity.test.mjs | 4 +- examples/game/run.sh | 37 ++- examples/game/server/Cargo.lock | 12 + examples/game/server/src/arena/mod.rs | 218 ++++++++++------- examples/game/server/src/arena/movement.rs | 41 +--- examples/game/server/src/freeze/mod.rs | 6 +- examples/game/server/src/mobpit/zone.rs | 5 +- examples/game/server/src/ripple/mod.rs | 8 +- .../game/server/tests/movement_fixture.rs | 3 +- examples/game/server/tests/support/mod.rs | 27 +- 20 files changed, 847 insertions(+), 240 deletions(-) create mode 100644 examples/game/client/src/generated/arena/client.ts create mode 100644 examples/game/client/src/generated/arena/events.ts create mode 100644 examples/game/client/src/generated/arena/index.ts create mode 100644 examples/game/client/src/generated/arena/input.ts create mode 100644 examples/game/client/src/generated/arena/schema.ts create mode 100644 examples/game/client/src/generated/arena/surface.json create mode 100644 examples/game/client/src/shared/latest.ts diff --git a/examples/game/client/src/arena/client.ts b/examples/game/client/src/arena/client.ts index 29b030e4b..0cf7a913e 100644 --- a/examples/game/client/src/arena/client.ts +++ b/examples/game/client/src/arena/client.ts @@ -1,64 +1,46 @@ /** - * Arena networking without rendering: builds the `GameClient` with - * prediction for the own capsule and binds it from the zone's hello event. - * Used by `main.ts` (Babylon) and by the headless Node test. + * Arena networking without rendering: the generated `createArenaClient` + * (input encoder, correction defaults, typed events) plus the demo's + * predicted movement step and dev tickets; binds the own capsule from the + * zone's typed `hello`. Used by `main.ts` (Babylon) and the headless test. */ -import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; +import type { GameSocketFactory } from '@hops-ops/distributed/game'; +import * as arena from '../generated/arena/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; -import { encodeMoveInput, predictPlayer, type MoveInput } from './movement.ts'; +import { latest } from '../shared/latest.ts'; +import { predictPlayer } from './movement.ts'; export const DEFAULT_ZONE = 'arena-1'; -/** Event type ids (server `arena::EVENT_*`). */ -export const EVENT_HELLO = 1; -/** Replicated kind names. */ -export const KIND = { player: 'player', drone: 'drone', pillar: 'pillar' } as const; -export type ArenaHello = Readonly<{ entity: number; viewRadius: number; half: number }>; - -export type ArenaClient = Readonly<{ - client: GameClient; - /** Latest hello (own entity id, view radius); undefined until joined. */ - hello(): ArenaHello | undefined; - /** Resolves on the first hello. */ - ready: Promise; -}>; +export type ArenaClient = arena.ArenaClient & + Readonly<{ + /** Latest hello (own entity id, view radius); undefined until joined. */ + hello(): arena.HelloEvent | undefined; + /** Resolves on the first hello. */ + ready: Promise; + }>; export type ArenaClientOptions = Readonly<{ api: DevApi; /** HTTP origin of the server (Node); default: the page origin. */ base?: string; socket?: GameSocketFactory; - /** Ease duration for position corrections (ms). */ - easeMs?: number; }>; export function createArenaClient(options: ArenaClientOptions): ArenaClient { - const ease = { mode: 'ease', durationMs: options.easeMs ?? 150 } as const; - const snap = { mode: 'snap' } as const; - const client = new GameClient({ + const typed = arena.createArenaClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 500, // One input = one 30 Hz command frame on the server. inputDtMs: 1000 / 30, - prediction: { - encodeInput: (input) => encodeMoveInput(input), - predict: (fields, input) => predictPlayer(fields, input), - corrections: { - [KIND.player]: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } - } - } - }); - let hello: ArenaHello | undefined; - let resolveReady: (h: ArenaHello) => void = () => undefined; - const ready = new Promise((resolve) => (resolveReady = resolve)); - onJsonEvent(client, EVENT_HELLO, (value) => { - hello = value; - client.setControlledEntity(value.entity); - resolveReady(value); + prediction: { predict: (fields, input) => predictPlayer(fields, input) } }); - return { client, hello: () => hello, ready }; + const hello = latest( + (h) => typed.on('hello', h), + (value) => typed.client.setControlledEntity(value.entity) + ); + return { ...typed, hello: hello.get, ready: hello.ready }; } diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index ea1ad6e84..167f56980 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -22,8 +22,9 @@ import { Hud } from '../shared/hud.ts'; import { cameraRelative, describeGamepad, InputSampler, toAxis } from '../shared/input.ts'; import { Minimap, type MinimapDot } from '../shared/minimap.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; -import { createArenaClient, DEFAULT_ZONE, KIND } from './client.ts'; -import { BUTTON_DASH, DASH_COOLDOWN, HALF, PLAYER_RADIUS, type MoveInput } from './movement.ts'; +import { droneFields, isDrone, isPillar, pillarFields, playerFields, BUTTON, type MoveInput } from '../generated/arena/index.ts'; +import { createArenaClient, DEFAULT_ZONE } from './client.ts'; +import { DASH_COOLDOWN, HALF, PLAYER_RADIUS } from './movement.ts'; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; @@ -90,7 +91,8 @@ const droneTemplate = (() => { return merged; })(); -type Visual = { mesh: Mesh | ReturnType; kind: string }; +type VisualKind = 'player' | 'drone' | 'pillar'; +type Visual = { mesh: Mesh | ReturnType; kind: VisualKind }; const visuals = new Map(); const ghost = capsule('ghost', mats.ghost); const ring = createRing(scene, 14, '#6cc4ff'); @@ -111,29 +113,20 @@ const minimap = new Minimap({ function visualFor(entity: RenderedEntity, mine: boolean): Visual { let visual = visuals.get(entity.key); if (visual !== undefined) return visual; - switch (entity.kindName) { - case KIND.drone: - visual = { mesh: droneTemplate.createInstance(entity.key), kind: KIND.drone }; - break; - case KIND.pillar: { - const r = num(entity, 'r'); - const mesh = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2, tessellation: 24 }, scene); - mesh.material = mats.pillar; - visual = { mesh, kind: KIND.pillar }; - break; - } - default: - visual = { mesh: capsule(entity.key, mine ? mats.me : mats.other), kind: KIND.player }; + if (isDrone(entity)) { + visual = { mesh: droneTemplate.createInstance(entity.key), kind: 'drone' }; + } else if (isPillar(entity)) { + const { r } = pillarFields(entity); + const mesh = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2, tessellation: 24 }, scene); + mesh.material = mats.pillar; + visual = { mesh, kind: 'pillar' }; + } else { + visual = { mesh: capsule(entity.key, mine ? mats.me : mats.other), kind: 'player' }; } visuals.set(entity.key, visual); return visual; } -function num(entity: RenderedEntity | { fields: RenderedEntity['fields'] }, field: string): number { - const v = entity.fields[field]; - return typeof v === 'number' ? v : 0; -} - // ---- input: one command frame per 30 Hz tick ---- const sampler = new InputSampler(); const commandFrames = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); @@ -142,7 +135,7 @@ let lastInput: MoveInput = { mx: 0, my: 0, buttons: 0 }; function sendCommandFrame(): void { const s = sampler.sample(); const move = cameraRelative(s, stage.cameraForward()); - lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON_DASH : 0 }; + lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON.dash : 0 }; client.sendInput(lastInput); } @@ -156,35 +149,34 @@ stage.onFrame((now, dtMs) => { const isMine = (entity: RenderedEntity) => authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; const mineEntity = rendered.find(isMine); - let me: { x: number; y: number } | undefined = - mineEntity === undefined ? undefined : { x: num(mineEntity, 'x'), y: num(mineEntity, 'y') }; + let me: { x: number; y: number } | undefined = mineEntity === undefined ? undefined : playerFields(mineEntity); const viewRadius = hello?.viewRadius ?? 14; const dots: MinimapDot[] = []; for (const entity of rendered) { const mine = isMine(entity); - // Prediction off (P): the SDK renders the own capsule like everyone - // else's, interpolated in the past. - const fields = entity.fields; const visual = visualFor(entity, mine); - const x = num({ fields }, 'x'); - const y = num({ fields }, 'y'); seen.add(entity.key); - const distance = me === undefined ? 0 : Math.hypot(x - me.x, y - me.y); - if (visual.kind === KIND.drone) { + const distanceTo = (x: number, y: number) => (me === undefined ? 0 : Math.hypot(x - me.x, y - me.y)); + if (visual.kind === 'drone') { + const { x, y, yaw } = droneFields(entity); // Shrink toward the edge so culling at the ring reads as "out of view". - const s = Math.min(1, Math.max(0.2, (viewRadius - distance) / FADE_BAND)); + const s = Math.min(1, Math.max(0.2, (viewRadius - distanceTo(x, y)) / FADE_BAND)); visual.mesh.position.copyFrom(toWorld(x, y, 1.3)); - visual.mesh.rotation.y = -num(entity, 'yaw'); + visual.mesh.rotation.y = -yaw; visual.mesh.scaling.setAll(s); dots.push({ x, y, color: COLORS.drone, size: 2 }); - } else if (visual.kind === KIND.pillar) { + } else if (visual.kind === 'pillar') { + const { x, y, r } = pillarFields(entity); visual.mesh.position.copyFrom(toWorld(x, y, 1)); - dots.push({ x, y, color: COLORS.pillar, size: Math.max(2, num(entity, 'r') * 2), hollow: true }); + dots.push({ x, y, color: COLORS.pillar, size: Math.max(2, r * 2), hollow: true }); } else { + // Prediction off (P): the SDK renders the own capsule like everyone + // else's, interpolated in the past. + const { x, y, dash, name: label } = playerFields(entity); + const distance = distanceTo(x, y); visual.mesh.position.copyFrom(toWorld(x, y, 0.9)); - const dashing = num({ fields }, 'dash') > 0; + const dashing = dash > 0; visual.mesh.scaling.copyFromFloats(dashing ? 1.25 : 1, 1, dashing ? 1.25 : 1); - const label = String(fields.name ?? ''); const outside = !mine && distance > viewRadius; if (!mine) (visual.mesh as Mesh).material = outside ? mats.otherFar : mats.other; const text = mine ? `${label} (you)` : outside ? `${label} · outside view` : label; @@ -194,7 +186,7 @@ stage.onFrame((now, dtMs) => { if (mine) me = { x, y }; dots.push({ x, y, color: mine ? COLORS.me : COLORS.other, size: mine ? 4 : 3.5 }); } - visual.mesh.setEnabled((!entity.stale || visual.kind === KIND.pillar) && !(mine && stage.view() === 'first')); + visual.mesh.setEnabled((!entity.stale || visual.kind === 'pillar') && !(mine && stage.view() === 'first')); } for (const [key, visual] of visuals) { if (seen.has(key)) continue; @@ -206,8 +198,7 @@ stage.onFrame((now, dtMs) => { const authoritative = client.predictor?.authoritative(); let ghostVisible = ghostOn && authoritative !== undefined; if (authoritative !== undefined) { - const gx = num({ fields: authoritative }, 'x'); - const gy = num({ fields: authoritative }, 'y'); + const { x: gx, y: gy } = playerFields({ fields: authoritative }); ghost.position.copyFrom(toWorld(gx, gy, 0.9)); // First person: the eye sits inside the ghost; show it only once it lags visibly. if (stage.view() === 'first' && me !== undefined && Math.hypot(gx - me.x, gy - me.y) < 0.8) ghostVisible = false; @@ -226,7 +217,7 @@ stage.onFrame((now, dtMs) => { minimap.draw({ me, viewRadius, dots }); hud.frame({ entities: rendered.length }); const predictor = client.predictor; - const cd = authoritative === undefined ? 0 : num({ fields: authoritative }, 'cd'); + const cd = authoritative === undefined ? 0 : playerFields({ fields: authoritative }).cd; hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); hud.row('Pending inputs', String(predictor?.pending.length ?? 0)); hud.row('Ack seq', String(predictor?.lastAck ?? 0)); diff --git a/examples/game/client/src/arena/movement.ts b/examples/game/client/src/arena/movement.ts index c8e7aaaa7..1c0746293 100644 --- a/examples/game/client/src/arena/movement.ts +++ b/examples/game/client/src/arena/movement.ts @@ -11,10 +11,17 @@ * `tests/movement-parity.test.mjs` replays the Rust-generated fixture * `examples/game/fixtures/arena-movement.json` through this file. * - * No imports except the SDK quantizers so Node can run it directly. + * The input type, its sanitize and the wire quantization come from the + * client generated from the Rust surface (`../generated/arena`). */ import { dequantizeLinear, quantizeLinear, type EntityFields } from '@hops-ops/distributed/game'; +import { BUTTON, FIELD_TYPES, sanitizeInput, type MoveInput } from '../generated/arena/index.ts'; + +export type { MoveInput } from '../generated/arena/index.ts'; +/** TEMPORARY (demo conversion in progress): use the generated `encodeInput`. */ +export { encodeInput as encodeMoveInput } from '../generated/arena/index.ts'; + const f = Math.fround; export const DT = f(1 / 30); @@ -25,7 +32,7 @@ export const ACCEL = 40; export const DASH_SPEED = 14; export const DASH_FRAMES = 6; export const DASH_COOLDOWN = 45; -export const BUTTON_DASH = 1; +export const BUTTON_DASH = BUTTON.dash; /** Static circular pillars `[x, y, radius]`. */ export const PILLARS: readonly (readonly [number, number, number])[] = [ @@ -42,17 +49,9 @@ export const PILLARS: readonly (readonly [number, number, number])[] = [ export type Quant = Readonly<{ min: number; max: number; bits: number }>; -/** `FieldType::quant_centered(range, bits)`: zero is on the grid. */ -export function quantCentered(range: number, bits: number): Quant { - return { min: -range, max: f(range - range / 2 ** (bits - 1)), bits }; -} - -/** Wire quantization of `x`/`y` and `vx`/`vy` (must match the Rust schema). */ -export const POS = quantCentered(HALF, 18); -export const VEL = quantCentered(16, 12); - -/** One command frame: stick per axis in [-127, 127] and button bits. */ -export type MoveInput = Readonly<{ mx: number; my: number; buttons: number }>; +/** Wire quantization of `x`/`y` and `vx`/`vy` (from the Rust schema). */ +export const POS: Quant = FIELD_TYPES.player.x; +export const VEL: Quant = FIELD_TYPES.player.vx; export type MoveState = Readonly<{ x: number; @@ -63,24 +62,14 @@ export type MoveState = Readonly<{ cooldown: number; }>; -/** Wire payload `[mx, my, buttons]` (as the server decodes it). */ -export function encodeMoveInput(input: MoveInput): Uint8Array { - return new Uint8Array([input.mx & 0xff, input.my & 0xff, input.buttons & 0xff]); -} - -/** The server's sanitization: -128 → -127, unknown buttons cleared. */ -export function sanitizeMoveInput(input: MoveInput): MoveInput { - const axis = (v: number) => Math.max(-127, Math.min(127, Math.trunc(v))); - return { mx: axis(input.mx), my: axis(input.my), buttons: input.buttons & BUTTON_DASH }; -} - function snap(q: Quant, v: number): number { return dequantizeLinear(quantizeLinear(v, q.min, q.max, q.bits), q.min, q.max, q.bits); } /** Advance one command frame (see the module docs). */ export function step(state: MoveState, raw: MoveInput): MoveState { - const input = sanitizeMoveInput(raw); + // What the server simulates: -128 → -127, unknown buttons cleared. + const input = sanitizeInput(raw); let { x, y, vx, vy, dash, cooldown } = state; let dx = f(input.mx / 127); let dy = f(input.my / 127); diff --git a/examples/game/client/src/generated/arena/client.ts b/examples/game/client/src/generated/arena/client.ts new file mode 100644 index 000000000..f3844df36 --- /dev/null +++ b/examples/game/client/src/generated/arena/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type MoveInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type ArenaPredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type ArenaClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: ArenaPredictionOptions }>; + +export type ArenaClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: MoveInput): number | undefined; +}>; + +/** A `GameClient` for the `arena` surface with its input encoder and correction defaults. */ +export function createArenaClient(options: ArenaClientOptions): ArenaClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/arena/events.ts b/examples/game/client/src/generated/arena/events.ts new file mode 100644 index 000000000..97f1109a9 --- /dev/null +++ b/examples/game/client/src/generated/arena/events.ts @@ -0,0 +1,54 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly viewRadius: number; + readonly half: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['viewRadius', { type: 'f32' }], + ['half', { type: 'f32' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/arena/index.ts b/examples/game/client/src/generated/arena/index.ts new file mode 100644 index 000000000..599e7b1ea --- /dev/null +++ b/examples/game/client/src/generated/arena/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/arena/input.ts b/examples/game/client/src/generated/arena/input.ts new file mode 100644 index 000000000..8b80618d0 --- /dev/null +++ b/examples/game/client/src/generated/arena/input.ts @@ -0,0 +1,46 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `MoveInput` input frame (`#[derive(GameInput)]`). */ +export interface MoveInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; +} + +export type Input = MoveInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + dash: 1, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 1 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: MoveInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): MoveInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as MoveInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: MoveInput): MoveInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/arena/schema.ts b/examples/game/client/src/generated/arena/schema.ts new file mode 100644 index 000000000..8630261b9 --- /dev/null +++ b/examples/game/client/src/generated/arena/schema.ts @@ -0,0 +1,136 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + drone: 2, + pillar: 3, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vx: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vy: number; + /** `u8` */ + readonly dash: number; + /** `u8` */ + readonly cd: number; + /** `short_str`, priority 0.2 */ + readonly name: string; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + vy: fieldNumber(f, 'vy'), + dash: fieldNumber(f, 'dash'), + cd: fieldNumber(f, 'cd'), + name: fieldString(f, 'name'), + }; +} + +/** `drone` (kind 2, priority 1). */ +export interface DroneFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; + /** `angle / 8 bits` */ + readonly yaw: number; +} + +/** True for a `drone` entity. */ +export function isDrone(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `drone` entity (rendered or replica). */ +export function droneFields(entity: { readonly fields: EntityFields }): DroneFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + yaw: fieldNumber(f, 'yaw'), + }; +} + +/** `pillar` (kind 3, priority 1). */ +export interface PillarFields { + /** `f32` */ + readonly x: number; + /** `f32` */ + readonly y: number; + /** `f32` */ + readonly r: number; +} + +/** True for a `pillar` entity. */ +export function isPillar(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `pillar` entity (rendered or replica). */ +export function pillarFields(entity: { readonly fields: EntityFields }): PillarFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + r: fieldNumber(f, 'r'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + dash: { type: 'u8' }, + cd: { type: 'u8' }, + name: { type: 'short_str' }, + }, + drone: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + yaw: { type: 'angle', bits: 8 }, + }, + pillar: { + x: { type: 'f32' }, + y: { type: 'f32' }, + r: { type: 'f32' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + vy: { mode: 'snap' }, + dash: { mode: 'snap' }, + cd: { mode: 'snap' }, + name: { mode: 'replace' }, + }, +}; diff --git a/examples/game/client/src/generated/arena/surface.json b/examples/game/client/src/generated/arena/surface.json new file mode 100644 index 000000000..a9a7da870 --- /dev/null +++ b/examples/game/client/src/generated/arena/surface.json @@ -0,0 +1,231 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "view_radius", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "type": "f32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash" + ], + "name": "buttons", + "type": { + "type": "u8" + } + } + ], + "name": "MoveInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vy", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "dash", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "cd", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "yaw", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + } + ], + "id": 2, + "name": "drone", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "r", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 3, + "name": "pillar", + "priority": 1.0 + } + ], + "name": "arena", + "protocolVersion": 1, + "records": [], + "schemaVersion": 1 +} diff --git a/examples/game/client/src/shared/latest.ts b/examples/game/client/src/shared/latest.ts new file mode 100644 index 000000000..504402ed2 --- /dev/null +++ b/examples/game/client/src/shared/latest.ts @@ -0,0 +1,29 @@ +/** + * The latest value of one typed event, plus a promise for the first one — + * e.g. a zone's `hello` (own entity id) that arrives right after joining: + * + * ```ts + * const hello = latest((h) => typed.on('hello', h)); + * ``` + */ +export type Latest = Readonly<{ + /** Latest value; undefined until the first event. */ + get(): T | undefined; + /** Resolves on the first event. */ + ready: Promise; +}>; + +export function latest( + subscribe: (handler: (value: T) => void) => unknown, + onValue?: (value: T) => void +): Latest { + let value: T | undefined; + let resolve: (v: T) => void = () => undefined; + const ready = new Promise((r) => (resolve = r)); + subscribe((v) => { + value = v; + onValue?.(v); + resolve(v); + }); + return { get: () => value, ready }; +} diff --git a/examples/game/client/tests/movement-parity.test.mjs b/examples/game/client/tests/movement-parity.test.mjs index 476ef7b4d..0bf0fcb7b 100644 --- a/examples/game/client/tests/movement-parity.test.mjs +++ b/examples/game/client/tests/movement-parity.test.mjs @@ -26,10 +26,10 @@ test('constants and wire quantization match the Rust side', () => { assert.equal(c.dashCooldown, movement.DASH_COOLDOWN); assert.deepEqual(c.pillars, movement.PILLARS.map((p) => [...p])); const byName = Object.fromEntries(fixture.fields.map((field) => [field.name, field])); - for (const [name, quant] of [['x', movement.POS], ['y', movement.POS], ['vx', movement.VEL], ['vy', movement.VEL]]) { + for (const [name, { min, max, bits }] of [['x', movement.POS], ['y', movement.POS], ['vx', movement.VEL], ['vy', movement.VEL]]) { assert.deepEqual( { min: byName[name].min, max: byName[name].max, bits: byName[name].bits }, - { ...quant }, + { min, max, bits }, name ); } diff --git a/examples/game/run.sh b/examples/game/run.sh index ea8b1d8d9..26254bb5c 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -6,7 +6,11 @@ # ./run.sh mobpit same for Mob Pit; `leaderboard` = same server, board page # ./run.sh grid|ripple same with TWO hosts (A on GAME_DEMOS_PORT, B on # the next port), one process each -# ./run.sh smoke every demo's smoke tests (Rust bots + headless JS) +# ./run.sh gen regenerate client/src/generated// from the +# Rust surfaces (`distributed game-manifest` + +# `distributed game-client`); `gen --check` verifies +# ./run.sh smoke every demo's smoke tests (Rust bots + headless JS, +# generated clients checked) # ./run.sh list demos this script knows # # Env: GAME_DEMOS_PORT (server, default 2567), GAME_DEMOS_CLIENT_PORT (Vite, @@ -25,6 +29,10 @@ DEMOS=(arena mobpit leaderboard gallery freeze grid ripple) export MOBPIT_DATA_DIR="${MOBPIT_DATA_DIR:-$HERE/.data/mobpit}" # Multi-host demos: `game-demos --host-id A|B --peer …`. CLUSTER_DEMOS=(grid ripple) +# Game surfaces with a generated client (`game_demos::::game_surface`); +# the leaderboard page uses Mob Pit's. +SURFACES=(arena mobpit gallery freeze grid ripple) +CLI="$REPO/target/debug/distributed" log() { printf '\033[1;36m[demos]\033[0m %s\n' "$*"; } @@ -54,6 +62,28 @@ ensure_server() { cargo build --quiet --manifest-path "$SERVER/Cargo.toml" } +ensure_cli() { + log "building distributed CLI" + cargo build --quiet --manifest-path "$REPO/Cargo.toml" -p distributed_cli --bin distributed +} + +# gen [--check]: GameSurface JSON from each Rust surface export → typed +# TypeScript in client/src/generated// (surface.json included, so a +# changed Rust definition shows up as drift). +gen() { + local check="${1:-}" + ensure_cli + local tmp + tmp="$(mktemp -d "${TMPDIR:-/tmp}/game-surfaces.XXXXXX")" + trap 'rm -rf "$tmp"' RETURN + for surface in "${SURFACES[@]}"; do + "$CLI" game-manifest --manifest-path "$SERVER/Cargo.toml" \ + --entrypoint "game_demos::$surface::game_surface" --out "$tmp/$surface.json" + "$CLI" game-client --manifest "$tmp/$surface.json" \ + --out "$CLIENT/src/generated/$surface" $check + done +} + run_demo() { local demo="$1" local port="${GAME_DEMOS_PORT:-2567}" @@ -132,6 +162,8 @@ run_cluster() { smoke() { ensure_sdk ensure_client + log "generated clients are current" + gen --check log "server: fmt, clippy, tests (bots smoke + movement fixture)" cargo fmt --manifest-path "$SERVER/Cargo.toml" --check cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --all-targets -- -D warnings @@ -144,8 +176,9 @@ smoke() { case "${1:-}" in smoke) smoke ;; + gen) gen "${2:-}" ;; list) printf '%s\n' "${DEMOS[@]}" ;; - "" | -h | --help | help) sed -n '2,16p' "$0" ;; + "" | -h | --help | help) sed -n '2,21p' "$0" ;; *) if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then run_cluster "$1" diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index f356b49f9..cc8a5c97b 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -437,15 +437,27 @@ dependencies = [ "axum", "base64 0.23.1", "distributed", + "distributed_game_macros", "futures-util", "hmac", "rusqlite", + "serde", "serde_json", "sha2", "tokio", "tokio-tungstenite 0.30.0", ] +[[package]] +name = "distributed_game_macros" +version = "0.1.0" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "distributed_macros" version = "0.1.0" diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index 9e2794cb3..71f2cff5c 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -15,9 +15,11 @@ //! | 2 `drone` | 1..=30 | x y yaw | wander between random targets | //! | 3 `pillar` | 100 + i | x y r | global (visible everywhere) | //! -//! Event [`EVENT_HELLO`] (JSON) tells a joining player its entity and the -//! view radius. Inputs are 3 bytes ([`MoveInput`]); each input is one -//! command frame. A player earns one frame credit per tick (max +//! Kinds are `#[derive(Replicated)]` views ([`PlayerView`], [`DroneView`], +//! [`PillarView`]); [`ArenaEvent::Hello`] tells a joining player its entity +//! and the view radius. Inputs are 3 bytes ([`MoveInput`], a +//! `#[derive(GameInput)]`); each input is one command frame. The browser +//! client is generated from [`game_surface`] (`run.sh gen`). A player earns one frame credit per tick (max //! [`MAX_CREDITS`], `distributed_game::InputCredits`), so a client cannot //! move faster than real time by sending more inputs, but jitter bursts are //! absorbed. @@ -28,22 +30,109 @@ use std::collections::BTreeMap; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::{ - Ctx, EntitySchema, EntityState, FieldType, FieldValue, InputCredits, KindDef, LeaveReason, - PlayerId, View, WorldView, Zone, + schema, Ctx, EntitySchema, GameEvent, GameInput, GameSurface, InputCredits, LeaveReason, + PlayerId, Replicated, View, WorldView, Zone, }; -use serde_json::json; -use crate::common::{send_json_event, Demo, Guests}; +use crate::common::{Demo, Guests}; pub use movement::{MoveInput, MoveState}; -/// Player kind. -pub const KIND_PLAYER: u16 = 1; -/// Drone kind. -pub const KIND_DRONE: u16 = 2; -/// Pillar kind. -pub const KIND_PILLAR: u16 = 3; -/// Event type: `{"entity": u32, "viewRadius": f32, "half": f32}` (JSON). -pub const EVENT_HELLO: u32 = 1; +/// A player's capsule: the full [`MoveState`] (so the client can rebase its +/// prediction) plus the display name. Global: everyone in the room is seen. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0, global)] +pub struct PlayerView { + /// Position x. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub x: f32, + /// Position y. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub y: f32, + /// Velocity x. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vx: f32, + /// Velocity y. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vy: f32, + /// Remaining dash frames. + #[correct(snap)] + pub dash: u8, + /// Remaining dash cooldown frames. + #[correct(snap)] + pub cd: u8, + /// Display name. + #[priority(0.2)] + #[correct(replace)] + pub name: String, +} + +impl PlayerView { + /// The view of a capsule. + pub fn of(state: &MoveState, name: &str) -> Self { + Self { + x: state.x, + y: state.y, + vx: state.vx, + vy: state.vy, + dash: state.dash, + cd: state.cooldown, + name: name.to_string(), + } + } +} + +/// A wandering drone (culled by the view radius). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "drone", id = 2)] +pub struct DroneView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub y: f32, + /// Heading. + #[angle(bits = 8)] + pub yaw: f32, +} + +/// A static pillar (visible everywhere). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pillar", id = 3, global)] +pub struct PillarView { + /// Centre x. + pub x: f32, + /// Centre y. + pub y: f32, + /// Radius. + pub r: f32, +} + +/// The Arena's events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum ArenaEvent { + /// To a joining player: its entity, the interest radius and floor size. + #[game_event(id = 1)] + Hello { + /// Own entity id. + entity: u32, + /// Interest radius (m). + view_radius: f32, + /// Floor half extent (m). + half: f32, + }, +} + +/// The Arena's client surface (`distributed game-manifest --entrypoint +/// game_demos::arena::game_surface`). +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("arena").events::() +} + /// Interest radius (m). pub const VIEW_RADIUS: f32 = 14.0; /// Wandering drones. @@ -116,35 +205,7 @@ impl Zone for Arena { type Timer = (); fn schema() -> EntitySchema { - let small = FieldType::QuantF32 { - min: -movement::HALF, - max: movement::HALF, - bits: 14, - }; - EntitySchema::new() - .kind( - KindDef::new(KIND_PLAYER, "player") - .field("x", movement::POS) - .field("y", movement::POS) - .field("vx", movement::VEL) - .field("vy", movement::VEL) - .field("dash", FieldType::U8) - .field("cd", FieldType::U8) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .priority(2.0), - ) - .kind( - KindDef::new(KIND_DRONE, "drone") - .field("x", small) - .field("y", small) - .field("yaw", FieldType::Angle { bits: 8 }), - ) - .kind( - KindDef::new(KIND_PILLAR, "pillar") - .field("x", FieldType::F32) - .field("y", FieldType::F32) - .field("r", FieldType::F32), - ) + schema![PlayerView, DroneView, PillarView] } fn on_create(ctx: &mut Ctx<'_, Self>, config: ArenaConfig) -> Self { @@ -190,11 +251,13 @@ impl Zone for Arena { }, ); ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); - send_json_event( - ctx, + ctx.send( player, - EVENT_HELLO, - &json!({ "entity": entity, "viewRadius": VIEW_RADIUS, "half": movement::HALF }), + &ArenaEvent::Hello { + entity, + view_radius: VIEW_RADIUS, + half: movement::HALF, + }, ); } @@ -204,7 +267,7 @@ impl Zone for Arena { } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - MoveInput::decode(payload) + MoveInput::from_payload(payload) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { @@ -236,50 +299,24 @@ impl Zone for Arena { fn replicate(&self, out: &mut WorldView) { for p in self.players.values() { - let s = p.state; - out.push( - EntityState::new( - p.entity, - KIND_PLAYER, - s.x, - s.y, - vec![ - FieldValue::F(s.x), - FieldValue::F(s.y), - FieldValue::F(s.vx), - FieldValue::F(s.vy), - FieldValue::U(s.dash.into()), - FieldValue::U(s.cooldown.into()), - FieldValue::Str(p.name.clone()), - ], - ) - // Players are global: a small room shows everyone; only drones are - // culled by the view radius. - .global(), - ); + out.add(p.entity, &PlayerView::of(&p.state, &p.name)); } for d in &self.drones { - out.push( - EntityState::new( - d.id, - KIND_DRONE, - d.x, - d.y, - vec![FieldValue::F(d.x), FieldValue::F(d.y), FieldValue::F(d.yaw)], - ) - .priority(0.5), - ); + let view = DroneView { + x: d.x, + y: d.y, + yaw: d.yaw, + }; + out.add(d.id, &view).priority(0.5); } for (i, (x, y, r)) in movement::PILLARS.iter().enumerate() { - out.push( - EntityState::new( - 100 + i as u32, - KIND_PILLAR, - *x, - *y, - vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::F(*r)], - ) - .global(), + out.add( + 100 + i as u32, + &PillarView { + x: *x, + y: *y, + r: *r, + }, ); } } @@ -293,8 +330,7 @@ pub fn encode_bot_input(dir: [f32; 2]) -> Vec { my: axis(dir[1]), buttons: 0, } - .encode() - .to_vec() + .to_payload() } /// Demo registration (`game-demos arena`). diff --git a/examples/game/server/src/arena/movement.rs b/examples/game/server/src/arena/movement.rs index 99250e8de..29a11a16d 100644 --- a/examples/game/server/src/arena/movement.rs +++ b/examples/game/server/src/arena/movement.rs @@ -18,7 +18,7 @@ //! it through the TypeScript step. Change both files together, then //! regenerate with `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. -use distributed_game::FieldType; +use distributed_game::{FieldType, GameInput}; /// Command frame length (s): the 30 Hz tick. pub const DT: f32 = 1.0 / 30.0; @@ -37,7 +37,7 @@ pub const DASH_FRAMES: u8 = 6; /// Dash cooldown in command frames (1.5 s). pub const DASH_COOLDOWN: u8 = 45; /// Input bit: dash. -pub const BUTTON_DASH: u8 = 1; +pub const BUTTON_DASH: u8 = MoveInput::DASH; /// Static circular pillars `(x, y, radius)`. pub const PILLARS: [(f32, f32, f32); 9] = [ @@ -59,37 +59,22 @@ pub const POS: FieldType = FieldType::quant_centered(HALF, 18); pub const VEL: FieldType = FieldType::quant_centered(16.0, 12); /// One command frame from the client: stick in `[-127, 127]` per axis -/// (+x right, +y forward) and button bits. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +/// (+x right, +y forward) and button bits. Wire payload `[mx, my, buttons]` +/// (3 bytes); [`GameInput::from_payload`] clamps `-128` to `-127` and clears +/// unknown buttons. The TypeScript encoder/sanitizer is generated from this. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] pub struct MoveInput { /// Stick x. + #[range(min = -127, max = 127)] pub mx: i8, /// Stick y. + #[range(min = -127, max = 127)] pub my: i8, - /// [`BUTTON_DASH`] … + /// [`MoveInput::DASH`]. + #[buttons(dash)] pub buttons: u8, } -impl MoveInput { - /// Wire payload: `[mx, my, buttons]`. - pub fn encode(self) -> [u8; 3] { - [self.mx as u8, self.my as u8, self.buttons] - } - - /// Parse and sanitize a payload (`-128` clamps to `-127`, unknown - /// buttons are cleared). `None` for a wrong length. - pub fn decode(payload: &[u8]) -> Option { - let [mx, my, buttons] = payload else { - return None; - }; - Some(Self { - mx: (*mx as i8).max(-127), - my: (*my as i8).max(-127), - buttons: buttons & BUTTON_DASH, - }) - } -} - /// Everything the step reads. Every field is replicated, so a client can /// rebase its prediction on the authoritative copy. #[derive(Debug, Clone, Copy, Default, PartialEq)] @@ -342,15 +327,15 @@ mod tests { my: 5, buttons: BUTTON_DASH, }; - assert_eq!(MoveInput::decode(&i.encode()), Some(i)); + assert_eq!(MoveInput::from_payload(&i.to_payload()), Some(i)); assert_eq!( - MoveInput::decode(&[0x80, 0, 0xff]), + MoveInput::from_payload(&[0x80, 0, 0xff]), Some(MoveInput { mx: -127, my: 0, buttons: BUTTON_DASH }) ); - assert_eq!(MoveInput::decode(&[1, 2]), None); + assert_eq!(MoveInput::from_payload(&[1, 2]), None); } } diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs index 23a53e6fe..e197fee2e 100644 --- a/examples/game/server/src/freeze/mod.rs +++ b/examples/game/server/src/freeze/mod.rs @@ -39,8 +39,8 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::{ - Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, InputCredits, KindDef, - LeaveReason, PlayerId, StalePolicy, View, WorldView, Zone, + Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, GameInput, + InputCredits, KindDef, LeaveReason, PlayerId, StalePolicy, View, WorldView, Zone, }; use serde_json::{json, Value}; @@ -336,7 +336,7 @@ impl Zone for FreezeZone { } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - MoveInput::decode(payload) + MoveInput::from_payload(payload) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index f2c4224a2..754e3f990 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -33,7 +33,8 @@ use std::time::Instant; use distributed_game::{ ConsumePolicy, Ctx, EmitError, EntitySchema, EntityState, Fact, FactOutcome, FactSettlement, - FieldType, FieldValue, KindDef, LeaveReason, ObserverId, PlayerId, View, WorldView, Zone, + FieldType, FieldValue, GameInput, KindDef, LeaveReason, ObserverId, PlayerId, View, WorldView, + Zone, }; use serde_json::{json, Value}; @@ -753,7 +754,7 @@ impl Zone for MobPit { } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - let movement = MoveInput::decode(payload)?; + let movement = MoveInput::from_payload(payload)?; Some(PitInput { movement, attack: payload[2] & BUTTON_ATTACK != 0, diff --git a/examples/game/server/src/ripple/mod.rs b/examples/game/server/src/ripple/mod.rs index 7db89698b..c123f1667 100644 --- a/examples/game/server/src/ripple/mod.rs +++ b/examples/game/server/src/ripple/mod.rs @@ -42,8 +42,8 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::world::{HostAddr, ZoneDirectory}; use distributed_game::{ - ChildEvent, ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, - LeaveReason, ObserverId, PlayerId, TimerId, WorldView, Zone, + ChildEvent, ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, GameInput, + KindDef, LeaveReason, ObserverId, PlayerId, TimerId, WorldView, Zone, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -230,7 +230,7 @@ pub struct HoodInput { impl HoodInput { /// Wire payload `[mx, my, buttons, action]`. pub fn encode(self) -> [u8; 4] { - let [mx, my, buttons] = self.movement.encode(); + let [mx, my, buttons] = <[u8; 3]>::try_from(self.movement.to_payload()).expect("3 bytes"); [mx, my, buttons, self.action] } @@ -241,7 +241,7 @@ impl HoodInput { return None; }; Some(Self { - movement: MoveInput::decode(movement)?, + movement: MoveInput::from_payload(movement)?, action: action & (ACTION_ATTACK | ACTION_SMITE), }) } diff --git a/examples/game/server/tests/movement_fixture.rs b/examples/game/server/tests/movement_fixture.rs index b9f806b07..5cf70c757 100644 --- a/examples/game/server/tests/movement_fixture.rs +++ b/examples/game/server/tests/movement_fixture.rs @@ -5,6 +5,7 @@ //! Regenerate after an intended change to BOTH implementations: //! `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. +use distributed_game::GameInput; use std::path::PathBuf; use game_demos::arena::movement::{self, MoveInput, MoveState, BUTTON_DASH}; @@ -53,7 +54,7 @@ fn build() -> Value { let mut steps = Vec::new(); for input in script() { // The server decodes the wire payload, so the fixture does too. - let decoded = MoveInput::decode(&input.encode()).unwrap(); + let decoded = MoveInput::from_payload(&input.to_payload()).unwrap(); s = movement::step(s, decoded); steps.push(json!({ "input": [input.mx, input.my, input.buttons], diff --git a/examples/game/server/tests/support/mod.rs b/examples/game/server/tests/support/mod.rs index 9ec693c8e..ac991e866 100644 --- a/examples/game/server/tests/support/mod.rs +++ b/examples/game/server/tests/support/mod.rs @@ -10,7 +10,7 @@ use distributed_game::net::TicketKey; use distributed_game::protocol::{Hello, Welcome}; use distributed_game::world::HostAddr; use distributed_game::{ - ClientMessage, ClientMirror, Role, ServerMessage, TicketClaims, PROTOCOL_VERSION, + ClientMessage, ClientMirror, GameEvent, Role, ServerMessage, TicketClaims, PROTOCOL_VERSION, }; use futures_util::{SinkExt, StreamExt}; use game_demos::cluster::{spawn_cluster, ClusterDemo, ClusterOptions, RunningHost}; @@ -225,6 +225,31 @@ impl Client { msg } + /// Typed events of `E` received so far. + pub fn seen_events(&self) -> Vec { + self.events + .iter() + .filter_map(|(t, p)| E::decode_event(*t, p).expect("event decodes")) + .collect() + } + + /// Wait (5 s) for the next event of `E` that `pick` accepts. + pub async fn wait_event(&mut self, pick: impl Fn(&E) -> bool) -> E { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + if let ServerMessage::Event { type_id, payload } = + self.next(left).await.expect("event within 5 s") + { + if let Some(event) = E::decode_event(type_id, &payload).expect("event decodes") { + if pick(&event) { + return event; + } + } + } + } + } + /// JSON events of `type_id` received so far. pub fn seen(&self, type_id: u32) -> Vec { self.events From d02815366869a917425e16d3afab682f355d3bc2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:40:27 -0500 Subject: [PATCH 183/484] feat(examples): author mob pit with derives and typed facts Mob Pit kinds, input and events are derived; kills emit the cell command's RecordKillInput as a typed fact (FactCommand bound to RECORD_KILL); the leaderboard snapshot is a typed record shared by the board event and the HTTP route. Mob Pit and Leaderboard pages use the generated client. --- .../client/src/generated/mobpit/client.ts | 49 ++ .../client/src/generated/mobpit/events.ts | 309 +++++++ .../game/client/src/generated/mobpit/index.ts | 7 + .../game/client/src/generated/mobpit/input.ts | 47 + .../client/src/generated/mobpit/schema.ts | 224 +++++ .../client/src/generated/mobpit/surface.json | 827 ++++++++++++++++++ examples/game/client/src/leaderboard/main.ts | 38 +- examples/game/client/src/mobpit/client.ts | 211 +---- examples/game/client/src/mobpit/main.ts | 102 +-- examples/game/client/tests/helpers/mobpit.mjs | 17 +- .../tests/leaderboard-headless.test.mjs | 4 +- .../client/tests/mobpit-headless.test.mjs | 12 +- examples/game/server/src/mobpit/board.rs | 214 +++-- examples/game/server/src/mobpit/crawler.rs | 10 +- examples/game/server/src/mobpit/mod.rs | 7 +- examples/game/server/src/mobpit/routes.rs | 3 +- examples/game/server/src/mobpit/world.rs | 2 +- examples/game/server/src/mobpit/zone.rs | 610 ++++++++----- examples/game/server/tests/mobpit_smoke.rs | 12 +- 19 files changed, 2163 insertions(+), 542 deletions(-) create mode 100644 examples/game/client/src/generated/mobpit/client.ts create mode 100644 examples/game/client/src/generated/mobpit/events.ts create mode 100644 examples/game/client/src/generated/mobpit/index.ts create mode 100644 examples/game/client/src/generated/mobpit/input.ts create mode 100644 examples/game/client/src/generated/mobpit/schema.ts create mode 100644 examples/game/client/src/generated/mobpit/surface.json diff --git a/examples/game/client/src/generated/mobpit/client.ts b/examples/game/client/src/generated/mobpit/client.ts new file mode 100644 index 000000000..9a9fddace --- /dev/null +++ b/examples/game/client/src/generated/mobpit/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type PitInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type MobpitPredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type MobpitClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: MobpitPredictionOptions }>; + +export type MobpitClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: PitInput): number | undefined; +}>; + +/** A `GameClient` for the `mobpit` surface with its input encoder and correction defaults. */ +export function createMobpitClient(options: MobpitClientOptions): MobpitClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts new file mode 100644 index 000000000..35ce3bb8d --- /dev/null +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -0,0 +1,309 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `BackgroundStats` (`#[derive(GameRecord)]`). */ +export interface BackgroundStats { + readonly enqueued: number; + readonly applied: number; + readonly dropped: number; + readonly failed: number; +} + +const BACKGROUND_STATS_TYPE: WireType = { + type: 'record', + fields: [ + ['enqueued', { type: 'u64' }], + ['applied', { type: 'u64' }], + ['dropped', { type: 'u64' }], + ['failed', { type: 'u64' }], + ] +}; + +/** Record `BoardRow` (`#[derive(GameRecord)]`). */ +export interface BoardRow { + readonly rank: number; + readonly member: string; + readonly name: string; + readonly score: number; +} + +const BOARD_ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u32' }], + ['member', { type: 'short_str' }], + ['name', { type: 'short_str' }], + ['score', { type: 'f64' }], + ] +}; + +/** Record `Scores` (`#[derive(GameRecord)]`). */ +export interface Scores { + readonly kills: number; + readonly xp: number; +} + +const SCORES_TYPE: WireType = { + type: 'record', + fields: [ + ['kills', { type: 'f64' }], + ['xp', { type: 'f64' }], + ] +}; + +/** Record `Mismatch` (`#[derive(GameRecord)]`). */ +export interface Mismatch { + readonly member: string; + readonly cell: Scores; + readonly board: Scores; +} + +const MISMATCH_TYPE: WireType = { + type: 'record', + fields: [ + ['member', { type: 'short_str' }], + ['cell', SCORES_TYPE], + ['board', SCORES_TYPE], + ] +}; + +/** Record `RebuildReport` (`#[derive(GameRecord)]`). */ +export interface RebuildReport { + readonly backend: string; + readonly crawlers: number; + readonly events: number; + readonly applied: number; + readonly duplicates: number; + readonly identicalTop: boolean; + readonly matchesCells: boolean; + readonly mismatches: readonly Mismatch[]; + readonly tookMs: number; +} + +const REBUILD_REPORT_TYPE: WireType = { + type: 'record', + fields: [ + ['backend', { type: 'short_str' }], + ['crawlers', { type: 'u32' }], + ['events', { type: 'u32' }], + ['applied', { type: 'u32' }], + ['duplicates', { type: 'u32' }], + ['identicalTop', { type: 'bool' }], + ['matchesCells', { type: 'bool' }], + ['mismatches', { type: 'list', item: MISMATCH_TYPE }], + ['tookMs', { type: 'f64' }], + ] +}; + +/** Record `BoardSnapshot` (`#[derive(GameRecord)]`). */ +export interface BoardSnapshot { + readonly version: number; + readonly backend: string; + readonly members: number; + readonly kills: readonly BoardRow[]; + readonly xp: readonly BoardRow[]; + readonly background: BackgroundStats; + readonly lastRebuild: RebuildReport | undefined; +} + +const BOARD_SNAPSHOT_TYPE: WireType = { + type: 'record', + fields: [ + ['version', { type: 'u64' }], + ['backend', { type: 'short_str' }], + ['members', { type: 'u64' }], + ['kills', { type: 'list', item: BOARD_ROW_TYPE }], + ['xp', { type: 'list', item: BOARD_ROW_TYPE }], + ['background', BACKGROUND_STATS_TYPE], + ['lastRebuild', { type: 'optional', item: REBUILD_REPORT_TYPE }], + ] +}; + +/** Record `Profile` (`#[derive(GameRecord)]`). */ +export interface Profile { + readonly xp: number; + readonly level: number; + readonly kills: number; + readonly levelXp: number; + readonly nextLevelXp: number; + readonly source: string; +} + +const PROFILE_TYPE: WireType = { + type: 'record', + fields: [ + ['xp', { type: 'u64' }], + ['level', { type: 'u32' }], + ['kills', { type: 'u32' }], + ['levelXp', { type: 'u64' }], + ['nextLevelXp', { type: 'u64' }], + ['source', { type: 'short_str' }], + ] +}; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly half: number; + readonly boot: string; + readonly attackRange: number; + readonly attackArcCos: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['half', { type: 'f32' }], + ['boot', { type: 'short_str' }], + ['attackRange', { type: 'f32' }], + ['attackArcCos', { type: 'f32' }], +]; + +/** Event `profile` (id 2). */ +export type ProfileEvent = Profile; + +const PROFILE_PAYLOAD: WireType = PROFILE_TYPE; + +/** Event `kill` (id 3). */ +export interface KillEvent { + readonly key: string; + readonly mob: number; + readonly tier: number; + readonly x: number; + readonly y: number; + readonly killer: number; + readonly killerName: string; +} + +const KILL_LAYOUT: PayloadLayout = [ + ['key', { type: 'short_str' }], + ['mob', { type: 'u32' }], + ['tier', { type: 'u8' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['killer', { type: 'u32' }], + ['killerName', { type: 'short_str' }], +]; + +/** Event `saved` (id 4). */ +export interface SavedEvent { + readonly key: string; + readonly ok: boolean; + readonly replayed: boolean; + readonly xp: number; + readonly totalXp: number; + readonly kills: number; + readonly level: number; + readonly waitedMs: number; + readonly x: number; + readonly y: number; + readonly error: string | undefined; + readonly attempts: number; +} + +const SAVED_LAYOUT: PayloadLayout = [ + ['key', { type: 'short_str' }], + ['ok', { type: 'bool' }], + ['replayed', { type: 'bool' }], + ['xp', { type: 'u32' }], + ['totalXp', { type: 'u64' }], + ['kills', { type: 'u32' }], + ['level', { type: 'u32' }], + ['waitedMs', { type: 'u32' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['error', { type: 'optional', item: { type: 'short_str' } }], + ['attempts', { type: 'u32' }], +]; + +/** Event `board` (id 5). */ +export type BoardEvent = BoardSnapshot; + +const BOARD_PAYLOAD: WireType = BOARD_SNAPSHOT_TYPE; + +/** Event `died` (id 6). */ +export interface DiedEvent { + readonly respawnMs: number; +} + +const DIED_LAYOUT: PayloadLayout = [ + ['respawnMs', { type: 'u32' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + profile: 2, + kill: 3, + saved: 4, + board: 5, + died: 6, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + profile: ProfileEvent; + kill: KillEvent; + saved: SavedEvent; + board: BoardEvent; + died: DiedEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + profile: { + id: 2, + name: 'profile', + encode: (value) => encodeValue(PROFILE_PAYLOAD, value), + decode: (payload) => decodeValue(PROFILE_PAYLOAD, payload) as ProfileEvent + }, + kill: { + id: 3, + name: 'kill', + encode: (value) => encodePayload(KILL_LAYOUT, value), + decode: (payload) => decodePayload(KILL_LAYOUT, payload) as unknown as KillEvent + }, + saved: { + id: 4, + name: 'saved', + encode: (value) => encodePayload(SAVED_LAYOUT, value), + decode: (payload) => decodePayload(SAVED_LAYOUT, payload) as unknown as SavedEvent + }, + board: { + id: 5, + name: 'board', + encode: (value) => encodeValue(BOARD_PAYLOAD, value), + decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent + }, + died: { + id: 6, + name: 'died', + encode: (value) => encodePayload(DIED_LAYOUT, value), + decode: (payload) => decodePayload(DIED_LAYOUT, payload) as unknown as DiedEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/mobpit/index.ts b/examples/game/client/src/generated/mobpit/index.ts new file mode 100644 index 000000000..c9b2dc6ff --- /dev/null +++ b/examples/game/client/src/generated/mobpit/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/mobpit/input.ts b/examples/game/client/src/generated/mobpit/input.ts new file mode 100644 index 000000000..d5ff8e8b1 --- /dev/null +++ b/examples/game/client/src/generated/mobpit/input.ts @@ -0,0 +1,47 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `PitInput` input frame (`#[derive(GameInput)]`). */ +export interface PitInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; +} + +export type Input = PitInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + dash: 1, + attack: 2, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 3 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: PitInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): PitInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as PitInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: PitInput): PitInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/mobpit/schema.ts b/examples/game/client/src/generated/mobpit/schema.ts new file mode 100644 index 000000000..e22f7ecf4 --- /dev/null +++ b/examples/game/client/src/generated/mobpit/schema.ts @@ -0,0 +1,224 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + mob: 2, + pillar: 3, + pit: 4, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vx: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vy: number; + /** `u8` */ + readonly dash: number; + /** `u8` */ + readonly cd: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u8` */ + readonly hp: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `u8` */ + readonly swing: number; + /** `u16` */ + readonly level: number; + /** `bool` */ + readonly dead: boolean; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + vy: fieldNumber(f, 'vy'), + dash: fieldNumber(f, 'dash'), + cd: fieldNumber(f, 'cd'), + name: fieldString(f, 'name'), + hp: fieldNumber(f, 'hp'), + face: fieldNumber(f, 'face'), + swing: fieldNumber(f, 'swing'), + level: fieldNumber(f, 'level'), + dead: fieldBool(f, 'dead'), + }; +} + +/** `mob` (kind 2, priority 1). */ +export interface MobFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `u8` */ + readonly tier: number; + /** `u8` */ + readonly hp: number; + /** `u8` */ + readonly state: number; + /** `u8` */ + readonly tele: number; +} + +/** True for a `mob` entity. */ +export function isMob(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `mob` entity (rendered or replica). */ +export function mobFields(entity: { readonly fields: EntityFields }): MobFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + face: fieldNumber(f, 'face'), + tier: fieldNumber(f, 'tier'), + hp: fieldNumber(f, 'hp'), + state: fieldNumber(f, 'state'), + tele: fieldNumber(f, 'tele'), + }; +} + +/** `pillar` (kind 3, priority 1). */ +export interface PillarFields { + /** `f32` */ + readonly x: number; + /** `f32` */ + readonly y: number; + /** `f32` */ + readonly r: number; +} + +/** True for a `pillar` entity. */ +export function isPillar(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `pillar` entity (rendered or replica). */ +export function pillarFields(entity: { readonly fields: EntityFields }): PillarFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + r: fieldNumber(f, 'r'), + }; +} + +/** `pit` (kind 4, priority 1). */ +export interface PitFields { + /** `u16` */ + readonly pending: number; + /** `u16` */ + readonly slowMs: number; + /** `f32` */ + readonly tickMs: number; + /** `f32` */ + readonly tickMaxMs: number; + /** `u32` */ + readonly workUs: number; + /** `u32` */ + readonly committed: number; + /** `u16` */ + readonly backlog: number; +} + +/** True for a `pit` entity. */ +export function isPit(entity: { readonly kind: number }): boolean { + return entity.kind === 4; +} + +/** Typed fields of a `pit` entity (rendered or replica). */ +export function pitFields(entity: { readonly fields: EntityFields }): PitFields { + const f = entity.fields; + return { + pending: fieldNumber(f, 'pending'), + slowMs: fieldNumber(f, 'slow_ms'), + tickMs: fieldNumber(f, 'tick_ms'), + tickMaxMs: fieldNumber(f, 'tick_max_ms'), + workUs: fieldNumber(f, 'work_us'), + committed: fieldNumber(f, 'committed'), + backlog: fieldNumber(f, 'backlog'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + dash: { type: 'u8' }, + cd: { type: 'u8' }, + name: { type: 'short_str' }, + hp: { type: 'u8' }, + face: { type: 'angle', bits: 8 }, + swing: { type: 'u8' }, + level: { type: 'u16' }, + dead: { type: 'bool' }, + }, + mob: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + face: { type: 'angle', bits: 8 }, + tier: { type: 'u8' }, + hp: { type: 'u8' }, + state: { type: 'u8' }, + tele: { type: 'u8' }, + }, + pillar: { + x: { type: 'f32' }, + y: { type: 'f32' }, + r: { type: 'f32' }, + }, + pit: { + pending: { type: 'u16' }, + slow_ms: { type: 'u16' }, + tick_ms: { type: 'f32' }, + tick_max_ms: { type: 'f32' }, + work_us: { type: 'u32' }, + committed: { type: 'u32' }, + backlog: { type: 'u16' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + vy: { mode: 'snap' }, + dash: { mode: 'snap' }, + cd: { mode: 'snap' }, + name: { mode: 'replace' }, + hp: { mode: 'replace' }, + face: { mode: 'replace' }, + swing: { mode: 'replace' }, + level: { mode: 'replace' }, + dead: { mode: 'replace' }, + }, +}; diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json new file mode 100644 index 000000000..86938ff72 --- /dev/null +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -0,0 +1,827 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "half", + "type": { + "type": "f32" + } + }, + { + "name": "boot", + "type": { + "type": "short_str" + } + }, + { + "name": "attack_range", + "type": { + "type": "f32" + } + }, + { + "name": "attack_arc_cos", + "type": { + "type": "f32" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "profile", + "payload": { + "kind": "value", + "type": { + "name": "Profile", + "type": "record" + } + } + }, + { + "id": 3, + "name": "kill", + "payload": { + "fields": [ + { + "name": "key", + "type": { + "type": "short_str" + } + }, + { + "name": "mob", + "type": { + "type": "u32" + } + }, + { + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "killer", + "type": { + "type": "u32" + } + }, + { + "name": "killer_name", + "type": { + "type": "short_str" + } + } + ], + "kind": "fields" + } + }, + { + "id": 4, + "name": "saved", + "payload": { + "fields": [ + { + "name": "key", + "type": { + "type": "short_str" + } + }, + { + "name": "ok", + "type": { + "type": "bool" + } + }, + { + "name": "replayed", + "type": { + "type": "bool" + } + }, + { + "name": "xp", + "type": { + "type": "u32" + } + }, + { + "name": "total_xp", + "type": { + "type": "u64" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "waited_ms", + "type": { + "type": "u32" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "error", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "attempts", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + }, + { + "id": 5, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "BoardSnapshot", + "type": "record" + } + } + }, + { + "id": 6, + "name": "died", + "payload": { + "fields": [ + { + "name": "respawn_ms", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + } + ], + "name": "PitInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vy", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "dash", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "cd", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "swing", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": null, + "name": "tier", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "state", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "tele", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 2, + "name": "mob", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "r", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 3, + "name": "pillar", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "pending", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "tick_max_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "work_us", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "committed", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "backlog", + "priority": 1.0, + "type": { + "type": "u16" + } + } + ], + "id": 4, + "name": "pit", + "priority": 1.0 + } + ], + "name": "mobpit", + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "enqueued", + "type": { + "type": "u64" + } + }, + { + "name": "applied", + "type": { + "type": "u64" + } + }, + { + "name": "dropped", + "type": { + "type": "u64" + } + }, + { + "name": "failed", + "type": { + "type": "u64" + } + } + ], + "name": "BackgroundStats" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u32" + } + }, + { + "name": "member", + "type": { + "type": "short_str" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "f64" + } + } + ], + "name": "BoardRow" + }, + { + "fields": [ + { + "name": "version", + "type": { + "type": "u64" + } + }, + { + "name": "backend", + "type": { + "type": "short_str" + } + }, + { + "name": "members", + "type": { + "type": "u64" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "BoardRow", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "xp", + "type": { + "item": { + "name": "BoardRow", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "background", + "type": { + "name": "BackgroundStats", + "type": "record" + } + }, + { + "name": "last_rebuild", + "type": { + "item": { + "name": "RebuildReport", + "type": "record" + }, + "type": "optional" + } + } + ], + "name": "BoardSnapshot" + }, + { + "fields": [ + { + "name": "member", + "type": { + "type": "short_str" + } + }, + { + "name": "cell", + "type": { + "name": "Scores", + "type": "record" + } + }, + { + "name": "board", + "type": { + "name": "Scores", + "type": "record" + } + } + ], + "name": "Mismatch" + }, + { + "fields": [ + { + "name": "xp", + "type": { + "type": "u64" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + }, + { + "name": "level_xp", + "type": { + "type": "u64" + } + }, + { + "name": "next_level_xp", + "type": { + "type": "u64" + } + }, + { + "name": "source", + "type": { + "type": "short_str" + } + } + ], + "name": "Profile" + }, + { + "fields": [ + { + "name": "backend", + "type": { + "type": "short_str" + } + }, + { + "name": "crawlers", + "type": { + "type": "u32" + } + }, + { + "name": "events", + "type": { + "type": "u32" + } + }, + { + "name": "applied", + "type": { + "type": "u32" + } + }, + { + "name": "duplicates", + "type": { + "type": "u32" + } + }, + { + "name": "identical_top", + "type": { + "type": "bool" + } + }, + { + "name": "matches_cells", + "type": { + "type": "bool" + } + }, + { + "name": "mismatches", + "type": { + "item": { + "name": "Mismatch", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "took_ms", + "type": { + "type": "f64" + } + } + ], + "name": "RebuildReport" + }, + { + "fields": [ + { + "name": "kills", + "type": { + "type": "f64" + } + }, + { + "name": "xp", + "type": { + "type": "f64" + } + } + ], + "name": "Scores" + } + ], + "schemaVersion": 1 +} diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts index f81e66e64..935207c24 100644 --- a/examples/game/client/src/leaderboard/main.ts +++ b/examples/game/client/src/leaderboard/main.ts @@ -4,17 +4,18 @@ * triggers a rebuild from the cells' event history. */ import { HALF } from '../arena/movement.ts'; -import { DevApi } from '../shared/dev-api.ts'; import { - createBoardWatcher, - DEFAULT_ZONE, - KIND, - MobPitApi, - TIERS, - type BoardPosition, + isMob, + isPillar, + isPlayer, + mobFields, + pillarFields, + playerFields, type BoardRow, type BoardSnapshot -} from '../mobpit/client.ts'; +} from '../generated/mobpit/index.ts'; +import { createBoardWatcher, DEFAULT_ZONE, MobPitApi, TIERS, type BoardPosition } from '../mobpit/client.ts'; +import { DevApi } from '../shared/dev-api.ts'; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; @@ -70,8 +71,8 @@ async function render(board: BoardSnapshot): Promise { table($('xp'), board.xp, 'XP', me); const bg = board.background; status.textContent = - `push #${pushes} · version ${board.version} · store ${board.backend ?? '?'} · ${board.members ?? 0} ranked` + - (bg === undefined ? '' : ` · background updates: ${bg.applied} applied, ${bg.dropped} dropped, ${bg.failed} failed`); + `push #${pushes} · version ${board.version} · store ${board.backend} · ${board.members} ranked` + + ` · background updates: ${bg.applied} applied, ${bg.dropped} dropped, ${bg.failed} failed`; status.classList.add('flash'); setTimeout(() => status.classList.remove('flash'), 120); if (me === undefined) return; @@ -114,18 +115,19 @@ function drawMap(): void { const px = (v: number) => (v + HALF) * s; ctx.clearRect(0, 0, map.width, map.height); for (const e of client.render()) { - const x = Number(e.fields.x ?? 0); - const y = Number(e.fields.y ?? 0); - if (e.kindName === KIND.pillar) { + if (isPillar(e)) { + const { x, y, r } = pillarFields(e); ctx.fillStyle = '#5d5566'; ctx.beginPath(); - ctx.arc(px(x), map.height - px(y), Number(e.fields.r ?? 1) * s, 0, Math.PI * 2); + ctx.arc(px(x), map.height - px(y), r * s, 0, Math.PI * 2); ctx.fill(); - } else if (e.kindName === KIND.mob) { - ctx.fillStyle = TIERS[Number(e.fields.tier ?? 1)]?.color ?? '#9ad16b'; + } else if (isMob(e)) { + const { x, y, tier } = mobFields(e); + ctx.fillStyle = TIERS[tier]?.color ?? '#9ad16b'; ctx.fillRect(px(x) - 3, map.height - px(y) - 3, 6, 6); - } else if (e.kindName === KIND.player) { - ctx.fillStyle = e.fields.dead ? '#555' : '#f2a65a'; + } else if (isPlayer(e)) { + const { x, y, dead } = playerFields(e); + ctx.fillStyle = dead ? '#555' : '#f2a65a'; ctx.beginPath(); ctx.arc(px(x), map.height - px(y), 4, 0, Math.PI * 2); ctx.fill(); diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts index f72b3ecbf..3f401ccdb 100644 --- a/examples/game/client/src/mobpit/client.ts +++ b/examples/game/client/src/mobpit/client.ts @@ -1,7 +1,8 @@ /** - * Mob Pit networking without rendering (Node-testable): the `GameClient` - * with the Arena's predicted movement for the own capsule, the zone's JSON - * events folded into a small state object, and the `/dev/mobpit/*` routes. + * Mob Pit networking without rendering (Node-testable): the generated + * `createMobpitClient` with the Arena's predicted movement for the own + * capsule, the zone's typed events folded into a small state object, and + * the `/dev/mobpit/*` routes. * * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the * fact is only *queued*) → `saved` (to the killer, when the durable cell @@ -9,17 +10,12 @@ */ import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; -import { encodeMoveInput, predictPlayer, type MoveInput } from '../arena/movement.ts'; +import { predictPlayer } from '../arena/movement.ts'; +import * as pit from '../generated/mobpit/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; +import { latest } from '../shared/latest.ts'; export const DEFAULT_ZONE = 'pit-1'; -/** Event type ids (server `mobpit::zone::EVENT_*`). */ -export const EVENT = { hello: 1, profile: 2, kill: 3, saved: 4, board: 5, died: 6 } as const; -/** Input bits: the Arena's dash (1) plus attack. */ -export const BUTTON_DASH = 1; -export const BUTTON_ATTACK = 2; -export const KIND = { player: 'player', mob: 'mob', pillar: 'pillar', pit: 'pit' } as const; export const MOB_STATE = ['idle', 'chase', 'windup', 'recover', 'return'] as const; /** Per tier: display name, body radius, telegraph radius (server `tier_stats`). */ export const TIERS: Readonly> = { @@ -28,72 +24,19 @@ export const TIERS: Readonly; -export type Profile = Readonly<{ - xp: number; - level: number; - kills: number; - levelXp: number; - nextLevelXp: number; - source: 'cell' | 'settled'; -}>; -export type KillEvent = Readonly<{ key: string; mob: number; tier: number; x: number; y: number; killer: number; killerName: string }>; -export type SavedEvent = Readonly<{ - key: string; - ok: boolean; - replayed?: boolean; - xp?: number; - totalXp?: number; - kills?: number; - level?: number; - waitedMs: number; - x: number; - y: number; - error?: string; -}>; -export type BoardRow = Readonly<{ rank: number; member: string; name: string; score: number }>; -export type BoardSnapshot = Readonly<{ - version: number; - backend?: 'memory' | 'redis'; - members?: number; - kills: BoardRow[]; - xp: BoardRow[]; - background?: Readonly<{ enqueued: number; applied: number; dropped: number; failed: number }>; - lastRebuild?: RebuildReport | null; -}>; -export type RebuildReport = Readonly<{ - backend: string; - crawlers: number; - events: number; - applied: number; - duplicates: number; - identicalTop: boolean; - matchesCells: boolean; - mismatches: unknown[]; - tookMs: number; -}>; -export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: BoardRow[] }>; +/** `/dev/mobpit/leaderboard` neighbourhood (HTTP only, not a zone event). */ +export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: pit.BoardRow[] }>; -export type MobPitEvents = { - hello: PitHello; - profile: Profile; - kill: KillEvent; - saved: SavedEvent; - board: BoardSnapshot; - died: { respawnMs: number }; -}; - -export type MobPitClient = Readonly<{ - client: GameClient; - hello(): PitHello | undefined; - profile(): Profile | undefined; - board(): BoardSnapshot | undefined; - /** Kills by me whose fact has not settled yet (key → event). */ - unsaved: ReadonlyMap; - /** Resolves on the first hello. */ - ready: Promise; - on(type: K, handler: (value: MobPitEvents[K]) => void): () => void; -}>; +export type MobPitClient = pit.MobpitClient & + Readonly<{ + hello(): pit.HelloEvent | undefined; + profile(): pit.Profile | undefined; + board(): pit.BoardSnapshot | undefined; + /** Kills by me whose fact has not settled yet (key → event). */ + unsaved: ReadonlyMap; + /** Resolves on the first hello. */ + ready: Promise; + }>; export type MobPitClientOptions = Readonly<{ api: DevApi; @@ -102,114 +45,50 @@ export type MobPitClientOptions = Readonly<{ }>; export function createMobPitClient(options: MobPitClientOptions): MobPitClient { - const ease = { mode: 'ease', durationMs: 150 } as const; - const snap = { mode: 'snap' } as const; - const replace = { mode: 'replace' } as const; - const client = new GameClient({ + const typed = pit.createMobpitClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 500, inputDtMs: 1000 / 30, - prediction: { - encodeInput: (input) => encodeMoveInput(input), - predict: (fields, input) => predictPlayer(fields, input), - corrections: { - [KIND.player]: { - x: ease, - y: ease, - vx: snap, - vy: snap, - dash: snap, - cd: snap, - name: replace, - hp: replace, - face: replace, - swing: replace, - level: replace, - dead: replace - } - } - } + // The movement part of the frame is the Arena's (attack only adds a bit). + prediction: { predict: (fields, input) => predictPlayer(fields, input) } }); - const listeners = new Map void>>(); - const emit = (type: string, value: unknown) => { - for (const handler of listeners.get(type) ?? []) handler(value); - }; - let hello: PitHello | undefined; - let profile: Profile | undefined; - let board: BoardSnapshot | undefined; - const unsaved = new Map(); - let resolveReady: (h: PitHello) => void = () => undefined; - const ready = new Promise((resolve) => (resolveReady = resolve)); - - onJsonEvent(client, EVENT.hello, (value) => { - hello = value; - client.setControlledEntity(value.entity); - resolveReady(value); - emit('hello', value); + const hello = latest( + (h) => typed.on('hello', h), + (value) => typed.client.setControlledEntity(value.entity) + ); + const profile = latest((h) => typed.on('profile', h)); + const board = latest((h) => typed.on('board', h)); + const unsaved = new Map(); + typed.on('kill', (kill) => { + if (kill.killer === hello.get()?.entity) unsaved.set(kill.key, kill); }); - onJsonEvent(client, EVENT.profile, (value) => { - profile = value; - emit('profile', value); - }); - onJsonEvent(client, EVENT.kill, (value) => { - if (hello !== undefined && value.killer === hello.entity) unsaved.set(value.key, value); - emit('kill', value); - }); - onJsonEvent(client, EVENT.saved, (value) => { - unsaved.delete(value.key); - emit('saved', value); - }); - onJsonEvent(client, EVENT.board, (value) => { - board = value; - emit('board', value); - }); - onJsonEvent<{ respawnMs: number }>(client, EVENT.died, (value) => emit('died', value)); - + typed.on('saved', (saved) => unsaved.delete(saved.key)); return { - client, - hello: () => hello, - profile: () => profile, - board: () => board, + ...typed, + hello: hello.get, + profile: profile.get, + board: board.get, unsaved, - ready, - on(type, handler) { - let set = listeners.get(type); - if (set === undefined) listeners.set(type, (set = new Set())); - const h = handler as (value: unknown) => void; - set.add(h); - return () => set.delete(h); - } + ready: hello.ready }; } /** Observer-only client for the leaderboard page (no prediction, no inputs). */ export function createBoardWatcher(options: MobPitClientOptions): Readonly<{ - client: GameClient; - board(): BoardSnapshot | undefined; - on(handler: (value: BoardSnapshot) => void): () => void; + client: GameClient; + board(): pit.BoardSnapshot | undefined; + on(handler: (value: pit.BoardSnapshot) => void): () => void; }> { - const client = new GameClient({ + const typed = pit.createMobpitClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 1000 }); - let board: BoardSnapshot | undefined; - const handlers = new Set<(value: BoardSnapshot) => void>(); - onJsonEvent(client, EVENT.board, (value) => { - board = value; - for (const h of handlers) h(value); - }); - return { - client, - board: () => board, - on(handler) { - handlers.add(handler); - return () => handlers.delete(handler); - } - }; + const board = latest((h) => typed.on('board', h)); + return { client: typed.client, board: board.get, on: (handler) => typed.on('board', handler) }; } /** `/dev/mobpit/*` (dev only; none of these take an identity or a reward). */ @@ -237,12 +116,12 @@ export class MobPitApi { return this.#json('/dev/mobpit/crawlers'); } - leaderboard(member?: string): Promise<{ snapshot: BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { + leaderboard(member?: string): Promise<{ snapshot: pit.BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { const query = member === undefined ? '' : `?member=${encodeURIComponent(member)}`; return this.#json(`/dev/mobpit/leaderboard${query}`); } - rebuild(): Promise { + rebuild(): Promise { return this.#json('/dev/mobpit/leaderboard/rebuild', {}); } diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index b2b808631..b23d8ecba 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -14,22 +14,25 @@ import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; +import { HALF, PLAYER_RADIUS } from '../arena/movement.ts'; +import { + BUTTON, + isMob, + isPillar, + isPit, + mobFields, + pillarFields, + pitFields, + playerFields, + type BoardSnapshot, + type PitFields, + type PitInput +} from '../generated/mobpit/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; -import { - BUTTON_ATTACK, - BUTTON_DASH, - createMobPitClient, - DEFAULT_ZONE, - KIND, - MobPitApi, - TIERS, - type BoardSnapshot, - type KillEvent -} from './client.ts'; +import { createMobPitClient, DEFAULT_ZONE, MobPitApi, TIERS } from './client.ts'; const SLOW_MS = 1500; const params = new URLSearchParams(location.search); @@ -138,7 +141,7 @@ function createPlayer(entity: RenderedEntity, mine: boolean): PlayerVisual { } function createMob(entity: RenderedEntity): MobVisual { - const tier = num(entity, 'tier') || 1; + const tier = mobFields(entity).tier || 1; const t = TIERS[tier] ?? TIERS[1]!; const body = tier === 3 @@ -159,19 +162,15 @@ function createMob(entity: RenderedEntity): MobVisual { function visualFor(entity: RenderedEntity, mine: boolean): Visual { let visual = visuals.get(entity.key); if (visual !== undefined) return visual; - switch (entity.kindName) { - case KIND.mob: - visual = createMob(entity); - break; - case KIND.pillar: { - const r = num(entity, 'r'); - const body = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2.4, tessellation: 24 }, scene); - body.material = mats.pillar; - visual = { kind: 'pillar', body }; - break; - } - default: - visual = createPlayer(entity, mine); + if (isMob(entity)) { + visual = createMob(entity); + } else if (isPillar(entity)) { + const { r } = pillarFields(entity); + const body = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2.4, tessellation: 24 }, scene); + body.material = mats.pillar; + visual = { kind: 'pillar', body }; + } else { + visual = createPlayer(entity, mine); } visuals.set(entity.key, visual); return visual; @@ -181,11 +180,6 @@ function dispose(visual: Visual): void { for (const mesh of Object.values(visual)) if (mesh instanceof Mesh) mesh.dispose(); } -function num(entity: RenderedEntity | { fields: RenderedEntity['fields'] }, f: string): number { - const v = entity.fields[f]; - return typeof v === 'number' ? v : typeof v === 'boolean' ? Number(v) : 0; -} - // ---- kill / saved popups (DOM labels anchored to invisible meshes) ---- type Popup = { mesh: Mesh; until: number }; const popups = new Map(); @@ -204,7 +198,7 @@ function popup(key: string, x: number, y: number, text: string, className: strin stage.labels.set(`popup:${key}`, p.mesh, text, 0.6, `pit-pop ${className}`); } -pit.on('kill', (kill: KillEvent) => { +pit.on('kill', (kill) => { const mine = kill.killer === pit.hello()?.entity; const tier = TIERS[kill.tier]?.name ?? 'Mob'; if (mine) popup(kill.key, kill.x, kill.y, `${tier} slain · saving…`, 'pending', 60_000); @@ -283,10 +277,10 @@ const commandFrames = new InputPacer({ tickRate: () => client.authority?.connect function sendCommandFrame(): void { const s = sampler.sample(); const move = cameraRelative(s, stage.cameraForward()); - const input: MoveInput = { + const input: PitInput = { mx: toAxis(move.x), my: toAxis(move.y), - buttons: (s.action ? BUTTON_ATTACK : 0) | (s.alt ? BUTTON_DASH : 0) + buttons: (s.action ? BUTTON.attack : 0) | (s.alt ? BUTTON.dash : 0) }; client.sendInput(input); } @@ -299,31 +293,32 @@ stage.onFrame((now, dtMs) => { const rendered = client.render(); const seen = new Set(); let me: { x: number; y: number; hp: number; dead: boolean } | undefined; - let stats: RenderedEntity | undefined; + let stats: PitFields | undefined; for (const entity of rendered) { - if (entity.kindName === KIND.pit) { - stats = entity; + if (isPit(entity)) { + stats = pitFields(entity); continue; } const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; const visual = visualFor(entity, mine); - const x = num(entity, 'x'); - const y = num(entity, 'y'); seen.add(entity.key); const visible = !entity.stale || visual.kind === 'pillar'; if (visual.kind === 'pillar') { + const { x, y } = pillarFields(entity); visual.body.position.copyFrom(toWorld(x, y, 1.2)); } else if (visual.kind === 'mob') { + const mob = mobFields(entity); + const { x, y } = mob; const height = visual.tier === 3 ? 1 : visual.tier === 2 ? 0.75 : 0.45; visual.body.position.copyFrom(toWorld(x, y, height)); - visual.body.rotation.y = -num(entity, 'face'); - const hp = num(entity, 'hp') / 100; + visual.body.rotation.y = -mob.face; + const hp = mob.hp / 100; const top = height * 2 + 0.35; visual.hpBack.position.copyFrom(toWorld(x, y, top)); visual.hpFill.position.copyFrom(toWorld(x, y, top)); visual.hpFill.scaling.x = Math.max(0.001, hp); - const tele = num(entity, 'tele') / 255; - const winding = num(entity, 'state') === 2; + const tele = mob.tele / 255; + const winding = mob.state === 2; visual.ring.setEnabled(visible && winding); visual.fill.setEnabled(visible && winding); if (winding) { @@ -334,9 +329,8 @@ stage.onFrame((now, dtMs) => { visual.body.scaling.setAll(winding ? 1 + 0.15 * tele : 1); for (const m of [visual.body, visual.hpBack, visual.hpFill]) m.setEnabled(visible); } else { - const dead = num(entity, 'dead') > 0; - const face = num(entity, 'face'); - const swing = num(entity, 'swing'); + const player = playerFields(entity); + const { x, y, dead, face, swing } = player; visual.body.position.copyFrom(toWorld(x, y, 0.9)); visual.body.material = dead ? mats.dead : mine ? mats.me : mats.other; visual.nose.position.copyFrom(toWorld(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3)); @@ -353,11 +347,11 @@ stage.onFrame((now, dtMs) => { // Disc arcs start at +x and run counter-clockwise; centre it on `face`. visual.arc.rotation.y = -(face - Math.PI / 3); } - const label = `${String(entity.fields.name ?? '')} · L${num(entity, 'level')} · ${num(entity, 'hp')} HP`; + const label = `${player.name} · L${player.level} · ${player.hp} HP`; stage.labels.set(entity.key, visual.body, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); visual.body.setEnabled(visible); visual.nose.setEnabled(visible && !dead); - if (mine) me = { x, y, hp: num(entity, 'hp'), dead }; + if (mine) me = { x, y, hp: player.hp, dead }; } } for (const [key, visual] of visuals) { @@ -376,18 +370,18 @@ stage.onFrame((now, dtMs) => { // ---- HUD ---- hud.frame({ entities: rendered.length }); - const pending = stats === undefined ? 0 : num(stats, 'pending'); - const tickMs = stats === undefined ? 0 : num(stats, 'tickMs'); - const tickMax = stats === undefined ? 0 : num(stats, 'tickMaxMs'); - const slowMs = stats === undefined ? 0 : num(stats, 'slowMs'); + const pending = stats?.pending ?? 0; + const tickMs = stats?.tickMs ?? 0; + const tickMax = stats?.tickMaxMs ?? 0; + const slowMs = stats?.slowMs ?? 0; hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); hud.row('HP', me === undefined ? '—' : me.dead ? 'dead' : String(me.hp)); hud.row('Facts pending (zone)', String(pending)); - hud.row('Facts saved (zone)', String(stats === undefined ? 0 : num(stats, 'committed'))); + hud.row('Facts saved (zone)', String(stats?.committed ?? 0)); hud.row('My unsaved kills', String(pit.unsaved.size)); hud.row('Storage latency', slowMs > 0 ? `${slowMs} ms (slow)` : 'normal'); hud.row('Server tick interval', `${tickMs.toFixed(1)} ms avg · ${tickMax.toFixed(1)} max`); - hud.row('Tick work', `${stats === undefined ? 0 : num(stats, 'workUs')} µs`); + hud.row('Tick work', `${stats?.workUs ?? 0} µs`); const profile = pit.profile(); if (profile !== undefined) { const span = Math.max(1, profile.nextLevelXp - profile.levelXp); diff --git a/examples/game/client/tests/helpers/mobpit.mjs b/examples/game/client/tests/helpers/mobpit.mjs index 919ef00ca..c930d07d8 100644 --- a/examples/game/client/tests/helpers/mobpit.mjs +++ b/examples/game/client/tests/helpers/mobpit.mjs @@ -6,7 +6,7 @@ import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { BUTTON_ATTACK } from '../../src/mobpit/client.ts'; +import { BUTTON, isMob, isPlayer, mobFields, playerFields } from '../../src/generated/mobpit/index.ts'; import { sleep } from './demo-server.mjs'; export function tempDataDir() { @@ -20,18 +20,19 @@ export async function hunt(pit, done, timeoutMs = 45_000) { while (!done()) { if (Date.now() > deadline) throw new Error('hunt timed out'); const rendered = client.render(); - const me = rendered.find((e) => e.id === pit.hello()?.entity && e.kindName === 'player'); - const mobs = rendered.filter((e) => e.kindName === 'mob' && !e.stale); + const meEntity = rendered.find((e) => e.id === pit.hello()?.entity && isPlayer(e)); + const me = meEntity && playerFields(meEntity); + const mobs = rendered.filter((e) => isMob(e) && !e.stale).map(mobFields); let input = { mx: 0, my: 0, buttons: 0 }; - if (me !== undefined && mobs.length > 0 && !me.fields.dead) { + if (me !== undefined && mobs.length > 0 && !me.dead) { const target = mobs - .map((m) => ({ m, d: Math.hypot(m.fields.x - me.fields.x, m.fields.y - me.fields.y) })) + .map((m) => ({ m, d: Math.hypot(m.x - me.x, m.y - me.y) })) .sort((a, b) => a.d - b.d)[0]; - const dx = target.m.fields.x - me.fields.x; - const dy = target.m.fields.y - me.fields.y; + const dx = target.m.x - me.x; + const dy = target.m.y - me.y; const near = target.d < 1.9; const k = (near ? 40 : 127) / Math.max(target.d, 1e-3); - input = { mx: Math.round(dx * k), my: Math.round(dy * k), buttons: near ? BUTTON_ATTACK : 0 }; + input = { mx: Math.round(dx * k), my: Math.round(dy * k), buttons: near ? BUTTON.attack : 0 }; } client.sendInput(input); await sleep(1000 / 30); diff --git a/examples/game/client/tests/leaderboard-headless.test.mjs b/examples/game/client/tests/leaderboard-headless.test.mjs index e1588f13d..d6510a5d5 100644 --- a/examples/game/client/tests/leaderboard-headless.test.mjs +++ b/examples/game/client/tests/leaderboard-headless.test.mjs @@ -48,13 +48,13 @@ test('board pushes match the cells and rebuild is identical', { timeout: 600_000 assert.equal(mine.kills.rank, 1); assert.equal(mine.kills.around[0].member, me); - const top = JSON.stringify([watcher.board().kills, watcher.board().xp]); + const top = [watcher.board().kills, watcher.board().xp]; const report = await pitApi.rebuild(); assert.equal(report.events, profile.kills); assert.equal(report.matchesCells, true); assert.equal(report.identicalTop, true); const after = (await pitApi.leaderboard()).snapshot; - assert.equal(JSON.stringify([after.kills, after.xp]), top, 'rebuild from events = live board'); + assert.deepEqual([after.kills, after.xp], top, 'rebuild from events = live board'); await until(() => watcher.board().lastRebuild?.events === profile.kills, 5_000, 'rebuild pushed'); } finally { for (const c of clients) c.close(); diff --git a/examples/game/client/tests/mobpit-headless.test.mjs b/examples/game/client/tests/mobpit-headless.test.mjs index 2ea553dfe..3257296bd 100644 --- a/examples/game/client/tests/mobpit-headless.test.mjs +++ b/examples/game/client/tests/mobpit-headless.test.mjs @@ -7,6 +7,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { isPit, pitFields } from '../src/generated/mobpit/index.ts'; import { createMobPitClient, MobPitApi } from '../src/mobpit/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { memoryStorage, startDemo, until } from './helpers/demo-server.mjs'; @@ -40,14 +41,21 @@ test('kills become durable facts without stalling the tick, and survive a restar await hunt(pit, () => saved.length >= 1); assert.ok(saved[0].ok && XP.has(saved[0].xp), JSON.stringify(saved[0])); assert.equal(saved[0].key, kills[0].key); - assert.match(saved[0].key, /^kill:pit-1:\d+:m\d+:\d+$/, "kill:{zone}:{boot_epoch}:m{mob}:{generation}"); + assert.match( + saved[0].key, + /^crawler\.record_kill:pit-1:\d+:m\d+:\d+$/, + '{command}:{zone}:{boot_epoch}:m{mob}:{generation}' + ); // One swing can kill several mobs: wait until every own kill settled. await until(() => pit.unsaved.size === 0 && saved.length === kills.length, 5_000, 'settlements'); await until(() => pit.profile().source === 'settled' && pit.profile().kills === kills.length, 5_000, `profile after settlement ${JSON.stringify(pit.profile())}`); // Slow storage: the next kill stays unsaved for ~1.5 s, the tick does not slow down. assert.equal((await pitApi.setStorage(1500)).latencyMs, 1500); - const pitStats = () => pit.client.render().find((e) => e.kindName === 'pit')?.fields; + const pitStats = () => { + const entity = pit.client.render().find(isPit); + return entity && pitFields(entity); + }; const fastKills = kills.length; await hunt(pit, () => kills.length > fastKills); await until(() => (pitStats()?.pending ?? 0) >= 1, 2_000, 'pending fact replicated'); diff --git a/examples/game/server/src/mobpit/board.rs b/examples/game/server/src/mobpit/board.rs index d57442a2b..44083b9c9 100644 --- a/examples/game/server/src/mobpit/board.rs +++ b/examples/game/server/src/mobpit/board.rs @@ -14,6 +14,10 @@ //! - Rebuild ([`Leaderboards::rebuild`]): read every cell's durable event //! history, project it into the *staging* boards and atomically promote //! them. Runs at startup too (the in-memory board starts empty). +//! - Snapshot ([`BoardSnapshot`]): a `#[derive(GameRecord)]` struct, pushed +//! to clients as the zone's typed `board` event and served as camelCase +//! JSON by `/dev/mobpit/leaderboard`; the generated TypeScript type +//! describes both. use std::collections::{BTreeMap, HashMap}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -26,6 +30,7 @@ use distributed::leaderboard::{ LeaderboardProjector, LeaderboardStore, RedisLeaderboard, ScorePolicy, ScoreSubmission, }; use distributed::{DomainEventOccurrence, ExternalEventSource}; +use distributed_game::GameRecord; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -41,6 +46,100 @@ pub const PRODUCER: &str = "mobpit.crawler-cell"; /// Rows pushed to clients. pub const TOP_N: usize = 10; +/// One leaderboard row. +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct BoardRow { + /// 1-based rank. + pub rank: u32, + /// Principal. + pub member: String, + /// Last display name seen with a kill. + pub name: String, + /// Score (kills or XP). + pub score: f64, +} + +/// Live-update counters of the background applier. +#[derive(Debug, Clone, Default, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct BackgroundStats { + /// Occurrences enqueued. + pub enqueued: u64, + /// Applied to the store. + pub applied: u64, + /// Dropped (queue full / store outage). + pub dropped: u64, + /// Failed to apply. + pub failed: u64, +} + +/// Kills and XP of one principal. +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct Scores { + /// Kills. + pub kills: f64, + /// XP. + pub xp: f64, +} + +/// A principal whose board scores disagree with its cell. +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct Mismatch { + /// Principal. + pub member: String, + /// What the cell says. + pub cell: Scores, + /// What the board says. + pub board: Scores, +} + +/// Result of [`Leaderboards::rebuild`]. +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct RebuildReport { + /// `"memory"` or `"redis"`. + pub backend: String, + /// Cells read. + pub crawlers: u32, + /// Kill events replayed. + pub events: u32, + /// Changes applied. + pub applied: u32, + /// Changes already applied (idempotent repeats). + pub duplicates: u32, + /// The top rows were the same before and after. + pub identical_top: bool, + /// Every principal's scores equal its cell. + pub matches_cells: bool, + /// Principals whose scores did not. + pub mismatches: Vec, + /// Duration (ms). + pub took_ms: f64, +} + +/// The top-N boards pushed to clients (`board` event) and served over HTTP. +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +#[serde(rename_all = "camelCase")] +pub struct BoardSnapshot { + /// Bumps whenever anything else changes. + pub version: u64, + /// `"memory"` or `"redis"`. + pub backend: String, + /// Principals on the kills board. + pub members: u64, + /// Top kills. + pub kills: Vec, + /// Top XP. + pub xp: Vec, + /// Background applier counters. + pub background: BackgroundStats, + /// Last rebuild, if any. + pub last_rebuild: Option, +} + /// Leaderboard projection input: one committed kill. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] #[domain_event(name = "mobpit.mob_killed", version = 1)] @@ -128,10 +227,10 @@ pub struct Leaderboards { kills: Board, xp: Board, names: Mutex>, - snapshot: Mutex>, + snapshot: Mutex>, version: AtomicU64, dirty: AtomicBool, - last_rebuild: Mutex>, + last_rebuild: Mutex>, rebuilding: tokio::sync::Mutex<()>, } @@ -164,7 +263,15 @@ impl Leaderboards { kills: Board::high_first(KILLS_BOARD).expect("board name"), xp: Board::high_first(XP_BOARD).expect("board name"), names: Mutex::new(HashMap::new()), - snapshot: Mutex::new(Arc::new(json!({ "version": 0, "kills": [], "xp": [] }))), + snapshot: Mutex::new(Arc::new(BoardSnapshot { + version: 0, + backend: backend.into(), + members: 0, + kills: Vec::new(), + xp: Vec::new(), + background: BackgroundStats::default(), + last_rebuild: None, + })), version: AtomicU64::new(0), dirty: AtomicBool::new(true), last_rebuild: Mutex::new(None), @@ -238,8 +345,8 @@ impl Leaderboards { self.version.load(Ordering::Acquire) } - /// Latest top-N snapshot (JSON pushed as `EVENT_BOARD`). - pub fn snapshot(&self) -> Arc { + /// Latest top-N snapshot (pushed as the zone's `board` event). + pub fn snapshot(&self) -> Arc { self.snapshot.lock().expect("snapshot").clone() } @@ -248,23 +355,19 @@ impl Leaderboards { self.dirty.store(true, Ordering::Release); } - fn rows(&self, entries: Vec) -> Value { - Value::Array( - entries - .into_iter() - .map(|e| { - json!({ - "rank": e.rank + 1, - "member": e.member, - "name": self.name_of(&e.member), - "score": e.score, - }) - }) - .collect(), - ) + fn rows(&self, entries: Vec) -> Vec { + entries + .into_iter() + .map(|e| BoardRow { + rank: u32::try_from(e.rank + 1).unwrap_or(u32::MAX), + name: self.name_of(&e.member), + member: e.member, + score: e.score, + }) + .collect() } - async fn top_rows(&self) -> Result<(Value, Value, u64), LeaderboardError> { + async fn top_rows(&self) -> Result<(Vec, Vec, u64), LeaderboardError> { let kills = self.store.top(&self.kills, TOP_N).await?; let xp = self.store.top(&self.xp, TOP_N).await?; let members = self.store.len(&self.kills).await?; @@ -274,27 +377,28 @@ impl Leaderboards { async fn refresh(&self) -> Result<(), LeaderboardError> { let (kills, xp, members) = self.top_rows().await?; let stats = self.background.stats(); - let mut body = json!({ - "backend": self.backend, - "members": members, - "kills": kills, - "xp": xp, - "background": { - "enqueued": stats.enqueued, - "applied": stats.applied, - "dropped": stats.dropped, - "failed": stats.failed, + let mut body = BoardSnapshot { + version: 0, + backend: self.backend.into(), + members, + kills, + xp, + background: BackgroundStats { + enqueued: stats.enqueued, + applied: stats.applied, + dropped: stats.dropped, + failed: stats.failed, }, - "lastRebuild": *self.last_rebuild.lock().expect("rebuild"), - }); + last_rebuild: self.last_rebuild.lock().expect("rebuild").clone(), + }; let mut snapshot = self.snapshot.lock().expect("snapshot"); - let mut current = (**snapshot).clone(); - if let Some(map) = current.as_object_mut() { - map.remove("version"); - } + let current = BoardSnapshot { + version: 0, + ..(**snapshot).clone() + }; if current != body { let version = self.version.load(Ordering::Acquire) + 1; - body["version"] = json!(version); + body.version = version; *snapshot = Arc::new(body); self.version.store(version, Ordering::Release); } @@ -326,7 +430,7 @@ impl Leaderboards { /// Rebuild both boards from every cell's durable event history and check /// the result against the cells' current state. - pub async fn rebuild(&self, cells: &CrawlerCells) -> Result { + pub async fn rebuild(&self, cells: &CrawlerCells) -> Result { let _one_at_a_time = self.rebuilding.lock().await; let started = Instant::now(); let before = self.top_rows().await.map_err(|e| e.to_string())?; @@ -372,22 +476,28 @@ impl Leaderboards { for (principal, (kills, xp)) in &expected { let (k, x) = self.scores(principal).await.map_err(|e| e.to_string())?; if k != f64::from(*kills) || x != *xp as f64 { - mismatches.push(json!({ - "member": principal, "cell": { "kills": kills, "xp": xp }, "board": { "kills": k, "xp": x } - })); + mismatches.push(Mismatch { + member: principal.clone(), + cell: Scores { + kills: f64::from(*kills), + xp: *xp as f64, + }, + board: Scores { kills: k, xp: x }, + }); } } - let result = json!({ - "backend": self.backend, - "crawlers": principals.len(), - "events": occurrences.len(), - "applied": report.applied, - "duplicates": report.duplicates, - "identicalTop": before.0 == after.0 && before.1 == after.1, - "matchesCells": mismatches.is_empty(), - "mismatches": mismatches, - "tookMs": started.elapsed().as_secs_f64() * 1000.0, - }); + let count = |n: u64| u32::try_from(n).unwrap_or(u32::MAX); + let result = RebuildReport { + backend: self.backend.into(), + crawlers: count(principals.len() as u64), + events: count(occurrences.len() as u64), + applied: count(report.applied), + duplicates: count(report.duplicates), + identical_top: before.0 == after.0 && before.1 == after.1, + matches_cells: mismatches.is_empty(), + mismatches, + took_ms: started.elapsed().as_secs_f64() * 1000.0, + }; *self.last_rebuild.lock().expect("rebuild") = Some(result.clone()); self.mark_dirty(); let _ = self.refresh().await; diff --git a/examples/game/server/src/mobpit/crawler.rs b/examples/game/server/src/mobpit/crawler.rs index dd7bde43b..57910cab8 100644 --- a/examples/game/server/src/mobpit/crawler.rs +++ b/examples/game/server/src/mobpit/crawler.rs @@ -97,7 +97,15 @@ impl Crawler { pub type MobKilledArgs = (String, String, String, u8, u32); /// [`RECORD_KILL`] input. No principal, no XP: both are server-decided. -#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandInput)] +/// +/// `FactCommand` binds it to [`RECORD_KILL`] (the name [`RecordKill`] +/// mounts it under), so the zone emits it typed — `ctx.emit_keyed(killer, +/// RecordKillInput { .. }, &[mob, generation])` — and the derive rejects +/// identity or reward fields at compile time. +#[derive( + Debug, Clone, Serialize, Deserialize, distributed::CommandInput, distributed_game::FactCommand, +)] +#[fact(command = RECORD_KILL)] pub struct RecordKillInput { /// Mob instance (`{zone}/m{id}`). pub mob: String, diff --git a/examples/game/server/src/mobpit/mod.rs b/examples/game/server/src/mobpit/mod.rs index 8aab74d6a..e11876ad9 100644 --- a/examples/game/server/src/mobpit/mod.rs +++ b/examples/game/server/src/mobpit/mod.rs @@ -34,7 +34,7 @@ use distributed_game::net::{GameServer, ServerConfig}; use crate::common::{self, random_hex, Demo, DemoArgs, DemoOptions, Guests, RunningDemo}; pub use world::{MobPitWorld, WorldOptions}; -pub use zone::{encode_bot_input, MobPit}; +pub use zone::{encode_bot_input, game_surface, MobPit}; /// `game-demos mobpit|leaderboard` options. #[derive(Debug, Clone, clap::Args)] @@ -128,7 +128,10 @@ pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { // Board = projection of the cells: rebuild it before accepting players // (the in-memory board starts empty; Redis may have missed updates). match world.rebuild_board().await { - Ok(report) => eprintln!("mobpit: leaderboard rebuilt from cells: {report}"), + Ok(report) => eprintln!( + "mobpit: leaderboard rebuilt from cells: {}", + serde_json::to_string(&report).unwrap_or_default() + ), Err(error) => eprintln!("mobpit: leaderboard rebuild failed (serving anyway): {error}"), } eprintln!( diff --git a/examples/game/server/src/mobpit/routes.rs b/examples/game/server/src/mobpit/routes.rs index 0e4917a0d..416b74c00 100644 --- a/examples/game/server/src/mobpit/routes.rs +++ b/examples/game/server/src/mobpit/routes.rs @@ -100,5 +100,6 @@ async fn leaderboard( } async fn rebuild(State(world): State>) -> ApiResult { - Ok(Json(world.rebuild_board().await.map_err(internal)?)) + let report = world.rebuild_board().await.map_err(internal)?; + Ok(Json(serde_json::to_value(report).map_err(internal)?)) } diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs index 1a10b0ef9..7d5adc831 100644 --- a/examples/game/server/src/mobpit/world.rs +++ b/examples/game/server/src/mobpit/world.rs @@ -144,7 +144,7 @@ impl MobPitWorld { } /// Rebuild the leaderboards from the cells' event history. - pub async fn rebuild_board(&self) -> Result { + pub async fn rebuild_board(&self) -> Result { self.board.rebuild(&self.cells).await } diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index 754e3f990..e448ab6d4 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -18,58 +18,265 @@ //! leash or target dead → `return` home → `idle`. Dead mobs respawn after 4 s //! with a new generation. //! -//! A kill emits a fact **without awaiting storage**: -//! `Fact::new(ctx.fact_key("kill", &[mob, generation]), "crawler.record_kill", -//! {mob, tier, name})` via `ctx.emit_fact_for(killer)` — the host binds the -//! killer's verified principal. The key is `kill:{zone}:{boot_epoch}:m{mob}: -//! {generation}`: the boot epoch grows across restarts, so keys never collide -//! with an earlier run's facts (generations and ticks restart at 0). The -//! settlement arrives in [`Zone::on_fact_settled`] on a later tick and is -//! pushed to the killer as [`EVENT_SAVED`] + [`EVENT_PROFILE`]. +//! Kinds are `#[derive(Replicated)]` views, events the typed [`PitEvent`], +//! input the `#[derive(GameInput)]` [`PitInput`]; the browser client is +//! generated from [`game_surface`]. +//! +//! A kill emits a typed fact **without awaiting storage**: the cell +//! command's own input, [`RecordKillInput`] `{mob, tier, name}`, keyed by +//! `ctx.fact_with_key(&input, &[m{mob}, generation])` and emitted with +//! `ctx.emit_fact_for(killer)` — the host binds the killer's verified +//! principal and the handler decides the XP. The key is +//! `crawler.record_kill:{zone}:{boot_epoch}:m{mob}:{generation}`: the boot +//! epoch grows across restarts, so keys never collide with an earlier run's +//! facts (generations and ticks restart at 0). The settlement arrives in +//! [`Zone::on_fact_settled`] on a later tick and is pushed to the killer as +//! [`PitEvent::Saved`] + [`PitEvent::Profile`]. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::Arc; use std::time::Instant; use distributed_game::{ - ConsumePolicy, Ctx, EmitError, EntitySchema, EntityState, Fact, FactOutcome, FactSettlement, - FieldType, FieldValue, GameInput, KindDef, LeaveReason, ObserverId, PlayerId, View, WorldView, - Zone, + schema, ConsumePolicy, Ctx, EmitError, EntitySchema, Fact, FactOutcome, FactSettlement, + GameEvent, GameInput, GameRecord, GameSurface, LeaveReason, ObserverId, PlayerId, Replicated, + View, WorldView, Zone, }; -use serde_json::{json, Value}; -use super::crawler::{level_floor, KillReceipt, RECORD_KILL}; +use super::board::BoardSnapshot; +use super::crawler::{level_floor, KillReceipt, RecordKillInput}; use super::world::MobPitWorld; use crate::arena::movement::{self, MoveInput, MoveState, PILLARS, PLAYER_RADIUS}; -use crate::common::{broadcast_json_event, send_json_event, Guests}; - -/// Player kind. -pub const KIND_PLAYER: u16 = 1; -/// Mob kind. -pub const KIND_MOB: u16 = 2; -/// Pillar kind. -pub const KIND_PILLAR: u16 = 3; -/// Zone stats kind. -pub const KIND_PIT: u16 = 4; +use crate::arena::PillarView; +use crate::common::Guests; + /// Entity id of the stats entity. pub const PIT_ENTITY: u32 = 900; -/// `{entity, half, boot, attackRange, attackArcCos}` to a joining player. -pub const EVENT_HELLO: u32 = 1; -/// `{xp, level, kills, levelXp, nextLevelXp, source}` — from the cell on -/// join (`source: "cell"`), after each settlement (`"settled"`). -pub const EVENT_PROFILE: u32 = 2; -/// Broadcast `{key, mob, tier, x, y, killer, killerName}` the tick a mob dies. -pub const EVENT_KILL: u32 = 3; -/// To the killer: `{key, ok, replayed, xp, totalXp, kills, level, waitedMs, x, y, error?}`. -pub const EVENT_SAVED: u32 = 4; -/// Broadcast leaderboard snapshot (see `board::Leaderboards::snapshot`). -pub const EVENT_BOARD: u32 = 5; -/// To a player that died: `{respawnMs}`. -pub const EVENT_DIED: u32 = 6; +/// A player: the Arena's predicted [`MoveState`] plus server-owned combat +/// state (replaced, never predicted, on the client). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0)] +pub struct PlayerView { + /// Position x. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub x: f32, + /// Position y. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub y: f32, + /// Velocity x. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vx: f32, + /// Velocity y. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vy: f32, + /// Remaining dash frames. + #[correct(snap)] + pub dash: u8, + /// Remaining dash cooldown frames. + #[correct(snap)] + pub cd: u8, + /// Display name. + #[priority(0.2)] + #[correct(replace)] + pub name: String, + /// Hit points. + #[correct(replace)] + pub hp: u8, + /// Facing (rad). + #[angle(bits = 8)] + #[correct(replace)] + pub face: f32, + /// Swing animation frames left. + #[correct(replace)] + pub swing: u8, + /// Level (from the durable cell). + #[correct(replace)] + pub level: u16, + /// Waiting to respawn. + #[correct(replace)] + pub dead: bool, +} + +/// A mob (dead mobs are not replicated). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "mob", id = 2)] +pub struct MobView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub y: f32, + /// Facing (rad). + #[angle(bits = 8)] + pub face: f32, + /// 1 grunt · 2 brute · 3 elite. + pub tier: u8, + /// HP percent. + pub hp: u8, + /// 0 idle · 1 chase · 2 windup · 3 recover · 4 return. + pub state: u8, + /// Telegraph progress 0..=255 during a windup. + pub tele: u8, +} + +/// Zone numbers for the HUD (global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pit", id = 4, global)] +pub struct PitView { + /// Facts emitted and not settled. + pub pending: u16, + /// Artificial storage latency (ms). + pub slow_ms: u16, + /// Tick interval EMA (ms). + pub tick_ms: f32, + /// Longest tick interval of the last 30 ticks (ms). + pub tick_max_ms: f32, + /// Tick work EMA (µs). + pub work_us: u32, + /// Settlements received. + pub committed: u32, + /// Facts waiting for backpressure to clear. + pub backlog: u16, +} + +/// A player's durable progress (from the cell on join, after each settlement). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Profile { + /// Total XP. + pub xp: u64, + /// Level. + pub level: u32, + /// Kills. + pub kills: u32, + /// First XP of the level. + pub level_xp: u64, + /// First XP of the next level. + pub next_level_xp: u64, + /// `"cell"` (loaded on join) or `"settled"` (after a kill committed). + pub source: String, +} + +/// Mob Pit's events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum PitEvent { + /// To a joining player. + #[game_event(id = 1)] + Hello { + /// Own entity id. + entity: u32, + /// Floor half extent (m). + half: f32, + /// Process boot id (changes on restart). + boot: String, + /// Melee reach (m). + attack_range: f32, + /// Cosine of the half cone angle. + attack_arc_cos: f32, + }, + /// Durable progress. + #[game_event(id = 2)] + Profile(Profile), + /// Broadcast the tick a mob dies (the fact is only queued). + #[game_event(id = 3)] + Kill { + /// Fact key. + key: String, + /// Mob entity id. + mob: u32, + /// Mob tier. + tier: u8, + /// Where it died. + x: f32, + /// Where it died. + y: f32, + /// Killer entity id. + killer: u32, + /// Killer display name. + killer_name: String, + }, + /// To the killer when its fact settled. + #[game_event(id = 4)] + Saved { + /// Fact key. + key: String, + /// Committed. + ok: bool, + /// The cell recognised the key (replayed receipt). + replayed: bool, + /// XP credited by this kill (decided by the cell). + xp: u32, + /// Total XP after it. + total_xp: u64, + /// Kills after it. + kills: u32, + /// Level after it. + level: u32, + /// Time from emit to settlement (ms). + waited_ms: u32, + /// Where the mob died. + x: f32, + /// Where the mob died. + y: f32, + /// Failure, if any. + error: Option, + /// Commit attempts (failures). + attempts: u32, + }, + /// Leaderboard snapshot (on join and whenever it changes). + #[game_event(id = 5)] + Board(BoardSnapshot), + /// To a player that died. + #[game_event(id = 6)] + Died { + /// Respawn delay (ms). + respawn_ms: u32, + }, +} + +/// Mob Pit's client surface (also used by the leaderboard page). +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("mobpit").events::() +} + +/// Input: the Arena's 3-byte frame (`[mx, my, buttons]`) with an attack +/// bit next to dash. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] +pub struct PitInput { + /// Stick x. + #[range(min = -127, max = 127)] + pub mx: i8, + /// Stick y. + #[range(min = -127, max = 127)] + pub my: i8, + /// [`PitInput::DASH`] | [`PitInput::ATTACK`]. + #[buttons(dash, attack)] + pub buttons: u8, +} + +impl PitInput { + /// The movement part (the Arena's step). + pub fn movement(self) -> MoveInput { + MoveInput { + mx: self.mx, + my: self.my, + buttons: self.buttons & MoveInput::DASH, + } + } + + /// Attack held. + pub fn attack(self) -> bool { + self.buttons & Self::ATTACK != 0 + } +} /// Input bit: attack (bit 0 is the Arena's dash). -pub const BUTTON_ATTACK: u8 = 2; +pub const BUTTON_ATTACK: u8 = PitInput::ATTACK; /// Melee reach (m, from the player's centre to the mob's edge). pub const ATTACK_RANGE: f32 = 2.2; /// Cosine of the half cone angle (60°). @@ -237,24 +444,15 @@ fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() } -/// Player input: the Arena's 3-byte frame plus [`BUTTON_ATTACK`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PitInput { - /// Movement part (dash bit only). - pub movement: MoveInput, - /// Attack held. - pub attack: bool, -} - impl MobPit { - fn profile_event(xp: u64, level: u32, kills: u32, source: &str) -> Value { - json!({ - "xp": xp, - "level": level, - "kills": kills, - "levelXp": level_floor(level), - "nextLevelXp": level_floor(level + 1), - "source": source, + fn profile_event(xp: u64, level: u32, kills: u32, source: &str) -> PitEvent { + PitEvent::Profile(Profile { + xp, + level, + kills, + level_xp: level_floor(level), + next_level_xp: level_floor(level + 1), + source: source.into(), }) } @@ -267,25 +465,29 @@ impl MobPit { fn emit_kill(&mut self, ctx: &mut Ctx<'_, Self>, killer: PlayerId, mob: usize) { let m = &self.mobs[mob]; - let zone = ctx.zone_id().to_string(); - let key = ctx.fact_key("kill", &[&format_args!("m{}", m.id), &m.generation]); - let (x, y, tier, id) = (m.x, m.y, m.tier, m.id); + let (x, y, tier, id, generation) = (m.x, m.y, m.tier, m.id, m.generation); let Some(player) = self.players.get(&killer) else { return; }; - let fact = Fact::new( - key.clone(), - RECORD_KILL, - json!({ "mob": format!("{zone}/m{id}"), "tier": tier, "name": player.name }), - ); - broadcast_json_event( - ctx, - EVENT_KILL, - &json!({ - "key": key, "mob": id, "tier": tier, "x": x, "y": y, - "killer": player.entity, "killerName": player.name, - }), - ); + // The cell command's own input: what died, never who or how much XP. + let input = RecordKillInput { + mob: format!("{}/m{id}", ctx.zone_id()), + tier, + name: player.name.clone(), + }; + let Ok(fact) = ctx.fact_with_key(&input, &[&format_args!("m{id}"), &generation]) else { + return; + }; + let key = fact.key().to_string(); + ctx.broadcast(&PitEvent::Kill { + key, + mob: id, + tier, + x, + y, + killer: player.entity, + killer_name: player.name.clone(), + }); self.backlog.push_back((killer, fact, x, y)); self.flush_backlog(ctx); } @@ -350,13 +552,13 @@ impl MobPit { break; }; let input = input.input; - p.state = movement::step(p.state, input.movement); + p.state = movement::step(p.state, input.movement()); p.credits -= 1; - let (sx, sy) = (f32::from(input.movement.mx), f32::from(input.movement.my)); + let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); if sx * sx + sy * sy > 20.0 * 20.0 { p.face = sy.atan2(sx); } - if input.attack && p.swing_cd == 0 { + if input.attack() && p.swing_cd == 0 { p.swing_cd = SWING_COOLDOWN; p.swing_anim = SWING_FRAMES; swings.push((*id, p.state.x, p.state.y, p.face)); @@ -540,11 +742,11 @@ impl MobPit { m.target = None; } } - send_json_event( - ctx, + ctx.send( id, - EVENT_DIED, - &json!({ "respawnMs": PLAYER_RESPAWN_TICKS * 1000 / 30 }), + &PitEvent::Died { + respawn_ms: (PLAYER_RESPAWN_TICKS * 1000 / 30) as u32, + }, ); } } @@ -559,12 +761,7 @@ impl MobPit { if let Some(p) = self.players.get_mut(&id) { p.level = level; } - send_json_event( - ctx, - id, - EVENT_PROFILE, - &Self::profile_event(xp, level, kills, "cell"), - ); + ctx.send(id, &Self::profile_event(xp, level, kills, "cell")); } } @@ -573,7 +770,7 @@ impl MobPit { if version != self.board_version { self.board_version = version; let snapshot = self.world.board().snapshot(); - broadcast_json_event(ctx, EVENT_BOARD, &snapshot); + ctx.broadcast(&PitEvent::Board((*snapshot).clone())); } } @@ -604,54 +801,7 @@ impl Zone for MobPit { type Timer = (); fn schema() -> EntitySchema { - let pos = FieldType::QuantF32 { - min: -movement::HALF, - max: movement::HALF, - bits: 14, - }; - EntitySchema::new() - .kind( - KindDef::new(KIND_PLAYER, "player") - .field("x", movement::POS) - .field("y", movement::POS) - .field("vx", movement::VEL) - .field("vy", movement::VEL) - .field("dash", FieldType::U8) - .field("cd", FieldType::U8) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .field("hp", FieldType::U8) - .field("face", FieldType::Angle { bits: 8 }) - .field("swing", FieldType::U8) - .field("level", FieldType::U16) - .field("dead", FieldType::Bool) - .priority(2.0), - ) - .kind( - KindDef::new(KIND_MOB, "mob") - .field("x", pos) - .field("y", pos) - .field("face", FieldType::Angle { bits: 8 }) - .field("tier", FieldType::U8) - .field("hp", FieldType::U8) - .field("state", FieldType::U8) - .field("tele", FieldType::U8), - ) - .kind( - KindDef::new(KIND_PILLAR, "pillar") - .field("x", FieldType::F32) - .field("y", FieldType::F32) - .field("r", FieldType::F32), - ) - .kind( - KindDef::new(KIND_PIT, "pit") - .field("pending", FieldType::U16) - .field("slowMs", FieldType::U16) - .field("tickMs", FieldType::F32) - .field("tickMaxMs", FieldType::F32) - .field("workUs", FieldType::U32) - .field("committed", FieldType::U32) - .field("backlog", FieldType::U16), - ) + schema![PlayerView, MobView, PillarView, PitView] } fn on_create(_ctx: &mut Ctx<'_, Self>, config: MobPitConfig) -> Self { @@ -725,16 +875,20 @@ impl Zone for MobPit { }, ); ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); - send_json_event( - ctx, + ctx.send( player, - EVENT_HELLO, - &json!({ - "entity": entity, "half": movement::HALF, "boot": self.world.boot(), - "attackRange": ATTACK_RANGE, "attackArcCos": ATTACK_ARC_COS, - }), + &PitEvent::Hello { + entity, + half: movement::HALF, + boot: self.world.boot().to_string(), + attack_range: ATTACK_RANGE, + attack_arc_cos: ATTACK_ARC_COS, + }, + ); + ctx.send( + player, + &PitEvent::Board((*self.world.board().snapshot()).clone()), ); - send_json_event(ctx, player, EVENT_BOARD, &self.world.board().snapshot()); // Read path: load the durable cell off the tick; delivered later. self.world.request_profile(&principal); } @@ -750,15 +904,14 @@ impl Zone for MobPit { fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); - send_json_event(ctx, observer, EVENT_BOARD, &self.world.board().snapshot()); + ctx.send( + observer, + &PitEvent::Board((*self.world.board().snapshot()).clone()), + ); } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - let movement = MoveInput::from_payload(payload)?; - Some(PitInput { - movement, - attack: payload[2] & BUTTON_ATTACK != 0, - }) + PitInput::from_payload(payload) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { @@ -787,7 +940,7 @@ impl Zone for MobPit { p.principal.clone(), p.x, p.y, - p.emitted.elapsed().as_millis() as u64, + p.emitted.elapsed().as_millis().min(u128::from(u32::MAX)) as u32, ), None => (String::new(), 0.0, 0.0, 0), }; @@ -795,40 +948,53 @@ impl Zone for MobPit { match settlement.outcome { FactOutcome::Committed(receipt) => { self.committed += 1; - let Ok(kill) = serde_json::from_value::(receipt.payload) else { + let Ok(kill) = receipt.payload_as::() else { return; }; let Some(player) = player else { return }; if let Some(p) = self.players.get_mut(&player) { p.level = kill.level; } - send_json_event( - ctx, + ctx.send( player, - EVENT_SAVED, - &json!({ - "key": settlement.key, "ok": true, "replayed": receipt.replayed, - "xp": kill.xp, "totalXp": kill.total_xp, "kills": kill.kills, - "level": kill.level, "waitedMs": waited_ms, "x": x, "y": y, - }), + &PitEvent::Saved { + key: settlement.key, + ok: true, + replayed: receipt.replayed, + xp: kill.xp, + total_xp: kill.total_xp, + kills: kill.kills, + level: kill.level, + waited_ms, + x, + y, + error: None, + attempts: 0, + }, ); - send_json_event( - ctx, + ctx.send( player, - EVENT_PROFILE, &Self::profile_event(kill.total_xp, kill.level, kill.kills, "settled"), ); } FactOutcome::Failed { error, attempts } => { if let Some(player) = player { - send_json_event( - ctx, + ctx.send( player, - EVENT_SAVED, - &json!({ - "key": settlement.key, "ok": false, "error": format!("{error:?}"), - "attempts": attempts, "waitedMs": waited_ms, "x": x, "y": y, - }), + &PitEvent::Saved { + key: settlement.key, + ok: false, + replayed: false, + xp: 0, + total_xp: 0, + kills: 0, + level: 0, + waited_ms, + x, + y, + error: Some(format!("{error:?}")), + attempts, + }, ); } } @@ -842,26 +1008,21 @@ impl Zone for MobPit { fn replicate(&self, out: &mut WorldView) { for p in self.players.values() { let s = p.state; - out.push(EntityState::new( - p.entity, - KIND_PLAYER, - s.x, - s.y, - vec![ - FieldValue::F(s.x), - FieldValue::F(s.y), - FieldValue::F(s.vx), - FieldValue::F(s.vy), - FieldValue::U(s.dash.into()), - FieldValue::U(s.cooldown.into()), - FieldValue::Str(p.name.clone()), - FieldValue::U(p.hp.max(0) as u32), - FieldValue::F(p.face), - FieldValue::U(p.swing_anim.into()), - FieldValue::U(p.level), - FieldValue::Bool(p.dead_until.is_some()), - ], - )); + let view = PlayerView { + x: s.x, + y: s.y, + vx: s.vx, + vy: s.vy, + dash: s.dash, + cd: s.cooldown, + name: p.name.clone(), + hp: p.hp.clamp(0, 255) as u8, + face: p.face, + swing: p.swing_anim, + level: p.level.min(u32::from(u16::MAX)) as u16, + dead: p.dead_until.is_some(), + }; + out.add(p.entity, &view); } for m in &self.mobs { if m.state == MobState::Dead { @@ -873,52 +1034,38 @@ impl Zone for MobPit { } else { 0 }; - out.push(EntityState::new( - m.id, - KIND_MOB, - m.x, - m.y, - vec![ - FieldValue::F(m.x), - FieldValue::F(m.y), - FieldValue::F(m.face), - FieldValue::U(m.tier.into()), - FieldValue::U((m.hp.max(0) * 100 / max_hp) as u32), - FieldValue::U(m.state as u32), - FieldValue::U(tele), - ], - )); + let view = MobView { + x: m.x, + y: m.y, + face: m.face, + tier: m.tier, + hp: (m.hp.max(0) * 100 / max_hp) as u8, + state: m.state as u8, + tele: tele as u8, + }; + out.add(m.id, &view); } for (i, (x, y, r)) in PILLARS.iter().enumerate() { - out.push( - EntityState::new( - 100 + i as u32, - KIND_PILLAR, - *x, - *y, - vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::F(*r)], - ) - .global(), + out.add( + 100 + i as u32, + &PillarView { + x: *x, + y: *y, + r: *r, + }, ); } - out.push( - EntityState::new( - PIT_ENTITY, - KIND_PIT, - 0.0, - 0.0, - vec![ - FieldValue::U(self.pending.len().min(65_535) as u32), - FieldValue::U(self.world.sink_state().latency().as_millis().min(65_535) as u32), - FieldValue::F(self.tick_ms), - FieldValue::F(self.tick_max_ms), - FieldValue::U(self.work_us as u32), - FieldValue::U(self.committed), - FieldValue::U(self.backlog.len().min(65_535) as u32), - ], - ) - .global(), - ); + let clamp16 = |n: usize| n.min(65_535) as u16; + let stats = PitView { + pending: clamp16(self.pending.len()), + slow_ms: self.world.sink_state().latency().as_millis().min(65_535) as u16, + tick_ms: self.tick_ms, + tick_max_ms: self.tick_max_ms, + work_us: self.work_us as u32, + committed: self.committed, + backlog: clamp16(self.backlog.len()), + }; + out.add(PIT_ENTITY, &stats); } } @@ -960,5 +1107,10 @@ impl MobPit { /// Bot payload: the direction as a move plus attack always held. pub fn encode_bot_input(dir: [f32; 2]) -> Vec { let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; - vec![axis(dir[0]) as u8, axis(dir[1]) as u8, BUTTON_ATTACK] + PitInput { + mx: axis(dir[0]), + my: axis(dir[1]), + buttons: PitInput::ATTACK, + } + .to_payload() } diff --git a/examples/game/server/tests/mobpit_smoke.rs b/examples/game/server/tests/mobpit_smoke.rs index a210121c9..338c6f3ba 100644 --- a/examples/game/server/tests/mobpit_smoke.rs +++ b/examples/game/server/tests/mobpit_smoke.rs @@ -179,10 +179,10 @@ async fn facts_commit_once_and_board_rebuilds_identically() { assert_eq!(assert_board_matches_cells(&world).await, 2); let report = world.rebuild_board().await.unwrap(); - assert_eq!(report["events"], 2); - assert_eq!(report["applied"], 4, "two boards per kill"); - assert_eq!(report["matchesCells"], true, "{report}"); - assert_eq!(report["identicalTop"], true, "{report}"); + assert_eq!(report.events, 2); + assert_eq!(report.applied, 4, "two boards per kill"); + assert!(report.matches_cells, "{report:?}"); + assert!(report.identical_top, "{report:?}"); // The live occurrence id equals the history one: replaying it after the // rebuild is a duplicate on both boards. @@ -534,8 +534,8 @@ async fn redis_board_projects_and_rebuilds_when_redis_url_is_set() { }) .await; let report = world.rebuild_board().await.unwrap(); - assert_eq!(report["matchesCells"], true, "{report}"); - assert_eq!(report["identicalTop"], true, "{report}"); + assert!(report.matches_cells, "{report:?}"); + assert!(report.identical_top, "{report:?}"); let (kills, xp) = world.board().boards(); for board in [kills, xp] { world.board().store().reset(board).await.unwrap(); From 83d11ff38fc451fb2c0bd8f48ec22a8764b63dcd Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:43:33 -0500 Subject: [PATCH 184/484] feat(examples): author the shooting gallery with derives ShotInput is a GameInput (flag bits, varuint ids, centered 16-bit aim) encoded by the generated client instead of a hand-packed DataView; kinds and verdict events are derived and typed on both sides. --- examples/game/client/src/gallery/client.ts | 86 ++--- examples/game/client/src/gallery/main.ts | 22 +- .../client/src/generated/gallery/client.ts | 49 +++ .../client/src/generated/gallery/events.ts | 87 ++++++ .../client/src/generated/gallery/index.ts | 7 + .../client/src/generated/gallery/input.ts | 56 ++++ .../client/src/generated/gallery/schema.ts | 96 ++++++ .../client/src/generated/gallery/surface.json | 269 ++++++++++++++++ .../client/tests/gallery-headless.test.mjs | 20 +- examples/game/server/src/gallery/mod.rs | 295 ++++++++++-------- examples/game/server/tests/gallery_smoke.rs | 37 +-- 11 files changed, 814 insertions(+), 210 deletions(-) create mode 100644 examples/game/client/src/generated/gallery/client.ts create mode 100644 examples/game/client/src/generated/gallery/events.ts create mode 100644 examples/game/client/src/generated/gallery/index.ts create mode 100644 examples/game/client/src/generated/gallery/input.ts create mode 100644 examples/game/client/src/generated/gallery/schema.ts create mode 100644 examples/game/client/src/generated/gallery/surface.json diff --git a/examples/game/client/src/gallery/client.ts b/examples/game/client/src/gallery/client.ts index 2b868c460..240229eb7 100644 --- a/examples/game/client/src/gallery/client.ts +++ b/examples/game/client/src/gallery/client.ts @@ -15,38 +15,24 @@ * predicted and confirmed hits. */ import { - GameClient, type AdaptiveDelay, type AdaptiveDelayOptions, + type GameClient, type GameSocketFactory, type GameZoneView, type RenderedEntity } from '@hops-ops/distributed/game'; +import * as gallery from '../generated/gallery/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; +import { latest } from '../shared/latest.ts'; export const DEFAULT_ZONE = 'gallery-1'; -/** Event type ids (server `gallery::EVENT_*`). */ -export const EVENT_HELLO = 1; -export const EVENT_SHOT = 2; -export const FLAG_FIRE = 1; -export const FLAG_NO_COMP = 2; -export const KIND = { shooter: 'shooter', target: 'target' } as const; export type Vec3 = [number, number, number]; -export type GalleryHello = Readonly<{ entity: number; eye: Vec3; maxRewindMs: number; range: number; half: number }>; - -export type ShotVerdict = Readonly<{ - shot: number; - hit: number | null; - compensated: boolean; - ageMs: number; - requestedAgeMs: number; - clamped: boolean; - tick: number; -}>; +export type GalleryHello = gallery.HelloEvent; +export type ShotVerdict = gallery.ShotEvent; export type ShotRecord = { id: number; @@ -75,17 +61,8 @@ export type GalleryStats = { lastAgeMs: number; }; -export function encodeShot(flags: number, shot: number, delayMs: number, dir: Vec3): Uint8Array { - const bytes = new Uint8Array(11); - const view = new DataView(bytes.buffer); - view.setUint8(0, flags); - view.setUint16(1, shot & 0xffff, true); - view.setUint16(3, Math.max(0, Math.min(0xffff, Math.round(delayMs))), true); - const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; - for (let i = 0; i < 3; i += 1) { - view.setInt16(5 + i * 2, Math.round(Math.max(-1, Math.min(1, dir[i] / len)) * 32767), true); - } - return bytes; +function vec3(v: readonly number[]): Vec3 { + return [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0]; } /** Entry distance of a ray (unit `dir`) into a sphere, if hit in front. */ @@ -100,12 +77,12 @@ export function raySphere(origin: Vec3, dir: Vec3, center: Vec3, radius: number) } export function targetPosition(entity: Pick): Vec3 { - const f = entity.fields; - return [Number(f.x ?? 0), Number(f.y ?? 0), Number(f.z ?? 0)]; + const { x, y, z } = gallery.targetFields(entity); + return [x, y, z]; } export type GalleryClient = Readonly<{ - client: GameClient; + client: GameClient; /** The SDK's adaptive interpolation delay of `zone` (default: the authority). */ delay(zone?: GameZoneView): AdaptiveDelay; hello(): GalleryHello | undefined; @@ -131,24 +108,19 @@ export type GalleryClientOptions = Readonly<{ }>; export function createGalleryClient(options: GalleryClientOptions): GalleryClient { - const client = new GameClient({ + const typed = gallery.createGalleryClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 250, adaptiveDelay: options.adaptiveDelay }); + const { client } = typed; const delay = (zone: GameZoneView | undefined = client.authority): AdaptiveDelay => { if (zone === undefined) throw new Error('not joined'); return client.adaptiveDelay(zone)!; }; - let hello: GalleryHello | undefined; - let resolveReady: (h: GalleryHello) => void = () => undefined; - const ready = new Promise((resolve) => (resolveReady = resolve)); - onJsonEvent(client, EVENT_HELLO, (value) => { - hello = value; - resolveReady(value); - }); + const hello = latest((h) => typed.on('hello', h)); const stats: GalleryStats = { shots: 0, @@ -166,13 +138,13 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien let next = 0; let compensatedVerdicts = 0; - onJsonEvent(client, EVENT_SHOT, (verdict) => { + typed.on('shot', (verdict) => { const shot = shots.get(verdict.shot); if (shot === undefined || shot.verdict !== undefined) return; shot.verdict = verdict; stats.resolved += 1; - if (verdict.hit !== null) stats.confirmedHits += 1; - if ((verdict.hit ?? undefined) === shot.predicted) stats.agreed += 1; + if (verdict.hit !== undefined) stats.confirmedHits += 1; + if (verdict.hit === shot.predicted) stats.agreed += 1; if (verdict.clamped) stats.clamped += 1; if (verdict.compensated) { compensatedVerdicts += 1; @@ -184,10 +156,10 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien for (const listener of listeners) listener(shot); }); - const targets = () => client.render().filter((e) => e.kindName === KIND.target && !e.stale); + const targets = () => client.render().filter((e) => gallery.isTarget(e) && !e.stale); function predict(dir: Vec3): { target: number | undefined; point: Vec3 | undefined } { - const eye = hello?.eye; + const eye = hello.get()?.eye; if (eye === undefined) return { target: undefined, point: undefined }; const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; const unit: Vec3 = [dir[0] / len, dir[1] / len, dir[2] / len]; @@ -195,8 +167,8 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien let point: Vec3 | undefined; let best = Infinity; for (const entity of targets()) { - const d = raySphere(eye, unit, targetPosition(entity), Number(entity.fields.r ?? 0.5)); - if (d !== undefined && d < best && d <= (hello?.range ?? 80)) { + const d = raySphere(vec3(eye), unit, targetPosition(entity), gallery.targetFields(entity).r); + if (d !== undefined && d < best && d <= (hello.get()?.range ?? 80)) { best = d; target = entity.id; point = [eye[0] + unit[0] * d, eye[1] + unit[1] * d, eye[2] + unit[2] * d]; @@ -207,7 +179,7 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien function shoot(dir: Vec3, opts: { compensated?: boolean } = {}): ShotRecord | undefined { const zone = client.authority; - const eye = hello?.eye; + const eye = hello.get()?.eye; if (zone === undefined || eye === undefined || !zone.connection.canSendInput()) return undefined; const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; const unit: Vec3 = [dir[0] / len, dir[1] / len, dir[2] / len]; @@ -220,8 +192,16 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien const compensated = opts.compensated ?? true; next = (next + 1) & 0xffff; const id = next; - const flags = FLAG_FIRE | (compensated ? 0 : FLAG_NO_COMP); - const seq = zone.connection.sendInput(encodeShot(flags, id, delayMs, unit), context.clientTick); + const flags = gallery.BUTTON.fire | (compensated ? 0 : gallery.BUTTON.noComp); + const payload = gallery.encodeInput({ + flags, + shot: id, + delayMs: Math.min(0xffff, Math.round(delayMs)), + dx: unit[0], + dy: unit[1], + dz: unit[2] + }); + const seq = zone.connection.sendInput(payload, context.clientTick); if (seq === undefined) return undefined; const record: ShotRecord = { id, @@ -242,8 +222,8 @@ export function createGalleryClient(options: GalleryClientOptions): GalleryClien return { client, delay, - hello: () => hello, - ready, + hello: hello.get, + ready: hello.ready, stats, shots, targets, diff --git a/examples/game/client/src/gallery/main.ts b/examples/game/client/src/gallery/main.ts index 7b9d95da7..0d635993f 100644 --- a/examples/game/client/src/gallery/main.ts +++ b/examples/game/client/src/gallery/main.ts @@ -23,7 +23,8 @@ import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { InputSampler } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; -import { createGalleryClient, DEFAULT_ZONE, KIND, targetPosition, type ShotRecord, type Vec3 } from './client.ts'; +import { isShooter, isTarget, shooterFields, targetFields } from '../generated/gallery/index.ts'; +import { createGalleryClient, DEFAULT_ZONE, targetPosition, type ShotRecord, type Vec3 } from './client.ts'; import '@babylonjs/core/Culling/ray'; // side effect: scene.createPickingRay import './gallery.css'; @@ -153,7 +154,7 @@ gallery.onVerdict((shot: ShotRecord) => { const v = shot.verdict!; const predictedMarker = pending.get(shot.id); pending.delete(shot.id); - const confirmed = v.hit !== null; + const confirmed = v.hit !== undefined; if (predictedMarker !== undefined) predictedMarker.material = confirmed && v.hit === shot.predicted ? mats.confirmed : mats.rejected; else if (confirmed) { const target = gallery.targets().find((t) => t.id === v.hit); @@ -202,21 +203,22 @@ stage.onFrame((now) => { const seen = new Set(); for (const entity of rendered) { seen.add(entity.key); - if (entity.kindName === KIND.target) { - const v = targetVisual(entity.key, Number(entity.fields.r ?? 0.5)); + if (isTarget(entity)) { + const { r, flash } = targetFields(entity); + const v = targetVisual(entity.key, r); const p = targetPosition(entity); v.mesh.position.copyFrom(toWorld(p[0], p[1], p[2])); - const flash = Number(entity.fields.flash ?? 0); if (v.flash >= 0 && flash !== v.flash) v.flashUntil = now + 150; v.flash = flash; v.mesh.material = now < v.flashUntil ? mats.flash : mats.target; const newest = authority?.replica.get(entity.id); v.ghost.setEnabled(ghostsOn && newest !== undefined); if (newest !== undefined) { - const f = newest.fields; - v.ghost.position.copyFrom(toWorld(Number(f.x), Number(f.y), Number(f.z))); + const g = targetPosition(newest); + v.ghost.position.copyFrom(toWorld(g[0], g[1], g[2])); } - } else if (entity.kindName === KIND.shooter) { + } else if (isShooter(entity)) { + const shooter = shooterFields(entity); let mesh = shooters.get(entity.key); const mine = entity.id === hello?.entity; if (mesh === undefined) { @@ -224,8 +226,8 @@ stage.onFrame((now) => { mesh.material = mine ? mats.me : mats.station; shooters.set(entity.key, mesh); } - mesh.position.copyFrom(toWorld(Number(entity.fields.x), Number(entity.fields.y), 0.08)); - if (!mine) stage.labels.set(entity.key, mesh, `${String(entity.fields.name)} · ${entity.fields.hits}/${entity.fields.shots}`, 1.9); + mesh.position.copyFrom(toWorld(shooter.x, shooter.y, 0.08)); + if (!mine) stage.labels.set(entity.key, mesh, `${shooter.name} · ${shooter.hits}/${shooter.shots}`, 1.9); } } for (const [key, v] of targets) { diff --git a/examples/game/client/src/generated/gallery/client.ts b/examples/game/client/src/generated/gallery/client.ts new file mode 100644 index 000000000..fbfd31ecc --- /dev/null +++ b/examples/game/client/src/generated/gallery/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type ShotInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type GalleryPredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type GalleryClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: GalleryPredictionOptions }>; + +export type GalleryClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: ShotInput): number | undefined; +}>; + +/** A `GameClient` for the `gallery` surface with its input encoder and correction defaults. */ +export function createGalleryClient(options: GalleryClientOptions): GalleryClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/gallery/events.ts b/examples/game/client/src/generated/gallery/events.ts new file mode 100644 index 000000000..a470ca5fe --- /dev/null +++ b/examples/game/client/src/generated/gallery/events.ts @@ -0,0 +1,87 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly eye: readonly number[]; + readonly maxRewindMs: number; + readonly range: number; + readonly half: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['eye', { type: 'list', item: { type: 'f32' } }], + ['maxRewindMs', { type: 'u32' }], + ['range', { type: 'f32' }], + ['half', { type: 'f32' }], +]; + +/** Event `shot` (id 2). */ +export interface ShotEvent { + readonly shot: number; + readonly hit: number | undefined; + readonly compensated: boolean; + readonly ageMs: number; + readonly requestedAgeMs: number; + readonly clamped: boolean; + readonly tick: number; +} + +const SHOT_LAYOUT: PayloadLayout = [ + ['shot', { type: 'u16' }], + ['hit', { type: 'optional', item: { type: 'u32' } }], + ['compensated', { type: 'bool' }], + ['ageMs', { type: 'f64' }], + ['requestedAgeMs', { type: 'f64' }], + ['clamped', { type: 'bool' }], + ['tick', { type: 'u32' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + shot: 2, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + shot: ShotEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + shot: { + id: 2, + name: 'shot', + encode: (value) => encodePayload(SHOT_LAYOUT, value), + decode: (payload) => decodePayload(SHOT_LAYOUT, payload) as unknown as ShotEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/gallery/index.ts b/examples/game/client/src/generated/gallery/index.ts new file mode 100644 index 000000000..aa58c899a --- /dev/null +++ b/examples/game/client/src/generated/gallery/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/gallery/input.ts b/examples/game/client/src/generated/gallery/input.ts new file mode 100644 index 000000000..b768d581b --- /dev/null +++ b/examples/game/client/src/generated/gallery/input.ts @@ -0,0 +1,56 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `ShotInput` input frame (`#[derive(GameInput)]`). */ +export interface ShotInput { + readonly flags: number; + readonly shot: number; + readonly delayMs: number; + readonly dx: number; + readonly dy: number; + readonly dz: number; +} + +export type Input = ShotInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + fire: 1, + noComp: 2, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['flags', { type: 'u8' }], + ['shot', { type: 'u16' }], + ['delayMs', { type: 'u16' }], + ['dx', { type: 'quant', min: -1, max: 0.999969482421875, bits: 16 }], + ['dy', { type: 'quant', min: -1, max: 0.999969482421875, bits: 16 }], + ['dz', { type: 'quant', min: -1, max: 0.999969482421875, bits: 16 }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { buttons: 3 }, + undefined, + undefined, + undefined, + undefined, + undefined, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: ShotInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): ShotInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as ShotInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: ShotInput): ShotInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/gallery/schema.ts b/examples/game/client/src/generated/gallery/schema.ts new file mode 100644 index 000000000..83a8d087c --- /dev/null +++ b/examples/game/client/src/generated/gallery/schema.ts @@ -0,0 +1,96 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + shooter: 1, + target: 2, +} as const; + +export type KindName = keyof typeof KIND; + +/** `shooter` (kind 1, priority 0.5). */ +export interface ShooterFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u32` */ + readonly shots: number; + /** `u32` */ + readonly hits: number; +} + +/** True for a `shooter` entity. */ +export function isShooter(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `shooter` entity (rendered or replica). */ +export function shooterFields(entity: { readonly fields: EntityFields }): ShooterFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + name: fieldString(f, 'name'), + shots: fieldNumber(f, 'shots'), + hits: fieldNumber(f, 'hits'), + }; +} + +/** `target` (kind 2, priority 2). */ +export interface TargetFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [0, 4] / 12 bits` */ + readonly z: number; + /** `f32` */ + readonly r: number; + /** `u8` */ + readonly flash: number; +} + +/** True for a `target` entity. */ +export function isTarget(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `target` entity (rendered or replica). */ +export function targetFields(entity: { readonly fields: EntityFields }): TargetFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + z: fieldNumber(f, 'z'), + r: fieldNumber(f, 'r'), + flash: fieldNumber(f, 'flash'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + shooter: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + name: { type: 'short_str' }, + shots: { type: 'u32' }, + hits: { type: 'u32' }, + }, + target: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + z: { type: 'quant', min: 0, max: 4, bits: 12 }, + r: { type: 'f32' }, + flash: { type: 'u8' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { +}; diff --git a/examples/game/client/src/generated/gallery/surface.json b/examples/game/client/src/generated/gallery/surface.json new file mode 100644 index 000000000..27d7d5e44 --- /dev/null +++ b/examples/game/client/src/generated/gallery/surface.json @@ -0,0 +1,269 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "eye", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + } + }, + { + "name": "max_rewind_ms", + "type": { + "type": "u32" + } + }, + { + "name": "range", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "type": "f32" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "shot", + "payload": { + "fields": [ + { + "name": "shot", + "type": { + "type": "u16" + } + }, + { + "name": "hit", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "compensated", + "type": { + "type": "bool" + } + }, + { + "name": "age_ms", + "type": { + "type": "f64" + } + }, + { + "name": "requested_age_ms", + "type": { + "type": "f64" + } + }, + { + "name": "clamped", + "type": { + "type": "bool" + } + }, + { + "name": "tick", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "buttons": [ + "fire", + "no_comp" + ], + "name": "flags", + "type": { + "type": "u8" + } + }, + { + "name": "shot", + "type": { + "type": "u16" + } + }, + { + "name": "delay_ms", + "type": { + "type": "u16" + } + }, + { + "name": "dx", + "type": { + "bits": 16, + "max": 0.9999695, + "min": -1.0, + "type": "quant" + } + }, + { + "name": "dy", + "type": { + "bits": 16, + "max": 0.9999695, + "min": -1.0, + "type": "quant" + } + }, + { + "name": "dz", + "type": { + "bits": 16, + "max": 0.9999695, + "min": -1.0, + "type": "quant" + } + } + ], + "name": "ShotInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "shots", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "hits", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "shooter", + "priority": 0.5 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "z", + "priority": 1.0, + "type": { + "bits": 12, + "max": 4.0, + "min": 0.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "r", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "flash", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 2, + "name": "target", + "priority": 2.0 + } + ], + "name": "gallery", + "protocolVersion": 1, + "records": [], + "schemaVersion": 1 +} diff --git a/examples/game/client/tests/gallery-headless.test.mjs b/examples/game/client/tests/gallery-headless.test.mjs index db51b6c87..5164f4581 100644 --- a/examples/game/client/tests/gallery-headless.test.mjs +++ b/examples/game/client/tests/gallery-headless.test.mjs @@ -8,7 +8,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { createGalleryClient, encodeShot, raySphere, targetPosition } from '../src/gallery/client.ts'; +import { createGalleryClient, raySphere, targetPosition } from '../src/gallery/client.ts'; +import { BUTTON, decodeInput, encodeInput, sanitizeInput, shooterFields } from '../src/generated/gallery/index.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; @@ -40,9 +41,15 @@ async function volley(gallery, n, compensated) { } test('shot payload and local ray test', () => { - const bytes = encodeShot(3, 0x1234, 287.4, [0, 2, 0]); - assert.deepEqual([...bytes.slice(0, 5)], [3, 0x34, 0x12, 31, 1]); - assert.equal(new DataView(bytes.buffer).getInt16(7, true), 32767); + // The generated codec (from the Rust `ShotInput` derive): flags u8, + // varuint shot id and delay, 16-bit centered quantized direction. + const shot = { flags: BUTTON.fire | BUTTON.noComp | 0x80, shot: 0x1234, delayMs: 287, dx: 0, dy: 1, dz: 0 }; + const bytes = encodeInput(shot); + assert.deepEqual([...bytes.slice(0, 5)], [0x83, 0xb4, 0x24, 0x9f, 0x02]); + const back = decodeInput(bytes); + assert.equal(back.dx, 0, 'zero is exact on the centered grid'); + assert.ok(Math.abs(back.dy - 1) < 1e-4); + assert.equal(sanitizeInput(shot).flags, 3, 'unknown flags cleared like the server'); assert.equal(raySphere([0, 0, 0], [0, 1, 0], [0, 10, 0], 1), 9); assert.equal(raySphere([0, 0, 0], [0, 1, 0], [0, -10, 0], 1), undefined, 'behind'); assert.equal(raySphere([0, 0, 0], [0, 1, 0], [2, 10, 0], 1), undefined, 'beside'); @@ -91,7 +98,10 @@ test('lag compensation confirms what the shooter saw; off misses; beyond max rew assert.equal(gallery.stats.predictedHits, 50); const me = gallery.client.render().find((e) => e.id === hello.entity); await until( - () => gallery.client.render().find((e) => e.id === hello.entity)?.fields.shots === 50, + () => { + const me = gallery.client.render().find((e) => e.id === hello.entity); + return me !== undefined && shooterFields(me).shots === 50; + }, 5_000, 'replicated shot counter' ); diff --git a/examples/game/server/src/gallery/mod.rs b/examples/game/server/src/gallery/mod.rs index a33250675..6217dd28d 100644 --- a/examples/game/server/src/gallery/mod.rs +++ b/examples/game/server/src/gallery/mod.rs @@ -17,8 +17,11 @@ //! | 1 `shooter` | 1000 + player | x y name shots hits | //! | 2 `target` | 1..=[`TARGETS`] | x y z r flash | //! -//! Inputs are shots only ([`ShotInput`], 11 bytes). The shooter gets one -//! [`EVENT_SHOT`] (JSON) per shot with the verdict and the rewind used. +//! Kinds are `#[derive(Replicated)]` views; inputs are shots only +//! ([`ShotInput`], a `#[derive(GameInput)]`: flags, shot id, view delay and +//! a 16-bit quantized unit direction). The shooter gets one +//! [`GalleryEvent::Shot`] per shot with the verdict and the rewind used. The +//! browser client is generated from [`game_surface`]. use std::collections::BTreeMap; use std::time::Duration; @@ -26,21 +29,11 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::rewind::{Historic, HitQuery, RewindFrame, ShotTiming, Vec3}; use distributed_game::{ - ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, - PlayerId, View, WorldView, Zone, + schema, ConsumePolicy, Ctx, EntitySchema, FieldType, GameEvent, GameInput, GameSurface, + LeaveReason, PlayerId, Replicated, View, WorldView, Zone, }; -use serde_json::json; - -use crate::common::{send_json_event, Demo, Guests}; - -/// Shooter kind. -pub const KIND_SHOOTER: u16 = 1; -/// Target kind. -pub const KIND_TARGET: u16 = 2; -/// Event: `{"entity", "eye": [x, y, z], "maxRewindMs", "range"}` (JSON). -pub const EVENT_HELLO: u32 = 1; -/// Event: shot verdict (JSON, see [`ShotVerdict`]). -pub const EVENT_SHOT: u32 = 2; + +use crate::common::{Demo, Guests}; /// Floor half extent (m). pub const HALF: f32 = 20.0; /// Firing line (m, game y). @@ -58,12 +51,92 @@ pub const RANGE: f32 = 80.0; /// Number of targets. pub const TARGETS: u32 = 6; /// Input flag: this input is a shot. -pub const FLAG_FIRE: u8 = 1; +pub const FLAG_FIRE: u8 = ShotInput::FIRE; /// Input flag: evaluate without lag compensation. -pub const FLAG_NO_COMP: u8 = 2; +pub const FLAG_NO_COMP: u8 = ShotInput::NO_COMP; const POS: FieldType = FieldType::quant_centered(HALF, 18); +/// A shooter at its station (positions never change while connected). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "shooter", id = 1, priority = 0.5)] +pub struct ShooterView { + /// Station x. + #[field_type(POS)] + pub x: f32, + /// Station y. + #[field_type(POS)] + pub y: f32, + /// Display name. + #[priority(0.2)] + pub name: String, + /// Shots resolved. + pub shots: u32, + /// Shots that hit. + pub hits: u32, +} + +/// A moving target (global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "target", id = 2, priority = 2.0, global)] +pub struct TargetView { + /// Position x. + #[field_type(POS)] + pub x: f32, + /// Position y. + #[field_type(POS)] + pub y: f32, + /// Height. + #[quant(min = 0.0, max = 4.0, bits = 12)] + pub z: f32, + /// Radius. + pub r: f32, + /// Bumps on every confirmed hit. + pub flash: u8, +} + +/// The gallery's events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum GalleryEvent { + /// To a joining shooter. + #[game_event(id = 1)] + Hello { + /// Own entity id. + entity: u32, + /// Eye position `[x, y, z]` (z up). + eye: Vec, + /// Furthest rewind (anti-cheat clamp). + max_rewind_ms: u32, + /// Hitscan range (m). + range: f32, + /// Floor half extent (m). + half: f32, + }, + /// The verdict of one shot. + #[game_event(id = 2)] + Shot { + /// Client shot id. + shot: u16, + /// Target hit. + hit: Option, + /// Lag compensation used. + compensated: bool, + /// Rewind applied (0 without compensation). + age_ms: f64, + /// Rewind the client asked for. + requested_age_ms: f64, + /// Limited by the clamp / stored history. + clamped: bool, + /// Server tick of the verdict. + tick: u32, + }, +} + +/// The gallery's client surface. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("gallery").events::() +} + /// How a target moves. #[derive(Debug, Clone, Copy)] enum Path { @@ -176,46 +249,65 @@ pub fn target_speed(index: usize) -> f32 { } } -/// One shot: `[flags, shot u16, delay_ms u16, dx i16, dy i16, dz i16]` -/// (little endian; the direction is a unit vector × 32767). -#[derive(Debug, Clone, Copy, PartialEq)] +/// One shot (`#[derive(GameInput)]`): flags, shot id, view delay and the +/// aim direction quantized to 16 bits per axis (centered, so a zero axis is +/// exact; the zone re-normalizes, see [`ShotInput::parse`]). +#[derive(Debug, Clone, Copy, PartialEq, GameInput)] pub struct ShotInput { - /// [`FLAG_FIRE`] | [`FLAG_NO_COMP`]. + /// [`ShotInput::FIRE`] | [`ShotInput::NO_COMP`]. + #[buttons(fire, no_comp)] pub flags: u8, /// Client shot id (echoed in the verdict). pub shot: u16, /// Interpolation delay behind `client_tick` the shooter was rendering (ms). pub delay_ms: u16, - /// Unit aim direction (game x, y, z-up). - pub dir: Vec3, + /// Aim direction x (game coordinates, z up). + #[quant(centered = 1.0, bits = 16)] + pub dx: f32, + /// Aim direction y. + #[quant(centered = 1.0, bits = 16)] + pub dy: f32, + /// Aim direction z. + #[quant(centered = 1.0, bits = 16)] + pub dz: f32, } impl ShotInput { - /// Wire payload. - pub fn encode(&self) -> Vec { - let mut out = vec![self.flags]; - out.extend_from_slice(&self.shot.to_le_bytes()); - out.extend_from_slice(&self.delay_ms.to_le_bytes()); - for v in self.dir { - out.extend_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()); + /// A shot along `dir` (normalized here). + pub fn new(flags: u8, shot: u16, delay_ms: u16, dir: Vec3) -> Self { + let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) + .sqrt() + .max(f32::EPSILON); + Self { + flags, + shot, + delay_ms, + dx: dir[0] / len, + dy: dir[1] / len, + dz: dir[2] / len, } - out } - /// Parse a payload; `None` for a wrong length or a zero direction. - pub fn decode(bytes: &[u8]) -> Option { - if bytes.len() != 11 { - return None; - } - let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]); - let axis = |i: usize| f32::from(u16_at(i) as i16) / 32767.0; - let dir = [axis(5), axis(7), axis(9)]; - let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt(); + /// The aim direction. + pub fn dir(&self) -> Vec3 { + [self.dx, self.dy, self.dz] + } + + /// Decode, sanitize and re-normalize a payload (the zone's decode); + /// `None` for a malformed frame or a (near-)zero direction. + pub fn parse(payload: &[u8]) -> Option { + Self::from_payload(payload).and_then(Self::normalized) + } + + /// Re-normalized after quantization; `None` for a (near-)zero direction. + pub fn normalized(self) -> Option { + let [x, y, z] = self.dir(); + let len = (x * x + y * y + z * z).sqrt(); (len > 0.5).then(|| Self { - flags: bytes[0] & (FLAG_FIRE | FLAG_NO_COMP), - shot: u16_at(1), - delay_ms: u16_at(3), - dir: [dir[0] / len, dir[1] / len, dir[2] / len], + dx: x / len, + dy: y / len, + dz: z / len, + ..self }) } } @@ -309,7 +401,7 @@ impl Gallery { shot: &ShotInput, ) -> Option { let shooter = self.shooters.get(&player)?; - let query = HitQuery::ray(shooter.eye(), shot.dir, RANGE); + let query = HitQuery::ray(shooter.eye(), shot.dir(), RANGE); let rewind = ctx.rewind(); let latest = rewind.latest()?.time(); let compensated = shot.flags & FLAG_NO_COMP == 0; @@ -343,32 +435,7 @@ impl Zone for Gallery { type Timer = (); fn schema() -> EntitySchema { - EntitySchema::new() - .kind( - KindDef::new(KIND_SHOOTER, "shooter") - .field("x", POS) - .field("y", POS) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .field("shots", FieldType::U32) - .field("hits", FieldType::U32) - .priority(0.5), - ) - .kind( - KindDef::new(KIND_TARGET, "target") - .field("x", POS) - .field("y", POS) - .field( - "z", - FieldType::QuantF32 { - min: 0.0, - max: 4.0, - bits: 12, - }, - ) - .field("r", FieldType::F32) - .field("flash", FieldType::U8) - .priority(2.0), - ) + schema![ShooterView, TargetView] } fn on_create(ctx: &mut Ctx<'_, Self>, config: GalleryConfig) -> Self { @@ -400,17 +467,15 @@ impl Zone for Gallery { let entity = shooter.entity; self.shooters.insert(player, shooter); ctx.set_view(player, View::new(0.0, 0.0, 100.0)); - send_json_event( - ctx, + ctx.send( player, - EVENT_HELLO, - &json!({ - "entity": entity, - "eye": eye, - "maxRewindMs": MAX_REWIND_MS, - "range": RANGE, - "half": HALF, - }), + &GalleryEvent::Hello { + entity, + eye: eye.to_vec(), + max_rewind_ms: MAX_REWIND_MS as u32, + range: RANGE, + half: HALF, + }, ); } @@ -419,7 +484,7 @@ impl Zone for Gallery { } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - ShotInput::decode(payload).filter(|s| s.flags & FLAG_FIRE != 0) + ShotInput::parse(payload).filter(|s| s.flags & FLAG_FIRE != 0) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { @@ -440,19 +505,18 @@ impl Zone for Gallery { let flash = &mut self.flash[(id - 1) as usize]; *flash = flash.wrapping_add(1); } - send_json_event( - ctx, + let tick = ctx.tick() as u32; + ctx.send( player, - EVENT_SHOT, - &json!({ - "shot": verdict.shot, - "hit": verdict.hit, - "compensated": verdict.compensated, - "ageMs": verdict.age.as_secs_f64() * 1000.0, - "requestedAgeMs": verdict.requested_age.as_secs_f64() * 1000.0, - "clamped": verdict.clamped, - "tick": ctx.tick(), - }), + &GalleryEvent::Shot { + shot: verdict.shot, + hit: verdict.hit, + compensated: verdict.compensated, + age_ms: verdict.age.as_secs_f64() * 1000.0, + requested_age_ms: verdict.requested_age.as_secs_f64() * 1000.0, + clamped: verdict.clamped, + tick, + }, ); } } @@ -471,37 +535,24 @@ impl Zone for Gallery { fn replicate(&self, out: &mut WorldView) { for s in self.shooters.values() { let (x, y) = station_position(s.station); - out.push(EntityState::new( - s.entity, - KIND_SHOOTER, + let view = ShooterView { x, y, - vec![ - FieldValue::F(x), - FieldValue::F(y), - FieldValue::Str(s.name.clone()), - FieldValue::U(s.stats.shots), - FieldValue::U(s.stats.hits), - ], - )); + name: s.name.clone(), + shots: s.stats.shots, + hits: s.stats.hits, + }; + out.add(s.entity, &view); } for (i, p) in self.targets.iter().enumerate() { - out.push( - EntityState::new( - i as u32 + 1, - KIND_TARGET, - p[0], - p[1], - vec![ - FieldValue::F(p[0]), - FieldValue::F(p[1]), - FieldValue::F(p[2]), - FieldValue::F(target_radius(i)), - FieldValue::U(self.flash[i].into()), - ], - ) - .global(), - ); + let view = TargetView { + x: p[0], + y: p[1], + z: p[2], + r: target_radius(i), + flash: self.flash[i], + }; + out.add(i as u32 + 1, &view); } } } diff --git a/examples/game/server/tests/gallery_smoke.rs b/examples/game/server/tests/gallery_smoke.rs index f5822fa6b..ad3d06932 100644 --- a/examples/game/server/tests/gallery_smoke.rs +++ b/examples/game/server/tests/gallery_smoke.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use std::time::Duration; +use distributed_game::GameInput; use distributed_game::{HostConfig, ManualClock, Role, TicketClaims, Viewer, ZoneHost}; use game_demos::gallery::{ self, Gallery, GalleryConfig, ShotInput, FLAG_FIRE, FLAG_NO_COMP, MAX_REWIND_MS, @@ -82,14 +83,14 @@ impl Rig { let d = [seen[0] - x, seen[1] - y, seen[2] - gallery::EYE]; let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); self.seq += 1; - let shot = ShotInput { - flags: FLAG_FIRE | flags, - shot: self.seq as u16, + let shot = ShotInput::new( + FLAG_FIRE | flags, + self.seq as u16, delay_ms, - dir: [d[0] / len, d[1] / len, d[2] / len], - }; + [d[0] / len, d[1] / len, d[2] / len], + ); self.host - .push_input(self.client, self.seq, latest as u32, &shot.encode()); + .push_input(self.client, self.seq, latest as u32, &shot.to_payload()); self.ticks(1); self.host.zone().stats(self.player).unwrap() } @@ -97,22 +98,18 @@ impl Rig { #[test] fn shot_payload_round_trips() { - let shot = ShotInput { - flags: FLAG_FIRE | FLAG_NO_COMP, - shot: 513, - delay_ms: 287, - dir: [0.6, 0.8, 0.0], - }; - let back = ShotInput::decode(&shot.encode()).unwrap(); - assert_eq!((back.flags, back.shot, back.delay_ms), (3, 513, 287)); - assert!((back.dir[0] - 0.6).abs() < 1e-4 && (back.dir[1] - 0.8).abs() < 1e-4); - assert_eq!(ShotInput::decode(&[1, 0, 0]), None, "wrong length"); - assert_eq!(ShotInput::decode(&[1; 10]), None); + let shot = ShotInput::new(FLAG_FIRE | FLAG_NO_COMP | 0x80, 513, 287, [0.6, 0.8, 0.0]); + let back = ShotInput::parse(&shot.to_payload()).unwrap(); assert_eq!( - ShotInput::decode(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), - None, - "zero direction" + (back.flags, back.shot, back.delay_ms), + (3, 513, 287), + "unknown flags cleared" ); + assert!((back.dx - 0.6).abs() < 1e-4 && (back.dy - 0.8).abs() < 1e-4); + assert_eq!(ShotInput::parse(&[1, 0, 0]), None, "truncated"); + assert_eq!(ShotInput::parse(&[1; 10]), None, "trailing bytes"); + let zero = ShotInput::new(FLAG_FIRE, 1, 0, [0.0, 0.0, 0.0]); + assert_eq!(ShotInput::parse(&zero.to_payload()), None, "zero direction"); } #[test] From dc27d73ad63466d3183325e127fdfa6573eb63b1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:47:05 -0500 Subject: [PATCH 185/484] feat(examples): author the freeze with derives and typed facts Freeze reuses the arena PlayerView, derives its other kinds and stamped events, and emits GemCollected / ContentApplied as typed facts. The gem fact now reports which spot was collected instead of a zone-decided reward value. --- examples/game/client/src/freeze/client.ts | 56 +-- examples/game/client/src/freeze/main.ts | 46 +- .../client/src/generated/freeze/client.ts | 49 +++ .../client/src/generated/freeze/events.ts | 141 +++++++ .../game/client/src/generated/freeze/index.ts | 7 + .../game/client/src/generated/freeze/input.ts | 46 ++ .../client/src/generated/freeze/schema.ts | 163 +++++++ .../client/src/generated/freeze/surface.json | 398 ++++++++++++++++++ examples/game/server/src/freeze/mod.rs | 351 ++++++++------- 9 files changed, 1052 insertions(+), 205 deletions(-) create mode 100644 examples/game/client/src/generated/freeze/client.ts create mode 100644 examples/game/client/src/generated/freeze/events.ts create mode 100644 examples/game/client/src/generated/freeze/index.ts create mode 100644 examples/game/client/src/generated/freeze/input.ts create mode 100644 examples/game/client/src/generated/freeze/schema.ts create mode 100644 examples/game/client/src/generated/freeze/surface.json diff --git a/examples/game/client/src/freeze/client.ts b/examples/game/client/src/freeze/client.ts index a7effeb3f..6540209f4 100644 --- a/examples/game/client/src/freeze/client.ts +++ b/examples/game/client/src/freeze/client.ts @@ -18,26 +18,21 @@ * - `Resume` with reason `content_update_aborted`: `lastResume().aborted`. */ import { - GameClient, + type GameClient, type GameSocketFactory, type ResumeMessage, type FreezeMessage } from '@hops-ops/distributed/game'; -import { encodeMoveInput, predictPlayer, type MoveInput } from '../arena/movement.ts'; +import { predictPlayer } from '../arena/movement.ts'; +import * as freeze from '../generated/freeze/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; export const ZONES = { hub: 'freeze-hub', meadow: 'freeze-meadow', ember: 'freeze-ember' } as const; export const DEFAULT_ZONE = ZONES.hub; -/** Event type ids (server `freeze::EVENT_*`). */ -export const EVENT_HELLO = 1; -export const EVENT_GEM = 2; -export const EVENT_BURNED = 3; -export const EVENT_CONTENT = 4; -export const KIND = { player: 'player', slime: 'slime', gem: 'gem', ritual: 'ritual' } as const; -export type Stamp = Readonly<{ zone: string; tick: number; contentVersion: string }>; +/** Provenance of an event or fact (generated from the Rust `Stamp` record). */ +export type Stamp = freeze.Stamp; export type ZoneLayout = Readonly<{ title: string; @@ -61,15 +56,7 @@ export type Pack = Readonly<{ zones: Readonly> & { crystals: readonly (readonly [number, number])[][] }; }>; -export type FreezeHello = Readonly<{ - entity: number; - zone: string; - title: string; - gate: boolean; - host: string; - half: number; - contentVersion: string; -}>; +export type FreezeHello = freeze.HelloEvent; export type LogEntry = Readonly<{ at: number; zone: string; kind: string; text: string; stamp?: Stamp }>; @@ -149,7 +136,7 @@ export type WorldStatus = Readonly<{ }>; export type FreezeClient = Readonly<{ - client: GameClient; + client: GameClient; /** Content pack the client renders. */ pack(): Pack; hello(): FreezeHello | undefined; @@ -168,7 +155,7 @@ export type FreezeClient = Readonly<{ reloads: { zone: string; version: string }[]; log: LogEntry[]; /** Send one command frame (counted when frozen). */ - sendInput(input: MoveInput): number | undefined; + sendInput(input: freeze.MoveInput): number | undefined; onChange(listener: (what: string) => void): () => void; }>; @@ -196,10 +183,8 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< if (log.length > 50) log.shift(); changed('log'); }; - const ease = { mode: 'ease', durationMs: 150 } as const; - const snap = { mode: 'snap' } as const; let reloadingZone = ''; - const client = new GameClient({ + const typed = freeze.createFreezeClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, @@ -213,14 +198,9 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< changed('pack'); return pack.version; }, - prediction: { - encodeInput: (input) => encodeMoveInput(input), - predict: (fields, input) => predictPlayer(fields, input), - corrections: { - player: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } - } - } + prediction: { predict: (fields, input) => predictPlayer(fields, input) } }); + const { client } = typed; client.on('reloadRequired', (zone) => (reloadingZone = zone)); let hello: FreezeHello | undefined; @@ -230,7 +210,7 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< let worldVersion: string | undefined; let dropped = 0; - onJsonEvent(client, EVENT_HELLO, (value) => { + typed.on('hello', (value) => { hello = value; client.setControlledEntity(value.entity); const waiters = helloWaiters; @@ -272,15 +252,9 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< .catch((error: unknown) => note(zone, 'error', String(error))); } }); - onJsonEvent<{ by: string; value: number; stamp: Stamp }>(client, EVENT_GEM, (v, zone) => - note(zone, 'gem', `${v.by} collected a gem (+${v.value})`, v.stamp) - ); - onJsonEvent<{ name: string; stamp: Stamp }>(client, EVENT_BURNED, (v, zone) => - note(zone, 'burned', `${v.name} stepped into lava`, v.stamp) - ); - onJsonEvent<{ from: string; to: string; name: string; stamp: Stamp }>(client, EVENT_CONTENT, (v, zone) => - note(zone, 'content', `zone switched ${v.from} → ${v.to} "${v.name}"`, v.stamp) - ); + typed.on('gem', (v, zone) => note(zone, 'gem', `${v.by} collected a gem (+${v.value})`, v.stamp)); + typed.on('burned', (v, zone) => note(zone, 'burned', `${v.name} stepped into lava`, v.stamp)); + typed.on('content', (v, zone) => note(zone, 'content', `zone switched ${v.from} → ${v.to} "${v.name}"`, v.stamp)); return { client, diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts index 54e34bbcc..33098742f 100644 --- a/examples/game/client/src/freeze/main.ts +++ b/examples/game/client/src/freeze/main.ts @@ -13,12 +13,13 @@ import type { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { BUTTON_DASH, HALF, PILLARS, PLAYER_RADIUS, type MoveInput } from '../arena/movement.ts'; +import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { BUTTON, KIND, gemFields, playerFields, ritualFields, slimeFields, type KindName, type MoveInput } from '../generated/freeze/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; -import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, KIND, ZONES, type Pack, type WorldStatus } from './client.ts'; +import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, ZONES, type Pack, type WorldStatus } from './client.ts'; import './freeze.css'; const params = new URLSearchParams(location.search); @@ -250,12 +251,14 @@ async function main(): Promise { scenery.push(c); } slimeMat = material(scene, `slime-${pack.version}`, pack.slimeColor); - for (const v of visuals.values()) if (v.kind === KIND.slime) v.mesh.material = slimeMat; + for (const v of visuals.values()) if (v.kind === 'slime') v.mesh.material = slimeMat; } const portalLabels = new Set(); // ---- entities ---- - type Visual = { mesh: Mesh; kind: string }; + type Visual = { mesh: Mesh; kind: KindName }; + const kindOf = (entity: RenderedEntity): KindName => + (Object.keys(KIND) as KindName[]).find((k) => KIND[k] === entity.kind) ?? 'player'; const visuals = new Map(); const ritualRing = createRing(scene, 2, '#ff4d6d'); ritualRing.setEnabled(false); @@ -264,17 +267,18 @@ async function main(): Promise { let v = visuals.get(entity.key); if (v !== undefined) return v; let mesh: Mesh; - switch (entity.kindName) { - case KIND.slime: + const kind = kindOf(entity); + switch (kind) { + case 'slime': mesh = MeshBuilder.CreateSphere(entity.key, { diameter: 0.9, segments: 10 }, scene); mesh.scaling.y = 0.6; mesh.material = slimeMat; break; - case KIND.gem: + case 'gem': mesh = MeshBuilder.CreatePolyhedron(entity.key, { type: 1, size: 0.35 }, scene); mesh.material = mats.gem; break; - case KIND.ritual: + case 'ritual': mesh = MeshBuilder.CreateBox(entity.key, { size: 0.01 }, scene); mesh.isVisible = false; break; @@ -282,7 +286,7 @@ async function main(): Promise { mesh = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); mesh.material = mine ? mats.me : mats.other; } - v = { mesh, kind: entity.kindName }; + v = { mesh, kind }; visuals.set(entity.key, v); return v; } @@ -294,7 +298,7 @@ async function main(): Promise { const sendFrame = () => { const s = sampler.sample(); const move = cameraRelative(s, stage.cameraForward()); - lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON_DASH : 0 }; + lastInput = { mx: toAxis(move.x), my: toAxis(move.y), buttons: s.action ? BUTTON.dash : 0 }; freeze.sendInput(lastInput); }; @@ -317,28 +321,34 @@ async function main(): Promise { const mine = hello !== undefined && entity.id === hello.entity; const v = visualFor(entity, mine); seen.add(entity.key); - const x = Number(entity.fields.x ?? 0); - const y = Number(entity.fields.y ?? 0); switch (v.kind) { - case KIND.slime: + case 'slime': { + const { x, y } = slimeFields(entity); v.mesh.position.copyFrom(toWorld(x, y, 0.3 * pack.slimeScale)); v.mesh.scaling.set(pack.slimeScale, 0.6 * pack.slimeScale, pack.slimeScale); break; - case KIND.gem: + } + case 'gem': { + const { x, y } = gemFields(entity); v.mesh.position.copyFrom(toWorld(x, y, 0.8 + 0.15 * Math.sin(now / 300))); v.mesh.rotation.y = now / 600; break; - case KIND.ritual: + } + case 'ritual': { + const { x, y, stuck } = ritualFields(entity); v.mesh.position.copyFrom(toWorld(x, y, 0)); - ritualStuck = Number(entity.fields.stuck ?? 0) === 1; + ritualStuck = stuck === 1; ritualRing.position.copyFrom(toWorld(x, y, 0)); if (ritualStuck) stage.labels.set('ritual', v.mesh, 'RITUAL IN PROGRESS — this zone cannot pause', 0.6, 'ritual'); else stage.labels.delete('ritual'); break; - default: + } + default: { + const { x, y, name } = playerFields(entity); v.mesh.position.copyFrom(toWorld(x, y, 0.9)); - stage.labels.set(entity.key, v.mesh, mine ? `${String(entity.fields.name)} (you)` : String(entity.fields.name ?? ''), 1.4, mine ? 'me' : ''); + stage.labels.set(entity.key, v.mesh, mine ? `${name} (you)` : name, 1.4, mine ? 'me' : ''); if (mine) me = { x, y }; + } } v.mesh.setEnabled(!entity.stale); } diff --git a/examples/game/client/src/generated/freeze/client.ts b/examples/game/client/src/generated/freeze/client.ts new file mode 100644 index 000000000..81195ec05 --- /dev/null +++ b/examples/game/client/src/generated/freeze/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type MoveInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type FreezePredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type FreezeClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: FreezePredictionOptions }>; + +export type FreezeClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: MoveInput): number | undefined; +}>; + +/** A `GameClient` for the `freeze` surface with its input encoder and correction defaults. */ +export function createFreezeClient(options: FreezeClientOptions): FreezeClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/freeze/events.ts b/examples/game/client/src/generated/freeze/events.ts new file mode 100644 index 000000000..b7044260e --- /dev/null +++ b/examples/game/client/src/generated/freeze/events.ts @@ -0,0 +1,141 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `Stamp` (`#[derive(GameRecord)]`). */ +export interface Stamp { + readonly zone: string; + readonly tick: number; + readonly contentVersion: string; +} + +const STAMP_TYPE: WireType = { + type: 'record', + fields: [ + ['zone', { type: 'short_str' }], + ['tick', { type: 'u64' }], + ['contentVersion', { type: 'short_str' }], + ] +}; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly zone: string; + readonly title: string; + readonly gate: boolean; + readonly host: string; + readonly half: number; + readonly contentVersion: string; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['zone', { type: 'short_str' }], + ['title', { type: 'short_str' }], + ['gate', { type: 'bool' }], + ['host', { type: 'short_str' }], + ['half', { type: 'f32' }], + ['contentVersion', { type: 'short_str' }], +]; + +/** Event `gem` (id 2). */ +export interface GemEvent { + readonly by: string; + readonly value: number; + readonly stamp: Stamp; +} + +const GEM_LAYOUT: PayloadLayout = [ + ['by', { type: 'short_str' }], + ['value', { type: 'u32' }], + ['stamp', STAMP_TYPE], +]; + +/** Event `burned` (id 3). */ +export interface BurnedEvent { + readonly name: string; + readonly stamp: Stamp; +} + +const BURNED_LAYOUT: PayloadLayout = [ + ['name', { type: 'short_str' }], + ['stamp', STAMP_TYPE], +]; + +/** Event `content` (id 4). */ +export interface ContentEvent { + readonly from: string; + readonly to: string; + readonly name: string; + readonly stamp: Stamp; +} + +const CONTENT_LAYOUT: PayloadLayout = [ + ['from', { type: 'short_str' }], + ['to', { type: 'short_str' }], + ['name', { type: 'short_str' }], + ['stamp', STAMP_TYPE], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + gem: 2, + burned: 3, + content: 4, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + gem: GemEvent; + burned: BurnedEvent; + content: ContentEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + gem: { + id: 2, + name: 'gem', + encode: (value) => encodePayload(GEM_LAYOUT, value), + decode: (payload) => decodePayload(GEM_LAYOUT, payload) as unknown as GemEvent + }, + burned: { + id: 3, + name: 'burned', + encode: (value) => encodePayload(BURNED_LAYOUT, value), + decode: (payload) => decodePayload(BURNED_LAYOUT, payload) as unknown as BurnedEvent + }, + content: { + id: 4, + name: 'content', + encode: (value) => encodePayload(CONTENT_LAYOUT, value), + decode: (payload) => decodePayload(CONTENT_LAYOUT, payload) as unknown as ContentEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/freeze/index.ts b/examples/game/client/src/generated/freeze/index.ts new file mode 100644 index 000000000..2a1459e77 --- /dev/null +++ b/examples/game/client/src/generated/freeze/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/freeze/input.ts b/examples/game/client/src/generated/freeze/input.ts new file mode 100644 index 000000000..9fdaa5918 --- /dev/null +++ b/examples/game/client/src/generated/freeze/input.ts @@ -0,0 +1,46 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `MoveInput` input frame (`#[derive(GameInput)]`). */ +export interface MoveInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; +} + +export type Input = MoveInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + dash: 1, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 1 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: MoveInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): MoveInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as MoveInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: MoveInput): MoveInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/freeze/schema.ts b/examples/game/client/src/generated/freeze/schema.ts new file mode 100644 index 000000000..535b284bc --- /dev/null +++ b/examples/game/client/src/generated/freeze/schema.ts @@ -0,0 +1,163 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + slime: 2, + gem: 3, + ritual: 4, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vx: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vy: number; + /** `u8` */ + readonly dash: number; + /** `u8` */ + readonly cd: number; + /** `short_str`, priority 0.2 */ + readonly name: string; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + vy: fieldNumber(f, 'vy'), + dash: fieldNumber(f, 'dash'), + cd: fieldNumber(f, 'cd'), + name: fieldString(f, 'name'), + }; +} + +/** `slime` (kind 2, priority 1). */ +export interface SlimeFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; + /** `angle / 8 bits` */ + readonly yaw: number; +} + +/** True for a `slime` entity. */ +export function isSlime(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `slime` entity (rendered or replica). */ +export function slimeFields(entity: { readonly fields: EntityFields }): SlimeFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + yaw: fieldNumber(f, 'yaw'), + }; +} + +/** `gem` (kind 3, priority 1). */ +export interface GemFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; +} + +/** True for a `gem` entity. */ +export function isGem(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `gem` entity (rendered or replica). */ +export function gemFields(entity: { readonly fields: EntityFields }): GemFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + }; +} + +/** `ritual` (kind 4, priority 1). */ +export interface RitualFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; + /** `u8` */ + readonly stuck: number; +} + +/** True for a `ritual` entity. */ +export function isRitual(entity: { readonly kind: number }): boolean { + return entity.kind === 4; +} + +/** Typed fields of a `ritual` entity (rendered or replica). */ +export function ritualFields(entity: { readonly fields: EntityFields }): RitualFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + stuck: fieldNumber(f, 'stuck'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + dash: { type: 'u8' }, + cd: { type: 'u8' }, + name: { type: 'short_str' }, + }, + slime: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + yaw: { type: 'angle', bits: 8 }, + }, + gem: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + }, + ritual: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + stuck: { type: 'u8' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + vy: { mode: 'snap' }, + dash: { mode: 'snap' }, + cd: { mode: 'snap' }, + name: { mode: 'replace' }, + }, +}; diff --git a/examples/game/client/src/generated/freeze/surface.json b/examples/game/client/src/generated/freeze/surface.json new file mode 100644 index 000000000..cb593fa52 --- /dev/null +++ b/examples/game/client/src/generated/freeze/surface.json @@ -0,0 +1,398 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "zone", + "type": { + "type": "short_str" + } + }, + { + "name": "title", + "type": { + "type": "short_str" + } + }, + { + "name": "gate", + "type": { + "type": "bool" + } + }, + { + "name": "host", + "type": { + "type": "short_str" + } + }, + { + "name": "half", + "type": { + "type": "f32" + } + }, + { + "name": "content_version", + "type": { + "type": "short_str" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "gem", + "payload": { + "fields": [ + { + "name": "by", + "type": { + "type": "short_str" + } + }, + { + "name": "value", + "type": { + "type": "u32" + } + }, + { + "name": "stamp", + "type": { + "name": "Stamp", + "type": "record" + } + } + ], + "kind": "fields" + } + }, + { + "id": 3, + "name": "burned", + "payload": { + "fields": [ + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "stamp", + "type": { + "name": "Stamp", + "type": "record" + } + } + ], + "kind": "fields" + } + }, + { + "id": 4, + "name": "content", + "payload": { + "fields": [ + { + "name": "from", + "type": { + "type": "short_str" + } + }, + { + "name": "to", + "type": { + "type": "short_str" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "stamp", + "type": { + "name": "Stamp", + "type": "record" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash" + ], + "name": "buttons", + "type": { + "type": "u8" + } + } + ], + "name": "MoveInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vy", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "dash", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "cd", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "yaw", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + } + ], + "id": 2, + "name": "slime", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + } + ], + "id": 3, + "name": "gem", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "stuck", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 4, + "name": "ritual", + "priority": 1.0 + } + ], + "name": "freeze", + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "zone", + "type": { + "type": "short_str" + } + }, + { + "name": "tick", + "type": { + "type": "u64" + } + }, + { + "name": "content_version", + "type": { + "type": "short_str" + } + } + ], + "name": "Stamp" + } + ], + "schemaVersion": 1 +} diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs index e197fee2e..75a79a9f0 100644 --- a/examples/game/server/src/freeze/mod.rs +++ b/examples/game/server/src/freeze/mod.rs @@ -24,11 +24,12 @@ //! Movement is the Arena's shared step ([`crate::arena::movement`], predicted //! by the client with the same TypeScript twin). //! -//! Entities: 1 `player` (Arena fields), 2 `slime` (x y yaw), 3 `gem` (x y), -//! 4 `ritual` (global: x y stuck). Events (JSON): [`EVENT_HELLO`], -//! [`EVENT_GEM`], [`EVENT_BURNED`], [`EVENT_CONTENT`]; gameplay events carry -//! `ctx.stamp()` (zone, tick, content version). Gems and content switches are -//! also durable facts stamped by the host. +//! Entities: 1 `player` (the Arena's [`PlayerView`]), 2 `slime` (x y yaw), +//! 3 `gem` (x y), 4 `ritual` (global: x y stuck). Events: [`FreezeEvent`]; +//! gameplay events carry `ctx.stamp()` (zone, tick, content version). Gems +//! and content switches are also typed durable facts ([`GemCollected`], +//! [`ContentApplied`]) stamped by the host. The browser client is generated +//! from [`game_surface`]. pub mod content; pub mod world; @@ -39,31 +40,162 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::{ - Ctx, EntitySchema, EntityState, Fact, FactStamp, FieldType, FieldValue, GameInput, - InputCredits, KindDef, LeaveReason, PlayerId, StalePolicy, View, WorldView, Zone, + schema, Ctx, EntitySchema, FactCommand, FactStamp, GameEvent, GameInput, GameRecord, + GameSurface, InputCredits, LeaveReason, PlayerId, Replicated, StalePolicy, View, WorldView, + Zone, }; -use serde_json::{json, Value}; +use serde::Serialize; use crate::arena::movement::{self, MoveInput, MoveState}; -use crate::common::{broadcast_json_event, send_json_event, Demo, Guests}; +use crate::arena::PlayerView; +use crate::common::{Demo, Guests}; use content::{Hazard, Pack, ZoneKind}; -/// Player kind (Arena fields: the client predicts it with Arena's step). -pub const KIND_PLAYER: u16 = 1; -/// Slime kind. -pub const KIND_SLIME: u16 = 2; -/// Gem kind. -pub const KIND_GEM: u16 = 3; -/// Ritual circle (global; `stuck` = 1 while it holds the zone). -pub const KIND_RITUAL: u16 = 4; -/// `{"entity", "zone", "title", "gate", "host", "half", "contentVersion"}`. -pub const EVENT_HELLO: u32 = 1; -/// `{"by", "value", "stamp"}` — someone collected a gem. -pub const EVENT_GEM: u32 = 2; -/// `{"name", "stamp"}` — someone stepped into lava. -pub const EVENT_BURNED: u32 = 3; -/// `{"from", "to", "name", "stamp"}` — the zone switched content. -pub const EVENT_CONTENT: u32 = 4; +/// A wandering slime. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "slime", id = 2)] +pub struct SlimeView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub y: f32, + /// Heading. + #[angle(bits = 8)] + pub yaw: f32, +} + +/// A gem waiting to be collected (global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "gem", id = 3, global)] +pub struct GemView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub y: f32, +} + +/// The ritual circle (global; `stuck` = 1 while it holds the zone). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "ritual", id = 4, global)] +pub struct RitualView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + pub y: f32, + /// 1 while the ritual refuses the freeze. + pub stuck: u8, +} + +/// Provenance of a gameplay event: which zone, tick and content version +/// produced it. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Stamp { + /// Zone id. + pub zone: String, + /// Zone tick. + pub tick: u64, + /// Content version in effect. + pub content_version: String, +} + +impl From for Stamp { + fn from(stamp: FactStamp) -> Self { + Self { + zone: stamp.zone_id, + tick: stamp.tick, + content_version: stamp.content_version, + } + } +} + +/// The Freeze's events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum FreezeEvent { + /// To a joining player (also after a handoff). + #[game_event(id = 1)] + Hello { + /// Own entity id. + entity: u32, + /// Zone id. + zone: String, + /// Zone title. + title: String, + /// This zone is the safe-room gate. + gate: bool, + /// Host id (`alpha` / `beta`). + host: String, + /// Floor half extent (m). + half: f32, + /// Content version the zone runs. + content_version: String, + }, + /// Someone collected a gem. + #[game_event(id = 2)] + Gem { + /// Collector's name. + by: String, + /// Gem value under the zone's content pack. + value: u32, + /// Provenance. + stamp: Stamp, + }, + /// Someone stepped into lava. + #[game_event(id = 3)] + Burned { + /// Who. + name: String, + /// Provenance. + stamp: Stamp, + }, + /// The zone switched content. + #[game_event(id = 4)] + Content { + /// Previous version. + from: String, + /// New version. + to: String, + /// New pack name. + name: String, + /// Provenance. + stamp: Stamp, + }, +} + +/// The Freeze's client surface. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("freeze").events::() +} + +/// Durable command recording a collected gem. +pub const GEM_COLLECTED: &str = "freeze.gem_collected"; +/// Durable command recording a content switch. +pub const CONTENT_APPLIED: &str = "freeze.content_applied"; + +/// [`GEM_COLLECTED`] input: *which* gem spot was collected. Its value is a +/// rule of the content pack at the fact's stamped content version, for the +/// handler to apply — the zone never reports a reward amount. +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = GEM_COLLECTED)] +pub struct GemCollected { + /// Gem spot of the zone layout. + pub spot: u32, +} + +/// [`CONTENT_APPLIED`] input (a zone/system fact). +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = CONTENT_APPLIED, key(to))] +pub struct ContentApplied { + /// Previous version. + pub from: String, + /// New version. + pub to: String, +} /// Content version every host starts on. pub const INITIAL_VERSION: &str = "v1"; const VIEW_RADIUS: f32 = 40.0; @@ -159,10 +291,6 @@ impl FreezeZone { self.players.get(&player).map(|p| (p.state.x, p.state.y)) } - fn stamp_json(stamp: &FactStamp) -> Value { - json!({ "zone": stamp.zone_id, "tick": stamp.tick, "contentVersion": stamp.content_version }) - } - fn arrival_point(&self, from_zone: &str) -> (f32, f32) { self.config .kind @@ -195,20 +323,16 @@ impl FreezeZone { }, ); ctx.set_view(player, View::new(at.0, at.1, VIEW_RADIUS)); - send_json_event( - ctx, - player, - EVENT_HELLO, - &json!({ - "entity": entity, - "zone": self.zone_id, - "title": self.config.kind.title(), - "gate": self.config.kind == ZoneKind::Hub, - "host": self.config.host, - "half": movement::HALF, - "contentVersion": ctx.content_version(), - }), - ); + let hello = FreezeEvent::Hello { + entity, + zone: self.zone_id.clone(), + title: self.config.kind.title().into(), + gate: self.config.kind == ZoneKind::Hub, + host: self.config.host.clone(), + half: movement::HALF, + content_version: ctx.content_version().into(), + }; + ctx.send(player, &hello); } fn random_point(ctx: &mut Ctx<'_, Self>) -> (f32, f32) { @@ -231,40 +355,7 @@ impl Zone for FreezeZone { type Timer = (); fn schema() -> EntitySchema { - let small = FieldType::QuantF32 { - min: -movement::HALF, - max: movement::HALF, - bits: 14, - }; - EntitySchema::new() - .kind( - KindDef::new(KIND_PLAYER, "player") - .field("x", movement::POS) - .field("y", movement::POS) - .field("vx", movement::VEL) - .field("vy", movement::VEL) - .field("dash", FieldType::U8) - .field("cd", FieldType::U8) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .priority(2.0), - ) - .kind( - KindDef::new(KIND_SLIME, "slime") - .field("x", small) - .field("y", small) - .field("yaw", FieldType::Angle { bits: 8 }), - ) - .kind( - KindDef::new(KIND_GEM, "gem") - .field("x", small) - .field("y", small), - ) - .kind( - KindDef::new(KIND_RITUAL, "ritual") - .field("x", small) - .field("y", small) - .field("stuck", FieldType::U8), - ) + schema![PlayerView, SlimeView, GemView, RitualView] } fn on_create(ctx: &mut Ctx<'_, Self>, config: FreezeConfig) -> Self { @@ -362,8 +453,11 @@ impl Zone for FreezeZone { y: sy, ..MoveState::default() }; - let event = json!({ "name": player.name, "stamp": Self::stamp_json(&ctx.stamp()) }); - broadcast_json_event(ctx, EVENT_BURNED, &event); + let event = FreezeEvent::Burned { + name: player.name.clone(), + stamp: ctx.stamp().into(), + }; + ctx.broadcast(&event); } let player = self.players.get_mut(&id).expect("present"); let (x, y) = (player.state.x, player.state.y); @@ -376,16 +470,15 @@ impl Zone for FreezeZone { { gem.respawn_at = Some(now + GEM_RESPAWN); self.collected += 1; - let value = self.pack.gem_value; - let key = format!("gem:{}:{}:{}", self.zone_id, ctx.tick(), gem.spot); - let _ = ctx.emit_fact_for( - id, - Fact::new(key, "freeze.gem_collected", json!({ "value": value })), - ); - let event = json!({ - "by": player.name, "value": value, "stamp": Self::stamp_json(&ctx.stamp()), - }); - broadcast_json_event(ctx, EVENT_GEM, &event); + // Keyed by tick + emission order (a spot respawns). + let spot = gem.spot as u32; + let _ = ctx.emit(id, GemCollected { spot }); + let event = FreezeEvent::Gem { + by: player.name.clone(), + value: self.pack.gem_value, + stamp: ctx.stamp().into(), + }; + ctx.broadcast(&event); } } // Portals. @@ -429,61 +522,26 @@ impl Zone for FreezeZone { fn replicate(&self, out: &mut WorldView) { for p in self.players.values() { - let s = p.state; - out.push(EntityState::new( - p.entity, - KIND_PLAYER, - s.x, - s.y, - vec![ - FieldValue::F(s.x), - FieldValue::F(s.y), - FieldValue::F(s.vx), - FieldValue::F(s.vy), - FieldValue::U(s.dash.into()), - FieldValue::U(s.cooldown.into()), - FieldValue::Str(p.name.clone()), - ], - )); + // The Arena's capsule, but culled by the view radius here. + out.add(p.entity, &PlayerView::of(&p.state, &p.name)) + .local(); } for (i, s) in self.slimes.iter().enumerate() { - out.push(EntityState::new( - 1 + i as u32, - KIND_SLIME, - s.x, - s.y, - vec![FieldValue::F(s.x), FieldValue::F(s.y), FieldValue::F(s.yaw)], - )); + let view = SlimeView { + x: s.x, + y: s.y, + yaw: s.yaw, + }; + out.add(1 + i as u32, &view); } let spots = self.config.kind.gem_spots(); for gem in self.gems.iter().filter(|g| g.respawn_at.is_none()) { let (x, y) = spots[gem.spot]; - out.push( - EntityState::new( - 100 + gem.spot as u32, - KIND_GEM, - x, - y, - vec![FieldValue::F(x), FieldValue::F(y)], - ) - .global(), - ); + out.add(100 + gem.spot as u32, &GemView { x, y }); } - let (rx, ry) = self.config.kind.ritual(); - out.push( - EntityState::new( - RITUAL_ID, - KIND_RITUAL, - rx, - ry, - vec![ - FieldValue::F(rx), - FieldValue::F(ry), - FieldValue::U(self.config.rituals.is_stuck(&self.zone_id).into()), - ], - ) - .global(), - ); + let (x, y) = self.config.kind.ritual(); + let stuck = u8::from(self.config.rituals.is_stuck(&self.zone_id)); + out.add(RITUAL_ID, &RitualView { x, y, stuck }); } fn is_gate(&self) -> bool { @@ -499,16 +557,17 @@ impl Zone for FreezeZone { self.pack = pack; } // A meaningful world transition: persisted (stamped with `to`). - let key = format!("content:{}:{to}", self.zone_id); - let _ = ctx.emit_fact(Fact::new( - key, - "freeze.content_applied", - json!({ "from": from, "to": to }), - )); - let event = json!({ - "from": from, "to": to, "name": self.pack.name, "stamp": Self::stamp_json(&ctx.stamp()), + let _ = ctx.emit_zone(ContentApplied { + from: from.into(), + to: to.into(), }); - broadcast_json_event(ctx, EVENT_CONTENT, &event); + let event = FreezeEvent::Content { + from: from.into(), + to: to.into(), + name: self.pack.name.clone(), + stamp: ctx.stamp().into(), + }; + ctx.broadcast(&event); } fn has_pending_work(&self) -> bool { From 03c83bd8047288b5cef965b12bf50dddfa483e51 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:51:41 -0500 Subject: [PATCH 186/484] feat(examples): author the endless grid with derives Grid's walker/critter/marker kinds, MoveInput and the struct-form GridHello event are derived; the client predicts with the generated input sanitize and quantization and reads typed fields. --- .../game/client/src/generated/grid/client.ts | 49 +++ .../game/client/src/generated/grid/events.ts | 74 +++++ .../game/client/src/generated/grid/index.ts | 7 + .../game/client/src/generated/grid/input.ts | 47 +++ .../game/client/src/generated/grid/schema.ts | 129 ++++++++ .../client/src/generated/grid/surface.json | 287 ++++++++++++++++++ examples/game/client/src/grid/client.ts | 56 +--- examples/game/client/src/grid/main.ts | 34 ++- examples/game/client/src/grid/world.ts | 29 +- examples/game/server/src/grid/mod.rs | 202 ++++++------ examples/game/server/src/grid/world.rs | 34 +-- examples/game/server/tests/grid_fixture.rs | 3 +- examples/game/server/tests/grid_smoke.rs | 46 +-- 13 files changed, 777 insertions(+), 220 deletions(-) create mode 100644 examples/game/client/src/generated/grid/client.ts create mode 100644 examples/game/client/src/generated/grid/events.ts create mode 100644 examples/game/client/src/generated/grid/index.ts create mode 100644 examples/game/client/src/generated/grid/input.ts create mode 100644 examples/game/client/src/generated/grid/schema.ts create mode 100644 examples/game/client/src/generated/grid/surface.json diff --git a/examples/game/client/src/generated/grid/client.ts b/examples/game/client/src/generated/grid/client.ts new file mode 100644 index 000000000..2e09d5619 --- /dev/null +++ b/examples/game/client/src/generated/grid/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type MoveInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type GridPredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type GridClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: GridPredictionOptions }>; + +export type GridClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: MoveInput): number | undefined; +}>; + +/** A `GameClient` for the `grid` surface with its input encoder and correction defaults. */ +export function createGridClient(options: GridClientOptions): GridClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/grid/events.ts b/examples/game/client/src/generated/grid/events.ts new file mode 100644 index 000000000..9ba78a6b4 --- /dev/null +++ b/examples/game/client/src/generated/grid/events.ts @@ -0,0 +1,74 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly zone: string; + readonly cell: readonly number[]; + readonly host: string; + readonly seed: number; + readonly contentVersion: number; + readonly cellSize: number; + readonly entity: number | undefined; + readonly restored: boolean; + readonly restores: number; + readonly hibernatedForMs: number | undefined; + readonly restoredCritters: number; + readonly restoredMarkers: number; + readonly activatedAt: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['zone', { type: 'short_str' }], + ['cell', { type: 'list', item: { type: 'i32' } }], + ['host', { type: 'short_str' }], + ['seed', { type: 'u32' }], + ['contentVersion', { type: 'u32' }], + ['cellSize', { type: 'f32' }], + ['entity', { type: 'optional', item: { type: 'u32' } }], + ['restored', { type: 'bool' }], + ['restores', { type: 'u32' }], + ['hibernatedForMs', { type: 'optional', item: { type: 'u64' } }], + ['restoredCritters', { type: 'u32' }], + ['restoredMarkers', { type: 'u32' }], + ['activatedAt', { type: 'u64' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/grid/index.ts b/examples/game/client/src/generated/grid/index.ts new file mode 100644 index 000000000..690a1ce7a --- /dev/null +++ b/examples/game/client/src/generated/grid/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/grid/input.ts b/examples/game/client/src/generated/grid/input.ts new file mode 100644 index 000000000..d1fe024f2 --- /dev/null +++ b/examples/game/client/src/generated/grid/input.ts @@ -0,0 +1,47 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `MoveInput` input frame (`#[derive(GameInput)]`). */ +export interface MoveInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; +} + +export type Input = MoveInput; + +/** Button bits (`#[buttons(..)]`). */ +export const BUTTON = { + sprint: 1, + mark: 2, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 3 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: MoveInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): MoveInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as MoveInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: MoveInput): MoveInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/grid/schema.ts b/examples/game/client/src/generated/grid/schema.ts new file mode 100644 index 000000000..c3e5a4684 --- /dev/null +++ b/examples/game/client/src/generated/grid/schema.ts @@ -0,0 +1,129 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + walker: 1, + critter: 2, + marker: 3, +} as const; + +export type KindName = keyof typeof KIND; + +/** `walker` (kind 1, priority 2). */ +export interface WalkerFields { + /** `quant [-8, 40] / 18 bits` */ + readonly x: number; + /** `quant [-8, 40] / 18 bits` */ + readonly y: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u8` */ + readonly hue: number; +} + +/** True for a `walker` entity. */ +export function isWalker(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `walker` entity (rendered or replica). */ +export function walkerFields(entity: { readonly fields: EntityFields }): WalkerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + name: fieldString(f, 'name'), + hue: fieldNumber(f, 'hue'), + }; +} + +/** `critter` (kind 2, priority 1). */ +export interface CritterFields { + /** `quant [-8, 40] / 18 bits` */ + readonly x: number; + /** `quant [-8, 40] / 18 bits` */ + readonly y: number; + /** `angle / 8 bits` */ + readonly yaw: number; + /** `u8` */ + readonly hue: number; +} + +/** True for a `critter` entity. */ +export function isCritter(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `critter` entity (rendered or replica). */ +export function critterFields(entity: { readonly fields: EntityFields }): CritterFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + yaw: fieldNumber(f, 'yaw'), + hue: fieldNumber(f, 'hue'), + }; +} + +/** `marker` (kind 3, priority 1). */ +export interface MarkerFields { + /** `quant [-8, 40] / 18 bits` */ + readonly x: number; + /** `quant [-8, 40] / 18 bits` */ + readonly y: number; + /** `short_str` */ + readonly label: string; + /** `u8` */ + readonly hue: number; +} + +/** True for a `marker` entity. */ +export function isMarker(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `marker` entity (rendered or replica). */ +export function markerFields(entity: { readonly fields: EntityFields }): MarkerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + label: fieldString(f, 'label'), + hue: fieldNumber(f, 'hue'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + walker: { + x: { type: 'quant', min: -8, max: 40, bits: 18 }, + y: { type: 'quant', min: -8, max: 40, bits: 18 }, + name: { type: 'short_str' }, + hue: { type: 'u8' }, + }, + critter: { + x: { type: 'quant', min: -8, max: 40, bits: 18 }, + y: { type: 'quant', min: -8, max: 40, bits: 18 }, + yaw: { type: 'angle', bits: 8 }, + hue: { type: 'u8' }, + }, + marker: { + x: { type: 'quant', min: -8, max: 40, bits: 18 }, + y: { type: 'quant', min: -8, max: 40, bits: 18 }, + label: { type: 'short_str' }, + hue: { type: 'u8' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + walker: { + x: { mode: 'ease', durationMs: 120 }, + y: { mode: 'ease', durationMs: 120 }, + name: { mode: 'replace' }, + hue: { mode: 'replace' }, + }, +}; diff --git a/examples/game/client/src/generated/grid/surface.json b/examples/game/client/src/generated/grid/surface.json new file mode 100644 index 000000000..eade6c48d --- /dev/null +++ b/examples/game/client/src/generated/grid/surface.json @@ -0,0 +1,287 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "zone", + "type": { + "type": "short_str" + } + }, + { + "name": "cell", + "type": { + "item": { + "type": "i32" + }, + "type": "list" + } + }, + { + "name": "host", + "type": { + "type": "short_str" + } + }, + { + "name": "seed", + "type": { + "type": "u32" + } + }, + { + "name": "content_version", + "type": { + "type": "u32" + } + }, + { + "name": "cell_size", + "type": { + "type": "f32" + } + }, + { + "name": "entity", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "restored", + "type": { + "type": "bool" + } + }, + { + "name": "restores", + "type": { + "type": "u32" + } + }, + { + "name": "hibernated_for_ms", + "type": { + "item": { + "type": "u64" + }, + "type": "optional" + } + }, + { + "name": "restored_critters", + "type": { + "type": "u32" + } + }, + { + "name": "restored_markers", + "type": { + "type": "u32" + } + }, + { + "name": "activated_at", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "sprint", + "mark" + ], + "name": "buttons", + "type": { + "type": "u8" + } + } + ], + "name": "MoveInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 120, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 120, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "hue", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 1, + "name": "walker", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "yaw", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": null, + "name": "hue", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 2, + "name": "critter", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 40.0, + "min": -8.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "label", + "priority": 1.0, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "hue", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 3, + "name": "marker", + "priority": 1.0 + } + ], + "name": "grid", + "protocolVersion": 1, + "records": [], + "schemaVersion": 1 +} diff --git a/examples/game/client/src/grid/client.ts b/examples/game/client/src/grid/client.ts index dbf528e07..9f20d6203 100644 --- a/examples/game/client/src/grid/client.ts +++ b/examples/game/client/src/grid/client.ts @@ -13,43 +13,16 @@ * - per-zone hello info (host, restored-from-hibernation …) and the * `/dev/grid/map` world map. */ -import { GameClient, type GameSocketFactory, type RenderedEntity } from '@hops-ops/distributed/game'; +import { fieldNumber, type GameClient, type GameSocketFactory, type RenderedEntity } from '@hops-ops/distributed/game'; +import * as grid from '../generated/grid/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; -import { - cellProps, - encodeMoveInput, - parseZone, - step, - zoneId, - CELL, - DEFAULT_SEED, - type Cell, - type MoveInput, - type Prop -} from './world.ts'; +import { cellProps, parseZone, step, zoneId, CELL, DEFAULT_SEED, type Cell, type MoveInput, type Prop } from './world.ts'; export const DEFAULT_ZONE = 'grid.0.0'; -/** Event type ids (server `grid::EVENT_*`). */ -export const EVENT_HELLO = 1; -export const KIND = { walker: 'walker', critter: 'critter', marker: 'marker' } as const; -export type GridHello = Readonly<{ - zone: string; - cell: [number, number]; - host: string; - seed: number; - contentVersion: number; - cellSize: number; - entity: number | null; - restored: boolean; - restores: number; - hibernatedForMs: number | null; - restoredCritters: number; - restoredMarkers: number; - activatedAt: number; -}>; +/** A zone's hello (generated from the Rust `GridHello` event). */ +export type GridHello = grid.HelloEvent; export type MapCell = Readonly<{ x: number; @@ -129,25 +102,21 @@ export function createGridClient(options: GridClientOptions): GridClient { } return list; }; - const num = (v: unknown) => (typeof v === 'number' ? v : 0); - const ease = { mode: 'ease', durationMs: 120 } as const; - - const client = new GameClient({ + const typed = grid.createGridClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 1000, inputDtMs: 1000 / 30, prediction: { - encodeInput: (input) => encodeMoveInput(input), predict: (fields, input) => { const cell = authorityCell ?? [0, 0]; - const [x, y] = step(num(fields.x), num(fields.y), input, props(cell)); + const [x, y] = step(fieldNumber(fields, 'x'), fieldNumber(fields, 'y'), input, props(cell)); return { x, y }; - }, - corrections: { [KIND.walker]: { x: ease, y: ease, name: { mode: 'replace' }, hue: { mode: 'replace' } } } + } } }); + const { client } = typed; let resolveReady: (h: GridHello) => void = () => undefined; const ready = new Promise((resolve) => (resolveReady = resolve)); @@ -174,10 +143,10 @@ export function createGridClient(options: GridClientOptions): GridClient { client.on('handoffComplete', () => { handoffs += 1; }); - onJsonEvent(client, EVENT_HELLO, (hello, zone) => { + typed.on('hello', (hello, zone) => { infos.set(zone, hello); seed = hello.seed; - if (hello.entity !== null && zone === client.authority?.zoneId) { + if (hello.entity !== undefined && zone === client.authority?.zoneId) { client.setControlledEntity(hello.entity); resolveReady(hello); } @@ -197,7 +166,8 @@ export function createGridClient(options: GridClientOptions): GridClient { worldOf(entity) { const cell = parseZone(entity.zoneId); if (cell === undefined) return undefined; - return { x: cell[0] * CELL + num(entity.fields.x), y: cell[1] * CELL + num(entity.fields.y) }; + // Every grid kind has local x / y. + return { x: cell[0] * CELL + fieldNumber(entity.fields, 'x'), y: cell[1] * CELL + fieldNumber(entity.fields, 'y') }; }, handoffs: () => handoffs, ready, diff --git a/examples/game/client/src/grid/main.ts b/examples/game/client/src/grid/main.ts index a8f699b86..88e45a1e3 100644 --- a/examples/game/client/src/grid/main.ts +++ b/examples/game/client/src/grid/main.ts @@ -31,7 +31,8 @@ import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material } from '../shared/scene.ts'; -import { createGridClient, DEFAULT_ZONE, KIND, type GridHello, type MapCell, type WorldMap } from './client.ts'; +import { critterFields, isCritter, isMarker, markerFields, walkerFields } from '../generated/grid/index.ts'; +import { createGridClient, DEFAULT_ZONE, type GridHello, type MapCell, type WorldMap } from './client.ts'; import { BIOMES, BUTTON_MARK, @@ -245,19 +246,23 @@ function hueMat(hue: number, kind: string): StandardMaterial { const meMat = material(scene, 'me', '#ffffff'); meMat.emissiveColor = Color3.FromHexString('#2a4c66'); -type Visual = { mesh: AbstractMesh; kind: string }; +type Visual = { mesh: AbstractMesh; kind: 'walker' | 'critter' | 'marker' }; const visuals = new Map(); function visualFor(entity: RenderedEntity, mine: boolean): Visual { let visual = visuals.get(entity.key); - const hue = typeof entity.fields.hue === 'number' ? entity.fields.hue : 0; if (visual !== undefined) return visual; let mesh: AbstractMesh; - if (entity.kindName === KIND.critter) { + let kind: Visual['kind'] = 'walker'; + if (isCritter(entity)) { + const { hue } = critterFields(entity); + kind = 'critter'; const body = MeshBuilder.CreateSphere(entity.key, { diameter: 0.7, segments: 8 }, scene); body.scaling.set(1.2, 0.7, 0.8); body.material = hueMat(hue, 'critter'); mesh = body; - } else if (entity.kindName === KIND.marker) { + } else if (isMarker(entity)) { + const { hue } = markerFields(entity); + kind = 'marker'; const pole = MeshBuilder.CreateCylinder(entity.key, { diameter: 0.08, height: 2.2 }, scene); pole.bakeTransformIntoVertices(Matrix.Translation(0, 1.1, 0)); const flag = MeshBuilder.CreateBox(`${entity.key}-flag`, { width: 0.8, height: 0.5, depth: 0.04 }, scene); @@ -266,11 +271,12 @@ function visualFor(entity: RenderedEntity, mine: boolean): Visual { flag.material = hueMat(hue, 'marker'); mesh = pole; } else { + const { hue } = walkerFields(entity); const capsule = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); capsule.material = mine ? meMat : hueMat(hue, 'walker'); mesh = capsule; } - visual = { mesh, kind: entity.kindName }; + visual = { mesh, kind }; visuals.set(entity.key, visual); return visual; } @@ -303,7 +309,7 @@ grid.onRestored((hello) => { const burst = restoredBurst; restoredBurst = []; const here = burst.find((h) => h.zone === client.authority?.zoneId) ?? burst[0]!; - const slept = here.hibernatedForMs === null ? '' : ` after ${(here.hibernatedForMs / 1000).toFixed(1)} s`; + const slept = here.hibernatedForMs === undefined ? '' : ` after ${(here.hibernatedForMs / 1000).toFixed(1)} s`; const others = burst.length > 1 ? ` (+${burst.length - 1} neighbour${burst.length > 2 ? 's' : ''})` : ''; toast( `${here.zone} restored from hibernation${slept} on host ${here.host}: ${here.restoredCritters} critters, ${here.restoredMarkers} markers${others}`, @@ -417,19 +423,19 @@ stage.onFrame((now, dtMs) => { if (ecell === undefined) continue; const mine = entity.predicted || (entity.authoritative && hello?.entity === entity.id); const visual = visualFor(entity, mine); - const x = Number(entity.fields.x ?? 0); - const y = Number(entity.fields.y ?? 0); seen.add(entity.key); - if (visual.kind === KIND.critter) { + if (visual.kind === 'critter') { + const { x, y, yaw } = critterFields(entity); visual.mesh.position.copyFrom(local(ecell, x, y, 0.3)); - visual.mesh.rotation.y = -Number(entity.fields.yaw ?? 0); - } else if (visual.kind === KIND.marker) { + visual.mesh.rotation.y = -yaw; + } else if (visual.kind === 'marker') { + const { x, y, label } = markerFields(entity); visual.mesh.position.copyFrom(local(ecell, x, y)); - stage.labels.set(entity.key, visual.mesh, `⚑ ${String(entity.fields.label ?? '')}`, 2.6); + stage.labels.set(entity.key, visual.mesh, `⚑ ${label}`, 2.6); if (entity.authoritative) markers += 1; } else { + const { x, y, name: label } = walkerFields(entity); visual.mesh.position.copyFrom(local(ecell, x, y, 0.9)); - const label = String(entity.fields.name ?? ''); stage.labels.set(entity.key, visual.mesh, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); if (mine) me = visual.mesh.position; } diff --git a/examples/game/client/src/grid/world.ts b/examples/game/client/src/grid/world.ts index e47c07edf..b8a735232 100644 --- a/examples/game/client/src/grid/world.ts +++ b/examples/game/client/src/grid/world.ts @@ -9,10 +9,16 @@ * `tests/grid-world-parity.test.mjs` replays the Rust-written fixture * `examples/game/fixtures/grid-world.json`. * - * No imports except the SDK quantizers so Node can run it directly. + * The input type, its sanitize, the button bits and the wire quantization + * of positions come from the client generated from the Rust surface + * (`../generated/grid`). */ import { dequantizeLinear, quantizeLinear } from '@hops-ops/distributed/game'; +import { BUTTON, FIELD_TYPES, sanitizeInput, type MoveInput } from '../generated/grid/index.ts'; + +export type { MoveInput } from '../generated/grid/index.ts'; + const f = Math.fround; export const CELL = 32; @@ -28,10 +34,10 @@ export const WALK_SPEED = 6; export const SPRINT_SPEED = 10; export const DT = f(1 / 30); export const OUTSIDE_LIMIT = 2; -export const BUTTON_SPRINT = 1; -export const BUTTON_MARK = 2; +export const BUTTON_SPRINT = BUTTON.sprint; +export const BUTTON_MARK = BUTTON.mark; /** Wire quantization of local positions (server `grid::world::POS`). */ -export const POS = { min: -8, max: 40, bits: 18 } as const; +export const POS = FIELD_TYPES.walker.x; export const BIOMES = ['highlands', 'steppe', 'forest', 'meadow'] as const; const PROP_DENSITY = [0.4375, 0.1875, 0.75, 0.3125]; @@ -164,19 +170,6 @@ export function cellProps(seed: number, cell: Cell): Prop[] { return props; } -/** One command frame: stick per axis in [-127, 127] and button bits. */ -export type MoveInput = Readonly<{ mx: number; my: number; buttons: number }>; - -export function encodeMoveInput(input: MoveInput): Uint8Array { - return new Uint8Array([input.mx & 0xff, input.my & 0xff, input.buttons & 0xff]); -} - -/** The server's sanitization: -128 → -127, unknown buttons cleared. */ -export function sanitizeMoveInput(input: MoveInput): MoveInput { - const axis = (v: number) => Math.max(-127, Math.min(127, Math.trunc(v))); - return { mx: axis(input.mx), my: axis(input.my), buttons: input.buttons & (BUTTON_SPRINT | BUTTON_MARK) }; -} - export function snap(v: number): number { return dequantizeLinear(quantizeLinear(v, POS.min, POS.max, POS.bits), POS.min, POS.max, POS.bits); } @@ -202,7 +195,7 @@ export function collide(x0: number, y0: number, radius: number, props: readonly /** Advance a walker one command frame inside its cell (see the Rust docs). */ export function step(x: number, y: number, raw: MoveInput, props: readonly Prop[]): [number, number] { - const input = sanitizeMoveInput(raw); + const input = sanitizeInput(raw); let dx = f(input.mx / 127); let dy = f(input.my / 127); const l2 = f(f(dx * dx) + f(dy * dy)); diff --git a/examples/game/server/src/grid/mod.rs b/examples/game/server/src/grid/mod.rs index 6000005f9..35daeb78b 100644 --- a/examples/game/server/src/grid/mod.rs +++ b/examples/game/server/src/grid/mod.rs @@ -32,6 +32,10 @@ //! | 2 `critter` | 1.. | x y yaw hue | wander, persisted on hibernation | //! | 3 `marker` | 500.. | x y label hue | dropped with E, persisted | //! +//! The kinds are `#[derive(Replicated)]` views, the hello a struct-form +//! `#[derive(GameEvent)]` ([`GridHello`]); the browser client is generated +//! from [`game_surface`]. +//! //! Every entity is global within its zone (a cell is small); interest //! between zones is the client's choice of observed neighbours. @@ -45,23 +49,76 @@ use std::time::{SystemTime, UNIX_EPOCH}; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::world::{FlatTopology, HashRing, HostAddr, ZoneDirectory}; use distributed_game::{ - ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, - ObserverId, PlayerId, WorldView, Zone, + schema, ConsumePolicy, Ctx, EntitySchema, GameEvent, GameInput, GameSurface, LeaveReason, + ObserverId, PlayerId, Replicated, WorldView, Zone, }; use serde::{Deserialize, Serialize}; use crate::cluster::{ClusterDemo, ClusterOptions, World}; -use crate::common::{send_json_event, Demo, Guests}; +use crate::common::{Demo, Guests}; use world::{MoveInput, Prop, CELL, POS}; -/// Walker kind. -pub const KIND_WALKER: u16 = 1; -/// Critter kind. -pub const KIND_CRITTER: u16 = 2; -/// Marker kind. -pub const KIND_MARKER: u16 = 3; -/// Event type (JSON) sent to every joining player and observer, see [`GridHello`]. -pub const EVENT_HELLO: u32 = 1; +/// A walker (a player), in cell-local coordinates. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "walker", id = 1, priority = 2.0, global)] +pub struct WalkerView { + /// Local x. + #[field_type(POS)] + #[correct(ease = 120)] + pub x: f32, + /// Local y. + #[field_type(POS)] + #[correct(ease = 120)] + pub y: f32, + /// Display name. + #[priority(0.2)] + #[correct(replace)] + pub name: String, + /// Colour. + #[correct(replace)] + pub hue: u8, +} + +/// A wandering critter (persisted on hibernation). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "critter", id = 2, global)] +pub struct CritterView { + /// Local x. + #[field_type(POS)] + pub x: f32, + /// Local y. + #[field_type(POS)] + pub y: f32, + /// Heading. + #[angle(bits = 8)] + pub yaw: f32, + /// Colour. + pub hue: u8, +} + +/// A dropped marker (persisted on hibernation). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "marker", id = 3, global)] +pub struct MarkerView { + /// Local x. + #[field_type(POS)] + pub x: f32, + /// Local y. + #[field_type(POS)] + pub y: f32, + /// Who dropped it. + pub label: String, + /// Colour. + pub hue: u8, +} + +/// Type id of [`GridHello`]. +pub const EVENT_HELLO: u32 = GridHello::EVENT_ID; + +/// The grid's client surface. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("grid").events::() +} /// Most markers a cell keeps (oldest dropped first). pub const MAX_MARKERS: usize = 12; /// Most command frames a walker may bank. @@ -70,14 +127,14 @@ const CRITTER_SPEED: f32 = 1.6; const CRITTER_RADIUS: f32 = 0.3; const MARK_COOLDOWN: u8 = 15; -/// What a zone tells each player / observer on arrival (JSON, camelCase). -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "camelCase")] +/// What a zone tells each player / observer on arrival. +#[derive(Debug, Clone, PartialEq, GameEvent)] +#[game_event(id = 1, name = "hello")] pub struct GridHello { /// Zone id. pub zone: String, - /// Cell coordinates. - pub cell: [i32; 2], + /// Cell coordinates `[x, y]`. + pub cell: Vec, /// Host running the zone. pub host: String, /// World seed (the client generates the same content). @@ -214,10 +271,10 @@ impl GridZone { (CELL / 2.0, CELL / 2.0) } - fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> serde_json::Value { - let hello = GridHello { + fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> GridHello { + GridHello { zone: ctx.zone_id().to_string(), - cell: [self.config.cell.0, self.config.cell.1], + cell: vec![self.config.cell.0, self.config.cell.1], host: self.config.host_id.clone(), seed: self.config.seed, content_version: world::CONTENT_VERSION, @@ -229,8 +286,7 @@ impl GridZone { restored_critters: self.restored.map_or(0, |(_, c, _)| c), restored_markers: self.restored.map_or(0, |(_, _, m)| m), activated_at: self.activated_at, - }; - serde_json::to_value(hello).unwrap_or_default() + } } fn admit( @@ -265,7 +321,7 @@ impl GridZone { }, ); let hello = self.hello(ctx, Some(entity)); - send_json_event(ctx, player, EVENT_HELLO, &hello); + ctx.send(player, &hello); } fn drop_marker(&mut self, x: f32, y: f32, label: String, hue: u8) { @@ -344,29 +400,7 @@ impl Zone for GridZone { type Timer = (); fn schema() -> EntitySchema { - EntitySchema::new() - .kind( - KindDef::new(KIND_WALKER, "walker") - .field("x", POS) - .field("y", POS) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .field("hue", FieldType::U8) - .priority(2.0), - ) - .kind( - KindDef::new(KIND_CRITTER, "critter") - .field("x", POS) - .field("y", POS) - .field("yaw", FieldType::Angle { bits: 8 }) - .field("hue", FieldType::U8), - ) - .kind( - KindDef::new(KIND_MARKER, "marker") - .field("x", POS) - .field("y", POS) - .field("label", FieldType::ShortStr) - .field("hue", FieldType::U8), - ) + schema![WalkerView, CritterView, MarkerView] } fn on_create(ctx: &mut Ctx<'_, Self>, config: GridConfig) -> Self { @@ -425,11 +459,11 @@ impl Zone for GridZone { fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { let hello = self.hello(ctx, None); - send_json_event(ctx, observer, EVENT_HELLO, &hello); + ctx.send(observer, &hello); } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - MoveInput::decode(payload) + MoveInput::from_payload(payload) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { @@ -486,58 +520,33 @@ impl Zone for GridZone { } fn replicate(&self, out: &mut WorldView) { - for w in self.walkers.values() { - out.push( - EntityState::new( - w.entity, - KIND_WALKER, - w.x, - w.y, - vec![ - FieldValue::F(w.x), - FieldValue::F(w.y), - FieldValue::Str(w.name.clone()), - FieldValue::U(w.hue.into()), - ], - ) - .global(), - ); + for w in &self.walkers { + let w = w.1; + let view = WalkerView { + x: w.x, + y: w.y, + name: w.name.clone(), + hue: w.hue, + }; + out.add(w.entity, &view); } for c in &self.critters { - out.push( - EntityState::new( - c.id, - KIND_CRITTER, - c.x, - c.y, - vec![ - FieldValue::F(c.x), - FieldValue::F(c.y), - FieldValue::F(c.yaw), - FieldValue::U(c.hue.into()), - ], - ) - .global() - .priority(0.5), - ); + let view = CritterView { + x: c.x, + y: c.y, + yaw: c.yaw, + hue: c.hue, + }; + out.add(c.id, &view).priority(0.5); } for m in &self.markers { - out.push( - EntityState::new( - m.id, - KIND_MARKER, - m.x, - m.y, - vec![ - FieldValue::F(m.x), - FieldValue::F(m.y), - FieldValue::Str(m.label.clone()), - FieldValue::U(m.hue.into()), - ], - ) - .global() - .priority(0.3), - ); + let view = MarkerView { + x: m.x, + y: m.y, + label: m.label.clone(), + hue: m.hue, + }; + out.add(m.id, &view); } } @@ -576,8 +585,7 @@ pub fn encode_bot_input(dir: [f32; 2]) -> Vec { my: axis(dir[1]), buttons: world::BUTTON_SPRINT, } - .encode() - .to_vec() + .to_payload() } /// World seed: `DG_GRID_SEED` (decimal or 0x-hex) or [`world::DEFAULT_SEED`]. diff --git a/examples/game/server/src/grid/world.rs b/examples/game/server/src/grid/world.rs index 289e66ec4..041612731 100644 --- a/examples/game/server/src/grid/world.rs +++ b/examples/game/server/src/grid/world.rs @@ -22,7 +22,7 @@ //! is a multiple of 8 m is a free path ("trail"), and props never reach //! across a cell border. -use distributed_game::{FieldType, FieldValue}; +use distributed_game::{FieldType, FieldValue, GameInput}; /// Cell edge length (m). pub const CELL: f32 = 32.0; @@ -52,9 +52,9 @@ pub const DT: f32 = 1.0 / 30.0; /// How far outside its cell a walker may be before it is clamped (m). pub const OUTSIDE_LIMIT: f32 = 2.0; /// Input bit: sprint. -pub const BUTTON_SPRINT: u8 = 1; +pub const BUTTON_SPRINT: u8 = MoveInput::SPRINT; /// Input bit: drop a marker. -pub const BUTTON_MARK: u8 = 2; +pub const BUTTON_MARK: u8 = MoveInput::MARK; /// Wire type of local positions (covers the walker's slack outside the cell). pub const POS: FieldType = FieldType::QuantF32 { min: -8.0, @@ -243,35 +243,21 @@ pub fn cell_props(seed: u32, cell: (i32, i32)) -> Vec { } /// One command frame: stick per axis in `[-127, 127]` and button bits. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +/// Wire payload `[mx, my, buttons]`; `GameInput::from_payload` clamps `-128` +/// to `-127` and clears unknown buttons (the client's encoder is generated). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] pub struct MoveInput { /// Stick x (+east). + #[range(min = -127, max = 127)] pub mx: i8, /// Stick y (+north). + #[range(min = -127, max = 127)] pub my: i8, - /// [`BUTTON_SPRINT`] | [`BUTTON_MARK`]. + /// [`MoveInput::SPRINT`] | [`MoveInput::MARK`]. + #[buttons(sprint, mark)] pub buttons: u8, } -impl MoveInput { - /// Wire payload `[mx, my, buttons]`. - pub fn encode(self) -> [u8; 3] { - [self.mx as u8, self.my as u8, self.buttons] - } - - /// Parse and sanitize (`-128` → `-127`, unknown buttons cleared). - pub fn decode(payload: &[u8]) -> Option { - let [mx, my, buttons] = payload else { - return None; - }; - Some(Self { - mx: (*mx as i8).max(-127), - my: (*my as i8).max(-127), - buttons: buttons & (BUTTON_SPRINT | BUTTON_MARK), - }) - } -} - /// Snap to the wire quantization so the server holds exactly what clients decode. pub fn snap(v: f32) -> f32 { match POS.canonicalize(&FieldValue::F(v)) { diff --git a/examples/game/server/tests/grid_fixture.rs b/examples/game/server/tests/grid_fixture.rs index 4d51d2d1a..f8b8e8a61 100644 --- a/examples/game/server/tests/grid_fixture.rs +++ b/examples/game/server/tests/grid_fixture.rs @@ -8,6 +8,7 @@ use std::path::PathBuf; +use distributed_game::GameInput; use game_demos::grid::world::{self, MoveInput, BUTTON_SPRINT, DEFAULT_SEED}; use serde_json::{json, Value}; @@ -77,7 +78,7 @@ fn walk(seed: u32) -> Value { }, buttons: if k % 2 == 0 { BUTTON_SPRINT } else { 0 }, }; - let decoded = MoveInput::decode(&input.encode()).unwrap(); + let decoded = MoveInput::from_payload(&input.to_payload()).unwrap(); (x, y) = world::step(x, y, decoded, &props); steps.push(json!({ "input": [input.mx, input.my, input.buttons], "x": x, "y": y })); } diff --git a/examples/game/server/tests/grid_smoke.rs b/examples/game/server/tests/grid_smoke.rs index 02e5b4f53..bf37afc80 100644 --- a/examples/game/server/tests/grid_smoke.rs +++ b/examples/game/server/tests/grid_smoke.rs @@ -12,8 +12,9 @@ use std::time::Duration; use distributed_game::world::ZoneStateStore; use distributed_game::{FieldValue, Role, ServerMessage}; +use distributed_game::{GameInput, Replicated}; use game_demos::grid::world::{self, MoveInput, BUTTON_MARK, BUTTON_SPRINT}; -use game_demos::grid::{GridDemo, EVENT_HELLO, KIND_CRITTER, KIND_MARKER}; +use game_demos::grid::{CritterView, GridDemo, GridHello, MarkerView}; use serde_json::{json, Value}; use support::{eventually, http, join, start_cluster, ticket, Client}; @@ -23,8 +24,7 @@ fn east(buttons: u8) -> Vec { my: 0, buttons: BUTTON_SPRINT | buttons, } - .encode() - .to_vec() + .to_payload() } fn f(fields: &[FieldValue], i: usize) -> f32 { @@ -53,12 +53,12 @@ async fn walker_crosses_borders_and_hosts_without_losing_its_session() { ) .await .unwrap(); - let hello = observer.json_event(EVENT_HELLO).await; - assert_eq!(hello["host"], owner(1).as_str()); - assert!(hello["entity"].is_null(), "observers control nothing"); + let hello = observer.wait_event::(|_| true).await; + assert_eq!(hello.host, owner(1)); + assert!(hello.entity.is_none(), "observers control nothing"); observer .until("critters replicated to the observer", |c| { - c.count(KIND_CRITTER) >= 2 + c.count(CritterView::KIND_ID) >= 2 }) .await; @@ -69,10 +69,10 @@ async fn walker_crosses_borders_and_hosts_without_losing_its_session() { ) .await .unwrap(); - let hello = client.json_event(EVENT_HELLO).await; + let hello = client.wait_event::(|_| true).await; let name = format!("Guest {}", &"guest-walker"[6..10]); - assert_eq!(hello["cell"], json!([0, 0])); - assert!(hello["entity"].as_u64().is_some()); + assert_eq!(hello.cell, [0, 0]); + assert!(hello.entity.is_some()); let mut zone = "grid.0.0".to_string(); let mut handoffs = 0; @@ -104,9 +104,9 @@ async fn walker_crosses_borders_and_hosts_without_losing_its_session() { let from_owner = world.owner(&zone); let to_owner = world.owner(&to); let mut next: Client = join(&base, &to, &transfer).await.expect("target admits"); - let hello = next.json_event(EVENT_HELLO).await; - assert_eq!(hello["zone"], to.as_str()); - assert_eq!(hello["host"], to_owner.as_str()); + let hello = next.wait_event::(|_| true).await; + assert_eq!(hello.zone, to); + assert_eq!(hello.host, to_owner); assert_eq!( next.redirects > 0, to_owner != "A", @@ -164,11 +164,11 @@ async fn empty_cell_hibernates_and_restores_critters_and_markers() { let mut client = join(&base, zone, &ticket("guest-marker", zone, Role::Player)) .await .unwrap(); - let hello = client.json_event(EVENT_HELLO).await; - assert_eq!(hello["restored"], false); + let hello = client.wait_event::(|_| true).await; + assert!(!hello.restored); client.input(east(BUTTON_MARK)).await; client - .until("marker replicated", |c| c.count(KIND_MARKER) == 1) + .until("marker replicated", |c| c.count(MarkerView::KIND_ID) == 1) .await; client.leave().await; drop(client); @@ -205,15 +205,15 @@ async fn empty_cell_hibernates_and_restores_critters_and_markers() { let mut again = join(&base, zone, &ticket("guest-marker", zone, Role::Player)) .await .unwrap(); - let hello = again.json_event(EVENT_HELLO).await; - assert_eq!(hello["restored"], true); - assert_eq!(hello["restores"], 1); - assert_eq!(hello["restoredMarkers"], 1); - assert_eq!(hello["restoredCritters"], critters.len()); + let hello = again.wait_event::(|_| true).await; + assert!(hello.restored); + assert_eq!(hello.restores, 1); + assert_eq!(hello.restored_markers, 1); + assert_eq!(hello.restored_critters as usize, critters.len()); let n = critters.len(); again .until("restored entities replicated", |c| { - c.count(KIND_CRITTER) == n && c.count(KIND_MARKER) == 1 + c.count(CritterView::KIND_ID) == n && c.count(MarkerView::KIND_ID) == 1 }) .await; // Critters resume exactly where they slept (first delta after restore). @@ -264,7 +264,7 @@ async fn dev_routes_share_names_and_map_both_hosts() { .await .unwrap(); assert_eq!(client.redirects, 1); - client.json_event(EVENT_HELLO).await; + client.wait_event::(|_| true).await; let walkers = cluster .host("B") .demo From 63390a0a9b9d7372c528a46722d04e4676e1d1bb Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:57:09 -0500 Subject: [PATCH 187/484] feat(cli): emit per-field bit maps for game inputs Inputs with several #[buttons] fields get BITS keyed by field; BUTTON stays as a shortcut when there is exactly one flag field. --- distributed_cli/src/game_client.rs | 29 ++++++++++++------- .../fixtures/game-client/sample/input.ts | 13 ++++++--- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs index 380a60cf0..e98ddbd82 100644 --- a/distributed_cli/src/game_client.rs +++ b/distributed_cli/src/game_client.rs @@ -789,22 +789,29 @@ impl<'a> Gen<'a> { &input.fields, )); let _ = writeln!(out, "\nexport type Input = {};", input.name); - let buttons: Vec<(String, u32)> = input + let flag_fields: Vec<&Field> = input .fields .iter() - .flat_map(|f| { - f.buttons - .iter() - .enumerate() - .map(|(bit, b)| (camel(b), 1u32 << bit)) - }) + .filter(|f| !f.buttons.is_empty()) .collect(); - if !buttons.is_empty() { - out.push_str("\n/** Button bits (`#[buttons(..)]`). */\nexport const BUTTON = {\n"); - for (name, bit) in &buttons { - let _ = writeln!(out, "\t{}: {bit},", key(name)); + if !flag_fields.is_empty() { + out.push_str("\n/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */\nexport const BITS = {\n"); + for field in &flag_fields { + let _ = writeln!(out, "\t{}: {{", key(&camel(&field.name))); + for (bit, name) in field.buttons.iter().enumerate() { + let _ = writeln!(out, "\t\t{}: {},", key(&camel(name)), 1u32 << bit); + } + out.push_str("\t},\n"); } out.push_str("} as const;\n"); + if let [only] = flag_fields.as_slice() { + let _ = writeln!( + out, + "\n/** Bits of `{}`, the only bit-flag field. */\nexport const BUTTON = BITS.{};", + camel(&only.name), + camel(&only.name) + ); + } } let _ = writeln!( out, diff --git a/distributed_cli/tests/fixtures/game-client/sample/input.ts b/distributed_cli/tests/fixtures/game-client/sample/input.ts index d0f65baab..5a836a29b 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/input.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/input.ts @@ -15,12 +15,17 @@ export interface SampleInput { export type Input = SampleInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - dash: 1, - attack: 2, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + attack: 2, + }, } as const; +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['mx', { type: 'i8' }], From 2f4cf6b6c0b0e3bd069db6a824b35a504ea456e8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Sun, 18 Oct 2026 23:57:09 -0500 Subject: [PATCH 188/484] feat(examples): author boss ripple with derives; drop JSON events Ripple's tiers, bosses, fighters, HoodInput (two bit-flag fields) and events are derived and the client uses the generated factory. With every demo converted, the JSON event helpers on both sides are gone. --- examples/game/client/src/arena/movement.ts | 2 - .../game/client/src/generated/arena/input.ts | 11 +- .../game/client/src/generated/freeze/input.ts | 11 +- .../client/src/generated/gallery/input.ts | 13 +- .../game/client/src/generated/grid/input.ts | 13 +- .../game/client/src/generated/mobpit/input.ts | 13 +- .../client/src/generated/ripple/client.ts | 49 ++ .../client/src/generated/ripple/events.ts | 156 +++++++ .../game/client/src/generated/ripple/index.ts | 7 + .../game/client/src/generated/ripple/input.ts | 55 +++ .../client/src/generated/ripple/schema.ts | 152 +++++++ .../client/src/generated/ripple/surface.json | 428 ++++++++++++++++++ examples/game/client/src/ripple/client.ts | 85 ++-- examples/game/client/src/ripple/main.ts | 12 +- examples/game/client/src/shared/events.ts | 18 - examples/game/server/src/common/mod.rs | 28 +- examples/game/server/src/lib.rs | 7 +- examples/game/server/src/ripple/mod.rs | 402 +++++++++------- examples/game/server/tests/ripple_smoke.rs | 96 ++-- examples/game/server/tests/support/mod.rs | 24 - 20 files changed, 1246 insertions(+), 336 deletions(-) create mode 100644 examples/game/client/src/generated/ripple/client.ts create mode 100644 examples/game/client/src/generated/ripple/events.ts create mode 100644 examples/game/client/src/generated/ripple/index.ts create mode 100644 examples/game/client/src/generated/ripple/input.ts create mode 100644 examples/game/client/src/generated/ripple/schema.ts create mode 100644 examples/game/client/src/generated/ripple/surface.json delete mode 100644 examples/game/client/src/shared/events.ts diff --git a/examples/game/client/src/arena/movement.ts b/examples/game/client/src/arena/movement.ts index 1c0746293..3eacf538c 100644 --- a/examples/game/client/src/arena/movement.ts +++ b/examples/game/client/src/arena/movement.ts @@ -19,8 +19,6 @@ import { dequantizeLinear, quantizeLinear, type EntityFields } from '@hops-ops/d import { BUTTON, FIELD_TYPES, sanitizeInput, type MoveInput } from '../generated/arena/index.ts'; export type { MoveInput } from '../generated/arena/index.ts'; -/** TEMPORARY (demo conversion in progress): use the generated `encodeInput`. */ -export { encodeInput as encodeMoveInput } from '../generated/arena/index.ts'; const f = Math.fround; diff --git a/examples/game/client/src/generated/arena/input.ts b/examples/game/client/src/generated/arena/input.ts index 8b80618d0..696221d8c 100644 --- a/examples/game/client/src/generated/arena/input.ts +++ b/examples/game/client/src/generated/arena/input.ts @@ -12,11 +12,16 @@ export interface MoveInput { export type Input = MoveInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - dash: 1, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + }, } as const; +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['mx', { type: 'i8' }], diff --git a/examples/game/client/src/generated/freeze/input.ts b/examples/game/client/src/generated/freeze/input.ts index 9fdaa5918..34dba4c77 100644 --- a/examples/game/client/src/generated/freeze/input.ts +++ b/examples/game/client/src/generated/freeze/input.ts @@ -12,11 +12,16 @@ export interface MoveInput { export type Input = MoveInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - dash: 1, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + }, } as const; +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['mx', { type: 'i8' }], diff --git a/examples/game/client/src/generated/gallery/input.ts b/examples/game/client/src/generated/gallery/input.ts index b768d581b..6318b8e10 100644 --- a/examples/game/client/src/generated/gallery/input.ts +++ b/examples/game/client/src/generated/gallery/input.ts @@ -15,12 +15,17 @@ export interface ShotInput { export type Input = ShotInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - fire: 1, - noComp: 2, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + flags: { + fire: 1, + noComp: 2, + }, } as const; +/** Bits of `flags`, the only bit-flag field. */ +export const BUTTON = BITS.flags; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['flags', { type: 'u8' }], diff --git a/examples/game/client/src/generated/grid/input.ts b/examples/game/client/src/generated/grid/input.ts index d1fe024f2..b9f032f36 100644 --- a/examples/game/client/src/generated/grid/input.ts +++ b/examples/game/client/src/generated/grid/input.ts @@ -12,12 +12,17 @@ export interface MoveInput { export type Input = MoveInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - sprint: 1, - mark: 2, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + sprint: 1, + mark: 2, + }, } as const; +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['mx', { type: 'i8' }], diff --git a/examples/game/client/src/generated/mobpit/input.ts b/examples/game/client/src/generated/mobpit/input.ts index d5ff8e8b1..863e9d8f2 100644 --- a/examples/game/client/src/generated/mobpit/input.ts +++ b/examples/game/client/src/generated/mobpit/input.ts @@ -12,12 +12,17 @@ export interface PitInput { export type Input = PitInput; -/** Button bits (`#[buttons(..)]`). */ -export const BUTTON = { - dash: 1, - attack: 2, +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + attack: 2, + }, } as const; +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + /** Wire layout, in field order. */ export const INPUT_LAYOUT: PayloadLayout = [ ['mx', { type: 'i8' }], diff --git a/examples/game/client/src/generated/ripple/client.ts b/examples/game/client/src/generated/ripple/client.ts new file mode 100644 index 000000000..df46664d1 --- /dev/null +++ b/examples/game/client/src/generated/ripple/client.ts @@ -0,0 +1,49 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type HoodInput } from './input.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** Prediction options; `encodeInput` and the correction defaults are filled in. */ +export type RipplePredictionOptions = Omit, 'encodeInput'> & + Partial, 'encodeInput'>>; + +export type RippleClientOptions = Omit, 'prediction'> & + Readonly<{ prediction?: RipplePredictionOptions }>; + +export type RippleClient = Readonly<{ + client: GameClient; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is configured, raw otherwise. */ + send(input: HoodInput): number | undefined; +}>; + +/** A `GameClient` for the `ripple` surface with its input encoder and correction defaults. */ +export function createRippleClient(options: RippleClientOptions): RippleClient { + const prediction = options.prediction; + const client = new GameClient({ + ...options, + prediction: + prediction === undefined + ? undefined + : { + ...prediction, + encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + } + }); + return { + client, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/client/src/generated/ripple/events.ts b/examples/game/client/src/generated/ripple/events.ts new file mode 100644 index 000000000..b19cdff91 --- /dev/null +++ b/examples/game/client/src/generated/ripple/events.ts @@ -0,0 +1,156 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `Weather` (`#[derive(GameRecord)]`). */ +export interface Weather { + readonly weather: string; + readonly remaining: number; +} + +const WEATHER_TYPE: WireType = { + type: 'record', + fields: [ + ['weather', { type: 'short_str' }], + ['remaining', { type: 'u32' }], + ] +}; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly zone: string; + readonly tier: string; + readonly parent: string | undefined; + readonly children: readonly string[]; + readonly host: string; + readonly tickRate: number; + readonly entity: number | undefined; + readonly weather: Weather | undefined; + readonly banner: string; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['zone', { type: 'short_str' }], + ['tier', { type: 'short_str' }], + ['parent', { type: 'optional', item: { type: 'short_str' } }], + ['children', { type: 'list', item: { type: 'short_str' } }], + ['host', { type: 'short_str' }], + ['tickRate', { type: 'u32' }], + ['entity', { type: 'optional', item: { type: 'u32' } }], + ['weather', { type: 'optional', item: WEATHER_TYPE }], + ['banner', { type: 'short_str' }], +]; + +/** Event `ripple` (id 2). */ +export interface RippleEvent { + readonly at: string; + readonly kind: string; + readonly from: string; + readonly origin: string; + readonly originTick: number; + readonly tick: number; +} + +const RIPPLE_LAYOUT: PayloadLayout = [ + ['at', { type: 'short_str' }], + ['kind', { type: 'short_str' }], + ['from', { type: 'short_str' }], + ['origin', { type: 'short_str' }], + ['originTick', { type: 'u64' }], + ['tick', { type: 'u64' }], +]; + +/** Event `weather` (id 3). */ +export type WeatherEvent = Weather; + +const WEATHER_PAYLOAD: WireType = WEATHER_TYPE; + +/** Event `banner` (id 4). */ +export interface BannerEvent { + readonly text: string; +} + +const BANNER_LAYOUT: PayloadLayout = [ + ['text', { type: 'short_str' }], +]; + +/** Event `boss` (id 5). */ +export interface BossEvent { + readonly kind: string; + readonly by: string | undefined; +} + +const BOSS_LAYOUT: PayloadLayout = [ + ['kind', { type: 'short_str' }], + ['by', { type: 'optional', item: { type: 'short_str' } }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + ripple: 2, + weather: 3, + banner: 4, + boss: 5, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + ripple: RippleEvent; + weather: WeatherEvent; + banner: BannerEvent; + boss: BossEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + ripple: { + id: 2, + name: 'ripple', + encode: (value) => encodePayload(RIPPLE_LAYOUT, value), + decode: (payload) => decodePayload(RIPPLE_LAYOUT, payload) as unknown as RippleEvent + }, + weather: { + id: 3, + name: 'weather', + encode: (value) => encodeValue(WEATHER_PAYLOAD, value), + decode: (payload) => decodeValue(WEATHER_PAYLOAD, payload) as WeatherEvent + }, + banner: { + id: 4, + name: 'banner', + encode: (value) => encodePayload(BANNER_LAYOUT, value), + decode: (payload) => decodePayload(BANNER_LAYOUT, payload) as unknown as BannerEvent + }, + boss: { + id: 5, + name: 'boss', + encode: (value) => encodePayload(BOSS_LAYOUT, value), + decode: (payload) => decodePayload(BOSS_LAYOUT, payload) as unknown as BossEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/client/src/generated/ripple/index.ts b/examples/game/client/src/generated/ripple/index.ts new file mode 100644 index 000000000..0495fe208 --- /dev/null +++ b/examples/game/client/src/generated/ripple/index.ts @@ -0,0 +1,7 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './schema.ts'; diff --git a/examples/game/client/src/generated/ripple/input.ts b/examples/game/client/src/generated/ripple/input.ts new file mode 100644 index 000000000..7854a6904 --- /dev/null +++ b/examples/game/client/src/generated/ripple/input.ts @@ -0,0 +1,55 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `HoodInput` input frame (`#[derive(GameInput)]`). */ +export interface HoodInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; + readonly action: number; +} + +export type Input = HoodInput; + +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + }, + action: { + attack: 1, + smite: 2, + }, +} as const; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], + ['action', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 1 }, + { buttons: 3 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: HoodInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): HoodInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as HoodInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: HoodInput): HoodInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/client/src/generated/ripple/schema.ts b/examples/game/client/src/generated/ripple/schema.ts new file mode 100644 index 000000000..93cf914d3 --- /dev/null +++ b/examples/game/client/src/generated/ripple/schema.ts @@ -0,0 +1,152 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + tier: 1, + boss: 2, + player: 3, +} as const; + +export type KindName = keyof typeof KIND; + +/** `tier` (kind 1, priority 1). */ +export interface TierFields { + /** `u8` */ + readonly defeated: number; + /** `u8` */ + readonly total: number; + /** `u8` */ + readonly cleared: number; + /** `bool` */ + readonly liberated: boolean; + /** `u8` */ + readonly weather: number; + /** `u32` */ + readonly clock: number; + /** `u32` */ + readonly events: number; +} + +/** True for a `tier` entity. */ +export function isTier(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `tier` entity (rendered or replica). */ +export function tierFields(entity: { readonly fields: EntityFields }): TierFields { + const f = entity.fields; + return { + defeated: fieldNumber(f, 'defeated'), + total: fieldNumber(f, 'total'), + cleared: fieldNumber(f, 'cleared'), + liberated: fieldBool(f, 'liberated'), + weather: fieldNumber(f, 'weather'), + clock: fieldNumber(f, 'clock'), + events: fieldNumber(f, 'events'), + }; +} + +/** `boss` (kind 2, priority 1). */ +export interface BossFields { + /** `u16` */ + readonly hp: number; + /** `u16` */ + readonly max: number; + /** `short_str` */ + readonly by: string; +} + +/** True for a `boss` entity. */ +export function isBoss(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `boss` entity (rendered or replica). */ +export function bossFields(entity: { readonly fields: EntityFields }): BossFields { + const f = entity.fields; + return { + hp: fieldNumber(f, 'hp'), + max: fieldNumber(f, 'max'), + by: fieldString(f, 'by'), + }; +} + +/** `player` (kind 3, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vx: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vy: number; + /** `u8` */ + readonly dash: number; + /** `u8` */ + readonly cd: number; + /** `short_str`, priority 0.2 */ + readonly name: string; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + vy: fieldNumber(f, 'vy'), + dash: fieldNumber(f, 'dash'), + cd: fieldNumber(f, 'cd'), + name: fieldString(f, 'name'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + tier: { + defeated: { type: 'u8' }, + total: { type: 'u8' }, + cleared: { type: 'u8' }, + liberated: { type: 'bool' }, + weather: { type: 'u8' }, + clock: { type: 'u32' }, + events: { type: 'u32' }, + }, + boss: { + hp: { type: 'u16' }, + max: { type: 'u16' }, + by: { type: 'short_str' }, + }, + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + dash: { type: 'u8' }, + cd: { type: 'u8' }, + name: { type: 'short_str' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + vy: { mode: 'snap' }, + dash: { mode: 'snap' }, + cd: { mode: 'snap' }, + name: { mode: 'replace' }, + }, +}; diff --git a/examples/game/client/src/generated/ripple/surface.json b/examples/game/client/src/generated/ripple/surface.json new file mode 100644 index 000000000..b7d6b4384 --- /dev/null +++ b/examples/game/client/src/generated/ripple/surface.json @@ -0,0 +1,428 @@ +{ + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "zone", + "type": { + "type": "short_str" + } + }, + { + "name": "tier", + "type": { + "type": "short_str" + } + }, + { + "name": "parent", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "children", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "host", + "type": { + "type": "short_str" + } + }, + { + "name": "tick_rate", + "type": { + "type": "u32" + } + }, + { + "name": "entity", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "weather", + "type": { + "item": { + "name": "Weather", + "type": "record" + }, + "type": "optional" + } + }, + { + "name": "banner", + "type": { + "type": "short_str" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "ripple", + "payload": { + "fields": [ + { + "name": "at", + "type": { + "type": "short_str" + } + }, + { + "name": "kind", + "type": { + "type": "short_str" + } + }, + { + "name": "from", + "type": { + "type": "short_str" + } + }, + { + "name": "origin", + "type": { + "type": "short_str" + } + }, + { + "name": "origin_tick", + "type": { + "type": "u64" + } + }, + { + "name": "tick", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + }, + { + "id": 3, + "name": "weather", + "payload": { + "kind": "value", + "type": { + "name": "Weather", + "type": "record" + } + } + }, + { + "id": 4, + "name": "banner", + "payload": { + "fields": [ + { + "name": "text", + "type": { + "type": "short_str" + } + } + ], + "kind": "fields" + } + }, + { + "id": 5, + "name": "boss", + "payload": { + "fields": [ + { + "name": "kind", + "type": { + "type": "short_str" + } + }, + { + "name": "by", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash" + ], + "name": "buttons", + "type": { + "type": "u8" + } + }, + { + "buttons": [ + "attack", + "smite" + ], + "name": "action", + "type": { + "type": "u8" + } + } + ], + "name": "HoodInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": null, + "name": "defeated", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "total", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "cleared", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "liberated", + "priority": 1.0, + "type": { + "type": "bool" + } + }, + { + "correction": null, + "name": "weather", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "clock", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "events", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "tier", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "max", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "by", + "priority": 1.0, + "type": { + "type": "short_str" + } + } + ], + "id": 2, + "name": "boss", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vy", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "dash", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "cd", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + } + ], + "id": 3, + "name": "player", + "priority": 2.0 + } + ], + "name": "ripple", + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "weather", + "type": { + "type": "short_str" + } + }, + { + "name": "remaining", + "type": { + "type": "u32" + } + } + ], + "name": "Weather" + } + ], + "schemaVersion": 1 +} diff --git a/examples/game/client/src/ripple/client.ts b/examples/game/client/src/ripple/client.ts index 4c197b66a..0f1fd36df 100644 --- a/examples/game/client/src/ripple/client.ts +++ b/examples/game/client/src/ripple/client.ts @@ -8,39 +8,27 @@ * receives what upper tiers broadcast: ripple events, the city's * weather, the realm's banner. */ -import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; +import type { GameClient, GameSocketFactory } from '@hops-ops/distributed/game'; -import { encodeMoveInput, predictPlayer } from '../arena/movement.ts'; +import { predictPlayer } from '../arena/movement.ts'; +import * as gen from '../generated/ripple/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { onJsonEvent } from '../shared/events.ts'; export const REALM = 'realm'; export const CITY = 'realm.city'; export const BOROUGHS = ['realm.city.borough-1', 'realm.city.borough-2'] as const; export const HOODS_PER_BOROUGH = 3; export const DEFAULT_ZONE = 'realm.city.borough-1.hood-1'; -/** Event type ids (server `ripple::EVENT_*`). */ -export const EVENT = { hello: 1, ripple: 2, weather: 3, banner: 4, boss: 5 } as const; -export const ACTION_ATTACK = 1; -export const ACTION_SMITE = 2; +export const ACTION_ATTACK = gen.BITS.action.attack; +export const ACTION_SMITE = gen.BITS.action.smite; export const WEATHER = ['storm', 'rain', 'clearing', 'clear'] as const; -export type HoodInput = Readonly<{ mx: number; my: number; buttons: number; action: number }>; +export type HoodInput = gen.HoodInput; export type TierName = 'realm' | 'city' | 'borough' | 'hood'; - -export type RippleHello = Readonly<{ - zone: string; - tier: TierName; - parent: string | null; - children: string[]; - host: string; - tickRate: number; - entity: number | null; - weather: Readonly<{ weather: string; remaining: number }> | null; - banner: string; -}>; - -export type RippleEvent = Readonly<{ at: string; kind: string; from: string; origin: string; originTick: number; tick: number }>; +/** A zone's hello (generated from the Rust `RippleEvent::Hello`). */ +export type RippleHello = gen.HelloEvent; +/** A tier-up event as broadcast by the receiving zone. */ +export type RippleEvent = gen.RippleEvent; /** Live state of one tier, from its replicated `tier` (and `boss`) entity. */ export type TierView = Readonly<{ @@ -75,11 +63,6 @@ export function tierOf(zone: string): TierName | undefined { return BOROUGHS.some((b) => hoods(b).includes(zone)) ? 'hood' : undefined; } -export function encodeHoodInput(input: HoodInput): Uint8Array { - const move = encodeMoveInput(input); - return new Uint8Array([move[0]!, move[1]!, move[2]!, input.action & 0xff]); -} - export type RippleClientOptions = Readonly<{ api: DevApi; base?: string; @@ -119,46 +102,42 @@ export function createRippleClient(options: RippleClientOptions): RippleClient { weather: new Set<(w: string) => void>(), boss: new Set<(z: string, e: { kind: string; by?: string }) => void>() }; - const ease = { mode: 'ease', durationMs: 150 } as const; - const snap = { mode: 'snap' } as const; - const client = new GameClient({ + const typed = gen.createRippleClient({ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 1000, inputDtMs: 1000 / 30, - prediction: { - encodeInput: (input) => encodeHoodInput(input), - predict: (fields, input) => predictPlayer(fields, input), - corrections: { player: { x: ease, y: ease, vx: snap, vy: snap, dash: snap, cd: snap, name: { mode: 'replace' } } } - } + // The movement part of the frame is the Arena's (`action` only adds bits). + prediction: { predict: (fields, input) => predictPlayer(fields, input) } }); + const { client } = typed; let resolveReady: (h: RippleHello) => void = () => undefined; const ready = new Promise((resolve) => (resolveReady = resolve)); - onJsonEvent(client, EVENT.hello, (hello, zone) => { + typed.on('hello', (hello, zone) => { hellos.set(zone, hello); - if (hello.weather !== null) weather = hello.weather.weather; + if (hello.weather !== undefined) weather = hello.weather.weather; if (hello.tier === 'realm' && hello.banner !== '') banner = hello.banner; - if (hello.entity !== null && zone === client.authority?.zoneId) { + if (hello.entity !== undefined && zone === client.authority?.zoneId) { client.setControlledEntity(hello.entity); resolveReady(hello); } }); - onJsonEvent(client, EVENT.ripple, (event) => { + typed.on('ripple', (event) => { ripples.push(event); if (ripples.length > 200) ripples.shift(); for (const l of listeners.ripple) l(event); }); - onJsonEvent<{ weather: string }>(client, EVENT.weather, (value) => { + typed.on('weather', (value) => { weather = value.weather; for (const l of listeners.weather) l(value.weather); }); - onJsonEvent<{ text: string }>(client, EVENT.banner, (value) => { + typed.on('banner', (value) => { banner = value.text; for (const l of listeners.banner) l(value.text); }); - onJsonEvent<{ kind: string; by?: string }>(client, EVENT.boss, (value, zone) => { + typed.on('boss', (value, zone) => { for (const l of listeners.boss) l(zone, value); }); @@ -176,27 +155,25 @@ export function createRippleClient(options: RippleClientOptions): RippleClient { set.add(l); return () => set.delete(l); }; - const n = (v: unknown) => (typeof v === 'number' ? v : typeof v === 'boolean' ? Number(v) : 0); - return { client, ready, tier(zone) { const view = client.zone(zone); - const tier = view?.replica.get(1)?.fields ?? {}; - const boss = view?.replica.get(2)?.fields; + const tier = gen.tierFields({ fields: view?.replica.get(1)?.fields ?? {} }); + const boss = view?.replica.get(2); return { zone, hello: hellos.get(zone), connected: view?.connection.state === 'open', - defeated: n(tier.defeated), - total: n(tier.total), - cleared: n(tier.cleared), - liberated: tier.liberated === true, - weather: WEATHER[n(tier.weather)] ?? 'storm', - clock: n(tier.clock), - events: n(tier.events), - boss: boss === undefined ? undefined : { hp: n(boss.hp), max: n(boss.max), by: String(boss.by ?? '') } + defeated: tier.defeated, + total: tier.total, + cleared: tier.cleared, + liberated: tier.liberated, + weather: WEATHER[tier.weather] ?? 'storm', + clock: tier.clock, + events: tier.events, + boss: boss === undefined ? undefined : gen.bossFields(boss) }; }, ripples: () => ripples, diff --git a/examples/game/client/src/ripple/main.ts b/examples/game/client/src/ripple/main.ts index e13088fd7..eef1a0393 100644 --- a/examples/game/client/src/ripple/main.ts +++ b/examples/game/client/src/ripple/main.ts @@ -17,7 +17,8 @@ import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { Scene } from '@babylonjs/core/scene'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { BUTTON_DASH, HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { BITS, isPlayer, playerFields } from '../generated/ripple/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; @@ -266,7 +267,7 @@ function sendFrame(): void { const input: HoodInput = { mx: toAxis(move.x), my: toAxis(move.y), - buttons: s.action ? BUTTON_DASH : 0, + buttons: s.action ? BITS.buttons.dash : 0, action: (s.alt ? ACTION_ATTACK : 0) | (smitePending ? ACTION_SMITE : 0) }; if (client.sendInput(input) !== undefined) smitePending = false; @@ -285,16 +286,15 @@ stage.onFrame((now, dtMs) => { boss.position.y = 2.2 * s; stage.labels.set('boss', boss, hp === 0 ? `defeated by ${view?.boss?.by ?? ''}` : `Boss ${hp}/${view?.boss?.max ?? ''}`, 2.2); - const rendered = client.render().filter((e) => e.authoritative && e.kindName === 'player'); + const rendered = client.render().filter((e) => e.authoritative && isPlayer(e)); const seen = new Set(); for (const entity of rendered) { const mine = entity.predicted; const mesh = capsule(entity, mine); - const x = Number(entity.fields.x ?? 0); - const y = Number(entity.fields.y ?? 0); + const { x, y, name: label } = playerFields(entity); mesh.position.copyFrom(toWorld(x, y, 0.9)); mesh.setEnabled(!entity.stale); - stage.labels.set(entity.key, mesh, mine ? `${String(entity.fields.name ?? '')} (you)` : String(entity.fields.name ?? ''), 1.4, mine ? 'me' : ''); + stage.labels.set(entity.key, mesh, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); if (mine) stage.follow(x, y, dtMs); seen.add(entity.key); } diff --git a/examples/game/client/src/shared/events.ts b/examples/game/client/src/shared/events.ts deleted file mode 100644 index 908213f16..000000000 --- a/examples/game/client/src/shared/events.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Demos send low-rate events as UTF-8 JSON (`common::send_json_event` on the - * server). Subscribe by type id; returns the unsubscribe function. - */ -import type { GameClient } from '@hops-ops/distributed/game'; - -const decoder = new TextDecoder(); - -export function onJsonEvent( - client: Pick, 'on'>, - typeId: number, - handler: (value: T, zoneId: string) => void -): () => void { - return client.on('event', (zoneId, event) => { - if (event.typeId !== typeId) return; - handler(JSON.parse(decoder.decode(event.payload)) as T, zoneId); - }); -} diff --git a/examples/game/server/src/common/mod.rs b/examples/game/server/src/common/mod.rs index 8965d23f0..b89ad0834 100644 --- a/examples/game/server/src/common/mod.rs +++ b/examples/game/server/src/common/mod.rs @@ -1,7 +1,8 @@ //! Shared plumbing for every demo: CLI options, the [`Demo`] trait, server //! startup ([`spawn`] / [`run`]), the dev-only routes ([`dev`]), guest display -//! names ([`Guests`]), small zone helpers ([`send_json_event`]) and process -//! helpers ([`shutdown_signal`], [`random_hex`]). +//! names ([`Guests`]) and process helpers ([`shutdown_signal`], +//! [`random_hex`]). Zone events are typed (`#[derive(GameEvent)]`, sent with +//! `ctx.send` / `ctx.broadcast`) in each demo module. //! //! A new demo implements [`Demo`] in its own module and adds one subcommand //! line in `main.rs`; everything else (ticket endpoint, NetSim control, @@ -15,7 +16,7 @@ use std::net::SocketAddr; use axum::Router; use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey}; -use distributed_game::{Ctx, Viewer, Zone}; +use distributed_game::Zone; pub use guests::{random_hex, Guests}; @@ -208,24 +209,3 @@ pub async fn shutdown_signal() { _ = term => {} } } - -/// Send a JSON-encoded Event (`type_id`, UTF-8 JSON payload). Demos use JSON -/// for low-rate events so clients can `JSON.parse` them; hot data belongs in -/// replicated fields. -pub fn send_json_event( - ctx: &mut Ctx<'_, Z>, - to: impl Into, - type_id: u32, - value: &serde_json::Value, -) { - ctx.send_event(to, type_id, value.to_string().into_bytes()); -} - -/// Broadcast a JSON-encoded Event to every connection of the zone. -pub fn broadcast_json_event( - ctx: &mut Ctx<'_, Z>, - type_id: u32, - value: &serde_json::Value, -) { - ctx.broadcast_event(type_id, value.to_string().into_bytes()); -} diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index f14133772..e6ca40b32 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -1,8 +1,11 @@ //! Playable demos of the `distributed_game` runtime (dev only). //! //! - [`common`]: what every demo shares — the [`common::Demo`] trait, -//! startup, dev ticket / NetSim routes, guest names, JSON events. -//! - One module per demo ([`arena`], …), each implementing `Demo`. +//! startup, dev ticket / NetSim routes, guest names. +//! - One module per demo ([`arena`], …), each implementing `Demo` and +//! exporting `game_surface()`: its kinds, input and events, authored with +//! the `distributed_game` derives, from which `run.sh gen` generates the +//! typed TypeScript client in `client/src/generated//`. //! //! See `examples/game/README.md`. diff --git a/examples/game/server/src/ripple/mod.rs b/examples/game/server/src/ripple/mod.rs index c123f1667..d8e816de0 100644 --- a/examples/game/server/src/ripple/mod.rs +++ b/examples/game/server/src/ripple/mod.rs @@ -34,6 +34,10 @@ //! Entities: 1 `tier` (id 1, every zone), 2 `boss` (id 2, hoods), 3 //! `player` (1000 + player, hoods; Arena movement fields so the client //! predicts with the Arena step — the boss stands on its central pillar). +//! They are `#[derive(Replicated)]` views; client events are the typed +//! [`RippleEvent`] and input the `#[derive(GameInput)]` [`HoodInput`]; the +//! browser client is generated from [`game_surface`]. (Tier-up payloads +//! between zones are server-internal JSON.) use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -42,15 +46,15 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::world::{HostAddr, ZoneDirectory}; use distributed_game::{ - ChildEvent, ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, GameInput, - KindDef, LeaveReason, ObserverId, PlayerId, TimerId, WorldView, Zone, + schema, ChildEvent, ConsumePolicy, Ctx, EntitySchema, GameEvent, GameInput, GameRecord, + GameSurface, LeaveReason, ObserverId, PlayerId, Replicated, TimerId, WorldView, Zone, }; use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; +use serde_json::json; use crate::arena::movement::{self, MoveInput, MoveState}; use crate::cluster::{ClusterDemo, ClusterOptions, World}; -use crate::common::{broadcast_json_event, send_json_event, Demo, Guests}; +use crate::common::{Demo, Guests}; /// Root zone. pub const REALM: &str = "realm"; @@ -70,25 +74,150 @@ pub const REACH: f32 = 4.5; pub const RESPAWN: Duration = Duration::from_secs(60); /// Kind: tier state (every zone). -pub const KIND_TIER: u16 = 1; -/// Kind: the boss (hoods). -pub const KIND_BOSS: u16 = 2; -/// Kind: a player (hoods). -pub const KIND_PLAYER: u16 = 3; -/// Event: `{zone, tier, parent, children, host, tickRate, entity?}` on join/observe. -pub const EVENT_HELLO: u32 = 1; -/// Event: a tier received a child event `{at, kind, from, origin, originTick}`. -pub const EVENT_RIPPLE: u32 = 2; -/// Event (city): `{weather, remaining}`. -pub const EVENT_WEATHER: u32 = 3; -/// Event (realm): `{text}`. -pub const EVENT_BANNER: u32 = 4; -/// Event (hood): `{kind: "defeated" | "respawned", by?}`. -pub const EVENT_BOSS: u32 = 5; +/// A tier's tallies (every zone; global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "tier", id = 1, global)] +pub struct TierView { + /// Bosses defeated below this tier. + pub defeated: u8, + /// Bosses in the world. + pub total: u8, + /// Boroughs cleared. + pub cleared: u8, + /// The city is liberated. + pub liberated: bool, + /// Index into [`WEATHER`]. + pub weather: u8, + /// Ticks of this zone. + pub clock: u32, + /// Tier-up events received. + pub events: u32, +} + +/// A neighbourhood's boss (global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "boss", id = 2, global)] +pub struct BossView { + /// Hit points. + pub hp: u16, + /// Max hit points. + pub max: u16, + /// Who defeated it ("" while alive). + pub by: String, +} + +/// A fighter (the Arena's movement fields; global within the hood). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 3, priority = 2.0, global)] +pub struct FighterView { + /// Position x. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub x: f32, + /// Position y. + #[field_type(movement::POS)] + #[correct(ease = 150)] + pub y: f32, + /// Velocity x. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vx: f32, + /// Velocity y. + #[field_type(movement::VEL)] + #[correct(snap)] + pub vy: f32, + /// Remaining dash frames. + #[correct(snap)] + pub dash: u8, + /// Remaining dash cooldown frames. + #[correct(snap)] + pub cd: u8, + /// Display name. + #[priority(0.2)] + #[correct(replace)] + pub name: String, +} + +/// The city's weather. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Weather { + /// One of [`WEATHER`]. + pub weather: String, + /// Bosses still standing. + pub remaining: u32, +} + +/// Boss Ripple's client events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum RippleEvent { + /// To every joining player and observer. + #[game_event(id = 1)] + Hello { + /// Zone id. + zone: String, + /// `realm` / `city` / `borough` / `hood`. + tier: String, + /// Parent zone. + parent: Option, + /// Child zones. + children: Vec, + /// Host running the zone. + host: String, + /// Tick rate of this tier. + tick_rate: u32, + /// Own fighter (players in hoods). + entity: Option, + /// Weather (the city only). + weather: Option, + /// Current realm banner. + banner: String, + }, + /// A tier-up event arrived at this zone. + #[game_event(id = 2)] + Ripple { + /// Receiving zone. + at: String, + /// Event kind (`boss_defeated` …). + kind: String, + /// Child zone that forwarded it. + from: String, + /// Zone where it started. + origin: String, + /// Tick of the origin zone. + origin_tick: u64, + /// Tick of the receiving zone. + tick: u64, + }, + /// The city's weather changed. + #[game_event(id = 3)] + Weather(Weather), + /// The realm's banner changed. + #[game_event(id = 4)] + Banner { + /// Banner text. + text: String, + }, + /// The hood's boss fell or respawned. + #[game_event(id = 5)] + Boss { + /// `defeated` / `respawned`. + kind: String, + /// Who defeated it. + by: Option, + }, +} + +/// Boss Ripple's client surface. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("ripple").events::() +} + +/// Kind id of [`TierView`] (tests mirror fields by it). +pub const KIND_TIER: u16 = TierView::KIND_ID; /// Input action bit: attack (needs [`REACH`]). -pub const ACTION_ATTACK: u8 = 1; +pub const ACTION_ATTACK: u8 = HoodInput::ATTACK; /// Input action bit: smite (demo shortcut: defeats the boss from anywhere). -pub const ACTION_SMITE: u8 = 2; +pub const ACTION_SMITE: u8 = HoodInput::SMITE; const ATTACK_COOLDOWN: u8 = 8; const MAX_CREDITS: u8 = 4; /// Weather names by index (city). @@ -219,31 +348,30 @@ impl ZoneDirectory for TierPlacement { } /// Hood input: Arena movement + action bits. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] pub struct HoodInput { - /// Movement (Arena step). - pub movement: MoveInput, - /// [`ACTION_ATTACK`] | [`ACTION_SMITE`]. + /// Stick x. + #[range(min = -127, max = 127)] + pub mx: i8, + /// Stick y. + #[range(min = -127, max = 127)] + pub my: i8, + /// [`HoodInput::DASH`]. + #[buttons(dash)] + pub buttons: u8, + /// [`HoodInput::ATTACK`] | [`HoodInput::SMITE`]. + #[buttons(attack, smite)] pub action: u8, } impl HoodInput { - /// Wire payload `[mx, my, buttons, action]`. - pub fn encode(self) -> [u8; 4] { - let [mx, my, buttons] = <[u8; 3]>::try_from(self.movement.to_payload()).expect("3 bytes"); - [mx, my, buttons, self.action] - } - - /// Parse and sanitize. - pub fn decode(payload: &[u8]) -> Option { - let (movement, action) = payload.split_at_checked(3)?; - let [action] = action else { - return None; - }; - Some(Self { - movement: MoveInput::from_payload(movement)?, - action: action & (ACTION_ATTACK | ACTION_SMITE), - }) + /// The movement part (the Arena's step). + pub fn movement(self) -> MoveInput { + MoveInput { + mx: self.mx, + my: self.my, + buttons: self.buttons, + } } } @@ -325,31 +453,31 @@ impl Ripple { } } - fn weather_json(&self) -> Value { - json!({ - "weather": WEATHER[self.weather()], - "remaining": total_bosses() - self.state.defeated.len().min(total_bosses()), - }) + fn weather_record(&self) -> Weather { + Weather { + weather: WEATHER[self.weather()].into(), + remaining: (total_bosses() - self.state.defeated.len().min(total_bosses())) as u32, + } } - fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> Value { + fn hello(&self, ctx: &Ctx<'_, Self>, entity: Option) -> RippleEvent { let tier = self.config.tier; - json!({ - "zone": ctx.zone_id(), - "tier": tier.name(), - "parent": ctx.zone_id().rsplit_once('.').map(|(p, _)| p), - "children": children(ctx.zone_id()), - "host": self.config.host_id, - "tickRate": tier.rates().0, - "entity": entity, - "weather": (tier == TierKind::City).then(|| self.weather_json()), - "banner": self.state.banner, - }) + RippleEvent::Hello { + zone: ctx.zone_id().into(), + tier: tier.name().into(), + parent: ctx.zone_id().rsplit_once('.').map(|(p, _)| p.to_string()), + children: children(ctx.zone_id()), + host: self.config.host_id.clone(), + tick_rate: tier.rates().0, + entity, + weather: (tier == TierKind::City).then(|| self.weather_record()), + banner: self.state.banner.clone(), + } } fn greet(&self, ctx: &mut Ctx<'_, Self>, to: distributed_game::Viewer, entity: Option) { let hello = self.hello(ctx, entity); - send_json_event(ctx, to, EVENT_HELLO, &hello); + ctx.send(to, &hello); } fn defeat(&mut self, ctx: &mut Ctx<'_, Self>, by: String) { @@ -362,7 +490,10 @@ impl Ripple { payload.to_string().into_bytes(), ChildEvent::TO_ROOT, ); - broadcast_json_event(ctx, EVENT_BOSS, &json!({ "kind": "defeated", "by": by })); + ctx.broadcast(&RippleEvent::Boss { + kind: "defeated".into(), + by: Some(by), + }); self.respawn = Some(ctx.set_timeout(RESPAWN, RippleTimer::Respawn)); } @@ -376,7 +507,7 @@ impl Ripple { break; }; let input = input.input; - f.state = movement::step(f.state, input.movement); + f.state = movement::step(f.state, input.movement()); f.credits -= 1; if input.action & ACTION_SMITE != 0 { blows.push((u32::MAX, f.name.clone())); @@ -449,8 +580,8 @@ impl Ripple { ctx.emit_upward(kind, payload, 1); } if self.weather() != weather_before { - let weather = self.weather_json(); - broadcast_json_event(ctx, EVENT_WEATHER, &weather); + let weather = self.weather_record(); + ctx.broadcast(&RippleEvent::Weather(weather)); } } TierKind::Realm => { @@ -471,21 +602,21 @@ impl Ripple { }; if let Some(text) = banner { self.state.banner = text.clone(); - broadcast_json_event(ctx, EVENT_BANNER, &json!({ "text": text })); + ctx.broadcast(&RippleEvent::Banner { text }); } } TierKind::Hood => {} } self.state.events += 1; - let ripple = json!({ - "at": ctx.zone_id(), - "kind": event.kind, - "from": event.from_zone, - "origin": event.origin_zone, - "originTick": event.origin_tick, - "tick": ctx.tick(), - }); - broadcast_json_event(ctx, EVENT_RIPPLE, &ripple); + let ripple = RippleEvent::Ripple { + at: ctx.zone_id().into(), + kind: event.kind.clone(), + from: event.from_zone.clone(), + origin: event.origin_zone.clone(), + origin_tick: event.origin_tick, + tick: ctx.tick(), + }; + ctx.broadcast(&ripple); } } @@ -495,34 +626,7 @@ impl Zone for Ripple { type Timer = RippleTimer; fn schema() -> EntitySchema { - EntitySchema::new() - .kind( - KindDef::new(KIND_TIER, "tier") - .field("defeated", FieldType::U8) - .field("total", FieldType::U8) - .field("cleared", FieldType::U8) - .field("liberated", FieldType::Bool) - .field("weather", FieldType::U8) - .field("clock", FieldType::U32) - .field("events", FieldType::U32), - ) - .kind( - KindDef::new(KIND_BOSS, "boss") - .field("hp", FieldType::U16) - .field("max", FieldType::U16) - .field("by", FieldType::ShortStr), - ) - .kind( - KindDef::new(KIND_PLAYER, "player") - .field("x", movement::POS) - .field("y", movement::POS) - .field("vx", movement::VEL) - .field("vy", movement::VEL) - .field("dash", FieldType::U8) - .field("cd", FieldType::U8) - .field_with_priority("name", FieldType::ShortStr, 0.2) - .priority(2.0), - ) + schema![TierView, BossView, FighterView] } fn on_create(_ctx: &mut Ctx<'_, Self>, config: RippleConfig) -> Self { @@ -594,7 +698,7 @@ impl Zone for Ripple { } fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - HoodInput::decode(payload) + HoodInput::from_payload(payload) } fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { @@ -613,7 +717,10 @@ impl Zone for Ripple { self.state.defeated.remove(ctx.zone_id()); let payload = json!({ "hood": ctx.zone_id() }).to_string().into_bytes(); ctx.emit_upward("boss_respawned", payload, ChildEvent::TO_ROOT); - broadcast_json_event(ctx, EVENT_BOSS, &json!({ "kind": "respawned" })); + ctx.broadcast(&RippleEvent::Boss { + kind: "respawned".into(), + by: None, + }); } } } @@ -629,61 +736,37 @@ impl Zone for Ripple { fn replicate(&self, out: &mut WorldView) { let s = &self.state; - out.push( - EntityState::new( - 1, - KIND_TIER, - 0.0, - 0.0, - vec![ - FieldValue::U(s.defeated.len() as u32), - FieldValue::U(total_bosses() as u32), - FieldValue::U(s.cleared.len() as u32), - FieldValue::Bool(s.liberated), - FieldValue::U(self.weather() as u32), - FieldValue::U(self.ticks), - FieldValue::U(s.events), - ], - ) - .global(), - ); + let tier = TierView { + defeated: s.defeated.len() as u8, + total: total_bosses() as u8, + cleared: s.cleared.len() as u8, + liberated: s.liberated, + weather: self.weather() as u8, + clock: self.ticks, + events: s.events, + }; + out.add(1, &tier); if self.config.tier != TierKind::Hood { return; } - out.push( - EntityState::new( - 2, - KIND_BOSS, - 0.0, - 0.0, - vec![ - FieldValue::U(s.hp), - FieldValue::U(BOSS_HP), - FieldValue::Str(s.defeated_by.clone().unwrap_or_default()), - ], - ) - .global(), - ); + let boss = BossView { + hp: s.hp as u16, + max: BOSS_HP as u16, + by: s.defeated_by.clone().unwrap_or_default(), + }; + out.add(2, &boss); for f in self.fighters.values() { let m = f.state; - out.push( - EntityState::new( - f.entity, - KIND_PLAYER, - m.x, - m.y, - vec![ - FieldValue::F(m.x), - FieldValue::F(m.y), - FieldValue::F(m.vx), - FieldValue::F(m.vy), - FieldValue::U(m.dash.into()), - FieldValue::U(m.cooldown.into()), - FieldValue::Str(f.name.clone()), - ], - ) - .global(), - ); + let view = FighterView { + x: m.x, + y: m.y, + vx: m.vx, + vy: m.vy, + dash: m.dash, + cd: m.cooldown, + name: f.name.clone(), + }; + out.add(f.entity, &view); } } @@ -704,11 +787,12 @@ impl Zone for Ripple { /// Bot / test payload. pub fn encode_input(mx: i8, my: i8, action: u8) -> Vec { HoodInput { - movement: MoveInput { mx, my, buttons: 0 }, + mx, + my, + buttons: 0, action, } - .encode() - .to_vec() + .to_payload() } /// Demo registration (`game-demos ripple`). @@ -780,9 +864,9 @@ mod tests { #[test] fn input_round_trips() { let bytes = encode_input(-128, 5, 0xff); - let input = HoodInput::decode(&bytes).unwrap(); - assert_eq!(input.movement.mx, -127); + let input = HoodInput::from_payload(&bytes).unwrap(); + assert_eq!(input.movement().mx, -127); assert_eq!(input.action, ACTION_ATTACK | ACTION_SMITE); - assert_eq!(HoodInput::decode(&bytes[..3]), None); + assert_eq!(HoodInput::from_payload(&bytes[..3]), None); } } diff --git a/examples/game/server/tests/ripple_smoke.rs b/examples/game/server/tests/ripple_smoke.rs index 6f907c261..4db41702c 100644 --- a/examples/game/server/tests/ripple_smoke.rs +++ b/examples/game/server/tests/ripple_smoke.rs @@ -6,12 +6,10 @@ mod support; use std::time::Duration; -use distributed_game::{FieldValue, Role, ServerMessage}; +use distributed_game::{FieldValue, GameEvent, Role, ServerMessage}; use game_demos::ripple::{ - self, encode_input, RippleDemo, ACTION_ATTACK, ACTION_SMITE, BOROUGHS, CITY, EVENT_BANNER, - EVENT_BOSS, EVENT_HELLO, EVENT_RIPPLE, EVENT_WEATHER, REALM, + self, encode_input, RippleDemo, RippleEvent, ACTION_ATTACK, ACTION_SMITE, BOROUGHS, CITY, REALM, }; -use serde_json::Value; use support::{eventually, join, start_cluster, ticket, Client}; /// Field `i` of the tier entity (id 1) as u32. @@ -23,12 +21,36 @@ fn tier_field(client: &Client, i: usize) -> u32 { } } +/// Wait for the zone's hello: `(zone, tier, entity)`. +async fn hello(c: &mut Client) -> (String, String, Option) { + match c + .wait_event::(|e| matches!(e, RippleEvent::Hello { .. })) + .await + { + RippleEvent::Hello { + zone, tier, entity, .. + } => (zone, tier, entity), + _ => unreachable!(), + } +} + +/// Wait for the next boss event's kind. +async fn boss(c: &mut Client) -> String { + match c + .wait_event::(|e| matches!(e, RippleEvent::Boss { .. })) + .await + { + RippleEvent::Boss { kind, .. } => kind, + _ => unreachable!(), + } +} + async fn observe(base: &str, zone: &str) -> Client { let mut c = join(base, zone, &ticket("guest-watch", zone, Role::Observer)) .await .unwrap(); - let hello = c.json_event(EVENT_HELLO).await; - assert_eq!(hello["zone"], zone); + let (at, _, _) = hello(&mut c).await; + assert_eq!(at, zone); c.until("tier entity", |c| c.mirror.entities.contains_key(&1)) .await; c @@ -61,15 +83,14 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { .await .unwrap(); assert_eq!(fighter.welcome.tick_rate, 30, "hot neighborhood"); - let hello = fighter.json_event(EVENT_HELLO).await; - assert_eq!(hello["tier"], "hood"); - assert!(hello["entity"].as_u64().is_some()); + let (_, tier, entity) = hello(&mut fighter).await; + assert_eq!(tier, "hood"); + let me = entity.expect("own fighter"); let deadline = tokio::time::Instant::now() + Duration::from_secs(20); let mut defeated = None; while defeated.is_none() { assert!(tokio::time::Instant::now() < deadline, "boss not defeated"); // Steer toward the boss at the center, attacking once in reach. - let me = hello["entity"].as_u64().unwrap() as u32; let (x, y) = match fighter .mirror .entities @@ -86,22 +107,24 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { .await; while let Some(msg) = fighter.next(Duration::from_millis(33)).await { if let ServerMessage::Event { type_id, payload } = msg { - if type_id == EVENT_BOSS { - defeated = Some(serde_json::from_slice::(&payload).unwrap()); + if let Some(RippleEvent::Boss { kind, .. }) = + RippleEvent::decode_event(type_id, &payload).unwrap() + { + defeated = Some(kind); } } } } - assert_eq!(defeated.unwrap()["kind"], "defeated"); + assert_eq!(defeated.unwrap(), "defeated"); // The rest of borough-1 by smiting. for hood in &ripple::hoods(BOROUGHS[0])[1..] { let mut c = join(&base, hood, &ticket("guest-smiter", hood, Role::Player)) .await .unwrap(); - c.json_event(EVENT_HELLO).await; + hello(&mut c).await; c.input(encode_input(0, 0, ACTION_SMITE)).await; - assert_eq!(c.json_event(EVENT_BOSS).await["kind"], "defeated"); + assert_eq!(boss(&mut c).await, "defeated"); let state = cluster .host("A") .demo @@ -115,7 +138,16 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { tier_field(c, 0) == 3 && tier_field(c, 2) == 1 }) .await; - let ripples = borough.seen(EVENT_RIPPLE); + let ripples: Vec<(String, String, String)> = borough + .seen_events::() + .into_iter() + .filter_map(|e| match e { + RippleEvent::Ripple { + at, kind, origin, .. + } => Some((at, kind, origin)), + _ => None, + }) + .collect(); city.until("city saw the borough cleared", |c| { tier_field(c, 2) == 1 && tier_field(c, 0) == 3 }) @@ -133,15 +165,18 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { let mut c = join(&base, &hood, &ticket("guest-smiter", &hood, Role::Player)) .await .unwrap(); - c.json_event(EVENT_HELLO).await; + hello(&mut c).await; c.input(encode_input(0, 0, ACTION_SMITE)).await; - c.json_event(EVENT_BOSS).await; + boss(&mut c).await; } - let banner = realm.json_event(EVENT_BANNER).await; - assert!( - banner["text"].as_str().unwrap().contains("liberated"), - "{banner}" - ); + let banner = match realm + .wait_event::(|e| matches!(e, RippleEvent::Banner { .. })) + .await + { + RippleEvent::Banner { text } => text, + _ => unreachable!(), + }; + assert!(banner.contains("liberated"), "{banner}"); realm .until("realm state", |c| { tier_field(c, 0) == 6 && tier_field(c, 2) == 2 && tier_field(c, 3) == 1 @@ -152,9 +187,12 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { }) .await; let weather: Vec = city - .seen(EVENT_WEATHER) - .iter() - .map(|w| w["weather"].as_str().unwrap().to_string()) + .seen_events::() + .into_iter() + .filter_map(|e| match e { + RippleEvent::Weather(w) => Some(w.weather), + _ => None, + }) .collect(); assert_eq!( weather.last().map(String::as_str), @@ -166,11 +204,11 @@ async fn boss_defeats_ripple_up_every_tier_across_hosts() { // Borough-1's ripple events name each hood as origin and the borough as receiver. let origins: std::collections::BTreeSet = ripples .iter() - .filter(|r| r["kind"] == "boss_defeated") - .map(|r| r["origin"].as_str().unwrap().to_string()) + .filter(|(_, kind, _)| kind == "boss_defeated") + .map(|(_, _, origin)| origin.clone()) .collect(); assert!(origins.len() >= 2, "{ripples:?}"); - assert!(ripples.iter().all(|r| r["at"] == BOROUGHS[0])); + assert!(ripples.iter().all(|(at, _, _)| at == BOROUGHS[0])); // The cascade's state lives where each tier runs. let city_state = cluster diff --git a/examples/game/server/tests/support/mod.rs b/examples/game/server/tests/support/mod.rs index ac991e866..09b17fea0 100644 --- a/examples/game/server/tests/support/mod.rs +++ b/examples/game/server/tests/support/mod.rs @@ -250,30 +250,6 @@ impl Client { } } - /// JSON events of `type_id` received so far. - pub fn seen(&self, type_id: u32) -> Vec { - self.events - .iter() - .filter(|(t, _)| *t == type_id) - .filter_map(|(_, p)| serde_json::from_slice(p).ok()) - .collect() - } - - /// Wait for the first JSON event of `type_id`. - pub async fn json_event(&mut self, type_id: u32) -> Value { - let deadline = tokio::time::Instant::now() + Duration::from_secs(5); - loop { - let left = deadline.saturating_duration_since(tokio::time::Instant::now()); - match self.next(left).await.expect("event within 5 s") { - ServerMessage::Event { - type_id: t, - payload, - } if t == type_id => return serde_json::from_slice(&payload).unwrap(), - _ => continue, - } - } - } - /// Read messages until `pred` holds (10 s). pub async fn until(&mut self, what: &str, pred: impl Fn(&Client) -> bool) { let deadline = tokio::time::Instant::now() + Duration::from_secs(10); From 3ca30e68fbaf9dbd2e926ea2c2077ed15ca3b4b9 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:03:40 -0500 Subject: [PATCH 189/484] fix(game): resolve derive paths in the crate's own doctests --- distributed_game/src/lib.rs | 4 ++++ distributed_game_macros/src/shared.rs | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index b47a14a78..230937347 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -37,6 +37,10 @@ #![warn(missing_docs)] +// Lets the authoring derives' `::distributed_game::…` paths resolve inside +// this crate too. +extern crate self as distributed_game; + pub mod authoring; #[cfg(feature = "bots")] pub mod bots; diff --git a/distributed_game_macros/src/shared.rs b/distributed_game_macros/src/shared.rs index 8b7bb5597..3d21cd2ea 100644 --- a/distributed_game_macros/src/shared.rs +++ b/distributed_game_macros/src/shared.rs @@ -10,7 +10,11 @@ use syn::{Attribute, Data, DeriveInput, Expr, Field, Fields, Ident, LitStr, Type /// crate itself included). pub(crate) fn runtime() -> syn::Result { let root = match crate_name("distributed_game") { - Ok(FoundCrate::Itself) => quote!(crate), + // `::distributed_game`, not `crate`: doctests of the crate itself + // report `Itself` but compile as a separate crate. The lib declares + // `extern crate self as distributed_game` so the path also works + // inside it. + Ok(FoundCrate::Itself) => quote!(::distributed_game), Ok(FoundCrate::Name(name)) => { let ident = Ident::new(&name, Span::call_site()); quote!(::#ident) From 20adcaf0e607cc0af74406246d154c73c338909f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:03:41 -0500 Subject: [PATCH 190/484] docs(game): document derive-based zones and generated clients Rewrite the Build a zone walkthrough and guides around the authoring derives, document game-manifest / game-client and the typed payload codec (informative PROTOCOL.md section), and describe how the demos are authored. Fix run.sh gen cleanup under set -u. --- distributed_cli/README.md | 36 ++++++ distributed_game/PROTOCOL.md | 35 +++++ distributed_game/README.md | 243 +++++++++++++++++++++++++++-------- examples/game/README.md | 69 +++++++--- examples/game/run.sh | 12 +- js/README.md | 11 ++ 6 files changed, 330 insertions(+), 76 deletions(-) diff --git a/distributed_cli/README.md b/distributed_cli/README.md index bf7747f4a..10213cc7e 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -267,6 +267,42 @@ prove ownership. Unsupported or unprovable selections fail at build time with their source location; the compiler does not emit a partial normalization plan or an adapter-specific route registry. +## `distributed game-manifest` / `distributed game-client` — typed game clients + +For [`distributed_game`](../distributed_game/README.md#generated-clients) +zones. The zone's authoring derives (`#[derive(Replicated)]`, +`#[derive(GameInput)]`, `#[derive(GameEvent)]`) describe a versioned +`GameSurface` (schema v1): kinds with fields, wire types, priorities and +client correction defaults, the input layout with its sanitize rules, +events and the records they mention. It is deliberately separate from the +GraphQL client manifest above. + +```bash +# Build and run the crate's surface export through the manifest harness +# (default entrypoint `::game_surface`). +distributed game-manifest --manifest-path game/Cargo.toml \ + --entrypoint my_game::arena::game_surface --out target/arena.surface.json + +# Generate TypeScript (imports only `@hops-ops/distributed/game`). +distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena + +# CI: compare without writing (also catches surface drift via surface.json) +distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena --check +``` + +`game-manifest` accepts the same `--path` / `--manifest-path` / +`--package` / `--features` / `--no-default-features` options as `describe` +and validates the JSON it prints (or writes with `--out`). `game-client` +owns its `--out` directory: it writes `schema.ts` (kind ids, typed field +interfaces and accessors, wire types, correction defaults), `input.ts` +(input interface, bit maps, encoder/decoder/sanitize), `events.ts` (record +and event types, codecs, `onEvent`), `client.ts` (`createClient`, a +`GameClient` with the encoder and corrections wired in and typed `on`), +`index.ts` and `surface.json`, removes stale files it generated earlier, +and refuses to delete files it did not. Output is deterministic. +`--import-extension ts|js|none` picks the specifier style between the +generated files (default `ts`, for Vite and Node type stripping). + ## `distributed describe` — manifest as JSON ```bash diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md index a4b38a3af..52a12eb94 100644 --- a/distributed_game/PROTOCOL.md +++ b/distributed_game/PROTOCOL.md @@ -534,6 +534,10 @@ distributed_game --test golden`; a drift fails the test): - `messages.json` — `{messages: [{name, direction, hex, decoded, known_entities?, schema?}]}`. Delta entries include the schema and the `known_entities` (`[{id, kind}]`) needed to decode updates. +- `authoring.json` (`--test authoring`) — a sample game surface and + input / event payloads encoded with the typed payload codec (§11), with + their expected TypeScript values; generated clients are round-tripped + against it (`js/tests/game-generated.test.mjs`). JSON conventions in `decoded`: @@ -558,3 +562,34 @@ error codes and treat them as "session over" / "request failed"): - Kick code `7` RELOAD. - Transfer tickets (§8.1) and content-version policies (§8.2); `Handoff` and `Freeze`/`Resume` encodings are unchanged. + +## 11. Typed payload codec (informative) + +`Input.payload` and `Event.payload` stay game-defined; this section is not +part of the frame format and changes nothing above. It specifies the +encoding the authoring derives (`#[derive(GameInput)]`, +`#[derive(GameEvent)]`, `#[derive(GameRecord)]`, `distributed_game::codec`) +and generated clients use, so both sides of a game can agree on it from a +game surface (`GameSurface` JSON, schema v1). + +A payload is its fields concatenated in declaration order, no tags or +lengths between fields. A whole payload must be consumed (trailing bytes +are an error). Field encodings: + +| Wire type | Encoding | +|---|---| +| `bool`, `u8`, `u16`, `u32`, `i32`, `f32`, `quant`, `angle`, `short_str`, `bytes` | exactly as the §4 field type of the same name (`quant` = `quant_f32`) | +| `i8` | one byte, two's complement | +| `i16` | zigzag `varint`, rejected outside `-32768..=32767` | +| `u64` | unsigned LEB128 like `varuint`, up to 8 bytes, value ≤ `2^53 − 1` (encoders saturate; JavaScript decodes it exactly) | +| `f64` | binary64 LE | +| `str` | `string` (§2: `varuint` length + UTF-8) | +| `list` | `varuint` count, then the items | +| `optional` | `u8` 0 (absent) or 1 followed by the value; other tags are invalid | +| `record` | the record's fields in order | + +An input decoded by `GameInput::from_payload` is then sanitized: fields +with a `range [min, max]` are clamped (integers truncated after the +clamp), bit-flag fields keep only their named bits, and a non-finite +`f32` rejects the whole input. + diff --git a/distributed_game/README.md b/distributed_game/README.md index f4d6fe2c4..5021362af 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -25,8 +25,8 @@ the browser, but the client SDK has no rendering dependency. - [Try it](#try-it) - [Build a zone](#build-a-zone) - [Guides](#guides): game loop · input · what clients see · the client SDK · - saving progress · scaling out · live updates · lag compensation · - testing and operations · security + generated clients · saving progress · scaling out · live updates · lag + compensation · testing and operations · security - [Design decisions](#design-decisions) - [Status and limits](#status-and-limits) - [Reference](#reference) @@ -64,8 +64,8 @@ The words used throughout: | **Tick** | One fixed simulation step (30 Hz by default). Separate from the **patch** rate (20 Hz by default), how often clients get updates. | | **Player / Observer** | A *player* controls something and sends inputs. An *observer* only watches: a spectator, a leaderboard page, or a client looking into the zone next door. | | **Entity** | Something clients can see. The zone describes its entities each patch; the engine works out what changed for each client. | -| **Schema** | The kinds of entity and their fields (with quantization). Sent to clients on connect, so clients need no generated code. | -| **Fact** | An outcome worth keeping ("Alice killed the elite, +60 XP"). The zone emits it and moves on; a background worker commits it to storage and reports back later. | +| **Schema** | The kinds of entity and their fields (with quantization), usually from `#[derive(Replicated)]` views. Sent to clients on connect, so a generic client needs no generated code; a generated one adds types. | +| **Fact** | An outcome worth keeping ("Alice killed the elite"). The zone emits it (typically the cell command's own input) and moves on; a background worker commits it to storage, where the command decides the reward, and reports back later. | | **Cell** | Durable, event-sourced state in `distributed`, for example one player's profile. Facts usually end up as commands on a cell. | | **Ticket** | A signed, single-use admission token naming the player (principal), the zone and a role. Identity always comes from the ticket, never from game input. | @@ -109,37 +109,61 @@ Then open `http://localhost:5173//`. Each page explains what to try. ## Build a zone -A zone is a struct plus a few trait methods. This one is a dot that -players push left and right: +A zone is a struct plus a few trait methods. You describe **what clients +see**, **what they send** and **what you tell them** as plain Rust structs +with derives; the engine encodes them, and `distributed game-client` +generates the matching TypeScript, so field order, ids and quantization are +written down exactly once. This zone is a dot that players push left and +right: ```rust use std::sync::Arc; use std::time::Duration; use distributed_game::*; +/// What clients see: one replicated kind. Field order is the wire order; +/// the KindDef and the encoding both come from this struct. +#[derive(Replicated)] +#[replicated(kind = "dot", id = 1, global)] +struct DotView { + #[quant(min = -50.0, max = 50.0, bits = 12)] // 12-bit wire precision + #[correct(ease = 100)] // client correction default + x: f32, +} + +/// What a player sends, once per tick. `from_payload` decodes it and +/// clamps `#[range]` fields, so cheating inputs never reach `on_tick`. +#[derive(Clone, Copy, GameInput)] +struct Push { + #[range(min = -1, max = 1)] + dx: i8, +} + +/// One-off messages, with stable ids and typed payloads. +#[derive(GameEvent)] +enum RoomEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, +} + struct Room { x: f32 } impl Zone for Room { type Config = (); - type Input = i8; // -1, 0, 1 + type Input = Push; type Timer = (); - // What clients can see: one kind, "dot", with a quantized x. - fn schema() -> EntitySchema { - EntitySchema::new().kind( - KindDef::new(1, "dot") - .field("x", FieldType::QuantF32 { min: -50.0, max: 50.0, bits: 12 }), - ) - } + fn schema() -> EntitySchema { schema![DotView] } fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { Room { x: 0.0 } } - // Bytes from the client → your input type. Never trust them: - fn decode_input(&self, _p: PlayerId, bytes: &[u8]) -> Option { - bytes.first().map(|b| *b as i8) + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send(player, &RoomEvent::Hello { entity: 1 }); } - fn sanitize_input(&self, _p: PlayerId, dx: i8) -> Option { - (-1..=1).contains(&dx).then_some(dx) + + // Bytes from the client → your input type (decoded and sanitized). + fn decode_input(&self, _p: PlayerId, bytes: &[u8]) -> Option { + Push::from_payload(bytes) } // The game rules, once per tick. @@ -147,26 +171,32 @@ impl Zone for Room { let players: Vec<_> = ctx.players().map(|p| p.id).collect(); for p in players { for input in ctx.take_inputs(p, ConsumePolicy::Drain) { - self.x += f32::from(input.input) * 5.0 * ctx.dt_secs(); + self.x += f32::from(input.input.dx) * 5.0 * ctx.dt_secs(); } } } // Describe the world; the engine diffs it per client. fn replicate(&self, out: &mut WorldView) { - out.push(EntityState::new(1, 1, self.x, 0.0, vec![FieldValue::F(self.x)])); + out.add(1, &DotView { x: self.x }); } } +/// Everything a browser needs to know about this zone, for the generator. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("room").events::() +} + // Drive it directly (tests, tools) with a manual clock: let clock = ManualClock::new(); let mut host = ZoneHost::::new("room-1", HostConfig::default(), Arc::new(clock.clone()), ()); let claims = TicketClaims::new("alice", "room-1", u64::MAX, "n", Role::Player); let joined = host.join(&claims, 0, "").unwrap(); -host.push_input(joined.client, 1, 0, &[1]); +host.push_input(joined.client, 1, 0, &Push { dx: 1 }.to_payload()); clock.advance(Duration::from_millis(100)); host.advance(); for out in host.drain_outbound() { /* Outbound::Frame bytes go to the client */ } +assert_eq!(game_surface().kinds[0].name, "dot"); ``` Serve it over WebSockets (`net` feature). The closure decides which zone @@ -179,25 +209,33 @@ let server = GameServer::::new(ServerConfig::new(TicketKey::new(secret)), server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_signal).await?; ``` -Connect a browser: +Generate the browser client from `game_surface` (see +[Generated clients](#generated-clients)): + +```sh +distributed game-manifest --entrypoint my_game::game_surface --out room.surface.json +distributed game-client --manifest room.surface.json --out web/src/generated/room +``` + +Connect a browser with it. The input encoder, the correction defaults and +the event decoders are generated; you write only the prediction rule (the +same rule as `on_tick`) and drawing: ```ts -import { GameClient, InputPacer } from '@hops-ops/distributed/game'; +import { InputPacer } from '@hops-ops/distributed/game'; +import { createRoomClient, dotFields, isDot } from './generated/room/index.ts'; -const game = new GameClient({ +const room = createRoomClient({ url: (zone) => `wss://game.example/zones/${zone}`, ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role), // your backend signs these - prediction: { - encodeInput: (dx) => new Uint8Array([dx & 0xff]), - predict: (s, dx, dtMs) => ({ x: s.x + (dx * 5 * dtMs) / 1000 }), // same rule as on_tick - controlledEntity: () => 1 - } + prediction: { predict: (s, push, dtMs) => ({ x: Number(s.x) + (push.dx * 5 * dtMs) / 1000 }) } }); -await game.connect('room-1'); -const pacer = new InputPacer({ tickRate: () => game.authority?.connection.welcome?.tickRate }); +room.on('hello', (hello) => room.client.setControlledEntity(hello.entity)); // typed payload +await room.client.connect('room-1'); +const pacer = new InputPacer({ tickRate: () => room.client.authority?.connection.welcome?.tickRate }); requestAnimationFrame(function frame(now) { - pacer.update(now, (dtMs) => game.sendInput(readKeys(), dtMs)); // one input per server tick - draw(game.render()); // entities ready to draw + pacer.update(now, (dtMs) => room.client.sendInput({ dx: readKeys() }, dtMs)); // one input per tick + for (const e of room.client.render()) if (isDot(e)) draw(dotFields(e).x); // typed fields requestAnimationFrame(frame); }); ``` @@ -207,7 +245,10 @@ The rest of `Zone` is optional hooks: `on_auth`, `on_join`, `on_leave`, `on_tier_changed`, `on_dispose`, `hibernate` / `on_restore`, `on_handoff_join`, `on_child_event`, `is_gate`, `freeze_ready`, `on_content_version_changed`, `record_rewind`, `state_hash`. Each is -explained in the guide that uses it. +explained in the guide that uses it. Hand-written schemas +(`EntitySchema::new().kind(KindDef::new(..).field(..))`), `EntityState`s, +byte inputs and `ctx.send_event(viewer, type_id, bytes)` still work; the +derives are a layer over them. ## Guides @@ -240,8 +281,15 @@ rejects duplicates and inputs older than the last processed one, and reports the last processed number back in every Delta. The client uses that to drop inputs the server has already applied when it reconciles. -- `decode_input` turns bytes into your type; `sanitize_input` rejects or - clamps anything a cheater could send (speed hacks, out-of-range values). +- `#[derive(GameInput)]` generates a compact codec for an input struct + (`i8`/`u8`/`i16`/`u16`/`i32`/`u32`/`bool`/`f32`, `#[quant]` / `#[angle]` + floats) and its sanitize: `#[range(min, max)]` **clamps**, a + `#[buttons(dash, attack)]` bit field clears unknown bits (and gets + `Input::DASH`, `Input::ATTACK` constants), any non-finite `f32` rejects + the input, and a frame of the wrong length is dropped. `decode_input` + is then one line: `MyInput::from_payload(bytes)`. Hand-written + `decode_input` / `sanitize_input` (rejecting or clamping anything a + cheater could send) keep working. - `ctx.take_inputs(player, ConsumePolicy::…)` reads them in `on_tick`. `InputCredits` allows one input per tick per player (with a small bank for network jitter), so flooding inputs cannot make anyone move faster. @@ -255,9 +303,19 @@ that to drop inputs the server has already applied when it reconciles. ### What each client sees -Each patch, `replicate` describes every entity once, as `EntityState`s -with a position and the schema's fields. For each client the engine then -sends only the difference from what that client already has: +Each patch, `replicate` describes every entity once: `out.add(id, &view)` +with a `#[derive(Replicated)]` view (or a hand-built `EntityState`). The +view's struct is the kind: `#[replicated(kind = "mob", id = 2, priority = +2.0, global)]`, one field per replicated field in wire order (`bool`, `u8`, +`u16`, `u32`, `i32`, `f32`, `String` as a short string, `Vec` as +bytes), `#[quant(min, max, bits)]` / `#[quant(centered = R, bits)]` (zero +exact) / `#[angle(bits)]` / `#[field_type(EXPR)]` for floats, +`#[priority(p)]`, and `#[correct(ease = ms | snap | replace)]` client +defaults. The interest position is the `x` / `y` fields (or +`#[replicated(x = .., y = ..)]`); a kind without one must be `global`. +`out.add(..)` returns a handle for `.global()`, `.local()`, `.priority(p)`. +For each client the engine then sends only the difference from what that +client already has: - **Schema and quantization.** Fields are typed (`QuantF32`, integers, booleans, strings, …). Floats are quantized to the precision you choose, @@ -271,9 +329,15 @@ sends only the difference from what that client already has: (4 KiB). Creates and updates compete by priority (kind × entity × field × nearness). Anything deferred builds up priority, so it is always sent eventually. -- **Events** (`ctx.send_event(viewer, type_id, bytes)`, - `ctx.broadcast_event(type_id, bytes)`) carry one-off messages such as "kill", "saved" or "weather changed" next to the - Deltas. +- **Events** carry one-off messages such as "kill", "saved" or "weather + changed" next to the Deltas. Declare them as a `#[derive(GameEvent)]` + enum (each variant `#[game_event(id = N)]`: unit, named fields, or one + value such as a `#[derive(GameRecord)]` struct) or struct, and send them + with `ctx.send(viewer, &event)` / `ctx.broadcast(&event)`. Payloads use + the same value codec as entity fields plus `i8`/`i16`/`u64`/`f64`, + `#[long]` strings, `Vec`, `Option` and nested records. + `E::decode_event(type_id, bytes)` decodes them (bots, tests). The raw + `ctx.send_event(viewer, type_id, bytes)` remains for custom payloads. Wire details are in [`PROTOCOL.md`](PROTOCOL.md). @@ -281,7 +345,8 @@ Wire details are in [`PROTOCOL.md`](PROTOCOL.md). `GameClient` (`@hops-ops/distributed/game`) handles the connection, reconnection and clock sync, and gives you `render()`: a list of entities -ready to draw. +ready to draw. A [generated client](#generated-clients) wraps it with your +zone's typed fields, input encoder, events and correction defaults. - **Interpolation.** Other entities are drawn a little in the past, between two received states, so movement is smooth whatever the network @@ -302,20 +367,68 @@ ready to draw. a newer content version, and the client rejoins afterwards with the same player. +### Generated clients + +The derives also describe the zone for the browser. A **game surface** +(`GameSurface`, versioned JSON, schema v1) lists the zone's kinds with +their fields, wire types, priorities and correction defaults, its input +layout and sanitize rules, its events and the records they mention. +Export one function per zone type, conventionally `game_surface`: + +```rust,ignore +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("arena").events::() +} +``` + +`distributed game-manifest` builds and runs it (through the same harness +as `distributed describe`), and `distributed game-client --manifest + --out [--check]` writes framework-neutral TypeScript that +imports only `@hops-ops/distributed/game`: + +| File | Contents | +|---|---| +| `schema.ts` | `KIND` ids, `PlayerFields` interfaces with `isPlayer(e)` / `playerFields(e)` over rendered or replica entities (camelCase properties), `FIELD_TYPES`, `CORRECTIONS` | +| `input.ts` | the input interface, `BITS` / `BUTTON`, `encodeInput`, `decodeInput`, `sanitizeInput` (what the server will simulate) | +| `events.ts` | record and event interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | +| `client.ts` | `createClient(options)`: a `GameClient` with the encoder and correction defaults wired in, a typed `on(name, handler)` and `send(input)` | +| `index.ts`, `surface.json` | re-exports; the surface it came from | + +The output is deterministic, so check it in and run `--check` in CI: a +changed Rust definition then fails the build until the client is +regenerated. The binary protocol is unchanged; the generated code only +removes the hand-written glue around it. Prediction functions stay +hand-written (they must match `on_tick` bit for bit), but they use the +generated input type, sanitize and field wire types. + ### Saving progress without pausing the game The rule: **the tick never waits for storage.** A slow disk or a busy -database must not freeze the world. Zones emit **facts** and continue: +database must not freeze the world. Zones emit **facts** and continue. +A fact is the cell command's own input type, bound to the command name +with `#[derive(FactCommand)]` (pointing at the same constant the cell +mounts the command under): ```rust,ignore -let key = ctx.fact_key("kill", &[&mob_id, &mob_generation]); -ctx.emit_fact_for(killer, Fact::new(key, "crawler.record_kill", json!({"mob": "elite"})))?; +#[derive(Serialize, CommandInput, FactCommand)] +#[fact(command = RECORD_KILL)] // typed_command::(RECORD_KILL) +pub struct RecordKillInput { pub mob: String, pub tier: u8 } + +// in on_tick: key "crawler.record_kill:{zone}:{boot_epoch}:m{mob}:{generation}" +ctx.emit_keyed(killer, RecordKillInput { mob, tier }, &[&format_args!("m{id}"), &generation])?; ``` - The host attaches the killer's **verified identity** from their ticket. The zone cannot claim to be someone else, and the payload names no - reward amount; the storage side decides the XP from the facts it - trusts. + reward amount; the command handler decides the XP from what it trusts. + The derive refuses identity- or reward-looking fields (`principal`, + `user_id`, `owner`, `xp`, `reward`, … including serde renames) at + compile time. +- Keys are restart-safe automatically: `ctx.emit(player, input)` uses the + input's `#[fact(key(field, ..))]` parts, or the tick and emission order; + `ctx.emit_keyed` takes explicit parts; `ctx.emit_zone` emits a zone + fact with no principal; `ctx.fact(&input)` builds the `Fact` for a retry + backlog. `Fact::new(key, command, json)` still works. - A background worker commits facts with retries. `cell::CellFactSink` turns each one into a command on that player's cell, with a command id derived from the fact key. A retry or a @@ -440,11 +553,28 @@ unlimited rewind. # Reference +## Authoring derives + +Re-exported from `distributed_game_macros`; each has spanned compile +errors for unsupported types and attributes. + +| Derive | On | Container attribute | Field attributes | Implements | +|---|---|---|---|---| +| `Replicated` | struct | `#[replicated(kind = "name", id = N, priority = P, global, x = f, y = f)]` | `quant`, `angle`, `field_type`, `priority`, `correct` | `Replicated` (`kind_def`, `field_values`, `position`) | +| `GameInput` | struct | – | `range`, `buttons`, `quant`, `angle`, `field_type` | `GameInput` (`from_payload`, `to_payload`, `sanitize`) + button consts | +| `GameEvent` | enum / struct | `#[game_event(id = N, name = "..")]` per variant / on the struct | `quant`, `angle`, `field_type`, `long` | `GameEvent` (`decode_event`, `to_payload`) + id consts | +| `GameRecord` | struct | – | `quant`, `angle`, `field_type`, `long` | `Wire` (nested payload record) | +| `FactCommand` | struct (`Serialize`) | `#[fact(command = CONST_OR_LITERAL, key(field, ..))]` | – | `FactCommand` (`COMMAND`, `dedupe_parts`) | + +`schema![A, B]` builds an `EntitySchema`; `GameSurface::for_zone::(name)` +(kinds from `Z::schema()`, input from `Z::Input`) `.events::()` builds +the surface; `codec` holds the shared value codec (`Wire`, `WireType`). + ## Features | Feature | Adds | Deps | |---|---|---| -| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication | `serde_json` | +| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication, authoring derives, game surface | `serde`, `serde_json`, `distributed_game_macros` | | `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | | `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | | `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | @@ -455,13 +585,20 @@ unlimited rewind. ## Durable facts -Zones never await storage. Emit a fact during a tick: +Zones never await storage. Emit a fact during a tick — typed (the cell +command's input with `#[derive(FactCommand)]`, key derived for you) or by +hand: ```rust,ignore -let key = ctx.fact_key("kill", &[&enemy_id, &enemy_generation]); // "kill:{zone}:{boot_epoch}:…" -ctx.emit_fact_for(player, Fact::new(key, "hero.credit_xp", json!({"amount": 25})))?; +ctx.emit_keyed(player, SlayInput { enemy: enemy_id }, &[&enemy_id, &enemy_generation])?; +// "hero.slay:{zone}:{boot_epoch}:{enemy}:{generation}"; or by hand: +let key = ctx.fact_key("slay", &[&enemy_id, &enemy_generation]); // "slay:{zone}:{boot_epoch}:…" +ctx.emit_fact_for(player, Fact::new(key, "hero.slay", json!({"enemy": enemy_id})))?; ``` +Settlements: `settlement.is::()`, and +`receipt.payload_as::()` for the command's typed output. + > **Warning — restart-safe keys.** Ticks, entity ids and generations all > restart from zero when a process restarts (or a zone is re-activated from > a snapshot). A key derived only from them — `format!("kill:{zone}:{tick}")` diff --git a/examples/game/README.md b/examples/game/README.md index 506309bea..9226edc41 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -16,7 +16,25 @@ guests and lets any page change the network simulation. | **Endless Grid** | `./run.sh grid` | Seeded procedural world (terrain/biomes/props generated bit-identically in Rust and TS, nothing static replicated), 32 m cells as zones, observer connections to the 8 neighbours, handoff across borders **and hosts** (2 processes, hash ring, Redirect + transfer tickets), hibernation to SQLite and restore | | **Boss Ripple** | `./run.sh ripple` | Zone hierarchy realm › city › borough › hood (`DottedTopology`), per-tier tick rates (2/5/10/30 Hz), boss defeats propagating up as tier-up events (each hop on another host), parent broadcasts reaching players through observer connections | -`./run.sh smoke` runs every demo's smoke tests; `./run.sh list` lists demos. +`./run.sh smoke` runs every demo's smoke tests (and checks the generated +clients are current); `./run.sh gen` regenerates the clients; `./run.sh +list` lists demos. + +**How the demos are written.** Each zone describes its world with the +`distributed_game` authoring derives: `#[derive(Replicated)]` view structs +for the kinds (`arena::PlayerView`, `mobpit::zone::MobView`, …), +`#[derive(GameInput)]` for the input frame (`arena::movement::MoveInput`, +`gallery::ShotInput`, …), `#[derive(GameEvent)]` enums for events +(`mobpit::zone::PitEvent`) and `#[derive(FactCommand)]` on the cell +command inputs they emit as facts (`mobpit::crawler::RecordKillInput`). +Each demo module exports `game_surface()`; `run.sh gen` runs `distributed +game-manifest` on it and `distributed game-client` writes +`client/src/generated//` (checked in, verified by `run.sh smoke`). +The pages use the generated `createClient`, typed field accessors +(`mobFields(entity).hp`), the input encoder and typed `on('kill', …)` +handlers; only the prediction steps (`arena/movement.ts`, `grid/world.ts`, +twins of the Rust step) are hand-written, and they import the generated +input type, sanitize and wire quantization. Requirements: Rust (stable), Node ≥ 22.18 (runs `.ts` test imports natively). @@ -84,9 +102,11 @@ the scene from *its own* pack. next rollout times out (`NotAcked: beta/freeze-ember`) and every zone resumes on the old version with "update aborted". -Each zone switch emits a `freeze.content_applied` fact and a stamped event; -gems emit `freeze.gem_collected` facts — the admin panel lists them with -their stamp. Display names live on the primary host: a player joining Ember +Each zone switch emits a typed `ContentApplied` fact +(`freeze.content_applied`) and a stamped event; gems emit `GemCollected` +facts (`freeze.gem_collected`, naming the gem spot — the gem's value is a +content-pack rule for the handler, not a zone-reported amount) — the admin +panel lists them with their stamp. Display names live on the primary host: a player joining Ember Fields directly (`&zone=freeze-ember`) shows as a guest there, names carry over portals. @@ -168,7 +188,7 @@ hood to fight there. │ ├ EntityReplica (interp.) │ ◄─ Welcome/Delta │ └ GameServer::serve_with │ │ └ Predictor ── movement.ts ═╪═ parity fixture ═╪══► ZoneHost 30 Hz │ │ src/shared/ hud · input · scene │ │ └ arena::movement (twin) │ - │ dev-api · events │ GET /metrics │ GET /metrics (Prometheus) │ + │ src/generated/arena (typed glue) │ GET /metrics │ GET /metrics (Prometheus) │ └──────────────────────────────────┘ └─────────────────────────────────────┘ ``` @@ -188,7 +208,7 @@ examples/game/ fixtures/ cross-language golden data (Rust writes, TS checks) server/ Rust crate `game_demos`, its own cargo workspace src/main.rs `game-demos ` subcommands - src/common/ shared: Demo trait, run/spawn, dev routes, guests, JSON events + src/common/ shared: Demo trait, run/spawn, dev routes, guests src/cluster.rs multi-host demos: --host-id/--peer, directory, ownership, snapshots src/arena/ Arena zone + movement.rs (twin of client movement.ts) src/mobpit/ Mob Pit zone, Crawler cell aggregate, fact sink, leaderboards, dev routes @@ -202,7 +222,9 @@ examples/game/ ripple_smoke.rs (+ support/ for two in-process hosts) client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html - src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, events.ts, style.css + src/generated// generated by `run.sh gen` (do not edit): schema/input/events/client.ts, + surface.json; `mobpit` also serves the leaderboard page + src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, latest.ts, style.css src/arena/ client.ts (headless), main.ts (Babylon), movement.ts src/mobpit/ client.ts (headless + /dev/mobpit API), main.ts (Babylon), style.css src/leaderboard/ main.ts (DOM page over the observer connection), style.css @@ -236,9 +258,11 @@ after dying. Level `n` starts at `40·(n−1)²` XP. **One kill, end to end** (`server/src/mobpit/`): -1. `zone.rs`, tick N: the mob's HP reaches 0. The zone calls - `ctx.emit_fact_for(killer, Fact::new(ctx.fact_key("kill", &[m{id}, gen]), - "crawler.record_kill", {mob, tier, name}))` and broadcasts a `kill` event. +1. `zone.rs`, tick N: the mob's HP reaches 0. The zone builds the cell + command's own input, `RecordKillInput { mob, tier, name }` — a + `#[derive(FactCommand)]` bound to `RECORD_KILL` — as a typed fact with + `ctx.fact_with_key(&input, &[m{id}, gen])`, emits it with + `ctx.emit_fact_for(killer, fact)` and broadcasts a typed `kill` event. `emit_fact_for` only enqueues: the host binds the killer's **verified ticket principal**; the zone never awaits storage. Backpressure (256 unsettled facts) parks facts in a backlog retried next tick. @@ -292,7 +316,7 @@ back from the cell. What survives: - **Retries and replays** of the same key (the worker's retry after a timeout, or a re-emitted fact) replay the stored receipt through the ledger: `replayed: true`, nothing credited twice. Fact keys - (`kill:{zone}:{boot_epoch}:m{id}:{gen}`) contain the activation's boot + (`crawler.record_kill:{zone}:{boot_epoch}:m{id}:{gen}`) contain the activation's boot epoch (`Ctx::boot_epoch`, grows across restarts) because zone ticks and mob generations restart at 0. @@ -343,8 +367,15 @@ pending, recent commits), `GET /dev/mobpit/crawlers` (every cell on disk), variant to `DemoCommand` in `main.rs`. You get `/dev/ticket`, `/dev/netsim`, `/metrics`, `--port/--dev/--secret`, graceful shutdown. - Display names: `guests.name(&ctx.player(p)?.principal)` in `on_join`. - - Low-rate events: `common::send_json_event` / `broadcast_json_event`. - - Signed quantities that must rest at zero: `FieldType::quant_centered`. + - Kinds: `#[derive(Replicated)]` views, `schema![..]` in `Zone::schema`, + `out.add(id, &view)` in `replicate`. Input: `#[derive(GameInput)]`, + `decode_input` = `MyInput::from_payload(bytes)`. Events: a + `#[derive(GameEvent)]` enum sent with `ctx.send` / `ctx.broadcast`. + Facts: the cell command input with `#[derive(FactCommand)]`. + - Export `pub fn game_surface() -> GameSurface` from the module and add + the demo to `SURFACES` in `run.sh`; `./run.sh gen` writes + `client/src/generated//`. + - Signed quantities that must rest at zero: `#[quant(centered = R, bits = N)]`. - State shared by the zones and demo-specific dev routes (a durable store, a leaderboard): build both in `common::spawn_with` / `common::run_with` (see `mobpit::spawn` / `mobpit::run`). @@ -353,11 +384,13 @@ pending, recent commits), `GET /dev/mobpit/crawlers` (every cell on disk), `distributed_game::bots::run_bots` (custom `encoder` for your input). 3. **Client** — `client//index.html` + `src//main.ts`, add the name to `DEMOS` in `vite.config.ts` and a link in `index.html`. Keep - networking in `src//client.ts` (no Babylon) so Node can test it. - Reuse `DevApi` + `zoneUrl` (tickets), `Hud` (status/RTT/jitter/tick/ - delta B/s/entities + NetSim sliders + `row`/`toggle`), `InputSampler`, - `FixedRate`, `cameraRelative`, `toAxis`, `createStage`/`toWorld`/ - `material`/`createRing`/`LabelLayer`, `onJsonEvent`. + networking in `src//client.ts` (no Babylon) so Node can test it: + a thin wrapper over the generated `createClient` (URLs, tickets, + your `predict`). Reuse `DevApi` + `zoneUrl` (tickets), `Hud` (status/RTT/ + jitter/tick/delta B/s/entities + NetSim sliders + `row`/`toggle`), + `InputSampler`, `FixedRate`, `cameraRelative`, `toAxis`, + `createStage`/`toWorld`/`material`/`createRing`/`LabelLayer`, `latest` + (latest value of a typed event, e.g. the hello). 4. **Headless test** — `client/tests/-headless.test.mjs` with `startDemo('')` from `tests/helpers/demo-server.mjs`. 5. Register the demo in `run.sh` (`DEMOS=(…)`) and in the table above. diff --git a/examples/game/run.sh b/examples/game/run.sh index 26254bb5c..e219154b9 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -73,15 +73,17 @@ ensure_cli() { gen() { local check="${1:-}" ensure_cli - local tmp + local tmp status=0 tmp="$(mktemp -d "${TMPDIR:-/tmp}/game-surfaces.XXXXXX")" - trap 'rm -rf "$tmp"' RETURN for surface in "${SURFACES[@]}"; do "$CLI" game-manifest --manifest-path "$SERVER/Cargo.toml" \ - --entrypoint "game_demos::$surface::game_surface" --out "$tmp/$surface.json" - "$CLI" game-client --manifest "$tmp/$surface.json" \ - --out "$CLIENT/src/generated/$surface" $check + --entrypoint "game_demos::$surface::game_surface" --out "$tmp/$surface.json" && + "$CLI" game-client --manifest "$tmp/$surface.json" \ + --out "$CLIENT/src/generated/$surface" $check || + status=1 done + rm -rf "$tmp" + return "$status" } run_demo() { diff --git a/js/README.md b/js/README.md index 51a3957c9..0eea9695f 100644 --- a/js/README.md +++ b/js/README.md @@ -632,6 +632,17 @@ server-side lag compensation (`replica.interpolationDelayMs`, `connection.stats` exposes cumulative bytes/messages in and out (Delta bytes separately) for bandwidth HUDs. +**Generated clients.** Rather than writing `encodeInput`, field names, +event ids and correction tables by hand, generate them from the zone's +Rust definitions: `distributed game-manifest` + `distributed game-client` +(see the [`distributed_game` README](../distributed_game/README.md#generated-clients)) +write a typed module per zone that wraps this `GameClient` — +`createArenaClient(options)`, `playerFields(entity)`, `encodeInput`, +`sanitizeInput`, typed `on('hello', …)`. It builds on the SDK's typed +payload codec (`encodePayload`, `decodePayload`, `sanitizePayload`, +`WireType`) and helpers (`onGameEvent`, `decodeGameEvent`, `fieldNumber`, +`mergeCorrections`), which hand-written code may use directly. + ## Protocol and security boundaries Every accepted artifact and response is protocol v1 and carries an exact From 8c9f211415cc986bb6605ce1b34ef2b2794c7318 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 10:56:12 -0500 Subject: [PATCH 191/484] chore: ignore build output of CLI fixture crates --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 05bdbb792..28784b1d2 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,6 @@ tests/celld/worker/build/ tests/celld/worker/.celld/ tests/celld/relay-worker/target/ tests/celld/relay-worker/build/ + +# Build output of CLI test fixture crates +/distributed_cli/tests/fixtures/*/target/ From a9b99bee054d56754dc717fec30b77f01dedba3e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:52:20 -0500 Subject: [PATCH 192/484] feat(game-sdk): predict with WASM steps over a binary ABI createWasmPrediction wraps a zone's Rust step compiled to WebAssembly as a PredictFn. PredictModule instantiates a self-contained module (no imports; memory, dg_predict_abi, dg_predict_buffer and one dg_predict_ export), writes state, input payload and context into its 64 KiB scratch buffer and reads the next state back. State uses the payload codec, so binary32 floats never round-trip through JSON or f64. Modules load from URLs (file: in Node), bytes, responses or compiled modules and are shared per URL; predict is a no-op until the module is ready and, for steps with a context, until setContext. --- examples/game/client/src/arena/movement.ts | 176 --------- .../client/tests/movement-parity.test.mjs | 58 --- examples/game/fixtures/arena-movement.json | 364 ------------------ .../arena/movement.rs => sim/src/arena.rs} | 0 .../{src/grid/world.rs => sim/src/grid.rs} | 0 .../game/server/tests/movement_fixture.rs | 111 ------ js/src/game/index.ts | 14 + js/src/game/wasm-prediction.ts | 303 +++++++++++++++ js/tests/fixtures/predict-module.mjs | 72 ++++ js/tests/game-wasm-prediction.test.mjs | 119 ++++++ 10 files changed, 508 insertions(+), 709 deletions(-) delete mode 100644 examples/game/client/src/arena/movement.ts delete mode 100644 examples/game/client/tests/movement-parity.test.mjs delete mode 100644 examples/game/fixtures/arena-movement.json rename examples/game/server/{src/arena/movement.rs => sim/src/arena.rs} (100%) rename examples/game/server/{src/grid/world.rs => sim/src/grid.rs} (100%) delete mode 100644 examples/game/server/tests/movement_fixture.rs create mode 100644 js/src/game/wasm-prediction.ts create mode 100644 js/tests/fixtures/predict-module.mjs create mode 100644 js/tests/game-wasm-prediction.test.mjs diff --git a/examples/game/client/src/arena/movement.ts b/examples/game/client/src/arena/movement.ts deleted file mode 100644 index 3eacf538c..000000000 --- a/examples/game/client/src/arena/movement.ts +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Shared deterministic movement step for the Arena demo. - * - * **Twin of `examples/game/server/src/arena/movement.rs`** — the server runs - * that one, the client predicts its own capsule with this one. They must - * produce identical numbers: every operation is rounded to binary32 with - * `f()` (= `Math.fround`), only `+ - * /` and `sqrt` are used, one input is - * one command frame of exactly `DT`, and positions/velocities are snapped - * to their wire quantization at the end of each step. - * - * `tests/movement-parity.test.mjs` replays the Rust-generated fixture - * `examples/game/fixtures/arena-movement.json` through this file. - * - * The input type, its sanitize and the wire quantization come from the - * client generated from the Rust surface (`../generated/arena`). - */ -import { dequantizeLinear, quantizeLinear, type EntityFields } from '@hops-ops/distributed/game'; - -import { BUTTON, FIELD_TYPES, sanitizeInput, type MoveInput } from '../generated/arena/index.ts'; - -export type { MoveInput } from '../generated/arena/index.ts'; - -const f = Math.fround; - -export const DT = f(1 / 30); -export const HALF = 20; -export const PLAYER_RADIUS = 0.5; -export const MAX_SPEED = 5; -export const ACCEL = 40; -export const DASH_SPEED = 14; -export const DASH_FRAMES = 6; -export const DASH_COOLDOWN = 45; -export const BUTTON_DASH = BUTTON.dash; - -/** Static circular pillars `[x, y, radius]`. */ -export const PILLARS: readonly (readonly [number, number, number])[] = [ - [0, 0, 2.5], - [-9, -9, 1.5], - [9, -9, 1.5], - [-9, 9, 1.5], - [9, 9, 1.5], - [0, -14, 1], - [0, 14, 1], - [-14, 0, 1], - [14, 0, 1] -]; - -export type Quant = Readonly<{ min: number; max: number; bits: number }>; - -/** Wire quantization of `x`/`y` and `vx`/`vy` (from the Rust schema). */ -export const POS: Quant = FIELD_TYPES.player.x; -export const VEL: Quant = FIELD_TYPES.player.vx; - -export type MoveState = Readonly<{ - x: number; - y: number; - vx: number; - vy: number; - dash: number; - cooldown: number; -}>; - -function snap(q: Quant, v: number): number { - return dequantizeLinear(quantizeLinear(v, q.min, q.max, q.bits), q.min, q.max, q.bits); -} - -/** Advance one command frame (see the module docs). */ -export function step(state: MoveState, raw: MoveInput): MoveState { - // What the server simulates: -128 → -127, unknown buttons cleared. - const input = sanitizeInput(raw); - let { x, y, vx, vy, dash, cooldown } = state; - let dx = f(input.mx / 127); - let dy = f(input.my / 127); - const l2 = f(f(dx * dx) + f(dy * dy)); - if (l2 > 1) { - const inv = f(1 / f(Math.sqrt(l2))); - dx = f(dx * inv); - dy = f(dy * inv); - } - - cooldown = Math.max(0, cooldown - 1); - if ((input.buttons & BUTTON_DASH) !== 0 && cooldown === 0 && dash === 0) { - const v2 = f(f(vx * vx) + f(vy * vy)); - let dir: [number, number] | undefined; - if (l2 > f(0.01)) { - const l = f(Math.sqrt(f(f(dx * dx) + f(dy * dy)))); - dir = [f(dx / l), f(dy / l)]; - } else if (v2 > f(0.01)) { - const l = f(Math.sqrt(v2)); - dir = [f(vx / l), f(vy / l)]; - } - if (dir !== undefined) { - vx = f(dir[0] * DASH_SPEED); - vy = f(dir[1] * DASH_SPEED); - dash = DASH_FRAMES; - cooldown = DASH_COOLDOWN; - } - } - - if (dash > 0) { - dash -= 1; - } else { - const ex = f(f(dx * MAX_SPEED) - vx); - const ey = f(f(dy * MAX_SPEED) - vy); - const e2 = f(f(ex * ex) + f(ey * ey)); - const maxDv = f(ACCEL * DT); - if (e2 > f(maxDv * maxDv)) { - const k = f(maxDv / f(Math.sqrt(e2))); - vx = f(vx + f(ex * k)); - vy = f(vy + f(ey * k)); - } else { - vx = f(vx + ex); - vy = f(vy + ey); - } - } - - x = f(x + f(vx * DT)); - y = f(y + f(vy * DT)); - - for (const [px, py, pr] of PILLARS) { - const ox = f(x - px); - const oy = f(y - py); - const d2 = f(f(ox * ox) + f(oy * oy)); - const min = f(PLAYER_RADIUS + pr); - if (d2 < f(min * min)) { - const d = f(Math.sqrt(d2)); - const [nx, ny] = d > f(1e-6) ? [f(ox / d), f(oy / d)] : [1, 0]; - x = f(px + f(nx * min)); - y = f(py + f(ny * min)); - const vn = f(f(vx * nx) + f(vy * ny)); - if (vn < 0) { - vx = f(vx - f(vn * nx)); - vy = f(vy - f(vn * ny)); - } - } - } - - const lim = f(HALF - PLAYER_RADIUS); - if (x < -lim) { - x = -lim; - vx = Math.max(vx, 0); - } else if (x > lim) { - x = lim; - vx = Math.min(vx, 0); - } - if (y < -lim) { - y = -lim; - vy = Math.max(vy, 0); - } else if (y > lim) { - y = lim; - vy = Math.min(vy, 0); - } - return { - x: snap(POS, x), - y: snap(POS, y), - vx: snap(VEL, vx), - vy: snap(VEL, vy), - dash, - cooldown - }; -} - -/** Replicated `player` fields → state. */ -export function stateFromFields(fields: EntityFields): MoveState { - const n = (name: string) => { - const v = fields[name]; - return typeof v === 'number' ? v : 0; - }; - return { x: n('x'), y: n('y'), vx: n('vx'), vy: n('vy'), dash: n('dash'), cooldown: n('cd') }; -} - -/** `Predictor` `predict` function for the `player` kind. */ -export function predictPlayer(fields: EntityFields, input: MoveInput): Record { - const s = step(stateFromFields(fields), input); - return { x: s.x, y: s.y, vx: s.vx, vy: s.vy, dash: s.dash, cd: s.cooldown }; -} diff --git a/examples/game/client/tests/movement-parity.test.mjs b/examples/game/client/tests/movement-parity.test.mjs deleted file mode 100644 index 0bf0fcb7b..000000000 --- a/examples/game/client/tests/movement-parity.test.mjs +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Rust ↔ TypeScript parity of the Arena movement step: replays the fixture - * written by `server/tests/movement_fixture.rs` through `src/arena/movement.ts` - * (Node strips the types). Prediction is only exact if this passes. - */ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -import * as movement from '../src/arena/movement.ts'; - -const fixture = JSON.parse( - readFileSync(new URL('../../fixtures/arena-movement.json', import.meta.url), 'utf8') -); -const EPSILON = 1e-4; - -test('constants and wire quantization match the Rust side', () => { - const c = fixture.constants; - assert.equal(Math.fround(c.dt), movement.DT); - assert.equal(c.half, movement.HALF); - assert.equal(c.playerRadius, movement.PLAYER_RADIUS); - assert.equal(c.maxSpeed, movement.MAX_SPEED); - assert.equal(c.accel, movement.ACCEL); - assert.equal(c.dashSpeed, movement.DASH_SPEED); - assert.equal(c.dashFrames, movement.DASH_FRAMES); - assert.equal(c.dashCooldown, movement.DASH_COOLDOWN); - assert.deepEqual(c.pillars, movement.PILLARS.map((p) => [...p])); - const byName = Object.fromEntries(fixture.fields.map((field) => [field.name, field])); - for (const [name, { min, max, bits }] of [['x', movement.POS], ['y', movement.POS], ['vx', movement.VEL], ['vy', movement.VEL]]) { - assert.deepEqual( - { min: byName[name].min, max: byName[name].max, bits: byName[name].bits }, - { min, max, bits }, - name - ); - } -}); - -test('the TypeScript step reproduces every Rust state', () => { - const toState = (s) => ({ x: s.x, y: s.y, vx: s.vx, vy: s.vy, dash: s.dash, cooldown: s.cd }); - let state = toState(fixture.start); - let exact = 0; - let maxError = 0; - fixture.steps.forEach(({ input, state: expected }, i) => { - state = movement.step(state, { mx: input[0], my: input[1], buttons: input[2] }); - const want = toState(expected); - for (const key of ['x', 'y', 'vx', 'vy']) { - const error = Math.abs(state[key] - Math.fround(want[key])); - maxError = Math.max(maxError, error); - assert.ok(error <= EPSILON, `step ${i} ${key}: ts ${state[key]} rust ${want[key]}`); - } - assert.equal(state.dash, want.dash, `step ${i} dash`); - assert.equal(state.cooldown, want.cooldown, `step ${i} cooldown`); - if (['x', 'y', 'vx', 'vy'].every((k) => state[k] === Math.fround(want[k]))) exact += 1; - }); - assert.ok(fixture.steps.length > 300); - // Binary32 discipline makes the twins bit-identical, not just close. - assert.equal(exact, fixture.steps.length, `bit-exact ${exact}/${fixture.steps.length}, max error ${maxError}`); -}); diff --git a/examples/game/fixtures/arena-movement.json b/examples/game/fixtures/arena-movement.json deleted file mode 100644 index 1c10b51c0..000000000 --- a/examples/game/fixtures/arena-movement.json +++ /dev/null @@ -1,364 +0,0 @@ -{ - "description": "Arena movement parity: Rust movement::step vs client/src/arena/movement.ts", - "constants": {"accel":40.0,"dashCooldown":45,"dashFrames":6,"dashSpeed":14.0,"dt":0.03333333507180214,"half":20.0,"maxSpeed":5.0,"pillars":[[0.0,0.0,2.5],[-9.0,-9.0,1.5],[9.0,-9.0,1.5],[-9.0,9.0,1.5],[9.0,9.0,1.5],[0.0,-14.0,1.0],[0.0,14.0,1.0],[-14.0,0.0,1.0],[14.0,0.0,1.0]],"playerRadius":0.5}, - "fields": [{"bits":18,"max":19.999847412109375,"min":-20.0,"name":"x","type":"quant_f32"},{"bits":18,"max":19.999847412109375,"min":-20.0,"name":"y","type":"quant_f32"},{"bits":12,"max":15.9921875,"min":-16.0,"name":"vx","type":"quant_f32"},{"bits":12,"max":15.9921875,"min":-16.0,"name":"vy","type":"quant_f32"}], - "start": {"cd":0,"dash":0,"vx":0.0,"vy":0.0,"x":-5.0,"y":-5.0}, - "steps": [ - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":1.3359375,"vy":0.0,"x":-4.955596923828125,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":2.671875,"vy":0.0,"x":-4.86663818359375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":4.0078125,"vy":0.0,"x":-4.733123779296875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.566497802734375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.399871826171875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.233245849609375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-4.066619873046875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.899993896484375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.733367919921875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.566741943359375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.400115966796875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.233489990234375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-3.066864013671875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.900238037109375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.733612060546875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.566986083984375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.400360107421875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.233734130859375,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-2.067108154296875,"y":-5.0}}, - {"input":[127,0,0],"state":{"cd":0,"dash":0,"vx":5.0,"vy":0.0,"x":-1.900482177734375,"y":-5.0}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":4.4921875,"vy":1.234375,"x":-1.75079345703125,"y":-4.958953857421875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.9765625,"vy":2.46875,"x":-1.6180419921875,"y":-4.876708984375}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.500244140625,"y":-4.7589111328125}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.3824462890625,"y":-4.64111328125}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.2646484375,"y":-4.5233154296875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.1468505859375,"y":-4.405517578125}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.029052734375,"y":-4.2877197265625}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.9112548828125,"y":-4.169921875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.79345703125,"y":-4.0521240234375}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.6756591796875,"y":-3.934326171875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.557861328125,"y":-3.8165283203125}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.4400634765625,"y":-3.69873046875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.322265625,"y":-3.5809326171875}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.2044677734375,"y":-3.463134765625}}, - {"input":[90,90,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.086669921875,"y":-3.3453369140625}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":3.0546875,"vy":2.296875,"x":0.015106201171875,"y":-3.26873779296875}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":2.5703125,"vy":1.0546875,"x":0.100860595703125,"y":-3.233642578125}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":2.0859375,"vy":-0.1875,"x":0.170440673828125,"y":-3.239898681640625}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.6015625,"vy":-1.4296875,"x":0.223846435546875,"y":-3.28765869140625}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.263214111328125,"y":-3.37158203125}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.302581787109375,"y":-3.45550537109375}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.341949462890625,"y":-3.5394287109375}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.381317138671875,"y":-3.62335205078125}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.420684814453125,"y":-3.707275390625}}, - {"input":[30,-64,0],"state":{"cd":0,"dash":0,"vx":1.1796875,"vy":-2.5234375,"x":0.460052490234375,"y":-3.79119873046875}}, - {"input":[0,0,1],"state":{"cd":45,"dash":5,"vx":5.9296875,"vy":-12.6796875,"x":0.65765380859375,"y":-4.214019775390625}}, - {"input":[0,0,0],"state":{"cd":44,"dash":4,"vx":5.9296875,"vy":-12.6796875,"x":0.855255126953125,"y":-4.636688232421875}}, - {"input":[0,0,0],"state":{"cd":43,"dash":3,"vx":5.9296875,"vy":-12.6796875,"x":1.0528564453125,"y":-5.059356689453125}}, - {"input":[0,0,0],"state":{"cd":42,"dash":2,"vx":5.9296875,"vy":-12.6796875,"x":1.250457763671875,"y":-5.482025146484375}}, - {"input":[0,0,0],"state":{"cd":41,"dash":1,"vx":5.9296875,"vy":-12.6796875,"x":1.44805908203125,"y":-5.904693603515625}}, - {"input":[0,0,0],"state":{"cd":40,"dash":0,"vx":5.9296875,"vy":-12.6796875,"x":1.645660400390625,"y":-6.327362060546875}}, - {"input":[0,0,0],"state":{"cd":39,"dash":0,"vx":5.3671875,"vy":-11.46875,"x":1.824493408203125,"y":-6.709747314453125}}, - {"input":[0,0,0],"state":{"cd":38,"dash":0,"vx":4.8046875,"vy":-10.2578125,"x":1.98455810546875,"y":-7.051849365234375}}, - {"input":[0,0,0],"state":{"cd":37,"dash":0,"vx":4.2421875,"vy":-9.046875,"x":2.1258544921875,"y":-7.353515625}}, - {"input":[0,0,0],"state":{"cd":36,"dash":0,"vx":3.6796875,"vy":-7.8359375,"x":2.248382568359375,"y":-7.614898681640625}}, - {"input":[0,0,0],"state":{"cd":35,"dash":0,"vx":3.109375,"vy":-6.6328125,"x":2.352142333984375,"y":-7.835845947265625}}, - {"input":[0,0,0],"state":{"cd":34,"dash":0,"vx":2.546875,"vy":-5.421875,"x":2.436981201171875,"y":-8.01666259765625}}, - {"input":[0,0,0],"state":{"cd":33,"dash":0,"vx":1.9765625,"vy":-4.21875,"x":2.5030517578125,"y":-8.157196044921875}}, - {"input":[-127,0,1],"state":{"cd":32,"dash":0,"vx":0.8359375,"vy":-3.53125,"x":2.530975341796875,"y":-8.27484130859375}}, - {"input":[-127,0,1],"state":{"cd":31,"dash":0,"vx":-0.3046875,"vy":-2.84375,"x":2.520751953125,"y":-8.369598388671875}}, - {"input":[-127,0,1],"state":{"cd":30,"dash":0,"vx":-1.4453125,"vy":-2.15625,"x":2.4725341796875,"y":-8.441314697265625}}, - {"input":[-127,0,1],"state":{"cd":29,"dash":0,"vx":-2.5859375,"vy":-1.4609375,"x":2.386322021484375,"y":-8.490142822265625}}, - {"input":[-127,0,1],"state":{"cd":28,"dash":0,"vx":-3.7265625,"vy":-0.7734375,"x":2.262115478515625,"y":-8.515777587890625}}, - {"input":[-127,0,1],"state":{"cd":27,"dash":0,"vx":-4.8671875,"vy":-0.078125,"x":2.09991455078125,"y":-8.518524169921875}}, - {"input":[-127,0,1],"state":{"cd":26,"dash":0,"vx":-5.0,"vy":0.0,"x":1.93328857421875,"y":-8.518524169921875}}, - {"input":[-127,0,1],"state":{"cd":25,"dash":0,"vx":-5.0,"vy":0.0,"x":1.76666259765625,"y":-8.518524169921875}}, - {"input":[-128,5,0],"state":{"cd":24,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.600189208984375,"y":-8.511962890625}}, - {"input":[-128,5,0],"state":{"cd":23,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.4337158203125,"y":-8.505401611328125}}, - {"input":[-128,5,0],"state":{"cd":22,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.267242431640625,"y":-8.49884033203125}}, - {"input":[-128,5,0],"state":{"cd":21,"dash":0,"vx":-5.0,"vy":0.1953125,"x":1.10076904296875,"y":-8.492279052734375}}, - {"input":[-128,5,0],"state":{"cd":20,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.934295654296875,"y":-8.4857177734375}}, - {"input":[-128,5,0],"state":{"cd":19,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.767822265625,"y":-8.479156494140625}}, - {"input":[-128,5,0],"state":{"cd":18,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.601348876953125,"y":-8.47259521484375}}, - {"input":[-128,5,0],"state":{"cd":17,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.43487548828125,"y":-8.466033935546875}}, - {"input":[-128,5,0],"state":{"cd":16,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.268402099609375,"y":-8.45947265625}}, - {"input":[-128,5,0],"state":{"cd":15,"dash":0,"vx":-5.0,"vy":0.1953125,"x":0.1019287109375,"y":-8.452911376953125}}, - {"input":[-128,5,0],"state":{"cd":14,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.064544677734375,"y":-8.44635009765625}}, - {"input":[-128,5,0],"state":{"cd":13,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.23101806640625,"y":-8.439788818359375}}, - {"input":[-128,5,0],"state":{"cd":12,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.397491455078125,"y":-8.4332275390625}}, - {"input":[-128,5,0],"state":{"cd":11,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.56396484375,"y":-8.426666259765625}}, - {"input":[-128,5,0],"state":{"cd":10,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.730438232421875,"y":-8.42010498046875}}, - {"input":[-128,5,0],"state":{"cd":9,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-0.89691162109375,"y":-8.413543701171875}}, - {"input":[-128,5,0],"state":{"cd":8,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.063385009765625,"y":-8.406982421875}}, - {"input":[-128,5,0],"state":{"cd":7,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.2298583984375,"y":-8.400421142578125}}, - {"input":[-128,5,0],"state":{"cd":6,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.396331787109375,"y":-8.39385986328125}}, - {"input":[-128,5,0],"state":{"cd":5,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.56280517578125,"y":-8.387298583984375}}, - {"input":[-128,5,0],"state":{"cd":4,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.729278564453125,"y":-8.3807373046875}}, - {"input":[-128,5,0],"state":{"cd":3,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-1.895751953125,"y":-8.374176025390625}}, - {"input":[-128,5,0],"state":{"cd":2,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.062225341796875,"y":-8.36761474609375}}, - {"input":[-128,5,0],"state":{"cd":1,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.22869873046875,"y":-8.361053466796875}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.395172119140625,"y":-8.3544921875}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.5616455078125,"y":-8.347930908203125}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.728118896484375,"y":-8.34136962890625}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-2.89459228515625,"y":-8.334808349609375}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.061065673828125,"y":-8.3282470703125}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.2275390625,"y":-8.321685791015625}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.394012451171875,"y":-8.31512451171875}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.56048583984375,"y":-8.308563232421875}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.726959228515625,"y":-8.302001953125}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-3.8934326171875,"y":-8.295440673828125}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.059906005859375,"y":-8.28887939453125}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.22637939453125,"y":-8.282318115234375}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.392852783203125,"y":-8.2757568359375}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.559326171875,"y":-8.269195556640625}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.725799560546875,"y":-8.26263427734375}}, - {"input":[-128,5,0],"state":{"cd":0,"dash":0,"vx":-5.0,"vy":0.1953125,"x":-4.89227294921875,"y":-8.256072998046875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-3.7578125,"vy":0.6796875,"x":-5.017547607421875,"y":-8.23333740234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-2.515625,"vy":1.1640625,"x":-5.101470947265625,"y":-8.194427490234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-1.2734375,"vy":1.6484375,"x":-5.143890380859375,"y":-8.13934326171875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":-0.03125,"vy":2.1328125,"x":-5.14495849609375,"y":-8.068084716796875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":1.2109375,"vy":2.6171875,"x":-5.10467529296875,"y":-7.98065185546875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":2.453125,"vy":3.109375,"x":-5.023040771484375,"y":-7.877044677734375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.905242919921875,"y":-7.759246826171875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.787445068359375,"y":-7.641448974609375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.669647216796875,"y":-7.523651123046875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.551849365234375,"y":-7.405853271484375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.434051513671875,"y":-7.288055419921875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.316253662109375,"y":-7.170257568359375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.198455810546875,"y":-7.052459716796875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-4.080657958984375,"y":-6.934661865234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.962860107421875,"y":-6.816864013671875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.845062255859375,"y":-6.699066162109375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.727264404296875,"y":-6.581268310546875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.609466552734375,"y":-6.463470458984375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.491668701171875,"y":-6.345672607421875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.373870849609375,"y":-6.227874755859375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.256072998046875,"y":-6.110076904296875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.138275146484375,"y":-5.992279052734375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-3.020477294921875,"y":-5.874481201171875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.902679443359375,"y":-5.756683349609375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.784881591796875,"y":-5.638885498046875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.667083740234375,"y":-5.521087646484375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.549285888671875,"y":-5.403289794921875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.431488037109375,"y":-5.285491943359375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.313690185546875,"y":-5.167694091796875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.195892333984375,"y":-5.049896240234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-2.078094482421875,"y":-4.932098388671875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.960296630859375,"y":-4.814300537109375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.842498779296875,"y":-4.696502685546875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.724700927734375,"y":-4.578704833984375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.606903076171875,"y":-4.460906982421875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.489105224609375,"y":-4.343109130859375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.371307373046875,"y":-4.225311279296875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.253509521484375,"y":-4.107513427734375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.135711669921875,"y":-3.989715576171875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-1.017913818359375,"y":-3.871917724609375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.900115966796875,"y":-3.754119873046875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.782318115234375,"y":-3.636322021484375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.664520263671875,"y":-3.518524169921875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.546722412109375,"y":-3.400726318359375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.428924560546875,"y":-3.282928466796875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.311126708984375,"y":-3.165130615234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5390625,"vy":3.5390625,"x":-0.193328857421875,"y":-3.047332763671875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.4453125,"vy":-0.0859375,"x":-0.07720947265625,"y":-2.99896240234375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.4921875,"vy":0.046875,"x":0.03936767578125,"y":-2.999725341796875}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.5703125,"vy":0.1875,"x":0.158538818359375,"y":-2.995758056640625}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.6640625,"vy":0.34375,"x":0.28106689453125,"y":-2.98675537109375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.765625,"vy":0.515625,"x":0.4071044921875,"y":-2.972259521484375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.875,"vy":0.703125,"x":0.536651611328125,"y":-2.95166015625}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":3.96875,"vy":0.90625,"x":0.669708251953125,"y":-2.924346923828125}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.0546875,"vy":1.1328125,"x":0.805816650390625,"y":-2.88970947265625}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.125,"vy":1.3671875,"x":0.94451904296875,"y":-2.847442626953125}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1796875,"vy":1.6171875,"x":1.085052490234375,"y":-2.79693603515625}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.203125,"vy":1.8828125,"x":1.226654052734375,"y":-2.73773193359375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1953125,"vy":2.15625,"x":1.368560791015625,"y":-2.669677734375}}, - {"input":[127,127,0],"state":{"cd":0,"dash":0,"vx":4.1640625,"vy":2.421875,"x":1.509552001953125,"y":-2.592620849609375}}, - {"input":[0,127,1],"state":{"cd":45,"dash":5,"vx":6.609375,"vy":4.6953125,"x":1.736907958984375,"y":-2.446136474609375}}, - {"input":[0,127,1],"state":{"cd":44,"dash":4,"vx":6.609375,"vy":4.6953125,"x":1.957244873046875,"y":-2.289581298828125}}, - {"input":[0,127,1],"state":{"cd":43,"dash":3,"vx":6.609375,"vy":4.6953125,"x":2.177581787109375,"y":-2.133026123046875}}, - {"input":[0,127,1],"state":{"cd":42,"dash":2,"vx":6.609375,"vy":4.6953125,"x":2.397918701171875,"y":-1.976470947265625}}, - {"input":[0,127,1],"state":{"cd":41,"dash":1,"vx":6.609375,"vy":4.6953125,"x":2.618255615234375,"y":-1.819915771484375}}, - {"input":[0,127,1],"state":{"cd":40,"dash":0,"vx":6.609375,"vy":4.6953125,"x":2.838592529296875,"y":-1.663360595703125}}, - {"input":[0,127,1],"state":{"cd":39,"dash":0,"vx":5.28125,"vy":4.7578125,"x":3.0145263671875,"y":-1.50482177734375}}, - {"input":[0,127,1],"state":{"cd":38,"dash":0,"vx":3.953125,"vy":4.8203125,"x":3.146209716796875,"y":-1.344146728515625}}, - {"input":[0,127,1],"state":{"cd":37,"dash":0,"vx":2.625,"vy":4.8828125,"x":3.233642578125,"y":-1.181488037109375}}, - {"input":[0,127,1],"state":{"cd":36,"dash":0,"vx":1.296875,"vy":4.9453125,"x":3.27667236328125,"y":-1.016693115234375}}, - {"input":[0,127,1],"state":{"cd":35,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.850067138671875}}, - {"input":[0,127,1],"state":{"cd":34,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.683441162109375}}, - {"input":[0,127,1],"state":{"cd":33,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.516815185546875}}, - {"input":[0,127,1],"state":{"cd":32,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.350189208984375}}, - {"input":[0,127,1],"state":{"cd":31,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.183563232421875}}, - {"input":[0,127,1],"state":{"cd":30,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":-0.016937255859375}}, - {"input":[0,127,1],"state":{"cd":29,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.149688720703125}}, - {"input":[0,127,1],"state":{"cd":28,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.316314697265625}}, - {"input":[0,127,1],"state":{"cd":27,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.482940673828125}}, - {"input":[0,127,1],"state":{"cd":26,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.649566650390625}}, - {"input":[0,127,1],"state":{"cd":25,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.816192626953125}}, - {"input":[0,127,1],"state":{"cd":24,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":0.982818603515625}}, - {"input":[0,127,1],"state":{"cd":23,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.149444580078125}}, - {"input":[0,127,1],"state":{"cd":22,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.316070556640625}}, - {"input":[0,127,1],"state":{"cd":21,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.482696533203125}}, - {"input":[0,127,1],"state":{"cd":20,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.649322509765625}}, - {"input":[0,127,1],"state":{"cd":19,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.815948486328125}}, - {"input":[0,127,1],"state":{"cd":18,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":1.982574462890625}}, - {"input":[0,127,1],"state":{"cd":17,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.149200439453125}}, - {"input":[0,127,1],"state":{"cd":16,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.315826416015625}}, - {"input":[0,127,1],"state":{"cd":15,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.482452392578125}}, - {"input":[0,127,1],"state":{"cd":14,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.649078369140625}}, - {"input":[0,127,1],"state":{"cd":13,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.815704345703125}}, - {"input":[0,127,1],"state":{"cd":12,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":2.982330322265625}}, - {"input":[0,127,1],"state":{"cd":11,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.148956298828125}}, - {"input":[0,127,1],"state":{"cd":10,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.315582275390625}}, - {"input":[0,127,1],"state":{"cd":9,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.482208251953125}}, - {"input":[0,127,1],"state":{"cd":8,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.648834228515625}}, - {"input":[0,127,1],"state":{"cd":7,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.815460205078125}}, - {"input":[0,127,1],"state":{"cd":6,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":3.982086181640625}}, - {"input":[0,127,1],"state":{"cd":5,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.148712158203125}}, - {"input":[0,127,1],"state":{"cd":4,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.315338134765625}}, - {"input":[0,127,1],"state":{"cd":3,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.481964111328125}}, - {"input":[0,127,1],"state":{"cd":2,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.648590087890625}}, - {"input":[0,127,1],"state":{"cd":1,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":4.815216064453125}}, - {"input":[0,127,1],"state":{"cd":45,"dash":5,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":5.281829833984375}}, - {"input":[0,127,1],"state":{"cd":44,"dash":4,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":5.748443603515625}}, - {"input":[0,127,1],"state":{"cd":43,"dash":3,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":6.215057373046875}}, - {"input":[0,127,1],"state":{"cd":42,"dash":2,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":6.681671142578125}}, - {"input":[0,127,1],"state":{"cd":41,"dash":1,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":7.148284912109375}}, - {"input":[0,127,1],"state":{"cd":40,"dash":0,"vx":0.0,"vy":14.0,"x":3.27667236328125,"y":7.614898681640625}}, - {"input":[0,127,1],"state":{"cd":39,"dash":0,"vx":0.0,"vy":12.6640625,"x":3.27667236328125,"y":8.037109375}}, - {"input":[0,127,1],"state":{"cd":38,"dash":0,"vx":0.0,"vy":11.328125,"x":3.27667236328125,"y":8.414764404296875}}, - {"input":[0,127,1],"state":{"cd":37,"dash":0,"vx":0.0,"vy":9.9921875,"x":3.27667236328125,"y":8.74786376953125}}, - {"input":[0,127,1],"state":{"cd":36,"dash":0,"vx":0.0,"vy":8.65625,"x":3.27667236328125,"y":9.03656005859375}}, - {"input":[0,127,1],"state":{"cd":35,"dash":0,"vx":0.0,"vy":7.3203125,"x":3.27667236328125,"y":9.28070068359375}}, - {"input":[0,127,1],"state":{"cd":34,"dash":0,"vx":0.0,"vy":5.984375,"x":3.27667236328125,"y":9.48028564453125}}, - {"input":[0,127,1],"state":{"cd":33,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.64691162109375}}, - {"input":[0,127,1],"state":{"cd":32,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.81353759765625}}, - {"input":[0,127,1],"state":{"cd":31,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":9.98016357421875}}, - {"input":[0,127,1],"state":{"cd":30,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.14678955078125}}, - {"input":[0,127,1],"state":{"cd":29,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.31341552734375}}, - {"input":[0,127,1],"state":{"cd":28,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.48004150390625}}, - {"input":[0,127,1],"state":{"cd":27,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.64666748046875}}, - {"input":[0,127,1],"state":{"cd":26,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.81329345703125}}, - {"input":[0,127,1],"state":{"cd":25,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":10.97991943359375}}, - {"input":[0,127,1],"state":{"cd":24,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.14654541015625}}, - {"input":[0,127,1],"state":{"cd":23,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.31317138671875}}, - {"input":[0,127,1],"state":{"cd":22,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.47979736328125}}, - {"input":[0,127,1],"state":{"cd":21,"dash":0,"vx":0.0,"vy":5.0,"x":3.27667236328125,"y":11.64642333984375}}, - {"input":[0,-127,0],"state":{"cd":20,"dash":0,"vx":0.0,"vy":3.6640625,"x":3.27667236328125,"y":11.768646240234375}}, - {"input":[0,-127,0],"state":{"cd":19,"dash":0,"vx":0.0,"vy":2.328125,"x":3.27667236328125,"y":11.8463134765625}}, - {"input":[0,-127,0],"state":{"cd":18,"dash":0,"vx":0.0,"vy":0.9921875,"x":3.27667236328125,"y":11.879425048828125}}, - {"input":[0,-127,0],"state":{"cd":17,"dash":0,"vx":0.0,"vy":-0.34375,"x":3.27667236328125,"y":11.86798095703125}}, - {"input":[0,-127,0],"state":{"cd":16,"dash":0,"vx":0.0,"vy":-1.6796875,"x":3.27667236328125,"y":11.8121337890625}}, - {"input":[0,-127,0],"state":{"cd":15,"dash":0,"vx":0.0,"vy":-3.015625,"x":3.27667236328125,"y":11.71173095703125}}, - {"input":[0,-127,0],"state":{"cd":14,"dash":0,"vx":0.0,"vy":-4.3515625,"x":3.27667236328125,"y":11.5667724609375}}, - {"input":[0,-127,0],"state":{"cd":13,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.400146484375}}, - {"input":[0,-127,0],"state":{"cd":12,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.2335205078125}}, - {"input":[0,-127,0],"state":{"cd":11,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":11.06689453125}}, - {"input":[0,-127,0],"state":{"cd":10,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.9002685546875}}, - {"input":[0,-127,0],"state":{"cd":9,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.733642578125}}, - {"input":[0,-127,0],"state":{"cd":8,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.5670166015625}}, - {"input":[0,-127,0],"state":{"cd":7,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.400390625}}, - {"input":[0,-127,0],"state":{"cd":6,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.2337646484375}}, - {"input":[0,-127,0],"state":{"cd":5,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":10.067138671875}}, - {"input":[0,-127,0],"state":{"cd":4,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.9005126953125}}, - {"input":[0,-127,0],"state":{"cd":3,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.73388671875}}, - {"input":[0,-127,0],"state":{"cd":2,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.5672607421875}}, - {"input":[0,-127,0],"state":{"cd":1,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.400634765625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.2340087890625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":9.0673828125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.9007568359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.734130859375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.5675048828125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.40087890625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.2342529296875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":8.067626953125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.9010009765625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.734375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.5677490234375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.401123046875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.2344970703125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":7.06787109375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.9012451171875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.734619140625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.5679931640625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.4013671875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.2347412109375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":6.068115234375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.9014892578125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.73486328125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.5682373046875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.401611328125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.2349853515625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":5.068359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.9017333984375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.735107421875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.5684814453125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.40185546875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.2352294921875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":4.068603515625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.9019775390625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.7353515625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.5687255859375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.402099609375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.2354736328125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":3.06884765625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.9022216796875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.735595703125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.5689697265625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.40234375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.2357177734375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":2.069091796875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.9024658203125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.73583984375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.5692138671875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.402587890625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.2359619140625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":1.0693359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.9027099609375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.736083984375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.5694580078125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.40283203125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.2362060546875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":0.069580078125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.0970458984375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.263671875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.4302978515625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.596923828125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.7635498046875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-0.93017578125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.0968017578125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.263427734375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.4300537109375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.5966796875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.7633056640625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-1.929931640625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.0965576171875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.26318359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.4298095703125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.596435546875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.7630615234375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-2.9296875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.0963134765625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.262939453125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.4295654296875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.59619140625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.7628173828125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-3.929443359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.0960693359375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.2626953125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.4293212890625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.595947265625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.7625732421875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-4.92919921875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.0958251953125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.262451171875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.4290771484375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.595703125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.7623291015625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-5.928955078125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.0955810546875}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.26220703125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.4288330078125}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.595458984375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.7620849609375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-6.9287109375}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-7.0953369140625}}, - {"input":[0,-127,0],"state":{"cd":0,"dash":0,"vx":0.0,"vy":-5.0,"x":3.27667236328125,"y":-7.261962890625}} - ] -} diff --git a/examples/game/server/src/arena/movement.rs b/examples/game/server/sim/src/arena.rs similarity index 100% rename from examples/game/server/src/arena/movement.rs rename to examples/game/server/sim/src/arena.rs diff --git a/examples/game/server/src/grid/world.rs b/examples/game/server/sim/src/grid.rs similarity index 100% rename from examples/game/server/src/grid/world.rs rename to examples/game/server/sim/src/grid.rs diff --git a/examples/game/server/tests/movement_fixture.rs b/examples/game/server/tests/movement_fixture.rs deleted file mode 100644 index 5cf70c757..000000000 --- a/examples/game/server/tests/movement_fixture.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Golden fixture for the shared Arena movement step. -//! -//! Writes/compares `examples/game/fixtures/arena-movement.json`, which the -//! TypeScript client replays in `client/tests/movement-parity.test.mjs`. -//! Regenerate after an intended change to BOTH implementations: -//! `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. - -use distributed_game::GameInput; -use std::path::PathBuf; - -use game_demos::arena::movement::{self, MoveInput, MoveState, BUTTON_DASH}; -use serde_json::{json, Value}; - -/// A scripted input sequence covering acceleration, diagonals, partial -/// stick, dash (stick and velocity direction), held dash, pillar and wall -/// contact. -fn script() -> Vec { - let i = |mx: i8, my: i8, buttons: u8| MoveInput { mx, my, buttons }; - let mut out = Vec::new(); - let mut push = |input: MoveInput, n: usize| out.extend(std::iter::repeat_n(input, n)); - push(i(127, 0, 0), 20); // accelerate right - push(i(90, 90, 0), 15); // diagonal (clamped length) - push(i(30, -64, 0), 10); // partial stick - push(i(0, 0, BUTTON_DASH), 1); // dash along velocity - push(i(0, 0, 0), 12); // decelerate - push(i(-127, 0, BUTTON_DASH), 8); // dash along stick, held - push(i(-128, 5, 0), 40); // into the left pillars / wall (-128 sanitizes) - push(i(127, 127, 0), 60); // towards the centre pillar - push(i(0, 127, BUTTON_DASH), 70); // repeated dashes after cooldown - push(i(0, -127, 0), 120); // across the floor into the far wall - out -} - -fn state_json(s: &MoveState) -> Value { - json!({ "x": s.x, "y": s.y, "vx": s.vx, "vy": s.vy, "dash": s.dash, "cd": s.cooldown }) -} - -fn field_json(name: &str, ty: distributed_game::FieldType) -> Value { - match ty { - distributed_game::FieldType::QuantF32 { min, max, bits } => { - json!({ "name": name, "type": "quant_f32", "min": min, "max": max, "bits": bits }) - } - _ => unreachable!(), - } -} - -fn build() -> Value { - let start = movement::canonicalize(MoveState { - x: -5.0, - y: -5.0, - ..MoveState::default() - }); - let mut s = start; - let mut steps = Vec::new(); - for input in script() { - // The server decodes the wire payload, so the fixture does too. - let decoded = MoveInput::from_payload(&input.to_payload()).unwrap(); - s = movement::step(s, decoded); - steps.push(json!({ - "input": [input.mx, input.my, input.buttons], - "state": state_json(&s), - })); - } - json!({ - "description": "Arena movement parity: Rust movement::step vs client/src/arena/movement.ts", - "constants": { - "dt": movement::DT, "half": movement::HALF, "playerRadius": movement::PLAYER_RADIUS, - "maxSpeed": movement::MAX_SPEED, "accel": movement::ACCEL, "dashSpeed": movement::DASH_SPEED, - "dashFrames": movement::DASH_FRAMES, "dashCooldown": movement::DASH_COOLDOWN, - "pillars": movement::PILLARS.iter().map(|(x, y, r)| json!([x, y, r])).collect::>(), - }, - "fields": [ - field_json("x", movement::POS), field_json("y", movement::POS), - field_json("vx", movement::VEL), field_json("vy", movement::VEL), - ], - "start": state_json(&start), - "steps": steps, - }) -} - -/// Stable, diff-friendly text: one step per line. Compared as text because -/// floats are written as the exact f64 widening of each f32. -fn render(v: &Value) -> String { - let mut out = String::from("{\n"); - for key in ["description", "constants", "fields", "start"] { - out += &format!(" \"{key}\": {},\n", v[key]); - } - out += " \"steps\": [\n"; - let steps = v["steps"].as_array().unwrap(); - for (i, step) in steps.iter().enumerate() { - let sep = if i + 1 == steps.len() { "" } else { "," }; - out += &format!(" {step}{sep}\n"); - } - out + " ]\n}\n" -} - -#[test] -fn movement_fixture_is_current() { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/arena-movement.json"); - let fresh = render(&build()); - if std::env::var_os("UPDATE_GOLDEN").is_some() { - std::fs::write(&path, fresh).unwrap(); - return; - } - let stored = - std::fs::read_to_string(&path).expect("fixture exists (UPDATE_GOLDEN=1 to create)"); - assert!( - stored == fresh, - "movement changed: update client/src/arena/movement.ts too, then UPDATE_GOLDEN=1" - ); -} diff --git a/js/src/game/index.ts b/js/src/game/index.ts index a19174d30..b9a0c2e0d 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -143,6 +143,20 @@ export { type PredictFn, type PredictorOptions } from './prediction.js'; +export { + PREDICT_ABI_VERSION, + PREDICT_SCRATCH_BYTES, + PredictAbiError, + PredictModule, + createWasmPrediction, + decodePredictState, + encodePredictState, + loadPredictModule, + type PredictStateLayout, + type WasmPrediction, + type WasmPredictionOptions, + type WasmSource +} from './wasm-prediction.js'; export { AdaptiveDelay, InputPacer, diff --git a/js/src/game/wasm-prediction.ts b/js/src/game/wasm-prediction.ts new file mode 100644 index 000000000..b0624d077 --- /dev/null +++ b/js/src/game/wasm-prediction.ts @@ -0,0 +1,303 @@ +/** + * Client prediction backed by the zone's Rust step compiled to WebAssembly + * (`#[predict]` in `distributed_game`, built by `distributed game-wasm`). + * + * The module speaks a small binary ABI (`distributed_game::prediction`, v1): + * it imports nothing and exports `memory`, `dg_predict_abi() -> u32`, + * `dg_predict_buffer() -> ptr` (a 64 KiB scratch area) and one + * `dg_predict_(state_len, input_len, context_len, dt) -> i32` per + * step. A call writes `state ‖ input ‖ context` into the scratch area — + * the state and context with the payload codec (`f32` stays binary32), the + * input as its wire payload — and reads the next state back from the start + * of it. No JSON, no allocation across the boundary. + * + * Generated clients (`distributed game-client`) wire this in for you: + * `createClient` predicts with the compiled step by default. + */ +import { readWire, writeWire, encodePayload, type PayloadLayout, type WireType } from './codec.js'; +import type { PredictFn } from './prediction.js'; +import type { EntityFields } from './replica.js'; +import type { FieldValue } from './schema.js'; +import { WireReader, WireWriter } from './wire.js'; + +/** The prediction ABI version this SDK speaks. */ +export const PREDICT_ABI_VERSION = 1; + +/** Size of the module's scratch area (ABI v1). */ +export const PREDICT_SCRATCH_BYTES = 64 * 1024; + +/** + * Where a compiled step comes from: a URL (fetched in browsers, read from + * disk for `file:` URLs in Node), its bytes, a compiled module or a + * response. + */ +export type WasmSource = + | URL + | string + | ArrayBuffer + | ArrayBufferView + | WebAssembly.Module + | Response + | PromiseLike; + +/** Predicted fields: `[wire field name, codec type]` in state-record order. */ +export type PredictStateLayout = readonly (readonly [string, WireType])[]; + +/** A step export returned a negative ABI code. */ +export class PredictAbiError extends Error { + readonly code: number; + constructor(exportName: string, code: number) { + const reasons: Record = { + [-1]: 'input larger than the scratch buffer', + [-2]: 'state does not decode', + [-3]: 'input payload rejected', + [-4]: 'context does not decode', + [-5]: 'next state does not fit' + }; + super(`dg_predict_${exportName} failed (${code}): ${reasons[code] ?? 'unknown error'}`); + this.name = 'PredictAbiError'; + this.code = code; + } +} + +type StepExport = (stateLen: number, inputLen: number, contextLen: number, dt: number) => number; + +/** An instantiated prediction module. One instance can serve every client. */ +export class PredictModule { + readonly #exports: WebAssembly.Exports; + readonly #memory: WebAssembly.Memory; + readonly #pointer: number; + #view: Uint8Array; + readonly #steps = new Map(); + + constructor(instance: WebAssembly.Instance) { + const exports = instance.exports; + const memory = exports.memory; + const buffer = exports.dg_predict_buffer; + const abi = exports.dg_predict_abi; + if (!(memory instanceof WebAssembly.Memory) || typeof buffer !== 'function' || typeof abi !== 'function') { + throw new TypeError('not a distributed_game prediction module (missing memory / dg_predict_buffer / dg_predict_abi)'); + } + const version = (abi as () => number)(); + if (version !== PREDICT_ABI_VERSION) { + throw new TypeError(`prediction module speaks ABI v${version}; this SDK speaks v${PREDICT_ABI_VERSION}`); + } + this.#exports = exports; + this.#memory = memory; + this.#pointer = (buffer as () => number)() >>> 0; + this.#view = new Uint8Array(memory.buffer, this.#pointer, PREDICT_SCRATCH_BYTES); + } + + /** Instantiate a compiled step (cached per URL / module, see `WasmSource`). */ + static load(source: WasmSource): Promise { + return loadPredictModule(source); + } + + /** Step names (`dg_predict_`) this module exports. */ + get steps(): readonly string[] { + return Object.keys(this.#exports) + .filter((name) => name.startsWith('dg_predict_') && name !== 'dg_predict_abi' && name !== 'dg_predict_buffer') + .map((name) => name.slice('dg_predict_'.length)); + } + + /** + * Run `dg_predict_` once. Returns a copy of the encoded next + * state. `dt` is the frame length in seconds (rounded to binary32). + */ + step(exportName: string, state: Uint8Array, input: Uint8Array, context: Uint8Array, dt: number): Uint8Array { + const fn = this.#step(exportName); + const total = state.length + input.length + context.length; + if (total > PREDICT_SCRATCH_BYTES) throw new PredictAbiError(exportName, -1); + let view = this.#scratch(); + view.set(state, 0); + view.set(input, state.length); + view.set(context, state.length + input.length); + const length = fn(state.length, input.length, context.length, Math.fround(dt)); + if (length < 0) throw new PredictAbiError(exportName, length); + view = this.#scratch(); // the call may have grown memory + return view.slice(0, length); + } + + #step(exportName: string): StepExport { + let fn = this.#steps.get(exportName); + if (fn === undefined) { + const found = this.#exports[`dg_predict_${exportName}`]; + if (typeof found !== 'function') { + throw new TypeError(`prediction module has no step dg_predict_${exportName}`); + } + fn = found as StepExport; + this.#steps.set(exportName, fn); + } + return fn; + } + + #scratch(): Uint8Array { + if (this.#view.buffer !== this.#memory.buffer || this.#view.byteLength === 0) { + this.#view = new Uint8Array(this.#memory.buffer, this.#pointer, PREDICT_SCRATCH_BYTES); + } + return this.#view; + } +} + +const cache = new Map>(); +const moduleCache = new WeakMap>(); + +/** + * Instantiate a prediction module. URL sources (and compiled modules) are + * cached, so every client of a page shares one instance. + */ +export function loadPredictModule(source: WasmSource): Promise { + if (source instanceof WebAssembly.Module) { + let loaded = moduleCache.get(source); + if (loaded === undefined) { + loaded = WebAssembly.instantiate(source, {}).then((instance) => new PredictModule(instance)); + moduleCache.set(source, loaded); + } + return loaded; + } + if (typeof source === 'string' || source instanceof URL) { + const href = String(source); + let loaded = cache.get(href); + if (loaded === undefined) { + loaded = instantiateUrl(href); + cache.set(href, loaded); + loaded.catch(() => cache.delete(href)); + } + return loaded; + } + return instantiateBytesOrResponse(source); +} + +async function instantiateUrl(href: string): Promise { + const url = new URL(href, typeof location === 'undefined' ? undefined : location.href); + if (url.protocol === 'file:') { + // Node (tests, tools): fetch() has no file: support. The specifier is + // computed so bundlers do not try to include `node:fs` in browsers. + const fsModule = 'node:fs/promises'; + const fs = (await import(/* @vite-ignore */ fsModule)) as { + readFile(path: URL): Promise; + }; + return instantiateBytesOrResponse(await fs.readFile(url)); + } + return instantiateBytesOrResponse(fetch(url)); +} + +async function instantiateBytesOrResponse( + source: ArrayBuffer | ArrayBufferView | Response | PromiseLike +): Promise { + if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) { + const { instance } = await WebAssembly.instantiate(source as BufferSource, {}); + return new PredictModule(instance); + } + const response = await source; + if (!response.ok) throw new Error(`prediction module: HTTP ${response.status} for ${response.url}`); + if (typeof WebAssembly.instantiateStreaming === 'function' && response.headers.get('content-type')?.startsWith('application/wasm')) { + const { instance } = await WebAssembly.instantiateStreaming(response, {}); + return new PredictModule(instance); + } + const { instance } = await WebAssembly.instantiate(await response.arrayBuffer(), {}); + return new PredictModule(instance); +} + +/** Encode the predicted fields of an entity (`[wire name, type]` layout). */ +export function encodePredictState(layout: PredictStateLayout, fields: EntityFields): Uint8Array { + const w = new WireWriter(32); + for (const [name, type] of layout) writeWire(w, type, fields[name]); + return w.finish(); +} + +/** Decode a state encoded by the step back into entity fields. */ +export function decodePredictState(layout: PredictStateLayout, bytes: Uint8Array): Record { + const r = new WireReader(bytes); + const out: Record = {}; + for (const [name, type] of layout) out[name] = readWire(r, type) as FieldValue; + r.finish(); + return out; +} + +export type WasmPredictionOptions = Readonly<{ + /** The compiled step (generated: `PREDICT_WASM_URL`). */ + source: WasmSource; + /** Step name: the module export is `dg_predict_`. */ + exportName: string; + /** Predicted fields and their codec types (generated `PREDICT_STATE`). */ + state: PredictStateLayout; + /** Context record layout, if the step takes one (generated `PREDICT_CONTEXT`). */ + context?: PayloadLayout; + /** Input payload encoder (generated `encodeInput`). */ + encodeInput(input: TInput): Uint8Array; + /** Loading failed (default: `console.error`); prediction then stays a no-op. */ + onError?(error: unknown): void; +}>; + +/** A compiled step wrapped as `GameClient` prediction. */ +export type WasmPrediction = Readonly<{ + /** `PredictFn` for `GameClient` / `Predictor`: the state unchanged until ready. */ + predict: PredictFn; + /** Resolves when the module is instantiated; rejects if it cannot load. */ + ready: Promise; + /** True once the module is instantiated. */ + loaded(): boolean; + /** Set what the step reads besides state and input (steps with a context). */ + setContext(context: TContext): void; + /** The current context. */ + context(): TContext | undefined; + /** The instantiated module, once loaded. */ + module(): PredictModule | undefined; + /** Steps run so far (diagnostics). */ + steps(): number; +}>; + +const NONE = new Uint8Array(0); + +/** + * Wrap a compiled step as prediction. `predict` encodes the controlled + * entity's predicted fields, the input and the context, runs the step and + * returns the next fields. Until the module is loaded (or, for steps with a + * context, until `setContext`), it returns no change, so the entity simply + * follows the server until prediction can start; the next reconciliation + * then replays every pending input through the step. + */ +export function createWasmPrediction( + options: WasmPredictionOptions +): WasmPrediction { + let module: PredictModule | undefined; + let context: TContext | undefined; + let contextBytes: Uint8Array | undefined = options.context === undefined ? NONE : undefined; + let steps = 0; + const ready = loadPredictModule(options.source).then((loaded) => { + if (!loaded.steps.includes(options.exportName)) { + throw new TypeError(`prediction module has no step dg_predict_${options.exportName}`); + } + module = loaded; + }); + ready.catch((error: unknown) => { + if (options.onError !== undefined) options.onError(error); + else console.error('distributed game prediction: the compiled step did not load', error); + }); + const predict: PredictFn = (fields, input, dtMs) => { + if (module === undefined || contextBytes === undefined) return {}; + const next = module.step( + options.exportName, + encodePredictState(options.state, fields), + options.encodeInput(input), + contextBytes, + dtMs / 1000 + ); + steps += 1; + return decodePredictState(options.state, next); + }; + return { + predict, + ready, + loaded: () => module !== undefined, + setContext(value) { + if (options.context === undefined) return; + context = value; + contextBytes = encodePayload(options.context, value as object); + }, + context: () => context, + module: () => module, + steps: () => steps + }; +} diff --git a/js/tests/fixtures/predict-module.mjs b/js/tests/fixtures/predict-module.mjs new file mode 100644 index 000000000..2737925bd --- /dev/null +++ b/js/tests/fixtures/predict-module.mjs @@ -0,0 +1,72 @@ +/** + * Hand-assembled WebAssembly modules speaking the prediction ABI + * (`distributed_game::prediction`, v1), for SDK tests that need no Rust + * toolchain. Steps: + * + * - `dg_predict_`: returns `state_len` (the next state is the state); + * - `dg_predict_fail`: returns -3 (input rejected). + */ +function leb(value) { + const out = []; + let v = value >>> 0; + do { + let byte = v & 0x7f; + v >>>= 7; + if (v !== 0) byte |= 0x80; + out.push(byte); + } while (v !== 0); + return out; +} + +function str(s) { + const bytes = [...new TextEncoder().encode(s)]; + return [...leb(bytes.length), ...bytes]; +} + +function section(id, body) { + return [id, ...leb(body.length), ...body]; +} + +/** Bytes of a prediction module (`abi` is what `dg_predict_abi` returns). */ +export function predictModuleBytes({ echo = 'sample_step', abi = 1, buffer = 1024 } = {}) { + const types = [2, 0x60, 0, 1, 0x7f, 0x60, 4, 0x7f, 0x7f, 0x7f, 0x7d, 1, 0x7f]; + const functions = [4, 0, 0, 1, 1]; + const memory = [1, 0, 2]; // 2 pages: buffer + 64 KiB scratch + const exports = [ + 5, + ...str('memory'), 2, 0, + ...str('dg_predict_abi'), 0, 0, + ...str('dg_predict_buffer'), 0, 1, + ...str(`dg_predict_${echo}`), 0, 2, + ...str('dg_predict_fail'), 0, 3 + ]; + // Signed LEB128 for i32.const (small values only). + const sleb = (v) => { + const out = []; + let more = true; + while (more) { + let byte = v & 0x7f; + v >>= 7; + if ((v === 0 && (byte & 0x40) === 0) || (v === -1 && (byte & 0x40) !== 0)) more = false; + else byte |= 0x80; + out.push(byte); + } + return out; + }; + const body = (code) => [...leb(code.length + 1), 0, ...code]; + const code = [ + 4, + ...body([0x41, ...sleb(abi), 0x0b]), + ...body([0x41, ...sleb(buffer), 0x0b]), + ...body([0x20, 0, 0x0b]), + ...body([0x41, ...sleb(-3), 0x0b]) + ]; + return new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, + ...section(1, types), + ...section(3, functions), + ...section(5, memory), + ...section(7, exports), + ...section(10, code) + ]); +} diff --git a/js/tests/game-wasm-prediction.test.mjs b/js/tests/game-wasm-prediction.test.mjs new file mode 100644 index 000000000..b567faf87 --- /dev/null +++ b/js/tests/game-wasm-prediction.test.mjs @@ -0,0 +1,119 @@ +// WebAssembly prediction host (`createWasmPrediction`, `PredictModule`): +// loading, the binary ABI round trip, errors, and the context gate. The +// demos' real Rust steps are checked bit for bit against native in +// `examples/game/client/tests/prediction-wasm.test.mjs`. +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import test from 'node:test'; + +import { + PredictAbiError, + PredictModule, + Predictor, + createWasmPrediction, + decodePredictState, + encodePredictState, + loadPredictModule +} from '@hops-ops/distributed/game'; + +import { predictModuleBytes } from './fixtures/predict-module.mjs'; + +const STATE = [ + ['x', { type: 'f32' }], + ['hp', { type: 'u8' }], + ['dead', { type: 'bool' }] +]; + +test('state layouts encode entity fields losslessly as binary32', () => { + const fields = { x: Math.fround(0.1), hp: 7, dead: true, name: 'ignored' }; + const bytes = encodePredictState(STATE, fields); + assert.equal(bytes.length, 4 + 1 + 1); + assert.deepEqual(decodePredictState(STATE, bytes), { x: Math.fround(0.1), hp: 7, dead: true }); +}); + +test('a module runs steps over the scratch buffer and reports ABI errors', async () => { + const module = await PredictModule.load(predictModuleBytes({ echo: 'echo' })); + assert.deepEqual([...module.steps].sort(), ['echo', 'fail']); + const state = new Uint8Array([1, 2, 3, 4]); + const next = module.step('echo', state, new Uint8Array([9]), new Uint8Array([8, 8]), 1 / 30); + assert.deepEqual([...next], [1, 2, 3, 4]); + assert.notEqual(next.buffer, state.buffer, 'a copy, not a view of wasm memory'); + assert.throws(() => module.step('fail', state, state, state, 0), (e) => e instanceof PredictAbiError && e.code === -3); + assert.throws(() => module.step('missing', state, state, state, 0), /no step dg_predict_missing/); + assert.throws(() => module.step('echo', new Uint8Array(70_000), state, state, 0), (e) => e.code === -1); +}); + +test('modules with another ABI version or without the exports are refused', async () => { + await assert.rejects(loadPredictModule(predictModuleBytes({ abi: 2 })), /ABI v2/); + await assert.rejects( + loadPredictModule(new Uint8Array([0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0])), + /not a distributed_game prediction module/ + ); +}); + +test('file: URLs load in Node and are instantiated once', async () => { + const dir = mkdtempSync(join(tmpdir(), 'predict-')); + try { + const path = join(dir, 'step.wasm'); + writeFileSync(path, predictModuleBytes()); + const url = pathToFileURL(path); + const [a, b] = await Promise.all([loadPredictModule(url), loadPredictModule(url.href)]); + assert.equal(a, b, 'cached by URL'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('createWasmPrediction is a no-op until loaded and (if needed) given a context', async () => { + const prediction = createWasmPrediction({ + source: predictModuleBytes(), + exportName: 'sample_step', + state: STATE, + context: [['speed', { type: 'f32' }]], + encodeInput: (input) => new Uint8Array([input.dx & 0xff]) + }); + const fields = { x: 1.5, hp: 3, dead: false }; + assert.deepEqual(prediction.predict(fields, { dx: 1 }, 33), {}, 'not loaded yet'); + await prediction.ready; + assert.ok(prediction.loaded()); + assert.deepEqual(prediction.predict(fields, { dx: 1 }, 33), {}, 'no context yet'); + prediction.setContext({ speed: 2 }); + assert.deepEqual(prediction.context(), { speed: 2 }); + assert.deepEqual(prediction.predict(fields, { dx: 1 }, 33), { x: 1.5, hp: 3, dead: false }); + assert.equal(prediction.steps(), 1); + + // Drives a Predictor like GameClient does. + const kind = { id: 1, name: 'player', priority: 1, fields: STATE.map(([name]) => ({ name, type: 'f32', priority: 1 })) }; + const predictor = new Predictor({ predict: prediction.predict }); + predictor.bind(5, kind, fields); + for (let seq = 1; seq <= 10; seq += 1) predictor.record(seq, { dx: 1 }, 33); + predictor.reconcile(4, { x: 2, hp: 3, dead: false }, 0); + assert.equal(predictor.pending.length, 6); + assert.equal(prediction.steps(), 1 + 10 + 6); + assert.equal(predictor.predicted().x, 2); +}); + +test('a module that does not load is reported and prediction stays off', async () => { + const errors = []; + const prediction = createWasmPrediction({ + source: new Uint8Array([1, 2, 3]), + exportName: 'sample_step', + state: STATE, + encodeInput: () => new Uint8Array(0), + onError: (e) => errors.push(e) + }); + await assert.rejects(prediction.ready); + assert.equal(errors.length, 1); + assert.deepEqual(prediction.predict({ x: 1 }, {}, 33), {}); + const missing = createWasmPrediction({ + source: predictModuleBytes({ echo: 'other' }), + exportName: 'sample_step', + state: STATE, + encodeInput: () => new Uint8Array(0), + onError: () => undefined + }); + await assert.rejects(missing.ready, /no step dg_predict_sample_step/); +}); From f4be902f5f4023cc1cf50768684b6fb2d20bdcc6 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:52:27 -0500 Subject: [PATCH 193/484] feat(game): compile #[predict] steps to WASM for generated clients A zone declares its client-predicted step once in Rust: #[predict(Step, kind = "player")] on fn(&State, &Input, &Context, dt) -> State keeps the function, implements PredictStep and, on wasm32, exports dg_predict_ over the prediction ABI (run_abi/step_bytes run the same path natively). GameSurface::predict records the step, its GameRecord state/context and the declaring Cargo package after checking the kind, the input and every state field type; the surface schema moves to v2. distributed game-wasm builds that package as a wasm32 cdylib, checks the module is self-contained and exports the ABI, and writes /wasm/.wasm with a stamp reusing the browser WASM pure source fingerprint. game-client emits predict.ts and makes the compiled step the default prediction of createClient. --- distributed_cli/src/cli.rs | 49 +++ distributed_cli/src/game_client.rs | 398 +++++++++++++++++- distributed_cli/src/game_wasm.rs | 384 +++++++++++++++++ distributed_cli/src/lib.rs | 7 +- distributed_cli/src/wasm_pures.rs | 44 +- distributed_cli/tests/cli_game_client.rs | 61 ++- .../fixtures/game-client/sample/client.ts | 49 ++- .../fixtures/game-client/sample/events.ts | 16 +- .../fixtures/game-client/sample/index.ts | 3 +- .../fixtures/game-client/sample/input.ts | 2 +- .../fixtures/game-client/sample/predict.ts | 53 +++ .../fixtures/game-client/sample/schema.ts | 2 +- .../fixtures/game-client/sample/surface.json | 56 ++- .../tests/fixtures/game-surface/src/lib.rs | 22 +- distributed_game/src/lib.rs | 12 +- distributed_game/src/prediction.rs | 351 +++++++++++++++ distributed_game/src/surface.rs | 124 +++++- distributed_game/tests/authoring/main.rs | 160 ++++++- .../tests/fixtures/authoring.json | 56 ++- distributed_game_macros/src/lib.rs | 20 +- distributed_game_macros/src/predict.rs | 158 +++++++ .../compile_fail/predict_bad_signature.rs | 19 + .../compile_fail/predict_bad_signature.stderr | 5 + .../tests/compile_fail/predict_needs_kind.rs | 18 + .../compile_fail/predict_needs_kind.stderr | 5 + .../compile_fail/predict_returns_state.rs | 18 + .../compile_fail/predict_returns_state.stderr | 13 + js/tests/game-generated.test.mjs | 33 ++ 28 files changed, 2070 insertions(+), 68 deletions(-) create mode 100644 distributed_cli/src/game_wasm.rs create mode 100644 distributed_cli/tests/fixtures/game-client/sample/predict.ts create mode 100644 distributed_game/src/prediction.rs create mode 100644 distributed_game_macros/src/predict.rs create mode 100644 distributed_game_macros/tests/compile_fail/predict_bad_signature.rs create mode 100644 distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr create mode 100644 distributed_game_macros/tests/compile_fail/predict_needs_kind.rs create mode 100644 distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr create mode 100644 distributed_game_macros/tests/compile_fail/predict_returns_state.rs create mode 100644 distributed_game_macros/tests/compile_fail/predict_returns_state.stderr diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index 8bc9a1a30..25c242691 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -75,6 +75,8 @@ pub enum DistributedCommands { GameManifest(GameManifestArgs), /// Generate typed TypeScript for a distributed_game zone from its GameSurface GameClient(GameClientArgs), + /// Compile a distributed_game zone's `#[predict]` step to WebAssembly for its generated client + GameWasm(GameWasmArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), /// Extract the embedded Distributed agent skills into a project @@ -130,6 +132,8 @@ pub enum ServiceCommands { GameManifest(GameManifestArgs), /// Generate typed TypeScript for a distributed_game zone from its GameSurface GameClient(GameClientArgs), + /// Compile a distributed_game zone's `#[predict]` step to WebAssembly for its generated client + GameWasm(GameWasmArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), /// Extract the embedded Distributed agent skills into a project @@ -488,6 +492,25 @@ pub struct GameClientArgs { pub import_extension: GameImportExtension, } +#[derive(Args, Debug)] +pub struct GameWasmArgs { + /// GameSurface JSON (from `distributed game-manifest`) with a predicted step. + #[arg(long)] + pub manifest: PathBuf, + /// Generated client directory; the module is written to `/wasm/.wasm`. + #[arg(long)] + pub out: PathBuf, + /// Cargo project containing the package that declares the step. + #[arg(long, default_value = ".")] + pub path: PathBuf, + /// Cargo.toml of that project. Overrides --path. + #[arg(long)] + pub manifest_path: Option, + /// Verify the module is current without compiling. + #[arg(long)] + pub check: bool, +} + #[derive(Args, Debug)] #[command(group( ArgGroup::new("client_surface") @@ -695,6 +718,7 @@ pub fn run_distributed(args: &DistributedArgs) -> Result<(), Box> { DistributedCommands::ClientManifest(client) => run_client_manifest(client), DistributedCommands::GameManifest(game) => run_game_manifest(game), DistributedCommands::GameClient(game) => run_game_client(game), + DistributedCommands::GameWasm(game) => run_game_wasm(game), DistributedCommands::Schema(schema) => run_schema(schema), DistributedCommands::Skills(skills) => match &skills.command { SkillsCommands::Init(init) => run_skills_init(init), @@ -744,6 +768,7 @@ pub fn run(args: &ServiceArgs) -> Result<(), Box> { ServiceCommands::ClientManifest(client) => run_client_manifest(client), ServiceCommands::GameManifest(game) => run_game_manifest(game), ServiceCommands::GameClient(game) => run_game_client(game), + ServiceCommands::GameWasm(game) => run_game_wasm(game), ServiceCommands::Schema(schema) => run_schema(schema), ServiceCommands::Skills(skills) => match &skills.command { SkillsCommands::Init(init) => run_skills_init(init), @@ -2413,6 +2438,30 @@ fn run_game_client(args: &GameClientArgs) -> Result<(), Box> { Ok(()) } +fn run_game_wasm(args: &GameWasmArgs) -> Result<(), Box> { + let source = read_utf8_bounded(&args.manifest, MAX_CLIENT_MANIFEST_BYTES, "game surface")?; + let cargo_manifest = args + .manifest_path + .clone() + .unwrap_or_else(|| args.path.join("Cargo.toml")); + let outcome = crate::game_wasm::run_game_wasm(&crate::game_wasm::GameWasmOptions { + surface: &source, + cargo_manifest: &cargo_manifest, + out: &args.out, + check: args.check, + }) + .map_err(|error| format!("{}: {error}", args.manifest.display()))?; + match outcome { + crate::game_wasm::GameWasmOutcome::Current(path) => { + println!("Predicted step {} is current", path.display()) + } + crate::game_wasm::GameWasmOutcome::Built(path) => { + println!("Compiled predicted step to {}", path.display()) + } + } + Ok(()) +} + /// Files directly in `root` (the generator owns the directory). fn game_client_dir_files(root: &Path) -> Result, Box> { let mut out = BTreeSet::new(); diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs index e98ddbd82..b9c3d6502 100644 --- a/distributed_cli/src/game_client.rs +++ b/distributed_cli/src/game_client.rs @@ -1,5 +1,5 @@ //! `distributed game-client`: typed TypeScript for one `distributed_game` -//! zone surface (`GameSurface` JSON, schema v1, from `distributed +//! zone surface (`GameSurface` JSON, schema v2, from `distributed //! game-manifest`). //! //! The generated files import only `@hops-ops/distributed/game` and are @@ -10,7 +10,8 @@ //! | `schema.ts` | `KIND` ids, per-kind field interfaces + accessors over rendered entities, field wire types, `CORRECTIONS` defaults | //! | `input.ts` | the input interface, `BUTTON` bits, `encodeInput` / `decodeInput` / `sanitizeInput` | //! | `events.ts` | record + event payload interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | -//! | `client.ts` | `createClient`: a `GameClient` with the input encoder and correction defaults wired in, plus typed `on` | +//! | `client.ts` | `createClient`: a `GameClient` with the input encoder and correction defaults wired in, plus typed `on`; with a predicted step, prediction defaults to the compiled WebAssembly step | +//! | `predict.ts` | only with a `#[predict]` step: its state/context layouts, the module URL (`wasm/.wasm`, built by `distributed game-wasm`) and `createPrediction` | //! | `index.ts` | re-exports | //! | `surface.json` | the surface it was generated from (so `--check` also catches manifest drift) | //! @@ -26,7 +27,10 @@ use serde::Deserialize; use crate::client_compiler::GeneratedClientFile; /// The only surface schema version this generator understands. -pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 1; +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 2; + +/// The only prediction ABI version this generator (and the SDK) speaks. +pub const PREDICT_ABI_VERSION: u32 = 1; const SDK: &str = "@hops-ops/distributed/game"; @@ -51,7 +55,7 @@ impl ImportExtension { } } -// ---- surface mirror (schema v1) ------------------------------------------- +// ---- surface mirror (schema v2) ------------------------------------------- #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -63,6 +67,21 @@ struct Surface { input: Option, events: Vec, records: Vec, + #[serde(default)] + predict: Option, +} + +/// The zone's client-predicted step (`#[predict]`). +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Predict { + pub(crate) kind: String, + pub(crate) package: String, + pub(crate) export: String, + pub(crate) state: String, + #[serde(default)] + pub(crate) context: Option, + pub(crate) abi: u32, } #[derive(Debug, Deserialize)] @@ -350,10 +369,28 @@ pub fn generate_game_client( serde_json::to_string_pretty(&value).expect("surface serializes") + "\n", ), ]; + if let Some(predict) = gen.predict_ts()? { + files.push(file("predict.ts", predict)); + } files.sort_by(|a, b| a.path.cmp(&b.path)); Ok(files) } +/// What `distributed game-wasm` builds for a surface: its name and its +/// validated predicted step (`None` when the zone predicts nothing). +pub(crate) fn surface_prediction(manifest_json: &str) -> GenResult<(String, Option)> { + validate_game_surface(manifest_json)?; + let surface: Surface = + serde_json::from_str(manifest_json).map_err(|e| format!("invalid game surface: {e}"))?; + Ok((surface.name, surface.predict)) +} + +/// Module path of a surface's compiled step, relative to the generated +/// client directory. +pub(crate) fn predict_wasm_path(surface: &str) -> String { + format!("wasm/{surface}.wasm") +} + /// Validate a manifest (as `game-manifest` prints it). pub fn validate_game_surface(manifest_json: &str) -> GenResult<()> { generate_game_client(manifest_json, ImportExtension::Ts).map(|_| ()) @@ -451,9 +488,91 @@ impl<'a> Gen<'a> { } } self.record_order()?; + self.check_predict()?; self.check_exports() } + /// The predicted step names a kind of this surface, a state record whose + /// fields are fields of that kind (plain scalar types), an optional + /// context record, and the ABI this generator speaks. + fn check_predict(&self) -> GenResult<()> { + let Some(predict) = &self.surface.predict else { + return Ok(()); + }; + if predict.abi != PREDICT_ABI_VERSION { + return Err(format!( + "predicted step uses ABI v{}; this CLI generates ABI v{PREDICT_ABI_VERSION}", + predict.abi + )); + } + if predict.export.is_empty() + || !predict + .export + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!( + "invalid predicted step export {:?}", + predict.export + )); + } + if predict.package.is_empty() { + return Err("predicted step names no Cargo package".into()); + } + if self.surface.input.is_none() { + return Err("a predicted step needs the zone's input type".into()); + } + let kind = self + .surface + .kinds + .iter() + .find(|k| k.name == predict.kind) + .ok_or_else(|| format!("predicted kind {:?} is not replicated", predict.kind))?; + let state = self + .records + .get(predict.state.as_str()) + .ok_or_else(|| format!("predicted state record {} is missing", predict.state))?; + if state.fields.is_empty() { + return Err(format!("predicted state {} has no fields", state.name)); + } + for field in &state.fields { + let entity = kind + .fields + .iter() + .find(|f| f.name == field.name) + .ok_or_else(|| { + format!( + "predicted state {} field {} is not a field of kind {}", + state.name, field.name, kind.name + ) + })?; + let matches = match field.ty { + Wire::F32 => matches!( + entity.ty, + Wire::F32 | Wire::Quant { .. } | Wire::Angle { .. } + ), + Wire::Bool => matches!(entity.ty, Wire::Bool), + Wire::U8 => matches!(entity.ty, Wire::U8), + Wire::U16 => matches!(entity.ty, Wire::U16), + Wire::U32 => matches!(entity.ty, Wire::U32), + Wire::I32 => matches!(entity.ty, Wire::I32), + _ => false, + }; + if !matches { + return Err(format!( + "predicted state {} field {} does not match the type of kind {} field {}", + state.name, field.name, kind.name, entity.name + )); + } + } + if let Some(context) = &predict.context { + if !self.records.contains_key(context.as_str()) { + return Err(format!("predicted context record {context} is missing")); + } + } + Ok(()) + } + /// Every name the generated modules export, so `index.ts` re-exports /// cannot collide. fn check_exports(&self) -> GenResult<()> { @@ -502,6 +621,20 @@ impl<'a> Gen<'a> { for event in &self.surface.events { names.push(format!("{}Event", pascal(&event.name))); } + if self.surface.predict.is_some() { + names.extend( + [ + "PREDICT", + "PREDICT_STATE", + "PREDICT_CONTEXT", + "PREDICT_WASM_URL", + "PredictContext", + ] + .map(String::from), + ); + names.push(format!("create{prefix}Prediction")); + names.push(format!("{prefix}Prediction")); + } let mut seen = BTreeSet::new(); for name in names { if !seen.insert(name.clone()) { @@ -883,12 +1016,17 @@ impl<'a> Gen<'a> { if uses_value { sdk.extend(["decodeValue", "encodeValue"]); } - if uses_value || !records.is_empty() { + if uses_value + || records + .iter() + .any(|r| self.encoded_records().contains(r.name.as_str())) + { sdk.push("type WireType"); } sdk.sort_by_key(|s| (s.starts_with("type "), s.to_string())); let _ = writeln!(out, "import {{ {} }} from '{SDK}';", sdk.join(", ")); + let encoded = self.encoded_records(); for record in &records { out.push('\n'); out.push_str(&self.interface( @@ -896,12 +1034,16 @@ impl<'a> Gen<'a> { &format!("Record `{}` (`#[derive(GameRecord)]`).", record.name), &record.fields, )); - let _ = writeln!( - out, - "\nconst {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};", - constant(&record.name), - indent(&self.layout(&record.fields)) - ); + // Records only the predicted step uses (its state and context) + // are encoded by `predict.ts` layouts, not by an event codec. + if encoded.contains(record.name.as_str()) { + let _ = writeln!( + out, + "\nconst {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};", + constant(&record.name), + indent(&self.layout(&record.fields)) + ); + } } for event in events { @@ -997,11 +1139,44 @@ impl<'a> Gen<'a> { Ok(out) } + /// Records an event payload (or the input) encodes, directly or nested. + fn encoded_records(&self) -> BTreeSet<&'a str> { + fn walk<'r>(ty: &'r Wire, out: &mut Vec<&'r str>) { + match ty { + Wire::List { item } | Wire::Optional { item } => walk(item, out), + Wire::Record { name } => out.push(name), + _ => {} + } + } + let mut pending = Vec::new(); + for event in &self.surface.events { + match &event.payload { + Payload::Fields { fields } => fields.iter().for_each(|f| walk(&f.ty, &mut pending)), + Payload::Value { ty } => walk(ty, &mut pending), + } + } + if let Some(input) = &self.surface.input { + input.fields.iter().for_each(|f| walk(&f.ty, &mut pending)); + } + let mut seen = BTreeSet::new(); + while let Some(name) = pending.pop() { + if seen.insert(name) { + if let Some(record) = self.records.get(name) { + record.fields.iter().for_each(|f| walk(&f.ty, &mut pending)); + } + } + } + seen + } + fn client_ts(&self) -> String { let prefix = pascal(&self.surface.name); let mut out = self.header("Typed client factory."); let input = self.surface.input.as_ref().map(|i| i.name.as_str()); match input { + Some(name) if self.surface.predict.is_some() => { + out.push_str(&self.predicted_client_ts(name)); + } Some(name) => { let _ = writeln!( out, @@ -1044,13 +1219,147 @@ impl<'a> Gen<'a> { out } + /// `client.ts` of a surface with a `#[predict]` step: prediction defaults + /// to the compiled WebAssembly step. + fn predicted_client_ts(&self, name: &str) -> String { + let prefix = pascal(&self.surface.name); + let mut out = String::new(); + let _ = writeln!( + out, + "import {{ GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\nimport {{ encodeInput, type {name} }} from '{}';\nimport {{ create{prefix}Prediction, type {prefix}Prediction }} from '{}';\nimport {{ CORRECTIONS }} from '{}';\n", + self.local("events"), + self.local("input"), + self.local("predict"), + self.local("schema") + ); + let _ = writeln!( + out, + "/**\n * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the\n * compiled `#[predict]` step) are filled in. A `predict` given here replaces\n * the WebAssembly step.\n */\nexport type {prefix}PredictionOptions = Omit, 'encodeInput' | 'predict'> &\n\tPartial, 'encodeInput' | 'predict'>>;\n\nexport type {prefix}ClientOptions = Omit, 'prediction'> &\n\tReadonly<{{\n\t\t/** Prediction tuning, or `false` for none. Default: the compiled step. */\n\t\tprediction?: {prefix}PredictionOptions | false;\n\t\t/** Where to load the compiled step from (default `PREDICT_WASM_URL`). */\n\t\twasm?: WasmSource;\n\t}}>;\n" + ); + let _ = writeln!( + out, + "export type {prefix}Client = Readonly<{{\n\tclient: GameClient<{name}>;\n\t/** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */\n\tprediction: {prefix}Prediction | undefined;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n\t/** Send one input: predicted when prediction is on, raw otherwise. */\n\tsend(input: {name}): number | undefined;\n}}>;\n" + ); + let _ = write!( + out, + "/**\n * A `GameClient` for the `{surface}` surface with its input encoder, correction\n * defaults and the compiled predicted step wired in.\n */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst {{ prediction: tuning, wasm, ...rest }} = options;\n\tconst prediction =\n\t\ttuning === false || tuning?.predict !== undefined ? undefined : create{prefix}Prediction(wasm);\n\tconst client = new GameClient<{name}>({{\n\t\t...rest,\n\t\tprediction:\n\t\t\ttuning === false\n\t\t\t\t? undefined\n\t\t\t\t: {{\n\t\t\t\t\t\t...tuning,\n\t\t\t\t\t\tpredict: tuning?.predict ?? prediction!.predict,\n\t\t\t\t\t\tencodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)),\n\t\t\t\t\t\tcorrections: mergeCorrections(CORRECTIONS, tuning?.corrections)\n\t\t\t\t\t}}\n\t}});\n\treturn {{\n\t\tclient,\n\t\tprediction,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}}),\n\t\tsend: (input) =>\n\t\t\ttuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input)\n\t}};\n}}\n", + surface = self.surface.name + ); + out + } + fn index_ts(&self) -> String { let mut out = self.header("Everything generated for this surface."); - for module in ["client", "events", "input", "schema"] { + let mut modules = vec!["client", "events", "input"]; + if self.surface.predict.is_some() { + modules.push("predict"); + } + modules.push("schema"); + for module in modules { let _ = writeln!(out, "export * from '{}';", self.local(module)); } out } + + fn predict_ts(&self) -> GenResult> { + let Some(predict) = &self.surface.predict else { + return Ok(None); + }; + let input = self + .surface + .input + .as_ref() + .ok_or("a predicted step needs the zone's input type")?; + let state = self.records[predict.state.as_str()]; + let prefix = pascal(&self.surface.name); + let mut out = self.header( + "Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI).", + ); + let mut sdk = vec![ + "createWasmPrediction", + "type PredictStateLayout", + "type WasmPrediction", + "type WasmSource", + ]; + if predict.context.is_some() { + sdk.push("type PayloadLayout"); + } + let _ = writeln!(out, "import {{ {} }} from '{SDK}';\n", sdk.join(", ")); + if let Some(context) = &predict.context { + let _ = writeln!( + out, + "import type {{ {context} }} from '{}';", + self.local("events") + ); + } + let _ = writeln!( + out, + "import {{ encodeInput, type {} }} from '{}';\n", + input.name, + self.local("input") + ); + let _ = writeln!( + out, + "/** The predicted step: `#[predict]` fn `{}` of Cargo package `{}`, predicting kind `{}`. */\nexport const PREDICT = {{\n\tkind: {},\n\texport: {},\n\tpackage: {},\n\tstate: {},\n\tabi: {},\n}} as const;\n", + predict.export, + predict.package, + predict.kind, + string(&predict.kind), + string(&predict.export), + string(&predict.package), + string(&predict.state), + predict.abi + ); + let _ = writeln!( + out, + "/** Predicted `{}` fields (record `{}`): wire field name and codec type, in record order. */\nexport const PREDICT_STATE: PredictStateLayout = [", + predict.kind, state.name + ); + for field in &state.fields { + let _ = writeln!( + out, + "\t[{}, {}],", + string(&field.name), + self.wire_literal(&field.ty) + ); + } + out.push_str("];\n\n"); + match &predict.context { + Some(context) => { + let record = self.records[context.as_str()]; + let _ = writeln!( + out, + "/** What the step reads besides state and input (`prediction.setContext`). */\nexport type PredictContext = {context};\n\n/** Layout of the context record `{context}`. */\nexport const PREDICT_CONTEXT: PayloadLayout | undefined = {};\n", + self.layout(&record.fields) + ); + } + None => { + out.push_str("/** The step takes no context. */\nexport type PredictContext = undefined;\n\n/** The step takes no context. */\nexport const PREDICT_CONTEXT = undefined;\n\n"); + } + } + let _ = writeln!( + out, + "/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */\nexport const PREDICT_WASM_URL: URL = new URL({}, import.meta.url);\n", + string(&format!("./{}", predict_wasm_path(&self.surface.name))) + ); + let _ = writeln!( + out, + "/** The `{surface}` step as `GameClient` prediction (see `createWasmPrediction`). */\nexport type {prefix}Prediction = WasmPrediction<{input}, PredictContext>;\n", + surface = self.surface.name, + input = input.name + ); + let _ = writeln!( + out, + "/**\n * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict`\n * leaves the state unchanged until `ready` resolves{}.\n */\nexport function create{prefix}Prediction(source: WasmSource = PREDICT_WASM_URL): {prefix}Prediction {{\n\treturn createWasmPrediction<{input}, PredictContext>({{\n\t\tsource,\n\t\texportName: PREDICT.export,\n\t\tstate: PREDICT_STATE,\n\t\tcontext: PREDICT_CONTEXT,\n\t\tencodeInput\n\t}});\n}}", + if predict.context.is_some() { + " and a context is set" + } else { + "" + }, + input = input.name + ); + Ok(Some(out)) + } } fn simple_tag(ty: &Wire) -> &'static str { @@ -1121,19 +1430,78 @@ mod tests { #[test] fn rejects_other_schema_versions_and_unknown_fields() { - let err = generate_game_client(r#"{"schemaVersion": 2}"#, ImportExtension::Ts).unwrap_err(); + let err = generate_game_client(r#"{"schemaVersion": 1}"#, ImportExtension::Ts).unwrap_err(); assert!(err.contains("schemaVersion"), "{err}"); let err = generate_game_client( - r#"{"schemaVersion":1,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, + r#"{"schemaVersion":2,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, ImportExtension::Ts, ) .unwrap_err(); assert!(err.contains("unknown field"), "{err}"); } + fn sample() -> serde_json::Value { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../distributed_game/tests/fixtures/authoring.json" + )) + .unwrap(); + fixture["surface"].clone() + } + + fn generate(surface: &serde_json::Value) -> GenResult> { + generate_game_client(&surface.to_string(), ImportExtension::Ts) + } + + #[test] + fn validates_the_predicted_step() { + let ok = sample(); + let files = generate(&ok).unwrap(); + let predict = files.iter().find(|f| f.path == "predict.ts").unwrap(); + assert!(predict + .contents + .contains("new URL('./wasm/sample.wasm', import.meta.url)")); + assert!(predict.contents.contains("['dead', { type: 'bool' }]")); + + type Mutate = fn(&mut serde_json::Value); + let cases: [(&str, Mutate); 6] = [ + ("ABI v9", |s| s["predict"]["abi"] = 9.into()), + ("not replicated", |s| s["predict"]["kind"] = "ghost".into()), + ("state record Nope is missing", |s| { + s["predict"]["state"] = "Nope".into() + }), + ("context record Nope is missing", |s| { + s["predict"]["context"] = "Nope".into() + }), + ("invalid predicted step export", |s| { + s["predict"]["export"] = "a-b".into() + }), + ("does not match the type", |s| { + let records = s["records"].as_array_mut().unwrap(); + let state = records + .iter_mut() + .find(|r| r["name"] == "SampleState") + .unwrap(); + state["fields"][2]["type"] = serde_json::json!({"type": "u16"}); + }), + ]; + for (expected, mutate) in cases { + let mut surface = ok.clone(); + mutate(&mut surface); + let err = generate(&surface).unwrap_err(); + assert!(err.contains(expected), "{expected}: {err}"); + } + + let mut none = ok.clone(); + none.as_object_mut().unwrap().remove("predict"); + let files = generate(&none).unwrap(); + assert!(files.iter().all(|f| f.path != "predict.ts")); + let client = files.iter().find(|f| f.path == "client.ts").unwrap(); + assert!(!client.contents.contains("Prediction(")); + } + #[test] fn rejects_recursive_records() { - let json = r#"{"schemaVersion":1,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], + let json = r#"{"schemaVersion":2,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], "records":[{"name":"Node","fields":[{"name":"next","type":{"type":"optional","item":{"type":"record","name":"Node"}}}]}]}"#; let err = generate_game_client(json, ImportExtension::Ts).unwrap_err(); assert!(err.contains("recursive"), "{err}"); diff --git a/distributed_cli/src/game_wasm.rs b/distributed_cli/src/game_wasm.rs new file mode 100644 index 000000000..3c44823cd --- /dev/null +++ b/distributed_cli/src/game_wasm.rs @@ -0,0 +1,384 @@ +//! `distributed game-wasm`: compile a zone's client-predicted step +//! (`#[predict]`, recorded in its `GameSurface`) to WebAssembly next to the +//! generated client. +//! +//! The surface names the Cargo package that declares the step. The command +//! builds that package's library as a `cdylib` for `wasm32-unknown-unknown` +//! (`cargo rustc --release`), checks the module speaks the prediction ABI +//! (no imports; exports `memory`, `dg_predict_buffer`, `dg_predict_abi` +//! and `dg_predict_`) and writes it to `/wasm/.wasm`, +//! which the generated `predict.ts` loads. No wasm-bindgen glue, no JSON: +//! the SDK instantiates the module directly. +//! +//! A stamp next to the module (`.stamp.json`) records the source +//! fingerprint of the package and its local dependencies (the same one the +//! browser WASM pures use), the compiler and the module's hash, so an +//! unchanged step is not rebuilt and `--check` can verify a build is current +//! without compiling. + +use std::error::Error; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::game_client::{predict_wasm_path, surface_prediction}; +use crate::wasm_pures::{cargo_metadata, ensure_real_directory_path, package_source_identity}; + +const TARGET: &str = "wasm32-unknown-unknown"; +const STAMP_VERSION: u32 = 1; +const MAX_MODULE_BYTES: u64 = 64 * 1024 * 1024; + +/// What to build. +pub(crate) struct GameWasmOptions<'a> { + /// Surface JSON text. + pub(crate) surface: &'a str, + /// Cargo.toml of the project containing the declaring package. + pub(crate) cargo_manifest: &'a Path, + /// Generated client directory. + pub(crate) out: &'a Path, + /// Verify only. + pub(crate) check: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Stamp { + version: u32, + package: String, + export: String, + abi: u32, + source_identity: String, + compiler_identity: String, + module_sha256: String, +} + +/// Outcome of a run. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum GameWasmOutcome { + /// The module on disk matches the sources. + Current(PathBuf), + /// The module was (re)built. + Built(PathBuf), +} + +pub(crate) fn run_game_wasm( + options: &GameWasmOptions<'_>, +) -> Result> { + let (surface, predict) = surface_prediction(options.surface)?; + let predict = predict.ok_or_else(|| { + format!( + "game surface `{surface}` declares no predicted step; add `.predict::()` (a `#[predict]` fn) to its GameSurface" + ) + })?; + let metadata = cargo_metadata(options.cargo_manifest)?; + let mut candidates = metadata + .packages + .iter() + .filter(|p| p.name == predict.package && p.source.is_none()); + let package = candidates.next().ok_or_else(|| { + format!( + "predicted step `{}` is declared by Cargo package `{}`, which is not a local package of {}", + predict.export, + predict.package, + options.cargo_manifest.display() + ) + })?; + if candidates.next().is_some() { + return Err(format!( + "more than one local Cargo package is named `{}`", + predict.package + ) + .into()); + } + let lib = package + .targets + .iter() + .find(|t| { + t.kind + .iter() + .any(|k| matches!(k.as_str(), "lib" | "rlib" | "cdylib")) + }) + .ok_or_else(|| format!("Cargo package `{}` has no library target", package.name))?; + let lib_name = lib.name.replace('-', "_"); + + let module_rel = predict_wasm_path(&surface); + let module_path = options.out.join(&module_rel); + let stamp_path = module_path.with_extension("stamp.json"); + let mut expected = Stamp { + version: STAMP_VERSION, + package: predict.package.clone(), + export: predict.export.clone(), + abi: predict.abi, + source_identity: package_source_identity(&metadata, &package.id)?, + compiler_identity: compiler_identity()?, + module_sha256: String::new(), + }; + if stamp_is_current(&stamp_path, &module_path, &expected)? { + return Ok(GameWasmOutcome::Current(module_path)); + } + if options.check { + return Err(format!( + "compiled step {} is missing or stale; run `distributed game-wasm` without --check", + module_path.display() + ) + .into()); + } + + eprintln!( + "distributed: compiling predicted step `{}` (Cargo package {}) to WebAssembly", + predict.export, predict.package + ); + let status = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .arg("rustc") + .arg("--manifest-path") + .arg(options.cargo_manifest) + .args([ + "-p", + &predict.package, + "--lib", + "--release", + "--target", + TARGET, + ]) + .args(["--crate-type", "cdylib"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::inherit()) + .status() + .map_err(|error| format!("failed to run cargo for the predicted step: {error}"))?; + if !status.success() { + return Err(format!( + "compiling predicted step `{}` for {TARGET} failed ({status}); is the target installed (`rustup target add {TARGET}`)?", + predict.export + ) + .into()); + } + let artifact = metadata + .target_directory + .join(TARGET) + .join("release") + .join(format!("{lib_name}.wasm")); + let size = fs::metadata(&artifact) + .map_err(|error| format!("cargo produced no {}: {error}", artifact.display()))? + .len(); + if size > MAX_MODULE_BYTES { + return Err(format!( + "{} is larger than {MAX_MODULE_BYTES} bytes", + artifact.display() + ) + .into()); + } + let module = fs::read(&artifact)?; + check_module(&module, &predict.export) + .map_err(|error| format!("{}: {error}", artifact.display()))?; + expected.module_sha256 = format!("{:x}", Sha256::digest(&module)); + + let wasm_dir = module_path.parent().expect("module path has a directory"); + fs::create_dir_all(options.out)?; + let out_root = options.out.canonicalize()?; + ensure_real_directory_path(&out_root, &out_root.join("wasm"))?; + let staged = wasm_dir.join(format!(".{surface}.wasm.tmp")); + fs::write(&staged, &module)?; + fs::rename(&staged, &module_path)?; + fs::write(&stamp_path, serde_json::to_string_pretty(&expected)? + "\n")?; + Ok(GameWasmOutcome::Built(module_path)) +} + +fn stamp_is_current( + stamp_path: &Path, + module_path: &Path, + expected: &Stamp, +) -> Result> { + let Ok(text) = fs::read_to_string(stamp_path) else { + return Ok(false); + }; + let Ok(stamp) = serde_json::from_str::(&text) else { + return Ok(false); + }; + let Ok(module) = fs::read(module_path) else { + return Ok(false); + }; + let actual = format!("{:x}", Sha256::digest(&module)); + Ok(stamp.module_sha256 == actual + && Stamp { + module_sha256: actual, + ..expected.clone() + } == stamp) +} + +/// `rustc -vV` (the toolchain cargo will use, including rustup overrides). +fn compiler_identity() -> Result> { + let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let output = Command::new(rustc) + .arg("-vV") + .output() + .map_err(|error| format!("failed to run `rustc -vV`: {error}"))?; + if !output.status.success() { + return Err("`rustc -vV` failed".into()); + } + Ok(format!("sha256:{:x}", Sha256::digest(&output.stdout))) +} + +/// The module imports nothing and exports the prediction ABI. +pub(crate) fn check_module(module: &[u8], export: &str) -> Result<(), String> { + let sections = wasm_sections(module)?; + let mut exports = Vec::new(); + for (id, body) in sections { + match id { + 2 => { + let mut r = WasmReader::new(body); + if r.u32()? != 0 { + return Err("the module imports functions or memory; a predicted step must be self-contained (no wasm-bindgen, no host calls)".into()); + } + } + 7 => { + let mut r = WasmReader::new(body); + for _ in 0..r.u32()? { + let name = r.name()?; + let kind = r.byte()?; + let _index = r.u32()?; + exports.push((name, kind)); + } + } + _ => {} + } + } + let step = format!("dg_predict_{export}"); + for (name, kind) in [ + ("memory", 2u8), + ("dg_predict_buffer", 0), + ("dg_predict_abi", 0), + (step.as_str(), 0), + ] { + if !exports.iter().any(|(n, k)| n == name && *k == kind) { + return Err(format!( + "the module does not export `{name}` (is the step declared with `#[predict]` in this package?)" + )); + } + } + Ok(()) +} + +fn wasm_sections(module: &[u8]) -> Result, String> { + if module.len() < 8 || &module[..4] != b"\0asm" || module[4..8] != [1, 0, 0, 0] { + return Err("not a WebAssembly v1 module".into()); + } + let mut r = WasmReader::new(&module[8..]); + let mut sections = Vec::new(); + while !r.done() { + let id = r.byte()?; + let len = r.u32()? as usize; + sections.push((id, r.take(len)?)); + } + Ok(sections) +} + +struct WasmReader<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> WasmReader<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, at: 0 } + } + + fn done(&self) -> bool { + self.at >= self.bytes.len() + } + + fn byte(&mut self) -> Result { + let b = *self.bytes.get(self.at).ok_or("truncated module")?; + self.at += 1; + Ok(b) + } + + fn u32(&mut self) -> Result { + let mut value = 0u32; + for shift in (0..35).step_by(7) { + let b = self.byte()?; + value |= u32::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Ok(value); + } + } + Err("malformed LEB128".into()) + } + + fn take(&mut self, len: usize) -> Result<&'a [u8], String> { + let end = self.at.checked_add(len).filter(|e| *e <= self.bytes.len()); + let end = end.ok_or("truncated section")?; + let out = &self.bytes[self.at..end]; + self.at = end; + Ok(out) + } + + fn name(&mut self) -> Result { + let len = self.u32()? as usize; + String::from_utf8(self.take(len)?.to_vec()).map_err(|_| "export name is not UTF-8".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn leb(mut v: u32, out: &mut Vec) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + + fn module(imports: u32, exports: &[(&str, u8)]) -> Vec { + let mut out = b"\0asm\x01\0\0\0".to_vec(); + let mut body = Vec::new(); + leb(imports, &mut body); + out.push(2); + leb(body.len() as u32, &mut out); + out.extend(&body); + let mut body = Vec::new(); + leb(exports.len() as u32, &mut body); + for (name, kind) in exports { + leb(name.len() as u32, &mut body); + body.extend(name.as_bytes()); + body.push(*kind); + leb(0, &mut body); + } + out.push(7); + leb(body.len() as u32, &mut out); + out.extend(&body); + out + } + + const ABI: [(&str, u8); 4] = [ + ("memory", 2), + ("dg_predict_buffer", 0), + ("dg_predict_abi", 0), + ("dg_predict_arena_step", 0), + ]; + + #[test] + fn accepts_a_self_contained_module_with_the_abi() { + check_module(&module(0, &ABI), "arena_step").unwrap(); + } + + #[test] + fn rejects_imports_missing_exports_and_garbage() { + let error = check_module(&module(1, &ABI), "arena_step").unwrap_err(); + assert!(error.contains("imports"), "{error}"); + let error = check_module(&module(0, &ABI), "grid_step").unwrap_err(); + assert!(error.contains("dg_predict_grid_step"), "{error}"); + assert!(check_module(b"nope", "x").is_err()); + let mut truncated = module(0, &ABI); + truncated.truncate(truncated.len() - 3); + assert!(check_module(&truncated, "arena_step").is_err()); + } +} diff --git a/distributed_cli/src/lib.rs b/distributed_cli/src/lib.rs index cea0aadde..6eab9ba80 100644 --- a/distributed_cli/src/lib.rs +++ b/distributed_cli/src/lib.rs @@ -10,6 +10,7 @@ mod cli; mod client_compiler; pub mod contracts; mod game_client; +mod game_wasm; mod generate; mod js_framework; pub mod lifecycle; @@ -22,9 +23,9 @@ pub use cli::{ run, run_distributed, AgentHarness, BuildArgs, Bus, ClientArgs, ClientManifestArgs, ContractsAcceptArgs, ContractsArgs, ContractsCheckArgs, ContractsCommands, ContractsOutput, DescribeArgs, DevArgs, DistributedArgs, DistributedCommands, Framework, GameClientArgs, - GameManifestArgs, GitopsPromote, JavascriptWatchArgs, LifecycleOutput, ManifestFormat, Metrics, - ProbeArgs, ScaffoldArgs, SchemaArgs, SchemaDialect, SchemaFormat, ServiceArgs, ServiceCommands, - SkillsArgs, SkillsCommands, SkillsInitArgs, Store, Transport, + GameManifestArgs, GameWasmArgs, GitopsPromote, JavascriptWatchArgs, LifecycleOutput, + ManifestFormat, Metrics, ProbeArgs, ScaffoldArgs, SchemaArgs, SchemaDialect, SchemaFormat, + ServiceArgs, ServiceCommands, SkillsArgs, SkillsCommands, SkillsInitArgs, Store, Transport, }; pub use client_compiler::{ compile_client, ClientCompileError, ClientCompileInput, ClientDocument, ClientSourceLocation, diff --git a/distributed_cli/src/wasm_pures.rs b/distributed_cli/src/wasm_pures.rs index 859f0a986..98a446d89 100644 --- a/distributed_cli/src/wasm_pures.rs +++ b/distributed_cli/src/wasm_pures.rs @@ -23,9 +23,11 @@ struct WasmPure { } #[derive(Debug, Deserialize)] -struct CargoMetadata { - workspace_root: PathBuf, - packages: Vec, +pub(crate) struct CargoMetadata { + pub(crate) workspace_root: PathBuf, + #[serde(default)] + pub(crate) target_directory: PathBuf, + pub(crate) packages: Vec, resolve: Option, #[serde(default)] metadata: Value, @@ -44,22 +46,24 @@ struct CargoResolveNode { } #[derive(Debug, Deserialize)] -struct CargoPackage { - id: String, - name: String, - manifest_path: PathBuf, - source: Option, +pub(crate) struct CargoPackage { + pub(crate) id: String, + pub(crate) name: String, + pub(crate) manifest_path: PathBuf, + pub(crate) source: Option, #[serde(default)] features: BTreeMap>, #[serde(default)] - targets: Vec, + pub(crate) targets: Vec, } #[derive(Debug, Deserialize)] -struct CargoTarget { +pub(crate) struct CargoTarget { + #[serde(default)] + pub(crate) name: String, src_path: PathBuf, #[serde(default)] - kind: Vec, + pub(crate) kind: Vec, } #[derive(Debug, Deserialize, Serialize)] @@ -253,7 +257,7 @@ fn portable_import_path(import: &str) -> Result> { Ok(path.to_path_buf()) } -fn cargo_metadata(manifest: &Path) -> Result> { +pub(crate) fn cargo_metadata(manifest: &Path) -> Result> { let output = Command::new("cargo") .args(["metadata", "--format-version", "1", "--manifest-path"]) .arg(manifest) @@ -269,7 +273,7 @@ fn cargo_metadata(manifest: &Path) -> Result> { Ok(serde_json::from_slice(&output.stdout)?) } -fn package_source_identity( +pub(crate) fn package_source_identity( metadata: &CargoMetadata, root_package_id: &str, ) -> Result> { @@ -618,7 +622,10 @@ fn build_wasm_pure( Ok(()) } -fn ensure_real_directory_path(root: &Path, directory: &Path) -> Result<(), Box> { +pub(crate) fn ensure_real_directory_path( + root: &Path, + directory: &Path, +) -> Result<(), Box> { let relative = directory.strip_prefix(root).map_err(|_| { format!( "generated directory `{}` escapes project `{}`", @@ -721,12 +728,14 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: directory.join("src/lib.rs"), kind: vec!["lib".to_string()], }], } }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: root.to_path_buf(), packages: vec![ package("pure", "pure"), @@ -769,6 +778,7 @@ mod tests { fs::write(package_dir.join("lib.rs"), "mod sibling;\n").unwrap(); fs::write(package_dir.join("sibling.rs"), "pub const VALUE: u8 = 1;\n").unwrap(); let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: workspace.to_path_buf(), packages: vec![CargoPackage { id: "pure".to_string(), @@ -777,6 +787,7 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: package_dir.join("lib.rs"), kind: vec!["lib".to_string()], }], @@ -816,12 +827,14 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: directory.join("src/lib.rs"), kind: vec![kind.to_string()], }], } }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: root.to_path_buf(), packages: vec![ package("pure", "cdylib"), @@ -866,6 +879,7 @@ mod tests { targets: Vec::new(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![package], resolve: None, @@ -885,6 +899,7 @@ mod tests { import: "domain/pkg/domain_wasm".to_string(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![CargoPackage { id: "registry+https://example.invalid#domain@0.1.0".to_string(), @@ -919,6 +934,7 @@ mod tests { targets: Vec::new(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![package("domain-one"), package("domain-two")], resolve: None, diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs index 0a7c9fe62..68c6901f2 100644 --- a/distributed_cli/tests/cli_game_client.rs +++ b/distributed_cli/tests/cli_game_client.rs @@ -46,6 +46,7 @@ fn generated_typescript_matches_the_golden_files() { "events.ts", "index.ts", "input.ts", + "predict.ts", "schema.ts", "surface.json" ] @@ -178,8 +179,10 @@ fn game_manifest_runs_the_surface_export() { ); let surface: serde_json::Value = serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); - assert_eq!(surface["schemaVersion"], 1); + assert_eq!(surface["schemaVersion"], 2); assert_eq!(surface["name"], "orbs"); + assert_eq!(surface["predict"]["export"], "orb_step"); + assert_eq!(surface["predict"]["package"], "game-surface-fixture"); assert_eq!( surface["kinds"][0]["fields"][0]["correction"]["durationMs"], 80 @@ -202,4 +205,60 @@ fn game_manifest_runs_the_surface_export() { assert!(fs::read_to_string(gen.join("client.ts")) .unwrap() .contains("createOrbsClient")); + + // The predicted step compiles to a self-contained module next to the + // client; a second run is a stamp hit, and --check verifies it. + let wasm = |extra: &[&str]| { + let mut args = vec![ + "game-wasm", + "--manifest", + out.to_str().unwrap(), + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + gen.to_str().unwrap(), + ]; + args.extend(extra); + distributed(&args) + }; + let check = wasm(&["--check"]); + assert!(!check.status.success(), "nothing built yet"); + let build = wasm(&[]); + assert!( + build.status.success(), + "{}", + String::from_utf8_lossy(&build.stderr) + ); + let module = fs::read(gen.join("wasm/orbs.wasm")).unwrap(); + assert_eq!(&module[..4], b"\0asm"); + let again = wasm(&[]); + assert!(String::from_utf8_lossy(&again.stdout).contains("is current")); + assert!(wasm(&["--check"]).status.success()); + fs::write(gen.join("wasm/orbs.wasm"), b"tampered").unwrap(); + assert!( + !wasm(&["--check"]).status.success(), + "a changed module is stale" + ); +} + +#[test] +fn game_wasm_needs_a_predicted_step() { + let tmp = tempfile::tempdir().unwrap(); + let mut surface: serde_json::Value = serde_json::from_str(&sample_surface()).unwrap(); + surface.as_object_mut().unwrap().remove("predict"); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, surface.to_string()).unwrap(); + let run = distributed(&[ + "game-wasm", + "--manifest", + manifest.to_str().unwrap(), + "--out", + tmp.path().join("gen").to_str().unwrap(), + ]); + assert!(!run.status.success()); + assert!( + String::from_utf8_lossy(&run.stderr).contains("declares no predicted step"), + "{}", + String::from_utf8_lossy(&run.stderr) + ); } diff --git a/distributed_cli/tests/fixtures/game-client/sample/client.ts b/distributed_cli/tests/fixtures/game-client/sample/client.ts index 81f139f22..5c63bfe3a 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/client.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type SampleInput } from './input.ts'; +import { createSamplePrediction, type SamplePrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type SamplePredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type SamplePredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type SampleClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: SamplePredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: SamplePredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type SampleClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: SamplePrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: SampleInput): number | undefined; }>; -/** A `GameClient` for the `sample` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `sample` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createSampleClient(options: SampleClientOptions): SampleClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createSamplePrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/distributed_cli/tests/fixtures/game-client/sample/events.ts b/distributed_cli/tests/fixtures/game-client/sample/events.ts index 89260ef91..24779185d 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/events.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/events.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; @@ -37,6 +37,20 @@ const BOARD_TYPE: WireType = { ] }; +/** Record `SampleState` (`#[derive(GameRecord)]`). */ +export interface SampleState { + readonly x: number; + readonly vx: number; + readonly hp: number; + readonly dead: boolean; +} + +/** Record `SampleWind` (`#[derive(GameRecord)]`). */ +export interface SampleWind { + readonly speed: number; + readonly gusts: number; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly entity: number; diff --git a/distributed_cli/tests/fixtures/game-client/sample/index.ts b/distributed_cli/tests/fixtures/game-client/sample/index.ts index 87034da95..e268d7c32 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/index.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/input.ts b/distributed_cli/tests/fixtures/game-client/sample/input.ts index 5a836a29b..99ed90947 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/input.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/predict.ts b/distributed_cli/tests/fixtures/game-client/sample/predict.ts new file mode 100644 index 000000000..63a841928 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/predict.ts @@ -0,0 +1,53 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +import type { SampleWind } from './events.ts'; +import { encodeInput, type SampleInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `sample_step` of Cargo package `distributed_game`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'sample_step', + package: 'distributed_game', + state: 'SampleState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `SampleState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['hp', { type: 'u8' }], + ['dead', { type: 'bool' }], +]; + +/** What the step reads besides state and input (`prediction.setContext`). */ +export type PredictContext = SampleWind; + +/** Layout of the context record `SampleWind`. */ +export const PREDICT_CONTEXT: PayloadLayout | undefined = [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], +]; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/sample.wasm', import.meta.url); + +/** The `sample` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type SamplePrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves and a context is set. + */ +export function createSamplePrediction(source: WasmSource = PREDICT_WASM_URL): SamplePrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/schema.ts b/distributed_cli/tests/fixtures/game-client/sample/schema.ts index 66b1efcc2..19212f5e9 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/schema.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldBytes, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/surface.json b/distributed_cli/tests/fixtures/game-client/sample/surface.json index 63dab5de2..189e39e7c 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/surface.json +++ b/distributed_cli/tests/fixtures/game-client/sample/surface.json @@ -374,6 +374,14 @@ } ], "name": "sample", + "predict": { + "abi": 1, + "context": "SampleWind", + "export": "sample_step", + "kind": "player", + "package": "distributed_game", + "state": "SampleState" + }, "protocolVersion": 1, "records": [ { @@ -434,7 +442,53 @@ } ], "name": "Row" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "hp", + "type": { + "type": "u8" + } + }, + { + "name": "dead", + "type": { + "type": "bool" + } + } + ], + "name": "SampleState" + }, + { + "fields": [ + { + "name": "speed", + "type": { + "type": "f32" + } + }, + { + "name": "gusts", + "type": { + "type": "u16" + } + } + ], + "name": "SampleWind" } ], - "schemaVersion": 1 + "schemaVersion": 2 } diff --git a/distributed_cli/tests/fixtures/game-surface/src/lib.rs b/distributed_cli/tests/fixtures/game-surface/src/lib.rs index a609ee6c0..ad8c0b48e 100644 --- a/distributed_cli/tests/fixtures/game-surface/src/lib.rs +++ b/distributed_cli/tests/fixtures/game-surface/src/lib.rs @@ -1,8 +1,8 @@ //! A minimal zone surface for `distributed game-manifest` tests. use distributed_game::{ - schema, Ctx, EntitySchema, GameEvent, GameInput, GameSurface, PlayerId, Replicated, WorldView, - Zone, + predict, schema, Ctx, EntitySchema, GameEvent, GameInput, GameRecord, GameSurface, PlayerId, + Replicated, WorldView, Zone, }; #[derive(Replicated)] @@ -30,6 +30,20 @@ pub enum OrbEvent { Hello { entity: u32 }, } +/// The predicted part of an orb. +#[derive(Clone, Copy, GameRecord)] +pub struct OrbState { + pub x: f32, +} + +/// The client-predicted step (compiled to WASM by `distributed game-wasm`). +#[predict(OrbStep, kind = "orb")] +pub fn orb_step(state: &OrbState, input: &Steer, _context: &(), dt: f32) -> OrbState { + OrbState { + x: state.x + f32::from(input.turn) * dt, + } +} + pub struct Orbs; impl Zone for Orbs { @@ -58,5 +72,7 @@ impl Zone for Orbs { /// The export `distributed game-manifest` runs by default. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("orbs").events::() + GameSurface::for_zone::("orbs") + .events::() + .predict::() } diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 230937347..bb059c835 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -24,6 +24,10 @@ //! ([`Ctx::emit`]). The derives also describe the zone's //! [`GameSurface`](surface::GameSurface), from which `distributed //! game-client` generates typed TypeScript. +//! - Client prediction ([`prediction`]): `#[predict]` declares a zone's +//! predicted step once in Rust; `distributed game-wasm` compiles it to +//! WebAssembly (binary ABI, no JSON) and the generated client predicts +//! with it. //! //! Physics is out of scope: games bring their own and run it in `on_tick`. //! @@ -57,6 +61,7 @@ pub mod interest; pub mod metrics; #[cfg(feature = "net")] pub mod net; +pub mod prediction; pub mod protocol; pub mod replay; pub mod replication; @@ -74,7 +79,9 @@ pub use authoring::{GameEvent, GameInput, Pushed, Replicated}; pub use clock::{Clock, ManualClock, SystemClock}; pub use codec::{Wire, WireType}; /// Authoring derives (see the crate docs and README). -pub use distributed_game_macros::{FactCommand, GameEvent, GameInput, GameRecord, Replicated}; +pub use distributed_game_macros::{ + predict, FactCommand, GameEvent, GameInput, GameRecord, Replicated, +}; #[cfg(feature = "runtime")] pub use facts::spawn_fact_worker; pub use facts::{ @@ -86,6 +93,7 @@ pub use handoff::{HandoffError, HandoffRequest, Transfer}; pub use host::{AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, ZoneHost}; pub use input::{ConsumePolicy, InputBuffer, InputCredits, PushOutcome, SequencedInput}; pub use interest::{InterestConfig, View}; +pub use prediction::{PredictContext, PredictStep}; pub use protocol::{ClientMessage, ClientMirror, Role, ServerMessage, PROTOCOL_VERSION}; pub use replay::{replay, Recorder, Recording}; pub use replication::{EntityState, WorldView}; @@ -109,6 +117,8 @@ pub mod __private { pub use crate::codec::{ special, ButtonBits, EntityField, InputField, LongString, QuantizedF32, Wire, WireType, }; + #[cfg(target_arch = "wasm32")] + pub use crate::prediction::wasm_export; pub use crate::protocol::wire::{DecodeError, Reader, Writer}; pub use crate::schema::{Correction, FieldType, FieldValue, KindDef}; pub use crate::surface::{ diff --git a/distributed_game/src/prediction.rs b/distributed_game/src/prediction.rs new file mode 100644 index 000000000..6bd3d50be --- /dev/null +++ b/distributed_game/src/prediction.rs @@ -0,0 +1,351 @@ +//! Client prediction steps, declared once in Rust and compiled to +//! WebAssembly for the browser. +//! +//! A zone's **predicted step** is a pure function `(state, input, context, +//! dt) -> state` over the locally controlled entity. The server runs it in +//! `on_tick` (directly or through the code it wraps); the browser runs the +//! *same* function compiled to `wasm32-unknown-unknown`, so client prediction +//! cannot drift from the simulation. Declare it with the `#[predict]` +//! attribute: +//! +//! ```ignore +//! /// What a client predicts for its own `player` entity. +//! #[predict(ArenaStep, kind = "player")] +//! pub fn arena_step(state: &MoveState, input: &MoveInput, _: &(), _dt: f32) -> MoveState { +//! movement::step(*state, *input) +//! } +//! +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("arena").predict::() +//! } +//! ``` +//! +//! - `State` is a `#[derive(GameRecord)]` struct whose fields are named after +//! fields of the predicted kind (`x`, `vx`, `cd`, …) and use their plain +//! scalar types (`f32` for a quantized field). The client rebases on the +//! authoritative copy of those fields. +//! - `Input` is the zone's `#[derive(GameInput)]` type; the WASM side decodes +//! it with `from_payload`, so it sees exactly what the server simulates +//! (ranges clamped, unknown buttons cleared). +//! - `Context` is `()` or a `#[derive(GameRecord)]` struct the client sets +//! (`prediction.setContext(..)`), e.g. the world seed and cell a step +//! collides against. +//! - `dt` is the input's frame length in seconds as the client sent it. +//! Prefer fixed command frames (one input = one tick) and ignore it. +//! +//! # Binary ABI +//! +//! The attribute emits, on `wasm32` only, one export per step: +//! `dg_predict_(state_len, input_len, context_len, dt) -> i32`. The +//! module also exports `dg_predict_buffer() -> *mut u8` (a +//! [`SCRATCH_BYTES`] scratch area), `dg_predict_abi() -> u32` +//! ([`ABI_VERSION`]) and its memory, and imports nothing. The caller writes +//! `state ‖ input ‖ context` (codec encodings: `state` and `context` with +//! [`Wire`], `input` as its payload) into the buffer and calls the step; a +//! non-negative result is the length of the next state, written at the +//! start of the buffer; negative values are [`AbiError`] codes. No allocation +//! crosses the boundary and nothing is JSON: floats stay binary32. +//! +//! # Determinism +//! +//! Native and WASM results are bit-identical when the step uses only +//! IEEE-754 operations that are correctly rounded on both targets: `+ - * /`, +//! `sqrt`, `abs`, `min`/`max`, `floor`/`ceil`/`trunc`/`round`, comparisons +//! and integer arithmetic. Rust never contracts `a * b + c` into an FMA on +//! its own. **Transcendentals are not portable**: `sin`, `cos`, `atan2`, +//! `exp`, `ln`, `powf` call the platform's libm natively and a different +//! implementation on `wasm32`, which may round differently. Use a +//! deterministic implementation on both sides (the `libm` crate, or a +//! polynomial in plain arithmetic) for anything the step computes with them. +//! NaN payloads may differ, so a step must not produce NaN. + +use crate::authoring::GameInput; +use crate::codec::{Wire, WireType}; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::surface::RecordSurface; + +/// Version of the binary ABI exported as `dg_predict_abi`. +pub const ABI_VERSION: u32 = 1; + +/// Size of the scratch buffer behind `dg_predict_buffer` (state, input and +/// context together; the next state is written back into it). +pub const SCRATCH_BYTES: usize = 64 * 1024; + +/// A zone's client-predicted step (see the module docs). Implemented by the +/// `#[predict]` attribute; implement it by hand only when the attribute +/// does not fit (and then also export the step, see [`run_abi`]). +pub trait PredictStep { + /// Name of the predicted kind (the controlled entity's kind). + const KIND: &'static str; + /// Cargo package that declares the step (`env!("CARGO_PKG_NAME")`); the + /// CLI compiles this package to WebAssembly. + const PACKAGE: &'static str; + /// Export suffix: the step is `dg_predict_` in the module. + const EXPORT: &'static str; + /// Predicted fields of the kind (a `#[derive(GameRecord)]` struct). + type State: Wire; + /// The zone's input frame. + type Input: GameInput; + /// Read-only data the client provides (`()` for none). + type Context: PredictContext; + + /// Advance one input frame. + fn step( + state: &Self::State, + input: &Self::Input, + context: &Self::Context, + dt: f32, + ) -> Self::State; +} + +/// The context type of a [`PredictStep`]: `()` (nothing) or any record. +pub trait PredictContext: Sized { + /// Wire type, or `None` for `()`. + fn context_type() -> Option; + /// Push the records it mentions. + fn context_records(out: &mut Vec); + /// Decode a whole context. + fn decode_context(bytes: &[u8]) -> Result; + /// Encode (native tools and tests). + fn encode_context(&self) -> Vec; +} + +impl PredictContext for () { + fn context_type() -> Option { + None + } + fn context_records(_out: &mut Vec) {} + fn decode_context(bytes: &[u8]) -> Result { + if bytes.is_empty() { + Ok(()) + } else { + Err(DecodeError::Invalid("this step takes no context")) + } + } + fn encode_context(&self) -> Vec { + Vec::new() + } +} + +impl PredictContext for T { + fn context_type() -> Option { + Some(T::wire_type()) + } + fn context_records(out: &mut Vec) { + T::records(out); + } + fn decode_context(bytes: &[u8]) -> Result { + crate::codec::from_bytes(bytes) + } + fn encode_context(&self) -> Vec { + crate::codec::to_bytes(self) + } +} + +/// Negative results of a step export. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum AbiError { + /// The lengths exceed the scratch buffer. + TooLarge = -1, + /// The state bytes do not decode. + State = -2, + /// The input payload does not decode or is rejected by sanitize. + Input = -3, + /// The context bytes do not decode. + Context = -4, + /// The next state does not fit the scratch buffer. + Output = -5, +} + +/// One step over encoded bytes: what the WASM export does, callable +/// natively (tools, tests). Returns the encoded next state. +pub fn step_bytes( + state: &[u8], + input: &[u8], + context: &[u8], + dt: f32, +) -> Result, AbiError> { + let state = crate::codec::from_bytes::(state).map_err(|_| AbiError::State)?; + let input = P::Input::from_payload(input).ok_or(AbiError::Input)?; + let context = P::Context::decode_context(context).map_err(|_| AbiError::Context)?; + let next = P::step(&state, &input, &context, dt); + let mut w = Writer::new(); + next.encode(&mut w); + Ok(w.into_bytes()) +} + +/// The ABI over a buffer laid out as `state ‖ input ‖ context`: decodes, +/// steps and writes the next state at the start of `buffer`. Returns its +/// length or a negative [`AbiError`] code. The WASM exports call this on +/// the scratch buffer. +pub fn run_abi( + buffer: &mut [u8], + state_len: u32, + input_len: u32, + context_len: u32, + dt: f32, +) -> i32 { + let (s, i, c) = (state_len as usize, input_len as usize, context_len as usize); + let Some(total) = s.checked_add(i).and_then(|n| n.checked_add(c)) else { + return AbiError::TooLarge as i32; + }; + if total > buffer.len() { + return AbiError::TooLarge as i32; + } + let next = match step_bytes::

    (&buffer[..s], &buffer[s..s + i], &buffer[s + i..total], dt) { + Ok(next) => next, + Err(error) => return error as i32, + }; + if next.len() > buffer.len() { + return AbiError::Output as i32; + } + buffer[..next.len()].copy_from_slice(&next); + next.len() as i32 +} + +/// Decode a state (native tools and tests). +pub fn decode_state(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let state = P::State::decode(&mut r)?; + r.finish()?; + Ok(state) +} + +#[cfg(target_arch = "wasm32")] +mod wasm { + use std::cell::UnsafeCell; + + struct Scratch(UnsafeCell<[u8; super::SCRATCH_BYTES]>); + // wasm32-unknown-unknown without atomics is single-threaded. + unsafe impl Sync for Scratch {} + + static SCRATCH: Scratch = Scratch(UnsafeCell::new([0; super::SCRATCH_BYTES])); + + /// Address of the scratch buffer (`state ‖ input ‖ context` in, next state out). + #[unsafe(no_mangle)] + pub extern "C" fn dg_predict_buffer() -> *mut u8 { + SCRATCH.0.get().cast() + } + + /// [`super::ABI_VERSION`]. + #[unsafe(no_mangle)] + pub extern "C" fn dg_predict_abi() -> u32 { + super::ABI_VERSION + } + + /// The scratch buffer (generated step exports). + pub fn scratch() -> &'static mut [u8] { + // SAFETY: single-threaded; each export call borrows it once and + // returns before the next call. + unsafe { &mut *SCRATCH.0.get() } + } +} + +/// Body of a generated step export (`#[predict]`, `wasm32` only). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub fn wasm_export( + state_len: u32, + input_len: u32, + context_len: u32, + dt: f32, +) -> i32 { + run_abi::

    (wasm::scratch(), state_len, input_len, context_len, dt) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GameInput, GameRecord}; + + #[derive(Debug, Clone, Copy, PartialEq, GameRecord)] + struct Dot { + x: f32, + n: u8, + } + + #[derive(Debug, Clone, Copy, PartialEq, GameInput)] + struct Push { + #[range(min = -1, max = 1)] + dx: i8, + } + + #[derive(Debug, Clone, PartialEq, GameRecord)] + struct Wind { + speed: f32, + } + + struct DotStep; + impl PredictStep for DotStep { + const KIND: &'static str = "dot"; + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "dot"; + type State = Dot; + type Input = Push; + type Context = Wind; + fn step(state: &Dot, input: &Push, context: &Wind, dt: f32) -> Dot { + Dot { + x: state.x + f32::from(input.dx) * context.speed * dt, + n: state.n.wrapping_add(1), + } + } + } + + #[test] + fn abi_steps_in_place_and_sanitizes_input() { + let state = crate::codec::to_bytes(&Dot { x: 1.5, n: 7 }); + let context = Wind { speed: 2.0 }.encode_context(); + let mut buffer = vec![0u8; 64]; + let mut at = 0; + for part in [&state[..], &[5u8][..], &context[..]] { + buffer[at..at + part.len()].copy_from_slice(part); + at += part.len(); + } + let n = run_abi::( + &mut buffer, + state.len() as u32, + 1, + context.len() as u32, + 0.5, + ); + assert!(n > 0); + // dx = 5 is clamped to 1, as the server would. + assert_eq!( + decode_state::(&buffer[..n as usize]).unwrap(), + Dot { x: 2.5, n: 8 } + ); + } + + #[test] + fn abi_reports_errors() { + let mut buffer = vec![0u8; 8]; + assert_eq!( + run_abi::(&mut buffer, 6, 3, 0, 0.0), + AbiError::TooLarge as i32 + ); + assert_eq!( + run_abi::(&mut buffer, 1, 1, 4, 0.0), + AbiError::State as i32 + ); + assert_eq!( + step_bytes::( + &crate::codec::to_bytes(&Dot { x: 0.0, n: 0 }), + &[], + &[0; 4], + 0.0 + ), + Err(AbiError::Input) + ); + assert_eq!( + step_bytes::( + &crate::codec::to_bytes(&Dot { x: 0.0, n: 0 }), + &[0], + &[0; 3], + 0.0 + ), + Err(AbiError::Context) + ); + assert!(<() as PredictContext>::decode_context(&[1]).is_err()); + } +} diff --git a/distributed_game/src/surface.rs b/distributed_game/src/surface.rs index d51802cf3..3d0911e12 100644 --- a/distributed_game/src/surface.rs +++ b/distributed_game/src/surface.rs @@ -21,12 +21,13 @@ use serde::{Deserialize, Serialize}; use crate::codec::WireType; +use crate::prediction::{PredictContext, PredictStep}; use crate::protocol::PROTOCOL_VERSION; use crate::schema::{Correction, EntitySchema}; -use crate::{GameEvent, GameInput, Zone}; +use crate::{GameEvent, GameInput, Wire, Zone}; /// Version of the [`GameSurface`] JSON shape. -pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 1; +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 2; /// One zone type's client-facing surface. See the module docs. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -44,8 +45,31 @@ pub struct GameSurface { pub input: Option, /// Events by id. pub events: Vec, - /// Records mentioned by inputs or events, by name. + /// Records mentioned by inputs, events or the predicted step, by name. pub records: Vec, + /// The client-predicted step, compiled to WebAssembly (see + /// [`crate::prediction`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub predict: Option, +} + +/// The zone's client-predicted step ([`crate::prediction::PredictStep`]). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PredictSurface { + /// Predicted kind (the controlled entity's kind). + pub kind: String, + /// Cargo package declaring the step (compiled to WebAssembly). + pub package: String, + /// Export suffix: the module exports `dg_predict_`. + pub export: String, + /// State record (fields named after the kind's fields). + pub state: String, + /// Context record, if the step takes one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, + /// Binary ABI version ([`crate::prediction::ABI_VERSION`]). + pub abi: u32, } /// One replicated kind. @@ -167,6 +191,7 @@ impl GameSurface { input: None, events: Vec::new(), records: Vec::new(), + predict: None, } } @@ -236,6 +261,74 @@ impl GameSurface { self } + /// Declare the zone's client-predicted step (`#[predict]`). Checks that + /// it predicts a kind of this surface, takes the surface's input, and + /// that every state field names a field of the kind with a matching + /// scalar type; panics otherwise (surface export time). + pub fn predict(mut self) -> Self { + let mut records = Vec::new(); + let input = P::Input::input_surface(&mut records); + assert_eq!( + self.input.as_ref(), + Some(&input), + "predicted step {} of game surface {} must take the zone's input type", + P::EXPORT, + self.name + ); + let kind = self + .kinds + .iter() + .find(|k| k.name == P::KIND) + .unwrap_or_else(|| { + panic!( + "predicted step {} names kind {:?}, which game surface {} does not replicate", + P::EXPORT, + P::KIND, + self.name + ) + }) + .clone(); + let state = record_name(P::State::wire_type(), "state", P::EXPORT); + P::State::records(&mut records); + let state_record = records + .iter() + .find(|r| r.name == state) + .expect("a record pushes its own definition") + .clone(); + for field in &state_record.fields { + let entity = kind + .fields + .iter() + .find(|f| f.name == field.name) + .unwrap_or_else(|| { + panic!( + "predicted state {state} field {} is not a field of kind {}", + field.name, kind.name + ) + }); + assert!( + state_field_matches(&field.ty, &entity.ty), + "predicted state {state} field {} ({:?}) does not match kind {} field type {:?}", + field.name, + field.ty, + kind.name, + entity.ty + ); + } + let context = P::Context::context_type().map(|ty| record_name(ty, "context", P::EXPORT)); + P::Context::context_records(&mut records); + self.predict = Some(PredictSurface { + kind: P::KIND.to_string(), + package: P::PACKAGE.to_string(), + export: P::EXPORT.to_string(), + state, + context, + abi: crate::prediction::ABI_VERSION, + }); + self.add_records(records); + self + } + fn add_records(&mut self, records: Vec) { for record in records { match self.records.iter().find(|r| r.name == record.name) { @@ -256,3 +349,28 @@ impl GameSurface { serde_json::to_string_pretty(self).expect("game surface serializes") } } + +fn record_name(ty: WireType, what: &str, export: &str) -> String { + match ty { + WireType::Record { name } => name, + other => panic!( + "predicted step {export}: the {what} must be a #[derive(GameRecord)] struct, not {other:?}" + ), + } +} + +/// A state field holds the plain value of an entity field: `f32` for float +/// fields (quantized or not, the step works on full binary32), the same +/// integer / bool type otherwise. +fn state_field_matches(state: &WireType, entity: &WireType) -> bool { + match state { + WireType::F32 => matches!( + entity, + WireType::F32 | WireType::Quant { .. } | WireType::Angle { .. } + ), + WireType::Bool | WireType::U8 | WireType::U16 | WireType::U32 | WireType::I32 => { + state == entity + } + _ => false, + } +} diff --git a/distributed_game/tests/authoring/main.rs b/distributed_game/tests/authoring/main.rs index b354c6d98..bdfe15e3c 100644 --- a/distributed_game/tests/authoring/main.rs +++ b/distributed_game/tests/authoring/main.rs @@ -14,10 +14,10 @@ use std::time::Duration; use distributed_game::protocol::{Reader, Writer}; use distributed_game::surface::{EventPayload, GameSurface}; use distributed_game::{ - fact_channel, schema, Correction, Ctx, EntitySchema, FactCommand, FactOutcome, FactSettlement, - FieldType, FieldValue, GameEvent, GameInput, GameRecord, HostConfig, ManualClock, - MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, Wire, WireType, - WorldView, Zone, ZoneHost, + fact_channel, predict, schema, Correction, Ctx, EntitySchema, FactCommand, FactOutcome, + FactSettlement, FieldType, FieldValue, GameEvent, GameInput, GameRecord, HostConfig, + ManualClock, MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, Wire, + WireType, WorldView, Zone, ZoneHost, }; use serde::Serialize; use serde_json::{json, Value}; @@ -150,10 +150,46 @@ pub struct TickNote { pub note: String, } +/// The predicted part of a `player` (fields named after the kind's). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct SampleState { + pub x: f32, + pub vx: f32, + pub hp: u8, + pub dead: bool, +} + +/// What a client tells the step. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct SampleWind { + pub speed: f32, + pub gusts: u16, +} + +/// The sample's client-predicted step. +#[predict(SampleStep, kind = "player")] +pub fn sample_step( + state: &SampleState, + input: &SampleInput, + wind: &SampleWind, + dt: f32, +) -> SampleState { + if state.dead { + return *state; + } + let vx = f32::from(input.mx) / 127.0 * wind.speed; + SampleState { + x: state.x + vx * dt, + vx, + ..*state + } +} + pub fn sample_surface() -> GameSurface { GameSurface::for_zone::("sample") .events::() .events::() + .predict::() } // ---- a zone using all of it ---------------------------------------------- @@ -419,7 +455,7 @@ fn records_round_trip_through_the_value_codec() { #[test] fn surface_describes_everything_once() { let surface = sample_surface(); - assert_eq!(surface.schema_version, 1); + assert_eq!(surface.schema_version, 2); assert_eq!(surface.kinds.len(), 3); assert_eq!( surface.kinds[0].fields[0].correction, @@ -453,7 +489,7 @@ fn surface_describes_everything_once() { } ); let records: Vec<_> = surface.records.iter().map(|r| r.name.as_str()).collect(); - assert_eq!(records, ["Board", "Row"]); + assert_eq!(records, ["Board", "Row", "SampleState", "SampleWind"]); // JSON round trip (the CLI reads this shape). let json = surface.to_json(); let back: GameSurface = serde_json::from_str(&json).unwrap(); @@ -688,3 +724,115 @@ fn golden_fixture_is_current() { "run with UPDATE_GOLDEN=1 to regenerate {path}" ); } + +// ---- predicted step --------------------------------------------------------- + +#[test] +fn the_predicted_step_is_declared_in_the_surface() { + use distributed_game::prediction::{step_bytes, PredictContext, PredictStep}; + let surface = sample_surface(); + let predict = surface.predict.as_ref().expect("predicted step"); + assert_eq!(predict.kind, "player"); + assert_eq!(predict.export, "sample_step"); + assert_eq!(predict.package, "distributed_game"); + assert_eq!(predict.state, "SampleState"); + assert_eq!(predict.context.as_deref(), Some("SampleWind")); + assert_eq!(predict.abi, distributed_game::prediction::ABI_VERSION); + for record in ["SampleState", "SampleWind"] { + assert!(surface.records.iter().any(|r| r.name == record), "{record}"); + } + assert_eq!(::KIND, "player"); + + // The ABI path: encoded state, input payload (sanitized) and context. + let state = SampleState { + x: 1.0, + vx: 0.0, + hp: 9, + dead: false, + }; + let input = SampleInput { + mx: -128, + my: 0, + buttons: 0, + aim: 0.0, + power: 0.0, + view_tick: 0, + }; + let wind = SampleWind { + speed: 2.0, + gusts: 3, + }; + let next = step_bytes::( + &distributed_game::codec::to_bytes(&state), + &input.to_payload(), + &wind.encode_context(), + 0.5, + ) + .unwrap(); + let next: SampleState = distributed_game::codec::from_bytes(&next).unwrap(); + // -128 is clamped to -127 before the step, as on the server. + assert_eq!( + next, + sample_step(&state, &input.sanitize().unwrap(), &wind, 0.5) + ); + assert_eq!((next.x, next.vx, next.hp), (0.0, -2.0, 9)); +} + +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct NotAField { + pub mana: f32, +} + +#[predict(UnknownFieldStep, kind = "player")] +pub fn unknown_field_step(state: &NotAField, _: &SampleInput, _: &(), _: f32) -> NotAField { + *state +} + +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct WrongType { + pub hp: f32, +} + +#[predict(WrongTypeStep, kind = "player")] +pub fn wrong_type_step(state: &WrongType, _: &SampleInput, _: &(), _: f32) -> WrongType { + *state +} + +#[predict(UnknownKindStep, kind = "ghost")] +pub fn unknown_kind_step(state: &SampleState, _: &SampleInput, _: &(), _: f32) -> SampleState { + *state +} + +#[predict(OtherInputStep, kind = "player")] +pub fn other_input_step(state: &SampleState, _: &Ping2, _: &(), _: f32) -> SampleState { + *state +} + +#[derive(Debug, Clone, Copy, PartialEq, GameInput)] +pub struct Ping2 { + pub n: u8, +} + +#[test] +#[should_panic(expected = "field mana is not a field of kind player")] +fn a_state_field_must_name_a_kind_field() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "does not match kind player field type")] +fn a_state_field_must_have_the_kind_field_type() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "names kind \"ghost\"")] +fn the_predicted_kind_must_be_replicated() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "must take the zone's input type")] +fn the_step_takes_the_zone_input() { + let _ = GameSurface::for_zone::("sample").predict::(); +} diff --git a/distributed_game/tests/fixtures/authoring.json b/distributed_game/tests/fixtures/authoring.json index de7cc6e67..172c4a84c 100644 --- a/distributed_game/tests/fixtures/authoring.json +++ b/distributed_game/tests/fixtures/authoring.json @@ -478,6 +478,14 @@ } ], "name": "sample", + "predict": { + "abi": 1, + "context": "SampleWind", + "export": "sample_step", + "kind": "player", + "package": "distributed_game", + "state": "SampleState" + }, "protocolVersion": 1, "records": [ { @@ -538,8 +546,54 @@ } ], "name": "Row" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "hp", + "type": { + "type": "u8" + } + }, + { + "name": "dead", + "type": { + "type": "bool" + } + } + ], + "name": "SampleState" + }, + { + "fields": [ + { + "name": "speed", + "type": { + "type": "f32" + } + }, + { + "name": "gusts", + "type": { + "type": "u16" + } + } + ], + "name": "SampleWind" } ], - "schemaVersion": 1 + "schemaVersion": 2 } } diff --git a/distributed_game_macros/src/lib.rs b/distributed_game_macros/src/lib.rs index 0a85fcd33..59ca7018b 100644 --- a/distributed_game_macros/src/lib.rs +++ b/distributed_game_macros/src/lib.rs @@ -9,6 +9,7 @@ //! | [`GameEvent`] | struct / enum | `GameEvent`: stable ids, typed payload codec | //! | [`GameRecord`] | struct | `Wire`: a nested payload record | //! | [`FactCommand`] | struct | `FactCommand`: the cell command name of a fact input | +//! | [`macro@predict`] (attribute) | fn | `PredictStep` for a client-predicted step + its WebAssembly export | //! //! Field attributes (where they apply): //! @@ -25,11 +26,12 @@ mod event; mod fact; mod input; +mod predict; mod replicated; mod shared; use proc_macro::TokenStream; -use syn::{parse_macro_input, DeriveInput}; +use syn::{parse_macro_input, DeriveInput, ItemFn}; fn finish(result: syn::Result) -> TokenStream { result.unwrap_or_else(|e| e.to_compile_error()).into() @@ -83,3 +85,19 @@ pub fn derive_game_record(input: TokenStream) -> TokenStream { pub fn derive_fact_command(input: TokenStream) -> TokenStream { finish(fact::expand(parse_macro_input!(input as DeriveInput))) } + +/// Declare a zone's client-predicted step: +/// `#[predict(ArenaStep, kind = "player")]` on +/// `fn(state: &State, input: &Input, context: &Context, dt: f32) -> State`. +/// +/// Keeps the function and adds `struct ArenaStep` implementing +/// `distributed_game::prediction::PredictStep` (name it in +/// `GameSurface::predict::()`). On `wasm32` it also exports the +/// step as `dg_predict_` over the binary ABI described in +/// `distributed_game::prediction`. +#[proc_macro_attribute] +pub fn predict(args: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(args as predict::Args); + let function = parse_macro_input!(item as ItemFn); + finish(predict::expand(args, function)) +} diff --git a/distributed_game_macros/src/predict.rs b/distributed_game_macros/src/predict.rs new file mode 100644 index 000000000..a97937e53 --- /dev/null +++ b/distributed_game_macros/src/predict.rs @@ -0,0 +1,158 @@ +//! `#[predict(StepType, kind = "player")]` on a step function +//! `fn(state: &S, input: &I, context: &C, dt: f32) -> S`. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{FnArg, Ident, ItemFn, LitStr, Pat, ReturnType, Token, Type}; + +use crate::shared::runtime; + +pub(crate) struct Args { + step: Ident, + kind: LitStr, +} + +impl Parse for Args { + fn parse(input: ParseStream<'_>) -> syn::Result { + let step: Ident = input.parse().map_err(|e| { + syn::Error::new( + e.span(), + "expected `#[predict(StepType, kind = \"kind_name\")]`", + ) + })?; + let mut kind = None; + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let key: Ident = input.parse()?; + input.parse::()?; + match key.to_string().as_str() { + "kind" => kind = Some(input.parse::()?), + other => { + return Err(syn::Error::new( + key.span(), + format!("unknown `#[predict]` option `{other}` (expected `kind`)"), + )) + } + } + } + let kind = kind.ok_or_else(|| { + syn::Error::new( + step.span(), + "`#[predict]` needs the predicted kind: `kind = \"player\"`", + ) + })?; + if kind.value().is_empty() { + return Err(syn::Error::new(kind.span(), "kind must not be empty")); + } + Ok(Self { step, kind }) + } +} + +fn referenced(arg: &FnArg, what: &str) -> syn::Result { + let FnArg::Typed(typed) = arg else { + return Err(syn::Error::new( + arg.span(), + "a predicted step is a free function, not a method", + )); + }; + if !matches!(&*typed.pat, Pat::Ident(_) | Pat::Wild(_)) { + return Err(syn::Error::new( + typed.pat.span(), + "use a plain binding for step arguments", + )); + } + match &*typed.ty { + Type::Reference(reference) if reference.mutability.is_none() => { + Ok((*reference.elem).clone()) + } + other => Err(syn::Error::new( + other.span(), + format!("the {what} argument must be a shared reference (`&T`)"), + )), + } +} + +pub(crate) fn expand(args: Args, function: ItemFn) -> syn::Result { + let root = runtime()?; + let sig = &function.sig; + if !sig.generics.params.is_empty() || sig.asyncness.is_some() || sig.unsafety.is_some() { + return Err(syn::Error::new( + sig.span(), + "a predicted step must be a plain, non-generic, synchronous fn", + )); + } + let inputs: Vec<&FnArg> = sig.inputs.iter().collect(); + let [state_arg, input_arg, context_arg, dt_arg] = inputs.as_slice() else { + return Err(syn::Error::new( + sig.inputs.span(), + "a predicted step takes `(state: &State, input: &Input, context: &Context, dt: f32)`", + )); + }; + let state = referenced(state_arg, "state")?; + let input = referenced(input_arg, "input")?; + let context = referenced(context_arg, "context")?; + match dt_arg { + FnArg::Typed(typed) if matches!(&*typed.ty, Type::Path(p) if p.path.is_ident("f32")) => {} + other => { + return Err(syn::Error::new( + other.span(), + "the last argument is the frame length `dt: f32` (seconds)", + )) + } + } + let ReturnType::Type(_, output) = &sig.output else { + return Err(syn::Error::new( + sig.span(), + "a predicted step returns the next state", + )); + }; + let name = &sig.ident; + let export = name.to_string(); + let export = export.strip_prefix("r#").unwrap_or(&export).to_string(); + let symbol = format_ident!("dg_predict_{}", export); + let step = &args.step; + let kind = &args.kind; + let vis = &function.vis; + let doc = format!( + "The predicted step [`{export}`]: kind `{}`, exported to WebAssembly as `dg_predict_{export}`.", + kind.value() + ); + // Spanned at the return type: a step that does not return its state + // fails there. + let call = quote_spanned! {output.span()=> + #name(state, input, context, dt) + }; + Ok(quote! { + #function + + #[doc = #doc] + #[derive(Debug, Clone, Copy, Default)] + #vis struct #step; + + impl #root::prediction::PredictStep for #step { + const KIND: &'static str = #kind; + const PACKAGE: &'static str = ::core::env!("CARGO_PKG_NAME"); + const EXPORT: &'static str = #export; + type State = #state; + type Input = #input; + type Context = #context; + + fn step(state: &#state, input: &#input, context: &#context, dt: f32) -> #state { + #call + } + } + + #[cfg(target_arch = "wasm32")] + const _: () = { + #[unsafe(no_mangle)] + extern "C" fn #symbol(state_len: u32, input_len: u32, context_len: u32, dt: f32) -> i32 { + #root::__private::wasm_export::<#step>(state_len, input_len, context_len, dt) + } + }; + }) +} diff --git a/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs b/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs new file mode 100644 index 000000000..fcc45c754 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs @@ -0,0 +1,19 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +// The state must be borrowed, and the frame length is a trailing `dt: f32`. +#[predict(Step, kind = "dot")] +fn step(state: State, _input: &Push) -> State { + state +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr b/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr new file mode 100644 index 000000000..890e894f3 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr @@ -0,0 +1,5 @@ +error: a predicted step takes `(state: &State, input: &Input, context: &Context, dt: f32)` + --> tests/compile_fail/predict_bad_signature.rs:15:9 + | +15 | fn step(state: State, _input: &Push) -> State { + | ^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs b/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs new file mode 100644 index 000000000..00c462c33 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs @@ -0,0 +1,18 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +#[predict(Step)] +fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> State { + *state +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr b/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr new file mode 100644 index 000000000..b56063d06 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr @@ -0,0 +1,5 @@ +error: `#[predict]` needs the predicted kind: `kind = "player"` + --> tests/compile_fail/predict_needs_kind.rs:13:11 + | +13 | #[predict(Step)] + | ^^^^ diff --git a/distributed_game_macros/tests/compile_fail/predict_returns_state.rs b/distributed_game_macros/tests/compile_fail/predict_returns_state.rs new file mode 100644 index 000000000..0826a0fc8 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_returns_state.rs @@ -0,0 +1,18 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +#[predict(Step, kind = "dot")] +fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 { + state.x +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr b/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr new file mode 100644 index 000000000..5ffaac908 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_returns_state.stderr @@ -0,0 +1,13 @@ +error[E0308]: mismatched types + --> tests/compile_fail/predict_returns_state.rs:14:4 + | +14 | fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 { + | ^^^^^^^^^^^^^-----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | | + | | expected `State` because of return type + | expected `State`, found `f32` + | +help: try wrapping the expression in `State` + | +14 | fn State { x: step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 } { + | ++++++++++ + diff --git a/js/tests/game-generated.test.mjs b/js/tests/game-generated.test.mjs index 08712f874..ef25a9062 100644 --- a/js/tests/game-generated.test.mjs +++ b/js/tests/game-generated.test.mjs @@ -12,6 +12,8 @@ import { after, before, test } from 'node:test'; import { fromHex, toHex } from '@hops-ops/distributed/game'; +import { predictModuleBytes } from './fixtures/predict-module.mjs'; + const fixture = JSON.parse( readFileSync(new URL('../../distributed_game/tests/fixtures/authoring.json', import.meta.url), 'utf8') ); @@ -109,3 +111,34 @@ test('the client factory wires the encoder and merged corrections', () => { assert.equal(typed.send({ mx: 0, my: 0, buttons: 0, aim: 0, power: 0, viewTick: 0 }), undefined, 'not connected'); typed.client.close(); }); + +test('the predicted step is described and wired in by default', async () => { + const surface = fixture.surface; + assert.equal(gen.PREDICT.export, surface.predict.export); + assert.equal(gen.PREDICT.kind, 'player'); + // Wire field names of the kind, with the state record's plain types. + assert.deepEqual(gen.PREDICT_STATE.map(([name]) => name), ['x', 'vx', 'hp', 'dead']); + assert.deepEqual(gen.PREDICT_STATE.map(([, type]) => type.type), ['f32', 'f32', 'u8', 'bool']); + assert.deepEqual(gen.PREDICT_CONTEXT.map(([name]) => name), ['speed', 'gusts']); + assert.ok(gen.PREDICT_WASM_URL.href.endsWith('/wasm/sample.wasm')); + + // Default: the compiled step (here a stand-in module that echoes the state). + const typed = gen.createSampleClient({ url: () => 'ws://unused', ticket: async () => 'unused', wasm: predictModuleBytes() }); + assert.ok(typed.prediction !== undefined); + await typed.prediction.ready; + typed.prediction.setContext({ speed: 2, gusts: 1 }); + const fields = { x: 1.25, vx: 0, hp: 5, dead: false, name: 'n' }; + assert.deepEqual(typed.prediction.predict(fields, { mx: 1, my: 0, buttons: 0, aim: 0, power: 0, viewTick: 0 }, 33), { + x: 1.25, + vx: 0, + hp: 5, + dead: false + }); + typed.client.close(); + + // `false` turns prediction off; a custom `predict` replaces the step. + const off = gen.createSampleClient({ url: () => 'ws://unused', ticket: async () => 'unused', prediction: false }); + assert.equal(off.prediction, undefined); + assert.equal(off.client.predictor, undefined); + off.client.close(); +}); From 649b272bc2b9526dcf5d220f1977d993ac1a6757 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:52:33 -0500 Subject: [PATCH 194/484] feat(examples): predict demo movement with compiled Rust steps The demos' predicted movement moves into the game_sim crate (server workspace member, no server dependencies): arena_step (Arena, The Freeze), pit_step (Mob Pit), hood_step (Boss Ripple) and grid_step (Endless Grid, context = seed + cell, props generated inside the module). Zones call the declared steps; surfaces record them; run.sh gen/smoke and run.sh compile them with game-wasm (gitignored). The pages predict through the generated clients; the TypeScript movement twins (arena/movement.ts, grid step/collide/snap), their parity test and arena-movement.json are gone. world.ts keeps only content generation for rendering. game-demos predict-trace prints native traces over recorded input streams and tests/prediction-wasm.test.mjs requires every surface's module to match them byte for byte and times prediction. --- examples/game/client/.gitignore | 2 + examples/game/client/src/arena/client.ts | 17 +- examples/game/client/src/arena/floor.ts | 29 ++ examples/game/client/src/arena/main.ts | 4 +- examples/game/client/src/freeze/client.ts | 13 +- examples/game/client/src/freeze/main.ts | 2 +- .../game/client/src/generated/arena/client.ts | 49 ++- .../game/client/src/generated/arena/events.ts | 12 +- .../game/client/src/generated/arena/index.ts | 3 +- .../game/client/src/generated/arena/input.ts | 2 +- .../client/src/generated/arena/predict.ts | 51 +++ .../game/client/src/generated/arena/schema.ts | 2 +- .../client/src/generated/arena/surface.json | 53 +++- .../client/src/generated/freeze/client.ts | 49 ++- .../client/src/generated/freeze/events.ts | 12 +- .../game/client/src/generated/freeze/index.ts | 3 +- .../game/client/src/generated/freeze/input.ts | 2 +- .../client/src/generated/freeze/predict.ts | 51 +++ .../client/src/generated/freeze/schema.ts | 2 +- .../client/src/generated/freeze/surface.json | 50 ++- .../client/src/generated/gallery/client.ts | 2 +- .../client/src/generated/gallery/events.ts | 2 +- .../client/src/generated/gallery/index.ts | 2 +- .../client/src/generated/gallery/input.ts | 2 +- .../client/src/generated/gallery/schema.ts | 2 +- .../client/src/generated/gallery/surface.json | 2 +- .../game/client/src/generated/grid/client.ts | 49 ++- .../game/client/src/generated/grid/events.ts | 15 +- .../game/client/src/generated/grid/index.ts | 3 +- .../game/client/src/generated/grid/input.ts | 2 +- .../game/client/src/generated/grid/predict.ts | 52 +++ .../game/client/src/generated/grid/schema.ts | 2 +- .../client/src/generated/grid/surface.json | 53 +++- .../client/src/generated/mobpit/client.ts | 49 ++- .../client/src/generated/mobpit/events.ts | 12 +- .../game/client/src/generated/mobpit/index.ts | 3 +- .../game/client/src/generated/mobpit/input.ts | 2 +- .../client/src/generated/mobpit/predict.ts | 51 +++ .../client/src/generated/mobpit/schema.ts | 2 +- .../client/src/generated/mobpit/surface.json | 50 ++- .../client/src/generated/ripple/client.ts | 49 ++- .../client/src/generated/ripple/events.ts | 12 +- .../game/client/src/generated/ripple/index.ts | 3 +- .../game/client/src/generated/ripple/input.ts | 2 +- .../client/src/generated/ripple/predict.ts | 51 +++ .../client/src/generated/ripple/schema.ts | 2 +- .../client/src/generated/ripple/surface.json | 50 ++- examples/game/client/src/grid/client.ts | 38 ++- examples/game/client/src/grid/world.ts | 87 +----- examples/game/client/src/leaderboard/main.ts | 2 +- examples/game/client/src/mobpit/client.ts | 17 +- examples/game/client/src/mobpit/main.ts | 2 +- examples/game/client/src/ripple/client.ts | 18 +- examples/game/client/src/ripple/main.ts | 2 +- .../game/client/tests/arena-headless.test.mjs | 26 +- .../client/tests/freeze-headless.test.mjs | 3 +- .../client/tests/grid-world-parity.test.mjs | 30 +- .../client/tests/prediction-wasm.test.mjs | 166 ++++++++++ examples/game/fixtures/grid-world.json | 7 +- examples/game/run.sh | 54 +++- examples/game/server/Cargo.lock | 8 + examples/game/server/Cargo.toml | 4 +- examples/game/server/sim/Cargo.toml | 16 + examples/game/server/sim/src/arena.rs | 66 ++-- examples/game/server/sim/src/grid.rs | 81 ++++- examples/game/server/sim/src/lib.rs | 22 ++ examples/game/server/sim/src/mobpit.rs | 44 +++ examples/game/server/sim/src/ripple.rs | 41 +++ examples/game/server/src/arena/mod.rs | 15 +- examples/game/server/src/freeze/mod.rs | 11 +- examples/game/server/src/grid/mod.rs | 9 +- examples/game/server/src/lib.rs | 4 + examples/game/server/src/main.rs | 8 + examples/game/server/src/mobpit/zone.rs | 48 +-- examples/game/server/src/predict_trace.rs | 295 ++++++++++++++++++ examples/game/server/src/ripple/mod.rs | 42 +-- examples/game/server/tests/grid_fixture.rs | 68 +--- 77 files changed, 1707 insertions(+), 461 deletions(-) create mode 100644 examples/game/client/src/arena/floor.ts create mode 100644 examples/game/client/src/generated/arena/predict.ts create mode 100644 examples/game/client/src/generated/freeze/predict.ts create mode 100644 examples/game/client/src/generated/grid/predict.ts create mode 100644 examples/game/client/src/generated/mobpit/predict.ts create mode 100644 examples/game/client/src/generated/ripple/predict.ts create mode 100644 examples/game/client/tests/prediction-wasm.test.mjs create mode 100644 examples/game/server/sim/Cargo.toml create mode 100644 examples/game/server/sim/src/lib.rs create mode 100644 examples/game/server/sim/src/mobpit.rs create mode 100644 examples/game/server/sim/src/ripple.rs create mode 100644 examples/game/server/src/predict_trace.rs diff --git a/examples/game/client/.gitignore b/examples/game/client/.gitignore index b94707787..17bb43423 100644 --- a/examples/game/client/.gitignore +++ b/examples/game/client/.gitignore @@ -1,2 +1,4 @@ node_modules/ dist/ +# Compiled predicted steps (`distributed game-wasm`, built by run.sh) +src/generated/*/wasm/ diff --git a/examples/game/client/src/arena/client.ts b/examples/game/client/src/arena/client.ts index 0cf7a913e..157e29efd 100644 --- a/examples/game/client/src/arena/client.ts +++ b/examples/game/client/src/arena/client.ts @@ -1,15 +1,15 @@ /** * Arena networking without rendering: the generated `createArenaClient` - * (input encoder, correction defaults, typed events) plus the demo's - * predicted movement step and dev tickets; binds the own capsule from the - * zone's typed `hello`. Used by `main.ts` (Babylon) and the headless test. + * (input encoder, correction defaults, typed events and prediction with the + * Rust movement step compiled to WebAssembly) plus dev tickets; binds the + * own capsule from the zone's typed `hello`. Used by `main.ts` (Babylon) + * and the headless test. */ import type { GameSocketFactory } from '@hops-ops/distributed/game'; import * as arena from '../generated/arena/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; import { latest } from '../shared/latest.ts'; -import { predictPlayer } from './movement.ts'; export const DEFAULT_ZONE = 'arena-1'; @@ -17,7 +17,7 @@ export type ArenaClient = arena.ArenaClient & Readonly<{ /** Latest hello (own entity id, view radius); undefined until joined. */ hello(): arena.HelloEvent | undefined; - /** Resolves on the first hello. */ + /** Resolves on the first hello, once the predicted step is loaded. */ ready: Promise; }>; @@ -35,12 +35,13 @@ export function createArenaClient(options: ArenaClientOptions): ArenaClient { socket: options.socket, pingIntervalMs: 500, // One input = one 30 Hz command frame on the server. - inputDtMs: 1000 / 30, - prediction: { predict: (fields, input) => predictPlayer(fields, input) } + inputDtMs: 1000 / 30 + // Prediction: the generated default, `arena_step` compiled to WASM. }); const hello = latest( (h) => typed.on('hello', h), (value) => typed.client.setControlledEntity(value.entity) ); - return { ...typed, hello: hello.get, ready: hello.ready }; + const ready = Promise.all([hello.ready, typed.prediction?.ready]).then(([h]) => h); + return { ...typed, hello: hello.get, ready }; } diff --git a/examples/game/client/src/arena/floor.ts b/examples/game/client/src/arena/floor.ts new file mode 100644 index 000000000..475a8c718 --- /dev/null +++ b/examples/game/client/src/arena/floor.ts @@ -0,0 +1,29 @@ +/** + * Drawing constants of the Arena floor, shared by the pages with an Arena + * capsule (Arena, Mob Pit, The Freeze, Boss Ripple). + * + * Rendering only: movement, collision and the dash run in Rust + * (`game_sim::arena`), on the server and — compiled to WebAssembly — in the + * client's prediction. `tests/prediction-wasm.test.mjs` checks these values + * against the native build so the drawn floor matches the simulated one. + */ + +/** Floor half extent (m). */ +export const HALF = 20; +/** Capsule radius (m). */ +export const PLAYER_RADIUS = 0.5; +/** Dash cooldown in command frames (for the HUD meter). */ +export const DASH_COOLDOWN = 45; + +/** Static circular pillars `[x, y, radius]`. */ +export const PILLARS: readonly (readonly [number, number, number])[] = [ + [0, 0, 2.5], + [-9, -9, 1.5], + [9, -9, 1.5], + [-9, 9, 1.5], + [9, 9, 1.5], + [0, -14, 1], + [0, 14, 1], + [-14, 0, 1], + [14, 0, 1] +]; diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 167f56980..32b0c11bc 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -24,7 +24,7 @@ import { Minimap, type MinimapDot } from '../shared/minimap.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { droneFields, isDrone, isPillar, pillarFields, playerFields, BUTTON, type MoveInput } from '../generated/arena/index.ts'; import { createArenaClient, DEFAULT_ZONE } from './client.ts'; -import { DASH_COOLDOWN, HALF, PLAYER_RADIUS } from './movement.ts'; +import { DASH_COOLDOWN, HALF, PLAYER_RADIUS } from './floor.ts'; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; @@ -233,6 +233,6 @@ declare global { arena?: unknown; } } -window.arena = { client, api, scene: scene as Scene }; +window.arena = { client, api, prediction: arena.prediction, scene: scene as Scene }; client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/freeze/client.ts b/examples/game/client/src/freeze/client.ts index 6540209f4..e8182ab2b 100644 --- a/examples/game/client/src/freeze/client.ts +++ b/examples/game/client/src/freeze/client.ts @@ -24,7 +24,6 @@ import { type FreezeMessage } from '@hops-ops/distributed/game'; -import { predictPlayer } from '../arena/movement.ts'; import * as freeze from '../generated/freeze/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; @@ -140,7 +139,7 @@ export type FreezeClient = Readonly<{ /** Content pack the client renders. */ pack(): Pack; hello(): FreezeHello | undefined; - /** Resolves on the next hello (each zone sends one). */ + /** Resolves on the next hello (each zone sends one), once the predicted step is loaded. */ nextHello(): Promise; /** Freeze notice while frozen. */ frozen(): FreezeMessage | undefined; @@ -197,8 +196,8 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< note(reloadingZone, 'reload', `server required content ${pack.version}: reloaded "${pack.name}"`); changed('pack'); return pack.version; - }, - prediction: { predict: (fields, input) => predictPlayer(fields, input) } + } + // Prediction: the generated default, `arena_step` compiled to WASM. }); const { client } = typed; client.on('reloadRequired', (zone) => (reloadingZone = zone)); @@ -260,7 +259,11 @@ export async function createFreezeClient(options: FreezeClientOptions): Promise< client, pack: () => pack, hello: () => hello, - nextHello: () => new Promise((resolve) => helloWaiters.push(resolve)), + nextHello: () => + Promise.all([ + new Promise((resolve) => helloWaiters.push(resolve)), + typed.prediction?.ready + ]).then(([h]) => h), frozen: () => frozen, lastResume: () => lastResume, worldVersion: () => worldVersion, diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts index 33098742f..5f0fdc818 100644 --- a/examples/game/client/src/freeze/main.ts +++ b/examples/game/client/src/freeze/main.ts @@ -13,7 +13,7 @@ import type { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/floor.ts'; import { BUTTON, KIND, gemFields, playerFields, ritualFields, slimeFields, type KindName, type MoveInput } from '../generated/freeze/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; diff --git a/examples/game/client/src/generated/arena/client.ts b/examples/game/client/src/generated/arena/client.ts index f3844df36..b49b5a356 100644 --- a/examples/game/client/src/generated/arena/client.ts +++ b/examples/game/client/src/generated/arena/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type MoveInput } from './input.ts'; +import { createArenaPrediction, type ArenaPrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type ArenaPredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type ArenaPredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type ArenaClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: ArenaPredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: ArenaPredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type ArenaClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: ArenaPrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: MoveInput): number | undefined; }>; -/** A `GameClient` for the `arena` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `arena` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createArenaClient(options: ArenaClientOptions): ArenaClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createArenaPrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/examples/game/client/src/generated/arena/events.ts b/examples/game/client/src/generated/arena/events.ts index 97f1109a9..8d7f3759e 100644 --- a/examples/game/client/src/generated/arena/events.ts +++ b/examples/game/client/src/generated/arena/events.ts @@ -1,8 +1,18 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; +/** Record `MoveState` (`#[derive(GameRecord)]`). */ +export interface MoveState { + readonly x: number; + readonly y: number; + readonly vx: number; + readonly vy: number; + readonly dash: number; + readonly cd: number; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly entity: number; diff --git a/examples/game/client/src/generated/arena/index.ts b/examples/game/client/src/generated/arena/index.ts index 599e7b1ea..ae6b92901 100644 --- a/examples/game/client/src/generated/arena/index.ts +++ b/examples/game/client/src/generated/arena/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/arena/input.ts b/examples/game/client/src/generated/arena/input.ts index 696221d8c..453828a26 100644 --- a/examples/game/client/src/generated/arena/input.ts +++ b/examples/game/client/src/generated/arena/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/predict.ts b/examples/game/client/src/generated/arena/predict.ts new file mode 100644 index 000000000..5c6aa22bc --- /dev/null +++ b/examples/game/client/src/generated/arena/predict.ts @@ -0,0 +1,51 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; + +import { encodeInput, type MoveInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `arena_step` of Cargo package `game_sim`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'arena_step', + package: 'game_sim', + state: 'MoveState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `MoveState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['vy', { type: 'f32' }], + ['dash', { type: 'u8' }], + ['cd', { type: 'u8' }], +]; + +/** The step takes no context. */ +export type PredictContext = undefined; + +/** The step takes no context. */ +export const PREDICT_CONTEXT = undefined; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/arena.wasm', import.meta.url); + +/** The `arena` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type ArenaPrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves. + */ +export function createArenaPrediction(source: WasmSource = PREDICT_WASM_URL): ArenaPrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/client/src/generated/arena/schema.ts b/examples/game/client/src/generated/arena/schema.ts index 8630261b9..029d05996 100644 --- a/examples/game/client/src/generated/arena/schema.ts +++ b/examples/game/client/src/generated/arena/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/surface.json b/examples/game/client/src/generated/arena/surface.json index a9a7da870..dba3f87b5 100644 --- a/examples/game/client/src/generated/arena/surface.json +++ b/examples/game/client/src/generated/arena/surface.json @@ -225,7 +225,56 @@ } ], "name": "arena", + "predict": { + "abi": 1, + "export": "arena_step", + "kind": "player", + "package": "game_sim", + "state": "MoveState" + }, "protocolVersion": 1, - "records": [], - "schemaVersion": 1 + "records": [ + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "vy", + "type": { + "type": "f32" + } + }, + { + "name": "dash", + "type": { + "type": "u8" + } + }, + { + "name": "cd", + "type": { + "type": "u8" + } + } + ], + "name": "MoveState" + } + ], + "schemaVersion": 2 } diff --git a/examples/game/client/src/generated/freeze/client.ts b/examples/game/client/src/generated/freeze/client.ts index 81195ec05..70872928f 100644 --- a/examples/game/client/src/generated/freeze/client.ts +++ b/examples/game/client/src/generated/freeze/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type MoveInput } from './input.ts'; +import { createFreezePrediction, type FreezePrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type FreezePredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type FreezePredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type FreezeClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: FreezePredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: FreezePredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type FreezeClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: FreezePrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: MoveInput): number | undefined; }>; -/** A `GameClient` for the `freeze` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `freeze` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createFreezeClient(options: FreezeClientOptions): FreezeClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createFreezePrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/examples/game/client/src/generated/freeze/events.ts b/examples/game/client/src/generated/freeze/events.ts index b7044260e..56ca661a6 100644 --- a/examples/game/client/src/generated/freeze/events.ts +++ b/examples/game/client/src/generated/freeze/events.ts @@ -1,8 +1,18 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; +/** Record `MoveState` (`#[derive(GameRecord)]`). */ +export interface MoveState { + readonly x: number; + readonly y: number; + readonly vx: number; + readonly vy: number; + readonly dash: number; + readonly cd: number; +} + /** Record `Stamp` (`#[derive(GameRecord)]`). */ export interface Stamp { readonly zone: string; diff --git a/examples/game/client/src/generated/freeze/index.ts b/examples/game/client/src/generated/freeze/index.ts index 2a1459e77..61710b7c9 100644 --- a/examples/game/client/src/generated/freeze/index.ts +++ b/examples/game/client/src/generated/freeze/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/freeze/input.ts b/examples/game/client/src/generated/freeze/input.ts index 34dba4c77..9b2b2135c 100644 --- a/examples/game/client/src/generated/freeze/input.ts +++ b/examples/game/client/src/generated/freeze/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/predict.ts b/examples/game/client/src/generated/freeze/predict.ts new file mode 100644 index 000000000..f3e1ab89d --- /dev/null +++ b/examples/game/client/src/generated/freeze/predict.ts @@ -0,0 +1,51 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; + +import { encodeInput, type MoveInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `arena_step` of Cargo package `game_sim`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'arena_step', + package: 'game_sim', + state: 'MoveState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `MoveState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['vy', { type: 'f32' }], + ['dash', { type: 'u8' }], + ['cd', { type: 'u8' }], +]; + +/** The step takes no context. */ +export type PredictContext = undefined; + +/** The step takes no context. */ +export const PREDICT_CONTEXT = undefined; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/freeze.wasm', import.meta.url); + +/** The `freeze` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type FreezePrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves. + */ +export function createFreezePrediction(source: WasmSource = PREDICT_WASM_URL): FreezePrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/client/src/generated/freeze/schema.ts b/examples/game/client/src/generated/freeze/schema.ts index 535b284bc..e859598c7 100644 --- a/examples/game/client/src/generated/freeze/schema.ts +++ b/examples/game/client/src/generated/freeze/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/surface.json b/examples/game/client/src/generated/freeze/surface.json index cb593fa52..f4904d5b1 100644 --- a/examples/game/client/src/generated/freeze/surface.json +++ b/examples/game/client/src/generated/freeze/surface.json @@ -368,8 +368,56 @@ } ], "name": "freeze", + "predict": { + "abi": 1, + "export": "arena_step", + "kind": "player", + "package": "game_sim", + "state": "MoveState" + }, "protocolVersion": 1, "records": [ + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "vy", + "type": { + "type": "f32" + } + }, + { + "name": "dash", + "type": { + "type": "u8" + } + }, + { + "name": "cd", + "type": { + "type": "u8" + } + } + ], + "name": "MoveState" + }, { "fields": [ { @@ -394,5 +442,5 @@ "name": "Stamp" } ], - "schemaVersion": 1 + "schemaVersion": 2 } diff --git a/examples/game/client/src/generated/gallery/client.ts b/examples/game/client/src/generated/gallery/client.ts index fbfd31ecc..c64bcdeb4 100644 --- a/examples/game/client/src/generated/gallery/client.ts +++ b/examples/game/client/src/generated/gallery/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/events.ts b/examples/game/client/src/generated/gallery/events.ts index a470ca5fe..511d75d81 100644 --- a/examples/game/client/src/generated/gallery/events.ts +++ b/examples/game/client/src/generated/gallery/events.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/index.ts b/examples/game/client/src/generated/gallery/index.ts index aa58c899a..cbcb3cb40 100644 --- a/examples/game/client/src/generated/gallery/index.ts +++ b/examples/game/client/src/generated/gallery/index.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; diff --git a/examples/game/client/src/generated/gallery/input.ts b/examples/game/client/src/generated/gallery/input.ts index 6318b8e10..b31e31f42 100644 --- a/examples/game/client/src/generated/gallery/input.ts +++ b/examples/game/client/src/generated/gallery/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/schema.ts b/examples/game/client/src/generated/gallery/schema.ts index 83a8d087c..1a19e3469 100644 --- a/examples/game/client/src/generated/gallery/schema.ts +++ b/examples/game/client/src/generated/gallery/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/surface.json b/examples/game/client/src/generated/gallery/surface.json index 27d7d5e44..850b11bad 100644 --- a/examples/game/client/src/generated/gallery/surface.json +++ b/examples/game/client/src/generated/gallery/surface.json @@ -265,5 +265,5 @@ "name": "gallery", "protocolVersion": 1, "records": [], - "schemaVersion": 1 + "schemaVersion": 2 } diff --git a/examples/game/client/src/generated/grid/client.ts b/examples/game/client/src/generated/grid/client.ts index 2e09d5619..38aef358c 100644 --- a/examples/game/client/src/generated/grid/client.ts +++ b/examples/game/client/src/generated/grid/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type MoveInput } from './input.ts'; +import { createGridPrediction, type GridPrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type GridPredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type GridPredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type GridClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: GridPredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: GridPredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type GridClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: GridPrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: MoveInput): number | undefined; }>; -/** A `GameClient` for the `grid` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `grid` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createGridClient(options: GridClientOptions): GridClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createGridPrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/examples/game/client/src/generated/grid/events.ts b/examples/game/client/src/generated/grid/events.ts index 9ba78a6b4..5325ff362 100644 --- a/examples/game/client/src/generated/grid/events.ts +++ b/examples/game/client/src/generated/grid/events.ts @@ -1,8 +1,21 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; +/** Record `GridContext` (`#[derive(GameRecord)]`). */ +export interface GridContext { + readonly seed: number; + readonly cx: number; + readonly cy: number; +} + +/** Record `WalkerState` (`#[derive(GameRecord)]`). */ +export interface WalkerState { + readonly x: number; + readonly y: number; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly zone: string; diff --git a/examples/game/client/src/generated/grid/index.ts b/examples/game/client/src/generated/grid/index.ts index 690a1ce7a..111904def 100644 --- a/examples/game/client/src/generated/grid/index.ts +++ b/examples/game/client/src/generated/grid/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/grid/input.ts b/examples/game/client/src/generated/grid/input.ts index b9f032f36..5e7963e92 100644 --- a/examples/game/client/src/generated/grid/input.ts +++ b/examples/game/client/src/generated/grid/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/predict.ts b/examples/game/client/src/generated/grid/predict.ts new file mode 100644 index 000000000..3088e1c5a --- /dev/null +++ b/examples/game/client/src/generated/grid/predict.ts @@ -0,0 +1,52 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +import type { GridContext } from './events.ts'; +import { encodeInput, type MoveInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `grid_step` of Cargo package `game_sim`, predicting kind `walker`. */ +export const PREDICT = { + kind: 'walker', + export: 'grid_step', + package: 'game_sim', + state: 'WalkerState', + abi: 1, +} as const; + +/** Predicted `walker` fields (record `WalkerState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], +]; + +/** What the step reads besides state and input (`prediction.setContext`). */ +export type PredictContext = GridContext; + +/** Layout of the context record `GridContext`. */ +export const PREDICT_CONTEXT: PayloadLayout | undefined = [ + ['seed', { type: 'u32' }], + ['cx', { type: 'i32' }], + ['cy', { type: 'i32' }], +]; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/grid.wasm', import.meta.url); + +/** The `grid` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type GridPrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves and a context is set. + */ +export function createGridPrediction(source: WasmSource = PREDICT_WASM_URL): GridPrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/client/src/generated/grid/schema.ts b/examples/game/client/src/generated/grid/schema.ts index c3e5a4684..bef34ff76 100644 --- a/examples/game/client/src/generated/grid/schema.ts +++ b/examples/game/client/src/generated/grid/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/surface.json b/examples/game/client/src/generated/grid/surface.json index eade6c48d..dddde57bb 100644 --- a/examples/game/client/src/generated/grid/surface.json +++ b/examples/game/client/src/generated/grid/surface.json @@ -281,7 +281,56 @@ } ], "name": "grid", + "predict": { + "abi": 1, + "context": "GridContext", + "export": "grid_step", + "kind": "walker", + "package": "game_sim", + "state": "WalkerState" + }, "protocolVersion": 1, - "records": [], - "schemaVersion": 1 + "records": [ + { + "fields": [ + { + "name": "seed", + "type": { + "type": "u32" + } + }, + { + "name": "cx", + "type": { + "type": "i32" + } + }, + { + "name": "cy", + "type": { + "type": "i32" + } + } + ], + "name": "GridContext" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + } + ], + "name": "WalkerState" + } + ], + "schemaVersion": 2 } diff --git a/examples/game/client/src/generated/mobpit/client.ts b/examples/game/client/src/generated/mobpit/client.ts index 9a9fddace..a4895c0be 100644 --- a/examples/game/client/src/generated/mobpit/client.ts +++ b/examples/game/client/src/generated/mobpit/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type PitInput } from './input.ts'; +import { createMobpitPrediction, type MobpitPrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type MobpitPredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type MobpitPredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type MobpitClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: MobpitPredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: MobpitPredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type MobpitClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: MobpitPrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: PitInput): number | undefined; }>; -/** A `GameClient` for the `mobpit` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `mobpit` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createMobpitClient(options: MobpitClientOptions): MobpitClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createMobpitPrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts index 35ce3bb8d..95028f84b 100644 --- a/examples/game/client/src/generated/mobpit/events.ts +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; @@ -121,6 +121,16 @@ const BOARD_SNAPSHOT_TYPE: WireType = { ] }; +/** Record `MoveState` (`#[derive(GameRecord)]`). */ +export interface MoveState { + readonly x: number; + readonly y: number; + readonly vx: number; + readonly vy: number; + readonly dash: number; + readonly cd: number; +} + /** Record `Profile` (`#[derive(GameRecord)]`). */ export interface Profile { readonly xp: number; diff --git a/examples/game/client/src/generated/mobpit/index.ts b/examples/game/client/src/generated/mobpit/index.ts index c9b2dc6ff..afb9021b6 100644 --- a/examples/game/client/src/generated/mobpit/index.ts +++ b/examples/game/client/src/generated/mobpit/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/mobpit/input.ts b/examples/game/client/src/generated/mobpit/input.ts index 863e9d8f2..dde466caf 100644 --- a/examples/game/client/src/generated/mobpit/input.ts +++ b/examples/game/client/src/generated/mobpit/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/predict.ts b/examples/game/client/src/generated/mobpit/predict.ts new file mode 100644 index 000000000..6044e287b --- /dev/null +++ b/examples/game/client/src/generated/mobpit/predict.ts @@ -0,0 +1,51 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; + +import { encodeInput, type PitInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `pit_step` of Cargo package `game_sim`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'pit_step', + package: 'game_sim', + state: 'MoveState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `MoveState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['vy', { type: 'f32' }], + ['dash', { type: 'u8' }], + ['cd', { type: 'u8' }], +]; + +/** The step takes no context. */ +export type PredictContext = undefined; + +/** The step takes no context. */ +export const PREDICT_CONTEXT = undefined; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/mobpit.wasm', import.meta.url); + +/** The `mobpit` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type MobpitPrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves. + */ +export function createMobpitPrediction(source: WasmSource = PREDICT_WASM_URL): MobpitPrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/client/src/generated/mobpit/schema.ts b/examples/game/client/src/generated/mobpit/schema.ts index e22f7ecf4..e0b6d6529 100644 --- a/examples/game/client/src/generated/mobpit/schema.ts +++ b/examples/game/client/src/generated/mobpit/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json index 86938ff72..9fd1629ec 100644 --- a/examples/game/client/src/generated/mobpit/surface.json +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -556,6 +556,13 @@ } ], "name": "mobpit", + "predict": { + "abi": 1, + "export": "pit_step", + "kind": "player", + "package": "game_sim", + "state": "MoveState" + }, "protocolVersion": 1, "records": [ { @@ -701,6 +708,47 @@ ], "name": "Mismatch" }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "vy", + "type": { + "type": "f32" + } + }, + { + "name": "dash", + "type": { + "type": "u8" + } + }, + { + "name": "cd", + "type": { + "type": "u8" + } + } + ], + "name": "MoveState" + }, { "fields": [ { @@ -823,5 +871,5 @@ "name": "Scores" } ], - "schemaVersion": 1 + "schemaVersion": 2 } diff --git a/examples/game/client/src/generated/ripple/client.ts b/examples/game/client/src/generated/ripple/client.ts index df46664d1..e4deecd3d 100644 --- a/examples/game/client/src/generated/ripple/client.ts +++ b/examples/game/client/src/generated/ripple/client.ts @@ -1,49 +1,68 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. -import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; import { EVENTS, type Events } from './events.ts'; import { encodeInput, type HoodInput } from './input.ts'; +import { createRipplePrediction, type RipplePrediction } from './predict.ts'; import { CORRECTIONS } from './schema.ts'; -/** Prediction options; `encodeInput` and the correction defaults are filled in. */ -export type RipplePredictionOptions = Omit, 'encodeInput'> & - Partial, 'encodeInput'>>; +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type RipplePredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; export type RippleClientOptions = Omit, 'prediction'> & - Readonly<{ prediction?: RipplePredictionOptions }>; + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: RipplePredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; export type RippleClient = Readonly<{ client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: RipplePrediction | undefined; /** Typed event subscription (every zone); returns the unsubscribe. */ on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; - /** Send one input: predicted when prediction is configured, raw otherwise. */ + /** Send one input: predicted when prediction is on, raw otherwise. */ send(input: HoodInput): number | undefined; }>; -/** A `GameClient` for the `ripple` surface with its input encoder and correction defaults. */ +/** + * A `GameClient` for the `ripple` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ export function createRippleClient(options: RippleClientOptions): RippleClient { - const prediction = options.prediction; + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createRipplePrediction(wasm); const client = new GameClient({ - ...options, + ...rest, prediction: - prediction === undefined + tuning === false ? undefined : { - ...prediction, - encodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)), - corrections: mergeCorrections(CORRECTIONS, prediction.corrections) + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) } }); return { client, + prediction, on: (name, handler) => client.on('event', (zoneId, event) => { const codec = EVENTS[name]; if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); }), send: (input) => - prediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) }; } diff --git a/examples/game/client/src/generated/ripple/events.ts b/examples/game/client/src/generated/ripple/events.ts index b19cdff91..4a1fff8a9 100644 --- a/examples/game/client/src/generated/ripple/events.ts +++ b/examples/game/client/src/generated/ripple/events.ts @@ -1,8 +1,18 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; +/** Record `MoveState` (`#[derive(GameRecord)]`). */ +export interface MoveState { + readonly x: number; + readonly y: number; + readonly vx: number; + readonly vy: number; + readonly dash: number; + readonly cd: number; +} + /** Record `Weather` (`#[derive(GameRecord)]`). */ export interface Weather { readonly weather: string; diff --git a/examples/game/client/src/generated/ripple/index.ts b/examples/game/client/src/generated/ripple/index.ts index 0495fe208..25c4ee88e 100644 --- a/examples/game/client/src/generated/ripple/index.ts +++ b/examples/game/client/src/generated/ripple/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; export * from './events.ts'; export * from './input.ts'; +export * from './predict.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/ripple/input.ts b/examples/game/client/src/generated/ripple/input.ts index 7854a6904..8acbd37d3 100644 --- a/examples/game/client/src/generated/ripple/input.ts +++ b/examples/game/client/src/generated/ripple/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/predict.ts b/examples/game/client/src/generated/ripple/predict.ts new file mode 100644 index 000000000..e6cebe7c9 --- /dev/null +++ b/examples/game/client/src/generated/ripple/predict.ts @@ -0,0 +1,51 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; + +import { encodeInput, type HoodInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `hood_step` of Cargo package `game_sim`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'hood_step', + package: 'game_sim', + state: 'MoveState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `MoveState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['vy', { type: 'f32' }], + ['dash', { type: 'u8' }], + ['cd', { type: 'u8' }], +]; + +/** The step takes no context. */ +export type PredictContext = undefined; + +/** The step takes no context. */ +export const PREDICT_CONTEXT = undefined; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/ripple.wasm', import.meta.url); + +/** The `ripple` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type RipplePrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves. + */ +export function createRipplePrediction(source: WasmSource = PREDICT_WASM_URL): RipplePrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/client/src/generated/ripple/schema.ts b/examples/game/client/src/generated/ripple/schema.ts index 93cf914d3..3bb495c1c 100644 --- a/examples/game/client/src/generated/ripple/schema.ts +++ b/examples/game/client/src/generated/ripple/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v1, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/surface.json b/examples/game/client/src/generated/ripple/surface.json index b7d6b4384..1b146aed8 100644 --- a/examples/game/client/src/generated/ripple/surface.json +++ b/examples/game/client/src/generated/ripple/surface.json @@ -404,8 +404,56 @@ } ], "name": "ripple", + "predict": { + "abi": 1, + "export": "hood_step", + "kind": "player", + "package": "game_sim", + "state": "MoveState" + }, "protocolVersion": 1, "records": [ + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "vy", + "type": { + "type": "f32" + } + }, + { + "name": "dash", + "type": { + "type": "u8" + } + }, + { + "name": "cd", + "type": { + "type": "u8" + } + } + ], + "name": "MoveState" + }, { "fields": [ { @@ -424,5 +472,5 @@ "name": "Weather" } ], - "schemaVersion": 1 + "schemaVersion": 2 } diff --git a/examples/game/client/src/grid/client.ts b/examples/game/client/src/grid/client.ts index 9f20d6203..455997c8d 100644 --- a/examples/game/client/src/grid/client.ts +++ b/examples/game/client/src/grid/client.ts @@ -8,8 +8,9 @@ * - observer connections to the 8 neighbouring cells, re-synced whenever * the authority changes, so what is across a border is visible before * crossing; - * - prediction of the own walker with the shared step (`world.ts`) against - * the props of the current cell; + * - prediction of the own walker by `grid_step`, the Rust step compiled to + * WebAssembly, which collides against the props of the cell named in its + * context (world seed + authoritative cell, set here); * - per-zone hello info (host, restored-from-hibernation …) and the * `/dev/grid/map` world map. */ @@ -17,7 +18,7 @@ import { fieldNumber, type GameClient, type GameSocketFactory, type RenderedEnti import * as grid from '../generated/grid/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { cellProps, parseZone, step, zoneId, CELL, DEFAULT_SEED, type Cell, type MoveInput, type Prop } from './world.ts'; +import { cellProps, parseZone, zoneId, CELL, DEFAULT_SEED, type Cell, type MoveInput, type Prop } from './world.ts'; export const DEFAULT_ZONE = 'grid.0.0'; @@ -52,6 +53,8 @@ export type GridClientOptions = Readonly<{ export type GridClient = Readonly<{ client: GameClient; + /** The compiled `grid_step` (context: seed + authoritative cell). */ + prediction: grid.GridPrediction | undefined; /** Cell of the authoritative zone. */ cell(): Cell | undefined; /** Latest hello per zone. */ @@ -64,7 +67,7 @@ export type GridClient = Readonly<{ worldOf(entity: RenderedEntity): { x: number; y: number } | undefined; /** Handoffs completed so far. */ handoffs(): number; - /** Resolves on the first hello with an own entity. */ + /** Resolves on the first hello with an own entity, once the predicted step is loaded. */ ready: Promise; /** Called once per restored activation of any zone we see. */ onRestored(listener: (hello: GridHello) => void): () => void; @@ -107,19 +110,21 @@ export function createGridClient(options: GridClientOptions): GridClient { ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 1000, - inputDtMs: 1000 / 30, - prediction: { - predict: (fields, input) => { - const cell = authorityCell ?? [0, 0]; - const [x, y] = step(fieldNumber(fields, 'x'), fieldNumber(fields, 'y'), input, props(cell)); - return { x, y }; - } - } + inputDtMs: 1000 / 30 + // Prediction: the generated default, `grid_step` compiled to WASM; + // its context (seed + cell) follows the authority below. }); const { client } = typed; + const setContext = () => { + const cell = authorityCell ?? [0, 0]; + typed.prediction?.setContext({ seed, cx: cell[0], cy: cell[1] }); + }; let resolveReady: (h: GridHello) => void = () => undefined; - const ready = new Promise((resolve) => (resolveReady = resolve)); + const ready = Promise.all([ + new Promise((resolve) => (resolveReady = resolve)), + typed.prediction?.ready + ]).then(([h]) => h); const syncNeighbours = () => { if (options.neighbours === false || authorityCell === undefined) return; @@ -138,6 +143,7 @@ export function createGridClient(options: GridClientOptions): GridClient { client.on('authority', (zone) => { authorityCell = parseZone(zone); + setContext(); syncNeighbours(); }); client.on('handoffComplete', () => { @@ -145,7 +151,10 @@ export function createGridClient(options: GridClientOptions): GridClient { }); typed.on('hello', (hello, zone) => { infos.set(zone, hello); - seed = hello.seed; + if (hello.seed !== seed) { + seed = hello.seed; + setContext(); + } if (hello.entity !== undefined && zone === client.authority?.zoneId) { client.setControlledEntity(hello.entity); resolveReady(hello); @@ -159,6 +168,7 @@ export function createGridClient(options: GridClientOptions): GridClient { return { client, + prediction: typed.prediction, cell: () => authorityCell, info: (zone) => infos.get(zone), seed: () => seed, diff --git a/examples/game/client/src/grid/world.ts b/examples/game/client/src/grid/world.ts index b8a735232..4966b29ca 100644 --- a/examples/game/client/src/grid/world.ts +++ b/examples/game/client/src/grid/world.ts @@ -1,21 +1,20 @@ /** - * Procedural world and movement of the Endless Grid. + * Procedural world *content* of the Endless Grid, for rendering: terrain + * height, biomes, props, zone ids. * - * **Twin of `examples/game/server/src/grid/world.rs`** — the server uses it - * for collision, the client for rendering and prediction; nothing static - * is replicated. Bit-identical by construction: `u32` hashing with - * `Math.imul` / `>>> 0`, binary32 arithmetic with `f()` (= `Math.fround`) - * after every operation, only `+ - * /`, `sqrt` and `floor`. - * `tests/grid-world-parity.test.mjs` replays the Rust-written fixture - * `examples/game/fixtures/grid-world.json`. + * **Twin of the generation in `examples/game/server/sim/src/grid.rs`**, + * bit-identical by construction (`u32` hashing with `Math.imul` / `>>> 0`, + * binary32 arithmetic with `f()` (= `Math.fround`) after every operation, + * only `+ - * /`, `sqrt` and `floor`) and checked against the Rust-written + * fixture `examples/game/fixtures/grid-world.json` by + * `tests/grid-world-parity.test.mjs`. Serving world content from WASM too + * would retire this file; it is a separate follow-up. * - * The input type, its sanitize, the button bits and the wire quantization - * of positions come from the client generated from the Rust surface - * (`../generated/grid`). + * Movement is **not** here: the own walker is predicted by the Rust step + * compiled to WebAssembly (`grid_step`, which generates the cell's props + * itself), wired by the generated client (`../generated/grid`). */ -import { dequantizeLinear, quantizeLinear } from '@hops-ops/distributed/game'; - -import { BUTTON, FIELD_TYPES, sanitizeInput, type MoveInput } from '../generated/grid/index.ts'; +import { BUTTON } from '../generated/grid/index.ts'; export type { MoveInput } from '../generated/grid/index.ts'; @@ -28,16 +27,10 @@ export const SUB = 4; export const SUB_SIZE = 8; export const PROP_MARGIN = 2; export const PROP_SPAN = 4; -export const HYSTERESIS = 0.5; +/** Walker radius (m, for drawing; collision is in the WASM step). */ export const PLAYER_RADIUS = f(0.45); -export const WALK_SPEED = 6; -export const SPRINT_SPEED = 10; -export const DT = f(1 / 30); -export const OUTSIDE_LIMIT = 2; export const BUTTON_SPRINT = BUTTON.sprint; export const BUTTON_MARK = BUTTON.mark; -/** Wire quantization of local positions (server `grid::world::POS`). */ -export const POS = FIELD_TYPES.walker.x; export const BIOMES = ['highlands', 'steppe', 'forest', 'meadow'] as const; const PROP_DENSITY = [0.4375, 0.1875, 0.75, 0.3125]; @@ -170,58 +163,6 @@ export function cellProps(seed: number, cell: Cell): Prop[] { return props; } -export function snap(v: number): number { - return dequantizeLinear(quantizeLinear(v, POS.min, POS.max, POS.bits), POS.min, POS.max, POS.bits); -} - -export function collide(x0: number, y0: number, radius: number, props: readonly Prop[]): [number, number] { - let x = x0; - let y = y0; - for (const p of props) { - if (!p.solid) continue; - const ox = f(x - p.x); - const oy = f(y - p.y); - const d2 = f(f(ox * ox) + f(oy * oy)); - const min = f(radius + p.r); - if (d2 < f(min * min)) { - const d = f(Math.sqrt(d2)); - const [nx, ny] = d > f(1e-6) ? [f(ox / d), f(oy / d)] : [1, 0]; - x = f(p.x + f(nx * min)); - y = f(p.y + f(ny * min)); - } - } - return [x, y]; -} - -/** Advance a walker one command frame inside its cell (see the Rust docs). */ -export function step(x: number, y: number, raw: MoveInput, props: readonly Prop[]): [number, number] { - const input = sanitizeInput(raw); - let dx = f(input.mx / 127); - let dy = f(input.my / 127); - const l2 = f(f(dx * dx) + f(dy * dy)); - if (l2 > 1) { - const inv = f(1 / f(Math.sqrt(l2))); - dx = f(dx * inv); - dy = f(dy * inv); - } - const speed = (input.buttons & BUTTON_SPRINT) !== 0 ? SPRINT_SPEED : WALK_SPEED; - const nx = f(x + f(f(dx * speed) * DT)); - const ny = f(y + f(f(dy * speed) * DT)); - const [cx, cy] = collide(nx, ny, PLAYER_RADIUS, props); - const lo = -OUTSIDE_LIMIT; - const hi = CELL + OUTSIDE_LIMIT; - return [snap(Math.min(hi, Math.max(lo, cx))), snap(Math.min(hi, Math.max(lo, cy)))]; -} - -/** Neighbour offset a walker belongs to past the hysteresis (x first), or undefined. */ -export function crossing(x: number, y: number): [number, number] | undefined { - if (x < -HYSTERESIS) return [-1, 0]; - if (x > CELL + HYSTERESIS) return [1, 0]; - if (y < -HYSTERESIS) return [0, -1]; - if (y > CELL + HYSTERESIS) return [0, 1]; - return undefined; -} - export const MAX_CELL = 1_000_000; export function zoneId(cell: Cell): string { diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts index 935207c24..e05c9c31e 100644 --- a/examples/game/client/src/leaderboard/main.ts +++ b/examples/game/client/src/leaderboard/main.ts @@ -3,7 +3,7 @@ * top-10 snapshots, reads your rank and neighbours on every push, and * triggers a rebuild from the cells' event history. */ -import { HALF } from '../arena/movement.ts'; +import { HALF } from '../arena/floor.ts'; import { isMob, isPillar, diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts index 3f401ccdb..949cd07b5 100644 --- a/examples/game/client/src/mobpit/client.ts +++ b/examples/game/client/src/mobpit/client.ts @@ -1,7 +1,7 @@ /** * Mob Pit networking without rendering (Node-testable): the generated - * `createMobpitClient` with the Arena's predicted movement for the own - * capsule, the zone's typed events folded into a small state object, and + * `createMobpitClient` (the own capsule predicted by `pit_step`, the Rust + * Arena movement compiled to WebAssembly), the zone's typed events folded into a small state object, and * the `/dev/mobpit/*` routes. * * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the @@ -10,7 +10,6 @@ */ import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; -import { predictPlayer } from '../arena/movement.ts'; import * as pit from '../generated/mobpit/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; import { latest } from '../shared/latest.ts'; @@ -34,7 +33,7 @@ export type MobPitClient = pit.MobpitClient & board(): pit.BoardSnapshot | undefined; /** Kills by me whose fact has not settled yet (key → event). */ unsaved: ReadonlyMap; - /** Resolves on the first hello. */ + /** Resolves on the first hello, once the predicted step is loaded. */ ready: Promise; }>; @@ -50,9 +49,8 @@ export function createMobPitClient(options: MobPitClientOptions): MobPitClient { ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 500, - inputDtMs: 1000 / 30, - // The movement part of the frame is the Arena's (attack only adds a bit). - prediction: { predict: (fields, input) => predictPlayer(fields, input) } + inputDtMs: 1000 / 30 + // Prediction: the generated default, `pit_step` compiled to WASM. }); const hello = latest( (h) => typed.on('hello', h), @@ -71,7 +69,7 @@ export function createMobPitClient(options: MobPitClientOptions): MobPitClient { profile: profile.get, board: board.get, unsaved, - ready: hello.ready + ready: Promise.all([hello.ready, typed.prediction?.ready]).then(([h]) => h) }; } @@ -85,7 +83,8 @@ export function createBoardWatcher(options: MobPitClientOptions): Readonly<{ url: (zone) => zoneUrl(zone, options.base), ticket: options.api.ticketSource(), socket: options.socket, - pingIntervalMs: 1000 + pingIntervalMs: 1000, + prediction: false }); const board = latest((h) => typed.on('board', h)); return { client: typed.client, board: board.get, on: (handler) => typed.on('board', handler) }; diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index b23d8ecba..e0c04c0ae 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -14,7 +14,7 @@ import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PLAYER_RADIUS } from '../arena/movement.ts'; +import { HALF, PLAYER_RADIUS } from '../arena/floor.ts'; import { BUTTON, isMob, diff --git a/examples/game/client/src/ripple/client.ts b/examples/game/client/src/ripple/client.ts index 0f1fd36df..760aaf228 100644 --- a/examples/game/client/src/ripple/client.ts +++ b/examples/game/client/src/ripple/client.ts @@ -1,8 +1,9 @@ /** * Boss Ripple networking without rendering (Node-testable): * - * - the player's authoritative zone is one neighborhood (predicted with - * the Arena movement step; the boss stands on the central pillar); + * - the player's authoritative zone is one neighborhood (predicted by + * `hood_step`, the Rust Arena movement compiled to WebAssembly; the boss + * stands on the central pillar); * - every other zone of the hierarchy is observed (realm, city, boroughs * and the other hoods), so the page shows each tier's live state and * receives what upper tiers broadcast: ripple events, the city's @@ -10,7 +11,6 @@ */ import type { GameClient, GameSocketFactory } from '@hops-ops/distributed/game'; -import { predictPlayer } from '../arena/movement.ts'; import * as gen from '../generated/ripple/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; @@ -73,7 +73,7 @@ export type RippleClientOptions = Readonly<{ export type RippleClient = Readonly<{ client: GameClient; - /** Resolves on the first hello of the player's hood. */ + /** Resolves on the first hello of the player's hood, once the predicted step is loaded. */ ready: Promise; tier(zone: string): TierView; /** Ripple events received (newest last, bounded). */ @@ -107,13 +107,15 @@ export function createRippleClient(options: RippleClientOptions): RippleClient { ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 1000, - inputDtMs: 1000 / 30, - // The movement part of the frame is the Arena's (`action` only adds bits). - prediction: { predict: (fields, input) => predictPlayer(fields, input) } + inputDtMs: 1000 / 30 + // Prediction: the generated default, `hood_step` compiled to WASM. }); const { client } = typed; let resolveReady: (h: RippleHello) => void = () => undefined; - const ready = new Promise((resolve) => (resolveReady = resolve)); + const ready = Promise.all([ + new Promise((resolve) => (resolveReady = resolve)), + typed.prediction?.ready + ]).then(([h]) => h); typed.on('hello', (hello, zone) => { hellos.set(zone, hello); diff --git a/examples/game/client/src/ripple/main.ts b/examples/game/client/src/ripple/main.ts index eef1a0393..a02b7bb52 100644 --- a/examples/game/client/src/ripple/main.ts +++ b/examples/game/client/src/ripple/main.ts @@ -17,7 +17,7 @@ import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { Scene } from '@babylonjs/core/scene'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/movement.ts'; +import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/floor.ts'; import { BITS, isPlayer, playerFields } from '../generated/ripple/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; diff --git a/examples/game/client/tests/arena-headless.test.mjs b/examples/game/client/tests/arena-headless.test.mjs index 8b291b6ab..2b66e10fe 100644 --- a/examples/game/client/tests/arena-headless.test.mjs +++ b/examples/game/client/tests/arena-headless.test.mjs @@ -1,16 +1,20 @@ /** * Headless Arena client (Node, no browser): dev ticket → join → move with - * prediction; the server agrees with the predicted position; NetSim control - * changes the measured RTT. Starts the real `game-demos arena` binary. + * prediction (the Rust step compiled to WebAssembly, loaded by the + * generated client); the server agrees with the predicted state bit for + * bit; NetSim control changes the measured RTT. Starts the real + * `game-demos arena` binary. */ import assert from 'node:assert/strict'; import test from 'node:test'; import { createArenaClient } from '../src/arena/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; -import { stateFromFields, step } from '../src/arena/movement.ts'; import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; +/** The predicted `player` fields (the Rust `MoveState`). */ +const stateFromFields = (f) => ({ x: f.x, y: f.y, vx: f.vx, vy: f.vy, dash: f.dash, cd: f.cd }); + test('headless client joins the arena and moves with exact prediction', { timeout: 600_000 }, async () => { const server = await startDemo('arena'); const clients = []; @@ -26,18 +30,22 @@ test('headless client joins the arena and moves with exact prediction', { timeou assert.equal(hello.viewRadius, 14); assert.ok(api.last.principal.startsWith('guest-'), 'server-generated principal'); await until(() => client.predictor.active, 5_000, 'own entity bound'); + assert.ok(arena.prediction?.loaded(), 'the compiled step is loaded'); const start = stateFromFields(client.predictor.predicted()); // 30 command frames forward + right at the server's tick rate. const input = { mx: 90, my: 90, buttons: 0 }; - let expected = start; - for (let i = 0; i < 30; i += 1) { - client.sendInput(input); - expected = step(expected, input); + client.sendInput(input); + const first = stateFromFields(client.predictor.predicted()); + assert.ok(first.vx > 0 && first.vy > 0, 'prediction applies the step immediately'); + for (let i = 1; i < 30; i += 1) { await sleep(1000 / 30); + client.sendInput(input); } - const predicted = stateFromFields(client.predictor.predicted()); - assert.deepEqual(predicted, expected, 'prediction applies the shared step immediately'); + // What the client showed after the last input: the last rebase plus a + // replay of every then-unacknowledged input through the WASM step. + const expected = stateFromFields(client.predictor.predicted()); + assert.ok(arena.prediction.steps() >= 30, 'every input ran through the WASM step'); await until(() => client.predictor.lastAck >= 30 && client.predictor.pending.length === 0, 5_000, 'acks'); const server_ = stateFromFields(client.authority.replica.get(hello.entity).fields); assert.deepEqual(server_, expected, 'authoritative state equals the prediction bit for bit'); diff --git a/examples/game/client/tests/freeze-headless.test.mjs b/examples/game/client/tests/freeze-headless.test.mjs index fd5a5537c..a97ee65d2 100644 --- a/examples/game/client/tests/freeze-headless.test.mjs +++ b/examples/game/client/tests/freeze-headless.test.mjs @@ -15,7 +15,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { stateFromFields } from '../src/arena/movement.ts'; import { createFreezeClient, FreezeAdmin, ZONES } from '../src/freeze/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { memoryStorage, sleep, startDemo, until } from './helpers/demo-server.mjs'; @@ -34,7 +33,7 @@ async function walk(p, [x, y], done, timeoutMs = 15_000) { assert.ok(Date.now() < deadline, `walk to ${x},${y} timed out`); const fields = p.client.predictor?.active ? p.client.predictor.predicted() : undefined; if (fields !== undefined) { - const at = stateFromFields(fields); + const at = { x: Number(fields.x), y: Number(fields.y) }; const dx = x - at.x; const dy = y - at.y; const d = Math.hypot(dx, dy); diff --git a/examples/game/client/tests/grid-world-parity.test.mjs b/examples/game/client/tests/grid-world-parity.test.mjs index 6d7ad39f8..6574de50a 100644 --- a/examples/game/client/tests/grid-world-parity.test.mjs +++ b/examples/game/client/tests/grid-world-parity.test.mjs @@ -1,9 +1,10 @@ /** - * Rust ↔ TypeScript parity of the Endless Grid's procedural world and - * movement: replays `examples/game/fixtures/grid-world.json` (written by - * `server/tests/grid_fixture.rs`) through `src/grid/world.ts`. Every value - * must match bit for bit — the client renders and predicts with the same - * content the server collides against. + * Rust ↔ TypeScript parity of the Endless Grid's procedural world content + * (rendering only): replays `examples/game/fixtures/grid-world.json` + * (written by `server/tests/grid_fixture.rs`) through `src/grid/world.ts`. + * Every value must match bit for bit — the client draws the props the + * server collides against. Movement prediction runs the Rust step as WASM + * (`prediction-wasm.test.mjs`), so it has no TypeScript twin to check. */ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -20,10 +21,6 @@ test('constants and hashes match', () => { assert.equal(c.contentVersion, world.CONTENT_VERSION); assert.equal(c.cell, world.CELL); assert.equal(c.propMargin, world.PROP_MARGIN); - assert.equal(c.hysteresis, world.HYSTERESIS); - assert.equal(f(c.playerRadius), world.PLAYER_RADIUS); - assert.equal(c.walk, world.WALK_SPEED); - assert.equal(c.sprint, world.SPRINT_SPEED); assert.deepEqual([0, 1, 0xdeadbeef, 0xffffffff].map(world.hash32), c.hashes); assert.deepEqual([world.mix(c.seed, 3, -5, 7), world.mix(0, 0, -2147483648, 2147483647)], c.mix); }); @@ -51,21 +48,6 @@ test('terrain, moisture, biomes and props are bit-identical', () => { assert.ok(props > 10, 'fixture cells have props'); }); -test('the movement step reproduces every Rust position', () => { - const walk = fixture.walk; - const props = world.cellProps(fixture.constants.seed, walk.cell); - let [x, y] = walk.start; - let pushed = 0; - walk.steps.forEach(({ input, x: wx, y: wy }, i) => { - const free = world.step(x, y, { mx: input[0], my: input[1], buttons: input[2] }, []); - [x, y] = world.step(x, y, { mx: input[0], my: input[1], buttons: input[2] }, props); - if (free[0] !== x || free[1] !== y) pushed += 1; - assert.equal(x, f(wx), `step ${i} x`); - assert.equal(y, f(wy), `step ${i} y`); - }); - assert.ok(pushed > 0, 'the walk collides with props'); -}); - test('zone ids round-trip', () => { assert.deepEqual(world.parseZone('grid.-3.12'), [-3, 12]); assert.equal(world.zoneId([4, -2]), 'grid.4.-2'); diff --git a/examples/game/client/tests/prediction-wasm.test.mjs b/examples/game/client/tests/prediction-wasm.test.mjs new file mode 100644 index 000000000..22d0d6904 --- /dev/null +++ b/examples/game/client/tests/prediction-wasm.test.mjs @@ -0,0 +1,166 @@ +/** + * Native ↔ WebAssembly exact match of every demo's client-predicted step, + * and the cost of prediction with it. + * + * `game-demos predict-trace` (the native build) prints, per step function, + * recorded input streams with the state after every frame. Each surface's + * compiled module (`src/generated//wasm/.wasm`, built by + * `distributed game-wasm`) replays the same streams and must produce the + * same bytes — every float bit included. The generated `predict` (state ↔ + * entity fields, input encoder) is checked over the same streams, and a + * `Predictor` reconciling with 10 pending inputs is timed. + * + * The steps only use operations that are correctly rounded on every target + * (`+ - * /`, `sqrt`, comparisons); see `distributed_game::prediction` for + * the float rules (no platform transcendentals). + */ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { readFileSync, readdirSync, existsSync } from 'node:fs'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { + PredictModule, + Predictor, + decodePayload, + decodePredictState, + encodePayload, + encodePredictState, + fromHex, + toHex +} from '@hops-ops/distributed/game'; + +import * as floor from '../src/arena/floor.ts'; + +const GENERATED = new URL('../src/generated/', import.meta.url); +const SERVER_DIR = fileURLToPath(new URL('../../server/', import.meta.url)); + +function nativeTraces() { + const bin = process.env.GAME_DEMOS_BIN; + const out = bin + ? execFileSync(bin, ['predict-trace'], { maxBuffer: 64 << 20 }) + : execFileSync('cargo', ['run', '-q', '--', 'predict-trace'], { cwd: SERVER_DIR, maxBuffer: 64 << 20 }); + return JSON.parse(String(out)); +} + +const traces = nativeTraces(); +const DT = Math.fround(1 / 30); + +/** Every generated surface with a predicted step. */ +const surfaces = readdirSync(GENERATED) + .filter((name) => existsSync(new URL(`${name}/predict.ts`, GENERATED))) + .map((name) => { + const surface = JSON.parse(readFileSync(new URL(`${name}/surface.json`, GENERATED), 'utf8')); + return { name, predict: surface.predict }; + }); + +test('every predicting demo has a compiled step and a native trace', () => { + assert.deepEqual(surfaces.map((s) => s.name).sort(), ['arena', 'freeze', 'grid', 'mobpit', 'ripple']); + assert.equal(traces.abi, 1); + for (const { name, predict } of surfaces) { + assert.ok(existsSync(new URL(`${name}/wasm/${name}.wasm`, GENERATED)), `${name}: run \`run.sh gen\``); + assert.ok(traces.steps.some((s) => s.export === predict.export), `${name}: trace for ${predict.export}`); + } + assert.deepEqual( + traces.steps.map((s) => s.export).sort(), + [...new Set(surfaces.map((s) => s.predict.export))].sort(), + 'every traced step is some surface\'s step' + ); +}); + +for (const { name, predict } of surfaces) { + test(`${name}: WASM ${predict.export} matches the native step bit for bit`, async () => { + const module = await PredictModule.load(new URL(`${name}/wasm/${name}.wasm`, GENERATED)); + assert.ok(module.steps.includes(predict.export)); + const trace = traces.steps.find((s) => s.export === predict.export); + assert.equal(trace.kind, predict.kind); + let frames = 0; + for (const stream of trace.streams) { + let state = fromHex(stream.start); + const context = fromHex(stream.context); + stream.inputs.forEach((input, i) => { + state = module.step(predict.export, state, fromHex(input), context, DT); + assert.equal(toHex(state), stream.states[i], `${stream.name} frame ${i}`); + frames += 1; + }); + } + assert.ok(frames > 3000, `${frames} frames compared`); + }); + + test(`${name}: the generated prediction maps entity fields through the step`, async () => { + const generated = await import(`../src/generated/${name}/index.ts`); + const prediction = generated[`create${name[0].toUpperCase()}${name.slice(1)}Prediction`](); + await prediction.ready; + const trace = traces.steps.find((s) => s.export === predict.export); + for (const stream of trace.streams.slice(0, 2)) { + if (generated.PREDICT_CONTEXT !== undefined) { + // The recorded context, decoded with the generated layout. + prediction.setContext(decodePayload(generated.PREDICT_CONTEXT, fromHex(stream.context))); + } + let fields = decodePredictState(generated.PREDICT_STATE, fromHex(stream.start)); + stream.inputs.forEach((input, i) => { + const next = prediction.predict(fields, generated.decodeInput(fromHex(input)), 1000 / 30); + fields = { ...fields, ...next }; + assert.equal(toHex(encodePredictState(generated.PREDICT_STATE, fields)), stream.states[i], `${stream.name} frame ${i}`); + }); + } + }); +} + +test('drawing constants of the Arena floor match the simulation', () => { + assert.equal(floor.HALF, traces.arena.half); + assert.equal(floor.PLAYER_RADIUS, traces.arena.playerRadius); + assert.equal(floor.DASH_COOLDOWN, traces.arena.dashCooldown); + assert.deepEqual(floor.PILLARS.map((p) => [...p]), traces.arena.pillars); +}); + +/** Median of `runs` timings of `fn` (each `iterations` calls), µs per call. */ +function measure(fn, iterations, runs = 7) { + const samples = []; + for (let r = 0; r < runs; r += 1) { + const start = process.hrtime.bigint(); + for (let i = 0; i < iterations; i += 1) fn(i); + samples.push(Number(process.hrtime.bigint() - start) / 1000 / iterations); + } + samples.sort((a, b) => a - b); + return samples[Math.floor(runs / 2)]; +} + +test('cost: one predicted step and a reconciliation replaying 10 inputs at 30 Hz', async () => { + const report = {}; + for (const name of ['arena', 'grid']) { + const generated = await import(`../src/generated/${name}/index.ts`); + const prediction = generated[`create${name[0].toUpperCase()}${name.slice(1)}Prediction`](); + await prediction.ready; + if (name === 'grid') prediction.setContext({ seed: 0x00c0ffee, cx: 3, cy: 2 }); + const kind = { id: 1, name: generated.PREDICT.kind, priority: 1, fields: generated.PREDICT_STATE.map(([field]) => ({ name: field, type: 'f32', priority: 1 })) }; + const start = name === 'grid' ? { x: 16, y: 16 } : { x: -5, y: -5, vx: 0, vy: 0, dash: 0, cd: 0 }; + const input = { mx: 90, my: -40, buttons: 0 }; + + // Raw ABI call (encoded bytes in, bytes out). + const module = prediction.module(); + const stateBytes = encodePredictState(generated.PREDICT_STATE, start); + const inputBytes = generated.encodeInput(input); + const contextBytes = + name === 'grid' ? encodePayload(generated.PREDICT_CONTEXT, prediction.context()) : new Uint8Array(0); + const abiUs = measure(() => module.step(generated.PREDICT.export, stateBytes, inputBytes, contextBytes, DT), 20_000); + // `predict` as GameClient calls it (fields → bytes → step → fields). + const predictUs = measure(() => prediction.predict(start, input, 1000 / 30), 20_000); + + // Reconcile: authoritative Delta + replay of 10 pending inputs. + const predictor = new Predictor({ predict: prediction.predict }); + predictor.bind(7, kind, start); + for (let seq = 1; seq <= 10; seq += 1) predictor.record(seq, input, 1000 / 30); + const reconcileUs = measure((i) => predictor.reconcile(0, start, i), 5_000); + report[name] = { abiUs, predictUs, reconcile10Us: reconcileUs }; + } + // 30 Hz leaves 33 ms per frame; a reconciliation per Delta (20 Hz) plus + // one step per input (30 Hz) must be a rounding error of it. + console.log(`prediction cost (Node ${process.version}, µs, median): ${JSON.stringify(report)}`); + for (const [name, r] of Object.entries(report)) { + assert.ok(r.reconcile10Us < 1000, `${name}: reconcile with 10 pending took ${r.reconcile10Us} µs`); + const perSecondMs = (r.reconcile10Us * 20 + r.predictUs * 30) / 1000; + assert.ok(perSecondMs < 33, `${name}: ${perSecondMs} ms of prediction per second`); + } +}); diff --git a/examples/game/fixtures/grid-world.json b/examples/game/fixtures/grid-world.json index bcd3ef763..3de650df8 100644 --- a/examples/game/fixtures/grid-world.json +++ b/examples/game/fixtures/grid-world.json @@ -1,6 +1,6 @@ { - "description": "Endless Grid parity: Rust grid::world vs client/src/grid/world.ts", - "constants": {"cell":32.0,"contentVersion":1,"hashes":[0,1753845952,3861431939,1734902346],"hysteresis":0.5,"mix":[81375972,3890567552],"playerRadius":0.44999998807907104,"propMargin":2.0,"seed":12648430,"sprint":10.0,"walk":6.0}, + "description": "Endless Grid world-content parity: Rust game_sim::grid vs client/src/grid/world.ts", + "constants": {"cell":32.0,"contentVersion":1,"hashes":[0,1753845952,3861431939,1734902346],"mix":[81375972,3890567552],"propMargin":2.0,"seed":12648430}, "cells": [ {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[0,0],"heights":[0.5932726860046387,0.6191548109054565,0.6287701725959778,0.5684976577758789,0.506608247756958,0.476431667804718,0.4526447653770447,0.40599799156188965,0.3470003008842468,0.5986464619636536,0.6271780133247375,0.6407992243766785,0.5713481307029724,0.499041885137558,0.48792269825935364,0.4807089567184448,0.43712469935417175,0.38371312618255615,0.6058180928230286,0.6377806663513184,0.6576048135757446,0.583746075630188,0.504568338394165,0.50711590051651,0.5085848569869995,0.4628223776817322,0.41231948137283325,0.612625241279602,0.6260185837745667,0.6300536394119263,0.5916079878807068,0.5455343723297119,0.5089141130447388,0.46644169092178345,0.44517818093299866,0.42410480976104736,0.6159852743148804,0.6130355596542358,0.6021124720573425,0.5914559960365295,0.5723928809165955,0.5054858326911926,0.43087658286094666,0.43410351872444153,0.4395725727081299,0.6654882431030273,0.6511151790618896,0.6289829611778259,0.6039171814918518,0.5709450244903564,0.5380295515060425,0.5008229613304138,0.4601622223854065,0.4185706079006195,0.7117636203765869,0.6877931356430054,0.6561192870140076,0.6189549565315247,0.5746230483055115,0.5735785961151123,0.5749499797821045,0.5053251385688782,0.4283277094364166,0.6724258065223694,0.6588683128356934,0.6377082467079163,0.6132182478904724,0.5823083519935608,0.5772964954376221,0.5812021493911743,0.5429924130439758,0.4911908209323883,0.6354392170906067,0.6307666897773743,0.6188353896141052,0.6054155230522156,0.5861055254936218,0.5758660435676575,0.5773574709892273,0.5610383749008179,0.5286053419113159],"moisture":[0.9225814342498779,0.9209369421005249,0.9161432385444641,0.9084103107452393,0.897948145866394,0.8849667310714722,0.8696759343147278,0.8522856831550598,0.833005964756012,0.9203137755393982,0.9186764359474182,0.9139037132263184,0.9062045812606812,0.8957881927490234,0.882863461971283,0.8676395416259766,0.8503252863883972,0.8311298489570618,0.9141969680786133,0.9125790596008301,0.9078628420829773,0.9002548456192017,0.889961838722229,0.8771901726722717,0.8621464371681213,0.8450372815132141,0.8260691165924072,0.9044886827468872,0.9029015302658081,0.8982750177383423,0.8908117413520813,0.880714476108551,0.8681857585906982,0.8534281849861145,0.8366444110870361,0.8180370330810547,0.8914466500282288,0.889900803565979,0.885394811630249,0.8781259655952454,0.8682916760444641,0.8560892343521118,0.8417160511016846,0.8253694176673889,0.8072466850280762,0.8753284811973572,0.8738337755203247,0.8694766759872437,0.8624480366706848,0.8529387712478638,0.8411396741867065,0.8272415399551392,0.8114351630210876,0.7939113974571228,0.8563919067382812,0.8549572229385376,0.8507750630378723,0.8440287113189697,0.8349013328552246,0.8235759735107422,0.8102359771728516,0.7950643301010132,0.7782442569732666,0.834894597530365,0.8335280418395996,0.8295445442199707,0.8231185674667358,0.8144246935844421,0.8036372661590576,0.7909308075904846,0.7764797210693359,0.7604585289955139,0.8110942840576172,0.8098031282424927,0.8060395121574402,0.7999683022499084,0.7917543649673462,0.7815624475479126,0.7695574164390564,0.7559041380882263,0.7407673597335815],"props":[[0,2.6997311115264893,3.5492422580718994,0.5242127180099487,true,19],[0,20.319786071777344,2.439387321472168,0.6280530691146851,true,104],[0,29.571075439453125,4.204550266265869,0.5941054821014404,true,77],[0,28.727685928344727,12.843689918518066,0.5227029919624329,true,18],[2,2.6637513637542725,20.259355545043945,0.5979864001274109,false,100],[0,10.334222793579102,21.184724807739258,0.7090258598327637,true,171],[0,21.481861114501953,20.544662475585938,0.6859129667282104,true,152],[2,27.356979370117188,19.172718048095703,0.7472004294395447,false,253],[0,4.534152030944824,26.57033920288086,0.6718509793281555,true,140],[0,10.943948745727539,27.216060638427734,0.6537189483642578,true,125],[0,21.012920379638672,26.721946716308594,0.7434372901916504,true,199]]}, {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,2,2],"cell":[-1,0],"heights":[0.4879056513309479,0.5361763834953308,0.5719524621963501,0.5911566615104675,0.617572546005249,0.6191596984863281,0.6134335398674011,0.607620894908905,0.5932726860046387,0.4937855303287506,0.5281368494033813,0.5436740517616272,0.5619687438011169,0.5938694477081299,0.6191307902336121,0.6376091241836548,0.6225482821464539,0.5986464619636536,0.5442072153091431,0.559651255607605,0.5435690879821777,0.5464216470718384,0.5757881999015808,0.6204748153686523,0.659502387046814,0.6373487114906311,0.6058180928230286,0.6223092079162598,0.6223706603050232,0.578648030757904,0.555199384689331,0.5708223581314087,0.6146619319915771,0.6540663242340088,0.6381969451904297,0.612625241279602,0.6648482084274292,0.6553021669387817,0.5970399975776672,0.5603602528572083,0.5680696964263916,0.6101231575012207,0.6485512256622314,0.6369460225105286,0.6159852743148804,0.6821573376655579,0.6640446186065674,0.6098151803016663,0.6010086536407471,0.6244459748268127,0.6555972099304199,0.6784183979034424,0.6735973358154297,0.6654882431030273,0.6619725227355957,0.6480416059494019,0.6232592463493347,0.6636747717857361,0.7115744948387146,0.7276552319526672,0.7254219651222229,0.7144866585731506,0.7117636203765869,0.6366078853607178,0.6480674147605896,0.6731057167053223,0.7349919676780701,0.7804715633392334,0.7645105123519897,0.720649778842926,0.6868299841880798,0.6724258065223694,0.6471416354179382,0.6704965233802795,0.7175806760787964,0.7777050733566284,0.8118277192115784,0.7723835110664368,0.701501190662384,0.6561596989631653,0.6354392170906067],"moisture":[0.8806808590888977,0.8896992802619934,0.8978338837623596,0.9049864411354065,0.9110587239265442,0.9159526228904724,0.9195698499679565,0.921812117099762,0.9225814342498779,0.8787924647331238,0.887729287147522,0.8957902789115906,0.9028780460357666,0.9088953733444214,0.9137449860572815,0.9173294305801392,0.919551432132721,0.9203137755393982,0.8736987709999084,0.8824153542518616,0.8902777433395386,0.8971908688545227,0.9030599594116211,0.9077900052070618,0.9112861752510071,0.9134534597396851,0.9141969680786133,0.8656143546104431,0.8739814162254333,0.8815285563468933,0.8881644606590271,0.8937982320785522,0.8983386158943176,0.9016945958137512,0.9037749767303467,0.9044886827468872,0.8547537326812744,0.8626512885093689,0.8697749376296997,0.8760384917259216,0.8813560605049133,0.8856416940689087,0.888809323310852,0.8907729983329773,0.8914466500282288,0.8413316011428833,0.8486488461494446,0.8552490472793579,0.861052393913269,0.8659793138504028,0.8699500560760498,0.87288498878479,0.8747043013572693,0.8753284811973572,0.8255624175071716,0.8321979641914368,0.8381832242012024,0.843445897102356,0.8479138016700745,0.8515145778656006,0.8541760444641113,0.8558259010314941,0.8563919067382812,0.8076608180999756,0.813522458076477,0.8188096284866333,0.8234584927558899,0.8274052739143372,0.8305861353874207,0.8329371809959412,0.8343945741653442,0.834894597530365,0.7878413796424866,0.7928462028503418,0.7973605394363403,0.8013298511505127,0.8046996593475342,0.8074155449867249,0.8094229698181152,0.8106673359870911,0.8110942840576172],"props":[[0,19.097110748291016,5.61630916595459,0.6776201128959656,true,145],[0,26.24727439880371,5.479523658752441,0.6100752949714661,true,90],[0,5.130196571350098,11.272446632385254,0.6444254517555237,true,118],[0,19.86644744873047,12.887415885925293,0.5775140523910522,true,63],[0,29.14185333251953,11.574310302734375,0.7816622257232666,true,230],[0,4.698641777038574,18.850263595581055,0.7559527158737183,true,209],[2,11.599629402160645,20.818233489990234,0.6331537365913391,false,136],[1,27.429126739501953,21.335290908813477,0.8450204133987427,true,150],[0,4.095309257507324,27.893505096435547,0.5584002733230591,true,47],[1,21.594541549682617,29.985082626342773,0.9263221025466919,true,205]]}, @@ -8,6 +8,5 @@ {"biomes":[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],"cell":[3,-7],"heights":[0.44168463349342346,0.4462580978870392,0.4758754372596741,0.5119243860244751,0.5240926146507263,0.5060517191886902,0.47019070386886597,0.4644808769226074,0.48008018732070923,0.43155404925346375,0.47093355655670166,0.5339734554290771,0.5748621821403503,0.5923664569854736,0.5602777600288391,0.5095936059951782,0.48983877897262573,0.48950710892677307,0.42734962701797485,0.4953855872154236,0.5845286846160889,0.627734899520874,0.6492524147033691,0.6065821051597595,0.5449163913726807,0.5144485235214233,0.5012316703796387,0.4742732644081116,0.5199416875839233,0.5842570066452026,0.618760347366333,0.6332355737686157,0.6235742568969727,0.5945666432380676,0.557242214679718,0.5351199507713318,0.5101231336593628,0.5382350087165833,0.5838687419891357,0.6132137775421143,0.6229410171508789,0.6408824920654297,0.6388668417930603,0.5955400466918945,0.5658830404281616,0.49519073963165283,0.5091087818145752,0.5367494225502014,0.5691434144973755,0.5851179361343384,0.6196902394294739,0.6370555758476257,0.6121094822883606,0.5962793827056885,0.45497655868530273,0.4533257484436035,0.457935631275177,0.484584242105484,0.5018151998519897,0.5534920692443848,0.5944374203681946,0.5922531485557556,0.5913298726081848,0.36176007986068726,0.3889848589897156,0.4152972102165222,0.4129660129547119,0.40809959173202515,0.47236132621765137,0.532341718673706,0.5400242209434509,0.5416451692581177,0.30415835976600647,0.3565188944339752,0.40500175952911377,0.3831290006637573,0.3615923523902893,0.43301910161972046,0.5028873085975647,0.5131760239601135,0.5143986940383911],"moisture":[0.5350773930549622,0.5283440351486206,0.5222705602645874,0.5169302821159363,0.5123965740203857,0.5087426900863647,0.5060420036315918,0.5043678283691406,0.503793478012085,0.5299458503723145,0.5241599678993225,0.5189410448074341,0.5143522024154663,0.510456383228302,0.5073166489601135,0.5049960017204285,0.5035573840141296,0.5030638575553894,0.5244593024253845,0.5196864604949951,0.5153812170028687,0.5115957856178284,0.5083820819854736,0.5057920217514038,0.5038776993751526,0.5026909112930298,0.5022838115692139,0.518669068813324,0.5149652361869812,0.5116243362426758,0.5086867809295654,0.5061928629875183,0.5041829943656921,0.5026974081993103,0.5017764568328857,0.5014605522155762,0.5126261711120605,0.5100380778312683,0.5077035427093506,0.5056508779525757,0.5039082169532776,0.5025037527084351,0.5014656782150269,0.500822126865387,0.5006013512611389,0.5063818693161011,0.5049466490745544,0.503652036190033,0.5025137066841125,0.5015473365783691,0.5007684826850891,0.5001928210258484,0.4998359680175781,0.4997135400772095,0.49998724460601807,0.4997326731681824,0.4995030164718628,0.49930107593536377,0.49912965297698975,0.4989914894104004,0.49888938665390015,0.4988260567188263,0.49880436062812805,0.4934934973716736,0.4944378733634949,0.49528968334198,0.49603864550590515,0.49667447805404663,0.49718692898750305,0.49756571650505066,0.4978005290031433,0.49788105487823486,0.4869517982006073,0.4891039729118347,0.491045206785202,0.4927521049976349,0.4942012131214142,0.4953690767288208,0.4962323009967804,0.49676740169525146,0.4969509541988373],"props":[[0,26.579748153686523,4.767230987548828,0.7743046283721924,true,224],[2,3.260620594024658,10.087486267089844,0.6818166971206665,false,186],[1,28.662282943725586,11.022789001464844,0.74249666929245,true,80],[0,26.725576400756836,18.9808406829834,0.5057967305183411,true,4]]}, {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3],"cell":[-12,5],"heights":[0.5121973752975464,0.4823082387447357,0.46220675110816956,0.5112564563751221,0.5501552820205688,0.4872822165489197,0.38883817195892334,0.31799912452697754,0.28261008858680725,0.4805338978767395,0.44521087408065796,0.4195011556148529,0.47392895817756653,0.5189605951309204,0.4671037197113037,0.39131978154182434,0.3571542799472809,0.3469882309436798,0.41997605562210083,0.37975943088531494,0.3484508991241455,0.4063468873500824,0.45611312985420227,0.42487290501594543,0.3929973244667053,0.4145159125328064,0.43692919611930847,0.3330213129520416,0.31364208459854126,0.3024783134460449,0.3571169674396515,0.40484189987182617,0.38624680042266846,0.38952183723449707,0.4628981053829193,0.5148381590843201,0.2848259508609772,0.2832028865814209,0.2896556258201599,0.3422389626502991,0.38851577043533325,0.3728458285331726,0.388386994600296,0.4877353012561798,0.5564621090888977,0.2816266715526581,0.2867536246776581,0.2998877167701721,0.3233092427253723,0.34088629484176636,0.35961490869522095,0.4112788140773773,0.5053136944770813,0.5671341419219971,0.2767845094203949,0.28718429803848267,0.3051665127277374,0.303689569234848,0.29709380865097046,0.34592780470848083,0.4310455322265625,0.5240169763565063,0.5815257430076599,0.3178563117980957,0.3185093402862549,0.32627564668655396,0.3392178416252136,0.3477005958557129,0.3815544545650482,0.45490309596061707,0.5379451513290405,0.582377016544342,0.35266175866127014,0.3454577326774597,0.34513136744499207,0.3703245520591736,0.3913551867008209,0.41152533888816833,0.47250428795814514,0.5445654988288879,0.576723039150238],"moisture":[0.8263142704963684,0.825194776058197,0.8219315409660339,0.8166675567626953,0.809545636177063,0.8007087707519531,0.7902998328208923,0.778461754322052,0.7653374671936035,0.8096745014190674,0.8085733652114868,0.805363655090332,0.8001859188079834,0.7931808233261108,0.7844889163970947,0.7742506861686707,0.7626067399978638,0.7496976852416992,0.7918837666511536,0.7908022403717041,0.7876497507095337,0.7825644016265869,0.7756841778755188,0.7671471834182739,0.7570914626121521,0.7456550598144531,0.7329761981964111,0.7731080055236816,0.772047221660614,0.7689551115036011,0.7639671564102173,0.7572187185287476,0.7488452792167664,0.7389822006225586,0.7277648448944092,0.7153288125991821,0.7535130977630615,0.7524739503860474,0.749444842338562,0.744558572769165,0.7379477024078369,0.7297449111938477,0.7200828194618225,0.7090941667556763,0.6969115734100342,0.7332649827003479,0.7322481870651245,0.7292842268943787,0.7245029807090759,0.7180342078208923,0.7100077867507935,0.7005534172058105,0.6898009777069092,0.6778803467750549,0.7125295400619507,0.7115355730056763,0.7086383104324341,0.7039646506309509,0.6976414918899536,0.6897956132888794,0.6805540323257446,0.6700435280799866,0.6583910584449768,0.6914726495742798,0.6905019283294678,0.6876724362373352,0.6831079721450806,0.6769325733184814,0.6692701578140259,0.6602445840835571,0.6499797701835632,0.638599693775177,0.6702602505683899,0.6693129539489746,0.6665516495704651,0.6620972752571106,0.6560707688331604,0.6485930681228638,0.63978511095047,0.6297678351402283,0.6186621189117432],"props":[[0,2.650817632675171,4.8241119384765625,0.6354243159294128,true,110],[2,11.57477855682373,4.872535705566406,0.7331044673919678,false,238],[0,28.03809928894043,4.916660308837891,0.578079342842102,true,63],[2,4.669862270355225,11.890331268310547,0.5852758288383484,false,87],[0,10.483098983764648,11.758493423461914,0.564202606678009,true,52],[0,19.052648544311523,11.650245666503906,0.6284025311470032,true,105],[0,28.663318634033203,11.259580612182617,0.7930710315704346,true,240],[0,5.82761287689209,19.1566104888916,0.5523130893707275,true,42],[0,10.243107795715332,19.25455093383789,0.6117123365402222,true,91],[0,2.6146390438079834,29.77297592163086,0.5455815196037292,true,37],[0,12.799676895141602,28.633228302001953,0.6608912348747253,true,131],[0,19.269079208374023,28.336078643798828,0.5150197744369507,true,12]]}, {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[999999,-1000000],"heights":[0.5270935297012329,0.5743997693061829,0.5953944325447083,0.5239696502685547,0.4753807783126831,0.5279929041862488,0.5514862537384033,0.5003933310508728,0.4679919481277466,0.5375649333000183,0.572934091091156,0.5820469260215759,0.5309256315231323,0.5026796460151672,0.5419862866401672,0.5614850521087646,0.513027548789978,0.474234402179718,0.5374559164047241,0.5614643096923828,0.5593416094779968,0.5240475535392761,0.5117505788803101,0.5481477379798889,0.5835541486740112,0.5567929744720459,0.5216204524040222,0.5208446979522705,0.5216416120529175,0.49646323919296265,0.46929264068603516,0.4653409719467163,0.5247509479522705,0.6015294790267944,0.6190511584281921,0.6109352111816406,0.5109962224960327,0.49113374948501587,0.44546449184417725,0.42380237579345703,0.42567700147628784,0.49693557620048523,0.5935209393501282,0.6337533593177795,0.6418488621711731,0.4949389100074768,0.4840001165866852,0.45257842540740967,0.4334706664085388,0.4331486225128174,0.4797436594963074,0.5479856133460999,0.6027395725250244,0.6307550072669983,0.4766243100166321,0.47689566016197205,0.4672740697860718,0.46044427156448364,0.46244776248931885,0.48313599824905396,0.5174170732498169,0.5744072794914246,0.6146253943443298,0.4837564527988434,0.4784761071205139,0.4735533893108368,0.498298704624176,0.5223067998886108,0.5017102360725403,0.4870026409626007,0.5422952175140381,0.5905597805976868,0.49135950207710266,0.4768757224082947,0.4670783579349518,0.5093743205070496,0.5473048686981201,0.4947369694709778,0.44537153840065,0.5052690505981445,0.5629271864891052],"moisture":[0.8571391701698303,0.8770757913589478,0.8950584530830383,0.9108702540397644,0.9242939352989197,0.9351125359535217,0.943108856678009,0.9480658769607544,0.9497664570808411,0.8566534519195557,0.8765634298324585,0.8945221900939941,0.9103129506111145,0.9237187504768372,0.9345229268074036,0.9425086379051208,0.9474590420722961,0.9491572976112366,0.8553431630134583,0.8751815557479858,0.893075704574585,0.9088096022605896,0.922167181968689,0.9329325556755066,0.9408894777297974,0.9458220601081848,0.9475142955780029,0.8532635569572449,0.8729882836341858,0.8907799124717712,0.9064236283302307,0.9197046756744385,0.9304082989692688,0.9383196830749512,0.9432240128517151,0.9449065327644348,0.8504698276519775,0.8700418472290039,0.8876957297325134,0.9032183289527893,0.9163965582847595,0.927017331123352,0.9348674416542053,0.9397338032722473,0.9414032697677612,0.847017228603363,0.8664004802703857,0.883884072303772,0.8992570638656616,0.9123081564903259,0.9228265285491943,0.9306009411811829,0.9354203343391418,0.9370737075805664,0.8429608345031738,0.8621223568916321,0.8794059753417969,0.8946030735969543,0.9075048565864563,0.9179028868675232,0.9255883693695068,0.9303526878356934,0.9319871068000793,0.8383559584617615,0.8572657108306885,0.8743222951889038,0.8893197178840637,0.9020520448684692,0.9123134613037109,0.9198979735374451,0.9245997071266174,0.9262126684188843,0.8332576751708984,0.8518888354301453,0.868694007396698,0.8834704160690308,0.8960150480270386,0.9061252474784851,0.9135980010032654,0.918230414390564,0.9198196530342102],"props":[[0,3.1682724952697754,2.740854263305664,0.7206481695175171,true,180],[0,10.771486282348633,2.1860263347625732,0.5887128710746765,true,72],[0,21.956050872802734,3.2204477787017822,0.779129147529602,true,228],[0,13.399469375610352,10.174410820007324,0.5151387453079224,true,12],[0,21.344093322753906,10.719156265258789,0.5965613126754761,true,79],[0,29.304264068603516,11.698976516723633,0.7484042644500732,true,203],[0,2.3951516151428223,26.584388732910156,0.7904362678527832,true,237],[0,18.772125244140625,28.845848083496094,0.5168313980102539,true,13],[0,27.48282241821289,26.896862030029297,0.5896564722061157,true,73]]} - ], - "walk": {"cell":[6,2],"start":[16.0,16.0],"steps":[{"input":[79,-128,1],"x":16.176055908203125,"y":15.717009544372559},{"input":[79,-128,1],"x":16.352205276489258,"y":15.433927536010742},{"input":[79,-128,1],"x":16.528352737426758,"y":15.150845527648926},{"input":[80,-128,1],"x":16.705965042114258,"y":14.868861198425293},{"input":[80,-128,1],"x":16.88357925415039,"y":14.586877822875977},{"input":[80,-128,1],"x":17.06119155883789,"y":14.30489444732666},{"input":[80,-128,1],"x":17.23880386352539,"y":14.022911071777344},{"input":[81,-128,1],"x":17.418066024780273,"y":13.741843223571777},{"input":[81,-128,1],"x":17.597326278686523,"y":13.460775375366211},{"input":[81,-128,1],"x":17.776588439941406,"y":13.179707527160645},{"input":[82,-128,1],"x":17.957313537597656,"y":12.899738311767578},{"input":[82,-128,1],"x":18.138038635253906,"y":12.619768142700195},{"input":[82,-128,1],"x":18.31876564025879,"y":12.339798927307129},{"input":[83,-128,1],"x":18.50113868713379,"y":12.060745239257812},{"input":[83,-128,1],"x":18.68351173400879,"y":11.781691551208496},{"input":[83,-128,1],"x":18.865886688232422,"y":11.50263786315918},{"input":[84,-128,1],"x":19.049724578857422,"y":11.224682807922363},{"input":[84,-128,1],"x":19.233562469482422,"y":10.946727752685547},{"input":[85,-128,1],"x":19.419050216674805,"y":10.66968822479248},{"input":[85,-128,1],"x":19.604536056518555,"y":10.392648696899414},{"input":[86,-128,1],"x":19.791488647460938,"y":10.116706848144531},{"input":[86,-128,1],"x":19.978439331054688,"y":9.840765953063965},{"input":[87,-128,1],"x":20.166854858398438,"y":9.565740585327148},{"input":[87,-128,1],"x":20.35527229309082,"y":9.290715217590332},{"input":[88,-128,1],"x":20.54515266418457,"y":9.016788482666016},{"input":[88,-128,1],"x":20.73503303527832,"y":8.7428617477417},{"input":[89,-128,1],"x":20.926380157470703,"y":8.469850540161133},{"input":[90,-128,1],"x":21.119190216064453,"y":8.197937965393066},{"input":[91,-128,1],"x":21.313283920288086,"y":7.926940441131592},{"input":[91,-128,1],"x":21.507375717163086,"y":7.655943393707275},{"input":[92,-128,1],"x":21.702932357788086,"y":7.386044979095459},{"input":[93,-128,1],"x":21.89995574951172,"y":7.117062091827393},{"input":[94,-128,1],"x":22.09825897216797,"y":6.849177837371826},{"input":[95,-128,1],"x":22.2978458404541,"y":6.58220911026001},{"input":[96,-128,1],"x":22.4988956451416,"y":6.316339015960693},{"input":[98,-128,1],"x":22.7025089263916,"y":6.052482604980469},{"input":[99,-128,1],"x":22.907405853271484,"y":5.789542198181152},{"input":[101,-128,1],"x":23.114864349365234,"y":5.528615951538086},{"input":[102,-128,1],"x":23.323606491088867,"y":5.2687883377075195},{"input":[104,-128,1],"x":23.534727096557617,"y":5.010974884033203},{"input":[106,-128,1],"x":23.748228073120117,"y":4.754992485046387},{"input":[109,-128,1],"x":23.96539306640625,"y":4.50212287902832},{"input":[111,-128,1],"x":24.18475341796875,"y":4.251084327697754},{"input":[115,-128,1],"x":24.408510208129883,"y":4.0040740966796875},{"input":[118,-128,1],"x":24.635377883911133,"y":3.759810447692871},{"input":[122,-128,1],"x":24.745058059692383,"y":3.535871744155884},{"input":[125,-128,1],"x":24.734071731567383,"y":3.2868473529815674},{"input":[126,-128,1],"x":24.778202056884766,"y":2.999919891357422},{"input":[122,-128,1],"x":24.896854400634766,"y":2.6990764141082764},{"input":[111,-128,1],"x":25.090946197509766,"y":2.42514967918396},{"input":[93,-128,1],"x":25.2879695892334,"y":2.1561665534973145},{"input":[71,-128,1],"x":25.4505672454834,"y":1.865211009979248},{"input":[51,-128,1],"x":25.5747127532959,"y":1.5559446811676025},{"input":[36,-128,1],"x":25.6655330657959,"y":1.235325813293457},{"input":[25,-128,1],"x":25.7299861907959,"y":0.908298134803772},{"input":[19,-128,1],"x":25.77924346923828,"y":0.5787070393562317},{"input":[14,-128,1],"x":25.81568145751953,"y":0.2474679797887802},{"input":[11,-128,1],"x":25.84442901611328,"y":-0.08468659967184067},{"input":[9,-128,1],"x":25.86804962158203,"y":-0.41720739006996155},{"input":[8,-128,1],"x":25.88892364501953,"y":-0.7499113082885742},{"input":[-94,84,0],"x":25.7409725189209,"y":-0.617708683013916},{"input":[-94,84,0],"x":25.5930233001709,"y":-0.48550599813461304},{"input":[-94,84,0],"x":25.4450740814209,"y":-0.35330334305763245},{"input":[-94,84,0],"x":25.2971248626709,"y":-0.22110070288181305},{"input":[-94,84,0],"x":25.149173736572266,"y":-0.08889804780483246},{"input":[-94,84,0],"x":25.001224517822266,"y":0.04330460727214813},{"input":[-94,84,0],"x":24.853275299072266,"y":0.17550726234912872},{"input":[-94,84,0],"x":24.705324172973633,"y":0.3077099025249481},{"input":[-94,84,0],"x":24.557374954223633,"y":0.4399125576019287},{"input":[-94,84,0],"x":24.409425735473633,"y":0.5721152424812317},{"input":[-94,84,0],"x":24.261476516723633,"y":0.7043178677558899},{"input":[-94,84,0],"x":24.113525390625,"y":0.8365205526351929},{"input":[-94,84,0],"x":23.965576171875,"y":0.9687231779098511},{"input":[-94,84,0],"x":23.817626953125,"y":1.1009258031845093},{"input":[-94,84,0],"x":23.669675827026367,"y":1.2331284284591675},{"input":[-94,84,0],"x":23.521726608276367,"y":1.3653311729431152},{"input":[-94,84,0],"x":23.373777389526367,"y":1.4975337982177734},{"input":[-94,84,0],"x":23.225826263427734,"y":1.6297364234924316},{"input":[-94,84,0],"x":23.077877044677734,"y":1.7619390487670898},{"input":[-94,84,0],"x":22.929927825927734,"y":1.8941417932510376},{"input":[-94,84,0],"x":22.781978607177734,"y":2.0263442993164062},{"input":[-94,84,0],"x":22.6340274810791,"y":2.1585471630096436},{"input":[-94,84,0],"x":22.4860782623291,"y":2.2907497882843018},{"input":[-94,84,0],"x":22.3381290435791,"y":2.42295241355896},{"input":[-94,84,0],"x":22.19017791748047,"y":2.555155038833618},{"input":[-94,84,0],"x":22.04222869873047,"y":2.6873576641082764},{"input":[-94,84,0],"x":21.89427947998047,"y":2.8195602893829346},{"input":[-94,84,0],"x":21.746328353881836,"y":2.9517629146575928},{"input":[-94,84,0],"x":21.598379135131836,"y":3.083965539932251},{"input":[-94,84,0],"x":21.450429916381836,"y":3.216168165206909},{"input":[-94,84,0],"x":21.302480697631836,"y":3.3483710289001465},{"input":[-94,84,0],"x":21.154529571533203,"y":3.4805736541748047},{"input":[-94,84,0],"x":21.006580352783203,"y":3.612776279449463},{"input":[-94,84,0],"x":20.858631134033203,"y":3.744978904724121},{"input":[-94,84,0],"x":20.71068000793457,"y":3.8771815299987793},{"input":[-94,84,0],"x":20.56273078918457,"y":4.0093841552734375},{"input":[-94,84,0],"x":20.41478157043457,"y":4.141586780548096},{"input":[-94,84,0],"x":20.26683235168457,"y":4.273789405822754},{"input":[-94,84,0],"x":20.118881225585938,"y":4.405992031097412},{"input":[-94,84,0],"x":19.970932006835938,"y":4.53819465637207},{"input":[-94,84,0],"x":19.822982788085938,"y":4.6703972816467285},{"input":[-94,84,0],"x":19.675031661987305,"y":4.802599906921387},{"input":[-94,84,0],"x":19.527082443237305,"y":4.934802532196045},{"input":[-94,84,0],"x":19.379133224487305,"y":5.067005634307861},{"input":[-94,84,0],"x":19.231182098388672,"y":5.1992082595825195},{"input":[-94,84,0],"x":19.083232879638672,"y":5.331410884857178},{"input":[-94,84,0],"x":18.935283660888672,"y":5.463613510131836},{"input":[-94,84,0],"x":18.787334442138672,"y":5.595816135406494},{"input":[-94,84,0],"x":18.63938331604004,"y":5.728018760681152},{"input":[-94,84,0],"x":18.49143409729004,"y":5.8602213859558105},{"input":[-94,84,0],"x":18.34348487854004,"y":5.992424011230469},{"input":[-94,84,0],"x":18.195533752441406,"y":6.124626636505127},{"input":[-94,84,0],"x":18.047584533691406,"y":6.256829261779785},{"input":[-94,84,0],"x":17.899635314941406,"y":6.389031887054443},{"input":[-94,84,0],"x":17.751686096191406,"y":6.521234512329102},{"input":[-94,84,0],"x":17.603734970092773,"y":6.65343713760376},{"input":[-94,84,0],"x":17.455785751342773,"y":6.785639762878418},{"input":[-94,84,0],"x":17.307836532592773,"y":6.917842388153076},{"input":[-94,84,0],"x":17.15988540649414,"y":7.050045013427734},{"input":[-94,84,0],"x":17.01193618774414,"y":7.182247638702393},{"input":[112,59,1],"x":17.305822372436523,"y":7.337155818939209},{"input":[112,59,1],"x":17.599706649780273,"y":7.492063522338867},{"input":[112,59,1],"x":17.893592834472656,"y":7.646971225738525},{"input":[112,59,1],"x":18.187477111816406,"y":7.801878929138184},{"input":[112,59,1],"x":18.48136329650879,"y":7.956787109375},{"input":[112,59,1],"x":18.775249481201172,"y":8.1116943359375},{"input":[112,59,1],"x":19.069133758544922,"y":8.266602516174316},{"input":[112,59,1],"x":19.363019943237305,"y":8.421510696411133},{"input":[112,59,1],"x":19.656904220581055,"y":8.576417922973633},{"input":[112,59,1],"x":19.950790405273438,"y":8.73132610321045},{"input":[112,59,1],"x":20.244674682617188,"y":8.886234283447266},{"input":[112,59,1],"x":20.53856086730957,"y":9.041141510009766},{"input":[112,59,1],"x":20.832447052001953,"y":9.196049690246582},{"input":[112,59,1],"x":21.126331329345703,"y":9.350956916809082},{"input":[112,59,1],"x":21.420217514038086,"y":9.505865097045898},{"input":[112,59,1],"x":21.714101791381836,"y":9.660773277282715},{"input":[112,59,1],"x":22.00798797607422,"y":9.815680503845215},{"input":[112,59,1],"x":22.3018741607666,"y":9.970588684082031},{"input":[112,59,1],"x":22.59575843811035,"y":10.125496864318848},{"input":[112,59,1],"x":22.889644622802734,"y":10.280404090881348},{"input":[112,59,1],"x":23.183528900146484,"y":10.435312271118164},{"input":[112,59,1],"x":23.477415084838867,"y":10.590219497680664},{"input":[112,59,1],"x":23.77130126953125,"y":10.74512767791748},{"input":[112,59,1],"x":24.065185546875,"y":10.900035858154297},{"input":[112,59,1],"x":24.359071731567383,"y":11.054943084716797},{"input":[112,59,1],"x":24.652956008911133,"y":11.209851264953613},{"input":[111,59,1],"x":24.944278717041016,"y":11.364758491516113},{"input":[111,59,1],"x":25.235599517822266,"y":11.51966667175293},{"input":[111,59,1],"x":25.52692222595215,"y":11.674574851989746},{"input":[111,59,1],"x":25.81824493408203,"y":11.829482078552246},{"input":[111,59,1],"x":26.10956573486328,"y":11.984390258789062},{"input":[111,60,1],"x":26.400888442993164,"y":12.141861915588379},{"input":[111,59,1],"x":26.692209243774414,"y":12.296769142150879},{"input":[111,60,1],"x":26.983531951904297,"y":12.454240798950195},{"input":[111,59,1],"x":27.198131561279297,"y":12.567949295043945},{"input":[111,60,1],"x":27.197582244873047,"y":12.569047927856445},{"input":[111,59,1],"x":27.198314666748047,"y":12.567766189575195},{"input":[111,60,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[111,60,1],"x":27.197765350341797,"y":12.568498611450195},{"input":[111,60,1],"x":27.197216033935547,"y":12.569780349731445},{"input":[111,59,1],"x":27.197765350341797,"y":12.568681716918945},{"input":[111,60,1],"x":27.197032928466797,"y":12.570146560668945},{"input":[112,59,1],"x":27.198314666748047,"y":12.567583084106445},{"input":[-121,-128,0],"x":27.060436248779297,"y":12.422746658325195},{"input":[-121,-128,0],"x":26.922557830810547,"y":12.277909278869629},{"input":[-121,-128,0],"x":26.784679412841797,"y":12.133072853088379},{"input":[-121,-128,0],"x":26.646799087524414,"y":11.988235473632812},{"input":[-120,-128,0],"x":26.509469985961914,"y":11.842848777770996},{"input":[-120,-128,0],"x":26.372140884399414,"y":11.697463035583496},{"input":[-120,-128,0],"x":26.23480987548828,"y":11.55207633972168},{"input":[-119,-128,0],"x":26.09803009033203,"y":11.40614128112793},{"input":[-119,-128,0],"x":25.96125030517578,"y":11.260205268859863},{"input":[-119,-128,0],"x":25.82447052001953,"y":11.114269256591797},{"input":[-118,-128,0],"x":25.68842124938965,"y":10.967784881591797},{"input":[-118,-128,0],"x":25.5523738861084,"y":10.82129955291748},{"input":[-118,-128,0],"x":25.41632652282715,"y":10.67481517791748},{"input":[-117,-128,0],"x":25.28082847595215,"y":10.527780532836914},{"input":[-117,-128,0],"x":25.145328521728516,"y":10.380746841430664},{"input":[-116,-128,0],"x":25.010379791259766,"y":10.233162879943848},{"input":[-116,-128,0],"x":24.875431060791016,"y":10.085578918457031},{"input":[-116,-128,0],"x":24.740480422973633,"y":9.937995910644531},{"input":[-115,-128,0],"x":24.606264114379883,"y":9.789679527282715},{"input":[-115,-128,0],"x":24.472047805786133,"y":9.641364097595215},{"input":[-114,-128,0],"x":24.338380813598633,"y":9.492498397827148},{"input":[-114,-128,0],"x":24.2047119140625,"y":9.343632698059082},{"input":[-113,-128,0],"x":24.07177734375,"y":9.194218635559082},{"input":[-113,-128,0],"x":23.9388427734375,"y":9.044803619384766},{"input":[-112,-128,0],"x":23.806640625,"y":8.894840240478516},{"input":[-112,-128,0],"x":23.674436569213867,"y":8.74487590789795},{"input":[-111,-128,0],"x":23.542783737182617,"y":8.594362258911133},{"input":[-111,-128,0],"x":23.411130905151367,"y":8.443849563598633},{"input":[-110,-128,0],"x":23.280210494995117,"y":8.292603492736816},{"input":[-110,-128,0],"x":23.149288177490234,"y":8.141358375549316},{"input":[-109,-128,0],"x":23.019100189208984,"y":7.98956298828125},{"input":[-109,-128,0],"x":22.888912200927734,"y":7.837768077850342},{"input":[-108,-128,0],"x":22.759273529052734,"y":7.685423374176025},{"input":[-107,-128,0],"x":22.6303653717041,"y":7.532529830932617},{"input":[-107,-128,0],"x":22.5014591217041,"y":7.379636287689209},{"input":[-106,-128,0],"x":22.3732852935791,"y":7.226010322570801},{"input":[-106,-128,0],"x":22.24510955810547,"y":7.072384357452393},{"input":[-105,-128,0],"x":22.11766815185547,"y":6.918208599090576},{"input":[-104,-128,0],"x":21.99095916748047,"y":6.763484001159668},{"input":[-104,-128,0],"x":21.86425018310547,"y":6.60875940322876},{"input":[-103,-128,0],"x":21.738271713256836,"y":6.453485488891602},{"input":[-102,-128,0],"x":21.613027572631836,"y":6.297478675842285},{"input":[-102,-128,0],"x":21.487783432006836,"y":6.141472339630127},{"input":[-101,-128,0],"x":21.363271713256836,"y":5.984916687011719},{"input":[-100,-128,0],"x":21.239490509033203,"y":5.8278117179870605},{"input":[-100,-128,0],"x":21.115711212158203,"y":5.670706272125244},{"input":[-99,-128,0],"x":20.992664337158203,"y":5.513051986694336},{"input":[-98,-128,0],"x":20.870532989501953,"y":5.354665279388428},{"input":[-97,-128,0],"x":20.74913215637207,"y":5.1957292556762695},{"input":[-97,-128,0],"x":20.62773323059082,"y":5.036792755126953},{"input":[-96,-128,0],"x":20.50706672668457,"y":4.877307415008545},{"input":[-95,-128,0],"x":20.38731575012207,"y":4.717089653015137},{"input":[-94,-128,0],"x":20.26829719543457,"y":4.55632209777832},{"input":[-94,-128,0],"x":20.149276733398438,"y":4.395555019378662},{"input":[-93,-128,0],"x":20.031173706054688,"y":4.234238624572754},{"input":[-92,-128,0],"x":19.913803100585938,"y":4.072189807891846},{"input":[-91,-128,0],"x":19.797348022460938,"y":3.9095914363861084},{"input":[-91,-128,0],"x":19.680891036987305,"y":3.746993064880371},{"input":[-90,-128,0],"x":19.565168380737305,"y":3.583845376968384},{"input":[-89,-128,0],"x":19.450361251831055,"y":3.4201486110687256},{"input":[35,121,1],"x":19.542280197143555,"y":3.737654685974121},{"input":[35,121,1],"x":19.634199142456055,"y":4.0551605224609375},{"input":[35,121,1],"x":19.726118087768555,"y":4.372666835784912},{"input":[35,121,1],"x":19.818038940429688,"y":4.690173149108887},{"input":[35,121,1],"x":19.909957885742188,"y":5.007678985595703},{"input":[35,121,1],"x":20.001876831054688,"y":5.325185298919678},{"input":[35,121,1],"x":20.093795776367188,"y":5.642691135406494},{"input":[35,121,1],"x":20.185714721679688,"y":5.960197448730469},{"input":[35,121,1],"x":20.27763557434082,"y":6.277703285217285},{"input":[35,121,1],"x":20.36955451965332,"y":6.59520959854126},{"input":[35,121,1],"x":20.46147346496582,"y":6.912715435028076},{"input":[35,121,1],"x":20.55339241027832,"y":7.230221748352051},{"input":[35,121,1],"x":20.64531135559082,"y":7.547727584838867},{"input":[35,121,1],"x":20.73723030090332,"y":7.865233898162842},{"input":[35,121,1],"x":20.829151153564453,"y":8.182740211486816},{"input":[35,121,1],"x":20.921070098876953,"y":8.500246047973633},{"input":[35,121,1],"x":21.012989044189453,"y":8.81775188446045},{"input":[35,121,1],"x":21.104907989501953,"y":9.135258674621582},{"input":[35,121,1],"x":21.196826934814453,"y":9.452764511108398},{"input":[35,121,1],"x":21.288747787475586,"y":9.770270347595215},{"input":[35,121,1],"x":21.380666732788086,"y":10.087776184082031},{"input":[35,121,1],"x":21.472585678100586,"y":10.405282974243164},{"input":[35,121,1],"x":21.564504623413086,"y":10.72278881072998},{"input":[35,121,1],"x":21.656423568725586,"y":11.040294647216797},{"input":[35,121,1],"x":21.748342514038086,"y":11.357800483703613},{"input":[35,121,1],"x":21.84026336669922,"y":11.675307273864746},{"input":[35,121,1],"x":21.93218231201172,"y":11.992813110351562},{"input":[35,121,1],"x":22.02410125732422,"y":12.310318946838379},{"input":[35,121,1],"x":22.11602020263672,"y":12.627825736999512},{"input":[35,121,1],"x":22.20793914794922,"y":12.945331573486328},{"input":[35,121,1],"x":22.29986000061035,"y":13.262837409973145},{"input":[35,121,1],"x":22.39177894592285,"y":13.580343246459961},{"input":[35,121,1],"x":22.48369789123535,"y":13.897850036621094},{"input":[35,121,1],"x":22.57561683654785,"y":14.21535587310791},{"input":[35,121,1],"x":22.66753578186035,"y":14.532861709594727},{"input":[35,121,1],"x":22.759456634521484,"y":14.850367546081543},{"input":[35,121,1],"x":22.851375579833984,"y":15.167874336242676},{"input":[35,121,1],"x":22.943294525146484,"y":15.485380172729492},{"input":[35,121,1],"x":23.035213470458984,"y":15.802886009216309},{"input":[35,121,1],"x":23.127132415771484,"y":16.120391845703125},{"input":[35,121,1],"x":23.219051361083984,"y":16.437898635864258},{"input":[35,121,1],"x":23.310972213745117,"y":16.75540542602539},{"input":[35,121,1],"x":23.402891159057617,"y":17.07291030883789},{"input":[35,121,1],"x":23.494810104370117,"y":17.390417098999023},{"input":[35,121,1],"x":23.586729049682617,"y":17.707921981811523},{"input":[35,121,1],"x":23.678647994995117,"y":18.025428771972656},{"input":[35,121,1],"x":23.77056884765625,"y":18.34293556213379},{"input":[35,121,1],"x":23.86248779296875,"y":18.66044044494629},{"input":[35,121,1],"x":23.95440673828125,"y":18.977947235107422},{"input":[35,121,1],"x":24.04632568359375,"y":19.295454025268555},{"input":[35,121,1],"x":24.13824462890625,"y":19.612958908081055},{"input":[35,121,1],"x":24.23016357421875,"y":19.930465698242188},{"input":[35,121,1],"x":24.322084426879883,"y":20.247970581054688},{"input":[35,121,1],"x":24.414003372192383,"y":20.56547737121582},{"input":[35,121,1],"x":24.505922317504883,"y":20.882984161376953},{"input":[35,121,1],"x":24.597841262817383,"y":21.200489044189453},{"input":[35,121,1],"x":24.689760208129883,"y":21.517995834350586},{"input":[35,121,1],"x":24.781681060791016,"y":21.83550262451172},{"input":[35,121,1],"x":24.873600006103516,"y":22.15300750732422},{"input":[35,121,1],"x":24.965518951416016,"y":22.47051429748535},{"input":[116,-50,0],"x":25.148258209228516,"y":22.39177894592285},{"input":[116,-50,0],"x":25.33099937438965,"y":22.31304359436035},{"input":[116,-50,0],"x":25.51373863220215,"y":22.23430633544922},{"input":[116,-50,0],"x":25.69647789001465,"y":22.15557098388672},{"input":[116,-50,0],"x":25.87921905517578,"y":22.07683563232422},{"input":[116,-50,0],"x":26.06195831298828,"y":21.99810028076172},{"input":[116,-50,0],"x":26.24469757080078,"y":21.91936492919922},{"input":[116,-50,0],"x":26.427438735961914,"y":21.84062957763672},{"input":[116,-50,0],"x":26.610177993774414,"y":21.76189422607422},{"input":[116,-50,0],"x":26.792919158935547,"y":21.683156967163086},{"input":[116,-50,0],"x":26.975658416748047,"y":21.604421615600586},{"input":[116,-50,0],"x":27.158397674560547,"y":21.525686264038086},{"input":[116,-50,0],"x":27.34113883972168,"y":21.446950912475586},{"input":[116,-50,0],"x":27.52387809753418,"y":21.368215560913086},{"input":[116,-50,0],"x":27.70661735534668,"y":21.289480209350586},{"input":[116,-50,0],"x":27.889358520507812,"y":21.210742950439453},{"input":[116,-50,0],"x":28.072097778320312,"y":21.132007598876953},{"input":[116,-50,0],"x":28.254838943481445,"y":21.053272247314453},{"input":[116,-50,0],"x":28.437578201293945,"y":20.974536895751953},{"input":[116,-50,0],"x":28.620317459106445,"y":20.895801544189453},{"input":[116,-50,0],"x":28.803058624267578,"y":20.817066192626953},{"input":[116,-50,0],"x":28.985797882080078,"y":20.73832893371582},{"input":[116,-50,0],"x":29.168537139892578,"y":20.65959358215332},{"input":[116,-50,0],"x":29.35127830505371,"y":20.58085823059082},{"input":[116,-50,0],"x":29.53401756286621,"y":20.50212287902832},{"input":[116,-50,0],"x":29.71675682067871,"y":20.42338752746582},{"input":[116,-50,0],"x":29.899497985839844,"y":20.34465217590332},{"input":[116,-50,0],"x":30.082237243652344,"y":20.26591682434082},{"input":[116,-50,0],"x":30.264978408813477,"y":20.187179565429688},{"input":[116,-50,0],"x":30.447717666625977,"y":20.108444213867188},{"input":[116,-50,0],"x":30.630456924438477,"y":20.029708862304688},{"input":[116,-50,0],"x":30.81319808959961,"y":19.950973510742188},{"input":[116,-50,0],"x":30.99593734741211,"y":19.872238159179688},{"input":[116,-50,0],"x":31.17867660522461,"y":19.793502807617188},{"input":[116,-50,0],"x":31.361417770385742,"y":19.714765548706055},{"input":[116,-50,0],"x":31.544157028198242,"y":19.636030197143555},{"input":[116,-50,0],"x":31.726896286010742,"y":19.557294845581055},{"input":[116,-50,0],"x":31.909637451171875,"y":19.478559494018555},{"input":[116,-50,0],"x":32.092376708984375,"y":19.399824142456055},{"input":[116,-50,0],"x":32.275115966796875,"y":19.321088790893555},{"input":[116,-50,0],"x":32.457855224609375,"y":19.242351531982422},{"input":[116,-50,0],"x":32.64059829711914,"y":19.163616180419922},{"input":[116,-50,0],"x":32.82333755493164,"y":19.084880828857422},{"input":[116,-50,0],"x":33.00607681274414,"y":19.006145477294922},{"input":[116,-50,0],"x":33.18881607055664,"y":18.927410125732422},{"input":[116,-50,0],"x":33.37155532836914,"y":18.848674774169922},{"input":[116,-50,0],"x":33.554298400878906,"y":18.769939422607422},{"input":[116,-50,0],"x":33.737037658691406,"y":18.69120216369629},{"input":[116,-50,0],"x":33.919776916503906,"y":18.61246681213379},{"input":[116,-50,0],"x":33.999977111816406,"y":18.53373146057129},{"input":[116,-49,0],"x":33.999977111816406,"y":18.45664405822754},{"input":[117,-48,0],"x":33.999977111816406,"y":18.38102149963379},{"input":[118,-46,0],"x":33.999977111816406,"y":18.30851173400879},{"input":[118,-45,0],"x":33.999977111816406,"y":18.237648010253906},{"input":[118,-44,0],"x":33.999977111816406,"y":18.168434143066406},{"input":[119,-43,0],"x":33.999977111816406,"y":18.100685119628906},{"input":[119,-41,0],"x":33.999977111816406,"y":18.036048889160156},{"input":[120,-40,0],"x":33.999977111816406,"y":17.973060607910156},{"input":[120,-39,0],"x":33.999977111816406,"y":17.911720275878906},{"input":[121,-38,0],"x":33.999977111816406,"y":17.851844787597656},{"input":[-78,-128,1],"x":33.825477600097656,"y":17.567846298217773},{"input":[-78,-128,1],"x":33.650978088378906,"y":17.283849716186523},{"input":[-78,-128,1],"x":33.47647476196289,"y":16.99985122680664},{"input":[-78,-128,1],"x":33.30197525024414,"y":16.715852737426758},{"input":[-79,-128,1],"x":33.12582778930664,"y":16.432771682739258},{"input":[-79,-128,1],"x":32.94968032836914,"y":16.149688720703125},{"input":[-79,-128,1],"x":32.77353286743164,"y":15.866606712341309},{"input":[-79,-128,1],"x":32.59738540649414,"y":15.583524703979492},{"input":[-79,-128,1],"x":32.421234130859375,"y":15.300442695617676},{"input":[-79,-128,1],"x":32.245086669921875,"y":15.01736068725586},{"input":[-80,-128,1],"x":32.067474365234375,"y":14.735377311706543},{"input":[-80,-128,1],"x":31.889862060546875,"y":14.453393936157227},{"input":[-80,-128,1],"x":31.712247848510742,"y":14.17141056060791},{"input":[-80,-128,1],"x":31.534635543823242,"y":13.889427185058594},{"input":[-80,-128,1],"x":31.357023239135742,"y":13.607442855834961},{"input":[-80,-128,1],"x":31.17940902709961,"y":13.325459480285645},{"input":[-81,-128,1],"x":31.00014877319336,"y":13.044391632080078},{"input":[-81,-128,1],"x":30.82088851928711,"y":12.763323783874512},{"input":[-81,-128,1],"x":30.641626358032227,"y":12.482255935668945},{"input":[-81,-128,1],"x":30.462366104125977,"y":12.201188087463379},{"input":[-81,-128,1],"x":30.283105850219727,"y":11.920120239257812},{"input":[-81,-128,1],"x":30.103843688964844,"y":11.639052391052246},{"input":[-82,-128,1],"x":29.923118591308594,"y":11.359082221984863},{"input":[-82,-128,1],"x":29.74239158630371,"y":11.079113006591797},{"input":[-82,-128,1],"x":29.56166648864746,"y":10.79914379119873},{"input":[-82,-128,1],"x":29.38094139099121,"y":10.519174575805664},{"input":[-82,-128,1],"x":29.200214385986328,"y":10.239205360412598},{"input":[-83,-128,1],"x":29.017841339111328,"y":9.960151672363281},{"input":[-83,-128,1],"x":28.835468292236328,"y":9.681097984313965},{"input":[-83,-128,1],"x":28.653093338012695,"y":9.402044296264648},{"input":[-83,-128,1],"x":28.470720291137695,"y":9.122989654541016},{"input":[-84,-128,1],"x":28.286882400512695,"y":8.8450345993042},{"input":[-84,-128,1],"x":28.103042602539062,"y":8.567079544067383},{"input":[-84,-128,1],"x":27.919204711914062,"y":8.289124488830566},{"input":[-84,-128,1],"x":27.73536491394043,"y":8.01116943359375},{"input":[-85,-128,1],"x":27.54987907409668,"y":7.734129905700684},{"input":[-85,-128,1],"x":27.36439323425293,"y":7.457090377807617},{"input":[-85,-128,1],"x":27.178905487060547,"y":7.180050373077393},{"input":[-85,-128,1],"x":26.993419647216797,"y":6.903010845184326},{"input":[-86,-128,1],"x":26.806468963623047,"y":6.62706995010376},{"input":[-86,-128,1],"x":26.619516372680664,"y":6.351129055023193},{"input":[-86,-128,1],"x":26.432565689086914,"y":6.075188159942627},{"input":[-87,-128,1],"x":26.24414825439453,"y":5.800162315368652},{"input":[-87,-128,1],"x":26.05573272705078,"y":5.525136947631836},{"input":[-87,-128,1],"x":25.86731719970703,"y":5.2501115798950195},{"input":[-88,-128,1],"x":25.67743492126465,"y":4.976184844970703},{"input":[-88,-128,1],"x":25.4875545501709,"y":4.702258110046387},{"input":[-88,-128,1],"x":25.2813777923584,"y":4.44993782043457},{"input":[-88,-128,1],"x":25.040225982666016,"y":4.217576026916504},{"input":[-88,-128,1],"x":24.850345611572266,"y":3.9436490535736084},{"input":[-89,-128,1],"x":24.658998489379883,"y":3.670637845993042},{"input":[-89,-128,1],"x":24.467653274536133,"y":3.3976263999938965},{"input":[-90,-128,1],"x":24.274843215942383,"y":3.12571382522583},{"input":[-90,-128,1],"x":24.08203125,"y":2.8538012504577637},{"input":[-91,-128,1],"x":23.887939453125,"y":2.582803964614868},{"input":[-91,-128,1],"x":23.693845748901367,"y":2.3118069171905518},{"input":[-92,-128,1],"x":23.498289108276367,"y":2.0419085025787354},{"input":[-92,-128,1],"x":23.302732467651367,"y":1.7720099687576294},{"input":[-93,-128,1],"x":23.105709075927734,"y":1.5030269622802734},{"input":[-93,-128,1],"x":22.908687591552734,"y":1.2340439558029175}]} + ] } diff --git a/examples/game/run.sh b/examples/game/run.sh index e219154b9..98fc4baa5 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -8,7 +8,11 @@ # the next port), one process each # ./run.sh gen regenerate client/src/generated// from the # Rust surfaces (`distributed game-manifest` + -# `distributed game-client`); `gen --check` verifies +# `distributed game-client`) and compile each +# `#[predict]` step to /wasm/.wasm +# (`distributed game-wasm`, gitignored, stamped so +# an unchanged step is not rebuilt); `gen --check` +# verifies the TypeScript (and still builds WASM) # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS, # generated clients checked) # ./run.sh list demos this script knows @@ -69,7 +73,9 @@ ensure_cli() { # gen [--check]: GameSurface JSON from each Rust surface export → typed # TypeScript in client/src/generated// (surface.json included, so a -# changed Rust definition shows up as drift). +# changed Rust definition shows up as drift), then the surface's predicted +# step → /wasm/.wasm. `--check` only applies to the +# checked-in TypeScript; the WASM is a build output and is (re)built. gen() { local check="${1:-}" ensure_cli @@ -79,7 +85,33 @@ gen() { "$CLI" game-manifest --manifest-path "$SERVER/Cargo.toml" \ --entrypoint "game_demos::$surface::game_surface" --out "$tmp/$surface.json" && "$CLI" game-client --manifest "$tmp/$surface.json" \ - --out "$CLIENT/src/generated/$surface" $check || + --out "$CLIENT/src/generated/$surface" $check && + wasm_for "$tmp/$surface.json" "$surface" || + status=1 + done + rm -rf "$tmp" + return "$status" +} + +# wasm_for : compile the surface's `#[predict]` step +# (if it declares one) next to its generated client. +wasm_for() { + grep -q '"predict"' "$1" || return 0 + "$CLI" game-wasm --manifest "$1" --manifest-path "$SERVER/Cargo.toml" \ + --out "$CLIENT/src/generated/$2" >/dev/null +} + +# ensure_wasm: build every predicted step the pages load (no TypeScript +# generation; the stamps make this quick when nothing changed). +ensure_wasm() { + ensure_cli + log "compiling predicted steps to WebAssembly" + local tmp status=0 + tmp="$(mktemp -d "${TMPDIR:-/tmp}/game-surfaces.XXXXXX")" + for surface in "${SURFACES[@]}"; do + "$CLI" game-manifest --manifest-path "$SERVER/Cargo.toml" \ + --entrypoint "game_demos::$surface::game_surface" --out "$tmp/$surface.json" && + wasm_for "$tmp/$surface.json" "$surface" || status=1 done rm -rf "$tmp" @@ -93,6 +125,7 @@ run_demo() { ensure_sdk ensure_client ensure_server + ensure_wasm local log_file log_file="$(mktemp -t game-demos.XXXXXX)" @@ -137,6 +170,7 @@ run_cluster() { ensure_sdk ensure_client ensure_server + ensure_wasm local dir secret dir="$(mktemp -d "${TMPDIR:-/tmp}/game-demos-$demo.XXXXXX")" @@ -164,14 +198,14 @@ run_cluster() { smoke() { ensure_sdk ensure_client - log "generated clients are current" + log "generated clients are current; predicted steps compiled to WASM" gen --check - log "server: fmt, clippy, tests (bots smoke + movement fixture)" - cargo fmt --manifest-path "$SERVER/Cargo.toml" --check - cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --all-targets -- -D warnings - cargo test --quiet --manifest-path "$SERVER/Cargo.toml" + log "server: fmt, clippy, tests (bots smoke + grid world fixture)" + cargo fmt --manifest-path "$SERVER/Cargo.toml" --check -p game_demos -p game_sim + cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --workspace --all-targets -- -D warnings + cargo test --quiet --manifest-path "$SERVER/Cargo.toml" --workspace cargo build --quiet --manifest-path "$SERVER/Cargo.toml" - log "client: type-check, build, tests (movement parity + headless SDK)" + log "client: type-check, build, tests (WASM prediction exact match + headless SDK)" (cd "$CLIENT" && npm run --silent check && npx vite build --logLevel warn && GAME_DEMOS_BIN="$BIN" npm test --silent) log "smoke OK" } @@ -180,7 +214,7 @@ case "${1:-}" in smoke) smoke ;; gen) gen "${2:-}" ;; list) printf '%s\n' "${DEMOS[@]}" ;; - "" | -h | --help | help) sed -n '2,21p' "$0" ;; + "" | -h | --help | help) sed -n '2,24p' "$0" ;; *) if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then run_cluster "$1" diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index cc8a5c97b..d44998324 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -593,6 +593,7 @@ dependencies = [ "distributed", "distributed_game", "futures-util", + "game_sim", "http-body-util", "serde", "serde_json", @@ -601,6 +602,13 @@ dependencies = [ "tower", ] +[[package]] +name = "game_sim" +version = "0.1.0" +dependencies = [ + "distributed_game", +] + [[package]] name = "generic-array" version = "0.14.7" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index 5322cab40..000a39bbe 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -2,7 +2,7 @@ # Own workspace (like tests/gateway-native) so demo-only dependencies never # reach the framework's lockfile; excluded from the root workspace. [workspace] -members = ["."] +members = [".", "sim"] resolver = "2" [package] @@ -20,6 +20,8 @@ name = "game-demos" path = "src/main.rs" [dependencies] +# The client-predicted simulation (also compiled to WASM for the browser). +game_sim = { path = "sim" } distributed_game = { path = "../../../distributed_game", features = ["net", "cell", "sqlite"] } # Mob Pit: native durable SQLite cells + sorted-set leaderboards (Redis optional at runtime). distributed = { path = "../../..", features = ["cell-sqlite", "redis"] } diff --git a/examples/game/server/sim/Cargo.toml b/examples/game/server/sim/Cargo.toml new file mode 100644 index 000000000..e6d855e5a --- /dev/null +++ b/examples/game/server/sim/Cargo.toml @@ -0,0 +1,16 @@ +# The demos' deterministic client-predicted simulation: movement steps, +# the inputs they read and the Endless Grid's procedural world. No server +# dependencies, so `distributed game-wasm` compiles it to WebAssembly for +# the browser while `game_demos` links the same code natively. +[package] +name = "game_sim" +version = "0.1.0" +edition = "2021" +publish = false +description = "Shared deterministic simulation of the distributed_game demos (server + WASM client prediction)" + +[lib] +path = "src/lib.rs" + +[dependencies] +distributed_game = { path = "../../../../distributed_game" } diff --git a/examples/game/server/sim/src/arena.rs b/examples/game/server/sim/src/arena.rs index 29a11a16d..8771d7cc0 100644 --- a/examples/game/server/sim/src/arena.rs +++ b/examples/game/server/sim/src/arena.rs @@ -1,24 +1,23 @@ -//! Shared deterministic movement step for the Arena demo. +//! The Arena's deterministic movement step, shared by every demo with an +//! Arena capsule (Arena, Mob Pit, The Freeze, Boss Ripple). //! -//! **This file has a twin:** `examples/game/client/src/arena/movement.ts`. -//! The client predicts its own capsule with the same step, so both must -//! produce the same numbers for the same inputs. Rules that keep them equal: +//! The server runs [`step`] in `on_tick`; the browser predicts its own +//! capsule with the **same code** compiled to WebAssembly ([`arena_step`] +//! is the `#[predict]` declaration; `distributed game-wasm` builds it). +//! Prediction is exact because: //! -//! - all state and arithmetic is binary32 (`f32` here, `Math.fround` after -//! every operation in TypeScript); only `+ - * /` and `sqrt` are used -//! (correctly rounded in both languages; no trig, no `powf`); //! - one input = one command frame of exactly [`DT`] seconds, independent -//! of the server's measured tick length; +//! of the server's measured tick length (the frame's `dt` is ignored); //! - after every step the replicated fields are snapped to their wire //! quantization ([`canonicalize`]), so the server's state is exactly what -//! clients decode and a rebase never introduces error. -//! -//! `tests/movement_fixture.rs` writes `examples/game/fixtures/arena-movement.json` -//! (inputs → states) and the client's `tests/movement-parity.test.mjs` replays -//! it through the TypeScript step. Change both files together, then -//! regenerate with `UPDATE_GOLDEN=1 cargo test --test movement_fixture`. +//! clients decode and a rebase never introduces error; +//! - only IEEE operations that are correctly rounded on every target are +//! used (`+ - * /`, `sqrt`, comparisons; no trig, no `powf`), so native +//! and WASM results are bit-identical. The client's +//! `tests/prediction-wasm.test.mjs` proves it against the native build +//! over recorded input streams. -use distributed_game::{FieldType, GameInput}; +use distributed_game::{predict, FieldType, GameInput, GameRecord}; /// Command frame length (s): the 30 Hz tick. pub const DT: f32 = 1.0 / 30.0; @@ -61,7 +60,7 @@ pub const VEL: FieldType = FieldType::quant_centered(16.0, 12); /// One command frame from the client: stick in `[-127, 127]` per axis /// (+x right, +y forward) and button bits. Wire payload `[mx, my, buttons]` /// (3 bytes); [`GameInput::from_payload`] clamps `-128` to `-127` and clears -/// unknown buttons. The TypeScript encoder/sanitizer is generated from this. +/// unknown buttons. The TypeScript encoder is generated from this. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] pub struct MoveInput { /// Stick x. @@ -75,9 +74,10 @@ pub struct MoveInput { pub buttons: u8, } -/// Everything the step reads. Every field is replicated, so a client can -/// rebase its prediction on the authoritative copy. -#[derive(Debug, Clone, Copy, Default, PartialEq)] +/// Everything the step reads. Every field is replicated under the same name +/// (`player` kinds: `x y vx vy dash cd`), so a client can rebase its +/// prediction on the authoritative copy; the record is the predicted state. +#[derive(Debug, Clone, Copy, Default, PartialEq, GameRecord)] pub struct MoveState { /// Position x. pub x: f32, @@ -89,8 +89,15 @@ pub struct MoveState { pub vy: f32, /// Remaining dash frames. pub dash: u8, - /// Remaining cooldown frames. - pub cooldown: u8, + /// Remaining dash cooldown frames. + pub cd: u8, +} + +/// The client-predicted step of every Arena capsule (`player` kinds whose +/// zone takes a plain [`MoveInput`]: Arena, The Freeze). +#[predict(ArenaStep, kind = "player")] +pub fn arena_step(state: &MoveState, input: &MoveInput, _context: &(), _dt: f32) -> MoveState { + step(*state, *input) } /// Advance one command frame. @@ -106,8 +113,8 @@ pub fn step(s: MoveState, input: MoveInput) -> MoveState { dy *= inv; } - s.cooldown = s.cooldown.saturating_sub(1); - if input.buttons & BUTTON_DASH != 0 && s.cooldown == 0 && s.dash == 0 { + s.cd = s.cd.saturating_sub(1); + if input.buttons & BUTTON_DASH != 0 && s.cd == 0 && s.dash == 0 { // Dash along the stick, else along the current velocity. let v2 = s.vx * s.vx + s.vy * s.vy; let dir = if l2 > 0.01 { @@ -123,7 +130,7 @@ pub fn step(s: MoveState, input: MoveInput) -> MoveState { s.vx = nx * DASH_SPEED; s.vy = ny * DASH_SPEED; s.dash = DASH_FRAMES; - s.cooldown = DASH_COOLDOWN; + s.cd = DASH_COOLDOWN; } } @@ -227,7 +234,7 @@ mod tests { vx: 0.0, vy: 0.0, dash: 0, - cooldown: 0, + cd: 0, }; #[test] @@ -305,19 +312,16 @@ mod tests { buttons: BUTTON_DASH, }; let s = step(START, dash); - assert_eq!((s.dash, s.cooldown), (DASH_FRAMES - 1, DASH_COOLDOWN)); + assert_eq!((s.dash, s.cd), (DASH_FRAMES - 1, DASH_COOLDOWN)); assert!(s.vy > 13.9); let s = run(s, dash, 14); assert!( s.vy <= MAX_SPEED + 0.01, "dash over, back to walking: {s:?}" ); - assert!( - s.cooldown > 0 && s.dash == 0, - "held button does not re-dash" - ); + assert!(s.cd > 0 && s.dash == 0, "held button does not re-dash"); let s = run(s, MoveInput::default(), 31); - assert_eq!(s.cooldown, 0); + assert_eq!(s.cd, 0); } #[test] diff --git a/examples/game/server/sim/src/grid.rs b/examples/game/server/sim/src/grid.rs index 041612731..156c58d3c 100644 --- a/examples/game/server/sim/src/grid.rs +++ b/examples/game/server/sim/src/grid.rs @@ -1,19 +1,21 @@ //! Procedural world and movement of the Endless Grid. //! -//! **This file has a twin:** `examples/game/client/src/grid/world.ts`. The -//! static content of a cell (terrain height, biome, props) is a pure +//! The static content of a cell (terrain height, biome, props) is a pure //! function of `(world seed, cell x, cell y, CONTENT_VERSION)`; the server //! uses it for collision and the client for rendering, and **nothing -//! static is replicated**. The movement step is shared too, so the client -//! predicts its own walker exactly. +//! static is replicated**. The walker's movement step collides with the +//! cell's props; the browser predicts it with this code compiled to +//! WebAssembly ([`grid_step`], whose context names the seed and cell, so +//! the props are generated inside the module). //! -//! Rules that keep both sides bit-identical (as in the Arena movement): -//! integer hashing on `u32` only (`Math.imul` / `>>> 0` in TypeScript); -//! floats are binary32 (`Math.fround` after every operation) using only -//! `+ - * /`, `sqrt` and `floor`; constants are dyadic where it matters. -//! `tests/grid_fixture.rs` writes `examples/game/fixtures/grid-world.json`, -//! replayed by the client's `tests/grid-world-parity.test.mjs`. Change both -//! files together, then `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. +//! The rendering side still has a TypeScript twin of the *generation* +//! (`examples/game/client/src/grid/world.ts`, checked bit-for-bit by +//! `fixtures/grid-world.json`) until world content is served from WASM as +//! well. Rules that keep everything bit-identical: integer hashing on `u32` +//! only; floats are binary32 using only `+ - * /`, `sqrt` and `floor`; +//! constants are dyadic where it matters. `tests/grid_fixture.rs` writes the +//! fixture; change both files together, then `UPDATE_GOLDEN=1 cargo test +//! --test grid_fixture`. //! //! Layout: a cell is [`CELL`] m square with local coordinates `0..CELL` on //! both axes; cell `(cx, cy)` covers world `cx*CELL .. (cx+1)*CELL`. Each @@ -22,7 +24,9 @@ //! is a multiple of 8 m is a free path ("trail"), and props never reach //! across a cell border. -use distributed_game::{FieldType, FieldValue, GameInput}; +use std::cell::RefCell; + +use distributed_game::{predict, FieldType, FieldValue, GameInput, GameRecord}; /// Cell edge length (m). pub const CELL: f32 = 32.0; @@ -312,6 +316,59 @@ pub fn step(x: f32, y: f32, input: MoveInput, props: &[Prop]) -> (f32, f32) { (snap(x.clamp(lo, hi)), snap(y.clamp(lo, hi))) } +/// A walker's predicted state: its cell-local position (the `walker` kind's +/// `x` / `y`). +#[derive(Debug, Clone, Copy, Default, PartialEq, GameRecord)] +pub struct WalkerState { + /// Local x. + pub x: f32, + /// Local y. + pub y: f32, +} + +/// What a client tells the predicted step: the world seed (from the +/// zone's hello) and the cell it walks in (its authoritative zone). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameRecord)] +pub struct GridContext { + /// World seed. + pub seed: u32, + /// Cell x. + pub cx: i32, + /// Cell y. + pub cy: i32, +} + +/// `(seed, cell x, cell y)` → that cell's props. +type PropsCache = Option<((u32, i32, i32), Vec)>; + +thread_local! { + /// Props of the last cell stepped in (a walker stays in one cell for + /// many frames). + static PROPS: RefCell = const { RefCell::new(None) }; +} + +/// The client-predicted step of the own walker: [`step`] against the +/// props of the context's cell (generated here, so the browser needs no +/// copy of the world to predict). +#[predict(GridStep, kind = "walker")] +pub fn grid_step( + state: &WalkerState, + input: &MoveInput, + context: &GridContext, + _dt: f32, +) -> WalkerState { + let key = (context.seed, context.cx, context.cy); + PROPS.with(|cache| { + let mut cache = cache.borrow_mut(); + if cache.as_ref().map(|(k, _)| *k) != Some(key) { + *cache = Some((key, cell_props(context.seed, (context.cx, context.cy)))); + } + let props = &cache.as_ref().expect("filled above").1; + let (x, y) = step(state.x, state.y, *input, props); + WalkerState { x, y } + }) +} + /// Neighbour a walker at `(x, y)` belongs to, as a cell offset, or None /// while inside (with hysteresis). X first, then y. pub fn crossing(x: f32, y: f32) -> Option<(i32, i32)> { diff --git a/examples/game/server/sim/src/lib.rs b/examples/game/server/sim/src/lib.rs new file mode 100644 index 000000000..08516525b --- /dev/null +++ b/examples/game/server/sim/src/lib.rs @@ -0,0 +1,22 @@ +//! The deterministic, client-predicted part of the `distributed_game` +//! demos, shared by the server (`game_demos`, natively) and the browser +//! (compiled to WebAssembly by `distributed game-wasm`). +//! +//! Each demo that predicts movement declares its step here with +//! `#[predict]` and names it in its game surface +//! (`GameSurface::predict::()`): +//! +//! | step | kind | used by | +//! |---|---|---| +//! | [`arena::ArenaStep`] | `player` | Arena, The Freeze | +//! | [`mobpit::PitStep`] | `player` | Mob Pit | +//! | [`ripple::HoodStep`] | `player` | Boss Ripple (hoods) | +//! | [`grid::GridStep`] | `walker` | Endless Grid (context: seed + cell) | +//! +//! Nothing here may depend on server-only crates (Tokio, axum, SQLite): +//! the crate must compile for `wasm32-unknown-unknown`. + +pub mod arena; +pub mod grid; +pub mod mobpit; +pub mod ripple; diff --git a/examples/game/server/sim/src/mobpit.rs b/examples/game/server/sim/src/mobpit.rs new file mode 100644 index 000000000..36a2e0f35 --- /dev/null +++ b/examples/game/server/sim/src/mobpit.rs @@ -0,0 +1,44 @@ +//! Mob Pit's input frame and its client-predicted step (the Arena's +//! movement; combat is server-owned and never predicted). + +use distributed_game::{predict, GameInput}; + +use crate::arena::{self, MoveInput, MoveState}; + +/// Input: the Arena's 3-byte frame (`[mx, my, buttons]`) with an attack +/// bit next to dash. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] +pub struct PitInput { + /// Stick x. + #[range(min = -127, max = 127)] + pub mx: i8, + /// Stick y. + #[range(min = -127, max = 127)] + pub my: i8, + /// [`PitInput::DASH`] | [`PitInput::ATTACK`]. + #[buttons(dash, attack)] + pub buttons: u8, +} + +impl PitInput { + /// The movement part (the Arena's step). + pub fn movement(self) -> MoveInput { + MoveInput { + mx: self.mx, + my: self.my, + buttons: self.buttons & MoveInput::DASH, + } + } + + /// Attack held. + pub fn attack(self) -> bool { + self.buttons & Self::ATTACK != 0 + } +} + +/// The own capsule's predicted step: the Arena's movement of +/// [`PitInput::movement`]. +#[predict(PitStep, kind = "player")] +pub fn pit_step(state: &MoveState, input: &PitInput, _context: &(), _dt: f32) -> MoveState { + arena::step(*state, input.movement()) +} diff --git a/examples/game/server/sim/src/ripple.rs b/examples/game/server/sim/src/ripple.rs new file mode 100644 index 000000000..6b53e598d --- /dev/null +++ b/examples/game/server/sim/src/ripple.rs @@ -0,0 +1,41 @@ +//! Boss Ripple's hood input and its client-predicted step (the Arena's +//! movement; attacks are server-owned). + +use distributed_game::{predict, GameInput}; + +use crate::arena::{self, MoveInput, MoveState}; + +/// Hood input: Arena movement + action bits. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] +pub struct HoodInput { + /// Stick x. + #[range(min = -127, max = 127)] + pub mx: i8, + /// Stick y. + #[range(min = -127, max = 127)] + pub my: i8, + /// [`HoodInput::DASH`]. + #[buttons(dash)] + pub buttons: u8, + /// [`HoodInput::ATTACK`] | [`HoodInput::SMITE`]. + #[buttons(attack, smite)] + pub action: u8, +} + +impl HoodInput { + /// The movement part (the Arena's step). + pub fn movement(self) -> MoveInput { + MoveInput { + mx: self.mx, + my: self.my, + buttons: self.buttons, + } + } +} + +/// A fighter's predicted step: the Arena's movement of +/// [`HoodInput::movement`]. +#[predict(HoodStep, kind = "player")] +pub fn hood_step(state: &MoveState, input: &HoodInput, _context: &(), _dt: f32) -> MoveState { + arena::step(*state, input.movement()) +} diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index 71f2cff5c..7c051c676 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -4,7 +4,8 @@ //! interest management (14 m view radius on a 40×40 m floor: far drones are //! culled at the ring's edge; players are global so you always see everyone //! in the room), client prediction + reconciliation of the -//! own capsule ([`movement`] is shared with the TypeScript client) and +//! own capsule ([`movement`], the `game_sim` step the browser runs as +//! WebAssembly) and //! interpolation of everything else (players, ~30 wandering drones). //! //! Entities: @@ -24,7 +25,8 @@ //! move faster than real time by sending more inputs, but jitter bursts are //! absorbed. -pub mod movement; +/// The shared movement step and its `#[predict]` declaration. +pub use game_sim::arena as movement; use std::collections::BTreeMap; @@ -79,7 +81,7 @@ impl PlayerView { vx: state.vx, vy: state.vy, dash: state.dash, - cd: state.cooldown, + cd: state.cd, name: name.to_string(), } } @@ -130,7 +132,9 @@ pub enum ArenaEvent { /// The Arena's client surface (`distributed game-manifest --entrypoint /// game_demos::arena::game_surface`). pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("arena").events::() + GameSurface::for_zone::("arena") + .events::() + .predict::() } /// Interest radius (m). @@ -273,7 +277,8 @@ impl Zone for Arena { fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { for (id, player) in &mut self.players { for input in self.credits.take(ctx, *id) { - player.state = movement::step(player.state, input.input); + // The declared predicted step: what the client runs as WASM. + player.state = movement::arena_step(&player.state, &input.input, &(), movement::DT); } ctx.set_view(*id, View::new(player.state.x, player.state.y, VIEW_RADIUS)); } diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs index 75a79a9f0..09e36c3b1 100644 --- a/examples/game/server/src/freeze/mod.rs +++ b/examples/game/server/src/freeze/mod.rs @@ -21,8 +21,8 @@ //! [`Zone::freeze_ready`]; the barrier times out (`NotAcked`) and every //! zone resumes on the old version ("update aborted"). //! -//! Movement is the Arena's shared step ([`crate::arena::movement`], predicted -//! by the client with the same TypeScript twin). +//! Movement is the Arena's step ([`crate::arena::movement::arena_step`]), +//! which the client predicts with, compiled to WebAssembly. //! //! Entities: 1 `player` (the Arena's [`PlayerView`]), 2 `slime` (x y yaw), //! 3 `gem` (x y), 4 `ritual` (global: x y stuck). Events: [`FreezeEvent`]; @@ -169,7 +169,9 @@ pub enum FreezeEvent { /// The Freeze's client surface. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("freeze").events::() + GameSurface::for_zone::("freeze") + .events::() + .predict::() } /// Durable command recording a collected gem. @@ -437,7 +439,8 @@ impl Zone for FreezeZone { for id in ids { let player = self.players.get_mut(&id).expect("present"); for input in self.credits.take(ctx, id) { - player.state = movement::step(player.state, input.input); + // The declared predicted step: what the client runs as WASM. + player.state = movement::arena_step(&player.state, &input.input, &(), movement::DT); } let (x, y) = (player.state.x, player.state.y); // Lava burns (ice is safe): back to a spawn point. diff --git a/examples/game/server/src/grid/mod.rs b/examples/game/server/src/grid/mod.rs index 35daeb78b..20202cb85 100644 --- a/examples/game/server/src/grid/mod.rs +++ b/examples/game/server/src/grid/mod.rs @@ -40,7 +40,8 @@ //! between zones is the client's choice of observed neighbours. pub mod dev; -pub mod world; +/// The procedural world, the walker step and its `#[predict]` declaration. +pub use game_sim::grid as world; use std::collections::BTreeMap; use std::sync::Arc; @@ -117,7 +118,9 @@ pub const EVENT_HELLO: u32 = GridHello::EVENT_ID; /// The grid's client surface. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("grid").events::() + GameSurface::for_zone::("grid") + .events::() + .predict::() } /// Most markers a cell keeps (oldest dropped first). pub const MAX_MARKERS: usize = 12; @@ -484,6 +487,8 @@ impl Zone for GridZone { break; }; let input = input.input; + // `world::grid_step` (the declared predicted step) with this + // cell's props, which the zone already holds. (w.x, w.y) = world::step(w.x, w.y, input, &self.props); w.credits -= 1; if input.buttons & world::BUTTON_MARK != 0 && w.mark_cooldown == 0 { diff --git a/examples/game/server/src/lib.rs b/examples/game/server/src/lib.rs index e6ca40b32..63343f6ed 100644 --- a/examples/game/server/src/lib.rs +++ b/examples/game/server/src/lib.rs @@ -6,6 +6,9 @@ //! exporting `game_surface()`: its kinds, input and events, authored with //! the `distributed_game` derives, from which `run.sh gen` generates the //! typed TypeScript client in `client/src/generated//`. +//! - The client-predicted steps live in the `game_sim` crate (`sim/`), +//! which `distributed game-wasm` compiles to WebAssembly; +//! [`predict_trace`] is the native side of their exact-match proof. //! //! See `examples/game/README.md`. @@ -16,4 +19,5 @@ pub mod freeze; pub mod gallery; pub mod grid; pub mod mobpit; +pub mod predict_trace; pub mod ripple; diff --git a/examples/game/server/src/main.rs b/examples/game/server/src/main.rs index 31a4d51b8..b523c2a20 100644 --- a/examples/game/server/src/main.rs +++ b/examples/game/server/src/main.rs @@ -36,6 +36,10 @@ enum DemoCommand { Grid(ClusterArgs), /// Boss Ripple: realm > city > borough > hood, tier-up events across hosts. Ripple(ClusterArgs), + /// Print native traces of every predicted step over recorded input + /// streams (JSON; the WASM exact-match test replays them). + #[command(hide = true)] + PredictTrace, } #[tokio::main] @@ -47,5 +51,9 @@ async fn main() -> std::io::Result<()> { DemoCommand::Freeze(args) => game_demos::freeze::world::run(args).await, DemoCommand::Grid(args) => run_cluster::(args).await, DemoCommand::Ripple(args) => run_cluster::(args).await, + DemoCommand::PredictTrace => { + println!("{}", game_demos::predict_trace::traces()); + Ok(()) + } } } diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index e448ab6d4..c843ab77e 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -1,8 +1,8 @@ //! The Mob Pit zone: authoritative melee combat at 30 Hz. //! -//! Movement reuses the Arena's predicted step ([`crate::arena::movement`], -//! same floor and pillars) so the own capsule is client-predicted; combat is -//! server-only. Entities: +//! Movement reuses the Arena's step ([`crate::arena::movement`], same floor +//! and pillars) through [`pit_step`], the declared predicted step the client +//! runs as WebAssembly; combat is server-only. Entities: //! //! | kind | ids | fields | //! |---|---|---| @@ -46,7 +46,7 @@ use distributed_game::{ use super::board::BoardSnapshot; use super::crawler::{level_floor, KillReceipt, RecordKillInput}; use super::world::MobPitWorld; -use crate::arena::movement::{self, MoveInput, MoveState, PILLARS, PLAYER_RADIUS}; +use crate::arena::movement::{self, MoveState, PILLARS, PLAYER_RADIUS}; use crate::arena::PillarView; use crate::common::Guests; @@ -241,39 +241,12 @@ pub enum PitEvent { /// Mob Pit's client surface (also used by the leaderboard page). pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("mobpit").events::() + GameSurface::for_zone::("mobpit") + .events::() + .predict::() } -/// Input: the Arena's 3-byte frame (`[mx, my, buttons]`) with an attack -/// bit next to dash. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] -pub struct PitInput { - /// Stick x. - #[range(min = -127, max = 127)] - pub mx: i8, - /// Stick y. - #[range(min = -127, max = 127)] - pub my: i8, - /// [`PitInput::DASH`] | [`PitInput::ATTACK`]. - #[buttons(dash, attack)] - pub buttons: u8, -} - -impl PitInput { - /// The movement part (the Arena's step). - pub fn movement(self) -> MoveInput { - MoveInput { - mx: self.mx, - my: self.my, - buttons: self.buttons & MoveInput::DASH, - } - } - - /// Attack held. - pub fn attack(self) -> bool { - self.buttons & Self::ATTACK != 0 - } -} +pub use game_sim::mobpit::{pit_step, PitInput, PitStep}; /// Input bit: attack (bit 0 is the Arena's dash). pub const BUTTON_ATTACK: u8 = PitInput::ATTACK; @@ -552,7 +525,8 @@ impl MobPit { break; }; let input = input.input; - p.state = movement::step(p.state, input.movement()); + // The declared predicted step: what the client runs as WASM. + p.state = pit_step(&p.state, &input, &(), movement::DT); p.credits -= 1; let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); if sx * sx + sy * sy > 20.0 * 20.0 { @@ -1014,7 +988,7 @@ impl Zone for MobPit { vx: s.vx, vy: s.vy, dash: s.dash, - cd: s.cooldown, + cd: s.cd, name: p.name.clone(), hp: p.hp.clamp(0, 255) as u8, face: p.face, diff --git a/examples/game/server/src/predict_trace.rs b/examples/game/server/src/predict_trace.rs new file mode 100644 index 000000000..46ab3cd00 --- /dev/null +++ b/examples/game/server/src/predict_trace.rs @@ -0,0 +1,295 @@ +//! Native traces of every demo's client-predicted step over recorded input +//! streams: the reference side of the native ↔ WebAssembly exact-match +//! proof. `game-demos predict-trace` prints them as JSON; the client's +//! `tests/prediction-wasm.test.mjs` replays the same streams through each +//! surface's compiled module and requires every state to be byte-identical. +//! +//! Every step runs through [`step_bytes`], the same decode → step → encode +//! path the WASM export takes, so the comparison covers the ABI as well as +//! the arithmetic. Inputs are raw payload bytes, deliberately including +//! values the decoder sanitizes (`-128` sticks, unknown button bits). + +use distributed_game::prediction::{step_bytes, PredictContext, PredictStep}; +use distributed_game::Wire; +use game_sim::arena::{self, ArenaStep, MoveState}; +use game_sim::grid::{self, GridContext, GridStep, WalkerState, BUTTON_SPRINT, DEFAULT_SEED}; +use game_sim::mobpit::PitStep; +use game_sim::ripple::HoodStep; +use serde_json::{json, Value}; + +/// Deterministic xorshift32 (streams must be identical on every run). +struct Rng(u32); + +impl Rng { + fn next(&mut self) -> u32 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self.0 = x; + x + } + + fn stick(&mut self) -> u8 { + match self.next() % 8 { + 0 => 0, + 1 => 0x80, // -128: sanitized to -127 + 2 => 127, + 3 => 0x81, // -127 + _ => self.next() as u8, + } + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// A recorded stream: the start state, the context and one payload per frame. +struct Stream { + name: String, + start: Vec, + context: Vec, + inputs: Vec>, +} + +fn trace(streams: Vec) -> Value { + let streams: Vec = streams + .into_iter() + .map(|stream| { + let mut state = stream.start.clone(); + let mut states = Vec::with_capacity(stream.inputs.len()); + for input in &stream.inputs { + state = step_bytes::

    (&state, input, &stream.context, arena::DT) + .unwrap_or_else(|e| panic!("{} {}: {e:?}", P::EXPORT, stream.name)); + states.push(hex(&state)); + } + json!({ + "name": stream.name, + "start": hex(&stream.start), + "context": hex(&stream.context), + "inputs": stream.inputs.iter().map(|i| hex(i)).collect::>(), + "states": states, + }) + }) + .collect(); + json!({ "export": P::EXPORT, "kind": P::KIND, "streams": streams }) +} + +fn state_bytes(state: &T) -> Vec { + distributed_game::codec::to_bytes(state) +} + +/// The Arena movement script (acceleration, diagonals, partial stick, +/// dashes along stick and velocity, held dash, pillar and wall contact), +/// as `[mx, my, buttons]`; `extra` appends bytes (Mob Pit / Ripple bits). +fn scripted(extra: &dyn Fn(usize) -> Vec) -> Vec> { + let dash = arena::BUTTON_DASH; + let script: [([i8; 2], u8, usize); 10] = [ + ([127, 0], 0, 20), + ([90, 90], 0, 15), + ([30, -64], 0, 10), + ([0, 0], dash, 1), + ([0, 0], 0, 12), + ([-127, 0], dash, 8), + ([-128, 5], 0, 40), + ([127, 127], 0, 60), + ([0, 127], dash, 70), + ([0, -127], 0, 120), + ]; + let mut out = Vec::new(); + for ([mx, my], buttons, n) in script { + for _ in 0..n { + let mut frame = vec![mx as u8, my as u8, buttons]; + frame.extend(extra(out.len())); + out.push(frame); + } + } + out +} + +/// Random held inputs (1–20 frames each) over the whole byte range. +fn random(seed: u32, frames: usize, extra_bytes: usize) -> Vec> { + let mut rng = Rng(seed); + let mut out = Vec::with_capacity(frames); + while out.len() < frames { + let mut frame = vec![rng.stick(), rng.stick(), rng.next() as u8]; + for _ in 0..extra_bytes { + frame.push(rng.next() as u8); + } + let hold = 1 + rng.next() as usize % 20; + for _ in 0..hold.min(frames - out.len()) { + out.push(frame.clone()); + } + } + out +} + +fn capsule_streams(extra_bytes: usize) -> Vec { + let start = |x: f32, y: f32| { + state_bytes(&arena::canonicalize(MoveState { + x, + y, + ..MoveState::default() + })) + }; + let extra = move |i: usize| vec![(i as u8).wrapping_mul(37); extra_bytes]; + vec![ + Stream { + name: "scripted".into(), + start: start(-5.0, -5.0), + context: Vec::new(), + inputs: scripted(&extra), + }, + Stream { + name: "random".into(), + start: start(8.0, 3.0), + context: Vec::new(), + inputs: random(0x1234_5678, 3000, extra_bytes), + }, + Stream { + name: "corner".into(), + start: start(18.5, -18.5), + context: Vec::new(), + inputs: random(0x0bad_cafe, 600, extra_bytes), + }, + ] +} + +/// The densest of a few cells, so a walk bumps into props. +fn busy_cell(seed: u32) -> (i32, i32) { + (0..12) + .map(|i| (i, 2)) + .max_by_key(|c| { + grid::cell_props(seed, *c) + .iter() + .filter(|p| p.solid) + .count() + }) + .expect("cells") +} + +fn grid_context(cell: (i32, i32)) -> GridContext { + GridContext { + seed: DEFAULT_SEED, + cx: cell.0, + cy: cell.1, + } +} + +/// Head for each solid prop of the busiest cell in turn (pushing into it), +/// then walk off two borders. +fn prop_walk() -> Stream { + let cell = busy_cell(DEFAULT_SEED); + let context = grid_context(cell); + let props = grid::cell_props(DEFAULT_SEED, cell); + let mut state = WalkerState { x: 16.0, y: 16.0 }; + let targets: Vec<(f32, f32)> = props + .iter() + .filter(|p| p.solid) + .map(|p| (p.x, p.y)) + .chain([(40.0, 16.0), (16.0, -5.0)]) + .collect(); + let mut inputs = Vec::new(); + for (k, (tx, ty)) in targets.iter().enumerate() { + for _ in 0..60 { + let (dx, dy) = (tx - state.x, ty - state.y); + let l = (dx * dx + dy * dy).sqrt().max(1e-3); + let input = [ + (dx / l * 127.0) as i8 as u8, + if k % 3 == 0 { + 0x80 + } else { + (dy / l * 127.0) as i8 as u8 + }, + if k % 2 == 0 { BUTTON_SPRINT } else { 0 }, + ]; + state = grid::grid_step( + &state, + &::from_payload(&input) + .expect("valid"), + &context, + arena::DT, + ); + inputs.push(input.to_vec()); + } + } + Stream { + name: format!("props {},{}", cell.0, cell.1), + start: state_bytes(&WalkerState { x: 16.0, y: 16.0 }), + context: context.encode_context(), + inputs, + } +} + +fn grid_streams() -> Vec { + let mut streams = vec![prop_walk()]; + for (i, cell) in [(0, 0), (3, -7), (999_999, -1_000_000)] + .into_iter() + .enumerate() + { + streams.push(Stream { + name: format!("random {},{}", cell.0, cell.1), + start: state_bytes(&WalkerState { x: 16.0, y: 16.0 }), + context: grid_context(cell).encode_context(), + inputs: random(0x9e37_79b9 ^ i as u32, 1500, 0), + }); + } + streams +} + +/// Every demo step's native trace (see the module docs), plus the Arena +/// drawing constants the client pages keep. +pub fn traces() -> Value { + json!({ + "abi": distributed_game::prediction::ABI_VERSION, + // Drawing constants the pages keep (`client/src/arena/floor.ts`). + "arena": { + "half": arena::HALF, + "playerRadius": arena::PLAYER_RADIUS, + "dashCooldown": arena::DASH_COOLDOWN, + "pillars": arena::PILLARS.iter().map(|(x, y, r)| json!([x, y, r])).collect::>(), + }, + "steps": [ + trace::(capsule_streams(0)), + trace::(capsule_streams(0)), + trace::(capsule_streams(1)), + trace::(grid_streams()), + ], + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grid_step_is_the_zone_step_against_the_cell_props() { + let cell = busy_cell(DEFAULT_SEED); + let props = grid::cell_props(DEFAULT_SEED, cell); + let mut zone = (16.0f32, 16.0f32); + let mut predicted = WalkerState { x: 16.0, y: 16.0 }; + for input in random(7, 400, 0) { + let input = ::from_payload(&input) + .expect("valid"); + zone = grid::step(zone.0, zone.1, input, &props); + predicted = grid::grid_step(&predicted, &input, &grid_context(cell), arena::DT); + assert_eq!((predicted.x, predicted.y), zone); + } + } + + #[test] + fn traces_cover_every_step_and_collide() { + let traces = traces(); + let steps = traces["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 4); + for step in steps { + for stream in step["streams"].as_array().unwrap() { + assert_eq!( + stream["inputs"].as_array().unwrap().len(), + stream["states"].as_array().unwrap().len() + ); + } + } + } +} diff --git a/examples/game/server/src/ripple/mod.rs b/examples/game/server/src/ripple/mod.rs index d8e816de0..310859e5a 100644 --- a/examples/game/server/src/ripple/mod.rs +++ b/examples/game/server/src/ripple/mod.rs @@ -33,7 +33,8 @@ //! //! Entities: 1 `tier` (id 1, every zone), 2 `boss` (id 2, hoods), 3 //! `player` (1000 + player, hoods; Arena movement fields so the client -//! predicts with the Arena step — the boss stands on its central pillar). +//! predicts with [`hood_step`], the Arena movement compiled to WebAssembly — +//! the boss stands on its central pillar). //! They are `#[derive(Replicated)]` views; client events are the typed //! [`RippleEvent`] and input the `#[derive(GameInput)]` [`HoodInput`]; the //! browser client is generated from [`game_surface`]. (Tier-up payloads @@ -52,7 +53,7 @@ use distributed_game::{ use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::arena::movement::{self, MoveInput, MoveState}; +use crate::arena::movement::{self, MoveState}; use crate::cluster::{ClusterDemo, ClusterOptions, World}; use crate::common::{Demo, Guests}; @@ -209,7 +210,9 @@ pub enum RippleEvent { /// Boss Ripple's client surface. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("ripple").events::() + GameSurface::for_zone::("ripple") + .events::() + .predict::() } /// Kind id of [`TierView`] (tests mirror fields by it). @@ -347,33 +350,7 @@ impl ZoneDirectory for TierPlacement { } } -/// Hood input: Arena movement + action bits. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameInput)] -pub struct HoodInput { - /// Stick x. - #[range(min = -127, max = 127)] - pub mx: i8, - /// Stick y. - #[range(min = -127, max = 127)] - pub my: i8, - /// [`HoodInput::DASH`]. - #[buttons(dash)] - pub buttons: u8, - /// [`HoodInput::ATTACK`] | [`HoodInput::SMITE`]. - #[buttons(attack, smite)] - pub action: u8, -} - -impl HoodInput { - /// The movement part (the Arena's step). - pub fn movement(self) -> MoveInput { - MoveInput { - mx: self.mx, - my: self.my, - buttons: self.buttons, - } - } -} +pub use game_sim::ripple::{hood_step, HoodInput, HoodStep}; /// Timers. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -507,7 +484,8 @@ impl Ripple { break; }; let input = input.input; - f.state = movement::step(f.state, input.movement()); + // The declared predicted step: what the client runs as WASM. + f.state = hood_step(&f.state, &input, &(), movement::DT); f.credits -= 1; if input.action & ACTION_SMITE != 0 { blows.push((u32::MAX, f.name.clone())); @@ -763,7 +741,7 @@ impl Zone for Ripple { vx: m.vx, vy: m.vy, dash: m.dash, - cd: m.cooldown, + cd: m.cd, name: f.name.clone(), }; out.add(f.entity, &view); diff --git a/examples/game/server/tests/grid_fixture.rs b/examples/game/server/tests/grid_fixture.rs index f8b8e8a61..dcce26ef8 100644 --- a/examples/game/server/tests/grid_fixture.rs +++ b/examples/game/server/tests/grid_fixture.rs @@ -1,15 +1,18 @@ -//! Golden fixture for the Endless Grid's procedural world and movement. +//! Golden fixture for the Endless Grid's procedural world *content* +//! (terrain, biomes, props), which the client still renders from a +//! TypeScript twin. //! //! Writes/compares `examples/game/fixtures/grid-world.json`, which the //! TypeScript client replays in `client/tests/grid-world-parity.test.mjs` //! (bit-exact). Regenerate after an intended change to BOTH -//! `server/src/grid/world.rs` and `client/src/grid/world.ts`: -//! `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. +//! `server/sim/src/grid.rs` and `client/src/grid/world.ts`: +//! `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. Movement is not part +//! of it: the client predicts with the Rust step compiled to WebAssembly +//! (proved by `client/tests/prediction-wasm.test.mjs`). use std::path::PathBuf; -use distributed_game::GameInput; -use game_demos::grid::world::{self, MoveInput, BUTTON_SPRINT, DEFAULT_SEED}; +use game_demos::grid::world::{self, DEFAULT_SEED}; use serde_json::{json, Value}; const CELLS: [(i32, i32); 6] = [ @@ -40,52 +43,6 @@ fn cell_json(seed: u32, cell: (i32, i32)) -> Value { json!({ "cell": [cell.0, cell.1], "props": props, "heights": heights, "moisture": moisture, "biomes": biomes }) } -/// The densest of a few cells, so the walk bumps into props. -fn busy_cell(seed: u32) -> (i32, i32) { - (0..12) - .map(|i| (i, 2)) - .max_by_key(|c| { - world::cell_props(seed, *c) - .iter() - .filter(|p| p.solid) - .count() - }) - .unwrap() -} - -fn walk(seed: u32) -> Value { - let cell = busy_cell(seed); - let props = world::cell_props(seed, cell); - // Head for each solid prop in turn (pushing into it), then wander off. - let (mut x, mut y) = (16.0f32, 16.0f32); - let mut steps = Vec::new(); - let targets: Vec<(f32, f32)> = props - .iter() - .filter(|p| p.solid) - .map(|p| (p.x, p.y)) - .chain([(40.0, 16.0), (16.0, -5.0)]) - .collect(); - for (k, (tx, ty)) in targets.iter().enumerate() { - for _ in 0..60 { - let (dx, dy) = (tx - x, ty - y); - let l = (dx * dx + dy * dy).sqrt().max(1e-3); - let input = MoveInput { - mx: (dx / l * 127.0) as i8, - my: if k % 3 == 0 { - -128 - } else { - (dy / l * 127.0) as i8 - }, - buttons: if k % 2 == 0 { BUTTON_SPRINT } else { 0 }, - }; - let decoded = MoveInput::from_payload(&input.to_payload()).unwrap(); - (x, y) = world::step(x, y, decoded, &props); - steps.push(json!({ "input": [input.mx, input.my, input.buttons], "x": x, "y": y })); - } - } - json!({ "cell": [cell.0, cell.1], "start": [16.0, 16.0], "steps": steps }) -} - fn build() -> Value { let seed = DEFAULT_SEED; let hashes = [0u32, 1, 0xdead_beef, u32::MAX].map(world::hash32); @@ -94,16 +51,14 @@ fn build() -> Value { world::mix(0, 0, i32::MIN, i32::MAX), ]; json!({ - "description": "Endless Grid parity: Rust grid::world vs client/src/grid/world.ts", + "description": "Endless Grid world-content parity: Rust game_sim::grid vs client/src/grid/world.ts", "constants": { "seed": seed, "contentVersion": world::CONTENT_VERSION, "cell": world::CELL, - "propMargin": world::PROP_MARGIN, "hysteresis": world::HYSTERESIS, - "playerRadius": world::PLAYER_RADIUS, "walk": world::WALK_SPEED, "sprint": world::SPRINT_SPEED, + "propMargin": world::PROP_MARGIN, "hashes": hashes, "mix": mixes, }, "cells": CELLS.iter().map(|c| cell_json(seed, *c)).collect::>(), - "walk": walk(seed), }) } @@ -118,8 +73,7 @@ fn render(v: &Value) -> String { let sep = if i + 1 == cells.len() { "" } else { "," }; out += &format!(" {cell}{sep}\n"); } - out += &format!(" ],\n \"walk\": {}\n}}\n", v["walk"]); - out + out + " ]\n}\n" } #[test] From bb6233d067c265d7dd2363532270657009a4a5f7 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 00:52:38 -0500 Subject: [PATCH 195/484] docs(game): document client prediction compiled to WebAssembly Prediction guide in distributed_game (declaring #[predict], recording it in the surface, building with game-wasm, the binary ABI, float determinism rules incl. transcendentals, measured cost, security), game-wasm in the CLI README, createWasmPrediction and generated-client prediction in the SDK README, and the demos' game_sim layout, the exact-match test and the remaining drawing-only TypeScript. --- distributed_cli/README.md | 36 ++++++-- distributed_game/README.md | 178 +++++++++++++++++++++++++++++++------ examples/game/README.md | 102 ++++++++++++++------- js/README.md | 48 ++++++++-- 4 files changed, 291 insertions(+), 73 deletions(-) diff --git a/distributed_cli/README.md b/distributed_cli/README.md index 10213cc7e..d3a2468cb 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -267,15 +267,16 @@ prove ownership. Unsupported or unprovable selections fail at build time with their source location; the compiler does not emit a partial normalization plan or an adapter-specific route registry. -## `distributed game-manifest` / `distributed game-client` — typed game clients +## `distributed game-manifest` / `game-client` / `game-wasm` — typed game clients For [`distributed_game`](../distributed_game/README.md#generated-clients) zones. The zone's authoring derives (`#[derive(Replicated)]`, -`#[derive(GameInput)]`, `#[derive(GameEvent)]`) describe a versioned -`GameSurface` (schema v1): kinds with fields, wire types, priorities and -client correction defaults, the input layout with its sanitize rules, -events and the records they mention. It is deliberately separate from the -GraphQL client manifest above. +`#[derive(GameInput)]`, `#[derive(GameEvent)]`, `#[predict]`) describe a +versioned `GameSurface` (schema v2): kinds with fields, wire types, +priorities and client correction defaults, the input layout with its +sanitize rules, events and the records they mention, and the zone's +client-predicted step. It is deliberately separate from the GraphQL client +manifest above. ```bash # Build and run the crate's surface export through the manifest harness @@ -288,6 +289,11 @@ distributed game-client --manifest target/arena.surface.json --out web/src/gener # CI: compare without writing (also catches surface drift via surface.json) distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena --check + +# Compile the zone's `#[predict]` step to web/src/generated/arena/wasm/arena.wasm +# (skipped when the stamp says the sources are unchanged; --check verifies only). +distributed game-wasm --manifest target/arena.surface.json --manifest-path game/Cargo.toml \ + --out web/src/generated/arena ``` `game-manifest` accepts the same `--path` / `--manifest-path` / @@ -301,7 +307,23 @@ and event types, codecs, `onEvent`), `client.ts` (`createClient`, a `index.ts` and `surface.json`, removes stale files it generated earlier, and refuses to delete files it did not. Output is deterministic. `--import-extension ts|js|none` picks the specifier style between the -generated files (default `ts`, for Vite and Node type stripping). +generated files (default `ts`, for Vite and Node type stripping). A surface +with a predicted step also gets `predict.ts` (state and context layouts, +`PREDICT_WASM_URL`, `createPrediction`), and `createClient` +predicts with the compiled step by default. + +`game-wasm` builds the Cargo package the surface names as the step's +declarer (`cargo rustc --release --target wasm32-unknown-unknown +--crate-type cdylib`; install the target with `rustup target add +wasm32-unknown-unknown`), checks the module is self-contained (no imports) +and exports the prediction ABI (`memory`, `dg_predict_abi`, +`dg_predict_buffer`, `dg_predict_`), and writes +`/wasm/.wasm` plus a stamp (the source fingerprint of the +package and its local dependencies — the same one browser WASM pures use — +the `rustc` identity and the module hash). The module is a build output: +keep `wasm/` out of version control and run `game-wasm` before bundling. +Unlike browser WASM pures it needs no wasm-pack, wasm-bindgen glue or JSON +bridge; the SDK instantiates the module directly over a binary ABI. ## `distributed describe` — manifest as JSON diff --git a/distributed_game/README.md b/distributed_game/README.md index 5021362af..cb0a21474 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -25,8 +25,9 @@ the browser, but the client SDK has no rendering dependency. - [Try it](#try-it) - [Build a zone](#build-a-zone) - [Guides](#guides): game loop · input · what clients see · the client SDK · - generated clients · saving progress · scaling out · live updates · lag - compensation · testing and operations · security + generated clients · client prediction (Rust → WebAssembly) · saving + progress · scaling out · live updates · lag compensation · testing and + operations · security - [Design decisions](#design-decisions) - [Status and limits](#status-and-limits) - [Reference](#reference) @@ -111,8 +112,10 @@ Then open `http://localhost:5173//`. Each page explains what to try. A zone is a struct plus a few trait methods. You describe **what clients see**, **what they send** and **what you tell them** as plain Rust structs -with derives; the engine encodes them, and `distributed game-client` -generates the matching TypeScript, so field order, ids and quantization are +with derives, and the rule clients **predict** as a plain Rust function; +the engine encodes them, `distributed game-client` generates the matching +TypeScript and `distributed game-wasm` compiles the predicted step to +WebAssembly, so field order, ids, quantization and movement rules are written down exactly once. This zone is a dot that players push left and right: @@ -146,6 +149,20 @@ enum RoomEvent { Hello { entity: u32 }, } +/// The predicted fields of a `dot` (named after the kind's fields). +#[derive(Clone, Copy, GameRecord)] +struct DotState { + x: f32, +} + +/// The movement rule: run by `on_tick` on the server and, compiled to +/// WebAssembly, by the browser to predict its own dot. One input is one +/// fixed 30 Hz frame. +#[predict(PushStep, kind = "dot")] +fn push_step(state: &DotState, input: &Push, _context: &(), _dt: f32) -> DotState { + DotState { x: state.x + f32::from(input.dx) * 5.0 / 30.0 } +} + struct Room { x: f32 } impl Zone for Room { @@ -171,7 +188,7 @@ impl Zone for Room { let players: Vec<_> = ctx.players().map(|p| p.id).collect(); for p in players { for input in ctx.take_inputs(p, ConsumePolicy::Drain) { - self.x += f32::from(input.input.dx) * 5.0 * ctx.dt_secs(); + self.x = push_step(&DotState { x: self.x }, &input.input, &(), ctx.dt_secs()).x; } } } @@ -184,7 +201,9 @@ impl Zone for Room { /// Everything a browser needs to know about this zone, for the generator. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("room").events::() + GameSurface::for_zone::("room") + .events::() + .predict::() } // Drive it directly (tests, tools) with a manual clock: @@ -215,11 +234,12 @@ Generate the browser client from `game_surface` (see ```sh distributed game-manifest --entrypoint my_game::game_surface --out room.surface.json distributed game-client --manifest room.surface.json --out web/src/generated/room +distributed game-wasm --manifest room.surface.json --out web/src/generated/room # push_step → wasm/room.wasm ``` -Connect a browser with it. The input encoder, the correction defaults and -the event decoders are generated; you write only the prediction rule (the -same rule as `on_tick`) and drawing: +Connect a browser with it. The input encoder, the correction defaults, the +event decoders and prediction (`push_step`, compiled) are generated; you +write only drawing: ```ts import { InputPacer } from '@hops-ops/distributed/game'; @@ -227,9 +247,8 @@ import { createRoomClient, dotFields, isDot } from './generated/room/index.ts'; const room = createRoomClient({ url: (zone) => `wss://game.example/zones/${zone}`, - ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role), // your backend signs these - prediction: { predict: (s, push, dtMs) => ({ x: Number(s.x) + (push.dx * 5 * dtMs) / 1000 }) } -}); + ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role) // your backend signs these +}); // predicts with wasm/room.wasm; `room.prediction.ready` once loaded room.on('hello', (hello) => room.client.setControlledEntity(hello.entity)); // typed payload await room.client.connect('room-1'); const pacer = new InputPacer({ tickRate: () => room.client.authority?.connection.welcome?.tickRate }); @@ -352,7 +371,9 @@ zone's typed fields, input encoder, events and correction defaults. between two received states, so movement is smooth whatever the network does. The delay adapts to measured latency and jitter (`AdaptiveDelay`). - **Prediction.** The player's own entity moves the moment they press a - key, using your `predict` function (the same rule as the server). Each + key, using a `predict` function — with a generated client, the zone's + `#[predict]` step compiled to WebAssembly (see + [Client prediction](#client-prediction-rust--webassembly)). Each Delta, the client replays not-yet-acknowledged inputs on top of the server's state; any difference is resolved per field (`ease`, `snap` or `replace`). `setPredictionEnabled(false)` turns it off, to feel the raw @@ -370,14 +391,17 @@ zone's typed fields, input encoder, events and correction defaults. ### Generated clients The derives also describe the zone for the browser. A **game surface** -(`GameSurface`, versioned JSON, schema v1) lists the zone's kinds with +(`GameSurface`, versioned JSON, schema v2) lists the zone's kinds with their fields, wire types, priorities and correction defaults, its input -layout and sanitize rules, its events and the records they mention. -Export one function per zone type, conventionally `game_surface`: +layout and sanitize rules, its events and the records they mention, and +its predicted step. Export one function per zone type, conventionally +`game_surface`: ```rust,ignore pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("arena").events::() + GameSurface::for_zone::("arena") + .events::() + .predict::() } ``` @@ -391,15 +415,105 @@ imports only `@hops-ops/distributed/game`: | `schema.ts` | `KIND` ids, `PlayerFields` interfaces with `isPlayer(e)` / `playerFields(e)` over rendered or replica entities (camelCase properties), `FIELD_TYPES`, `CORRECTIONS` | | `input.ts` | the input interface, `BITS` / `BUTTON`, `encodeInput`, `decodeInput`, `sanitizeInput` (what the server will simulate) | | `events.ts` | record and event interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | -| `client.ts` | `createClient(options)`: a `GameClient` with the encoder and correction defaults wired in, a typed `on(name, handler)` and `send(input)` | +| `client.ts` | `createClient(options)`: a `GameClient` with the encoder and correction defaults wired in (and, with a predicted step, prediction by the compiled step), a typed `on(name, handler)` and `send(input)` | +| `predict.ts` | with a `#[predict]` step: `PREDICT`, the state/context layouts, `PREDICT_WASM_URL` (`./wasm/.wasm`) and `createPrediction` | | `index.ts`, `surface.json` | re-exports; the surface it came from | The output is deterministic, so check it in and run `--check` in CI: a changed Rust definition then fails the build until the client is regenerated. The binary protocol is unchanged; the generated code only -removes the hand-written glue around it. Prediction functions stay -hand-written (they must match `on_tick` bit for bit), but they use the -generated input type, sanitize and field wire types. +removes the hand-written glue around it. The compiled step +(`distributed game-wasm`, `wasm/.wasm`) is a build output: ignore +`wasm/` in version control and build it before bundling. + +### Client prediction (Rust → WebAssembly) + +Prediction is an optimistic update at tick rate: the client applies each +input to its own entity at once and, on every Delta, replays the inputs the +server has not acknowledged yet on top of the authoritative state. That is +only invisible if the client's step is *exactly* the server's. So the step +is declared **once**, in Rust, and the browser runs it compiled to +WebAssembly — there is no TypeScript twin to keep in sync. + +```rust,ignore +/// Predicted fields of the `player` kind (same names, plain scalar types: +/// `f32` for quantized floats, u8/u16/u32/i32/bool otherwise). +#[derive(Clone, Copy, GameRecord)] +pub struct MoveState { pub x: f32, pub y: f32, pub vx: f32, pub vy: f32, pub dash: u8, pub cd: u8 } + +/// Read-only data the client supplies (optional; `&()` for none). +#[derive(Clone, Copy, GameRecord)] +pub struct GridContext { pub seed: u32, pub cx: i32, pub cy: i32 } + +#[predict(GridStep, kind = "walker")] +pub fn grid_step(state: &WalkerState, input: &MoveInput, context: &GridContext, _dt: f32) -> WalkerState { + let props = cell_props(context.seed, (context.cx, context.cy)); + let (x, y) = step(state.x, state.y, *input, &props); + WalkerState { x, y } +} +``` + +- **Declare.** `#[predict(StepType, kind = "…")]` on a + `fn(&State, &Input, &Context, dt: f32) -> State` keeps the function and + adds `StepType: PredictStep`. `Input` is the zone's `GameInput`; the + WASM side decodes it with `from_payload`, so it steps exactly what the + server simulates (ranges clamped, unknown buttons cleared). Call the + function from `on_tick` (or the code it wraps) so there is one rule. +- **Record.** `GameSurface::…​.predict::()` checks that the kind + is replicated, that the step takes the zone's input, and that every state + field is a field of the kind with a matching type (it panics at export + time otherwise), then records the step, its state/context records and + the declaring Cargo package in the surface. +- **Build.** `distributed game-wasm --manifest + --manifest-path --out ` compiles that package + for `wasm32-unknown-unknown` (`cargo rustc --release --crate-type + cdylib`) and writes `wasm/.wasm`, stamped with the sources' + fingerprint. Put the step and everything it reads in a crate without + server-only dependencies (the demos use `game_sim`); `distributed_game` + itself compiles to `wasm32` with default features. +- **Run.** The generated `createClient` loads the module and predicts + with it; `client.prediction.setContext(…)` provides the context. + `prediction: false` turns prediction off; a `predict` in `prediction` + replaces it. + +**Binary ABI (v1).** The module imports nothing and exports `memory`, +`dg_predict_abi() -> 1`, `dg_predict_buffer()` (a 64 KiB scratch area) and +`dg_predict_(state_len, input_len, context_len, dt) -> i32`. The client +writes `state ‖ input ‖ context` into the scratch area — state and context +with the payload codec (binary32 floats, never rounded through JSON or +`f64`), the input as its wire payload — calls the step, and reads the next +state from the start of the buffer (a negative result is an error code). +`prediction::step_bytes::` runs the same path natively. + +**Determinism.** Native and WASM results are bit-identical when the step +uses only operations that are correctly rounded on both targets: `+ - * /`, +`sqrt`, `abs`, `min`/`max`, `floor`/`ceil`/`trunc`/`round`, comparisons and +integer arithmetic (Rust never fuses `a * b + c` into an FMA on its own). +Transcendentals are **not** portable: `sin`, `cos`, `atan2`, `exp`, `ln`, +`powf` use the platform libm natively and another implementation on +`wasm32`. If a step needs them, use one deterministic implementation on +both sides (the `libm` crate, or a polynomial in plain arithmetic). Never +produce NaN (payloads may differ). Prefer fixed command frames (one input += one tick, `dt` ignored) and snap replicated floats to their wire +quantization after each step, so the server holds exactly what clients +decode. The demos prove all of this per step function: `game-demos +predict-trace` prints native traces over recorded input streams +(scripted, random, every sanitize edge) and +`examples/game/client/tests/prediction-wasm.test.mjs` requires every state +from the compiled module to be byte-identical (16 788 frames across the +four steps — 20 744 comparisons over the five surfaces' modules — +including the grid's prop collisions). + +**Cost.** Measured on Apple silicon: ~0.2 µs per raw ABI call, ~0.8 µs per +`predict` (fields → bytes → step → fields) in Node 24 and ~1.2 µs in Chrome +156; a reconciliation that replays 10 pending inputs takes ~8–12 µs. +At 30 Hz input and 20 Hz Deltas that is ≈ 0.2 ms of prediction per +second — far below one 33 ms frame. The module is ~90 KB (the demos' four +steps plus the grid's world generation). + +**Security.** Prediction is cosmetic. The server never runs client code +and never trusts a predicted value: it simulates the inputs itself, and +every Delta replaces the prediction with the authoritative state. ### Saving progress without pausing the game @@ -529,6 +643,12 @@ unlimited rewind. - **Static world from a seed.** Terrain and props are a pure function of seed and content version, generated identically on server and client. Only things that change are replicated. +- **Prediction compiled from the server's Rust, over a binary ABI.** A + TypeScript twin of the movement code drifts the first time someone + changes one side; running the same Rust as WebAssembly cannot. JSON + bridges (as browser WASM pures use) round-trip `f32` through `f64` and + allocate per call; a fixed scratch buffer with codec-encoded state keeps + every float bit and costs about a microsecond per step. - **Binary protocol with the schema sent on connect.** Small, diff-friendly frames, and any client can decode them without generated code. @@ -546,8 +666,11 @@ unlimited rewind. was unavailable) and the Redis leaderboard against a real Redis (only a fake). - No production deployment or load testing beyond local bots. -- WebSocket only (no UDP or WebTransport). No built-in physics. Input - replay on the client assumes your `predict` matches `on_tick` exactly. +- WebSocket only (no UDP or WebTransport). No built-in physics. Exact + input replay needs the predicted step to be what `on_tick` runs: declare + it once with `#[predict]` and call it from the zone. Steps must stay + within portable float operations (see + [Client prediction](#client-prediction-rust--webassembly)). --- @@ -565,16 +688,19 @@ errors for unsupported types and attributes. | `GameEvent` | enum / struct | `#[game_event(id = N, name = "..")]` per variant / on the struct | `quant`, `angle`, `field_type`, `long` | `GameEvent` (`decode_event`, `to_payload`) + id consts | | `GameRecord` | struct | – | `quant`, `angle`, `field_type`, `long` | `Wire` (nested payload record) | | `FactCommand` | struct (`Serialize`) | `#[fact(command = CONST_OR_LITERAL, key(field, ..))]` | – | `FactCommand` (`COMMAND`, `dedupe_parts`) | +| `#[predict]` (attribute) | `fn(&State, &Input, &Context, f32) -> State` | `#[predict(StepType, kind = "name")]` | – | `struct StepType: PredictStep` + the `wasm32` export `dg_predict_` | `schema![A, B]` builds an `EntitySchema`; `GameSurface::for_zone::(name)` -(kinds from `Z::schema()`, input from `Z::Input`) `.events::()` builds -the surface; `codec` holds the shared value codec (`Wire`, `WireType`). +(kinds from `Z::schema()`, input from `Z::Input`) `.events::()` +`.predict::()` builds the surface; `codec` holds the shared value codec +(`Wire`, `WireType`); `prediction` the predicted-step trait, its ABI +(`run_abi`, `step_bytes`) and the float rules. ## Features | Feature | Adds | Deps | |---|---|---| -| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication, authoring derives, game surface | `serde`, `serde_json`, `distributed_game_macros` | +| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication, authoring derives, game surface, predicted steps (compiles to `wasm32-unknown-unknown`, where `#[predict]` exports its steps) | `serde`, `serde_json`, `distributed_game_macros` | | `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | | `cell` | `cell::CellFactSink` → `AggregateCell::dispatch_idempotent`, `stamp_event_record` | `distributed`, `sha2` | | `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | diff --git a/examples/game/README.md b/examples/game/README.md index 9226edc41..414fd7149 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -8,7 +8,7 @@ guests and lets any page change the network simulation. | Demo | Run | Mechanic it demonstrates | |---|---|---| -| **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (shared Rust/TS movement step, bit-exact), interpolation of remote entities, live latency/jitter/loss | +| **Arena** | `./run.sh arena` | Fixed 30 Hz tick / 20 Hz patches, binary deltas, interest management (view ring, drones pop in/out), client prediction + reconciliation (the Rust movement step compiled to WebAssembly, bit-exact), interpolation of remote entities, live latency/jitter/loss | | **Mob Pit** | `./run.sh mobpit` | Authoritative melee combat vs. 12 telegraphing mobs; kills are **non-blocking durable facts** committed exactly once into per-player native SQLite cells (`cell-sqlite`); "slow storage" toggle (tick stays flat, pending facts climb); `kill -9` crash recovery | | **Leaderboard** | `./run.sh leaderboard` | Same server as Mob Pit: kills/XP sorted-set boards (in-memory or Redis) fed fire-and-forget with idempotent apply keys, top 10 pushed live, your rank + neighbours, rebuild from the cells' event history | | **Shooting Gallery** | `./run.sh gallery` | Lag compensation: hitscan shots resolved with `ctx.rewind().hit_test_shot` at the shooter's view time (`client_tick` + interpolation delay in the payload), `max_rewind` clamp, per-shot compensation on/off, predicted vs confirmed hits | @@ -27,16 +27,29 @@ for the kinds (`arena::PlayerView`, `mobpit::zone::MobView`, …), `gallery::ShotInput`, …), `#[derive(GameEvent)]` enums for events (`mobpit::zone::PitEvent`) and `#[derive(FactCommand)]` on the cell command inputs they emit as facts (`mobpit::crawler::RecordKillInput`). -Each demo module exports `game_surface()`; `run.sh gen` runs `distributed -game-manifest` on it and `distributed game-client` writes -`client/src/generated//` (checked in, verified by `run.sh smoke`). -The pages use the generated `createClient`, typed field accessors +The movement that clients predict is declared once with `#[predict]` in +the `game_sim` crate (`server/sim/`, no server dependencies): +`arena_step` (Arena, The Freeze), `pit_step` (Mob Pit), `hood_step` (Boss +Ripple) and `grid_step` (Endless Grid, whose context is the world seed and +cell); the zones call those functions in `on_tick`. Each demo module +exports `game_surface()`; `run.sh gen` runs `distributed game-manifest` on +it, `distributed game-client` writes `client/src/generated//` +(checked in, verified by `run.sh smoke`) and `distributed game-wasm` +compiles the step to `client/src/generated//wasm/.wasm` +(gitignored, rebuilt only when the Rust sources change; `run.sh ` +builds it too). The pages use the generated `createClient`, which +predicts with the compiled step, typed field accessors (`mobFields(entity).hp`), the input encoder and typed `on('kill', …)` -handlers; only the prediction steps (`arena/movement.ts`, `grid/world.ts`, -twins of the Rust step) are hand-written, and they import the generated -input type, sanitize and wire quantization. +handlers. No movement code is written in TypeScript; what remains +hand-written for drawing is `arena/floor.ts` (floor size, pillars, capsule +radius — checked against the native build) and `grid/world.ts` (the grid's +terrain/props generation for rendering, see below). The Shooting Gallery +predicts hits by ray-testing what it renders, not movement, so it has no +predicted step. -Requirements: Rust (stable), Node ≥ 22.18 (runs `.ts` test imports natively). +Requirements: Rust (stable) with the `wasm32-unknown-unknown` target +(`rustup target add wasm32-unknown-unknown`), Node ≥ 22.18 (runs `.ts` +test imports natively). ## Run @@ -126,13 +139,16 @@ is derived from it) and keeping hibernation snapshots under one - **World.** Cell `(x, y)` is zone `grid..` (canonical integers, |x|,|y| ≤ 10⁶; the server uses `FlatTopology`, the dots are not a hierarchy). Its terrain height, biome and props are a pure function of - `(seed, x, y, CONTENT_VERSION)` in `server/src/grid/world.rs` and its twin - `client/src/grid/world.ts` (u32 hashing + binary32 value noise; checked + `(seed, x, y, CONTENT_VERSION)` in `server/sim/src/grid.rs` and, for + rendering only, its twin `client/src/grid/world.ts` (u32 hashing + + binary32 value noise; checked bit-for-bit by `fixtures/grid-world.json`). Props sit inside 8 m sub-cells 2 m from their edges, so lines every 8 m are free trails and no prop reaches across a border. Seed: `DG_GRID_SEED`. -- **Zones.** A cell simulates walkers (predicted with the shared step, - colliding with the cell's props) and 2–4 critters. Past a border by +- **Zones.** A cell simulates walkers (predicted by `grid_step` compiled to + WebAssembly, which generates and collides with the cell's props itself; + the client sets its context from the hello's seed and the authoritative + cell) and 2–4 critters. Past a border by 0.5 m the walker is handed off with its position in the neighbour's frame (`ctx.handoff`); the SDK follows the Handoff — through a Redirect when the neighbour lives on the other host (`HashRing`, 64 vnodes). @@ -186,52 +202,64 @@ hood to fight there. │ GameClient (SDK) │ ───────────────► │ │ guest principal (server-made) │ │ ├ GameConnection ws ───────┼─ /zones/{zone} ─►│ │ /dev/netsim → set_net_sim │ │ ├ EntityReplica (interp.) │ ◄─ Welcome/Delta │ └ GameServer::serve_with │ - │ └ Predictor ── movement.ts ═╪═ parity fixture ═╪══► ZoneHost 30 Hz │ - │ src/shared/ hud · input · scene │ │ └ arena::movement (twin) │ + │ └ Predictor ── arena.wasm │ │ ZoneHost 30 Hz │ + │ src/shared/ hud · input · scene │ │ └ game_sim::arena::arena_step │ │ src/generated/arena (typed glue) │ GET /metrics │ GET /metrics (Prometheus) │ + │ └ wasm/arena.wasm ◄═════════════╪══ distributed game-wasm (same Rust, wasm32) ══╝ │ └──────────────────────────────────┘ └─────────────────────────────────────┘ ``` Prediction is exact because (1) every input is one command frame of exactly one tick (sent by the SDK's `InputPacer`), consumed one per tick with a small -credit bank (`distributed_game::InputCredits`, `arena::MAX_CREDITS`), (2) the step uses binary32 arithmetic only -(`Math.fround` in TS) without trig, and (3) the server snaps its state to the -wire quantization after each step, so the client rebases on exactly what the -server holds. `fixtures/arena-movement.json` (written by Rust) is replayed by -the TS step in `client/tests/movement-parity.test.mjs`. +credit bank (`distributed_game::InputCredits`, `arena::MAX_CREDITS`), (2) the +client runs the server's own Rust step compiled to WebAssembly, over a +binary ABI that keeps every binary32 bit, and the step uses only operations +that round identically on every target (`+ - * /`, `sqrt`, comparisons; no +trig), and (3) the server snaps its state to the wire quantization after +each step, so the client rebases on exactly what the server holds. +`client/tests/prediction-wasm.test.mjs` replays the native traces of +`game-demos predict-trace` (recorded input streams per step function) +through every surface's module and requires byte-identical states; it also +times prediction (≈ 1 µs per step, ≈ 8–12 µs for a reconciliation +replaying 10 inputs). ## Layout ``` examples/game/ run.sh one-command dev + smoke runner - fixtures/ cross-language golden data (Rust writes, TS checks) - server/ Rust crate `game_demos`, its own cargo workspace - src/main.rs `game-demos ` subcommands + fixtures/ grid-world.json: grid content golden data (Rust writes, world.ts checks) + server/ Rust crate `game_demos`, its own cargo workspace (with sim/) + sim/ crate `game_sim`: the `#[predict]` steps (arena.rs movement, mobpit.rs, + ripple.rs inputs + steps, grid.rs world + walker step); compiled + natively for the server and to wasm32 for the browser + src/main.rs `game-demos ` subcommands (+ hidden `predict-trace`) + src/predict_trace.rs native traces of every step over recorded input streams src/common/ shared: Demo trait, run/spawn, dev routes, guests src/cluster.rs multi-host demos: --host-id/--peer, directory, ownership, snapshots - src/arena/ Arena zone + movement.rs (twin of client movement.ts) + src/arena/ Arena zone (`movement` = `game_sim::arena`) src/mobpit/ Mob Pit zone, Crawler cell aggregate, fact sink, leaderboards, dev routes src/gallery/ Shooting Gallery zone (targets, rewind hit tests) src/freeze/ The Freeze zone, content packs, two-host world + admin routes - src/grid/ Endless Grid zone, world.rs (twin of world.ts), dev map routes + src/grid/ Endless Grid zone (`world` = `game_sim::grid`), dev map routes src/ripple/ Boss Ripple tiers and placement - tests/ arena_smoke.rs (bots, dev routes), movement_fixture.rs, + tests/ arena_smoke.rs (bots, dev routes), mobpit_smoke.rs (facts, slow storage, kill -9 recovery, boards), gallery_smoke.rs, freeze_smoke.rs, grid_smoke.rs, grid_fixture.rs, ripple_smoke.rs (+ support/ for two in-process hosts) client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/generated// generated by `run.sh gen` (do not edit): schema/input/events/client.ts, - surface.json; `mobpit` also serves the leaderboard page + predict.ts, surface.json, wasm/.wasm (gitignored build output); + `mobpit` also serves the leaderboard page src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, latest.ts, style.css - src/arena/ client.ts (headless), main.ts (Babylon), movement.ts + src/arena/ client.ts (headless), main.ts (Babylon), floor.ts (drawing constants) src/mobpit/ client.ts (headless + /dev/mobpit API), main.ts (Babylon), style.css src/leaderboard/ main.ts (DOM page over the observer connection), style.css src/gallery/ client.ts (shots, adaptive delay), main.ts src/freeze/ client.ts (content packs, live patch / reload, admin API), main.ts - src/grid/, src/ripple/ client.ts (headless), main.ts (Babylon); grid/world.ts - tests/ movement-parity, arena-headless, mobpit-headless, leaderboard-headless, + src/grid/, src/ripple/ client.ts (headless), main.ts (Babylon); grid/world.ts (content, rendering) + tests/ prediction-wasm (native ↔ WASM exact match + cost), arena-headless, mobpit-headless, leaderboard-headless, gallery-headless, freeze-headless, grid-world-parity, grid-headless, ripple-headless (+ helpers/demo-server.mjs, helpers/mobpit.mjs, helpers/cluster.mjs for multi-host demos) @@ -249,7 +277,7 @@ examples/game/run.sh mobpit # → http://localhost:5173/mobpit/ examples/game/run.sh leaderboard # same server → http://localhost:5173/leaderboard/ ``` -Controls: WASD / stick move (the Arena's predicted step, same floor and +Controls: WASD / stick move (the Arena's movement, predicted by `pit_step`, same floor and pillars), **Space** attack (120° cone, 2.2 m), **E** dash, **L** slow storage. Mobs wander near home, aggro within 7 m, chase, stop and show a red **telegraph ring** that fills for 0.8 s, then hit everyone inside it. Grunts @@ -372,9 +400,14 @@ pending, recent commits), `GET /dev/mobpit/crawlers` (every cell on disk), `decode_input` = `MyInput::from_payload(bytes)`. Events: a `#[derive(GameEvent)]` enum sent with `ctx.send` / `ctx.broadcast`. Facts: the cell command input with `#[derive(FactCommand)]`. + - Predicted movement: declare the step with `#[predict(Step, kind = "…")]` + in `server/sim/` (with the input type and everything the step reads; + no server-only dependencies), call it from `on_tick`, add + `.predict::()` to the surface and a stream for it in + `src/predict_trace.rs` (the exact-match test fails until you do). - Export `pub fn game_surface() -> GameSurface` from the module and add the demo to `SURFACES` in `run.sh`; `./run.sh gen` writes - `client/src/generated//`. + `client/src/generated//` and compiles the step. - Signed quantities that must rest at zero: `#[quant(centered = R, bits = N)]`. - State shared by the zones and demo-specific dev routes (a durable store, a leaderboard): build both in `common::spawn_with` / @@ -385,8 +418,9 @@ pending, recent commits), `GET /dev/mobpit/crawlers` (every cell on disk), 3. **Client** — `client//index.html` + `src//main.ts`, add the name to `DEMOS` in `vite.config.ts` and a link in `index.html`. Keep networking in `src//client.ts` (no Babylon) so Node can test it: - a thin wrapper over the generated `createClient` (URLs, tickets, - your `predict`). Reuse `DevApi` + `zoneUrl` (tickets), `Hud` (status/RTT/ + a thin wrapper over the generated `createClient` (URLs, tickets; + it predicts with the compiled step — set its context if it has one, and + await `prediction.ready` with the first hello). Reuse `DevApi` + `zoneUrl` (tickets), `Hud` (status/RTT/ jitter/tick/delta B/s/entities + NetSim sliders + `row`/`toggle`), `InputSampler`, `FixedRate`, `cameraRelative`, `toAxis`, `createStage`/`toWorld`/`material`/`createRing`/`LabelLayer`, `latest` diff --git a/js/README.md b/js/README.md index 0eea9695f..a8c40a90b 100644 --- a/js/README.md +++ b/js/README.md @@ -578,7 +578,10 @@ explicit redactor. `@hops-ops/distributed/game` speaks the `distributed_game` binary protocol (golden-tested against the Rust fixtures). The app supplies tickets — a function, so a fresh single-use ticket is fetched whenever a reconnect token -can no longer be used — and a pure `predict` for its own entity. +can no longer be used — and a pure `predict` for its own entity. With a +[generated client](#generated-game-clients) that `predict` is the zone's +own Rust step compiled to WebAssembly; the hand-written form below is the +low-level API. ```ts import { GameClient, InputPacer } from '@hops-ops/distributed/game'; @@ -632,9 +635,11 @@ server-side lag compensation (`replica.interpolationDelayMs`, `connection.stats` exposes cumulative bytes/messages in and out (Delta bytes separately) for bandwidth HUDs. -**Generated clients.** Rather than writing `encodeInput`, field names, -event ids and correction tables by hand, generate them from the zone's -Rust definitions: `distributed game-manifest` + `distributed game-client` +### Generated game clients + +Rather than writing `encodeInput`, field names, event ids, correction +tables or the prediction step by hand, generate them from the zone's Rust +definitions: `distributed game-manifest` + `distributed game-client` (see the [`distributed_game` README](../distributed_game/README.md#generated-clients)) write a typed module per zone that wraps this `GameClient` — `createArenaClient(options)`, `playerFields(entity)`, `encodeInput`, @@ -643,6 +648,36 @@ payload codec (`encodePayload`, `decodePayload`, `sanitizePayload`, `WireType`) and helpers (`onGameEvent`, `decodeGameEvent`, `fieldNumber`, `mergeCorrections`), which hand-written code may use directly. +**Prediction from WebAssembly.** When the zone declares its step with +`#[predict]`, `distributed game-wasm` compiles it to +`/wasm/.wasm` and the generated `createClient` +predicts with it by default (`prediction: false` turns prediction off, a +`predict` in `prediction` replaces it, `wasm` overrides where the module +is loaded from). The client exposes the step as `prediction`: + +```ts +const grid = createGridClient({ url, ticket }); // loads wasm/grid.wasm +await grid.prediction?.ready; // instantiated +grid.prediction?.setContext({ seed, cx: 3, cy: -2 }); // steps with a context +``` + +Underneath, `createWasmPrediction({ source, exportName, state, context, +encodeInput })` wraps a `PredictModule` (`loadPredictModule(source)`: +URL, `file:` URL in Node, bytes, `Response` or compiled module; one +instance per URL) as a `PredictFn`. The ABI is binary: the controlled +entity's predicted fields (`PredictStateLayout`, binary32 floats), the +input payload and the context are written into the module's scratch +buffer and the next state is read back — no JSON, no allocation across the +boundary. Until the module is ready (and, for steps with a context, until +`setContext`), `predict` leaves the state unchanged; the next +reconciliation replays every pending input through the step. Cost +(Node 24 / Chrome 156, Apple silicon): ~0.8–1.2 µs per predicted step, ~8–12 µs +for a reconciliation replaying 10 pending inputs — well under 0.1 % of a +33 ms frame at 30 Hz. Bundlers emit the module as an asset through +`new URL('./wasm/.wasm', import.meta.url)` (Vite does out of the +box); with `--import-extension js` copy `wasm/` next to the emitted +JavaScript. + ## Protocol and security boundaries Every accepted artifact and response is protocol v1 and carries an exact @@ -677,8 +712,9 @@ duplicated as decision documents in this package. - `@hops-ops/distributed/react` — provider and query hook over the same replica. - `@hops-ops/distributed/game` — binary `distributed_game` zone protocol client: codec, `GameConnection` (handshake, reconnect, clock sync), - interpolating `EntityReplica`, `Predictor` reconciliation and the - multi-zone `GameClient` with handoff, `AdaptiveDelay` and `InputPacer`. + interpolating `EntityReplica`, `Predictor` reconciliation (with + `createWasmPrediction` for steps compiled from Rust) and the multi-zone + `GameClient` with handoff, `AdaptiveDelay` and `InputPacer`. See `distributed_game/PROTOCOL.md`. All other subpaths are private and blocked by the package export map. From 2663b3969d64dc3a986cb1eff37235ac9c7adcba Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 11:12:33 -0500 Subject: [PATCH 196/484] feat(game-sdk): call #[game_pure] functions over the WASM ABI A compiled game module may export pure functions next to its predicted step: dg_pure_(arg_len) -> i32 over the same scratch buffer and ABI v1 (argument encoding in, result encoding out, -6 when the argument does not decode). PredictModule.call runs one and lists them in `pures`; createWasmPures wraps a set of them as typed synchronous functions (payload codec, binary32 stays exact) with ready / loaded / module, sharing the instance a URL source already loaded. --- js/src/game/index.ts | 3 ++ js/src/game/wasm-prediction.ts | 38 +++++++++++++- js/src/game/wasm-pures.ts | 78 ++++++++++++++++++++++++++++ js/tests/fixtures/predict-module.mjs | 20 ++++--- js/tests/game-wasm-pures.test.mjs | 55 ++++++++++++++++++++ 5 files changed, 184 insertions(+), 10 deletions(-) create mode 100644 js/src/game/wasm-pures.ts create mode 100644 js/tests/game-wasm-pures.test.mjs diff --git a/js/src/game/index.ts b/js/src/game/index.ts index b9a0c2e0d..271131bcd 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -11,6 +11,8 @@ * one-input-per-tick pacing for render loops. * - Typed payload codec (`encodePayload`, …) and helpers for clients * generated by `distributed game-client` from a Rust game surface. + * - Rust compiled to WebAssembly: `createWasmPrediction` (a zone's + * `#[predict]` step) and `createWasmPures` (`#[game_pure]` functions). */ export { MAX_BLOB_LEN, @@ -157,6 +159,7 @@ export { type WasmPredictionOptions, type WasmSource } from './wasm-prediction.js'; +export { createWasmPures, type WasmPureSpec, type WasmPures, type WasmPuresHandle } from './wasm-pures.js'; export { AdaptiveDelay, InputPacer, diff --git a/js/src/game/wasm-prediction.ts b/js/src/game/wasm-prediction.ts index b0624d077..8c34e978a 100644 --- a/js/src/game/wasm-prediction.ts +++ b/js/src/game/wasm-prediction.ts @@ -13,6 +13,10 @@ * * Generated clients (`distributed game-client`) wire this in for you: * `createClient` predicts with the compiled step by default. + * + * The same module may also export pure functions (`#[game_pure]`, + * `dg_pure_(arg_len) -> i32`, see `wasm-pures.ts`): `PredictModule.call` + * runs one over the same scratch area. */ import { readWire, writeWire, encodePayload, type PayloadLayout, type WireType } from './codec.js'; import type { PredictFn } from './prediction.js'; @@ -52,15 +56,17 @@ export class PredictAbiError extends Error { [-2]: 'state does not decode', [-3]: 'input payload rejected', [-4]: 'context does not decode', - [-5]: 'next state does not fit' + [-5]: 'output does not fit', + [-6]: 'argument does not decode' }; - super(`dg_predict_${exportName} failed (${code}): ${reasons[code] ?? 'unknown error'}`); + super(`${exportName.startsWith('dg_') ? exportName : `dg_predict_${exportName}`} failed (${code}): ${reasons[code] ?? 'unknown error'}`); this.name = 'PredictAbiError'; this.code = code; } } type StepExport = (stateLen: number, inputLen: number, contextLen: number, dt: number) => number; +type PureExport = (argLen: number) => number; /** An instantiated prediction module. One instance can serve every client. */ export class PredictModule { @@ -69,6 +75,7 @@ export class PredictModule { readonly #pointer: number; #view: Uint8Array; readonly #steps = new Map(); + readonly #pures = new Map(); constructor(instance: WebAssembly.Instance) { const exports = instance.exports; @@ -100,6 +107,33 @@ export class PredictModule { .map((name) => name.slice('dg_predict_'.length)); } + /** Pure function names (`dg_pure_`) this module exports. */ + get pures(): readonly string[] { + return Object.keys(this.#exports) + .filter((name) => name.startsWith('dg_pure_')) + .map((name) => name.slice('dg_pure_'.length)); + } + + /** + * Call the pure function `dg_pure_` with an encoded + * argument (empty for none). Returns a copy of the encoded result. + */ + call(exportName: string, arg: Uint8Array): Uint8Array { + let fn = this.#pures.get(exportName); + if (fn === undefined) { + const found = this.#exports[`dg_pure_${exportName}`]; + if (typeof found !== 'function') throw new TypeError(`module has no pure function dg_pure_${exportName}`); + fn = found as PureExport; + this.#pures.set(exportName, fn); + } + const name = `dg_pure_${exportName}`; + if (arg.length > PREDICT_SCRATCH_BYTES) throw new PredictAbiError(name, -1); + this.#scratch().set(arg, 0); + const length = fn(arg.length); + if (length < 0) throw new PredictAbiError(name, length); + return this.#scratch().slice(0, length); + } + /** * Run `dg_predict_` once. Returns a copy of the encoded next * state. `dt` is the frame length in seconds (rounded to binary32). diff --git a/js/src/game/wasm-pures.ts b/js/src/game/wasm-pures.ts new file mode 100644 index 000000000..9ab694e8a --- /dev/null +++ b/js/src/game/wasm-pures.ts @@ -0,0 +1,78 @@ +/** + * Pure game functions compiled to WebAssembly (`#[game_pure]` in + * `distributed_game::pure`, built by `distributed game-wasm` into the same + * module as the zone's predicted step). + * + * Each function is an export `dg_pure_(arg_len) -> i32` over the module's + * scratch area (ABI v1): the argument's payload-codec encoding goes in, the + * result's encoding comes back at the start of the area. Generated clients + * (`pures.ts`) wrap every function with its types: + * `createGridPures().gridCell({ seed, cx, cy })`. + */ +import { decodeValue, encodeValue, type WireType } from './codec.js'; +import { loadPredictModule, type PredictModule, type WasmSource } from './wasm-prediction.js'; + +/** How to call one pure function: its export and argument / result types. */ +export type WasmPureSpec = Readonly<{ + /** The export is `dg_pure_`. */ + exportName: string; + /** Argument type (omitted: the function takes none). */ + arg?: WireType; + /** Result type. */ + output: WireType; +}>; + +/** Loading state of a set of pure functions. */ +export type WasmPuresHandle = Readonly<{ + /** Resolves when the module is instantiated and exports every function. */ + ready: Promise; + /** True once `ready` resolved. */ + loaded(): boolean; + /** The instantiated module, once loaded. */ + module(): PredictModule | undefined; +}>; + +/** Typed functions `F` (synchronous; they throw until loaded) plus the handle. */ +export type WasmPures = F & WasmPuresHandle; + +const RESERVED = new Set(['ready', 'loaded', 'module']); + +/** + * Wrap the pure functions of a compiled module. Each wrapper encodes its + * argument, calls the export and decodes the result; calls before `ready` + * resolves throw (await `ready`, or check `loaded()`). URL sources share + * one instance with the predicted step (`loadPredictModule` caches them). + */ +export function createWasmPures( + source: WasmSource, + specs: Readonly> +): WasmPures { + let module: PredictModule | undefined; + const ready = loadPredictModule(source).then((loaded) => { + for (const spec of Object.values(specs)) { + if (!loaded.pures.includes(spec.exportName)) { + throw new TypeError(`module has no pure function dg_pure_${spec.exportName}`); + } + } + module = loaded; + }); + ready.catch(() => undefined); // surfaced through `ready` and the calls + const fns: Record unknown> = {}; + for (const [name, spec] of Object.entries(specs)) { + if (RESERVED.has(name)) throw new TypeError(`pure function name ${name} is reserved`); + const empty = new Uint8Array(0); + fns[name] = (arg?: unknown) => { + if (module === undefined) { + throw new Error(`pure function ${spec.exportName} called before its module loaded (await ready)`); + } + const bytes = spec.arg === undefined ? empty : encodeValue(spec.arg, arg); + return decodeValue(spec.output, module.call(spec.exportName, bytes)); + }; + } + return { + ...fns, + ready, + loaded: () => module !== undefined, + module: () => module + } as WasmPures; +} diff --git a/js/tests/fixtures/predict-module.mjs b/js/tests/fixtures/predict-module.mjs index 2737925bd..6e444efb2 100644 --- a/js/tests/fixtures/predict-module.mjs +++ b/js/tests/fixtures/predict-module.mjs @@ -4,7 +4,9 @@ * toolchain. Steps: * * - `dg_predict_`: returns `state_len` (the next state is the state); - * - `dg_predict_fail`: returns -3 (input rejected). + * - `dg_predict_fail`: returns -3 (input rejected); + * - `dg_pure_` for each of `pures`: returns `arg_len` (the result is + * the argument, `#[game_pure]` ABI). */ function leb(value) { const out = []; @@ -28,17 +30,18 @@ function section(id, body) { } /** Bytes of a prediction module (`abi` is what `dg_predict_abi` returns). */ -export function predictModuleBytes({ echo = 'sample_step', abi = 1, buffer = 1024 } = {}) { - const types = [2, 0x60, 0, 1, 0x7f, 0x60, 4, 0x7f, 0x7f, 0x7f, 0x7d, 1, 0x7f]; - const functions = [4, 0, 0, 1, 1]; +export function predictModuleBytes({ echo = 'sample_step', abi = 1, buffer = 1024, pures = [] } = {}) { + const types = [3, 0x60, 0, 1, 0x7f, 0x60, 4, 0x7f, 0x7f, 0x7f, 0x7d, 1, 0x7f, 0x60, 1, 0x7f, 1, 0x7f]; + const functions = [4 + pures.length, 0, 0, 1, 1, ...pures.map(() => 2)]; const memory = [1, 0, 2]; // 2 pages: buffer + 64 KiB scratch const exports = [ - 5, + 5 + pures.length, ...str('memory'), 2, 0, ...str('dg_predict_abi'), 0, 0, ...str('dg_predict_buffer'), 0, 1, ...str(`dg_predict_${echo}`), 0, 2, - ...str('dg_predict_fail'), 0, 3 + ...str('dg_predict_fail'), 0, 3, + ...pures.flatMap((name, i) => [...str(`dg_pure_${name}`), 0, ...leb(4 + i)]) ]; // Signed LEB128 for i32.const (small values only). const sleb = (v) => { @@ -55,11 +58,12 @@ export function predictModuleBytes({ echo = 'sample_step', abi = 1, buffer = 102 }; const body = (code) => [...leb(code.length + 1), 0, ...code]; const code = [ - 4, + 4 + pures.length, ...body([0x41, ...sleb(abi), 0x0b]), ...body([0x41, ...sleb(buffer), 0x0b]), ...body([0x20, 0, 0x0b]), - ...body([0x41, ...sleb(-3), 0x0b]) + ...body([0x41, ...sleb(-3), 0x0b]), + ...pures.flatMap(() => body([0x20, 0, 0x0b])) ]; return new Uint8Array([ 0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, diff --git a/js/tests/game-wasm-pures.test.mjs b/js/tests/game-wasm-pures.test.mjs new file mode 100644 index 000000000..681962041 --- /dev/null +++ b/js/tests/game-wasm-pures.test.mjs @@ -0,0 +1,55 @@ +// Pure functions compiled to WebAssembly (`createWasmPures`, +// `PredictModule.call`): the `dg_pure_` ABI, typed wrappers, errors and +// the load gate. The demos' real Rust functions are checked bit for bit +// against native in `examples/game/client/tests/prediction-wasm.test.mjs`. +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { PredictAbiError, PredictModule, createWasmPures, decodeValue, encodeValue } from '@hops-ops/distributed/game'; + +import { predictModuleBytes } from './fixtures/predict-module.mjs'; + +const POINT = { type: 'record', fields: [['x', { type: 'f32' }], ['label', { type: 'short_str' }]] }; + +test('a module calls pure functions over the scratch buffer', async () => { + const module = await PredictModule.load(predictModuleBytes({ echo: 'step', pures: ['echo', 'same'] })); + assert.deepEqual([...module.pures].sort(), ['echo', 'same']); + assert.deepEqual([...module.steps].sort(), ['fail', 'step'], 'pure functions are not steps'); + const arg = encodeValue(POINT, { x: 0.1, label: 'a' }); + const out = module.call('echo', arg); + assert.deepEqual([...out], [...arg]); + assert.notEqual(out.buffer, arg.buffer, 'a copy, not a view of wasm memory'); + assert.deepEqual(decodeValue(POINT, out), { x: Math.fround(0.1), label: 'a' }); + assert.equal(module.call('echo', new Uint8Array(0)).length, 0); + assert.throws(() => module.call('missing', arg), /no pure function dg_pure_missing/); + assert.throws( + () => module.call('echo', new Uint8Array(70_000)), + (e) => e instanceof PredictAbiError && e.code === -1 && /dg_pure_echo/.test(e.message) + ); +}); + +test('createWasmPures wraps each function with its types and gates on loading', async () => { + const pures = createWasmPures(predictModuleBytes({ pures: ['mirror', 'list'] }), { + mirror: { exportName: 'mirror', arg: POINT, output: POINT }, + list: { exportName: 'list', arg: { type: 'list', item: { type: 'u16' } }, output: { type: 'list', item: { type: 'u16' } } } + }); + assert.equal(pures.loaded(), false); + assert.throws(() => pures.mirror({ x: 1, label: '' }), /before its module loaded/); + await pures.ready; + assert.equal(pures.loaded(), true); + assert.ok(pures.module() instanceof PredictModule); + assert.deepEqual(pures.mirror({ x: 1.5, label: 'z' }), { x: 1.5, label: 'z' }); + assert.deepEqual(pures.list([1, 300, 65535]), [1, 300, 65535]); +}); + +test('a module without a wrapped function rejects ready; reserved names are refused', async () => { + const missing = createWasmPures(predictModuleBytes({ pures: ['a'] }), { + b: { exportName: 'b', output: { type: 'u8' } } + }); + await assert.rejects(missing.ready, /no pure function dg_pure_b/); + assert.equal(missing.loaded(), false); + assert.throws( + () => createWasmPures(predictModuleBytes(), { ready: { exportName: 'ready', output: { type: 'u8' } } }), + /reserved/ + ); +}); From c08b78049383b9c8414493fe5381611d26de8aa2 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 11:12:34 -0500 Subject: [PATCH 197/484] feat(game): compile #[game_pure] fns; surface constants and codecs #[game_pure(FnType)] on fn(&Arg) -> Out (or fn() -> Out) implements GamePure and, on wasm32, exports dg_pure_ over the prediction ABI. GameSurface gains pure::() (one Cargo package per surface module), constant(name, &value) (stored as the client decodes it, via the new codec::to_json_value) and record::() (standalone codec); the surface schema moves to v3. game-client emits pures.ts (createPures with one typed wrapper per function), constants.ts (typed literals, exact binary32) and encode/decode; game-wasm builds the module when a surface has a step or pure functions and checks every export (stamp v2 lists them). --- distributed_cli/src/cli.rs | 10 +- distributed_cli/src/game_client.rs | 558 +++++++++++++++++- distributed_cli/src/game_wasm.rs | 103 ++-- distributed_cli/tests/cli_game_client.rs | 16 +- .../fixtures/game-client/sample/client.ts | 2 +- .../fixtures/game-client/sample/constants.ts | 21 + .../fixtures/game-client/sample/events.ts | 26 +- .../fixtures/game-client/sample/index.ts | 4 +- .../fixtures/game-client/sample/input.ts | 2 +- .../fixtures/game-client/sample/predict.ts | 2 +- .../fixtures/game-client/sample/pures.ts | 54 ++ .../fixtures/game-client/sample/schema.ts | 2 +- .../fixtures/game-client/sample/surface.json | 102 +++- .../tests/fixtures/game-surface/src/lib.rs | 16 +- distributed_game/src/codec.rs | 79 +++ distributed_game/src/lib.rs | 10 +- distributed_game/src/prediction.rs | 13 +- distributed_game/src/pure.rs | 183 ++++++ distributed_game/src/surface.rs | 161 ++++- distributed_game/tests/authoring/main.rs | 129 +++- .../tests/fixtures/authoring.json | 119 +++- distributed_game_macros/src/lib.rs | 18 + distributed_game_macros/src/pure.rs | 118 ++++ .../tests/compile_fail/game_pure_by_value.rs | 9 + .../compile_fail/game_pure_by_value.stderr | 5 + .../tests/compile_fail/game_pure_two_args.rs | 9 + .../compile_fail/game_pure_two_args.stderr | 5 + .../game_pure_unsupported_output.rs | 11 + .../game_pure_unsupported_output.stderr | 27 + js/tests/game-generated.test.mjs | 49 +- 30 files changed, 1777 insertions(+), 86 deletions(-) create mode 100644 distributed_cli/tests/fixtures/game-client/sample/constants.ts create mode 100644 distributed_cli/tests/fixtures/game-client/sample/pures.ts create mode 100644 distributed_game/src/pure.rs create mode 100644 distributed_game_macros/src/pure.rs create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_by_value.rs create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_two_args.rs create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs create mode 100644 distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index 25c242691..6028043fd 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -75,7 +75,7 @@ pub enum DistributedCommands { GameManifest(GameManifestArgs), /// Generate typed TypeScript for a distributed_game zone from its GameSurface GameClient(GameClientArgs), - /// Compile a distributed_game zone's `#[predict]` step to WebAssembly for its generated client + /// Compile a distributed_game zone's `#[predict]` step and `#[game_pure]` functions to WebAssembly for its generated client GameWasm(GameWasmArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), @@ -132,7 +132,7 @@ pub enum ServiceCommands { GameManifest(GameManifestArgs), /// Generate typed TypeScript for a distributed_game zone from its GameSurface GameClient(GameClientArgs), - /// Compile a distributed_game zone's `#[predict]` step to WebAssembly for its generated client + /// Compile a distributed_game zone's `#[predict]` step and `#[game_pure]` functions to WebAssembly for its generated client GameWasm(GameWasmArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), @@ -494,7 +494,7 @@ pub struct GameClientArgs { #[derive(Args, Debug)] pub struct GameWasmArgs { - /// GameSurface JSON (from `distributed game-manifest`) with a predicted step. + /// GameSurface JSON (from `distributed game-manifest`) with a predicted step or pure functions. #[arg(long)] pub manifest: PathBuf, /// Generated client directory; the module is written to `/wasm/.wasm`. @@ -2453,10 +2453,10 @@ fn run_game_wasm(args: &GameWasmArgs) -> Result<(), Box> { .map_err(|error| format!("{}: {error}", args.manifest.display()))?; match outcome { crate::game_wasm::GameWasmOutcome::Current(path) => { - println!("Predicted step {} is current", path.display()) + println!("Compiled game module {} is current", path.display()) } crate::game_wasm::GameWasmOutcome::Built(path) => { - println!("Compiled predicted step to {}", path.display()) + println!("Compiled game module to {}", path.display()) } } Ok(()) diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs index b9c3d6502..75eecb8b8 100644 --- a/distributed_cli/src/game_client.rs +++ b/distributed_cli/src/game_client.rs @@ -1,5 +1,5 @@ //! `distributed game-client`: typed TypeScript for one `distributed_game` -//! zone surface (`GameSurface` JSON, schema v2, from `distributed +//! zone surface (`GameSurface` JSON, schema v3, from `distributed //! game-manifest`). //! //! The generated files import only `@hops-ops/distributed/game` and are @@ -9,9 +9,11 @@ //! |---|---| //! | `schema.ts` | `KIND` ids, per-kind field interfaces + accessors over rendered entities, field wire types, `CORRECTIONS` defaults | //! | `input.ts` | the input interface, `BUTTON` bits, `encodeInput` / `decodeInput` / `sanitizeInput` | -//! | `events.ts` | record + event payload interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | +//! | `events.ts` | record + event payload interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent`; `encode` / `decode` for the surface's standalone codecs | //! | `client.ts` | `createClient`: a `GameClient` with the input encoder and correction defaults wired in, plus typed `on`; with a predicted step, prediction defaults to the compiled WebAssembly step | //! | `predict.ts` | only with a `#[predict]` step: its state/context layouts, the module URL (`wasm/.wasm`, built by `distributed game-wasm`) and `createPrediction` | +//! | `pures.ts` | only with `#[game_pure]` functions: `createPures`, one typed wrapper per function over the same module | +//! | `constants.ts` | only with constants: each value as a typed TypeScript literal (exact binary32 floats) | //! | `index.ts` | re-exports | //! | `surface.json` | the surface it was generated from (so `--check` also catches manifest drift) | //! @@ -27,7 +29,7 @@ use serde::Deserialize; use crate::client_compiler::GeneratedClientFile; /// The only surface schema version this generator understands. -pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 2; +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 3; /// The only prediction ABI version this generator (and the SDK) speaks. pub const PREDICT_ABI_VERSION: u32 = 1; @@ -55,7 +57,7 @@ impl ImportExtension { } } -// ---- surface mirror (schema v2) ------------------------------------------- +// ---- surface mirror (schema v3) ------------------------------------------- #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -69,8 +71,47 @@ struct Surface { records: Vec, #[serde(default)] predict: Option, + #[serde(default)] + pures: Vec, + #[serde(default)] + constants: Vec, + #[serde(default)] + codecs: Vec, +} + +/// A pure function compiled into the surface's module (`#[game_pure]`). +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Pure { + pub(crate) export: String, + pub(crate) package: String, + #[serde(default)] + arg: Option, + output: Wire, + pub(crate) abi: u32, +} + +/// A constant emitted as TypeScript data. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Constant { + name: String, + #[serde(rename = "type")] + ty: Wire, + value: serde_json::Value, } +/// What `distributed game-wasm` compiles for a surface: one module from one +/// Cargo package exporting the predicted step and the pure functions. +#[derive(Debug)] +pub(crate) struct ModulePlan { + /// The declaring Cargo package. + pub(crate) package: String, + /// Required function exports (`dg_predict_`, `dg_pure_`). + pub(crate) exports: Vec, + /// ABI version. + pub(crate) abi: u32, +} /// The zone's client-predicted step (`#[predict]`). #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -372,17 +413,47 @@ pub fn generate_game_client( if let Some(predict) = gen.predict_ts()? { files.push(file("predict.ts", predict)); } + if let Some(pures) = gen.pures_ts()? { + files.push(file("pures.ts", pures)); + } + if let Some(constants) = gen.constants_ts()? { + files.push(file("constants.ts", constants)); + } files.sort_by(|a, b| a.path.cmp(&b.path)); Ok(files) } -/// What `distributed game-wasm` builds for a surface: its name and its -/// validated predicted step (`None` when the zone predicts nothing). -pub(crate) fn surface_prediction(manifest_json: &str) -> GenResult<(String, Option)> { +/// What `distributed game-wasm` builds for a surface: its name and the +/// validated module plan (`None` when the zone compiles nothing: no +/// predicted step and no pure functions). +pub(crate) fn surface_module(manifest_json: &str) -> GenResult<(String, Option)> { validate_game_surface(manifest_json)?; let surface: Surface = serde_json::from_str(manifest_json).map_err(|e| format!("invalid game surface: {e}"))?; - Ok((surface.name, surface.predict)) + let package = surface + .predict + .as_ref() + .map(|p| p.package.clone()) + .or_else(|| surface.pures.first().map(|p| p.package.clone())); + let plan = package.map(|package| { + let mut exports: Vec = surface + .predict + .iter() + .map(|p| format!("dg_predict_{}", p.export)) + .collect(); + exports.extend( + surface + .pures + .iter() + .map(|p| format!("dg_pure_{}", p.export)), + ); + ModulePlan { + package, + exports, + abi: PREDICT_ABI_VERSION, + } + }); + Ok((surface.name, plan)) } /// Module path of a surface's compiled step, relative to the generated @@ -489,9 +560,89 @@ impl<'a> Gen<'a> { } self.record_order()?; self.check_predict()?; + self.check_pures()?; + self.check_constants()?; + for codec in &self.surface.codecs { + if !self.records.contains_key(codec.as_str()) { + return Err(format!("codec record {codec} is missing")); + } + } self.check_exports() } + /// Pure functions: valid unique exports, one Cargo package (the + /// predicted step's, if any), known types, the ABI this generator speaks. + fn check_pures(&self) -> GenResult<()> { + let mut exports = BTreeSet::new(); + let mut wrappers = BTreeSet::new(); + let package = self.surface.predict.as_ref().map(|p| p.package.as_str()); + for pure in &self.surface.pures { + if pure.abi != PREDICT_ABI_VERSION { + return Err(format!( + "pure function {} uses ABI v{}; this CLI generates ABI v{PREDICT_ABI_VERSION}", + pure.export, pure.abi + )); + } + if pure.export.is_empty() + || !pure + .export + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!("invalid pure function export {:?}", pure.export)); + } + if !exports.insert(pure.export.as_str()) || !wrappers.insert(camel(&pure.export)) { + return Err(format!("duplicate pure function {}", pure.export)); + } + if matches!(camel(&pure.export).as_str(), "ready" | "loaded" | "module") { + return Err(format!( + "pure function name {} is reserved by the generated handle", + pure.export + )); + } + if pure.package.is_empty() { + return Err(format!( + "pure function {} names no Cargo package", + pure.export + )); + } + let expected = package.unwrap_or(self.surface.pures[0].package.as_str()); + if pure.package != expected { + return Err(format!( + "pure function {} is declared in Cargo package {}, but the surface's module is built from {expected}", + pure.export, pure.package + )); + } + if let Some(arg) = &pure.arg { + self.check_type(arg, &pure.export)?; + } + self.check_type(&pure.output, &pure.export)?; + } + Ok(()) + } + + /// Constants: unique `snake_case` names, values that match their type. + fn check_constants(&self) -> GenResult<()> { + let mut names = BTreeSet::new(); + for constant in &self.surface.constants { + let valid = constant.name.starts_with(|c: char| c.is_ascii_lowercase()) + && constant + .name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); + if !valid || !names.insert(constant.name.as_str()) { + return Err(format!( + "constant name {:?} is not snake_case or is declared twice", + constant.name + )); + } + self.check_type(&constant.ty, &constant.name)?; + self.literal(&constant.ty, &constant.value, 0) + .map_err(|e| format!("constant {}: {e}", constant.name))?; + } + Ok(()) + } + /// The predicted step names a kind of this surface, a state record whose /// fields are fields of that kind (plain scalar types), an optional /// context record, and the ABI this generator speaks. @@ -621,6 +772,19 @@ impl<'a> Gen<'a> { for event in &self.surface.events { names.push(format!("{}Event", pascal(&event.name))); } + if !self.surface.pures.is_empty() { + names.extend(["PURES", "PURES_WASM_URL"].map(String::from)); + names.push(format!("create{prefix}Pures")); + names.push(format!("{prefix}Pures")); + names.push(format!("{prefix}PureFns")); + } + for c in &self.surface.constants { + names.push(constant(&c.name)); + } + for codec in &self.surface.codecs { + names.push(format!("encode{codec}")); + names.push(format!("decode{codec}")); + } if self.surface.predict.is_some() { names.extend( [ @@ -1013,10 +1177,12 @@ impl<'a> Gen<'a> { if uses_fields { sdk.extend(["decodePayload", "encodePayload", "type PayloadLayout"]); } - if uses_value { + let has_codecs = !self.surface.codecs.is_empty(); + if uses_value || has_codecs { sdk.extend(["decodeValue", "encodeValue"]); } if uses_value + || has_codecs || records .iter() .any(|r| self.encoded_records().contains(r.name.as_str())) @@ -1046,6 +1212,14 @@ impl<'a> Gen<'a> { } } + for codec in &self.surface.codecs { + let c = constant(codec); + let _ = writeln!( + out, + "\n/** Encode a `{codec}` record (standalone codec, e.g. served over HTTP). */\nexport function encode{codec}(value: {codec}): Uint8Array {{\n\treturn encodeValue({c}_TYPE, value);\n}}\n\n/** Decode a whole `{codec}` record (throws on trailing or missing bytes). */\nexport function decode{codec}(bytes: Uint8Array): {codec} {{\n\treturn decodeValue({c}_TYPE, bytes) as {codec};\n}}" + ); + } + for event in events { let type_name = format!("{}Event", pascal(&event.name)); out.push('\n'); @@ -1158,6 +1332,7 @@ impl<'a> Gen<'a> { if let Some(input) = &self.surface.input { input.fields.iter().for_each(|f| walk(&f.ty, &mut pending)); } + pending.extend(self.surface.codecs.iter().map(String::as_str)); let mut seen = BTreeSet::new(); while let Some(name) = pending.pop() { if seen.insert(name) { @@ -1250,10 +1425,17 @@ impl<'a> Gen<'a> { fn index_ts(&self) -> String { let mut out = self.header("Everything generated for this surface."); - let mut modules = vec!["client", "events", "input"]; + let mut modules = vec!["client"]; + if !self.surface.constants.is_empty() { + modules.push("constants"); + } + modules.extend(["events", "input"]); if self.surface.predict.is_some() { modules.push("predict"); } + if !self.surface.pures.is_empty() { + modules.push("pures"); + } modules.push("schema"); for module in modules { let _ = writeln!(out, "export * from '{}';", self.local(module)); @@ -1362,6 +1544,295 @@ impl<'a> Gen<'a> { } } +impl Gen<'_> { + /// Records reachable from `roots` (nested ones included). + fn reachable<'t>(&self, roots: impl IntoIterator) -> BTreeSet<&str> { + let mut pending = Vec::new(); + for root in roots { + top_records(root, &mut pending); + } + let mut seen = BTreeSet::new(); + while let Some(name) = pending.pop() { + if let Some((name, record)) = self.records.get_key_value(name.as_str()) { + if seen.insert(*name) { + for field in &record.fields { + top_records(&field.ty, &mut pending); + } + } + } + } + seen + } + + /// `const _TYPE: WireType` for `names`, dependencies first. + fn type_consts(&self, names: &BTreeSet<&str>) -> GenResult { + let mut out = String::new(); + for record in self.record_order()? { + if names.contains(record.name.as_str()) { + let _ = writeln!( + out, + "const {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};\n", + constant(&record.name), + indent(&self.layout(&record.fields)) + ); + } + } + Ok(out) + } + + /// `import type { A, B } from './events'` for the records `types` + /// mention directly. + fn import_records<'t>(&self, types: impl IntoIterator) -> String { + let mut names = Vec::new(); + for ty in types { + top_records(ty, &mut names); + } + let names: BTreeSet = names.into_iter().collect(); + if names.is_empty() { + return String::new(); + } + format!( + "import type {{ {} }} from '{}';\n", + names.into_iter().collect::>().join(", "), + self.local("events") + ) + } + + fn pures_ts(&self) -> GenResult> { + let pures = &self.surface.pures; + let Some(first) = pures.first() else { + return Ok(None); + }; + let prefix = pascal(&self.surface.name); + let mut out = self.header( + "Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI).", + ); + let types: Vec<&Wire> = pures + .iter() + .flat_map(|p| p.arg.iter().chain([&p.output])) + .collect(); + let records = self.reachable(types.iter().copied()); + let _ = writeln!( + out, + "import {{ createWasmPures, type WasmPures, type WasmSource{} }} from '{SDK}';\n", + if records.is_empty() && !types.iter().any(|t| !matches!(t, Wire::Record { .. })) { + "" + } else { + ", type WireType" + } + ); + let imports = self.import_records(types.iter().copied()); + if !imports.is_empty() { + out.push_str(&imports); + out.push('\n'); + } + out.push_str(&self.type_consts(&records)?); + let _ = writeln!( + out, + "/** The pure functions (`#[game_pure]`) of Cargo package `{}`: wrapper name → module export. */\nexport const PURES = {{", + first.package + ); + for pure in pures { + let _ = writeln!( + out, + "\t{}: {{ export: {}, abi: {} }},", + key(&camel(&pure.export)), + string(&pure.export), + pure.abi + ); + } + out.push_str("} as const;\n\n"); + let _ = writeln!( + out, + "/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */\nexport const PURES_WASM_URL: URL = new URL({}, import.meta.url);\n", + string(&format!("./{}", predict_wasm_path(&self.surface.name))) + ); + let _ = writeln!( + out, + "/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */\nexport interface {prefix}PureFns {{" + ); + for pure in pures { + let signature = match &pure.arg { + Some(arg) => format!("arg: {}", self.ts_type(arg)), + None => String::new(), + }; + let _ = writeln!( + out, + "\t/** `{}` (`dg_pure_{}`). */\n\t{}({signature}): {};", + pure.export, + pure.export, + camel(&pure.export), + self.ts_type(&pure.output) + ); + } + out.push_str("}\n\n"); + let _ = writeln!( + out, + "/** The `{surface}` pure functions plus `ready` / `loaded()` / `module()`. */\nexport type {prefix}Pures = WasmPures<{prefix}PureFns>;\n", + surface = self.surface.name + ); + let _ = writeln!( + out, + "/**\n * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by\n * the predicted step too is instantiated once).\n */\nexport function create{prefix}Pures(source: WasmSource = PURES_WASM_URL): {prefix}Pures {{\n\treturn createWasmPures<{prefix}PureFns>(source, {{" + ); + for pure in pures { + let arg = match &pure.arg { + Some(arg) => format!(", arg: {}", self.wire_literal(arg)), + None => String::new(), + }; + let _ = writeln!( + out, + "\t\t{}: {{ exportName: {}{arg}, output: {} }},", + key(&camel(&pure.export)), + string(&pure.export), + self.wire_literal(&pure.output) + ); + } + out.push_str("\t});\n}\n"); + Ok(Some(out)) + } + + fn constants_ts(&self) -> GenResult> { + let constants = &self.surface.constants; + if constants.is_empty() { + return Ok(None); + } + let mut out = + self.header("Constants: static data defined once in Rust (`GameSurface::constant`)."); + let imports = self.import_records(constants.iter().map(|c| &c.ty)); + if !imports.is_empty() { + out.push_str(&imports); + } + for c in constants { + let _ = writeln!( + out, + "\n/** `{}`, as the client decodes it. */\nexport const {}: {} = {};", + c.name, + constant(&c.name), + self.ts_type(&c.ty), + self.literal(&c.ty, &c.value, 0) + .map_err(|e| format!("constant {}: {e}", c.name))? + ); + } + Ok(Some(out)) + } + + /// A TypeScript literal of `value` (JSON as `GameSurface::constant` + /// stores it) of type `ty`: records keyed by camelCase field name, floats + /// as exact binary32 values, `null` as `undefined`. + fn literal(&self, ty: &Wire, value: &serde_json::Value, depth: usize) -> GenResult { + use serde_json::Value; + let pad = "\t".repeat(depth + 1); + let close = "\t".repeat(depth); + let mismatch = || format!("value {value} does not match {}", self.ts_type(ty)); + let int = |min: i128, max: i128| -> GenResult { + let v = value + .as_i64() + .map(i128::from) + .or(value.as_u64().map(i128::from)) + .ok_or_else(mismatch)?; + if v < min || v > max { + return Err(format!("{v} is out of range")); + } + Ok(v.to_string()) + }; + Ok(match ty { + Wire::Bool => value.as_bool().ok_or_else(mismatch)?.to_string(), + Wire::U8 => int(0, 255)?, + Wire::I8 => int(-128, 127)?, + Wire::U16 => int(0, 65_535)?, + Wire::I16 => int(-32_768, 32_767)?, + Wire::U32 => int(0, u32::MAX.into())?, + Wire::I32 => int(i32::MIN.into(), i32::MAX.into())?, + Wire::U64 => int(0, (1 << 53) - 1)?, + Wire::F32 | Wire::Quant { .. } | Wire::Angle { .. } => { + let v = value.as_f64().ok_or_else(mismatch)?; + if f64::from(v as f32) != v { + return Err(format!("{v} is not a binary32 value")); + } + f32_exact(v as f32) + } + Wire::F64 => f64_literal(value.as_f64().ok_or_else(mismatch)?), + Wire::ShortStr | Wire::Str => string(value.as_str().ok_or_else(mismatch)?), + Wire::Bytes => { + let bytes = value.as_array().ok_or_else(mismatch)?; + let mut items = Vec::new(); + for b in bytes { + items.push(self.literal(&Wire::U8, b, depth)?); + } + format!("new Uint8Array([{}])", items.join(", ")) + } + Wire::Optional { item } => match value { + Value::Null => "undefined".into(), + other => self.literal(item, other, depth)?, + }, + Wire::List { item } => { + let items = value.as_array().ok_or_else(mismatch)?; + if items.is_empty() { + return Ok("[]".into()); + } + let parts = items + .iter() + .map(|v| self.literal(item, v, depth + 1)) + .collect::>>()?; + let inline = format!("[{}]", parts.join(", ")); + if is_scalar(item) && inline.len() <= 100 { + inline + } else { + format!("[\n{pad}{}\n{close}]", parts.join(&format!(",\n{pad}"))) + } + } + Wire::Record { name } => { + let record = self.records[name.as_str()]; + let object = value.as_object().ok_or_else(mismatch)?; + if object.len() != record.fields.len() { + return Err(format!( + "record {name} value has fields {:?}", + object.keys().collect::>() + )); + } + let mut parts = Vec::new(); + let mut simple = true; + for field in &record.fields { + let v = object + .get(&field.name) + .ok_or_else(|| format!("record {name} value lacks field {}", field.name))?; + simple &= is_scalar(&field.ty); + parts.push(format!( + "{}: {}", + key(&camel(&field.name)), + self.literal(&field.ty, v, depth + 1)? + )); + } + let inline = format!("{{ {} }}", parts.join(", ")); + if simple && inline.len() <= 100 { + inline + } else { + format!("{{\n{pad}{}\n{close}}}", parts.join(&format!(",\n{pad}"))) + } + } + }) + } +} + +/// Records a type names directly (through lists and options, not through +/// other records). +fn top_records(ty: &Wire, out: &mut Vec) { + match ty { + Wire::List { item } | Wire::Optional { item } => top_records(item, out), + Wire::Record { name } => out.push(name.clone()), + _ => {} + } +} + +fn is_scalar(ty: &Wire) -> bool { + match ty { + Wire::List { .. } | Wire::Record { .. } | Wire::Bytes => false, + Wire::Optional { item } => is_scalar(item), + _ => true, + } +} + fn simple_tag(ty: &Wire) -> &'static str { match ty { Wire::Bool => "bool", @@ -1433,7 +1904,7 @@ mod tests { let err = generate_game_client(r#"{"schemaVersion": 1}"#, ImportExtension::Ts).unwrap_err(); assert!(err.contains("schemaVersion"), "{err}"); let err = generate_game_client( - r#"{"schemaVersion":2,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, + r#"{"schemaVersion":3,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, ImportExtension::Ts, ) .unwrap_err(); @@ -1499,9 +1970,72 @@ mod tests { assert!(!client.contents.contains("Prediction(")); } + #[test] + fn validates_pures_constants_and_codecs() { + type Mutate = fn(&mut serde_json::Value); + let cases: [(&str, Mutate); 9] = [ + ("ABI v2", |s| s["pures"][0]["abi"] = 2.into()), + ("module is built from distributed_game", |s| { + s["pures"][1]["package"] = "other".into() + }), + ("reserved", |s| s["pures"][0]["export"] = "ready".into()), + ("duplicate pure function", |s| { + s["pures"][1]["export"] = "sample_mirror".into() + }), + ("unknown record Nope", |s| { + s["pures"][0]["output"] = serde_json::json!({"type": "record", "name": "Nope"}) + }), + ("not a binary32 value", |s| { + s["constants"][1]["value"][0] = 0.1.into() + }), + ("out of range", |s| { + s["constants"][0]["value"]["version"] = (-1).into() + }), + ("lacks field label", |s| { + let spot = s["constants"][2]["value"].as_object_mut().unwrap(); + spot.remove("label"); + spot.insert("other".into(), "x".into()); + }), + ("codec record Nope is missing", |s| { + s["codecs"][0] = "Nope".into() + }), + ]; + for (expected, mutate) in cases { + let mut surface = sample(); + mutate(&mut surface); + let err = generate(&surface).unwrap_err(); + assert!(err.contains(expected), "{expected}: {err}"); + } + // Without pures, constants or codecs: no extra files or functions. + let mut plain = sample(); + for key in ["pures", "constants", "codecs"] { + plain.as_object_mut().unwrap().remove(key); + } + let files = generate(&plain).unwrap(); + assert!(files + .iter() + .all(|f| f.path != "pures.ts" && f.path != "constants.ts")); + let events = files.iter().find(|f| f.path == "events.ts").unwrap(); + assert!(!events.contents.contains("decodeSampleWind")); + // The module plan lists the step and every pure function. + let (name, plan) = surface_module(&sample().to_string()).unwrap(); + let plan = plan.unwrap(); + assert_eq!(name, "sample"); + assert_eq!( + plan.exports, + [ + "dg_predict_sample_step", + "dg_pure_sample_mirror", + "dg_pure_sample_rows" + ] + ); + plain.as_object_mut().unwrap().remove("predict"); + assert!(surface_module(&plain.to_string()).unwrap().1.is_none()); + } + #[test] fn rejects_recursive_records() { - let json = r#"{"schemaVersion":2,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], + let json = r#"{"schemaVersion":3,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], "records":[{"name":"Node","fields":[{"name":"next","type":{"type":"optional","item":{"type":"record","name":"Node"}}}]}]}"#; let err = generate_game_client(json, ImportExtension::Ts).unwrap_err(); assert!(err.contains("recursive"), "{err}"); diff --git a/distributed_cli/src/game_wasm.rs b/distributed_cli/src/game_wasm.rs index 3c44823cd..5bd7a8daf 100644 --- a/distributed_cli/src/game_wasm.rs +++ b/distributed_cli/src/game_wasm.rs @@ -1,14 +1,15 @@ //! `distributed game-wasm`: compile a zone's client-predicted step -//! (`#[predict]`, recorded in its `GameSurface`) to WebAssembly next to the -//! generated client. +//! (`#[predict]`) and pure functions (`#[game_pure]`), recorded in its +//! `GameSurface`, to one WebAssembly module next to the generated client. //! -//! The surface names the Cargo package that declares the step. The command +//! The surface names the Cargo package that declares them. The command //! builds that package's library as a `cdylib` for `wasm32-unknown-unknown` -//! (`cargo rustc --release`), checks the module speaks the prediction ABI -//! (no imports; exports `memory`, `dg_predict_buffer`, `dg_predict_abi` -//! and `dg_predict_`) and writes it to `/wasm/.wasm`, -//! which the generated `predict.ts` loads. No wasm-bindgen glue, no JSON: -//! the SDK instantiates the module directly. +//! (`cargo rustc --release`), checks the module speaks the ABI (no imports; +//! exports `memory`, `dg_predict_buffer`, `dg_predict_abi`, the step's +//! `dg_predict_` and every `dg_pure_`) and writes it to +//! `/wasm/.wasm`, which the generated `predict.ts` and +//! `pures.ts` load. No wasm-bindgen glue, no JSON: the SDK instantiates the +//! module directly. //! //! A stamp next to the module (`.stamp.json`) records the source //! fingerprint of the package and its local dependencies (the same one the @@ -24,11 +25,11 @@ use std::process::Command; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use crate::game_client::{predict_wasm_path, surface_prediction}; +use crate::game_client::{predict_wasm_path, surface_module}; use crate::wasm_pures::{cargo_metadata, ensure_real_directory_path, package_source_identity}; const TARGET: &str = "wasm32-unknown-unknown"; -const STAMP_VERSION: u32 = 1; +const STAMP_VERSION: u32 = 2; const MAX_MODULE_BYTES: u64 = 64 * 1024 * 1024; /// What to build. @@ -48,7 +49,7 @@ pub(crate) struct GameWasmOptions<'a> { struct Stamp { version: u32, package: String, - export: String, + exports: Vec, abi: u32, source_identity: String, compiler_identity: String, @@ -67,29 +68,28 @@ pub(crate) enum GameWasmOutcome { pub(crate) fn run_game_wasm( options: &GameWasmOptions<'_>, ) -> Result> { - let (surface, predict) = surface_prediction(options.surface)?; - let predict = predict.ok_or_else(|| { + let (surface, plan) = surface_module(options.surface)?; + let plan = plan.ok_or_else(|| { format!( - "game surface `{surface}` declares no predicted step; add `.predict::()` (a `#[predict]` fn) to its GameSurface" + "game surface `{surface}` declares nothing to compile; add `.predict::()` (a `#[predict]` fn) or `.pure::()` (a `#[game_pure]` fn) to its GameSurface" ) })?; let metadata = cargo_metadata(options.cargo_manifest)?; let mut candidates = metadata .packages .iter() - .filter(|p| p.name == predict.package && p.source.is_none()); + .filter(|p| p.name == plan.package && p.source.is_none()); let package = candidates.next().ok_or_else(|| { format!( - "predicted step `{}` is declared by Cargo package `{}`, which is not a local package of {}", - predict.export, - predict.package, + "the WebAssembly functions of game surface `{surface}` are declared by Cargo package `{}`, which is not a local package of {}", + plan.package, options.cargo_manifest.display() ) })?; if candidates.next().is_some() { return Err(format!( "more than one local Cargo package is named `{}`", - predict.package + plan.package ) .into()); } @@ -109,9 +109,9 @@ pub(crate) fn run_game_wasm( let stamp_path = module_path.with_extension("stamp.json"); let mut expected = Stamp { version: STAMP_VERSION, - package: predict.package.clone(), - export: predict.export.clone(), - abi: predict.abi, + package: plan.package.clone(), + exports: plan.exports.clone(), + abi: plan.abi, source_identity: package_source_identity(&metadata, &package.id)?, compiler_identity: compiler_identity()?, module_sha256: String::new(), @@ -121,15 +121,16 @@ pub(crate) fn run_game_wasm( } if options.check { return Err(format!( - "compiled step {} is missing or stale; run `distributed game-wasm` without --check", + "compiled module {} is missing or stale; run `distributed game-wasm` without --check", module_path.display() ) .into()); } eprintln!( - "distributed: compiling predicted step `{}` (Cargo package {}) to WebAssembly", - predict.export, predict.package + "distributed: compiling {} (Cargo package {}) to WebAssembly", + plan.exports.join(", "), + plan.package ); let status = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) .arg("rustc") @@ -137,7 +138,7 @@ pub(crate) fn run_game_wasm( .arg(options.cargo_manifest) .args([ "-p", - &predict.package, + &plan.package, "--lib", "--release", "--target", @@ -147,11 +148,11 @@ pub(crate) fn run_game_wasm( .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::inherit()) .status() - .map_err(|error| format!("failed to run cargo for the predicted step: {error}"))?; + .map_err(|error| format!("failed to run cargo for the WebAssembly module: {error}"))?; if !status.success() { return Err(format!( - "compiling predicted step `{}` for {TARGET} failed ({status}); is the target installed (`rustup target add {TARGET}`)?", - predict.export + "compiling Cargo package `{}` for {TARGET} failed ({status}); is the target installed (`rustup target add {TARGET}`)?", + plan.package ) .into()); } @@ -171,7 +172,7 @@ pub(crate) fn run_game_wasm( .into()); } let module = fs::read(&artifact)?; - check_module(&module, &predict.export) + check_module(&module, &plan.exports) .map_err(|error| format!("{}: {error}", artifact.display()))?; expected.module_sha256 = format!("{:x}", Sha256::digest(&module)); @@ -221,8 +222,9 @@ fn compiler_identity() -> Result> { Ok(format!("sha256:{:x}", Sha256::digest(&output.stdout))) } -/// The module imports nothing and exports the prediction ABI. -pub(crate) fn check_module(module: &[u8], export: &str) -> Result<(), String> { +/// The module imports nothing and exports the ABI plus every function in +/// `functions` (`dg_predict_`, `dg_pure_`). +pub(crate) fn check_module(module: &[u8], functions: &[String]) -> Result<(), String> { let sections = wasm_sections(module)?; let mut exports = Vec::new(); for (id, body) in sections { @@ -230,7 +232,7 @@ pub(crate) fn check_module(module: &[u8], export: &str) -> Result<(), String> { 2 => { let mut r = WasmReader::new(body); if r.u32()? != 0 { - return Err("the module imports functions or memory; a predicted step must be self-contained (no wasm-bindgen, no host calls)".into()); + return Err("the module imports functions or memory; compiled game functions must be self-contained (no wasm-bindgen, no host calls)".into()); } } 7 => { @@ -245,16 +247,17 @@ pub(crate) fn check_module(module: &[u8], export: &str) -> Result<(), String> { _ => {} } } - let step = format!("dg_predict_{export}"); - for (name, kind) in [ + let required = [ ("memory", 2u8), ("dg_predict_buffer", 0), ("dg_predict_abi", 0), - (step.as_str(), 0), - ] { + ] + .into_iter() + .chain(functions.iter().map(|f| (f.as_str(), 0))); + for (name, kind) in required { if !exports.iter().any(|(n, k)| n == name && *k == kind) { return Err(format!( - "the module does not export `{name}` (is the step declared with `#[predict]` in this package?)" + "the module does not export `{name}` (is it declared with `#[predict]` / `#[game_pure]` in this package?)" )); } } @@ -365,20 +368,34 @@ mod tests { ("dg_predict_arena_step", 0), ]; + fn names(names: &[&str]) -> Vec { + names.iter().map(|n| n.to_string()).collect() + } + #[test] fn accepts_a_self_contained_module_with_the_abi() { - check_module(&module(0, &ABI), "arena_step").unwrap(); + check_module(&module(0, &ABI), &names(&["dg_predict_arena_step"])).unwrap(); + let mut with_pure = ABI.to_vec(); + with_pure.push(("dg_pure_grid_cell", 0)); + check_module( + &module(0, &with_pure), + &names(&["dg_predict_arena_step", "dg_pure_grid_cell"]), + ) + .unwrap(); } #[test] fn rejects_imports_missing_exports_and_garbage() { - let error = check_module(&module(1, &ABI), "arena_step").unwrap_err(); + let step = names(&["dg_predict_arena_step"]); + let error = check_module(&module(1, &ABI), &step).unwrap_err(); assert!(error.contains("imports"), "{error}"); - let error = check_module(&module(0, &ABI), "grid_step").unwrap_err(); + let error = check_module(&module(0, &ABI), &names(&["dg_predict_grid_step"])).unwrap_err(); assert!(error.contains("dg_predict_grid_step"), "{error}"); - assert!(check_module(b"nope", "x").is_err()); + let error = check_module(&module(0, &ABI), &names(&["dg_pure_grid_cell"])).unwrap_err(); + assert!(error.contains("dg_pure_grid_cell"), "{error}"); + assert!(check_module(b"nope", &step).is_err()); let mut truncated = module(0, &ABI); truncated.truncate(truncated.len() - 3); - assert!(check_module(&truncated, "arena_step").is_err()); + assert!(check_module(&truncated, &step).is_err()); } } diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs index 68c6901f2..9fc85ebcd 100644 --- a/distributed_cli/tests/cli_game_client.rs +++ b/distributed_cli/tests/cli_game_client.rs @@ -43,10 +43,12 @@ fn generated_typescript_matches_the_golden_files() { names, [ "client.ts", + "constants.ts", "events.ts", "index.ts", "input.ts", "predict.ts", + "pures.ts", "schema.ts", "surface.json" ] @@ -179,10 +181,12 @@ fn game_manifest_runs_the_surface_export() { ); let surface: serde_json::Value = serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); - assert_eq!(surface["schemaVersion"], 2); + assert_eq!(surface["schemaVersion"], 3); assert_eq!(surface["name"], "orbs"); assert_eq!(surface["predict"]["export"], "orb_step"); assert_eq!(surface["predict"]["package"], "game-surface-fixture"); + assert_eq!(surface["pures"][0]["export"], "orb_radius"); + assert_eq!(surface["constants"][0]["value"]["limit"], 32.0); assert_eq!( surface["kinds"][0]["fields"][0]["correction"]["durationMs"], 80 @@ -206,8 +210,9 @@ fn game_manifest_runs_the_surface_export() { .unwrap() .contains("createOrbsClient")); - // The predicted step compiles to a self-contained module next to the - // client; a second run is a stamp hit, and --check verifies it. + // The predicted step and the pure function compile to one + // self-contained module next to the client (game-wasm checks both + // exports); a second run is a stamp hit, and --check verifies it. let wasm = |extra: &[&str]| { let mut args = vec![ "game-wasm", @@ -242,10 +247,11 @@ fn game_manifest_runs_the_surface_export() { } #[test] -fn game_wasm_needs_a_predicted_step() { +fn game_wasm_needs_something_to_compile() { let tmp = tempfile::tempdir().unwrap(); let mut surface: serde_json::Value = serde_json::from_str(&sample_surface()).unwrap(); surface.as_object_mut().unwrap().remove("predict"); + surface.as_object_mut().unwrap().remove("pures"); let manifest = tmp.path().join("surface.json"); fs::write(&manifest, surface.to_string()).unwrap(); let run = distributed(&[ @@ -257,7 +263,7 @@ fn game_wasm_needs_a_predicted_step() { ]); assert!(!run.status.success()); assert!( - String::from_utf8_lossy(&run.stderr).contains("declares no predicted step"), + String::from_utf8_lossy(&run.stderr).contains("declares nothing to compile"), "{}", String::from_utf8_lossy(&run.stderr) ); diff --git a/distributed_cli/tests/fixtures/game-client/sample/client.ts b/distributed_cli/tests/fixtures/game-client/sample/client.ts index 5c63bfe3a..7d2651912 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/client.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/constants.ts b/distributed_cli/tests/fixtures/game-client/sample/constants.ts new file mode 100644 index 000000000..1d0bbf15a --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/constants.ts @@ -0,0 +1,21 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { Board, Spot } from './events.ts'; + +/** `sample_board`, as the client decodes it. */ +export const SAMPLE_BOARD: Board = { + version: 7, + kills: [ + { rank: 1, name: 'Ada', score: 9007199254740991 }, + { rank: 2, name: 'Bob ✓', score: 3 } + ], + note: undefined, + motd: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +}; + +/** `sample_gusts`, as the client decodes it. */ +export const SAMPLE_GUSTS: readonly number[] = [0.10000000149011612, -2.5]; + +/** `sample_spot`, as the client decodes it. */ +export const SAMPLE_SPOT: Spot = { at: 1.313783049583435, label: 'dock' }; diff --git a/distributed_cli/tests/fixtures/game-client/sample/events.ts b/distributed_cli/tests/fixtures/game-client/sample/events.ts index 24779185d..d94e2bddc 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/events.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/events.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; @@ -51,6 +51,30 @@ export interface SampleWind { readonly gusts: number; } +const SAMPLE_WIND_TYPE: WireType = { + type: 'record', + fields: [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], + ] +}; + +/** Record `Spot` (`#[derive(GameRecord)]`). */ +export interface Spot { + readonly at: number; + readonly label: string; +} + +/** Encode a `SampleWind` record (standalone codec, e.g. served over HTTP). */ +export function encodeSampleWind(value: SampleWind): Uint8Array { + return encodeValue(SAMPLE_WIND_TYPE, value); +} + +/** Decode a whole `SampleWind` record (throws on trailing or missing bytes). */ +export function decodeSampleWind(bytes: Uint8Array): SampleWind { + return decodeValue(SAMPLE_WIND_TYPE, bytes) as SampleWind; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly entity: number; diff --git a/distributed_cli/tests/fixtures/game-client/sample/index.ts b/distributed_cli/tests/fixtures/game-client/sample/index.ts index e268d7c32..aa01a9bfc 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/index.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/index.ts @@ -1,8 +1,10 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; +export * from './pures.ts'; export * from './schema.ts'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/input.ts b/distributed_cli/tests/fixtures/game-client/sample/input.ts index 99ed90947..c30fd7a07 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/input.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/predict.ts b/distributed_cli/tests/fixtures/game-client/sample/predict.ts index 63a841928..a90c23756 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/predict.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/pures.ts b/distributed_cli/tests/fixtures/game-client/sample/pures.ts new file mode 100644 index 000000000..c56081ff6 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/pures.ts @@ -0,0 +1,54 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPures, type WasmPures, type WasmSource, type WireType } from '@hops-ops/distributed/game'; + +import type { Row, SampleWind } from './events.ts'; + +const ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u16' }], + ['name', { type: 'short_str' }], + ['score', { type: 'u64' }], + ] +}; + +const SAMPLE_WIND_TYPE: WireType = { + type: 'record', + fields: [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], + ] +}; + +/** The pure functions (`#[game_pure]`) of Cargo package `distributed_game`: wrapper name → module export. */ +export const PURES = { + sampleMirror: { export: 'sample_mirror', abi: 1 }, + sampleRows: { export: 'sample_rows', abi: 1 }, +} as const; + +/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */ +export const PURES_WASM_URL: URL = new URL('./wasm/sample.wasm', import.meta.url); + +/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */ +export interface SamplePureFns { + /** `sample_mirror` (`dg_pure_sample_mirror`). */ + sampleMirror(arg: SampleWind): SampleWind; + /** `sample_rows` (`dg_pure_sample_rows`). */ + sampleRows(): readonly Row[]; +} + +/** The `sample` pure functions plus `ready` / `loaded()` / `module()`. */ +export type SamplePures = WasmPures; + +/** + * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by + * the predicted step too is instantiated once). + */ +export function createSamplePures(source: WasmSource = PURES_WASM_URL): SamplePures { + return createWasmPures(source, { + sampleMirror: { exportName: 'sample_mirror', arg: SAMPLE_WIND_TYPE, output: SAMPLE_WIND_TYPE }, + sampleRows: { exportName: 'sample_rows', output: { type: 'list', item: ROW_TYPE } }, + }); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/schema.ts b/distributed_cli/tests/fixtures/game-client/sample/schema.ts index 19212f5e9..9cfc8648b 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/schema.ts +++ b/distributed_cli/tests/fixtures/game-client/sample/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `sample` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldBytes, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/surface.json b/distributed_cli/tests/fixtures/game-client/sample/surface.json index 189e39e7c..6629d2703 100644 --- a/distributed_cli/tests/fixtures/game-client/sample/surface.json +++ b/distributed_cli/tests/fixtures/game-client/sample/surface.json @@ -1,4 +1,57 @@ { + "codecs": [ + "SampleWind" + ], + "constants": [ + { + "name": "sample_board", + "type": { + "name": "Board", + "type": "record" + }, + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "name": "sample_gusts", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + }, + "value": [ + 0.10000000149011612, + -2.5 + ] + }, + { + "name": "sample_spot", + "type": { + "name": "Spot", + "type": "record" + }, + "value": { + "at": 1.313783049583435, + "label": "dock" + } + } + ], "events": [ { "id": 1, @@ -383,6 +436,33 @@ "state": "SampleState" }, "protocolVersion": 1, + "pures": [ + { + "abi": 1, + "arg": { + "name": "SampleWind", + "type": "record" + }, + "export": "sample_mirror", + "output": { + "name": "SampleWind", + "type": "record" + }, + "package": "distributed_game" + }, + { + "abi": 1, + "export": "sample_rows", + "output": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + }, + "package": "distributed_game" + } + ], "records": [ { "fields": [ @@ -488,7 +568,27 @@ } ], "name": "SampleWind" + }, + { + "fields": [ + { + "name": "at", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + }, + { + "name": "label", + "type": { + "type": "short_str" + } + } + ], + "name": "Spot" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/distributed_cli/tests/fixtures/game-surface/src/lib.rs b/distributed_cli/tests/fixtures/game-surface/src/lib.rs index ad8c0b48e..a660ad4a7 100644 --- a/distributed_cli/tests/fixtures/game-surface/src/lib.rs +++ b/distributed_cli/tests/fixtures/game-surface/src/lib.rs @@ -1,7 +1,7 @@ //! A minimal zone surface for `distributed game-manifest` tests. use distributed_game::{ - predict, schema, Ctx, EntitySchema, GameEvent, GameInput, GameRecord, GameSurface, PlayerId, + game_pure, predict, schema, Ctx, EntitySchema, GameEvent, GameInput, GameRecord, GameSurface, PlayerId, Replicated, WorldView, Zone, }; @@ -44,6 +44,18 @@ pub fn orb_step(state: &OrbState, input: &Steer, _context: &(), dt: f32) -> OrbS } } +/// A pure function compiled into the same module (`dg_pure_orb_radius`). +#[game_pure(OrbRadiusFn)] +pub fn orb_radius(state: &OrbState) -> f32 { + (state.x * state.x).sqrt() +} + +/// Static data the client gets as a generated constant. +#[derive(Clone, Copy, GameRecord)] +pub struct OrbLimits { + pub limit: f32, +} + pub struct Orbs; impl Zone for Orbs { @@ -75,4 +87,6 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("orbs") .events::() .predict::() + .pure::() + .constant("orb_limits", &OrbLimits { limit: 32.0 }) } diff --git a/distributed_game/src/codec.rs b/distributed_game/src/codec.rs index f7c7bd963..504deecad 100644 --- a/distributed_game/src/codec.rs +++ b/distributed_game/src/codec.rs @@ -301,6 +301,85 @@ pub fn from_bytes(bytes: &[u8]) -> Result { Ok(value) } +/// A value as the JSON a client decodes from its encoding: records are +/// objects keyed by Rust field name, lists arrays, `None` `null`, `bytes` +/// arrays of numbers, and every float the exact binary32 / binary64 value +/// the decoder yields (quantized fields after quantization). Built by +/// encoding the value and decoding it against its wire type, so it is the +/// codec's view by construction +/// ([`GameSurface::constant`](crate::GameSurface::constant)). +pub fn to_json_value(value: &T) -> Result { + let mut records = Vec::new(); + T::records(&mut records); + let bytes = to_bytes(value); + let mut r = Reader::new(&bytes); + let json = decode_json(&T::wire_type(), &records, &mut r)?; + r.finish()?; + Ok(json) +} + +/// Decode one value of type `ty` (records looked up in `records`) as JSON; +/// see [`to_json_value`]. Non-finite floats are rejected. +pub fn decode_json( + ty: &WireType, + records: &[RecordSurface], + r: &mut Reader<'_>, +) -> Result { + use serde_json::{json, Map, Value}; + let float = |v: f64| { + serde_json::Number::from_f64(v) + .map(Value::Number) + .ok_or(DecodeError::Invalid("non-finite float")) + }; + Ok(match ty { + WireType::Bool => json!(r.bool()?), + WireType::U8 => json!(r.u8()?), + WireType::I8 => json!(r.u8()? as i8), + WireType::U16 => json!(u16::decode(r)?), + WireType::I16 => json!(i16::decode(r)?), + WireType::U32 => json!(r.varuint()?), + WireType::I32 => json!(r.varint()?), + WireType::U64 => json!(r.varuint64()?), + WireType::F32 => float(f64::from(r.f32()?))?, + WireType::F64 => float(r.f64()?)?, + WireType::Quant { .. } | WireType::Angle { .. } => { + let field = ty.field_type().expect("float field type"); + float(f64::from(special::decode_f32(r, field)?))? + } + WireType::ShortStr => json!(r.short_string()?), + WireType::Str => json!(r.string()?), + WireType::Bytes => json!(r.bytes()?), + WireType::List { item } => { + let count = r.varuint()? as usize; + // As `Vec::decode`: every item takes at least one byte. + if count > r.remaining() { + return Err(DecodeError::UnexpectedEof); + } + let mut out = Vec::with_capacity(count); + for _ in 0..count { + out.push(decode_json(item, records, r)?); + } + Value::Array(out) + } + WireType::Optional { item } => match r.u8()? { + 0 => Value::Null, + 1 => decode_json(item, records, r)?, + _ => return Err(DecodeError::Invalid("option tag must be 0 or 1")), + }, + WireType::Record { name } => { + let record = records + .iter() + .find(|record| &record.name == name) + .ok_or(DecodeError::Invalid("unknown record"))?; + let mut out = Map::new(); + for field in &record.fields { + out.insert(field.name.clone(), decode_json(&field.ty, records, r)?); + } + Value::Object(out) + } + }) +} + /// A Rust type usable as a replicated entity field (`#[derive(Replicated)]`). #[diagnostic::on_unimplemented( message = "`{Self}` cannot be a replicated entity field", diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index bb059c835..a5670bdbe 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -28,6 +28,10 @@ //! predicted step once in Rust; `distributed game-wasm` compiles it to //! WebAssembly (binary ABI, no JSON) and the generated client predicts //! with it. +//! - Shared client logic and data ([`pure`], [`GameSurface::constant`](surface::GameSurface::constant)): +//! `#[game_pure]` compiles any other pure function (procedural content, +//! …) into the same module with a typed generated wrapper; constants and +//! standalone records are emitted as generated TypeScript data / codecs. //! //! Physics is out of scope: games bring their own and run it in `on_tick`. //! @@ -63,6 +67,7 @@ pub mod metrics; pub mod net; pub mod prediction; pub mod protocol; +pub mod pure; pub mod replay; pub mod replication; pub mod rewind; @@ -80,7 +85,7 @@ pub use clock::{Clock, ManualClock, SystemClock}; pub use codec::{Wire, WireType}; /// Authoring derives (see the crate docs and README). pub use distributed_game_macros::{ - predict, FactCommand, GameEvent, GameInput, GameRecord, Replicated, + game_pure, predict, FactCommand, GameEvent, GameInput, GameRecord, Replicated, }; #[cfg(feature = "runtime")] pub use facts::spawn_fact_worker; @@ -95,6 +100,7 @@ pub use input::{ConsumePolicy, InputBuffer, InputCredits, PushOutcome, Sequenced pub use interest::{InterestConfig, View}; pub use prediction::{PredictContext, PredictStep}; pub use protocol::{ClientMessage, ClientMirror, Role, ServerMessage, PROTOCOL_VERSION}; +pub use pure::GamePure; pub use replay::{replay, Recorder, Recording}; pub use replication::{EntityState, WorldView}; pub use rewind::{Historic, HitQuery, Rewind, RewindConfig, RewindFrame, ShotTiming}; @@ -120,6 +126,8 @@ pub mod __private { #[cfg(target_arch = "wasm32")] pub use crate::prediction::wasm_export; pub use crate::protocol::wire::{DecodeError, Reader, Writer}; + #[cfg(target_arch = "wasm32")] + pub use crate::pure::wasm_export as pure_wasm_export; pub use crate::schema::{Correction, FieldType, FieldValue, KindDef}; pub use crate::surface::{ EventPayload, EventSurface, InputSurface, PayloadField, RecordSurface, diff --git a/distributed_game/src/prediction.rs b/distributed_game/src/prediction.rs index 6bd3d50be..6afc6a933 100644 --- a/distributed_game/src/prediction.rs +++ b/distributed_game/src/prediction.rs @@ -154,8 +154,11 @@ pub enum AbiError { Input = -3, /// The context bytes do not decode. Context = -4, - /// The next state does not fit the scratch buffer. + /// The next state (or a pure function's output) does not fit the + /// scratch buffer. Output = -5, + /// A pure function's argument does not decode ([`crate::pure`]). + Argument = -6, } /// One step over encoded bytes: what the WASM export does, callable @@ -234,7 +237,7 @@ mod wasm { super::ABI_VERSION } - /// The scratch buffer (generated step exports). + /// The scratch buffer (generated step and pure function exports). pub fn scratch() -> &'static mut [u8] { // SAFETY: single-threaded; each export call borrows it once and // returns before the next call. @@ -242,6 +245,12 @@ mod wasm { } } +/// The module's scratch buffer (`wasm32` only). +#[cfg(target_arch = "wasm32")] +pub(crate) fn scratch_buffer() -> &'static mut [u8] { + wasm::scratch() +} + /// Body of a generated step export (`#[predict]`, `wasm32` only). #[cfg(target_arch = "wasm32")] #[doc(hidden)] diff --git a/distributed_game/src/pure.rs b/distributed_game/src/pure.rs new file mode 100644 index 000000000..d49d6f558 --- /dev/null +++ b/distributed_game/src/pure.rs @@ -0,0 +1,183 @@ +//! Pure game functions, declared once in Rust and compiled to WebAssembly +//! for the browser next to the zone's predicted step. +//! +//! Some client code is neither prediction nor protocol but must still agree +//! with the server exactly: procedural world content (terrain, props), a +//! loot table preview, a path cost. Declare such a function with +//! `#[game_pure]`, name it in the zone's [`GameSurface`](crate::GameSurface) +//! and the generated client calls the *same* code, compiled to +//! `wasm32-unknown-unknown`: +//! +//! ```ignore +//! /// Terrain and props of one cell. +//! #[game_pure(GridCellFn)] +//! pub fn grid_cell(cell: &CellRequest) -> CellContent { +//! /* … */ +//! } +//! +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("grid").pure::() +//! } +//! ``` +//! +//! The function takes nothing or one shared reference to a [`Wire`] value +//! (typically a `#[derive(GameRecord)]` struct) and returns a [`Wire`] +//! value. `distributed game-client` emits `pures.ts`, a typed wrapper per +//! function (`gridCell(cell: CellRequest): CellContent`), and `distributed +//! game-wasm` compiles it into the surface's module. +//! +//! # Binary ABI +//! +//! Pure functions share the module and the ABI of the predicted step +//! ([`crate::prediction`], v1): the same `memory`, `dg_predict_abi` and +//! `dg_predict_buffer` scratch area, and one export per function, +//! `dg_pure_(arg_len) -> i32`. The caller writes the argument's codec +//! encoding into the scratch buffer and calls the export; a non-negative +//! result is the length of the output's encoding, written at the start of +//! the buffer; negative values are [`AbiError`] codes. The output must fit +//! the 64 KiB buffer. No JSON, no allocation crosses the boundary. +//! +//! # Determinism +//! +//! The rules of [`crate::prediction`] apply: only correctly rounded IEEE-754 +//! operations (`+ - * /`, `sqrt`, `floor`, …), no platform transcendentals, +//! no NaN. The function must be a pure function of its argument (caching +//! inside is fine; the module is single-threaded). + +use crate::codec::{Wire, WireType}; +use crate::prediction::{AbiError, PredictContext}; +use crate::protocol::wire::Writer; +use crate::surface::RecordSurface; + +/// A pure game function compiled to WebAssembly (see the module docs). +/// Implemented by the `#[game_pure]` attribute. +pub trait GamePure { + /// Cargo package that declares the function (`env!("CARGO_PKG_NAME")`). + const PACKAGE: &'static str; + /// Export suffix: the function is `dg_pure_` in the module. + const EXPORT: &'static str; + /// Argument: `()` for none, otherwise any [`Wire`] value. + type Arg: PureArg; + /// Result. + type Output: Wire; + + /// Run the function. + fn call(arg: &Self::Arg) -> Self::Output; +} + +/// The argument of a [`GamePure`]: `()` (none) or any [`Wire`] value. Same +/// shape as a predicted step's context. +pub trait PureArg: PredictContext {} + +impl PureArg for T {} + +/// The wire type of `T`'s argument (`None` for `()`) and the records it +/// mentions. +pub(crate) fn arg_type(records: &mut Vec) -> Option { + F::Arg::context_records(records); + F::Arg::context_type() +} + +/// One call over encoded bytes: what the WASM export does, callable natively +/// (tools, tests). Returns the encoded output. +pub fn call_bytes(arg: &[u8]) -> Result, AbiError> { + let arg = F::Arg::decode_context(arg).map_err(|_| AbiError::Argument)?; + let out = F::call(&arg); + let mut w = Writer::new(); + out.encode(&mut w); + Ok(w.into_bytes()) +} + +/// The ABI over a buffer holding the encoded argument: decodes, calls and +/// writes the encoded output at the start of `buffer`. Returns its length or +/// a negative [`AbiError`] code. The WASM exports call this on the scratch +/// buffer. +pub fn run_abi(buffer: &mut [u8], arg_len: u32) -> i32 { + let len = arg_len as usize; + if len > buffer.len() { + return AbiError::TooLarge as i32; + } + let out = match call_bytes::(&buffer[..len]) { + Ok(out) => out, + Err(error) => return error as i32, + }; + if out.len() > buffer.len() { + return AbiError::Output as i32; + } + buffer[..out.len()].copy_from_slice(&out); + out.len() as i32 +} + +/// Body of a generated `dg_pure_` export (`#[game_pure]`, `wasm32` only). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub fn wasm_export(arg_len: u32) -> i32 { + run_abi::(crate::prediction::scratch_buffer(), arg_len) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::GameRecord; + + #[derive(Debug, Clone, PartialEq, GameRecord)] + struct Span { + from: i32, + to: i32, + } + + struct Squares; + impl GamePure for Squares { + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "squares"; + type Arg = Span; + type Output = Vec; + fn call(span: &Span) -> Vec { + (span.from..span.to).map(|i| (i * i) as u32).collect() + } + } + + struct Answer; + impl GamePure for Answer { + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "answer"; + type Arg = (); + type Output = u8; + fn call(_: &()) -> u8 { + 42 + } + } + + #[test] + fn abi_calls_in_place() { + let arg = crate::codec::to_bytes(&Span { from: -2, to: 3 }); + let mut buffer = vec![0u8; 64]; + buffer[..arg.len()].copy_from_slice(&arg); + let n = run_abi::(&mut buffer, arg.len() as u32); + assert!(n > 0); + let out: Vec = crate::codec::from_bytes(&buffer[..n as usize]).unwrap(); + assert_eq!(out, [4, 1, 0, 1, 4]); + assert_eq!(call_bytes::(&[]).unwrap(), [42]); + } + + #[test] + fn abi_reports_errors() { + let mut buffer = vec![0u8; 4]; + assert_eq!( + run_abi::(&mut buffer, 9), + AbiError::TooLarge as i32 + ); + assert_eq!( + run_abi::(&mut buffer, 1), + AbiError::Argument as i32 + ); + assert_eq!(call_bytes::(&[1]), Err(AbiError::Argument)); + let arg = crate::codec::to_bytes(&Span { from: 0, to: 100 }); + let mut small = vec![0u8; 8]; + small[..arg.len()].copy_from_slice(&arg); + assert_eq!( + run_abi::(&mut small, arg.len() as u32), + AbiError::Output as i32 + ); + } +} diff --git a/distributed_game/src/surface.rs b/distributed_game/src/surface.rs index 3d0911e12..5e744068a 100644 --- a/distributed_game/src/surface.rs +++ b/distributed_game/src/surface.rs @@ -3,7 +3,11 @@ //! //! A [`GameSurface`] lists the zone's replicated kinds (fields, wire types, //! priorities, client correction defaults), its input layout, its events and -//! the records their payloads mention. It is versioned +//! the records their payloads mention; optionally its client-predicted step +//! ([`GameSurface::predict`]), pure functions compiled to WebAssembly +//! ([`GameSurface::pure`]), constants the client needs +//! ([`GameSurface::constant`]) and standalone records it decodes +//! ([`GameSurface::record`]). It is versioned //! ([`GAME_SURFACE_SCHEMA_VERSION`]) and serialized as JSON by an app export //! function (conventionally `game_surface`), which `distributed //! game-manifest` runs and `distributed game-client` turns into typed @@ -23,11 +27,12 @@ use serde::{Deserialize, Serialize}; use crate::codec::WireType; use crate::prediction::{PredictContext, PredictStep}; use crate::protocol::PROTOCOL_VERSION; +use crate::pure::GamePure; use crate::schema::{Correction, EntitySchema}; use crate::{GameEvent, GameInput, Wire, Zone}; /// Version of the [`GameSurface`] JSON shape. -pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 2; +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 3; /// One zone type's client-facing surface. See the module docs. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -51,6 +56,48 @@ pub struct GameSurface { /// [`crate::prediction`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub predict: Option, + /// Pure functions compiled into the same WebAssembly module, by export + /// (see [`crate::pure`]). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pures: Vec, + /// Constants emitted as generated TypeScript data, by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub constants: Vec, + /// Records with a standalone codec in the generated client + /// (`encode` / `decode`), by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub codecs: Vec, +} + +/// A pure function compiled to WebAssembly ([`crate::pure::GamePure`]). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PureSurface { + /// Export suffix: the module exports `dg_pure_`. + pub export: String, + /// Cargo package declaring it (the surface's module is built from it). + pub package: String, + /// Argument type, if it takes one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub arg: Option, + /// Result type. + pub output: WireType, + /// Binary ABI version ([`crate::prediction::ABI_VERSION`]). + pub abi: u32, +} + +/// A constant value of the client (static data defined once in Rust). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConstantSurface { + /// `snake_case` name (generated TypeScript: `SCREAMING_SNAKE`). + pub name: String, + /// Wire type of the value. + #[serde(rename = "type")] + pub ty: WireType, + /// The value as a client decodes it ([`crate::codec::to_json_value`]): + /// records keyed by Rust field name, exact float values. + pub value: serde_json::Value, } /// The zone's client-predicted step ([`crate::prediction::PredictStep`]). @@ -192,6 +239,9 @@ impl GameSurface { events: Vec::new(), records: Vec::new(), predict: None, + pures: Vec::new(), + constants: Vec::new(), + codecs: Vec::new(), } } @@ -266,6 +316,15 @@ impl GameSurface { /// that every state field names a field of the kind with a matching /// scalar type; panics otherwise (surface export time). pub fn predict(mut self) -> Self { + if let Some(pure) = self.pures.first() { + assert_eq!( + pure.package, + P::PACKAGE, + "predicted step {} of game surface {} must be declared in the Cargo package of its pure functions", + P::EXPORT, + self.name + ); + } let mut records = Vec::new(); let input = P::Input::input_surface(&mut records); assert_eq!( @@ -329,6 +388,104 @@ impl GameSurface { self } + /// Add a pure function (`#[game_pure]`) to the surface's WebAssembly + /// module. Every compiled function of a surface (and its predicted step) + /// must come from one Cargo package; export names must be unique. + pub fn pure(mut self) -> Self { + assert!( + self.pures.iter().all(|p| p.export != F::EXPORT), + "pure function {} added twice to game surface {}", + F::EXPORT, + self.name + ); + let package = self + .predict + .as_ref() + .map(|p| p.package.as_str()) + .or(self.pures.first().map(|p| p.package.as_str())); + if let Some(package) = package { + assert_eq!( + package, + F::PACKAGE, + "pure function {} of game surface {} is declared in Cargo package {}, but the surface's module is built from {package}", + F::EXPORT, + self.name, + F::PACKAGE + ); + } + let mut records = Vec::new(); + let arg = crate::pure::arg_type::(&mut records); + F::Output::records(&mut records); + self.pures.push(PureSurface { + export: F::EXPORT.to_string(), + package: F::PACKAGE.to_string(), + arg, + output: F::Output::wire_type(), + abi: crate::prediction::ABI_VERSION, + }); + self.pures.sort_by(|a, b| a.export.cmp(&b.export)); + self.add_records(records); + self + } + + /// Add a constant the generated client exports as TypeScript data + /// (`constant("arena_floor", &floor)` → `ARENA_FLOOR: ArenaFloor`). The + /// value is stored as the client would decode it (exact floats, + /// quantized fields quantized); its records join the surface. Names are + /// `snake_case` and unique; panics on a non-finite float. + pub fn constant(mut self, name: &str, value: &T) -> Self { + assert!( + !name.is_empty() + && name.starts_with(|c: char| c.is_ascii_lowercase()) + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), + "constant name {name:?} of game surface {} must be snake_case", + self.name + ); + assert!( + self.constants.iter().all(|c| c.name != name), + "constant {name} added twice to game surface {}", + self.name + ); + let value = crate::codec::to_json_value(value).unwrap_or_else(|error| { + panic!( + "constant {name} of game surface {} has no client value: {error:?}", + self.name + ) + }); + let mut records = Vec::new(); + T::records(&mut records); + self.constants.push(ConstantSurface { + name: name.to_string(), + ty: T::wire_type(), + value, + }); + self.constants.sort_by(|a, b| a.name.cmp(&b.name)); + self.add_records(records); + self + } + + /// Give a record (`#[derive(GameRecord)]`) a standalone codec in the + /// generated client (`encode` / `decode`), e.g. for a + /// payload served over HTTP. + pub fn record(mut self) -> Self { + let name = match T::wire_type() { + WireType::Record { name } => name, + other => { + panic!("GameSurface::record takes a #[derive(GameRecord)] struct, not {other:?}") + } + }; + let mut records = Vec::new(); + T::records(&mut records); + if !self.codecs.contains(&name) { + self.codecs.push(name); + self.codecs.sort(); + } + self.add_records(records); + self + } + fn add_records(&mut self, records: Vec) { for record in records { match self.records.iter().find(|r| r.name == record.name) { diff --git a/distributed_game/tests/authoring/main.rs b/distributed_game/tests/authoring/main.rs index bdfe15e3c..21b18449f 100644 --- a/distributed_game/tests/authoring/main.rs +++ b/distributed_game/tests/authoring/main.rs @@ -14,10 +14,10 @@ use std::time::Duration; use distributed_game::protocol::{Reader, Writer}; use distributed_game::surface::{EventPayload, GameSurface}; use distributed_game::{ - fact_channel, predict, schema, Correction, Ctx, EntitySchema, FactCommand, FactOutcome, - FactSettlement, FieldType, FieldValue, GameEvent, GameInput, GameRecord, HostConfig, - ManualClock, MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, Wire, - WireType, WorldView, Zone, ZoneHost, + fact_channel, game_pure, predict, schema, Correction, Ctx, EntitySchema, FactCommand, + FactOutcome, FactSettlement, FieldType, FieldValue, GameEvent, GameInput, GameRecord, + HostConfig, ManualClock, MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, + Wire, WireType, WorldView, Zone, ZoneHost, }; use serde::Serialize; use serde_json::{json, Value}; @@ -185,11 +185,47 @@ pub fn sample_step( } } +/// A sample pure function compiled next to the step (generated `sampleMirror`). +#[game_pure(SampleMirrorFn)] +pub fn sample_mirror(wind: &SampleWind) -> SampleWind { + SampleWind { + speed: -wind.speed, + gusts: wind.gusts.wrapping_add(1), + } +} + +/// One without an argument (generated `sampleRows()`). +#[game_pure(SampleRowsFn)] +pub fn sample_rows() -> Vec { + sample_board().kills +} + +/// A record only a constant uses; its value is quantized like a payload. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Spot { + #[quant(min = 0.0, max = 64.0, bits = 10)] + pub at: f32, + pub label: String, +} + +pub fn sample_spot() -> Spot { + Spot { + at: 1.3, + label: "dock".into(), + } +} + pub fn sample_surface() -> GameSurface { GameSurface::for_zone::("sample") .events::() .events::() .predict::() + .pure::() + .pure::() + .constant("sample_board", &sample_board()) + .constant("sample_gusts", &vec![0.1f32, -2.5]) + .constant("sample_spot", &sample_spot()) + .record::() } // ---- a zone using all of it ---------------------------------------------- @@ -455,7 +491,7 @@ fn records_round_trip_through_the_value_codec() { #[test] fn surface_describes_everything_once() { let surface = sample_surface(); - assert_eq!(surface.schema_version, 2); + assert_eq!(surface.schema_version, 3); assert_eq!(surface.kinds.len(), 3); assert_eq!( surface.kinds[0].fields[0].correction, @@ -489,7 +525,10 @@ fn surface_describes_everything_once() { } ); let records: Vec<_> = surface.records.iter().map(|r| r.name.as_str()).collect(); - assert_eq!(records, ["Board", "Row", "SampleState", "SampleWind"]); + assert_eq!( + records, + ["Board", "Row", "SampleState", "SampleWind", "Spot"] + ); // JSON round trip (the CLI reads this shape). let json = surface.to_json(); let back: GameSurface = serde_json::from_str(&json).unwrap(); @@ -679,6 +718,8 @@ fn hex(bytes: &[u8]) -> String { #[test] fn golden_fixture_is_current() { + use distributed_game::prediction::PredictContext; + use distributed_game::pure::call_bytes; let input = SampleInput { mx: -128, my: 100, @@ -712,6 +753,25 @@ fn golden_fixture_is_current() { "sanitized": {"mx": sanitized.mx, "my": sanitized.my, "buttons": sanitized.buttons, "aim": aim_wire, "power": 0.25, "viewTick": 123_456}, }, "events": events, + // Each constant's encoding: the generated literal must decode-equal it. + "constants": { + "sample_board": hex(&distributed_game::codec::to_bytes(&sample_board())), + "sample_gusts": hex(&distributed_game::codec::to_bytes(&vec![0.1f32, -2.5])), + "sample_spot": hex(&distributed_game::codec::to_bytes(&sample_spot())), + }, + // Native calls of the pure functions (argument → output bytes). + "pures": [ + { + "export": "sample_mirror", + "arg": hex(&SampleWind { speed: 1.5, gusts: 65535 }.encode_context()), + "output": hex(&call_bytes::(&SampleWind { speed: 1.5, gusts: 65535 }.encode_context()).unwrap()), + }, + { + "export": "sample_rows", + "arg": "", + "output": hex(&call_bytes::(&[]).unwrap()), + }, + ], }); let text = serde_json::to_string_pretty(&fixture).unwrap() + "\n"; let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/authoring.json"); @@ -836,3 +896,60 @@ fn the_predicted_kind_must_be_replicated() { fn the_step_takes_the_zone_input() { let _ = GameSurface::for_zone::("sample").predict::(); } + +// ---- pure functions, constants, standalone codecs --------------------------- + +#[test] +fn pure_functions_constants_and_codecs_are_declared() { + use distributed_game::pure::{call_bytes, GamePure}; + let surface = sample_surface(); + let pures: Vec<_> = surface.pures.iter().map(|p| p.export.as_str()).collect(); + assert_eq!(pures, ["sample_mirror", "sample_rows"], "sorted by export"); + let mirror = &surface.pures[0]; + assert_eq!(mirror.package, "distributed_game"); + assert_eq!( + mirror.arg, + Some(WireType::Record { + name: "SampleWind".into() + }) + ); + assert_eq!(mirror.output, mirror.arg.clone().unwrap()); + assert_eq!(surface.pures[1].arg, None); + assert_eq!(::EXPORT, "sample_rows"); + let rows: Vec = + distributed_game::codec::from_bytes(&call_bytes::(&[]).unwrap()).unwrap(); + assert_eq!(rows, sample_board().kills); + + let names: Vec<_> = surface.constants.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["sample_board", "sample_gusts", "sample_spot"]); + // Values are what a client decodes: exact binary32, quantized, Rust field names. + assert_eq!(surface.constants[1].value, json!([f64::from(0.1f32), -2.5])); + let spot = &surface.constants[2].value; + let quantized = f32_of( + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 10, + }, + 1.3, + ); + assert_eq!(spot, &json!({"at": quantized, "label": "dock"})); + assert_ne!(quantized, f64::from(1.3f32)); + assert_eq!( + surface.constants[0].value["kills"][0]["score"], + 9_007_199_254_740_991u64 + ); + assert_eq!(surface.codecs, ["SampleWind"]); +} + +#[test] +#[should_panic(expected = "snake_case")] +fn constant_names_are_snake_case() { + let _ = sample_surface().constant("Bad", &1u8); +} + +#[test] +#[should_panic(expected = "added twice")] +fn pure_exports_are_unique() { + let _ = sample_surface().pure::(); +} diff --git a/distributed_game/tests/fixtures/authoring.json b/distributed_game/tests/fixtures/authoring.json index 172c4a84c..5983f862c 100644 --- a/distributed_game/tests/fixtures/authoring.json +++ b/distributed_game/tests/fixtures/authoring.json @@ -1,4 +1,9 @@ { + "constants": { + "sample_board": "07020103416461ffffffffffffff0f0207426f6220e29c930300ac02787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878", + "sample_gusts": "02cdcccc3d000020c0", + "sample_spot": "1504646f636b" + }, "events": [ { "hex": "e90700006041ff07", @@ -102,7 +107,72 @@ "viewTick": 123456 } }, + "pures": [ + { + "arg": "0000c03fffff03", + "export": "sample_mirror", + "output": "0000c0bf00" + }, + { + "arg": "", + "export": "sample_rows", + "output": "020103416461ffffffffffffff0f0207426f6220e29c9303" + } + ], "surface": { + "codecs": [ + "SampleWind" + ], + "constants": [ + { + "name": "sample_board", + "type": { + "name": "Board", + "type": "record" + }, + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "name": "sample_gusts", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + }, + "value": [ + 0.10000000149011612, + -2.5 + ] + }, + { + "name": "sample_spot", + "type": { + "name": "Spot", + "type": "record" + }, + "value": { + "at": 1.313783049583435, + "label": "dock" + } + } + ], "events": [ { "id": 1, @@ -487,6 +557,33 @@ "state": "SampleState" }, "protocolVersion": 1, + "pures": [ + { + "abi": 1, + "arg": { + "name": "SampleWind", + "type": "record" + }, + "export": "sample_mirror", + "output": { + "name": "SampleWind", + "type": "record" + }, + "package": "distributed_game" + }, + { + "abi": 1, + "export": "sample_rows", + "output": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + }, + "package": "distributed_game" + } + ], "records": [ { "fields": [ @@ -592,8 +689,28 @@ } ], "name": "SampleWind" + }, + { + "fields": [ + { + "name": "at", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + }, + { + "name": "label", + "type": { + "type": "short_str" + } + } + ], + "name": "Spot" } ], - "schemaVersion": 2 + "schemaVersion": 3 } } diff --git a/distributed_game_macros/src/lib.rs b/distributed_game_macros/src/lib.rs index 59ca7018b..b3bd97a75 100644 --- a/distributed_game_macros/src/lib.rs +++ b/distributed_game_macros/src/lib.rs @@ -10,6 +10,7 @@ //! | [`GameRecord`] | struct | `Wire`: a nested payload record | //! | [`FactCommand`] | struct | `FactCommand`: the cell command name of a fact input | //! | [`macro@predict`] (attribute) | fn | `PredictStep` for a client-predicted step + its WebAssembly export | +//! | [`macro@game_pure`] (attribute) | fn | `GamePure` for a pure function compiled to WebAssembly + its export | //! //! Field attributes (where they apply): //! @@ -27,6 +28,7 @@ mod event; mod fact; mod input; mod predict; +mod pure; mod replicated; mod shared; @@ -101,3 +103,19 @@ pub fn predict(args: TokenStream, item: TokenStream) -> TokenStream { let function = parse_macro_input!(item as ItemFn); finish(predict::expand(args, function)) } + +/// Declare a pure function the generated client calls through WebAssembly: +/// `#[game_pure(GridCellFn)]` on `fn(arg: &A) -> R` or `fn() -> R` (`A`, `R`: +/// `Wire` types, typically `#[derive(GameRecord)]` structs). +/// +/// Keeps the function and adds `struct GridCellFn` implementing +/// `distributed_game::pure::GamePure` (name it in +/// `GameSurface::pure::()`). On `wasm32` it also exports the +/// function as `dg_pure_` over the binary ABI described in +/// `distributed_game::pure`. +#[proc_macro_attribute] +pub fn game_pure(args: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(args as pure::Args); + let function = parse_macro_input!(item as ItemFn); + finish(pure::expand(args, function)) +} diff --git a/distributed_game_macros/src/pure.rs b/distributed_game_macros/src/pure.rs new file mode 100644 index 000000000..793ce94f2 --- /dev/null +++ b/distributed_game_macros/src/pure.rs @@ -0,0 +1,118 @@ +//! `#[game_pure(FnType)]` on a pure function `fn(arg: &A) -> R` or +//! `fn() -> R`. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{FnArg, Ident, ItemFn, Pat, ReturnType, Type}; + +use crate::shared::runtime; + +pub(crate) struct Args { + name: Ident, +} + +impl Parse for Args { + fn parse(input: ParseStream<'_>) -> syn::Result { + let name: Ident = input + .parse() + .map_err(|e| syn::Error::new(e.span(), "expected `#[game_pure(FnType)]`"))?; + if !input.is_empty() { + return Err(input.error("`#[game_pure]` takes only the generated type name")); + } + Ok(Self { name }) + } +} + +pub(crate) fn expand(args: Args, function: ItemFn) -> syn::Result { + let root = runtime()?; + let sig = &function.sig; + if !sig.generics.params.is_empty() || sig.asyncness.is_some() || sig.unsafety.is_some() { + return Err(syn::Error::new( + sig.span(), + "a game pure function must be a plain, non-generic, synchronous fn", + )); + } + let arg = match sig.inputs.iter().collect::>().as_slice() { + [] => None, + [FnArg::Typed(typed)] => { + if !matches!(&*typed.pat, Pat::Ident(_) | Pat::Wild(_)) { + return Err(syn::Error::new( + typed.pat.span(), + "use a plain binding for the argument", + )); + } + match &*typed.ty { + Type::Reference(reference) if reference.mutability.is_none() => { + Some((*reference.elem).clone()) + } + other => { + return Err(syn::Error::new( + other.span(), + "the argument must be a shared reference (`&T`, T: Wire)", + )) + } + } + } + [FnArg::Receiver(receiver)] => { + return Err(syn::Error::new( + receiver.span(), + "a game pure function is a free function, not a method", + )) + } + _ => { + return Err(syn::Error::new( + sig.inputs.span(), + "a game pure function takes nothing or one argument `&T` (bundle several values in a #[derive(GameRecord)] struct)", + )) + } + }; + let ReturnType::Type(_, output) = &sig.output else { + return Err(syn::Error::new( + sig.span(), + "a game pure function returns a value (any `Wire` type)", + )); + }; + let fn_name = &sig.ident; + let export = fn_name.to_string(); + let export = export.strip_prefix("r#").unwrap_or(&export).to_string(); + let symbol = format_ident!("dg_pure_{}", export); + let name = &args.name; + let vis = &function.vis; + let doc = + format!("The pure function [`{export}`], exported to WebAssembly as `dg_pure_{export}`."); + let (arg_ty, call) = match &arg { + Some(ty) => (quote!(#ty), quote_spanned! {output.span()=> #fn_name(arg) }), + None => ( + quote!(()), + quote_spanned! {output.span()=> { let _ = arg; #fn_name() } }, + ), + }; + Ok(quote! { + #function + + #[doc = #doc] + #[derive(Debug, Clone, Copy, Default)] + #vis struct #name; + + impl #root::pure::GamePure for #name { + const PACKAGE: &'static str = ::core::env!("CARGO_PKG_NAME"); + const EXPORT: &'static str = #export; + type Arg = #arg_ty; + type Output = #output; + + fn call(arg: &#arg_ty) -> #output { + #call + } + } + + #[cfg(target_arch = "wasm32")] + const _: () = { + #[unsafe(no_mangle)] + extern "C" fn #symbol(arg_len: u32) -> i32 { + #root::__private::pure_wasm_export::<#name>(arg_len) + } + }; + }) +} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs b/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs new file mode 100644 index 000000000..80e7c33e5 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs @@ -0,0 +1,9 @@ +use distributed_game::game_pure; + +// The argument is borrowed. +#[game_pure(Double)] +fn double(a: u32) -> u32 { + a * 2 +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr b/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr new file mode 100644 index 000000000..d3ff31283 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr @@ -0,0 +1,5 @@ +error: the argument must be a shared reference (`&T`, T: Wire) + --> tests/compile_fail/game_pure_by_value.rs:5:14 + | +5 | fn double(a: u32) -> u32 { + | ^^^ diff --git a/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs b/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs new file mode 100644 index 000000000..b299e48d7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs @@ -0,0 +1,9 @@ +use distributed_game::game_pure; + +// One argument at most: bundle several values in a #[derive(GameRecord)] struct. +#[game_pure(Sum)] +fn sum(a: &u32, b: &u32) -> u32 { + a + b +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr b/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr new file mode 100644 index 000000000..3f005d058 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr @@ -0,0 +1,5 @@ +error: a game pure function takes nothing or one argument `&T` (bundle several values in a #[derive(GameRecord)] struct) + --> tests/compile_fail/game_pure_two_args.rs:5:8 + | +5 | fn sum(a: &u32, b: &u32) -> u32 { + | ^ diff --git a/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs b/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs new file mode 100644 index 000000000..86503879f --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.rs @@ -0,0 +1,11 @@ +use distributed_game::game_pure; + +struct Opaque; + +// The output must have a payload encoding. +#[game_pure(Make)] +fn make() -> Opaque { + Opaque +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr b/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr new file mode 100644 index 000000000..f0a52a4a1 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_unsupported_output.stderr @@ -0,0 +1,27 @@ +error[E0277]: `Opaque` has no game payload encoding + --> tests/compile_fail/game_pure_unsupported_output.rs:7:14 + | +7 | fn make() -> Opaque { + | ^^^^^^ unsupported payload field type + | +help: the trait `Wire` is not implemented for `Opaque` + --> tests/compile_fail/game_pure_unsupported_output.rs:3:1 + | +3 | struct Opaque; + | ^^^^^^^^^^^^^ + = note: supported: bool, u8, i8, u16, i16, u32, i32, u64, f32, f64, String, Vec, Option and `#[derive(GameRecord)]` structs + = help: the following other types implement trait `Wire`: + bool + f32 + f64 + i16 + i32 + i8 + u16 + u32 + and $N others +note: required by a bound in `distributed_game::GamePure::Output` + --> $WORKSPACE/distributed_game/src/pure.rs + | + | type Output: Wire; + | ^^^^ required by this bound in `GamePure::Output` diff --git a/js/tests/game-generated.test.mjs b/js/tests/game-generated.test.mjs index ef25a9062..0fc9250d1 100644 --- a/js/tests/game-generated.test.mjs +++ b/js/tests/game-generated.test.mjs @@ -10,7 +10,7 @@ import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { after, before, test } from 'node:test'; -import { fromHex, toHex } from '@hops-ops/distributed/game'; +import { decodeValue, fromHex, toHex } from '@hops-ops/distributed/game'; import { predictModuleBytes } from './fixtures/predict-module.mjs'; @@ -29,6 +29,18 @@ before(async () => { }); after(() => rmSync(dir, { recursive: true, force: true })); +const ROW = { type: 'record', fields: [['rank', { type: 'u16' }], ['name', { type: 'short_str' }], ['score', { type: 'u64' }]] }; + +/** A surface wire type as the SDK codec takes it (records resolved, camelCase fields). */ +function wireType(type) { + if (type.type === 'record') { + const record = fixture.surface.records.find((r) => r.name === type.name); + return { type: 'record', fields: record.fields.map((f) => [camel(f.name), wireType(f.type)]) }; + } + if (type.item !== undefined) return { ...type, item: wireType(type.item) }; + return type; +} + const camel = (name) => name.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()); /** JSON fixture values → what the decoder returns (null → undefined, byte arrays). */ @@ -142,3 +154,38 @@ test('the predicted step is described and wired in by default', async () => { assert.equal(off.client.predictor, undefined); off.client.close(); }); + +test('constants are the values the codec decodes from the Rust encoding', () => { + for (const constant of fixture.surface.constants) { + const name = constant.name.toUpperCase(); + const decoded = decodeValue(wireType(constant.type), fromHex(fixture.constants[constant.name])); + assert.deepEqual(gen[name], decoded, constant.name); + } + assert.equal(gen.SAMPLE_GUSTS[0], Math.fround(0.1)); + assert.notEqual(gen.SAMPLE_SPOT.at, Math.fround(1.3), 'quantized like a payload'); +}); + +test('standalone record codecs round-trip the Rust encoding', () => { + const wind = { speed: 1.5, gusts: 65535 }; + const hex = fixture.pures.find((p) => p.export === 'sample_mirror').arg; + assert.equal(toHex(gen.encodeSampleWind(wind)), hex); + assert.deepEqual(gen.decodeSampleWind(fromHex(hex)), wind); + assert.throws(() => gen.decodeSampleWind(fromHex(`${hex}00`))); +}); + +test('pure functions are wrapped with their types over the compiled module', async () => { + assert.deepEqual(gen.PURES, { sampleMirror: { export: 'sample_mirror', abi: 1 }, sampleRows: { export: 'sample_rows', abi: 1 } }); + assert.ok(gen.PURES_WASM_URL.href.endsWith('/wasm/sample.wasm')); + // A stand-in module whose functions echo their argument. + const pures = gen.createSamplePures(predictModuleBytes({ pures: ['sample_mirror', 'sample_rows'] })); + await pures.ready; + const mirror = fixture.pures.find((p) => p.export === 'sample_mirror'); + // Echo: the result is the argument, decoded with the output type. + assert.deepEqual(pures.sampleMirror(gen.decodeSampleWind(fromHex(mirror.arg))), { speed: 1.5, gusts: 65535 }); + // No argument: the module sees zero bytes; echoed back they are not a + // list, and the decode error surfaces from the call. + assert.throws(() => pures.sampleRows(), /UNEXPECTED_EOF/); + // What the real module returns decodes with the generated types. + const rows = fixture.pures.find((p) => p.export === 'sample_rows'); + assert.deepEqual(decodeValue({ type: 'list', item: ROW }, fromHex(rows.output)), normalize(fixture.events.find((e) => e.name === 'board').value.kills)); +}); From 8a020ffdfd553efe49811c34f2a67df780f4800c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 11:33:18 -0500 Subject: [PATCH 198/484] feat(examples): share grid content, packs and constants from Rust MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Endless Grid: terrain, biomes and props now render from the server's own generation compiled to WebAssembly. game_sim declares #[game_pure] grid_cell (17x17 height/moisture/biome lattice + props) and grid_sample (one point); the page calls them through the generated createGridPures, sharing the predicted step's module. grid/world.ts, its parity test, grid_fixture.rs and fixtures/grid-world.json are gone. The Freeze: Pack is a GameRecord served in its payload encoding and decoded by the generated decodePack; the zone layout is the generated FREEZE_WORLD constant. The hand-written Pack/ZoneLayout types and the ad hoc layout JSON are gone. Static data the pages draw is generated from the Rust values: ARENA_FLOOR (replaces arena/floor.ts), GRID_WORLD, PIT_RULES, RIPPLE_WORLD and GALLERY_COURSE. predict-trace adds native traces of every pure function; prediction-wasm.test.mjs requires byte-identical WASM results and times grid generation (~13 µs per cell in Node, ~77 µs for the removed TypeScript twin). --- examples/game/client/src/arena/floor.ts | 29 -- examples/game/client/src/arena/main.ts | 5 +- examples/game/client/src/freeze/client.ts | 41 +- examples/game/client/src/freeze/main.ts | 15 +- examples/game/client/src/gallery/main.ts | 25 +- .../game/client/src/generated/arena/client.ts | 2 +- .../client/src/generated/arena/constants.ts | 22 + .../game/client/src/generated/arena/events.ts | 17 +- .../game/client/src/generated/arena/index.ts | 3 +- .../game/client/src/generated/arena/input.ts | 2 +- .../client/src/generated/arena/predict.ts | 2 +- .../game/client/src/generated/arena/schema.ts | 2 +- .../client/src/generated/arena/surface.json | 119 ++++- .../client/src/generated/freeze/client.ts | 2 +- .../client/src/generated/freeze/constants.ts | 75 ++++ .../client/src/generated/freeze/events.ts | 83 +++- .../game/client/src/generated/freeze/index.ts | 3 +- .../game/client/src/generated/freeze/input.ts | 2 +- .../client/src/generated/freeze/predict.ts | 2 +- .../client/src/generated/freeze/schema.ts | 2 +- .../client/src/generated/freeze/surface.json | 421 +++++++++++++++++- .../client/src/generated/gallery/client.ts | 2 +- .../client/src/generated/gallery/constants.ts | 19 + .../client/src/generated/gallery/events.ts | 23 +- .../client/src/generated/gallery/index.ts | 3 +- .../client/src/generated/gallery/input.ts | 2 +- .../client/src/generated/gallery/schema.ts | 2 +- .../client/src/generated/gallery/surface.json | 128 +++++- .../game/client/src/generated/grid/client.ts | 2 +- .../client/src/generated/grid/constants.ts | 17 + .../game/client/src/generated/grid/events.ts | 49 +- .../game/client/src/generated/grid/index.ts | 4 +- .../game/client/src/generated/grid/input.ts | 2 +- .../game/client/src/generated/grid/predict.ts | 2 +- .../game/client/src/generated/grid/pures.ts | 88 ++++ .../game/client/src/generated/grid/schema.ts | 2 +- .../client/src/generated/grid/surface.json | 262 ++++++++++- .../client/src/generated/mobpit/client.ts | 2 +- .../client/src/generated/mobpit/constants.ts | 14 + .../client/src/generated/mobpit/events.ts | 15 +- .../game/client/src/generated/mobpit/index.ts | 3 +- .../game/client/src/generated/mobpit/input.ts | 2 +- .../client/src/generated/mobpit/predict.ts | 2 +- .../client/src/generated/mobpit/schema.ts | 2 +- .../client/src/generated/mobpit/surface.json | 85 +++- .../client/src/generated/ripple/client.ts | 2 +- .../client/src/generated/ripple/constants.ts | 21 + .../client/src/generated/ripple/events.ts | 16 +- .../game/client/src/generated/ripple/index.ts | 3 +- .../game/client/src/generated/ripple/input.ts | 2 +- .../client/src/generated/ripple/predict.ts | 2 +- .../client/src/generated/ripple/schema.ts | 2 +- .../client/src/generated/ripple/surface.json | 95 +++- examples/game/client/src/grid/client.ts | 74 ++- examples/game/client/src/grid/main.ts | 79 ++-- examples/game/client/src/grid/world.ts | 179 -------- examples/game/client/src/leaderboard/main.ts | 5 +- examples/game/client/src/mobpit/client.ts | 20 +- examples/game/client/src/mobpit/main.ts | 5 +- examples/game/client/src/ripple/client.ts | 17 +- examples/game/client/src/ripple/main.ts | 9 +- .../game/client/tests/grid-headless.test.mjs | 12 +- .../client/tests/grid-world-parity.test.mjs | 57 --- .../client/tests/prediction-wasm.test.mjs | 116 ++++- examples/game/fixtures/grid-world.json | 12 - examples/game/run.sh | 27 +- examples/game/server/sim/src/arena.rs | 38 ++ examples/game/server/sim/src/grid.rs | 185 +++++++- examples/game/server/sim/src/lib.rs | 9 +- examples/game/server/src/arena/mod.rs | 1 + examples/game/server/src/freeze/content.rs | 193 ++++++-- examples/game/server/src/freeze/mod.rs | 2 + examples/game/server/src/freeze/world.rs | 18 +- examples/game/server/src/gallery/mod.rs | 57 ++- examples/game/server/src/grid/mod.rs | 3 + examples/game/server/src/mobpit/zone.rs | 40 ++ examples/game/server/src/predict_trace.rs | 142 +++++- examples/game/server/src/ripple/mod.rs | 39 ++ examples/game/server/tests/freeze_smoke.rs | 63 ++- examples/game/server/tests/grid_fixture.rs | 111 ----- 80 files changed, 2588 insertions(+), 674 deletions(-) delete mode 100644 examples/game/client/src/arena/floor.ts create mode 100644 examples/game/client/src/generated/arena/constants.ts create mode 100644 examples/game/client/src/generated/freeze/constants.ts create mode 100644 examples/game/client/src/generated/gallery/constants.ts create mode 100644 examples/game/client/src/generated/grid/constants.ts create mode 100644 examples/game/client/src/generated/grid/pures.ts create mode 100644 examples/game/client/src/generated/mobpit/constants.ts create mode 100644 examples/game/client/src/generated/ripple/constants.ts delete mode 100644 examples/game/client/src/grid/world.ts delete mode 100644 examples/game/client/tests/grid-world-parity.test.mjs delete mode 100644 examples/game/fixtures/grid-world.json delete mode 100644 examples/game/server/tests/grid_fixture.rs diff --git a/examples/game/client/src/arena/floor.ts b/examples/game/client/src/arena/floor.ts deleted file mode 100644 index 475a8c718..000000000 --- a/examples/game/client/src/arena/floor.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Drawing constants of the Arena floor, shared by the pages with an Arena - * capsule (Arena, Mob Pit, The Freeze, Boss Ripple). - * - * Rendering only: movement, collision and the dash run in Rust - * (`game_sim::arena`), on the server and — compiled to WebAssembly — in the - * client's prediction. `tests/prediction-wasm.test.mjs` checks these values - * against the native build so the drawn floor matches the simulated one. - */ - -/** Floor half extent (m). */ -export const HALF = 20; -/** Capsule radius (m). */ -export const PLAYER_RADIUS = 0.5; -/** Dash cooldown in command frames (for the HUD meter). */ -export const DASH_COOLDOWN = 45; - -/** Static circular pillars `[x, y, radius]`. */ -export const PILLARS: readonly (readonly [number, number, number])[] = [ - [0, 0, 2.5], - [-9, -9, 1.5], - [9, -9, 1.5], - [-9, 9, 1.5], - [9, 9, 1.5], - [0, -14, 1], - [0, 14, 1], - [-14, 0, 1], - [14, 0, 1] -]; diff --git a/examples/game/client/src/arena/main.ts b/examples/game/client/src/arena/main.ts index 32b0c11bc..1fceb6d29 100644 --- a/examples/game/client/src/arena/main.ts +++ b/examples/game/client/src/arena/main.ts @@ -24,7 +24,10 @@ import { Minimap, type MinimapDot } from '../shared/minimap.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; import { droneFields, isDrone, isPillar, pillarFields, playerFields, BUTTON, type MoveInput } from '../generated/arena/index.ts'; import { createArenaClient, DEFAULT_ZONE } from './client.ts'; -import { DASH_COOLDOWN, HALF, PLAYER_RADIUS } from './floor.ts'; +import { ARENA_FLOOR } from '../generated/arena/constants.ts'; + +/** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ +const { half: HALF, playerRadius: PLAYER_RADIUS, dashCooldown: DASH_COOLDOWN } = ARENA_FLOOR; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; diff --git a/examples/game/client/src/freeze/client.ts b/examples/game/client/src/freeze/client.ts index e8182ab2b..86b290238 100644 --- a/examples/game/client/src/freeze/client.ts +++ b/examples/game/client/src/freeze/client.ts @@ -2,8 +2,10 @@ * The Freeze networking without rendering (Node-testable). * * The client "build" runs one content pack (`pack()`), fetched from the - * demo's content CDN (`GET /dev/freeze/content/{version}`). What happens - * at a world barrier: + * demo's content CDN (`GET /dev/freeze/content/{version}`, the Rust `Pack` + * record in its payload encoding, decoded by the generated `decodePack`). + * The version-independent layout is the generated `FREEZE_WORLD`. What + * happens at a world barrier: * * - `Freeze`: `frozen()` holds the notice; inputs are not sent and are * counted in `droppedWhileFrozen` (the server also drops and counts any @@ -27,33 +29,22 @@ import { import * as freeze from '../generated/freeze/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -export const ZONES = { hub: 'freeze-hub', meadow: 'freeze-meadow', ember: 'freeze-ember' } as const; +const { hub, meadow, ember } = freeze.FREEZE_WORLD; +/** Zone ids (from the generated `FREEZE_WORLD`). */ +export const ZONES = { hub: hub.id, meadow: meadow.id, ember: ember.id } as const; export const DEFAULT_ZONE = ZONES.hub; /** Provenance of an event or fact (generated from the Rust `Stamp` record). */ export type Stamp = freeze.Stamp; +/** One content pack (generated from the Rust `Pack` record). */ +export type Pack = freeze.Pack; +/** A zone's layout (generated from the Rust `ZoneLayout` record). */ +export type ZoneLayout = freeze.ZoneLayout; -export type ZoneLayout = Readonly<{ - title: string; - gate: boolean; - portals: readonly Readonly<{ x: number; y: number; to: string; title: string }>[]; - pools: readonly Readonly<{ x: number; y: number; r: number }>[]; - ritual: Readonly<{ x: number; y: number }>; -}>; - -export type Pack = Readonly<{ - version: string; - name: string; - notes: readonly string[]; - hazard: 'lava' | 'ice'; - slimeSpeed: number; - slimeColor: string; - slimeScale: number; - crystalColor: string; - crystalLayout: number; - gemValue: number; - zones: Readonly> & { crystals: readonly (readonly [number, number])[][] }; -}>; +/** Layout of a zone id (`undefined` for an unknown id). */ +export function zoneLayout(zoneId: string): ZoneLayout | undefined { + return [hub, meadow, ember].find((z) => z.id === zoneId); +} export type FreezeHello = freeze.HelloEvent; @@ -72,7 +63,7 @@ export type ResumeInfo = Readonly<{ export async function fetchPack(base: string, version: string): Promise { const response = await fetch(`${base}/dev/freeze/content/${encodeURIComponent(version)}`); if (!response.ok) throw new Error(`content ${version}: HTTP ${response.status}`); - return (await response.json()) as Pack; + return freeze.decodePack(new Uint8Array(await response.arrayBuffer())); } /** Admin side of the demo (`x-game-admin-secret`). */ diff --git a/examples/game/client/src/freeze/main.ts b/examples/game/client/src/freeze/main.ts index 5f0fdc818..e8a4ae94f 100644 --- a/examples/game/client/src/freeze/main.ts +++ b/examples/game/client/src/freeze/main.ts @@ -13,15 +13,18 @@ import type { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/floor.ts'; -import { BUTTON, KIND, gemFields, playerFields, ritualFields, slimeFields, type KindName, type MoveInput } from '../generated/freeze/index.ts'; +import { ARENA_FLOOR } from '../generated/arena/constants.ts'; +import { BUTTON, FREEZE_WORLD, KIND, gemFields, playerFields, ritualFields, slimeFields, type KindName, type MoveInput } from '../generated/freeze/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createRing, createStage, material, toWorld } from '../shared/scene.ts'; -import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, ZONES, type Pack, type WorldStatus } from './client.ts'; +import { createFreezeClient, DEFAULT_ZONE, FreezeAdmin, ZONES, zoneLayout, type Pack, type WorldStatus } from './client.ts'; import './freeze.css'; +/** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ +const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; + const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; const name = params.get('name') ?? undefined; @@ -206,7 +209,7 @@ async function main(): Promise { }; mats.portal.emissiveColor = Color3.FromHexString('#5b3fa8'); mats.gem.emissiveColor = Color3.FromHexString('#8a7d1e'); - for (const [x, y, r] of PILLARS) { + for (const { x, y, r } of ARENA_FLOOR.pillars) { const p = MeshBuilder.CreateCylinder('pillar', { diameter: r * 2, height: 2, tessellation: 24 }, scene); p.position = toWorld(x, y, 1); p.material = mats.pillar; @@ -220,7 +223,7 @@ async function main(): Promise { for (const key of [...portalLabels]) stage.labels.delete(key); portalLabels.clear(); scenery = []; - const layout = pack.zones[zoneId]; + const layout = zoneLayout(zoneId); if (layout === undefined) return; const lava = pack.hazard === 'lava'; const pool = material(scene, `pool-${pack.version}`, lava ? '#ff5a1f' : '#bfe9ff', lava ? 1 : 0.85); @@ -244,7 +247,7 @@ async function main(): Promise { } const crystal = material(scene, `crystal-${pack.version}`, pack.crystalColor); crystal.emissiveColor = Color3.FromHexString(pack.crystalColor).scale(0.35); - for (const [x, y] of pack.zones.crystals[pack.crystalLayout] ?? []) { + for (const { x, y } of FREEZE_WORLD.crystals[pack.crystalLayout] ?? []) { const c = MeshBuilder.CreateCylinder('crystal', { diameterTop: 0, diameterBottom: 1.1, height: 2.6, tessellation: 5 }, scene); c.position = toWorld(x, y, 1.3); c.material = crystal; diff --git a/examples/game/client/src/gallery/main.ts b/examples/game/client/src/gallery/main.ts index 0d635993f..ac33338ab 100644 --- a/examples/game/client/src/gallery/main.ts +++ b/examples/game/client/src/gallery/main.ts @@ -23,7 +23,7 @@ import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { InputSampler } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; -import { isShooter, isTarget, shooterFields, targetFields } from '../generated/gallery/index.ts'; +import { GALLERY_COURSE, isShooter, isTarget, shooterFields, targetFields } from '../generated/gallery/index.ts'; import { createGalleryClient, DEFAULT_ZONE, targetPosition, type ShotRecord, type Vec3 } from './client.ts'; import '@babylonjs/core/Culling/ray'; // side effect: scene.createPickingRay import './gallery.css'; @@ -87,27 +87,20 @@ const mats = { mats.ghost.wireframe = true; for (const m of [mats.predicted, mats.confirmed, mats.rejected, mats.flash]) m.emissiveColor = m.diffuseColor.clone(); -// Rails / circles (decor matching the server course) and the firing line. -for (const [y, half] of [ - [2, 12], - [6, 14], - [16, 16], - [-2, 10] -] as const) { - const rail = MeshBuilder.CreateBox('rail', { width: half * 2, height: 0.05, depth: 0.1 }, scene); - rail.position = toWorld(0, y, 0.03); +// Rails / circles of the server course (generated `GALLERY_COURSE`) and the +// firing line (drawn just in front of the stations). +for (const { y, x0, x1 } of GALLERY_COURSE.rails) { + const rail = MeshBuilder.CreateBox('rail', { width: x1 - x0, height: 0.05, depth: 0.1 }, scene); + rail.position = toWorld((x0 + x1) / 2, y, 0.03); rail.material = mats.rail; } -for (const [x, y, r] of [ - [-7, 11, 4], - [7, 11, 3] -] as const) { +for (const { cx, cy, r } of GALLERY_COURSE.circles) { const ring = MeshBuilder.CreateTorus('loop', { diameter: r * 2, thickness: 0.08, tessellation: 48 }, scene); - ring.position = toWorld(x, y, 0.04); + ring.position = toWorld(cx, cy, 0.04); ring.material = mats.rail; } const line = MeshBuilder.CreateBox('firing-line', { width: 18, height: 0.04, depth: 0.15 }, scene); -line.position = toWorld(0, -13.2, 0.02); +line.position = toWorld(0, GALLERY_COURSE.firingLine + 0.8, 0.02); line.material = mats.station; type TargetVisual = { mesh: Mesh; ghost: Mesh; flash: number; flashUntil: number }; diff --git a/examples/game/client/src/generated/arena/client.ts b/examples/game/client/src/generated/arena/client.ts index b49b5a356..35174cb12 100644 --- a/examples/game/client/src/generated/arena/client.ts +++ b/examples/game/client/src/generated/arena/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/constants.ts b/examples/game/client/src/generated/arena/constants.ts new file mode 100644 index 000000000..935e5326b --- /dev/null +++ b/examples/game/client/src/generated/arena/constants.ts @@ -0,0 +1,22 @@ +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { ArenaFloor } from './events.ts'; + +/** `arena_floor`, as the client decodes it. */ +export const ARENA_FLOOR: ArenaFloor = { + half: 20, + playerRadius: 0.5, + dashCooldown: 45, + pillars: [ + { x: 0, y: 0, r: 2.5 }, + { x: -9, y: -9, r: 1.5 }, + { x: 9, y: -9, r: 1.5 }, + { x: -9, y: 9, r: 1.5 }, + { x: 9, y: 9, r: 1.5 }, + { x: 0, y: -14, r: 1 }, + { x: 0, y: 14, r: 1 }, + { x: -14, y: 0, r: 1 }, + { x: 14, y: 0, r: 1 } + ] +}; diff --git a/examples/game/client/src/generated/arena/events.ts b/examples/game/client/src/generated/arena/events.ts index 8d7f3759e..76b8dadb1 100644 --- a/examples/game/client/src/generated/arena/events.ts +++ b/examples/game/client/src/generated/arena/events.ts @@ -1,8 +1,23 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; +/** Record `Pillar` (`#[derive(GameRecord)]`). */ +export interface Pillar { + readonly x: number; + readonly y: number; + readonly r: number; +} + +/** Record `ArenaFloor` (`#[derive(GameRecord)]`). */ +export interface ArenaFloor { + readonly half: number; + readonly playerRadius: number; + readonly dashCooldown: number; + readonly pillars: readonly Pillar[]; +} + /** Record `MoveState` (`#[derive(GameRecord)]`). */ export interface MoveState { readonly x: number; diff --git a/examples/game/client/src/generated/arena/index.ts b/examples/game/client/src/generated/arena/index.ts index ae6b92901..e138f392e 100644 --- a/examples/game/client/src/generated/arena/index.ts +++ b/examples/game/client/src/generated/arena/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; diff --git a/examples/game/client/src/generated/arena/input.ts b/examples/game/client/src/generated/arena/input.ts index 453828a26..5aa128ccb 100644 --- a/examples/game/client/src/generated/arena/input.ts +++ b/examples/game/client/src/generated/arena/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/predict.ts b/examples/game/client/src/generated/arena/predict.ts index 5c6aa22bc..9d66870d1 100644 --- a/examples/game/client/src/generated/arena/predict.ts +++ b/examples/game/client/src/generated/arena/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/schema.ts b/examples/game/client/src/generated/arena/schema.ts index 029d05996..60cb7d0ab 100644 --- a/examples/game/client/src/generated/arena/schema.ts +++ b/examples/game/client/src/generated/arena/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `arena` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `arena` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/arena/surface.json b/examples/game/client/src/generated/arena/surface.json index dba3f87b5..14d787ce9 100644 --- a/examples/game/client/src/generated/arena/surface.json +++ b/examples/game/client/src/generated/arena/surface.json @@ -1,4 +1,65 @@ { + "constants": [ + { + "name": "arena_floor", + "type": { + "name": "ArenaFloor", + "type": "record" + }, + "value": { + "dash_cooldown": 45, + "half": 20.0, + "pillars": [ + { + "r": 2.5, + "x": 0.0, + "y": 0.0 + }, + { + "r": 1.5, + "x": -9.0, + "y": -9.0 + }, + { + "r": 1.5, + "x": 9.0, + "y": -9.0 + }, + { + "r": 1.5, + "x": -9.0, + "y": 9.0 + }, + { + "r": 1.5, + "x": 9.0, + "y": 9.0 + }, + { + "r": 1.0, + "x": 0.0, + "y": -14.0 + }, + { + "r": 1.0, + "x": 0.0, + "y": 14.0 + }, + { + "r": 1.0, + "x": -14.0, + "y": 0.0 + }, + { + "r": 1.0, + "x": 14.0, + "y": 0.0 + } + ], + "player_radius": 0.5 + } + } + ], "events": [ { "id": 1, @@ -234,6 +295,39 @@ }, "protocolVersion": 1, "records": [ + { + "fields": [ + { + "name": "half", + "type": { + "type": "f32" + } + }, + { + "name": "player_radius", + "type": { + "type": "f32" + } + }, + { + "name": "dash_cooldown", + "type": { + "type": "u8" + } + }, + { + "name": "pillars", + "type": { + "item": { + "name": "Pillar", + "type": "record" + }, + "type": "list" + } + } + ], + "name": "ArenaFloor" + }, { "fields": [ { @@ -274,7 +368,30 @@ } ], "name": "MoveState" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "r", + "type": { + "type": "f32" + } + } + ], + "name": "Pillar" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/examples/game/client/src/generated/freeze/client.ts b/examples/game/client/src/generated/freeze/client.ts index 70872928f..79e78f6d1 100644 --- a/examples/game/client/src/generated/freeze/client.ts +++ b/examples/game/client/src/generated/freeze/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/constants.ts b/examples/game/client/src/generated/freeze/constants.ts new file mode 100644 index 000000000..49ef025bb --- /dev/null +++ b/examples/game/client/src/generated/freeze/constants.ts @@ -0,0 +1,75 @@ +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { FreezeWorld } from './events.ts'; + +/** `freeze_world`, as the client decodes it. */ +export const FREEZE_WORLD: FreezeWorld = { + hub: { + id: 'freeze-hub', + title: 'Town Hub (safe room)', + gate: true, + portals: [ + { x: -16.5, y: 5, to: 'freeze-meadow', title: 'Whisper Meadow' }, + { x: 16.5, y: 5, to: 'freeze-ember', title: 'Ember Fields' } + ], + pools: [], + ritual: { x: 0, y: -10 } + }, + meadow: { + id: 'freeze-meadow', + title: 'Whisper Meadow', + gate: false, + portals: [ + { x: 16.5, y: 5, to: 'freeze-hub', title: 'Town Hub (safe room)' } + ], + pools: [ + { x: -6, y: 6, r: 2.200000047683716 }, + { x: 6, y: -5, r: 2.5 } + ], + ritual: { x: 0, y: -10 } + }, + ember: { + id: 'freeze-ember', + title: 'Ember Fields', + gate: false, + portals: [ + { x: -16.5, y: 5, to: 'freeze-hub', title: 'Town Hub (safe room)' } + ], + pools: [ + { x: -5, y: -5, r: 2.5 }, + { x: 6, y: 5, r: 3 }, + { x: -4, y: 12, r: 2 } + ], + ritual: { x: 0, y: -10 } + }, + crystals: [ + [ + { x: -17, y: -17 }, + { x: -11, y: -17.5 }, + { x: 17, y: -16 }, + { x: 17.5, y: 11 }, + { x: -17.5, y: 15 }, + { x: -8, y: 17 }, + { x: 10, y: 17.5 } + ], + [ + { x: 17, y: -17 }, + { x: 11, y: -17.5 }, + { x: -17, y: -16 }, + { x: -17.5, y: 11 }, + { x: 17.5, y: 15 }, + { x: 8, y: 17 }, + { x: -10, y: 17.5 } + ], + [ + { x: -17, y: -17 }, + { x: -17.5, y: -11 }, + { x: -16, y: 17 }, + { x: 11, y: 17.5 }, + { x: 15, y: -17.5 }, + { x: 17, y: -8 }, + { x: 17.5, y: 10 } + ] + ] +}; diff --git a/examples/game/client/src/generated/freeze/events.ts b/examples/game/client/src/generated/freeze/events.ts index 56ca661a6..0e4cebdbd 100644 --- a/examples/game/client/src/generated/freeze/events.ts +++ b/examples/game/client/src/generated/freeze/events.ts @@ -1,7 +1,46 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. -import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `Portal` (`#[derive(GameRecord)]`). */ +export interface Portal { + readonly x: number; + readonly y: number; + readonly to: string; + readonly title: string; +} + +/** Record `Pool` (`#[derive(GameRecord)]`). */ +export interface Pool { + readonly x: number; + readonly y: number; + readonly r: number; +} + +/** Record `Spot` (`#[derive(GameRecord)]`). */ +export interface Spot { + readonly x: number; + readonly y: number; +} + +/** Record `ZoneLayout` (`#[derive(GameRecord)]`). */ +export interface ZoneLayout { + readonly id: string; + readonly title: string; + readonly gate: boolean; + readonly portals: readonly Portal[]; + readonly pools: readonly Pool[]; + readonly ritual: Spot; +} + +/** Record `FreezeWorld` (`#[derive(GameRecord)]`). */ +export interface FreezeWorld { + readonly hub: ZoneLayout; + readonly meadow: ZoneLayout; + readonly ember: ZoneLayout; + readonly crystals: readonly (readonly Spot[])[]; +} /** Record `MoveState` (`#[derive(GameRecord)]`). */ export interface MoveState { @@ -13,6 +52,36 @@ export interface MoveState { readonly cd: number; } +/** Record `Pack` (`#[derive(GameRecord)]`). */ +export interface Pack { + readonly version: string; + readonly name: string; + readonly notes: readonly string[]; + readonly hazard: string; + readonly slimeSpeed: number; + readonly slimeColor: string; + readonly slimeScale: number; + readonly crystalColor: string; + readonly crystalLayout: number; + readonly gemValue: number; +} + +const PACK_TYPE: WireType = { + type: 'record', + fields: [ + ['version', { type: 'short_str' }], + ['name', { type: 'short_str' }], + ['notes', { type: 'list', item: { type: 'short_str' } }], + ['hazard', { type: 'short_str' }], + ['slimeSpeed', { type: 'f32' }], + ['slimeColor', { type: 'short_str' }], + ['slimeScale', { type: 'f32' }], + ['crystalColor', { type: 'short_str' }], + ['crystalLayout', { type: 'u8' }], + ['gemValue', { type: 'u32' }], + ] +}; + /** Record `Stamp` (`#[derive(GameRecord)]`). */ export interface Stamp { readonly zone: string; @@ -29,6 +98,16 @@ const STAMP_TYPE: WireType = { ] }; +/** Encode a `Pack` record (standalone codec, e.g. served over HTTP). */ +export function encodePack(value: Pack): Uint8Array { + return encodeValue(PACK_TYPE, value); +} + +/** Decode a whole `Pack` record (throws on trailing or missing bytes). */ +export function decodePack(bytes: Uint8Array): Pack { + return decodeValue(PACK_TYPE, bytes) as Pack; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly entity: number; diff --git a/examples/game/client/src/generated/freeze/index.ts b/examples/game/client/src/generated/freeze/index.ts index 61710b7c9..728a97c9c 100644 --- a/examples/game/client/src/generated/freeze/index.ts +++ b/examples/game/client/src/generated/freeze/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; diff --git a/examples/game/client/src/generated/freeze/input.ts b/examples/game/client/src/generated/freeze/input.ts index 9b2b2135c..f4050e863 100644 --- a/examples/game/client/src/generated/freeze/input.ts +++ b/examples/game/client/src/generated/freeze/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/predict.ts b/examples/game/client/src/generated/freeze/predict.ts index f3e1ab89d..c4d44deed 100644 --- a/examples/game/client/src/generated/freeze/predict.ts +++ b/examples/game/client/src/generated/freeze/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/schema.ts b/examples/game/client/src/generated/freeze/schema.ts index e859598c7..5630875eb 100644 --- a/examples/game/client/src/generated/freeze/schema.ts +++ b/examples/game/client/src/generated/freeze/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `freeze` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `freeze` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/freeze/surface.json b/examples/game/client/src/generated/freeze/surface.json index f4904d5b1..6715a24bf 100644 --- a/examples/game/client/src/generated/freeze/surface.json +++ b/examples/game/client/src/generated/freeze/surface.json @@ -1,4 +1,197 @@ { + "codecs": [ + "Pack" + ], + "constants": [ + { + "name": "freeze_world", + "type": { + "name": "FreezeWorld", + "type": "record" + }, + "value": { + "crystals": [ + [ + { + "x": -17.0, + "y": -17.0 + }, + { + "x": -11.0, + "y": -17.5 + }, + { + "x": 17.0, + "y": -16.0 + }, + { + "x": 17.5, + "y": 11.0 + }, + { + "x": -17.5, + "y": 15.0 + }, + { + "x": -8.0, + "y": 17.0 + }, + { + "x": 10.0, + "y": 17.5 + } + ], + [ + { + "x": 17.0, + "y": -17.0 + }, + { + "x": 11.0, + "y": -17.5 + }, + { + "x": -17.0, + "y": -16.0 + }, + { + "x": -17.5, + "y": 11.0 + }, + { + "x": 17.5, + "y": 15.0 + }, + { + "x": 8.0, + "y": 17.0 + }, + { + "x": -10.0, + "y": 17.5 + } + ], + [ + { + "x": -17.0, + "y": -17.0 + }, + { + "x": -17.5, + "y": -11.0 + }, + { + "x": -16.0, + "y": 17.0 + }, + { + "x": 11.0, + "y": 17.5 + }, + { + "x": 15.0, + "y": -17.5 + }, + { + "x": 17.0, + "y": -8.0 + }, + { + "x": 17.5, + "y": 10.0 + } + ] + ], + "ember": { + "gate": false, + "id": "freeze-ember", + "pools": [ + { + "r": 2.5, + "x": -5.0, + "y": -5.0 + }, + { + "r": 3.0, + "x": 6.0, + "y": 5.0 + }, + { + "r": 2.0, + "x": -4.0, + "y": 12.0 + } + ], + "portals": [ + { + "title": "Town Hub (safe room)", + "to": "freeze-hub", + "x": -16.5, + "y": 5.0 + } + ], + "ritual": { + "x": 0.0, + "y": -10.0 + }, + "title": "Ember Fields" + }, + "hub": { + "gate": true, + "id": "freeze-hub", + "pools": [], + "portals": [ + { + "title": "Whisper Meadow", + "to": "freeze-meadow", + "x": -16.5, + "y": 5.0 + }, + { + "title": "Ember Fields", + "to": "freeze-ember", + "x": 16.5, + "y": 5.0 + } + ], + "ritual": { + "x": 0.0, + "y": -10.0 + }, + "title": "Town Hub (safe room)" + }, + "meadow": { + "gate": false, + "id": "freeze-meadow", + "pools": [ + { + "r": 2.200000047683716, + "x": -6.0, + "y": 6.0 + }, + { + "r": 2.5, + "x": 6.0, + "y": -5.0 + } + ], + "portals": [ + { + "title": "Town Hub (safe room)", + "to": "freeze-hub", + "x": 16.5, + "y": 5.0 + } + ], + "ritual": { + "x": 0.0, + "y": -10.0 + }, + "title": "Whisper Meadow" + } + } + } + ], "events": [ { "id": 1, @@ -377,6 +570,45 @@ }, "protocolVersion": 1, "records": [ + { + "fields": [ + { + "name": "hub", + "type": { + "name": "ZoneLayout", + "type": "record" + } + }, + { + "name": "meadow", + "type": { + "name": "ZoneLayout", + "type": "record" + } + }, + { + "name": "ember", + "type": { + "name": "ZoneLayout", + "type": "record" + } + }, + { + "name": "crystals", + "type": { + "item": { + "item": { + "name": "Spot", + "type": "record" + }, + "type": "list" + }, + "type": "list" + } + } + ], + "name": "FreezeWorld" + }, { "fields": [ { @@ -418,6 +650,143 @@ ], "name": "MoveState" }, + { + "fields": [ + { + "name": "version", + "type": { + "type": "short_str" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "notes", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "hazard", + "type": { + "type": "short_str" + } + }, + { + "name": "slime_speed", + "type": { + "type": "f32" + } + }, + { + "name": "slime_color", + "type": { + "type": "short_str" + } + }, + { + "name": "slime_scale", + "type": { + "type": "f32" + } + }, + { + "name": "crystal_color", + "type": { + "type": "short_str" + } + }, + { + "name": "crystal_layout", + "type": { + "type": "u8" + } + }, + { + "name": "gem_value", + "type": { + "type": "u32" + } + } + ], + "name": "Pack" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "r", + "type": { + "type": "f32" + } + } + ], + "name": "Pool" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "to", + "type": { + "type": "short_str" + } + }, + { + "name": "title", + "type": { + "type": "short_str" + } + } + ], + "name": "Portal" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + } + ], + "name": "Spot" + }, { "fields": [ { @@ -440,7 +809,57 @@ } ], "name": "Stamp" + }, + { + "fields": [ + { + "name": "id", + "type": { + "type": "short_str" + } + }, + { + "name": "title", + "type": { + "type": "short_str" + } + }, + { + "name": "gate", + "type": { + "type": "bool" + } + }, + { + "name": "portals", + "type": { + "item": { + "name": "Portal", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "pools", + "type": { + "item": { + "name": "Pool", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "ritual", + "type": { + "name": "Spot", + "type": "record" + } + } + ], + "name": "ZoneLayout" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/examples/game/client/src/generated/gallery/client.ts b/examples/game/client/src/generated/gallery/client.ts index c64bcdeb4..d14738b41 100644 --- a/examples/game/client/src/generated/gallery/client.ts +++ b/examples/game/client/src/generated/gallery/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/constants.ts b/examples/game/client/src/generated/gallery/constants.ts new file mode 100644 index 000000000..8e41724fa --- /dev/null +++ b/examples/game/client/src/generated/gallery/constants.ts @@ -0,0 +1,19 @@ +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { GalleryCourse } from './events.ts'; + +/** `gallery_course`, as the client decodes it. */ +export const GALLERY_COURSE: GalleryCourse = { + rails: [ + { y: 2, x0: -12, x1: 12 }, + { y: 6, x0: -14, x1: 14 }, + { y: 16, x0: -16, x1: 16 }, + { y: -2, x0: -10, x1: 10 } + ], + circles: [ + { cx: -7, cy: 11, r: 4 }, + { cx: 7, cy: 11, r: 3 } + ], + firingLine: -14 +}; diff --git a/examples/game/client/src/generated/gallery/events.ts b/examples/game/client/src/generated/gallery/events.ts index 511d75d81..2ccc19923 100644 --- a/examples/game/client/src/generated/gallery/events.ts +++ b/examples/game/client/src/generated/gallery/events.ts @@ -1,8 +1,29 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; +/** Record `CircleTrack` (`#[derive(GameRecord)]`). */ +export interface CircleTrack { + readonly cx: number; + readonly cy: number; + readonly r: number; +} + +/** Record `RailTrack` (`#[derive(GameRecord)]`). */ +export interface RailTrack { + readonly y: number; + readonly x0: number; + readonly x1: number; +} + +/** Record `GalleryCourse` (`#[derive(GameRecord)]`). */ +export interface GalleryCourse { + readonly rails: readonly RailTrack[]; + readonly circles: readonly CircleTrack[]; + readonly firingLine: number; +} + /** Event `hello` (id 1). */ export interface HelloEvent { readonly entity: number; diff --git a/examples/game/client/src/generated/gallery/index.ts b/examples/game/client/src/generated/gallery/index.ts index cbcb3cb40..8f76cd21c 100644 --- a/examples/game/client/src/generated/gallery/index.ts +++ b/examples/game/client/src/generated/gallery/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/gallery/input.ts b/examples/game/client/src/generated/gallery/input.ts index b31e31f42..c6e3dccc1 100644 --- a/examples/game/client/src/generated/gallery/input.ts +++ b/examples/game/client/src/generated/gallery/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/schema.ts b/examples/game/client/src/generated/gallery/schema.ts index 1a19e3469..1bf71cebe 100644 --- a/examples/game/client/src/generated/gallery/schema.ts +++ b/examples/game/client/src/generated/gallery/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `gallery` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `gallery` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/gallery/surface.json b/examples/game/client/src/generated/gallery/surface.json index 850b11bad..9b94c5850 100644 --- a/examples/game/client/src/generated/gallery/surface.json +++ b/examples/game/client/src/generated/gallery/surface.json @@ -1,4 +1,50 @@ { + "constants": [ + { + "name": "gallery_course", + "type": { + "name": "GalleryCourse", + "type": "record" + }, + "value": { + "circles": [ + { + "cx": -7.0, + "cy": 11.0, + "r": 4.0 + }, + { + "cx": 7.0, + "cy": 11.0, + "r": 3.0 + } + ], + "firing_line": -14.0, + "rails": [ + { + "x0": -12.0, + "x1": 12.0, + "y": 2.0 + }, + { + "x0": -14.0, + "x1": 14.0, + "y": 6.0 + }, + { + "x0": -16.0, + "x1": 16.0, + "y": 16.0 + }, + { + "x0": -10.0, + "x1": 10.0, + "y": -2.0 + } + ] + } + } + ], "events": [ { "id": 1, @@ -264,6 +310,84 @@ ], "name": "gallery", "protocolVersion": 1, - "records": [], - "schemaVersion": 2 + "records": [ + { + "fields": [ + { + "name": "cx", + "type": { + "type": "f32" + } + }, + { + "name": "cy", + "type": { + "type": "f32" + } + }, + { + "name": "r", + "type": { + "type": "f32" + } + } + ], + "name": "CircleTrack" + }, + { + "fields": [ + { + "name": "rails", + "type": { + "item": { + "name": "RailTrack", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "circles", + "type": { + "item": { + "name": "CircleTrack", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "firing_line", + "type": { + "type": "f32" + } + } + ], + "name": "GalleryCourse" + }, + { + "fields": [ + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "x0", + "type": { + "type": "f32" + } + }, + { + "name": "x1", + "type": { + "type": "f32" + } + } + ], + "name": "RailTrack" + } + ], + "schemaVersion": 3 } diff --git a/examples/game/client/src/generated/grid/client.ts b/examples/game/client/src/generated/grid/client.ts index 38aef358c..325a29164 100644 --- a/examples/game/client/src/generated/grid/client.ts +++ b/examples/game/client/src/generated/grid/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/constants.ts b/examples/game/client/src/generated/grid/constants.ts new file mode 100644 index 000000000..8d16e48fd --- /dev/null +++ b/examples/game/client/src/generated/grid/constants.ts @@ -0,0 +1,17 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { GridWorld } from './events.ts'; + +/** `grid_world`, as the client decodes it. */ +export const GRID_WORLD: GridWorld = { + cell: 32, + defaultSeed: 12648430, + contentVersion: 1, + samples: 17, + sampleSpacing: 2, + playerRadius: 0.44999998807907104, + maxCell: 1000000, + biomes: ['highlands', 'steppe', 'forest', 'meadow'], + propKinds: ['tree', 'rock', 'bush'] +}; diff --git a/examples/game/client/src/generated/grid/events.ts b/examples/game/client/src/generated/grid/events.ts index 5325ff362..3df9d2356 100644 --- a/examples/game/client/src/generated/grid/events.ts +++ b/examples/game/client/src/generated/grid/events.ts @@ -1,8 +1,26 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, encodePayload, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout } from '@hops-ops/distributed/game'; +/** Record `Prop` (`#[derive(GameRecord)]`). */ +export interface Prop { + readonly kind: number; + readonly x: number; + readonly y: number; + readonly r: number; + readonly solid: boolean; + readonly variant: number; +} + +/** Record `GridCellContent` (`#[derive(GameRecord)]`). */ +export interface GridCellContent { + readonly heights: readonly number[]; + readonly moisture: readonly number[]; + readonly biomes: Uint8Array; + readonly props: readonly Prop[]; +} + /** Record `GridContext` (`#[derive(GameRecord)]`). */ export interface GridContext { readonly seed: number; @@ -10,6 +28,35 @@ export interface GridContext { readonly cy: number; } +/** Record `GridPoint` (`#[derive(GameRecord)]`). */ +export interface GridPoint { + readonly seed: number; + readonly cx: number; + readonly cy: number; + readonly x: number; + readonly y: number; +} + +/** Record `GridSample` (`#[derive(GameRecord)]`). */ +export interface GridSample { + readonly height: number; + readonly moisture: number; + readonly biome: number; +} + +/** Record `GridWorld` (`#[derive(GameRecord)]`). */ +export interface GridWorld { + readonly cell: number; + readonly defaultSeed: number; + readonly contentVersion: number; + readonly samples: number; + readonly sampleSpacing: number; + readonly playerRadius: number; + readonly maxCell: number; + readonly biomes: readonly string[]; + readonly propKinds: readonly string[]; +} + /** Record `WalkerState` (`#[derive(GameRecord)]`). */ export interface WalkerState { readonly x: number; diff --git a/examples/game/client/src/generated/grid/index.ts b/examples/game/client/src/generated/grid/index.ts index 111904def..3b6637722 100644 --- a/examples/game/client/src/generated/grid/index.ts +++ b/examples/game/client/src/generated/grid/index.ts @@ -1,8 +1,10 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; +export * from './pures.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/grid/input.ts b/examples/game/client/src/generated/grid/input.ts index 5e7963e92..6fbbdb41d 100644 --- a/examples/game/client/src/generated/grid/input.ts +++ b/examples/game/client/src/generated/grid/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/predict.ts b/examples/game/client/src/generated/grid/predict.ts index 3088e1c5a..22b33bb51 100644 --- a/examples/game/client/src/generated/grid/predict.ts +++ b/examples/game/client/src/generated/grid/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/pures.ts b/examples/game/client/src/generated/grid/pures.ts new file mode 100644 index 000000000..79f06eb38 --- /dev/null +++ b/examples/game/client/src/generated/grid/pures.ts @@ -0,0 +1,88 @@ +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). +// Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPures, type WasmPures, type WasmSource, type WireType } from '@hops-ops/distributed/game'; + +import type { GridCellContent, GridContext, GridPoint, GridSample } from './events.ts'; + +const PROP_TYPE: WireType = { + type: 'record', + fields: [ + ['kind', { type: 'u8' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['r', { type: 'f32' }], + ['solid', { type: 'bool' }], + ['variant', { type: 'u8' }], + ] +}; + +const GRID_CELL_CONTENT_TYPE: WireType = { + type: 'record', + fields: [ + ['heights', { type: 'list', item: { type: 'f32' } }], + ['moisture', { type: 'list', item: { type: 'f32' } }], + ['biomes', { type: 'bytes' }], + ['props', { type: 'list', item: PROP_TYPE }], + ] +}; + +const GRID_CONTEXT_TYPE: WireType = { + type: 'record', + fields: [ + ['seed', { type: 'u32' }], + ['cx', { type: 'i32' }], + ['cy', { type: 'i32' }], + ] +}; + +const GRID_POINT_TYPE: WireType = { + type: 'record', + fields: [ + ['seed', { type: 'u32' }], + ['cx', { type: 'i32' }], + ['cy', { type: 'i32' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ] +}; + +const GRID_SAMPLE_TYPE: WireType = { + type: 'record', + fields: [ + ['height', { type: 'f32' }], + ['moisture', { type: 'f32' }], + ['biome', { type: 'u8' }], + ] +}; + +/** The pure functions (`#[game_pure]`) of Cargo package `game_sim`: wrapper name → module export. */ +export const PURES = { + gridCell: { export: 'grid_cell', abi: 1 }, + gridSample: { export: 'grid_sample', abi: 1 }, +} as const; + +/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */ +export const PURES_WASM_URL: URL = new URL('./wasm/grid.wasm', import.meta.url); + +/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */ +export interface GridPureFns { + /** `grid_cell` (`dg_pure_grid_cell`). */ + gridCell(arg: GridContext): GridCellContent; + /** `grid_sample` (`dg_pure_grid_sample`). */ + gridSample(arg: GridPoint): GridSample; +} + +/** The `grid` pure functions plus `ready` / `loaded()` / `module()`. */ +export type GridPures = WasmPures; + +/** + * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by + * the predicted step too is instantiated once). + */ +export function createGridPures(source: WasmSource = PURES_WASM_URL): GridPures { + return createWasmPures(source, { + gridCell: { exportName: 'grid_cell', arg: GRID_CONTEXT_TYPE, output: GRID_CELL_CONTENT_TYPE }, + gridSample: { exportName: 'grid_sample', arg: GRID_POINT_TYPE, output: GRID_SAMPLE_TYPE }, + }); +} diff --git a/examples/game/client/src/generated/grid/schema.ts b/examples/game/client/src/generated/grid/schema.ts index bef34ff76..3adcaa89e 100644 --- a/examples/game/client/src/generated/grid/schema.ts +++ b/examples/game/client/src/generated/grid/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `grid` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `grid` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/grid/surface.json b/examples/game/client/src/generated/grid/surface.json index dddde57bb..154cd36ac 100644 --- a/examples/game/client/src/generated/grid/surface.json +++ b/examples/game/client/src/generated/grid/surface.json @@ -1,4 +1,33 @@ { + "constants": [ + { + "name": "grid_world", + "type": { + "name": "GridWorld", + "type": "record" + }, + "value": { + "biomes": [ + "highlands", + "steppe", + "forest", + "meadow" + ], + "cell": 32.0, + "content_version": 1, + "default_seed": 12648430, + "max_cell": 1000000, + "player_radius": 0.44999998807907104, + "prop_kinds": [ + "tree", + "rock", + "bush" + ], + "sample_spacing": 2.0, + "samples": 17 + } + } + ], "events": [ { "id": 1, @@ -290,7 +319,74 @@ "state": "WalkerState" }, "protocolVersion": 1, + "pures": [ + { + "abi": 1, + "arg": { + "name": "GridContext", + "type": "record" + }, + "export": "grid_cell", + "output": { + "name": "GridCellContent", + "type": "record" + }, + "package": "game_sim" + }, + { + "abi": 1, + "arg": { + "name": "GridPoint", + "type": "record" + }, + "export": "grid_sample", + "output": { + "name": "GridSample", + "type": "record" + }, + "package": "game_sim" + } + ], "records": [ + { + "fields": [ + { + "name": "heights", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + } + }, + { + "name": "moisture", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + } + }, + { + "name": "biomes", + "type": { + "type": "bytes" + } + }, + { + "name": "props", + "type": { + "item": { + "name": "Prop", + "type": "record" + }, + "type": "list" + } + } + ], + "name": "GridCellContent" + }, { "fields": [ { @@ -314,6 +410,170 @@ ], "name": "GridContext" }, + { + "fields": [ + { + "name": "seed", + "type": { + "type": "u32" + } + }, + { + "name": "cx", + "type": { + "type": "i32" + } + }, + { + "name": "cy", + "type": { + "type": "i32" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + } + ], + "name": "GridPoint" + }, + { + "fields": [ + { + "name": "height", + "type": { + "type": "f32" + } + }, + { + "name": "moisture", + "type": { + "type": "f32" + } + }, + { + "name": "biome", + "type": { + "type": "u8" + } + } + ], + "name": "GridSample" + }, + { + "fields": [ + { + "name": "cell", + "type": { + "type": "f32" + } + }, + { + "name": "default_seed", + "type": { + "type": "u32" + } + }, + { + "name": "content_version", + "type": { + "type": "u32" + } + }, + { + "name": "samples", + "type": { + "type": "u8" + } + }, + { + "name": "sample_spacing", + "type": { + "type": "f32" + } + }, + { + "name": "player_radius", + "type": { + "type": "f32" + } + }, + { + "name": "max_cell", + "type": { + "type": "i32" + } + }, + { + "name": "biomes", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "prop_kinds", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + } + ], + "name": "GridWorld" + }, + { + "fields": [ + { + "name": "kind", + "type": { + "type": "u8" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "r", + "type": { + "type": "f32" + } + }, + { + "name": "solid", + "type": { + "type": "bool" + } + }, + { + "name": "variant", + "type": { + "type": "u8" + } + } + ], + "name": "Prop" + }, { "fields": [ { @@ -332,5 +592,5 @@ "name": "WalkerState" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/examples/game/client/src/generated/mobpit/client.ts b/examples/game/client/src/generated/mobpit/client.ts index a4895c0be..547157f12 100644 --- a/examples/game/client/src/generated/mobpit/client.ts +++ b/examples/game/client/src/generated/mobpit/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/constants.ts b/examples/game/client/src/generated/mobpit/constants.ts new file mode 100644 index 000000000..2e4517bda --- /dev/null +++ b/examples/game/client/src/generated/mobpit/constants.ts @@ -0,0 +1,14 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { PitRules } from './events.ts'; + +/** `pit_rules`, as the client decodes it. */ +export const PIT_RULES: PitRules = { + tiers: [ + { tier: 1, radius: 0.5, tele: 1.7999999523162842 }, + { tier: 2, radius: 0.699999988079071, tele: 2.200000047683716 }, + { tier: 3, radius: 0.800000011920929, tele: 2.5999999046325684 } + ], + states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'] +}; diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts index 95028f84b..d2e63390a 100644 --- a/examples/game/client/src/generated/mobpit/events.ts +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; @@ -121,6 +121,13 @@ const BOARD_SNAPSHOT_TYPE: WireType = { ] }; +/** Record `MobTier` (`#[derive(GameRecord)]`). */ +export interface MobTier { + readonly tier: number; + readonly radius: number; + readonly tele: number; +} + /** Record `MoveState` (`#[derive(GameRecord)]`). */ export interface MoveState { readonly x: number; @@ -131,6 +138,12 @@ export interface MoveState { readonly cd: number; } +/** Record `PitRules` (`#[derive(GameRecord)]`). */ +export interface PitRules { + readonly tiers: readonly MobTier[]; + readonly states: readonly string[]; +} + /** Record `Profile` (`#[derive(GameRecord)]`). */ export interface Profile { readonly xp: number; diff --git a/examples/game/client/src/generated/mobpit/index.ts b/examples/game/client/src/generated/mobpit/index.ts index afb9021b6..481102c6c 100644 --- a/examples/game/client/src/generated/mobpit/index.ts +++ b/examples/game/client/src/generated/mobpit/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; diff --git a/examples/game/client/src/generated/mobpit/input.ts b/examples/game/client/src/generated/mobpit/input.ts index dde466caf..7914746a8 100644 --- a/examples/game/client/src/generated/mobpit/input.ts +++ b/examples/game/client/src/generated/mobpit/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/predict.ts b/examples/game/client/src/generated/mobpit/predict.ts index 6044e287b..fcfeb0e96 100644 --- a/examples/game/client/src/generated/mobpit/predict.ts +++ b/examples/game/client/src/generated/mobpit/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/schema.ts b/examples/game/client/src/generated/mobpit/schema.ts index e0b6d6529..3d9f5f004 100644 --- a/examples/game/client/src/generated/mobpit/schema.ts +++ b/examples/game/client/src/generated/mobpit/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `mobpit` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json index 9fd1629ec..f6b182a2f 100644 --- a/examples/game/client/src/generated/mobpit/surface.json +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -1,4 +1,40 @@ { + "constants": [ + { + "name": "pit_rules", + "type": { + "name": "PitRules", + "type": "record" + }, + "value": { + "states": [ + "idle", + "chase", + "windup", + "recover", + "return", + "dead" + ], + "tiers": [ + { + "radius": 0.5, + "tele": 1.7999999523162842, + "tier": 1 + }, + { + "radius": 0.699999988079071, + "tele": 2.200000047683716, + "tier": 2 + }, + { + "radius": 0.800000011920929, + "tele": 2.5999999046325684, + "tier": 3 + } + ] + } + } + ], "events": [ { "id": 1, @@ -708,6 +744,29 @@ ], "name": "Mismatch" }, + { + "fields": [ + { + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "radius", + "type": { + "type": "f32" + } + }, + { + "name": "tele", + "type": { + "type": "f32" + } + } + ], + "name": "MobTier" + }, { "fields": [ { @@ -749,6 +808,30 @@ ], "name": "MoveState" }, + { + "fields": [ + { + "name": "tiers", + "type": { + "item": { + "name": "MobTier", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "states", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + } + ], + "name": "PitRules" + }, { "fields": [ { @@ -871,5 +954,5 @@ "name": "Scores" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/examples/game/client/src/generated/ripple/client.ts b/examples/game/client/src/generated/ripple/client.ts index e4deecd3d..089b35949 100644 --- a/examples/game/client/src/generated/ripple/client.ts +++ b/examples/game/client/src/generated/ripple/client.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Typed client factory. // Do not edit: change the Rust definitions and regenerate. import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/constants.ts b/examples/game/client/src/generated/ripple/constants.ts new file mode 100644 index 000000000..9e1ab7c6d --- /dev/null +++ b/examples/game/client/src/generated/ripple/constants.ts @@ -0,0 +1,21 @@ +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { RippleWorld } from './events.ts'; + +/** `ripple_world`, as the client decodes it. */ +export const RIPPLE_WORLD: RippleWorld = { + realm: 'realm', + city: 'realm.city', + boroughs: [ + { + id: 'realm.city.borough-1', + hoods: ['realm.city.borough-1.hood-1', 'realm.city.borough-1.hood-2', 'realm.city.borough-1.hood-3'] + }, + { + id: 'realm.city.borough-2', + hoods: ['realm.city.borough-2.hood-1', 'realm.city.borough-2.hood-2', 'realm.city.borough-2.hood-3'] + } + ], + weather: ['storm', 'rain', 'clearing', 'clear'] +}; diff --git a/examples/game/client/src/generated/ripple/events.ts b/examples/game/client/src/generated/ripple/events.ts index 4a1fff8a9..2915a4b94 100644 --- a/examples/game/client/src/generated/ripple/events.ts +++ b/examples/game/client/src/generated/ripple/events.ts @@ -1,8 +1,14 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Events and records: payload interfaces, ids, codecs, typed subscriptions. // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; +/** Record `BoroughLayout` (`#[derive(GameRecord)]`). */ +export interface BoroughLayout { + readonly id: string; + readonly hoods: readonly string[]; +} + /** Record `MoveState` (`#[derive(GameRecord)]`). */ export interface MoveState { readonly x: number; @@ -13,6 +19,14 @@ export interface MoveState { readonly cd: number; } +/** Record `RippleWorld` (`#[derive(GameRecord)]`). */ +export interface RippleWorld { + readonly realm: string; + readonly city: string; + readonly boroughs: readonly BoroughLayout[]; + readonly weather: readonly string[]; +} + /** Record `Weather` (`#[derive(GameRecord)]`). */ export interface Weather { readonly weather: string; diff --git a/examples/game/client/src/generated/ripple/index.ts b/examples/game/client/src/generated/ripple/index.ts index 25c4ee88e..734c924a7 100644 --- a/examples/game/client/src/generated/ripple/index.ts +++ b/examples/game/client/src/generated/ripple/index.ts @@ -1,7 +1,8 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Everything generated for this surface. // Do not edit: change the Rust definitions and regenerate. export * from './client.ts'; +export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; diff --git a/examples/game/client/src/generated/ripple/input.ts b/examples/game/client/src/generated/ripple/input.ts index 8acbd37d3..7280c9a40 100644 --- a/examples/game/client/src/generated/ripple/input.ts +++ b/examples/game/client/src/generated/ripple/input.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Input frame: interface, button bits, encoder, decoder, sanitize. // Do not edit: change the Rust definitions and regenerate. import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/predict.ts b/examples/game/client/src/generated/ripple/predict.ts index e6cebe7c9..4c5324a76 100644 --- a/examples/game/client/src/generated/ripple/predict.ts +++ b/examples/game/client/src/generated/ripple/predict.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). // Do not edit: change the Rust definitions and regenerate. import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/schema.ts b/examples/game/client/src/generated/ripple/schema.ts index 3bb495c1c..19daac914 100644 --- a/examples/game/client/src/generated/ripple/schema.ts +++ b/examples/game/client/src/generated/ripple/schema.ts @@ -1,4 +1,4 @@ -// @generated by `distributed game-client` from game surface `ripple` (schema v2, protocol v1). +// @generated by `distributed game-client` from game surface `ripple` (schema v3, protocol v1). // Replicated kinds: ids, typed fields, wire types, correction defaults. // Do not edit: change the Rust definitions and regenerate. import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; diff --git a/examples/game/client/src/generated/ripple/surface.json b/examples/game/client/src/generated/ripple/surface.json index 1b146aed8..3b1bae7b2 100644 --- a/examples/game/client/src/generated/ripple/surface.json +++ b/examples/game/client/src/generated/ripple/surface.json @@ -1,4 +1,41 @@ { + "constants": [ + { + "name": "ripple_world", + "type": { + "name": "RippleWorld", + "type": "record" + }, + "value": { + "boroughs": [ + { + "hoods": [ + "realm.city.borough-1.hood-1", + "realm.city.borough-1.hood-2", + "realm.city.borough-1.hood-3" + ], + "id": "realm.city.borough-1" + }, + { + "hoods": [ + "realm.city.borough-2.hood-1", + "realm.city.borough-2.hood-2", + "realm.city.borough-2.hood-3" + ], + "id": "realm.city.borough-2" + } + ], + "city": "realm.city", + "realm": "realm", + "weather": [ + "storm", + "rain", + "clearing", + "clear" + ] + } + } + ], "events": [ { "id": 1, @@ -413,6 +450,26 @@ }, "protocolVersion": 1, "records": [ + { + "fields": [ + { + "name": "id", + "type": { + "type": "short_str" + } + }, + { + "name": "hoods", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + } + ], + "name": "BoroughLayout" + }, { "fields": [ { @@ -454,6 +511,42 @@ ], "name": "MoveState" }, + { + "fields": [ + { + "name": "realm", + "type": { + "type": "short_str" + } + }, + { + "name": "city", + "type": { + "type": "short_str" + } + }, + { + "name": "boroughs", + "type": { + "item": { + "name": "BoroughLayout", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "weather", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + } + ], + "name": "RippleWorld" + }, { "fields": [ { @@ -472,5 +565,5 @@ "name": "Weather" } ], - "schemaVersion": 2 + "schemaVersion": 3 } diff --git a/examples/game/client/src/grid/client.ts b/examples/game/client/src/grid/client.ts index 455997c8d..923799add 100644 --- a/examples/game/client/src/grid/client.ts +++ b/examples/game/client/src/grid/client.ts @@ -11,6 +11,10 @@ * - prediction of the own walker by `grid_step`, the Rust step compiled to * WebAssembly, which collides against the props of the cell named in its * context (world seed + authoritative cell, set here); + * - world content for rendering — terrain lattice, biomes, props + * (`grid_cell`) and point samples (`grid_sample`) — from the Rust world + * generation compiled into the same module (`#[game_pure]`); nothing + * static comes over the wire and there is no TypeScript twin; * - per-zone hello info (host, restored-from-hibernation …) and the * `/dev/grid/map` world map. */ @@ -18,10 +22,39 @@ import { fieldNumber, type GameClient, type GameSocketFactory, type RenderedEnti import * as grid from '../generated/grid/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -import { cellProps, parseZone, zoneId, CELL, DEFAULT_SEED, type Cell, type MoveInput, type Prop } from './world.ts'; + +export type MoveInput = grid.MoveInput; + +/** Static world facts (cell size, biome / prop names, lattice), generated from Rust. */ +export const WORLD = grid.GRID_WORLD; +export const CELL = WORLD.cell; +export const BUTTON_SPRINT = grid.BUTTON.sprint; +export const BUTTON_MARK = grid.BUTTON.mark; + +export type Cell = readonly [number, number]; +/** A cell's terrain lattice and props (`grid_cell`). */ +export type CellContent = grid.GridCellContent; +export type Prop = grid.Prop; +/** Terrain at one point (`grid_sample`). */ +export type Sample = grid.GridSample; export const DEFAULT_ZONE = 'grid.0.0'; +/** `grid..` (the zone id naming scheme of `game_sim::grid::zone_id`). */ +export function zoneId(cell: Cell): string { + return `grid.${cell[0]}.${cell[1]}`; +} + +/** Inverse of `zoneId` (canonical integers within ±`WORLD.maxCell` only). */ +export function parseZone(zone: string): [number, number] | undefined { + const m = /^grid\.(-?\d+)\.(-?\d+)$/.exec(zone); + if (m === null) return undefined; + const x = Number(m[1]); + const y = Number(m[2]); + if (String(x) !== m[1] || String(y) !== m[2] || Math.abs(x) > WORLD.maxCell || Math.abs(y) > WORLD.maxCell) return undefined; + return [x, y]; +} + /** A zone's hello (generated from the Rust `GridHello` event). */ export type GridHello = grid.HelloEvent; @@ -61,13 +94,19 @@ export type GridClient = Readonly<{ info(zone: string): GridHello | undefined; /** Seed announced by the zones (falls back to the default). */ seed(): number; - /** Props of a cell (memoized). */ + /** The compiled world generation (`grid_cell`, `grid_sample`). */ + pures: grid.GridPures; + /** Terrain lattice and props of a cell (memoized); undefined until the module loaded. */ + content(cell: Cell): CellContent | undefined; + /** Props of a cell; empty until the module loaded. */ props(cell: Cell): readonly Prop[]; + /** Terrain at a local point (clamped into the cell); undefined until the module loaded. */ + sample(cell: Cell, x: number, y: number): Sample | undefined; /** World position (m) of a rendered entity. */ worldOf(entity: RenderedEntity): { x: number; y: number } | undefined; /** Handoffs completed so far. */ handoffs(): number; - /** Resolves on the first hello with an own entity, once the predicted step is loaded. */ + /** Resolves on the first hello with an own entity, once the compiled module is loaded. */ ready: Promise; /** Called once per restored activation of any zone we see. */ onRestored(listener: (hello: GridHello) => void): () => void; @@ -88,22 +127,25 @@ export function neighbours(cell: Cell): string[] { export function createGridClient(options: GridClientOptions): GridClient { const infos = new Map(); - const propsCache = new Map(); - let seed = DEFAULT_SEED; + const contentCache = new Map(); + let seed = WORLD.defaultSeed; let authorityCell: Cell | undefined; let handoffs = 0; const restoredSeen = new Set(); const restoredListeners = new Set<(hello: GridHello) => void>(); - const props = (cell: Cell): readonly Prop[] => { + // Same module URL as the predicted step: one fetch, one instance. + const pures = grid.createGridPures(); + const content = (cell: Cell): CellContent | undefined => { + if (!pures.loaded()) return undefined; const key = `${seed}:${cell[0]}:${cell[1]}`; - let list = propsCache.get(key); - if (list === undefined) { - list = cellProps(seed, cell); - if (propsCache.size > 256) propsCache.clear(); - propsCache.set(key, list); + let cached = contentCache.get(key); + if (cached === undefined) { + cached = pures.gridCell({ seed, cx: cell[0], cy: cell[1] }); + if (contentCache.size > 256) contentCache.clear(); + contentCache.set(key, cached); } - return list; + return cached; }; const typed = grid.createGridClient({ url: (zone) => zoneUrl(zone, options.base), @@ -123,7 +165,8 @@ export function createGridClient(options: GridClientOptions): GridClient { let resolveReady: (h: GridHello) => void = () => undefined; const ready = Promise.all([ new Promise((resolve) => (resolveReady = resolve)), - typed.prediction?.ready + typed.prediction?.ready, + pures.ready ]).then(([h]) => h); const syncNeighbours = () => { @@ -172,7 +215,10 @@ export function createGridClient(options: GridClientOptions): GridClient { cell: () => authorityCell, info: (zone) => infos.get(zone), seed: () => seed, - props, + pures, + content, + props: (cell) => content(cell)?.props ?? [], + sample: (cell, x, y) => (pures.loaded() ? pures.gridSample({ seed, cx: cell[0], cy: cell[1], x, y }) : undefined), worldOf(entity) { const cell = parseZone(entity.zoneId); if (cell === undefined) return undefined; diff --git a/examples/game/client/src/grid/main.ts b/examples/game/client/src/grid/main.ts index 88e45a1e3..9ee01916b 100644 --- a/examples/game/client/src/grid/main.ts +++ b/examples/game/client/src/grid/main.ts @@ -2,8 +2,9 @@ * Endless Grid page: Babylon scene over `createGridClient`. * * - terrain, biomes and props of the 5×5 cells around you are generated - * locally from the seed (`world.ts`, bit-identical to the server) — - * nothing static comes over the wire; + * locally from the seed by the server's own Rust world generation, + * compiled to WebAssembly (`grid_cell` / `grid_sample` via the generated + * `createGridPures`) — nothing static comes over the wire; * - cell borders are tinted by the host that runs the cell; the minimap * (`/dev/grid/map`) shows active / hibernated / cold cells per host; * - your walker is predicted; everything else (critters, other walkers, @@ -32,24 +33,22 @@ import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material } from '../shared/scene.ts'; import { critterFields, isCritter, isMarker, markerFields, walkerFields } from '../generated/grid/index.ts'; -import { createGridClient, DEFAULT_ZONE, type GridHello, type MapCell, type WorldMap } from './client.ts'; import { - BIOMES, BUTTON_MARK, BUTTON_SPRINT, CELL, - PLAYER_RADIUS, - PROP_BUSH, - PROP_ROCK, - PROP_TREE, - biomeOf, - height, - moisture, + createGridClient, + DEFAULT_ZONE, parseZone, + WORLD, zoneId, type Cell, - type MoveInput -} from './world.ts'; + type CellContent, + type GridHello, + type MapCell, + type MoveInput, + type WorldMap +} from './client.ts'; import './grid.css'; const params = new URLSearchParams(location.search); @@ -58,6 +57,10 @@ const name = params.get('name') ?? undefined; const VIEW_CELLS = 2; const RELIEF = 4; const HOST_COLORS = ['#4ea1ff', '#ff9f43', '#b48cff', '#5fd39a']; +const PLAYER_RADIUS = WORLD.playerRadius; +/** Ground mesh: one vertex per terrain lattice point. */ +const SUBDIVISIONS = WORLD.samples - 1; +const PROP = Object.fromEntries(WORLD.propKinds.map((name, i) => [name, i])) as Record<'tree' | 'rock' | 'bush', number>; const api = new DevApi({ name: () => name }); const grid = createGridClient({ api }); @@ -91,10 +94,15 @@ let origin: Cell = parseZone(startZone) ?? [0, 0]; function local(cell: Cell, x: number, y: number, up = 0): Vector3 { return new Vector3((cell[0] - origin[0]) * CELL + x, terrain(cell, x, y) + up, (cell[1] - origin[1]) * CELL + y); } +/** Ground height (m) at a local point (`grid_sample`, clamped into the cell). */ function terrain(cell: Cell, x: number, y: number): number { - const cx = Math.min(CELL, Math.max(0, x)); - const cy = Math.min(CELL, Math.max(0, y)); - return height(grid.seed(), cell, cx, cy) * RELIEF; + return (grid.sample(cell, x, y)?.height ?? 0) * RELIEF; +} + +/** Lattice index of a ground vertex (local coordinates on the lattice). */ +function lattice(lx: number, ly: number): number { + const step = WORLD.sampleSpacing; + return Math.round(ly / step) * WORLD.samples + Math.round(lx / step); } // ---- terrain chunks ---- @@ -126,25 +134,24 @@ const templates = (() => { bush.bakeCurrentTransformIntoVertices(); bush.material = material(scene, 'shrub', '#4f8f3a'); for (const m of [trunk, canopy, rock, bush]) m.setEnabled(false); - return { [PROP_TREE]: [trunk, canopy], [PROP_ROCK]: [rock], [PROP_BUSH]: [bush] } as Record; + return { [PROP.tree]: [trunk, canopy], [PROP.rock]: [rock], [PROP.bush]: [bush] } as Record; })(); // Props are not parented to the ground: instanced children of a moved // parent rendered fully fogged (white) here, so they are placed directly. -type Chunk = { cell: Cell; ground: Mesh; props: { mesh: InstancedMesh; at: Vector3 }[]; border: LinesMesh; owner?: string }; +type Chunk = { cell: Cell; content: CellContent; ground: Mesh; props: { mesh: InstancedMesh; at: Vector3 }[]; border: LinesMesh; owner?: string }; const chunks = new Map(); -function chunkColors(cell: Cell, ground: Mesh, owner: string | undefined): void { +function chunkColors(content: CellContent, ground: Mesh, owner: string | undefined): void { const positions = ground.getVerticesData(VertexBuffer.PositionKind)!; const colors = new Float32Array((positions.length / 3) * 4); const tint = owner === undefined ? undefined : Color3.FromHexString(hostColor(owner)); - const seed = grid.seed(); for (let i = 0; i < positions.length / 3; i += 1) { const lx = positions[i * 3]! + CELL / 2; const ly = positions[i * 3 + 2]! + CELL / 2; - const h = height(seed, cell, lx, ly); - const b = biomeOf(h, moisture(seed, cell, lx, ly)); - let c = BIOME_COLORS[b]!.scale(0.72 + h * 0.55); + const k = lattice(lx, ly); + const h = content.heights[k]!; + let c = BIOME_COLORS[content.biomes[k]!]!.scale(0.72 + h * 0.55); if (lx % 8 === 0 || ly % 8 === 0) c = Color3.Lerp(c, Color3.FromHexString('#d9c9a3'), 0.28); // trails if (tint !== undefined) c = Color3.Lerp(c, tint, 0.1); colors.set([c.r, c.g, c.b, 1], i * 4); @@ -152,12 +159,12 @@ function chunkColors(cell: Cell, ground: Mesh, owner: string | undefined): void ground.setVerticesData(VertexBuffer.ColorKind, colors); } -function createChunk(cell: Cell): Chunk { +function createChunk(cell: Cell, content: CellContent): Chunk { const key = zoneId(cell); - const ground = MeshBuilder.CreateGround(`ground-${key}`, { width: CELL, height: CELL, subdivisions: 16, updatable: true }, scene); + const ground = MeshBuilder.CreateGround(`ground-${key}`, { width: CELL, height: CELL, subdivisions: SUBDIVISIONS, updatable: true }, scene); const positions = ground.getVerticesData(VertexBuffer.PositionKind)!; for (let i = 0; i < positions.length / 3; i += 1) { - positions[i * 3 + 1] = height(grid.seed(), cell, positions[i * 3]! + CELL / 2, positions[i * 3 + 2]! + CELL / 2) * RELIEF; + positions[i * 3 + 1] = content.heights[lattice(positions[i * 3]! + CELL / 2, positions[i * 3 + 2]! + CELL / 2)]! * RELIEF; } const normals: number[] = []; VertexData.ComputeNormals(positions, ground.getIndices()!, normals); @@ -165,13 +172,13 @@ function createChunk(cell: Cell): Chunk { ground.updateVerticesData(VertexBuffer.NormalKind, normals); ground.material = groundMat; const owner = owners.get(key); - chunkColors(cell, ground, owner); + chunkColors(content, ground, owner); const props: Chunk['props'] = []; - for (const [i, p] of grid.props(cell).entries()) { + for (const [i, p] of content.props.entries()) { for (const [j, template] of templates[p.kind]!.entries()) { const inst = template.createInstance(`prop-${key}-${i}-${j}`); - inst.scaling.setAll(p.kind === PROP_TREE ? p.r / 0.55 : p.r); + inst.scaling.setAll(p.kind === PROP.tree ? p.r / 0.55 : p.r); inst.rotation.y = (p.variant / 255) * Math.PI * 2; props.push({ mesh: inst, at: new Vector3(p.x - CELL / 2, terrain(cell, p.x, p.y) - 0.1, p.y - CELL / 2) }); } @@ -186,7 +193,7 @@ function createChunk(cell: Cell): Chunk { const border = MeshBuilder.CreateLines(`border-${key}`, { points: edge }, scene); border.parent = ground; border.color = Color3.FromHexString(hostColor(owner)); - return { cell, ground, props, border, owner }; + return { cell, content, ground, props, border, owner }; } function syncChunks(): void { @@ -196,7 +203,10 @@ function syncChunks(): void { const cell: Cell = [origin[0] + dx, origin[1] + dy]; const key = zoneId(cell); wanted.add(key); - if (!chunks.has(key)) chunks.set(key, createChunk(cell)); + if (chunks.has(key)) continue; + // Content comes from the compiled module; until it loads there is nothing to draw. + const content = grid.content(cell); + if (content !== undefined) chunks.set(key, createChunk(cell, content)); } } for (const [key, chunk] of chunks) { @@ -212,7 +222,7 @@ function syncChunks(): void { if (owner !== chunk.owner) { chunk.owner = owner; chunk.border.color = Color3.FromHexString(hostColor(owner)); - chunkColors(chunk.cell, chunk.ground, owner); + chunkColors(chunk.content, chunk.ground, owner); } } } @@ -409,6 +419,8 @@ function sendCommandFrame(): void { // ---- frame ---- syncChunks(); +// The world generation is compiled Rust: draw the chunks once it is loaded. +grid.pures.ready.then(syncChunks, (error: unknown) => hud.row('Status', `world module failed: ${String(error)}`)); stage.onFrame((now, dtMs) => { commandFrames.update(now, sendCommandFrame); const cell = grid.cell(); @@ -457,7 +469,8 @@ stage.onFrame((now, dtMs) => { hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); hud.row('Cell', cell === undefined ? '—' : `${cell[0]}, ${cell[1]} · local ${px.toFixed(1)}, ${py.toFixed(1)}`); hud.row('Host', hello?.host ?? '—'); - hud.row('Biome', cell === undefined ? '—' : BIOMES[biomeOf(height(grid.seed(), cell, px, py), moisture(grid.seed(), cell, px, py))]!); + const here = cell === undefined ? undefined : grid.sample(cell, px, py); + hud.row('Biome', here === undefined ? '—' : WORLD.biomes[here.biome]!); hud.row('Neighbours', `${observers.filter((z) => z.connection.state === 'open').length}/8 observed`); hud.row('Handoffs', String(grid.handoffs())); hud.row('Markers here', String(markers)); diff --git a/examples/game/client/src/grid/world.ts b/examples/game/client/src/grid/world.ts deleted file mode 100644 index 4966b29ca..000000000 --- a/examples/game/client/src/grid/world.ts +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Procedural world *content* of the Endless Grid, for rendering: terrain - * height, biomes, props, zone ids. - * - * **Twin of the generation in `examples/game/server/sim/src/grid.rs`**, - * bit-identical by construction (`u32` hashing with `Math.imul` / `>>> 0`, - * binary32 arithmetic with `f()` (= `Math.fround`) after every operation, - * only `+ - * /`, `sqrt` and `floor`) and checked against the Rust-written - * fixture `examples/game/fixtures/grid-world.json` by - * `tests/grid-world-parity.test.mjs`. Serving world content from WASM too - * would retire this file; it is a separate follow-up. - * - * Movement is **not** here: the own walker is predicted by the Rust step - * compiled to WebAssembly (`grid_step`, which generates the cell's props - * itself), wired by the generated client (`../generated/grid`). - */ -import { BUTTON } from '../generated/grid/index.ts'; - -export type { MoveInput } from '../generated/grid/index.ts'; - -const f = Math.fround; - -export const CELL = 32; -export const CONTENT_VERSION = 1; -export const DEFAULT_SEED = 0x00c0ffee; -export const SUB = 4; -export const SUB_SIZE = 8; -export const PROP_MARGIN = 2; -export const PROP_SPAN = 4; -/** Walker radius (m, for drawing; collision is in the WASM step). */ -export const PLAYER_RADIUS = f(0.45); -export const BUTTON_SPRINT = BUTTON.sprint; -export const BUTTON_MARK = BUTTON.mark; - -export const BIOMES = ['highlands', 'steppe', 'forest', 'meadow'] as const; -const PROP_DENSITY = [0.4375, 0.1875, 0.75, 0.3125]; -const SALT_HEIGHT = [1, 2, 3]; -const SALT_MOISTURE = 7; -const SALT_PROP = 100; - -export const PROP_TREE = 0; -export const PROP_ROCK = 1; -export const PROP_BUSH = 2; - -export type Prop = Readonly<{ kind: number; x: number; y: number; r: number; solid: boolean; variant: number }>; -export type Cell = readonly [number, number]; - -/** lowbias32. */ -export function hash32(v: number): number { - let x = v >>> 0; - x = (x ^ (x >>> 16)) >>> 0; - x = Math.imul(x, 0x7feb352d) >>> 0; - x = (x ^ (x >>> 15)) >>> 0; - x = Math.imul(x, 0x846ca68b) >>> 0; - x = (x ^ (x >>> 16)) >>> 0; - return x; -} - -export function mix(seed: number, salt: number, a: number, b: number): number { - const salted = ((salt >>> 0) + (Math.imul(CONTENT_VERSION, 0x9e3779b9) >>> 0)) >>> 0; - let h = hash32((seed ^ hash32(salted)) >>> 0); - h = hash32((h ^ (a >>> 0)) >>> 0); - return hash32((h + (Math.imul(b | 0, 0x85ebca6b) >>> 0)) >>> 0); -} - -/** Top 24 bits in [0, 1) (exact binary32). */ -export function unit(h: number): number { - return (h >>> 8) * (1 / 16777216); -} - -function lattice(c: number, l: number, spacing: number): [number, number] { - const s = spacing; - if (spacing <= CELL) { - const per = CELL / spacing; - const k = Math.max(0, Math.min(per, Math.floor(f(l / s)))); - const frac = f(f(l - k * spacing) / s); - return [(Math.imul(c, per) + k) | 0, frac]; - } - const n = spacing / CELL; - let i = Math.floor(c / n); - let off = f(f((c - i * n) * CELL) + l); - if (off >= s) { - i = (i + 1) | 0; - off = f(off - s); - } - return [i, f(off / s)]; -} - -function smooth(t: number): number { - return f(f(t * t) * f(3 - f(2 * t))); -} - -function lerp(a: number, b: number, t: number): number { - return f(a + f(f(b - a) * t)); -} - -/** Value noise in [0, 1) with lattice `spacing` (m). */ -export function noise(seed: number, salt: number, cell: Cell, lx: number, ly: number, spacing: number): number { - const [ix, fx] = lattice(cell[0], lx, spacing); - const [iy, fy] = lattice(cell[1], ly, spacing); - const v = (dx: number, dy: number) => unit(mix(seed, salt, (ix + dx) | 0, (iy + dy) | 0)); - const sx = smooth(fx); - const sy = smooth(fy); - return lerp(lerp(v(0, 0), v(1, 0), sx), lerp(v(0, 1), v(1, 1), sx), sy); -} - -/** Terrain height in [0, 1). */ -export function height(seed: number, cell: Cell, lx: number, ly: number): number { - const a = f(noise(seed, SALT_HEIGHT[0]!, cell, lx, ly, 64) * 0.5625); - const b = f(noise(seed, SALT_HEIGHT[1]!, cell, lx, ly, 16) * 0.3125); - const c = f(noise(seed, SALT_HEIGHT[2]!, cell, lx, ly, 8) * 0.125); - return f(f(a + b) + c); -} - -export function moisture(seed: number, cell: Cell, lx: number, ly: number): number { - return noise(seed, SALT_MOISTURE, cell, lx, ly, 128); -} - -/** Biome index into BIOMES (given height and moisture, or computed). */ -export function biome(seed: number, cell: Cell, lx: number, ly: number): number { - return biomeOf(height(seed, cell, lx, ly), moisture(seed, cell, lx, ly)); -} - -export function biomeOf(h: number, m: number): number { - if (h > 0.6875) return 0; - if (m < 0.375) return 1; - if (m > 0.625) return 2; - return 3; -} - -/** The props of a cell, sub-cell by sub-cell (row-major). */ -export function cellProps(seed: number, cell: Cell): Prop[] { - const props: Prop[] = []; - for (let j = 0; j < SUB; j += 1) { - for (let i = 0; i < SUB; i += 1) { - const gx = (Math.imul(cell[0], SUB) + i) | 0; - const gy = (Math.imul(cell[1], SUB) + j) | 0; - const h0 = mix(seed, SALT_PROP, gx, gy); - const b = biome(seed, cell, i * SUB_SIZE + SUB_SIZE / 2, j * SUB_SIZE + SUB_SIZE / 2); - if (unit(h0) >= PROP_DENSITY[b]!) continue; - const h1 = hash32((h0 ^ 0x68e31da4) >>> 0); - const h2 = hash32((h1 ^ 0xb5297a4d) >>> 0); - const h3 = hash32((h2 ^ 0x1b56c4e9) >>> 0); - const h4 = hash32((h3 ^ 0x2545f491) >>> 0); - const x = f(f(i * SUB_SIZE + PROP_MARGIN) + f(unit(h1) * PROP_SPAN)); - const y = f(f(j * SUB_SIZE + PROP_MARGIN) + f(unit(h2) * PROP_SPAN)); - const k = unit(h3); - let kind: number; - if (b === 0) kind = k < 0.8125 ? PROP_ROCK : PROP_TREE; - else if (b === 1) kind = k < 0.5 ? PROP_ROCK : PROP_BUSH; - else if (b === 2) kind = k < 0.8125 ? PROP_TREE : k < 0.875 ? PROP_ROCK : PROP_BUSH; - else kind = k < 0.375 ? PROP_TREE : k < 0.5625 ? PROP_ROCK : PROP_BUSH; - const u = unit(h4); - const r = - kind === PROP_TREE - ? f(0.5 + f(u * 0.3125)) - : kind === PROP_ROCK - ? f(0.625 + f(u * 0.375)) - : f(0.5 + f(u * 0.25)); - props.push({ kind, x, y, r, solid: kind !== PROP_BUSH, variant: h4 >>> 24 }); - } - } - return props; -} - -export const MAX_CELL = 1_000_000; - -export function zoneId(cell: Cell): string { - return `grid.${cell[0]}.${cell[1]}`; -} - -export function parseZone(zone: string): [number, number] | undefined { - const m = /^grid\.(-?\d+)\.(-?\d+)$/.exec(zone); - if (m === null) return undefined; - const x = Number(m[1]); - const y = Number(m[2]); - if (String(x) !== m[1] || String(y) !== m[2] || Math.abs(x) > MAX_CELL || Math.abs(y) > MAX_CELL) return undefined; - return [x, y]; -} diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts index e05c9c31e..07e28d326 100644 --- a/examples/game/client/src/leaderboard/main.ts +++ b/examples/game/client/src/leaderboard/main.ts @@ -3,7 +3,7 @@ * top-10 snapshots, reads your rank and neighbours on every push, and * triggers a rebuild from the cells' event history. */ -import { HALF } from '../arena/floor.ts'; +import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { isMob, isPillar, @@ -17,6 +17,9 @@ import { import { createBoardWatcher, DEFAULT_ZONE, MobPitApi, TIERS, type BoardPosition } from '../mobpit/client.ts'; import { DevApi } from '../shared/dev-api.ts'; +/** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ +const { half: HALF } = ARENA_FLOOR; + const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; const api = new DevApi(); diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts index 949cd07b5..543ddfed3 100644 --- a/examples/game/client/src/mobpit/client.ts +++ b/examples/game/client/src/mobpit/client.ts @@ -15,13 +15,21 @@ import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; import { latest } from '../shared/latest.ts'; export const DEFAULT_ZONE = 'pit-1'; -export const MOB_STATE = ['idle', 'chase', 'windup', 'recover', 'return'] as const; -/** Per tier: display name, body radius, telegraph radius (server `tier_stats`). */ -export const TIERS: Readonly> = { - 1: { name: 'Grunt', radius: 0.5, tele: 1.8, color: '#9ad16b' }, - 2: { name: 'Brute', radius: 0.7, tele: 2.2, color: '#b48cf2' }, - 3: { name: 'Elite', radius: 0.8, tele: 2.6, color: '#ff6b6b' } +/** `state` names of the `mob` kind, by value (generated from the Rust `MOB_STATES`). */ +export const MOB_STATE = pit.PIT_RULES.states; +/** Presentation of each tier (client only). */ +const TIER_LOOK: Readonly> = { + 1: { name: 'Grunt', color: '#9ad16b' }, + 2: { name: 'Brute', color: '#b48cf2' }, + 3: { name: 'Elite', color: '#ff6b6b' } }; +/** + * Per tier: display name and color (client presentation), body and + * telegraph radius (the server's `tier_stats`, generated `PIT_RULES`). + */ +export const TIERS: Readonly> = Object.fromEntries( + pit.PIT_RULES.tiers.map((t) => [t.tier, { ...(TIER_LOOK[t.tier] ?? { name: `Tier ${t.tier}`, color: '#9ad16b' }), radius: t.radius, tele: t.tele }]) +); /** `/dev/mobpit/leaderboard` neighbourhood (HTTP only, not a zone event). */ export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: pit.BoardRow[] }>; diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index e0c04c0ae..e1af20b90 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -14,7 +14,7 @@ import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PLAYER_RADIUS } from '../arena/floor.ts'; +import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { BUTTON, isMob, @@ -34,6 +34,9 @@ import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; import { createMobPitClient, DEFAULT_ZONE, MobPitApi, TIERS } from './client.ts'; +/** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ +const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; + const SLOW_MS = 1500; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; diff --git a/examples/game/client/src/ripple/client.ts b/examples/game/client/src/ripple/client.ts index 760aaf228..410156046 100644 --- a/examples/game/client/src/ripple/client.ts +++ b/examples/game/client/src/ripple/client.ts @@ -14,14 +14,15 @@ import type { GameClient, GameSocketFactory } from '@hops-ops/distributed/game'; import * as gen from '../generated/ripple/index.ts'; import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; -export const REALM = 'realm'; -export const CITY = 'realm.city'; -export const BOROUGHS = ['realm.city.borough-1', 'realm.city.borough-2'] as const; -export const HOODS_PER_BOROUGH = 3; -export const DEFAULT_ZONE = 'realm.city.borough-1.hood-1'; +/** The zone hierarchy and weather names, generated from the Rust `ripple_world()`. */ +const WORLD = gen.RIPPLE_WORLD; +export const REALM = WORLD.realm; +export const CITY = WORLD.city; +export const BOROUGHS: readonly string[] = WORLD.boroughs.map((b) => b.id); +export const DEFAULT_ZONE = WORLD.boroughs[0]!.hoods[0]!; export const ACTION_ATTACK = gen.BITS.action.attack; export const ACTION_SMITE = gen.BITS.action.smite; -export const WEATHER = ['storm', 'rain', 'clearing', 'clear'] as const; +export const WEATHER = WORLD.weather; export type HoodInput = gen.HoodInput; export type TierName = 'realm' | 'city' | 'borough' | 'hood'; @@ -46,7 +47,7 @@ export type TierView = Readonly<{ }>; export function hoods(borough: string): string[] { - return Array.from({ length: HOODS_PER_BOROUGH }, (_, i) => `${borough}.hood-${i + 1}`); + return [...(WORLD.boroughs.find((b) => b.id === borough)?.hoods ?? [])]; } /** Every zone, root first (tree order). */ @@ -59,7 +60,7 @@ export function allZones(): string[] { export function tierOf(zone: string): TierName | undefined { if (zone === REALM) return 'realm'; if (zone === CITY) return 'city'; - if ((BOROUGHS as readonly string[]).includes(zone)) return 'borough'; + if (BOROUGHS.includes(zone)) return 'borough'; return BOROUGHS.some((b) => hoods(b).includes(zone)) ? 'hood' : undefined; } diff --git a/examples/game/client/src/ripple/main.ts b/examples/game/client/src/ripple/main.ts index a02b7bb52..39c7e09cd 100644 --- a/examples/game/client/src/ripple/main.ts +++ b/examples/game/client/src/ripple/main.ts @@ -17,7 +17,7 @@ import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; import { Scene } from '@babylonjs/core/scene'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; -import { HALF, PILLARS, PLAYER_RADIUS } from '../arena/floor.ts'; +import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { BITS, isPlayer, playerFields } from '../generated/ripple/index.ts'; import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; @@ -35,6 +35,9 @@ import { } from './client.ts'; import './ripple.css'; +/** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ +const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; + const params = new URLSearchParams(location.search); let hood = params.get('hood') ?? DEFAULT_ZONE; if (tierOf(hood) !== 'hood') hood = DEFAULT_ZONE; @@ -76,13 +79,13 @@ const mats = { down: material(scene, 'down', '#4a4a4a') }; mats.boss.emissiveColor = Color3.FromHexString('#3a0b08'); -for (const [i, [x, y, r]] of PILLARS.entries()) { +for (const [i, { x, y, r }] of ARENA_FLOOR.pillars.entries()) { if (i === 0) continue; // the boss stands on the central pillar const ruin = MeshBuilder.CreateCylinder(`ruin-${i}`, { diameter: r * 2, height: 1.2 + (i % 3) * 0.8, tessellation: 7 }, scene); ruin.position = toWorld(x, y, ruin.getBoundingInfo().boundingBox.extendSize.y); ruin.material = mats.pillar; } -const boss = MeshBuilder.CreateSphere('boss', { diameter: PILLARS[0]![2] * 2, segments: 12 }, scene); +const boss = MeshBuilder.CreateSphere('boss', { diameter: ARENA_FLOOR.pillars[0]!.r * 2, segments: 12 }, scene); boss.scaling.y = 1.3; boss.material = mats.boss; boss.position = toWorld(0, 0, 2.2); diff --git a/examples/game/client/tests/grid-headless.test.mjs b/examples/game/client/tests/grid-headless.test.mjs index db72d5c89..d29b0f4af 100644 --- a/examples/game/client/tests/grid-headless.test.mjs +++ b/examples/game/client/tests/grid-headless.test.mjs @@ -8,13 +8,14 @@ * between hosts, following every Handoff/Redirect with the SDK — the * session survives and the walker ends in the expected cell; * - the cell left behind hibernates (world map) and a new visitor gets - * the "restored from hibernation" hello. + * the "restored from hibernation" hello; + * - the world content each crossed cell renders (terrain lattice, props) + * comes from the compiled Rust generation (`grid_cell`). */ import assert from 'node:assert/strict'; import test from 'node:test'; -import { createGridClient } from '../src/grid/client.ts'; -import { BUTTON_SPRINT, zoneId } from '../src/grid/world.ts'; +import { BUTTON_SPRINT, createGridClient, WORLD, zoneId } from '../src/grid/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { startCluster } from './helpers/cluster.mjs'; import { memoryStorage, sleep, until } from './helpers/demo-server.mjs'; @@ -34,6 +35,11 @@ test('grid walker crosses cells and hosts; empty cells hibernate and restore', { await client.connect('grid.0.0'); const hello = await grid.ready; assert.deepEqual(hello.cell, [0, 0]); + // The module is loaded with the step: content is there for every cell. + const origin = grid.content([0, 0]); + assert.equal(origin.heights.length, WORLD.samples * WORLD.samples); + assert.ok(grid.props([0, 0]).length > 0, 'the origin cell has props'); + assert.equal(grid.sample([0, 0], 32, 32).height, grid.content([0, 0]).heights.at(-1)); const principal = api.last.principal; await until(() => client.predictor.active, 5_000, 'walker bound'); await until( diff --git a/examples/game/client/tests/grid-world-parity.test.mjs b/examples/game/client/tests/grid-world-parity.test.mjs deleted file mode 100644 index 6574de50a..000000000 --- a/examples/game/client/tests/grid-world-parity.test.mjs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Rust ↔ TypeScript parity of the Endless Grid's procedural world content - * (rendering only): replays `examples/game/fixtures/grid-world.json` - * (written by `server/tests/grid_fixture.rs`) through `src/grid/world.ts`. - * Every value must match bit for bit — the client draws the props the - * server collides against. Movement prediction runs the Rust step as WASM - * (`prediction-wasm.test.mjs`), so it has no TypeScript twin to check. - */ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -import * as world from '../src/grid/world.ts'; - -const fixture = JSON.parse(readFileSync(new URL('../../fixtures/grid-world.json', import.meta.url), 'utf8')); -const f = Math.fround; - -test('constants and hashes match', () => { - const c = fixture.constants; - assert.equal(c.seed, world.DEFAULT_SEED); - assert.equal(c.contentVersion, world.CONTENT_VERSION); - assert.equal(c.cell, world.CELL); - assert.equal(c.propMargin, world.PROP_MARGIN); - assert.deepEqual([0, 1, 0xdeadbeef, 0xffffffff].map(world.hash32), c.hashes); - assert.deepEqual([world.mix(c.seed, 3, -5, 7), world.mix(0, 0, -2147483648, 2147483647)], c.mix); -}); - -test('terrain, moisture, biomes and props are bit-identical', () => { - const seed = fixture.constants.seed; - let props = 0; - for (const expected of fixture.cells) { - const cell = expected.cell; - let k = 0; - for (let j = 0; j <= 8; j += 1) { - for (let i = 0; i <= 8; i += 1, k += 1) { - const lx = i * 4; - const ly = j * 4 + 0.25; - assert.equal(world.height(seed, cell, lx, ly), f(expected.heights[k]), `height ${cell} ${i},${j}`); - assert.equal(world.moisture(seed, cell, lx, ly), f(expected.moisture[k]), `moisture ${cell} ${i},${j}`); - assert.equal(world.biome(seed, cell, lx, ly), expected.biomes[k], `biome ${cell} ${i},${j}`); - } - } - const actual = world.cellProps(seed, cell).map((p) => [p.kind, p.x, p.y, p.r, p.solid, p.variant]); - const want = expected.props.map(([kind, x, y, r, solid, variant]) => [kind, f(x), f(y), f(r), solid, variant]); - assert.deepEqual(actual, want, `props of ${cell}`); - props += actual.length; - } - assert.ok(props > 10, 'fixture cells have props'); -}); - -test('zone ids round-trip', () => { - assert.deepEqual(world.parseZone('grid.-3.12'), [-3, 12]); - assert.equal(world.zoneId([4, -2]), 'grid.4.-2'); - for (const bad of ['grid.1', 'grid.01.2', 'grid.1.2.3', 'grid.2000000.0', 'arena-1']) { - assert.equal(world.parseZone(bad), undefined, bad); - } -}); diff --git a/examples/game/client/tests/prediction-wasm.test.mjs b/examples/game/client/tests/prediction-wasm.test.mjs index 22d0d6904..42e6719b4 100644 --- a/examples/game/client/tests/prediction-wasm.test.mjs +++ b/examples/game/client/tests/prediction-wasm.test.mjs @@ -1,18 +1,21 @@ /** - * Native ↔ WebAssembly exact match of every demo's client-predicted step, - * and the cost of prediction with it. + * Native ↔ WebAssembly exact match of every demo's client-predicted step + * and `#[game_pure]` function, and the cost of using them. * * `game-demos predict-trace` (the native build) prints, per step function, - * recorded input streams with the state after every frame. Each surface's - * compiled module (`src/generated//wasm/.wasm`, built by - * `distributed game-wasm`) replays the same streams and must produce the - * same bytes — every float bit included. The generated `predict` (state ↔ - * entity fields, input encoder) is checked over the same streams, and a - * `Predictor` reconciling with 10 pending inputs is timed. + * recorded input streams with the state after every frame, and per pure + * function recorded arguments with their results. Each surface's compiled + * module (`src/generated//wasm/.wasm`, built by + * `distributed game-wasm`) replays the same streams and calls and must + * produce the same bytes — every float bit included. The generated + * `predict` (state ↔ entity fields, input encoder) and pure wrappers + * (`createGridPures`) are checked over the same data; a `Predictor` + * reconciling with 10 pending inputs and generating a grid cell are timed. * - * The steps only use operations that are correctly rounded on every target - * (`+ - * /`, `sqrt`, comparisons); see `distributed_game::prediction` for - * the float rules (no platform transcendentals). + * The code only uses operations that are correctly rounded on every target + * (`+ - * /`, `sqrt`, `floor`, comparisons); see + * `distributed_game::prediction` for the float rules (no platform + * transcendentals). */ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; @@ -25,14 +28,14 @@ import { Predictor, decodePayload, decodePredictState, + decodeValue, encodePayload, encodePredictState, + encodeValue, fromHex, toHex } from '@hops-ops/distributed/game'; -import * as floor from '../src/arena/floor.ts'; - const GENERATED = new URL('../src/generated/', import.meta.url); const SERVER_DIR = fileURLToPath(new URL('../../server/', import.meta.url)); @@ -108,15 +111,72 @@ for (const { name, predict } of surfaces) { }); } -test('drawing constants of the Arena floor match the simulation', () => { - assert.equal(floor.HALF, traces.arena.half); - assert.equal(floor.PLAYER_RADIUS, traces.arena.playerRadius); - assert.equal(floor.DASH_COOLDOWN, traces.arena.dashCooldown); - assert.deepEqual(floor.PILLARS.map((p) => [...p]), traces.arena.pillars); +/** Every generated surface with pure functions. */ +const pureSurfaces = readdirSync(GENERATED) + .filter((name) => existsSync(new URL(`${name}/pures.ts`, GENERATED))) + .map((name) => ({ name, pures: JSON.parse(readFileSync(new URL(`${name}/surface.json`, GENERATED), 'utf8')).pures })); + +test('every pure function has a native trace and every trace a surface', () => { + assert.deepEqual(pureSurfaces.map((s) => s.name), ['grid']); + const declared = pureSurfaces.flatMap((s) => s.pures.map((p) => p.export)).sort(); + assert.deepEqual(traces.pures.map((p) => p.export).sort(), declared); +}); + +for (const { name, pures } of pureSurfaces) { + for (const pure of pures) { + test(`${name}: WASM ${pure.export} matches the native function bit for bit`, async () => { + const module = await PredictModule.load(new URL(`${name}/wasm/${name}.wasm`, GENERATED)); + assert.ok(module.pures.includes(pure.export)); + const trace = traces.pures.find((p) => p.export === pure.export); + for (const [i, call] of trace.calls.entries()) { + assert.equal(toHex(module.call(pure.export, fromHex(call.arg))), call.output, `call ${i}`); + } + assert.ok(trace.calls.length >= 60, `${trace.calls.length} calls compared`); + }); + } +} + +test('grid: the generated wrappers decode what the native generation encodes', async () => { + const generated = await import('../src/generated/grid/index.ts'); + const pures = generated.createGridPures(); + await pures.ready; + const types = { + grid_cell: pureType(generated, 'grid_cell'), + grid_sample: pureType(generated, 'grid_sample') + }; + for (const pure of traces.pures) { + const { arg, output } = types[pure.export]; + const wrapper = pure.export === 'grid_cell' ? pures.gridCell : pures.gridSample; + for (const call of pure.calls.slice(0, 12)) { + const value = wrapper(decodeValue(arg, fromHex(call.arg))); + assert.equal(toHex(encodeValue(output, value)), call.output); + } + } + // Lattice and props as the page draws them. + const cell = pures.gridCell({ seed: generated.GRID_WORLD.defaultSeed, cx: 0, cy: 0 }); + assert.equal(cell.heights.length, generated.GRID_WORLD.samples ** 2); + assert.ok(cell.props.every((p) => p.kind < generated.GRID_WORLD.propKinds.length)); + assert.ok([...cell.biomes].every((b) => b < generated.GRID_WORLD.biomes.length)); }); +/** Argument / output wire types of a pure function, from its surface (records resolved, camelCase fields). */ +function pureType(generated, exportName) { + const surface = JSON.parse(readFileSync(new URL('grid/surface.json', GENERATED), 'utf8')); + const camel = (n) => n.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()); + const resolve = (type) => { + if (type.type === 'record') { + const record = surface.records.find((r) => r.name === type.name); + return { type: 'record', fields: record.fields.map((f) => [camel(f.name), resolve(f.type)]) }; + } + return type.item === undefined ? type : { ...type, item: resolve(type.item) }; + }; + const pure = surface.pures.find((p) => p.export === exportName); + return { arg: resolve(pure.arg), output: resolve(pure.output) }; +} + /** Median of `runs` timings of `fn` (each `iterations` calls), µs per call. */ function measure(fn, iterations, runs = 7) { + for (let i = 0; i < iterations; i += 1) fn(i); // warm up (JIT tiers, wasm tier-up) const samples = []; for (let r = 0; r < runs; r += 1) { const start = process.hrtime.bigint(); @@ -127,6 +187,26 @@ function measure(fn, iterations, runs = 7) { return samples[Math.floor(runs / 2)]; } +test('cost: generating a grid cell and sampling a point in WASM', async () => { + const generated = await import('../src/generated/grid/index.ts'); + const pures = generated.createGridPures(); + await pures.ready; + const seed = generated.GRID_WORLD.defaultSeed; + // A different cell every call (no cache inside or outside the module). + const cellUs = measure((i) => pures.gridCell({ seed, cx: (i % 97) - 48, cy: Math.floor(i / 97) - 20 }), 400); + // Without decoding the result into JS objects (generation + ABI copy). + const argType = pureType(generated, 'grid_cell').arg; + const abiUs = measure((i) => pures.module().call('grid_cell', encodeValue(argType, { seed, cx: (i % 89) - 44, cy: -7 })), 400); + const sampleUs = measure((i) => pures.gridSample({ seed, cx: 3, cy: -2, x: (i % 320) / 10, y: 7.25 }), 20_000); + // The page builds a ring of up to 5 new cells per border crossing; it must + // fit in a frame with room to spare. + console.log( + `grid generation cost (Node ${process.version}, µs, median): ${JSON.stringify({ cellUs, cellAbiOnlyUs: abiUs, sampleUs })}` + ); + assert.ok(cellUs < 2000, `grid_cell took ${cellUs} µs`); + assert.ok(sampleUs < 100, `grid_sample took ${sampleUs} µs`); +}); + test('cost: one predicted step and a reconciliation replaying 10 inputs at 30 Hz', async () => { const report = {}; for (const name of ['arena', 'grid']) { diff --git a/examples/game/fixtures/grid-world.json b/examples/game/fixtures/grid-world.json deleted file mode 100644 index 3de650df8..000000000 --- a/examples/game/fixtures/grid-world.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "description": "Endless Grid world-content parity: Rust game_sim::grid vs client/src/grid/world.ts", - "constants": {"cell":32.0,"contentVersion":1,"hashes":[0,1753845952,3861431939,1734902346],"mix":[81375972,3890567552],"propMargin":2.0,"seed":12648430}, - "cells": [ - {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[0,0],"heights":[0.5932726860046387,0.6191548109054565,0.6287701725959778,0.5684976577758789,0.506608247756958,0.476431667804718,0.4526447653770447,0.40599799156188965,0.3470003008842468,0.5986464619636536,0.6271780133247375,0.6407992243766785,0.5713481307029724,0.499041885137558,0.48792269825935364,0.4807089567184448,0.43712469935417175,0.38371312618255615,0.6058180928230286,0.6377806663513184,0.6576048135757446,0.583746075630188,0.504568338394165,0.50711590051651,0.5085848569869995,0.4628223776817322,0.41231948137283325,0.612625241279602,0.6260185837745667,0.6300536394119263,0.5916079878807068,0.5455343723297119,0.5089141130447388,0.46644169092178345,0.44517818093299866,0.42410480976104736,0.6159852743148804,0.6130355596542358,0.6021124720573425,0.5914559960365295,0.5723928809165955,0.5054858326911926,0.43087658286094666,0.43410351872444153,0.4395725727081299,0.6654882431030273,0.6511151790618896,0.6289829611778259,0.6039171814918518,0.5709450244903564,0.5380295515060425,0.5008229613304138,0.4601622223854065,0.4185706079006195,0.7117636203765869,0.6877931356430054,0.6561192870140076,0.6189549565315247,0.5746230483055115,0.5735785961151123,0.5749499797821045,0.5053251385688782,0.4283277094364166,0.6724258065223694,0.6588683128356934,0.6377082467079163,0.6132182478904724,0.5823083519935608,0.5772964954376221,0.5812021493911743,0.5429924130439758,0.4911908209323883,0.6354392170906067,0.6307666897773743,0.6188353896141052,0.6054155230522156,0.5861055254936218,0.5758660435676575,0.5773574709892273,0.5610383749008179,0.5286053419113159],"moisture":[0.9225814342498779,0.9209369421005249,0.9161432385444641,0.9084103107452393,0.897948145866394,0.8849667310714722,0.8696759343147278,0.8522856831550598,0.833005964756012,0.9203137755393982,0.9186764359474182,0.9139037132263184,0.9062045812606812,0.8957881927490234,0.882863461971283,0.8676395416259766,0.8503252863883972,0.8311298489570618,0.9141969680786133,0.9125790596008301,0.9078628420829773,0.9002548456192017,0.889961838722229,0.8771901726722717,0.8621464371681213,0.8450372815132141,0.8260691165924072,0.9044886827468872,0.9029015302658081,0.8982750177383423,0.8908117413520813,0.880714476108551,0.8681857585906982,0.8534281849861145,0.8366444110870361,0.8180370330810547,0.8914466500282288,0.889900803565979,0.885394811630249,0.8781259655952454,0.8682916760444641,0.8560892343521118,0.8417160511016846,0.8253694176673889,0.8072466850280762,0.8753284811973572,0.8738337755203247,0.8694766759872437,0.8624480366706848,0.8529387712478638,0.8411396741867065,0.8272415399551392,0.8114351630210876,0.7939113974571228,0.8563919067382812,0.8549572229385376,0.8507750630378723,0.8440287113189697,0.8349013328552246,0.8235759735107422,0.8102359771728516,0.7950643301010132,0.7782442569732666,0.834894597530365,0.8335280418395996,0.8295445442199707,0.8231185674667358,0.8144246935844421,0.8036372661590576,0.7909308075904846,0.7764797210693359,0.7604585289955139,0.8110942840576172,0.8098031282424927,0.8060395121574402,0.7999683022499084,0.7917543649673462,0.7815624475479126,0.7695574164390564,0.7559041380882263,0.7407673597335815],"props":[[0,2.6997311115264893,3.5492422580718994,0.5242127180099487,true,19],[0,20.319786071777344,2.439387321472168,0.6280530691146851,true,104],[0,29.571075439453125,4.204550266265869,0.5941054821014404,true,77],[0,28.727685928344727,12.843689918518066,0.5227029919624329,true,18],[2,2.6637513637542725,20.259355545043945,0.5979864001274109,false,100],[0,10.334222793579102,21.184724807739258,0.7090258598327637,true,171],[0,21.481861114501953,20.544662475585938,0.6859129667282104,true,152],[2,27.356979370117188,19.172718048095703,0.7472004294395447,false,253],[0,4.534152030944824,26.57033920288086,0.6718509793281555,true,140],[0,10.943948745727539,27.216060638427734,0.6537189483642578,true,125],[0,21.012920379638672,26.721946716308594,0.7434372901916504,true,199]]}, - {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,2,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,2,2],"cell":[-1,0],"heights":[0.4879056513309479,0.5361763834953308,0.5719524621963501,0.5911566615104675,0.617572546005249,0.6191596984863281,0.6134335398674011,0.607620894908905,0.5932726860046387,0.4937855303287506,0.5281368494033813,0.5436740517616272,0.5619687438011169,0.5938694477081299,0.6191307902336121,0.6376091241836548,0.6225482821464539,0.5986464619636536,0.5442072153091431,0.559651255607605,0.5435690879821777,0.5464216470718384,0.5757881999015808,0.6204748153686523,0.659502387046814,0.6373487114906311,0.6058180928230286,0.6223092079162598,0.6223706603050232,0.578648030757904,0.555199384689331,0.5708223581314087,0.6146619319915771,0.6540663242340088,0.6381969451904297,0.612625241279602,0.6648482084274292,0.6553021669387817,0.5970399975776672,0.5603602528572083,0.5680696964263916,0.6101231575012207,0.6485512256622314,0.6369460225105286,0.6159852743148804,0.6821573376655579,0.6640446186065674,0.6098151803016663,0.6010086536407471,0.6244459748268127,0.6555972099304199,0.6784183979034424,0.6735973358154297,0.6654882431030273,0.6619725227355957,0.6480416059494019,0.6232592463493347,0.6636747717857361,0.7115744948387146,0.7276552319526672,0.7254219651222229,0.7144866585731506,0.7117636203765869,0.6366078853607178,0.6480674147605896,0.6731057167053223,0.7349919676780701,0.7804715633392334,0.7645105123519897,0.720649778842926,0.6868299841880798,0.6724258065223694,0.6471416354179382,0.6704965233802795,0.7175806760787964,0.7777050733566284,0.8118277192115784,0.7723835110664368,0.701501190662384,0.6561596989631653,0.6354392170906067],"moisture":[0.8806808590888977,0.8896992802619934,0.8978338837623596,0.9049864411354065,0.9110587239265442,0.9159526228904724,0.9195698499679565,0.921812117099762,0.9225814342498779,0.8787924647331238,0.887729287147522,0.8957902789115906,0.9028780460357666,0.9088953733444214,0.9137449860572815,0.9173294305801392,0.919551432132721,0.9203137755393982,0.8736987709999084,0.8824153542518616,0.8902777433395386,0.8971908688545227,0.9030599594116211,0.9077900052070618,0.9112861752510071,0.9134534597396851,0.9141969680786133,0.8656143546104431,0.8739814162254333,0.8815285563468933,0.8881644606590271,0.8937982320785522,0.8983386158943176,0.9016945958137512,0.9037749767303467,0.9044886827468872,0.8547537326812744,0.8626512885093689,0.8697749376296997,0.8760384917259216,0.8813560605049133,0.8856416940689087,0.888809323310852,0.8907729983329773,0.8914466500282288,0.8413316011428833,0.8486488461494446,0.8552490472793579,0.861052393913269,0.8659793138504028,0.8699500560760498,0.87288498878479,0.8747043013572693,0.8753284811973572,0.8255624175071716,0.8321979641914368,0.8381832242012024,0.843445897102356,0.8479138016700745,0.8515145778656006,0.8541760444641113,0.8558259010314941,0.8563919067382812,0.8076608180999756,0.813522458076477,0.8188096284866333,0.8234584927558899,0.8274052739143372,0.8305861353874207,0.8329371809959412,0.8343945741653442,0.834894597530365,0.7878413796424866,0.7928462028503418,0.7973605394363403,0.8013298511505127,0.8046996593475342,0.8074155449867249,0.8094229698181152,0.8106673359870911,0.8110942840576172],"props":[[0,19.097110748291016,5.61630916595459,0.6776201128959656,true,145],[0,26.24727439880371,5.479523658752441,0.6100752949714661,true,90],[0,5.130196571350098,11.272446632385254,0.6444254517555237,true,118],[0,19.86644744873047,12.887415885925293,0.5775140523910522,true,63],[0,29.14185333251953,11.574310302734375,0.7816622257232666,true,230],[0,4.698641777038574,18.850263595581055,0.7559527158737183,true,209],[2,11.599629402160645,20.818233489990234,0.6331537365913391,false,136],[1,27.429126739501953,21.335290908813477,0.8450204133987427,true,150],[0,4.095309257507324,27.893505096435547,0.5584002733230591,true,47],[1,21.594541549682617,29.985082626342773,0.9263221025466919,true,205]]}, - {"biomes":[2,2,2,2,2,2,3,3,3,2,2,2,2,2,2,2,3,3,2,2,2,2,2,2,2,3,3,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[1,-1],"heights":[0.42138075828552246,0.40141475200653076,0.39124739170074463,0.41956472396850586,0.43916285037994385,0.432271271944046,0.4294608235359192,0.4508451819419861,0.47138655185699463,0.45944392681121826,0.4243382215499878,0.3924155831336975,0.38853707909584045,0.3834754526615143,0.36564576625823975,0.35151854157447815,0.37482354044914246,0.400425523519516,0.5155394673347473,0.4601888060569763,0.39446061849594116,0.348171204328537,0.31514886021614075,0.2859475314617157,0.25848180055618286,0.27967092394828796,0.3077928423881531,0.5293982625007629,0.47131720185279846,0.38974568247795105,0.3340299427509308,0.3055242598056793,0.25335049629211426,0.20097412168979645,0.20033006370067596,0.21104685962200165,0.5239297151565552,0.4678651988506317,0.3830241858959198,0.32936185598373413,0.30893680453300476,0.23856870830059052,0.16770951449871063,0.15107545256614685,0.14831487834453583,0.4844319522380829,0.4264620542526245,0.34375059604644775,0.2833406329154968,0.252756804227829,0.2121821790933609,0.17443953454494476,0.16420844197273254,0.1663990318775177,0.42037874460220337,0.3649688959121704,0.29274648427963257,0.23549142479896545,0.2006106972694397,0.18751025199890137,0.1829589456319809,0.18365724384784698,0.19249162077903748,0.3685966432094574,0.3160467743873596,0.25430747866630554,0.22343163192272186,0.20760875940322876,0.18155789375305176,0.16938230395317078,0.17390522360801697,0.1821434199810028,0.3470003008842468,0.2953859865665436,0.2377258837223053,0.22395597398281097,0.22219297289848328,0.18450671434402466,0.16285213828086853,0.16717854142189026,0.17335659265518188],"moisture":[0.7218424081802368,0.7066196203231812,0.6903294324874878,0.6731244325637817,0.6551569700241089,0.6365795135498047,0.6175447106361389,0.5982049107551575,0.5787125825881958,0.7459695339202881,0.7295016646385193,0.7118791341781616,0.6932669878005981,0.673829972743988,0.6537331342697144,0.6331414580345154,0.6122198700904846,0.5911333560943604,0.7677018642425537,0.7501124739646912,0.7312898635864258,0.7114101648330688,0.6906495094299316,0.6691840887069702,0.6471900939941406,0.6248437762260437,0.602321207523346,0.7867749929428101,0.7682013511657715,0.7483254671096802,0.7273334264755249,0.7054109573364258,0.6827444434165955,0.6595197916030884,0.6359229683876038,0.6121401786804199,0.802924633026123,0.7835177183151245,0.7627500295639038,0.7408159971237183,0.7179099321365356,0.6942263841629028,0.6699596047401428,0.6453040838241577,0.6204540729522705,0.8158867359161377,0.795810878276825,0.7743273973464966,0.75163733959198,0.7279418706893921,0.7034419775009155,0.6783388257026672,0.6528334617614746,0.6271270513534546,0.8253968954086304,0.8048302531242371,0.7828216552734375,0.7595769166946411,0.735302209854126,0.7102034091949463,0.6844866275787354,0.6583577394485474,0.6320229172706604,0.831190824508667,0.8103252649307251,0.7879966497421265,0.7644140720367432,0.7397863864898682,0.7143227458000183,0.6882320642471313,0.6617233753204346,0.6350056529045105,0.833005964756012,0.8120467066764832,0.7896178960800171,0.7659293413162231,0.7411910891532898,0.7156131267547607,0.6894053220748901,0.6627776026725769,0.6359399557113647],"props":[[2,2.6364169120788574,5.466867446899414,0.5331394672393799,false,33],[0,18.785797119140625,5.822574138641357,0.6876273155212402,true,153],[0,2.7611401081085205,10.10028076171875,0.5881384611129761,true,72],[2,11.367517471313477,13.671693801879883,0.5278894901275635,false,28],[0,18.445932388305664,13.27216911315918,0.6055808663368225,true,86],[0,11.479331016540527,20.873830795288086,0.617036759853363,true,95],[0,18.60265350341797,18.293407440185547,0.7304015159606934,true,188],[0,29.521440505981445,19.42812156677246,0.6016110777854919,true,83],[0,4.589646339416504,29.109691619873047,0.5978066921234131,true,80],[0,13.470664978027344,28.999820709228516,0.6673028469085693,true,137],[0,18.913860321044922,29.154817581176758,0.7499248385429382,true,204],[0,29.176136016845703,27.976917266845703,0.7947177886962891,true,241]]}, - {"biomes":[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],"cell":[3,-7],"heights":[0.44168463349342346,0.4462580978870392,0.4758754372596741,0.5119243860244751,0.5240926146507263,0.5060517191886902,0.47019070386886597,0.4644808769226074,0.48008018732070923,0.43155404925346375,0.47093355655670166,0.5339734554290771,0.5748621821403503,0.5923664569854736,0.5602777600288391,0.5095936059951782,0.48983877897262573,0.48950710892677307,0.42734962701797485,0.4953855872154236,0.5845286846160889,0.627734899520874,0.6492524147033691,0.6065821051597595,0.5449163913726807,0.5144485235214233,0.5012316703796387,0.4742732644081116,0.5199416875839233,0.5842570066452026,0.618760347366333,0.6332355737686157,0.6235742568969727,0.5945666432380676,0.557242214679718,0.5351199507713318,0.5101231336593628,0.5382350087165833,0.5838687419891357,0.6132137775421143,0.6229410171508789,0.6408824920654297,0.6388668417930603,0.5955400466918945,0.5658830404281616,0.49519073963165283,0.5091087818145752,0.5367494225502014,0.5691434144973755,0.5851179361343384,0.6196902394294739,0.6370555758476257,0.6121094822883606,0.5962793827056885,0.45497655868530273,0.4533257484436035,0.457935631275177,0.484584242105484,0.5018151998519897,0.5534920692443848,0.5944374203681946,0.5922531485557556,0.5913298726081848,0.36176007986068726,0.3889848589897156,0.4152972102165222,0.4129660129547119,0.40809959173202515,0.47236132621765137,0.532341718673706,0.5400242209434509,0.5416451692581177,0.30415835976600647,0.3565188944339752,0.40500175952911377,0.3831290006637573,0.3615923523902893,0.43301910161972046,0.5028873085975647,0.5131760239601135,0.5143986940383911],"moisture":[0.5350773930549622,0.5283440351486206,0.5222705602645874,0.5169302821159363,0.5123965740203857,0.5087426900863647,0.5060420036315918,0.5043678283691406,0.503793478012085,0.5299458503723145,0.5241599678993225,0.5189410448074341,0.5143522024154663,0.510456383228302,0.5073166489601135,0.5049960017204285,0.5035573840141296,0.5030638575553894,0.5244593024253845,0.5196864604949951,0.5153812170028687,0.5115957856178284,0.5083820819854736,0.5057920217514038,0.5038776993751526,0.5026909112930298,0.5022838115692139,0.518669068813324,0.5149652361869812,0.5116243362426758,0.5086867809295654,0.5061928629875183,0.5041829943656921,0.5026974081993103,0.5017764568328857,0.5014605522155762,0.5126261711120605,0.5100380778312683,0.5077035427093506,0.5056508779525757,0.5039082169532776,0.5025037527084351,0.5014656782150269,0.500822126865387,0.5006013512611389,0.5063818693161011,0.5049466490745544,0.503652036190033,0.5025137066841125,0.5015473365783691,0.5007684826850891,0.5001928210258484,0.4998359680175781,0.4997135400772095,0.49998724460601807,0.4997326731681824,0.4995030164718628,0.49930107593536377,0.49912965297698975,0.4989914894104004,0.49888938665390015,0.4988260567188263,0.49880436062812805,0.4934934973716736,0.4944378733634949,0.49528968334198,0.49603864550590515,0.49667447805404663,0.49718692898750305,0.49756571650505066,0.4978005290031433,0.49788105487823486,0.4869517982006073,0.4891039729118347,0.491045206785202,0.4927521049976349,0.4942012131214142,0.4953690767288208,0.4962323009967804,0.49676740169525146,0.4969509541988373],"props":[[0,26.579748153686523,4.767230987548828,0.7743046283721924,true,224],[2,3.260620594024658,10.087486267089844,0.6818166971206665,false,186],[1,28.662282943725586,11.022789001464844,0.74249666929245,true,80],[0,26.725576400756836,18.9808406829834,0.5057967305183411,true,4]]}, - {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3],"cell":[-12,5],"heights":[0.5121973752975464,0.4823082387447357,0.46220675110816956,0.5112564563751221,0.5501552820205688,0.4872822165489197,0.38883817195892334,0.31799912452697754,0.28261008858680725,0.4805338978767395,0.44521087408065796,0.4195011556148529,0.47392895817756653,0.5189605951309204,0.4671037197113037,0.39131978154182434,0.3571542799472809,0.3469882309436798,0.41997605562210083,0.37975943088531494,0.3484508991241455,0.4063468873500824,0.45611312985420227,0.42487290501594543,0.3929973244667053,0.4145159125328064,0.43692919611930847,0.3330213129520416,0.31364208459854126,0.3024783134460449,0.3571169674396515,0.40484189987182617,0.38624680042266846,0.38952183723449707,0.4628981053829193,0.5148381590843201,0.2848259508609772,0.2832028865814209,0.2896556258201599,0.3422389626502991,0.38851577043533325,0.3728458285331726,0.388386994600296,0.4877353012561798,0.5564621090888977,0.2816266715526581,0.2867536246776581,0.2998877167701721,0.3233092427253723,0.34088629484176636,0.35961490869522095,0.4112788140773773,0.5053136944770813,0.5671341419219971,0.2767845094203949,0.28718429803848267,0.3051665127277374,0.303689569234848,0.29709380865097046,0.34592780470848083,0.4310455322265625,0.5240169763565063,0.5815257430076599,0.3178563117980957,0.3185093402862549,0.32627564668655396,0.3392178416252136,0.3477005958557129,0.3815544545650482,0.45490309596061707,0.5379451513290405,0.582377016544342,0.35266175866127014,0.3454577326774597,0.34513136744499207,0.3703245520591736,0.3913551867008209,0.41152533888816833,0.47250428795814514,0.5445654988288879,0.576723039150238],"moisture":[0.8263142704963684,0.825194776058197,0.8219315409660339,0.8166675567626953,0.809545636177063,0.8007087707519531,0.7902998328208923,0.778461754322052,0.7653374671936035,0.8096745014190674,0.8085733652114868,0.805363655090332,0.8001859188079834,0.7931808233261108,0.7844889163970947,0.7742506861686707,0.7626067399978638,0.7496976852416992,0.7918837666511536,0.7908022403717041,0.7876497507095337,0.7825644016265869,0.7756841778755188,0.7671471834182739,0.7570914626121521,0.7456550598144531,0.7329761981964111,0.7731080055236816,0.772047221660614,0.7689551115036011,0.7639671564102173,0.7572187185287476,0.7488452792167664,0.7389822006225586,0.7277648448944092,0.7153288125991821,0.7535130977630615,0.7524739503860474,0.749444842338562,0.744558572769165,0.7379477024078369,0.7297449111938477,0.7200828194618225,0.7090941667556763,0.6969115734100342,0.7332649827003479,0.7322481870651245,0.7292842268943787,0.7245029807090759,0.7180342078208923,0.7100077867507935,0.7005534172058105,0.6898009777069092,0.6778803467750549,0.7125295400619507,0.7115355730056763,0.7086383104324341,0.7039646506309509,0.6976414918899536,0.6897956132888794,0.6805540323257446,0.6700435280799866,0.6583910584449768,0.6914726495742798,0.6905019283294678,0.6876724362373352,0.6831079721450806,0.6769325733184814,0.6692701578140259,0.6602445840835571,0.6499797701835632,0.638599693775177,0.6702602505683899,0.6693129539489746,0.6665516495704651,0.6620972752571106,0.6560707688331604,0.6485930681228638,0.63978511095047,0.6297678351402283,0.6186621189117432],"props":[[0,2.650817632675171,4.8241119384765625,0.6354243159294128,true,110],[2,11.57477855682373,4.872535705566406,0.7331044673919678,false,238],[0,28.03809928894043,4.916660308837891,0.578079342842102,true,63],[2,4.669862270355225,11.890331268310547,0.5852758288383484,false,87],[0,10.483098983764648,11.758493423461914,0.564202606678009,true,52],[0,19.052648544311523,11.650245666503906,0.6284025311470032,true,105],[0,28.663318634033203,11.259580612182617,0.7930710315704346,true,240],[0,5.82761287689209,19.1566104888916,0.5523130893707275,true,42],[0,10.243107795715332,19.25455093383789,0.6117123365402222,true,91],[0,2.6146390438079834,29.77297592163086,0.5455815196037292,true,37],[0,12.799676895141602,28.633228302001953,0.6608912348747253,true,131],[0,19.269079208374023,28.336078643798828,0.5150197744369507,true,12]]}, - {"biomes":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],"cell":[999999,-1000000],"heights":[0.5270935297012329,0.5743997693061829,0.5953944325447083,0.5239696502685547,0.4753807783126831,0.5279929041862488,0.5514862537384033,0.5003933310508728,0.4679919481277466,0.5375649333000183,0.572934091091156,0.5820469260215759,0.5309256315231323,0.5026796460151672,0.5419862866401672,0.5614850521087646,0.513027548789978,0.474234402179718,0.5374559164047241,0.5614643096923828,0.5593416094779968,0.5240475535392761,0.5117505788803101,0.5481477379798889,0.5835541486740112,0.5567929744720459,0.5216204524040222,0.5208446979522705,0.5216416120529175,0.49646323919296265,0.46929264068603516,0.4653409719467163,0.5247509479522705,0.6015294790267944,0.6190511584281921,0.6109352111816406,0.5109962224960327,0.49113374948501587,0.44546449184417725,0.42380237579345703,0.42567700147628784,0.49693557620048523,0.5935209393501282,0.6337533593177795,0.6418488621711731,0.4949389100074768,0.4840001165866852,0.45257842540740967,0.4334706664085388,0.4331486225128174,0.4797436594963074,0.5479856133460999,0.6027395725250244,0.6307550072669983,0.4766243100166321,0.47689566016197205,0.4672740697860718,0.46044427156448364,0.46244776248931885,0.48313599824905396,0.5174170732498169,0.5744072794914246,0.6146253943443298,0.4837564527988434,0.4784761071205139,0.4735533893108368,0.498298704624176,0.5223067998886108,0.5017102360725403,0.4870026409626007,0.5422952175140381,0.5905597805976868,0.49135950207710266,0.4768757224082947,0.4670783579349518,0.5093743205070496,0.5473048686981201,0.4947369694709778,0.44537153840065,0.5052690505981445,0.5629271864891052],"moisture":[0.8571391701698303,0.8770757913589478,0.8950584530830383,0.9108702540397644,0.9242939352989197,0.9351125359535217,0.943108856678009,0.9480658769607544,0.9497664570808411,0.8566534519195557,0.8765634298324585,0.8945221900939941,0.9103129506111145,0.9237187504768372,0.9345229268074036,0.9425086379051208,0.9474590420722961,0.9491572976112366,0.8553431630134583,0.8751815557479858,0.893075704574585,0.9088096022605896,0.922167181968689,0.9329325556755066,0.9408894777297974,0.9458220601081848,0.9475142955780029,0.8532635569572449,0.8729882836341858,0.8907799124717712,0.9064236283302307,0.9197046756744385,0.9304082989692688,0.9383196830749512,0.9432240128517151,0.9449065327644348,0.8504698276519775,0.8700418472290039,0.8876957297325134,0.9032183289527893,0.9163965582847595,0.927017331123352,0.9348674416542053,0.9397338032722473,0.9414032697677612,0.847017228603363,0.8664004802703857,0.883884072303772,0.8992570638656616,0.9123081564903259,0.9228265285491943,0.9306009411811829,0.9354203343391418,0.9370737075805664,0.8429608345031738,0.8621223568916321,0.8794059753417969,0.8946030735969543,0.9075048565864563,0.9179028868675232,0.9255883693695068,0.9303526878356934,0.9319871068000793,0.8383559584617615,0.8572657108306885,0.8743222951889038,0.8893197178840637,0.9020520448684692,0.9123134613037109,0.9198979735374451,0.9245997071266174,0.9262126684188843,0.8332576751708984,0.8518888354301453,0.868694007396698,0.8834704160690308,0.8960150480270386,0.9061252474784851,0.9135980010032654,0.918230414390564,0.9198196530342102],"props":[[0,3.1682724952697754,2.740854263305664,0.7206481695175171,true,180],[0,10.771486282348633,2.1860263347625732,0.5887128710746765,true,72],[0,21.956050872802734,3.2204477787017822,0.779129147529602,true,228],[0,13.399469375610352,10.174410820007324,0.5151387453079224,true,12],[0,21.344093322753906,10.719156265258789,0.5965613126754761,true,79],[0,29.304264068603516,11.698976516723633,0.7484042644500732,true,203],[0,2.3951516151428223,26.584388732910156,0.7904362678527832,true,237],[0,18.772125244140625,28.845848083496094,0.5168313980102539,true,13],[0,27.48282241821289,26.896862030029297,0.5896564722061157,true,73]]} - ] -} diff --git a/examples/game/run.sh b/examples/game/run.sh index 98fc4baa5..537662b34 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -9,9 +9,10 @@ # ./run.sh gen regenerate client/src/generated// from the # Rust surfaces (`distributed game-manifest` + # `distributed game-client`) and compile each -# `#[predict]` step to /wasm/.wasm +# surface's `#[predict]` step and `#[game_pure]` +# functions to /wasm/.wasm # (`distributed game-wasm`, gitignored, stamped so -# an unchanged step is not rebuilt); `gen --check` +# an unchanged module is not rebuilt); `gen --check` # verifies the TypeScript (and still builds WASM) # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS, # generated clients checked) @@ -74,8 +75,9 @@ ensure_cli() { # gen [--check]: GameSurface JSON from each Rust surface export → typed # TypeScript in client/src/generated// (surface.json included, so a # changed Rust definition shows up as drift), then the surface's predicted -# step → /wasm/.wasm. `--check` only applies to the -# checked-in TypeScript; the WASM is a build output and is (re)built. +# step and pure functions → /wasm/.wasm. `--check` only +# applies to the checked-in TypeScript; the WASM is a build output and is +# (re)built. gen() { local check="${1:-}" ensure_cli @@ -94,18 +96,19 @@ gen() { } # wasm_for : compile the surface's `#[predict]` step -# (if it declares one) next to its generated client. +# and `#[game_pure]` functions (if it declares any) next to its generated +# client. wasm_for() { - grep -q '"predict"' "$1" || return 0 + grep -q -e '"predict"' -e '"pures"' "$1" || return 0 "$CLI" game-wasm --manifest "$1" --manifest-path "$SERVER/Cargo.toml" \ --out "$CLIENT/src/generated/$2" >/dev/null } -# ensure_wasm: build every predicted step the pages load (no TypeScript -# generation; the stamps make this quick when nothing changed). +# ensure_wasm: build every module the pages load (no TypeScript generation; +# the stamps make this quick when nothing changed). ensure_wasm() { ensure_cli - log "compiling predicted steps to WebAssembly" + log "compiling predicted steps and pure functions to WebAssembly" local tmp status=0 tmp="$(mktemp -d "${TMPDIR:-/tmp}/game-surfaces.XXXXXX")" for surface in "${SURFACES[@]}"; do @@ -198,14 +201,14 @@ run_cluster() { smoke() { ensure_sdk ensure_client - log "generated clients are current; predicted steps compiled to WASM" + log "generated clients are current; predicted steps and pure functions compiled to WASM" gen --check - log "server: fmt, clippy, tests (bots smoke + grid world fixture)" + log "server: fmt, clippy, tests (bots smoke)" cargo fmt --manifest-path "$SERVER/Cargo.toml" --check -p game_demos -p game_sim cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --workspace --all-targets -- -D warnings cargo test --quiet --manifest-path "$SERVER/Cargo.toml" --workspace cargo build --quiet --manifest-path "$SERVER/Cargo.toml" - log "client: type-check, build, tests (WASM prediction exact match + headless SDK)" + log "client: type-check, build, tests (WASM steps + pure functions exact match, headless SDK)" (cd "$CLIENT" && npm run --silent check && npx vite build --logLevel warn && GAME_DEMOS_BIN="$BIN" npm test --silent) log "smoke OK" } diff --git a/examples/game/server/sim/src/arena.rs b/examples/game/server/sim/src/arena.rs index 8771d7cc0..5c11dd20f 100644 --- a/examples/game/server/sim/src/arena.rs +++ b/examples/game/server/sim/src/arena.rs @@ -51,6 +51,44 @@ pub const PILLARS: [(f32, f32, f32); 9] = [ (14.0, 0.0, 1.0), ]; +/// A pillar of the floor. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct Pillar { + /// Center x (m). + pub x: f32, + /// Center y (m). + pub y: f32, + /// Radius (m). + pub r: f32, +} + +/// What the pages draw of the Arena floor (generated `ARENA_FLOOR`, shared by +/// every page with an Arena capsule): the simulation's own constants. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct ArenaFloor { + /// Floor half extent (m). + pub half: f32, + /// Capsule radius (m). + pub player_radius: f32, + /// Dash cooldown in command frames (the HUD meter). + pub dash_cooldown: u8, + /// The pillars. + pub pillars: Vec, +} + +/// The `ARENA_FLOOR` constant. +pub fn arena_floor() -> ArenaFloor { + ArenaFloor { + half: HALF, + player_radius: PLAYER_RADIUS, + dash_cooldown: DASH_COOLDOWN, + pillars: PILLARS + .iter() + .map(|&(x, y, r)| Pillar { x, y, r }) + .collect(), + } +} + /// Wire type of `x`/`y`: 20/2^17 m ≈ 0.15 mm steps, 0 exact. pub const POS: FieldType = FieldType::quant_centered(HALF, 18); /// Wire type of `vx`/`vy`: 1/128 m/s steps, 0 exact (a resting capsule diff --git a/examples/game/server/sim/src/grid.rs b/examples/game/server/sim/src/grid.rs index 156c58d3c..eeea74a72 100644 --- a/examples/game/server/sim/src/grid.rs +++ b/examples/game/server/sim/src/grid.rs @@ -3,19 +3,23 @@ //! The static content of a cell (terrain height, biome, props) is a pure //! function of `(world seed, cell x, cell y, CONTENT_VERSION)`; the server //! uses it for collision and the client for rendering, and **nothing -//! static is replicated**. The walker's movement step collides with the -//! cell's props; the browser predicts it with this code compiled to -//! WebAssembly ([`grid_step`], whose context names the seed and cell, so -//! the props are generated inside the module). +//! static is replicated**. The browser runs this very code compiled to +//! WebAssembly (`distributed game-wasm`), so there is no client twin: //! -//! The rendering side still has a TypeScript twin of the *generation* -//! (`examples/game/client/src/grid/world.ts`, checked bit-for-bit by -//! `fixtures/grid-world.json`) until world content is served from WASM as -//! well. Rules that keep everything bit-identical: integer hashing on `u32` -//! only; floats are binary32 using only `+ - * /`, `sqrt` and `floor`; -//! constants are dyadic where it matters. `tests/grid_fixture.rs` writes the -//! fixture; change both files together, then `UPDATE_GOLDEN=1 cargo test -//! --test grid_fixture`. +//! - [`grid_step`] (`#[predict]`) predicts the own walker; its context +//! names the seed and cell, so the props are generated inside the module; +//! - [`grid_cell`] (`#[game_pure]`) returns what the page draws for a cell: +//! the terrain lattice ([`SAMPLES`]² heights, moisture, biomes) and the +//! props; +//! - [`grid_sample`] (`#[game_pure]`) samples one point (entity heights, +//! the HUD's biome); +//! - [`grid_world`] is the generated `GRID_WORLD` constant (cell size, +//! biome and prop names, lattice spacing, default seed). +//! +//! `client/tests/prediction-wasm.test.mjs` requires the WASM results to +//! equal the native ones byte for byte. Rules that keep them identical: +//! integer hashing on `u32` only; floats are binary32 using only +//! `+ - * /`, `sqrt` and `floor` (see `distributed_game::prediction`). //! //! Layout: a cell is [`CELL`] m square with local coordinates `0..CELL` on //! both axes; cell `(cx, cy)` covers world `cx*CELL .. (cx+1)*CELL`. Each @@ -26,7 +30,9 @@ use std::cell::RefCell; -use distributed_game::{predict, FieldType, FieldValue, GameInput, GameRecord}; +use distributed_game::codec::{Wire, WireType}; +use distributed_game::protocol::{DecodeError, Reader, Writer}; +use distributed_game::{game_pure, predict, FieldType, FieldValue, GameInput, GameRecord}; /// Cell edge length (m). pub const CELL: f32 = 32.0; @@ -73,7 +79,7 @@ const SALT_HEIGHT: [u32; 3] = [1, 2, 3]; const SALT_MOISTURE: u32 = 7; const SALT_PROP: u32 = 100; -/// Prop kinds. +/// Prop kinds (on the wire: their `u8` index into [`PROP_KINDS`]). #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum PropKind { @@ -85,8 +91,28 @@ pub enum PropKind { Bush = 2, } +/// Names of the [`PropKind`]s, by index. +pub const PROP_KINDS: [&str; 3] = ["tree", "rock", "bush"]; + +impl Wire for PropKind { + fn wire_type() -> WireType { + WireType::U8 + } + fn encode(&self, w: &mut Writer) { + w.u8(*self as u8); + } + fn decode(r: &mut Reader<'_>) -> Result { + match r.u8()? { + 0 => Ok(Self::Tree), + 1 => Ok(Self::Rock), + 2 => Ok(Self::Bush), + _ => Err(DecodeError::Invalid("unknown prop kind")), + } + } +} + /// One static prop in cell-local coordinates. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] pub struct Prop { /// Kind. pub kind: PropKind, @@ -179,8 +205,11 @@ pub fn moisture(seed: u32, cell: (i32, i32), l: (f32, f32)) -> f32 { /// Biome index into [`BIOMES`]. pub fn biome(seed: u32, cell: (i32, i32), l: (f32, f32)) -> u8 { - let h = height(seed, cell, l); - let m = moisture(seed, cell, l); + biome_of(height(seed, cell, l), moisture(seed, cell, l)) +} + +/// Biome of a point with height `h` and moisture `m`. +pub fn biome_of(h: f32, m: f32) -> u8 { if h > 0.6875 { 0 } else if m < 0.375 { @@ -369,6 +398,128 @@ pub fn grid_step( }) } +/// Terrain lattice points per cell axis (every [`SAMPLE_SPACING`] m, +/// borders included). +pub const SAMPLES: usize = 17; +/// Distance between lattice points (m). +pub const SAMPLE_SPACING: f32 = 2.0; + +/// What the client draws for one cell ([`grid_cell`]). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct GridCellContent { + /// Terrain height in `[0, 1)` at lattice point `(i, j)` (local + /// `(i, j) * SAMPLE_SPACING`), row-major by `j` (index `j * SAMPLES + i`). + pub heights: Vec, + /// Moisture in `[0, 1)`, same lattice. + pub moisture: Vec, + /// Biome index into [`BIOMES`], same lattice. + pub biomes: Vec, + /// The cell's props ([`cell_props`]). + pub props: Vec, +} + +/// A point of a cell ([`grid_sample`]). +#[derive(Debug, Clone, Copy, Default, PartialEq, GameRecord)] +pub struct GridPoint { + /// World seed. + pub seed: u32, + /// Cell x. + pub cx: i32, + /// Cell y. + pub cy: i32, + /// Local x (clamped to `0..=CELL`). + pub x: f32, + /// Local y (clamped to `0..=CELL`). + pub y: f32, +} + +/// Terrain at one point. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct GridSample { + /// Height in `[0, 1)`. + pub height: f32, + /// Moisture in `[0, 1)`. + pub moisture: f32, + /// Biome index into [`BIOMES`]. + pub biome: u8, +} + +/// Static facts of the world the client needs (generated `GRID_WORLD`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct GridWorld { + /// Cell edge length (m). + pub cell: f32, + /// Default world seed (before a zone's hello names it). + pub default_seed: u32, + /// Generation version. + pub content_version: u32, + /// Terrain lattice points per cell axis ([`SAMPLES`]). + pub samples: u8, + /// Lattice spacing (m). + pub sample_spacing: f32, + /// Walker radius (m). + pub player_radius: f32, + /// Largest |cell coordinate|. + pub max_cell: i32, + /// Biome names by index. + pub biomes: Vec, + /// Prop kind names by index. + pub prop_kinds: Vec, +} + +/// The `GRID_WORLD` constant. +pub fn grid_world() -> GridWorld { + GridWorld { + cell: CELL, + default_seed: DEFAULT_SEED, + content_version: CONTENT_VERSION, + samples: SAMPLES as u8, + sample_spacing: SAMPLE_SPACING, + player_radius: PLAYER_RADIUS, + max_cell: MAX_CELL, + biomes: BIOMES.map(String::from).to_vec(), + prop_kinds: PROP_KINDS.map(String::from).to_vec(), + } +} + +/// Terrain lattice and props of the context's cell (the page's chunk). +#[game_pure(GridCellFn)] +pub fn grid_cell(cell: &GridContext) -> GridCellContent { + let at = (cell.cx, cell.cy); + let n = SAMPLES * SAMPLES; + let mut content = GridCellContent { + heights: Vec::with_capacity(n), + moisture: Vec::with_capacity(n), + biomes: Vec::with_capacity(n), + props: cell_props(cell.seed, at), + }; + for j in 0..SAMPLES { + for i in 0..SAMPLES { + let l = (i as f32 * SAMPLE_SPACING, j as f32 * SAMPLE_SPACING); + let h = height(cell.seed, at, l); + let m = moisture(cell.seed, at, l); + content.heights.push(h); + content.moisture.push(m); + content.biomes.push(biome_of(h, m)); + } + } + content +} + +/// Terrain at one point of a cell (coordinates clamped into the cell). +#[game_pure(GridSampleFn)] +pub fn grid_sample(point: &GridPoint) -> GridSample { + let at = (point.cx, point.cy); + let l = (point.x.clamp(0.0, CELL), point.y.clamp(0.0, CELL)); + let height = height(point.seed, at, l); + let moisture = moisture(point.seed, at, l); + GridSample { + height, + moisture, + biome: biome_of(height, moisture), + } +} + /// Neighbour a walker at `(x, y)` belongs to, as a cell offset, or None /// while inside (with hysteresis). X first, then y. pub fn crossing(x: f32, y: f32) -> Option<(i32, i32)> { diff --git a/examples/game/server/sim/src/lib.rs b/examples/game/server/sim/src/lib.rs index 08516525b..0509a7746 100644 --- a/examples/game/server/sim/src/lib.rs +++ b/examples/game/server/sim/src/lib.rs @@ -1,6 +1,7 @@ //! The deterministic, client-predicted part of the `distributed_game` //! demos, shared by the server (`game_demos`, natively) and the browser -//! (compiled to WebAssembly by `distributed game-wasm`). +//! (compiled to WebAssembly by `distributed game-wasm`), and the pure +//! functions the browser shares with them. //! //! Each demo that predicts movement declares its step here with //! `#[predict]` and names it in its game surface @@ -13,6 +14,12 @@ //! | [`ripple::HoodStep`] | `player` | Boss Ripple (hoods) | //! | [`grid::GridStep`] | `walker` | Endless Grid (context: seed + cell) | //! +//! The Endless Grid's world generation is also compiled for the page: +//! [`grid::grid_cell`] and [`grid::grid_sample`] are `#[game_pure]` +//! functions (terrain lattice, biomes, props), so the browser renders the +//! server's own content. Static data the pages draw is exported as +//! surface constants ([`arena::arena_floor`], [`grid::grid_world`]). +//! //! Nothing here may depend on server-only crates (Tokio, axum, SQLite): //! the crate must compile for `wasm32-unknown-unknown`. diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index 7c051c676..3dcafd4bd 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -135,6 +135,7 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("arena") .events::() .predict::() + .constant("arena_floor", &movement::arena_floor()) } /// Interest radius (m). diff --git a/examples/game/server/src/freeze/content.rs b/examples/game/server/src/freeze/content.rs index 7002fc25a..4b41a266d 100644 --- a/examples/game/server/src/freeze/content.rs +++ b/examples/game/server/src/freeze/content.rs @@ -3,19 +3,25 @@ //! Version `v{n}` uses pack `(n - 1) % 3`, so the admin can keep rolling //! out "new" versions. The server derives its rules (hazard, slime speed, //! gem value) from the pack of the zone's content version; clients fetch -//! the same pack as JSON (`GET /dev/freeze/content/{version}`, the demo's -//! stand-in for a content CDN) and derive colors, props and labels from -//! it. A client pinned to an old version keeps rendering its old pack. +//! the same pack (`GET /dev/freeze/content/{version}`, the demo's stand-in +//! for a content CDN) and derive colors, props and labels from it. A client +//! pinned to an old version keeps rendering its old pack. //! -//! The zone layout (portals, pools, gem spots) is version independent and -//! shipped inside every pack so the client needs nothing else. +//! Everything here is defined once, in Rust. A [`Pack`] is a +//! `#[derive(GameRecord)]`: the CDN serves its payload-codec encoding and +//! the generated client decodes it (`decodePack`, from +//! `GameSurface::record::()`). The version-independent layout +//! (zones, portals, pools, crystal spots) is [`freeze_world`], the +//! generated `FREEZE_WORLD` constant (`GameSurface::constant`). Packs are +//! *served* rather than compiled into the client because the point of the +//! demo is a client receiving content it was not built with. -use serde::Serialize; -use serde_json::{json, Value}; +use distributed_game::codec::{Wire, WireType}; +use distributed_game::protocol::{DecodeError, Reader, Writer}; +use distributed_game::GameRecord; -/// What standing in a pool does. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] +/// What standing in a pool does (on the wire: `"lava"` / `"ice"`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Hazard { /// Burns: the player is sent back to a spawn point. Lava, @@ -23,9 +29,34 @@ pub enum Hazard { Ice, } -/// One content pack. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] +impl Hazard { + /// Wire name. + pub fn name(self) -> &'static str { + match self { + Self::Lava => "lava", + Self::Ice => "ice", + } + } +} + +impl Wire for Hazard { + fn wire_type() -> WireType { + WireType::ShortStr + } + fn encode(&self, w: &mut Writer) { + w.short_string(self.name()); + } + fn decode(r: &mut Reader<'_>) -> Result { + match r.short_string()?.as_str() { + "lava" => Ok(Self::Lava), + "ice" => Ok(Self::Ice), + _ => Err(DecodeError::Invalid("unknown hazard")), + } + } +} + +/// One content pack (served encoded; the client's `Pack` is generated). +#[derive(Debug, Clone, PartialEq, GameRecord)] pub struct Pack { /// `v{n}`. pub version: String, @@ -43,7 +74,7 @@ pub struct Pack { pub slime_scale: f32, /// Crystal prop color (hex). pub crystal_color: String, - /// Crystal props `(x, y)` per field zone (mirrored per pack). + /// Index into [`FreezeWorld::crystals`] (mirrored per pack). pub crystal_layout: u8, /// Value of a collected gem. pub gem_value: u32, @@ -142,11 +173,9 @@ impl Pack { out } - /// Pack plus the world layout, as served to clients. - pub fn to_json(&self) -> Value { - let mut v = serde_json::to_value(self).expect("pack serializes"); - v["zones"] = layout_json(); - v + /// What the content CDN serves: the payload-codec encoding. + pub fn to_bytes(&self) -> Vec { + distributed_game::codec::to_bytes(self) } } @@ -261,22 +290,108 @@ pub fn crystals(layout: u8) -> Vec<(f32, f32)> { .collect() } -fn layout_json() -> Value { - let zone = |kind: ZoneKind| { - json!({ - "title": kind.title(), - "gate": kind == ZoneKind::Hub, - "portals": kind.portals().iter().map(|(x, y, to)| json!({"x": x, "y": y, "to": to, "title": ZoneKind::of(to).map(ZoneKind::title)})).collect::>(), - "pools": kind.pools().iter().map(|(x, y, r)| json!({"x": x, "y": y, "r": r})).collect::>(), - "ritual": { "x": kind.ritual().0, "y": kind.ritual().1 }, - }) +/// A point of a zone (m). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct Spot { + /// x. + pub x: f32, + /// y. + pub y: f32, +} + +/// A portal to another zone. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Portal { + /// x. + pub x: f32, + /// y. + pub y: f32, + /// Target zone id. + pub to: String, + /// Target zone title. + pub title: String, +} + +/// A pool (lava or ice, by pack). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct Pool { + /// x. + pub x: f32, + /// y. + pub y: f32, + /// Radius. + pub r: f32, +} + +/// The layout of one zone. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct ZoneLayout { + /// Zone id. + pub id: String, + /// Display title. + pub title: String, + /// The safe-room gate (the hub). + pub gate: bool, + /// Portals. + pub portals: Vec, + /// Pools. + pub pools: Vec, + /// Where a ritual holds the zone. + pub ritual: Spot, +} + +/// The version-independent world (generated `FREEZE_WORLD`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct FreezeWorld { + /// Town hub. + pub hub: ZoneLayout, + /// Whisper Meadow. + pub meadow: ZoneLayout, + /// Ember Fields. + pub ember: ZoneLayout, + /// Crystal spots per layout id ([`Pack::crystal_layout`]). + pub crystals: Vec>, +} + +/// The `FREEZE_WORLD` constant. +pub fn freeze_world() -> FreezeWorld { + let zone = |kind: ZoneKind, id: &str| ZoneLayout { + id: id.into(), + title: kind.title().into(), + gate: kind == ZoneKind::Hub, + portals: kind + .portals() + .iter() + .map(|&(x, y, to)| Portal { + x, + y, + to: to.into(), + title: ZoneKind::of(to).map_or("", ZoneKind::title).into(), + }) + .collect(), + pools: kind + .pools() + .iter() + .map(|&(x, y, r)| Pool { x, y, r }) + .collect(), + ritual: Spot { + x: kind.ritual().0, + y: kind.ritual().1, + }, }; - json!({ - HUB: zone(ZoneKind::Hub), - MEADOW: zone(ZoneKind::Meadow), - EMBER: zone(ZoneKind::Ember), - "crystals": [crystals(0), crystals(1), crystals(2)], - }) + FreezeWorld { + hub: zone(ZoneKind::Hub, HUB), + meadow: zone(ZoneKind::Meadow, MEADOW), + ember: zone(ZoneKind::Ember, EMBER), + crystals: (0..PACKS as u8) + .map(|layout| { + crystals(layout) + .into_iter() + .map(|(x, y)| Spot { x, y }) + .collect() + }) + .collect(), + } } #[cfg(test)] @@ -292,9 +407,13 @@ mod tests { assert_eq!(pack("v2").unwrap().hazard, Hazard::Ice); assert_eq!(pack("v4").unwrap().name, pack("v1").unwrap().name); assert_eq!(pack("v4").unwrap().version, "v4"); - let json = pack("v2").unwrap().to_json(); - assert_eq!(json["hazard"], "ice"); - assert_eq!(json["zones"][EMBER]["portals"][0]["to"], HUB); + let served: Pack = + distributed_game::codec::from_bytes(&pack("v2").unwrap().to_bytes()).unwrap(); + assert_eq!(served, pack("v2").unwrap()); + let world = freeze_world(); + assert_eq!(world.ember.portals[0].to, HUB); + assert_eq!(world.ember.portals[0].title, ZoneKind::Hub.title()); + assert_eq!(world.crystals.len(), PACKS as usize); assert!(pack("v2") .unwrap() .resume_notes() diff --git a/examples/game/server/src/freeze/mod.rs b/examples/game/server/src/freeze/mod.rs index 09e36c3b1..10a477e1a 100644 --- a/examples/game/server/src/freeze/mod.rs +++ b/examples/game/server/src/freeze/mod.rs @@ -172,6 +172,8 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("freeze") .events::() .predict::() + .record::() + .constant("freeze_world", &content::freeze_world()) } /// Durable command recording a collected gem. diff --git a/examples/game/server/src/freeze/world.rs b/examples/game/server/src/freeze/world.rs index 5885c89e7..2a0376422 100644 --- a/examples/game/server/src/freeze/world.rs +++ b/examples/game/server/src/freeze/world.rs @@ -13,7 +13,7 @@ //! //! | Route | Effect | //! |---|---| -//! | `GET /dev/freeze/content/{version}` | content pack JSON (`current` = the world's version; future versions 404) | +//! | `GET /dev/freeze/content/{version}` | content pack, payload-codec encoded (`application/octet-stream`, decoded by the generated `decodePack`; `current` = the world's version; future versions 404 with JSON) | //! | `GET /dev/freeze/world` | status of every host's zones (freeze state, players, inputs dropped while frozen, recent facts) | //! | `POST /dev/freeze/rollout` `{mode: hard\|rolling}` | **admin** — primary only: `WorldCoordinator::rollout` to the next version | //! | `POST /dev/freeze/stuck` `{zone, stuck}` | **admin** — start/stop a zone's ritual (forwarded to the owning host) | @@ -270,7 +270,11 @@ fn routes(state: FreezeRoutes) -> Router { .with_state(state) } -async fn content_pack(State(state): State, Path(version): Path) -> Reply { +async fn content_pack( + State(state): State, + Path(version): Path, +) -> axum::response::Response { + use axum::response::IntoResponse; let current = state.server.content_version(); let wanted = if version == "current" { current.clone() @@ -281,11 +285,17 @@ async fn content_pack(State(state): State, Path(version): Path reply(StatusCode::OK, pack.to_json()), + Some(pack) => ( + StatusCode::OK, + [(axum::http::header::CONTENT_TYPE, "application/octet-stream")], + pack.to_bytes(), + ) + .into_response(), None => reply( StatusCode::NOT_FOUND, json!({ "error": format!("content {wanted} is not published (world runs {current})") }), - ), + ) + .into_response(), } } diff --git a/examples/game/server/src/gallery/mod.rs b/examples/game/server/src/gallery/mod.rs index 6217dd28d..005c6a90d 100644 --- a/examples/game/server/src/gallery/mod.rs +++ b/examples/game/server/src/gallery/mod.rs @@ -29,8 +29,8 @@ use std::time::Duration; use distributed_game::net::{GameServer, ServerConfig}; use distributed_game::rewind::{Historic, HitQuery, RewindFrame, ShotTiming, Vec3}; use distributed_game::{ - schema, ConsumePolicy, Ctx, EntitySchema, FieldType, GameEvent, GameInput, GameSurface, - LeaveReason, PlayerId, Replicated, View, WorldView, Zone, + schema, ConsumePolicy, Ctx, EntitySchema, FieldType, GameEvent, GameInput, GameRecord, + GameSurface, LeaveReason, PlayerId, Replicated, View, WorldView, Zone, }; use crate::common::{Demo, Guests}; @@ -134,7 +134,58 @@ pub enum GalleryEvent { /// The gallery's client surface. pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("gallery").events::() + GameSurface::for_zone::("gallery") + .events::() + .constant("gallery_course", &gallery_course()) +} + +/// A rail target's track. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct RailTrack { + /// y (m). + pub y: f32, + /// West end (m). + pub x0: f32, + /// East end (m). + pub x1: f32, +} + +/// A circling target's track. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct CircleTrack { + /// Center x (m). + pub cx: f32, + /// Center y (m). + pub cy: f32, + /// Radius (m). + pub r: f32, +} + +/// The course decor the page draws (generated `GALLERY_COURSE`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct GalleryCourse { + /// Rails, in course order. + pub rails: Vec, + /// Circles, in course order. + pub circles: Vec, + /// y of the firing line (m). + pub firing_line: f32, +} + +/// The `GALLERY_COURSE` constant (from [`COURSE`] and [`FIRING_LINE`]). +pub fn gallery_course() -> GalleryCourse { + let mut course = GalleryCourse { + rails: Vec::new(), + circles: Vec::new(), + firing_line: FIRING_LINE, + }; + for (path, _, _) in COURSE { + match path { + Path::Rail { y, x0, x1, .. } => course.rails.push(RailTrack { y, x0, x1 }), + Path::Circle { cx, cy, r, .. } => course.circles.push(CircleTrack { cx, cy, r }), + } + } + course } /// How a target moves. diff --git a/examples/game/server/src/grid/mod.rs b/examples/game/server/src/grid/mod.rs index 20202cb85..ae462487b 100644 --- a/examples/game/server/src/grid/mod.rs +++ b/examples/game/server/src/grid/mod.rs @@ -121,6 +121,9 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("grid") .events::() .predict::() + .pure::() + .pure::() + .constant("grid_world", &world::grid_world()) } /// Most markers a cell keeps (oldest dropped first). pub const MAX_MARKERS: usize = 12; diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index c843ab77e..cc0cc26b5 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -244,6 +244,7 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("mobpit") .events::() .predict::() + .constant("pit_rules", &pit_rules()) } pub use game_sim::mobpit::{pit_step, PitInput, PitStep}; @@ -282,6 +283,45 @@ fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { } } +/// Mob tiers (1..=3). +pub const TIERS: [u8; 3] = [1, 2, 3]; +/// Names of the `mob` kind's `state` values, by value. +pub const MOB_STATES: [&str; 6] = ["idle", "chase", "windup", "recover", "return", "dead"]; + +/// What the page draws of a mob tier (from [`tier_stats`]). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct MobTier { + /// Tier (the `mob` kind's `tier`). + pub tier: u8, + /// Body radius (m). + pub radius: f32, + /// Telegraph radius (m). + pub tele: f32, +} + +/// Mob Pit rules the client draws with (generated `PIT_RULES`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct PitRules { + /// Every tier. + pub tiers: Vec, + /// `state` names by value. + pub states: Vec, +} + +/// The `PIT_RULES` constant. +pub fn pit_rules() -> PitRules { + PitRules { + tiers: TIERS + .iter() + .map(|&tier| { + let (_, _, _, radius, tele) = tier_stats(tier); + MobTier { tier, radius, tele } + }) + .collect(), + states: MOB_STATES.map(String::from).to_vec(), + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum MobState { Idle = 0, diff --git a/examples/game/server/src/predict_trace.rs b/examples/game/server/src/predict_trace.rs index 46ab3cd00..f532af6fe 100644 --- a/examples/game/server/src/predict_trace.rs +++ b/examples/game/server/src/predict_trace.rs @@ -1,18 +1,25 @@ //! Native traces of every demo's client-predicted step over recorded input -//! streams: the reference side of the native ↔ WebAssembly exact-match -//! proof. `game-demos predict-trace` prints them as JSON; the client's -//! `tests/prediction-wasm.test.mjs` replays the same streams through each -//! surface's compiled module and requires every state to be byte-identical. +//! streams, and of every `#[game_pure]` function over recorded arguments: +//! the reference side of the native ↔ WebAssembly exact-match proof. +//! `game-demos predict-trace` prints them as JSON; the client's +//! `tests/prediction-wasm.test.mjs` replays the same streams and arguments +//! through each surface's compiled module and requires every state and +//! result to be byte-identical. //! -//! Every step runs through [`step_bytes`], the same decode → step → encode -//! path the WASM export takes, so the comparison covers the ABI as well as -//! the arithmetic. Inputs are raw payload bytes, deliberately including -//! values the decoder sanitizes (`-128` sticks, unknown button bits). +//! Every step runs through [`step_bytes`] and every function through +//! [`call_bytes`], the same decode → run → encode paths the WASM exports +//! take, so the comparison covers the ABI as well as the arithmetic. Inputs +//! are raw payload bytes, deliberately including values the decoder +//! sanitizes (`-128` sticks, unknown button bits). use distributed_game::prediction::{step_bytes, PredictContext, PredictStep}; +use distributed_game::pure::{call_bytes, GamePure}; use distributed_game::Wire; use game_sim::arena::{self, ArenaStep, MoveState}; -use game_sim::grid::{self, GridContext, GridStep, WalkerState, BUTTON_SPRINT, DEFAULT_SEED}; +use game_sim::grid::{ + self, GridCellFn, GridContext, GridPoint, GridSampleFn, GridStep, WalkerState, BUTTON_SPRINT, + CELL, DEFAULT_SEED, +}; use game_sim::mobpit::PitStep; use game_sim::ripple::HoodStep; use serde_json::{json, Value}; @@ -238,18 +245,90 @@ fn grid_streams() -> Vec { streams } -/// Every demo step's native trace (see the module docs), plus the Arena -/// drawing constants the client pages keep. +fn pure_trace(args: Vec>) -> Value { + let calls: Vec = args + .iter() + .map(|arg| { + let output = call_bytes::(arg).unwrap_or_else(|e| panic!("{}: {e:?}", F::EXPORT)); + json!({ "arg": hex(arg), "output": hex(&output) }) + }) + .collect(); + json!({ "export": F::EXPORT, "calls": calls }) +} + +/// Cells for the content traces: around the origin, far away, the +/// coordinate limits (lattice wrap-around) and the random walk's cells. +fn content_cells() -> Vec<(i32, i32)> { + let mut cells = vec![ + (0, 0), + (-1, 0), + (1, -1), + (3, -7), + (-12, 5), + (999_999, -1_000_000), + (-1_000_000, 1_000_000), + busy_cell(DEFAULT_SEED), + ]; + let mut rng = Rng(0x5eed_cafe); + for _ in 0..24 { + let c = |r: &mut Rng| (r.next() % 2001) as i32 - 1000; + cells.push((c(&mut rng), c(&mut rng))); + } + cells +} + +/// `grid_cell` for every content cell, under two seeds. +fn grid_cell_args() -> Vec> { + let mut args = Vec::new(); + for seed in [DEFAULT_SEED, 0xdead_beef] { + for (cx, cy) in content_cells() { + args.push(GridContext { seed, cx, cy }.encode_context()); + } + } + args +} + +/// `grid_sample` on lattice points, borders, arbitrary floats and points +/// outside the cell (clamped). +fn grid_sample_args() -> Vec> { + let mut rng = Rng(0x0dd_ba11); + let mut args = Vec::new(); + for (cx, cy) in content_cells() { + let mut points: Vec<(f32, f32)> = vec![ + (0.0, 0.0), + (CELL, CELL), + (CELL, 7.25), + (16.0, 0.0), + (-3.0, 40.0), + ]; + for _ in 0..40 { + let f = |r: &mut Rng| (r.next() >> 8) as f32 / 16_777_216.0 * (CELL + 4.0) - 2.0; + points.push((f(&mut rng), f(&mut rng))); + } + for (x, y) in points { + args.push( + GridPoint { + seed: DEFAULT_SEED, + cx, + cy, + x, + y, + } + .encode_context(), + ); + } + } + args +} + +/// Every demo step's and pure function's native trace (see the module docs). pub fn traces() -> Value { json!({ "abi": distributed_game::prediction::ABI_VERSION, - // Drawing constants the pages keep (`client/src/arena/floor.ts`). - "arena": { - "half": arena::HALF, - "playerRadius": arena::PLAYER_RADIUS, - "dashCooldown": arena::DASH_COOLDOWN, - "pillars": arena::PILLARS.iter().map(|(x, y, r)| json!([x, y, r])).collect::>(), - }, + "pures": [ + pure_trace::(grid_cell_args()), + pure_trace::(grid_sample_args()), + ], "steps": [ trace::(capsule_streams(0)), trace::(capsule_streams(0)), @@ -278,6 +357,33 @@ mod tests { } } + #[test] + fn grid_cell_is_the_world_generation() { + let cell = busy_cell(DEFAULT_SEED); + let content = grid::grid_cell(&grid_context(cell)); + assert_eq!(content.props, grid::cell_props(DEFAULT_SEED, cell)); + assert_eq!(content.heights.len(), grid::SAMPLES * grid::SAMPLES); + let (i, j) = (5, 11); + let l = ( + i as f32 * grid::SAMPLE_SPACING, + j as f32 * grid::SAMPLE_SPACING, + ); + let k = j * grid::SAMPLES + i; + assert_eq!(content.heights[k], grid::height(DEFAULT_SEED, cell, l)); + assert_eq!(content.biomes[k], grid::biome(DEFAULT_SEED, cell, l)); + let sample = grid::grid_sample(&GridPoint { + seed: DEFAULT_SEED, + cx: cell.0, + cy: cell.1, + x: l.0, + y: l.1, + }); + assert_eq!( + (sample.height, sample.moisture, sample.biome), + (content.heights[k], content.moisture[k], content.biomes[k]) + ); + } + #[test] fn traces_cover_every_step_and_collide() { let traces = traces(); diff --git a/examples/game/server/src/ripple/mod.rs b/examples/game/server/src/ripple/mod.rs index 310859e5a..7d1110762 100644 --- a/examples/game/server/src/ripple/mod.rs +++ b/examples/game/server/src/ripple/mod.rs @@ -213,6 +213,7 @@ pub fn game_surface() -> GameSurface { GameSurface::for_zone::("ripple") .events::() .predict::() + .constant("ripple_world", &ripple_world()) } /// Kind id of [`TierView`] (tests mirror fields by it). @@ -272,6 +273,44 @@ impl TierKind { } } +/// A borough and its neighborhoods. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct BoroughLayout { + /// Borough zone id. + pub id: String, + /// Neighborhood zone ids. + pub hoods: Vec, +} + +/// The zone hierarchy and weather names (generated `RIPPLE_WORLD`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct RippleWorld { + /// Root zone. + pub realm: String, + /// The city. + pub city: String, + /// Boroughs with their neighborhoods. + pub boroughs: Vec, + /// [`WEATHER`] names by index. + pub weather: Vec, +} + +/// The `RIPPLE_WORLD` constant. +pub fn ripple_world() -> RippleWorld { + RippleWorld { + realm: REALM.into(), + city: CITY.into(), + boroughs: BOROUGHS + .iter() + .map(|b| BoroughLayout { + id: b.to_string(), + hoods: hoods(b), + }) + .collect(), + weather: WEATHER.map(String::from).to_vec(), + } +} + /// Neighborhoods of a borough. pub fn hoods(borough: &str) -> Vec { (1..=HOODS_PER_BOROUGH) diff --git a/examples/game/server/tests/freeze_smoke.rs b/examples/game/server/tests/freeze_smoke.rs index 3039acd53..daf23e915 100644 --- a/examples/game/server/tests/freeze_smoke.rs +++ b/examples/game/server/tests/freeze_smoke.rs @@ -11,7 +11,7 @@ use distributed_game::net::TicketKey; use distributed_game::world::HostAddr; use distributed_game::FreezeState; use game_demos::arena; -use game_demos::freeze::content::{EMBER, HUB, MEADOW}; +use game_demos::freeze::content::{Hazard, Pack, EMBER, HUB, MEADOW}; use game_demos::freeze::world::{assignment, start_host, HostSpec, WorldHost}; use serde_json::{json, Value}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -52,13 +52,13 @@ async fn world() -> (WorldHost, WorldHost, Vec> } /// Minimal HTTP/1.1 client: `(status, JSON body or Null)`. -async fn http( +async fn request( addr: SocketAddr, method: &str, path: &str, body: Option, admin: bool, -) -> (u16, Value) { +) -> (u16, Vec) { let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); let body = body.map(|b| b.to_string()).unwrap_or_default(); let secret = if admin { @@ -71,14 +71,42 @@ async fn http( body.len() ); stream.write_all(request.as_bytes()).await.unwrap(); - let mut response = String::new(); - stream.read_to_string(&mut response).await.unwrap(); - let status = response[9..12].parse().unwrap(); - let json = response - .split_once("\r\n\r\n") - .and_then(|(_, b)| serde_json::from_str(b).ok()) - .unwrap_or(Value::Null); - (status, json) + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.unwrap(); + let status = std::str::from_utf8(&response[9..12]) + .unwrap() + .parse() + .unwrap(); + let body = response + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|at| response[at + 4..].to_vec()) + .unwrap_or_default(); + (status, body) +} + +async fn http( + addr: SocketAddr, + method: &str, + path: &str, + body: Option, + admin: bool, +) -> (u16, Value) { + let (status, body) = request(addr, method, path, body, admin).await; + (status, serde_json::from_slice(&body).unwrap_or(Value::Null)) +} + +/// The content CDN: a pack in its payload encoding (what `decodePack` reads). +async fn content(addr: SocketAddr, version: &str) -> (u16, Option) { + let (status, body) = request( + addr, + "GET", + &format!("/dev/freeze/content/{version}"), + None, + false, + ) + .await; + (status, distributed_game::codec::from_bytes(&body).ok()) } fn bots(url: String, zone: &str) -> BotConfig { @@ -115,10 +143,13 @@ async fn rollout_spans_both_hosts_drops_frozen_inputs_and_stamps_the_new_version ) .await; assert_eq!(status, 401); - let (status, _) = http(a.addr, "GET", "/dev/freeze/content/v2", None, false).await; + let (status, _) = content(a.addr, "v2").await; assert_eq!(status, 404); - let (status, pack) = http(a.addr, "GET", "/dev/freeze/content/current", None, false).await; - assert_eq!((status, pack["version"].as_str()), (200, Some("v1"))); + let (status, pack) = content(a.addr, "current").await; + assert_eq!( + (status, pack), + (200, game_demos::freeze::content::pack("v1")) + ); // Bots keep sending inputs through the freeze on both hosts. let addr = a.addr; @@ -176,8 +207,8 @@ async fn rollout_spans_both_hosts_drops_frozen_inputs_and_stamps_the_new_version && f.stamp().zone_id == zone && f.stamp().content_version == "v2")); } - let (_, pack) = http(a.addr, "GET", "/dev/freeze/content/current", None, false).await; - assert_eq!(pack["hazard"], "ice"); + let (_, pack) = content(a.addr, "current").await; + assert_eq!(pack.unwrap().hazard, Hazard::Ice); let (_, status) = http(a.addr, "GET", "/dev/freeze/world", None, false).await; assert_eq!(status["hosts"][1]["host"], "beta"); assert_eq!(status["hosts"][1]["zones"][0]["contentVersion"], "v2"); diff --git a/examples/game/server/tests/grid_fixture.rs b/examples/game/server/tests/grid_fixture.rs deleted file mode 100644 index dcce26ef8..000000000 --- a/examples/game/server/tests/grid_fixture.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Golden fixture for the Endless Grid's procedural world *content* -//! (terrain, biomes, props), which the client still renders from a -//! TypeScript twin. -//! -//! Writes/compares `examples/game/fixtures/grid-world.json`, which the -//! TypeScript client replays in `client/tests/grid-world-parity.test.mjs` -//! (bit-exact). Regenerate after an intended change to BOTH -//! `server/sim/src/grid.rs` and `client/src/grid/world.ts`: -//! `UPDATE_GOLDEN=1 cargo test --test grid_fixture`. Movement is not part -//! of it: the client predicts with the Rust step compiled to WebAssembly -//! (proved by `client/tests/prediction-wasm.test.mjs`). - -use std::path::PathBuf; - -use game_demos::grid::world::{self, DEFAULT_SEED}; -use serde_json::{json, Value}; - -const CELLS: [(i32, i32); 6] = [ - (0, 0), - (-1, 0), - (1, -1), - (3, -7), - (-12, 5), - (999_999, -1_000_000), -]; - -fn cell_json(seed: u32, cell: (i32, i32)) -> Value { - let props: Vec = world::cell_props(seed, cell) - .iter() - .map(|p| json!([p.kind as u8, p.x, p.y, p.r, p.solid, p.variant])) - .collect(); - let mut heights = Vec::new(); - let mut moisture = Vec::new(); - let mut biomes = Vec::new(); - for j in 0..=8 { - for i in 0..=8 { - let l = (i as f32 * 4.0, j as f32 * 4.0 + 0.25); - heights.push(json!(world::height(seed, cell, l))); - moisture.push(json!(world::moisture(seed, cell, l))); - biomes.push(json!(world::biome(seed, cell, l))); - } - } - json!({ "cell": [cell.0, cell.1], "props": props, "heights": heights, "moisture": moisture, "biomes": biomes }) -} - -fn build() -> Value { - let seed = DEFAULT_SEED; - let hashes = [0u32, 1, 0xdead_beef, u32::MAX].map(world::hash32); - let mixes = [ - world::mix(seed, 3, -5, 7), - world::mix(0, 0, i32::MIN, i32::MAX), - ]; - json!({ - "description": "Endless Grid world-content parity: Rust game_sim::grid vs client/src/grid/world.ts", - "constants": { - "seed": seed, "contentVersion": world::CONTENT_VERSION, "cell": world::CELL, - "propMargin": world::PROP_MARGIN, - "hashes": hashes, - "mix": mixes, - }, - "cells": CELLS.iter().map(|c| cell_json(seed, *c)).collect::>(), - }) -} - -fn render(v: &Value) -> String { - let mut out = String::from("{\n"); - for key in ["description", "constants"] { - out += &format!(" \"{key}\": {},\n", v[key]); - } - out += " \"cells\": [\n"; - let cells = v["cells"].as_array().unwrap(); - for (i, cell) in cells.iter().enumerate() { - let sep = if i + 1 == cells.len() { "" } else { "," }; - out += &format!(" {cell}{sep}\n"); - } - out + " ]\n}\n" -} - -#[test] -fn grid_world_fixture_is_current() { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/grid-world.json"); - let fresh = render(&build()); - if std::env::var_os("UPDATE_GOLDEN").is_some() { - std::fs::write(&path, fresh).unwrap(); - return; - } - let stored = - std::fs::read_to_string(&path).expect("fixture exists (UPDATE_GOLDEN=1 to create)"); - assert!( - stored == fresh, - "grid world changed: update client/src/grid/world.ts too, then UPDATE_GOLDEN=1" - ); -} - -#[test] -fn biomes_and_props_vary() { - let mut biomes = [0usize; 4]; - let mut props = 0; - for cx in -10..10 { - for cy in -10..10 { - biomes[world::biome(DEFAULT_SEED, (cx, cy), (16.0, 16.0)) as usize] += 1; - props += world::cell_props(DEFAULT_SEED, (cx, cy)).len(); - } - } - eprintln!("biomes {biomes:?}, props/cell {}", props as f32 / 400.0); - assert!( - biomes.iter().all(|n| *n > 10), - "every biome appears: {biomes:?}" - ); - assert!((3..12).contains(&(props / 400)), "props per cell"); -} From 17ee2d79f49f61013d029d7feaade62555be4b7a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 11:33:19 -0500 Subject: [PATCH 199/484] docs(game): document pure functions, constants and record codecs Explains when shared client code is a #[game_pure] function, a surface constant or a served record, the dg_pure_ ABI, schema v3 output (pures.ts, constants.ts, encode/decode), game-wasm building a module for steps and pure functions, the SDK's createWasmPures, and what the demos still mirror in TypeScript and why. --- distributed_cli/README.md | 44 +++++++----- distributed_game/README.md | 109 +++++++++++++++++++++++++---- distributed_game/src/prediction.rs | 3 + examples/game/README.md | 98 +++++++++++++++++--------- js/README.md | 23 +++++- 5 files changed, 213 insertions(+), 64 deletions(-) diff --git a/distributed_cli/README.md b/distributed_cli/README.md index d3a2468cb..f53a96995 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -271,12 +271,13 @@ or an adapter-specific route registry. For [`distributed_game`](../distributed_game/README.md#generated-clients) zones. The zone's authoring derives (`#[derive(Replicated)]`, -`#[derive(GameInput)]`, `#[derive(GameEvent)]`, `#[predict]`) describe a -versioned `GameSurface` (schema v2): kinds with fields, wire types, -priorities and client correction defaults, the input layout with its -sanitize rules, events and the records they mention, and the zone's -client-predicted step. It is deliberately separate from the GraphQL client -manifest above. +`#[derive(GameInput)]`, `#[derive(GameEvent)]`, `#[predict]`, +`#[game_pure]`) describe a versioned `GameSurface` (schema v3): kinds with +fields, wire types, priorities and client correction defaults, the input +layout with its sanitize rules, events and the records they mention, the +zone's client-predicted step, pure functions compiled to WebAssembly, +constants and standalone record codecs. It is deliberately separate from +the GraphQL client manifest above. ```bash # Build and run the crate's surface export through the manifest harness @@ -290,7 +291,8 @@ distributed game-client --manifest target/arena.surface.json --out web/src/gener # CI: compare without writing (also catches surface drift via surface.json) distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena --check -# Compile the zone's `#[predict]` step to web/src/generated/arena/wasm/arena.wasm +# Compile the zone's `#[predict]` step and `#[game_pure]` functions to +# web/src/generated/arena/wasm/arena.wasm # (skipped when the stamp says the sources are unchanged; --check verifies only). distributed game-wasm --manifest target/arena.surface.json --manifest-path game/Cargo.toml \ --out web/src/generated/arena @@ -310,17 +312,23 @@ and refuses to delete files it did not. Output is deterministic. generated files (default `ts`, for Vite and Node type stripping). A surface with a predicted step also gets `predict.ts` (state and context layouts, `PREDICT_WASM_URL`, `createPrediction`), and `createClient` -predicts with the compiled step by default. - -`game-wasm` builds the Cargo package the surface names as the step's -declarer (`cargo rustc --release --target wasm32-unknown-unknown ---crate-type cdylib`; install the target with `rustup target add -wasm32-unknown-unknown`), checks the module is self-contained (no imports) -and exports the prediction ABI (`memory`, `dg_predict_abi`, -`dg_predict_buffer`, `dg_predict_`), and writes -`/wasm/.wasm` plus a stamp (the source fingerprint of the -package and its local dependencies — the same one browser WASM pures use — -the `rustc` identity and the module hash). The module is a build output: +predicts with the compiled step by default. Pure functions add `pures.ts` +(`createPures`, one typed synchronous wrapper per function over the +same module), constants add `constants.ts` (typed literals; floats are the +exact binary32 values, and each value is validated against its type), and +record codecs add `encode` / `decode` to `events.ts`. + +`game-wasm` builds the Cargo package the surface names as the declarer of +its step and pure functions (one package per surface; `cargo rustc +--release --target wasm32-unknown-unknown --crate-type cdylib`; install the +target with `rustup target add wasm32-unknown-unknown`), checks the module +is self-contained (no imports) and exports the ABI (`memory`, +`dg_predict_abi`, `dg_predict_buffer`, `dg_predict_`, every +`dg_pure_`), and writes `/wasm/.wasm` plus a stamp (the +source fingerprint of the package and its local dependencies — the same +one browser WASM pures use — the `rustc` identity, the required exports +and the module hash). A surface with neither a step nor pure functions is +an error. The module is a build output: keep `wasm/` out of version control and run `game-wasm` before bundling. Unlike browser WASM pures it needs no wasm-pack, wasm-bindgen glue or JSON bridge; the SDK instantiates the module directly over a binary ABI. diff --git a/distributed_game/README.md b/distributed_game/README.md index cb0a21474..e2442b9da 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -25,9 +25,9 @@ the browser, but the client SDK has no rendering dependency. - [Try it](#try-it) - [Build a zone](#build-a-zone) - [Guides](#guides): game loop · input · what clients see · the client SDK · - generated clients · client prediction (Rust → WebAssembly) · saving - progress · scaling out · live updates · lag compensation · testing and - operations · security + generated clients · client prediction (Rust → WebAssembly) · shared + logic and data (no TypeScript twins) · saving progress · scaling out · + live updates · lag compensation · testing and operations · security - [Design decisions](#design-decisions) - [Status and limits](#status-and-limits) - [Reference](#reference) @@ -391,17 +391,19 @@ zone's typed fields, input encoder, events and correction defaults. ### Generated clients The derives also describe the zone for the browser. A **game surface** -(`GameSurface`, versioned JSON, schema v2) lists the zone's kinds with +(`GameSurface`, versioned JSON, schema v3) lists the zone's kinds with their fields, wire types, priorities and correction defaults, its input -layout and sanitize rules, its events and the records they mention, and -its predicted step. Export one function per zone type, conventionally -`game_surface`: +layout and sanitize rules, its events and the records they mention, its +predicted step, and what else the client shares with Rust: pure functions +compiled to WebAssembly, constants and standalone record codecs. Export +one function per zone type, conventionally `game_surface`: ```rust,ignore pub fn game_surface() -> GameSurface { GameSurface::for_zone::("arena") .events::() .predict::() + .constant("arena_floor", &arena_floor()) } ``` @@ -417,14 +419,20 @@ imports only `@hops-ops/distributed/game`: | `events.ts` | record and event interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | | `client.ts` | `createClient(options)`: a `GameClient` with the encoder and correction defaults wired in (and, with a predicted step, prediction by the compiled step), a typed `on(name, handler)` and `send(input)` | | `predict.ts` | with a `#[predict]` step: `PREDICT`, the state/context layouts, `PREDICT_WASM_URL` (`./wasm/.wasm`) and `createPrediction` | +| `pures.ts` | with `#[game_pure]` functions: `PURES`, `PURES_WASM_URL` (the same module) and `createPures()`, one typed wrapper per function | +| `constants.ts` | with `.constant(..)`s: each value as a typed literal (`ARENA_FLOOR: ArenaFloor`) | | `index.ts`, `surface.json` | re-exports; the surface it came from | +`events.ts` also gets `encode` / `decode` for every +`.record::()` (see [Shared logic and data](#shared-logic-and-data-no-typescript-twins)). + The output is deterministic, so check it in and run `--check` in CI: a changed Rust definition then fails the build until the client is regenerated. The binary protocol is unchanged; the generated code only -removes the hand-written glue around it. The compiled step -(`distributed game-wasm`, `wasm/.wasm`) is a build output: ignore -`wasm/` in version control and build it before bundling. +removes the hand-written glue around it. The compiled module +(`distributed game-wasm`, `wasm/.wasm`: the predicted step and the +pure functions) is a build output: ignore `wasm/` in version control and +build it before bundling. ### Client prediction (Rust → WebAssembly) @@ -515,6 +523,78 @@ steps plus the grid's world generation). and never trusts a predicted value: it simulates the inputs itself, and every Delta replaces the prediction with the authoritative state. +### Shared logic and data (no TypeScript twins) + +Prediction is not the only client code that must agree with the server. +Procedural content, drawing constants and served data have the same +problem: a TypeScript copy drifts. The surface gives each kind of shared +thing one home in Rust and one generated way into the client: + +| What | Rust | Surface | Client | +|---|---|---|---| +| **Logic** (pure functions: world generation, previews) | `#[game_pure(FnType)] fn f(arg: &A) -> R` (or `fn f() -> R`) | `.pure::()` | `createPures().f(arg)`: the same code, compiled into the surface's WebAssembly module | +| **Static data** (sizes, layouts, names) | any `Wire` value (`#[derive(GameRecord)]` struct, list, …) | `.constant("name", &value)` | `NAME` in `constants.ts`, a typed literal | +| **Served data** (fetched at run time, e.g. a content pack) | a `#[derive(GameRecord)]` struct | `.record::()` | `decodeT(bytes)` / `encodeT(value)` over the payload codec | + +Choose by what the thing *is*: computation the client repeats with +arguments it only knows at run time belongs in a pure function (the +Endless Grid generates terrain and props for any cell); data fixed at +build time is a constant (no module to wait for, readable in diffs); +data that changes after the client was built is served and decoded (The +Freeze's content packs, which a client must be able to receive without a +rebuild). + +```rust,ignore +/// What the page draws for one cell (terrain lattice + props). +#[game_pure(GridCellFn)] +pub fn grid_cell(cell: &GridContext) -> GridCellContent { + /* the server's own generation */ +} + +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("grid") + .predict::() + .pure::() + .constant("grid_world", &grid_world()) +} +``` + +```ts +const pures = createGridPures(); // same module (and instance) as the predicted step +await pures.ready; +const content = pures.gridCell({ seed, cx: 3, cy: -2 }); // GridCellContent, exact binary32 floats +``` + +- **Pure functions** share the predicted step's module, package and ABI + v1: each is an export `dg_pure_(arg_len) -> i32`; the argument's + codec encoding goes into the scratch buffer, the result's comes back + (≤ 64 KiB; negative results are errors, `-6` = argument does not + decode). Every function and the step of one surface must be declared in + one Cargo package; `distributed game-wasm` builds the module when a + surface has either and checks every export. The wrappers are + synchronous and throw until `ready` resolves. `pure::call_bytes::` + runs the export's path natively, so native ↔ WASM tests compare bytes. + The [determinism rules](#client-prediction-rust--webassembly) apply. +- **Constants** are stored in the surface as the client decodes them + (`codec::to_json_value`: encoded, then decoded against the wire type — + floats are exact binary32 values, quantized fields quantized), so the + generated literal equals what `decodeValue` would return for the Rust + encoding. +- **Record codecs** are the event payload codec for one record; serve the + bytes (`codec::to_bytes`) from any transport. + +The demos have no TypeScript twins left for these: the Endless Grid's +terrain, biomes and props (`grid_cell`, `grid_sample`), the Arena floor, +The Freeze's world layout and content packs, Mob Pit's tier radii and +Boss Ripple's zone hierarchy all come from Rust. `game-demos +predict-trace` also prints native traces of every pure function, and +`prediction-wasm.test.mjs` requires the module's results to be +byte-identical (1 440 `grid_sample` points and 64 `grid_cell` cells, +coordinate limits included). Generating one grid cell (17 × 17 heights, +moisture and biomes plus props) costs ~6 µs in the module and ~13 µs +including decoding the result into JS objects in Node 24 (native Rust +~5.6 µs; the removed TypeScript twin took ~77 µs); a point sample ~0.5 µs. + ### Saving progress without pausing the game The rule: **the tick never waits for storage.** A slow disk or a busy @@ -689,12 +769,15 @@ errors for unsupported types and attributes. | `GameRecord` | struct | – | `quant`, `angle`, `field_type`, `long` | `Wire` (nested payload record) | | `FactCommand` | struct (`Serialize`) | `#[fact(command = CONST_OR_LITERAL, key(field, ..))]` | – | `FactCommand` (`COMMAND`, `dedupe_parts`) | | `#[predict]` (attribute) | `fn(&State, &Input, &Context, f32) -> State` | `#[predict(StepType, kind = "name")]` | – | `struct StepType: PredictStep` + the `wasm32` export `dg_predict_` | +| `#[game_pure]` (attribute) | `fn(&A) -> R` or `fn() -> R` (`Wire` types) | `#[game_pure(FnType)]` | – | `struct FnType: GamePure` + the `wasm32` export `dg_pure_` | `schema![A, B]` builds an `EntitySchema`; `GameSurface::for_zone::(name)` (kinds from `Z::schema()`, input from `Z::Input`) `.events::()` -`.predict::()` builds the surface; `codec` holds the shared value codec -(`Wire`, `WireType`); `prediction` the predicted-step trait, its ABI -(`run_abi`, `step_bytes`) and the float rules. +`.predict::()` `.pure::()` `.constant(name, &v)` `.record::()` +builds the surface; `codec` holds the shared value codec (`Wire`, +`WireType`, `to_json_value`); `prediction` the predicted-step trait, its +ABI (`run_abi`, `step_bytes`) and the float rules; `pure` the pure-function +trait and its ABI (`run_abi`, `call_bytes`). ## Features diff --git a/distributed_game/src/prediction.rs b/distributed_game/src/prediction.rs index 6afc6a933..b3613e046 100644 --- a/distributed_game/src/prediction.rs +++ b/distributed_game/src/prediction.rs @@ -46,6 +46,9 @@ //! start of the buffer; negative values are [`AbiError`] codes. No allocation //! crosses the boundary and nothing is JSON: floats stay binary32. //! +//! Pure functions (`#[game_pure]`, [`crate::pure`]) live in the same module +//! and share the buffer and ABI version: `dg_pure_(arg_len) -> i32`. +//! //! # Determinism //! //! Native and WASM results are bit-identical when the step uses only diff --git a/examples/game/README.md b/examples/game/README.md index 414fd7149..9565cb1b2 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -35,17 +35,25 @@ cell); the zones call those functions in `on_tick`. Each demo module exports `game_surface()`; `run.sh gen` runs `distributed game-manifest` on it, `distributed game-client` writes `client/src/generated//` (checked in, verified by `run.sh smoke`) and `distributed game-wasm` -compiles the step to `client/src/generated//wasm/.wasm` -(gitignored, rebuilt only when the Rust sources change; `run.sh ` -builds it too). The pages use the generated `createClient`, which -predicts with the compiled step, typed field accessors -(`mobFields(entity).hp`), the input encoder and typed `on('kill', …)` -handlers. No movement code is written in TypeScript; what remains -hand-written for drawing is `arena/floor.ts` (floor size, pillars, capsule -radius — checked against the native build) and `grid/world.ts` (the grid's -terrain/props generation for rendering, see below). The Shooting Gallery -predicts hits by ray-testing what it renders, not movement, so it has no -predicted step. +compiles the step — and the grid's `#[game_pure]` world generation — to +`client/src/generated//wasm/.wasm` (gitignored, rebuilt only +when the Rust sources change; `run.sh ` builds it too). The pages use +the generated `createClient`, which predicts with the compiled step, +typed field accessors (`mobFields(entity).hp`), the input encoder and typed +`on('kill', …)` handlers. + +No simulation or content code is written twice. Movement is the compiled +step; the Endless Grid's terrain, biomes and props come from the compiled +`grid_cell` / `grid_sample` (`createGridPures`); static data the pages +draw is a generated constant from the Rust values (`ARENA_FLOOR` — floor +size, pillars, capsule radius, used by every Arena-floor page — +`GRID_WORLD`, `FREEZE_WORLD`, `PIT_RULES` tier radii, `RIPPLE_WORLD` zone +hierarchy, `GALLERY_COURSE` rails); The Freeze's content packs are a Rust +record served in its payload encoding and decoded by the generated +`decodePack`. What TypeScript still mirrors is small and listed under +[Remaining client-side mirrors](#remaining-client-side-mirrors). The +Shooting Gallery predicts hits by ray-testing what it renders, not +movement, so it has no predicted step. Requirements: Rust (stable) with the `wasm32-unknown-unknown` target (`rustup target add wasm32-unknown-unknown`), Node ≥ 22.18 (runs `.ts` @@ -93,8 +101,12 @@ ticket + admin secrets, exits with its parent); portals hand players off between them (`Redirect` + `/admin/transfer` across processes). Content is data-driven per version (`freeze::content`: v1 lava pools that burn, v2 "lava is now ice", v3 back to lava; slime speed/size/color, crystals, gem -value) and served by `GET /dev/freeze/content/{version}`; the client derives -the scene from *its own* pack. +value) and served by `GET /dev/freeze/content/{version}` — the Rust `Pack` +record in its payload encoding, decoded by the generated `decodePack`; the +version-independent layout (zones, portals, pools, crystal spots) is the +generated `FREEZE_WORLD` constant. The client derives the scene from *its +own* pack. Packs are served, not compiled into the page, because the demo +is about a client receiving content it was not built with. - **Roll out update (Hard)**: every zone on both hosts freezes (SYSTEM overlay, inputs dropped and counted — client side, plus any in flight on @@ -139,10 +151,13 @@ is derived from it) and keeping hibernation snapshots under one - **World.** Cell `(x, y)` is zone `grid..` (canonical integers, |x|,|y| ≤ 10⁶; the server uses `FlatTopology`, the dots are not a hierarchy). Its terrain height, biome and props are a pure function of - `(seed, x, y, CONTENT_VERSION)` in `server/sim/src/grid.rs` and, for - rendering only, its twin `client/src/grid/world.ts` (u32 hashing + - binary32 value noise; checked - bit-for-bit by `fixtures/grid-world.json`). Props sit inside 8 m + `(seed, x, y, CONTENT_VERSION)` in `server/sim/src/grid.rs` (u32 hashing + + binary32 value noise). The page renders the same code compiled to + WebAssembly: `grid_cell` returns a cell's 17 × 17 terrain lattice + (heights, moisture, biomes) and props, `grid_sample` one point (entity + heights, the HUD biome); generating a cell costs ~13 µs in Node including + decoding (~6 µs in the module; the removed TypeScript twin took ~77 µs). + Props sit inside 8 m sub-cells 2 m from their edges, so lines every 8 m are free trails and no prop reaches across a border. Seed: `DG_GRID_SEED`. - **Zones.** A cell simulates walkers (predicted by `grid_step` compiled to @@ -218,23 +233,40 @@ that round identically on every target (`+ - * /`, `sqrt`, comparisons; no trig), and (3) the server snaps its state to the wire quantization after each step, so the client rebases on exactly what the server holds. `client/tests/prediction-wasm.test.mjs` replays the native traces of -`game-demos predict-trace` (recorded input streams per step function) -through every surface's module and requires byte-identical states; it also -times prediction (≈ 1 µs per step, ≈ 8–12 µs for a reconciliation -replaying 10 inputs). +`game-demos predict-trace` (recorded input streams per step function, and +recorded arguments per pure function) through every surface's module and +requires byte-identical states and results; it also times prediction +(≈ 1 µs per step, ≈ 8–12 µs for a reconciliation replaying 10 inputs) and +grid generation (≈ 13 µs per cell, ≈ 0.5 µs per point sample). + +## Remaining client-side mirrors + +What the TypeScript still restates, and why it stays: + +- **Zone id formats and defaults** — `grid..` (`zoneId` / + `parseZone` in `grid/client.ts`) and each page's default zone + (`arena-1`, `pit-1`, …). They are addressing, needed synchronously before + any module loads; a mismatch fails loudly (the server rejects the zone). +- **Dev / admin HTTP JSON shapes** — `WorldMap`, `WorldStatus`, + `BoardPosition`: debugging routes outside the game surface. +- **The Shooting Gallery's predicted hit** (`raySphere` over rendered + targets) — cosmetic feedback; the server's rewound `HitQuery` decides. + It could become a `#[game_pure]` over the rendered targets. +- **Presentation** — colors, tier display names, camera and HUD constants: + client-only by nature. ## Layout ``` examples/game/ run.sh one-command dev + smoke runner - fixtures/ grid-world.json: grid content golden data (Rust writes, world.ts checks) server/ Rust crate `game_demos`, its own cargo workspace (with sim/) - sim/ crate `game_sim`: the `#[predict]` steps (arena.rs movement, mobpit.rs, - ripple.rs inputs + steps, grid.rs world + walker step); compiled - natively for the server and to wasm32 for the browser + sim/ crate `game_sim`: the `#[predict]` steps (arena.rs movement + floor, + mobpit.rs, ripple.rs inputs + steps, grid.rs world + walker step + + `#[game_pure]` grid_cell / grid_sample); compiled natively for the + server and to wasm32 for the browser src/main.rs `game-demos ` subcommands (+ hidden `predict-trace`) - src/predict_trace.rs native traces of every step over recorded input streams + src/predict_trace.rs native traces of every step (recorded inputs) and pure function (arguments) src/common/ shared: Demo trait, run/spawn, dev routes, guests src/cluster.rs multi-host demos: --host-id/--peer, directory, ownership, snapshots src/arena/ Arena zone (`movement` = `game_sim::arena`) @@ -245,22 +277,24 @@ examples/game/ src/ripple/ Boss Ripple tiers and placement tests/ arena_smoke.rs (bots, dev routes), mobpit_smoke.rs (facts, slow storage, kill -9 recovery, boards), - gallery_smoke.rs, freeze_smoke.rs, grid_smoke.rs, grid_fixture.rs, + gallery_smoke.rs, freeze_smoke.rs (binary content packs), grid_smoke.rs, ripple_smoke.rs (+ support/ for two in-process hosts) client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/generated// generated by `run.sh gen` (do not edit): schema/input/events/client.ts, - predict.ts, surface.json, wasm/.wasm (gitignored build output); + predict.ts, pures.ts (grid), constants.ts, surface.json, + wasm/.wasm (gitignored build output); `mobpit` also serves the leaderboard page src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, latest.ts, style.css - src/arena/ client.ts (headless), main.ts (Babylon), floor.ts (drawing constants) + src/arena/ client.ts (headless), main.ts (Babylon) src/mobpit/ client.ts (headless + /dev/mobpit API), main.ts (Babylon), style.css src/leaderboard/ main.ts (DOM page over the observer connection), style.css src/gallery/ client.ts (shots, adaptive delay), main.ts src/freeze/ client.ts (content packs, live patch / reload, admin API), main.ts - src/grid/, src/ripple/ client.ts (headless), main.ts (Babylon); grid/world.ts (content, rendering) - tests/ prediction-wasm (native ↔ WASM exact match + cost), arena-headless, mobpit-headless, leaderboard-headless, - gallery-headless, freeze-headless, grid-world-parity, grid-headless, + src/grid/, src/ripple/ client.ts (headless; grid: compiled world content), main.ts (Babylon) + tests/ prediction-wasm (native ↔ WASM exact match of steps + pure functions, cost), + arena-headless, mobpit-headless, leaderboard-headless, + gallery-headless, freeze-headless, grid-headless, ripple-headless (+ helpers/demo-server.mjs, helpers/mobpit.mjs, helpers/cluster.mjs for multi-host demos) ``` diff --git a/js/README.md b/js/README.md index a8c40a90b..db83307df 100644 --- a/js/README.md +++ b/js/README.md @@ -678,6 +678,26 @@ for a reconciliation replaying 10 pending inputs — well under 0.1 % of a box); with `--import-extension js` copy `wasm/` next to the emitted JavaScript. +**Shared logic and data.** Pure functions the zone declares with +`#[game_pure]` are compiled into the same module; the generated +`createPures()` returns one typed, synchronous wrapper per function +(plus `ready`, `loaded()`, `module()`) and shares the instance the +prediction already loaded: + +```ts +const pures = createGridPures(); +await pures.ready; +const cell = pures.gridCell({ seed, cx: 3, cy: -2 }); // the server's own world generation +``` + +Underneath, `createWasmPures(source, specs)` calls +`PredictModule.call(exportName, argBytes)` (`dg_pure_`, payload codec in +and out; calls before `ready` throw). Static data the zone exports with +`GameSurface::constant` arrives as generated constants (`constants.ts`), and +records it serves (e.g. a content pack over HTTP) get generated +`decode` / `encode` functions over `decodeValue` / +`encodeValue`. + ## Protocol and security boundaries Every accepted artifact and response is protocol v1 and carries an exact @@ -713,7 +733,8 @@ duplicated as decision documents in this package. - `@hops-ops/distributed/game` — binary `distributed_game` zone protocol client: codec, `GameConnection` (handshake, reconnect, clock sync), interpolating `EntityReplica`, `Predictor` reconciliation (with - `createWasmPrediction` for steps compiled from Rust) and the multi-zone + `createWasmPrediction` for steps compiled from Rust, and `createWasmPures` + for pure functions compiled alongside them) and the multi-zone `GameClient` with handoff, `AdaptiveDelay` and `InputPacer`. See `distributed_game/PROTOCOL.md`. From 1835d9fa96ca50bd3501eb87d23466e091a6329c Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 13:02:13 -0500 Subject: [PATCH 200/484] test: fix migration list and Node 20 generated-client test The lease work added migration 0010, but the inventory test still expected 1..=9. The generated-client test imported .ts files, which Node 20 cannot load; compile them with TypeScript first. --- distributed_cli/src/contracts/tests.rs | 2 +- js/tests/game-generated.test.mjs | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 2edef446b..a23582ee8 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/js/tests/game-generated.test.mjs b/js/tests/game-generated.test.mjs index 0fc9250d1..f4304238a 100644 --- a/js/tests/game-generated.test.mjs +++ b/js/tests/game-generated.test.mjs @@ -3,13 +3,16 @@ // `distributed_game/tests/fixtures/authoring.json` holds a sample surface and // payloads encoded by the Rust derives; the TypeScript generated from that // surface is pinned in `distributed_cli/tests/fixtures/game-client/sample/`. -// This test loads the generated files (Node strips their types) and checks -// they encode and decode byte-for-byte like Rust. +// This test compiles the generated files to JavaScript (so it also runs on +// Node 20, which cannot load .ts) and checks they encode and decode +// byte-for-byte like Rust. import assert from 'node:assert/strict'; -import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { after, before, test } from 'node:test'; +import ts from 'typescript'; + import { decodeValue, fromHex, toHex } from '@hops-ops/distributed/game'; import { predictModuleBytes } from './fixtures/predict-module.mjs'; @@ -24,8 +27,14 @@ let gen; before(async () => { // Inside the package so `@hops-ops/distributed/game` resolves to this build. dir = mkdtempSync(fileURLToPath(new URL('./.generated-', import.meta.url))); - cpSync(GOLDEN, dir, { recursive: true }); - gen = await import(pathToFileURL(`${dir}/index.ts`).href); + for (const file of readdirSync(GOLDEN)) { + if (!file.endsWith('.ts')) continue; + const { outputText } = ts.transpileModule(readFileSync(`${GOLDEN}/${file}`, 'utf8'), { + compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } + }); + writeFileSync(`${dir}/${file.replace(/\.ts$/, '.js')}`, outputText.replace(/(from '\.\/[\w-]+)\.ts'/g, "$1.js'")); + } + gen = await import(pathToFileURL(`${dir}/index.js`).href); }); after(() => rmSync(dir, { recursive: true, force: true })); From 03582a33dc8ab8d2a8d517176ec775991b032287 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 14:36:03 -0500 Subject: [PATCH 201/484] test: re-record compiler messages; add wasm target to CLI CI Rust 1.99 prints String instead of std::string::String in two compile-fail notes. The game-wasm CLI test builds a wasm32 module, so the CLI job needs the target installed. --- .github/workflows/integration-distributed-cli.yaml | 2 ++ .../input_default_list.stderr | 4 ++-- .../input_default_nullable.stderr | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/integration-distributed-cli.yaml b/.github/workflows/integration-distributed-cli.yaml index b095d0816..80dcacc34 100644 --- a/.github/workflows/integration-distributed-cli.yaml +++ b/.github/workflows/integration-distributed-cli.yaml @@ -19,6 +19,8 @@ jobs: - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 with: toolchain: stable + # game-wasm tests compile prediction steps to WebAssembly. + targets: wasm32-unknown-unknown - uses: actions/setup-node@v4 with: node-version: "22" diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr index 994eef3d9..e2cae2fa0 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr @@ -9,8 +9,8 @@ note: expected this to be `std::string::String` | 5 | ids: Vec, | ^^^^^^^^^^^ - = note: expected struct `std::string::String` - found struct `Vec` + = note: expected struct `String` + found struct `Vec` note: required by a bound in `distributed::command::__input_default_ulid` --> $WORKSPACE/src/command/effect_wire.rs | diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr index 0fc9282ad..2fcf0f976 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr +++ b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr @@ -9,8 +9,8 @@ note: expected this to be `std::string::String` | 6 | id: Option, | ^^^^^^^^^^^^^^ - = note: expected struct `std::string::String` - found enum `std::option::Option` + = note: expected struct `String` + found enum `std::option::Option` note: required by a bound in `distributed::command::__input_default_uuid_v7` --> $WORKSPACE/src/command/effect_wire.rs | From c5802007243d7969685028ffbbd0554a9320490a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:00:18 -0500 Subject: [PATCH 202/484] test(game): wait for hibernation saves, not just deactivation A zone leaves the active set before its snapshot is written, so tests that checked the store right after deactivation raced the save and failed on slow CI runners. --- distributed_game/tests/world/main.rs | 17 +++++++++++++---- examples/game/server/tests/grid_smoke.rs | 9 +++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs index f5c99a074..6283d11f4 100644 --- a/distributed_game/tests/world/main.rs +++ b/distributed_game/tests/world/main.rs @@ -534,9 +534,11 @@ async fn dormant_zone_hibernates_to_sqlite_and_restores() { }) .await; send(&mut ana.ws, ClientMessage::Leave).await; - eventually("hibernation", || { + // The zone leaves the active set before its snapshot is written, so wait + // for the save itself. + eventually("hibernation save", || { let server = server.clone(); - async move { !server.is_active("realm.vault") } + async move { !server.is_active("realm.vault") && hibernation_outcomes(&server) >= 1 } }) .await; let saved = store.load("realm.vault").unwrap().expect("snapshot stored"); @@ -627,9 +629,10 @@ async fn hibernation_saves_succeed_after_a_host_restart_on_the_same_store() { .unwrap(), ); send(&mut ana.ws, ClientMessage::Leave).await; - eventually("hibernation", || { + // Saved, stale or error: the assertions below say which. + eventually("hibernation save", || { let server = server.clone(); - async move { !server.is_active("realm.keep") } + async move { !server.is_active("realm.keep") && hibernation_outcomes(&server) >= cycle } }) .await; assert_eq!(server.metrics().hibernation_saves("stale"), 0, "run {run}"); @@ -1045,3 +1048,9 @@ fn directory_types_are_object_safe() { let dir: Arc = Arc::new(StaticDirectory::new()); assert!(dir.locate("x").is_none()); } + +/// Hibernation snapshot saves finished so far, whatever their outcome. +fn hibernation_outcomes(server: &GameServer) -> u64 { + let m = server.metrics(); + m.hibernation_saves("saved") + m.hibernation_saves("stale") + m.hibernation_saves("error") +} diff --git a/examples/game/server/tests/grid_smoke.rs b/examples/game/server/tests/grid_smoke.rs index bf37afc80..09d0cb6bd 100644 --- a/examples/game/server/tests/grid_smoke.rs +++ b/examples/game/server/tests/grid_smoke.rs @@ -170,12 +170,17 @@ async fn empty_cell_hibernates_and_restores_critters_and_markers() { client .until("marker replicated", |c| c.count(MarkerView::KIND_ID) == 1) .await; + let saves_before = owner.demo.server.metrics().hibernation_saves("saved"); client.leave().await; drop(client); - eventually("hibernation", || { + // The zone leaves the active set before its snapshot is written, so wait + // for the save itself. + eventually("hibernation save", || { let server = owner.demo.server.clone(); - async move { !server.is_active(zone) } + async move { + !server.is_active(zone) && server.metrics().hibernation_saves("saved") >= saves_before + 1 + } }) .await; let saved = owner From 2afa90c51a5e04eab1b5f3cb7d99c7c7269c4525 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:24:34 -0500 Subject: [PATCH 203/484] feat(sveltekit): game ticket handler and runes game state Add @hops-ops/distributed/sveltekit/game (useGame, createGameState, gameTicketSource) and /sveltekit/game/server (createGameTicketHandler, mintGameTicket). Tickets are HS256 PROTOCOL.md section 8 JWTs minted with WebCrypto from the verified session principal and a server-chosen zone; a JS-minted fixture is admitted by a real GameServer in net_e2e, and the tampered, expired, wrong-zone and replayed tickets are refused. --- .../tests/fixtures/sveltekit_tickets.json | 19 + distributed_game/tests/net_e2e/main.rs | 90 +++- js/package.json | 10 +- js/src/sveltekit/game/index.ts | 20 + js/src/sveltekit/game/server.ts | 418 ++++++++++++++++++ js/src/sveltekit/game/state.ts | 380 ++++++++++++++++ js/src/sveltekit/game/ticket.ts | 156 +++++++ js/tests/sveltekit-game.test.mjs | 398 +++++++++++++++++ 8 files changed, 1489 insertions(+), 2 deletions(-) create mode 100644 distributed_game/tests/fixtures/sveltekit_tickets.json create mode 100644 js/src/sveltekit/game/index.ts create mode 100644 js/src/sveltekit/game/server.ts create mode 100644 js/src/sveltekit/game/state.ts create mode 100644 js/src/sveltekit/game/ticket.ts create mode 100644 js/tests/sveltekit-game.test.mjs diff --git a/distributed_game/tests/fixtures/sveltekit_tickets.json b/distributed_game/tests/fixtures/sveltekit_tickets.json new file mode 100644 index 000000000..ca6fbe151 --- /dev/null +++ b/distributed_game/tests/fixtures/sveltekit_tickets.json @@ -0,0 +1,19 @@ +{ + "secret": "sveltekit-fixture-secret-0123456789abcdef", + "zone": "z-sveltekit", + "valid": { + "ticket": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXZhbGlkIiwicm9sZSI6InBsYXllciIsIm5hbWUiOiJBbmEifQ.6dm_sJTidsFT1CAz_YrO6v4mPRk61DGA-sfkSZ2Zi40", + "principal": "session-user-1", + "name": "Ana", + "exp": 4000000000, + "nonce": "fixture-valid" + }, + "observer": { + "ticket": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMiIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLW9ic2VydmVyIiwicm9sZSI6Im9ic2VydmVyIn0.1j2Ql0XePnslZ1kJf64VhjUeDYkdl_nAt6Vep2zQ1bs", + "principal": "session-user-2" + }, + "expired": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6MzAwLCJub25jZSI6ImZpeHR1cmUtZXhwaXJlZCIsInJvbGUiOiJwbGF5ZXIifQ.pJED6dt-O-JNtFi-fqzUFNPtEWYljUs0pKR9gJrX380", + "wrongZone": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LWVsc2V3aGVyZSIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXdyb25nLXpvbmUiLCJyb2xlIjoicGxheWVyIn0.s4mdpfnnVke8Ntt_LjHAgonARO5RRt_KVgKH5v96k7A", + "tampered": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXRhbXBlcmVkIiwicm9sZSI6InBsYXllciJ9.k0UNks88hcYz9M18yZdUA2OPH-Xwgf6jBwi6snvkoJE", + "otherKey": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLW90aGVyLWtleSIsInJvbGUiOiJwbGF5ZXIifQ.qVpH3bUXNhkfwk-J-AdLw40Fnyu0k6aEFf5ItmBIlLw" +} diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs index 05d3f1ebf..f4f1c13b6 100644 --- a/distributed_game/tests/net_e2e/main.rs +++ b/distributed_game/tests/net_e2e/main.rs @@ -36,7 +36,14 @@ fn ticket(principal: &str, zone: &str, nonce: &str, role: Role) -> String { async fn start( net_sim: Option, ) -> (String, GameServer, tokio::task::JoinHandle<()>) { - let mut config = ServerConfig::new(TicketKey::new(SECRET)); + start_keyed(SECRET, net_sim).await +} + +async fn start_keyed( + secret: &str, + net_sim: Option, +) -> (String, GameServer, tokio::task::JoinHandle<()>) { + let mut config = ServerConfig::new(TicketKey::new(secret)); config.host.tick_rate = 30; config.host.patch_rate = 20; config.net_sim = net_sim; @@ -257,6 +264,87 @@ async fn client_joins_sends_inputs_receives_deltas_and_reconnects() { .unwrap(); } +/// Tickets minted in JavaScript by `@hops-ops/distributed/sveltekit/game/server` +/// (`mintGameTicket`, reproduced byte for byte by `js/tests/sveltekit-game.test.mjs`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn admits_tickets_minted_by_the_sveltekit_handler() { + let fixture: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/sveltekit_tickets.json")).unwrap(); + let text = |path: &str| { + fixture + .pointer(path) + .and_then(serde_json::Value::as_str) + .unwrap_or_else(|| panic!("fixture {path}")) + .to_string() + }; + let secret = text("/secret"); + let zone = text("/zone"); + + // The same key verifies the claims exactly. + let claims = TicketKey::new(secret.as_str()) + .verify(&text("/valid/ticket"), 1_700_000_000) + .unwrap(); + assert_eq!(claims.principal, text("/valid/principal")); + assert_eq!(claims.zone, zone); + assert_eq!(claims.expires_at, 4_000_000_000); + assert_eq!(claims.nonce, text("/valid/nonce")); + assert_eq!(claims.role, Role::Player); + assert_eq!(claims.name.as_deref(), Some("Ana")); + + let (url, server, handle) = start_keyed(&secret, None).await; + + // A real GameServer admits the JS-minted player ticket ... + let mut ws = connect(&url, &zone).await; + hello(&mut ws, text("/valid/ticket"), String::new()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome for the JS-minted ticket") + }; + assert_eq!(welcome.zone_id, zone); + assert_eq!(welcome.role, Role::Player); + let players = server + .inspect(&zone, |host| host.players().cloned().collect::>()) + .await + .expect("zone active"); + let player = players + .iter() + .find(|p| p.principal == text("/valid/principal")) + .expect("the principal comes from the JS-minted ticket"); + assert_eq!(player.name.as_deref(), Some("Ana")); + + // ... and the observer ticket. + let mut obs = connect(&url, &zone).await; + hello(&mut obs, text("/observer/ticket"), String::new()).await; + let Some(ServerMessage::Welcome(w)) = next(&mut obs, &mut ClientMirror::new()).await else { + panic!("expected Welcome for the JS-minted observer ticket") + }; + assert_eq!(w.role, Role::Observer); + + // Single use, signature, expiry and zone binding are enforced. + for (what, ticket) in [ + ("replayed", text("/valid/ticket")), + ("tampered", text("/tampered")), + ("expired", text("/expired")), + ("wrong zone", text("/wrongZone")), + ("other key", text("/otherKey")), + ] { + let mut ws = connect(&url, &zone).await; + hello(&mut ws, ticket, String::new()).await; + match next(&mut ws, &mut ClientMirror::new()).await { + Some(ServerMessage::Error { code, .. }) => { + assert_eq!(code, error::UNAUTHORIZED, "{what}") + } + other => panic!("{what}: expected UNAUTHORIZED, got {other:?}"), + } + } + + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn latency_simulation_delays_but_preserves_order() { let sim = NetSim { diff --git a/js/package.json b/js/package.json index a3d1de708..0f3ec0f00 100644 --- a/js/package.json +++ b/js/package.json @@ -30,6 +30,14 @@ "types": "./dist/sveltekit/public-vite.d.ts", "import": "./dist/sveltekit/public-vite.js" }, + "./sveltekit/game": { + "types": "./dist/sveltekit/game/index.d.ts", + "import": "./dist/sveltekit/game/index.js" + }, + "./sveltekit/game/server": { + "types": "./dist/sveltekit/game/server.d.ts", + "import": "./dist/sveltekit/game/server.js" + }, "./react": { "types": "./dist/react/index.d.ts", "import": "./dist/react/index.js" @@ -64,7 +72,7 @@ }, "peerDependencies": { "react": "^18.2.0 || ^19.0.0", - "svelte": "^5.0.0" + "svelte": "^5.7.0" }, "peerDependenciesMeta": { "react": { diff --git a/js/src/sveltekit/game/index.ts b/js/src/sveltekit/game/index.ts new file mode 100644 index 000000000..28047fb9d --- /dev/null +++ b/js/src/sveltekit/game/index.ts @@ -0,0 +1,20 @@ +/** + * Browser-safe SvelteKit integration for `distributed_game` zones: the + * Svelte 5 runes adapter for the UI around a game (`useGame`, + * `createGameState`) and the ticket source for a `createGameTicketHandler` + * route (`gameTicketSource`). Server-side minting lives in + * `@hops-ops/distributed/sveltekit/game/server`. + */ +export { + GameState, + createGameState, + gameTicketSource, + useGame, + type GameEventList, + type GameLatest, + type GameStateOptions, + type GameStateSource, + type GameStatus, + type GameTicketSourceOptions, + type UseGameOptions +} from './state.js'; diff --git a/js/src/sveltekit/game/server.ts b/js/src/sveltekit/game/server.ts new file mode 100644 index 000000000..a7a198342 --- /dev/null +++ b/js/src/sveltekit/game/server.ts @@ -0,0 +1,418 @@ +/** + * Server-only SvelteKit helpers for `distributed_game` zones: + * `createGameTicketHandler` turns the app's verified session into a + * single-use zone admission ticket (`POST` route), and `mintGameTicket` + * signs one directly. Import only from `+server.ts` / `+page.server.ts` / + * `$lib/server`: the handler holds the zone servers' shared secret. + */ +import { + MAX_GAME_TICKET_TTL_SECONDS, + MIN_GAME_TICKET_SECRET_BYTES, + mintGameTicket, + type GameTicketRole, + type GameTicketSecret +} from './ticket.js'; + +export { + MAX_GAME_TICKET_TTL_SECONDS, + MIN_GAME_TICKET_SECRET_BYTES, + mintGameTicket, + type GameTicketRole, + type GameTicketSecret, + type MintGameTicketOptions, + type MintedGameTicket +} from './ticket.js'; + +const MAX_BODY_BYTES = 1024; +const BODY_KEYS = new Set(['zone', 'role']); +const ROLES: readonly GameTicketRole[] = ['player', 'observer']; + +/** The subset of a SvelteKit `RequestEvent` the handler reads. */ +export type GameTicketRequestEvent = Readonly<{ + request: Request; + url: URL; +}>; + +/** Session shape read by the default `principal` / `name` (Auth.js-compatible). */ +export type GameTicketSessionLike = { + user?: { + id?: string | null; + name?: string | null; + username?: string | null; + } | null; +} | null | undefined; + +export type GameTicketZoneContext = Readonly<{ + event: TEvent; + session: TSession; + /** Verified principal from the session. */ + principal: string; + /** Zone the browser is connecting to (a hint; undefined for a page load). */ + requested: string | undefined; + role: GameTicketRole; +}>; + +/** Sliding-window limiter; `take` returns false when the key is over budget. */ +export type GameTicketRateLimiter = Readonly<{ + take(key: string, now: number): boolean; +}>; + +export type GameTicketRateLimit = + | false + | Readonly<{ max: number; windowMs: number }> + | GameTicketRateLimiter; + +export type CreateGameTicketHandlerOptions = Readonly<{ + /** + * The zone servers' shared HS256 secret (≥ 32 bytes), or a function read + * on every request (e.g. from `$env/dynamic/private`). Missing → 503. + */ + secret: GameTicketSecret | (() => GameTicketSecret | undefined); + /** + * The app's verified session — the same source the GraphQL side uses + * (`createDistributedSvelteKitServer({ getSession })`), e.g. + * `({ locals }) => locals.auth()`. + */ + getSession(event: TEvent): TSession | null | undefined | Promise; + /** Principal from the verified session. Default `session.user.id`. */ + principal?(session: TSession, event: TEvent): string | null | undefined; + /** Display name for the ticket. Default `session.user.name ?? username`. */ + name?(session: TSession, event: TEvent): string | null | undefined; + /** + * The zone this principal may join, decided on the server (ownership, + * party, last position…). `requested` is only a hint from the browser: + * returning another zone answers 409 with the server's choice; returning + * undefined answers 403. + */ + zone( + context: GameTicketZoneContext + ): string | null | undefined | Promise; + /** Roles a browser may ask for. Default both (`observer` owns no player). */ + roles?: readonly GameTicketRole[]; + /** Ticket lifetime in seconds (1..=300). Default 60. */ + ttlSeconds?: number; + /** Per-principal limit. Default 10 tickets per minute; `false` disables. */ + rateLimit?: GameTicketRateLimit; + /** Extra origins allowed besides the request URL's own (e.g. a dev proxy). */ + allowedOrigins?: readonly string[]; + /** Clock in Unix milliseconds (tests). */ + now?(): number; +}>; + +export type ResolvedGameTicketZone = Readonly<{ + principal: string; + zone: string; + session: TSession; +}>; + +/** A SvelteKit `RequestHandler` (export it as `POST`) plus a load-time resolver. */ +export type GameTicketHandler = (( + event: TEvent +) => Promise) & + Readonly<{ + /** + * Principal and server-chosen zone for a page `load` (no ticket, no + * rate limit); undefined without a session or zone. + */ + resolve(event: TEvent): Promise | undefined>; + }>; + +/** Response body of a successful ticket request. */ +export type GameTicketResponse = Readonly<{ + ticket: string; + zone: string; + role: GameTicketRole; + /** Unix milliseconds. */ + expiresAt: number; +}>; + +class TicketRefusal extends Error { + readonly status: number; + readonly code: string; + readonly extra: Readonly>; + + constructor(status: number, code: string, message: string, extra: Readonly> = {}) { + super(message); + this.status = status; + this.code = code; + this.extra = extra; + } +} + +function json(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { + status, + headers: { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff' + } + }); +} + +/** In-memory sliding window per key (one process; use a shared store behind a load balancer). */ +export function createGameTicketRateLimiter(max: number, windowMs: number): GameTicketRateLimiter { + if (!Number.isSafeInteger(max) || max < 1 || !Number.isFinite(windowMs) || windowMs <= 0) { + throw new TypeError('game ticket rate limit needs max >= 1 and windowMs > 0'); + } + const starts = new Map(); + return Object.freeze({ + take(key: string, now: number): boolean { + const since = now - windowMs; + if (starts.size > 10_000) { + for (const [existing, times] of starts) { + if (times.every((at) => at <= since)) starts.delete(existing); + } + } + const recent = (starts.get(key) ?? []).filter((at) => at > since); + if (recent.length >= max) { + starts.set(key, recent); + return false; + } + recent.push(now); + starts.set(key, recent); + return true; + } + }); +} + +function limiterFrom(option: GameTicketRateLimit | undefined): GameTicketRateLimiter | undefined { + if (option === false) return undefined; + if (option === undefined) return createGameTicketRateLimiter(10, 60_000); + if ('take' in option && typeof option.take === 'function') return option; + const { max, windowMs } = option as Readonly<{ max: number; windowMs: number }>; + return createGameTicketRateLimiter(max, windowMs); +} + +function defaultPrincipal(session: unknown): string | undefined { + const id = (session as GameTicketSessionLike)?.user?.id; + return typeof id === 'string' && id.length > 0 ? id : undefined; +} + +function defaultName(session: unknown): string | undefined { + const user = (session as GameTicketSessionLike)?.user; + const name = user?.name ?? user?.username; + return typeof name === 'string' && name.trim().length > 0 ? name : undefined; +} + +function checkOrigin(request: Request, url: URL, allowed: ReadonlySet): void { + const origin = request.headers.get('origin'); + if (origin === null || (origin !== url.origin && !allowed.has(origin))) { + throw new TicketRefusal(403, 'cross_origin', 'Ticket requests must come from this site.'); + } + // Browsers that send Fetch Metadata say so explicitly. + const site = request.headers.get('sec-fetch-site'); + if (site !== null && site !== 'same-origin' && !allowed.has(origin)) { + throw new TicketRefusal(403, 'cross_origin', 'Ticket requests must come from this site.'); + } +} + +async function readBody(request: Request): Promise<{ zone?: string; role?: GameTicketRole }> { + const length = request.headers.get('content-length'); + if (length !== null && Number(length) > MAX_BODY_BYTES) { + throw new TicketRefusal(413, 'body_too_large', 'Ticket request body is too large.'); + } + if (request.body === null) return {}; + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > MAX_BODY_BYTES) { + await reader.cancel().catch(() => undefined); + throw new TicketRefusal(413, 'body_too_large', 'Ticket request body is too large.'); + } + chunks.push(value); + } + if (total === 0) return {}; + const contentType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase(); + if (contentType !== 'application/json') { + throw new TicketRefusal(415, 'unsupported_media_type', 'Send the ticket request as JSON.'); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + let parsed: unknown; + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + throw new TicketRefusal(400, 'invalid_body', 'Ticket request body is not valid JSON.'); + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new TicketRefusal(400, 'invalid_body', 'Ticket request body must be an object.'); + } + const body = parsed as Record; + for (const key of Object.keys(body)) { + // Identity, ownership and rewards are never caller input. + if (!BODY_KEYS.has(key)) { + throw new TicketRefusal(400, 'unexpected_field', `Unexpected ticket request field \`${key}\`.`); + } + } + const result: { zone?: string; role?: GameTicketRole } = {}; + if (body.zone !== undefined) { + if (typeof body.zone !== 'string' || body.zone.length === 0 || body.zone.length > 128) { + throw new TicketRefusal(400, 'invalid_zone', 'zone must be a short string.'); + } + result.zone = body.zone; + } + if (body.role !== undefined) { + if (body.role !== 'player' && body.role !== 'observer') { + throw new TicketRefusal(400, 'invalid_role', 'role must be player or observer.'); + } + result.role = body.role; + } + return result; +} + +/** + * A SvelteKit `POST` handler that mints a `distributed_game` admission + * ticket for the **verified session's** principal and the zone **the server + * chooses**. The request body may only carry `{ zone?, role? }` hints + * (unknown fields → 400); identity, zone ownership and rewards are never + * accepted from it. Every response is `cache-control: no-store`. + * + * ```ts + * // src/lib/server/game.ts + * export const tickets = createGameTicketHandler({ + * secret: () => env.GAME_TICKET_SECRET, + * getSession: ({ locals }) => locals.auth(), + * zone: ({ principal }) => zoneOwnedBy(principal) + * }); + * // src/routes/api/game/ticket/+server.ts + * export const POST = tickets; + * ``` + */ +export function createGameTicketHandler( + options: CreateGameTicketHandlerOptions +): GameTicketHandler { + if (options === null || typeof options !== 'object') { + throw new TypeError('createGameTicketHandler requires options'); + } + if (typeof options.getSession !== 'function' || typeof options.zone !== 'function') { + throw new TypeError('createGameTicketHandler requires getSession and zone'); + } + const ttlSeconds = options.ttlSeconds ?? 60; + if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > MAX_GAME_TICKET_TTL_SECONDS) { + throw new TypeError(`ttlSeconds must be 1..=${MAX_GAME_TICKET_TTL_SECONDS}`); + } + const roles = new Set(options.roles ?? ROLES); + for (const role of roles) { + if (!ROLES.includes(role)) throw new TypeError(`unknown game ticket role ${String(role)}`); + } + const allowedOrigins = new Set( + (options.allowedOrigins ?? []).map((origin) => { + const parsed = new URL(origin); + if (parsed.origin !== origin) { + throw new TypeError(`allowedOrigins entry ${origin} must be a bare origin`); + } + return origin; + }) + ); + const limiter = limiterFrom(options.rateLimit); + const now = options.now ?? Date.now; + const principalOf = options.principal ?? defaultPrincipal; + const nameOf = options.name ?? defaultName; + + const authenticate = async (event: TEvent): Promise<{ session: TSession; principal: string } | undefined> => { + let session: TSession | null | undefined; + try { + session = await options.getSession(event); + } catch { + return undefined; + } + if (session === null || session === undefined) return undefined; + const principal = principalOf(session, event); + if (typeof principal !== 'string' || principal.length === 0) return undefined; + return { session, principal }; + }; + + const chooseZone = async ( + event: TEvent, + session: TSession, + principal: string, + requested: string | undefined, + role: GameTicketRole + ): Promise => { + const zone = await options.zone({ event, session, principal, requested, role }); + return typeof zone === 'string' && zone.length > 0 ? zone : undefined; + }; + + const handler = async (event: TEvent): Promise => { + try { + if (event.request.method !== 'POST') { + throw new TicketRefusal(405, 'method_not_allowed', 'Use POST.'); + } + checkOrigin(event.request, event.url, allowedOrigins); + const verified = await authenticate(event); + if (verified === undefined) { + throw new TicketRefusal(401, 'unauthenticated', 'Sign in to join the game.'); + } + if (limiter !== undefined && !limiter.take(verified.principal, now())) { + throw new TicketRefusal(429, 'rate_limited', 'Too many ticket requests; wait a moment.'); + } + const body = await readBody(event.request); + const role = body.role ?? 'player'; + if (!roles.has(role)) { + throw new TicketRefusal(403, 'role_not_allowed', `Role ${role} is not allowed here.`); + } + const zone = await chooseZone(event, verified.session, verified.principal, body.zone, role); + if (zone === undefined) { + throw new TicketRefusal(403, 'no_zone', 'There is no zone for you to join.'); + } + if (body.zone !== undefined && body.zone !== zone) { + throw new TicketRefusal(409, 'zone_mismatch', 'Join the zone the server assigned.', { zone }); + } + let secret: GameTicketSecret | undefined; + try { + secret = typeof options.secret === 'function' ? options.secret() : options.secret; + } catch { + secret = undefined; + } + const secretLength = + typeof secret === 'string' ? new TextEncoder().encode(secret).byteLength : secret?.byteLength ?? 0; + if (secret === undefined || secretLength < MIN_GAME_TICKET_SECRET_BYTES) { + throw new TicketRefusal(503, 'not_configured', 'The game connection is not configured.'); + } + const name = nameOf(verified.session, event) ?? undefined; + const minted = await mintGameTicket({ + secret, + principal: verified.principal, + zone, + role, + ...(name === undefined ? {} : { name }), + ttlSeconds, + now: now() + }); + const response: GameTicketResponse = { + ticket: minted.ticket, + zone: minted.zone, + role: minted.role, + expiresAt: minted.expiresAt + }; + return json(200, response); + } catch (error) { + if (error instanceof TicketRefusal) { + return json(error.status, { error: error.code, message: error.message, ...error.extra }); + } + if (error instanceof TypeError) { + // Claim values the zone server would refuse (e.g. an oversize principal). + return json(400, { error: 'invalid_claims', message: 'The ticket could not be issued.' }); + } + throw error; + } + }; + + return Object.assign(handler, { + async resolve(event: TEvent): Promise | undefined> { + const verified = await authenticate(event); + if (verified === undefined) return undefined; + const zone = await chooseZone(event, verified.session, verified.principal, undefined, 'player'); + return zone === undefined ? undefined : Object.freeze({ ...verified, zone }); + } + }); +} diff --git a/js/src/sveltekit/game/state.ts b/js/src/sveltekit/game/state.ts new file mode 100644 index 000000000..e19448a3b --- /dev/null +++ b/js/src/sveltekit/game/state.ts @@ -0,0 +1,380 @@ +/** + * Svelte 5 runes adapter for the UI *around* a game: connection status, + * RTT, current zone, prediction readiness and typed event subscriptions + * (decoded with the generated `EVENTS` codecs) for a generated + * `createClient` or a plain `GameClient`. + * + * Every getter is reactive in runes mode (`createSubscriber`), so templates + * and `$derived` read it directly; outside an effect it is a plain read. The + * render loop stays outside Svelte: it reads `state.client.render()` from its + * own `requestAnimationFrame`, never through reactivity. + */ +import { onMount } from 'svelte'; +import { createSubscriber } from 'svelte/reactivity'; + +import { onGameEvent } from '../../game/typed.js'; +import type { + GameEventCodecs, + GameClient, + GameConnection, + GameConnectionState, + GameTicketSource, + WelcomeMessage +} from '../../game/index.js'; + +/** A generated client (`createClient`) or a bare `GameClient`. */ +export type GameStateSource = + | GameClient + | Readonly<{ + client: GameClient; + prediction?: Readonly<{ ready: Promise }> | undefined; + }>; + +export type GameStatus = GameConnectionState; + +/** Latest value of one typed event; `current` is reactive. */ +export type GameLatest = Readonly<{ readonly current: T | undefined }>; + +/** Newest-first bounded list of one typed event; `items` is reactive. */ +export type GameEventList = Readonly<{ readonly items: readonly T[] }>; + +export type GameStateOptions = Readonly<{ + /** + * The surface's event codecs (generated `EVENTS`): types `latest`, + * `events` and `on` by event name. + */ + events?: GameEventCodecs; + /** Report errors thrown while connecting (default: kept in `error`). */ + onConnectError?: (error: unknown) => void; +}>; + +/** A value whose reads subscribe the active Svelte effect. */ +class Cell { + #value: T; + readonly #updates = new Set<() => void>(); + readonly #subscribe = createSubscriber((update) => { + this.#updates.add(update); + return () => { + this.#updates.delete(update); + }; + }); + + constructor(value: T) { + this.#value = value; + } + + get(): T { + this.#subscribe(); + return this.#value; + } + + peek(): T { + return this.#value; + } + + set(value: T): void { + if (Object.is(value, this.#value)) return; + this.#value = value; + for (const update of [...this.#updates]) update(); + } +} + +type AnySource = GameStateSource; + +function clientOf(source: AnySource): GameClient { + return 'client' in source && typeof source.client === 'object' ? source.client : (source as GameClient); +} + +function describe(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Reactive state for one game client. Create it during component setup; + * the client itself is built lazily by `connect` (so nothing runs during + * SSR) or adopted from `source`. + */ +export class GameState> { + readonly #factory: () => TSource; + readonly #options: GameStateOptions; + readonly #source = new Cell(undefined); + readonly #status = new Cell('idle'); + readonly #zone = new Cell(undefined); + readonly #rtt = new Cell(undefined); + readonly #jitter = new Cell(undefined); + readonly #predictionReady = new Cell(false); + readonly #error = new Cell(undefined); + readonly #attachers: Array<(source: TSource) => () => void> = []; + readonly #disposers: Array<() => void> = []; + #connectionOffs: Array<() => void> = []; + #disposed = false; + + constructor(source: TSource | (() => TSource), options: GameStateOptions = {}) { + this.#factory = typeof source === 'function' ? (source as () => TSource) : () => source; + this.#options = options; + } + + /** The generated client (or `GameClient`) once created. */ + get source(): TSource | undefined { + return this.#source.get(); + } + + /** The underlying `GameClient` once created (render loops read `render()` from it). */ + get client(): GameClient | undefined { + const source = this.#source.get(); + return source === undefined ? undefined : clientOf(source); + } + + /** Authority connection state: `idle` → `connecting` → `open` (→ `reconnecting` …). */ + get status(): GameStatus { + return this.#status.get(); + } + + /** True while the authority connection is open. */ + get connected(): boolean { + return this.#status.get() === 'open'; + } + + /** Zone the player is in (follows handoffs). */ + get zone(): string | undefined { + return this.#zone.get(); + } + + /** Round-trip time of the authority connection (ms), after the first pong. */ + get rttMs(): number | undefined { + return this.#rtt.get(); + } + + /** RTT jitter estimate (ms). */ + get jitterMs(): number | undefined { + return this.#jitter.get(); + } + + /** True once the compiled prediction step is loaded (false without prediction). */ + get predictionReady(): boolean { + return this.#predictionReady.get(); + } + + /** Last refusal, kick or connection failure, cleared by the next Welcome. */ + get error(): string | undefined { + return this.#error.get(); + } + + /** Latest value of a typed event. */ + latest(name: K): GameLatest { + const cell = new Cell(undefined); + this.#subscribeEvent(name, (value) => cell.set(value)); + return Object.freeze({ + get current() { + return cell.get(); + } + }); + } + + /** The last `limit` values of a typed event, newest first. */ + events( + name: K, + options: Readonly<{ limit?: number }> = {} + ): GameEventList { + const limit = options.limit ?? 20; + if (!Number.isSafeInteger(limit) || limit < 1) throw new TypeError('events limit must be >= 1'); + const cell = new Cell(Object.freeze([])); + this.#subscribeEvent(name, (value) => { + cell.set(Object.freeze([value, ...cell.peek()].slice(0, limit))); + }); + return Object.freeze({ + get items() { + return cell.get(); + } + }); + } + + /** Subscribe a callback to a typed event (unsubscribed by `dispose`). */ + on(name: K, handler: (value: TEvents[K], zoneId: string) => void): () => void { + return this.#subscribeEvent(name, handler); + } + + /** Create the client if needed and join `zone`. */ + async connect(zone: string): Promise { + if (this.#disposed) throw new Error('GameState is disposed'); + const source = this.#ensureSource(); + const client = clientOf(source); + this.#error.set(undefined); + this.#status.set('connecting'); + const pending = client.connect(zone); + this.#watchConnection(client.zone(zone)?.connection); + try { + return await pending; + } catch (error) { + if (!this.#disposed) { + this.#error.set(describe(error)); + this.#status.set(client.zone(zone)?.connection.state ?? 'closed'); + } + this.#options.onConnectError?.(error); + throw error; + } + } + + /** Close every connection and drop every subscription (component destroy / navigation). */ + dispose(): void { + if (this.#disposed) return; + this.#disposed = true; + for (const off of this.#connectionOffs) off(); + this.#connectionOffs = []; + for (const dispose of this.#disposers.splice(0)) dispose(); + const source = this.#source.peek(); + if (source !== undefined) clientOf(source).close(); + this.#status.set('closed'); + } + + #ensureSource(): TSource { + const existing = this.#source.peek(); + if (existing !== undefined) return existing; + const source = this.#factory(); + const client = clientOf(source); + this.#disposers.push( + client.on('authority', (zoneId) => { + this.#zone.set(zoneId); + this.#watchConnection(client.zone(zoneId)?.connection); + }), + client.on('welcome', (zoneId) => { + if (client.authority?.zoneId === zoneId) this.#error.set(undefined); + }), + client.on('error', (zoneId, message) => { + if (client.authority === undefined || client.authority.zoneId === zoneId) { + this.#error.set(message.message || `error ${message.code}`); + } + }), + client.on('kick', (_zoneId, message) => { + this.#error.set(message.message || `kicked (${message.code})`); + }) + ); + const prediction = 'client' in source ? source.prediction : undefined; + prediction?.ready.then( + () => this.#predictionReady.set(true), + (error: unknown) => this.#error.set(`prediction unavailable: ${describe(error)}`) + ); + for (const attach of this.#attachers) this.#disposers.push(attach(source)); + this.#source.set(source); + return source; + } + + #watchConnection(connection: GameConnection | undefined): void { + if (connection === undefined) return; + for (const off of this.#connectionOffs) off(); + this.#status.set(connection.state); + this.#connectionOffs = [ + connection.on('state', (state) => this.#status.set(state)), + connection.on('pong', ({ rtt, jitter }) => { + this.#rtt.set(Math.round(rtt)); + this.#jitter.set(Math.round(jitter)); + }) + ]; + } + + #subscribeEvent( + name: K, + handler: (value: TEvents[K], zoneId: string) => void + ): () => void { + const codecs = this.#options.events; + if (codecs === undefined || codecs[name] === undefined) { + throw new TypeError(`unknown game event \`${name}\`: pass the generated EVENTS as \`events\``); + } + let off: (() => void) | undefined; + let cancelled = false; + const attach = (source: TSource): (() => void) => { + if (cancelled) return () => undefined; + off = onGameEvent(clientOf(source), codecs, name, handler); + return () => off?.(); + }; + const existing = this.#source.peek(); + if (existing === undefined) { + this.#attachers.push(attach); + } else { + this.#disposers.push(attach(existing)); + } + return () => { + cancelled = true; + off?.(); + }; + } +} + +/** Reactive state for `source` (or a factory, called on the first `connect`). */ +export function createGameState>( + source: TSource | (() => TSource), + options?: GameStateOptions +): GameState { + return new GameState(source, options); +} + +export type UseGameOptions = GameStateOptions & + Readonly<{ + /** Zone to join on mount (e.g. from the page's server `load`). */ + zone: string | (() => string); + }>; + +/** + * `createGameState` bound to the component lifecycle: the client is created + * and joins `zone` on mount (browser only) and is closed on destroy, which + * includes navigating away. Call it during component initialisation. + * + * ```svelte + * + *

    {game.status} · {game.rttMs ?? '–'} ms · XP {profile.current?.xp ?? 0}

    + * ``` + */ +export function useGame>( + factory: () => TSource, + options: UseGameOptions +): GameState { + const state = new GameState(factory, options); + onMount(() => { + const zone = typeof options.zone === 'function' ? options.zone() : options.zone; + state.connect(zone).catch(() => undefined); + return () => state.dispose(); + }); + return state; +} + +export type GameTicketSourceOptions = Readonly<{ + /** Same-origin ticket route (`createGameTicketHandler`). Default `/api/game/ticket`. */ + endpoint?: string; + fetch?: typeof fetch; +}>; + +/** + * `GameClient` ticket source backed by a `createGameTicketHandler` route: + * POSTs `{ zone, role }` with the session cookie; identity comes from the + * server session, never from this request. + */ +export function gameTicketSource(options: GameTicketSourceOptions = {}): GameTicketSource { + const endpoint = options.endpoint ?? '/api/game/ticket'; + return async ({ zoneId, role }) => { + const request = options.fetch ?? globalThis.fetch; + const response = await request(endpoint, { + method: 'POST', + credentials: 'same-origin', + cache: 'no-store', + headers: { 'content-type': 'application/json', accept: 'application/json' }, + body: JSON.stringify({ zone: zoneId, role }) + }); + let body: { ticket?: unknown; error?: unknown; message?: unknown } = {}; + try { + body = (await response.json()) as typeof body; + } catch { + // Non-JSON error page; reported by status below. + } + if (!response.ok || typeof body.ticket !== 'string') { + const reason = typeof body.message === 'string' ? body.message : `HTTP ${response.status}`; + throw new Error(`game ticket refused: ${reason}`); + } + return body.ticket; + }; +} diff --git a/js/src/sveltekit/game/ticket.ts b/js/src/sveltekit/game/ticket.ts new file mode 100644 index 000000000..10a473baa --- /dev/null +++ b/js/src/sveltekit/game/ticket.ts @@ -0,0 +1,156 @@ +/** + * `distributed_game` admission tickets minted on the web server + * (`distributed_game/PROTOCOL.md` §8): a compact HS256 JWT over + * `{sub, zone, exp, nonce, role, name?}`, verified by the zone server's + * `TicketKey`. WebCrypto only, so it runs in Node 20+, Deno, Bun and Workers; + * it must only ever run where the shared secret lives (a server route). + */ + +/** Smallest accepted HS256 secret (bytes); the Rust demos use 32+ as well. */ +export const MIN_GAME_TICKET_SECRET_BYTES = 32; +/** Longest accepted ticket lifetime (tickets are single use and short-lived). */ +export const MAX_GAME_TICKET_TTL_SECONDS = 300; + +const MAX_PRINCIPAL_BYTES = 256; +const MAX_ZONE_BYTES = 128; +const MAX_NAME_CHARS = 64; +const CONTROL = /[\u0000-\u001f\u007f]/; +const CONTROLS = /[\u0000-\u001f\u007f]/g; +const encoder = new TextEncoder(); + +export type GameTicketRole = 'player' | 'observer'; + +export type GameTicketSecret = string | Uint8Array; + +export type MintGameTicketOptions = Readonly<{ + /** Shared HS256 secret (the zone server's `TicketKey`); at least 32 bytes. */ + secret: GameTicketSecret; + /** Verified principal (`sub`): the only identity the zone ever sees. */ + principal: string; + /** Zone the ticket admits to; must equal the route zone. */ + zone: string; + /** Default `player`. */ + role?: GameTicketRole; + /** Display name vouched for by this issuer (never identity). */ + name?: string; + /** Lifetime in seconds (1..=300, default 60). */ + ttlSeconds?: number; + /** Clock in Unix milliseconds (tests). Default `Date.now()`. */ + now?: number; + /** Single-use replay key (tests). Default `crypto.randomUUID()`. */ + nonce?: string; +}>; + +export type MintedGameTicket = Readonly<{ + ticket: string; + zone: string; + role: GameTicketRole; + /** Unix milliseconds. */ + expiresAt: number; + nonce: string; +}>; + +function secretBytes(secret: GameTicketSecret): Uint8Array { + const bytes = typeof secret === 'string' ? encoder.encode(secret) : secret; + if (!(bytes instanceof Uint8Array) || bytes.byteLength < MIN_GAME_TICKET_SECRET_BYTES) { + throw new TypeError( + `game ticket secret must be at least ${MIN_GAME_TICKET_SECRET_BYTES} bytes` + ); + } + return bytes; +} + +function boundedText(value: unknown, label: string, maxBytes: number): string { + if ( + typeof value !== 'string' || + value.length === 0 || + value !== value.trim() || + CONTROL.test(value) || + encoder.encode(value).byteLength > maxBytes + ) { + throw new TypeError(`game ticket ${label} must be 1..=${maxBytes} bytes of trimmed text`); + } + return value; +} + +/** Unpadded base64url (RFC 7515 §2). */ +export function base64url(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} + +const keys = new WeakMap>(); +const stringKeys = new Map>(); + +function hmacKey(secret: GameTicketSecret): Promise { + const bytes = secretBytes(secret); + const cached = typeof secret === 'string' ? stringKeys.get(secret) : keys.get(bytes); + if (cached !== undefined) return cached; + const key = globalThis.crypto.subtle.importKey( + 'raw', + bytes as Uint8Array, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ); + if (typeof secret === 'string') { + // Bounded: a process normally holds one or two secrets (rotation). + if (stringKeys.size >= 8) stringKeys.clear(); + stringKeys.set(secret, key); + } else { + keys.set(bytes, key); + } + return key; +} + +/** Sign an arbitrary claims object as a compact HS256 JWT. */ +export async function signHs256( + secret: GameTicketSecret, + claims: Readonly> +): Promise { + const header = base64url(encoder.encode('{"alg":"HS256","typ":"JWT"}')); + const payload = base64url(encoder.encode(JSON.stringify(claims))); + const signingInput = `${header}.${payload}`; + const signature = await globalThis.crypto.subtle.sign( + 'HMAC', + await hmacKey(secret), + encoder.encode(signingInput) + ); + return `${signingInput}.${base64url(new Uint8Array(signature))}`; +} + +/** + * Mint a single-use admission ticket the zone server's `TicketKey` accepts. + * Throws `TypeError` on a short secret or malformed claim values. + */ +export async function mintGameTicket(options: MintGameTicketOptions): Promise { + const principal = boundedText(options.principal, 'principal', MAX_PRINCIPAL_BYTES); + const zone = boundedText(options.zone, 'zone', MAX_ZONE_BYTES); + const role = options.role ?? 'player'; + if (role !== 'player' && role !== 'observer') { + throw new TypeError('game ticket role must be player or observer'); + } + const ttl = options.ttlSeconds ?? 60; + if (!Number.isSafeInteger(ttl) || ttl < 1 || ttl > MAX_GAME_TICKET_TTL_SECONDS) { + throw new TypeError(`game ticket ttlSeconds must be 1..=${MAX_GAME_TICKET_TTL_SECONDS}`); + } + const now = options.now ?? Date.now(); + if (!Number.isFinite(now) || now < 0) throw new TypeError('game ticket clock is invalid'); + const nonce = boundedText(options.nonce ?? globalThis.crypto.randomUUID(), 'nonce', 128); + let name: string | undefined; + if (options.name !== undefined) { + const trimmed = [...options.name.replace(CONTROLS, '').trim()].slice(0, MAX_NAME_CHARS).join(''); + name = trimmed.length === 0 ? undefined : trimmed; + } + const exp = Math.floor(now / 1000) + ttl; + const ticket = await signHs256(options.secret, { + sub: principal, + zone, + exp, + nonce, + role, + ...(name === undefined ? {} : { name }) + }); + return Object.freeze({ ticket, zone, role, expiresAt: exp * 1000, nonce }); +} diff --git a/js/tests/sveltekit-game.test.mjs b/js/tests/sveltekit-game.test.mjs new file mode 100644 index 000000000..9806230b6 --- /dev/null +++ b/js/tests/sveltekit-game.test.mjs @@ -0,0 +1,398 @@ +/** + * SvelteKit integration for `distributed_game` zones: + * - `mintGameTicket` reproduces `distributed_game/tests/fixtures/sveltekit_tickets.json` + * byte for byte; the Rust `net_e2e` test admits those tickets on a real + * `GameServer` and refuses the tampered / expired / wrong-zone / replayed + * ones (`UPDATE_GOLDEN=1` rewrites the fixture); + * - `createGameTicketHandler` rejection paths (session, origin, rate limit, + * caller-supplied identity, zone choice, secret); + * - `gameTicketSource`; + * - the runes adapter (`createGameState` reactive in a compiled Svelte + * module under the browser runtime; `useGame` inert during SSR). + */ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHmac } from 'node:crypto'; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import test from 'node:test'; + +import { compile, compileModule } from 'svelte/compiler'; +import { render } from 'svelte/server'; + +import { createGameTicketHandler, mintGameTicket } from '@hops-ops/distributed/sveltekit/game/server'; +import { createGameState, gameTicketSource } from '@hops-ops/distributed/sveltekit/game'; + +const FIXTURE = new URL('../../distributed_game/tests/fixtures/sveltekit_tickets.json', import.meta.url); +const SECRET = 'sveltekit-fixture-secret-0123456789abcdef'; +const TMP = fileURLToPath(new URL('./.tmp-sveltekit-game/', import.meta.url)); + +const decodeClaims = (ticket) => JSON.parse(Buffer.from(ticket.split('.')[1], 'base64url').toString('utf8')); +const signatureValid = (ticket, secret) => { + const [h, p, s] = ticket.split('.'); + return createHmac('sha256', secret).update(`${h}.${p}`).digest('base64url') === s; +}; + +async function fixtureTickets() { + // exp = 4_000_000_000 (year 2096): far future; exp = 300: long expired. + const future = (4_000_000_000 - 300) * 1000; + const valid = await mintGameTicket({ + secret: SECRET, principal: 'session-user-1', zone: 'z-sveltekit', name: 'Ana', + ttlSeconds: 300, now: future, nonce: 'fixture-valid' + }); + const observer = await mintGameTicket({ + secret: SECRET, principal: 'session-user-2', zone: 'z-sveltekit', role: 'observer', + ttlSeconds: 300, now: future, nonce: 'fixture-observer' + }); + const expired = await mintGameTicket({ + secret: SECRET, principal: 'session-user-1', zone: 'z-sveltekit', + ttlSeconds: 300, now: 0, nonce: 'fixture-expired' + }); + const wrongZone = await mintGameTicket({ + secret: SECRET, principal: 'session-user-1', zone: 'z-elsewhere', + ttlSeconds: 300, now: future, nonce: 'fixture-wrong-zone' + }); + // Same signature, payload rewritten to another principal. + const [h, , s] = (await mintGameTicket({ + secret: SECRET, principal: 'session-user-1', zone: 'z-sveltekit', + ttlSeconds: 300, now: future, nonce: 'fixture-tampered' + })).ticket.split('.'); + const forgedClaims = Buffer.from(JSON.stringify({ + sub: 'admin', zone: 'z-sveltekit', exp: 4_000_000_000, nonce: 'fixture-tampered', role: 'player' + })).toString('base64url'); + const otherKey = await mintGameTicket({ + secret: 'a-different-secret-0123456789abcdef!!', principal: 'session-user-1', zone: 'z-sveltekit', + ttlSeconds: 300, now: future, nonce: 'fixture-other-key' + }); + return { + secret: SECRET, + zone: 'z-sveltekit', + valid: { ticket: valid.ticket, principal: 'session-user-1', name: 'Ana', exp: 4_000_000_000, nonce: 'fixture-valid' }, + observer: { ticket: observer.ticket, principal: 'session-user-2' }, + expired: expired.ticket, + wrongZone: wrongZone.ticket, + tampered: `${h}.${forgedClaims}.${s}`, + otherKey: otherKey.ticket + }; +} + +test('mintGameTicket is the PROTOCOL.md §8 format the Rust GameServer admits (fixture)', async () => { + const tickets = await fixtureTickets(); + if (process.env.UPDATE_GOLDEN === '1') { + writeFileSync(FIXTURE, `${JSON.stringify(tickets, null, 2)}\n`); + } + assert.deepEqual(tickets, JSON.parse(readFileSync(FIXTURE, 'utf8')), 'fixture drift: UPDATE_GOLDEN=1'); + const header = JSON.parse(Buffer.from(tickets.valid.ticket.split('.')[0], 'base64url').toString()); + assert.deepEqual(header, { alg: 'HS256', typ: 'JWT' }); + assert.deepEqual(decodeClaims(tickets.valid.ticket), { + sub: 'session-user-1', zone: 'z-sveltekit', exp: 4_000_000_000, nonce: 'fixture-valid', role: 'player', name: 'Ana' + }); + assert.ok(signatureValid(tickets.valid.ticket, SECRET)); + assert.ok(!signatureValid(tickets.tampered, SECRET)); + assert.equal(decodeClaims(tickets.observer.ticket).role, 'observer'); +}); + +test('mintGameTicket rejects short secrets and malformed claims', async () => { + await assert.rejects(mintGameTicket({ secret: 'short', principal: 'p', zone: 'z' }), /at least 32 bytes/); + const secret = SECRET; + await assert.rejects(mintGameTicket({ secret, principal: '', zone: 'z' }), /principal/); + await assert.rejects(mintGameTicket({ secret, principal: 'p\n', zone: 'z' }), /principal/); + await assert.rejects(mintGameTicket({ secret, principal: 'p', zone: 'x'.repeat(129) }), /zone/); + await assert.rejects(mintGameTicket({ secret, principal: 'p', zone: 'z', ttlSeconds: 301 }), /ttlSeconds/); + await assert.rejects(mintGameTicket({ secret, principal: 'p', zone: 'z', role: 'admin' }), /role/); + const minted = await mintGameTicket({ secret, principal: 'p', zone: 'z', name: ' \u0000Bo\u0007b ', now: 1_000_000 }); + assert.equal(decodeClaims(minted.ticket).name, 'Bob'); + assert.equal(minted.expiresAt, (1_000 + 60) * 1000); + const a = await mintGameTicket({ secret, principal: 'p', zone: 'z' }); + const b = await mintGameTicket({ secret, principal: 'p', zone: 'z' }); + assert.notEqual(a.nonce, b.nonce, 'fresh nonce per ticket (single use)'); +}); + +const ORIGIN = 'https://game.example'; + +function harness(overrides = {}) { + let clock = 1_700_000_000_000; + const zones = []; + const handler = createGameTicketHandler({ + secret: SECRET, + getSession: (event) => event.locals.session, + zone: (context) => { + zones.push(context); + return context.principal === 'homeless' ? undefined : `pit-${context.principal}`; + }, + rateLimit: { max: 3, windowMs: 60_000 }, + now: () => clock, + ...overrides + }); + const call = (init = {}) => { + const headers = new Headers(init.headers ?? {}); + if (init.origin !== null) headers.set('origin', init.origin ?? ORIGIN); + if (init.body !== undefined && !headers.has('content-type')) headers.set('content-type', 'application/json'); + const body = init.body === undefined ? undefined : typeof init.body === 'string' ? init.body : JSON.stringify(init.body); + return handler({ + request: new Request(`${ORIGIN}/api/game/ticket`, { method: init.method ?? 'POST', headers, body }), + url: new URL(`${ORIGIN}/api/game/ticket`), + locals: { session: init.session === undefined ? { user: { id: 'u1', name: 'Ana' } } : init.session } + }); + }; + return { handler, call, zones, advance: (ms) => (clock += ms) }; +} + +async function expectStatus(promise, status, error) { + const response = await promise; + assert.equal(response.status, status); + assert.equal(response.headers.get('cache-control'), 'no-store'); + const body = await response.json(); + if (error !== undefined) assert.equal(body.error, error); + return body; +} + +test('ticket handler: principal from the verified session, zone chosen by the server', async () => { + const { call, zones } = harness(); + const body = await expectStatus(call({ body: { zone: 'pit-u1' } }), 200); + assert.equal(body.zone, 'pit-u1'); + assert.equal(body.role, 'player'); + assert.equal(body.expiresAt, (1_700_000_000 + 60) * 1000); + assert.ok(signatureValid(body.ticket, SECRET)); + const claims = decodeClaims(body.ticket); + assert.equal(claims.sub, 'u1'); + assert.equal(claims.zone, 'pit-u1'); + assert.equal(claims.name, 'Ana'); + assert.equal(claims.exp, 1_700_000_000 + 60); + assert.equal(zones.at(-1).requested, 'pit-u1'); + // An empty body asks for the server's zone; observers are allowed by default. + assert.equal((await expectStatus(call({}), 200)).zone, 'pit-u1'); + const observer = await expectStatus(call({ body: { role: 'observer' } }), 200); + assert.equal(decodeClaims(observer.ticket).role, 'observer'); +}); + +test('ticket handler rejects: no session, cross-origin, rate limit, caller-supplied identity', async () => { + const { call, advance } = harness(); + await expectStatus(call({ session: null }), 401, 'unauthenticated'); + await expectStatus(call({ session: { user: { id: '' } } }), 401, 'unauthenticated'); + await expectStatus(call({ origin: 'https://evil.example' }), 403, 'cross_origin'); + await expectStatus(call({ origin: null }), 403, 'cross_origin'); + await expectStatus(call({ headers: { 'sec-fetch-site': 'cross-site' } }), 403, 'cross_origin'); + await expectStatus(call({ method: 'GET' }), 405, 'method_not_allowed'); + + // Identity, ownership and rewards are not request fields. + for (const field of ['principal', 'sub', 'name', 'xp', 'owner']) { + const fresh = harness(); + await expectStatus(fresh.call({ body: { zone: 'pit-u1', [field]: 'admin' } }), 400, 'unexpected_field'); + } + const fresh = harness(); + await expectStatus(fresh.call({ body: 'not json' }), 400, 'invalid_body'); + await expectStatus(fresh.call({ body: '{"zone":"pit-u1"}', headers: { 'content-type': 'text/plain' } }), 415, 'unsupported_media_type'); + await expectStatus(harness().call({ body: { zone: 'x'.repeat(2000) } }), 413, 'body_too_large'); + await expectStatus(harness().call({ body: { role: 'admin' } }), 400, 'invalid_role'); + + // A zone the server did not choose: 409 with the server's choice. + const mismatch = await expectStatus(harness().call({ body: { zone: 'pit-someone-else' } }), 409, 'zone_mismatch'); + assert.equal(mismatch.zone, 'pit-u1'); + await expectStatus(harness().call({ session: { user: { id: 'homeless' } } }), 403, 'no_zone'); + + // 3 per minute per principal (the limit counts refused bodies too). + await expectStatus(call({}), 200); + await expectStatus(call({}), 200); + await expectStatus(call({}), 200); + await expectStatus(call({}), 429, 'rate_limited'); + await expectStatus(call({ session: { user: { id: 'u2' } } }), 200); // per principal + advance(60_001); + await expectStatus(call({}), 200); +}); + +test('ticket handler: secret, roles and origins are server configuration', async () => { + await expectStatus(harness({ secret: () => undefined }).call({}), 503, 'not_configured'); + await expectStatus(harness({ secret: 'too-short' }).call({}), 503, 'not_configured'); + await expectStatus(harness({ roles: ['player'] }).call({ body: { role: 'observer' } }), 403, 'role_not_allowed'); + const proxied = harness({ allowedOrigins: ['http://localhost:5573'] }); + await expectStatus(proxied.call({ origin: 'http://localhost:5573' }), 200); + assert.throws(() => createGameTicketHandler({ secret: SECRET, getSession: () => null, zone: () => 'z', ttlSeconds: 0 }), /ttlSeconds/); + assert.throws(() => createGameTicketHandler({ secret: SECRET, getSession: () => null, zone: () => 'z', allowedOrigins: ['http://a/b'] }), /bare origin/); + assert.throws(() => createGameTicketHandler({ secret: SECRET, getSession: () => null }), /zone/); + // A throwing session source is "no session", not a 500. + await expectStatus(harness({ getSession: () => { throw new Error('jwt'); } }).call({}), 401, 'unauthenticated'); +}); + +test('ticket handler resolve(): the same principal and zone for a page load', async () => { + const { handler } = harness(); + const event = (session) => ({ + request: new Request(`${ORIGIN}/pit`), + url: new URL(`${ORIGIN}/pit`), + locals: { session } + }); + const resolved = await handler.resolve(event({ user: { id: 'u7' } })); + assert.equal(resolved.principal, 'u7'); + assert.equal(resolved.zone, 'pit-u7'); + assert.equal(await handler.resolve(event(null)), undefined); + assert.equal(await handler.resolve(event({ user: { id: 'homeless' } })), undefined); +}); + +test('gameTicketSource posts only the zone and role, and surfaces refusals', async () => { + const requests = []; + const ok = gameTicketSource({ + endpoint: '/t', + fetch: async (url, init) => { + requests.push({ url, init }); + return new Response(JSON.stringify({ ticket: 'T', zone: 'z' }), { status: 200 }); + } + }); + assert.equal(await ok({ zoneId: 'z', role: 'player' }), 'T'); + assert.equal(requests[0].url, '/t'); + assert.equal(requests[0].init.method, 'POST'); + assert.equal(requests[0].init.credentials, 'same-origin'); + assert.deepEqual(JSON.parse(requests[0].init.body), { zone: 'z', role: 'player' }); + const refused = gameTicketSource({ + fetch: async () => new Response(JSON.stringify({ error: 'unauthenticated', message: 'Sign in' }), { status: 401 }) + }); + await assert.rejects(refused({ zoneId: 'z', role: 'player' }), /Sign in/); + const broken = gameTicketSource({ fetch: async () => new Response('', { status: 502 }) }); + await assert.rejects(broken({ zoneId: 'z', role: 'player' }), /HTTP 502/); +}); + +test('runes adapter: reactive status, RTT, zone, prediction, typed events; dispose closes', () => { + // Svelte's reactivity is a no-op under Node's default (server) export + // condition, so the reactive half runs in a child with the browser runtime. + mkdirSync(TMP, { recursive: true }); + try { + const effects = compileModule( + `export function track(read, log) { + return $effect.root(() => { $effect(() => { log.push(read()); }); }); + }`, + { generate: 'client', filename: 'track.svelte.js' } + ); + writeFileSync(`${TMP}/track.mjs`, effects.js.code); + writeFileSync(`${TMP}/run.mjs`, RUNES_SCRIPT); + const output = execFileSync(process.execPath, ['--conditions=browser', `${TMP}/run.mjs`], { + encoding: 'utf8', + cwd: fileURLToPath(new URL('..', import.meta.url)) + }); + assert.match(output, /RUNES OK/); + } finally { + rmSync(TMP, { recursive: true, force: true }); + } +}); + +const RUNES_SCRIPT = ` +import assert from 'node:assert/strict'; +import { flushSync } from 'svelte'; +import { createGameState } from '@hops-ops/distributed/sveltekit/game'; +import { track } from './track.mjs'; + +class Emitter { + listeners = new Map(); + on(type, fn) { const set = this.listeners.get(type) ?? new Set(); set.add(fn); this.listeners.set(type, set); return () => set.delete(fn); } + emit(type, ...args) { for (const fn of [...(this.listeners.get(type) ?? [])]) fn(...args); } +} +class FakeConnection extends Emitter { + state = 'idle'; + set(state) { this.state = state; this.emit('state', state); } +} +class FakeClient extends Emitter { + zones = new Map(); authority = undefined; closed = false; connects = []; + zone(id) { return this.zones.get(id); } + connect(id) { + const connection = new FakeConnection(); + this.zones.set(id, { zoneId: id, connection }); + this.connects.push(id); + connection.set('connecting'); + return new Promise((resolve) => { this.welcome = () => { + connection.set('open'); + this.authority = { zoneId: id, connection }; + this.emit('welcome', id, {}); + this.emit('authority', id, {}); + resolve({ zoneId: id }); + }; }); + } + close() { this.closed = true; for (const z of this.zones.values()) z.connection.set('closed'); } +} + +const EVENTS = { + profile: { id: 2, name: 'profile', decode: (p) => ({ xp: p[0] }), encode: () => new Uint8Array() }, + kill: { id: 3, name: 'kill', decode: (p) => ({ mob: p[0] }), encode: () => new Uint8Array() } +}; +const client = new FakeClient(); +let resolvePrediction; +const prediction = { ready: new Promise((r) => (resolvePrediction = r)) }; +let created = 0; +const game = createGameState(() => { created += 1; return { client, prediction }; }, { events: EVENTS }); +const profile = game.latest('profile'); +const kills = game.events('kill', { limit: 2 }); +assert.equal(created, 0, 'the client is built lazily (never during SSR)'); + +const log = []; +const stop = track(() => [game.status, game.zone, game.rttMs, game.predictionReady, profile.current?.xp, kills.items.map((k) => k.mob).join(',')].join('|'), log); +flushSync(); +assert.equal(log.at(-1), 'idle|||false||'); + +const joined = game.connect('pit-1'); +flushSync(); +assert.equal(created, 1); +assert.equal(log.at(-1), 'connecting|||false||'); +client.welcome(); +await joined; +flushSync(); +assert.equal(log.at(-1), 'open|pit-1||false||'); + +client.zone('pit-1').connection.emit('pong', { rtt: 41.6, offset: 0, jitter: 2.2 }); +resolvePrediction(); +await prediction.ready; await Promise.resolve(); +flushSync(); +assert.equal(log.at(-1), 'open|pit-1|42|true||'); + +client.emit('event', 'pit-1', { typeId: 2, payload: new Uint8Array([25]) }); +client.emit('event', 'pit-1', { typeId: 3, payload: new Uint8Array([7]) }); +client.emit('event', 'pit-1', { typeId: 3, payload: new Uint8Array([8]) }); +client.emit('event', 'pit-1', { typeId: 3, payload: new Uint8Array([9]) }); +client.emit('event', 'pit-1', { typeId: 99, payload: new Uint8Array([1]) }); +flushSync(); +assert.equal(log.at(-1), 'open|pit-1|42|true|25|9,8', 'latest + bounded newest-first list'); + +// Errors from the authority zone are surfaced. +client.emit('error', 'pit-1', { code: 4, message: 'unauthorized' }); +flushSync(); +assert.equal(game.error, 'unauthorized'); + +// Unchanged values do not re-run effects. +const before = log.length; +client.zone('pit-1').connection.emit('pong', { rtt: 42.1, offset: 0, jitter: 2.4 }); +flushSync(); +assert.equal(log.length, before); + +assert.throws(() => game.latest('nope'), /unknown game event/); + +game.dispose(); +flushSync(); +assert.equal(client.closed, true); +assert.equal(log.at(-1).split('|')[0], 'closed'); +// Subscriptions are gone after dispose. +const settled = log.length; +client.emit('event', 'pit-1', { typeId: 2, payload: new Uint8Array([99]) }); +flushSync(); +assert.equal(log.length, settled); +await assert.rejects(game.connect('pit-2'), /disposed/); +stop(); +console.log('RUNES OK'); +`; + +test('useGame does nothing during SSR (no client, no connection)', async () => { + const dir = `${TMP.replace(/\/$/, '')}-ssr`; + mkdirSync(dir, { recursive: true }); + try { + const component = compile( + ` +

    {game.status}|{game.zone ?? '-'}|{game.connected}

    `, + { generate: 'server', filename: 'Game.svelte' } + ); + const file = `${dir}/Game.mjs`; + writeFileSync(file, component.js.code); + const { default: Game } = await import(pathToFileURL(file).href); + const { body } = render(Game); + assert.match(body, /idle\|-\|false/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); From eba59beff88b85cca76722068c2731163cacd961 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:24:35 -0500 Subject: [PATCH 204/484] feat(sveltekit): generate game clients from the Vite plugin A games option on distributedSvelteKit runs game-manifest, game-client and game-wasm on dev start, on Rust changes (full reload when outputs change) and once per build. checkDistributedGames runs game-client --check for CI. Games-only apps run under plain Vite; GraphQL clients stay lifecycle-owned. --- js/scripts/pack-smoke.mjs | 19 ++ js/src/sveltekit/public-vite.ts | 10 +- js/src/sveltekit/vite.ts | 387 +++++++++++++++++++++++++- js/tests/sveltekit-game-vite.test.mjs | 224 +++++++++++++++ 4 files changed, 629 insertions(+), 11 deletions(-) create mode 100644 js/tests/sveltekit-game-vite.test.mjs diff --git a/js/scripts/pack-smoke.mjs b/js/scripts/pack-smoke.mjs index 8995d0057..32b243ecc 100644 --- a/js/scripts/pack-smoke.mjs +++ b/js/scripts/pack-smoke.mjs @@ -85,6 +85,8 @@ function inspectPackageContract(packageJson) { './replica', './replica/lazy', './sveltekit', + './sveltekit/game', + './sveltekit/game/server', './sveltekit/vite' ]); assert.equal( @@ -608,12 +610,29 @@ assert.deepEqual(Object.keys(sveltekitSurface).sort(), [ ]); assert.deepEqual(Object.keys(sveltekitViteSurface).sort(), [ 'analyzeDistributedSvelteKitBoundaries', + 'checkDistributedGames', 'distributedGraphqlProxy', 'distributedSvelteKit', 'distributedSvelteKitAliases', + 'generateDistributedGames', 'validateDistributedSvelteKitBoundaryPlan' ]); assert.equal(typeof sveltekitViteSurface.distributedSvelteKit, 'function'); +const sveltekitGameSurface = await import('@hops-ops/distributed/sveltekit/game'); +assert.deepEqual(Object.keys(sveltekitGameSurface).sort(), [ + 'GameState', + 'createGameState', + 'gameTicketSource', + 'useGame' +]); +const sveltekitGameServerSurface = await import('@hops-ops/distributed/sveltekit/game/server'); +assert.deepEqual(Object.keys(sveltekitGameServerSurface).sort(), [ + 'MAX_GAME_TICKET_TTL_SECONDS', + 'MIN_GAME_TICKET_SECRET_BYTES', + 'createGameTicketHandler', + 'createGameTicketRateLimiter', + 'mintGameTicket' +]); const pageData = createPageDataSessionSource({ session: null, diff --git a/js/src/sveltekit/public-vite.ts b/js/src/sveltekit/public-vite.ts index 496d12d03..ca238c99d 100644 --- a/js/src/sveltekit/public-vite.ts +++ b/js/src/sveltekit/public-vite.ts @@ -7,7 +7,9 @@ import { export { analyzeDistributedSvelteKitBoundaries, + checkDistributedGames, distributedGraphqlProxy, + generateDistributedGames, validateDistributedSvelteKitBoundaryPlan } from './vite.js'; @@ -22,6 +24,8 @@ export type { DistributedSvelteKitBoundaryPlan, DistributedSvelteKitBoundaryRegistration, DistributedSvelteKitClientCompiler, + DistributedGameManifestSource, + DistributedGameSurfaceCompiler, DistributedSvelteKitManifestSource, DistributedSvelteKitViteOptions, DistributedSvelteKitVitePlugin @@ -39,7 +43,11 @@ const requireApplicationLifecycle = (): void => { export function distributedSvelteKit( options: DistributedSvelteKitViteOptions ): DistributedSvelteKitVitePlugin { - requireApplicationLifecycle(); + // GraphQL clients are lifecycle outputs; game surfaces (`games`) are + // generated by the plugin itself, so a games-only app runs under plain Vite. + const gamesOnly = + (options?.clients?.length ?? 0) === 0 && (options?.games?.length ?? 0) > 0; + if (!gamesOnly) requireApplicationLifecycle(); return createDistributedSvelteKitPlugin(options); } diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index 1d72ea99a..b8993eb01 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -28,6 +28,7 @@ import { resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; import { isMainThread } from 'node:worker_threads'; import { @@ -122,6 +123,40 @@ export type DistributedSvelteKitClientCompiler = Readonly<{ out: string; }>; +export type DistributedGameManifestSource = + | string + | Readonly<{ + /** + * Arguments passed to the configured distributed command. The first value + * must be `game-manifest`; stdout (the GameSurface JSON) becomes + * ephemeral compiler input. + */ + args: readonly string[]; + }>; + +/** One `distributed_game` surface: GameSurface → typed client (+ WebAssembly). */ +export type DistributedGameSurfaceCompiler = Readonly<{ + /** Existing GameSurface JSON path, or canonical `distributed game-manifest` argv. */ + manifest: DistributedGameManifestSource; + /** Directory owned by `distributed game-client` (and `game-wasm`'s `wasm/`), relative to `cwd`. */ + out: string; + /** `game-client --import-extension`. Default `ts` (Vite resolves it). */ + importExtension?: 'ts' | 'js' | 'none'; + /** + * `distributed game-wasm` for the zone's `#[predict]` step and + * `#[game_pure]` functions: `'auto'` (default) when the surface declares + * any, using the manifest's `--manifest-path`; `{ manifestPath }` to name + * the Cargo manifest; `false` to skip. + */ + wasm?: 'auto' | false | Readonly<{ manifestPath: string }>; + /** + * Extra Rust roots whose changes regenerate this surface (e.g. a local + * crate holding the predicted step). The manifest crate's `Cargo.toml`, + * `src/` and `crates/` are always watched. + */ + watch?: readonly string[]; +}>; + export type DistributedSvelteKitViteOptions = Readonly<{ /** Project root used for distributed cwd, document globs, and output containment. */ cwd?: string; @@ -139,7 +174,22 @@ export type DistributedSvelteKitViteOptions = Readonly<{ libDir?: string; /** Additional project-local `$name` aliases used by static component imports. */ aliases?: Readonly>; - clients: readonly DistributedSvelteKitClientCompiler[]; + /** GraphQL client surfaces (lifecycle-owned). Optional when `games` is set. */ + clients?: readonly DistributedSvelteKitClientCompiler[]; + /** + * `distributed_game` surfaces generated by this plugin on dev start, on + * Rust changes and on build (`game-manifest` → `game-client` → + * `game-wasm`). Not lifecycle-owned: they run in the Vite process. + */ + games?: readonly DistributedGameSurfaceCompiler[]; +}>; + +type ResolvedGame = Readonly<{ + manifest: DistributedGameManifestSource; + out: string; + importExtension: 'ts' | 'js' | 'none'; + wasm: false | 'auto' | Readonly<{ manifestPath: string }>; + watchRoots: readonly string[]; }>; type ResolvedClient = Readonly<{ @@ -166,6 +216,7 @@ type ResolvedIntegration = Readonly<{ libDir: string; aliases: Readonly>; clients: readonly ResolvedClient[]; + games: readonly ResolvedGame[]; }>; type CompilerCoordinator = { @@ -235,7 +286,7 @@ type RollupWatchContextLike = Readonly<{ export type DistributedSvelteKitVitePlugin = Readonly<{ name: string; enforce: 'pre'; - configResolved(config: Readonly<{ root: string }>): Promise; + configResolved(config: Readonly<{ root: string; command?: 'serve' | 'build' }>): Promise; configureServer(server: ViteServerLike): void; buildStart(this: RollupWatchContextLike): void; resolveId(source: string, importer?: string): string | undefined; @@ -333,6 +384,32 @@ export function distributedSvelteKit( const children = new Set(); const cancellation = new AbortController(); let lock: CompilerLockLease | undefined; + let gamesDirty = false; + let gamesRunning: Promise | undefined; + let gamesChanged = false; + + /** Serialized, coalescing game generation; resolves true when any output changed. */ + const compileGames = (): Promise => { + if (stopped) { + return Promise.reject(new Error('Distributed game compiler is closed')); + } + gamesDirty = true; + if (gamesRunning !== undefined) return gamesRunning; + gamesRunning = (async () => { + gamesChanged = false; + while (gamesDirty && !stopped) { + gamesDirty = false; + const integration = requireResolved(resolved); + if (await generateGames(integration, 'generate', children, cancellation.signal)) { + gamesChanged = true; + } + } + return gamesChanged; + })().finally(() => { + gamesRunning = undefined; + }); + return gamesRunning; + }; const stop = async (): Promise => { if (stopped) return; @@ -345,7 +422,10 @@ export function distributedSvelteKit( }, 1_500); force.unref(); await Promise.race([ - running?.catch(() => undefined) ?? Promise.resolve(), + Promise.all([ + running?.catch(() => undefined), + gamesRunning?.catch(() => undefined) + ]), new Promise((resolvePromise) => { const bounded = setTimeout(resolvePromise, 3_000); bounded.unref(); @@ -411,7 +491,16 @@ export function distributedSvelteKit( * the owning build's physical project lock and duplicate generation. */ if (!isMainThread && process.env.SVELTEKIT_FORK === 'true') return; - if (lifecycleOwnsCompile) return; + if (resolved.games.length > 0) { + // Game surfaces are not lifecycle outputs: generate them here, once + // per build process (SvelteKit's client pass reloads the config). + if (config.command === 'build') { + await onceForBuild(resolved, () => compileGames()); + } else { + await compileGames(); + } + } + if (lifecycleOwnsCompile || resolved.clients.length === 0) return; lock = await acquireCompilerLock(resolved.cwd); try { await compile('Vite startup', true); @@ -428,7 +517,7 @@ export function distributedSvelteKit( if (lifecycleOwnsCompile && activePointer !== undefined) { server.watcher.add(activePointer); } - if (!lifecycleOwnsCompile) { + if (!lifecycleOwnsCompile && integration.clients.length > 0) { const roots = [ integration.routesDir, integration.libDir, @@ -439,13 +528,18 @@ export function distributedSvelteKit( ]; if (roots.length > 0) server.watcher.add(roots); } + const gameRoots = integration.games.flatMap((game) => game.watchRoots); + if (gameRoots.length > 0) server.watcher.add(gameRoots); server.httpServer?.once('close', () => { void stop(); }); }, buildStart(): void { const integration = requireResolved(resolved); - if (lifecycleOwnsCompile) return; + for (const game of integration.games) { + for (const root of game.watchRoots) this.addWatchFile(root); + } + if (lifecycleOwnsCompile || integration.clients.length === 0) return; this.addWatchFile(integration.routesDir); this.addWatchFile(integration.libDir); for (const client of integration.clients) { @@ -533,6 +627,16 @@ export function distributedSvelteKit( // the old virtual modules so that reload resolves the active generation. return []; } + if (isGameInput(context.file, integration)) { + try { + if (await compileGames()) { + context.server.ws.send({ type: 'full-reload', path: '*' }); + } + } catch (error) { + context.server.ws.send({ type: 'error', err: viteError(error) }); + } + if (!isCompilerInput(context.file, integration)) return []; + } if (!isCompilerInput(context.file, integration)) return undefined; if (lifecycleOwnsCompile) return []; try { @@ -561,6 +665,7 @@ export function distributedSvelteKit( }, async watchChange(id): Promise { const integration = requireResolved(resolved); + if (isGameInput(id, integration)) await compileGames(); if (lifecycleOwnsCompile) return; if (isCompilerInput(id, integration)) { await compile(`GraphQL/Svelte watch change ${id}`); @@ -993,9 +1098,14 @@ function resolveIntegration( if (command.length === 0) { throw new TypeError('Distributed SvelteKit command must not be empty'); } - if (!Array.isArray(options.clients) || options.clients.length === 0) { + const configuredClients = options.clients ?? []; + const configuredGames = options.games ?? []; + if (!Array.isArray(configuredClients) || !Array.isArray(configuredGames)) { + throw new TypeError('Distributed SvelteKit clients and games must be arrays'); + } + if (configuredClients.length === 0 && configuredGames.length === 0) { throw new TypeError( - 'Distributed SvelteKit requires at least one client surface' + 'Distributed SvelteKit requires at least one client or game surface' ); } const modules = new Set(); @@ -1012,7 +1122,7 @@ function resolveIntegration( }) ) ); - const clients = options.clients.map((client, index): ResolvedClient => { + const clients = configuredClients.map((client, index): ResolvedClient => { if (client === null || typeof client !== 'object') { throw new TypeError(`Distributed client[${index}] must be an object`); } @@ -1136,7 +1246,8 @@ function resolveIntegration( routesDir, libDir, aliases, - clients: Object.freeze(clients) + clients: Object.freeze(clients), + games: Object.freeze(resolveGames(cwd, configuredGames, outputs)) }); } @@ -1263,6 +1374,7 @@ function manifestWatchRoots( } function isCompilerInput(file: string, integration: ResolvedIntegration): boolean { + if (integration.clients.length === 0) return false; if (isGraphqlInput(file, integration)) return true; const absolute = resolve(integration.cwd, file); const basenameValue = basename(absolute); @@ -2342,3 +2454,258 @@ function viteError(error: unknown): Readonly<{ } return { message: String(error) }; } + +const GAME_EXTENSIONS = new Set(['ts', 'js', 'none']); +const MAX_GAME_TREE_FILES = 2_000; +const MAX_GAME_TREE_BYTES = 64 * 1024 * 1024; + +function resolveGames( + cwd: string, + games: readonly DistributedGameSurfaceCompiler[], + clientOutputs: readonly string[] +): ResolvedGame[] { + const outputs = [...clientOutputs]; + return games.map((game, index): ResolvedGame => { + const label = `Distributed game[${index}]`; + if (game === null || typeof game !== 'object') { + throw new TypeError(`${label} must be an object`); + } + const manifest = game.manifest; + if (typeof manifest === 'string') { + nonempty(manifest, `${label} manifest path`); + } else if ( + manifest === null || + typeof manifest !== 'object' || + !Array.isArray(manifest.args) || + manifest.args[0] !== 'game-manifest' || + manifest.args.some((argument) => typeof argument !== 'string') + ) { + throw new TypeError(`${label} manifest args must begin with game-manifest`); + } + const out = containedPath(cwd, game.out, `${label} out`); + if (out === cwd) throw new TypeError(`${label} cannot use the project root as generated output`); + for (const existing of outputs) { + if (isWithin(existing, out) || isWithin(out, existing)) { + throw new TypeError(`Distributed generated outputs must not overlap: \`${existing}\` and \`${out}\``); + } + } + outputs.push(out); + const importExtension = game.importExtension ?? 'ts'; + if (!GAME_EXTENSIONS.has(importExtension)) { + throw new TypeError(`${label} importExtension must be ts, js or none`); + } + const wasm = game.wasm ?? 'auto'; + let resolvedWasm: ResolvedGame['wasm']; + if (wasm === false || wasm === 'auto') { + resolvedWasm = wasm; + } else if (wasm !== null && typeof wasm === 'object') { + resolvedWasm = Object.freeze({ + manifestPath: resolve(cwd, nonempty(wasm.manifestPath, `${label} wasm.manifestPath`)) + }); + } else { + throw new TypeError(`${label} wasm must be 'auto', false or { manifestPath }`); + } + const extra = (game.watch ?? []).map((root, rootIndex) => + resolve(cwd, nonempty(root, `${label} watch[${rootIndex}]`)) + ); + const wasmRoots = + typeof resolvedWasm === 'object' ? manifestWatchRoots(cwd, resolvedWasm.manifestPath) : []; + const watchRoots = [ + ...new Set([ + ...manifestWatchRoots(cwd, manifest as DistributedSvelteKitManifestSource), + ...wasmRoots, + ...extra.filter((root) => existsSync(root)) + ]) + ].sort(); + return Object.freeze({ + manifest, + out, + importExtension, + wasm: resolvedWasm, + watchRoots: Object.freeze(watchRoots) + }); + }); +} + +/** A Rust source of a game surface (or its Cargo manifest / lockfile). */ +function isGameInput(file: string, integration: ResolvedIntegration): boolean { + if (integration.games.length === 0) return false; + const absolute = resolve(integration.cwd, file); + const name = basename(absolute); + if (!absolute.endsWith('.rs') && name !== 'Cargo.toml' && name !== 'Cargo.lock') return false; + if (absolute.split(sep).includes('target')) return false; + return integration.games.some((game) => + game.watchRoots.some( + (root) => isWithin(root, absolute) || (name === 'Cargo.lock' && isWithin(dirname(root), absolute)) + ) + ); +} + +function gameManifestPath(game: ResolvedGame, cwd: string): string | undefined { + if (typeof game.wasm === 'object') return game.wasm.manifestPath; + if (typeof game.manifest === 'string') return undefined; + const index = game.manifest.args.indexOf('--manifest-path'); + const value = index === -1 ? undefined : game.manifest.args[index + 1]; + return value === undefined ? undefined : resolve(cwd, value); +} + +async function gameTreeDigest(root: string): Promise { + const { createHash } = await import('node:crypto'); + const hash = createHash('sha256'); + const budget = { files: 0, bytes: 0 }; + const walk = async (directory: string): Promise => { + let entries; + try { + entries = await readdir(directory, { withFileTypes: true }); + } catch (error) { + if (isMissing(error)) return; + throw error; + } + entries.sort((a, b) => a.name.localeCompare(b.name)); + for (const entry of entries) { + const path = join(directory, entry.name); + if (entry.isDirectory()) { + await walk(path); + } else if (entry.isFile()) { + budget.files += 1; + const bytes = await readFile(path); + budget.bytes += bytes.byteLength; + if (budget.files > MAX_GAME_TREE_FILES || budget.bytes > MAX_GAME_TREE_BYTES) { + throw new Error(`generated game output ${root} exceeds its size budget`); + } + hash.update(relative(root, path)).update('\0').update(bytes).update('\0'); + } + } + }; + await walk(root); + return hash.digest('hex'); +} + +/** + * Run `game-manifest` → `game-client` (→ `game-wasm`) for every game surface. + * `check` runs `game-client --check` only (the WebAssembly is a build output, + * never committed). Resolves true when any generated output changed. + */ +async function generateGames( + integration: ResolvedIntegration, + mode: 'generate' | 'check', + children: Set, + signal: AbortSignal +): Promise { + let changed = false; + for (const [index, game] of integration.games.entries()) { + throwIfAborted(signal); + const scratch = await mkdtemp(join(tmpdir(), 'distributed-game-')); + try { + let manifest: string; + if (typeof game.manifest === 'string') { + manifest = resolve(integration.cwd, game.manifest); + } else { + const result = await runCommand(integration, [...game.manifest.args], children, signal); + manifest = join(scratch, `surface-${index}.json`); + await writeFile(manifest, result.stdout, { encoding: 'utf8', flag: 'wx' }); + } + let surface: { predict?: unknown; pures?: unknown }; + try { + surface = JSON.parse(await readFile(manifest, 'utf8')) as typeof surface; + } catch (error) { + throw new Error(`distributed game-manifest for ${game.out} did not emit valid JSON`, { + cause: error + }); + } + const before = mode === 'generate' ? await gameTreeDigest(game.out) : ''; + if (mode === 'generate') await mkdir(game.out, { recursive: true }); + await validateNearestExistingParent(integration.cwd, game.out); + await runCommand( + integration, + [ + 'game-client', + '--manifest', + manifest, + '--out', + game.out, + '--import-extension', + game.importExtension, + ...(mode === 'check' ? ['--check'] : []) + ], + children, + signal + ); + const declaresWasm = + (surface.predict !== undefined && surface.predict !== null) || + (Array.isArray(surface.pures) && surface.pures.length > 0); + if (mode === 'generate' && game.wasm !== false && (game.wasm !== 'auto' || declaresWasm)) { + const manifestPath = gameManifestPath(game, integration.cwd); + if (manifestPath === undefined) { + throw new Error( + `Distributed game ${game.out}: game-wasm needs the Cargo manifest; pass wasm: { manifestPath }` + ); + } + await runCommand( + integration, + ['game-wasm', '--manifest', manifest, '--manifest-path', manifestPath, '--out', game.out], + children, + signal + ); + } + if (mode === 'generate' && (await gameTreeDigest(game.out)) !== before) changed = true; + } finally { + await rm(scratch, { recursive: true, force: true }); + } + } + return changed; +} + +const BUILD_GAME_RUNS = Symbol.for('@hops-ops/distributed/sveltekit/game-build-runs/v1'); + +function onceForBuild(integration: ResolvedIntegration, run: () => Promise): Promise { + const scope = globalThis as unknown as Record> | undefined>; + const runs = (scope[BUILD_GAME_RUNS] ??= new Map()); + const key = JSON.stringify([integration.cwd, integration.games]); + let pending = runs.get(key); + if (pending === undefined) { + pending = run(); + runs.set(key, pending); + pending.catch(() => runs.delete(key)); + } + return pending; +} + +async function runGamesOnce( + options: DistributedSvelteKitViteOptions, + mode: 'generate' | 'check' +): Promise { + const integration = resolveIntegration( + { ...options, clients: [] }, + options.cwd ?? process.cwd() + ); + const children = new Set(); + const cancellation = new AbortController(); + const cancel = (): void => { + cancellation.abort(); + for (const child of children) killChild(child, 'SIGTERM'); + }; + process.once('SIGINT', cancel); + process.once('SIGTERM', cancel); + try { + return await generateGames(integration, mode, children, cancellation.signal); + } finally { + process.removeListener('SIGINT', cancel); + process.removeListener('SIGTERM', cancel); + for (const child of children) killChild(child, 'SIGKILL'); + } +} + +/** Generate every configured game surface once (what the plugin does on start). */ +export async function generateDistributedGames( + options: DistributedSvelteKitViteOptions +): Promise { + return runGamesOnce(options, 'generate'); +} + +/** CI: `game-client --check` for every game surface; never writes. */ +export async function checkDistributedGames( + options: DistributedSvelteKitViteOptions +): Promise { + await runGamesOnce(options, 'check'); +} diff --git a/js/tests/sveltekit-game-vite.test.mjs b/js/tests/sveltekit-game-vite.test.mjs new file mode 100644 index 000000000..f57887fde --- /dev/null +++ b/js/tests/sveltekit-game-vite.test.mjs @@ -0,0 +1,224 @@ +/** + * The Vite plugin's `games` option: `game-manifest` → `game-client` → + * `game-wasm` on start, on Rust changes and on build, a `--check` mode for + * CI, and games-only apps outside the application lifecycle. A fake + * `distributed` executable records argv and writes deterministic outputs. + */ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; + +import { distributedSvelteKit } from '../dist/sveltekit/vite.js'; +import { + checkDistributedGames, + distributedSvelteKit as distributedSvelteKitPublic, + generateDistributedGames +} from '../dist/sveltekit/public-vite.js'; + +const FAKE = String.raw` +import { appendFileSync, mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +const args = process.argv.slice(2); +appendFileSync(process.env.FAKE_LOG, JSON.stringify(args) + '\n'); +const opt = (name) => args[args.indexOf(name) + 1]; +const [command] = args; +if (command === 'game-manifest') { + const surface = readFileSync(join(process.env.FAKE_RUST, 'src', 'lib.rs'), 'utf8'); + process.stdout.write(JSON.stringify({ name: 'pit', schemaVersion: 3, ...(surface.includes('predict') ? { predict: { export: 'pit_step' } } : {}), source: surface })); +} else if (command === 'game-client') { + const surface = JSON.parse(readFileSync(opt('--manifest'), 'utf8')); + const out = opt('--out'); + const text = '// generated (' + opt('--import-extension') + ')\nexport const SOURCE = ' + JSON.stringify(surface.source) + ';\n'; + if (args.includes('--check')) { + const current = existsSync(join(out, 'index.ts')) ? readFileSync(join(out, 'index.ts'), 'utf8') : ''; + if (current !== text) { process.stderr.write('drift in ' + out); process.exit(1); } + } else { + mkdirSync(out, { recursive: true }); + writeFileSync(join(out, 'index.ts'), text); + } +} else if (command === 'game-wasm') { + const out = opt('--out'); + mkdirSync(join(out, 'wasm'), { recursive: true }); + writeFileSync(join(out, 'wasm', 'pit.wasm'), readFileSync(join(opt('--manifest-path'), '..', 'src', 'lib.rs'))); +} else { + process.exit(2); +} +`; + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'distributed-game-vite-')); + const app = join(root, 'app'); + const rust = join(root, 'game'); + await mkdir(join(rust, 'src'), { recursive: true }); + await mkdir(join(app, 'src'), { recursive: true }); + await writeFile(join(rust, 'Cargo.toml'), '[package]\nname = "game"\n'); + await writeFile(join(rust, 'src', 'lib.rs'), '// zone v1 with predict\n'); + const fake = join(root, 'fake-distributed.mjs'); + await writeFile(fake, FAKE); + const log = join(root, 'argv.log'); + await writeFile(log, ''); + process.env.FAKE_LOG = log; + process.env.FAKE_RUST = rust; + const options = (game = {}) => ({ + cwd: app, + command: process.execPath, + commandArgs: [fake], + games: [ + { + manifest: { + args: ['game-manifest', '--manifest-path', join(rust, 'Cargo.toml'), '--entrypoint', 'game::pit::game_surface'] + }, + out: 'src/lib/generated/pit', + ...game + } + ] + }); + const calls = async () => + (await readFile(log, 'utf8')).trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)); + return { root, app, rust, options, calls, out: join(app, 'src/lib/generated/pit') }; +} + +test('generateDistributedGames runs game-manifest → game-client → game-wasm, then is a no-op', async () => { + const f = await fixture(); + try { + assert.equal(await generateDistributedGames(f.options()), true); + const argv = await f.calls(); + assert.deepEqual(argv.map((a) => a[0]), ['game-manifest', 'game-client', 'game-wasm']); + assert.deepEqual(argv[1].slice(3), ['--out', f.out, '--import-extension', 'ts']); + assert.equal(argv[2][argv[2].indexOf('--manifest-path') + 1], join(f.rust, 'Cargo.toml')); + assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v1/); + assert.ok(existsSync(join(f.out, 'wasm', 'pit.wasm'))); + assert.equal(await generateDistributedGames(f.options()), false, 'unchanged outputs'); + + // CI check: current → ok; drift → fails without writing; never builds WASM. + await checkDistributedGames(f.options()); + await writeFile(join(f.rust, 'src', 'lib.rs'), '// zone v2 with predict\n'); + await assert.rejects(checkDistributedGames(f.options()), /drift/); + assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v1/); + assert.ok(!(await f.calls()).slice(6).some((a) => a[0] === 'game-wasm')); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test('wasm: auto skips surfaces without a step, false never compiles', async () => { + const f = await fixture(); + try { + await writeFile(join(f.rust, 'src', 'lib.rs'), '// zone without a step\n'); + await generateDistributedGames(f.options()); + assert.deepEqual((await f.calls()).map((a) => a[0]), ['game-manifest', 'game-client']); + await writeFile(join(f.rust, 'src', 'lib.rs'), '// zone with predict\n'); + await generateDistributedGames(f.options({ wasm: false, importExtension: 'js' })); + const argv = await f.calls(); + assert.deepEqual(argv.slice(2).map((a) => a[0]), ['game-manifest', 'game-client']); + assert.equal(argv[3].at(-1), 'js'); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test('invalid game configuration fails before running anything', async () => { + const f = await fixture(); + try { + await assert.rejects( + generateDistributedGames({ ...f.options(), games: [{ manifest: { args: ['client-manifest'] }, out: 'x' }] }), + /must begin with game-manifest/ + ); + await assert.rejects( + generateDistributedGames({ ...f.options(), games: [{ manifest: 'surface.json', out: '../outside' }] }), + /must stay within project root/ + ); + await assert.rejects( + generateDistributedGames({ + ...f.options(), + games: [ + { manifest: 'a.json', out: 'src/gen' }, + { manifest: 'b.json', out: 'src/gen/b' } + ] + }), + /must not overlap/ + ); + await assert.rejects( + generateDistributedGames({ ...f.options(), games: [{ manifest: 'a.json', out: 'x', importExtension: 'mjs' }] }), + /importExtension/ + ); + assert.deepEqual(await f.calls(), []); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test('plugin: generates on start, regenerates on a Rust change and reloads; games-only needs no lifecycle', async () => { + const f = await fixture(); + const previous = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + delete process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + try { + // The public entry accepts a games-only configuration under plain Vite. + const plugin = distributedSvelteKitPublic(f.options({ watch: [join(f.root, 'missing-is-ignored')] })); + await plugin.configResolved({ root: f.app, command: 'serve' }); + assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v1/); + const watched = []; + const sent = []; + const server = { + watcher: { add: (paths) => watched.push(...[paths].flat()) }, + ws: { send: (payload) => sent.push(payload) }, + moduleGraph: { getModuleById: () => undefined, invalidateModule: () => undefined }, + httpServer: { once: () => undefined } + }; + plugin.configureServer(server); + assert.ok(watched.includes(join(f.rust, 'src'))); + assert.ok(watched.includes(join(f.rust, 'Cargo.toml'))); + + // Unrelated files are not game inputs. + assert.equal(await plugin.handleHotUpdate({ file: join(f.app, 'src', 'app.ts'), server }), undefined); + assert.equal(await plugin.handleHotUpdate({ file: join(f.rust, 'target', 'x.rs'), server }), undefined); + + await writeFile(join(f.rust, 'src', 'lib.rs'), '// zone v2 with predict\n'); + assert.deepEqual(await plugin.handleHotUpdate({ file: join(f.rust, 'src', 'lib.rs'), server }), []); + assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v2/); + assert.deepEqual(sent, [{ type: 'full-reload', path: '*' }]); + + // A change that generates the same outputs does not reload. + await plugin.handleHotUpdate({ file: join(f.rust, 'Cargo.toml'), server }); + assert.equal(sent.length, 1); + + // A failing compile is reported to the overlay, not thrown into Vite. + process.env.FAKE_RUST = join(f.root, 'nowhere'); + assert.deepEqual(await plugin.handleHotUpdate({ file: join(f.rust, 'src', 'lib.rs'), server }), []); + assert.equal(sent.at(-1).type, 'error'); + await plugin.closeBundle(); + } finally { + if (previous !== undefined) process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = previous; + await rm(f.root, { recursive: true, force: true }); + } +}); + +test('plugin build: one generation per build process (SvelteKit reloads the config)', async () => { + const f = await fixture(); + try { + const first = distributedSvelteKit(f.options()); + const second = distributedSvelteKit(f.options()); + await first.configResolved({ root: f.app, command: 'build' }); + await second.configResolved({ root: f.app, command: 'build' }); + assert.equal((await f.calls()).filter((a) => a[0] === 'game-client').length, 1); + await first.closeBundle(); + await second.closeBundle(); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test('games-free configuration still requires the lifecycle and a surface', async () => { + const previous = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + delete process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + try { + assert.throws(() => distributedSvelteKitPublic({ clients: [] }), /distributed dev/); + const plugin = distributedSvelteKit({ games: [] }); + await assert.rejects(plugin.configResolved({ root: tmpdir() }), /at least one client or game surface/); + } finally { + if (previous !== undefined) process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = previous; + } +}); From aeb1c0cc26286e0a6216758360d4464bc5134ae3 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:36:54 -0500 Subject: [PATCH 205/484] fix(cli): leave unchanged game-client files untouched Rewriting identical files made dev servers watching the generated directory reload (and drop the game connection) on every Rust change. --- distributed_cli/src/cli.rs | 6 ++++++ distributed_cli/tests/cli_game_client.rs | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index 6028043fd..fff086802 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -2531,6 +2531,12 @@ fn write_game_client(root: &Path, files: &[GeneratedClientFile]) -> Result<(), B } for file in files { let path = root.join(&file.path); + // Leave unchanged files untouched: dev servers watching the + // directory (e.g. the Vite plugin's regeneration on Rust changes) + // would otherwise reload for nothing. + if fs::read(&path).is_ok_and(|current| current == file.contents.as_bytes()) { + continue; + } fs::write(&path, &file.contents) .map_err(|error| format!("write {}: {error}", path.display()))?; } diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs index 9fc85ebcd..5139fb1cf 100644 --- a/distributed_cli/tests/cli_game_client.rs +++ b/distributed_cli/tests/cli_game_client.rs @@ -120,6 +120,15 @@ fn check_mode_detects_drift_and_write_keeps_foreign_files() { .success() ); + // Regenerating identical output does not rewrite (or touch) any file. + let modified = |name: &str| fs::metadata(out.join(name)).unwrap().modified().unwrap(); + let before = modified("schema.ts"); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert_eq!(modified("schema.ts"), before); + fs::write(out.join("events.ts"), "// edited").unwrap(); fs::write( out.join("stale.ts"), From 6ee02935d06e1f902bf74ab455d98cb610d6d382 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:36:55 -0500 Subject: [PATCH 206/484] feat(examples): Mob Pit in SvelteKit with session tickets examples/game/sveltekit uses the three SvelteKit game pieces: Auth.js session tickets (dev sign-in), the Vite plugin generating the mobpit client and WASM step, and a runes HUD next to a canvas loop, with the settled-kill read model from SSR and live zone pushes. run.sh sveltekit starts it; smoke checks codegen, svelte-check, build and Playwright. Mob Pit names players from the ticket name when no guest name exists. --- examples/game/run.sh | 54 +- examples/game/server/src/mobpit/zone.rs | 7 +- examples/game/sveltekit/.gitignore | 5 + examples/game/sveltekit/distributed.config.js | 26 + examples/game/sveltekit/package-lock.json | 2050 +++++++++++++++++ examples/game/sveltekit/package.json | 33 + .../game/sveltekit/scripts/check-games.mjs | 6 + examples/game/sveltekit/src/app.d.ts | 6 + examples/game/sveltekit/src/app.html | 12 + examples/game/sveltekit/src/auth.ts | 55 + examples/game/sveltekit/src/hooks.server.ts | 1 + .../src/lib/generated/mobpit/client.ts | 68 + .../src/lib/generated/mobpit/constants.ts | 14 + .../src/lib/generated/mobpit/events.ts | 332 +++ .../src/lib/generated/mobpit/index.ts | 9 + .../src/lib/generated/mobpit/input.ts | 52 + .../src/lib/generated/mobpit/predict.ts | 51 + .../src/lib/generated/mobpit/schema.ts | 224 ++ .../src/lib/generated/mobpit/surface.json | 958 ++++++++ examples/game/sveltekit/src/lib/pit/loop.ts | 131 ++ .../game/sveltekit/src/lib/server/game.ts | 37 + .../sveltekit/src/routes/+layout.server.ts | 1 + .../game/sveltekit/src/routes/+layout.svelte | 19 + .../game/sveltekit/src/routes/+page.server.ts | 3 + .../game/sveltekit/src/routes/+page.svelte | 25 + .../src/routes/api/game/ticket/+server.ts | 3 + .../sveltekit/src/routes/pit/+page.server.ts | 14 + .../sveltekit/src/routes/pit/+page.svelte | 82 + .../src/routes/signout/+page.server.ts | 3 + examples/game/sveltekit/svelte.config.js | 8 + examples/game/sveltekit/tests/pit.test.mjs | 154 ++ examples/game/sveltekit/tsconfig.json | 17 + examples/game/sveltekit/vite.config.ts | 10 + 33 files changed, 4464 insertions(+), 6 deletions(-) create mode 100644 examples/game/sveltekit/.gitignore create mode 100644 examples/game/sveltekit/distributed.config.js create mode 100644 examples/game/sveltekit/package-lock.json create mode 100644 examples/game/sveltekit/package.json create mode 100644 examples/game/sveltekit/scripts/check-games.mjs create mode 100644 examples/game/sveltekit/src/app.d.ts create mode 100644 examples/game/sveltekit/src/app.html create mode 100644 examples/game/sveltekit/src/auth.ts create mode 100644 examples/game/sveltekit/src/hooks.server.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/client.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/constants.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/events.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/index.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/input.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/predict.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/schema.ts create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/surface.json create mode 100644 examples/game/sveltekit/src/lib/pit/loop.ts create mode 100644 examples/game/sveltekit/src/lib/server/game.ts create mode 100644 examples/game/sveltekit/src/routes/+layout.server.ts create mode 100644 examples/game/sveltekit/src/routes/+layout.svelte create mode 100644 examples/game/sveltekit/src/routes/+page.server.ts create mode 100644 examples/game/sveltekit/src/routes/+page.svelte create mode 100644 examples/game/sveltekit/src/routes/api/game/ticket/+server.ts create mode 100644 examples/game/sveltekit/src/routes/pit/+page.server.ts create mode 100644 examples/game/sveltekit/src/routes/pit/+page.svelte create mode 100644 examples/game/sveltekit/src/routes/signout/+page.server.ts create mode 100644 examples/game/sveltekit/svelte.config.js create mode 100644 examples/game/sveltekit/tests/pit.test.mjs create mode 100644 examples/game/sveltekit/tsconfig.json create mode 100644 examples/game/sveltekit/vite.config.ts diff --git a/examples/game/run.sh b/examples/game/run.sh index 537662b34..dc2b30126 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -14,21 +14,26 @@ # (`distributed game-wasm`, gitignored, stamped so # an unchanged module is not rebuilt); `gen --check` # verifies the TypeScript (and still builds WASM) +# ./run.sh sveltekit Mob Pit in SvelteKit (sveltekit/): dev sign-in, +# session-minted tickets, game client generated by +# the Vite plugin, Svelte HUD + settled read model # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS, -# generated clients checked) +# generated clients checked, SvelteKit headless) # ./run.sh list demos this script knows # # Env: GAME_DEMOS_PORT (server, default 2567), GAME_DEMOS_CLIENT_PORT (Vite, # default 5173), DG_NET_LATENCY_MS / DG_NET_JITTER_MS / DG_NET_LOSS (initial # server NetSim; the HUD sliders change it live), MOBPIT_DATA_DIR (Mob Pit / # Leaderboard cells, default examples/game/.data/mobpit), REDIS_URL (Redis -# leaderboard instead of in-memory). +# leaderboard instead of in-memory), SVELTEKIT_PORT (SvelteKit demo, default +# 5573; its game server uses GAME_DEMOS_PORT, default 2967 there). set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO="$(cd "$HERE/../.." && pwd)" SERVER="$HERE/server" CLIENT="$HERE/client" +SVELTEKIT="$HERE/sveltekit" BIN="$SERVER/target/debug/game-demos" DEMOS=(arena mobpit leaderboard gallery freeze grid ripple) export MOBPIT_DATA_DIR="${MOBPIT_DATA_DIR:-$HERE/.data/mobpit}" @@ -62,6 +67,14 @@ ensure_client() { fi } +ensure_sveltekit() { + local stamp="$SVELTEKIT/node_modules/.package-lock.json" + if [[ ! -f "$stamp" ]] || [[ "$SVELTEKIT/package-lock.json" -nt "$stamp" ]]; then + log "installing SvelteKit demo dependencies (npm ci)" + (cd "$SVELTEKIT" && npm ci --no-audit --no-fund) + fi +} + ensure_server() { log "building game-demos server" cargo build --quiet --manifest-path "$SERVER/Cargo.toml" @@ -198,6 +211,33 @@ run_cluster() { GAME_DEMOS_SERVER="http://127.0.0.1:$port_a" GAME_DEMOS_CLIENT_PORT="$client_port" npx vite } +# The SvelteKit demo: Mob Pit server + `vite dev`. The Vite plugin generates +# src/lib/generated/mobpit (and its WASM) on start and on Rust changes. +run_sveltekit() { + local port="${GAME_DEMOS_PORT:-2967}" + local ui_port="${SVELTEKIT_PORT:-5573}" + ensure_sdk + ensure_sveltekit + ensure_server + ensure_cli + local log_file secret + log_file="$(mktemp -t game-demos-sveltekit.XXXXXX)" + secret="${DISTRIBUTED_GAME_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --dev --port "$port" \ + --data-dir "${MOBPIT_DATA_DIR%/}-sveltekit" >"$log_file" 2>&1 & + local server_pid=$! + trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; rm -f "$log_file"' EXIT INT TERM + wait_listening "$log_file" "$server_pid" "game-demos mobpit" + echo + log "open http://localhost:$ui_port/ (sign in with any username; Mob Pit server :$port, dev routes ON — local only)" + echo + cd "$SVELTEKIT" + PORT="$ui_port" GAME_DEV_AUTH=1 \ + AUTH_SECRET="${AUTH_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" \ + GAME_TICKET_SECRET="$secret" GAME_ZONES_URL="ws://127.0.0.1:$port" \ + GAME_SERVER_HTTP="http://127.0.0.1:$port" npx vite dev +} + smoke() { ensure_sdk ensure_client @@ -210,14 +250,20 @@ smoke() { cargo build --quiet --manifest-path "$SERVER/Cargo.toml" log "client: type-check, build, tests (WASM steps + pure functions exact match, headless SDK)" (cd "$CLIENT" && npm run --silent check && npx vite build --logLevel warn && GAME_DEMOS_BIN="$BIN" npm test --silent) + log "sveltekit: generated game client current, svelte-check, build (plugin codegen + WASM), headless Playwright" + ensure_sveltekit + (cd "$SVELTEKIT" && npm run --silent check:games && npm run --silent check && + npx vite build --logLevel warn && npx playwright install chromium >/dev/null && + GAME_DEMOS_BIN="$BIN" npm test --silent) log "smoke OK" } case "${1:-}" in smoke) smoke ;; gen) gen "${2:-}" ;; - list) printf '%s\n' "${DEMOS[@]}" ;; - "" | -h | --help | help) sed -n '2,24p' "$0" ;; + sveltekit) run_sveltekit ;; + list) printf '%s\n' "${DEMOS[@]}" sveltekit ;; + "" | -h | --help | help) sed -n '2,29p' "$0" ;; *) if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then run_cluster "$1" diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index cc0cc26b5..7336e4a35 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -857,13 +857,16 @@ impl Zone for MobPit { } fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { - let principal = ctx + let (principal, ticket_name) = ctx .player(player) - .map(|p| p.principal.clone()) + .map(|p| (p.principal.clone(), p.name.clone())) .unwrap_or_default(); + // A dev guest's registered name, else the name the ticket issuer + // vouched for (e.g. a SvelteKit session), else the principal. let name = self .guests .name(&principal) + .or(ticket_name) .unwrap_or_else(|| principal.clone()); let (x, y) = spawn_point(player); let entity = 1000 + player.0; diff --git a/examples/game/sveltekit/.gitignore b/examples/game/sveltekit/.gitignore new file mode 100644 index 000000000..ae7698b50 --- /dev/null +++ b/examples/game/sveltekit/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.svelte-kit/ +build/ +# Compiled predicted step (`distributed game-wasm`, built by the Vite plugin) +src/lib/generated/*/wasm/ diff --git a/examples/game/sveltekit/distributed.config.js b/examples/game/sveltekit/distributed.config.js new file mode 100644 index 000000000..bc4fa126e --- /dev/null +++ b/examples/game/sveltekit/distributed.config.js @@ -0,0 +1,26 @@ +// Game surfaces generated by the Distributed Vite plugin (dev start, Rust +// changes, build) and checked in CI by `npm run check:games`. +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const app = dirname(fileURLToPath(import.meta.url)); +const repo = resolve(app, '../../..'); +const server = resolve(app, '../server'); + +/** @type {import('@hops-ops/distributed/sveltekit/vite').DistributedSvelteKitViteOptions} */ +export const distributedViteOptions = { + cwd: app, + // The CLI from this checkout (an installed `distributed` works the same). + command: 'cargo', + commandArgs: ['run', '--quiet', '--manifest-path', resolve(repo, 'Cargo.toml'), '-p', 'distributed_cli', '--bin', 'distributed', '--'], + games: [ + { + manifest: { + args: ['game-manifest', '--manifest-path', resolve(server, 'Cargo.toml'), '--entrypoint', 'game_demos::mobpit::game_surface'] + }, + out: 'src/lib/generated/mobpit', + // The predicted step (`pit_step`) lives in the sim crate. + watch: [resolve(server, 'sim')] + } + ] +}; diff --git a/examples/game/sveltekit/package-lock.json b/examples/game/sveltekit/package-lock.json new file mode 100644 index 000000000..defffc717 --- /dev/null +++ b/examples/game/sveltekit/package-lock.json @@ -0,0 +1,2050 @@ +{ + "name": "game-demos-sveltekit", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "game-demos-sveltekit", + "version": "0.0.0", + "dependencies": { + "@auth/core": "0.41.3", + "@auth/sveltekit": "1.11.3", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "@sveltejs/adapter-node": "5.2.12", + "@sveltejs/kit": "2.70.1", + "@sveltejs/vite-plugin-svelte": "5.1.1", + "@types/node": "^24.7.0", + "playwright": "1.61.1", + "svelte": "5.56.7", + "svelte-check": "4.1.7", + "typescript": "5.8.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } + }, + "../../../js": { + "name": "@hops-ops/distributed", + "version": "0.1.0", + "license": "UNLICENSED", + "dependencies": { + "@graphql-typed-document-node/core": "^3.2.0", + "graphql": "^16.14.0", + "wasm-pack": "0.15.0" + }, + "devDependencies": { + "@apollo/client": "^4.2.7", + "@types/node": "^20.0.0", + "@types/react": "19.2.18", + "esbuild": "^0.28.0", + "publint": "^0.3.22", + "react": "19.2.8", + "react-dom": "19.2.8", + "react-test-renderer": "19.2.8", + "svelte": "5.56.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=20.3.0" + }, + "peerDependencies": { + "react": "^18.2.0 || ^19.0.0", + "svelte": "^5.7.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "svelte": { + "optional": true + } + } + }, + "node_modules/@auth/core": { + "version": "0.41.3", + "resolved": "https://registry.npmjs.org/@auth/core/-/core-0.41.3.tgz", + "integrity": "sha512-sJ3JMHHkXMD3aOjopv7mOBTO1Ocw4b0fAEXJBz6k7YHLpYQI6C40jCUPc5fNvUKxXRXNE1/sRISA15UrwWJBTw==", + "license": "ISC", + "dependencies": { + "@panva/hkdf": "^1.2.1", + "jose": "^6.0.6", + "oauth4webapi": "^3.3.0", + "preact": "10.24.3", + "preact-render-to-string": "6.5.11" + }, + "peerDependencies": { + "@simplewebauthn/browser": "^9.0.1", + "@simplewebauthn/server": "^9.0.2", + "nodemailer": "^7.0.7 || ^8.0.5" + }, + "peerDependenciesMeta": { + "@simplewebauthn/browser": { + "optional": true + }, + "@simplewebauthn/server": { + "optional": true + }, + "nodemailer": { + "optional": true + } + } + }, + "node_modules/@auth/sveltekit": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@auth/sveltekit/-/sveltekit-1.11.3.tgz", + "integrity": "sha512-nfI/CFHD9hpJG4W+u+xtMrw9XSrA1k6kbgbGc9PvbiEf67oPMuzLAvLDj6/3yd98kFz+51Rq04JLBckKp8T5Kg==", + "license": "ISC", + "dependencies": { + "@auth/core": "0.41.3", + "set-cookie-parser": "^2.7.0" + }, + "peerDependencies": { + "@simplewebauthn/browser": "^9.0.1", + "@simplewebauthn/server": "^9.0.3", + "@sveltejs/kit": "^1.0.0 || ^2.0.0", + "nodemailer": "^7.0.7 || ^8.0.5", + "svelte": "^3.54.0 || ^4.0.0 || ^5.0.0-0" + }, + "peerDependenciesMeta": { + "@simplewebauthn/browser": { + "optional": true + }, + "@simplewebauthn/server": { + "optional": true + }, + "nodemailer": { + "optional": true + } + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hops-ops/distributed": { + "resolved": "../../../js", + "link": true + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@panva/hkdf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", + "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.29", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", + "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==", + "license": "MIT" + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "28.0.9", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-28.0.9.tgz", + "integrity": "sha512-PIR4/OHZ79romx0BVVll/PkwWpJ7e5lsqFa3gFfcrFPWwLXLV39JVUzQV9RKjWerE7B845Hqjj9VYlQeieZ2dA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.1.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.10.tgz", + "integrity": "sha512-oJ9ZfVIZjSjts0ZIYA48+5T0vurE5fQfX/Liad2U52Y6EN99x/OCdjGGuKMDP6jSk2i2lY6jwwA3X0drEc4PBg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.10.tgz", + "integrity": "sha512-LylBINgYYwgHNz8OMCy5+Y0w/LEgRYE0PcAIZfEuTuLNMf0S40GSLX6SFwqZsBLplS7RIHHy4zOAbl8Y5cQEvg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.10.tgz", + "integrity": "sha512-vbuT3VT1GBI2fAOoUJUrsHVoOg9nbrFXTM7e3DSnb9PYf4n6jZCN8v4Vo8O6x4u5B67+/c803b8BtCZe2nIeqA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.10.tgz", + "integrity": "sha512-qYUp/qYvM3T4cF+VWalPl+przBUESILxi+qZ1m1MVRHpg06vS+jHaxXubjCaRpXjLJPDFdXzOZ0FABDghHOhNQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.10.tgz", + "integrity": "sha512-v9NRQG+JztbP4DP/0yuhSyDcEJk047lYbqeNnqIgbXITcVDjGDS7OpkW5nadSY3tJ7MY8W1qIMMqP4Q3Q8BDjQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.10.tgz", + "integrity": "sha512-CHc9LBHdxhn6/NXfb9IegXCWoz5VlvcDOx9QrzZ9q+XYhFlfzwymSWJjOlZcEMMtC1zgMV7qxDe6U18AI1SG0A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.10.tgz", + "integrity": "sha512-ble2WR7kWfzZFJUd3ODMGCJn1XDszptfRC0QvWc0h9/EA6MxnrQ1mvbjPZifEdgHyfHhDrwWeKeJONDITcrHSg==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.10.tgz", + "integrity": "sha512-DMCYegihxBMKvLpODdk4OsvIgxtHTi+Oddf1Pm3d6wMVNjcBiG2pqyXjMPy55HgG1gCdEFr9VfhB1CmvuKn1lw==", + "cpu": [ + "arm" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.10.tgz", + "integrity": "sha512-HQ6HuVH9TmhvPWIas7MA/KeAROgdwqH3REpUU6hZq47NW7m1b1QCrHgM+M3+N/B8DfMt88x1/z79ppRc9RflCQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.10.tgz", + "integrity": "sha512-avBhxba1DdctX0kxKkN3JWdTSg72QsxSn6FdfhZ9MkL3TTYDOXqxY1GqbC7VNttlgviK7tCe2No5btfRkFgeIg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.10.tgz", + "integrity": "sha512-UtQMex7fiXq0W/GqcWRpy6XKqUbXgQeGKB+Bd5rJngmHzpI+3kjwpWFLAhKg02onFsIMSh+Zx0zp9JIMQ7/05A==", + "cpu": [ + "loong64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.10.tgz", + "integrity": "sha512-0Aum2pUsCSuOopi6oka+nR1DTj/nfvc1xjL979lvh6kXUjNa30TCX7sKFjyMsrX7bK3bNVs0FsJwQcE2HCWX1Q==", + "cpu": [ + "loong64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.10.tgz", + "integrity": "sha512-4dgsouKal3qfMFORgtNigLPt7K3HXiO6jTr7+nFJv1GWu1OkZx0kvQIXbK4sjrIGnaLBk0s80eQCQ9hPIelLrw==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.10.tgz", + "integrity": "sha512-d7NE89try3jisYzBD7J9M5iwfgcrXYC4dwHEjQ3HIWBftvwch1U/cy3iZ26SthtUOyClKiu7iqYiFjQEwiOlqQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.10.tgz", + "integrity": "sha512-dqB5ChSBp91JWXxpCKAS5ZVAE38esKQvdfyqANm0lF5JPiQrXnYwgG3oVBQmuNRcQ1WHkA3j5qYLsrl2CtfhCA==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.10.tgz", + "integrity": "sha512-7GMf3vbQQslorWLmfsbi5fdt9RVnglk205XpOMFvW6UY5jE5oJc6JLieQJPHtsYlZ2EO0PtC06nY9Hz/IG8guw==", + "cpu": [ + "riscv64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.10.tgz", + "integrity": "sha512-tuKbkB23DKc5LG+irPSUnZZztRHqC3CNmyxeWloueBteHB+i+1HkRCMzAE41lseLDlarybeLhqfibFitKOxKMg==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.10.tgz", + "integrity": "sha512-ntHtQOMw7oIshHRF1swV3vyBw+beQt9PeZ04O3D32EeDZUMoHMJuZKp4/fDllH/+xogeK0GUCONVfjjKusqKLg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.10.tgz", + "integrity": "sha512-Dlh8q8r145aYgh+N3gNIG1dz35Fz/FCxe5hs/43orDsffjP8S1P4Xz5I4FpSJsDS4LpQw1QmswZkQlUbkCldjQ==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.10.tgz", + "integrity": "sha512-VBJhHWz/55u45CWFv9OmfSRDgJDVENESgFxSAn13gIKJpTuFJbP4/7ymMZhDfeKFx1zGn1XBsLnNB7Ryy71qww==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.10.tgz", + "integrity": "sha512-Vjcazg+EEzUfIz+LcaxS6YtbQHo+sv0sCD+5VbwhY504bCKNW4OOreVgKq61pHT2esRQ/+AXYVPStDwxSvAOdw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.10.tgz", + "integrity": "sha512-jJAaP4El+HWxYkM0jeJghASaFgfnluY0FRHhyHXxU6STs/nBhKMIxIMDrJEFg2ftKz6orX9WAo4diVan5NugNA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.10.tgz", + "integrity": "sha512-bXXdRUfRx9PaHCToKt8R/7wjDV6Tbk/hmSHK0uQBKmD3rj4jkuYndct8uGX77ZuZsePrVkQbWUgPR2jJhCTMpQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.10.tgz", + "integrity": "sha512-57Idx+VkEOQeG6Ys6sZOBFT7FfbeyxGv9A3k1m+Lf/z2SwqT40rNWbAINzjPHSMoCCBvY7Fnb9RGZWQin/HHAw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.10.tgz", + "integrity": "sha512-vrvuasIpm/xf+BpZbzgirku0WnrQZMAc+H2Ai26jzqBxYEmQQE4DdJb7h8erkJMfRRipx0ma2Cty8jJwUm9ocQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/adapter-node": { + "version": "5.2.12", + "resolved": "https://registry.npmjs.org/@sveltejs/adapter-node/-/adapter-node-5.2.12.tgz", + "integrity": "sha512-0bp4Yb3jKIEcZWVcJC/L1xXp9zzJS4hDwfb4VITAkfT4OVdkspSHsx7YhqJDbb2hgLl6R9Vs7VQR+fqIVOxPUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/plugin-commonjs": "^28.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.0", + "rollup": "^4.9.5" + }, + "peerDependencies": { + "@sveltejs/kit": "^2.4.0" + } + }, + "node_modules/@sveltejs/kit": { + "version": "2.70.1", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.1.tgz", + "integrity": "sha512-nY9SPHGOZro3doud9vZXDBwl9tCZIouuJztjgSHs6PAIrv9M/z5O7eOhPV5xU7CgVHA976Jwu3BA1hIFvXztkA==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@sveltejs/acorn-typescript": "^1.0.9", + "@types/cookie": "^0.6.0", + "acorn": "^8.16.0", + "cookie": "^0.6.0", + "devalue": "^5.8.1", + "esm-env": "^1.2.2", + "kleur": "^4.1.5", + "magic-string": "^0.30.5", + "mrmime": "^2.0.0", + "set-cookie-parser": "^3.0.0", + "sirv": "^3.0.0" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "engines": { + "node": ">=18.13" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0", + "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.3.3 || ^6.0.0", + "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@sveltejs/kit/node_modules/set-cookie-parser": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.4.tgz", + "integrity": "sha512-iEmdEew+Tn1BwMGMP8LzGBEPC7Mf1sySjglCeEPb/Vchm9bnGezePvacYcId+fGprQzIng+TBkzqfJ/qS7AsBg==", + "license": "MIT" + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-5.1.1.tgz", + "integrity": "sha512-Y1Cs7hhTc+a5E9Va/xwKlAJoariQyHY+5zBgCZg4PFWNYQ1nMN9sjK1zhw1gK69DuqVP++sht/1GZg1aRwmAXQ==", + "license": "MIT", + "dependencies": { + "@sveltejs/vite-plugin-svelte-inspector": "^4.0.1", + "debug": "^4.4.1", + "deepmerge": "^4.3.1", + "kleur": "^4.1.5", + "magic-string": "^0.30.17", + "vitefu": "^1.0.6" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte-inspector": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-4.0.1.tgz", + "integrity": "sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.7" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.0", + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.7.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.7.0.tgz", + "integrity": "sha512-IbKooQVqUBrlzWTi79E8Fw78l8k1RNtlDDNWsFZs7XonuQSJ8oNYfEeclhprUldXISRMLzBpILuKgPlIxm+/Yw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.14.0" + } + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/devalue": { + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", + "license": "MIT" + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", + "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-core-module": { + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", + "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/oauth4webapi": { + "version": "3.8.8", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz", + "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "10.24.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz", + "integrity": "sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/preact-render-to-string": { + "version": "6.5.11", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.5.11.tgz", + "integrity": "sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==", + "license": "MIT", + "peerDependencies": { + "preact": ">=10" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve": { + "version": "1.22.13", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", + "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.17.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.10.tgz", + "integrity": "sha512-8N52YH1B5JzBP+B1rkcBERG7rfRTGAM0RmUpyd76yyRfTljuG452GCNbVm6MPzs1+gXBha6Rw5/oHRFohOpfDg==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.10", + "@rollup/rollup-android-arm64": "4.64.10", + "@rollup/rollup-darwin-arm64": "4.64.10", + "@rollup/rollup-darwin-x64": "4.64.10", + "@rollup/rollup-freebsd-arm64": "4.64.10", + "@rollup/rollup-freebsd-x64": "4.64.10", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.10", + "@rollup/rollup-linux-arm-musleabihf": "4.64.10", + "@rollup/rollup-linux-arm64-gnu": "4.64.10", + "@rollup/rollup-linux-arm64-musl": "4.64.10", + "@rollup/rollup-linux-loong64-gnu": "4.64.10", + "@rollup/rollup-linux-loong64-musl": "4.64.10", + "@rollup/rollup-linux-ppc64-gnu": "4.64.10", + "@rollup/rollup-linux-ppc64-musl": "4.64.10", + "@rollup/rollup-linux-riscv64-gnu": "4.64.10", + "@rollup/rollup-linux-riscv64-musl": "4.64.10", + "@rollup/rollup-linux-s390x-gnu": "4.64.10", + "@rollup/rollup-linux-x64-gnu": "4.64.10", + "@rollup/rollup-linux-x64-musl": "4.64.10", + "@rollup/rollup-openbsd-x64": "4.64.10", + "@rollup/rollup-openharmony-arm64": "4.64.10", + "@rollup/rollup-win32-arm64-msvc": "4.64.10", + "@rollup/rollup-win32-ia32-msvc": "4.64.10", + "@rollup/rollup-win32-x64-gnu": "4.64.10", + "@rollup/rollup-win32-x64-msvc": "4.64.10", + "fsevents": "~2.3.2" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/sirv": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", + "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==", + "license": "MIT", + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svelte": { + "version": "5.56.7", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.7.tgz", + "integrity": "sha512-5qERUZX80oQj6XrDMUmD2Uhd/cIpCPDWWKBK3ZHmyRUC9apPyamWM8xMo31mbWsIQxwG2hVoSnOJ/EcnhVkkzQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.10", + "@types/estree": "^1.0.5", + "@types/trusted-types": "^2.0.7", + "acorn": "^8.12.1", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.8.1", + "esm-env": "^1.2.1", + "esrap": "^2.2.12", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte-check": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.1.7.tgz", + "integrity": "sha512-1jX4BzXrQJhC/Jt3SqYf6Ntu//vmfc6VWp07JkRfK2nn+22yIblspVUo96gzMkg0Zov8lQicxhxsMzOctwcMQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "chokidar": "^4.0.1", + "fdir": "^6.2.0", + "picocolors": "^1.0.0", + "sade": "^1.7.4" + }, + "bin": { + "svelte-check": "bin/svelte-check" + }, + "engines": { + "node": ">= 18.0.0" + }, + "peerDependencies": { + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": ">=5.0.0" + } + }, + "node_modules/svelte/node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.14.0.tgz", + "integrity": "sha512-QQiYxHuyZ9gQUIrmPo3IA+hUl4KYk8uSA7cHrcKd/l3p1OTpZcM0Tbp9x7FAtXdAYhlasd60ncPpgu6ihG6TOA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "license": "MIT" + } + } +} diff --git a/examples/game/sveltekit/package.json b/examples/game/sveltekit/package.json new file mode 100644 index 000000000..69f504444 --- /dev/null +++ b/examples/game/sveltekit/package.json @@ -0,0 +1,33 @@ +{ + "name": "game-demos-sveltekit", + "private": true, + "version": "0.0.0", + "description": "Mob Pit in SvelteKit: session tickets, Vite-generated game client, runes HUD (dev only)", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", + "check:games": "node scripts/check-games.mjs", + "test": "node --test tests/*.test.mjs" + }, + "dependencies": { + "@auth/core": "0.41.3", + "@auth/sveltekit": "1.11.3", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "@sveltejs/adapter-node": "5.2.12", + "@sveltejs/kit": "2.70.1", + "@sveltejs/vite-plugin-svelte": "5.1.1", + "@types/node": "^24.7.0", + "playwright": "1.61.1", + "svelte": "5.56.7", + "svelte-check": "4.1.7", + "typescript": "5.8.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } +} diff --git a/examples/game/sveltekit/scripts/check-games.mjs b/examples/game/sveltekit/scripts/check-games.mjs new file mode 100644 index 000000000..81f7099f0 --- /dev/null +++ b/examples/game/sveltekit/scripts/check-games.mjs @@ -0,0 +1,6 @@ +// CI: generated game clients match the Rust surfaces (never writes). +import { checkDistributedGames } from '@hops-ops/distributed/sveltekit/vite'; +import { distributedViteOptions } from '../distributed.config.js'; + +await checkDistributedGames(distributedViteOptions); +console.log('game clients are current'); diff --git a/examples/game/sveltekit/src/app.d.ts b/examples/game/sveltekit/src/app.d.ts new file mode 100644 index 000000000..be79b78b1 --- /dev/null +++ b/examples/game/sveltekit/src/app.d.ts @@ -0,0 +1,6 @@ +// See https://svelte.dev/docs/kit/types#app.d.ts +declare global { + namespace App {} +} + +export {}; diff --git a/examples/game/sveltekit/src/app.html b/examples/game/sveltekit/src/app.html new file mode 100644 index 000000000..a4f13df29 --- /dev/null +++ b/examples/game/sveltekit/src/app.html @@ -0,0 +1,12 @@ + + + + + + Mob Pit · SvelteKit + %sveltekit.head% + + +
    %sveltekit.body%
    + + diff --git a/examples/game/sveltekit/src/auth.ts b/examples/game/sveltekit/src/auth.ts new file mode 100644 index 000000000..a0b5ff9a3 --- /dev/null +++ b/examples/game/sveltekit/src/auth.ts @@ -0,0 +1,55 @@ +/** + * Auth.js, the session mechanism the framework's SvelteKit apps use + * (`tests/e2e-ui`): `locals.auth()` returns the verified session from an + * encrypted, HttpOnly cookie. Real deployments configure the OIDC provider + * (`OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`); local dev and the + * smoke test enable a **dev-only** username sign-in with `GAME_DEV_AUTH=1`. + * Either way the game ticket route only ever reads `session.user.id`. + */ +import { SvelteKitAuth, type SvelteKitAuthConfig } from '@auth/sveltekit'; +import Credentials from '@auth/sveltekit/providers/credentials'; +import { env } from '$env/dynamic/private'; + +const USERNAME = /^[a-z][a-z0-9_-]{2,15}$/; + +export const { handle, signIn, signOut } = SvelteKitAuth(async (): Promise => ({ + trustHost: true, + secret: env.AUTH_SECRET, + session: { strategy: 'jwt' }, + pages: { signIn: '/' }, + providers: [ + ...(env.OIDC_ISSUER + ? [ + { + id: 'oidc', + name: 'OIDC', + type: 'oidc' as const, + issuer: env.OIDC_ISSUER, + clientId: env.OIDC_CLIENT_ID, + clientSecret: env.OIDC_CLIENT_SECRET, + checks: ['pkce' as const, 'state' as const, 'nonce' as const] + } + ] + : []), + ...(env.GAME_DEV_AUTH === '1' + ? [ + Credentials({ + id: 'dev', + name: 'Dev sign-in (local only)', + credentials: { username: { label: 'Username' } }, + authorize(credentials) { + const username = String(credentials?.username ?? '').trim().toLowerCase(); + return USERNAME.test(username) ? { id: `dev-${username}`, name: username } : null; + } + }) + ] + : []) + ], + callbacks: { + session({ session, token }) { + // The verified subject is the game principal. + if (session.user && typeof token.sub === 'string') session.user.id = token.sub; + return session; + } + } +})); diff --git a/examples/game/sveltekit/src/hooks.server.ts b/examples/game/sveltekit/src/hooks.server.ts new file mode 100644 index 000000000..e6726b061 --- /dev/null +++ b/examples/game/sveltekit/src/hooks.server.ts @@ -0,0 +1 @@ +export { handle } from './auth'; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/client.ts b/examples/game/sveltekit/src/lib/generated/mobpit/client.ts new file mode 100644 index 000000000..547157f12 --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/client.ts @@ -0,0 +1,68 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type PitInput } from './input.ts'; +import { createMobpitPrediction, type MobpitPrediction } from './predict.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type MobpitPredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; + +export type MobpitClientOptions = Omit, 'prediction'> & + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: MobpitPredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; + +export type MobpitClient = Readonly<{ + client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: MobpitPrediction | undefined; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is on, raw otherwise. */ + send(input: PitInput): number | undefined; +}>; + +/** + * A `GameClient` for the `mobpit` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ +export function createMobpitClient(options: MobpitClientOptions): MobpitClient { + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createMobpitPrediction(wasm); + const client = new GameClient({ + ...rest, + prediction: + tuning === false + ? undefined + : { + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) + } + }); + return { + client, + prediction, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts new file mode 100644 index 000000000..2e4517bda --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts @@ -0,0 +1,14 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { PitRules } from './events.ts'; + +/** `pit_rules`, as the client decodes it. */ +export const PIT_RULES: PitRules = { + tiers: [ + { tier: 1, radius: 0.5, tele: 1.7999999523162842 }, + { tier: 2, radius: 0.699999988079071, tele: 2.200000047683716 }, + { tier: 3, radius: 0.800000011920929, tele: 2.5999999046325684 } + ], + states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'] +}; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts new file mode 100644 index 000000000..d2e63390a --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts @@ -0,0 +1,332 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `BackgroundStats` (`#[derive(GameRecord)]`). */ +export interface BackgroundStats { + readonly enqueued: number; + readonly applied: number; + readonly dropped: number; + readonly failed: number; +} + +const BACKGROUND_STATS_TYPE: WireType = { + type: 'record', + fields: [ + ['enqueued', { type: 'u64' }], + ['applied', { type: 'u64' }], + ['dropped', { type: 'u64' }], + ['failed', { type: 'u64' }], + ] +}; + +/** Record `BoardRow` (`#[derive(GameRecord)]`). */ +export interface BoardRow { + readonly rank: number; + readonly member: string; + readonly name: string; + readonly score: number; +} + +const BOARD_ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u32' }], + ['member', { type: 'short_str' }], + ['name', { type: 'short_str' }], + ['score', { type: 'f64' }], + ] +}; + +/** Record `Scores` (`#[derive(GameRecord)]`). */ +export interface Scores { + readonly kills: number; + readonly xp: number; +} + +const SCORES_TYPE: WireType = { + type: 'record', + fields: [ + ['kills', { type: 'f64' }], + ['xp', { type: 'f64' }], + ] +}; + +/** Record `Mismatch` (`#[derive(GameRecord)]`). */ +export interface Mismatch { + readonly member: string; + readonly cell: Scores; + readonly board: Scores; +} + +const MISMATCH_TYPE: WireType = { + type: 'record', + fields: [ + ['member', { type: 'short_str' }], + ['cell', SCORES_TYPE], + ['board', SCORES_TYPE], + ] +}; + +/** Record `RebuildReport` (`#[derive(GameRecord)]`). */ +export interface RebuildReport { + readonly backend: string; + readonly crawlers: number; + readonly events: number; + readonly applied: number; + readonly duplicates: number; + readonly identicalTop: boolean; + readonly matchesCells: boolean; + readonly mismatches: readonly Mismatch[]; + readonly tookMs: number; +} + +const REBUILD_REPORT_TYPE: WireType = { + type: 'record', + fields: [ + ['backend', { type: 'short_str' }], + ['crawlers', { type: 'u32' }], + ['events', { type: 'u32' }], + ['applied', { type: 'u32' }], + ['duplicates', { type: 'u32' }], + ['identicalTop', { type: 'bool' }], + ['matchesCells', { type: 'bool' }], + ['mismatches', { type: 'list', item: MISMATCH_TYPE }], + ['tookMs', { type: 'f64' }], + ] +}; + +/** Record `BoardSnapshot` (`#[derive(GameRecord)]`). */ +export interface BoardSnapshot { + readonly version: number; + readonly backend: string; + readonly members: number; + readonly kills: readonly BoardRow[]; + readonly xp: readonly BoardRow[]; + readonly background: BackgroundStats; + readonly lastRebuild: RebuildReport | undefined; +} + +const BOARD_SNAPSHOT_TYPE: WireType = { + type: 'record', + fields: [ + ['version', { type: 'u64' }], + ['backend', { type: 'short_str' }], + ['members', { type: 'u64' }], + ['kills', { type: 'list', item: BOARD_ROW_TYPE }], + ['xp', { type: 'list', item: BOARD_ROW_TYPE }], + ['background', BACKGROUND_STATS_TYPE], + ['lastRebuild', { type: 'optional', item: REBUILD_REPORT_TYPE }], + ] +}; + +/** Record `MobTier` (`#[derive(GameRecord)]`). */ +export interface MobTier { + readonly tier: number; + readonly radius: number; + readonly tele: number; +} + +/** Record `MoveState` (`#[derive(GameRecord)]`). */ +export interface MoveState { + readonly x: number; + readonly y: number; + readonly vx: number; + readonly vy: number; + readonly dash: number; + readonly cd: number; +} + +/** Record `PitRules` (`#[derive(GameRecord)]`). */ +export interface PitRules { + readonly tiers: readonly MobTier[]; + readonly states: readonly string[]; +} + +/** Record `Profile` (`#[derive(GameRecord)]`). */ +export interface Profile { + readonly xp: number; + readonly level: number; + readonly kills: number; + readonly levelXp: number; + readonly nextLevelXp: number; + readonly source: string; +} + +const PROFILE_TYPE: WireType = { + type: 'record', + fields: [ + ['xp', { type: 'u64' }], + ['level', { type: 'u32' }], + ['kills', { type: 'u32' }], + ['levelXp', { type: 'u64' }], + ['nextLevelXp', { type: 'u64' }], + ['source', { type: 'short_str' }], + ] +}; + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly half: number; + readonly boot: string; + readonly attackRange: number; + readonly attackArcCos: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['half', { type: 'f32' }], + ['boot', { type: 'short_str' }], + ['attackRange', { type: 'f32' }], + ['attackArcCos', { type: 'f32' }], +]; + +/** Event `profile` (id 2). */ +export type ProfileEvent = Profile; + +const PROFILE_PAYLOAD: WireType = PROFILE_TYPE; + +/** Event `kill` (id 3). */ +export interface KillEvent { + readonly key: string; + readonly mob: number; + readonly tier: number; + readonly x: number; + readonly y: number; + readonly killer: number; + readonly killerName: string; +} + +const KILL_LAYOUT: PayloadLayout = [ + ['key', { type: 'short_str' }], + ['mob', { type: 'u32' }], + ['tier', { type: 'u8' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['killer', { type: 'u32' }], + ['killerName', { type: 'short_str' }], +]; + +/** Event `saved` (id 4). */ +export interface SavedEvent { + readonly key: string; + readonly ok: boolean; + readonly replayed: boolean; + readonly xp: number; + readonly totalXp: number; + readonly kills: number; + readonly level: number; + readonly waitedMs: number; + readonly x: number; + readonly y: number; + readonly error: string | undefined; + readonly attempts: number; +} + +const SAVED_LAYOUT: PayloadLayout = [ + ['key', { type: 'short_str' }], + ['ok', { type: 'bool' }], + ['replayed', { type: 'bool' }], + ['xp', { type: 'u32' }], + ['totalXp', { type: 'u64' }], + ['kills', { type: 'u32' }], + ['level', { type: 'u32' }], + ['waitedMs', { type: 'u32' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['error', { type: 'optional', item: { type: 'short_str' } }], + ['attempts', { type: 'u32' }], +]; + +/** Event `board` (id 5). */ +export type BoardEvent = BoardSnapshot; + +const BOARD_PAYLOAD: WireType = BOARD_SNAPSHOT_TYPE; + +/** Event `died` (id 6). */ +export interface DiedEvent { + readonly respawnMs: number; +} + +const DIED_LAYOUT: PayloadLayout = [ + ['respawnMs', { type: 'u32' }], +]; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + profile: 2, + kill: 3, + saved: 4, + board: 5, + died: 6, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + profile: ProfileEvent; + kill: KillEvent; + saved: SavedEvent; + board: BoardEvent; + died: DiedEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + profile: { + id: 2, + name: 'profile', + encode: (value) => encodeValue(PROFILE_PAYLOAD, value), + decode: (payload) => decodeValue(PROFILE_PAYLOAD, payload) as ProfileEvent + }, + kill: { + id: 3, + name: 'kill', + encode: (value) => encodePayload(KILL_LAYOUT, value), + decode: (payload) => decodePayload(KILL_LAYOUT, payload) as unknown as KillEvent + }, + saved: { + id: 4, + name: 'saved', + encode: (value) => encodePayload(SAVED_LAYOUT, value), + decode: (payload) => decodePayload(SAVED_LAYOUT, payload) as unknown as SavedEvent + }, + board: { + id: 5, + name: 'board', + encode: (value) => encodeValue(BOARD_PAYLOAD, value), + decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent + }, + died: { + id: 6, + name: 'died', + encode: (value) => encodePayload(DIED_LAYOUT, value), + decode: (payload) => decodePayload(DIED_LAYOUT, payload) as unknown as DiedEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/index.ts b/examples/game/sveltekit/src/lib/generated/mobpit/index.ts new file mode 100644 index 000000000..481102c6c --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/index.ts @@ -0,0 +1,9 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './constants.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './predict.ts'; +export * from './schema.ts'; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/input.ts b/examples/game/sveltekit/src/lib/generated/mobpit/input.ts new file mode 100644 index 000000000..7914746a8 --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/input.ts @@ -0,0 +1,52 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `PitInput` input frame (`#[derive(GameInput)]`). */ +export interface PitInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; +} + +export type Input = PitInput; + +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + attack: 2, + }, +} as const; + +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 3 }, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: PitInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): PitInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as PitInput; +} + +/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */ +export function sanitizeInput(input: PitInput): PitInput { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!; +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/predict.ts b/examples/game/sveltekit/src/lib/generated/mobpit/predict.ts new file mode 100644 index 000000000..fcfeb0e96 --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/predict.ts @@ -0,0 +1,51 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource } from '@hops-ops/distributed/game'; + +import { encodeInput, type PitInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `pit_step` of Cargo package `game_sim`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'pit_step', + package: 'game_sim', + state: 'MoveState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `MoveState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['vy', { type: 'f32' }], + ['dash', { type: 'u8' }], + ['cd', { type: 'u8' }], +]; + +/** The step takes no context. */ +export type PredictContext = undefined; + +/** The step takes no context. */ +export const PREDICT_CONTEXT = undefined; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/mobpit.wasm', import.meta.url); + +/** The `mobpit` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type MobpitPrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves. + */ +export function createMobpitPrediction(source: WasmSource = PREDICT_WASM_URL): MobpitPrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts new file mode 100644 index 000000000..3d9f5f004 --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts @@ -0,0 +1,224 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldBool, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + mob: 2, + pillar: 3, + pit: 4, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vx: number; + /** `quant [-16, 15.9921875] / 12 bits` */ + readonly vy: number; + /** `u8` */ + readonly dash: number; + /** `u8` */ + readonly cd: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u8` */ + readonly hp: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `u8` */ + readonly swing: number; + /** `u16` */ + readonly level: number; + /** `bool` */ + readonly dead: boolean; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + vy: fieldNumber(f, 'vy'), + dash: fieldNumber(f, 'dash'), + cd: fieldNumber(f, 'cd'), + name: fieldString(f, 'name'), + hp: fieldNumber(f, 'hp'), + face: fieldNumber(f, 'face'), + swing: fieldNumber(f, 'swing'), + level: fieldNumber(f, 'level'), + dead: fieldBool(f, 'dead'), + }; +} + +/** `mob` (kind 2, priority 1). */ +export interface MobFields { + /** `quant [-20, 20] / 14 bits` */ + readonly x: number; + /** `quant [-20, 20] / 14 bits` */ + readonly y: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `u8` */ + readonly tier: number; + /** `u8` */ + readonly hp: number; + /** `u8` */ + readonly state: number; + /** `u8` */ + readonly tele: number; +} + +/** True for a `mob` entity. */ +export function isMob(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `mob` entity (rendered or replica). */ +export function mobFields(entity: { readonly fields: EntityFields }): MobFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + face: fieldNumber(f, 'face'), + tier: fieldNumber(f, 'tier'), + hp: fieldNumber(f, 'hp'), + state: fieldNumber(f, 'state'), + tele: fieldNumber(f, 'tele'), + }; +} + +/** `pillar` (kind 3, priority 1). */ +export interface PillarFields { + /** `f32` */ + readonly x: number; + /** `f32` */ + readonly y: number; + /** `f32` */ + readonly r: number; +} + +/** True for a `pillar` entity. */ +export function isPillar(entity: { readonly kind: number }): boolean { + return entity.kind === 3; +} + +/** Typed fields of a `pillar` entity (rendered or replica). */ +export function pillarFields(entity: { readonly fields: EntityFields }): PillarFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + r: fieldNumber(f, 'r'), + }; +} + +/** `pit` (kind 4, priority 1). */ +export interface PitFields { + /** `u16` */ + readonly pending: number; + /** `u16` */ + readonly slowMs: number; + /** `f32` */ + readonly tickMs: number; + /** `f32` */ + readonly tickMaxMs: number; + /** `u32` */ + readonly workUs: number; + /** `u32` */ + readonly committed: number; + /** `u16` */ + readonly backlog: number; +} + +/** True for a `pit` entity. */ +export function isPit(entity: { readonly kind: number }): boolean { + return entity.kind === 4; +} + +/** Typed fields of a `pit` entity (rendered or replica). */ +export function pitFields(entity: { readonly fields: EntityFields }): PitFields { + const f = entity.fields; + return { + pending: fieldNumber(f, 'pending'), + slowMs: fieldNumber(f, 'slow_ms'), + tickMs: fieldNumber(f, 'tick_ms'), + tickMaxMs: fieldNumber(f, 'tick_max_ms'), + workUs: fieldNumber(f, 'work_us'), + committed: fieldNumber(f, 'committed'), + backlog: fieldNumber(f, 'backlog'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, + dash: { type: 'u8' }, + cd: { type: 'u8' }, + name: { type: 'short_str' }, + hp: { type: 'u8' }, + face: { type: 'angle', bits: 8 }, + swing: { type: 'u8' }, + level: { type: 'u16' }, + dead: { type: 'bool' }, + }, + mob: { + x: { type: 'quant', min: -20, max: 20, bits: 14 }, + y: { type: 'quant', min: -20, max: 20, bits: 14 }, + face: { type: 'angle', bits: 8 }, + tier: { type: 'u8' }, + hp: { type: 'u8' }, + state: { type: 'u8' }, + tele: { type: 'u8' }, + }, + pillar: { + x: { type: 'f32' }, + y: { type: 'f32' }, + r: { type: 'f32' }, + }, + pit: { + pending: { type: 'u16' }, + slow_ms: { type: 'u16' }, + tick_ms: { type: 'f32' }, + tick_max_ms: { type: 'f32' }, + work_us: { type: 'u32' }, + committed: { type: 'u32' }, + backlog: { type: 'u16' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150 }, + vx: { mode: 'snap' }, + vy: { mode: 'snap' }, + dash: { mode: 'snap' }, + cd: { mode: 'snap' }, + name: { mode: 'replace' }, + hp: { mode: 'replace' }, + face: { mode: 'replace' }, + swing: { mode: 'replace' }, + level: { mode: 'replace' }, + dead: { mode: 'replace' }, + }, +}; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json new file mode 100644 index 000000000..f6b182a2f --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json @@ -0,0 +1,958 @@ +{ + "constants": [ + { + "name": "pit_rules", + "type": { + "name": "PitRules", + "type": "record" + }, + "value": { + "states": [ + "idle", + "chase", + "windup", + "recover", + "return", + "dead" + ], + "tiers": [ + { + "radius": 0.5, + "tele": 1.7999999523162842, + "tier": 1 + }, + { + "radius": 0.699999988079071, + "tele": 2.200000047683716, + "tier": 2 + }, + { + "radius": 0.800000011920929, + "tele": 2.5999999046325684, + "tier": 3 + } + ] + } + } + ], + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "half", + "type": { + "type": "f32" + } + }, + { + "name": "boot", + "type": { + "type": "short_str" + } + }, + { + "name": "attack_range", + "type": { + "type": "f32" + } + }, + { + "name": "attack_arc_cos", + "type": { + "type": "f32" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "profile", + "payload": { + "kind": "value", + "type": { + "name": "Profile", + "type": "record" + } + } + }, + { + "id": 3, + "name": "kill", + "payload": { + "fields": [ + { + "name": "key", + "type": { + "type": "short_str" + } + }, + { + "name": "mob", + "type": { + "type": "u32" + } + }, + { + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "killer", + "type": { + "type": "u32" + } + }, + { + "name": "killer_name", + "type": { + "type": "short_str" + } + } + ], + "kind": "fields" + } + }, + { + "id": 4, + "name": "saved", + "payload": { + "fields": [ + { + "name": "key", + "type": { + "type": "short_str" + } + }, + { + "name": "ok", + "type": { + "type": "bool" + } + }, + { + "name": "replayed", + "type": { + "type": "bool" + } + }, + { + "name": "xp", + "type": { + "type": "u32" + } + }, + { + "name": "total_xp", + "type": { + "type": "u64" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "waited_ms", + "type": { + "type": "u32" + } + }, + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "error", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "attempts", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + }, + { + "id": 5, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "BoardSnapshot", + "type": "record" + } + } + }, + { + "id": 6, + "name": "died", + "payload": { + "fields": [ + { + "name": "respawn_ms", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + } + ], + "name": "PitInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vy", + "priority": 1.0, + "type": { + "bits": 12, + "max": 15.9921875, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "dash", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "cd", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "swing", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "bits": 14, + "max": 20.0, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": null, + "name": "tier", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "state", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "tele", + "priority": 1.0, + "type": { + "type": "u8" + } + } + ], + "id": 2, + "name": "mob", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "x", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "y", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "r", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 3, + "name": "pillar", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "pending", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "tick_max_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "work_us", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "committed", + "priority": 1.0, + "type": { + "type": "u32" + } + }, + { + "correction": null, + "name": "backlog", + "priority": 1.0, + "type": { + "type": "u16" + } + } + ], + "id": 4, + "name": "pit", + "priority": 1.0 + } + ], + "name": "mobpit", + "predict": { + "abi": 1, + "export": "pit_step", + "kind": "player", + "package": "game_sim", + "state": "MoveState" + }, + "protocolVersion": 1, + "records": [ + { + "fields": [ + { + "name": "enqueued", + "type": { + "type": "u64" + } + }, + { + "name": "applied", + "type": { + "type": "u64" + } + }, + { + "name": "dropped", + "type": { + "type": "u64" + } + }, + { + "name": "failed", + "type": { + "type": "u64" + } + } + ], + "name": "BackgroundStats" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u32" + } + }, + { + "name": "member", + "type": { + "type": "short_str" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "f64" + } + } + ], + "name": "BoardRow" + }, + { + "fields": [ + { + "name": "version", + "type": { + "type": "u64" + } + }, + { + "name": "backend", + "type": { + "type": "short_str" + } + }, + { + "name": "members", + "type": { + "type": "u64" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "BoardRow", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "xp", + "type": { + "item": { + "name": "BoardRow", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "background", + "type": { + "name": "BackgroundStats", + "type": "record" + } + }, + { + "name": "last_rebuild", + "type": { + "item": { + "name": "RebuildReport", + "type": "record" + }, + "type": "optional" + } + } + ], + "name": "BoardSnapshot" + }, + { + "fields": [ + { + "name": "member", + "type": { + "type": "short_str" + } + }, + { + "name": "cell", + "type": { + "name": "Scores", + "type": "record" + } + }, + { + "name": "board", + "type": { + "name": "Scores", + "type": "record" + } + } + ], + "name": "Mismatch" + }, + { + "fields": [ + { + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "radius", + "type": { + "type": "f32" + } + }, + { + "name": "tele", + "type": { + "type": "f32" + } + } + ], + "name": "MobTier" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "y", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "vy", + "type": { + "type": "f32" + } + }, + { + "name": "dash", + "type": { + "type": "u8" + } + }, + { + "name": "cd", + "type": { + "type": "u8" + } + } + ], + "name": "MoveState" + }, + { + "fields": [ + { + "name": "tiers", + "type": { + "item": { + "name": "MobTier", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "states", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + } + ], + "name": "PitRules" + }, + { + "fields": [ + { + "name": "xp", + "type": { + "type": "u64" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + }, + { + "name": "level_xp", + "type": { + "type": "u64" + } + }, + { + "name": "next_level_xp", + "type": { + "type": "u64" + } + }, + { + "name": "source", + "type": { + "type": "short_str" + } + } + ], + "name": "Profile" + }, + { + "fields": [ + { + "name": "backend", + "type": { + "type": "short_str" + } + }, + { + "name": "crawlers", + "type": { + "type": "u32" + } + }, + { + "name": "events", + "type": { + "type": "u32" + } + }, + { + "name": "applied", + "type": { + "type": "u32" + } + }, + { + "name": "duplicates", + "type": { + "type": "u32" + } + }, + { + "name": "identical_top", + "type": { + "type": "bool" + } + }, + { + "name": "matches_cells", + "type": { + "type": "bool" + } + }, + { + "name": "mismatches", + "type": { + "item": { + "name": "Mismatch", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "took_ms", + "type": { + "type": "f64" + } + } + ], + "name": "RebuildReport" + }, + { + "fields": [ + { + "name": "kills", + "type": { + "type": "f64" + } + }, + { + "name": "xp", + "type": { + "type": "f64" + } + } + ], + "name": "Scores" + } + ], + "schemaVersion": 3 +} diff --git a/examples/game/sveltekit/src/lib/pit/loop.ts b/examples/game/sveltekit/src/lib/pit/loop.ts new file mode 100644 index 000000000..badc35788 --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/loop.ts @@ -0,0 +1,131 @@ +/** + * The Mob Pit render and input loop: plain TypeScript on its own + * `requestAnimationFrame`, outside Svelte. It reads `client.render()` every + * frame and sends one input per server tick; the Svelte page only starts it + * and reads the slower facts (status, RTT, events) through `useGame`. + */ +import { InputPacer, type GameClient } from '@hops-ops/distributed/game'; + +import { + BUTTON, + PIT_RULES, + isMob, + isPillar, + isPlayer, + mobFields, + pillarFields, + playerFields, + type HelloEvent, + type PitInput +} from '$lib/generated/mobpit/index.ts'; + +const TIER_COLOR: Record = { 1: '#9ad16b', 2: '#b48cf2', 3: '#ff6b6b' }; +const TIER_RADIUS = Object.fromEntries(PIT_RULES.tiers.map((t) => [t.tier, t])); + +export type PitLoopOptions = Readonly<{ + client: GameClient; + hello: () => HelloEvent | undefined; + /** Steer to the nearest mob and swing (demo and headless test). */ + autoHunt: () => boolean; +}>; + +/** Start drawing on `canvas`; returns the stop function. */ +export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions): () => void { + const { client } = options; + const ctx = canvas.getContext('2d')!; + const keys = new Set(); + const down = (e: KeyboardEvent) => { + if (['KeyW', 'KeyA', 'KeyS', 'KeyD', 'Space', 'KeyE'].includes(e.code)) e.preventDefault(); + keys.add(e.code); + }; + const up = (e: KeyboardEvent) => keys.delete(e.code); + window.addEventListener('keydown', down); + window.addEventListener('keyup', up); + const pacer = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); + + const steer = (): PitInput => { + const hello = options.hello(); + const rendered = client.render(); + const me = rendered.find((e) => e.id === hello?.entity && isPlayer(e)); + if (options.autoHunt() && me !== undefined) { + const p = playerFields(me); + const target = rendered + .filter((e) => isMob(e) && !e.stale) + .map(mobFields) + .map((m) => ({ m, d: Math.hypot(m.x - p.x, m.y - p.y) })) + .sort((a, b) => a.d - b.d)[0]; + if (target === undefined || p.dead) return { mx: 0, my: 0, buttons: 0 }; + const near = target.d < 1.9; + const k = (near ? 40 : 127) / Math.max(target.d, 1e-3); + return { + mx: Math.round((target.m.x - p.x) * k), + my: Math.round((target.m.y - p.y) * k), + buttons: near ? BUTTON.attack : 0 + }; + } + const axis = (neg: string, pos: string) => (keys.has(pos) ? 127 : 0) - (keys.has(neg) ? 127 : 0); + return { + mx: axis('KeyA', 'KeyD'), + // Screen y grows downwards; world y grows upwards. + my: axis('KeyS', 'KeyW'), + buttons: (keys.has('Space') ? BUTTON.attack : 0) | (keys.has('KeyE') ? BUTTON.dash : 0) + }; + }; + + let frame = requestAnimationFrame(function draw(now) { + pacer.update(now, () => client.sendInput(steer())); + const half = options.hello()?.half ?? 12; + const { width, height } = canvas; + const scale = Math.min(width, height) / (2 * half); + const at = (x: number, y: number): [number, number] => [width / 2 + x * scale, height / 2 - y * scale]; + const circle = (x: number, y: number, r: number, fill: string, stroke?: string) => { + const [cx, cy] = at(x, y); + ctx.beginPath(); + ctx.arc(cx, cy, r * scale, 0, Math.PI * 2); + ctx.fillStyle = fill; + ctx.fill(); + if (stroke !== undefined) { + ctx.strokeStyle = stroke; + ctx.stroke(); + } + }; + ctx.fillStyle = '#120f14'; + ctx.fillRect(0, 0, width, height); + ctx.strokeStyle = '#2b2533'; + ctx.strokeRect(...at(-half, half), 2 * half * scale, 2 * half * scale); + for (const entity of client.render()) { + if (isPillar(entity)) { + const p = pillarFields(entity); + circle(p.x, p.y, p.r, '#3a3443'); + } else if (isMob(entity)) { + const m = mobFields(entity); + const look = TIER_RADIUS[m.tier]; + if (m.tele > 0 && look !== undefined) circle(m.x, m.y, look.tele, 'rgba(255,80,80,0.12)', '#ff5050'); + circle(m.x, m.y, look?.radius ?? 0.5, TIER_COLOR[m.tier] ?? '#9ad16b'); + } else if (isPlayer(entity)) { + const p = playerFields(entity); + const mine = entity.id === options.hello()?.entity; + // Own position for the headless test (a DOM attribute, not Svelte state). + if (mine) canvas.dataset.me = `${p.x.toFixed(2)},${p.y.toFixed(2)}`; + circle(p.x, p.y, 0.45, p.dead ? '#555' : mine ? '#ffd166' : '#6ec3ff'); + const [nx, ny] = at(p.x + Math.cos(p.face) * 0.6, p.y + Math.sin(p.face) * 0.6); + const [cx, cy] = at(p.x, p.y); + ctx.strokeStyle = '#fff'; + ctx.beginPath(); + ctx.moveTo(cx, cy); + ctx.lineTo(nx, ny); + ctx.stroke(); + ctx.fillStyle = '#ddd'; + ctx.font = '11px system-ui'; + ctx.fillText(p.name, cx - 16, cy - 0.7 * scale); + } + } + frame = requestAnimationFrame(draw); + }); + + return () => { + cancelAnimationFrame(frame); + window.removeEventListener('keydown', down); + window.removeEventListener('keyup', up); + }; +} diff --git a/examples/game/sveltekit/src/lib/server/game.ts b/examples/game/sveltekit/src/lib/server/game.ts new file mode 100644 index 000000000..2eef8926e --- /dev/null +++ b/examples/game/sveltekit/src/lib/server/game.ts @@ -0,0 +1,37 @@ +import { env } from '$env/dynamic/private'; +import type { RequestEvent } from '@sveltejs/kit'; +import { createGameTicketHandler } from '@hops-ops/distributed/sveltekit/game/server'; + +/** Zone admission: principal from the Auth.js session, zone chosen here. */ +export const tickets = createGameTicketHandler({ + secret: () => env.GAME_TICKET_SECRET, + getSession: (event: RequestEvent) => event.locals.auth(), + // One shared pit; a real game picks the zone the player is in or owns. + zone: () => env.PIT_ZONE ?? 'pit-1' +}); + +export type BoardRow = { rank: number; member: string; name: string; score: number }; +export type SettledFacts = { + board: { kills: BoardRow[]; xp: BoardRow[] }; + me: { kills: { score: number | null }; xp: { score: number | null } } | null; +}; + +/** + * Read model of settled kills for the first render: the Mob Pit + * leaderboard, a projection of the durable Crawler cells (dev HTTP route of + * the game server, read server-side with the session's principal). Live + * updates then arrive as the zone's `profile` and `board` events. + */ +export async function settledFacts(principal: string): Promise { + const base = env.GAME_SERVER_HTTP ?? 'http://127.0.0.1:2967'; + try { + const response = await fetch(`${base}/dev/mobpit/leaderboard?member=${encodeURIComponent(principal)}`, { + signal: AbortSignal.timeout(2_000) + }); + if (!response.ok) return null; + const { snapshot, me } = (await response.json()) as { snapshot: SettledFacts['board']; me: SettledFacts['me'] }; + return { board: { kills: snapshot.kills, xp: snapshot.xp }, me }; + } catch { + return null; + } +} diff --git a/examples/game/sveltekit/src/routes/+layout.server.ts b/examples/game/sveltekit/src/routes/+layout.server.ts new file mode 100644 index 000000000..345aa9c46 --- /dev/null +++ b/examples/game/sveltekit/src/routes/+layout.server.ts @@ -0,0 +1 @@ +export const load = async ({ locals }) => ({ session: await locals.auth() }); diff --git a/examples/game/sveltekit/src/routes/+layout.svelte b/examples/game/sveltekit/src/routes/+layout.svelte new file mode 100644 index 000000000..0f779f229 --- /dev/null +++ b/examples/game/sveltekit/src/routes/+layout.svelte @@ -0,0 +1,19 @@ + + +
    + Mob Pit · SvelteKit + {#if data.session?.user} + {data.session.user.name} +
    + {/if} +
    +{@render children()} + + diff --git a/examples/game/sveltekit/src/routes/+page.server.ts b/examples/game/sveltekit/src/routes/+page.server.ts new file mode 100644 index 000000000..46852c5ce --- /dev/null +++ b/examples/game/sveltekit/src/routes/+page.server.ts @@ -0,0 +1,3 @@ +import { signIn } from '../auth'; + +export const actions = { default: signIn }; diff --git a/examples/game/sveltekit/src/routes/+page.svelte b/examples/game/sveltekit/src/routes/+page.svelte new file mode 100644 index 000000000..d6effad11 --- /dev/null +++ b/examples/game/sveltekit/src/routes/+page.svelte @@ -0,0 +1,25 @@ + + +
    + {#if data.session?.user} +

    Signed in as {data.session.user.name}.

    + Enter the pit → + {:else} +

    Sign in

    + +
    + + + + +
    + {/if} +
    + + diff --git a/examples/game/sveltekit/src/routes/api/game/ticket/+server.ts b/examples/game/sveltekit/src/routes/api/game/ticket/+server.ts new file mode 100644 index 000000000..d385c021f --- /dev/null +++ b/examples/game/sveltekit/src/routes/api/game/ticket/+server.ts @@ -0,0 +1,3 @@ +import { tickets } from '$lib/server/game'; + +export const POST = tickets; diff --git a/examples/game/sveltekit/src/routes/pit/+page.server.ts b/examples/game/sveltekit/src/routes/pit/+page.server.ts new file mode 100644 index 000000000..45e3b75f2 --- /dev/null +++ b/examples/game/sveltekit/src/routes/pit/+page.server.ts @@ -0,0 +1,14 @@ +import { redirect } from '@sveltejs/kit'; +import { env } from '$env/dynamic/private'; +import { settledFacts, tickets } from '$lib/server/game'; + +export const load = async (event) => { + const joined = await tickets.resolve(event); + if (joined === undefined) redirect(303, '/'); + return { + zone: joined.zone, + zonesUrl: env.GAME_ZONES_URL ?? 'ws://127.0.0.1:2967', + principal: joined.principal, + settled: await settledFacts(joined.principal) + }; +}; diff --git a/examples/game/sveltekit/src/routes/pit/+page.svelte b/examples/game/sveltekit/src/routes/pit/+page.svelte new file mode 100644 index 000000000..fd8ea961f --- /dev/null +++ b/examples/game/sveltekit/src/routes/pit/+page.svelte @@ -0,0 +1,82 @@ + + +
    + + +
    + + diff --git a/examples/game/sveltekit/src/routes/signout/+page.server.ts b/examples/game/sveltekit/src/routes/signout/+page.server.ts new file mode 100644 index 000000000..e6c982b6e --- /dev/null +++ b/examples/game/sveltekit/src/routes/signout/+page.server.ts @@ -0,0 +1,3 @@ +import { signOut } from '../../auth'; + +export const actions = { default: signOut }; diff --git a/examples/game/sveltekit/svelte.config.js b/examples/game/sveltekit/svelte.config.js new file mode 100644 index 000000000..4845ff7c3 --- /dev/null +++ b/examples/game/sveltekit/svelte.config.js @@ -0,0 +1,8 @@ +import adapter from '@sveltejs/adapter-node'; +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + +/** @type {import('@sveltejs/kit').Config} */ +export default { + preprocess: vitePreprocess(), + kit: { adapter: adapter({ out: 'build' }) } +}; diff --git a/examples/game/sveltekit/tests/pit.test.mjs b/examples/game/sveltekit/tests/pit.test.mjs new file mode 100644 index 000000000..c33fc78ab --- /dev/null +++ b/examples/game/sveltekit/tests/pit.test.mjs @@ -0,0 +1,154 @@ +/** + * Headless SvelteKit demo (production build, real `game-demos mobpit`): + * dev session sign-in → the page joins the server-chosen zone with a + * session-minted ticket → keyboard movement → auto-hunt kills a mob → the + * settled fact shows up in the live read model and in the SSR read model + * after a reload → no page errors. Ports: GAME_DEMOS_PORT (default 2967) and + * SVELTEKIT_PORT (default 5573). Needs `npm run build` and the server binary + * (GAME_DEMOS_BIN, else `cargo run`). + */ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +import { chromium } from 'playwright'; + +const APP = fileURLToPath(new URL('..', import.meta.url)); +const SERVER_DIR = fileURLToPath(new URL('../../server/', import.meta.url)); +const GAME_PORT = Number(process.env.GAME_DEMOS_PORT ?? 2967); +const UI_PORT = Number(process.env.SVELTEKIT_PORT ?? 5573); +const ORIGIN = `http://127.0.0.1:${UI_PORT}`; + +function start(command, args, options, ready) { + const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] }); + let output = ''; + const up = new Promise((resolve, reject) => { + const onData = (chunk) => { + output += chunk; + if (ready.test(output)) resolve(); + }; + child.stdout.on('data', onData); + child.stderr.on('data', onData); + child.on('exit', (code) => reject(new Error(`${command} exited with ${code}:\n${output}`))); + }); + return { + up, + output: () => output, + async stop() { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((resolve) => child.on('exit', resolve)); + child.kill('SIGTERM'); + const timer = setTimeout(() => child.kill('SIGKILL'), 5000); + await exited; + clearTimeout(timer); + } + }; +} + +test('sign in, join, move, kill, settled read model updates', { timeout: 600_000 }, async () => { + const secret = randomBytes(32).toString('hex'); + const dataDir = mkdtempSync(join(tmpdir(), 'mobpit-sveltekit-')); + const bin = process.env.GAME_DEMOS_BIN; + const gameArgs = ['mobpit', '--port', String(GAME_PORT), '--dev', '--data-dir', dataDir]; + const game = bin + ? start(bin, gameArgs, { env: { ...process.env, DISTRIBUTED_GAME_SECRET: secret } }, /LISTENING/) + : start('cargo', ['run', '-q', '--', ...gameArgs], { cwd: SERVER_DIR, env: { ...process.env, DISTRIBUTED_GAME_SECRET: secret } }, /LISTENING/); + const ui = start(process.execPath, ['build'], { + cwd: APP, + env: { + ...process.env, + PORT: String(UI_PORT), + HOST: '127.0.0.1', + ORIGIN, + AUTH_SECRET: randomBytes(32).toString('hex'), + GAME_DEV_AUTH: '1', + GAME_TICKET_SECRET: secret, + GAME_ZONES_URL: `ws://127.0.0.1:${GAME_PORT}`, + GAME_SERVER_HTTP: `http://127.0.0.1:${GAME_PORT}` + } + }, /Listening on/); + let browser; + try { + await Promise.all([game.up, ui.up]); + + // No session → no ticket; a body cannot name the principal. + const anonymous = await fetch(`${ORIGIN}/api/game/ticket`, { + method: 'POST', headers: { origin: ORIGIN, 'content-type': 'application/json' }, body: '{"zone":"pit-1"}' + }); + assert.equal(anonymous.status, 401); + assert.equal(anonymous.headers.get('cache-control'), 'no-store'); + + browser = await chromium.launch(); + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`)); + page.on('console', (message) => message.type() === 'error' && errors.push(`console: ${message.text()}`)); + + await page.goto(ORIGIN); + await page.fill('input[name=username]', 'ana'); + await page.click('[data-testid=signin]'); + await page.waitForURL(`${ORIGIN}/pit`); + assert.equal(await page.textContent('[data-testid=user]'), 'ana'); + + // With the session cookie: a ticket for the server's zone; a smuggled + // principal, a foreign zone or a cross-site origin is refused. + const cookie = (await page.context().cookies()).map((c) => `${c.name}=${c.value}`).join('; '); + const ticket = (body, origin = ORIGIN) => + fetch(`${ORIGIN}/api/game/ticket`, { method: 'POST', headers: { cookie, origin, 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const minted = await ticket({ zone: 'pit-1' }); + assert.equal(minted.status, 200); + const claims = JSON.parse(Buffer.from((await minted.json()).ticket.split('.')[1], 'base64url').toString()); + assert.equal(claims.sub, 'dev-ana'); + assert.equal((await ticket({ zone: 'pit-1', principal: 'admin' })).status, 400); + assert.equal((await ticket({ zone: 'pit-2' })).status, 409); + assert.equal((await ticket({ zone: 'pit-1' }, 'http://evil.example')).status, 403); + + // HUD: connected to the server-chosen zone, RTT measured, WASM prediction loaded. + await page.waitForSelector('[data-testid=status]:text-is("open")', { timeout: 30_000 }); + assert.equal(await page.textContent('[data-testid=zone]'), 'pit-1'); + await page.waitForFunction(() => /^\d+$/.test(document.querySelector('[data-testid=rtt]')?.textContent ?? ''), null, { timeout: 10_000 }); + await page.waitForSelector('[data-testid=prediction]:text-is("wasm")', { timeout: 10_000 }); + + // Movement (keyboard → predicted + authoritative position). + await page.waitForFunction(() => document.querySelector('canvas')?.dataset.me !== undefined, null, { timeout: 10_000 }); + const start = await page.evaluate(() => document.querySelector('canvas').dataset.me.split(',').map(Number)); + await page.keyboard.down('KeyD'); + await page.waitForTimeout(700); + await page.keyboard.up('KeyD'); + const moved = await page.evaluate(() => document.querySelector('canvas').dataset.me.split(',').map(Number)); + assert.ok(moved[0] > start[0] + 0.5 || Math.hypot(moved[0] - start[0], moved[1] - start[1]) > 0.5, `moved ${start} → ${moved}`); + + // Settled fact: auto-hunt kills a mob; the cell commit settles; the + // live read model (profile + board pushes) shows it. + assert.equal(await page.textContent('[data-testid=xp]'), '0'); + await page.check('[data-testid=autohunt]'); + await page.waitForFunction(() => Number(document.querySelector('[data-testid=xp]')?.textContent) > 0, null, { timeout: 90_000 }); + await page.waitForSelector('.saved', { timeout: 10_000 }); + await page.waitForSelector('[data-testid=settled] li.me', { timeout: 10_000 }); + await page.uncheck('[data-testid=autohunt]'); + await page.waitForFunction(() => document.querySelector('[data-testid=unsaved]')?.textContent === '0', null, { timeout: 15_000 }); + const xp = Number(await page.textContent('[data-testid=xp]')); + const kills = Number(await page.textContent('[data-testid=kills]')); + assert.ok([10, 25, 60].some((tier) => xp >= tier) && kills >= 1, `xp ${xp} kills ${kills}`); + + // SSR read model after a reload: the settled numbers are in the HTML. + const html = await page.evaluate(() => fetch('/pit', { headers: { accept: 'text/html' } }).then((r) => r.text())); + assert.match(html, new RegExp(`data-testid="kills"[^>]*>${kills}<`)); + + // Navigation away disposes the client (no errors, socket closed). + await page.click('header a'); + await page.waitForURL(`${ORIGIN}/`); + await page.waitForTimeout(300); + assert.deepEqual(errors, []); + } finally { + await browser?.close(); + await ui.stop(); + await game.stop(); + rmSync(dataDir, { recursive: true, force: true }); + } +}); diff --git a/examples/game/sveltekit/tsconfig.json b/examples/game/sveltekit/tsconfig.json new file mode 100644 index 000000000..e58c40719 --- /dev/null +++ b/examples/game/sveltekit/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "noEmit": true, + "verbatimModuleSyntax": true + } +} diff --git a/examples/game/sveltekit/vite.config.ts b/examples/game/sveltekit/vite.config.ts new file mode 100644 index 000000000..c5e423b9c --- /dev/null +++ b/examples/game/sveltekit/vite.config.ts @@ -0,0 +1,10 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { distributedSvelteKit } from '@hops-ops/distributed/sveltekit/vite'; +import { defineConfig } from 'vite'; + +import { distributedViteOptions } from './distributed.config.js'; + +export default defineConfig({ + plugins: [distributedSvelteKit(distributedViteOptions), sveltekit()], + server: { port: Number(process.env.PORT ?? 5573), strictPort: true } +}); From 3f8232b31669dd711d1967a9abac7b1f9d4d44c1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:38:38 -0500 Subject: [PATCH 207/484] docs: SvelteKit integration for game zones Document session tickets, Vite-generated game clients and the runes state in the js and distributed_game READMEs, and the SvelteKit Mob Pit demo in the examples README. --- distributed_game/README.md | 46 ++++++++++++++- examples/game/README.md | 73 ++++++++++++++++++++++- js/README.md | 118 ++++++++++++++++++++++++++++++++++++- 3 files changed, 230 insertions(+), 7 deletions(-) diff --git a/distributed_game/README.md b/distributed_game/README.md index e2442b9da..fc9fee873 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -25,7 +25,7 @@ the browser, but the client SDK has no rendering dependency. - [Try it](#try-it) - [Build a zone](#build-a-zone) - [Guides](#guides): game loop · input · what clients see · the client SDK · - generated clients · client prediction (Rust → WebAssembly) · shared + generated clients · SvelteKit apps · client prediction (Rust → WebAssembly) · shared logic and data (no TypeScript twins) · saving progress · scaling out · live updates · lag compensation · testing and operations · security - [Design decisions](#design-decisions) @@ -434,6 +434,45 @@ removes the hand-written glue around it. The compiled module pure functions) is a build output: ignore `wasm/` in version control and build it before bundling. +### SvelteKit apps + +`@hops-ops/distributed` integrates zones with SvelteKit where it removes +boilerplate — admission, code generation and the HUD around the game — and +leaves the canvas and render loop to you (game state is never +server-rendered). Full API: [js README](../js/README.md#game-zones-in-sveltekit); +runnable: [`examples/game/sveltekit`](../examples/game/sveltekit) +(`examples/game/run.sh sveltekit`). + +1. **Tickets from the session.** `createGameTicketHandler` (server-only, + `@hops-ops/distributed/sveltekit/game/server`) is a `POST` route that + signs this crate's ticket format (§8, HS256 with the zone servers' + `TicketKey` secret) for the app's **verified session** principal and the + zone **your server code** chooses. The browser may only hint `{ zone, + role }`; any other body field is refused, so identity, ownership and + rewards never come from the request. Same-origin, a per-principal rate + limit and `cache-control: no-store` are built in; the zone server still + enforces signature, zone, expiry and single use. `js/tests` reproduce + `tests/fixtures/sveltekit_tickets.json` byte for byte and `net_e2e` + admits those tickets on a real `GameServer` (and refuses tampered, + expired, wrong-zone and replayed ones). +2. **Clients generated by Vite.** `distributedSvelteKit({ games: [...] })` + runs `game-manifest` → `game-client` → `game-wasm` on dev start, on Rust + changes and on build; `checkDistributedGames` is the CI check. +3. **Runes state.** `useGame(() => createClient({ url, ticket: + gameTicketSource() }), { zone, events: EVENTS })` gives reactive + `status`, `zone`, `rttMs`, `predictionReady`, `error` and typed + `latest(event)` / `events(event)`; it connects on mount and closes on + destroy or navigation. + +```ts +// src/routes/api/game/ticket/+server.ts +export const POST = createGameTicketHandler({ + secret: () => env.GAME_TICKET_SECRET, + getSession: (event) => event.locals.auth(), + zone: ({ principal }) => zoneFor(principal) +}); +``` + ### Client prediction (Rust → WebAssembly) Prediction is an optimistic update at tick rate: the client applies each @@ -696,8 +735,9 @@ unlimited rewind. ### Security - Players are admitted only with a signed, single-use, expiring ticket. - Your web backend mints it; plug in your own verifier with - `with_ticket_verifier`. + Your web backend mints it (in SvelteKit, `createGameTicketHandler` binds + it to the verified session — see [SvelteKit apps](#sveltekit-apps)); plug + in your own verifier with `with_ticket_verifier`. - The ticket's principal is the only identity the zone sees, and the only one attached to facts. Inputs are game data, never identity, owner or reward amounts. diff --git a/examples/game/README.md b/examples/game/README.md index 9565cb1b2..d19251ab0 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -14,10 +14,11 @@ guests and lets any page change the network simulation. | **Shooting Gallery** | `./run.sh gallery` | Lag compensation: hitscan shots resolved with `ctx.rewind().hit_test_shot` at the shooter's view time (`client_tick` + interpolation delay in the payload), `max_rewind` clamp, per-shot compensation on/off, predicted vs confirmed hits | | **The Freeze** | `./run.sh freeze` | World-version barrier (`WorldCoordinator::rollout`) across **two server processes** as an in-world "admin update": freeze → apply → resume with change notes, inputs dropped while frozen, Hard reload vs safe-room gating (`StalePolicy::SafeRoom`, `Zone::is_gate`) of old clients, aborted rollout (`freeze_ready` → `NotAcked`), facts/events stamped with the content version | | **Endless Grid** | `./run.sh grid` | Seeded procedural world (terrain/biomes/props generated bit-identically in Rust and TS, nothing static replicated), 32 m cells as zones, observer connections to the 8 neighbours, handoff across borders **and hosts** (2 processes, hash ring, Redirect + transfer tickets), hibernation to SQLite and restore | +| **Mob Pit · SvelteKit** | `./run.sh sveltekit` | The same Mob Pit server behind a SvelteKit app: Auth.js session sign-in, admission tickets minted from the session (`createGameTicketHandler`), the game client and WASM step generated by the Vite plugin (`games`), a runes HUD (`useGame`) next to a plain canvas loop, and a settled-kill read model (SSR, then live zone pushes). See [SvelteKit](#sveltekit) | | **Boss Ripple** | `./run.sh ripple` | Zone hierarchy realm › city › borough › hood (`DottedTopology`), per-tier tick rates (2/5/10/30 Hz), boss defeats propagating up as tier-up events (each hop on another host), parent broadcasts reaching players through observer connections | `./run.sh smoke` runs every demo's smoke tests (and checks the generated -clients are current); `./run.sh gen` regenerates the clients; `./run.sh +clients are current, and drives the SvelteKit demo headlessly); `./run.sh gen` regenerates the clients; `./run.sh list` lists demos. **How the demos are written.** Each zone describes its world with the @@ -207,6 +208,60 @@ tier's state is its hibernation snapshot. The page shows the tree with each tier's host, rate and clock, animates each hop, and lets you click a hood to fight there. +## SvelteKit + +```sh +examples/game/run.sh sveltekit # → http://localhost:5573/ — sign in with any username +``` + +`sveltekit/` is Mob Pit as a SvelteKit app. The script starts `game-demos +mobpit --dev` on `GAME_DEMOS_PORT` (default 2967 here; data in +`.data/mobpit-sveltekit`) with a fresh ticket secret and runs `vite dev` on +`SVELTEKIT_PORT` (default 5573) with the same secret. What each piece +replaces: + +- **Sign-in and tickets.** `src/auth.ts` is Auth.js, the session mechanism + of the framework's SvelteKit apps (`tests/e2e-ui`): with `OIDC_ISSUER` + set it uses OIDC; locally `GAME_DEV_AUTH=1` enables a **dev-only** + username sign-in (`dev-` principal, same encrypted session + cookie, nothing external). `src/lib/server/game.ts` is the whole ticket + path: `createGameTicketHandler({ secret, getSession: (e) => + e.locals.auth(), zone: () => 'pit-1' })`, exported as `POST` from + `routes/api/game/ticket/+server.ts`. The principal comes from the session, + the zone from the server; a body naming a principal is refused (400), a + foreign zone gets 409, another origin 403, no session 401. The page's + `load` uses `tickets.resolve(event)` for the same zone. There is no + `/dev/ticket` call and no guest token. +- **Code generation.** `distributed.config.js` lists the Mob Pit surface for + the Vite plugin; `vite dev` / `vite build` run `game-manifest`, + `game-client` and `game-wasm` (watching `server/src` and `server/sim`, so + editing the zone or `pit_step` regenerates and reloads). The TypeScript in + `src/lib/generated/mobpit/` is checked in and verified by `npm run + check:games`; `wasm/` is a build output. No `run.sh gen` step. +- **HUD.** `routes/pit/+page.svelte` calls `useGame(() => + createMobpitClient({ url, ticket: gameTicketSource() }), { zone, events: + EVENTS })` and renders `status`, `zone`, `rttMs`, `predictionReady`, + `error`, `latest('profile')`, `latest('board')`, `events('kill')` and + `events('saved')` as Svelte markup. `src/lib/pit/loop.ts` is the + canvas render and input loop (one input per tick via `InputPacer`), plain + TypeScript started from an `$effect`; Svelte never sees per-frame state. + **Auto-hunt** steers to the nearest mob (used by the headless test). +- **Settled read model.** The *Settled* panel shows your XP and kills from + durable Crawler cells and the XP board. The first render comes from the + page `load`, which reads the leaderboard projection server-side for the + session principal (`GET /dev/mobpit/leaderboard?member=`, a dev route); + afterwards the zone's `profile` (sent after each fact settles) and `board` + pushes update it live. Kills show as "saving" until their `saved` event. + The business side's GraphQL `@live` queries would need a Distributed + service with SQL read models projecting these facts, which Mob Pit does + not have; the zone's settled pushes are the existing live channel. + +`./run.sh smoke` runs `check:games`, `svelte-check`, `vite build` and +`tests/pit.test.mjs`: the production build (`node build`) against the real +server in headless Chromium — sign-in, ticket rejection paths, join, +keyboard movement, auto-hunt until a kill settles, the live and the +server-rendered read model, navigation away, no page errors. + ## Architecture ``` @@ -279,6 +334,14 @@ examples/game/ mobpit_smoke.rs (facts, slow storage, kill -9 recovery, boards), gallery_smoke.rs, freeze_smoke.rs (binary content packs), grid_smoke.rs, ripple_smoke.rs (+ support/ for two in-process hosts) + sveltekit/ SvelteKit app over the Mob Pit server (see SvelteKit above) + distributed.config.js game surface for the Vite plugin (`games`) + src/auth.ts Auth.js (OIDC, or dev username sign-in with GAME_DEV_AUTH=1) + src/lib/server/game.ts createGameTicketHandler + settled read model (server-side) + src/lib/generated/mobpit generated by the Vite plugin (TypeScript checked in, wasm/ ignored) + src/lib/pit/loop.ts canvas render + input loop (outside Svelte) + src/routes/pit/ load (zone, read model) + page (useGame HUD, settled panel) + tests/pit.test.mjs headless Playwright against `node build` + game-demos client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/generated// generated by `run.sh gen` (do not edit): schema/input/events/client.ts, @@ -480,3 +543,11 @@ over the hosts, `cluster_server`, optional dev routes), uses - `/dev/netsim` changes the simulation for every connection on the server. - The ticket secret is random per process unless `DISTRIBUTED_GAME_SECRET` is set (needed to point `game-bots` at a running demo). +- The SvelteKit demo does not use `/dev/ticket`: its tickets are minted by + the SvelteKit server from the Auth.js session. It is still dev only: the + game server runs with `--dev` (the page's first render reads + `/dev/mobpit/leaderboard`, and `/dev/*` stays reachable on 127.0.0.1), + and `GAME_DEV_AUTH=1` lets anyone sign in with any username. A real + deployment sets the OIDC variables, leaves `GAME_DEV_AUTH` unset, runs + the zone servers without `--dev` and serves the read model from its own + backend. diff --git a/js/README.md b/js/README.md index db83307df..a0fd64750 100644 --- a/js/README.md +++ b/js/README.md @@ -414,6 +414,110 @@ Use a separate generated surface and replica for elevated routes. A normal client cannot import or mix admin artifacts. Configure it as a separate virtual module such as `$distributed/admin` and provide it only in the elevated layout. +### Game zones in SvelteKit + +`distributed_game` zones get three pieces; the canvas, render loop and +entity drawing stay outside Svelte, and game state is never server-rendered. +Svelte 5.7+ is required (`svelte/reactivity`). A runnable example is +[`examples/game/sveltekit`](../examples/game/sveltekit). + +**1. Generated game clients from the Vite plugin.** Add `games` to the same +plugin. Each surface runs `distributed game-manifest` → `game-client` → +`game-wasm` (the `#[predict]` step and `#[game_pure]` functions) when Vite +starts, when the zone's Rust sources change (a full reload follows only if +an output changed), and once per `vite build`; Vite emits the WebAssembly as +an asset through the generated `new URL('./wasm/.wasm', +import.meta.url)`. Game surfaces are not lifecycle outputs, so a games-only +app runs under plain `vite dev` / `vite build`; GraphQL `clients` still need +`distributed dev` / `distributed build`. + +```js +// distributed.config.js +export const distributedViteOptions = { + games: [{ + manifest: { + args: ['game-manifest', '--manifest-path', '../game/Cargo.toml', + '--entrypoint', 'my_game::pit::game_surface'] + }, + out: 'src/lib/generated/pit', + watch: ['../game-sim'] // extra crates whose changes regenerate (optional) + // wasm: 'auto' (default) | false | { manifestPath } + // importExtension: 'ts' (default) | 'js' | 'none' + }] +}; +// vite.config.ts: plugins: [distributedSvelteKit(distributedViteOptions), sveltekit()] +``` + +Commit the generated TypeScript (keep `wasm/` ignored) and check it in CI +with `checkDistributedGames(distributedViteOptions)` from +`@hops-ops/distributed/sveltekit/vite` (`game-client --check`, never writes; +`generateDistributedGames` runs the full pipeline once). `command` / +`commandArgs` choose the CLI exactly as for GraphQL clients. + +**2. Session-bound tickets** (`@hops-ops/distributed/sveltekit/game/server`, +server-only). The route mints the zone server's HS256 admission ticket +(PROTOCOL.md §8) with WebCrypto, so the shared secret stays on the SvelteKit +server and no extra admission service is needed: + +```ts +// src/lib/server/game.ts +import { env } from '$env/dynamic/private'; +import { createGameTicketHandler } from '@hops-ops/distributed/sveltekit/game/server'; + +export const tickets = createGameTicketHandler({ + secret: () => env.GAME_TICKET_SECRET, // the zone servers' TicketKey (>= 32 bytes) + getSession: (event) => event.locals.auth(), // the same session source as GraphQL + zone: ({ principal, requested }) => zoneFor(principal) // decided here, never by the body +}); +// src/routes/api/game/ticket/+server.ts +export const POST = tickets; +// a +page.server.ts load: const { zone, principal } = await tickets.resolve(event) +``` + +The principal is `session.user.id` (override with `principal(session)`; +`name(session)` sets the ticket's display name). The handler answers 403 +unless the `Origin` is the app's own (`allowedOrigins` adds more) and +`Sec-Fetch-Site`, when sent, is `same-origin`; 401 without a session; 429 +over the per-principal limit (default 10 per minute, in memory; +`rateLimit: { max, windowMs }`, a custom `{ take(key, now) }`, or `false`); +400 for any body field other than `zone` / `role` (so a body cannot name the +principal, an owner or a reward); 409 with the server's zone when the +requested zone differs; 403 when `zone` returns nothing; 503 without a valid +secret. Every response is `cache-control: no-store`. Tickets live 60 s by +default (`ttlSeconds` ≤ 300) and are single use on the zone server. +`mintGameTicket({ secret, principal, zone, role, name })` signs one directly. + +**3. Runes state for the UI around the game** +(`@hops-ops/distributed/sveltekit/game`, browser-safe): + +```svelte + +

    {game.status} · {game.zone} · {game.rttMs ?? '–'} ms · {game.predictionReady ? 'predicted' : '…'}

    +

    XP {profile.current?.xp ?? 0} · last kills {kills.items.length}

    +``` + +`useGame` builds the client on mount (browser only, nothing during SSR), +joins the zone and closes it on destroy, which includes navigation. +`createGameState(source | factory, { events })` is the same state without the +lifecycle (`connect(zone)`, `dispose()`). Getters — `status`, `connected`, +`zone` (follows handoffs), `rttMs`, `jitterMs`, `predictionReady`, `error`, +`client`, `source` — and `latest(name).current` / `events(name).items` are +reactive through `createSubscriber`: an unchanged value does not re-run +effects. `on(name, handler)` subscribes a callback (e.g. to set the +controlled entity from a `hello`). `gameTicketSource({ endpoint })` POSTs +`{ zone, role }` to the ticket route with the session cookie. + ## Framework-neutral replica Other frameworks can bind the same core directly: @@ -576,7 +680,9 @@ explicit redactor. ## Game zones `@hops-ops/distributed/game` speaks the `distributed_game` binary protocol -(golden-tested against the Rust fixtures). The app supplies tickets — a +(golden-tested against the Rust fixtures). In SvelteKit, see +[game zones in SvelteKit](#game-zones-in-sveltekit) for session tickets, +Vite-generated clients and runes state. The app supplies tickets — a function, so a fresh single-use ticket is fetched whenever a reconnect token can no longer be used — and a pure `predict` for its own entity. With a [generated client](#generated-game-clients) that `predict` is the zone's @@ -727,8 +833,14 @@ duplicated as decision documents in this package. inspection. - `@hops-ops/distributed/sveltekit` — Svelte stores, island SSR composition, hydration, auth lifecycle, and tree-local generated bindings. -- `@hops-ops/distributed/sveltekit/vite` — public Vite plugin, virtual module - aliases, and GraphQL HTTP/WebSocket proxy helpers. +- `@hops-ops/distributed/sveltekit/vite` — public Vite plugin (GraphQL + clients and `games` surfaces), virtual module aliases, GraphQL + HTTP/WebSocket proxy helpers, `generateDistributedGames` / + `checkDistributedGames`. +- `@hops-ops/distributed/sveltekit/game` — runes state for the UI around a + game zone (`useGame`, `createGameState`) and `gameTicketSource`. +- `@hops-ops/distributed/sveltekit/game/server` — server-only + `createGameTicketHandler` and `mintGameTicket` (session-bound zone tickets). - `@hops-ops/distributed/react` — provider and query hook over the same replica. - `@hops-ops/distributed/game` — binary `distributed_game` zone protocol client: codec, `GameConnection` (handshake, reconnect, clock sync), From ad74160114f96e17fdb55f6d5ddb146e2c51229f Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 15:43:45 -0500 Subject: [PATCH 208/484] style(examples): fix grid smoke fmt and int_plus_one lint --- examples/game/server/tests/grid_smoke.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/game/server/tests/grid_smoke.rs b/examples/game/server/tests/grid_smoke.rs index 09d0cb6bd..62928d557 100644 --- a/examples/game/server/tests/grid_smoke.rs +++ b/examples/game/server/tests/grid_smoke.rs @@ -179,7 +179,7 @@ async fn empty_cell_hibernates_and_restores_critters_and_markers() { eventually("hibernation save", || { let server = owner.demo.server.clone(); async move { - !server.is_active(zone) && server.metrics().hibernation_saves("saved") >= saves_before + 1 + !server.is_active(zone) && server.metrics().hibernation_saves("saved") > saves_before } }) .await; From a223da66c682e00b878c9c2f5ebe6ba1d0c059cb Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 16:57:23 -0500 Subject: [PATCH 209/484] fix(cli): serialize manifest harness runs per package and mode Every entrypoint of a package shares one harness directory. Two runs at once (a dev-server watcher beside a manual regenerate) overwrote each other's main.rs, so both exported the last writer's surface: 10 of 15 concurrent game-manifest runs were wrong. Hold a file lock from writing main.rs until the output is read. --- distributed_cli/src/manifest_harness.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/distributed_cli/src/manifest_harness.rs b/distributed_cli/src/manifest_harness.rs index 44fe0249c..eb6731476 100644 --- a/distributed_cli/src/manifest_harness.rs +++ b/distributed_cli/src/manifest_harness.rs @@ -90,6 +90,12 @@ pub(crate) fn run_manifest_harness( .join(&package.name); let harness_dir = harness_root.join(mode.cache_key()); fs::create_dir_all(harness_dir.join("src"))?; + // One harness directory serves every entrypoint of this package and mode: + // hold it from writing `main.rs` until its output is read, or a concurrent + // run (a dev-server watcher next to a manual regenerate) swaps entrypoints + // under us and both print the last writer's export. + let lock = fs::File::create(harness_root.join(format!("{}.lock", mode.cache_key())))?; + fs2::FileExt::lock_exclusive(&lock)?; fs::write( harness_dir.join("Cargo.toml"), harness_cargo_toml( From abd690e235a33bf70bae8e2bfa0f6d4d0e46e8d5 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 16:57:24 -0500 Subject: [PATCH 210/484] feat(examples): draw player swings in blue from shared pit rules The SvelteKit Mob Pit drew mob telegraphs but not player swings. Both clients now draw the swing cone in blue from PIT_RULES (reach, half angle, swing frames) instead of the 3D demo's hard-coded 2.2 m. --- .../client/src/generated/mobpit/constants.ts | 5 ++++- .../client/src/generated/mobpit/events.ts | 3 +++ .../client/src/generated/mobpit/surface.json | 21 +++++++++++++++++++ examples/game/client/src/mobpit/main.ts | 14 ++++++++----- examples/game/server/src/mobpit/zone.rs | 9 ++++++++ .../src/lib/generated/mobpit/constants.ts | 5 ++++- .../src/lib/generated/mobpit/events.ts | 3 +++ .../src/lib/generated/mobpit/surface.json | 21 +++++++++++++++++++ examples/game/sveltekit/src/lib/pit/loop.ts | 21 ++++++++++++++++++- 9 files changed, 94 insertions(+), 8 deletions(-) diff --git a/examples/game/client/src/generated/mobpit/constants.ts b/examples/game/client/src/generated/mobpit/constants.ts index 2e4517bda..0e96cb0ab 100644 --- a/examples/game/client/src/generated/mobpit/constants.ts +++ b/examples/game/client/src/generated/mobpit/constants.ts @@ -10,5 +10,8 @@ export const PIT_RULES: PitRules = { { tier: 2, radius: 0.699999988079071, tele: 2.200000047683716 }, { tier: 3, radius: 0.800000011920929, tele: 2.5999999046325684 } ], - states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'] + states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'], + attackRange: 2.200000047683716, + attackHalfAngle: 1.0471975803375244, + swingFrames: 6 }; diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts index d2e63390a..c748ce269 100644 --- a/examples/game/client/src/generated/mobpit/events.ts +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -142,6 +142,9 @@ export interface MoveState { export interface PitRules { readonly tiers: readonly MobTier[]; readonly states: readonly string[]; + readonly attackRange: number; + readonly attackHalfAngle: number; + readonly swingFrames: number; } /** Record `Profile` (`#[derive(GameRecord)]`). */ diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json index f6b182a2f..05ed196c4 100644 --- a/examples/game/client/src/generated/mobpit/surface.json +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -7,6 +7,8 @@ "type": "record" }, "value": { + "attack_half_angle": 1.0471975803375244, + "attack_range": 2.200000047683716, "states": [ "idle", "chase", @@ -15,6 +17,7 @@ "return", "dead" ], + "swing_frames": 6, "tiers": [ { "radius": 0.5, @@ -828,6 +831,24 @@ }, "type": "list" } + }, + { + "name": "attack_range", + "type": { + "type": "f32" + } + }, + { + "name": "attack_half_angle", + "type": { + "type": "f32" + } + }, + { + "name": "swing_frames", + "type": { + "type": "u8" + } } ], "name": "PitRules" diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index e1af20b90..661a50e94 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -17,6 +17,7 @@ import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { BUTTON, + PIT_RULES, isMob, isPillar, isPit, @@ -36,6 +37,9 @@ import { createMobPitClient, DEFAULT_ZONE, MobPitApi, TIERS } from './client.ts' /** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; +/** Swing cone, from the server's rules: reach to a mob's edge, plus the body. */ +const { attackRange, attackHalfAngle: SWING_HALF, swingFrames: SWING_FRAMES } = PIT_RULES; +const ATTACK_REACH = attackRange + PLAYER_RADIUS; const SLOW_MS = 1500; const params = new URLSearchParams(location.search); @@ -106,7 +110,7 @@ const mats = { dead: material(scene, 'dead', '#555555', 0.4), pillar: material(scene, 'pillar', '#5d5566'), blade: material(scene, 'blade', '#e8eef7'), - swing: material(scene, 'swing', '#ffffff', 0.18), + swing: material(scene, 'swing', '#4da3ff', 0.3), hpBack: material(scene, 'hp-back', '#1b1b1b'), hpFill: material(scene, 'hp-fill', '#e04848'), tele: material(scene, 'tele', '#ff3b3b', 0.25), @@ -139,7 +143,7 @@ function createPlayer(entity: RenderedEntity, mine: boolean): PlayerVisual { const blade = MeshBuilder.CreateBox(`${entity.key}-blade`, { width: 1.6, height: 0.08, depth: 0.14 }, scene); blade.material = mats.blade; // Swing wedge: 120° (the server's cone), flat on the floor. - const arc = flatDisc(`${entity.key}-arc`, 2.2 + PLAYER_RADIUS, mats.swing, 1 / 3); + const arc = flatDisc(`${entity.key}-arc`, ATTACK_REACH, mats.swing, SWING_HALF / Math.PI); return { kind: 'player', body, blade, arc, nose }; } @@ -338,8 +342,8 @@ stage.onFrame((now, dtMs) => { visual.body.material = dead ? mats.dead : mine ? mats.me : mats.other; visual.nose.position.copyFrom(toWorld(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3)); visual.nose.rotation.y = -face; - // Blade sweeps through the 120° cone while `swing` counts down (6 → 0). - const sweep = swing > 0 ? ((6 - swing) / 6) * (Math.PI * 2 / 3) - Math.PI / 3 : -Math.PI / 2.5; + // Blade sweeps through the swing cone while `swing` counts down to 0. + const sweep = swing > 0 ? ((SWING_FRAMES - swing) / SWING_FRAMES) * 2 * SWING_HALF - SWING_HALF : -Math.PI / 2.5; const a = face + sweep; visual.blade.position.copyFrom(toWorld(x + Math.cos(a) * 0.8, y + Math.sin(a) * 0.8, 1.0)); visual.blade.rotation.y = -a; @@ -348,7 +352,7 @@ stage.onFrame((now, dtMs) => { if (swing > 0) { visual.arc.position.copyFrom(toWorld(x, y, 0.05)); // Disc arcs start at +x and run counter-clockwise; centre it on `face`. - visual.arc.rotation.y = -(face - Math.PI / 3); + visual.arc.rotation.y = -(face - SWING_HALF); } const label = `${player.name} · L${player.level} · ${player.hp} HP`; stage.labels.set(entity.key, visual.body, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index 7336e4a35..22375c768 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -306,6 +306,12 @@ pub struct PitRules { pub tiers: Vec, /// `state` names by value. pub states: Vec, + /// Melee reach (m, from the player's centre to the mob's edge). + pub attack_range: f32, + /// Half angle of the swing cone (radians). + pub attack_half_angle: f32, + /// Swing animation length (ticks; the player's `swing` counts down from it). + pub swing_frames: u8, } /// The `PIT_RULES` constant. @@ -319,6 +325,9 @@ pub fn pit_rules() -> PitRules { }) .collect(), states: MOB_STATES.map(String::from).to_vec(), + attack_range: ATTACK_RANGE, + attack_half_angle: ATTACK_ARC_COS.acos(), + swing_frames: SWING_FRAMES, } } diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts index 2e4517bda..0e96cb0ab 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts @@ -10,5 +10,8 @@ export const PIT_RULES: PitRules = { { tier: 2, radius: 0.699999988079071, tele: 2.200000047683716 }, { tier: 3, radius: 0.800000011920929, tele: 2.5999999046325684 } ], - states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'] + states: ['idle', 'chase', 'windup', 'recover', 'return', 'dead'], + attackRange: 2.200000047683716, + attackHalfAngle: 1.0471975803375244, + swingFrames: 6 }; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts index d2e63390a..c748ce269 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts @@ -142,6 +142,9 @@ export interface MoveState { export interface PitRules { readonly tiers: readonly MobTier[]; readonly states: readonly string[]; + readonly attackRange: number; + readonly attackHalfAngle: number; + readonly swingFrames: number; } /** Record `Profile` (`#[derive(GameRecord)]`). */ diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json index f6b182a2f..05ed196c4 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json +++ b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json @@ -7,6 +7,8 @@ "type": "record" }, "value": { + "attack_half_angle": 1.0471975803375244, + "attack_range": 2.200000047683716, "states": [ "idle", "chase", @@ -15,6 +17,7 @@ "return", "dead" ], + "swing_frames": 6, "tiers": [ { "radius": 0.5, @@ -828,6 +831,24 @@ }, "type": "list" } + }, + { + "name": "attack_range", + "type": { + "type": "f32" + } + }, + { + "name": "attack_half_angle", + "type": { + "type": "f32" + } + }, + { + "name": "swing_frames", + "type": { + "type": "u8" + } } ], "name": "PitRules" diff --git a/examples/game/sveltekit/src/lib/pit/loop.ts b/examples/game/sveltekit/src/lib/pit/loop.ts index badc35788..8cf8e7509 100644 --- a/examples/game/sveltekit/src/lib/pit/loop.ts +++ b/examples/game/sveltekit/src/lib/pit/loop.ts @@ -21,6 +21,10 @@ import { const TIER_COLOR: Record = { 1: '#9ad16b', 2: '#b48cf2', 3: '#ff6b6b' }; const TIER_RADIUS = Object.fromEntries(PIT_RULES.tiers.map((t) => [t.tier, t])); +const PLAYER_RADIUS = 0.45; +/** Swing cone, from the server's rules (reach to a mob's edge, plus the body). */ +const SWING_REACH = PIT_RULES.attackRange + PLAYER_RADIUS; +const SWING_HALF = PIT_RULES.attackHalfAngle; export type PitLoopOptions = Readonly<{ client: GameClient; @@ -107,7 +111,22 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) const mine = entity.id === options.hello()?.entity; // Own position for the headless test (a DOM attribute, not Svelte state). if (mine) canvas.dataset.me = `${p.x.toFixed(2)},${p.y.toFixed(2)}`; - circle(p.x, p.y, 0.45, p.dead ? '#555' : mine ? '#ffd166' : '#6ec3ff'); + if (p.swing > 0 && !p.dead) { + // The swing cone (blue), fading as `swing` counts down. + const fade = p.swing / PIT_RULES.swingFrames; + ctx.beginPath(); + ctx.moveTo(...at(p.x, p.y)); + for (let i = 0; i <= 16; i += 1) { + const a = p.face - SWING_HALF + (2 * SWING_HALF * i) / 16; + ctx.lineTo(...at(p.x + Math.cos(a) * SWING_REACH, p.y + Math.sin(a) * SWING_REACH)); + } + ctx.closePath(); + ctx.fillStyle = `rgba(77,163,255,${0.12 + 0.25 * fade})`; + ctx.fill(); + ctx.strokeStyle = '#4da3ff'; + ctx.stroke(); + } + circle(p.x, p.y, PLAYER_RADIUS, p.dead ? '#555' : mine ? '#ffd166' : '#6ec3ff'); const [nx, ny] = at(p.x + Math.cos(p.face) * 0.6, p.y + Math.sin(p.face) * 0.6); const [cx, cy] = at(p.x, p.y); ctx.strokeStyle = '#fff'; From b056b63365769901a79066a53e4726ef0e4407d5 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 17:33:48 -0500 Subject: [PATCH 211/484] fix(game): wait for other writers in the SQLite zone-state store Hosts sharing one state file failed at once with "database is locked" (the grid smoke flake): the store set no busy timeout, and the WAL switch at open never waits on one. Set a 5 s busy timeout and retry the open setup until the same deadline. Test: 8 stores open one file and save concurrently (failed 1 in 3 before, 40/40 after). --- distributed_game/src/world/state.rs | 79 +++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 10 deletions(-) diff --git a/distributed_game/src/world/state.rs b/distributed_game/src/world/state.rs index ef7e6fad1..e0667a870 100644 --- a/distributed_game/src/world/state.rs +++ b/distributed_game/src/world/state.rs @@ -132,16 +132,35 @@ impl SqliteZoneStateStore { } fn from_connection(conn: rusqlite::Connection) -> Result { - conn.execute_batch( - "PRAGMA journal_mode=WAL; - CREATE TABLE IF NOT EXISTS game_zone_state ( - zone_id TEXT PRIMARY KEY, - token INTEGER NOT NULL, - content_version TEXT NOT NULL, - state BLOB NOT NULL - );", - ) - .map_err(backend)?; + // Hosts sharing one file collide on writes; wait for the other writer + // instead of failing at once with "database is locked". + const BUSY: std::time::Duration = std::time::Duration::from_secs(5); + conn.busy_timeout(BUSY).map_err(backend)?; + // The WAL switch at open does not use the busy handler, so two hosts + // opening the file together retry it until the same deadline. + let deadline = std::time::Instant::now() + BUSY; + loop { + match conn.execute_batch( + "PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS game_zone_state ( + zone_id TEXT PRIMARY KEY, + token INTEGER NOT NULL, + content_version TEXT NOT NULL, + state BLOB NOT NULL + );", + ) { + Ok(()) => break, + Err(rusqlite::Error::SqliteFailure(e, _)) + if matches!( + e.code, + rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked + ) && std::time::Instant::now() < deadline => + { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + Err(e) => return Err(backend(e)), + } + } Ok(Self { conn: Mutex::new(conn), }) @@ -232,6 +251,46 @@ mod tests { exercise(&MemoryZoneStateStore::new()); } + #[cfg(feature = "sqlite")] + #[test] + fn sqlite_stores_sharing_a_file_wait_for_each_other() { + // Hosts sharing one file (the multi-host demos) open and write at the + // same time; a colliding writer must wait, not fail "database is locked". + let path = std::env::temp_dir().join(format!( + "dg-zone-state-shared-{}-{}.sqlite3", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let threads: Vec<_> = (0..8u64) + .map(|host| { + let path = path.clone(); + std::thread::spawn(move || { + let store = SqliteZoneStateStore::open(&path)?; + for token in 1..=50 { + store.save(&format!("zone.{host}"), &snap(token, b"s"))?; + } + Ok::<_, StateError>(()) + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap().unwrap(); + } + let store = SqliteZoneStateStore::open(&path).unwrap(); + for host in 0..8 { + assert_eq!( + store.load(&format!("zone.{host}")).unwrap(), + Some(snap(50, b"s")) + ); + } + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + } + #[cfg(feature = "sqlite")] #[test] fn sqlite_store_is_fenced_and_durable() { From 88f4ffde59b7bba8228850fe6dbd6e9a45518597 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 17:33:48 -0500 Subject: [PATCH 212/484] test(cli): concurrent game-manifest runs export their own surface Fails without the manifest-harness lock (an export prints the other entrypoint's surface). --- distributed_cli/tests/cli_game_client.rs | 59 +++++++++++++++++++ .../tests/fixtures/game-surface/src/lib.rs | 6 ++ 2 files changed, 65 insertions(+) diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs index 5139fb1cf..4b4dd6b10 100644 --- a/distributed_cli/tests/cli_game_client.rs +++ b/distributed_cli/tests/cli_game_client.rs @@ -277,3 +277,62 @@ fn game_wasm_needs_something_to_compile() { String::from_utf8_lossy(&run.stderr) ); } + +#[test] +#[ignore = "compiles the fixture via the manifest harness; run in the integration job"] +fn concurrent_game_manifests_export_their_own_entrypoints() { + // Every entrypoint of a package shares one harness directory; without + // the harness lock, concurrent runs overwrote each other's `main.rs` and + // exported the last writer's surface. + let manifest = root().join("tests/fixtures/game-surface/Cargo.toml"); + let tmp = tempfile::tempdir().unwrap(); + // Warm the harness build so the concurrent runs race on `main.rs`, not + // on the first compile. + let warm = distributed(&[ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + tmp.path().join("warm.json").to_str().unwrap(), + ]); + assert!( + warm.status.success(), + "{}", + String::from_utf8_lossy(&warm.stderr) + ); + for round in 0..4 { + let runs: Vec<_> = [("game_surface", "orbs"), ("bare_surface", "bare")] + .into_iter() + .flat_map(|pair| [pair, pair]) + .enumerate() + .map(|(i, (entrypoint, name))| { + let out = tmp.path().join(format!("{round}-{i}.json")); + let child = Command::new(env!("CARGO_BIN_EXE_distributed")) + .args([ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--entrypoint", + entrypoint, + "--out", + out.to_str().unwrap(), + ]) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("distributed should run"); + (child, out, name) + }) + .collect(); + for (child, out, name) in runs { + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let surface: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(surface["name"], name, "round {round}: {}", out.display()); + } + } +} diff --git a/distributed_cli/tests/fixtures/game-surface/src/lib.rs b/distributed_cli/tests/fixtures/game-surface/src/lib.rs index a660ad4a7..2712e56c4 100644 --- a/distributed_cli/tests/fixtures/game-surface/src/lib.rs +++ b/distributed_cli/tests/fixtures/game-surface/src/lib.rs @@ -90,3 +90,9 @@ pub fn game_surface() -> GameSurface { .pure::() .constant("orb_limits", &OrbLimits { limit: 32.0 }) } + +/// A second export of the same package (concurrent harness runs must each +/// print their own entrypoint's surface). +pub fn bare_surface() -> GameSurface { + GameSurface::for_zone::("bare") +} From a94caa28e81e6c4ca96e397cc227e4109930571d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 17:33:49 -0500 Subject: [PATCH 213/484] ci: run the examples/game smoke on pull requests examples/game is outside the root workspace, so its demo tests, the generated-client check and both headless suites never ran in CI. The SvelteKit browser test now also checks player swings are drawn. --- .github/workflows/integration-game-demos.yaml | 39 +++++++++++++++++++ .github/workflows/on-pr-quality.yaml | 4 ++ examples/game/sveltekit/src/lib/pit/loop.ts | 2 + examples/game/sveltekit/tests/pit.test.mjs | 5 +++ 4 files changed, 50 insertions(+) create mode 100644 .github/workflows/integration-game-demos.yaml diff --git a/.github/workflows/integration-game-demos.yaml b/.github/workflows/integration-game-demos.yaml new file mode 100644 index 000000000..83d918ef2 --- /dev/null +++ b/.github/workflows/integration-game-demos.yaml @@ -0,0 +1,39 @@ +name: Game demos smoke + +# Reusable workflow: referenced via `uses: ./.github/workflows/integration-game-demos.yaml`. +# `examples/game` is outside the root workspace, so nothing else runs its tests: +# generated clients current (`gen --check`), demo server fmt/clippy/tests, client +# type-check, build and headless tests, and the SvelteKit demo end to end +# (Playwright against the production build and a real Mob Pit server). +on: + workflow_call: + +jobs: + game-demos: + name: Game demos smoke (examples/game) + runs-on: ubuntu-latest + env: + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + components: clippy, rustfmt + # Predicted steps and pure functions compile to WebAssembly. + targets: wasm32-unknown-unknown + - uses: actions/setup-node@v4 + with: + node-version: "24" + cache: npm + cache-dependency-path: | + js/package-lock.json + examples/game/client/package-lock.json + examples/game/sveltekit/package-lock.json + - name: Install SvelteKit demo dependencies and Chromium + working-directory: examples/game/sveltekit + run: npm ci --no-audit --no-fund && npx playwright install --with-deps chromium + - name: Run examples/game smoke + run: examples/game/run.sh smoke diff --git a/.github/workflows/on-pr-quality.yaml b/.github/workflows/on-pr-quality.yaml index 6528c0fd9..5d3906655 100644 --- a/.github/workflows/on-pr-quality.yaml +++ b/.github/workflows/on-pr-quality.yaml @@ -76,5 +76,9 @@ jobs: needs: [contracts] uses: ./.github/workflows/integration-js.yaml + game-demos: + needs: [contracts] + uses: ./.github/workflows/integration-game-demos.yaml + celld: uses: ./.github/workflows/integration-celld.yaml diff --git a/examples/game/sveltekit/src/lib/pit/loop.ts b/examples/game/sveltekit/src/lib/pit/loop.ts index 8cf8e7509..ddec7fb60 100644 --- a/examples/game/sveltekit/src/lib/pit/loop.ts +++ b/examples/game/sveltekit/src/lib/pit/loop.ts @@ -125,6 +125,8 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) ctx.fill(); ctx.strokeStyle = '#4da3ff'; ctx.stroke(); + // Frames that drew an own swing, for the headless test. + if (mine) canvas.dataset.swings = String(Number(canvas.dataset.swings ?? 0) + 1); } circle(p.x, p.y, PLAYER_RADIUS, p.dead ? '#555' : mine ? '#ffd166' : '#6ec3ff'); const [nx, ny] = at(p.x + Math.cos(p.face) * 0.6, p.y + Math.sin(p.face) * 0.6); diff --git a/examples/game/sveltekit/tests/pit.test.mjs b/examples/game/sveltekit/tests/pit.test.mjs index c33fc78ab..597e6f9d6 100644 --- a/examples/game/sveltekit/tests/pit.test.mjs +++ b/examples/game/sveltekit/tests/pit.test.mjs @@ -123,6 +123,11 @@ test('sign in, join, move, kill, settled read model updates', { timeout: 600_000 const moved = await page.evaluate(() => document.querySelector('canvas').dataset.me.split(',').map(Number)); assert.ok(moved[0] > start[0] + 0.5 || Math.hypot(moved[0] - start[0], moved[1] - start[1]) > 0.5, `moved ${start} → ${moved}`); + // Attack: the server's swing reaches the client and the cone is drawn. + await page.keyboard.down('Space'); + await page.waitForFunction(() => Number(document.querySelector('canvas')?.dataset.swings ?? 0) > 0, null, { timeout: 5_000 }); + await page.keyboard.up('Space'); + // Settled fact: auto-hunt kills a mob; the cell commit settles; the // live read model (profile + board pushes) shows it. assert.equal(await page.textContent('[data-testid=xp]'), '0'); From dfbaff364f0b5aea55bdbe7588444752a97508e8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 17:55:20 -0500 Subject: [PATCH 214/484] feat(js): share game ticket rate limits through Redis `take` may now return a promise and the ticket handler awaits it. A limiter that throws, rejects or times out answers 503 rate_limit_unavailable (fail closed). createRedisGameTicketRateLimiter keeps a sliding-window log per principal in one atomic Lua EVAL over a caller-supplied node-redis or ioredis client (or an eval function); no Redis dependency. onUnavailable: 'open' admits while the store is down. --- js/README.md | 55 ++++- js/src/sveltekit/game/rate-limit.ts | 199 ++++++++++++++++ js/src/sveltekit/game/server.ts | 67 +++--- js/tests/sveltekit-game-rate-limit.test.mjs | 252 ++++++++++++++++++++ 4 files changed, 533 insertions(+), 40 deletions(-) create mode 100644 js/src/sveltekit/game/rate-limit.ts create mode 100644 js/tests/sveltekit-game-rate-limit.test.mjs diff --git a/js/README.md b/js/README.md index a0fd64750..29f2eb4c6 100644 --- a/js/README.md +++ b/js/README.md @@ -479,14 +479,57 @@ The principal is `session.user.id` (override with `principal(session)`; unless the `Origin` is the app's own (`allowedOrigins` adds more) and `Sec-Fetch-Site`, when sent, is `same-origin`; 401 without a session; 429 over the per-principal limit (default 10 per minute, in memory; -`rateLimit: { max, windowMs }`, a custom `{ take(key, now) }`, or `false`); -400 for any body field other than `zone` / `role` (so a body cannot name the -principal, an owner or a reward); 409 with the server's zone when the -requested zone differs; 403 when `zone` returns nothing; 503 without a valid -secret. Every response is `cache-control: no-store`. Tickets live 60 s by -default (`ttlSeconds` ≤ 300) and are single use on the zone server. +`rateLimit: { max, windowMs }`, a custom `{ take(key, now) }` returning a +boolean or a promise of one, or `false`); 400 for any body field other than +`zone` / `role` (so a body cannot name the principal, an owner or a reward); +409 with the server's zone when the requested zone differs; 403 when `zone` +returns nothing; 503 without a valid secret. Every response is +`cache-control: no-store`. Tickets live 60 s by default (`ttlSeconds` ≤ 300) +and are single use on the zone server. `mintGameTicket({ secret, principal, zone, role, name })` signs one directly. +The default limiter counts per process, so N instances behind a load +balancer allow N× the budget. Share it through Redis (or any store that runs +Redis Lua) with `createRedisGameTicketRateLimiter`. It imports no Redis +package: pass your connected node-redis client (`sendCommand`) or ioredis +client (`call`), or `eval(script, keys, args)` for anything else (cluster +clients, a pooled wrapper): + +```ts +import { createClient } from 'redis'; +import { + createGameTicketHandler, + createRedisGameTicketRateLimiter +} from '@hops-ops/distributed/sveltekit/game/server'; + +const redis = await createClient({ url: env.REDIS_URL }).connect(); +export const tickets = createGameTicketHandler({ + // … + rateLimit: createRedisGameTicketRateLimiter({ + client: redis, + prefix: 'mygame:ticket:', // default 'distributed:game-ticket:' + principal + limit: 10, + windowMs: 60_000, + timeoutMs: 1_000, // slower store calls count as errors (default) + onUnavailable: 'closed', // default; 'open' = no limit while the store is down + onError: (error) => log.warn({ error }, 'ticket limiter store') + }) +}); +``` + +One atomic `EVAL` (`GAME_TICKET_RATE_LIMIT_SCRIPT`) keeps a sliding-window +log per principal in a sorted set: it drops entries older than the window, +refuses when `limit` remain, else adds one, and expires the key with the +window. Refused requests are not counted, matching the in-memory limiter. +The timestamp is the instance clock, so keep instances NTP-synchronized. + +**Store unreachable:** a store error, a timeout or an unexpected reply makes +the limiter reject, and the handler answers **503 `rate_limit_unavailable`** +(fail closed — ticket issuance stops rather than run unlimited; the message +carries no store details, which go to `onError`). `onUnavailable: 'open'` +admits instead. The same applies to any custom limiter: a `take` that +throws or rejects is a 503, never an allow. + **3. Runes state for the UI around the game** (`@hops-ops/distributed/sveltekit/game`, browser-safe): diff --git a/js/src/sveltekit/game/rate-limit.ts b/js/src/sveltekit/game/rate-limit.ts new file mode 100644 index 000000000..719b5c66a --- /dev/null +++ b/js/src/sveltekit/game/rate-limit.ts @@ -0,0 +1,199 @@ +/** + * Per-principal limiters for `createGameTicketHandler`: the in-memory + * default (one process) and a Redis-backed one shared by every instance + * behind a load balancer. No Redis package is imported: the caller passes + * its own node-redis or ioredis client (or a plain `eval` function). + */ + +/** + * Sliding-window limiter; `take` resolves false when `key` is over budget. + * A `take` that throws or rejects makes the ticket handler answer 503 + * (`rate_limit_unavailable`): an unreachable limiter fails closed. + */ +export type GameTicketRateLimiter = Readonly<{ + take(key: string, now: number): boolean | Promise; +}>; + +/** In-memory sliding window per key (one process; use a shared store behind a load balancer). */ +export function createGameTicketRateLimiter(max: number, windowMs: number): GameTicketRateLimiter { + checkBudget(max, windowMs); + const starts = new Map(); + return Object.freeze({ + take(key: string, now: number): boolean { + const since = now - windowMs; + if (starts.size > 10_000) { + for (const [existing, times] of starts) { + if (times.every((at) => at <= since)) starts.delete(existing); + } + } + const recent = (starts.get(key) ?? []).filter((at) => at > since); + if (recent.length >= max) { + starts.set(key, recent); + return false; + } + recent.push(now); + starts.set(key, recent); + return true; + } + }); +} + +function checkBudget(max: number, windowMs: number): void { + if (!Number.isSafeInteger(max) || max < 1 || !Number.isFinite(windowMs) || windowMs <= 0) { + throw new TypeError('game ticket rate limit needs max >= 1 and windowMs > 0'); + } +} + +/** + * The Redis commands the limiter sends, structurally: node-redis v4/v5 + * (`sendCommand(['EVAL', …])`) and ioredis (`call('EVAL', …)`) both satisfy + * it without an adapter. + */ +export type GameTicketRedisClient = + | Readonly<{ sendCommand(args: string[]): Promise }> + | Readonly<{ call(command: string, ...args: string[]): Promise }>; + +/** Runs `script` with `keys` / `args` atomically (Redis `EVAL` semantics). */ +export type GameTicketRedisEval = (script: string, keys: string[], args: string[]) => Promise; + +export type RedisGameTicketRateLimiterOptions = Readonly<{ + /** A connected node-redis or ioredis client (or anything with `sendCommand` / `call`). */ + client?: GameTicketRedisClient; + /** Instead of `client`: run the script yourself (cluster clients, other stores with Lua). */ + eval?: GameTicketRedisEval; + /** Key prefix; the principal is appended. Default `distributed:game-ticket:`. */ + prefix?: string; + /** Tickets per principal per window, across every instance. */ + limit: number; + /** Window length in milliseconds. */ + windowMs: number; + /** A store call slower than this counts as a store error. Default 1000 ms. */ + timeoutMs?: number; + /** + * What a store error (unreachable, timeout, script error) means: + * `'closed'` (default) rejects, so the handler answers 503 + * `rate_limit_unavailable`; `'open'` lets the request through unlimited. + */ + onUnavailable?: 'closed' | 'open'; + /** Called with every store error (log / metric). Never throws into the request. */ + onError?(error: unknown): void; +}>; + +/** Thrown (fail-closed) when the shared store cannot answer. */ +export class GameTicketRateLimiterUnavailable extends Error { + constructor(cause: unknown) { + super('game ticket rate limiter store unavailable', { cause }); + this.name = 'GameTicketRateLimiterUnavailable'; + } +} + +/** + * Sliding-window log in one sorted set per principal: drop entries older + * than the window, count, add when under the limit, expire the key with the + * window. One `EVAL`, so concurrent instances cannot both take the last slot. + * `now` comes from the instance clock (keep instances NTP-synchronized). + */ +export const GAME_TICKET_RATE_LIMIT_SCRIPT = `local key = KEYS[1] +local now = tonumber(ARGV[1]) +local window = tonumber(ARGV[2]) +local limit = tonumber(ARGV[3]) +redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window) +if redis.call('ZCARD', key) >= limit then + redis.call('PEXPIRE', key, window) + return 0 +end +redis.call('ZADD', key, now, ARGV[4]) +redis.call('PEXPIRE', key, window) +return 1`; + +function evalWith(options: RedisGameTicketRateLimiterOptions): GameTicketRedisEval { + if (typeof options.eval === 'function') { + if (options.client !== undefined) throw new TypeError('pass either client or eval, not both'); + return options.eval; + } + const client = options.client as Record | undefined; + if (client === undefined || client === null || typeof client !== 'object') { + throw new TypeError('createRedisGameTicketRateLimiter needs a client or eval'); + } + const command = (script: string, keys: string[], args: string[]): string[] => [ + script, + String(keys.length), + ...keys, + ...args + ]; + if (typeof client.sendCommand === 'function') { + const send = client.sendCommand as (args: string[]) => Promise; + return (script, keys, args) => send.call(client, ['EVAL', ...command(script, keys, args)]); + } + if (typeof client.call === 'function') { + const call = client.call as (name: string, ...args: string[]) => Promise; + return (script, keys, args) => call.call(client, 'EVAL', ...command(script, keys, args)); + } + throw new TypeError('the Redis client needs sendCommand (node-redis) or call (ioredis)'); +} + +let sequence = 0; + +/** + * A ticket limiter shared by every SvelteKit instance through Redis (or any + * store that runs Redis Lua). Same semantics as the in-memory limiter: + * `limit` tickets per principal in any `windowMs`, refused requests are not + * counted. + * + * ```ts + * import { createClient } from 'redis'; + * const redis = await createClient({ url: env.REDIS_URL }).connect(); + * createGameTicketHandler({ …, rateLimit: createRedisGameTicketRateLimiter({ client: redis, limit: 10, windowMs: 60_000 }) }); + * ``` + */ +export function createRedisGameTicketRateLimiter(options: RedisGameTicketRateLimiterOptions): GameTicketRateLimiter { + if (options === null || typeof options !== 'object') { + throw new TypeError('createRedisGameTicketRateLimiter requires options'); + } + checkBudget(options.limit, options.windowMs); + if (!Number.isSafeInteger(options.windowMs)) throw new TypeError('windowMs must be whole milliseconds'); + const run = evalWith(options); + const prefix = options.prefix ?? 'distributed:game-ticket:'; + const timeoutMs = options.timeoutMs ?? 1_000; + if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new TypeError('timeoutMs must be > 0'); + const failOpen = options.onUnavailable === 'open'; + if (options.onUnavailable !== undefined && options.onUnavailable !== 'open' && options.onUnavailable !== 'closed') { + throw new TypeError("onUnavailable must be 'closed' or 'open'"); + } + const instance = Math.random().toString(36).slice(2, 10); + const limit = String(options.limit); + const windowMs = String(options.windowMs); + + const unavailable = (error: unknown): boolean => { + try { + options.onError?.(error); + } catch { + // A logging hook never decides the request. + } + if (failOpen) return true; + throw new GameTicketRateLimiterUnavailable(error); + }; + + return Object.freeze({ + async take(key: string, now: number): Promise { + // Unique per take, so two instances at the same millisecond both count. + const member = `${now}:${instance}:${(sequence = (sequence + 1) % Number.MAX_SAFE_INTEGER)}`; + let timer: ReturnType | undefined; + try { + const reply = await Promise.race([ + run(GAME_TICKET_RATE_LIMIT_SCRIPT, [`${prefix}${key}`], [String(now), windowMs, limit, member]), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`rate limit store timed out after ${timeoutMs} ms`)), timeoutMs); + }) + ]); + const allowed = Number(reply); + if (allowed !== 0 && allowed !== 1) throw new Error(`unexpected rate limit reply ${String(reply)}`); + return allowed === 1; + } catch (error) { + return unavailable(error); + } finally { + if (timer !== undefined) clearTimeout(timer); + } + } + }); +} diff --git a/js/src/sveltekit/game/server.ts b/js/src/sveltekit/game/server.ts index a7a198342..5076090c6 100644 --- a/js/src/sveltekit/game/server.ts +++ b/js/src/sveltekit/game/server.ts @@ -12,6 +12,18 @@ import { type GameTicketRole, type GameTicketSecret } from './ticket.js'; +import { createGameTicketRateLimiter, type GameTicketRateLimiter } from './rate-limit.js'; + +export { + GAME_TICKET_RATE_LIMIT_SCRIPT, + GameTicketRateLimiterUnavailable, + createGameTicketRateLimiter, + createRedisGameTicketRateLimiter, + type GameTicketRateLimiter, + type GameTicketRedisClient, + type GameTicketRedisEval, + type RedisGameTicketRateLimiterOptions +} from './rate-limit.js'; export { MAX_GAME_TICKET_TTL_SECONDS, @@ -52,11 +64,6 @@ export type GameTicketZoneContext = Readonly<{ role: GameTicketRole; }>; -/** Sliding-window limiter; `take` returns false when the key is over budget. */ -export type GameTicketRateLimiter = Readonly<{ - take(key: string, now: number): boolean; -}>; - export type GameTicketRateLimit = | false | Readonly<{ max: number; windowMs: number }> @@ -91,7 +98,12 @@ export type CreateGameTicketHandlerOptions= 1 and windowMs > 0'); - } - const starts = new Map(); - return Object.freeze({ - take(key: string, now: number): boolean { - const since = now - windowMs; - if (starts.size > 10_000) { - for (const [existing, times] of starts) { - if (times.every((at) => at <= since)) starts.delete(existing); - } - } - const recent = (starts.get(key) ?? []).filter((at) => at > since); - if (recent.length >= max) { - starts.set(key, recent); - return false; - } - recent.push(now); - starts.set(key, recent); - return true; - } - }); -} - function limiterFrom(option: GameTicketRateLimit | undefined): GameTicketRateLimiter | undefined { if (option === false) return undefined; if (option === undefined) return createGameTicketRateLimiter(10, 60_000); @@ -352,8 +338,21 @@ export function createGameTicketHandler {}); + assert.equal(script, GAME_TICKET_RATE_LIMIT_SCRIPT); + const [key] = keys; + const [now, window, limit, member] = [Number(args[0]), Number(args[1]), Number(args[2]), args[3]]; + const entries = (sets.get(key) ?? []).filter((entry) => entry.score > now - window); + sets.set(key, entries); + if (entries.length >= limit) return 0; + entries.push({ score: now, member }); + return 1; + } + }; + return store; +} + +/** A node-redis-shaped client (`sendCommand(['EVAL', script, n, ...keys, ...args])`). */ +const nodeRedisShape = (store) => ({ + async sendCommand(args) { + assert.equal(args[0], 'EVAL'); + const n = Number(args[2]); + return store.eval(args[1], args.slice(3, 3 + n), args.slice(3 + n)); + } +}); + +/** An ioredis-shaped client (`call('EVAL', script, n, ...keys, ...args)`). */ +const ioredisShape = (store) => ({ + async call(command, script, n, ...rest) { + assert.equal(command, 'EVAL'); + return store.eval(script, rest.slice(0, Number(n)), rest.slice(Number(n))); + } +}); + +function instance(rateLimit, clock) { + const handler = createGameTicketHandler({ + secret: SECRET, + getSession: (event) => event.locals.session, + zone: () => 'pit-1', + rateLimit, + now: () => clock.now + }); + return (principal = 'u1') => + handler({ + request: new Request(`${ORIGIN}/api/game/ticket`, { method: 'POST', headers: { origin: ORIGIN } }), + url: new URL(`${ORIGIN}/api/game/ticket`), + locals: { session: { user: { id: principal } } } + }); +} + +async function status(promise, expected, error) { + const response = await promise; + const body = await response.json(); + assert.equal(response.status, expected, JSON.stringify(body)); + assert.equal(response.headers.get('cache-control'), 'no-store'); + if (error !== undefined) assert.equal(body.error, error); + return body; +} + +test('two handler instances over one store share one budget per principal', async () => { + const store = fakeRedis(); + const clock = { now: 1_700_000_000_000 }; + // Separate limiter objects (as in separate processes), one store. + const a = instance(createRedisGameTicketRateLimiter({ client: nodeRedisShape(store), limit: 3, windowMs: 60_000 }), clock); + const b = instance(createRedisGameTicketRateLimiter({ client: ioredisShape(store), limit: 3, windowMs: 60_000 }), clock); + await status(a(), 200); + await status(b(), 200); + await status(a(), 200); + await status(b(), 429, 'rate_limited'); + await status(a(), 429, 'rate_limited'); + // Another principal has its own budget; the key carries the prefix. + await status(b('u2'), 200); + assert.deepEqual([...store.sets.keys()].sort(), ['distributed:game-ticket:u1', 'distributed:game-ticket:u2']); + // Refusals are not counted: the 3 recorded takes are all successes. + assert.equal(store.sets.get('distributed:game-ticket:u1').length, 3); +}); + +test('the window slides: a slot frees exactly when its oldest take leaves the window', async () => { + const store = fakeRedis(); + const clock = { now: 1_000_000 }; + const limiter = createRedisGameTicketRateLimiter({ eval: store.eval, prefix: 't:', limit: 2, windowMs: 10_000 }); + const call = instance(limiter, clock); + await status(call(), 200); // t = 0 + clock.now += 4_000; + await status(call(), 200); // t = 4 s + await status(call(), 429, 'rate_limited'); + clock.now += 5_999; // t = 9.999 s: the first take is still inside + await status(call(), 429, 'rate_limited'); + clock.now += 1; // t = 10 s: it left + await status(call(), 200); + await status(call(), 429, 'rate_limited'); + clock.now += 10_000; + await status(call(), 200); + await status(call(), 200); +}); + +test('store errors fail closed with 503 (or open when configured) and reach onError', async () => { + const store = fakeRedis(); + const clock = { now: 5_000 }; + const errors = []; + const closed = instance( + createRedisGameTicketRateLimiter({ client: nodeRedisShape(store), limit: 5, windowMs: 1_000, onError: (e) => errors.push(e) }), + clock + ); + store.failing = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:6379'), { code: 'ECONNREFUSED' }); + const body = await status(closed(), 503, 'rate_limit_unavailable'); + assert.doesNotMatch(body.message, /ECONNREFUSED|6379/, 'store details stay on the server'); + assert.equal(errors.length, 1); + + const open = instance( + createRedisGameTicketRateLimiter({ client: nodeRedisShape(store), limit: 1, windowMs: 1_000, onUnavailable: 'open' }), + clock + ); + await status(open(), 200); + await status(open(), 200, undefined); // unlimited while the store is down + + // A hung store is a store error after timeoutMs. + store.failing = undefined; + store.hang = true; + const slow = instance(createRedisGameTicketRateLimiter({ eval: store.eval, limit: 5, windowMs: 1_000, timeoutMs: 20 }), clock); + await status(slow(), 503, 'rate_limit_unavailable'); + + // A garbage reply is a store error too, not "allowed". + const odd = instance(createRedisGameTicketRateLimiter({ eval: async () => 'OK', limit: 5, windowMs: 1_000 }), clock); + await status(odd(), 503, 'rate_limit_unavailable'); + + // Any custom async limiter: awaited; rejection → 503; resolve(false) → 429. + await status(instance({ take: async () => false }, clock)(), 429, 'rate_limited'); + await status(instance({ take: async () => { throw new Error('down'); } }, clock)(), 503, 'rate_limit_unavailable'); + await status(instance({ take: () => { throw new Error('down'); } }, clock)(), 503, 'rate_limit_unavailable'); +}); + +test('createRedisGameTicketRateLimiter validates its options', () => { + const store = fakeRedis(); + assert.throws(() => createRedisGameTicketRateLimiter({ limit: 1, windowMs: 1 }), /client or eval/); + assert.throws(() => createRedisGameTicketRateLimiter({ client: {}, limit: 1, windowMs: 1 }), /sendCommand/); + assert.throws(() => createRedisGameTicketRateLimiter({ eval: store.eval, limit: 0, windowMs: 1 }), /max >= 1/); + assert.throws(() => createRedisGameTicketRateLimiter({ eval: store.eval, limit: 1, windowMs: 1.5 }), /whole milliseconds/); + assert.throws(() => createRedisGameTicketRateLimiter({ eval: store.eval, limit: 1, windowMs: 1, onUnavailable: 'maybe' }), /onUnavailable/); + assert.throws( + () => createRedisGameTicketRateLimiter({ eval: store.eval, client: nodeRedisShape(store), limit: 1, windowMs: 1 }), + /either client or eval/ + ); +}); + +/** Minimal RESP2 client: enough for `sendCommand(['EVAL', …])` (integer / error / bulk replies). */ +async function respClient(url) { + const { hostname, port } = new URL(url); + const socket = connect({ host: hostname || '127.0.0.1', port: Number(port || 6379) }); + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('error', reject); + }); + let buffer = ''; + const waiting = []; + socket.on('data', (chunk) => { + buffer += chunk.toString('utf8'); + for (;;) { + const end = buffer.indexOf('\r\n'); + if (end < 0 || waiting.length === 0) return; + const line = buffer.slice(0, end); + const kind = line[0]; + if (kind === '$') { + const length = Number(line.slice(1)); + if (length < 0) { + buffer = buffer.slice(end + 2); + waiting.shift().resolve(null); + continue; + } + if (buffer.length < end + 2 + length + 2) return; + const value = buffer.slice(end + 2, end + 2 + length); + buffer = buffer.slice(end + 2 + length + 2); + waiting.shift().resolve(value); + continue; + } + buffer = buffer.slice(end + 2); + const next = waiting.shift(); + if (kind === ':') next.resolve(Number(line.slice(1))); + else if (kind === '+') next.resolve(line.slice(1)); + else next.reject(new Error(line.slice(1))); + } + }); + return { + sendCommand(args) { + const frame = `*${args.length}\r\n${args.map((a) => `$${Buffer.byteLength(a)}\r\n${a}\r\n`).join('')}`; + return new Promise((resolve, reject) => { + waiting.push({ resolve, reject }); + socket.write(frame); + }); + }, + close: () => socket.end() + }; +} + +test('real Redis: the Lua script shares one sliding budget', { skip: !REDIS_E2E, timeout: 30_000 }, async () => { + const client = await respClient(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379'); + try { + const prefix = `distributed-test:${randomUUID()}:`; + const clock = { now: Date.now() }; + const a = instance(createRedisGameTicketRateLimiter({ client, prefix, limit: 2, windowMs: 2_000 }), clock); + const b = instance(createRedisGameTicketRateLimiter({ client, prefix, limit: 2, windowMs: 2_000 }), clock); + await status(a(), 200); + await status(b(), 200); + await status(a(), 429, 'rate_limited'); + await status(b('other'), 200); + clock.now += 2_001; + await status(b(), 200); + // The key expires with the window (no unbounded growth). + const ttl = await client.sendCommand(['PTTL', `${prefix}u1`]); + assert.ok(ttl > 0 && ttl <= 2_000, `pttl ${ttl}`); + } finally { + client.close(); + } +}); From 1f2cb0f1b899861c76889830b402a26dee64302b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 18:17:48 -0500 Subject: [PATCH 215/484] fix(js): keep vite dev running when game generation fails Vite's dev watcher awaits plugin watchChange without handling a rejection, so a Rust compile error in a game surface exited the dev server. In serve mode a failed game-manifest/game-client/game-wasm run (startup, watcher or HMR) is now logged once, sent to the error overlay (replayed to overlays that connect later) and the last generated client keeps serving. vite build and build --watch still fail. --- js/README.md | 6 ++- js/src/sveltekit/vite.ts | 72 +++++++++++++++++++++---- js/tests/sveltekit-game-vite.test.mjs | 77 ++++++++++++++++++++++++++- 3 files changed, 144 insertions(+), 11 deletions(-) diff --git a/js/README.md b/js/README.md index 29f2eb4c6..9983310d7 100644 --- a/js/README.md +++ b/js/README.md @@ -425,7 +425,11 @@ Svelte 5.7+ is required (`svelte/reactivity`). A runnable example is plugin. Each surface runs `distributed game-manifest` → `game-client` → `game-wasm` (the `#[predict]` step and `#[game_pure]` functions) when Vite starts, when the zone's Rust sources change (a full reload follows only if -an output changed), and once per `vite build`; Vite emits the WebAssembly as +an output changed), and once per `vite build`. In `vite dev` a failing run +(a Rust compile error, say) is logged and shown in the error overlay — also +to overlays opened later — and the server keeps serving the last generated +client until the next change succeeds; `vite build` (and `build --watch`) +fails instead; Vite emits the WebAssembly as an asset through the generated `new URL('./wasm/.wasm', import.meta.url)`. Game surfaces are not lifecycle outputs, so a games-only app runs under plain `vite dev` / `vite build`; GraphQL `clients` still need diff --git a/js/src/sveltekit/vite.ts b/js/src/sveltekit/vite.ts index b8993eb01..545fd3354 100644 --- a/js/src/sveltekit/vite.ts +++ b/js/src/sveltekit/vite.ts @@ -235,6 +235,8 @@ type CompilerLockLease = { type ViteWebSocketLike = Readonly<{ send(payload: unknown): void; + /** Vite's `server.ws.on('connection', …)` (optional in test doubles). */ + on?(event: 'connection', listener: () => void): void; }>; type ViteModuleGraphLike = Readonly<{ @@ -286,7 +288,13 @@ type RollupWatchContextLike = Readonly<{ export type DistributedSvelteKitVitePlugin = Readonly<{ name: string; enforce: 'pre'; - configResolved(config: Readonly<{ root: string; command?: 'serve' | 'build' }>): Promise; + configResolved( + config: Readonly<{ + root: string; + command?: 'serve' | 'build'; + logger?: Readonly<{ error(message: string): void }>; + }> + ): Promise; configureServer(server: ViteServerLike): void; buildStart(this: RollupWatchContextLike): void; resolveId(source: string, importer?: string): string | undefined; @@ -387,6 +395,41 @@ export function distributedSvelteKit( let gamesDirty = false; let gamesRunning: Promise | undefined; let gamesChanged = false; + /** `vite dev`: a failed game generation is reported, never thrown into Vite. */ + let serving = false; + let logger: Readonly<{ error(message: string): void }> = { error: (message) => console.error(message) }; + /** Last dev-mode game failure, replayed to overlays that connect later; cleared on success. */ + let gameFailure: unknown; + let devServer: Readonly<{ ws: { send(payload: unknown): void } }> | undefined; + + const reportGameFailure = (error: unknown): void => { + // The watcher and HMR hooks share one run: report its failure once. + if (error === gameFailure) return; + gameFailure = error; + logger.error( + `[distributed] game client generation failed; the dev server keeps the last generated client:\n${ + error instanceof Error ? error.message : String(error) + }` + ); + devServer?.ws.send({ type: 'error', err: viteError(error) }); + }; + + /** + * Dev-mode game regeneration (startup, HMR, watcher): failures go to the + * console and the error overlay; the server keeps running on the last + * generated client. Builds use `compileGames` directly and fail. + */ + const compileGamesInDev = async (): Promise => { + try { + const changed = await compileGames(); + gameFailure = undefined; + return changed; + } catch (error) { + if (stopped) return false; + reportGameFailure(error); + return false; + } + }; /** Serialized, coalescing game generation; resolves true when any output changed. */ const compileGames = (): Promise => { @@ -475,6 +518,8 @@ export function distributedSvelteKit( 'Distributed SvelteKit Vite plugin was configured more than once' ); } + serving = config.command === 'serve'; + if (config.logger !== undefined) logger = config.logger; resolved = resolveIntegration(options, options.cwd ?? config.root); frameworkDist = localFrameworkDist(config.root); await validateResolvedPaths(resolved); @@ -497,7 +542,8 @@ export function distributedSvelteKit( if (config.command === 'build') { await onceForBuild(resolved, () => compileGames()); } else { - await compileGames(); + // A Rust error at dev start must not keep the server down. + await compileGamesInDev(); } } if (lifecycleOwnsCompile || resolved.clients.length === 0) return; @@ -530,6 +576,11 @@ export function distributedSvelteKit( } const gameRoots = integration.games.flatMap((game) => game.watchRoots); if (gameRoots.length > 0) server.watcher.add(gameRoots); + devServer = server; + // An overlay opened after a failed startup generation still shows it. + server.ws.on?.('connection', () => { + if (gameFailure !== undefined) server.ws.send({ type: 'error', err: viteError(gameFailure) }); + }); server.httpServer?.once('close', () => { void stop(); }); @@ -628,12 +679,9 @@ export function distributedSvelteKit( return []; } if (isGameInput(context.file, integration)) { - try { - if (await compileGames()) { - context.server.ws.send({ type: 'full-reload', path: '*' }); - } - } catch (error) { - context.server.ws.send({ type: 'error', err: viteError(error) }); + devServer ??= context.server; + if (await compileGamesInDev()) { + context.server.ws.send({ type: 'full-reload', path: '*' }); } if (!isCompilerInput(context.file, integration)) return []; } @@ -665,7 +713,13 @@ export function distributedSvelteKit( }, async watchChange(id): Promise { const integration = requireResolved(resolved); - if (isGameInput(id, integration)) await compileGames(); + // `vite dev` calls this hook from its file watcher without handling a + // rejection (the process would exit): there, report and keep serving. + // `vite build --watch` still fails the rebuild. + if (isGameInput(id, integration)) { + if (serving) await compileGamesInDev(); + else await compileGames(); + } if (lifecycleOwnsCompile) return; if (isCompilerInput(id, integration)) { await compile(`GraphQL/Svelte watch change ${id}`); diff --git a/js/tests/sveltekit-game-vite.test.mjs b/js/tests/sveltekit-game-vite.test.mjs index f57887fde..b975081bb 100644 --- a/js/tests/sveltekit-game-vite.test.mjs +++ b/js/tests/sveltekit-game-vite.test.mjs @@ -158,7 +158,7 @@ test('plugin: generates on start, regenerates on a Rust change and reloads; game try { // The public entry accepts a games-only configuration under plain Vite. const plugin = distributedSvelteKitPublic(f.options({ watch: [join(f.root, 'missing-is-ignored')] })); - await plugin.configResolved({ root: f.app, command: 'serve' }); + await plugin.configResolved({ root: f.app, command: 'serve', logger: { error: () => undefined } }); assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v1/); const watched = []; const sent = []; @@ -196,6 +196,81 @@ test('plugin: generates on start, regenerates on a Rust change and reloads; game } }); +test('dev: a failing Rust change never takes the server down (watcher, HMR, startup); builds still fail', async () => { + const f = await fixture(); + const previous = process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + delete process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE; + const logged = []; + const logger = { error: (message) => logged.push(message) }; + const server = () => { + const sent = []; + const listeners = []; + return { + sent, + connect: () => listeners.forEach((listener) => listener()), + watcher: { add: () => undefined }, + ws: { send: (payload) => sent.push(payload), on: (event, listener) => event === 'connection' && listeners.push(listener) }, + moduleGraph: { getModuleById: () => undefined, invalidateModule: () => undefined }, + httpServer: { once: () => undefined } + }; + }; + const rustFile = join(f.rust, 'src', 'lib.rs'); + try { + const plugin = distributedSvelteKitPublic(f.options()); + await plugin.configResolved({ root: f.app, command: 'serve', logger }); + const dev = server(); + plugin.configureServer(dev); + + // Vite's dev watcher awaits `watchChange` without a catch: it must resolve. + process.env.FAKE_RUST = join(f.root, 'nowhere'); + await plugin.watchChange(rustFile); + assert.equal(logged.length, 1); + assert.match(logged[0], /game client generation failed[\s\S]*Distributed compiler command failed/); + assert.equal(dev.sent.at(-1).type, 'error'); + assert.match(await readFile(join(f.out, 'index.ts'), 'utf8'), /zone v1/, 'last good client kept'); + // HMR path: same (overlay + console, no throw). + assert.deepEqual(await plugin.handleHotUpdate({ file: rustFile, server: dev }), []); + assert.equal(logged.length, 2); + + // Fixed: regenerates, reloads, and a newly opened overlay sees no stale error. + process.env.FAKE_RUST = f.rust; + await writeFile(rustFile, '// zone v3 with predict\n'); + await plugin.handleHotUpdate({ file: rustFile, server: dev }); + assert.deepEqual(dev.sent.at(-1), { type: 'full-reload', path: '*' }); + const before = dev.sent.length; + dev.connect(); + assert.equal(dev.sent.length, before); + await plugin.closeBundle(); + + // A broken surface at dev start: the server still starts; the error is + // logged and replayed to overlays that connect afterwards. + process.env.FAKE_RUST = join(f.root, 'nowhere'); + const late = distributedSvelteKitPublic(f.options()); + await late.configResolved({ root: f.app, command: 'serve', logger }); + assert.equal(logged.length, 3); + const lateServer = server(); + late.configureServer(lateServer); + lateServer.connect(); + assert.equal(lateServer.sent.at(-1).type, 'error'); + await late.closeBundle(); + + // Builds fail: one-shot build and `vite build --watch` rebuilds. + const build = distributedSvelteKit(f.options()); + await assert.rejects(build.configResolved({ root: f.app, command: 'build', logger }), /Distributed compiler command failed/); + process.env.FAKE_RUST = f.rust; + const watching = distributedSvelteKit(f.options()); + await watching.configResolved({ root: f.app, command: 'build', logger }); + process.env.FAKE_RUST = join(f.root, 'nowhere'); + await assert.rejects(watching.watchChange(rustFile), /Distributed compiler command failed/); + await watching.closeBundle(); + assert.equal(logged.length, 3, 'build failures are thrown, not just logged'); + } finally { + process.env.FAKE_RUST = f.rust; + if (previous !== undefined) process.env.DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE = previous; + await rm(f.root, { recursive: true, force: true }); + } +}); + test('plugin build: one generation per build process (SvelteKit reloads the config)', async () => { const f = await fixture(); try { From 3d22078cae6e495ea596b119b73590ca7220266e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 18:17:48 -0500 Subject: [PATCH 216/484] feat(examples): project Mob Pit kills into a SQL read model Move the Crawler aggregate into the mobpit_crawler crate and publish crawler.mob_killed as a domain event (post-kill CrawlerState) through the cell outbox in the same transaction. With --projection-bus the zone server drains cell outboxes onto a SQLite bus after each commit, at startup and on a sweep. The new read-only mobpit_service projects the events into player_stats with a modeled projector and serves it over GraphQL @live (Bearer JWT only, no commands). --- examples/game/server/Cargo.lock | 2019 ++++++++++++++++- examples/game/server/Cargo.toml | 11 +- examples/game/server/crawler/Cargo.toml | 22 + examples/game/server/crawler/src/lib.rs | 271 +++ examples/game/server/service/Cargo.toml | 34 + examples/game/server/service/src/http.rs | 78 + examples/game/server/service/src/lib.rs | 290 +++ examples/game/server/service/src/main.rs | 69 + .../save_player_stats.mutation.graphql | 5 + .../game/server/service/tests/projection.rs | 226 ++ examples/game/server/src/mobpit/crawler.rs | 230 +- examples/game/server/src/mobpit/mod.rs | 13 + examples/game/server/src/mobpit/store.rs | 113 +- examples/game/server/src/mobpit/world.rs | 39 +- 14 files changed, 3105 insertions(+), 315 deletions(-) create mode 100644 examples/game/server/crawler/Cargo.toml create mode 100644 examples/game/server/crawler/src/lib.rs create mode 100644 examples/game/server/service/Cargo.toml create mode 100644 examples/game/server/service/src/http.rs create mode 100644 examples/game/server/service/src/lib.rs create mode 100644 examples/game/server/service/src/main.rs create mode 100644 examples/game/server/service/src/mutations/save_player_stats.mutation.graphql create mode 100644 examples/game/server/service/tests/projection.rs diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index d44998324..04d21531d 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -2,6 +2,27 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "Inflector" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "anstream" version = "1.0.0" @@ -38,7 +59,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -49,7 +70,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -73,6 +94,121 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "ascii_utils" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71938f30533e4d95a6d17aa530939da3842c2ab6f4f84b9dae68447e4129f74a" + +[[package]] +name = "async-graphql" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1057a9f7ccf2404d94571dec3451ade1cb524790df6f1ada0d19c2a49f6b0f40" +dependencies = [ + "async-graphql-derive", + "async-graphql-parser", + "async-graphql-value", + "async-io", + "async-trait", + "asynk-strim", + "base64 0.22.1", + "bytes", + "fast_chemail", + "fnv", + "futures-util", + "handlebars", + "http", + "indexmap", + "mime", + "multer", + "num-traits", + "pin-project-lite", + "regex", + "serde", + "serde_json", + "serde_urlencoded", + "static_assertions_next", + "tempfile", + "thiserror", +] + +[[package]] +name = "async-graphql-axum" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e37c5532e4b686acf45e7162bc93da91fc2c702fb0d465efc2c20c8f973795" +dependencies = [ + "async-graphql", + "axum", + "bytes", + "futures-util", + "serde_json", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", +] + +[[package]] +name = "async-graphql-derive" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6cbeadc8515e66450fba0985ce722192e28443697799988265d86304d7cc68" +dependencies = [ + "Inflector", + "async-graphql-parser", + "darling 0.23.0", + "proc-macro-crate", + "proc-macro2", + "quote", + "strum", + "syn 2.0.119", + "thiserror", +] + +[[package]] +name = "async-graphql-parser" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64ef70f77a1c689111e52076da1cd18f91834bcb847de0a9171f83624b07fbf" +dependencies = [ + "async-graphql-value", + "pest", + "serde", + "serde_json", +] + +[[package]] +name = "async-graphql-value" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3ef112905abea9dea592fc868a6873b10ebd3f983e83308f995d6284e9ba41" +dependencies = [ + "bytes", + "indexmap", + "serde", + "serde_json", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + [[package]] name = "async-lock" version = "3.4.2" @@ -95,12 +231,60 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "asynk-strim" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52697735bdaac441a29391a9e97102c74c6ef0f9b60a40cf109b1b404e29d2f6" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "axum" version = "0.8.9" @@ -134,6 +318,7 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -152,6 +337,7 @@ dependencies = [ "sync_wrapper", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -204,6 +390,9 @@ name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -235,11 +424,20 @@ version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] [[package]] name = "cc" @@ -248,6 +446,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -257,6 +457,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -308,6 +514,21 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -328,12 +549,43 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "const-oid" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -352,6 +604,36 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "crypto-common" version = "0.1.7" @@ -371,12 +653,127 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +dependencies = [ + "cmov", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote", + "syn 2.0.119", +] + [[package]] name = "data-encoding" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + [[package]] name = "digest" version = "0.10.7" @@ -397,6 +794,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -414,17 +812,24 @@ dependencies = [ name = "distributed" version = "0.1.0" dependencies = [ + "async-graphql", + "async-graphql-axum", "async-trait", + "axum", "base64 0.23.1", "bitcode", "distributed_macros", "futures-util", + "hmac 0.12.1", "js-sys", + "jsonwebtoken", "redis", + "reqwest", "rusqlite", "serde", "serde_json", - "sha2", + "sha2 0.10.9", + "sqlx", "tokio", "tonic-build", "uuid", @@ -439,11 +844,11 @@ dependencies = [ "distributed", "distributed_game_macros", "futures-util", - "hmac", + "hmac 0.12.1", "rusqlite", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tokio", "tokio-tungstenite 0.30.0", ] @@ -465,29 +870,74 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "sha2", + "sha2 0.10.9", "syn 2.0.119", ] [[package]] -name = "equivalent" -version = "1.0.3" +name = "dotenvy" +version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] -name = "errno" -version = "0.3.14" +name = "dunce" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" dependencies = [ - "libc", - "windows-sys", + "serde", ] [[package]] -name = "event-listener" -version = "5.4.2" +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ @@ -517,6 +967,15 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fast_chemail" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "495a39d30d624c2caabe6312bfead73e7717692b44e0b32df168c275a2e8e9e4" +dependencies = [ + "ascii_utils", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -529,6 +988,23 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -544,6 +1020,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures-channel" version = "0.3.34" @@ -551,6 +1033,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -559,6 +1042,55 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -578,8 +1110,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", + "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -595,8 +1130,10 @@ dependencies = [ "futures-util", "game_sim", "http-body-util", + "mobpit_crawler", "serde", "serde_json", + "sqlx", "tokio", "tokio-tungstenite 0.30.0", "tower", @@ -619,6 +1156,19 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -638,9 +1188,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -649,12 +1201,30 @@ version = "0.34.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc148d4ddd3930c52f9e5ae79b89805c6f07e9ff417e7b083e0348cea60a5aba" +[[package]] +name = "handlebars" +version = "6.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c54236f9045c8004a77942bebc52145b4844639db934a5c70fe08617fbe61a" +dependencies = [ + "derive_builder", + "log", + "num-order", + "pest", + "pest_derive", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ + "allocator-api2", + "equivalent", "foldhash", ] @@ -679,6 +1249,27 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + [[package]] name = "hmac" version = "0.12.1" @@ -688,6 +1279,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -759,6 +1359,22 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", ] [[package]] @@ -767,13 +1383,22 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", ] [[package]] @@ -859,6 +1484,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -888,8 +1519,16 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -902,6 +1541,65 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.106" @@ -913,6 +1611,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "libc" version = "0.2.191" @@ -930,24 +1643,55 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "matchit" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.8.3" @@ -968,33 +1712,215 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +name = "mobpit_crawler" +version = "0.1.0" +dependencies = [ + "distributed", + "distributed_game", + "serde", + "serde_json", +] [[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +name = "mobpit_service" +version = "0.1.0" +dependencies = [ + "async-graphql", + "axum", + "distributed", + "distributed_game", + "futures-util", + "game_demos", + "mobpit_crawler", + "serde", + "serde_json", + "sqlx", + "tokio", +] [[package]] -name = "parking" -version = "2.2.1" +name = "multer" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "percent-encoding" -version = "2.3.2" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-modular" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd8e500409e6cd603b03e477c26a6caecdc27ac58979a53e881c75eafc079f44" + +[[package]] +name = "num-order" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6" +dependencies = [ + "num-modular", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pest" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd47a460a9cbc3b3429c7e22bf0d76653e779319bae45a499ca010c9a990bb23" +dependencies = [ + "memchr", + "psm", + "stacker", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "203e46697708f7519ab1608393cf89239cafb46b8e6d08a8ffe359359b11ef44" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e84ae6340a458d3d6cfc73cf328cf3cfe90b2484cd0de25eb66aa954615ed4d5" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "pest_meta" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b57f92f32b3dbce6598fd8f5cdf1f06a6072570b8103fa21728fa9036923e710" +dependencies = [ + "pest", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1007,6 +1933,20 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1016,6 +1956,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1053,6 +1999,72 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -1120,6 +2132,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "redis" version = "1.7.1" @@ -1147,6 +2168,95 @@ dependencies = [ "xxhash-rust", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsqlite-vfs" version = "0.1.1" @@ -1172,6 +2282,109 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -1184,6 +2397,59 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1273,84 +2539,356 @@ dependencies = [ ] [[package]] -name = "sha1_smol" -version = "1.0.1" +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "sqlx" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" +dependencies = [ + "base64 0.22.1", + "bytes", + "cfg-if", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap", + "log", + "memchr", + "percent-encoding", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "sqlx-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3" +dependencies = [ + "cfg-if", + "dotenvy", + "either", + "heck", + "hex", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27" +dependencies = [ + "bitflags", + "byteorder", + "bytes", + "crc", + "digest 0.11.3", + "dotenvy", + "either", + "futures-core", + "futures-util", + "generic-array", + "log", + "percent-encoding", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "sqlx-core", + "thiserror", + "tracing", +] + +[[package]] +name = "sqlx-postgres" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" +dependencies = [ + "atoi", + "base64 0.22.1", + "bitflags", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac 0.13.0", + "itoa", + "log", + "md-5", + "memchr", + "rand 0.10.3", + "serde", + "serde_json", + "sha2 0.11.1", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" +dependencies = [ + "atoi", + "flume", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] -name = "sha2" -version = "0.10.9" +name = "stacker" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" dependencies = [ + "cc", "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", + "libc", + "psm", + "windows-sys 0.61.2", ] [[package]] -name = "shlex" -version = "2.0.1" +name = "static_assertions_next" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +checksum = "d7beae5182595e9a8b683fa98c4317f956c9a2dec3b9716990d20023cc60c766" [[package]] -name = "signal-hook-registry" -version = "1.4.8" +name = "stringprep" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" dependencies = [ - "errno", - "libc", + "unicode-bidi", + "unicode-normalization", + "unicode-properties", ] [[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.3" +name = "strsim" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] -name = "socket2" -version = "0.6.5" +name = "strum" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" dependencies = [ - "libc", - "windows-sys", + "strum_macros", ] [[package]] -name = "sqlite-wasm-rs" -version = "0.5.5" +name = "strum_macros" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" dependencies = [ - "cc", - "js-sys", - "rsqlite-vfs", - "wasm-bindgen", + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - [[package]] name = "subtle" version = "2.6.1" @@ -1384,6 +2922,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -1396,6 +2937,19 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -1416,6 +2970,36 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -1426,6 +3010,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.3" @@ -1439,7 +3029,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1453,6 +3043,27 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + [[package]] name = "tokio-tungstenite" version = "0.29.0" @@ -1485,6 +3096,7 @@ checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", + "futures-io", "futures-sink", "libc", "pin-project-lite", @@ -1546,6 +3158,25 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", ] [[package]] @@ -1560,6 +3191,44 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "tungstenite" version = "0.29.0" @@ -1598,12 +3267,45 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -1651,6 +3353,25 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1679,6 +3400,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -1711,12 +3443,65 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1726,6 +3511,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "1.0.4" @@ -1817,6 +3666,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index 000a39bbe..cbe40eb72 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -2,7 +2,7 @@ # Own workspace (like tests/gateway-native) so demo-only dependencies never # reach the framework's lockfile; excluded from the root workspace. [workspace] -members = [".", "sim"] +members = [".", "sim", "crawler", "service"] resolver = "2" [package] @@ -22,9 +22,14 @@ path = "src/main.rs" [dependencies] # The client-predicted simulation (also compiled to WASM for the browser). game_sim = { path = "sim" } +# The Crawler aggregate + RecordKill (shared with the read-model service). +mobpit_crawler = { path = "crawler" } distributed_game = { path = "../../../distributed_game", features = ["net", "cell", "sqlite"] } -# Mob Pit: native durable SQLite cells + sorted-set leaderboards (Redis optional at runtime). -distributed = { path = "../../..", features = ["cell-sqlite", "redis"] } +# Mob Pit: native durable SQLite cells + sorted-set leaderboards (Redis optional +# at runtime) + the SQLite bus for the read-model service. +distributed = { path = "../../..", features = ["cell-sqlite", "redis", "sqlite"] } +# The SQLite bus the cells' domain events are drained onto (`--projection-bus`). +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite"] } axum = { version = "0.8", default-features = false, features = ["json", "query", "tokio", "http1"] } clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } diff --git a/examples/game/server/crawler/Cargo.toml b/examples/game/server/crawler/Cargo.toml new file mode 100644 index 000000000..0f9368895 --- /dev/null +++ b/examples/game/server/crawler/Cargo.toml @@ -0,0 +1,22 @@ +# Mob Pit's durable domain: the per-player `Crawler` aggregate, its one +# command (`crawler.record_kill`) and the outward `CrawlerState` domain +# event. Shared by the zone server (`game_demos`, which commits kills into +# Crawler cells) and the read-model service (`mobpit_service`, which +# projects the published events into SQL). +[package] +name = "mobpit_crawler" +version = "0.1.0" +edition = "2021" +publish = false +description = "Mob Pit Crawler aggregate, RecordKill command and domain events (dev demo)" + +[lib] +path = "src/lib.rs" + +[dependencies] +distributed = { path = "../../../.." } +distributed_game = { path = "../../../../distributed_game" } +serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +serde_json = "1" diff --git a/examples/game/server/crawler/src/lib.rs b/examples/game/server/crawler/src/lib.rs new file mode 100644 index 000000000..adb311930 --- /dev/null +++ b/examples/game/server/crawler/src/lib.rs @@ -0,0 +1,271 @@ +//! The durable side of Mob Pit: one `Crawler` aggregate per player, each in +//! its own native SQLite cell (`distributed` feature `cell-sqlite`, opened by +//! `game_demos`). +//! +//! The only command is [`RECORD_KILL`]. It is dispatched by the zone's fact +//! worker through `distributed_game::cell::CellFactSink`, never by a client: +//! +//! - the **principal** comes from the trusted server-built session +//! (`x-user-id`, bound by the host from the player's verified ticket); the +//! input has no identity field and unknown fields are rejected; +//! - the **XP amount** is decided here from the mob tier ([`xp_for_tier`]); +//! the zone only reports which mob died; +//! - the command id is derived from the fact key, so a retry or re-emission +//! replays the stored receipt through the cell's command ledger instead of +//! crediting twice; +//! - `crawler.mob_killed` is a **domain event**: the commit publishes the +//! post-kill [`CrawlerState`] into the cell's outbox in the same SQLite +//! transaction ([`CrawlerMobKilledDomainEvent`]). The zone server drains +//! that outbox onto a bus and the read-model service (`mobpit_service`) +//! projects it into the `player_stats` table behind GraphQL `@live`. + +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, DomainState, Entity}; +use serde::{Deserialize, Serialize}; +use std::time::UNIX_EPOCH; + +/// Aggregate type (cell instance names are `Crawler:{principal}`). +pub const AGGREGATE_TYPE: &str = "Crawler"; +/// Command dispatched for every `MobKilled` fact. +pub const RECORD_KILL: &str = "crawler.record_kill"; +/// Event recorded by [`RECORD_KILL`]. +pub const MOB_KILLED_EVENT: &str = "crawler.mob_killed"; + +/// XP per mob tier — server-side game rules, never client input. +pub fn xp_for_tier(tier: u8) -> Option { + match tier { + 1 => Some(10), + 2 => Some(25), + 3 => Some(60), + _ => None, + } +} + +/// Level for a total XP: level `n` starts at `40 · (n − 1)²` XP. +pub fn level_for(xp: u64) -> u32 { + let mut level = 1u32; + while level_floor(level + 1) <= xp { + level += 1; + } + level +} + +/// First XP of `level`. +pub fn level_floor(level: u32) -> u64 { + let n = u64::from(level.saturating_sub(1)); + 40 * n * n +} + +/// One player's durable progress. +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct Crawler { + entity: Entity, + /// Last display name seen with a kill (cosmetic; identity is the id). + pub name: String, + /// Total XP. + pub xp: u64, + /// Mobs killed. + pub kills: u32, + /// Derived from `xp`. + pub level: u32, +} + +/// The public post-kill state carried by `crawler.mob_killed` domain events +/// (versioned independently of the replay event and the snapshot). Its +/// fields are the `player_stats` read-model row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, DomainState)] +#[domain_state(version = 1)] +pub struct CrawlerState { + /// Principal (the cell's stream id). + pub player_id: String, + /// Display name at the last kill. + pub name: String, + /// Total XP. + pub xp: u64, + /// Mobs killed. + pub kills: u32, + /// Level for `xp`. + pub level: u32, +} + +impl From<&Crawler> for CrawlerState { + fn from(crawler: &Crawler) -> Self { + Self { + player_id: crawler.id().to_string(), + name: crawler.name.clone(), + xp: crawler.xp, + kills: crawler.kills, + level: crawler.level, + } + } +} + +#[sourced( + entity, + aggregate_type = "Crawler", + events = "CrawlerEvent", + domain_state = CrawlerState +)] +impl Crawler { + #[event("crawler.mob_killed", version = 1, domain)] + fn mob_killed(&mut self, id: String, name: String, mob: String, tier: u8, xp: u32) { + let _ = (mob, tier); + self.entity.set_id(id); + self.name = name; + self.xp += u64::from(xp); + self.kills += 1; + self.level = level_for(self.xp); + } +} + +impl Crawler { + /// Principal (stream id). + pub fn id(&self) -> &str { + self.entity.id() + } + + /// Committed stream version. + pub fn version(&self) -> u64 { + self.entity.version() + } +} + +/// Arguments of a recorded `crawler.mob_killed` event, in declaration order +/// (`EventRecord::decode` of the stored payload). +pub type MobKilledArgs = (String, String, String, u8, u32); + +/// [`RECORD_KILL`] input. No principal, no XP: both are server-decided. +/// +/// `FactCommand` binds it to [`RECORD_KILL`] (the name [`RecordKill`] +/// mounts it under), so the zone emits it typed — `ctx.emit_keyed(killer, +/// RecordKillInput { .. }, &[mob, generation])` — and the derive rejects +/// identity or reward fields at compile time. +#[derive( + Debug, Clone, Serialize, Deserialize, distributed::CommandInput, distributed_game::FactCommand, +)] +#[fact(command = RECORD_KILL)] +pub struct RecordKillInput { + /// Mob instance (`{zone}/m{id}`). + pub mob: String, + /// Mob tier (1..=3); XP comes from [`xp_for_tier`]. + pub tier: u8, + /// Display name at the time of the kill (server-sanitized). + pub name: String, +} + +/// [`RECORD_KILL`] result, replayed verbatim for a repeated fact key. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandOutput)] +pub struct KillReceipt { + /// Principal credited. + pub crawler: String, + /// Display name recorded. + pub name: String, + /// Mob instance. + pub mob: String, + /// Mob tier. + pub tier: u8, + /// XP credited by this kill. + pub xp: u32, + /// Total XP after it. + pub total_xp: u64, + /// Total kills after it. + pub kills: u32, + /// Level after it. + pub level: u32, + /// Stream sequence of the recorded event (leaderboard occurrence position). + pub sequence: u64, + /// Event time (Unix ms). + pub at_ms: u64, +} + +/// Mounts [`RECORD_KILL`] on a `Crawler` cell. +pub struct RecordKill; + +impl PortableCommand for RecordKill +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + RECORD_KILL, + )) + .guarded( + |ctx: &CausalCommandContext<'_, Crawler>| ctx.session().user_id().is_some(), + handle_record_kill, + ) + } +} + +async fn handle_record_kill( + ctx: &CausalCommandContext<'_, Crawler>, + input: RecordKillInput, +) -> Result>, HandlerError> { + // Identity: the trusted session only. The cell is the principal's own + // shard, so a mismatched principal cannot load it either. + let principal = ctx.session().user_id().unwrap_or_default().to_string(); + let xp = xp_for_tier(input.tier) + .ok_or_else(|| HandlerError::Rejected(format!("unknown mob tier {}", input.tier)))?; + let name: String = input.name.chars().take(16).collect(); + let repo = ctx.repo(); + let mut crawler = match repo.get(&principal).await? { + Some(crawler) => crawler, + None => repo.create(), + }; + crawler + .mob_killed( + principal.clone(), + name.clone(), + input.mob.clone(), + input.tier, + xp, + ) + .map_err(|e| HandlerError::Rejected(e.to_string()))?; + let (sequence, at_ms) = crawler + .entity + .events() + .last() + .map(|record| { + let at = record + .timestamp + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + (record.sequence, at) + }) + .unwrap_or_default(); + let receipt = KillReceipt { + crawler: principal, + name, + mob: input.mob, + tier: input.tier, + xp, + total_xp: crawler.xp, + kills: crawler.kills, + level: crawler.level, + sequence, + at_ms, + }; + // Event, ledger receipt, snapshot and the outbox row of the domain event + // commit in one cell transaction. + repo.publish_events().commit(crawler)?.succeeded(receipt) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_follow_the_quadratic_curve() { + assert_eq!(level_for(0), 1); + assert_eq!(level_for(39), 1); + assert_eq!(level_for(40), 2); + assert_eq!(level_for(159), 2); + assert_eq!(level_for(160), 3); + assert_eq!(level_floor(3), 160); + assert_eq!(xp_for_tier(0), None); + assert_eq!(xp_for_tier(3), Some(60)); + } +} diff --git a/examples/game/server/service/Cargo.toml b/examples/game/server/service/Cargo.toml new file mode 100644 index 000000000..33022fd4a --- /dev/null +++ b/examples/game/server/service/Cargo.toml @@ -0,0 +1,34 @@ +# Mob Pit's business-side read model: a Distributed service that projects +# the Crawler cells' published `crawler.mob_killed` domain events (drained +# by the zone server onto a SQLite bus) into a `player_stats` SQL table and +# serves it over GraphQL with `@live`. Read-only: it has no commands, so +# nothing here can credit XP. +[package] +name = "mobpit_service" +version = "0.1.0" +edition = "2021" +publish = false +description = "Mob Pit player stats read model + GraphQL @live (dev demo)" + +[lib] +path = "src/lib.rs" + +[[bin]] +name = "mobpit-service" +path = "src/main.rs" + +[dependencies] +mobpit_crawler = { path = "../crawler" } +distributed = { path = "../../../..", features = ["sqlite", "http", "graphql"] } +axum = { version = "0.8", default-features = false, features = ["json", "tokio", "http1", "ws"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "time", "sync"] } + +[dev-dependencies] +# The zone server's world: real Crawler cells + the fact sink + the bus drain. +game_demos = { path = ".." } +distributed_game = { path = "../../../../distributed_game", features = ["cell"] } +async-graphql = "7" +futures-util = { version = "0.3", default-features = false, features = ["std"] } diff --git a/examples/game/server/service/src/http.rs b/examples/game/server/service/src/http.rs new file mode 100644 index 000000000..376f23074 --- /dev/null +++ b/examples/game/server/service/src/http.rs @@ -0,0 +1,78 @@ +//! HTTP surface: `POST /graphql`, `GET /graphql/ws` (`graphql-transport-ws`, +//! the `@live` channel) and `GET /health`, plus CORS for the UI origins. +//! +//! The browser calls this service directly (Bearer token from the SvelteKit +//! page data; no cookies), so only exact configured origins are allowed and +//! credentials mode is never enabled. + +use std::sync::Arc; + +use axum::extract::{Request, State}; +use axum::http::header::{ + ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, + ACCESS_CONTROL_MAX_AGE, ORIGIN, VARY, +}; +use axum::http::{HeaderValue, Method, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use axum::Router; +use distributed::graphql::{graphql_router_composed, GraphqlEngine}; + +const ALLOWED_HEADERS: &str = "authorization, content-type, accept, x-distributed-participant"; + +#[derive(Clone)] +struct Cors { + origins: Arc>, +} + +async fn cors(State(cors): State, request: Request, next: Next) -> Response { + let origin = request + .headers() + .get(ORIGIN) + .filter(|origin| cors.origins.iter().any(|allowed| allowed == *origin)) + .cloned(); + let preflight = request.method() == Method::OPTIONS; + let mut response = if preflight { + if origin.is_some() { + StatusCode::NO_CONTENT.into_response() + } else { + StatusCode::FORBIDDEN.into_response() + } + } else { + next.run(request).await + }; + let headers = response.headers_mut(); + headers.append(VARY, HeaderValue::from_static("origin")); + if let Some(origin) = origin { + headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, origin); + if preflight { + headers.insert( + ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, OPTIONS"), + ); + headers.insert( + ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static(ALLOWED_HEADERS), + ); + headers.insert(ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("600")); + } + } + response +} + +/// The service router. +pub fn router(engine: Arc, allowed_origins: &[String]) -> Router { + let origins = allowed_origins + .iter() + .filter_map(|origin| HeaderValue::from_str(origin.trim_end_matches('/')).ok()) + .collect(); + graphql_router_composed(engine, None, None) + .route("/health", get(|| async { "ok" })) + .layer(middleware::from_fn_with_state( + Cors { + origins: Arc::new(origins), + }, + cors, + )) +} diff --git a/examples/game/server/service/src/lib.rs b/examples/game/server/service/src/lib.rs new file mode 100644 index 000000000..690232fb7 --- /dev/null +++ b/examples/game/server/service/src/lib.rs @@ -0,0 +1,290 @@ +//! Mob Pit's business-side read model (dev demo). +//! +//! ```text +//! zone ──fact──▶ Crawler cell (RecordKill: XP decided there; event + outbox +//! row in one SQLite transaction) +//! └─ zone server drains the cell outbox ──▶ SQLite bus (`bus_log`) +//! │ ordered, at-least-once +//! mobpit-service: modeled projector `project_player_stats` ◀──┘ +//! └─ upsert `player_stats` (checkpointed, deduplicated) ──▶ GraphQL +//! `@live` (in-process change stream) ──▶ SvelteKit `$distributed` +//! ``` +//! +//! - [`PlayerStats`] is the table: one row per principal, the Crawler's +//! post-kill state ([`mobpit_crawler::CrawlerState`]). The leaderboard is a +//! query over it (`order_by: xp desc`). +//! - [`PLAYER_STATS`] maps `CrawlerMobKilledDomainEvent` to the +//! [`SavePlayerStats`] upsert. The projector runtime keeps the cursor, +//! skips redelivered messages and commits each projection atomically. +//! - The service is **read-only**: no commands, so no caller can name a +//! player, an XP amount or a reward here. XP is decided by the Crawler +//! cell's `RecordKill` handler from the mob tier; the principal comes from +//! the zone ticket the SvelteKit server minted from the verified session. +//! - GraphQL identity is a verified Bearer JWT only (`OidcBearer`): the +//! SvelteKit server's ES256 token in dev, or the OIDC provider's access +//! token. There is no header-trust mode. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +use distributed::bus::SqliteBus; +use distributed::graphql::{ + build_surface, read, surface_for_application_contract, DistributedClientSurfaceExport, + GraphqlEngine, IdentityConfig, ModelPermissions, OidcConfig, RoleGrant, Surface, + SurfaceOptions, SurfaceProjector, +}; +use distributed::microsvc::{ + spawn_service_consumer_loop, CausalProjectorContext, HandlerError, ModeledProjection, Routes, + Service, CONSUMER_IDLE_POLL, +}; +use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; +use distributed::{ + mutation_file, Application, ApplicationManifest, LocalProjectionMountsBuilder, Mutation, + ReadModel, ReadModelCatalog, RelationalReadModel, SqliteRepository, SurfaceSpec, +}; +use mobpit_crawler::CrawlerMobKilledDomainEvent; +use serde::{Deserialize, Serialize}; + +/// Application, GraphQL service id and client surface name. +pub const APPLICATION: &str = "mobpit"; +/// Projection name. +pub const PROJECTOR: &str = "project_player_stats"; +/// Projection epoch: bump to rebuild the table from the bus log. +pub const EPOCH: &str = "mobpit-player-stats-v1"; +/// The one engine role. Every signed-in player reads the whole board. +pub const ROLE: &str = "user"; + +/// One player's settled progress (a projection of their Crawler cell). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] +#[table("player_stats")] +pub struct PlayerStats { + /// Principal (the verified session's user id). + #[id("player_id")] + pub player_id: String, + /// Display name at the last kill. + pub name: String, + /// Total XP (decided by the Crawler cell, never by a caller). + pub xp: i64, + /// Mobs killed. + pub kills: i64, + /// Level for `xp`. + pub level: i64, +} + +impl PlayerStats { + /// Read authorization: the leaderboard is public to signed-in players; + /// there is nothing to write (no commands, no mutations). + pub fn permissions() -> ModelPermissions { + ModelPermissions::new().grant(ROLE, read().all_columns()) + } +} + +/// Upsert one `player_stats` row from the domain event's state body. +#[allow(non_snake_case)] +pub fn SavePlayerStats() -> Mutation<()> { + mutation_file!("src/mutations/save_player_stats.mutation.graphql") +} + +distributed::projection! { + pub const PLAYER_STATS: ProjectionDescriptor = { + name: "project_player_stats", + version: 1, + epoch: "mobpit-player-stats-v1", + model: PlayerStats, + on { + events: [CrawlerMobKilledDomainEvent], + mutation: SavePlayerStats, + input: { player: body }, + }, + }; +} + +/// Physical read-model catalog (`player_stats`). +pub fn read_model_catalog() -> ReadModelCatalog { + ReadModelCatalog::new(APPLICATION).table_schema(PlayerStats::schema().clone()) +} + +/// The modeled projector mount for [`PLAYER_STATS`]. +pub fn projector() -> SurfaceProjector { + LocalProjectionMountsBuilder::new(APPLICATION, "ordered-domain-events") + .expect("projection source") + .eventual_model::(PROJECTOR, PLAYER_STATS, EPOCH) + .expect("player stats mount") + .build() + .expect("projection catalog") + .projector(PROJECTOR) + .expect("player stats projector") +} + +async fn project( + context: CausalProjectorContext, + projection: ModeledProjection, +) -> Result<(), HandlerError> { + projection.apply(PLAYER_STATS, &context).await +} + +/// The consumer service (bus consumer identity = [`APPLICATION`]): the +/// modeled projector over `read_models`. +pub fn projection_service(read_models: SqliteRepository) -> Service { + Service::new().named(APPLICATION).routes( + Routes::new() + .with_read_model_store(read_models) + .modeled_projector(projector()) + .handle(project), + ) +} + +/// Run the projector against the bus forever (restarted on errors; the +/// cursor lives in the read-model database, so a restart resumes). +pub fn spawn_projector(read_models: SqliteRepository, bus: sqlx::SqlitePool) { + spawn_service_consumer_loop(move || { + projection_service(read_models.clone()) + .with_bus(SqliteBus::new(bus.clone()).with_idle_poll(CONSUMER_IDLE_POLL)) + }); +} + +fn grants() -> BTreeMap> { + let mut grants: BTreeMap> = BTreeMap::new(); + for (role, grant) in PlayerStats::permissions().surface_grants() { + grants + .entry(role) + .or_default() + .insert(PlayerStats::schema().model_name.clone(), grant); + } + grants +} + +fn full_surface() -> Surface { + build_surface(&read_model_catalog().tables, &SurfaceOptions::sqlite()) + .expect("mobpit Surface should build") + .with_projection_owners([projector().into()]) + .expect("mobpit projector should bind") +} + +/// Logical application artifact (`distributed describe`, the lifecycle). +pub fn application_manifest() -> ApplicationManifest { + let surface = SurfaceSpec::from_surface(APPLICATION, &full_surface()) + .expect("mobpit Surface should compile into an application artifact"); + Application::new(APPLICATION) + .surface(surface) + .build() + .expect("mobpit application manifest should compile") + .manifest() + .clone() +} + +/// Pool-free client export consumed by `distributed client-manifest`. +pub fn distributed_client_surface() -> DistributedClientSurfaceExport { + let roles = [ROLE.to_string()]; + let selected = + surface_for_application_contract(&full_surface(), APPLICATION, &roles, &roles, &grants()) + .expect("mobpit application Surface should select"); + DistributedClientSurfaceExport::from_selected(APPLICATION, selected) + .expect("mobpit application Surface should export") +} + +/// GraphQL identity: a verified Bearer JWT, nothing else. +#[derive(Debug, Clone)] +pub struct BearerIdentity { + /// Expected `iss`. + pub issuer: String, + /// Expected `aud`. + pub audience: String, + /// Static JWKS JSON (dev: the SvelteKit server's public key); None = + /// discover from the issuer. + pub jwks: Option, +} + +impl BearerIdentity { + fn config(&self) -> IdentityConfig { + let mut oidc = OidcConfig::new(&self.issuer, &self.audience).engine_roles(&[ROLE]); + if let Some(jwks) = &self.jwks { + oidc = oidc.with_static_jwks(jwks.clone()); + } + IdentityConfig::oidc_bearer(oidc) + } +} + +/// The GraphQL engine over `repo` with `@live` pushes from its change stream. +pub fn build_engine( + repo: &SqliteRepository, + identity: &BearerIdentity, + protocol_key: [u8; 32], +) -> Result { + GraphqlEngine::builder(repo.pool().clone()) + .service_id(APPLICATION) + .protocol_token_key(protocol_key) + .roles(&[ROLE]) + .client_application_surface(APPLICATION, [ROLE], [ROLE]) + .model::(PlayerStats::permissions()) + .client_projection_owners([projector().into()]) + .identity(identity.config()) + .graphiql(false) + .change_stream(repo.read_model_changes()) + .build() + .map_err(|e| e.to_string()) +} + +/// Open (creating if needed) a SQLite pool another process may share: WAL +/// and a busy timeout, so the zone server's appends and this service's reads +/// of the bus wait for each other instead of failing. +pub async fn open_shared_sqlite(url: &str) -> Result { + use std::str::FromStr; + let options = sqlx::sqlite::SqliteConnectOptions::from_str(url)? + .create_if_missing(true) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .busy_timeout(Duration::from_secs(10)); + sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(4) + .connect_with(options) + .await +} + +/// Runtime configuration. +#[derive(Debug, Clone)] +pub struct ServiceOptions { + /// `sqlite:` URL of the read-model database. + pub database_url: String, + /// `sqlite:` URL of the bus the zone server publishes to. + pub bus_url: String, + /// Listen address. + pub bind: String, + /// Bearer verification. + pub identity: BearerIdentity, + /// Generated clients' protocol-token key (32 bytes, non-zero). + pub protocol_key: [u8; 32], + /// Browser origins allowed to call `/graphql` cross-origin (the UI). + pub allowed_origins: Vec, +} + +/// Open the read model, start the projector, serve `/graphql` + `/graphql/ws`. +pub async fn run(options: ServiceOptions) -> Result<(), Box> { + let repo = SqliteRepository::connect_and_migrate(&options.database_url).await?; + repo.bootstrap_table_schema_for_dev(&read_model_catalog().table_registry()?) + .await?; + let bus_pool = open_shared_sqlite(&options.bus_url).await?; + SqliteBus::new(bus_pool.clone()).ensure_tables().await?; + + let engine = Arc::new(build_engine( + &repo, + &options.identity, + options.protocol_key, + )?); + spawn_projector(repo.clone(), bus_pool); + let app = http::router(engine, &options.allowed_origins); + let listener = tokio::net::TcpListener::bind(&options.bind).await?; + eprintln!( + "mobpit-service: player_stats @live on http://{}/graphql", + listener.local_addr()? + ); + println!("LISTENING http://{}", listener.local_addr()?); + axum::serve(listener, app) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} + +pub mod http; diff --git a/examples/game/server/service/src/main.rs b/examples/game/server/service/src/main.rs new file mode 100644 index 000000000..0192de021 --- /dev/null +++ b/examples/game/server/service/src/main.rs @@ -0,0 +1,69 @@ +//! `mobpit-service` — Mob Pit's player-stats read model behind GraphQL `@live`. +//! +//! Env (dev defaults in `examples/game/run.sh`): +//! - `DATABASE_URL` — read model, `sqlite:…` (default `sqlite:./mobpit-service.db`) +//! - `MOBPIT_BUS_URL` — the SQLite bus the zone server publishes Crawler +//! domain events to (default `sqlite:./mobpit-bus.db`) +//! - `BIND` (default `127.0.0.1:8791`, the `distributed dev` convention) +//! - `MOBPIT_API_ISSUER`, `MOBPIT_API_AUDIENCE` — expected `iss` / `aud` of the +//! Bearer JWT (required) +//! - `MOBPIT_API_JWKS` — static JWKS JSON (dev: the SvelteKit server's ES256 +//! public key); unset = discover from the issuer (`/.well-known/openid-configuration`) +//! - `MOBPIT_PROTOCOL_KEY` — 64 hex chars for the generated clients' +//! protocol tokens (required) +//! - `MOBPIT_UI_ORIGINS` — comma-separated browser origins allowed to call +//! `/graphql` (the SvelteKit app) + +use std::env; + +use mobpit_service::{run, BearerIdentity, ServiceOptions}; + +fn required(name: &str) -> Result { + env::var(name) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + .ok_or_else(|| format!("{name} is required")) +} + +fn protocol_key() -> Result<[u8; 32], String> { + let hex = required("MOBPIT_PROTOCOL_KEY")?; + let bytes: Vec = (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(hex.get(i..i + 2).unwrap_or("x"), 16)) + .collect::>() + .map_err(|_| "MOBPIT_PROTOCOL_KEY must be hex".to_string())?; + let key: [u8; 32] = bytes + .try_into() + .map_err(|_| "MOBPIT_PROTOCOL_KEY must be 32 bytes".to_string())?; + if key.iter().all(|b| *b == 0) { + return Err("MOBPIT_PROTOCOL_KEY must not be all zero".into()); + } + Ok(key) +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let options = ServiceOptions { + database_url: env::var("DATABASE_URL") + .unwrap_or_else(|_| "sqlite:./mobpit-service.db?mode=rwc".into()), + bus_url: env::var("MOBPIT_BUS_URL").unwrap_or_else(|_| "sqlite:./mobpit-bus.db".into()), + bind: env::var("BIND").unwrap_or_else(|_| "127.0.0.1:8791".into()), + identity: BearerIdentity { + issuer: required("MOBPIT_API_ISSUER")?, + audience: required("MOBPIT_API_AUDIENCE")?, + jwks: env::var("MOBPIT_API_JWKS") + .ok() + .filter(|v| !v.trim().is_empty()), + }, + protocol_key: protocol_key()?, + allowed_origins: env::var("MOBPIT_UI_ORIGINS") + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|origin| !origin.is_empty()) + .map(String::from) + .collect(), + }; + run(options).await +} diff --git a/examples/game/server/service/src/mutations/save_player_stats.mutation.graphql b/examples/game/server/service/src/mutations/save_player_stats.mutation.graphql new file mode 100644 index 000000000..b691e26c6 --- /dev/null +++ b/examples/game/server/service/src/mutations/save_player_stats.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR (not a public field). +# The row is the Crawler's post-kill state carried by the domain event. +mutation SavePlayerStats { + upsert_player_stats(object: $input.player) +} diff --git a/examples/game/server/service/tests/projection.rs b/examples/game/server/service/tests/projection.rs new file mode 100644 index 000000000..81952af98 --- /dev/null +++ b/examples/game/server/service/tests/projection.rs @@ -0,0 +1,226 @@ +//! Kill settlements → Crawler cell → outbox → SQLite bus → `player_stats` +//! → GraphQL `@live`, with the real zone-server world (cells + fact sink + +//! drain) and the service's projector and engine: +//! +//! 1. settled kills project into one row per player with the cell's totals +//! (XP decided by the cell; a replayed fact changes nothing); +//! 2. a live leaderboard subscription pushes the next settled kill; +//! 3. the rows equal the cells after a restart of the projector (cursor +//! resumes, redelivery is deduplicated); +//! 4. the surface has no mutations and the HTTP endpoint refuses a request +//! without a verified Bearer token. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use async_graphql::Request; +use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; +use distributed::SqliteRepository; +use distributed_game::{Fact, FactSink, FactStamp}; +use futures_util::StreamExt; +use game_demos::common::random_hex; +use game_demos::mobpit::crawler::RECORD_KILL; +use game_demos::mobpit::{MobPitWorld, WorldOptions}; +use mobpit_service::{ + build_engine, open_shared_sqlite, read_model_catalog, spawn_projector, BearerIdentity, +}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +fn temp_dir() -> PathBuf { + std::env::temp_dir().join(format!("mobpit-service-{}", random_hex(10))) +} + +fn kill(key: &str, principal: &str, tier: u8, name: &str) -> Fact { + Fact::trusted( + key, + RECORD_KILL, + json!({ "mob": format!("pit-1/{key}"), "tier": tier, "name": name }), + Some(principal.into()), + FactStamp::default(), + ) +} + +fn identity() -> BearerIdentity { + // Never used to verify here (sessions are passed directly); HTTP refuses + // a request without a Bearer before any key is needed. + BearerIdentity { + issuer: "https://mobpit.test".into(), + audience: "mobpit-service".into(), + jwks: Some(r#"{"keys":[]}"#.into()), + } +} + +fn user(id: &str) -> Session { + let mut session = Session::new(); + session.set(ROLE_KEY, "user"); + session.set(USER_ID_KEY, id); + session +} + +async fn rows(repo: &SqliteRepository) -> Vec<(String, String, i64, i64, i64)> { + sqlx::query_as( + "SELECT player_id, name, xp, kills, level FROM player_stats ORDER BY xp DESC, player_id", + ) + .fetch_all(repo.pool()) + .await + .unwrap() +} + +async fn eventually>( + what: &str, + mut check: impl FnMut() -> F, +) { + let start = Instant::now(); + while !check().await { + assert!( + start.elapsed() < Duration::from_secs(20), + "timed out waiting for {what}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn settled_kills_project_into_live_player_stats() { + let dir = temp_dir(); + std::fs::create_dir_all(&dir).unwrap(); + let bus_url = format!("sqlite:{}", dir.join("bus.db").display()); + let db_url = format!("sqlite:{}?mode=rwc", dir.join("service.db").display()); + + // Zone-server side: cells + sink, events drained to the bus. + let world = MobPitWorld::open(WorldOptions::new(dir.join("cells"))).unwrap(); + let sink = world.fact_sink(); + // A kill settled before the bus existed waits in the cell's outbox. + sink.commit(&kill("k0", "dev-ana", 2, "ana")).await.unwrap(); + let pending = world + .attach_projection_bus(&bus_url, Duration::from_millis(200)) + .await + .unwrap(); + assert_eq!(pending, 1, "startup drain publishes the waiting event"); + + // Service side. + let repo = SqliteRepository::connect_and_migrate(&db_url) + .await + .unwrap(); + repo.bootstrap_table_schema_for_dev(&read_model_catalog().table_registry().unwrap()) + .await + .unwrap(); + let bus = open_shared_sqlite(&bus_url).await.unwrap(); + spawn_projector(repo.clone(), bus.clone()); + let engine = build_engine(&repo, &identity(), [7; 32]).unwrap(); + + sink.commit(&kill("k1", "dev-ana", 3, "ana")).await.unwrap(); + sink.commit(&kill("k2", "dev-bo", 1, "bo")).await.unwrap(); + // A redelivered fact replays the receipt: no new event, no double XP. + assert!( + sink.commit(&kill("k1", "dev-ana", 3, "ana")) + .await + .unwrap() + .replayed + ); + eventually("projection", || async { + rows(&repo).await + == vec![ + ("dev-ana".into(), "ana".into(), 85, 2, 2), + ("dev-bo".into(), "bo".into(), 10, 1, 1), + ] + }) + .await; + + // Live leaderboard: the initial result, then a push for the next kill. + let board = Request::new( + "subscription { player_stats(order_by: [{ xp: desc }, { player_id: asc }], limit: 5) { player_id xp kills level } }", + ); + let mut live = Box::pin(engine.execute_stream(&user("dev-bo"), board)); + let first = tokio::time::timeout(Duration::from_secs(5), live.next()) + .await + .unwrap() + .unwrap(); + assert!(first.errors.is_empty(), "{:?}", first.errors); + let data: Value = serde_json::to_value(&first.data).unwrap(); + assert_eq!(data["player_stats"][0]["player_id"], "dev-ana"); + sink.commit(&kill("k3", "dev-bo", 3, "bo")).await.unwrap(); + let pushed = tokio::time::timeout(Duration::from_secs(10), live.next()) + .await + .expect("live push after the settled kill") + .unwrap(); + let data: Value = serde_json::to_value(&pushed.data).unwrap(); + assert_eq!( + data["player_stats"][0], + json!({ "player_id": "dev-ana", "xp": 85, "kills": 2, "level": 2 }) + ); + assert_eq!( + data["player_stats"][1], + json!({ "player_id": "dev-bo", "xp": 70, "kills": 2, "level": 2 }) + ); + + // "My stats" is the same table filtered by the session's id. + let mine = engine + .execute( + &user("dev-bo"), + Request::new( + r#"query { player_stats(where: { player_id: { _eq: "dev-bo" } }) { xp } }"#, + ), + ) + .await; + assert_eq!( + serde_json::to_value(&mine.data).unwrap(), + json!({ "player_stats": [{ "xp": 70 }] }) + ); + + // Read-only surface: there is no mutation to credit XP with. + let forged = engine + .execute( + &user("dev-bo"), + Request::new(r#"mutation { upsert_player_stats(object: { player_id: "dev-bo", xp: 9999 }) { xp } }"#), + ) + .await; + assert!(!forged.errors.is_empty(), "mutations must not exist"); + + // A second projector over the same cursor (a restart) re-reads nothing + // twice: the rows still equal the cells. + spawn_projector(repo.clone(), bus.clone()); + sink.commit(&kill("k4", "dev-cy", 2, "cy")).await.unwrap(); + eventually("third player", || async { rows(&repo).await.len() == 3 }).await; + for (player, _, xp, kills, level) in rows(&repo).await { + let cell = world + .cells() + .get(&player) + .unwrap() + .load() + .await + .unwrap() + .unwrap(); + assert_eq!( + (xp, kills, level), + (cell.xp as i64, i64::from(cell.kills), i64::from(cell.level)) + ); + } + + // HTTP: no Bearer → refused (no header-trust identity mode). + let app = mobpit_service::http::router(std::sync::Arc::new(engine), &["http://ui.test".into()]); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let body = r#"{"query":"{ player_stats { player_id xp } }"}"#; + let raw = |extra: &str| { + format!( + "POST /graphql HTTP/1.1\r\nHost: t\r\nConnection: close\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\n\r\n{body}", + body.len() + ) + }; + for extra in ["", "x-user-id: dev-ana\r\nx-roles: user\r\n"] { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + stream.write_all(raw(extra).as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + assert!( + !response.contains("dev-ana"), + "unauthenticated read leaked rows: {response}" + ); + assert!(response.starts_with("HTTP/1.1 401"), "{response}"); + } + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/examples/game/server/src/mobpit/crawler.rs b/examples/game/server/src/mobpit/crawler.rs index 57910cab8..3515781fa 100644 --- a/examples/game/server/src/mobpit/crawler.rs +++ b/examples/game/server/src/mobpit/crawler.rs @@ -1,228 +1,4 @@ -//! The durable side of Mob Pit: one `Crawler` aggregate per player, each in -//! its own native SQLite cell (`distributed` feature `cell-sqlite`). -//! -//! The only command is [`RECORD_KILL`]. It is dispatched by the zone's fact -//! worker through `distributed_game::cell::CellFactSink`, never by a client: -//! -//! - the **principal** comes from the trusted server-built session -//! (`x-user-id`, bound by the host from the player's verified ticket); the -//! input has no identity field and unknown fields are rejected; -//! - the **XP amount** is decided here from the mob tier ([`xp_for_tier`]); -//! the zone only reports which mob died; -//! - the command id is derived from the fact key, so a retry or re-emission -//! replays the stored receipt through the cell's command ledger instead of -//! crediting twice. +//! The durable side of Mob Pit lives in the `mobpit_crawler` crate (shared +//! with the read-model service); re-exported here for the zone and tests. -use distributed::command::{typed_command, PreparedCommand, Succeeded}; -use distributed::microsvc::{ - CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, -}; -use distributed::{sourced, Entity}; -use serde::{Deserialize, Serialize}; -use std::time::UNIX_EPOCH; - -/// Aggregate type (cell instance names are `Crawler:{principal}`). -pub const AGGREGATE_TYPE: &str = "Crawler"; -/// Command dispatched for every `MobKilled` fact. -pub const RECORD_KILL: &str = "crawler.record_kill"; -/// Event recorded by [`RECORD_KILL`]. -pub const MOB_KILLED_EVENT: &str = "crawler.mob_killed"; - -/// XP per mob tier — server-side game rules, never client input. -pub fn xp_for_tier(tier: u8) -> Option { - match tier { - 1 => Some(10), - 2 => Some(25), - 3 => Some(60), - _ => None, - } -} - -/// Level for a total XP: level `n` starts at `40 · (n − 1)²` XP. -pub fn level_for(xp: u64) -> u32 { - let mut level = 1u32; - while level_floor(level + 1) <= xp { - level += 1; - } - level -} - -/// First XP of `level`. -pub fn level_floor(level: u32) -> u64 { - let n = u64::from(level.saturating_sub(1)); - 40 * n * n -} - -/// One player's durable progress. -#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] -pub struct Crawler { - entity: Entity, - /// Last display name seen with a kill (cosmetic; identity is the id). - pub name: String, - /// Total XP. - pub xp: u64, - /// Mobs killed. - pub kills: u32, - /// Derived from `xp`. - pub level: u32, -} - -#[sourced(entity, aggregate_type = "Crawler", events = "CrawlerEvent")] -impl Crawler { - #[event("crawler.mob_killed", version = 1)] - fn mob_killed(&mut self, id: String, name: String, mob: String, tier: u8, xp: u32) { - let _ = (mob, tier); - self.entity.set_id(id); - self.name = name; - self.xp += u64::from(xp); - self.kills += 1; - self.level = level_for(self.xp); - } -} - -impl Crawler { - /// Principal (stream id). - pub fn id(&self) -> &str { - self.entity.id() - } - - /// Committed stream version. - pub fn version(&self) -> u64 { - self.entity.version() - } -} - -/// Arguments of a recorded `crawler.mob_killed` event, in declaration order -/// (`EventRecord::decode` of the stored payload). -pub type MobKilledArgs = (String, String, String, u8, u32); - -/// [`RECORD_KILL`] input. No principal, no XP: both are server-decided. -/// -/// `FactCommand` binds it to [`RECORD_KILL`] (the name [`RecordKill`] -/// mounts it under), so the zone emits it typed — `ctx.emit_keyed(killer, -/// RecordKillInput { .. }, &[mob, generation])` — and the derive rejects -/// identity or reward fields at compile time. -#[derive( - Debug, Clone, Serialize, Deserialize, distributed::CommandInput, distributed_game::FactCommand, -)] -#[fact(command = RECORD_KILL)] -pub struct RecordKillInput { - /// Mob instance (`{zone}/m{id}`). - pub mob: String, - /// Mob tier (1..=3); XP comes from [`xp_for_tier`]. - pub tier: u8, - /// Display name at the time of the kill (server-sanitized). - pub name: String, -} - -/// [`RECORD_KILL`] result, replayed verbatim for a repeated fact key. -#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandOutput)] -pub struct KillReceipt { - /// Principal credited. - pub crawler: String, - /// Display name recorded. - pub name: String, - /// Mob instance. - pub mob: String, - /// Mob tier. - pub tier: u8, - /// XP credited by this kill. - pub xp: u32, - /// Total XP after it. - pub total_xp: u64, - /// Total kills after it. - pub kills: u32, - /// Level after it. - pub level: u32, - /// Stream sequence of the recorded event (leaderboard occurrence position). - pub sequence: u64, - /// Event time (Unix ms). - pub at_ms: u64, -} - -/// Mounts [`RECORD_KILL`] on a `Crawler` cell. -pub struct RecordKill; - -impl PortableCommand for RecordKill -where - D: CausalRouteDependencies + Send + Sync + 'static, -{ - fn install(self, routes: Routes) -> Routes { - routes - .typed_command(typed_command::>( - RECORD_KILL, - )) - .guarded( - |ctx: &CausalCommandContext<'_, Crawler>| ctx.session().user_id().is_some(), - handle_record_kill, - ) - } -} - -async fn handle_record_kill( - ctx: &CausalCommandContext<'_, Crawler>, - input: RecordKillInput, -) -> Result>, HandlerError> { - // Identity: the trusted session only. The cell is the principal's own - // shard, so a mismatched principal cannot load it either. - let principal = ctx.session().user_id().unwrap_or_default().to_string(); - let xp = xp_for_tier(input.tier) - .ok_or_else(|| HandlerError::Rejected(format!("unknown mob tier {}", input.tier)))?; - let name: String = input.name.chars().take(16).collect(); - let repo = ctx.repo(); - let mut crawler = match repo.get(&principal).await? { - Some(crawler) => crawler, - None => repo.create(), - }; - crawler - .mob_killed( - principal.clone(), - name.clone(), - input.mob.clone(), - input.tier, - xp, - ) - .map_err(|e| HandlerError::Rejected(e.to_string()))?; - let (sequence, at_ms) = crawler - .entity - .events() - .last() - .map(|record| { - let at = record - .timestamp - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as u64); - (record.sequence, at) - }) - .unwrap_or_default(); - let receipt = KillReceipt { - crawler: principal, - name, - mob: input.mob, - tier: input.tier, - xp, - total_xp: crawler.xp, - kills: crawler.kills, - level: crawler.level, - sequence, - at_ms, - }; - repo.commit(crawler)?.succeeded(receipt) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn levels_follow_the_quadratic_curve() { - assert_eq!(level_for(0), 1); - assert_eq!(level_for(39), 1); - assert_eq!(level_for(40), 2); - assert_eq!(level_for(159), 2); - assert_eq!(level_for(160), 3); - assert_eq!(level_floor(3), 160); - assert_eq!(xp_for_tier(0), None); - assert_eq!(xp_for_tier(3), Some(60)); - } -} +pub use mobpit_crawler::*; diff --git a/examples/game/server/src/mobpit/mod.rs b/examples/game/server/src/mobpit/mod.rs index e11876ad9..850d89706 100644 --- a/examples/game/server/src/mobpit/mod.rs +++ b/examples/game/server/src/mobpit/mod.rs @@ -52,6 +52,12 @@ pub struct MobPitArgs { /// Start with this artificial storage latency (ms). #[arg(long, env = "MOBPIT_STORAGE_LATENCY_MS", default_value_t = 0)] pub storage_latency_ms: u64, + /// SQLite bus (`sqlite:/path/bus.db`) to publish the Crawler cells' + /// `crawler.mob_killed` domain events to; `mobpit-service` projects them + /// into its `player_stats` read model. Unset: events stay in the cells' + /// outboxes until a bus is attached. + #[arg(long, env = "MOBPIT_PROJECTION_BUS")] + pub projection_bus: Option, } /// Demo registration. @@ -134,6 +140,13 @@ pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { ), Err(error) => eprintln!("mobpit: leaderboard rebuild failed (serving anyway): {error}"), } + if let Some(url) = &args.projection_bus { + let published = world + .attach_projection_bus(url, std::time::Duration::from_secs(2)) + .await + .map_err(std::io::Error::other)?; + eprintln!("mobpit: projection bus {url} (published {published} pending events)"); + } eprintln!( "mobpit: data dir {} · boot {} · leaderboard {}", data_dir.display(), diff --git a/examples/game/server/src/mobpit/store.rs b/examples/game/server/src/mobpit/store.rs index f9d5df62c..aebfd0e47 100644 --- a/examples/game/server/src/mobpit/store.rs +++ b/examples/game/server/src/mobpit/store.rs @@ -9,6 +9,14 @@ //! [`CrawlerFactSink`] is the game's `FactSink`: optional artificial latency //! (the "slow storage" toggle), then `CellFactSink::commit` into the killer's //! cell, then a fire-and-forget leaderboard update. +//! +//! Each commit also writes the `crawler.mob_killed` domain event into the +//! cell's outbox (same transaction). With a [`ProjectionBus`] attached +//! (`--projection-bus`), the sink drains that outbox onto the SQLite bus +//! after the commit, and a sweep drains every cell at startup and +//! periodically (a crash between commit and drain, a bus outage). Delivery +//! is at-least-once with stable message ids; the read-model service's +//! projector deduplicates. Without a bus the rows wait in the cells. use std::collections::{BTreeMap, VecDeque}; use std::path::{Path, PathBuf}; @@ -16,8 +24,10 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; +use distributed::bus::SqliteBus; use distributed::cell_host::{AggregateCell, CellSqlitePath, CellStreamStore}; use distributed::entity::EventRecord; +use distributed::BusPublisher; use distributed::{RepositoryError, StreamIdentity}; use distributed_game::cell::CellFactSink; use distributed_game::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; @@ -36,6 +46,8 @@ const FILE_PREFIX: &str = "Crawler%3A"; pub struct CrawlerCell { cell: Arc>, sink: CellFactSink, + /// One drain at a time per cell keeps the published order = commit order. + draining: tokio::sync::Mutex<()>, } impl CrawlerCell { @@ -53,6 +65,70 @@ impl CrawlerCell { pub fn cell(&self) -> &Arc> { &self.cell } + + /// Publish this cell's pending outbox rows (its domain events) to `bus`, + /// oldest first; returns how many were published. + pub async fn drain_to(&self, bus: &ProjectionBus) -> Result { + let _turn = self.draining.lock().await; + let mut published = 0; + loop { + let outcome = self + .cell + .drain_outbox_with( + bus.publisher.clone(), + Duration::from_secs(30), + DRAIN_MAX_ATTEMPTS, + DRAIN_BATCH, + ) + .await + .map_err(|e| e.to_string())?; + published += outcome.published; + if outcome.released > 0 || outcome.failed > 0 { + return Err(format!( + "projection bus publish failed ({} released, {} failed)", + outcome.released, outcome.failed + )); + } + if outcome.claimed < DRAIN_BATCH { + return Ok(published); + } + } + } +} + +const DRAIN_BATCH: usize = 32; +/// Rows are retried by later drains rather than dropped. +const DRAIN_MAX_ATTEMPTS: u32 = 10_000; + +/// The SQLite bus Crawler domain events are published to (consumed by +/// `mobpit-service`'s projector). +#[derive(Clone)] +pub struct ProjectionBus { + publisher: BusPublisher, +} + +impl ProjectionBus { + /// Open (creating) the bus at a `sqlite:` URL shared with the service. + pub async fn open(url: &str) -> Result { + use std::str::FromStr; + let options = sqlx::sqlite::SqliteConnectOptions::from_str(url) + .map_err(|e| format!("projection bus {url}: {e}"))? + .create_if_missing(true) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .busy_timeout(Duration::from_secs(10)); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(2) + .connect_with(options) + .await + .map_err(|e| format!("projection bus {url}: {e}"))?; + let bus = SqliteBus::new(pool); + bus.ensure_tables() + .await + .map_err(|e| format!("projection bus tables: {e}"))?; + Ok(Self { + publisher: BusPublisher::new(Arc::new(bus)), + }) + } } /// Lazily opened `Crawler` cells under one directory. @@ -88,6 +164,7 @@ impl CrawlerCells { let entry = Arc::new(CrawlerCell { sink: CellFactSink::new(cell.clone(), SERVICE_ID, SYSTEM_PRINCIPAL), cell, + draining: tokio::sync::Mutex::new(()), }); open.insert(principal.to_string(), entry.clone()); Ok(entry) @@ -119,6 +196,23 @@ impl CrawlerCells { out.dedup(); out } + + /// Drain every cell on disk to `bus` (startup recovery and the periodic + /// sweep). Returns rows published; per-cell errors are reported and + /// retried by the next sweep. + pub async fn drain_all(&self, bus: &ProjectionBus) -> usize { + let mut published = 0; + for principal in self.principals() { + match self.get(&principal) { + Ok(cell) => match cell.drain_to(bus).await { + Ok(n) => published += n, + Err(error) => eprintln!("mobpit: drain {principal}: {error}"), + }, + Err(error) => eprintln!("mobpit: open {principal}: {error}"), + } + } + published + } } fn percent_decode(stem: &str) -> Option { @@ -217,15 +311,22 @@ pub struct CrawlerFactSink { cells: Arc, state: Arc, board: Arc, + projection: Arc>, } impl CrawlerFactSink { /// Sink over `cells`, reporting into `state`, feeding `board`. - pub fn new(cells: Arc, state: Arc, board: Arc) -> Self { + pub fn new( + cells: Arc, + state: Arc, + board: Arc, + projection: Arc>, + ) -> Self { Self { cells, state, board, + projection, } } @@ -242,6 +343,16 @@ impl CrawlerFactSink { .get(principal) .map_err(|e| FactError::Retryable(format!("open cell: {e}")))?; let receipt = cell.sink.commit(fact).await?; + if let Some(bus) = self.projection.get().cloned() { + // Off the settlement path: the zone hears "saved" when the cell + // commits; the read model follows from the outbox. + let cell = cell.clone(); + tokio::spawn(async move { + if let Err(error) = cell.drain_to(&bus).await { + eprintln!("mobpit: projection drain (retried by the sweep): {error}"); + } + }); + } if fact.command() == RECORD_KILL { if let Ok(kill) = serde_json::from_value::(receipt.payload.clone()) { // Fire-and-forget: never awaits the leaderboard store. diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs index 7d5adc831..278e3287b 100644 --- a/examples/game/server/src/mobpit/world.rs +++ b/examples/game/server/src/mobpit/world.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::Duration; use axum::Router; use distributed_game::net::{GameServer, ServerConfig}; @@ -12,7 +13,7 @@ use distributed_game::RetryPolicy; use serde_json::{json, Value}; use super::board::Leaderboards; -use super::store::{CrawlerCells, CrawlerFactSink, SinkState}; +use super::store::{CrawlerCells, CrawlerFactSink, ProjectionBus, SinkState}; use super::zone::{MobPit, MobPitConfig}; use super::{routes, MobPitDemo}; use crate::common::{random_hex, Demo, Guests}; @@ -58,6 +59,7 @@ pub struct MobPitWorld { board: Arc, zone_pending: AtomicUsize, profiles: Arc>>, + projection: Arc>, } impl MobPitWorld { @@ -74,6 +76,7 @@ impl MobPitWorld { board, zone_pending: AtomicUsize::new(0), profiles: Arc::default(), + projection: Arc::default(), })) } @@ -105,7 +108,39 @@ impl MobPitWorld { /// The game's fact sink. pub fn fact_sink(&self) -> CrawlerFactSink { - CrawlerFactSink::new(self.cells.clone(), self.sink.clone(), self.board.clone()) + CrawlerFactSink::new( + self.cells.clone(), + self.sink.clone(), + self.board.clone(), + self.projection.clone(), + ) + } + + /// Publish the cells' Crawler domain events to the SQLite bus at `url` + /// (the read-model service consumes it): drain what is pending now, then + /// after every commit, and sweep every `sweep` for anything a crash or a + /// bus outage left behind. Call once, inside a Tokio runtime. + pub async fn attach_projection_bus(&self, url: &str, sweep: Duration) -> Result { + let bus = ProjectionBus::open(url).await?; + let published = self.cells.drain_all(&bus).await; + self.projection + .set(bus.clone()) + .map_err(|_| "projection bus already attached".to_string())?; + let cells = self.cells.clone(); + tokio::spawn(async move { + let mut every = tokio::time::interval(sweep); + every.tick().await; + loop { + every.tick().await; + cells.drain_all(&bus).await; + } + }); + Ok(published) + } + + /// The attached projection bus, if any. + pub fn projection_bus(&self) -> Option<&ProjectionBus> { + self.projection.get() } pub(crate) fn set_zone_pending(&self, n: usize) { From 5e3a58af23a017f15ae6b783efa9d96019f19f36 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Mon, 19 Oct 2026 18:33:27 -0500 Subject: [PATCH 217/484] feat(examples): read Mob Pit stats via generated @live GraphQL The SvelteKit demo now reads settled progress from mobpit-service: MyStats ($playerId bound by sessionClaim) and Leaderboard islands with @load @live, SSR through createDistributedSvelteKitServer, then live over graphql-transport-ws. Auth.js binds an ES256 API Bearer to the verified session subject. The UI runs under distributed build|dev (clients need the lifecycle); the zone profile/board pushes and the --dev leaderboard route are no longer used, and the zone server runs without --dev. Playwright covers live updates for two players and SSR. --- .github/workflows/integration-game-demos.yaml | 9 +- distributed_game/README.md | 9 ++ examples/game/README.md | 144 +++++++++++------ examples/game/run.sh | 73 +++++++-- examples/game/server/.gitignore | 3 + examples/game/server/Cargo.toml | 5 + examples/game/server/service/Cargo.toml | 8 + .../game/sveltekit/distributed.clients.json | 11 ++ examples/game/sveltekit/distributed.config.js | 40 ++++- examples/game/sveltekit/src/app.d.ts | 7 + examples/game/sveltekit/src/auth.ts | 19 ++- .../sveltekit/src/lib/pit/Leaderboard.graphql | 8 + .../sveltekit/src/lib/pit/Leaderboard.svelte | 20 +++ .../sveltekit/src/lib/pit/MyStats.graphql | 13 ++ .../src/lib/pit/MyStats.graphql.bindings.js | 7 + .../game/sveltekit/src/lib/pit/MyStats.svelte | 26 ++++ .../sveltekit/src/lib/server/api-token.ts | 61 ++++++++ .../sveltekit/src/lib/server/distributed.ts | 31 ++++ .../game/sveltekit/src/lib/server/game.ts | 26 ---- .../sveltekit/src/routes/+layout.server.ts | 14 +- .../game/sveltekit/src/routes/+layout.svelte | 54 +++++++ .../sveltekit/src/routes/pit/+page.server.ts | 5 +- .../sveltekit/src/routes/pit/+page.svelte | 21 +-- examples/game/sveltekit/svelte.config.js | 9 +- examples/game/sveltekit/tests/pit.test.mjs | 145 ++++++++++++++---- js/README.md | 5 +- 26 files changed, 626 insertions(+), 147 deletions(-) create mode 100644 examples/game/sveltekit/distributed.clients.json create mode 100644 examples/game/sveltekit/src/lib/pit/Leaderboard.graphql create mode 100644 examples/game/sveltekit/src/lib/pit/Leaderboard.svelte create mode 100644 examples/game/sveltekit/src/lib/pit/MyStats.graphql create mode 100644 examples/game/sveltekit/src/lib/pit/MyStats.graphql.bindings.js create mode 100644 examples/game/sveltekit/src/lib/pit/MyStats.svelte create mode 100644 examples/game/sveltekit/src/lib/server/api-token.ts create mode 100644 examples/game/sveltekit/src/lib/server/distributed.ts diff --git a/.github/workflows/integration-game-demos.yaml b/.github/workflows/integration-game-demos.yaml index 83d918ef2..a7569c0d6 100644 --- a/.github/workflows/integration-game-demos.yaml +++ b/.github/workflows/integration-game-demos.yaml @@ -2,9 +2,12 @@ name: Game demos smoke # Reusable workflow: referenced via `uses: ./.github/workflows/integration-game-demos.yaml`. # `examples/game` is outside the root workspace, so nothing else runs its tests: -# generated clients current (`gen --check`), demo server fmt/clippy/tests, client -# type-check, build and headless tests, and the SvelteKit demo end to end -# (Playwright against the production build and a real Mob Pit server). +# generated clients current (`gen --check`), demo server fmt/clippy/tests +# (incl. the mobpit_service projection test), client type-check, build and +# headless tests, and the SvelteKit demo end to end: `distributed build +# examples/game/server` (GraphQL client, svelte-check, vite build), then +# Playwright against the production build, a real Mob Pit server and the real +# mobpit-service read model (SQLite only; no external services). on: workflow_call: diff --git a/distributed_game/README.md b/distributed_game/README.md index fc9fee873..8f20ca5db 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -463,6 +463,15 @@ runnable: [`examples/game/sveltekit`](../examples/game/sveltekit) `status`, `zone`, `rttMs`, `predictionReady`, `error` and typed `latest(event)` / `events(event)`; it connects on mount and closes on destroy or navigation. +4. **Settled progress through the business side.** Game state stays in the + zone; what a player keeps belongs to a Distributed service. Mark the cell + command's event as a domain event (`#[event(.., domain)]` + + `repo.publish_events()`), drain the cell outbox onto a bus + (`AggregateCell::drain_outbox_with(BusPublisher::new(bus), ..)`), project + it with a modeled projector into a SQL read model and read that with + generated `@load @live` GraphQL (`clients` in the same Vite plugin, + session-bound variables via `sessionClaim`). The example does this with + `mobpit_service` and a SQLite bus. ```ts // src/routes/api/game/ticket/+server.ts diff --git a/examples/game/README.md b/examples/game/README.md index d19251ab0..8454a8223 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -14,7 +14,7 @@ guests and lets any page change the network simulation. | **Shooting Gallery** | `./run.sh gallery` | Lag compensation: hitscan shots resolved with `ctx.rewind().hit_test_shot` at the shooter's view time (`client_tick` + interpolation delay in the payload), `max_rewind` clamp, per-shot compensation on/off, predicted vs confirmed hits | | **The Freeze** | `./run.sh freeze` | World-version barrier (`WorldCoordinator::rollout`) across **two server processes** as an in-world "admin update": freeze → apply → resume with change notes, inputs dropped while frozen, Hard reload vs safe-room gating (`StalePolicy::SafeRoom`, `Zone::is_gate`) of old clients, aborted rollout (`freeze_ready` → `NotAcked`), facts/events stamped with the content version | | **Endless Grid** | `./run.sh grid` | Seeded procedural world (terrain/biomes/props generated bit-identically in Rust and TS, nothing static replicated), 32 m cells as zones, observer connections to the 8 neighbours, handoff across borders **and hosts** (2 processes, hash ring, Redirect + transfer tickets), hibernation to SQLite and restore | -| **Mob Pit · SvelteKit** | `./run.sh sveltekit` | The same Mob Pit server behind a SvelteKit app: Auth.js session sign-in, admission tickets minted from the session (`createGameTicketHandler`), the game client and WASM step generated by the Vite plugin (`games`), a runes HUD (`useGame`) next to a plain canvas loop, and a settled-kill read model (SSR, then live zone pushes). See [SvelteKit](#sveltekit) | +| **Mob Pit · SvelteKit** | `./run.sh sveltekit` | The same Mob Pit server behind a SvelteKit app: Auth.js session sign-in, admission tickets minted from the session (`createGameTicketHandler`), the game client and WASM step generated by the Vite plugin (`games`), a runes HUD (`useGame`) next to a plain canvas loop, and the settled kills as a business-side read model: Crawler domain events projected by `mobpit-service` into SQL and read through generated `@load @live` GraphQL (SSR, then live). See [SvelteKit](#sveltekit) | | **Boss Ripple** | `./run.sh ripple` | Zone hierarchy realm › city › borough › hood (`DottedTopology`), per-tier tick rates (2/5/10/30 Hz), boss defeats propagating up as tier-up events (each hop on another host), parent broadcasts reaching players through observer connections | `./run.sh smoke` runs every demo's smoke tests (and checks the generated @@ -214,11 +214,14 @@ hood to fight there. examples/game/run.sh sveltekit # → http://localhost:5573/ — sign in with any username ``` -`sveltekit/` is Mob Pit as a SvelteKit app. The script starts `game-demos -mobpit --dev` on `GAME_DEMOS_PORT` (default 2967 here; data in -`.data/mobpit-sveltekit`) with a fresh ticket secret and runs `vite dev` on -`SVELTEKIT_PORT` (default 5573) with the same secret. What each piece -replaces: +`sveltekit/` is Mob Pit as a SvelteKit app over two backends: the Mob Pit +zone server (gameplay) and `mobpit-service` (the business-side read model). +The script starts `game-demos mobpit` (no `--dev`) on `GAME_DEMOS_PORT` +(default 2967 here; data in `.data/mobpit-sveltekit`) with a fresh ticket secret and +`--projection-bus sqlite:…/bus.db`, then runs `distributed dev server/`: the +application lifecycle generates the `$distributed` GraphQL client, starts +`mobpit-service` on `MOBPIT_SERVICE_PORT` (default `GAME_DEMOS_PORT + 2`) +and `vite dev` on `SVELTEKIT_PORT` (default 5573). What each piece replaces: - **Sign-in and tickets.** `src/auth.ts` is Auth.js, the session mechanism of the framework's SvelteKit apps (`tests/e2e-ui`): with `OIDC_ISSUER` @@ -232,35 +235,56 @@ replaces: foreign zone gets 409, another origin 403, no session 401. The page's `load` uses `tickets.resolve(event)` for the same zone. There is no `/dev/ticket` call and no guest token. -- **Code generation.** `distributed.config.js` lists the Mob Pit surface for - the Vite plugin; `vite dev` / `vite build` run `game-manifest`, - `game-client` and `game-wasm` (watching `server/src` and `server/sim`, so - editing the zone or `pit_step` regenerates and reloads). The TypeScript in - `src/lib/generated/mobpit/` is checked in and verified by `npm run - check:games`; `wasm/` is a build output. No `run.sh gen` step. +- **Code generation.** `distributed.config.js` lists both surfaces. + `games`: the Mob Pit zone surface; the Vite plugin runs `game-manifest`, + `game-client` and `game-wasm` on start and on Rust changes (`server/src`, + `server/sim`; a failing Rust build is reported in the overlay and the dev + server keeps running), the TypeScript in `src/lib/generated/mobpit/` is + checked in and verified by `npm run check:games`, `wasm/` is a build + output. `clients` (from `distributed.clients.json`): the `mobpit` + application surface of `mobpit_service`; `distributed build|dev server/` + generates it from `src/lib/pit/*.graphql` into the lifecycle's generation + store (never checked in), which is why the UI runs under the lifecycle + instead of plain `vite` (`server/Cargo.toml` points + `[workspace.metadata.distributed.ui]` at `../sveltekit`). - **HUD.** `routes/pit/+page.svelte` calls `useGame(() => createMobpitClient({ url, ticket: gameTicketSource() }), { zone, events: EVENTS })` and renders `status`, `zone`, `rttMs`, `predictionReady`, - `error`, `latest('profile')`, `latest('board')`, `events('kill')` and - `events('saved')` as Svelte markup. `src/lib/pit/loop.ts` is the - canvas render and input loop (one input per tick via `InputPacer`), plain - TypeScript started from an `$effect`; Svelte never sees per-frame state. - **Auto-hunt** steers to the nearest mob (used by the headless test). -- **Settled read model.** The *Settled* panel shows your XP and kills from - durable Crawler cells and the XP board. The first render comes from the - page `load`, which reads the leaderboard projection server-side for the - session principal (`GET /dev/mobpit/leaderboard?member=`, a dev route); - afterwards the zone's `profile` (sent after each fact settles) and `board` - pushes update it live. Kills show as "saving" until their `saved` event. - The business side's GraphQL `@live` queries would need a Distributed - service with SQL read models projecting these facts, which Mob Pit does - not have; the zone's settled pushes are the existing live channel. - -`./run.sh smoke` runs `check:games`, `svelte-check`, `vite build` and -`tests/pit.test.mjs`: the production build (`node build`) against the real -server in headless Chromium — sign-in, ticket rejection paths, join, -keyboard movement, auto-hunt until a kill settles, the live and the -server-rendered read model, navigation away, no page errors. + `error`, `events('kill')` and `events('saved')` as Svelte markup. + `src/lib/pit/loop.ts` is the canvas render and input loop (one input per + tick via `InputPacer`), plain TypeScript started from an `$effect`; Svelte + never sees per-frame state. **Auto-hunt** steers to the nearest mob (used + by the headless test). Kills show as "saving" until their `saved` event. +- **Settled read model (business side).** The *Settled* panel is two + generated GraphQL islands, both `@load @live`: + `src/lib/pit/MyStats.graphql` (my `player_stats` row; `$playerId` is bound + by `MyStats.graphql.bindings.js` to `sessionClaim('user', 'id')`, so the + value is the verified session's id for SSR and in the browser, never a URL + or form value) and `src/lib/pit/Leaderboard.graphql` (top 5 by XP). The + root layout's `createDistributedSvelteKitServer` runs them during SSR, the + page hydrates without refetching, and the `graphql-transport-ws` + subscription pushes every later settlement — to every signed-in player. + The rows come from the cells (see *Mob Pit*, step 5): the zone's + `profile`/`board` pushes and the `--dev` leaderboard route are not used by + this app (they remain for the vanilla client pages). +- **API identity.** `mobpit-service` trusts no identity header + (`IdentityMode::OidcBearer`). Auth.js's `session` callback puts a Bearer + in `session.accessToken`: an ES256 JWT this server signs for the session's + verified `sub` (15 min, `src/lib/server/api-token.ts`; + `MOBPIT_API_SIGNING_JWK`), or, with OIDC and no signing key, the + provider's access token. `run.sh` and the smoke test generate a key pair per + run and give the service only the public JWKS (`MOBPIT_API_JWKS`). The + browser calls the service directly (`MOBPIT_PUBLIC_GRAPHQL_URL`, CORS for + `MOBPIT_UI_ORIGINS`, no cookies). + +`./run.sh smoke` runs `check:games`, then `distributed build server/` (the +GraphQL client, `svelte-check`, `vite build` with the game codegen and WASM) +and `tests/pit.test.mjs`: the production build (`node build`) against the +real zone server and `mobpit-service` in headless Chromium — sign-in, ticket +rejection paths, an unauthenticated GraphQL request refused, join, keyboard +movement, auto-hunt until a kill settles, the killer's stats and a second +signed-in player's leaderboard updating live without a reload, the +server-rendered numbers after a reload, navigation away, no page errors. ## Architecture @@ -315,7 +339,13 @@ What the TypeScript still restates, and why it stays: ``` examples/game/ run.sh one-command dev + smoke runner - server/ Rust crate `game_demos`, its own cargo workspace (with sim/) + server/ Rust crate `game_demos`, its own cargo workspace (with sim/, + crawler/, service/); also the `distributed build|dev` project + crawler/ crate `mobpit_crawler`: Crawler aggregate, RecordKill (XP rules), + `CrawlerState` domain event (shared by the zone and the service) + service/ crate `mobpit_service` (bin `mobpit-service`): player_stats read + model, modeled projector from the bus, GraphQL @live (Bearer only), + tests/projection.rs (cells → bus → table → live push, no mutations, 401) sim/ crate `game_sim`: the `#[predict]` steps (arena.rs movement + floor, mobpit.rs, ripple.rs inputs + steps, grid.rs world + walker step + `#[game_pure]` grid_cell / grid_sample); compiled natively for the @@ -325,7 +355,8 @@ examples/game/ src/common/ shared: Demo trait, run/spawn, dev routes, guests src/cluster.rs multi-host demos: --host-id/--peer, directory, ownership, snapshots src/arena/ Arena zone (`movement` = `game_sim::arena`) - src/mobpit/ Mob Pit zone, Crawler cell aggregate, fact sink, leaderboards, dev routes + src/mobpit/ Mob Pit zone, Crawler cells, fact sink + projection-bus drain, + leaderboards, dev routes src/gallery/ Shooting Gallery zone (targets, rewind hit tests) src/freeze/ The Freeze zone, content packs, two-host world + admin routes src/grid/ Endless Grid zone (`world` = `game_sim::grid`), dev map routes @@ -334,14 +365,19 @@ examples/game/ mobpit_smoke.rs (facts, slow storage, kill -9 recovery, boards), gallery_smoke.rs, freeze_smoke.rs (binary content packs), grid_smoke.rs, ripple_smoke.rs (+ support/ for two in-process hosts) - sveltekit/ SvelteKit app over the Mob Pit server (see SvelteKit above) - distributed.config.js game surface for the Vite plugin (`games`) + sveltekit/ SvelteKit app over the Mob Pit server + mobpit-service (see SvelteKit above) + distributed.config.js game surface (`games`) + GraphQL client (`clients`) for the Vite plugin + distributed.clients.json the `$distributed` client of `mobpit_service` (lifecycle-generated) src/auth.ts Auth.js (OIDC, or dev username sign-in with GAME_DEV_AUTH=1) - src/lib/server/game.ts createGameTicketHandler + settled read model (server-side) + + the session-bound API Bearer + src/lib/server/ game.ts (createGameTicketHandler), distributed.ts (SSR loader), + api-token.ts (ES256 Bearer for the session subject) src/lib/generated/mobpit generated by the Vite plugin (TypeScript checked in, wasm/ ignored) - src/lib/pit/loop.ts canvas render + input loop (outside Svelte) - src/routes/pit/ load (zone, read model) + page (useGame HUD, settled panel) - tests/pit.test.mjs headless Playwright against `node build` + game-demos + src/lib/pit/ loop.ts (canvas render + input loop, outside Svelte); + MyStats / Leaderboard .graphql islands (@load @live) + components + src/routes/+layout.* session + SSR seed, provideDistributed + src/routes/pit/ load (zone) + page (useGame HUD, settled panel) + tests/pit.test.mjs headless Playwright against `node build` + game-demos + mobpit-service client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) index.html, /index.html src/generated// generated by `run.sh gen` (do not edit): schema/input/events/client.ts, @@ -406,6 +442,17 @@ after dying. Level `n` starts at `40·(n−1)²` XP. `waitedMs`) and `profile`; the popup turns from "saving…" to "+XP saved ✓". The sink also hands the kill to the leaderboard (fire-and-forget). +5. The read model (`crawler/`, `service/`): `crawler.mob_killed` is a + **domain event** — the same transaction writes the post-kill + `CrawlerState` (principal, name, XP, kills, level) to the cell's outbox + (`repo.publish_events()`). With `--projection-bus sqlite:` the sink + drains that outbox onto a `SqliteBus` after the commit (and a sweep drains + every cell at startup and every 2 s, so a crash between commit and drain + or a bus outage only delays it). `mobpit-service` consumes the bus with a + modeled projector (`projection!` → `upsert_player_stats`), checkpointed + and deduplicated in its own SQLite database, and serves `player_stats` + over GraphQL with `@live`. The service has no commands: nothing on that + side can name a player or an amount. The read path: on join the zone asks a background task to load the player's cell and sends `profile` (`source: "cell"`) a few ticks later. @@ -543,11 +590,12 @@ over the hosts, `cluster_server`, optional dev routes), uses - `/dev/netsim` changes the simulation for every connection on the server. - The ticket secret is random per process unless `DISTRIBUTED_GAME_SECRET` is set (needed to point `game-bots` at a running demo). -- The SvelteKit demo does not use `/dev/ticket`: its tickets are minted by - the SvelteKit server from the Auth.js session. It is still dev only: the - game server runs with `--dev` (the page's first render reads - `/dev/mobpit/leaderboard`, and `/dev/*` stays reachable on 127.0.0.1), - and `GAME_DEV_AUTH=1` lets anyone sign in with any username. A real - deployment sets the OIDC variables, leaves `GAME_DEV_AUTH` unset, runs - the zone servers without `--dev` and serves the read model from its own - backend. +- The SvelteKit demo uses no `/dev/*` route: its tickets are minted by the + SvelteKit server from the Auth.js session, and its read model is + `mobpit-service`, so `run.sh sveltekit` and the smoke test start the zone + server without `--dev`. It is still dev only: `GAME_DEV_AUTH=1` lets + anyone sign in with any username, the SvelteKit server signs the API + Bearer with a per-run key, and the bus is a SQLite file shared by two + local processes. A real deployment sets the OIDC variables, leaves + `GAME_DEV_AUTH` unset, and uses a networked bus (NATS, Postgres…) and + database for `mobpit-service`. diff --git a/examples/game/run.sh b/examples/game/run.sh index dc2b30126..8c1ca8858 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -16,7 +16,9 @@ # verifies the TypeScript (and still builds WASM) # ./run.sh sveltekit Mob Pit in SvelteKit (sveltekit/): dev sign-in, # session-minted tickets, game client generated by -# the Vite plugin, Svelte HUD + settled read model +# the Vite plugin, Svelte HUD, and the settled +# read model from mobpit-service over GraphQL @live +# (`distributed dev server/` runs the service + UI) # ./run.sh smoke every demo's smoke tests (Rust bots + headless JS, # generated clients checked, SvelteKit headless) # ./run.sh list demos this script knows @@ -26,7 +28,8 @@ # server NetSim; the HUD sliders change it live), MOBPIT_DATA_DIR (Mob Pit / # Leaderboard cells, default examples/game/.data/mobpit), REDIS_URL (Redis # leaderboard instead of in-memory), SVELTEKIT_PORT (SvelteKit demo, default -# 5573; its game server uses GAME_DEMOS_PORT, default 2967 there). +# 5573; its game server uses GAME_DEMOS_PORT, default 2967 there, and its +# read-model service MOBPIT_SERVICE_PORT, default GAME_DEMOS_PORT + 2). set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -35,6 +38,7 @@ SERVER="$HERE/server" CLIENT="$HERE/client" SVELTEKIT="$HERE/sveltekit" BIN="$SERVER/target/debug/game-demos" +SERVICE_BIN="$SERVER/target/debug/mobpit-service" DEMOS=(arena mobpit leaderboard gallery freeze grid ripple) export MOBPIT_DATA_DIR="${MOBPIT_DATA_DIR:-$HERE/.data/mobpit}" # Multi-host demos: `game-demos --host-id A|B --peer …`. @@ -211,31 +215,61 @@ run_cluster() { GAME_DEMOS_SERVER="http://127.0.0.1:$port_a" GAME_DEMOS_CLIENT_PORT="$client_port" npx vite } -# The SvelteKit demo: Mob Pit server + `vite dev`. The Vite plugin generates -# src/lib/generated/mobpit (and its WASM) on start and on Rust changes. +# api_keys: an ES256 key pair for the SvelteKit server's read-model Bearer +# tokens — sets API_SIGNING_JWK (private, for the UI) and API_JWKS (public, +# for mobpit-service). Fresh per run; nothing is written to disk. +api_keys() { + local keys + keys="$(node -e ' + const { generateKeyPairSync, randomBytes } = require("node:crypto"); + const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" }); + const kid = randomBytes(8).toString("hex"); + const priv = { ...privateKey.export({ format: "jwk" }), kid, alg: "ES256" }; + const pub = { ...publicKey.export({ format: "jwk" }), kid, alg: "ES256", use: "sig" }; + process.stdout.write(JSON.stringify(priv) + "\n" + JSON.stringify({ keys: [pub] })); + ')" + API_SIGNING_JWK="$(sed -n 1p <<<"$keys")" + API_JWKS="$(sed -n 2p <<<"$keys")" +} + +# The SvelteKit demo: the Mob Pit zone server (publishing Crawler domain +# events to a SQLite bus), then `distributed dev server/`, which generates +# the `$distributed` GraphQL client, runs mobpit-service (the player_stats +# read model, GraphQL @live) and `vite dev` (the Vite plugin also generates +# src/lib/generated/mobpit and its WASM on start and on Rust changes). run_sveltekit() { local port="${GAME_DEMOS_PORT:-2967}" local ui_port="${SVELTEKIT_PORT:-5573}" + local service_port="${MOBPIT_SERVICE_PORT:-$((port + 2))}" + local data="${MOBPIT_DATA_DIR%/}-sveltekit" ensure_sdk ensure_sveltekit ensure_server ensure_cli + mkdir -p "$data" local log_file secret log_file="$(mktemp -t game-demos-sveltekit.XXXXXX)" secret="${DISTRIBUTED_GAME_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" - DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --dev --port "$port" \ - --data-dir "${MOBPIT_DATA_DIR%/}-sveltekit" >"$log_file" 2>&1 & + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --port "$port" \ + --data-dir "$data" --projection-bus "sqlite:$data/bus.db" >"$log_file" 2>&1 & local server_pid=$! trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; rm -f "$log_file"' EXIT INT TERM wait_listening "$log_file" "$server_pid" "game-demos mobpit" + api_keys echo - log "open http://localhost:$ui_port/ (sign in with any username; Mob Pit server :$port, dev routes ON — local only)" + log "open http://localhost:$ui_port/ (sign in with any username; Mob Pit server :$port, read model :$service_port; dev sign-in — local only)" echo - cd "$SVELTEKIT" - PORT="$ui_port" GAME_DEV_AUTH=1 \ - AUTH_SECRET="${AUTH_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" \ + # mobpit-service (the lifecycle's runtime) and the UI share these. + BIND="127.0.0.1:$service_port" UI_PORT="$ui_port" \ + DATABASE_URL="sqlite:$data/service.db?mode=rwc" MOBPIT_BUS_URL="sqlite:$data/bus.db" \ + MOBPIT_API_ISSUER=mobpit-sveltekit MOBPIT_API_AUDIENCE=mobpit-service \ + MOBPIT_API_JWKS="$API_JWKS" MOBPIT_API_SIGNING_JWK="$API_SIGNING_JWK" \ + MOBPIT_PROTOCOL_KEY="$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')" \ + MOBPIT_UI_ORIGINS="http://localhost:$ui_port,http://127.0.0.1:$ui_port" \ + MOBPIT_GRAPHQL_URL="http://127.0.0.1:$service_port/graphql" \ + GAME_DEV_AUTH=1 AUTH_SECRET="${AUTH_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" \ GAME_TICKET_SECRET="$secret" GAME_ZONES_URL="ws://127.0.0.1:$port" \ - GAME_SERVER_HTTP="http://127.0.0.1:$port" npx vite dev + "$CLI" dev "$SERVER" } smoke() { @@ -247,14 +281,19 @@ smoke() { cargo fmt --manifest-path "$SERVER/Cargo.toml" --check -p game_demos -p game_sim cargo clippy --quiet --manifest-path "$SERVER/Cargo.toml" --workspace --all-targets -- -D warnings cargo test --quiet --manifest-path "$SERVER/Cargo.toml" --workspace - cargo build --quiet --manifest-path "$SERVER/Cargo.toml" + cargo build --quiet --manifest-path "$SERVER/Cargo.toml" --workspace --bins log "client: type-check, build, tests (WASM steps + pure functions exact match, headless SDK)" (cd "$CLIENT" && npm run --silent check && npx vite build --logLevel warn && GAME_DEMOS_BIN="$BIN" npm test --silent) - log "sveltekit: generated game client current, svelte-check, build (plugin codegen + WASM), headless Playwright" + log "sveltekit: generated game client current; distributed build (GraphQL client, svelte-check, vite build + game codegen/WASM); headless Playwright" ensure_sveltekit - (cd "$SVELTEKIT" && npm run --silent check:games && npm run --silent check && - npx vite build --logLevel warn && npx playwright install chromium >/dev/null && - GAME_DEMOS_BIN="$BIN" npm test --silent) + ensure_cli + (cd "$SVELTEKIT" && npm run --silent check:games) + local build_log + build_log="$(mktemp -t game-demos-build.XXXXXX)" + "$CLI" build "$SERVER" >"$build_log" 2>&1 || { cat "$build_log"; rm -f "$build_log"; exit 1; } + rm -f "$build_log" + (cd "$SVELTEKIT" && npx playwright install chromium >/dev/null && + GAME_DEMOS_BIN="$BIN" MOBPIT_SERVICE_BIN="$SERVICE_BIN" npm test --silent) log "smoke OK" } @@ -263,7 +302,7 @@ case "${1:-}" in gen) gen "${2:-}" ;; sveltekit) run_sveltekit ;; list) printf '%s\n' "${DEMOS[@]}" sveltekit ;; - "" | -h | --help | help) sed -n '2,29p' "$0" ;; + "" | -h | --help | help) sed -n '2,32p' "$0" ;; *) if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then run_cluster "$1" diff --git a/examples/game/server/.gitignore b/examples/game/server/.gitignore index b83d22266..bd82bd223 100644 --- a/examples/game/server/.gitignore +++ b/examples/game/server/.gitignore @@ -1 +1,4 @@ /target/ +# `distributed build|dev` lifecycle state (generated GraphQL clients, logs) +/.distributed/ +/.distributed-dev.* diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index cbe40eb72..06ecc2518 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -5,6 +5,11 @@ members = [".", "sim", "crawler", "service"] resolver = "2" +# `distributed build|dev examples/game/server` owns the SvelteKit demo's +# GraphQL client generation (`sveltekit/distributed.clients.json`). +[workspace.metadata.distributed.ui] +path = "../sveltekit" + [package] name = "game_demos" version = "0.1.0" diff --git a/examples/game/server/service/Cargo.toml b/examples/game/server/service/Cargo.toml index 33022fd4a..e684ea58d 100644 --- a/examples/game/server/service/Cargo.toml +++ b/examples/game/server/service/Cargo.toml @@ -32,3 +32,11 @@ game_demos = { path = ".." } distributed_game = { path = "../../../../distributed_game", features = ["cell"] } async-graphql = "7" futures-util = { version = "0.3", default-features = false, features = ["std"] } + +# `distributed build|dev examples/game/server`: this crate is the +# application (logical manifest + GraphQL client surface) and its runtime. +[package.metadata.distributed.application] +entrypoint = "application_manifest" + +[package.metadata.distributed.runtime] +binary = "mobpit-service" diff --git a/examples/game/sveltekit/distributed.clients.json b/examples/game/sveltekit/distributed.clients.json new file mode 100644 index 000000000..4bec86250 --- /dev/null +++ b/examples/game/sveltekit/distributed.clients.json @@ -0,0 +1,11 @@ +{ + "schema_version": 1, + "clients": [ + { + "module": "$distributed", + "surface": "mobpit", + "documents": ["src/lib/pit/*.graphql"], + "output": "src/lib/generated/distributed" + } + ] +} diff --git a/examples/game/sveltekit/distributed.config.js b/examples/game/sveltekit/distributed.config.js index bc4fa126e..e7be09289 100644 --- a/examples/game/sveltekit/distributed.config.js +++ b/examples/game/sveltekit/distributed.config.js @@ -1,5 +1,12 @@ -// Game surfaces generated by the Distributed Vite plugin (dev start, Rust -// changes, build) and checked in CI by `npm run check:games`. +// @ts-nocheck — config script read by Node (Vite plugin, lifecycle, CI). +// +// - `clients`: the business side. `distributed.clients.json` declares the +// `$distributed` GraphQL client of `mobpit_service` (the player_stats read +// model); `distributed build|dev ../server` generates it (lifecycle-owned, +// never checked in). +// - `games`: the Mob Pit zone surface, generated by the Vite plugin itself +// (dev start, Rust changes, build) and checked in CI by `npm run check:games`. +import { readFileSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -7,12 +14,39 @@ const app = dirname(fileURLToPath(import.meta.url)); const repo = resolve(app, '../../..'); const server = resolve(app, '../server'); +const inventory = JSON.parse(readFileSync(resolve(app, 'distributed.clients.json'), 'utf8')); + +/** GraphQL clients from `distributed.clients.json` + how to export their surface. */ +export const distributedClients = Object.freeze( + inventory.clients.map((client) => + Object.freeze({ + module: client.module, + manifest: { + args: [ + 'client-manifest', + '--manifest-path', + resolve(server, 'Cargo.toml'), + '--package', + 'mobpit_service', + '--distributed-path', + repo + ] + }, + surface: client.surface, + documents: client.documents, + out: client.output + }) + ) +); + /** @type {import('@hops-ops/distributed/sveltekit/vite').DistributedSvelteKitViteOptions} */ export const distributedViteOptions = { cwd: app, - // The CLI from this checkout (an installed `distributed` works the same). + // The CLI from this checkout (an installed `distributed` works the same; + // under `distributed build|dev` the lifecycle's own executable is used). command: 'cargo', commandArgs: ['run', '--quiet', '--manifest-path', resolve(repo, 'Cargo.toml'), '-p', 'distributed_cli', '--bin', 'distributed', '--'], + clients: distributedClients, games: [ { manifest: { diff --git a/examples/game/sveltekit/src/app.d.ts b/examples/game/sveltekit/src/app.d.ts index be79b78b1..9464f5ffb 100644 --- a/examples/game/sveltekit/src/app.d.ts +++ b/examples/game/sveltekit/src/app.d.ts @@ -3,4 +3,11 @@ declare global { namespace App {} } +declare module '@auth/sveltekit' { + interface Session { + /** Bearer for `mobpit-service`, bound to the verified session subject. */ + accessToken?: string; + } +} + export {}; diff --git a/examples/game/sveltekit/src/auth.ts b/examples/game/sveltekit/src/auth.ts index a0b5ff9a3..373a82287 100644 --- a/examples/game/sveltekit/src/auth.ts +++ b/examples/game/sveltekit/src/auth.ts @@ -4,11 +4,14 @@ * encrypted, HttpOnly cookie. Real deployments configure the OIDC provider * (`OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`); local dev and the * smoke test enable a **dev-only** username sign-in with `GAME_DEV_AUTH=1`. - * Either way the game ticket route only ever reads `session.user.id`. + * Either way the game ticket route only ever reads `session.user.id`, and + * `session.accessToken` (the read-model service's Bearer) is bound to the + * same verified subject. */ import { SvelteKitAuth, type SvelteKitAuthConfig } from '@auth/sveltekit'; import Credentials from '@auth/sveltekit/providers/credentials'; import { env } from '$env/dynamic/private'; +import { mintApiToken } from '$lib/server/api-token'; const USERNAME = /^[a-z][a-z0-9_-]{2,15}$/; @@ -46,10 +49,20 @@ export const { handle, signIn, signOut } = SvelteKitAuth(async (): Promise + import { Leaderboard } from '$distributed'; + + let { me }: { me: string } = $props(); + + // Island: promoted to the page's `@load` (SSR), then live. + const board = Leaderboard.use(); + const rows = $derived($board.complete ? $board.data.player_stats : []); + + +
      + {#each rows as row (row.player_id)} +
    1. {row.name} — {row.xp} XP
    2. + {/each} +
    + + diff --git a/examples/game/sveltekit/src/lib/pit/MyStats.graphql b/examples/game/sveltekit/src/lib/pit/MyStats.graphql new file mode 100644 index 000000000..a42bd5e39 --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/MyStats.graphql @@ -0,0 +1,13 @@ +# "My stats": my row of the player_stats read model (mobpit-service). +# `$playerId` is bound to the verified session's user id +# (MyStats.graphql.bindings.js, `sessionClaim`); it is never a URL or form +# value. SSR seeds it, `@live` keeps it current as kills settle. +query MyStats($playerId: String!) @load @live { + player_stats(where: { player_id: { _eq: $playerId } }, limit: 1) { + player_id + name + xp + kills + level + } +} diff --git a/examples/game/sveltekit/src/lib/pit/MyStats.graphql.bindings.js b/examples/game/sveltekit/src/lib/pit/MyStats.graphql.bindings.js new file mode 100644 index 000000000..2bb6e9920 --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/MyStats.graphql.bindings.js @@ -0,0 +1,7 @@ +import { defineGraphqlIslandBindings, sessionClaim } from '@hops-ops/distributed/sveltekit'; + +// The principal comes from the session only (`session.user.id`, the Auth.js +// verified subject) — the same id the zone ticket and the read model use. +export default defineGraphqlIslandBindings({ + playerId: sessionClaim('user', 'id') +}); diff --git a/examples/game/sveltekit/src/lib/pit/MyStats.svelte b/examples/game/sveltekit/src/lib/pit/MyStats.svelte new file mode 100644 index 000000000..4e15d4d19 --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/MyStats.svelte @@ -0,0 +1,26 @@ + + +
    + XP {mine?.xp ?? 0} · kills {mine?.kills ?? 0} · + level {mine?.level ?? 1} +
    diff --git a/examples/game/sveltekit/src/lib/server/api-token.ts b/examples/game/sveltekit/src/lib/server/api-token.ts new file mode 100644 index 000000000..151c8fb07 --- /dev/null +++ b/examples/game/sveltekit/src/lib/server/api-token.ts @@ -0,0 +1,61 @@ +/** + * Bearer tokens for `mobpit-service` (GraphQL `@live` read model), minted + * by this server for the **verified session's** subject. The service + * verifies them (ES256, static JWKS of the public key) and maps `sub` to + * `x-user-id`; it trusts no identity header. With a real OIDC provider and + * no signing key, the provider's access token is used instead (see + * `auth.ts`). + * + * `MOBPIT_API_SIGNING_JWK` is the private EC P-256 JWK (`run.sh` and the + * smoke test generate one per run and hand the public half to the service). + */ +import { env } from '$env/dynamic/private'; + +export const API_ISSUER_DEFAULT = 'mobpit-sveltekit'; +export const API_AUDIENCE_DEFAULT = 'mobpit-service'; +/** Lifetime of a minted token; every session read mints a fresh one. */ +const TTL_SECONDS = 15 * 60; + +let cached: { jwk: string; key: Promise; kid: string | undefined } | undefined; + +function signingKey(): { key: Promise; kid: string | undefined } | undefined { + const raw = env.MOBPIT_API_SIGNING_JWK; + if (raw === undefined || raw.trim() === '') return undefined; + if (cached?.jwk !== raw) { + const jwk = JSON.parse(raw) as JsonWebKey & { kid?: string }; + cached = { + jwk: raw, + kid: jwk.kid, + key: crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']) + }; + } + return cached; +} + +const b64url = (bytes: Uint8Array | string) => + Buffer.from(typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes).toString('base64url'); + +/** A token for `subject`, or undefined when this server has no signing key. */ +export async function mintApiToken(subject: string): Promise { + const signer = signingKey(); + if (signer === undefined || subject.length === 0) return undefined; + const now = Math.floor(Date.now() / 1000); + const header = b64url(JSON.stringify({ alg: 'ES256', typ: 'JWT', ...(signer.kid ? { kid: signer.kid } : {}) })); + const claims = b64url( + JSON.stringify({ + iss: env.MOBPIT_API_ISSUER ?? API_ISSUER_DEFAULT, + aud: env.MOBPIT_API_AUDIENCE ?? API_AUDIENCE_DEFAULT, + sub: subject, + roles: ['user'], + iat: now, + exp: now + TTL_SECONDS + }) + ); + // WebCrypto ECDSA signatures are raw r‖s, exactly JWS ES256. + const signature = await crypto.subtle.sign( + { name: 'ECDSA', hash: 'SHA-256' }, + await signer.key, + new TextEncoder().encode(`${header}.${claims}`) + ); + return `${header}.${claims}.${b64url(new Uint8Array(signature))}`; +} diff --git a/examples/game/sveltekit/src/lib/server/distributed.ts b/examples/game/sveltekit/src/lib/server/distributed.ts new file mode 100644 index 000000000..a5c77d7a2 --- /dev/null +++ b/examples/game/sveltekit/src/lib/server/distributed.ts @@ -0,0 +1,31 @@ +import { env } from '$env/dynamic/private'; +import { createDistributedSvelteKitServer, type SveltekitServerLoadEventLike } from '@hops-ops/distributed/sveltekit'; +import { DISTRIBUTED_BOUNDARY_OPERATIONS } from '$distributed'; + +type LoadEvent = SveltekitServerLoadEventLike; +type Session = NonNullable>>; + +/** `mobpit-service` GraphQL endpoint as this server reaches it. */ +export function graphqlUrl(): string { + if (env.MOBPIT_GRAPHQL_URL) return env.MOBPIT_GRAPHQL_URL; + // `distributed dev` hands the UI its API origin. + if (env.DISTRIBUTED_API_ORIGIN) return `${env.DISTRIBUTED_API_ORIGIN.replace(/\/$/, '')}/graphql`; + return 'http://127.0.0.1:8791/graphql'; +} + +/** The same endpoint as the browser reaches it (HTTP + `/graphql/ws` for `@live`). */ +export function publicGraphqlUrl(): string { + return env.MOBPIT_PUBLIC_GRAPHQL_URL || graphqlUrl(); +} + +/** + * One root loader for every generated `@load` operation (SSR). The Bearer + * token comes from the verified session (`session.accessToken`, see + * `auth.ts`); session-bound variables (`sessionClaim`) read the same session. + */ +export const distributed = createDistributedSvelteKitServer({ + boundaries: DISTRIBUTED_BOUNDARY_OPERATIONS, + getSession: (event) => event.locals.auth(), + getRole: () => 'user', + getUrl: graphqlUrl +}); diff --git a/examples/game/sveltekit/src/lib/server/game.ts b/examples/game/sveltekit/src/lib/server/game.ts index 2eef8926e..d8ec1c7dd 100644 --- a/examples/game/sveltekit/src/lib/server/game.ts +++ b/examples/game/sveltekit/src/lib/server/game.ts @@ -9,29 +9,3 @@ export const tickets = createGameTicketHandler({ // One shared pit; a real game picks the zone the player is in or owns. zone: () => env.PIT_ZONE ?? 'pit-1' }); - -export type BoardRow = { rank: number; member: string; name: string; score: number }; -export type SettledFacts = { - board: { kills: BoardRow[]; xp: BoardRow[] }; - me: { kills: { score: number | null }; xp: { score: number | null } } | null; -}; - -/** - * Read model of settled kills for the first render: the Mob Pit - * leaderboard, a projection of the durable Crawler cells (dev HTTP route of - * the game server, read server-side with the session's principal). Live - * updates then arrive as the zone's `profile` and `board` events. - */ -export async function settledFacts(principal: string): Promise { - const base = env.GAME_SERVER_HTTP ?? 'http://127.0.0.1:2967'; - try { - const response = await fetch(`${base}/dev/mobpit/leaderboard?member=${encodeURIComponent(principal)}`, { - signal: AbortSignal.timeout(2_000) - }); - if (!response.ok) return null; - const { snapshot, me } = (await response.json()) as { snapshot: SettledFacts['board']; me: SettledFacts['me'] }; - return { board: { kills: snapshot.kills, xp: snapshot.xp }, me }; - } catch { - return null; - } -} diff --git a/examples/game/sveltekit/src/routes/+layout.server.ts b/examples/game/sveltekit/src/routes/+layout.server.ts index 345aa9c46..9bd8070fa 100644 --- a/examples/game/sveltekit/src/routes/+layout.server.ts +++ b/examples/game/sveltekit/src/routes/+layout.server.ts @@ -1 +1,13 @@ -export const load = async ({ locals }) => ({ session: await locals.auth() }); +import { distributed, publicGraphqlUrl } from '$lib/server/distributed'; + +/** + * Session + the SSR seed of every generated `@load` query on the route + * (`$distributed`). Signed-out visitors run no GraphQL. + */ +export const load = async (event) => { + const session = await event.locals.auth(); + if (!session?.user) { + return { session: null, accessToken: null, engineRole: null, gqlError: null, graphqlUrl: null }; + } + return { ...(await distributed.load(event)), graphqlUrl: publicGraphqlUrl() }; +}; diff --git a/examples/game/sveltekit/src/routes/+layout.svelte b/examples/game/sveltekit/src/routes/+layout.svelte index 0f779f229..8b2f13c33 100644 --- a/examples/game/sveltekit/src/routes/+layout.svelte +++ b/examples/game/sveltekit/src/routes/+layout.svelte @@ -1,5 +1,57 @@
    @@ -9,6 +61,7 @@
    {/if}
    +{#if data.gqlError}

    {data.gqlError}

    {/if} {@render children()} diff --git a/examples/game/sveltekit/src/routes/pit/+page.server.ts b/examples/game/sveltekit/src/routes/pit/+page.server.ts index 45e3b75f2..5d7188d63 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.server.ts +++ b/examples/game/sveltekit/src/routes/pit/+page.server.ts @@ -1,6 +1,6 @@ import { redirect } from '@sveltejs/kit'; import { env } from '$env/dynamic/private'; -import { settledFacts, tickets } from '$lib/server/game'; +import { tickets } from '$lib/server/game'; export const load = async (event) => { const joined = await tickets.resolve(event); @@ -8,7 +8,6 @@ export const load = async (event) => { return { zone: joined.zone, zonesUrl: env.GAME_ZONES_URL ?? 'ws://127.0.0.1:2967', - principal: joined.principal, - settled: await settledFacts(joined.principal) + principal: joined.principal }; }; diff --git a/examples/game/sveltekit/src/routes/pit/+page.svelte b/examples/game/sveltekit/src/routes/pit/+page.svelte index fd8ea961f..486748e57 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.svelte +++ b/examples/game/sveltekit/src/routes/pit/+page.svelte @@ -1,6 +1,8 @@ -
      - {#each rows as row (row.player_id)} -
    1. {row.name} — {row.xp} XP
    2. +
        + {#each rows as row (row.member)} +
      1. {nameOf.get(row.member) ?? row.member} — {row.score} XP
      2. {/each}
      +{#if $board.error}

      {$board.error}

      {/if} diff --git a/examples/game/sveltekit/src/routes/pit/+page.server.ts b/examples/game/sveltekit/src/routes/pit/+page.server.ts index 5d7188d63..e987cd5fb 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.server.ts +++ b/examples/game/sveltekit/src/routes/pit/+page.server.ts @@ -1,13 +1,30 @@ import { redirect } from '@sveltejs/kit'; import { env } from '$env/dynamic/private'; +import { loadDistributedLeaderboard } from '@hops-ops/distributed/sveltekit'; +import { XpLeaderboardLeaderboard, type XpLeaderboardData } from '$distributed'; import { tickets } from '$lib/server/game'; +import { graphqlUrl } from '$lib/server/distributed'; export const load = async (event) => { const joined = await tickets.resolve(event); if (joined === undefined) redirect(303, '/'); + // The XP board is server-ranked (Redis), not a replica query: load it + // here so the first HTML has it; the component then follows `@live`. + const session = await event.locals.auth(); + let board: XpLeaderboardData | undefined; + try { + board = await loadDistributedLeaderboard(XpLeaderboardLeaderboard, { first: 5 }, { + url: graphqlUrl(), + auth: { accessToken: session?.accessToken ?? null }, + fetch: event.fetch + }); + } catch (error) { + console.error(`leaderboard SSR: ${error}`); + } return { zone: joined.zone, zonesUrl: env.GAME_ZONES_URL ?? 'ws://127.0.0.1:2967', - principal: joined.principal + principal: joined.principal, + board }; }; diff --git a/examples/game/sveltekit/src/routes/pit/+page.svelte b/examples/game/sveltekit/src/routes/pit/+page.svelte index 486748e57..f3d8fde83 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.svelte +++ b/examples/game/sveltekit/src/routes/pit/+page.svelte @@ -56,7 +56,7 @@ (projected from the Crawler cells' domain events): SSR, then @live. -->
      saving {unsaved}
      - + {#each saved.items.slice(0, 3) as s (s.key)}
      +{s.xp} XP saved ✓ {s.waitedMs} ms
      {/each} diff --git a/examples/game/sveltekit/tests/pit.test.mjs b/examples/game/sveltekit/tests/pit.test.mjs index 8bda959fa..14c0db5ce 100644 --- a/examples/game/sveltekit/tests/pit.test.mjs +++ b/examples/game/sveltekit/tests/pit.test.mjs @@ -5,9 +5,12 @@ * auto-hunt kills a mob → the celld Crawler cell commits it, its domain event * goes through the cell outbox and celld's Queue to the zone server's relay, * onto the bus, and is projected into `player_stats` → the `@live` GraphQL queries - * (MyStats, bound to the session; Leaderboard) update without a reload, for - * the killer and for a second signed-in player → the SSR HTML after a reload - * has the settled numbers → no page errors. + * (MyStats, bound to the session; the leaderboard's names) update without a + * reload; the zone server's Redis XP board reaches the page through + * mobpit-service's GraphQL board roots (`xpLeaderboard`, SSR-seeded, `@live` + * from the board change notices on the bus) for the killer and for a second + * signed-in player → the SSR HTML after a reload has the settled numbers → + * no page errors. Needs REDIS_URL. * * Ports: GAME_DEMOS_PORT (default 2967), SVELTEKIT_PORT (default 5573), * MOBPIT_SERVICE_PORT (default GAME_DEMOS_PORT + 2). Needs the lifecycle @@ -74,6 +77,11 @@ function start(command, args, options, ready) { } test('sign in, join, move, kill, live read model updates for two players', { timeout: 600_000 }, async () => { + // The leaderboard is the Redis board the zone server writes and + // mobpit-service serves through its GraphQL board roots. + const redisUrl = process.env.REDIS_URL; + assert.ok(redisUrl, 'REDIS_URL is required: the SvelteKit leaderboard is the Redis board (docker compose up -d redis)'); + const redisPrefix = `mobpit-sveltekit-${randomBytes(6).toString('hex')}`; const secret = randomBytes(32).toString('hex'); const dataDir = mkdtempSync(join(tmpdir(), 'mobpit-sveltekit-')); const busUrl = `sqlite:${join(dataDir, 'bus.db')}`; @@ -82,7 +90,7 @@ test('sign in, join, move, kill, live read model updates for two players', { tim // The Crawler cells run on celld; its outbox Queue relays the domain // events to the game server, which publishes them onto the bus. const celld = await startCelld({ relayPort: GAME_PORT }); - const gameEnv = { ...process.env, ...celld.env, DISTRIBUTED_GAME_SECRET: secret }; + const gameEnv = { ...process.env, ...celld.env, DISTRIBUTED_GAME_SECRET: secret, REDIS_URL: redisUrl, MOBPIT_REDIS_PREFIX: redisPrefix }; const gameArgs = ['mobpit', '--port', String(GAME_PORT), '--data-dir', join(dataDir, 'local'), '--projection-bus', busUrl]; const game = bin ? start(bin, gameArgs, { env: gameEnv }, /LISTENING/) @@ -92,6 +100,8 @@ test('sign in, join, move, kill, live read model updates for two players', { tim BIND: `127.0.0.1:${SERVICE_PORT}`, DATABASE_URL: `sqlite:${join(dataDir, 'service.db')}?mode=rwc`, MOBPIT_BUS_URL: busUrl, + REDIS_URL: redisUrl, + MOBPIT_REDIS_PREFIX: redisPrefix, MOBPIT_API_ISSUER: 'mobpit-sveltekit', MOBPIT_API_AUDIENCE: 'mobpit-service', MOBPIT_API_JWKS: keys.jwks, @@ -229,7 +239,10 @@ test('sign in, join, move, kill, live read model updates for two players', { tim assert.ok([10, 25, 60].some((tier) => xp >= tier) && kills >= 1, `xp ${xp} kills ${kills}`); assert.deepEqual(navigations, [], 'the read model updated without a reload'); - // The other player's leaderboard updated live too. + // The other player's leaderboard (the Redis board via the GraphQL + // board roots) updated live too: the zone server's board change + // notice crossed the bus to mobpit-service, which pushed it. + assert.equal(await bob.getAttribute('[data-testid=leaderboard]', 'data-live'), 'active'); await bob.waitForFunction( (expected) => [...document.querySelectorAll('[data-testid=leaderboard] li')].some((li) => li.textContent === expected), `ana — ${xp} XP`, From 68359a2d6e62dcd9af70e2ef7bae5e1cfaf682bb Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:29:34 -0500 Subject: [PATCH 256/484] test: expect migration 13 in the migration version assertions The schedule claims migration (0013) made three version assertions stale: the SQLite and Postgres upgrade tests and the CLI's migration inventory order test. [[tasks/gr-p39-postgres-game-adapters]] --- distributed_cli/src/contracts/tests.rs | 2 +- tests/postgres_repository/main.rs | 2 +- tests/sqlite_repository/main.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 65105aa22..8b56b33d5 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -1259,7 +1259,7 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]); assert_eq!( inventory.canonical_bytes().expect("canonical inventory"), inventory diff --git a/tests/postgres_repository/main.rs b/tests/postgres_repository/main.rs index e77d6efed..763fa7e50 100644 --- a/tests/postgres_repository/main.rs +++ b/tests/postgres_repository/main.rs @@ -234,7 +234,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_and_preserve_checks() { .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 12); + assert_eq!(latest_version, 13); let invalid_service = sqlx::query( r#" diff --git a/tests/sqlite_repository/main.rs b/tests/sqlite_repository/main.rs index e44a89fc4..26035bf04 100644 --- a/tests/sqlite_repository/main.rs +++ b/tests/sqlite_repository/main.rs @@ -202,7 +202,7 @@ async fn projected_command_ledger_rows_upgrade_to_atomic_without_schema_drift() .fetch_one(repo.pool()) .await .unwrap(); - assert_eq!(latest_version, 12); + assert_eq!(latest_version, 13); let created_at_type: String = sqlx::query_scalar( "SELECT typeof(created_at) FROM command_ledger WHERE service_id = 'service'", From 8138354e1b43c0f2b98d5808e1f0081a60a005fa Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:37:59 -0500 Subject: [PATCH 257/484] test(schedule): make the worker crash test robust on Postgres The crash test assumed the restarted worker's first pass ran within the crashed worker's 400 ms claim; opening and migrating a Postgres pool sometimes took longer. The claim is now 3 s and the test waits from the observed commit. The flaky-command counter was a process-wide static shared by the SQLite and Postgres variants running in parallel; each test now marks its own ticker id. [[tasks/gr-p39-postgres-game-adapters]] --- tests/schedule_worker/main.rs | 58 +++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/tests/schedule_worker/main.rs b/tests/schedule_worker/main.rs index c9feb9193..7d89c2d1b 100644 --- a/tests/schedule_worker/main.rs +++ b/tests/schedule_worker/main.rs @@ -162,9 +162,12 @@ async fn handle_tick( }) } -static FLAKY_FAILURES: AtomicUsize = AtomicUsize::new(0); +/// Ticker ids whose next `ticker.flaky` fails once (tests on different +/// backends run in parallel, so each uses its own id). +static FLAKY_ONCE: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); -/// Fails with a retryable (500) error while `FLAKY_FAILURES` > 0. +/// Fails with a retryable (500) error once per id in `FLAKY_ONCE`. struct Flaky; impl PortableCommand for Flaky where @@ -182,23 +185,7 @@ async fn handle_flaky( ctx: &CausalCommandContext<'_, Ticker>, input: TickInput, ) -> Result>, HandlerError> { - let mut current = FLAKY_FAILURES.load(Ordering::SeqCst); - let mut fail = false; - while current > 0 { - match FLAKY_FAILURES.compare_exchange( - current, - current - 1, - Ordering::SeqCst, - Ordering::SeqCst, - ) { - Ok(_) => { - fail = true; - break; - } - Err(actual) => current = actual, - } - } - if fail { + if FLAKY_ONCE.lock().unwrap().remove(&input.id) { return Err(HandlerError::Other("transient dependency outage".into())); } handle_tick(ctx, input).await @@ -389,7 +376,13 @@ macro_rules! scenarios { #[tokio::test] async fn crash_between_commit_and_settle_does_not_fire_twice() { let Some(ctx) = $fresh.await else { return }; - let (repo, crashing_worker) = ctx.repo().await.with_schedule_worker(fast()); + // A claim long enough to still hold after the restart below + // (opening and migrating a Postgres pool takes a while). + let claim_ttl = Duration::from_secs(3); + let (repo, crashing_worker) = ctx + .repo() + .await + .with_schedule_worker(fast().with_claim_ttl(claim_ttl)); let committed = Arc::new(AtomicUsize::new(0)); let crashing: Arc = Arc::new(CrashAfterCommit { inner: LocalCommandHost::new(service(repo.clone())), @@ -408,6 +401,9 @@ macro_rules! scenarios { committed.load(Ordering::SeqCst) == 1 }) .await; + // The claim was taken before the commit, so it lapses before + // `committed_at + claim_ttl`. + let committed_at = Instant::now(); running.abort(); assert_eq!(ticks(&repo, "crash").await, 1); assert_eq!( @@ -420,8 +416,15 @@ macro_rules! scenarios { let (repo, worker) = $reopen(&ctx).await.with_schedule_worker(fast()); let host = LocalCommandHost::new(service(repo.clone())); let first = worker.run_once(&host).await.unwrap(); - assert!(first.is_empty(), "the crashed worker's claim still holds"); - tokio::time::sleep(Duration::from_millis(450)).await; + assert!( + committed_at.elapsed() >= claim_ttl - Duration::from_millis(500) + || first.is_empty(), + "the crashed worker's claim still holds: {first:?}" + ); + tokio::time::sleep( + (claim_ttl + Duration::from_millis(100)).saturating_sub(committed_at.elapsed()), + ) + .await; let replay = worker.run_once(&host).await.unwrap(); assert_eq!(replay.fired.len(), 1, "{replay:?}"); assert!( @@ -472,11 +475,12 @@ macro_rules! scenarios { let Some(ctx) = $fresh.await else { return }; let (repo, worker) = ctx.repo().await.with_schedule_worker(fast()); let host = LocalCommandHost::new(service(repo.clone())); - FLAKY_FAILURES.store(1, Ordering::SeqCst); - start(&host, "flaky", 1, 0, FLAKY).await; + let flaky = format!("flaky-{}", command_id()); + FLAKY_ONCE.lock().unwrap().insert(flaky.clone()); + start(&host, &flaky, 1, 0, FLAKY).await; let report = worker.run_once(&host).await.unwrap(); assert_eq!(report.retried.len(), 1, "{report:?}"); - let retry = repo.armed_schedules(&owner("flaky")).await.unwrap(); + let retry = repo.armed_schedules(&owner(&flaky)).await.unwrap(); assert_eq!(retry[0].attempts, 1); assert!( worker.run_once(&host).await.unwrap().is_empty(), @@ -485,8 +489,8 @@ macro_rules! scenarios { tokio::time::sleep(Duration::from_millis(1_050)).await; let report = worker.run_once(&host).await.unwrap(); assert_eq!(report.fired.len(), 1, "{report:?}"); - assert_eq!(ticks(&repo, "flaky").await, 1); - assert_eq!(armed(&repo, "flaky").await, 0); + assert_eq!(ticks(&repo, &flaky).await, 1); + assert_eq!(armed(&repo, &flaky).await, 0); } }; } From 0c4a940ec264fe8a7cf438ce59031fa0e0114d6e Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:50:34 -0500 Subject: [PATCH 258/484] fix(game): give REDIS_URL only to the SvelteKit test in run.sh smoke With REDIS_URL exported for the whole smoke run, the other demos' tests (which assert their in-memory boards) got Redis too. smoke now requires REDIS_URL, unsets it, and passes it to the SvelteKit test only. [[tasks/gr-p40-examples-e2e-coverage]] --- examples/game/run.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/examples/game/run.sh b/examples/game/run.sh index fb8e46991..51cd396b2 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -399,8 +399,11 @@ smoke() { # own `celld dev` (CELLD_BIN) on the cells worker. ensure_celld ensure_cells - # The SvelteKit test's leaderboard is the Redis board. + # The SvelteKit test's leaderboard is the Redis board. Only that test gets + # REDIS_URL: the other demos' tests expect their in-memory boards. require_redis + local sveltekit_redis="$REDIS_URL" + unset REDIS_URL log "generated clients are current; predicted steps and pure functions compiled to WASM" gen --check log "server: fmt, clippy, tests (bots smoke)" @@ -421,7 +424,7 @@ smoke() { "$CLI" build "$SERVER" >"$build_log" 2>&1 || { cat "$build_log"; rm -f "$build_log"; exit 1; } rm -f "$build_log" (cd "$SVELTEKIT" && npx playwright install chromium >/dev/null && - GAME_DEMOS_BIN="$BIN" MOBPIT_SERVICE_BIN="$SERVICE_BIN" npm test --silent) + REDIS_URL="$sveltekit_redis" GAME_DEMOS_BIN="$BIN" MOBPIT_SERVICE_BIN="$SERVICE_BIN" npm test --silent) log "smoke OK" } From 140b1c02467a6355b3215120553a04c474327e38 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 17:54:49 -0500 Subject: [PATCH 259/484] feat(game): spike a Mob Pit room as a celld Durable Object One Mob Pit room runs as a celld Durable Object (wasm32 Rust): the existing ZoneHost, wire protocol and HS256 tickets, a setTimeout tick loop while occupied, a hibernation snapshot in object storage, and the celld node / isolate / activation replicated as a global `host` entity. run.sh starts a 3-node production-mode fleet on one RustFS bucket; tools/ hold the headless test and the measurement scripts. Framework changes the spike needed: a `ticket` feature (admission tickets without the axum server) and wasm32-safe tick timing in ZoneHost (no `Instant` on wasm32-unknown-unknown). Spike only: not wired into the demos. [[tasks/gr-p42-zones-as-celld-objects-spike]] --- distributed_game/Cargo.toml | 5 +- distributed_game/src/host.rs | 10 + distributed_game/src/lib.rs | 5 + distributed_game/src/net/mod.rs | 2 +- examples/game/zone-do-spike/.gitignore | 4 + examples/game/zone-do-spike/Cargo.toml | 27 + examples/game/zone-do-spike/page/main.ts | 60 ++ .../game/zone-do-spike/page/room-client.ts | 61 ++ examples/game/zone-do-spike/public/index.html | 19 + examples/game/zone-do-spike/run.sh | 87 ++ examples/game/zone-do-spike/src/lib.rs | 755 +++++++++++++++ examples/game/zone-do-spike/src/pit.rs | 859 ++++++++++++++++++ .../game/zone-do-spike/tools/baseline.mjs | 5 + examples/game/zone-do-spike/tools/bench.ts | 166 ++++ examples/game/zone-do-spike/tools/drain.ts | 28 + examples/game/zone-do-spike/tools/failover.ts | 48 + examples/game/zone-do-spike/tools/headless.ts | 65 ++ examples/game/zone-do-spike/tools/peek.ts | 11 + .../game/zone-do-spike/tools/s3-compose.yaml | 13 + examples/game/zone-do-spike/wrangler.jsonc | 20 + 20 files changed, 2248 insertions(+), 2 deletions(-) create mode 100644 examples/game/zone-do-spike/.gitignore create mode 100644 examples/game/zone-do-spike/Cargo.toml create mode 100644 examples/game/zone-do-spike/page/main.ts create mode 100644 examples/game/zone-do-spike/page/room-client.ts create mode 100644 examples/game/zone-do-spike/public/index.html create mode 100755 examples/game/zone-do-spike/run.sh create mode 100644 examples/game/zone-do-spike/src/lib.rs create mode 100644 examples/game/zone-do-spike/src/pit.rs create mode 100644 examples/game/zone-do-spike/tools/baseline.mjs create mode 100644 examples/game/zone-do-spike/tools/bench.ts create mode 100644 examples/game/zone-do-spike/tools/drain.ts create mode 100644 examples/game/zone-do-spike/tools/failover.ts create mode 100644 examples/game/zone-do-spike/tools/headless.ts create mode 100644 examples/game/zone-do-spike/tools/peek.ts create mode 100644 examples/game/zone-do-spike/tools/s3-compose.yaml create mode 100644 examples/game/zone-do-spike/wrangler.jsonc diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 9116199d7..1b101016b 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -31,7 +31,10 @@ metrics = [] # Load-test bots (library + `game-bots` binary). bots = ["net", "dep:tokio-tungstenite", "dep:futures-util", "tokio/rt-multi-thread"] # axum WebSocket zone server with signed-ticket admission (+ /metrics). -net = ["runtime", "metrics", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros", "tokio/io-util"] +# HMAC-signed admission tickets (`ticket`) without the axum server: what a +# celld zone host (wasm32) needs to admit players (spike gr-p42). +ticket = ["dep:hmac", "dep:sha2", "dep:base64"] +net = ["runtime", "metrics", "ticket", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros", "tokio/io-util"] # `world::FencedLeaseOwnership`: zone ownership over `distributed::lease`. lease = ["dep:distributed"] diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index a2cb7b046..45b9106d9 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -1847,7 +1847,12 @@ impl ZoneHost { } fn tick_once(&mut self, dt: Duration) { + // wasm32-unknown-unknown (celld) has no `Instant`: measure with the + // host clock there (spike gr-p42). + #[cfg(not(target_arch = "wasm32"))] let started = std::time::Instant::now(); + #[cfg(target_arch = "wasm32")] + let started = self.core.clock.now(); self.core.tick += 1; self.core.sim_time += dt; self.core.dt = dt; @@ -1867,7 +1872,12 @@ impl ZoneHost { .rewind .record(self.core.tick, self.core.sim_time, entities); } + #[cfg(not(target_arch = "wasm32"))] self.pending.tick_durations.push(started.elapsed()); + #[cfg(target_arch = "wasm32")] + self.pending + .tick_durations + .push(self.core.clock.now().saturating_sub(started)); if self.hash_ticks { let hash = self.state_hash(); self.pending.tick_hashes.push((self.core.tick, hash)); diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 721d48d87..828b3a404 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -83,6 +83,11 @@ pub mod rng; pub mod schema; pub mod stamp; pub mod surface; +/// Signed admission tickets (also `net::ticket`); usable without the axum +/// server, e.g. by a celld zone host on wasm32. +#[cfg(feature = "ticket")] +#[path = "net/ticket.rs"] +pub mod ticket; pub mod timers; pub mod timestep; pub mod world; diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs index 637b5e6fb..b94220d54 100644 --- a/distributed_game/src/net/mod.rs +++ b/distributed_game/src/net/mod.rs @@ -45,7 +45,7 @@ pub mod inbox; pub mod peer; -pub mod ticket; +pub use crate::ticket; pub mod transfer; pub mod world; diff --git a/examples/game/zone-do-spike/.gitignore b/examples/game/zone-do-spike/.gitignore new file mode 100644 index 000000000..ba946d67f --- /dev/null +++ b/examples/game/zone-do-spike/.gitignore @@ -0,0 +1,4 @@ +build/ +target/ +public/page.js +.run/ diff --git a/examples/game/zone-do-spike/Cargo.toml b/examples/game/zone-do-spike/Cargo.toml new file mode 100644 index 000000000..ac34e3907 --- /dev/null +++ b/examples/game/zone-do-spike/Cargo.toml @@ -0,0 +1,27 @@ +# Spike gr-p42: one Mob Pit room as a celld Durable Object (wasm32). +# Own workspace (cdylib for wasm32-unknown-unknown); built with +# `worker-build --release` by `./run.sh`. Not a product crate. +[workspace] +members = ["."] +resolver = "2" + +[package] +name = "zone-do-spike" +version = "0.1.0" +edition = "2021" +publish = false +description = "Spike: a live Mob Pit zone as a celld Durable Object (dev only)" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +console_error_panic_hook = "0.1" +distributed_game = { path = "../../../distributed_game", default-features = false, features = ["ticket"] } +game_sim = { path = "../server/sim" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +worker = "0.8" + +[package.metadata.wasm-pack.profile.release] +wasm-opt = false diff --git a/examples/game/zone-do-spike/page/main.ts b/examples/game/zone-do-spike/page/main.ts new file mode 100644 index 000000000..3522d5f05 --- /dev/null +++ b/examples/game/zone-do-spike/page/main.ts @@ -0,0 +1,60 @@ +// Spike gr-p42 debug page: one Mob Pit room on celld, drawn in 2D, with the +// node / isolate / activation running it. +import { connectRoom, ATTACK } from './room-client.ts'; + +const params = new URLSearchParams(location.search); +const room = params.get('room') ?? 'pit-1'; +const name = params.get('name') ?? `p${Math.floor(Math.random() * 1000)}`; +const rc = connectRoom(location.origin, room, name); +const canvas = document.querySelector('canvas')!; +const g = canvas.getContext('2d')!; +const overlay = document.querySelector('#overlay')!; +const keys = new Set(); +addEventListener('keydown', (e) => keys.add(e.key.toLowerCase())); +addEventListener('keyup', (e) => keys.delete(e.key.toLowerCase())); +let status = 'connecting'; +rc.welcome.then(() => (status = 'joined'), (e) => (status = `failed: ${e}`)); +rc.client.on('zoneClosed', (_z, info) => (status = `closed ${JSON.stringify(info)}`)); +setInterval(() => { + const mx = (keys.has('d') ? 127 : 0) - (keys.has('a') ? 127 : 0); + const my = (keys.has('s') ? 127 : 0) - (keys.has('w') ? 127 : 0); + if (status === 'joined') rc.input(mx, my, keys.has(' ') || keys.has('j') ? ATTACK : 0); +}, 1000 / 30); +async function placement() { + try { + const r = await fetch(`/placement?rooms=${encodeURIComponent(room)}`); + const p = await r.json(); + (document.querySelector('#placement') as HTMLElement).textContent = + `operator view: ${room} owned by ${p.rooms[room] ?? '?'}\n` + + p.nodes.map((n: any) => `${n.node}: ${n.up ? `${n.resident_cells} cells, cpu ${n.cpu_percent}%` : 'down'}`).join('\n'); + } catch {} +} +setInterval(placement, 2000); +placement(); +function frame() { + const s = canvas.width / 42; + g.fillStyle = '#14161a'; + g.fillRect(0, 0, canvas.width, canvas.height); + const P = (x: number, y: number) => [(x + 21) * s, (y + 21) * s] as const; + const me = rc.hello()?.entity; + for (const e of rc.entities()) { + const f = e.fields as Record; + if (e.kindName === 'pillar') { const [x, y] = P(f.x, f.y); g.fillStyle = '#444'; g.beginPath(); g.arc(x, y, f.r * s, 0, 7); g.fill(); } + if (e.kindName === 'mob') { const [x, y] = P(f.x, f.y); g.fillStyle = ['', '#9ad16b', '#b48cf2', '#ff6b6b'][f.tier] ?? '#9ad16b'; g.beginPath(); g.arc(x, y, (0.4 + f.tier * 0.12) * s, 0, 7); g.fill(); if (f.tele) { g.strokeStyle = '#f80'; g.beginPath(); g.arc(x, y, 2 * s * f.tele / 255, 0, 7); g.stroke(); } } + if (e.kindName === 'player') { const [x, y] = P(f.x, f.y); g.fillStyle = e.id === me ? '#4cc3ff' : '#ddd'; g.beginPath(); g.arc(x, y, 0.5 * s, 0, 7); g.fill(); g.fillStyle = '#fff'; g.fillText(`${f.name} hp${f.hp} k${f.level}`, x + 8, y - 8); } + } + const h = rc.host(); + const pit = rc.entities().find((e) => e.kindName === 'pit')?.fields as any; + overlay.textContent = [ + `room ${room} as ${name} — ${status}`, + `celld node ${h?.node ?? '?'}`, + `isolate ${h?.isolate ?? '?'} (${h?.isolate_rooms ?? '?'} rooms seen by this isolate)`, + `activation ${h?.activation ?? '?'} #${h?.activations ?? '?'} ${h?.restored ? 'restored from storage' : 'fresh'} wake ${h?.wake_ms ?? '?'} ms`, + `tick ${h?.hz ?? '?'} Hz late ${h?.late_ms?.toFixed(2)} ms (max/s ${h?.late_max_ms?.toFixed(1)})`, + `room kills ${pit?.kills ?? '?'} lifetime ticks ${pit?.ticks ?? '?'}`, + `rtt ${rc.rtt()?.toFixed(1) ?? '?'} ms (via ${location.host})`, + `WASD move, space/J attack` + ].join('\n'); + requestAnimationFrame(frame); +} +frame(); diff --git a/examples/game/zone-do-spike/page/room-client.ts b/examples/game/zone-do-spike/page/room-client.ts new file mode 100644 index 000000000..144e081af --- /dev/null +++ b/examples/game/zone-do-spike/page/room-client.ts @@ -0,0 +1,61 @@ +// Spike gr-p42: a Mob Pit room client over the framework's generic +// GameClient (no generated code, no prediction). Shared by the debug page +// and the headless test (Node 22+ has a global WebSocket). +import { GameClient, decodePayload, encodePayload, type PayloadLayout, type RenderedEntity } from '../../../../js/src/game/index.ts'; + +const INPUT: PayloadLayout = [['mx', { type: 'i8' }], ['my', { type: 'i8' }], ['buttons', { type: 'u8' }]]; +const HELLO: PayloadLayout = [['entity', { type: 'u32' }], ['half', { type: 'f32' }], ['boot', { type: 'short_str' }], ['attackRange', { type: 'f32' }], ['attackArcCos', { type: 'f32' }]]; +const KILL: PayloadLayout = [['mob', { type: 'u32' }], ['tier', { type: 'u8' }], ['killer', { type: 'u32' }], ['killerName', { type: 'short_str' }], ['kills', { type: 'u32' }]]; +export const ATTACK = 2; + +export type Host = { node: string; isolate: string; activation: string; activations: number; restored: boolean; wakeMs: number; hz: number; lateMs: number; lateMaxMs: number; workUs: number; isolateRooms: number }; + +export type RoomClient = { + client: GameClient; + welcome: Promise; + hello: () => { entity: number; boot: string } | undefined; + host: () => Host | undefined; + entities: () => RenderedEntity[]; + me: () => RenderedEntity | undefined; + kills: { mob: number; killer: number; killerName: string; kills: number }[]; + input: (mx: number, my: number, buttons: number) => void; + rtt: () => number | undefined; + close: () => void; +}; + +export function connectRoom(base: string, room: string, name: string): RoomClient { + const ws = base.replace(/^http/, 'ws'); + let hello: { entity: number; boot: string } | undefined; + const kills: RoomClient['kills'] = []; + const client = new GameClient({ + url: (zone) => `${ws}/rooms/${encodeURIComponent(zone)}`, + ticket: async ({ zoneId }) => { + const r = await fetch(`${base}/ticket?room=${encodeURIComponent(zoneId)}&name=${encodeURIComponent(name)}`); + return ((await r.json()) as { ticket: string }).ticket; + }, + pingIntervalMs: 500, + reconnect: false + }); + client.on('event', (_zone, e) => { + if (e.typeId === 1) hello = decodePayload(HELLO, e.payload) as never; + if (e.typeId === 3) kills.push(decodePayload(KILL, e.payload) as never); + }); + const welcome = client.connect(room); + const entities = () => client.render(); + const host = (): Host | undefined => entities().find((e) => e.kindName === 'host')?.fields as never; + return { + client, + welcome, + hello: () => hello, + host, + entities, + me: () => entities().find((e) => e.kindName === 'player' && hello && e.id === hello.entity), + kills, + input: (mx, my, buttons) => client.sendRawInput(encodePayload(INPUT, { mx, my, buttons })), + rtt: () => { + const z = client.zone(room) as unknown as { connection?: { clock?: { rtt?: number } } } | undefined; + return z?.connection?.clock?.rtt; + }, + close: () => client.close() + }; +} diff --git a/examples/game/zone-do-spike/public/index.html b/examples/game/zone-do-spike/public/index.html new file mode 100644 index 000000000..44c437155 --- /dev/null +++ b/examples/game/zone-do-spike/public/index.html @@ -0,0 +1,19 @@ + + + + +Pit on celld + + + + +

      + + + diff --git a/examples/game/zone-do-spike/run.sh b/examples/game/zone-do-spike/run.sh new file mode 100755 index 000000000..3db39e0c8 --- /dev/null +++ b/examples/game/zone-do-spike/run.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Spike gr-p42: Mob Pit rooms as celld Durable Objects on a local +# multi-node celld fleet (production mode, one shared S3 bucket). +# +# ./run.sh up [N] S3 container + bucket, build, deploy, N nodes (default 3) +# ./run.sh deploy rebuild and publish a new version (nodes adopt it live) +# ./run.sh nodes [N] start N nodes ./run.sh kill SIGKILL one node +# ./run.sh status per-node owned/resident cells (operator view) +# ./run.sh down stop nodes, remove the S3 container +# +# Nodes: node-a/b/c, public 127.0.0.1:18101-18103 (open any of them in a +# browser: /?room=pit-1&name=ana), operator 127.0.0.1:18201-18203. +# Needs: CELLD (celld >= 0.6.2), worker-build, esbuild (CELLD_ESBUILD), docker. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +STATE="${SPIKE_STATE:-$HERE/.run}" +CELLD="${CELLD:-celld}" +export CELLD_ESBUILD="${CELLD_ESBUILD:-$HERE/../client/node_modules/.bin/esbuild}" +export AWS_ACCESS_KEY_ID=spikeadmin AWS_SECRET_ACCESS_KEY=spikesecret123 AWS_REGION=us-east-1 +S3_PORT="${S3_PORT:-19400}" +export S3_ENDPOINT="http://127.0.0.1:$S3_PORT" +BUCKET="s3://zone-spike/zone" +NAMES=(a b c d) +mkdir -p "$STATE" + +s3_up() { + S3_PORT="$S3_PORT" docker compose -p zone-do-spike -f "$HERE/tools/s3-compose.yaml" up -d >/dev/null 2>&1 + for _ in $(seq 1 30); do curl -s -o /dev/null "$S3_ENDPOINT/" && break; sleep 1; done + aws --endpoint-url "$S3_ENDPOINT" s3 mb s3://zone-spike >/dev/null 2>&1 || true +} + +build() { + (cd "$HERE" && worker-build --release >/dev/null) + "$CELLD_ESBUILD" "$HERE/page/main.ts" --bundle --format=esm --target=es2022 \ + --outfile="$HERE/public/page.js" --log-level=warning +} + +deploy() { + build + (cd "$HERE" && "$CELLD" deploy . --bucket "$BUCKET" 2>&1 | grep -E "Version ID|rror") +} + +nodes() { + local n="${1:-3}" + for i in $(seq 0 $((n - 1))); do + local nm=${NAMES[$i]} dir="$STATE/node-${NAMES[$i]}" + mkdir -p "$dir" + [[ -f "$dir/pid" ]] && kill -0 "$(cat "$dir/pid")" 2>/dev/null && continue + CELLD_NODE="node-$nm" CELLD_WATCH="$dir/watch" RUST_LOG="${RUST_LOG:-warn}" \ + CELLD_IDLE_EVICT_S="${CELLD_IDLE_EVICT_S:-10}" \ + nohup "$CELLD" --bucket "$BUCKET" --listen "127.0.0.1:$((18101 + i))" \ + --internal-listen "127.0.0.1:$((18201 + i))" --advertise "127.0.0.1:$((18201 + i))" \ + >"$dir/celld.log" 2>&1 & + echo $! >"$dir/pid" + echo "node-$nm: http://127.0.0.1:$((18101 + i))/ (operator :$((18201 + i)), pid $!)" + done + for i in $(seq 0 $((n - 1))); do + for _ in $(seq 1 60); do curl -fs "http://127.0.0.1:$((18101 + i))/ticket" >/dev/null && break; sleep 0.5; done + done +} + +status() { + for i in 0 1 2 3; do + curl -s -m 2 "http://127.0.0.1:$((18201 + i))/state" 2>/dev/null | python3 -c ' +import json,sys +d=json.load(sys.stdin); l=d["node_load"] +print(sys.argv[1], "owned", d["owned_cells"], "resident", l["resident_cells"], "cpu%", l["cpu_percent_x100"]/100, "rebalanced", d["rebalanced"], "version", d["deployment"]["version"])' "node-${NAMES[$i]}" 2>/dev/null || true + done +} + +down() { + for nm in "${NAMES[@]}"; do + local f="$STATE/node-$nm/pid" + [[ -f $f ]] && { kill "$(cat "$f")" 2>/dev/null || true; rm -f "$f"; } + done + docker compose -p zone-do-spike -f "$HERE/tools/s3-compose.yaml" down -v >/dev/null 2>&1 || true +} + +case "${1:-}" in +up) s3_up; deploy; nodes "${2:-3}" ;; +deploy) deploy ;; +nodes) nodes "${2:-3}" ;; +kill) kill -9 "$(cat "$STATE/node-$2/pid")"; rm -f "$STATE/node-$2/pid"; echo "killed node-$2" ;; +status) status ;; +down) down ;; +*) sed -n '2,13p' "$0"; exit 1 ;; +esac diff --git a/examples/game/zone-do-spike/src/lib.rs b/examples/game/zone-do-spike/src/lib.rs new file mode 100644 index 000000000..8ae065785 --- /dev/null +++ b/examples/game/zone-do-spike/src/lib.rs @@ -0,0 +1,755 @@ +//! Spike gr-p42: a live Mob Pit room as a celld Durable Object. +//! +//! - `GET /ticket?room=&name=` (dev only): a signed join ticket, the same +//! HS256 format the native zone server admits (`distributed_game::ticket`). +//! - `GET /rooms/{room}` (WebSocket upgrade): the room object named `room`. +//! The client speaks the existing `distributed_game` wire protocol: Hello +//! with the ticket, then Input / Ping / Leave; the room answers Welcome, +//! Delta, Event, Pong. +//! - `GET /rooms/{room}/stats`: tick timing numbers of the room (JSON). +//! - `GET /placement?rooms=a,b`: which node owns each room (operator view). +//! - everything else: the static debug page (`public/`). +//! +//! The room (`PitRoom`) runs a `ZoneHost` in the object's memory. It +//! ticks with a `setTimeout` loop while any player is in it, writes its +//! hibernation snapshot to object storage every few seconds and when the +//! last player leaves, then stops; celld may then evict it. The next join +//! reactivates it on whichever node owns it and restores the snapshot. +//! +//! celld does not tell application code which node runs it, so the room +//! asks every node's operator listener (`NODES`) whether it holds the room. + +mod pit; + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::rc::Rc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::protocol::{error, ClientMessage, ServerMessage, PROTOCOL_VERSION}; +use distributed_game::ticket::TicketKey; +use distributed_game::{Clock, HostConfig, Outbound, Role, TicketClaims, ZoneHost}; +use pit::Pit; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use worker::*; + +const SNAPSHOT_KEY: &str = "pit-snapshot"; +const PERSIST_EVERY_MS: f64 = 5_000.0; + +// ------------------------------------------------------------------ time + +fn performance_now() -> f64 { + let global = js_sys::global(); + js_sys::Reflect::get(&global, &"performance".into()) + .ok() + .and_then(|p| { + let now = js_sys::Reflect::get(&p, &"now".into()).ok()?; + let now: js_sys::Function = now.into(); + now.call0(&p).ok()?.as_f64() + }) + .unwrap_or_else(js_sys::Date::now) +} + +/// Monotonic clock over `Date.now()` (`Instant` panics on wasm32). +struct JsClock { + origin_ms: f64, + last_us: AtomicU64, +} + +impl JsClock { + fn new() -> Self { + Self { + origin_ms: js_sys::Date::now(), + last_us: AtomicU64::new(0), + } + } +} + +impl Clock for JsClock { + fn now(&self) -> Duration { + let us = ((js_sys::Date::now() - self.origin_ms).max(0.0) * 1000.0) as u64; + let us = self.last_us.fetch_max(us, Ordering::Relaxed).max(us); + Duration::from_micros(us) + } + + fn unix_ms(&self) -> u64 { + self.origin_ms as u64 + self.now().as_millis() as u64 + } +} + +fn random_id() -> String { + format!( + "{:08x}", + (js_sys::Math::random() * f64::from(u32::MAX)) as u32 + ) +} + +thread_local! { + /// One id per V8 isolate (module instance). + static ISOLATE: String = random_id(); + /// Rooms alive in this isolate. + static ISOLATE_ROOMS: RefCell> = RefCell::new(HashSet::new()); +} + +// ------------------------------------------------------------------ stats + +/// Loop timing over the life of an activation. +#[derive(Default)] +struct TickStats { + /// How late each wake-up was against its deadline (ms). + late: VecDeque, + /// Interval between consecutive loop iterations (ms). + interval: VecDeque, + /// Work per iteration (ms; advance + sends). + work: VecDeque, + /// Fixed steps dropped by the catch-up cap. + dropped_ticks: u64, + /// Iterations that ran more than one fixed step (catch-up). + catch_up: u64, + iterations: u64, + last_wake: Option, + late_ema: f64, + work_ema: f64, + late_max_window: f64, + window: u32, + late_max: f64, +} + +const STAT_WINDOW: usize = 20_000; + +fn push(q: &mut VecDeque, v: f64) { + if q.len() == STAT_WINDOW { + q.pop_front(); + } + q.push_back(v); +} + +fn pct(q: &VecDeque, p: f64) -> f64 { + if q.is_empty() { + return 0.0; + } + let mut v: Vec = q.iter().copied().collect(); + v.sort_by(|a, b| a.total_cmp(b)); + v[((v.len() - 1) as f64 * p).round() as usize] +} + +// ------------------------------------------------------------------ room + +#[derive(Serialize, Deserialize)] +struct Attachment { + client: u32, + activation: String, +} + +struct Room { + name: String, + id_hex: String, + activation: String, + constructed_ms: f64, + host: Option>, + sockets: HashMap, + ticking: bool, + hz: u32, + key: TicketKey, + nonces: HashSet, + stats: TickStats, + first_tick_ms: Option, + restored: bool, + node: String, + welcome_ms: Vec, +} + +impl Room { + fn flush(&mut self) { + let Some(host) = self.host.as_mut() else { + return; + }; + for out in host.drain_outbound() { + match out { + Outbound::Frame { client, frame } => { + if let Some(ws) = self.sockets.get(&client.0) { + let _ = ws.send_with_bytes(frame); + } + } + Outbound::Close { client } => { + if let Some(ws) = self.sockets.remove(&client.0) { + let _ = ws.close(Some(1000), Some("closed by zone")); + } + } + } + } + } + + fn occupied(&self) -> bool { + self.host + .as_ref() + .is_some_and(|h| h.player_count() > 0 || h.client_count() > 0) + } + + fn snapshot(&self) -> Option { + let state = self.host.as_ref()?.hibernate_state()?; + String::from_utf8(state).ok() + } + + fn sync_host_info(&mut self) { + let isolate_rooms = ISOLATE_ROOMS.with(|r| r.borrow().len()) as u16; + let (late, late_max, work) = ( + self.stats.late_ema, + self.stats.late_max, + self.stats.work_ema, + ); + let wake_ms = self + .first_tick_ms + .map(|t| (t - self.constructed_ms).max(0.0) as u32) + .unwrap_or(0); + let (node, restored, hz) = (self.node.clone(), self.restored, self.hz as u8); + if let Some(host) = self.host.as_mut() { + let zone = host.zone_mut(); + let activations = zone.activations; + let info = &mut zone.host; + info.node = node; + info.restored = restored; + info.activations = activations; + info.hz = hz; + info.late_ms = late as f32; + info.late_max_ms = late_max as f32; + info.work_us = (work * 1000.0) as u32; + info.wake_ms = wake_ms; + info.isolate_rooms = isolate_rooms; + } + } +} + +#[durable_object] +pub struct PitRoom { + state: State, + env: Env, + room: Rc>, +} + +impl DurableObject for PitRoom { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let constructed_ms = performance_now(); + let id_hex = state.id().to_string(); + let name = state.id().name().unwrap_or_default(); + let hz = env + .var("TICK_HZ") + .ok() + .and_then(|v| v.to_string().parse().ok()) + .unwrap_or(30); + let secret = env + .var("TICKET_SECRET") + .map(|v| v.to_string()) + .unwrap_or_default(); + let room = Room { + name, + id_hex, + activation: random_id(), + constructed_ms, + host: None, + sockets: HashMap::new(), + ticking: false, + hz, + key: TicketKey::new(secret.into_bytes()), + nonces: HashSet::new(), + stats: TickStats::default(), + first_tick_ms: None, + restored: false, + node: "?".into(), + welcome_ms: Vec::new(), + }; + Self { + state, + env, + room: Rc::new(RefCell::new(room)), + } + } + + async fn fetch(&self, req: Request) -> Result { + let url = req.url()?; + if let Some(name) = req.headers().get("x-room")? { + let mut room = self.room.borrow_mut(); + if room.name.is_empty() { + room.name = name; + } + } + self.ensure_host().await?; + if url.path().ends_with("/stats") { + if url.query_pairs().any(|(k, _)| k == "reset") { + self.room.borrow_mut().stats = TickStats::default(); + } + return Response::from_json(&self.stats_json()); + } + if req.headers().get("upgrade")?.as_deref() != Some("websocket") { + return Response::error("expected a WebSocket upgrade", 426); + } + let pair = WebSocketPair::new()?; + self.state.accept_web_socket(&pair.server); + Response::from_websocket(pair.client) + } + + async fn websocket_message( + &self, + ws: WebSocket, + message: WebSocketIncomingMessage, + ) -> Result<()> { + let WebSocketIncomingMessage::Binary(bytes) = message else { + let _ = ws.close(Some(1003), Some("binary frames only")); + return Ok(()); + }; + self.ensure_host().await?; + let msg = match ClientMessage::decode(&bytes) { + Ok(m) => m, + Err(_) => { + reject(&ws, error::BAD_MESSAGE, "bad message"); + return Ok(()); + } + }; + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let activation = self.room.borrow().activation.clone(); + let client = match attached { + Some(a) if a.activation == activation => Some(a.client), + // The socket outlived the activation that admitted it (the room + // was evicted and woke up again): its player is gone. + Some(_) => { + let _ = ws.close(Some(1012), Some("room restarted; rejoin")); + return Ok(()); + } + None => None, + }; + match (client, msg) { + (None, ClientMessage::Hello(hello)) => { + let t0 = performance_now(); + if hello.protocol_version != PROTOCOL_VERSION { + reject(&ws, error::VERSION_MISMATCH, "protocol version"); + return Ok(()); + } + let joined = { + let mut room = self.room.borrow_mut(); + let now = (js_sys::Date::now() / 1000.0) as u64; + let claims = match room.key.verify(&hello.ticket, now) { + Ok(c) => c, + Err(e) => { + drop(room); + reject(&ws, error::UNAUTHORIZED, &format!("{e:?}")); + return Ok(()); + } + }; + if claims.zone != room.name || !room.nonces.insert(claims.nonce.clone()) { + drop(room); + reject(&ws, error::UNAUTHORIZED, "wrong room or replayed ticket"); + return Ok(()); + } + room.sync_host_info(); + let host = room.host.as_mut().expect("host loaded"); + match host.join(&claims, hello.capabilities, &hello.content_version) { + Ok(joined) => { + let client = joined.client.0; + ws.serialize_attachment(Attachment { + client, + activation: activation.clone(), + })?; + room.sockets.insert(client, ws.clone()); + room.flush(); + let elapsed = performance_now() - t0; + room.welcome_ms.push(elapsed); + Ok(()) + } + Err(e) => Err(e), + } + }; + match joined { + Ok(()) => self.start_loop(), + Err(e) => reject(&ws, e.code, &e.message), + } + } + ( + Some(client), + ClientMessage::Input { + seq, + client_tick, + payload, + }, + ) => { + let mut room = self.room.borrow_mut(); + if let Some(host) = room.host.as_mut() { + host.push_input( + distributed_game::ClientId(client), + seq, + client_tick, + &payload, + ); + } + } + (_, ClientMessage::Ping { client_time }) => { + let room = self.room.borrow(); + let server_time = room.host.as_ref().map_or(0.0, |h| h.server_time_ms()); + let pong = ServerMessage::Pong { + client_time, + server_time, + } + .encode(&()) + .expect("pong encodes"); + let _ = ws.send_with_bytes(pong); + } + (Some(client), ClientMessage::Leave) => { + let mut room = self.room.borrow_mut(); + room.sockets.remove(&client); + if let Some(host) = room.host.as_mut() { + host.disconnect(distributed_game::ClientId(client), true); + } + room.flush(); + let _ = ws.close(Some(1000), Some("left")); + } + _ => reject(&ws, error::BAD_MESSAGE, "unexpected message"), + } + Ok(()) + } + + async fn websocket_close( + &self, + ws: WebSocket, + _code: usize, + _reason: String, + _was_clean: bool, + ) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } + + async fn websocket_error(&self, ws: WebSocket, _error: Error) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } +} + +fn reject(ws: &WebSocket, code: u32, message: &str) { + if let Ok(frame) = (ServerMessage::Error { + code, + message: message.into(), + }) + .encode(&()) + { + let _ = ws.send_with_bytes(frame); + } + let _ = ws.close(Some(1008), Some(message)); +} + +impl PitRoom { + fn drop_socket(&self, ws: &WebSocket) { + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let mut room = self.room.borrow_mut(); + if let Some(a) = attached.filter(|a| a.activation == room.activation) { + room.sockets.remove(&a.client); + if let Some(host) = room.host.as_mut() { + host.disconnect(distributed_game::ClientId(a.client), false); + } + } + } + + /// Create the zone host on first use: restore the stored snapshot and + /// find out which node this is. + async fn ensure_host(&self) -> Result<()> { + if self.room.borrow().host.is_some() { + return Ok(()); + } + let stored: Option = self.state.storage().get(SNAPSHOT_KEY).await?; + let mut room = self.room.borrow_mut(); + if room.host.is_some() { + return Ok(()); + } + // `name@20` runs the room at 20 Hz (measurements). + if let Some(hz) = room + .name + .split_once('@') + .and_then(|(_, hz)| hz.parse().ok()) + { + room.hz = hz; + } + let config = HostConfig { + tick_rate: room.hz, + patch_rate: room.hz.min(20), + // The Durable Object stops ticking when empty instead. + idle_tick_rate: None, + boot_epoch: (js_sys::Date::now() * 1000.0) as u64, + reconnect_grace: Duration::from_secs(5), + ..HostConfig::default() + }; + let name = room.name.clone(); + let mut host = ZoneHost::::new(name.clone(), config, Arc::new(JsClock::new()), ()) + .with_token_source(|| format!("{}{}", random_id(), random_id())); + if let Some(state) = stored { + host.restore(state.as_bytes(), ""); + room.restored = true; + } + { + let activation = room.activation.clone(); + let info = &mut host.zone_mut().host; + info.activation = activation; + info.isolate = ISOLATE.with(|i| i.clone()); + } + room.host = Some(host); + ISOLATE_ROOMS.with(|r| r.borrow_mut().insert(name)); + drop(room); + self.find_node(); + Ok(()) + } + + /// Ask each node's operator listener whether it holds this room. + fn find_node(&self) { + let nodes = self + .env + .var("NODES") + .map(|v| v.to_string()) + .unwrap_or_default(); + let room = self.room.clone(); + let id_hex = room.borrow().id_hex.clone(); + wasm_bindgen_futures::spawn_local(async move { + for entry in nodes.split(',').filter(|e| !e.is_empty()) { + let Some((node, addr)) = entry.split_once('=') else { + continue; + }; + let Ok(mut resp) = Fetch::Url( + format!("http://{addr}/state") + .parse() + .expect("operator url"), + ) + .send() + .await + else { + continue; + }; + let Ok(state) = resp.json::().await else { + continue; + }; + let mine = state["deployment"]["cells"] + .as_object() + .is_some_and(|cells| cells.keys().any(|k| k.ends_with(&id_hex))); + if mine { + let mut room = room.borrow_mut(); + room.node = node.to_string(); + room.sync_host_info(); + return; + } + } + }); + } + + fn start_loop(&self) { + { + let mut room = self.room.borrow_mut(); + if room.ticking { + return; + } + room.ticking = true; + } + let room = self.room.clone(); + let storage = self.state.storage(); + wasm_bindgen_futures::spawn_local(async move { + let step_ms = 1000.0 / f64::from(room.borrow().hz); + let start = performance_now(); + let mut k: u64 = 1; + let mut last_persist = start; + loop { + let deadline = start + k as f64 * step_ms; + let wait = (deadline - performance_now()).max(0.0); + Delay::from(Duration::from_micros((wait * 1000.0) as u64)).await; + let woke = performance_now(); + // Skip deadlines we already missed (the fixed timestep + // catches up with several steps in one advance). + k = (((woke - start) / step_ms).floor() as u64 + 1).max(k + 1); + let (stop, snapshot) = { + let mut room = room.borrow_mut(); + let late = (woke - deadline).max(0.0); + let interval = room.stats.last_wake.map(|l| woke - l); + let report = room.host.as_mut().map(|h| h.advance()); + if room.first_tick_ms.is_none() { + room.first_tick_ms = Some(woke); + } + room.flush(); + let work = performance_now() - woke; + let s = &mut room.stats; + s.iterations += 1; + s.last_wake = Some(woke); + push(&mut s.late, late); + if let Some(i) = interval { + push(&mut s.interval, i); + } + push(&mut s.work, work); + if let Some(r) = &report { + s.dropped_ticks += u64::from(r.dropped_ticks); + if r.ticks > 1 { + s.catch_up += 1; + } + } + s.late_ema = if s.iterations == 1 { + late + } else { + s.late_ema * 0.95 + late * 0.05 + }; + s.work_ema = if s.iterations == 1 { + work + } else { + s.work_ema * 0.95 + work * 0.05 + }; + s.late_max_window = s.late_max_window.max(late); + s.window += 1; + if s.window >= room.hz { + let s = &mut room.stats; + s.late_max = s.late_max_window; + s.late_max_window = 0.0; + s.window = 0; + } + room.sync_host_info(); + let stop = !room.occupied(); + let persist = stop || woke - last_persist >= PERSIST_EVERY_MS; + if stop { + room.ticking = false; + } + (stop, persist.then(|| room.snapshot()).flatten()) + }; + if let Some(snapshot) = snapshot { + last_persist = woke; + if let Err(e) = storage.put(SNAPSHOT_KEY, snapshot).await { + console_error!("persist failed: {e}"); + } + } + if stop { + return; + } + } + }); + } + + fn stats_json(&self) -> serde_json::Value { + let room = self.room.borrow(); + let s = &room.stats; + let host = room.host.as_ref(); + json!({ + "room": room.name, + "node": room.node, + "isolate": ISOLATE.with(|i| i.clone()), + "activation": room.activation, + "restored": room.restored, + "hz": room.hz, + "ticking": room.ticking, + "players": host.map_or(0, |h| h.player_count()), + "tick": host.map_or(0, |h| h.tick()), + "lifetime_ticks": host.map_or(0, |h| h.zone().ticks()), + "kills": host.map_or(0, |h| h.zone().kills), + "activations": host.map_or(0, |h| h.zone().activations), + "isolate_rooms": ISOLATE_ROOMS.with(|r| r.borrow().len()), + "wake_ms": room.first_tick_ms.map(|t| t - room.constructed_ms), + "welcome_ms": room.welcome_ms, + "iterations": s.iterations, + "dropped_ticks": s.dropped_ticks, + "catch_up_iterations": s.catch_up, + "late_ms": {"p50": pct(&s.late, 0.5), "p99": pct(&s.late, 0.99), "max": pct(&s.late, 1.0)}, + "interval_ms": {"p50": pct(&s.interval, 0.5), "p99": pct(&s.interval, 0.99), "max": pct(&s.interval, 1.0)}, + "work_ms": {"p50": pct(&s.work, 0.5), "p99": pct(&s.work, 0.99), "max": pct(&s.work, 1.0)}, + }) + } +} + +// ------------------------------------------------------------------ worker + +fn ticket(env: &Env, room: &str, name: &str) -> Result { + let secret = env.var("TICKET_SECRET")?.to_string(); + let key = TicketKey::new(secret.into_bytes()); + let exp = (js_sys::Date::now() / 1000.0) as u64 + 300; + let principal = format!("guest:{name}"); + let claims = TicketClaims::new( + principal, + room, + exp, + random_id() + &random_id(), + Role::Player, + ) + .with_name(name); + Ok(key.sign(&claims)) +} + +async fn placement(env: &Env, rooms: &str) -> Result { + let ns = env.durable_object("PIT_ROOM")?; + let mut ids = Vec::new(); + for room in rooms.split(',').filter(|r| !r.is_empty()) { + ids.push((room.to_string(), ns.id_from_name(room)?.to_string())); + } + let nodes = env.var("NODES")?.to_string(); + let mut out = serde_json::Map::new(); + let mut node_rows = Vec::new(); + for entry in nodes.split(',').filter(|e| !e.is_empty()) { + let Some((node, addr)) = entry.split_once('=') else { + continue; + }; + let state = match Fetch::Url(format!("http://{addr}/state").parse()?) + .send() + .await + { + Ok(mut r) => r.json::().await.ok(), + Err(_) => None, + }; + let Some(state) = state else { + node_rows.push(json!({"node": node, "up": false})); + continue; + }; + let cells = state["deployment"]["cells"] + .as_object() + .cloned() + .unwrap_or_default(); + for (room, id) in &ids { + if cells.keys().any(|k| k.ends_with(id.as_str())) { + out.insert(room.clone(), json!(node)); + } + } + node_rows.push(json!({ + "node": node, + "up": true, + "resident_cells": state["node_load"]["resident_cells"], + "owned_cells": state["owned_cells"], + "cpu_percent": state["node_load"]["cpu_percent_x100"].as_f64().map(|c| c / 100.0), + "rebalanced": state["rebalanced"], + })); + } + Response::from_json(&json!({"rooms": out, "nodes": node_rows})) +} + +#[event(fetch)] +async fn main(req: Request, env: Env, _ctx: Context) -> Result { + console_error_panic_hook::set_once(); + let url = req.url()?; + let path = url.path().to_string(); + let query: HashMap = url.query_pairs().into_owned().collect(); + if path == "/ticket" { + let room = query.get("room").cloned().unwrap_or_else(|| "pit-1".into()); + let name = query.get("name").cloned().unwrap_or_else(|| "guest".into()); + return Response::from_json(&json!({"ticket": ticket(&env, &room, &name)?})); + } + if path == "/placement" { + return placement(&env, query.get("rooms").map_or("", |s| s.as_str())).await; + } + if let Some(rest) = path.strip_prefix("/rooms/") { + let raw = rest.split('/').next().unwrap_or_default(); + let room: String = js_sys::decode_uri_component(raw) + .map(String::from) + .unwrap_or_else(|_| raw.to_string()); + if room.is_empty() { + return Response::error("room required", 400); + } + let ns = env.durable_object("PIT_ROOM")?; + let stub = ns.id_from_name(&room)?.get_stub()?; + // Name the room for the object (its id has no name on some paths). + let headers = req.headers().clone(); + headers.set("x-room", &room)?; + let mut init = RequestInit::new(); + init.with_method(req.method()).with_headers(headers); + let forwarded = Request::new_with_init(req.url()?.as_str(), &init)?; + return stub.fetch_with_request(forwarded).await; + } + let assets = env.assets("ASSETS")?; + assets.fetch_request(req).await +} diff --git a/examples/game/zone-do-spike/src/pit.rs b/examples/game/zone-do-spike/src/pit.rs new file mode 100644 index 000000000..b7ae1ac1f --- /dev/null +++ b/examples/game/zone-do-spike/src/pit.rs @@ -0,0 +1,859 @@ +//! Mob Pit, trimmed for the spike: the same players, mobs, pillars, melee +//! combat and the same replicated kinds/ids as +//! `examples/game/server/src/mobpit/zone.rs` (copied, not shared: that zone +//! lives in the native `game_demos` crate next to tokio, reqwest and the +//! Crawler fact sink, so it does not build for wasm32 as is). +//! +//! Left out: kill facts / Crawler XP settlement, leaderboard, profiles. +//! Added: the global `host` kind (which celld node, isolate and activation +//! run the room, tick numbers) and a hibernation snapshot (mobs, kill +//! counts) that the Durable Object keeps in its storage. + +use std::collections::BTreeMap; + +use distributed_game::{ + schema, ConsumePolicy, Ctx, Entities, Entity, EntityId, EntitySchema, GameEvent, GameInput, + LeaveReason, ObserverId, PlayerId, Project, Replicated, View, Zone, +}; +use game_sim::arena::{self as movement, MoveState, PILLARS, PLAYER_RADIUS}; +pub use game_sim::mobpit::{pit_step, PitInput}; +use serde::{Deserialize, Serialize}; + +/// Entity id of the zone's HUD view (as in Mob Pit). +pub const PIT_ENTITY: EntityId = EntityId(900); +/// Entity id of the host view (spike only). +pub const HOST_ENTITY: EntityId = EntityId(901); + +/// A player (Mob Pit's `player` kind, id 1). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0, of = Player)] +pub struct PlayerView { + #[field_type(movement::POS)] + #[correct(ease = 150)] + #[from(state.x)] + pub x: f32, + #[field_type(movement::POS)] + #[correct(ease = 150)] + #[from(state.y)] + pub y: f32, + #[field_type(movement::VEL)] + #[correct(snap)] + #[from(state.vx)] + pub vx: f32, + #[field_type(movement::VEL)] + #[correct(snap)] + #[from(state.vy)] + pub vy: f32, + #[correct(snap)] + #[from(state.dash)] + pub dash: u8, + #[correct(snap)] + #[from(state.cd)] + pub cd: u8, + #[priority(0.2)] + #[correct(replace)] + #[from] + pub name: String, + #[correct(replace)] + pub hp: u8, + #[angle(bits = 8)] + #[correct(replace)] + #[from] + pub face: f32, + #[correct(replace)] + pub swing: u8, + /// Kills by this player in this room (persisted with the room). + #[correct(replace)] + pub level: u16, + #[correct(replace)] + pub dead: bool, +} + +/// A mob (Mob Pit's `mob` kind, id 2). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "mob", id = 2, of = Mob)] +pub struct MobView { + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + #[from] + pub x: f32, + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + #[from] + pub y: f32, + #[angle(bits = 8)] + #[from] + pub face: f32, + #[from] + pub tier: u8, + pub hp: u8, + pub state: u8, + pub tele: u8, +} + +/// A pillar (the Arena's `pillar` kind, id 3). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pillar", id = 3, global, of = Pillar)] +pub struct PillarView { + #[from] + pub x: f32, + #[from] + pub y: f32, + #[from] + pub r: f32, +} + +/// Room numbers (global). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pit", id = 4, global, of = Pit)] +pub struct PitView { + /// Kills in this room since it was first created (persisted). + pub kills: u32, + /// Ticks this room has simulated across all activations (persisted). + pub ticks: u32, +} + +/// Where the room runs (global, spike only): set by the Durable Object. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "host", id = 5, global, of = HostInfo)] +pub struct HostView { + /// celld node id (`CELLD_NODE`), found through the operator listeners. + #[from] + pub node: String, + /// Random id of the V8 isolate (module instance) running the room. + #[from] + pub isolate: String, + /// Random id of this activation of the object (new on every wake). + #[from] + pub activation: String, + /// Activations of this room so far (persisted). + #[from] + pub activations: u32, + /// The room was restored from storage on this activation. + #[from] + pub restored: bool, + /// Cold start: object constructor to first tick (ms). + #[from] + pub wake_ms: u32, + /// Tick rate (Hz). + #[from] + pub hz: u8, + /// Loop wake lateness EMA (ms; how late the timer fired). + #[from] + pub late_ms: f32, + /// Max lateness over the last second (ms). + #[from] + pub late_max_ms: f32, + /// Work per loop iteration EMA (µs: advance + sends). + #[from] + pub work_us: u32, + /// Rooms resident in the same isolate. + #[from] + pub isolate_rooms: u16, +} + +/// A static pillar (the Arena's floor). +pub struct Pillar { + id: EntityId, + pub x: f32, + pub y: f32, + pub r: f32, +} + +impl Pillar { + fn all() -> Vec { + PILLARS + .iter() + .enumerate() + .map(|(i, &(x, y, r))| Pillar { + id: EntityId(100 + i as u32), + x, + y, + r, + }) + .collect() + } +} + +impl Entity for Pillar { + fn entity_id(&self) -> EntityId { + self.id + } +} + +/// The host info the Durable Object keeps current. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HostInfo { + pub node: String, + pub isolate: String, + pub activation: String, + pub activations: u32, + pub restored: bool, + pub wake_ms: u32, + pub hz: u8, + pub late_ms: f32, + pub late_max_ms: f32, + pub work_us: u32, + pub isolate_rooms: u16, +} + +impl Entity for HostInfo { + fn entity_id(&self) -> EntityId { + HOST_ENTITY + } +} + +/// Mob Pit's events (ids as in Mob Pit; `Kill` trimmed). +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum PitEvent { + #[game_event(id = 1)] + Hello { + entity: u32, + half: f32, + boot: String, + attack_range: f32, + attack_arc_cos: f32, + }, + #[game_event(id = 3)] + Kill { + mob: u32, + tier: u8, + killer: u32, + killer_name: String, + /// The killer's kills in this room. + kills: u32, + }, + #[game_event(id = 6)] + Died { respawn_ms: u32 }, +} + +pub const ATTACK_RANGE: f32 = 2.2; +pub const ATTACK_ARC_COS: f32 = 0.5; +pub const ATTACK_DAMAGE: i32 = 10; +pub const SWING_COOLDOWN: u8 = 13; +const SWING_FRAMES: u8 = 6; +pub const PLAYER_HP: i32 = 100; +pub const MOBS: usize = 12; +const MAX_CREDITS: u8 = 4; +const VIEW_RADIUS: f32 = 40.0; +const AGGRO: f32 = 7.0; +const LEASH: f32 = 15.0; +const WINDUP_TICKS: u16 = 24; +const RECOVER_TICKS: u16 = 18; +const RESPAWN_TICKS: u64 = 120; +const PLAYER_RESPAWN_TICKS: u64 = 90; + +fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { + match tier { + 3 => (100, 3.3, 24, 0.8, 2.6), + 2 => (60, 2.4, 16, 0.7, 2.2), + _ => (30, 3.0, 9, 0.5, 1.8), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum MobState { + Idle = 0, + Chase = 1, + Windup = 2, + Recover = 3, + Return = 4, + Dead = 5, +} + +#[derive(Serialize, Deserialize)] +struct Mob { + id: u32, + tier: u8, + home: (f32, f32), + x: f32, + y: f32, + face: f32, + hp: i32, + state: MobState, + timer: u16, + #[serde(skip)] + target: Option, + generation: u32, + respawn_at: u64, + wander: (f32, f32), +} + +struct Player { + id: EntityId, + principal: String, + name: String, + state: MoveState, + credits: u8, + hp: i32, + face: f32, + swing_cd: u8, + swing_anim: u8, + dead_until: Option, + regen: u8, + kills: u32, +} + +/// The persisted part of a room. +#[derive(Serialize, Deserialize)] +struct Snapshot { + mobs: Vec, + kills: u32, + ticks: u64, + activations: u32, + kills_by: BTreeMap, +} + +/// One Mob Pit room. +pub struct Pit { + players: BTreeMap, + mobs: Vec, + pillars: Vec, + /// Lifetime kills (persisted). + pub kills: u32, + /// Lifetime ticks (persisted; this activation adds `ctx.tick()`). + pub ticks_before: u64, + tick: u64, + /// Kills per principal (persisted). + pub kills_by: BTreeMap, + /// Activations including this one (persisted). + pub activations: u32, + /// Host info (set by the Durable Object). + pub host: HostInfo, +} + +fn mob_layout() -> Vec<(u8, (f32, f32))> { + (0..MOBS) + .map(|i| { + let ring = if i % 2 == 0 { 11.5 } else { 16.0 }; + let a = (i as f32 + 0.5) / MOBS as f32 * std::f32::consts::TAU; + let tier = match i { + 0 => 3, + 3 | 6 | 9 | 11 => 2, + _ => 1, + }; + (tier, (ring * a.cos(), ring * a.sin())) + }) + .collect() +} + +fn spawn_point(player: PlayerId) -> (f32, f32) { + const SPOTS: [(f32, f32); 6] = [ + (-4.5, -4.5), + (4.5, -4.5), + (4.5, 4.5), + (-4.5, 4.5), + (0.0, -5.5), + (0.0, 5.5), + ]; + SPOTS[player.0 as usize % SPOTS.len()] +} + +fn push_out_of_pillars(x: &mut f32, y: &mut f32, radius: f32) { + for (px, py, pr) in PILLARS { + let (ox, oy) = (*x - px, *y - py); + let d2 = ox * ox + oy * oy; + let min = radius + pr; + if d2 < min * min { + let d = d2.sqrt().max(1e-4); + *x = px + ox / d * min; + *y = py + oy / d * min; + } + } + let lim = movement::HALF - radius; + *x = x.clamp(-lim, lim); + *y = y.clamp(-lim, lim); +} + +fn step_toward(x: &mut f32, y: &mut f32, tx: f32, ty: f32, stride: f32) -> f32 { + let (dx, dy) = (tx - *x, ty - *y); + let d = (dx * dx + dy * dy).sqrt(); + if d > 1e-4 { + let s = stride.min(d); + *x += dx / d * s; + *y += dy / d * s; + } + dy.atan2(dx) +} + +fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { + ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() +} + +impl Pit { + /// Lifetime ticks. + pub fn ticks(&self) -> u64 { + self.ticks_before + self.tick + } + + /// Kills of one principal in this room. + pub fn kills_of(&self, principal: &str) -> u32 { + self.kills_by.get(principal).copied().unwrap_or(0) + } + + fn step_players(&mut self, ctx: &mut Ctx<'_, Self>) -> Vec<(PlayerId, f32, f32, f32)> { + let tick = ctx.tick(); + let mut swings = Vec::new(); + for (id, p) in &mut self.players { + p.credits = (p.credits + 1).min(MAX_CREDITS); + p.swing_cd = p.swing_cd.saturating_sub(1); + p.swing_anim = p.swing_anim.saturating_sub(1); + if let Some(until) = p.dead_until { + let _ = ctx.take_inputs(*id, ConsumePolicy::Drain); + if tick >= until { + let (x, y) = spawn_point(*id); + p.state = MoveState { + x, + y, + ..MoveState::default() + }; + p.hp = PLAYER_HP; + p.dead_until = None; + } + continue; + } + while p.credits > 0 { + let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { + break; + }; + let input = input.input; + p.state = pit_step(&p.state, &input, &(), movement::DT); + p.credits -= 1; + let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); + if sx * sx + sy * sy > 20.0 * 20.0 { + p.face = sy.atan2(sx); + } + if input.attack() && p.swing_cd == 0 { + p.swing_cd = SWING_COOLDOWN; + p.swing_anim = SWING_FRAMES; + swings.push((*id, p.state.x, p.state.y, p.face)); + } + } + p.regen = p.regen.wrapping_add(1); + if p.regen % 15 == 0 && p.hp < PLAYER_HP { + p.hp += 1; + } + ctx.set_view(*id, View::new(p.state.x, p.state.y, VIEW_RADIUS)); + } + swings + } + + fn resolve_swings(&mut self, ctx: &mut Ctx<'_, Self>, swings: Vec<(PlayerId, f32, f32, f32)>) { + for (player, x, y, face) in swings { + let (fx, fy) = (face.cos(), face.sin()); + for i in 0..self.mobs.len() { + let m = &mut self.mobs[i]; + if m.state == MobState::Dead { + continue; + } + let (_, _, _, radius, _) = tier_stats(m.tier); + let (dx, dy) = (m.x - x, m.y - y); + let d = (dx * dx + dy * dy).sqrt(); + if d > ATTACK_RANGE + radius { + continue; + } + let cos = if d < 1e-3 { + 1.0 + } else { + (dx * fx + dy * fy) / d + }; + if cos < ATTACK_ARC_COS && d > radius + PLAYER_RADIUS { + continue; + } + m.hp -= ATTACK_DAMAGE; + if matches!(m.state, MobState::Idle | MobState::Return) { + m.state = MobState::Chase; + m.target = Some(player); + } + if m.hp <= 0 { + m.hp = 0; + m.state = MobState::Dead; + m.respawn_at = ctx.tick() + RESPAWN_TICKS; + m.target = None; + let (mob, tier) = (m.id, m.tier); + self.kills += 1; + if let Some(p) = self.players.get_mut(&player) { + let kills = self.kills_by.entry(p.principal.clone()).or_default(); + *kills += 1; + let kills = *kills; + p.kills = kills; + ctx.broadcast(&PitEvent::Kill { + mob, + tier, + killer: p.id.get(), + killer_name: p.name.clone(), + kills, + }); + } + } + } + } + } + + fn step_mobs(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + let tick = ctx.tick(); + let living: Vec<(PlayerId, f32, f32)> = self + .players + .iter() + .filter(|(_, p)| p.dead_until.is_none()) + .map(|(id, p)| (*id, p.state.x, p.state.y)) + .collect(); + let mut hits: Vec<(PlayerId, i32)> = Vec::new(); + for i in 0..self.mobs.len() { + let (max_hp, speed, damage, radius, tele) = tier_stats(self.mobs[i].tier); + let target_pos = |t: Option| { + t.and_then(|t| living.iter().find(|(id, _, _)| *id == t)) + .map(|(_, x, y)| (*x, *y)) + }; + let m = &mut self.mobs[i]; + match m.state { + MobState::Dead => { + if tick >= m.respawn_at { + m.generation += 1; + m.hp = max_hp; + (m.x, m.y) = m.home; + m.state = MobState::Idle; + } + continue; + } + MobState::Idle => { + let nearest = living + .iter() + .map(|(id, x, y)| (*id, dist((m.x, m.y), (*x, *y)))) + .filter(|(_, d)| *d < AGGRO) + .min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((id, _)) = nearest { + m.state = MobState::Chase; + m.target = Some(id); + } else if dist((m.x, m.y), m.wander) < 0.3 { + let a = ctx.rng().next_f32() * std::f32::consts::TAU; + let r = ctx.rng().next_f32() * 2.5; + let m = &mut self.mobs[i]; + m.wander = (m.home.0 + r * a.cos(), m.home.1 + r * a.sin()); + } else { + let (wx, wy) = m.wander; + m.face = step_toward(&mut m.x, &mut m.y, wx, wy, 1.0 * dt); + } + } + MobState::Chase => match target_pos(m.target) { + Some((tx, ty)) if dist(m.home, (m.x, m.y)) < LEASH => { + let reach = radius + PLAYER_RADIUS + 0.6; + if dist((m.x, m.y), (tx, ty)) <= reach { + m.state = MobState::Windup; + m.timer = WINDUP_TICKS; + m.face = (ty - m.y).atan2(tx - m.x); + } else { + m.face = step_toward(&mut m.x, &mut m.y, tx, ty, speed * dt); + } + } + _ => { + m.state = MobState::Return; + m.target = None; + } + }, + MobState::Windup => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + for (id, x, y) in &living { + if dist((m.x, m.y), (*x, *y)) <= tele + PLAYER_RADIUS * 0.5 { + hits.push((*id, damage)); + } + } + m.state = MobState::Recover; + m.timer = RECOVER_TICKS; + } + } + MobState::Recover => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + m.state = MobState::Chase; + } + } + MobState::Return => { + let (hx, hy) = m.home; + m.face = step_toward(&mut m.x, &mut m.y, hx, hy, speed * 1.3 * dt); + m.hp = (m.hp + 1).min(max_hp); + if dist((m.x, m.y), m.home) < 0.3 { + m.state = MobState::Idle; + m.wander = m.home; + } + } + } + let m = &mut self.mobs[i]; + push_out_of_pillars(&mut m.x, &mut m.y, radius); + } + for i in 0..self.mobs.len() { + for j in (i + 1)..self.mobs.len() { + let (a, b) = (&self.mobs[i], &self.mobs[j]); + if a.state == MobState::Dead || b.state == MobState::Dead { + continue; + } + let min = tier_stats(a.tier).3 + tier_stats(b.tier).3; + let (dx, dy) = (b.x - a.x, b.y - a.y); + let d = (dx * dx + dy * dy).sqrt(); + if d < min && d > 1e-4 { + let push = (min - d) * 0.5; + let (nx, ny) = (dx / d * push, dy / d * push); + self.mobs[i].x -= nx; + self.mobs[i].y -= ny; + self.mobs[j].x += nx; + self.mobs[j].y += ny; + } + } + } + for (id, damage) in hits { + let Some(p) = self.players.get_mut(&id) else { + continue; + }; + if p.dead_until.is_some() { + continue; + } + p.hp -= damage; + if p.hp <= 0 { + p.hp = 0; + p.state.vx = 0.0; + p.state.vy = 0.0; + p.dead_until = Some(tick + PLAYER_RESPAWN_TICKS); + for m in &mut self.mobs { + if m.target == Some(id) { + m.target = None; + } + } + ctx.send( + id, + &PitEvent::Died { + respawn_ms: (PLAYER_RESPAWN_TICKS * 1000 / 30) as u32, + }, + ); + } + } + } +} + +impl Zone for Pit { + type Config = (); + type Input = PitInput; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + schema![PlayerView, MobView, PillarView, PitView, HostView] + } + + fn entities() -> Entities { + Entities::new() + .each(|z: &Self| &z.players) + .each(|z: &Self| &z.mobs) + .each(|z: &Self| &z.pillars) + .one(|z: &Self| z) + .one(|z: &Self| &z.host) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + let mobs = mob_layout() + .into_iter() + .enumerate() + .map(|(i, (tier, home))| Mob { + id: i as u32 + 1, + tier, + home, + x: home.0, + y: home.1, + face: 0.0, + hp: tier_stats(tier).0, + state: MobState::Idle, + timer: 0, + target: None, + generation: 0, + respawn_at: 0, + wander: home, + }) + .collect(); + Self { + players: BTreeMap::new(), + mobs, + pillars: Pillar::all(), + kills: 0, + ticks_before: 0, + tick: 0, + kills_by: BTreeMap::new(), + activations: 1, + host: HostInfo::default(), + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let (principal, name) = ctx + .player(player) + .map(|p| (p.principal.clone(), p.name.clone())) + .unwrap_or_default(); + let name = name.unwrap_or_else(|| principal.clone()); + let kills = self.kills_of(&principal); + let (x, y) = spawn_point(player); + let entity = EntityId(1000 + player.0); + self.players.insert( + player, + Player { + id: entity, + principal, + name, + state: MoveState { + x, + y, + ..MoveState::default() + }, + credits: MAX_CREDITS, + hp: PLAYER_HP, + face: 0.0, + swing_cd: 0, + swing_anim: 0, + dead_until: None, + regen: 0, + kills, + }, + ); + ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); + ctx.send( + player, + &PitEvent::Hello { + entity: entity.get(), + half: movement::HALF, + boot: self.host.activation.clone(), + attack_range: ATTACK_RANGE, + attack_arc_cos: ATTACK_ARC_COS, + }, + ); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.players.remove(&player); + for m in &mut self.mobs { + if m.target == Some(player) { + m.target = None; + } + } + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + PitInput::from_payload(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.tick = ctx.tick(); + let swings = self.step_players(ctx); + self.resolve_swings(ctx, swings); + self.step_mobs(ctx); + } + + fn hibernate(&self) -> Option> { + #[derive(Serialize)] + struct SnapshotRef<'a> { + mobs: &'a [Mob], + kills: u32, + ticks: u64, + activations: u32, + kills_by: &'a BTreeMap, + } + serde_json::to_vec(&SnapshotRef { + mobs: &self.mobs, + kills: self.kills, + ticks: self.ticks(), + activations: self.activations, + kills_by: &self.kills_by, + }) + .ok() + } + + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { + let Ok(snapshot) = serde_json::from_slice::(state) else { + return; + }; + // Respawn timers are tick numbers of the old activation. + self.mobs = snapshot + .mobs + .into_iter() + .map(|mut m| { + m.respawn_at = m + .respawn_at + .saturating_sub(snapshot.ticks.min(m.respawn_at)); + if m.state != MobState::Dead { + m.state = MobState::Return; + } + m + }) + .collect(); + self.kills = snapshot.kills; + self.ticks_before = snapshot.ticks; + self.activations = snapshot.activations + 1; + self.kills_by = snapshot.kills_by; + } +} + +impl Entity for Player { + fn entity_id(&self) -> EntityId { + self.id + } +} + +impl Project for Player { + fn view(&self) -> Option { + Some(PlayerView::project( + self, + PlayerViewRest { + hp: self.hp.clamp(0, 255) as u8, + swing: self.swing_anim, + level: self.kills.min(u32::from(u16::MAX)) as u16, + dead: self.dead_until.is_some(), + }, + )) + } +} + +impl Entity for Mob { + fn entity_id(&self) -> EntityId { + EntityId(self.id) + } +} + +impl Project for Mob { + fn view(&self) -> Option { + if self.state == MobState::Dead { + return None; + } + let max_hp = tier_stats(self.tier).0; + let tele = if self.state == MobState::Windup { + 255 - (u32::from(self.timer) * 255 / u32::from(WINDUP_TICKS)) + } else { + 0 + }; + Some(MobView::project( + self, + MobViewRest { + hp: (self.hp.max(0) * 100 / max_hp) as u8, + state: self.state as u8, + tele: tele as u8, + }, + )) + } +} + +impl Entity for Pit { + fn entity_id(&self) -> EntityId { + PIT_ENTITY + } +} + +impl Project for Pit { + fn view(&self) -> Option { + Some(PitView::project( + self, + PitViewRest { + kills: self.kills, + ticks: self.ticks().min(u64::from(u32::MAX)) as u32, + }, + )) + } +} diff --git a/examples/game/zone-do-spike/tools/baseline.mjs b/examples/game/zone-do-spike/tools/baseline.mjs new file mode 100644 index 000000000..5809396a4 --- /dev/null +++ b/examples/game/zone-do-spike/tools/baseline.mjs @@ -0,0 +1,5 @@ +// Noise floor: setTimeout 30 Hz loop lateness in a plain Node process. +const hz = Number(process.argv[2] ?? 30), secs = Number(process.argv[3] ?? 15), step = 1000 / hz; +const start = performance.now(); const late = []; let k = 1; +function tick() { const now = performance.now(); late.push(now - (start + (k - 1) * step)); k = Math.floor((now - start) / step) + 2; if (now - start < secs * 1000) setTimeout(tick, Math.max(0, start + (k - 1) * step - performance.now())); else { late.shift(); const s = late.sort((a, b) => a - b); console.log(JSON.stringify({ baselineNodeTimer: { hz, p50: +s[Math.floor(s.length / 2)].toFixed(2), p99: +s[Math.floor(s.length * 0.99)].toFixed(2), max: +s.at(-1).toFixed(2) } })); } } +setTimeout(tick, step); diff --git a/examples/game/zone-do-spike/tools/bench.ts b/examples/game/zone-do-spike/tools/bench.ts new file mode 100644 index 000000000..1d5e99ef2 --- /dev/null +++ b/examples/game/zone-do-spike/tools/bench.ts @@ -0,0 +1,166 @@ +// Spike gr-p42 measurements with raw protocol bots (no rendering). +// +// node bench.mjs join join phase timings +// node bench.mjs rtt [n] Ping/Pong RTT through +// node bench.mjs load [hz] [pids] +// one bot per room (moves + attacks at 30 Hz); all rooms first touched +// through so celld places them on that node. Reports the +// rooms' own loop timing (/rooms//stats), Delta inter-arrival at +// the bots and the node processes' CPU (ps) while loaded. +import { execFileSync } from 'node:child_process'; +import { decodeServerMessage, encodeClientMessage, encodePayload, type PayloadLayout } from '../../../../js/src/game/index.ts'; + +const INPUT: PayloadLayout = [['mx', { type: 'i8' }], ['my', { type: 'i8' }], ['buttons', { type: 'u8' }]]; +const TAG_DELTA = 0x81; // GameMessageTag.DELTA +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const q = (a: number[], p: number) => { if (!a.length) return NaN; const s = [...a].sort((x, y) => x - y); return +s[Math.round(p * (s.length - 1))].toFixed(2); }; +const summary = (a: number[]) => ({ n: a.length, p50: q(a, 0.5), p99: q(a, 0.99), max: q(a, 1) }); + +type Bot = { ws: WebSocket; deltas: number[]; pongs: Map void>; seq: number; timings: Record }; + +async function bot(base: string, room: string, name: string): Promise { + const t0 = performance.now(); + const r = await fetch(`${base}/ticket?room=${encodeURIComponent(room)}&name=${name}`); + const { ticket } = (await r.json()) as { ticket: string }; + const tTicket = performance.now(); + const ws = new WebSocket(`${base.replace(/^http/, 'ws')}/rooms/${encodeURIComponent(room)}`); + ws.binaryType = 'arraybuffer'; + const b: Bot = { ws, deltas: [], pongs: new Map(), seq: 0, timings: {} }; + await new Promise((ok, fail) => { ws.onopen = () => ok(); ws.onerror = () => fail(new Error(`ws error ${room}`)); }); + const tOpen = performance.now(); + ws.send(encodeClientMessage({ type: 'Hello', protocolVersion: 1, contentVersion: '', capabilities: 0, ticket, reconnectToken: '' })); + await new Promise((ok, fail) => { + let welcomed = false; + ws.onclose = (e) => { if (!welcomed) fail(new Error(`closed ${e.code} ${e.reason}`)); }; + ws.onmessage = (e) => { + const bytes = new Uint8Array(e.data as ArrayBuffer); + const now = performance.now(); + if (bytes[0] === TAG_DELTA) { b.deltas.push(now); if (!b.timings.firstDelta) b.timings.firstDelta = now - t0; return; } + const m = decodeServerMessage(bytes); + if (m.type === 'Welcome') { welcomed = true; b.timings.welcome = now - t0; ok(); } + if (m.type === 'Pong') b.pongs.get(m.clientTime)?.(now); + if (m.type === 'Error') fail(new Error(`error ${m.code} ${m.message}`)); + }; + }); + b.timings.ticket = tTicket - t0; + b.timings.open = tOpen - tTicket; + b.timings.hello = b.timings.welcome - (tOpen - t0); + return b; +} + +function ping(b: Bot): Promise { + const t = performance.now(); + return new Promise((ok) => { b.pongs.set(t, (now) => { b.pongs.delete(t); ok(now - t); }); b.ws.send(encodeClientMessage({ type: 'Ping', clientTime: t })); }); +} + +function drive(b: Bot, phase: number) { + let k = phase; + return setInterval(() => { + k++; + const a = k / 40; + b.seq++; + b.ws.send(encodeClientMessage({ type: 'Input', seq: b.seq, clientTick: b.seq, payload: encodePayload(INPUT, { mx: Math.round(Math.cos(a) * 100), my: Math.round(Math.sin(a) * 100), buttons: 2 }) })); + }, 1000 / 30); +} + +function cpu(pids: string[]) { + if (!pids.length) return []; + const out = execFileSync('ps', ['-o', 'pid=,%cpu=,rss=', '-p', pids.join(',')]).toString().trim().split('\n'); + return out.map((l) => { const [pid, c, rss] = l.trim().split(/\s+/); return { pid, cpu: +c, rssMb: Math.round(+rss / 1024) }; }); +} + +const [mode, base, room, ...rest] = process.argv.slice(2); +if (mode === 'join') { + // Warm the Node HTTP/WebSocket stack (its first use costs 50-500 ms). + const w = await bot(base, 'warmup', 'w'); + w.ws.close(); + for (const r of room.split(',')) { + const b = await bot(base, r, 'joiner'); + await sleep(200); + console.log(JSON.stringify({ room: r, via: base, ...Object.fromEntries(Object.entries(b.timings).map(([k, v]) => [k, +v.toFixed(1)])) })); + b.ws.close(); + } +} else if (mode === 'wake') { + // wake : create n rooms + // through the owner (fresh activation), leave, wait for eviction, then + // rejoin each (even through the owner, odd through ). + const [n, waitS, other] = rest; + const w = await bot(base, 'warmup', 'w'); w.ws.close(); + const w2 = await bot(other, 'warmup', 'w'); w2.ws.close(); + const tag = Date.now().toString(36); + const rooms = Array.from({ length: Number(n) }, (_, i) => `${room}-${tag}-${i}`); + const fresh: number[] = []; + const before: Record = {}; const after: Record = {}; const moved: string[] = []; + const ownerOf = async (r: string) => ((await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any).node as string; + const first: string[] = []; + for (const r of rooms) { const b = await bot(base, r, 'x'); fresh.push(b.timings.welcome); await sleep(300); const o = await ownerOf(r); first.push(o); before[o] = (before[o] ?? 0) + 1; b.ws.close(); } + await sleep(Number(waitS) * 1000); + const viaOwner: number[] = []; const viaOther: number[] = []; const restored: boolean[] = []; + for (const [i, r] of rooms.entries()) { + const b = await bot(i % 2 ? other : base, r, 'x'); + (i % 2 ? viaOther : viaOwner).push(b.timings.welcome); + b.ws.close(); + const st = await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json() as any; + restored.push(st.restored && st.activations === 2); + after[st.node] = (after[st.node] ?? 0) + 1; + if (st.node !== first[i]) moved.push(`${r}:${first[i]}->${st.node}`); + } + console.log(JSON.stringify({ fresh: summary(fresh), wakeViaOwner: summary(viaOwner), wakeViaOther: summary(viaOther), restoredAll: restored.every(Boolean), restored: restored.filter(Boolean).length, ownersBefore: before, ownersAfter: after, moved: moved.length, movedRooms: moved.slice(0, 5) })); +} else if (mode === 'rtt') { + const n = Number(rest[0] ?? 200); + const b = await bot(base, room, 'pinger'); + const rtts: number[] = []; + const t0 = performance.now(); const spikes: string[] = []; + for (let i = 0; i < n; i++) { const r = await ping(b); rtts.push(r); if (r > 15) spikes.push(`${((performance.now() - t0) / 1000).toFixed(2)}s:${r.toFixed(0)}`); await sleep(10); } + if (process.env.SPIKES) console.log('spikes', spikes.join(' ')); + const st = await (await fetch(`${base}/rooms/${encodeURIComponent(room)}/stats`)).json() as any; + console.log(JSON.stringify({ room, via: base, owner: st.node, rtt: summary(rtts) })); + b.ws.close(); +} else if (mode === 'load') { + const [count, secs, hz = '30', pidList = ''] = rest; + const pids = pidList ? pidList.split(',') : []; + const rooms = Array.from({ length: Number(count) }, (_, i) => `${room}-${i}@${hz}`); + const bots: Bot[] = []; + const t0 = performance.now(); + for (let i = 0; i < rooms.length; i += 20) { + bots.push(...(await Promise.all(rooms.slice(i, i + 20).map((r, j) => bot(base, r, `b${i + j}`))))); + } + const joinS = (performance.now() - t0) / 1000; + const timers = bots.map((b, i) => drive(b, i * 7)); + await sleep(3000); + await Promise.all(rooms.map((r) => fetch(`${base}/rooms/${encodeURIComponent(r)}/stats?reset=1`).catch(() => undefined))); + for (const b of bots) b.deltas.length = 0; + const samples: ReturnType[] = []; + const end = Date.now() + Number(secs) * 1000; + while (Date.now() < end) { await sleep(1000); samples.push(cpu(pids)); } + const fetched = await Promise.all(rooms.map(async (r) => { try { return await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json() as any; } catch { return undefined; } })); + const stats = fetched.filter(Boolean); + if (stats.length < rooms.length) console.log(`stats unavailable for ${rooms.length - stats.length} rooms`); + const rtts: number[] = []; + for (const b of bots.slice(0, 10)) rtts.push(await ping(b)); + timers.forEach(clearInterval); + const late99 = stats.map((s) => s.late_ms.p99); + const late50 = stats.map((s) => s.late_ms.p50); + const interval = stats.map((s) => s.interval_ms.p99); + const dropped = stats.reduce((a, s) => a + s.dropped_ticks, 0); + const catchUp = stats.reduce((a, s) => a + s.catch_up_iterations, 0); + const iterations = stats.reduce((a, s) => a + s.iterations, 0); + const arrivals = bots.flatMap((b) => b.deltas.slice(1).map((t, i) => t - b.deltas[i])); + const nodes: Record = {}; + for (const s of stats) nodes[s.node] = (nodes[s.node] ?? 0) + 1; + const isolates = new Set(stats.map((s) => s.isolate)).size; + const cpuByPid: Record = {}; + for (const s of samples) for (const c of s) (cpuByPid[c.pid] ??= []).push(c.cpu); + console.log(JSON.stringify({ + rooms: rooms.length, hz: Number(hz), secs: Number(secs), joinS: +joinS.toFixed(1), nodes, isolates, + lateP50_median: q(late50, 0.5), lateP99_median: q(late99, 0.5), lateP99_worstRoom: q(late99, 1), + intervalP99_median: q(interval, 0.5), droppedTicks: dropped, catchUpIterations: catchUp, iterations, + expectedIterations: Math.round(rooms.length * Number(hz) * Number(secs)), + deltaArrival: summary(arrivals), pingUnderLoad: summary(rtts), + cpu: Object.fromEntries(Object.entries(cpuByPid).map(([p, a]) => [p, { avg: +(a.reduce((x, y) => x + y, 0) / a.length).toFixed(1), max: Math.max(...a) }])), + rss: samples.at(-1) + })); + for (const b of bots) b.ws.close(); + await sleep(500); +} +process.exit(0); diff --git a/examples/game/zone-do-spike/tools/drain.ts b/examples/game/zone-do-spike/tools/drain.ts new file mode 100644 index 000000000..f5be9ae94 --- /dev/null +++ b/examples/game/zone-do-spike/tools/drain.ts @@ -0,0 +1,28 @@ +// Graceful node stop: create rooms through , leave, wait for +// eviction, print READY (operator stops that node with SIGTERM), then +// rejoin each through and report where it runs now. +import { connectRoom } from '../page/room-client.ts'; +const [ownerBase, entry, n, waitS] = process.argv.slice(2); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const tag = Date.now().toString(36); +const rooms = Array.from({ length: Number(n) }, (_, i) => `dr-${tag}-${i}`); +const node = async (base: string, r: string) => ((await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any); +const before: Record = {}; +for (const r of rooms) { + const rc = connectRoom(ownerBase, r, 'd'); await rc.welcome; await sleep(400); rc.close(); + const st = await node(ownerBase, r); before[st.node] = (before[st.node] ?? 0) + 1; +} +console.log('placed', JSON.stringify(before)); +await sleep(Number(waitS) * 1000); +console.log('READY'); +for (let i = 0; i < 200 && !(await fetch(`${ownerBase}/ticket`).then(() => false, () => true)); i++) await sleep(100); +const t0 = performance.now(); +const after: Record = {}; let restored = 0; const waits: number[] = []; +for (const r of rooms) { + const t = performance.now(); + for (;;) { try { const rc = connectRoom(entry, r, 'd'); await rc.welcome; rc.close(); break; } catch { await sleep(200); } } + waits.push(performance.now() - t); + const st = await node(entry, r); after[st.node] = (after[st.node] ?? 0) + 1; if (st.restored) restored++; +} +console.log('after stop', JSON.stringify({ owners: after, restored, rooms: rooms.length, firstRejoinMs: Math.round(waits[0]), allRejoinedS: +((performance.now() - t0) / 1000).toFixed(1) })); +process.exit(0); diff --git a/examples/game/zone-do-spike/tools/failover.ts b/examples/game/zone-do-spike/tools/failover.ts new file mode 100644 index 000000000..7809d5b4b --- /dev/null +++ b/examples/game/zone-do-spike/tools/failover.ts @@ -0,0 +1,48 @@ +// Node failure: a room placed on one node (first touch through ) +// with a player connected through another node (); the +// operator SIGKILLs the owner when this prints READY. The player then +// rejoins through until a room answers again. +// usage: node failover.mjs +import { connectRoom, ATTACK } from '../page/room-client.ts'; +const [ownerBase, entry, room] = process.argv.slice(2); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const log = (...a: unknown[]) => console.log(new Date().toISOString().slice(11, 23), ...a); +// First touch through the owner places the room there. +await (await fetch(`${ownerBase}/rooms/${encodeURIComponent(room)}/stats`)).json(); +const rc = connectRoom(entry, room, 'survivor'); +await rc.welcome; +for (let i = 0; i < 100 && !(rc.host()?.node && rc.host()!.node !== '?'); i++) await sleep(50); +log(`joined ${room} via ${entry}; runs on ${rc.host()?.node}`); +let closedAt = 0; +rc.client.on('zoneClosed', (_z, info) => { closedAt = performance.now(); log('connection closed', JSON.stringify(info)); }); +const fight = setInterval(() => { + const me = rc.me()?.fields as any; const mobs = rc.entities().filter((e) => e.kindName === 'mob').map((e) => e.fields as any); + if (!me || !mobs.length) return; + const t = mobs.sort((a, b) => Math.hypot(a.x - me.x, a.y - me.y) - Math.hypot(b.x - me.x, b.y - me.y))[0]; + const [dx, dy] = [t.x - me.x, t.y - me.y]; const d = Math.hypot(dx, dy) || 1; const s = d < 1.8 ? 30 : 127; + rc.input(Math.round(dx / d * s), Math.round(dy / d * s), ATTACK); +}, 33); +while (rc.kills.length < 3) await sleep(100); +await sleep(6000); // > the room's 5 s persist interval +const before = rc.kills.at(-1)!.kills; +log(`kills before failure: ${before} (persisted at most 5 s ago); READY`); +const t0 = performance.now(); +while (!closedAt && performance.now() - t0 < 60_000) await sleep(20); +clearInterval(fight); +const killDetected = closedAt; +let attempt = 0; +for (;;) { + attempt++; + try { + const r2 = connectRoom(entry, room, 'survivor'); + await r2.welcome; + for (let i = 0; i < 100 && !(r2.host()?.node && r2.host()!.node !== '?' && r2.me()); i++) await sleep(50); + const h = r2.host()!; const me = r2.me()?.fields as any; + log(`rejoined after ${((performance.now() - killDetected) / 1000).toFixed(2)} s (${attempt} attempts): node=${h.node} activation #${h.activations} restored=${h.restored}; my kills ${me?.level} (had ${before})`); + r2.close(); break; + } catch (e) { + if (attempt % 10 === 1) log(`attempt ${attempt}: ${String(e).slice(0, 120)}`); + await sleep(250); + } +} +process.exit(0); diff --git a/examples/game/zone-do-spike/tools/headless.ts b/examples/game/zone-do-spike/tools/headless.ts new file mode 100644 index 000000000..545a37e1a --- /dev/null +++ b/examples/game/zone-do-spike/tools/headless.ts @@ -0,0 +1,65 @@ +// Headless check of one room on celld: join, move, attack until a kill, +// leave, wait for eviction, rejoin (possibly via another node) and check +// the room restored its state in a new activation. +// usage: node headless.mjs [rejoin-base-url] [evict-wait-s] +import { connectRoom, ATTACK, type RoomClient } from '../page/room-client.ts'; + +const [base, room, rejoinBase = base, waitS = '25'] = process.argv.slice(2); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const until = async (f: () => T | undefined | false, ms: number, what: string): Promise => { + const end = Date.now() + ms; + for (;;) { const v = f(); if (v) return v; if (Date.now() > end) throw new Error(`timeout: ${what}`); await sleep(20); } +}; +const log = (...a: unknown[]) => console.log(new Date().toISOString().slice(11, 23), ...a); + +async function join(url: string, name: string) { + const t0 = performance.now(); + const rc = connectRoom(url, room, name); + await rc.welcome; + const welcomeMs = performance.now() - t0; + await until(() => rc.host()?.node && rc.host()!.node !== '?' && rc.me(), 5000, 'host node + own player'); + return { rc, welcomeMs }; +} + +async function fight(rc: RoomClient, kills: number) { + const start = rc.kills.length; + const end = Date.now() + 60_000; + let moved = 0; + const at0 = rc.me()!.fields as any; + while (rc.kills.length - start < kills) { + if (Date.now() > end) throw new Error('no kill within 60 s'); + const me = rc.me()?.fields as any; + const mobs = rc.entities().filter((e) => e.kindName === 'mob').map((e) => e.fields as any); + if (me && mobs.length) { + const t = mobs.sort((a, b) => Math.hypot(a.x - me.x, a.y - me.y) - Math.hypot(b.x - me.x, b.y - me.y))[0]; + const [dx, dy] = [t.x - me.x, t.y - me.y]; const d = Math.hypot(dx, dy) || 1; + const near = d < 1.8; + rc.input(near ? Math.round(dx / d * 30) : Math.round(dx / d * 127), near ? Math.round(dy / d * 30) : Math.round(dy / d * 127), ATTACK); + moved = Math.max(moved, Math.hypot(me.x - at0.x, me.y - at0.y)); + } + await sleep(33); + } + return { moved }; +} + +const { rc, welcomeMs } = await join(base, 'bot-ana'); +const h1 = { ...rc.host()! }; +log(`joined ${room} via ${base}: node=${h1.node} isolate=${h1.isolate} activation=${h1.activation} #${h1.activations} restored=${h1.restored} welcome=${welcomeMs.toFixed(1)}ms`); +const kills0 = (rc.entities().find((e) => e.kindName === 'pit')?.fields as any)?.kills; +const { moved } = await fight(rc, 1); +await sleep(500); +const k = rc.kills.at(-1)!; +log(`moved ${moved.toFixed(1)} m, killed mob ${k.mob}; my kills in room=${k.kills}; room kills ${kills0} -> ${(rc.entities().find((e) => e.kindName === 'pit')?.fields as any)?.kills}`); +rc.client.close(); +log(`left; waiting ${waitS}s for the room to persist, stop and be evicted`); +await sleep(Number(waitS) * 1000); +const r2 = await join(rejoinBase, 'bot-ana'); +const h2 = { ...r2.rc.host()! }; +const me2 = r2.rc.me()!.fields as any; +const pit2 = r2.rc.entities().find((e) => e.kindName === 'pit')?.fields as any; +log(`rejoined via ${rejoinBase}: node=${h2.node} isolate=${h2.isolate} activation=${h2.activation} #${h2.activations} restored=${h2.restored} wake=${(h2 as any).wake_ms}ms welcome=${r2.welcomeMs.toFixed(1)}ms`); +log(`restored state: my kills=${me2.level} (expected ${k.kills}), room kills=${pit2?.kills}, lifetime ticks=${pit2?.ticks}`); +const ok = h2.activation !== h1.activation && h2.restored && me2.level === k.kills && pit2?.kills >= k.kills; +r2.rc.client.close(); +log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); diff --git a/examples/game/zone-do-spike/tools/peek.ts b/examples/game/zone-do-spike/tools/peek.ts new file mode 100644 index 000000000..2d4855b6c --- /dev/null +++ b/examples/game/zone-do-spike/tools/peek.ts @@ -0,0 +1,11 @@ +// Print one room's replicated host entity and stats. +import { connectRoom } from '../page/room-client.ts'; +const [base, room] = process.argv.slice(2); +const t0 = performance.now(); +const rc = connectRoom(base, room, 'peek'); +await rc.welcome; +const tw = performance.now() - t0; +for (let i = 0; i < 100 && !(rc.host() as any)?.node; i++) await new Promise((r) => setTimeout(r, 20)); +await new Promise((r) => setTimeout(r, 1500)); +console.log(JSON.stringify({ welcomeMs: +tw.toFixed(1), host: rc.host(), rtt: rc.rtt() })); +rc.client.close(); process.exit(0); diff --git a/examples/game/zone-do-spike/tools/s3-compose.yaml b/examples/game/zone-do-spike/tools/s3-compose.yaml new file mode 100644 index 000000000..b0b1d8e91 --- /dev/null +++ b/examples/game/zone-do-spike/tools/s3-compose.yaml @@ -0,0 +1,13 @@ +# The spike's one S3-compatible store (RustFS) for the celld fleet bucket. +# Compose rather than `docker run`: Dory (this machine's Docker) published +# ports only for containers on a user-defined network. +services: + s3: + image: rustfs/rustfs:1.0.3 + container_name: zone-do-spike-s3 + command: ["/data"] + environment: + RUSTFS_ADDRESS: "0.0.0.0:9000" + RUSTFS_ACCESS_KEY: spikeadmin + RUSTFS_SECRET_KEY: spikesecret123 + ports: ["127.0.0.1:${S3_PORT:-19400}:9000"] diff --git a/examples/game/zone-do-spike/wrangler.jsonc b/examples/game/zone-do-spike/wrangler.jsonc new file mode 100644 index 000000000..70455c401 --- /dev/null +++ b/examples/game/zone-do-spike/wrangler.jsonc @@ -0,0 +1,20 @@ +// Spike gr-p42: Mob Pit rooms as celld Durable Objects. `./run.sh deploy` +// publishes this to the fleet bucket (`celld deploy`); every node runs it. +{ + "name": "zone-do-spike", + "main": "build/worker/shim.mjs", + "compatibility_date": "2026-01-01", + "durable_objects": { + "bindings": [{ "name": "PIT_ROOM", "class_name": "PitRoom" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PitRoom"] }], + "assets": { "directory": "./public", "binding": "ASSETS" }, + "vars": { + // Dev-only ticket key (the spike's /ticket endpoint signs with it). + "TICKET_SECRET": "spike-only-ticket-secret-not-for-production", + "TICK_HZ": "30", + // Operator listeners, only to find out which node runs a room + // (celld does not tell application code its node id). + "NODES": "node-a=127.0.0.1:18201,node-b=127.0.0.1:18202,node-c=127.0.0.1:18203" + } +} From 264b967262c87d1cb9c3f2cd3f11a78d7cecda1a Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 18:08:08 -0500 Subject: [PATCH 260/484] test(spike): crowd mode, many players in one room [[tasks/gr-p42-zones-as-celld-objects-spike]] --- examples/game/zone-do-spike/tools/bench.ts | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/examples/game/zone-do-spike/tools/bench.ts b/examples/game/zone-do-spike/tools/bench.ts index 1d5e99ef2..ba5e61621 100644 --- a/examples/game/zone-do-spike/tools/bench.ts +++ b/examples/game/zone-do-spike/tools/bench.ts @@ -116,6 +116,59 @@ if (mode === 'join') { const st = await (await fetch(`${base}/rooms/${encodeURIComponent(room)}/stats`)).json() as any; console.log(JSON.stringify({ room, via: base, owner: st.node, rtt: summary(rtts) })); b.ws.close(); +} else if (mode === 'crowd') { + // crowd [hz] [pids] [bases]: bots + // in ONE room, joins spread over [bases] (comma list, default ), so + // every bot not on the owner node is forwarded. Reports the room's loop + // timing, per-bot Delta size/interval/bandwidth, ping and node CPU. + const [count, secs, hz = '30', pidList = '', baseList = ''] = rest; + const pids = pidList ? pidList.split(',') : []; + const bases = baseList ? baseList.split(',') : [base]; + const r = `${room}@${hz}`; + const bots: Bot[] = []; + const bytes: number[][] = []; + const t0 = performance.now(); + for (let i = 0; i < Number(count); i += 10) { + const batch = await Promise.all(Array.from({ length: Math.min(10, Number(count) - i) }, (_, j) => bot(bases[(i + j) % bases.length], r, `p${i + j}`))); + for (const b of batch) { + const sizes: number[] = []; + bytes.push(sizes); + const prev = b.ws.onmessage!; + b.ws.onmessage = (e) => { const d = e.data as ArrayBuffer; if (new Uint8Array(d)[0] === TAG_DELTA) sizes.push(d.byteLength); (prev as any).call(b.ws, e); }; + bots.push(b); + } + } + const joinS = (performance.now() - t0) / 1000; + const welcome = bots.map((b) => b.timings.welcome); + const timers = bots.map((b, i) => drive(b, i * 7)); + await sleep(3000); + await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats?reset=1`).catch(() => undefined); + for (const b of bots) b.deltas.length = 0; + for (const s of bytes) s.length = 0; + const samples: ReturnType[] = []; + const end = Date.now() + Number(secs) * 1000; + while (Date.now() < end) { await sleep(1000); samples.push(cpu(pids)); } + const st = (await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any; + const rtts: number[] = []; + for (const b of bots.filter((_, i) => i % 5 === 0)) rtts.push(await ping(b)); + timers.forEach(clearInterval); + const arrivals = bots.flatMap((b) => b.deltas.slice(1).map((t, i) => t - b.deltas[i])); + const sizes = bytes.flat(); + const perBotKBps = bytes.map((s) => s.reduce((a, x) => a + x, 0) / 1024 / Number(secs)); + const cpuByPid: Record = {}; + for (const s of samples) for (const c of s) (cpuByPid[c.pid] ??= []).push(c.cpu); + console.log(JSON.stringify({ + room: r, players: bots.length, connected: bots.filter((b) => b.ws.readyState === 1).length, hz: Number(hz), secs: Number(secs), + joinS: +joinS.toFixed(1), welcome: summary(welcome), owner: st.node, + lateP50: st.late_ms?.p50, lateP99: st.late_ms?.p99, intervalP99: st.interval_ms?.p99, droppedTicks: st.dropped_ticks, + iterations: st.iterations, expectedIterations: Math.round(Number(hz) * Number(secs)), + deltaBytes: summary(sizes), deltaArrival: summary(arrivals), + perBotKBps: summary(perBotKBps), roomOutKBps: +perBotKBps.reduce((a, x) => a + x, 0).toFixed(1), + pingUnderLoad: summary(rtts), + cpu: Object.fromEntries(Object.entries(cpuByPid).map(([p, a]) => [p, { avg: +(a.reduce((x, y) => x + y, 0) / a.length).toFixed(1), max: Math.max(...a) }])) + })); + for (const b of bots) b.ws.close(); + await sleep(500); } else if (mode === 'load') { const [count, secs, hz = '30', pidList = ''] = rest; const pids = pidList ? pidList.split(',') : []; From fd647aa872f337341fccc36a3515f2929563fb08 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:05:35 -0500 Subject: [PATCH 261/484] feat(game)!: celld zone host, zones as Durable Objects distributed_game's `celld-zone` feature hosts any Zone as a celld Durable Object, one object per zone id: celld places, forwards, evicts, rebalances idle objects and recovers crashed ones; game code never names a server. The spike's PitRoom glue becomes framework code: - ZoneObject + celld_zone_object!: hibernatable WebSocket joins (ticket, single-use transfer ticket, reconnect token), a self-correcting deadline tick loop while occupied, snapshots in object storage, dormant -> hibernated by object alarm, restore on wake, 1012 for sockets of an earlier activation, GET .../info debug JSON. - Facts object to object: CelldObjectHost under CommandFactSink, with a durable outbox in object storage (FactQueue journal) so facts reach cells exactly once across crashes. - world::zone_activity: the zone reports active / dormant / hibernated as facts into its ZoneActivity cell; zone_status projects them into zone_activities (ZoneStatus::Dormant, of_activity). - Debug-only node lookup via operator listeners (CELLD_ZONE_NODES), off by default. Breaking: CommandFactSink is portable (feature `cell`) over the new FactHost trait, which replaces FactRouting and the CommandHost bound. The JS GameConnection rejoins with a fresh ticket on close 1012 (GAME_CLOSE_RESTARTED). Tests: celld_zone on celld dev and on a 3-node RustFS fleet (owner killed mid-flight: 1012, recovery elsewhere, 200 facts exactly once), zone_status activity projection, plan unit tests, wasm32 domain check. [[tasks/gr-p43-celld-zone-host]] --- .github/workflows/integration-celld.yaml | 8 + Cargo.toml | 2 +- distributed_game/Cargo.toml | 21 +- distributed_game/README.md | 71 +- distributed_game/src/celld_zone/cells.rs | 189 +++ distributed_game/src/celld_zone/mod.rs | 85 + distributed_game/src/celld_zone/object.rs | 1407 +++++++++++++++++ distributed_game/src/celld_zone/plan.rs | 473 ++++++ distributed_game/src/command_sink.rs | 200 ++- distributed_game/src/facts.rs | 21 + distributed_game/src/host.rs | 10 + distributed_game/src/lib.rs | 7 +- distributed_game/src/world/mod.rs | 13 +- .../save_zone_activity.mutation.graphql | 5 + distributed_game/src/world/zone_activity.rs | 288 ++++ distributed_game/src/world/zone_status.rs | 139 +- distributed_game/tests/celld_zone/main.rs | 420 +++++ distributed_game/tests/support/celld.rs | 37 +- distributed_game/tests/support/fleet.rs | 308 ++++ distributed_game/tests/zone_status/main.rs | 152 ++ js/src/game/connection.ts | 6 + js/src/game/index.ts | 1 + js/src/game/messages.ts | 7 + js/tests/game-connection.test.mjs | 20 + scripts/check-wasm32-domains.sh | 13 +- tests/celld/README.md | 17 + tests/celld/zone-worker/.gitignore | 4 + tests/celld/zone-worker/Cargo.toml | 27 + tests/celld/zone-worker/src/lib.rs | 288 ++++ tests/celld/zone-worker/wrangler.jsonc | 29 + 30 files changed, 4176 insertions(+), 92 deletions(-) create mode 100644 distributed_game/src/celld_zone/cells.rs create mode 100644 distributed_game/src/celld_zone/mod.rs create mode 100644 distributed_game/src/celld_zone/object.rs create mode 100644 distributed_game/src/celld_zone/plan.rs create mode 100644 distributed_game/src/world/mutations/save_zone_activity.mutation.graphql create mode 100644 distributed_game/src/world/zone_activity.rs create mode 100644 distributed_game/tests/celld_zone/main.rs create mode 100644 distributed_game/tests/support/fleet.rs create mode 100644 tests/celld/zone-worker/.gitignore create mode 100644 tests/celld/zone-worker/Cargo.toml create mode 100644 tests/celld/zone-worker/src/lib.rs create mode 100644 tests/celld/zone-worker/wrangler.jsonc diff --git a/.github/workflows/integration-celld.yaml b/.github/workflows/integration-celld.yaml index 5f196a208..2e9b3da62 100644 --- a/.github/workflows/integration-celld.yaml +++ b/.github/workflows/integration-celld.yaml @@ -42,6 +42,7 @@ jobs: tests/celld/worker -> tests/celld/worker/target tests/celld/alarm-worker -> tests/celld/alarm-worker/target tests/celld/fact-worker -> tests/celld/fact-worker/target + tests/celld/zone-worker -> tests/celld/zone-worker/target shared-key: celld-storage - uses: actions/setup-node@v4 with: @@ -82,6 +83,13 @@ jobs: run: | cargo test -p distributed_game --features celld,runtime --test celld_zone_state cargo test -p distributed_game --features celld,net,lease --test world + - name: Build the celld zone host test Worker + working-directory: tests/celld/zone-worker + run: worker-build --release + - name: Zones as celld objects (celld dev; 3-node fleet on RustFS, crash, facts exactly once) + env: + CELLD_ZONE_REQUIRED: "1" + run: cargo test -p distributed_game --features celld,net --test celld_zone - name: Retain storage proof results and logs if: always() uses: actions/upload-artifact@v4 diff --git a/Cargo.toml b/Cargo.toml index 9b341917f..6fdd03778 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] members = ["distributed_macros", "distributed_cli", "distributed_game", "distributed_game_macros"] -exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker", "tests/celld/alarm-worker", "tests/celld/fact-worker", "tests/fixtures/wasm32-native-domain", "examples/game/server"] +exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker", "tests/celld/alarm-worker", "tests/celld/fact-worker", "tests/celld/zone-worker", "tests/fixtures/wasm32-native-domain", "examples/game/server"] resolver = "2" [workspace.package] diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml index 1b101016b..198ed9eab 100644 --- a/distributed_game/Cargo.toml +++ b/distributed_game/Cargo.toml @@ -16,9 +16,9 @@ default = [] runtime = ["dep:tokio"] # Adapter that commits facts into a `distributed` AggregateCell. cell = ["dep:distributed", "dep:sha2", "dep:base64"] -# `command_sink::CommandFactSink`: facts dispatched as -# commands through any command host (a local service over any repository, -# or celld cells). +# `command_sink::CommandFactSink` over `CelldCommandHost` / +# `LocalCommandHost` (a local service over any repository, or celld cells +# over HTTP). The sink itself is portable (`cell`). command-host = ["cell", "distributed/graphql"] # celld clients: `CelldFactSink` (the command sink over a remote-only # `CelldCommandHost`), `CellZoneOwnership`, `CellZoneStateStore`. @@ -26,13 +26,16 @@ celld = ["cell", "command-host", "dep:reqwest", "dep:uuid"] # celld worker glue (wasm32 Durable Objects): `world::zone_state::celld_worker`, # the zone-state HTTP surface over a cell and an R2 bucket binding. workers-rs = ["cell", "dep:worker", "distributed/workers-rs"] +# Zones as celld Durable Objects (wasm32): `celld_zone::ZoneObject`, +# `CelldObjectHost` (facts object to object), `celld_zone_object!`. +celld-zone = ["cell", "ticket", "workers-rs", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"] # Per-zone Prometheus metrics (dependency-free text exposition). metrics = [] # Load-test bots (library + `game-bots` binary). bots = ["net", "dep:tokio-tungstenite", "dep:futures-util", "tokio/rt-multi-thread"] # axum WebSocket zone server with signed-ticket admission (+ /metrics). -# HMAC-signed admission tickets (`ticket`) without the axum server: what a -# celld zone host (wasm32) needs to admit players (spike gr-p42). +# HMAC-signed admission tickets (`ticket`) without the axum server (the +# celld zone host admits players with it). ticket = ["dep:hmac", "dep:sha2", "dep:base64"] net = ["runtime", "metrics", "ticket", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros", "tokio/io-util"] # `world::FencedLeaseOwnership`: zone ownership over `distributed::lease`. @@ -53,6 +56,9 @@ futures-util = { version = "0.3", default-features = false, features = ["sink", reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"], optional = true } uuid = { version = "1", features = ["v7"], optional = true } worker = { version = "0.8", optional = true } +js-sys = { version = "0.3", optional = true } +wasm-bindgen = { version = "0.2", optional = true } +wasm-bindgen-futures = { version = "0.4", optional = true } [dev-dependencies] base64 = "0.23" @@ -121,6 +127,11 @@ name = "celld_facts" path = "tests/celld_facts/main.rs" required-features = ["celld", "runtime"] +[[test]] +name = "celld_zone" +path = "tests/celld_zone/main.rs" +required-features = ["celld", "net"] + [[test]] name = "inbox" path = "tests/inbox/main.rs" diff --git a/distributed_game/README.md b/distributed_game/README.md index 616f1da4b..e61e09fca 100644 --- a/distributed_game/README.md +++ b/distributed_game/README.md @@ -26,7 +26,8 @@ the browser, but the client SDK has no rendering dependency. - [Build a zone](#build-a-zone) - [Guides](#guides): game loop · input · what clients see · the client SDK · generated clients · SvelteKit apps · client prediction (Rust → WebAssembly) · shared - logic and data (no TypeScript twins) · saving progress · scaling out · + logic and data (no TypeScript twins) · saving progress · scaling out + (zones as celld objects, the native multi-host server) · live updates · lag compensation · testing and operations · security - [Design decisions](#design-decisions) - [Status and limits](#status-and-limits) @@ -291,7 +292,7 @@ A zone is in one of three **tiers**: Idle forever (a city clock, say) or from `has_pending_work` to stay Hot. - **Dormant**: idle for `dormant_after` (30 s); no ticks. With hibernation on, a Dormant zone is saved and unloaded (see - [Scaling out](#scaling-out-many-zones-many-servers)). + [Scaling out](#scaling-out-zones-as-celld-objects)). `on_tier_changed` tells you about transitions. Timers (`ctx.set_timeout(after, value)`, `ctx.set_interval(every, value)`, @@ -786,7 +787,66 @@ ctx.emit_keyed(killer, RecordKillInput { mob, tier }, &[&format_args!("m{id}"), B" sorts after "left A" even when it commits first or the two hosts' clocks disagree. -### Scaling out: many zones, many servers +### Scaling out: zones as celld objects + +On celld every zone is a Durable Object (feature `celld-zone`, +[`celld_zone`](src/celld_zone/mod.rs)): one object per zone id, so a room +*is* a cell. Game code implements `CelldZone` for its `Zone` and declares +the class; nothing in the game or its API names a server. + +```rust,ignore +impl CelldZone for MobPit { + fn object_config(zone: &str, env: &ObjectEnv) -> Result { /* … */ } + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink.route(FactRoute::by_principal::("crawler")) + } +} +distributed_game::celld_zone_object!(PitRoom, MobPit); + +// worker entry: /rooms/{zone} → the zone's object (WebSocket or …/info) +if let Some(response) = forward_to_zone(req, &env, "PIT_ROOM", "/rooms/").await? { … } +``` + +**What celld handles:** where a zone runs (first touch; overflow to the +least-loaded node with `CELLD_MAX_RESIDENT_CELLS`), forwarding a WebSocket +from any node to the owner, one live instance per zone (fenced by its own +epochs), evicting idle objects, moving idle ones to balance load, draining +a stopping node and recovering a crashed node's objects elsewhere. + +**What the framework handles:** the WebSocket join (signed ticket, transfer +ticket of a doorway handoff — single use across activations — or reconnect +token), a self-correcting tick loop that runs only while someone is +connected, the zone's snapshot in object storage (every +`ZONE_PERSIST_MS` while occupied, and when it empties), dormancy and +hibernation (`ZONE_HIBERNATE_AFTER_MS` later, by object alarm, so it also +happens after an eviction), restore on the next join, facts to the cells +of the same worker object to object (`CelldObjectHost` under the usual +`CommandFactSink` routes; a durable outbox in the object's storage makes +them exactly once across crashes), and the zone's lifecycle reports +(`active` / `dormant` / `hibernated`) into its +[`zone_activity`](src/world/zone_activity.rs) cell, which the +`zone_status` read model projects for minimaps. + +**Limits.** A live zone never moves (only idle objects are rebalanced), so +load spreads by first touch and node caps. Objects of one class share V8 +isolates: a slow zone delays its neighbours. A node crash takes about the +node lease TTL (`CELLD_TTL_MS`, 10 s) to recover and loses at most the +snapshot interval of zone state; facts survive in the outbox. A socket +that outlives its activation closes with 1012 and the SDK rejoins with a +fresh ticket. celld does not tell code which node it runs on: the node +shown in debug views comes from an opt-in operator lookup +(`CELLD_ZONE_NODES`), never used for routing. + +Measured on celld 0.6.2 (gr-p42 spike, a loaded 18-core laptop): about 150 +one-player rooms or 4–5 fifty-player rooms per core at 30 Hz; forwarding +through another node adds under a millisecond; a hibernated room wakes in +35–130 ms (p50). + +### Scaling out: the native multi-host server + +The `net` server can also spread zones over several processes itself +(Endless Grid and Boss Ripple use it): placement, ownership and +hibernation are then the framework's job. - **Placement.** A `ZoneDirectory` (`HashRing`) maps each zone id to a host. A client that connects to the wrong host is told where to go @@ -942,7 +1002,10 @@ trait and its ABI (`run_abi`, `call_bytes`). | *(default)* | Zone/host runtime, facts queue, protocol, schema, replication, authoring derives, game surface, predicted steps (compiles to `wasm32-unknown-unknown`, where `#[predict]` exports its steps) | `serde`, `serde_json`, `distributed_game_macros` | | `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | | `cell` | `cell::CellFactSink` → in-process `AggregateCell::dispatch_idempotent` (native, unit tests); `cell::fact_session_from_headers` / `session_stamp` for cells (also wasm32); `stamp_event_record`; the `world::zone_lease` and `world::zone_state` cell aggregates | `distributed`, `sha2`, `base64` | -| `command-host` | `command_sink::CommandFactSink`: facts → commands through any command host, routed by command (`FactRoute`) | `cell` + `distributed/graphql` | +| `cell` (also) | `command_sink::CommandFactSink`: facts → commands through any fact host, routed by command (`FactRoute`); `world::zone_activity` | | +| `command-host` | `FactHost` for `CelldCommandHost` / `LocalCommandHost` (`CelldFactSink`) | `cell` + `distributed/graphql` | +| `celld-zone` | `celld_zone`: any `Zone` as a celld Durable Object (`ZoneObject`, `celld_zone_object!`, `forward_to_zone`), facts object to object (`CelldObjectHost`), `serve_cell` / `ZoneActivityCell` for the worker's cells (wasm32) | `cell`, `ticket`, `workers-rs` + `js-sys`, `wasm-bindgen(-futures)` | +| `ticket` | `ticket`: HS256 admission and transfer tickets without the axum server | `hmac`, `sha2`, `base64` | | `celld` | `celld::CelldFactSink` (the command sink over a remote-only `CelldCommandHost`): facts → celld cells over the internal HTTP path; `celld::CellZoneOwnership`: zone leases in celld `ZoneLease` cells; `celld::CellZoneStateStore`: hibernation snapshots in celld `ZoneState` cells | `command-host` + `reqwest`, `uuid` | | `workers-rs` | `world::zone_state::celld_worker`: the `zone-state/{zone}` route of a celld worker (cell + R2 bucket binding for large snapshots) | `cell` + `worker` | | `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | diff --git a/distributed_game/src/celld_zone/cells.rs b/distributed_game/src/celld_zone/cells.rs new file mode 100644 index 000000000..b03f7bce5 --- /dev/null +++ b/distributed_game/src/celld_zone/cells.rs @@ -0,0 +1,189 @@ +//! Serving fact cells next to celld zones (wasm32): the internal wait-path +//! route every fact cell of a game worker needs, and the zone-activity cell. + +use distributed::cell_host::{ + AggregateCell, CellCommandIdentity, CellDispatchError, CellWaitPathRequest, CelldOutbox, + InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, +}; +use distributed::microsvc::Session; +use distributed::Aggregate; +use serde_json::{json, Value}; +use worker::{Env, Method, Request, Response, Result, State}; + +use crate::cell::fact_session_from_headers; +use crate::world::zone_activity::{mount_zone_activity, ZoneActivity}; + +/// Builds the handler session from trusted request headers (after the +/// internal secret was checked); `None` refuses the command. +pub type Sessions = fn(&dyn Fn(&str) -> Option) -> Option; + +/// Facts only: the principal and the `x-game-*` stamp +/// ([`fact_session_from_headers`]). +pub fn fact_sessions(header: &dyn Fn(&str) -> Option) -> Option { + fact_session_from_headers(header) +} + +/// Check `x-distributed-internal-secret` against +/// `DISTRIBUTED_INTERNAL_SECRET`. +pub fn authenticate(req: &Request, env: &Env) -> std::result::Result<(), CellDispatchError> { + let configured = env + .secret(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + .or_else(|_| { + env.var(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + }) + .map_err(|_| CellDispatchError::Internal("internal secret is required".into()))?; + let secret = InternalHttpSecret::new(configured).map_err(CellDispatchError::Internal)?; + let candidate = req + .headers() + .get(CELL_INTERNAL_SECRET_HEADER) + .ok() + .flatten() + .ok_or(CellDispatchError::Unauthorized)?; + if secret.matches(&candidate) { + Ok(()) + } else { + Err(CellDispatchError::Unauthorized) + } +} + +/// A JSON response with `status`. +pub fn json_status(body: Value, status: u16) -> Result { + Ok(Response::from_json(&body)?.with_status(status)) +} + +/// The wire form of a dispatch error. +pub fn error_response(error: CellDispatchError) -> Result { + json_status( + json!({ "error": error.client_message(), "code": error.code() }), + error.status_code(), + ) +} + +/// One cell's internal routes: `GET /{kind}/{shard}` → `read(cell)`, `POST +/// /{kind}/{shard}/{command}` → the idempotent wait-path dispatch (identity +/// from the service-id and principal-partition headers, the session from +/// `sessions`), then a best-effort outbox drain. Every request must carry +/// the internal secret. +pub async fn serve_cell( + env: &Env, + cell: &AggregateCell, + mut req: Request, + read: F, + sessions: Sessions, +) -> Result +where + A: Aggregate + Send + Sync + 'static, + F: AsyncFnOnce(&AggregateCell) -> std::result::Result, +{ + if let Err(error) = authenticate(&req, env) { + return error_response(error); + } + let url = req.url()?; + let parts: Vec = url + .path() + .split('/') + .filter(|part| !part.is_empty()) + .map(str::to_string) + .collect(); + match (req.method(), parts.get(2)) { + (Method::Get, None) => match read(cell).await { + Ok(body) => json_status(body, 200), + Err(error) => error_response(CellDispatchError::Internal(error)), + }, + (Method::Post, Some(command)) => { + let command = command.clone(); + let body: Value = match req.json().await { + Ok(body) => body, + Err(_) => { + return error_response(CellDispatchError::BadRequest("invalid JSON".into())) + } + }; + let parsed = match CellWaitPathRequest::parse(body) { + Ok(parsed) => parsed, + Err(error) => return error_response(CellDispatchError::BadRequest(error)), + }; + let header = |name: &str| req.headers().get(name).ok().flatten(); + let identity = match ( + header(CELL_SERVICE_ID_HEADER), + header(CELL_PRINCIPAL_PARTITION_HEADER), + ) { + (Some(service), Some(partition)) => { + match CellCommandIdentity::new(service, partition, &parsed.command_id) { + Ok(identity) => identity, + Err(error) => return error_response(error), + } + } + _ => return error_response(CellDispatchError::Unauthorized), + }; + let Some(session) = sessions(&header) else { + return error_response(CellDispatchError::Forbidden); + }; + let result = cell + .dispatch_idempotent(&command, &identity, parsed.input, session) + .await; + if let Err(error) = cell.drain_outbox(env).await { + worker::console_error!("post-commit drain deferred: {error}"); + } + match result { + Ok(dispatch) => json_status(dispatch.wait_path_wire(), 200), + Err(error) => error_response(error), + } + } + _ => json_status(json!({ "error": "not found" }), 404), + } +} + +/// A cell's alarm: due schedules, then the outbox drain. +pub async fn cell_alarm(env: &Env, cell: &AggregateCell) -> Result +where + A: Aggregate + Send + Sync + 'static, +{ + let wake = cell + .alarm(env) + .await + .map_err(|error| worker::Error::RustError(error.to_string()))?; + for error in &wake.drain.deferred { + worker::console_error!("drain deferred: {error}"); + } + Response::ok("ok") +} + +/// The zone-activity cell of a game worker (`ZoneActivity:{zone}`, kind +/// `zone-activity`, binding `ZONE_ACTIVITY`): the zone's own lifecycle +/// facts; its `zone.activity_changed` events leave through `outbox` (the +/// worker's Queue) for the zone status read model. `GET` returns the row. +pub struct ZoneActivityCell { + cell: AggregateCell, + env: Env, +} + +impl ZoneActivityCell { + /// Open the cell of `state`, publishing its events to `outbox` (the + /// worker's Queue producer binding; cells commit only with one). + pub fn new(state: State, env: Env, outbox: CelldOutbox) -> Self { + let cell = mount_zone_activity( + AggregateCell::::from_state_with_snapshots(state, 20) + .expect("zone activity cell identity"), + ) + .with_celld_outbox(outbox); + Self { cell, env } + } + + /// Durable Object `fetch`. + pub async fn fetch(&self, req: Request) -> Result { + serve_cell(&self.env, &self.cell, req, read_activity, fact_sessions).await + } + + /// Durable Object `alarm`. + pub async fn alarm(&self) -> Result { + cell_alarm(&self.env, &self.cell).await + } +} + +async fn read_activity(cell: &AggregateCell) -> std::result::Result { + let activity = cell.load().await.map_err(|error| error.to_string())?; + Ok(json!({ "activity": activity.map(|a| a.row()) })) +} diff --git a/distributed_game/src/celld_zone/mod.rs b/distributed_game/src/celld_zone/mod.rs new file mode 100644 index 000000000..e7b50c7ad --- /dev/null +++ b/distributed_game/src/celld_zone/mod.rs @@ -0,0 +1,85 @@ +//! Zones as celld Durable Objects (feature `celld-zone`): host any [`Zone`] +//! as one object per zone id. celld decides where a zone runs, forwards +//! every connection to it, moves idle zones, evicts sleeping ones and +//! recovers them after a node crash; game code and game APIs never name a +//! server. +//! +//! ```text +//! client ──WebSocket /rooms/{zone}──▶ any celld node ──forward──▶ the zone's object +//! │ ZoneHost (this activation) +//! Hello(ticket | transfer ticket | reconnect token) ┤ deadline tick loop while occupied +//! │ snapshot every few s + when empty +//! facts (outbox in object storage) ───┼──▶ cell objects (CommandFactSink +//! │ over CelldObjectHost, exactly once) +//! zone_activity.record (active / dormant / hibernated)┘──▶ zone-activity/{zone} cell +//! └ outbox ▶ Queue ▶ zone_status read model +//! ``` +//! +//! What the framework does per object ([`ZoneObject`], wasm32): +//! - **Join.** A WebSocket upgrade is accepted as a hibernatable socket; +//! its attachment holds the client id and the activation id. Hello is +//! verified with the shared HS256 [`TicketKey`](crate::ticket::TicketKey) +//! (env `GAME_TICKET_SECRET`): a join ticket, a transfer ticket from a +//! neighbouring zone's handoff (single use, also across activations) or a +//! reconnect token inside the grace window. +//! - **Ticks.** A self-correcting `setTimeout` loop over absolute deadlines +//! ([`TickSchedule`]; `setInterval` drifts) drives +//! [`ZoneHost::advance`](crate::ZoneHost::advance) while anyone is +//! connected, and stops when the zone is empty. +//! - **State.** The zone's [`Zone::hibernate`] snapshot is written to object +//! storage every `ZONE_PERSIST_MS` while occupied and when the last +//! player leaves (`dormant`); after `ZONE_HIBERNATE_AFTER_MS` empty (an +//! object alarm, so it survives eviction) the zone is dropped from memory +//! (`hibernated`). The next join wakes it and restores the snapshot. +//! - **Restarts.** A socket that outlives its activation (eviction, a move, +//! a crash) is closed with [`CLOSE_RESTARTED`] (1012); the client rejoins +//! with a fresh ticket. +//! - **Facts.** Zone facts go to cells of the same worker object to object +//! ([`CelldObjectHost`] under [`CommandFactSink`](crate::command_sink::CommandFactSink), +//! the same routes and command ids as over HTTP). Each fact is written to +//! the object's outbox before it is sent and deleted when settled; the +//! next activation or the outbox alarm resends what is left, and the +//! cells' command ledger turns a resend into a replay: exactly once. +//! - **Status.** The zone reports its lifecycle as facts into its +//! [`zone_activity`](crate::world::zone_activity) cell, projected into the +//! [`zone_status`](crate::world::zone_status) read model (minimaps). +//! +//! What celld does: placement (first touch, overflow by +//! `CELLD_MAX_RESIDENT_CELLS`), forwarding from any node, idle eviction, +//! rebalancing of idle objects, graceful drain and crash recovery (fenced +//! by its own epochs; one instance per object name). +//! +//! Limits: a live zone never moves (only idle ones are rebalanced), so +//! spreading load depends on first touch and node caps; objects of one +//! class share V8 isolates (a slow zone delays its neighbours); a crash +//! loses at most the snapshot interval of zone state (facts are kept by +//! the outbox) and takes the node lease TTL (~10 s) to recover. +//! +//! Debug only: celld does not tell application code which node runs an +//! object. With `CELLD_ZONE_NODES` set (operator listeners) the object asks +//! each node whether it holds it; `CELLD_ZONE_NODE` names a fixed node. +//! Both are off by default; nothing routes by them. + +pub mod plan; + +#[cfg(target_arch = "wasm32")] +mod cells; +#[cfg(target_arch = "wasm32")] +mod object; + +pub use plan::{ + cell_binding, ObjectOptions, RoomState, StoredFact, TickSchedule, CLOSE_RESTARTED, ZONE_HEADER, +}; + +#[cfg(target_arch = "wasm32")] +pub use cells::{ + authenticate, cell_alarm, error_response, fact_sessions, json_status, serve_cell, Sessions, + ZoneActivityCell, +}; +#[cfg(target_arch = "wasm32")] +pub use object::{ + forward_to_zone, CelldObjectHost, CelldZone, LocalFuture, ObjectEnv, ObjectFactSink, ZoneObject, +}; + +#[cfg(doc)] +use crate::Zone; diff --git a/distributed_game/src/celld_zone/object.rs b/distributed_game/src/celld_zone/object.rs new file mode 100644 index 000000000..3180fc9ca --- /dev/null +++ b/distributed_game/src/celld_zone/object.rs @@ -0,0 +1,1407 @@ +//! The Durable Object side of the celld zone host (wasm32 only). + +use std::cell::RefCell; +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::rc::Rc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use distributed::cell_host::{ + CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, + CELL_SERVICE_ID_HEADER, +}; +use distributed::USER_ID_KEY; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use worker::send::{SendFuture, SendWrapper}; +use worker::{ + Delay, Env, Headers, Method, Request, RequestInit, Response, Result, State, Storage, WebSocket, + WebSocketIncomingMessage, WebSocketPair, +}; + +use super::plan::{ + cell_binding, classify_wait_path, zone_from_path, ObjectOptions, RoomState, StoredFact, + TickSchedule, Window, CLOSE_RESTARTED, OUTBOX_PREFIX, ZONE_HEADER, +}; +use crate::command_sink::{CommandFactSink, FactCall, FactHost, FactRoute}; +use crate::facts::{ + fact_channel, BoxFuture, Fact, FactError, FactQueue, FactReceipt, FactSink, RetryPolicy, +}; +use crate::handoff::{HandoffRequest, Transfer}; +use crate::inbox::ZoneInbound; +use crate::protocol::{error, ClientMessage, Role, ServerMessage, PROTOCOL_VERSION}; +use crate::stamp::FactStamp; +use crate::ticket::{NonceCache, TicketKey, VerifiedTicket}; +use crate::world::zone_activity::{ + zone_principal, RecordActivity, ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED, + ZONE_ACTIVITY_KIND, +}; +use crate::{ClientId, Clock, HostConfig, Outbound, TicketClaims, Zone, ZoneHost}; + +/// A future that runs on the object's (single) thread. +pub type LocalFuture = Pin + 'static>>; + +/// The zone's fact sink on celld: commands to cells, object to object. +pub type ObjectFactSink = CommandFactSink; + +const SNAPSHOT_KEY: &str = "zone:snapshot"; +const STATUS_KEY: &str = "zone:status"; +const NONCE_PREFIX: &str = "nonce:"; +/// Transfer tickets (doorways) live this long. +const TRANSFER_TTL_SECS: u64 = 30; +/// Unsettled facts one activation may hold. +const FACT_CAPACITY: usize = 512; +/// Retry stored facts this often while any is unsettled (ms). +const OUTBOX_RETRY_MS: f64 = 10_000.0; + +/// A game zone the framework can host as a celld Durable Object: one object +/// per zone id (celld places it, forwards to it, hibernates and moves it). +pub trait CelldZone: Zone { + /// The zone's construction parameters for `zone_id` (validate the id + /// here: `Err` refuses the join). + fn object_config(zone_id: &str, env: &ObjectEnv) -> std::result::Result; + + /// Host tuning; the object sets the tick and patch rates, reconnect + /// grace and boot epoch from its options. Default: [`HostConfig`] + /// defaults. + fn host_config(_zone_id: &str, _env: &ObjectEnv) -> HostConfig { + HostConfig::default() + } + + /// Fact routes of the zone (lifecycle facts too, if the host config + /// emits them). The zone-activity route is added by the framework. + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink + } + + /// Async work after a player joined (e.g. read the player's profile + /// from its cell); the message it returns is delivered into the zone + /// ([`Zone::on_message`]). Runs off the tick; the zone must not wait + /// for it. + fn after_join( + _env: &ObjectEnv, + _principal: &str, + ) -> Option>> { + None + } +} + +// ------------------------------------------------------------------ env + +/// The object's environment for game hooks: vars and cell reads. +#[derive(Clone)] +pub struct ObjectEnv { + env: Env, +} + +impl ObjectEnv { + /// Wrap a worker env. + pub fn new(env: Env) -> Self { + Self { env } + } + + /// A var or secret. + pub fn var(&self, name: &str) -> Option { + self.env + .var(name) + .map(|v| v.to_string()) + .or_else(|_| self.env.secret(name).map(|v| v.to_string())) + .ok() + } + + /// The worker env. + pub fn env(&self) -> &Env { + &self.env + } + + /// `GET /{kind}/{shard}` on a cell of this worker (its read route), + /// object to object, with the internal secret. + pub async fn read_cell(&self, kind: &str, shard: &str) -> std::result::Result { + let secret = self + .var(CELL_INTERNAL_SECRET_ENV) + .ok_or_else(|| format!("{CELL_INTERNAL_SECRET_ENV} is required"))?; + let headers = Headers::new(); + headers + .set(CELL_INTERNAL_SECRET_HEADER, &secret) + .map_err(|e| e.to_string())?; + let mut init = RequestInit::new(); + init.with_method(Method::Get).with_headers(headers); + let url = format!("https://cell/{kind}/{}", encode_segment(shard)); + let request = Request::new_with_init(&url, &init).map_err(|e| e.to_string())?; + let stub = stub_for(&self.env, kind, shard).map_err(|e| e.to_string())?; + let mut response = stub + .fetch_with_request(request) + .await + .map_err(|e| e.to_string())?; + let status = response.status_code(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if (200..300).contains(&status) { + Ok(body) + } else { + Err(format!("HTTP {status}: {body}")) + } + } +} + +/// The stub of cell `kind/shard` (binding [`cell_binding`]`(kind)`). +fn stub_for(env: &Env, kind: &str, shard: &str) -> Result { + let namespace = env.durable_object(&cell_binding(kind))?; + let id = namespace.id_from_name(shard)?; + id.get_stub() +} + +fn encode_segment(segment: &str) -> String { + let mut encoded = String::with_capacity(segment.len()); + for byte in segment.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~' | b':') { + encoded.push(byte as char); + } else { + encoded.push_str(&format!("%{byte:02X}")); + } + } + encoded +} + +// ------------------------------------------------------------------ fact host + +/// [`FactHost`] over the cells of the same worker: the cell wait-path +/// request (`POST /{kind}/{shard}/{command}`, internal secret, principal, +/// `x-game-*` stamp) sent straight to the cell's Durable Object stub — +/// object to object, no HTTP hop through a node's public listener. The +/// binding of kind `k` is [`cell_binding`]`(k)`. +pub struct CelldObjectHost { + env: SendWrapper, + secret: String, + service_id: String, +} + +impl CelldObjectHost { + /// A host for `env`'s cells under command-ledger `service_id`. + pub fn new(env: Env, secret: impl Into, service_id: impl Into) -> Self { + Self { + env: SendWrapper::new(env), + secret: secret.into(), + service_id: service_id.into(), + } + } + + async fn post(&self, call: &FactCall<'_>) -> std::result::Result { + let retry = |e: worker::Error| FactError::Retryable(e.to_string()); + let headers = Headers::new(); + let set = |name: &str, value: &str| { + headers + .set(name, value) + .map_err(|e| FactError::Permanent(format!("header {name}: {e}"))) + }; + set(CELL_INTERNAL_SECRET_HEADER, &self.secret)?; + set(CELL_SERVICE_ID_HEADER, &self.service_id)?; + set(CELL_PRINCIPAL_PARTITION_HEADER, &call.principal)?; + set(USER_ID_KEY, &call.principal)?; + set("content-type", "application/json")?; + for (name, value) in call.session.variables() { + if name.starts_with(crate::stamp::SESSION_PREFIX) { + set(name, value)?; + } + } + let body = json!({ "commandId": call.command_id, "input": call.input }).to_string(); + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(body.into())); + let url = format!( + "https://cell/{}/{}/{}", + encode_segment(call.kind), + encode_segment(&call.shard), + encode_segment(call.command) + ); + let request = Request::new_with_init(&url, &init).map_err(retry)?; + let stub = stub_for(&self.env, call.kind, &call.shard) + .map_err(|e| FactError::Permanent(format!("cell `{}`: {e}", call.kind)))?; + let mut response = stub.fetch_with_request(request).await.map_err(retry)?; + let status = response.status_code(); + let body: Value = response.json().await.unwrap_or(Value::Null); + classify_wait_path(status, &body) + } +} + +impl FactHost for CelldObjectHost { + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, std::result::Result> { + Box::pin(SendFuture::new(async move { self.post(&call).await })) + } +} + +/// The durable fact outbox around the sink: every emitted fact is written +/// to object storage right after the call that emitted it (from the fact +/// queues' journals, [`FactQueue::with_journal`]) and deleted here once it +/// settled (committed or permanently refused). The next activation (or the +/// outbox alarm) resends what is left; the cells' command ledger makes a +/// resend a replay. +#[derive(Clone)] +struct DurableFacts { + sink: ObjectFactSink, + storage: SendWrapper>, +} + +impl FactSink for DurableFacts { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> BoxFuture<'a, std::result::Result> { + Box::pin(SendFuture::new(async move { + let result = self.sink.commit(fact).await; + match &result { + Err(FactError::Permanent(e)) => { + worker::console_error!("fact {} refused: {e}", fact.key()) + } + Err(FactError::Retryable(e)) => { + worker::console_warn!("fact {} will be retried: {e}", fact.key()) + } + Ok(_) => {} + } + if !matches!(result, Err(FactError::Retryable(_))) { + let _ = self + .storage + .delete(&StoredFact::storage_key(fact.key())) + .await; + } + result + })) + } +} + +// ------------------------------------------------------------------ time + +fn now_ms() -> f64 { + js_sys::Date::now() +} + +/// Monotonic host clock over `Date.now()` (`Instant` panics on +/// wasm32-unknown-unknown). +struct JsClock { + origin_ms: f64, + last_us: AtomicU64, +} + +impl JsClock { + fn new() -> Self { + Self { + origin_ms: now_ms(), + last_us: AtomicU64::new(0), + } + } +} + +impl Clock for JsClock { + fn now(&self) -> Duration { + let us = ((now_ms() - self.origin_ms).max(0.0) * 1000.0) as u64; + Duration::from_micros(self.last_us.fetch_max(us, Ordering::Relaxed).max(us)) + } + + fn unix_ms(&self) -> u64 { + self.origin_ms as u64 + self.now().as_millis() as u64 + } +} + +/// `n` random bytes as hex, from `crypto.getRandomValues`. +fn random_hex(n: usize) -> String { + let bytes = js_sys::Uint8Array::new_with_length(n as u32); + let crypto = js_sys::Reflect::get(&js_sys::global(), &"crypto".into()).ok(); + let filled = crypto.and_then(|crypto| { + let get = js_sys::Reflect::get(&crypto, &"getRandomValues".into()).ok()?; + let get: js_sys::Function = get.into(); + get.call1(&crypto, &bytes).ok() + }); + if filled.is_none() { + for i in 0..n { + bytes.set_index(i as u32, (js_sys::Math::random() * 256.0) as u8); + } + } + bytes.to_vec().iter().map(|b| format!("{b:02x}")).collect() +} + +async fn yield_now() { + let _ = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::resolve( + &wasm_bindgen::JsValue::NULL, + )) + .await; +} + +thread_local! { + /// One id per V8 isolate (module instance), for the debug info. + static ISOLATE: String = random_hex(4); +} + +// ------------------------------------------------------------------ object + +#[derive(Serialize, Deserialize)] +struct Attachment { + client: u32, + activation: String, +} + +#[derive(Serialize, Deserialize)] +struct Snapshot { + version: String, + state: String, +} + +#[derive(Default)] +struct TickStats { + late: Window, + work: Window, + dropped: u64, + iterations: u64, +} + +struct Inner { + zone_id: String, + activation: String, + activation_epoch: u64, + options: Option, + key: Option, + host: Option>, + restored: bool, + wakes: u64, + state: RoomState, + sockets: HashMap, + ticking: bool, + nonces: NonceCache, + sink: Option, + activity: Option, + activity_seq: u64, + outbox_loaded: bool, + last_status: String, + node: String, + stats: TickStats, + last_persist_ms: f64, + spooled: u64, +} + +impl Inner { + fn occupied(&self) -> bool { + self.host + .as_ref() + .is_some_and(|h| h.player_count() > 0 || h.client_count() > 0) + } + + fn flush(&mut self) { + let Some(host) = self.host.as_mut() else { + return; + }; + for out in host.drain_outbound() { + match out { + Outbound::Frame { client, frame } => { + if let Some(ws) = self.sockets.get(&client.0) { + let _ = ws.send_with_bytes(frame); + } + } + Outbound::Close { client } => { + if let Some(ws) = self.sockets.remove(&client.0) { + let _ = ws.close(Some(1000), Some("closed by zone")); + } + } + } + } + } + + /// Facts emitted since the last call (zone and activity queues). + fn emitted(&mut self) -> Vec { + let mut facts = self + .host + .as_mut() + .map(ZoneHost::take_emitted_facts) + .unwrap_or_default(); + if let Some(queue) = self.activity.as_mut() { + facts.extend(queue.take_journal()); + } + facts + } + + fn snapshot(&self) -> Option { + let host = self.host.as_ref()?; + let state = host.hibernate_state()?; + use base64::Engine as _; + Some(Snapshot { + version: host.config().content_version.clone(), + state: base64::engine::general_purpose::STANDARD.encode(state), + }) + } + + /// Queue an activity report (a zone fact into its zone-activity cell). + fn report(&mut self, status: &str) { + if let Some(queue) = self.activity.as_mut() { + queue.drain(); + } + let Some(queue) = self.activity.as_mut() else { + return; + }; + self.activity_seq += 1; + let input = RecordActivity { + status: status.to_string(), + activation: self.activation.clone(), + restored: self.restored, + players: self.host.as_ref().map_or(0, |h| h.player_count() as u32), + node: self.node.clone(), + isolate: ISOLATE.with(|i| i.clone()), + }; + let stamp = FactStamp { + zone_id: self.zone_id.clone(), + tick: self.host.as_ref().map_or(0, |h| h.tick()), + emitted_at_ms: now_ms() as u64, + activation: self.activation_epoch, + seq: self.activity_seq, + ..FactStamp::default() + }; + let key = format!( + "zone_activity.record:{}:{}:{}", + self.zone_id, self.activation_epoch, self.activity_seq + ); + match serde_json::to_value(&input) { + Ok(value) => { + let fact = Fact::trusted( + key, + crate::world::zone_activity::RECORD, + value, + Some(zone_principal(&self.zone_id)), + stamp, + ); + if let Err(e) = queue.try_send(fact) { + worker::console_error!("zone {}: activity report dropped: {e:?}", self.zone_id); + } + } + Err(e) => worker::console_error!("zone activity encode: {e}"), + } + self.last_status = status.to_string(); + } +} + +/// Hosts one [`CelldZone`] as a celld Durable Object. The game's +/// `#[durable_object]` delegates to it (see [`crate::celld_zone_object!`]). +/// +/// Routes (on the object, via [`forward_to_zone`]): a WebSocket upgrade +/// joins the zone (the `distributed_game` wire protocol: Hello with a +/// ticket, a transfer ticket or a reconnect token); `GET …/info` returns +/// debug JSON (activation, node, isolate, tick timing) without waking a +/// hibernated zone. +pub struct ZoneObject { + state: Rc, + env: ObjectEnv, + inner: Rc>>, +} + +impl ZoneObject { + /// The object for `state` (constructor of the Durable Object). + pub fn new(state: State, env: Env) -> Self { + let zone_id = state.id().name().unwrap_or_default(); + let env = ObjectEnv::new(env); + let options = ObjectOptions::from_vars(|name| env.var(name)); + if let Err(e) = &options { + worker::console_error!("celld zone: {e}"); + } + let options = options.ok(); + let key = options + .as_ref() + .map(|o| TicketKey::new(o.ticket_secret.clone().into_bytes())); + let node = options + .as_ref() + .and_then(|o| o.node.clone()) + .unwrap_or_default(); + let inner = Inner { + zone_id, + activation: random_hex(6), + activation_epoch: (now_ms() * 1000.0) as u64, + options, + key, + host: None, + restored: false, + wakes: 0, + state: RoomState::Cold, + sockets: HashMap::new(), + ticking: false, + nonces: NonceCache::default(), + sink: None, + activity: None, + activity_seq: 0, + outbox_loaded: false, + last_status: String::new(), + node, + stats: TickStats::default(), + last_persist_ms: 0.0, + spooled: 0, + }; + Self { + state: Rc::new(state), + env, + inner: Rc::new(RefCell::new(inner)), + } + } + + /// The game hook environment. + pub fn env(&self) -> &ObjectEnv { + &self.env + } + + /// Durable Object `fetch`. + pub async fn fetch(&self, req: Request) -> Result { + if let Some(zone) = req.headers().get(ZONE_HEADER)? { + let mut inner = self.inner.borrow_mut(); + if inner.zone_id.is_empty() { + inner.zone_id = zone; + } + } + if self.inner.borrow().zone_id.is_empty() { + return Response::error("zone id required", 400); + } + let path = req.url()?.path().to_string(); + if path.ends_with("/info") { + return Response::from_json(&self.info()); + } + if req.headers().get("upgrade")?.as_deref() != Some("websocket") { + return Response::error("expected a WebSocket upgrade", 426); + } + if self.inner.borrow().options.is_none() { + return Response::error("zone host is not configured", 503); + } + self.wake().await?; + let pair = WebSocketPair::new()?; + self.state.accept_web_socket(&pair.server); + Response::from_websocket(pair.client) + } + + /// Durable Object `websocket_message`. + pub async fn websocket_message( + &self, + ws: WebSocket, + message: WebSocketIncomingMessage, + ) -> Result<()> { + let WebSocketIncomingMessage::Binary(bytes) = message else { + let _ = ws.close(Some(1003), Some("binary frames only")); + return Ok(()); + }; + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let activation = self.inner.borrow().activation.clone(); + let client = match attached { + Some(a) if a.activation == activation => Some(a.client), + // The socket outlived the activation that admitted it. + Some(_) => { + let _ = ws.close(Some(CLOSE_RESTARTED), Some("zone restarted; rejoin")); + return Ok(()); + } + None => None, + }; + let msg = match ClientMessage::decode(&bytes) { + Ok(m) => m, + Err(_) => { + reject(&ws, error::BAD_MESSAGE, "bad message"); + return Ok(()); + } + }; + match (client, msg) { + (None, ClientMessage::Hello(hello)) => self.hello(&ws, hello).await?, + ( + Some(client), + ClientMessage::Input { + seq, + client_tick, + payload, + }, + ) => { + let mut inner = self.inner.borrow_mut(); + match inner.host.as_mut() { + Some(host) => { + host.push_input(ClientId(client), seq, client_tick, &payload); + } + None => { + drop(inner); + let _ = ws.close(Some(CLOSE_RESTARTED), Some("zone asleep; rejoin")); + } + } + } + (_, ClientMessage::Ping { client_time }) => { + let server_time = self + .inner + .borrow() + .host + .as_ref() + .map_or(0.0, |h| h.server_time_ms()); + if let Ok(pong) = (ServerMessage::Pong { + client_time, + server_time, + }) + .encode(&()) + { + let _ = ws.send_with_bytes(pong); + } + } + (Some(client), ClientMessage::Leave) => { + { + let mut inner = self.inner.borrow_mut(); + inner.sockets.remove(&client); + if let Some(host) = inner.host.as_mut() { + host.disconnect(ClientId(client), true); + } + inner.flush(); + } + self.spool().await; + let _ = ws.close(Some(1000), Some("left")); + } + _ => reject(&ws, error::BAD_MESSAGE, "unexpected message"), + } + Ok(()) + } + + /// Durable Object `websocket_close`. + pub async fn websocket_close( + &self, + ws: WebSocket, + _code: usize, + _reason: String, + _was_clean: bool, + ) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } + + /// Durable Object `websocket_error`. + pub async fn websocket_error(&self, ws: WebSocket, _error: worker::Error) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } + + /// Durable Object `alarm`: hibernate a room that stayed empty, resend + /// unsettled facts, and after a crash mark the room asleep. + pub async fn alarm(&self) -> Result { + if self.inner.borrow().options.is_none() { + return Response::ok("unconfigured"); + } + self.load_zone_id().await; + self.start_facts().await; + let (cold, due, hibernate_after) = { + let inner = self.inner.borrow(); + let after = inner + .options + .as_ref() + .map_or(Duration::from_secs(10), |o| o.hibernate_after); + ( + inner.host.is_none(), + !inner.occupied() && inner.state.hibernate_due(now_ms(), after), + after, + ) + }; + if due { + self.hibernate().await; + } else if cold { + // A fresh activation woken by its alarm: the last one crashed or + // was evicted while awake. Its snapshot is what it left. + let stored: Option = self.state.storage().get(STATUS_KEY).await.ok().flatten(); + if stored.as_deref().is_some_and(|s| s != ACTIVITY_HIBERNATED) { + self.inner.borrow_mut().report(ACTIVITY_HIBERNATED); + self.store_status().await; + } + } else { + let since = match self.inner.borrow().state { + RoomState::Dormant { since_ms } => Some(since_ms), + _ => None, + }; + if let Some(since) = since { + let wait = since + hibernate_after.as_millis() as f64 - now_ms(); + self.arm(wait.max(10.0)).await; + } + } + self.arm_outbox().await; + Response::ok("ok") + } + + // -------------------------------------------------------------- internals + + /// Sockets accepted before an eviction reach a new instance without a + /// zone id from a request; the id is kept in storage. + async fn load_zone_id(&self) { + if !self.inner.borrow().zone_id.is_empty() { + return; + } + if let Ok(Some(zone)) = self.state.storage().get::("zone:id").await { + let mut inner = self.inner.borrow_mut(); + if inner.zone_id.is_empty() { + inner.zone_id = zone; + } + } + } + + /// Start the fact pipeline once per activation and resend what the + /// previous activation left in the outbox. + async fn start_facts(&self) { + if self.inner.borrow().sink.is_some() { + return; + } + let (zone_id, service, secret) = { + let inner = self.inner.borrow(); + let Some(options) = inner.options.as_ref() else { + return; + }; + ( + inner.zone_id.clone(), + options.fact_service.clone(), + options.internal_secret.clone(), + ) + }; + let Some(secret) = secret else { + worker::console_error!( + "zone {zone_id}: {CELL_INTERNAL_SECRET_ENV} is not set; facts are disabled" + ); + return; + }; + let host = CelldObjectHost::new(self.env.env().clone(), secret, &service); + let sink = match ObjectFactSink::new(host, service, zone_principal(&zone_id)) { + Ok(sink) => { + Z::fact_routes(sink.route(FactRoute::by_zone::(ZONE_ACTIVITY_KIND))) + } + Err(e) => { + worker::console_error!("zone {zone_id}: fact sink: {e}"); + return; + } + }; + let durable = DurableFacts { + sink, + storage: SendWrapper::new(Rc::new(self.state.storage())), + }; + let (queue, feed) = fact_channel(FACT_CAPACITY, retry_policy()); + let queue = queue.with_journal(); + wasm_bindgen_futures::spawn_local( + feed.with_max_concurrent_commits(4) + .run(durable.clone(), sleep), + ); + { + let mut inner = self.inner.borrow_mut(); + if inner.sink.is_some() { + return; + } + inner.sink = Some(durable); + inner.activity = Some(queue); + } + let _ = self.state.storage().put("zone:id", &zone_id).await; + // Resend the previous activations' unsettled facts. + let stored = self + .state + .storage() + .list_with_options(worker::ListOptions::new().prefix(OUTBOX_PREFIX)) + .await; + let mut inner = self.inner.borrow_mut(); + inner.outbox_loaded = true; + if let Ok(map) = stored { + let Some(queue) = inner.activity.as_mut() else { + return; + }; + for value in map.values().into_iter().flatten() { + let Some(stored) = value + .as_string() + .and_then(|text| serde_json::from_str::(&text).ok()) + else { + continue; + }; + if let Some(fact) = stored.into_fact() { + let _ = queue.try_send(fact); + } + } + // Already stored. + queue.take_journal(); + } + } + + /// Make sure the zone is in memory (restoring its snapshot). + async fn wake(&self) -> Result<()> { + self.start_facts().await; + if self.inner.borrow().host.is_some() { + return Ok(()); + } + let stored: Option = self.state.storage().get(SNAPSHOT_KEY).await.ok().flatten(); + let host = { + let inner = self.inner.borrow(); + if inner.host.is_some() { + return Ok(()); + } + let options = inner + .options + .as_ref() + .ok_or_else(|| worker::Error::RustError("zone host is not configured".into()))?; + let zone_id = inner.zone_id.clone(); + let config = Z::object_config(&zone_id, &self.env).map_err(worker::Error::RustError)?; + let mut host_config = Z::host_config(&zone_id, &self.env); + host_config.tick_rate = options.tick_hz; + host_config.patch_rate = options.patch_hz; + // The object stops ticking when empty instead of idling. + host_config.idle_tick_rate = None; + host_config.reconnect_grace = options.reconnect_grace; + host_config.boot_epoch = (now_ms() * 1000.0) as u64; + let key = inner.key.clone().expect("ticket key with options"); + let issuer_zone = zone_id.clone(); + let generation = inner.activation_epoch; + let mut host = + ZoneHost::::new(zone_id, host_config, Arc::new(JsClock::new()), config) + .with_token_source(|| random_hex(24)) + .with_transfer_issuer(move |request: &HandoffRequest| { + let expires_at = (now_ms() / 1000.0) as u64 + TRANSFER_TTL_SECS; + Some(key.sign_transfer(&Transfer { + claims: TicketClaims { + principal: request.principal.clone(), + zone: request.target_zone.clone(), + expires_at, + nonce: random_hex(16), + role: Role::Player, + name: request.name.clone(), + extensions: request.extensions.clone(), + }, + source_zone: request.source_zone.clone(), + issuer: issuer_zone.clone(), + generation, + carried: request.carried.clone(), + departed_at_ms: request.departed_at_ms, + })) + }); + let (queue, feed) = fact_channel(FACT_CAPACITY, retry_policy()); + if let Some(sink) = inner.sink.clone() { + wasm_bindgen_futures::spawn_local( + feed.with_max_concurrent_commits(4).run(sink, sleep), + ); + host = host.with_facts(queue.with_journal()); + } + let restored = match &stored { + Some(snapshot) => { + use base64::Engine as _; + match base64::engine::general_purpose::STANDARD.decode(&snapshot.state) { + Ok(state) => { + host.restore(&state, &snapshot.version); + true + } + Err(_) => false, + } + } + None => false, + }; + (host, restored) + }; + let (host, restored) = host; + { + let mut inner = self.inner.borrow_mut(); + if inner.host.is_some() { + return Ok(()); + } + inner.host = Some(host); + inner.restored = restored; + inner.wakes += 1; + // Each wake is a new activation: sockets of an earlier one are + // told to rejoin (1012). + if inner.wakes > 1 { + inner.activation = random_hex(6); + } + inner.state = RoomState::Active; + inner.last_persist_ms = now_ms(); + inner.report(ACTIVITY_ACTIVE); + } + self.store_status().await; + self.find_node(); + Ok(()) + } + + async fn hello(&self, ws: &WebSocket, hello: crate::protocol::Hello) -> Result<()> { + if hello.protocol_version != PROTOCOL_VERSION { + reject(ws, error::VERSION_MISMATCH, "protocol version"); + return Ok(()); + } + if let Err(e) = self.wake().await { + reject(ws, error::NOT_FOUND, &e.to_string()); + return Ok(()); + } + let now = (now_ms() / 1000.0) as u64; + // Transfer tickets are single use across activations too. + let mut principal = None; + let joined = if hello.reconnect_token.is_empty() { + let verified = { + let inner = self.inner.borrow(); + let key = inner.key.as_ref().expect("configured"); + key.verify_ticket(&hello.ticket, now) + }; + let verified = match verified { + Ok(v) => v, + Err(e) => { + reject(ws, error::UNAUTHORIZED, &format!("{e:?}")); + return Ok(()); + } + }; + let zone_id = self.inner.borrow().zone_id.clone(); + let (claims, transfer) = match verified { + VerifiedTicket::Join(claims) => (claims, None), + VerifiedTicket::Transfer(transfer) => (transfer.claims.clone(), Some(transfer)), + }; + if claims.zone != zone_id { + reject(ws, error::UNAUTHORIZED, "ticket is for another zone"); + return Ok(()); + } + let replayed = self + .inner + .borrow_mut() + .nonces + .check_and_insert(&claims.nonce, claims.expires_at, now) + .is_err(); + let nonce_key = format!("{NONCE_PREFIX}{}", claims.nonce); + let used_before = transfer.is_some() + && self + .state + .storage() + .get::(&nonce_key) + .await + .ok() + .flatten() + .is_some(); + if replayed || used_before { + reject(ws, error::UNAUTHORIZED, "ticket already used"); + return Ok(()); + } + if transfer.is_some() { + let _ = self + .state + .storage() + .put(&nonce_key, claims.expires_at) + .await; + } + principal = Some(claims.principal.clone()); + let mut inner = self.inner.borrow_mut(); + let host = inner.host.as_mut().expect("woken"); + match &transfer { + Some(transfer) => { + host.join_transfer(transfer, hello.capabilities, &hello.content_version) + } + None => host.join(&claims, hello.capabilities, &hello.content_version), + } + } else { + let mut inner = self.inner.borrow_mut(); + let host = inner.host.as_mut().expect("woken"); + host.reconnect_with_version( + &hello.reconnect_token, + hello.capabilities, + &hello.content_version, + ) + }; + match joined { + Ok(joined) => { + { + let mut inner = self.inner.borrow_mut(); + let activation = inner.activation.clone(); + ws.serialize_attachment(Attachment { + client: joined.client.0, + activation, + })?; + inner.sockets.insert(joined.client.0, ws.clone()); + inner.flush(); + if inner.state != RoomState::Active { + inner.state = RoomState::Active; + inner.report(ACTIVITY_ACTIVE); + } + } + self.store_status().await; + self.start_loop(); + if let Some(principal) = principal { + self.after_join(principal); + } + } + Err(e) => reject(ws, e.code, &e.message), + } + Ok(()) + } + + fn after_join(&self, principal: String) { + let Some(work) = Z::after_join(&self.env, &principal) else { + return; + }; + let inner = self.inner.clone(); + wasm_bindgen_futures::spawn_local(async move { + if let Some(message) = work.await { + let mut inner = inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.deliver(ZoneInbound::Message(message)); + inner.flush(); + } + // Facts the message produced are written on the next tick. + } + }); + } + + fn drop_socket(&self, ws: &WebSocket) { + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let mut inner = self.inner.borrow_mut(); + if let Some(a) = attached.filter(|a| a.activation == inner.activation) { + inner.sockets.remove(&a.client); + if let Some(host) = inner.host.as_mut() { + host.disconnect(ClientId(a.client), false); + } + inner.flush(); + drop(inner); + self.spool_later(); + } + } + + fn start_loop(&self) { + { + let mut inner = self.inner.borrow_mut(); + if inner.ticking || inner.host.is_none() { + return; + } + inner.ticking = true; + } + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.tick_loop().await }); + } + + fn handle(&self) -> Self { + Self { + state: self.state.clone(), + env: self.env.clone(), + inner: self.inner.clone(), + } + } + + async fn tick_loop(&self) { + let (hz, persist_every) = { + let inner = self.inner.borrow(); + let options = inner.options.as_ref().expect("configured"); + (options.tick_hz, options.persist_every.as_millis() as f64) + }; + let mut schedule = TickSchedule::new(now_ms(), hz); + self.arm(persist_every * 3.0).await; + loop { + Delay::from(Duration::from_micros( + (schedule.wait_ms(now_ms()) * 1000.0) as u64, + )) + .await; + let woke = now_ms(); + let late = schedule.woke(woke); + let (stop, persist) = { + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + inner.ticking = false; + return; + }; + let report = host.advance(); + inner.flush(); + let stats = &mut inner.stats; + stats.iterations += 1; + stats.late.push(late); + stats.work.push(now_ms() - woke); + stats.dropped += u64::from(report.dropped_ticks); + if let Some(queue) = inner.activity.as_mut() { + queue.drain(); + } + let stop = !inner.occupied(); + let persist = stop || woke - inner.last_persist_ms >= persist_every; + if stop { + inner.ticking = false; + } + (stop, persist) + }; + self.spool().await; + if persist { + self.persist().await; + if !stop { + self.arm(persist_every * 3.0).await; + } + } + if stop { + self.go_dormant().await; + return; + } + } + } + + /// Write the zone's snapshot (after the fact outbox writes queued by + /// this tick, so a crash never keeps an outcome without its fact). + async fn persist(&self) { + yield_now().await; + let snapshot = { + let mut inner = self.inner.borrow_mut(); + inner.last_persist_ms = now_ms(); + inner.snapshot() + }; + if let Some(snapshot) = snapshot { + if let Err(e) = self.state.storage().put(SNAPSHOT_KEY, snapshot).await { + worker::console_error!("zone snapshot write failed: {e}"); + } + } + } + + async fn go_dormant(&self) { + let after = { + let mut inner = self.inner.borrow_mut(); + if inner.occupied() { + return; + } + inner.state = RoomState::Dormant { since_ms: now_ms() }; + inner.report(ACTIVITY_DORMANT); + inner + .options + .as_ref() + .map_or(10_000.0, |o| o.hibernate_after.as_millis() as f64) + }; + self.store_status().await; + self.arm(after).await; + } + + async fn hibernate(&self) { + self.persist().await; + { + let mut inner = self.inner.borrow_mut(); + if inner.occupied() { + return; + } + inner.report(ACTIVITY_HIBERNATED); + // Dropped, so the next join restores from storage. + inner.host = None; + inner.state = RoomState::Cold; + inner.ticking = false; + } + self.store_status().await; + } + + /// Write the facts emitted since the last call to the outbox. + async fn spool(&self) { + let facts = self.inner.borrow_mut().emitted(); + if facts.is_empty() { + return; + } + let storage = self.state.storage(); + // One batched write (the storage API takes at most 128 keys). + for chunk in facts.chunks(128) { + let batch = js_sys::Object::new(); + for fact in chunk { + let text = serde_json::to_string(&StoredFact::of(fact)).unwrap_or_default(); + let _ = js_sys::Reflect::set( + &batch, + &StoredFact::storage_key(fact.key()).into(), + &text.into(), + ); + } + if let Err(e) = storage.put_multiple_raw(batch).await { + worker::console_error!("fact outbox write failed: {e}"); + } + } + self.inner.borrow_mut().spooled += facts.len() as u64; + self.arm_outbox().await; + } + + /// [`spool`](Self::spool) from a synchronous handler. + fn spool_later(&self) { + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.spool().await }); + } + + async fn store_status(&self) { + self.spool().await; + let status = self.inner.borrow().last_status.clone(); + if !status.is_empty() { + let _ = self.state.storage().put(STATUS_KEY, status).await; + } + } + + /// Set the object's alarm `in_ms` from now. + async fn arm(&self, in_ms: f64) { + if let Err(e) = self + .state + .storage() + .set_alarm(Duration::from_millis(in_ms.max(1.0) as u64)) + .await + { + worker::console_error!("zone alarm: {e}"); + } + } + + /// Keep an alarm while unsettled facts wait in the outbox. + async fn arm_outbox(&self) { + let pending = { + let inner = self.inner.borrow(); + inner.activity.as_ref().map_or(0, |q| q.in_flight()) + + inner.host.as_ref().map_or(0, |h| h.facts_in_flight()) + }; + let alarm = self.state.storage().get_alarm().await.ok().flatten(); + if pending > 0 && alarm.is_none() { + self.arm(OUTBOX_RETRY_MS).await; + } + } + + /// Debug only, off by default: ask each configured operator listener + /// whether it holds this object. + fn find_node(&self) { + let (nodes, id) = { + let inner = self.inner.borrow(); + let Some(options) = inner.options.as_ref() else { + return; + }; + if options.nodes.is_empty() || options.node.is_some() { + return; + } + (options.nodes.clone(), self.state.id().to_string()) + }; + let inner = self.inner.clone(); + wasm_bindgen_futures::spawn_local(async move { + for (node, addr) in nodes { + let Ok(url) = format!("http://{addr}/state").parse() else { + continue; + }; + let Ok(mut response) = worker::Fetch::Url(url).send().await else { + continue; + }; + let Ok(state) = response.json::().await else { + continue; + }; + let mine = state["deployment"]["cells"] + .as_object() + .is_some_and(|cells| cells.keys().any(|k| k.ends_with(&id))); + if mine { + let mut inner = inner.borrow_mut(); + inner.node = node; + if inner.state == RoomState::Active { + inner.report(ACTIVITY_ACTIVE); + } + return; + } + } + }); + } + + fn info(&self) -> Value { + let inner = self.inner.borrow(); + let host = inner.host.as_ref(); + let stats = &inner.stats; + json!({ + "zone": inner.zone_id, + "status": inner.last_status, + "awake": host.is_some(), + "activation": inner.activation, + "restored": inner.restored, + "wakes": inner.wakes, + "node": inner.node, + "isolate": ISOLATE.with(|i| i.clone()), + "players": host.map_or(0, |h| h.player_count()), + "tick": host.map_or(0, |h| h.tick()), + "hz": inner.options.as_ref().map_or(0, |o| o.tick_hz), + "ticking": inner.ticking, + "factsInFlight": host.map_or(0, |h| h.facts_in_flight()) + + inner.activity.as_ref().map_or(0, |q| q.in_flight()), + "spooledFacts": inner.spooled, + "iterations": stats.iterations, + "droppedTicks": stats.dropped, + "lateMs": { "p50": stats.late.percentile(0.5), "p99": stats.late.percentile(0.99) }, + "workMs": { "p50": stats.work.percentile(0.5), "p99": stats.work.percentile(0.99) }, + }) + } +} + +fn retry_policy() -> RetryPolicy { + RetryPolicy::until_settled(Duration::from_millis(100), Duration::from_secs(5)) +} + +fn sleep(d: Duration) -> Delay { + Delay::from(d) +} + +fn reject(ws: &WebSocket, code: u32, message: &str) { + if let Ok(frame) = (ServerMessage::Error { + code, + message: message.into(), + }) + .encode(&()) + { + let _ = ws.send_with_bytes(frame); + } + let _ = ws.close(Some(1008), Some(message)); +} + +/// Worker entry helper: route `"{prefix}{zone}[/…]"` to the zone's object +/// in Durable Object namespace `binding` (one object per zone id; celld +/// places it). Returns `None` when the path is not under `prefix`. +pub async fn forward_to_zone( + req: Request, + env: &Env, + binding: &str, + prefix: &str, +) -> Result> { + let path = req.url()?.path().to_string(); + let Some((zone, _)) = zone_from_path(prefix, &path) else { + return Ok(None); + }; + let stub = env + .durable_object(binding)? + .id_from_name(&zone)? + .get_stub()?; + let headers = req.headers().clone(); + headers.set(ZONE_HEADER, &zone)?; + let mut init = RequestInit::new(); + init.with_method(req.method()).with_headers(headers); + let forwarded = Request::new_with_init(req.url()?.as_str(), &init)?; + stub.fetch_with_request(forwarded).await.map(Some) +} + +/// Declare the Durable Object class hosting zone type `$zone`: +/// +/// ```ignore +/// distributed_game::celld_zone_object!(PitRoom, MobPit); +/// ``` +/// +/// The crate needs `worker` as a dependency. Bind the class in +/// `wrangler.jsonc` (a SQLite class) and route to it with +/// [`forward_to_zone`]. +#[macro_export] +macro_rules! celld_zone_object { + ($name:ident, $zone:ty) => { + #[::worker::durable_object] + pub struct $name { + zone: $crate::celld_zone::ZoneObject<$zone>, + } + + impl ::worker::DurableObject for $name { + fn new(state: ::worker::State, env: ::worker::Env) -> Self { + Self { + zone: $crate::celld_zone::ZoneObject::new(state, env), + } + } + + async fn fetch(&self, req: ::worker::Request) -> ::worker::Result<::worker::Response> { + self.zone.fetch(req).await + } + + async fn websocket_message( + &self, + ws: ::worker::WebSocket, + message: ::worker::WebSocketIncomingMessage, + ) -> ::worker::Result<()> { + self.zone.websocket_message(ws, message).await + } + + async fn websocket_close( + &self, + ws: ::worker::WebSocket, + code: usize, + reason: String, + was_clean: bool, + ) -> ::worker::Result<()> { + self.zone.websocket_close(ws, code, reason, was_clean).await + } + + async fn websocket_error( + &self, + ws: ::worker::WebSocket, + error: ::worker::Error, + ) -> ::worker::Result<()> { + self.zone.websocket_error(ws, error).await + } + + async fn alarm(&self) -> ::worker::Result<::worker::Response> { + self.zone.alarm().await + } + } + }; +} diff --git a/distributed_game/src/celld_zone/plan.rs b/distributed_game/src/celld_zone/plan.rs new file mode 100644 index 000000000..c9e4ab28e --- /dev/null +++ b/distributed_game/src/celld_zone/plan.rs @@ -0,0 +1,473 @@ +//! The runtime-free parts of the celld zone host: options, the room's +//! lifecycle states, the self-correcting tick schedule, the durable fact +//! outbox encoding and the cell wait-path answer classification. Compiled +//! on every target so they are unit-tested natively; the Durable Object glue +//! ([`super::ZoneObject`], wasm32) drives them. + +use std::collections::HashMap; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::facts::{Fact, FactError, FactReceipt}; +use crate::stamp::FactStamp; + +/// Env var: HS256 secret admission (and transfer) tickets are signed with. +pub const TICKET_SECRET_VAR: &str = "GAME_TICKET_SECRET"; +/// Env var: tick rate (Hz, default 30). +pub const TICK_HZ_VAR: &str = "ZONE_TICK_HZ"; +/// Env var: patch rate (Hz, default 20, at most the tick rate). +pub const PATCH_HZ_VAR: &str = "ZONE_PATCH_HZ"; +/// Env var: snapshot interval while occupied (ms, default 5000). +pub const PERSIST_MS_VAR: &str = "ZONE_PERSIST_MS"; +/// Env var: how long an empty room stays dormant before it hibernates (ms, +/// default 10000). +pub const HIBERNATE_AFTER_MS_VAR: &str = "ZONE_HIBERNATE_AFTER_MS"; +/// Env var: reconnect grace (ms, default 5000). +pub const RECONNECT_GRACE_MS_VAR: &str = "ZONE_RECONNECT_GRACE_MS"; +/// Env var: command-ledger service id of the zone's facts (default +/// `celld-zone`). +pub const FACT_SERVICE_VAR: &str = "ZONE_FACT_SERVICE"; +/// Env var (debug only, off by default): `name=host:port,…` celld operator +/// listeners asked which node holds the room (celld does not tell +/// application code its node id). +pub const NODES_VAR: &str = "CELLD_ZONE_NODES"; +/// Env var (debug only): a fixed node name (e.g. `dev` for `celld dev`). +pub const NODE_VAR: &str = "CELLD_ZONE_NODE"; + +/// Request header naming the zone (set by [`super::forward_to_zone`]; the +/// object's id has no name on some celld paths). +pub const ZONE_HEADER: &str = "x-celld-zone"; + +/// Close code for sockets of an earlier activation (the room restarted or +/// moved): the client rejoins with a fresh ticket. +pub const CLOSE_RESTARTED: u16 = 1012; + +/// Object settings, from the worker's vars and secrets. +#[derive(Debug, Clone, PartialEq)] +pub struct ObjectOptions { + /// Ticket key secret. + pub ticket_secret: String, + /// Internal secret for cell calls (`DISTRIBUTED_INTERNAL_SECRET`). + pub internal_secret: Option, + /// Hot tick rate. + pub tick_hz: u32, + /// Patch rate. + pub patch_hz: u32, + /// Snapshot interval while occupied. + pub persist_every: Duration, + /// Dormant → hibernated. + pub hibernate_after: Duration, + /// Reconnect grace window. + pub reconnect_grace: Duration, + /// Fact command-ledger service id. + pub fact_service: String, + /// Debug node lookup: `(name, operator host:port)`. + pub nodes: Vec<(String, String)>, + /// Debug fixed node name. + pub node: Option, +} + +fn parse( + get: &impl Fn(&str) -> Option, + name: &str, + default: T, +) -> Result { + match get(name).filter(|value| !value.trim().is_empty()) { + None => Ok(default), + Some(value) => value + .trim() + .parse() + .map_err(|_| format!("{name}: not a number: {value}")), + } +} + +impl ObjectOptions { + /// Read the options through `get` (vars, then secrets). + pub fn from_vars(get: impl Fn(&str) -> Option) -> Result { + let ticket_secret = get(TICKET_SECRET_VAR) + .filter(|secret| secret.len() >= 16) + .ok_or_else(|| format!("{TICKET_SECRET_VAR} (>= 16 bytes) is required"))?; + let tick_hz: u32 = parse(&get, TICK_HZ_VAR, 30)?; + if !(1..=120).contains(&tick_hz) { + return Err(format!("{TICK_HZ_VAR} must be within 1..=120")); + } + let patch_hz: u32 = parse(&get, PATCH_HZ_VAR, 20)?; + let nodes = get(NODES_VAR) + .unwrap_or_default() + .split(',') + .filter_map(|entry| { + let (name, addr) = entry.trim().split_once('=')?; + (!name.is_empty() && !addr.is_empty()).then(|| (name.into(), addr.into())) + }) + .collect(); + Ok(Self { + ticket_secret, + internal_secret: get(distributed::cell_host::CELL_INTERNAL_SECRET_ENV) + .filter(|secret| !secret.is_empty()), + tick_hz, + patch_hz: patch_hz.clamp(1, tick_hz), + persist_every: Duration::from_millis(parse(&get, PERSIST_MS_VAR, 5_000)?), + hibernate_after: Duration::from_millis(parse(&get, HIBERNATE_AFTER_MS_VAR, 10_000)?), + reconnect_grace: Duration::from_millis(parse(&get, RECONNECT_GRACE_MS_VAR, 5_000)?), + fact_service: get(FACT_SERVICE_VAR) + .filter(|service| !service.trim().is_empty()) + .unwrap_or_else(|| "celld-zone".into()), + nodes, + node: get(NODE_VAR).filter(|node| !node.is_empty()), + }) + } +} + +/// Where a room is in its life (per object activation). +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RoomState { + /// No zone in memory (fresh activation, or hibernated and dropped). + Cold, + /// Zone in memory with players (or just woke up). + Active, + /// Empty since `since_ms` (Unix ms); snapshot written. + Dormant { + /// When the last player left. + since_ms: f64, + }, +} + +impl RoomState { + /// True when an empty room should hibernate at `now_ms`. + pub fn hibernate_due(&self, now_ms: f64, after: Duration) -> bool { + match self { + Self::Dormant { since_ms } => now_ms + 1.0 >= since_ms + after.as_millis() as f64, + _ => false, + } + } +} + +/// A self-correcting fixed-rate schedule over absolute deadlines +/// (`setInterval` drifts: 33.3 ms gave 35 ms on celld). Each wake-up aims at +/// `start + k × step`; deadlines already missed are skipped (the fixed +/// timestep catches up inside one `advance`). +#[derive(Debug, Clone)] +pub struct TickSchedule { + start_ms: f64, + step_ms: f64, + k: u64, +} + +impl TickSchedule { + /// A schedule at `hz` from `now_ms`. + pub fn new(now_ms: f64, hz: u32) -> Self { + Self { + start_ms: now_ms, + step_ms: 1000.0 / f64::from(hz.max(1)), + k: 1, + } + } + + /// The next deadline. + pub fn deadline(&self) -> f64 { + self.start_ms + self.k as f64 * self.step_ms + } + + /// How long to wait from `now_ms` (never negative). + pub fn wait_ms(&self, now_ms: f64) -> f64 { + (self.deadline() - now_ms).max(0.0) + } + + /// Record a wake-up at `now_ms`: returns how late it was, and moves to + /// the first deadline after `now_ms`. + pub fn woke(&mut self, now_ms: f64) -> f64 { + let late = (now_ms - self.deadline()).max(0.0); + let next = ((now_ms - self.start_ms) / self.step_ms).floor() as u64 + 1; + self.k = next.max(self.k + 1); + late + } +} + +/// A fact in the object's durable outbox (written before it is sent, +/// deleted once settled, resent by the next activation). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct StoredFact { + /// Idempotency key. + pub key: String, + /// Command. + pub command: String, + /// Input. + pub input: Value, + /// Bound principal. + pub principal: Option, + /// Stamp as its `x-game-*` session variables. + pub stamp: HashMap, +} + +impl StoredFact { + /// Storage key of a fact. + pub fn storage_key(key: &str) -> String { + format!("{OUTBOX_PREFIX}{key}") + } + + /// Encode `fact`. + pub fn of(fact: &Fact) -> Self { + Self { + key: fact.key().to_string(), + command: fact.command().to_string(), + input: fact.input().clone(), + principal: fact.principal().map(str::to_string), + stamp: fact.stamp().session_vars().into_iter().collect(), + } + } + + /// Decode (None for a malformed stamp). + pub fn into_fact(self) -> Option { + let stamp = FactStamp::from_session_vars(&self.stamp)?; + Some(Fact::trusted( + self.key, + self.command, + self.input, + self.principal, + stamp, + )) + } +} + +/// Storage key prefix of the durable fact outbox. +pub const OUTBOX_PREFIX: &str = "fact:"; + +/// Durable Object binding of a cell kind: upper case, `-` → `_` +/// (`zone-activity` → `ZONE_ACTIVITY`, `crawler` → `CRAWLER`). +pub fn cell_binding(kind: &str) -> String { + kind.chars() + .map(|c| { + if c == '-' { + '_' + } else { + c.to_ascii_uppercase() + } + }) + .collect() +} + +/// Classify a cell wait-path answer (`status`, JSON `body`). +pub fn classify_wait_path(status: u16, body: &Value) -> Result { + if (200..300).contains(&status) { + return Ok(FactReceipt { + payload: body.get("payload").cloned().unwrap_or(Value::Null), + replayed: body + .pointer("/receipt/replayed") + .and_then(Value::as_bool) + .unwrap_or(false), + }); + } + let code = body.get("code").and_then(Value::as_str).unwrap_or(""); + let message = body + .get("error") + .and_then(Value::as_str) + .unwrap_or("rejected"); + let detail = format!("HTTP {status} {code}: {message}"); + if status >= 500 || matches!(status, 408 | 429) || code == "COMMAND_IN_PROGRESS" { + Err(FactError::Retryable(detail)) + } else { + Err(FactError::Permanent(detail)) + } +} + +/// `"{prefix}{zone}[/rest]"` → `(zone, rest)` (percent-decoded zone; None +/// when the path does not match or the zone is empty / not printable). +pub fn zone_from_path<'a>(prefix: &str, path: &'a str) -> Option<(String, &'a str)> { + let rest = path.strip_prefix(prefix)?; + let (raw, tail) = rest.split_once('/').unwrap_or((rest, "")); + let zone = percent_decode(raw)?; + (!zone.is_empty() + && zone.len() <= 128 + && zone.bytes().all(|byte| (0x21..=0x7e).contains(&byte))) + .then_some((zone, tail)) +} + +fn percent_decode(segment: &str) -> Option { + let bytes = segment.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + out.push(u8::from_str_radix(segment.get(i + 1..i + 3)?, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +/// Percentiles of the last values (tick timing in the debug info). +#[derive(Debug, Clone, Default)] +pub struct Window { + values: std::collections::VecDeque, +} + +impl Window { + const MAX: usize = 900; + + /// Add a value. + pub fn push(&mut self, value: f64) { + if self.values.len() == Self::MAX { + self.values.pop_front(); + } + self.values.push_back(value); + } + + /// The `p` percentile (0 when empty). + pub fn percentile(&self, p: f64) -> f64 { + if self.values.is_empty() { + return 0.0; + } + let mut sorted: Vec = self.values.iter().copied().collect(); + sorted.sort_by(f64::total_cmp); + sorted[((sorted.len() - 1) as f64 * p.clamp(0.0, 1.0)).round() as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: HashMap = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + move |name| map.get(name).cloned() + } + + #[test] + fn options_need_a_ticket_secret_and_default_the_rest() { + assert!(ObjectOptions::from_vars(vars(&[])).is_err()); + assert!(ObjectOptions::from_vars(vars(&[(TICKET_SECRET_VAR, "short")])).is_err()); + let options = + ObjectOptions::from_vars(vars(&[(TICKET_SECRET_VAR, "0123456789abcdef")])).unwrap(); + assert_eq!((options.tick_hz, options.patch_hz), (30, 20)); + assert_eq!(options.hibernate_after, Duration::from_secs(10)); + assert!(options.nodes.is_empty(), "node lookup is off by default"); + assert_eq!(options.fact_service, "celld-zone"); + let options = ObjectOptions::from_vars(vars(&[ + (TICKET_SECRET_VAR, "0123456789abcdef"), + (TICK_HZ_VAR, "10"), + (PATCH_HZ_VAR, "20"), + (NODES_VAR, "node-a=127.0.0.1:1, bad ,node-b=127.0.0.1:2"), + ("DISTRIBUTED_INTERNAL_SECRET", "s"), + ])) + .unwrap(); + assert_eq!(options.patch_hz, 10, "patches never outpace ticks"); + assert_eq!(options.nodes.len(), 2); + assert_eq!(options.internal_secret.as_deref(), Some("s")); + assert!(ObjectOptions::from_vars(vars(&[ + (TICKET_SECRET_VAR, "0123456789abcdef"), + (TICK_HZ_VAR, "0"), + ])) + .is_err()); + } + + #[test] + fn the_tick_schedule_corrects_itself_and_skips_missed_deadlines() { + let mut schedule = TickSchedule::new(1000.0, 20); + assert_eq!(schedule.deadline(), 1050.0); + assert_eq!(schedule.wait_ms(1010.0), 40.0); + // Woke 3 ms late: the next deadline stays on the grid (no drift). + assert_eq!(schedule.woke(1053.0), 3.0); + assert_eq!(schedule.deadline(), 1100.0); + // A 130 ms stall skips the missed deadlines. + assert_eq!(schedule.woke(1230.0), 130.0); + assert_eq!(schedule.deadline(), 1250.0); + assert_eq!(schedule.wait_ms(1300.0), 0.0); + // Early wake-ups still advance by one step. + let before = schedule.deadline(); + schedule.woke(before - 5.0); + assert_eq!(schedule.deadline(), before + 50.0); + } + + #[test] + fn dormant_rooms_hibernate_after_the_delay() { + let after = Duration::from_millis(500); + assert!(!RoomState::Active.hibernate_due(10_000.0, after)); + assert!(!RoomState::Cold.hibernate_due(10_000.0, after)); + let dormant = RoomState::Dormant { since_ms: 1_000.0 }; + assert!(!dormant.hibernate_due(1_400.0, after)); + assert!(dormant.hibernate_due(1_500.0, after)); + } + + #[test] + fn stored_facts_round_trip() { + let fact = Fact::trusted( + "kill:pit:1:m1:0", + "crawler.record_kill", + json!({ "mob": 1 }), + Some("alice".into()), + FactStamp { + zone_id: "pit.0.0".into(), + tick: 7, + activation: 9, + seq: 2, + emitted_at_ms: 1_700_000_000_000, + ..FactStamp::default() + }, + ); + let stored = StoredFact::of(&fact); + let text = serde_json::to_string(&stored).unwrap(); + let back: StoredFact = serde_json::from_str(&text).unwrap(); + assert_eq!(back.into_fact().unwrap(), fact); + assert_eq!(StoredFact::storage_key("k"), format!("{OUTBOX_PREFIX}k")); + } + + #[test] + fn wait_path_answers_are_classified() { + let ok = classify_wait_path( + 200, + &json!({ "payload": { "xp": 3 }, "receipt": { "replayed": true } }), + ) + .unwrap(); + assert_eq!(ok.payload, json!({ "xp": 3 })); + assert!(ok.replayed); + let retry = |status, code: &str| { + matches!( + classify_wait_path(status, &json!({ "code": code })), + Err(FactError::Retryable(_)) + ) + }; + assert!(retry(503, "INTERNAL")); + assert!(retry(409, "COMMAND_IN_PROGRESS")); + assert!(retry(429, "")); + assert!(!retry(401, "UNAUTHORIZED")); + assert!(!retry(422, "REJECTED")); + } + + #[test] + fn bindings_and_paths() { + assert_eq!(cell_binding("zone-activity"), "ZONE_ACTIVITY"); + assert_eq!(cell_binding("crawler"), "CRAWLER"); + assert_eq!( + zone_from_path("/rooms/", "/rooms/pit.1.-2/info"), + Some(("pit.1.-2".to_string(), "info")) + ); + assert_eq!( + zone_from_path("/rooms/", "/rooms/a%20b"), + None, + "zones are printable ASCII without spaces" + ); + assert_eq!(zone_from_path("/rooms/", "/rooms/"), None); + assert_eq!(zone_from_path("/rooms/", "/other/x"), None); + } + + #[test] + fn windows_report_percentiles() { + let mut window = Window::default(); + assert_eq!(window.percentile(0.5), 0.0); + for v in 1..=100 { + window.push(f64::from(v)); + } + assert_eq!(window.percentile(0.0), 1.0); + assert_eq!(window.percentile(1.0), 100.0); + assert!((window.percentile(0.99) - 99.0).abs() <= 1.0); + } +} diff --git a/distributed_game/src/command_sink.rs b/distributed_game/src/command_sink.rs index da08e751e..b5acc84b1 100644 --- a/distributed_game/src/command_sink.rs +++ b/distributed_game/src/command_sink.rs @@ -1,26 +1,27 @@ -//! [`CommandFactSink`]: a zone server's facts dispatched as commands through -//! any [`CommandHost`] — the same durable aggregates whether they run in -//! celld cells ([`CelldCommandHost`], `POST {celld}/{kind}/{shard}/{command}` -//! over the internal path) or in an ordinary service over any repository -//! ([`LocalCommandHost`]: in-memory, SQLite, Postgres). +//! [`CommandFactSink`]: a zone's facts dispatched as commands through any +//! [`FactHost`] — the same durable aggregates whether they are reached over +//! celld's internal HTTP path ([`CelldCommandHost`], feature `command-host`, +//! `POST {celld}/{kind}/{shard}/{command}`), object-to-object from a zone +//! running as a celld Durable Object +//! ([`CelldObjectHost`](crate::celld_zone::CelldObjectHost), feature +//! `celld-zone`, wasm32), or in an ordinary service over any repository +//! ([`LocalCommandHost`], feature `command-host`). //! -//! One sink per zone server routes every fact by its command +//! One sink per zone (host) routes every fact by its command //! ([`FactCommand::COMMAND`](crate::FactCommand::COMMAND)) to a registered //! [`FactRoute`]: a cell kind and a shard function of the fact's input and //! trusted session (principal + [`FactStamp`](crate::FactStamp)). A host -//! that addresses cells uses both ([`FactRouting`]); a service routes by -//! command and its handler picks the stream from the same session or input. -//! Player lifecycle facts (`zone.*`, [`crate::lifecycle`]) route to the -//! presence aggregate of the player's account ([`CommandFactSink::lifecycle_route`]). +//! that addresses cells uses both; a service routes by command and its +//! handler picks the stream from the same session or input. Player +//! lifecycle facts (`zone.*`, [`crate::lifecycle`]) route to the presence +//! aggregate of the player's account ([`CommandFactSink::lifecycle_route`]). //! //! - **Exactly one commit per key.** The command id is //! [`command_id_for`]`(service_id, fact key)`, so a retry after a timeout //! replays through the aggregate's command ledger (`replayed` receipt). //! - **Trusted identity.** The principal (bound by the zone host from the -//! verified ticket) is the session's `x-user-id` and the verified -//! principal ([`VerifiedPrincipal::from_trusted_transport`]); the stamp -//! travels as `x-game-*` session variables (forwarded to cells as trusted -//! metadata, [`CelldCommandHost::forward_session_prefix`]). +//! verified ticket) is the session's `x-user-id`; the stamp travels as +//! `x-game-*` session variables (forwarded to cells as trusted metadata). //! - **No local durable fallback.** A host that is slow or unreachable, a //! 5xx, or a command still in progress is [`FactError::Retryable`]: the fact //! stays in the zone's queue (use @@ -28,17 +29,24 @@ //! unrouted or rejected command is [`FactError::Permanent`]. use std::sync::Arc; +#[cfg(feature = "command-host")] use std::time::Duration; +#[cfg(feature = "command-host")] use distributed::cell_host::{CelldCommandHost, InternalHttpSecret}; +#[cfg(feature = "command-host")] use distributed::command_dispatch::{CommandHost, LocalCommandHost}; +#[cfg(feature = "command-host")] use distributed::graphql::identity::VerifiedPrincipal; -use distributed::microsvc::{CausalDispatchError, Session}; +#[cfg(feature = "command-host")] +use distributed::microsvc::CausalDispatchError; +use distributed::microsvc::Session; use serde_json::Value; use crate::cell::{command_id_for, session_stamp, trusted_session}; use crate::facts::{BoxFuture, Fact, FactCommand, FactError, FactReceipt, FactSink}; use crate::lifecycle::LIFECYCLE_COMMANDS; +#[cfg(feature = "command-host")] use crate::stamp::SESSION_PREFIX; type ShardFn = Arc Option + Send + Sync>; @@ -109,26 +117,41 @@ impl FactRoute { } } -/// A [`CommandHost`] that learns the fact routes it needs. -pub trait FactRouting { - /// Register `route` (a host that addresses aggregates by kind and shard - /// records it; one that routes by command ignores it). - fn register_fact_route(&mut self, route: &FactRoute); +/// One routed fact, ready for a [`FactHost`]. +#[derive(Debug, Clone)] +pub struct FactCall<'a> { + /// Durable command name. + pub command: &'a str, + /// Aggregate kind of the route. + pub kind: &'a str, + /// Validated shard (non-empty, printable ASCII, ≤ 256 bytes). + pub shard: String, + /// Deterministic command id ([`command_id_for`]). + pub command_id: String, + /// Command input. + pub input: &'a Value, + /// Verified principal of the fact (or the sink's system principal). + pub principal: String, + /// Trusted session: `x-user-id` + the `x-game-*` stamp. + pub session: Session, } -/// A service routes by command: its handler selects the stream. -impl FactRouting for LocalCommandHost { +/// What a [`CommandFactSink`] dispatches through: anything that runs one +/// durable command idempotently by command id. Implemented for +/// [`CelldCommandHost`] and [`LocalCommandHost`] (feature `command-host`) +/// and for the celld object host (feature `celld-zone`). +pub trait FactHost: Send + Sync + 'static { + /// Learn `route` (a host that addresses aggregates by kind and shard + /// records it; one that routes by command ignores it). fn register_fact_route(&mut self, _route: &FactRoute) {} -} -/// celld addresses cells: `{kind}/{shard}/{command}`. -impl FactRouting for CelldCommandHost { - fn register_fact_route(&mut self, route: &FactRoute) { - let shard = route.shard.clone(); - self.add_cell_route(route.command(), route.kind(), move |input, session| { - shard(input, session) - }); - } + /// Run `call` once per command id. Classify failures: unreachable, + /// 5xx, in progress → [`FactError::Retryable`]; anything else → + /// [`FactError::Permanent`]. + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result>; } /// See the module docs. @@ -150,7 +173,7 @@ impl Clone for CommandFactSink { } } -impl CommandFactSink { +impl CommandFactSink { /// A sink dispatching through `host` under command-ledger `service_id`; /// zone facts without a player use `system_principal`. pub fn new( @@ -202,6 +225,11 @@ impl CommandFactSink { &self.host } + /// The command-ledger service id. + pub fn service_id(&self) -> &str { + &self.service_id + } + /// The route a fact would take, if any. pub fn route_for(&self, command: &str) -> Option<&FactRoute> { self.routes.iter().find(|route| route.command == command) @@ -209,6 +237,15 @@ impl CommandFactSink { /// `(principal, trusted session, command id)` of a routed fact. pub fn prepare(&self, fact: &Fact) -> Result<(String, Session, String), FactError> { + let (_, _, principal, session, command_id) = self.resolve(fact)?; + Ok((principal, session, command_id)) + } + + #[allow(clippy::type_complexity)] + fn resolve( + &self, + fact: &Fact, + ) -> Result<(&FactRoute, String, String, Session, String), FactError> { let route = self.route_for(fact.command()).ok_or_else(|| { FactError::Permanent(format!("no route for fact command `{}`", fact.command())) })?; @@ -217,7 +254,7 @@ impl CommandFactSink { .unwrap_or(&self.system_principal) .to_string(); let session = trusted_session(&principal, fact); - route + let shard = route .shard(fact.input(), &session) .filter(|shard| { !shard.is_empty() @@ -232,6 +269,8 @@ impl CommandFactSink { )) })?; Ok(( + route, + shard, principal, session, command_id_for(&self.service_id, fact.key()), @@ -239,7 +278,27 @@ impl CommandFactSink { } } +impl FactSink for CommandFactSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + let (route, shard, principal, session, command_id) = self.resolve(fact)?; + self.host + .dispatch_fact(FactCall { + command: fact.command(), + kind: route.kind(), + shard, + command_id, + input: fact.input(), + principal, + session, + }) + .await + }) + } +} + /// celld slow, down or still running the command: keep the fact queued. +#[cfg(feature = "command-host")] fn classify(error: CausalDispatchError) -> FactError { let detail = format!("{}: {error:?}", error.code()); match &error { @@ -258,36 +317,69 @@ fn classify(error: CausalDispatchError) -> FactError { } } -impl FactSink for CommandFactSink { - fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { - Box::pin(async move { - let (principal, session, command_id) = self.prepare(fact)?; - let result = self - .host - .invoke( - fact.command(), - &command_id, - fact.input().clone(), - session, - VerifiedPrincipal::from_trusted_transport(&principal), - None, - ) - .await - .map_err(classify)?; - Ok(FactReceipt { - payload: result.payload().clone(), - replayed: result.replayed(), - }) +/// Any [`CommandHost`]: `invoke` with the fact's trusted session. +#[cfg(feature = "command-host")] +fn invoke_command_host<'a, H: CommandHost>( + host: &'a H, + call: FactCall<'a>, +) -> BoxFuture<'a, Result> { + Box::pin(async move { + let result = host + .invoke( + call.command, + &call.command_id, + call.input.clone(), + call.session, + VerifiedPrincipal::from_trusted_transport(&call.principal), + None, + ) + .await + .map_err(classify)?; + Ok(FactReceipt { + payload: result.payload().clone(), + replayed: result.replayed(), }) + }) +} + +/// A service routes by command: its handler selects the stream. +#[cfg(feature = "command-host")] +impl FactHost for LocalCommandHost { + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result> { + invoke_command_host(self, call) + } +} + +/// celld addresses cells: `{kind}/{shard}/{command}`. +#[cfg(feature = "command-host")] +impl FactHost for CelldCommandHost { + fn register_fact_route(&mut self, route: &FactRoute) { + let shard = route.shard.clone(); + self.add_cell_route(route.command(), route.kind(), move |input, session| { + shard(input, session) + }); + } + + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result> { + invoke_command_host(self, call) } } /// Default per-request timeout of [`CelldFactSink`]. +#[cfg(feature = "command-host")] pub const DEFAULT_CELLD_FACT_TIMEOUT: Duration = Duration::from_secs(10); /// Facts into celld cells over the internal path. +#[cfg(feature = "command-host")] pub type CelldFactSink = CommandFactSink; +#[cfg(feature = "command-host")] impl CommandFactSink { /// A sink for the cells at `celld_url` under command-ledger /// `service_id`: a remote-only [`CelldCommandHost`] forwarding the fact @@ -324,7 +416,7 @@ impl CommandFactSink { } } -#[cfg(test)] +#[cfg(all(test, feature = "command-host"))] mod tests { use super::*; use crate::stamp::FactStamp; diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs index baf00eb59..66e784662 100644 --- a/distributed_game/src/facts.rs +++ b/distributed_game/src/facts.rs @@ -320,6 +320,7 @@ pub struct FactQueue { in_flight: HashSet, capacity: usize, script: Option, + journal: Option>, } /// Worker-side handle consumed by [`FactFeed::run`]. @@ -342,6 +343,7 @@ pub fn fact_channel(capacity: usize, policy: RetryPolicy) -> (FactQueue, FactFee in_flight: HashSet::new(), capacity: capacity.max(1), script: None, + journal: None, }, FactFeed { shared, @@ -362,6 +364,9 @@ impl FactQueue { return Err(EmitError::Backpressure); } self.in_flight.insert(fact.key.clone()); + if let Some(journal) = self.journal.as_mut() { + journal.push(fact.clone()); + } if self.script.is_some() { return Ok(()); } @@ -374,6 +379,22 @@ impl FactQueue { Ok(()) } + /// Keep a copy of every accepted fact until [`take_journal`](Self::take_journal): + /// a host that keeps its own durable outbox writes them there right + /// after the tick that emitted them (the celld zone host does). + pub fn with_journal(mut self) -> Self { + self.journal = Some(Vec::new()); + self + } + + /// Facts accepted since the last call (empty without a journal). + pub fn take_journal(&mut self) -> Vec { + self.journal + .as_mut() + .map(std::mem::take) + .unwrap_or_default() + } + /// Settlements that arrived since the last call. pub fn drain(&mut self) -> Vec { let settled: Vec<_> = self.settlements.try_iter().collect(); diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs index 45b9106d9..cda03f58b 100644 --- a/distributed_game/src/host.rs +++ b/distributed_game/src/host.rs @@ -1014,6 +1014,16 @@ impl ZoneHost { self.core.in_flight() } + /// Facts emitted since the last call, when the fact queue keeps a + /// journal ([`FactQueue::with_journal`]); empty otherwise. + pub fn take_emitted_facts(&mut self) -> Vec { + self.core + .facts + .as_mut() + .map(FactQueue::take_journal) + .unwrap_or_default() + } + /// True after [`dispose`](Self::dispose). pub fn is_disposed(&self) -> bool { self.disposed diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs index 828b3a404..03fe2fdb8 100644 --- a/distributed_game/src/lib.rs +++ b/distributed_game/src/lib.rs @@ -13,6 +13,9 @@ //! priority accumulation. Wire format: [`protocol`] / `PROTOCOL.md`. //! - Transport (`net` feature): axum WebSocket server hosting many zones //! with HMAC-signed ticket admission ([`net`]). +//! - celld (`celld-zone` feature, wasm32): each zone is a celld Durable +//! Object; celld places, forwards, hibernates and recovers it +//! ([`celld_zone`]). //! //! - Authoring derives (re-exported from `distributed_game_macros`): //! `#[derive(Replicated)]` views generate a kind's schema and field @@ -56,10 +59,12 @@ pub mod bots; pub mod cell; #[cfg(feature = "celld")] pub mod celld; +#[cfg(feature = "celld-zone")] +pub mod celld_zone; pub mod claims; pub mod clock; pub mod codec; -#[cfg(feature = "command-host")] +#[cfg(feature = "cell")] pub mod command_sink; pub mod entity; pub mod facts; diff --git a/distributed_game/src/world/mod.rs b/distributed_game/src/world/mod.rs index 2183010e6..b07d536fa 100644 --- a/distributed_game/src/world/mod.rs +++ b/distributed_game/src/world/mod.rs @@ -14,10 +14,12 @@ //! - [`allocation`]: [`ZoneAllocation`] records written by the service that //! allocates a zone, read before the zone is created //! ([`ZoneActivation`], [`ZoneAllocationStore`]). -//! - `zone_status` (feature `cell`): the read model of every zone's lease -//! and hibernation slot, projected from the `zone_lease` / `zone_state` -//! cells' outward events (active / hibernated / cold without opening a -//! cell). +//! - `zone_activity` (feature `cell`): a celld-hosted zone's own lifecycle +//! reports (active / dormant / hibernated) as a cell. +//! - `zone_status` (feature `cell`): the read model of every zone's lease, +//! hibernation slot and activity, projected from the `zone_lease` / +//! `zone_state` / `zone_activity` cells' outward events (active / dormant +//! / hibernated / cold without opening a cell). //! - [`barrier`]: content-version policy types shared by the host and the //! world barrier ([`StalePolicy`], [`BarrierMode`]). @@ -28,6 +30,9 @@ pub mod ownership; pub mod state; pub mod topology; #[cfg(feature = "cell")] +#[allow(missing_docs)] +pub mod zone_activity; +#[cfg(feature = "cell")] // The `sourced` and `Snapshot` derives generate undocumented public items. #[allow(missing_docs)] pub mod zone_lease; diff --git a/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql b/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql new file mode 100644 index 000000000..368e212f4 --- /dev/null +++ b/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR (not a public field). +# The row is the zone's post-transition `ZoneActivityStatus`. +mutation SaveZoneActivity { + upsert_zone_activities(object: $input.activity) +} diff --git a/distributed_game/src/world/zone_activity.rs b/distributed_game/src/world/zone_activity.rs new file mode 100644 index 000000000..d9fbc31a3 --- /dev/null +++ b/distributed_game/src/world/zone_activity.rs @@ -0,0 +1,288 @@ +//! What a zone running as a celld object is doing, as a cell: +//! `ZoneActivity:{zone_id}` (cell kind [`ZONE_ACTIVITY_KIND`]). +//! +//! A zone hosted by [`celld_zone`](crate::celld_zone) reports its own +//! lifecycle — woke up (`active`, `restored` when it came back from a +//! snapshot), emptied (`dormant`), slept (`hibernated`) — as facts +//! ([`RecordActivity`], command [`RECORD`]) through its fact sink, so the +//! transitions are durable and exactly once like any other zone fact. +//! +//! | Command | Effect | Outward event | +//! |---|---|---| +//! | `zone_activity.record` | the reported status, if emitted after the one stored | `zone.activity_changed` | +//! +//! Facts can settle out of order (retries, concurrent commits): a report +//! emitted before the stored one ([`FactStamp::emission_order`]) is +//! ignored. The outward event carries the post-transition +//! [`ZoneActivityStatus`]; the [`zone_status`](super::zone_status) read model +//! projects it into `zone_activity` rows (minimaps, dashboards). +//! +//! Only the zone itself may report: the fact's principal must be the +//! zone's system principal [`zone_principal`]`(zone)`, and the stamp's zone +//! is the shard. +//! +//! `node` and `isolate` are debug details (which celld node and V8 isolate +//! ran the activation, when known); nothing may route by them. + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +use crate::cell::session_stamp; +use crate::FactStamp; + +/// Aggregate type (cell `ZoneActivity:{zone_id}`). +pub const ZONE_ACTIVITY: &str = "ZoneActivity"; +/// Cell kind (URL segment / Durable Object routing) of zone-activity cells. +pub const ZONE_ACTIVITY_KIND: &str = "zone-activity"; +/// The one command (a zone fact). +pub const RECORD: &str = "zone_activity.record"; + +/// Status: ticking with players (or just woke up). +pub const ACTIVITY_ACTIVE: &str = "active"; +/// Status: empty, still in memory, snapshot written. +pub const ACTIVITY_DORMANT: &str = "dormant"; +/// Status: asleep; the next join restores the snapshot. +pub const ACTIVITY_HIBERNATED: &str = "hibernated"; + +/// The system principal a zone reports its own activity under. +pub fn zone_principal(zone_id: &str) -> String { + format!("zone:{zone_id}") +} + +/// One zone's activity. +#[derive(Clone, Debug, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct ZoneActivity { + entity: Entity, + status: String, + activation: String, + restored: bool, + players: u32, + node: String, + isolate: String, + activations: u64, + changed_at_ms: u64, + /// Ordering key of the report that set the current status. + last: Option, +} + +/// The emission-order key of the last applied report. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StampKey { + /// Zone. + pub zone_id: String, + /// Activation epoch. + pub activation: u64, + /// Tick. + pub tick: u64, + /// Emission wall time. + pub emitted_at_ms: u64, + /// Emission sequence. + pub seq: u64, +} + +impl StampKey { + fn of(stamp: &FactStamp) -> Self { + Self { + zone_id: stamp.zone_id.clone(), + activation: stamp.activation, + tick: stamp.tick, + emitted_at_ms: stamp.emitted_at_ms, + seq: stamp.seq, + } + } + + fn stamp(&self) -> FactStamp { + FactStamp { + zone_id: self.zone_id.clone(), + activation: self.activation, + tick: self.tick, + emitted_at_ms: self.emitted_at_ms, + seq: self.seq, + ..FactStamp::default() + } + } +} + +/// The public state carried by `zone.activity_changed`: one +/// `zone_activity` read-model row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::DomainState)] +#[domain_state(version = 1)] +pub struct ZoneActivityStatus { + /// Zone (the cell's stream id). + pub zone_id: String, + /// [`ACTIVITY_ACTIVE`], [`ACTIVITY_DORMANT`] or [`ACTIVITY_HIBERNATED`]. + pub status: String, + /// Id of the object activation that reported it. + pub activation: String, + /// That activation restored a snapshot. + pub restored: bool, + /// Players in the zone when reported. + pub players: u32, + /// celld node running the activation (debug; empty when unknown). + pub node: String, + /// V8 isolate running the activation (debug). + pub isolate: String, + /// Activations seen so far. + pub activations: u64, + /// When the zone reported it (zone clock, Unix ms). + pub changed_at_ms: u64, +} + +impl From<&ZoneActivity> for ZoneActivityStatus { + fn from(activity: &ZoneActivity) -> Self { + Self { + zone_id: activity.entity.id().to_string(), + status: activity.status.clone(), + activation: activity.activation.clone(), + restored: activity.restored, + players: activity.players, + node: activity.node.clone(), + isolate: activity.isolate.clone(), + activations: activity.activations, + changed_at_ms: activity.changed_at_ms, + } + } +} + +#[sourced( + entity, + aggregate_type = "ZoneActivity", + events = "ZoneActivityEvent", + domain_state = ZoneActivityStatus +)] +impl ZoneActivity { + #[event("zone.activity_changed", version = 1, domain)] + fn changed(&mut self, zone_id: String, report: RecordActivity, stamp: StampKey) { + if self.entity.id().is_empty() { + self.entity.set_id(zone_id); + } + if report.activation != self.activation { + self.activations += 1; + } + self.status = report.status; + self.activation = report.activation; + self.restored = report.restored; + self.players = report.players; + self.node = report.node; + self.isolate = report.isolate; + self.changed_at_ms = stamp.emitted_at_ms; + self.last = Some(stamp); + } +} + +impl ZoneActivity { + /// Current status (empty before the first report). + pub fn status(&self) -> &str { + &self.status + } + + /// The public row. + pub fn row(&self) -> ZoneActivityStatus { + self.into() + } +} + +/// `zone_activity.record` input: what the zone reports about itself. +#[derive( + Debug, + Clone, + PartialEq, + Eq, + Default, + Serialize, + Deserialize, + distributed::CommandInput, + crate::FactCommand, +)] +#[fact(command = "zone_activity.record")] +pub struct RecordActivity { + /// [`ACTIVITY_ACTIVE`], [`ACTIVITY_DORMANT`] or [`ACTIVITY_HIBERNATED`]. + pub status: String, + /// Object activation id. + pub activation: String, + /// The activation restored a snapshot. + pub restored: bool, + /// Players present. + pub players: u32, + /// celld node (debug; empty when unknown). + pub node: String, + /// V8 isolate (debug). + pub isolate: String, +} + +/// The applied (or ignored) report. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, distributed::CommandOutput)] +pub struct ActivityApplied { + /// False when a later-emitted report already set the status. + pub applied: bool, + /// The status after the command. + pub status: String, +} + +fn rejected(message: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(message.to_string()) +} + +async fn handle_record( + ctx: &CausalCommandContext<'_, ZoneActivity>, + input: RecordActivity, +) -> Result>, HandlerError> { + if ![ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED].contains(&input.status.as_str()) { + return Err(rejected(format!("unknown activity `{}`", input.status))); + } + let stamp = session_stamp(ctx.session()) + .ok_or_else(|| rejected("activity reports are zone facts and need a fact stamp"))?; + if ctx.user_id()? != zone_principal(&stamp.zone_id) { + return Err(rejected("only the zone itself reports its activity")); + } + let repo = ctx.repo(); + let mut activity = match repo.get(&stamp.zone_id).await? { + Some(activity) => activity, + None => repo.create(), + }; + let newer = activity + .last + .as_ref() + .is_none_or(|last| last.stamp().emission_order(&stamp) == std::cmp::Ordering::Less); + if !newer { + let status = activity.status.clone(); + return repo.commit(activity)?.succeeded(ActivityApplied { + applied: false, + status, + }); + } + let status = input.status.clone(); + activity + .changed(stamp.zone_id.clone(), input, StampKey::of(&stamp)) + .map_err(rejected)?; + repo.publish_events() + .commit(activity)? + .succeeded(ActivityApplied { + applied: true, + status, + }) +} + +struct Record; +impl PortableCommand for Record +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + RECORD, + )) + .handle(handle_record) + } +} + +/// Mount the zone-activity command on a `ZoneActivity` cell. +pub fn mount_zone_activity(cell: AggregateCell) -> AggregateCell { + cell.mount(Record) +} diff --git a/distributed_game/src/world/zone_status.rs b/distributed_game/src/world/zone_status.rs index 2d029ec22..5ac3d4f12 100644 --- a/distributed_game/src/world/zone_status.rs +++ b/distributed_game/src/world/zone_status.rs @@ -8,11 +8,15 @@ //! |---|---|---| //! | [`ZoneLease`](super::zone_lease::ZoneLease) | `zone.activated`, `zone.released`, `zone.lease_expired` | [`ZoneLeases`] (`zone_leases`) | //! | [`ZoneState`](super::zone_state::ZoneState) | `zone_state.saved`, `zone_state.deleted` | [`ZoneSnapshots`] (`zone_snapshots`) | +//! | [`ZoneActivity`](super::zone_activity::ZoneActivity) (zones hosted as celld objects) | `zone.activity_changed` | [`ZoneActivities`] (`zone_activities`) | //! //! Each event carries its cell's post-transition state, so a row is an -//! upsert of the body ([`ZONE_LEASES`], [`ZONE_SNAPSHOTS`]); the projector -//! runtime orders and deduplicates per stream. [`ZoneStatus::of`] combines -//! a zone's two rows. Mount [`projectors`] on a consumer service (any read +//! upsert of the body ([`ZONE_LEASES`], [`ZONE_SNAPSHOTS`], +//! [`ZONE_ACTIVITIES`]); the projector runtime orders and deduplicates per +//! stream. [`ZoneStatus::of`] combines a zone's rows: a zone hosted as a +//! celld object ([`crate::celld_zone`]) has only an activity row (active / +//! dormant / hibernated); a zone on the native multi-host server has lease +//! and snapshot rows. Mount [`projectors`] on a consumer service (any read //! model store: SQLite, Postgres) fed by the bus the cells' outbox reaches. //! //! The read model is eventually consistent: it is for views (world maps, @@ -27,6 +31,9 @@ use distributed::{ }; use serde::{Deserialize, Serialize}; +use super::zone_activity::{ + ZoneActivityActivityChangedDomainEvent, ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED, +}; use super::zone_lease::{ ZoneLeaseActivatedDomainEvent, ZoneLeaseLeaseExpiredDomainEvent, ZoneLeaseReleasedDomainEvent, STATUS_ACTIVE, @@ -44,6 +51,10 @@ pub const SNAPSHOTS_PROJECTOR: &str = "project_zone_snapshots"; pub const LEASES_EPOCH: &str = "zone-leases-v1"; /// Epoch of [`ZONE_SNAPSHOTS`]. pub const SNAPSHOTS_EPOCH: &str = "zone-snapshots-v1"; +/// Projector of [`ZoneActivities`]. +pub const ACTIVITIES_PROJECTOR: &str = "project_zone_activities"; +/// Epoch of [`ZONE_ACTIVITIES`]. +pub const ACTIVITIES_EPOCH: &str = "zone-activities-v1"; /// One `zone_leases` row: the last lease transition of a zone /// ([`ZoneLeaseStatus`](super::zone_lease::ZoneLeaseStatus); the type is @@ -80,6 +91,39 @@ pub struct ZoneSnapshots { pub bytes: i64, } +/// One `zone_activities` row: what a zone hosted as a celld object last +/// reported about itself +/// ([`ZoneActivityStatus`](super::zone_activity::ZoneActivityStatus)). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] +#[table("zone_activities")] +pub struct ZoneActivities { + /// Zone id. + #[id("zone_id")] + pub zone_id: String, + /// `active`, `dormant` or `hibernated`. + pub status: String, + /// Object activation id. + pub activation: String, + /// The activation restored a snapshot. + pub restored: bool, + /// Players when reported. + pub players: i64, + /// celld node of the activation (debug; empty when unknown). + pub node: String, + /// V8 isolate of the activation (debug). + pub isolate: String, + /// Activations seen. + pub activations: i64, + /// When the zone reported it (Unix ms). + pub changed_at_ms: i64, +} + +/// Upsert a [`ZoneActivities`] row from a `zone.activity_changed` body. +#[allow(non_snake_case)] +pub fn SaveZoneActivity() -> Mutation<()> { + mutation_file!("src/world/mutations/save_zone_activity.mutation.graphql") +} + /// Upsert a [`ZoneLeases`] from a lease event's state body. #[allow(non_snake_case)] pub fn SaveZoneLease() -> Mutation<()> { @@ -124,11 +168,52 @@ distributed::projection! { }; } -/// Physical read-model catalog (`zone_leases`, `zone_snapshots`). +distributed::projection! { + pub const ZONE_ACTIVITIES: ProjectionDescriptor = { + name: "project_zone_activities", + version: 1, + epoch: "zone-activities-v1", + model: ZoneActivities, + on { + events: [ZoneActivityActivityChangedDomainEvent], + mutation: SaveZoneActivity, + input: { activity: body }, + }, + }; +} + +/// Physical read-model catalog (`zone_leases`, `zone_snapshots`, +/// `zone_activities`). pub fn read_model_catalog() -> ReadModelCatalog { ReadModelCatalog::new(APPLICATION) .table_schema(ZoneLeases::schema().clone()) .table_schema(ZoneSnapshots::schema().clone()) + .table_schema(ZoneActivities::schema().clone()) +} + +/// The modeled projector of [`ZoneActivities`] alone (a consumer that +/// shows celld-hosted zones, e.g. a minimap service), applying +/// [`ZONE_ACTIVITIES`]. Mount it on a consumer service named +/// [`APPLICATION`] (or any name of the caller's, with its own cursor). +pub fn activity_projector() -> SurfaceProjector { + activity_projector_for(APPLICATION) +} + +/// [`activity_projector`] owned by `application` (when the consumer service +/// is not named [`APPLICATION`]). +pub fn activity_projector_for(application: &str) -> SurfaceProjector { + LocalProjectionMountsBuilder::new(application, "ordered-domain-events") + .expect("projection source") + .eventual_model::( + ACTIVITIES_PROJECTOR, + ZONE_ACTIVITIES, + ACTIVITIES_EPOCH, + ) + .expect("zone activities mount") + .build() + .expect("projection catalog") + .projector(ACTIVITIES_PROJECTOR) + .expect("zone activities projector") } /// The modeled projector mounts `(leases, snapshots)`: mount both on one @@ -157,11 +242,16 @@ pub fn projectors() -> (SurfaceProjector, SurfaceProjector) { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "state", rename_all = "camelCase")] pub enum ZoneStatus { - /// A holder has the lease. + /// Running: a holder has the lease (native multi-host server; `holder` + /// is the host) or a celld object reported `active` (`holder` is its + /// node when known, a debug detail). Active { - /// The lease holder. + /// The lease holder, or the celld node (may be empty). holder: String, }, + /// A celld-hosted zone that emptied: still in memory, snapshot written, + /// about to hibernate. + Dormant, /// No holder; a hibernation snapshot is stored. Hibernated { /// Snapshot size in bytes. @@ -172,6 +262,18 @@ pub enum ZoneStatus { } impl ZoneStatus { + /// The status of a celld-hosted zone from its activity row. + pub fn of_activity(activity: Option<&ZoneActivities>) -> Self { + match activity.map(|row| row.status.as_str()) { + Some(ACTIVITY_ACTIVE) => Self::Active { + holder: activity.map(|row| row.node.clone()).unwrap_or_default(), + }, + Some(ACTIVITY_DORMANT) => Self::Dormant, + Some(ACTIVITY_HIBERNATED) => Self::Hibernated { bytes: 0 }, + _ => Self::Cold, + } + } + /// Combine a zone's rows (either may be missing). pub fn of(lease: Option<&ZoneLeases>, snapshot: Option<&ZoneSnapshots>) -> Self { if let Some(lease) = lease.filter(|lease| lease.status == STATUS_ACTIVE) { @@ -224,7 +326,28 @@ mod tests { assert_eq!(ZoneStatus::of(None, None), ZoneStatus::Cold); // The projections compile against the cells' outward events. let (leases, snapshots) = projectors(); - drop((leases, snapshots)); - assert_eq!(read_model_catalog().tables.len(), 2); + drop((leases, snapshots, activity_projector())); + assert_eq!(read_model_catalog().tables.len(), 3); + let activity = |status: &str| ZoneActivities { + zone_id: "z".into(), + status: status.into(), + node: "node-a".into(), + ..ZoneActivities::default() + }; + assert_eq!( + ZoneStatus::of_activity(Some(&activity("active"))), + ZoneStatus::Active { + holder: "node-a".into() + } + ); + assert_eq!( + ZoneStatus::of_activity(Some(&activity("dormant"))), + ZoneStatus::Dormant + ); + assert_eq!( + ZoneStatus::of_activity(Some(&activity("hibernated"))), + ZoneStatus::Hibernated { bytes: 0 } + ); + assert_eq!(ZoneStatus::of_activity(None), ZoneStatus::Cold); } } diff --git a/distributed_game/tests/celld_zone/main.rs b/distributed_game/tests/celld_zone/main.rs new file mode 100644 index 000000000..37b9f5017 --- /dev/null +++ b/distributed_game/tests/celld_zone/main.rs @@ -0,0 +1,420 @@ +//! Zones as celld Durable Objects (`celld_zone`), end to end against +//! `tests/celld/zone-worker` (a tally zone, its Tally cells and its +//! ZoneActivity cell): +//! +//! - `single_node`: `celld dev`. Join with a ticket, input, facts settle in +//! the player's cell, the empty zone goes dormant then hibernated, a new +//! join wakes it with its state, tickets and transfer tickets are single +//! use, a doorway hands the player to the next zone. +//! - `fleet`: three celld nodes in production mode on one RustFS bucket +//! (docker compose). A zone is reached through a node that does not own +//! it, the owner is killed while 200 facts are in flight: the socket +//! closes with 1012, the client rejoins through another node, the zone +//! restores, and every fact reaches the cell exactly once. +//! +//! ```text +//! (cd tests/celld/zone-worker && worker-build --release) +//! CELLD_BIN=… CELLD_ESBUILD=… cargo test -p distributed_game \ +//! --features celld,net --test celld_zone +//! ``` +//! +//! Skips without a built worker / celld (and, for `fleet`, docker and the +//! aws CLI) unless `CELLD_ZONE_REQUIRED=1`. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use distributed_game::protocol::{error, ClientMessage, Hello, ServerMessage, PROTOCOL_VERSION}; +use distributed_game::ticket::TicketKey; +use distributed_game::{Role, TicketClaims}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::Value; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::tungstenite::Message; + +#[path = "../support/celld.rs"] +mod celld_support; +#[path = "../support/fleet.rs"] +mod fleet; + +const INTERNAL_SECRET: &str = "test-only-internal-secret-change-me-2026"; +const TICKET_SECRET: &str = "test-only-ticket-secret-change-me-2026"; +const REQUIRED: &str = "CELLD_ZONE_REQUIRED"; + +fn worker() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/celld/zone-worker") +} + +fn ticket(principal: &str, zone: &str) -> String { + let exp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + + 120; + let nonce = format!( + "{principal}-{zone}-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + TicketKey::new(TICKET_SECRET) + .sign(&TicketClaims::new(principal, zone, exp, nonce, Role::Player).with_name(principal)) +} + +type Ws = + tokio_tungstenite::WebSocketStream>; + +#[derive(Debug)] +enum Got { + Server(ServerMessage), + Closed(Option), +} + +struct Player { + ws: Ws, + seq: u32, +} + +impl Player { + async fn connect(base: &str, zone: &str) -> Self { + Self::try_connect(base, zone).await.expect("connect") + } + + async fn try_connect(base: &str, zone: &str) -> Result { + let url = format!("{}/rooms/{zone}", base.replacen("http://", "ws://", 1)); + let (ws, _) = tokio_tungstenite::connect_async(url) + .await + .map_err(|e| e.to_string())?; + Ok(Self { ws, seq: 0 }) + } + + async fn send(&mut self, message: ClientMessage) { + self.ws + .send(Message::Binary(message.encode().into())) + .await + .expect("send"); + } + + async fn hello(&mut self, ticket: &str) { + self.send(ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: String::new(), + capabilities: 0, + ticket: ticket.into(), + reconnect_token: String::new(), + })) + .await; + } + + async fn input(&mut self, payload: &[u8]) { + self.seq += 1; + self.send(ClientMessage::Input { + seq: self.seq, + client_tick: 0, + payload: payload.to_vec(), + }) + .await; + } + + async fn next(&mut self, within: Duration) -> Option { + let deadline = Instant::now() + within; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + let frame = tokio::time::timeout(left, self.ws.next()).await.ok()?; + match frame { + Some(Ok(Message::Binary(bytes))) => match ServerMessage::decode(&bytes, &()) { + Ok(message) => return Some(Got::Server(message)), + // Deltas need the Welcome's schema; these tests skip them. + Err(_) => continue, + }, + Some(Ok(Message::Close(frame))) => { + return Some(Got::Closed(frame.map(|f| u16::from(f.code)))) + } + Some(Ok(_)) => continue, + Some(Err(_)) | None => return Some(Got::Closed(None)), + } + } + } + + /// The first message matching `pick`, skipping others (Deltas, Pongs). + async fn expect( + &mut self, + within: Duration, + what: &str, + mut pick: impl FnMut(&Got) -> Option, + ) -> T { + let deadline = Instant::now() + within; + while let Some(got) = self + .next(deadline.saturating_duration_since(Instant::now())) + .await + { + if let Some(value) = pick(&got) { + return value; + } + if let Got::Closed(code) = got { + panic!("closed ({code:?}) while waiting for {what}"); + } + } + panic!("timed out waiting for {what}"); + } + + async fn welcome(&mut self) { + self.expect(Duration::from_secs(20), "Welcome", |got| match got { + Got::Server(ServerMessage::Welcome(_)) => Some(()), + Got::Server(ServerMessage::Error { code, message }) => { + panic!("join refused: {code} {message}") + } + _ => None, + }) + .await + } + + /// Event `type_id` carrying a u64 total. + async fn total(&mut self, type_id: u32) -> u64 { + self.expect(Duration::from_secs(20), "a total event", |got| match got { + Got::Server(ServerMessage::Event { + type_id: t, + payload, + .. + }) if *t == type_id => Some(u64::from_le_bytes(payload[..8].try_into().unwrap())), + _ => None, + }) + .await + } + + async fn refused(&mut self) -> u32 { + self.expect(Duration::from_secs(20), "an Error", |got| match got { + Got::Server(ServerMessage::Error { code, .. }) => Some(*code), + Got::Server(ServerMessage::Welcome(_)) => panic!("admitted a used ticket"), + _ => None, + }) + .await + } +} + +/// GET a JSON route with the internal secret (Null on any failure: the +/// callers poll). +async fn get(base: &str, path: &str) -> Value { + let response = reqwest::Client::new() + .get(format!("{base}{path}")) + .header("x-distributed-internal-secret", INTERNAL_SECRET) + .send() + .await + .and_then(|r| r.error_for_status()); + match response { + Ok(response) => response.json().await.unwrap_or(Value::Null), + Err(_) => Value::Null, + } +} + +/// Poll `path` until `ok` (or panic after `within`). +async fn until(base: &str, path: &str, within: Duration, ok: impl Fn(&Value) -> bool) -> Value { + let deadline = Instant::now() + within; + loop { + let value = get(base, path).await; + if ok(&value) { + return value; + } + assert!(Instant::now() < deadline, "{path}: last {value}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } +} + +fn status(value: &Value) -> &str { + value["activity"]["status"].as_str().unwrap_or("") +} + +fn exactly_once(value: &Value, count: u64) -> bool { + let hits: Vec<&str> = value["hits"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let distinct: std::collections::HashSet<_> = hits.iter().collect(); + assert_eq!( + distinct.len(), + hits.len(), + "a fact committed twice: {value}" + ); + hits.len() as u64 == count +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn single_node() { + let Some(celld) = celld_support::Celld::start_worker(&worker(), REQUIRED) else { + return; + }; + let base = celld.base(); + let long = Duration::from_secs(30); + + // Join, input, facts. + let mut ana = Player::connect(&base, "room-a").await; + let first = ticket("ana", "room-a"); + ana.hello(&first).await; + ana.welcome().await; + assert_eq!(ana.total(1).await, 0); + let active = until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "active" + }) + .await; + assert_eq!(active["activity"]["restored"], false); + ana.input(&[1, 5]).await; + assert_eq!(ana.total(2).await, 5); + until(&base, "/tally/ana", long, |v| exactly_once(v, 5)).await; + + // A used ticket is refused. + let mut replay = Player::connect(&base, "room-a").await; + replay.hello(&first).await; + assert_eq!(replay.refused().await, error::UNAUTHORIZED); + + // Empty: dormant, then hibernated (dropped from memory). + ana.send(ClientMessage::Leave).await; + until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "dormant" + }) + .await; + until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "hibernated" + }) + .await; + let info = get(&base, "/rooms/room-a/info").await; + assert_eq!(info["awake"], false, "{info}"); + + // Wake with state. + let mut ana = Player::connect(&base, "room-a").await; + ana.hello(&ticket("ana", "room-a")).await; + ana.welcome().await; + assert_eq!(ana.total(1).await, 5, "restored from the snapshot"); + let woke = until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "active" + }) + .await; + assert_eq!(woke["activity"]["restored"], true); + assert!(woke["activity"]["activations"].as_u64().unwrap() >= 2); + + // A doorway: handoff to room-b with a single-use transfer ticket. + ana.input(&[2, b'b']).await; + let transfer = ana + .expect(long, "Handoff", |got| match got { + Got::Server(ServerMessage::Handoff { + target_zone, + transfer_ticket, + }) => { + assert_eq!(target_zone, "room-b"); + Some(transfer_ticket.clone()) + } + _ => None, + }) + .await; + let mut ana_b = Player::connect(&base, "room-b").await; + ana_b.hello(&transfer).await; + ana_b.welcome().await; + let mut again = Player::connect(&base, "room-b").await; + again.hello(&transfer).await; + assert_eq!(again.refused().await, error::UNAUTHORIZED); + ana_b.input(&[1, 3]).await; + assert_eq!(ana_b.total(2).await, 3); + until(&base, "/tally/ana", long, |v| exactly_once(v, 8)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fleet() { + let Some(mut fleet) = + fleet::Fleet::start(&worker(), 3, &[("CELLD_ZONE_NODES", "{nodes}")], REQUIRED) + else { + return; + }; + let long = Duration::from_secs(60); + // First touch through node-a places the zone (celld: first touch). + let a = fleet.base(0); + let mut probe = Player::connect(&a, "room-x").await; + probe.hello(&ticket("probe", "room-x")).await; + probe.welcome().await; + let info = until(&a, "/rooms/room-x/info", long, |v| { + v["node"].as_str().is_some_and(|n| !n.is_empty()) + }) + .await; + let owner = fleet + .index(info["node"].as_str().unwrap()) + .expect("known node"); + probe.send(ClientMessage::Leave).await; + // Empty: the zone writes its snapshot and goes dormant. + until(&a, "/zone-activity/room-x", long, |v| { + status(v) == "dormant" + }) + .await; + let via = (owner + 1) % 3; + let rejoin_via = (owner + 2) % 3; + + // Play through a node that does not own the zone (forwarded). + let mut bo = Player::connect(&fleet.base(via), "room-x").await; + bo.hello(&ticket("bo", "room-x")).await; + bo.welcome().await; + bo.input(&[1, 200]).await; + assert_eq!(bo.total(2).await, 200); + // Crash the owner once the 200 facts are in the zone's outbox (written + // right after the tick that emitted them); some may already be + // committed, most are in flight. + until(&a, "/rooms/room-x/info", long, |v| { + v["spooledFacts"].as_u64().unwrap_or(0) >= 200 + }) + .await; + fleet.kill(owner); + let closed = bo + .expect(Duration::from_secs(30), "the close", |got| match got { + Got::Closed(code) => Some(*code), + _ => None, + }) + .await; + assert_eq!( + closed, + Some(u16::from(CloseCode::Restart)), + "a forwarded socket of a crashed zone closes with 1012" + ); + + // Rejoin through the third node: celld recovers the zone elsewhere. + let base = fleet.base(rejoin_via); + let deadline = Instant::now() + long; + let (_bo, restored) = loop { + let mut bo = match Player::try_connect(&base, "room-x").await { + Ok(bo) => bo, + // celld answers 500 until the dead owner's lease expires. + Err(_) => { + assert!(Instant::now() < deadline, "the zone never came back"); + tokio::time::sleep(Duration::from_millis(500)).await; + continue; + } + }; + bo.hello(&ticket("bo", "room-x")).await; + let got = bo + .expect( + Duration::from_secs(20), + "Welcome or Error", + |got| match got { + Got::Server(ServerMessage::Welcome(_)) => Some(true), + Got::Server(ServerMessage::Error { .. }) => Some(false), + Got::Closed(_) => Some(false), + _ => None, + }, + ) + .await; + if got { + let total = bo.total(1).await; + break (bo, total); + } + assert!(Instant::now() < deadline, "the zone never came back"); + tokio::time::sleep(Duration::from_millis(500)).await; + }; + assert!(restored <= 200, "restored total {restored}"); + // Every hit the zone emitted reaches the cell exactly once. + until(&base, "/tally/bo", long, |v| exactly_once(v, 200)).await; + let activity = until(&base, "/zone-activity/room-x", long, |v| { + status(v) == "active" && v["activity"]["restored"] == true + }) + .await; + assert_ne!( + activity["activity"]["node"].as_str().unwrap_or(""), + fleet.nodes[owner].name, + "recovered on a live node" + ); +} diff --git a/distributed_game/tests/support/celld.rs b/distributed_game/tests/support/celld.rs index 1efd2fffa..03d2ce17d 100644 --- a/distributed_game/tests/support/celld.rs +++ b/distributed_game/tests/support/celld.rs @@ -26,13 +26,23 @@ pub struct Celld { impl Celld { pub fn start_new() -> Option { - let build = worker_dir().join("build"); + Self::start_worker(&worker_dir(), "CELLD_FACTS_REQUIRED") + } + + /// `celld dev` serving the built worker in `dir`; skips (None) when it + /// is not built or celld cannot start, unless env `required` is set. + pub fn start_worker(dir: &Path, required: &str) -> Option { + let build = dir.join("build"); if !build.join("worker/shim.mjs").exists() { assert!( - std::env::var_os("CELLD_FACTS_REQUIRED").is_none(), - "CELLD_FACTS_REQUIRED is set but the fact worker is not built" + std::env::var_os(required).is_none(), + "{required} is set but {} is not built", + dir.display() + ); + eprintln!( + "skipping: build {} first (worker-build --release)", + dir.display() ); - eprintln!("skipping celld fact routing: build tests/celld/fact-worker first"); return None; } let project = std::env::temp_dir().join(format!( @@ -44,11 +54,7 @@ impl Celld { .as_nanos() )); copy_dir(&build, &project.join("build")); - std::fs::copy( - worker_dir().join("wrangler.jsonc"), - project.join("wrangler.jsonc"), - ) - .unwrap(); + std::fs::copy(dir.join("wrangler.jsonc"), project.join("wrangler.jsonc")).unwrap(); let port = TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() @@ -62,10 +68,10 @@ impl Celld { }; if let Err(reason) = celld.start() { assert!( - std::env::var_os("CELLD_FACTS_REQUIRED").is_none(), + std::env::var_os(required).is_none(), "celld dev is required but did not start: {reason}" ); - eprintln!("skipping celld fact routing: {reason}"); + eprintln!("skipping: {reason}"); return None; } Some(celld) @@ -100,7 +106,10 @@ impl Celld { let log = std::fs::File::create(&log_path).unwrap(); let child = Command::new(&binary) .args(&args) - .env("RUST_LOG", "warn") + .env( + "RUST_LOG", + std::env::var("CELLD_RUST_LOG").unwrap_or_else(|_| "warn".into()), + ) .stdin(Stdio::null()) .stdout(log.try_clone().unwrap()) .stderr(log) @@ -200,7 +209,7 @@ impl Drop for Celld { } } -fn copy_dir(from: &Path, to: &Path) { +pub fn copy_dir(from: &Path, to: &Path) { std::fs::create_dir_all(to).unwrap(); for entry in std::fs::read_dir(from).unwrap() { let entry = entry.unwrap(); @@ -213,7 +222,7 @@ fn copy_dir(from: &Path, to: &Path) { } } -fn blocking_get(url: &str) -> Option { +pub fn blocking_get(url: &str) -> Option { let url = url.strip_prefix("http://")?; let (host, path) = url.split_once('/')?; let mut stream = std::net::TcpStream::connect(host).ok()?; diff --git a/distributed_game/tests/support/fleet.rs b/distributed_game/tests/support/fleet.rs new file mode 100644 index 000000000..9eb7231be --- /dev/null +++ b/distributed_game/tests/support/fleet.rs @@ -0,0 +1,308 @@ +//! A local multi-node celld fleet owned by one test: one RustFS container +//! (docker compose, its own project and port) holding the fleet bucket, the +//! worker deployed to it with `celld deploy`, and N `celld` nodes in +//! production mode. Kills only what it started; removes the container on +//! drop. Skips (None) without docker / aws / a built worker unless env +//! `required` is set. + +#![allow(dead_code)] + +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use super::celld_support::{blocking_get, copy_dir}; + +const ACCESS_KEY: &str = "fleettest"; +const SECRET_KEY: &str = "fleettestsecret123"; + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() +} + +pub struct Node { + pub name: String, + pub public: u16, + pub operator: u16, + child: Option, +} + +pub struct Fleet { + dir: PathBuf, + project: String, + s3_port: u16, + bucket: String, + binary: String, + pub nodes: Vec, +} + +fn skip(required: &str, reason: String) -> Option { + assert!( + std::env::var_os(required).is_none(), + "{required} is set but the fleet is unavailable: {reason}" + ); + eprintln!("skipping the celld fleet test: {reason}"); + None +} + +impl Fleet { + /// Start `nodes` nodes serving the worker in `worker` with extra + /// string `vars` (`{nodes}` in a value is replaced by the operator + /// listeners, `node-a=127.0.0.1:p,…`). + pub fn start( + worker: &Path, + nodes: usize, + vars: &[(&str, &str)], + required: &str, + ) -> Option { + if !worker.join("build/worker/shim.mjs").exists() { + return skip(required, format!("build {} first", worker.display())); + } + for tool in ["docker", "aws"] { + if Command::new(tool).arg("--version").output().is_err() { + return skip(required, format!("`{tool}` is not available")); + } + } + let binary = std::env::var("CELLD_BIN").unwrap_or_else(|_| "celld".into()); + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let dir = std::env::temp_dir().join(format!( + "distributed-celld-fleet-{}-{stamp}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut fleet = Self { + project: format!("dg-fleet-{}-{}", std::process::id(), stamp % 100_000), + s3_port: free_port(), + bucket: "dg-fleet".into(), + binary, + nodes: Vec::new(), + dir, + }; + for i in 0..nodes { + fleet.nodes.push(Node { + name: format!("node-{}", (b'a' + i as u8) as char), + public: free_port(), + operator: free_port(), + child: None, + }); + } + if let Err(reason) = fleet.s3_up() { + return skip(required, reason); + } + let listeners = fleet + .nodes + .iter() + .map(|n| format!("{}=127.0.0.1:{}", n.name, n.operator)) + .collect::>() + .join(","); + let vars: Vec<(String, String)> = vars + .iter() + .map(|(k, v)| (k.to_string(), v.replace("{nodes}", &listeners))) + .collect(); + if let Err(reason) = fleet.deploy(worker, &vars) { + return skip(required, reason); + } + for i in 0..fleet.nodes.len() { + if let Err(reason) = fleet.start_node(i) { + return skip(required, reason); + } + } + Some(fleet) + } + + fn env(&self, command: &mut Command) { + command + .env("AWS_ACCESS_KEY_ID", ACCESS_KEY) + .env("AWS_SECRET_ACCESS_KEY", SECRET_KEY) + .env("AWS_REGION", "us-east-1") + .env("S3_ENDPOINT", self.endpoint()); + } + + fn endpoint(&self) -> String { + format!("http://127.0.0.1:{}", self.s3_port) + } + + fn s3_up(&self) -> Result<(), String> { + let compose = self.dir.join("s3-compose.yaml"); + std::fs::write( + &compose, + format!( + "services:\n s3:\n image: rustfs/rustfs:1.0.3\n command: [\"/data\"]\n environment:\n RUSTFS_ADDRESS: \"0.0.0.0:9000\"\n RUSTFS_ACCESS_KEY: {ACCESS_KEY}\n RUSTFS_SECRET_KEY: {SECRET_KEY}\n ports: [\"127.0.0.1:{}:9000\"]\n", + self.s3_port + ), + ) + .unwrap(); + let up = Command::new("docker") + .args(["compose", "-p", &self.project, "-f"]) + .arg(&compose) + .args(["up", "-d"]) + .output() + .map_err(|e| format!("docker compose: {e}"))?; + if !up.status.success() { + return Err(format!( + "docker compose up: {}", + String::from_utf8_lossy(&up.stderr) + )); + } + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let mut mb = Command::new("aws"); + self.env(&mut mb); + let made = mb + .args(["--endpoint-url", &self.endpoint(), "s3", "mb"]) + .arg(format!("s3://{}", self.bucket)) + .output() + .map_err(|e| format!("aws: {e}"))?; + let text = String::from_utf8_lossy(&made.stderr); + if made.status.success() || text.contains("BucketAlready") { + return Ok(()); + } + if Instant::now() > deadline { + return Err(format!("bucket: {text}")); + } + std::thread::sleep(Duration::from_millis(500)); + } + } + + fn bucket_url(&self) -> String { + format!("s3://{}/fleet", self.bucket) + } + + fn deploy(&self, worker: &Path, vars: &[(String, String)]) -> Result<(), String> { + let project = self.dir.join("worker"); + copy_dir(&worker.join("build"), &project.join("build")); + let config = std::fs::read_to_string(worker.join("wrangler.jsonc")).unwrap(); + let mut config: serde_json::Value = serde_json::from_str(&strip_comments(&config)) + .map_err(|e| format!("wrangler.jsonc: {e}"))?; + for (key, value) in vars { + config["vars"][key] = serde_json::Value::String(value.clone()); + } + std::fs::write(project.join("wrangler.json"), config.to_string()).unwrap(); + let mut deploy = Command::new(&self.binary); + self.env(&mut deploy); + let out = deploy + .arg("deploy") + .arg(&project) + .args(["--bucket", &self.bucket_url()]) + .output() + .map_err(|e| format!("celld deploy: {e}"))?; + if !out.status.success() { + return Err(format!( + "celld deploy: {}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + )); + } + Ok(()) + } + + /// (Re)start node `i`. + pub fn start_node(&mut self, i: usize) -> Result<(), String> { + let node = &self.nodes[i]; + let dir = self.dir.join(&node.name); + std::fs::create_dir_all(&dir).unwrap(); + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("celld.log")) + .unwrap(); + let mut command = Command::new(&self.binary); + self.env(&mut command); + let child = command + .args(["--bucket", &self.bucket_url()]) + .args(["--listen", &format!("127.0.0.1:{}", node.public)]) + .args(["--internal-listen", &format!("127.0.0.1:{}", node.operator)]) + .args(["--advertise", &format!("127.0.0.1:{}", node.operator)]) + .env("CELLD_NODE", &node.name) + .env("CELLD_WATCH", dir.join("watch")) + .env("CELLD_READY_FLEET_GATE_MS", "0") + .env( + "RUST_LOG", + std::env::var("CELLD_RUST_LOG").unwrap_or_else(|_| "warn".into()), + ) + .stdin(Stdio::null()) + .stdout(log.try_clone().unwrap()) + .stderr(log) + .spawn() + .map_err(|e| format!("celld: {e}"))?; + let public = node.public; + self.nodes[i].child = Some(child); + let deadline = Instant::now() + Duration::from_secs(90); + while Instant::now() < deadline { + if blocking_get(&format!("http://127.0.0.1:{public}/health")) == Some(200) { + return Ok(()); + } + let exited = self.nodes[i] + .child + .as_mut() + .and_then(|c| c.try_wait().ok().flatten()); + if let Some(status) = exited { + // A cold node sometimes fails its first start; retry once. + self.nodes[i].child = None; + return Err(format!( + "{} exited ({status}); logs in {}", + self.nodes[i].name, + dir.display() + )); + } + std::thread::sleep(Duration::from_millis(250)); + } + Err(format!( + "{} not ready; logs in {}", + self.nodes[i].name, + dir.display() + )) + } + + /// `http://127.0.0.1:{public port}` of node `i`. + pub fn base(&self, i: usize) -> String { + format!("http://127.0.0.1:{}", self.nodes[i].public) + } + + /// Index of the node named `name`. + pub fn index(&self, name: &str) -> Option { + self.nodes.iter().position(|n| n.name == name) + } + + /// SIGKILL node `i` (a crash). + pub fn kill(&mut self, i: usize) { + if let Some(mut child) = self.nodes[i].child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Drop for Fleet { + fn drop(&mut self) { + for i in 0..self.nodes.len() { + self.kill(i); + } + let _ = Command::new("docker") + .args(["compose", "-p", &self.project, "-f"]) + .arg(self.dir.join("s3-compose.yaml")) + .args(["down", "-v"]) + .output(); + if std::thread::panicking() { + eprintln!("fleet logs kept in {}", self.dir.display()); + } else { + let _ = std::fs::remove_dir_all(&self.dir); + } + } +} + +/// Drop `//` line comments (wrangler.jsonc). +fn strip_comments(text: &str) -> String { + text.lines() + .filter(|line| !line.trim_start().starts_with("//")) + .collect::>() + .join("\n") +} diff --git a/distributed_game/tests/zone_status/main.rs b/distributed_game/tests/zone_status/main.rs index 18e6ffa15..fc0b1c116 100644 --- a/distributed_game/tests/zone_status/main.rs +++ b/distributed_game/tests/zone_status/main.rs @@ -230,3 +230,155 @@ async fn cell_events_project_into_zone_status_rows() { assert_eq!(of(status("z-never").await), ZoneStatus::Cold); let _ = std::fs::remove_dir_all(dir); } + +/// A celld-hosted zone's lifecycle reports (`zone_activity.record` facts) +/// project into `zone_activities`; a report emitted earlier but settled +/// later never overwrites a newer one; only the zone itself may report. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn zone_activity_reports_project_into_zone_status() { + use distributed_game::cell::trusted_session; + use distributed_game::world::zone_activity::{ + mount_zone_activity, zone_principal, RecordActivity, ZoneActivity, RECORD, + }; + use distributed_game::world::zone_status::{ + activity_projector_for, ZoneActivities, ZONE_ACTIVITIES, + }; + use distributed_game::{Fact, FactStamp}; + + let clock = ManualClock::new(SystemTime::UNIX_EPOCH + Duration::from_millis(T0)); + let cell = mount_zone_activity(cell::("ZoneActivity", "pit.0.1", &clock)); + let report = |status: &str, seq: u64, principal: &str| { + let fact = Fact::trusted( + format!("zone_activity.record:pit.0.1:9:{seq}"), + RECORD, + serde_json::to_value(RecordActivity { + status: status.into(), + activation: "act-1".into(), + restored: status == "active" && seq > 1, + players: u32::from(status == "active"), + node: "node-b".into(), + isolate: "iso".into(), + }) + .unwrap(), + Some(principal.to_string()), + FactStamp { + zone_id: "pit.0.1".into(), + activation: 9, + seq, + emitted_at_ms: T0 + seq, + ..FactStamp::default() + }, + ); + (fact.clone(), trusted_session(principal, &fact)) + }; + let send = |status: &'static str, seq: u64, principal: &'static str| { + let cell = &cell; + async move { + let (fact, session) = report(status, seq, principal); + let identity = CellCommandIdentity::new( + "celld-zone", + principal, + command_id_for("celld-zone", fact.key()), + ) + .unwrap(); + cell.dispatch_idempotent(RECORD, &identity, fact.input().clone(), session) + .await + } + }; + let me = Box::leak(zone_principal("pit.0.1").into_boxed_str()); + assert_eq!( + send("active", 1, me).await.unwrap().payload()["applied"], + true + ); + assert_eq!( + send("hibernated", 3, me).await.unwrap().payload()["applied"], + true + ); + // Emitted before `hibernated`, settled after it: ignored. + let late = send("dormant", 2, me).await.unwrap(); + assert_eq!(late.payload()["applied"], false); + assert_eq!(late.payload()["status"], "hibernated"); + assert!( + send("active", 4, "guest-x").await.is_err(), + "only the zone reports" + ); + assert_eq!(cell.load().await.unwrap().unwrap().status(), "hibernated"); + + let dir = std::env::temp_dir().join(format!( + "zone-activity-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let bus_url = format!("sqlite:{}?mode=rwc", dir.join("bus.db").display()); + let pool = sqlx::SqlitePool::connect(&bus_url).await.unwrap(); + let bus = SqliteBus::new(pool.clone()); + bus.ensure_tables().await.unwrap(); + let publisher = BusPublisher::new(Arc::new(bus)); + let mut messages = cell.durable_outbox().unwrap(); + messages.sort_by_key(|m| m.created_at); + assert_eq!(messages.len(), 2, "one event per applied report"); + for message in messages { + publisher.publish(Message::from(message)).await.unwrap(); + } + let read_url = format!("sqlite:{}?mode=rwc", dir.join("read.db").display()); + let repo = SqliteRepository::connect_and_migrate(&read_url) + .await + .unwrap(); + repo.bootstrap_table_schema_for_dev(&read_model_catalog().table_registry().unwrap()) + .await + .unwrap(); + let read_models = repo.clone(); + async fn project( + context: CausalProjectorContext, + projection: ModeledProjection, + ) -> Result<(), HandlerError> { + projection.apply(ZONE_ACTIVITIES, &context).await + } + // A consumer of its own (a minimap service would be one too). + spawn_service_consumer_loop(move || { + Service::new() + .named("zone-minimap") + .routes( + Routes::new() + .with_read_model_store(read_models.clone()) + .modeled_projector(activity_projector_for("zone-minimap")) + .handle(project), + ) + .with_bus(SqliteBus::new(pool.clone()).with_idle_poll(CONSUMER_IDLE_POLL)) + }); + let start = Instant::now(); + let row = loop { + let row = sqlx::query_as::<_, (String, String, String, i64)>( + "SELECT zone_id, status, node, activations FROM zone_activities WHERE zone_id = ?", + ) + .bind("pit.0.1") + .fetch_optional(repo.pool()) + .await + .unwrap(); + if let Some(row) = row.filter(|row| row.1 == "hibernated") { + break row; + } + assert!( + start.elapsed() < Duration::from_secs(20), + "projection timed out" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!(row.2, "node-b"); + assert_eq!(row.3, 1); + let activity = ZoneActivities { + zone_id: row.0, + status: row.1, + node: row.2, + ..ZoneActivities::default() + }; + assert_eq!( + ZoneStatus::of_activity(Some(&activity)), + ZoneStatus::Hibernated { bytes: 0 } + ); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts index bd7c79ac6..61a12614d 100644 --- a/js/src/game/connection.ts +++ b/js/src/game/connection.ts @@ -10,6 +10,7 @@ import { ClockSync, type ClockSyncOptions } from './clock.js'; import { Emitter } from './emitter.js'; import { encodeClientMessage, + GAME_CLOSE_RESTARTED, GAME_PROTOCOL_VERSION, GameClientMirror, GameErrorCode, @@ -643,6 +644,11 @@ export class GameConnection { this.#disconnectedAt = this.#scheduler.now(); this.#failedAttempts = 0; } + if (code === GAME_CLOSE_RESTARTED) { + // The zone restarted or moved: its sessions are gone. Rejoin now + // with a fresh ticket instead of presenting a void token. + this.#reconnectToken = ''; + } if (attempt.redirect !== undefined) { this.#redirects += 1; if (this.#redirects > (this.#options.maxRedirects ?? 3)) { diff --git a/js/src/game/index.ts b/js/src/game/index.ts index 271131bcd..05e9b39eb 100644 --- a/js/src/game/index.ts +++ b/js/src/game/index.ts @@ -45,6 +45,7 @@ export { type GameSchema } from './schema.js'; export { + GAME_CLOSE_RESTARTED, GAME_PROTOCOL_VERSION, GameClientMirror, GameErrorCode, diff --git a/js/src/game/messages.ts b/js/src/game/messages.ts index 685afb641..b414bceb2 100644 --- a/js/src/game/messages.ts +++ b/js/src/game/messages.ts @@ -45,6 +45,13 @@ export const GameKickCode = Object.freeze({ RELOAD: 7 }); +/** + * WebSocket close code of a zone that restarted or moved (a celld zone + * object woke up again, its node stopped or crashed): the reconnect token is + * void, the client rejoins at once with a fresh ticket. + */ +export const GAME_CLOSE_RESTARTED = 1012; + /** Error codes. */ export const GameErrorCode = Object.freeze({ BAD_MESSAGE: 1, diff --git a/js/tests/game-connection.test.mjs b/js/tests/game-connection.test.mjs index 7da338af4..a678d3fc0 100644 --- a/js/tests/game-connection.test.mjs +++ b/js/tests/game-connection.test.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { + GAME_CLOSE_RESTARTED, GAME_PROTOCOL_VERSION, GameClient, GameConnection, @@ -214,6 +215,25 @@ test('reconnects with the token inside the grace window, then falls back to a fr conn.close(); }); +test('a zone that restarted (close 1012) is rejoined at once with a fresh ticket', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + scriptedServer(network); + const { conn, tickets } = connection(network, scheduler, { + reconnect: { graceMs: 15_000, maxAttempts: 100, backoffMs: () => 1000 } + }); + await conn.connect(); + assert.equal(conn.reconnectToken, 'rt-1'); + network.last().close(GAME_CLOSE_RESTARTED); + await scheduler.advance(10); + const hello = network.last().lastHello; + assert.equal(hello.reconnectToken, '', 'the old session is gone: no token'); + assert.equal(hello.ticket, 't:z1:2'); + assert.deepEqual(tickets.at(-1), { zoneId: 'z1', role: 'player', reason: 'rejoin' }); + assert.equal(conn.state, 'open'); + conn.close(); +}); + test('kick and handshake rejection close without reconnecting', async () => { const network = new FakeNetwork(); const scheduler = new FakeScheduler(); diff --git a/scripts/check-wasm32-domains.sh b/scripts/check-wasm32-domains.sh index bd35cf117..452fd2827 100755 --- a/scripts/check-wasm32-domains.sh +++ b/scripts/check-wasm32-domains.sh @@ -15,7 +15,9 @@ # tests/e2e-ui/crates/*-domain, examples/game/server/crawler, # game_services/crates/*-domain, game_services/crates/kernel # plus the framework crates domains depend on: distributed (no features) and -# distributed_game (no features; the FactCommand derive). +# distributed_game (no features; the FactCommand derive), and distributed_game +# with `celld-zone` (the celld zone host: zones as Durable Objects), plus the +# game zones hosted that way (examples/game/server/rooms). # # Excluded, with the reason (a crate here never runs in a cell): # tests/e2e-ui/crates/blob-domain e2e-ui blob game host: its `domain` @@ -34,6 +36,7 @@ manifests() { echo distributed_game/Cargo.toml for manifest in tests/e2e-ui/crates/*-domain/Cargo.toml \ examples/game/server/crawler/Cargo.toml \ + examples/game/server/rooms/Cargo.toml \ game_services/crates/*-domain/Cargo.toml \ game_services/crates/kernel/Cargo.toml; do case "$manifest" in @@ -65,6 +68,14 @@ for manifest in $(manifests); do fi done +# The celld zone host is wasm32 code by design. +printf '==> wasm32 distributed_game/Cargo.toml --features celld-zone\n' +if ! "$cargo" build --quiet --lib --target "$target" --manifest-path distributed_game/Cargo.toml \ + --target-dir "$target_dir" --no-default-features --features celld-zone; then + printf 'FAIL: distributed_game with celld-zone does not build for %s\n' "$target" >&2 + failed=1 +fi + fixture=tests/fixtures/wasm32-native-domain/Cargo.toml printf '==> negative fixture %s (must fail)\n' "$fixture" if "$cargo" build --quiet --lib --target "$target" --manifest-path "$fixture" \ diff --git a/tests/celld/README.md b/tests/celld/README.md index 7c04021bb..675b7dd3e 100644 --- a/tests/celld/README.md +++ b/tests/celld/README.md @@ -211,3 +211,20 @@ from the full Queue/NATS/browser profile. Every non-health aggregate route requires `DISTRIBUTED_INTERNAL_SECRET`. The checked-in value is loopback test data only; production requires a separately provisioned secret plus the normal network policy. + +## Zones as celld objects + +`zone-worker/` hosts a small tally zone with `distributed_game`'s +`celld-zone` feature (one Durable Object per zone, `celld_zone_object!`), +its `Tally` cells and the `ZoneActivity` cell. `distributed_game`'s +`celld_zone` test drives it over WebSockets: on `celld dev` (join, input, +facts, dormant → hibernated, wake with state, single-use tickets, a +doorway handoff) and on a three-node production-mode fleet on one RustFS +bucket started with docker compose (a forwarded socket closes with 1012 +when the owner node is killed, the zone recovers on another node, and 200 +in-flight facts reach the cell exactly once): + +```sh +(cd tests/celld/zone-worker && worker-build --release) +CELLD_BIN=… CELLD_ESBUILD=… cargo test -p distributed_game --features celld,net --test celld_zone +``` diff --git a/tests/celld/zone-worker/.gitignore b/tests/celld/zone-worker/.gitignore new file mode 100644 index 000000000..28ef41919 --- /dev/null +++ b/tests/celld/zone-worker/.gitignore @@ -0,0 +1,4 @@ +build/ +target/ +.celld/ +.dev.vars diff --git a/tests/celld/zone-worker/Cargo.toml b/tests/celld/zone-worker/Cargo.toml new file mode 100644 index 000000000..1fe2caf63 --- /dev/null +++ b/tests/celld/zone-worker/Cargo.toml @@ -0,0 +1,27 @@ +# A test zone hosted as celld Durable Objects (`distributed_game`'s +# `celld-zone` feature) with the cells its facts go to. Used by +# `distributed_game/tests/celld_zone` (single node and a multi-node fleet). +[workspace] +members = ["."] +resolver = "2" + +[package] +name = "celld-zone-test-worker" +version = "0.1.0" +edition = "2021" +publish = false +description = "workers-rs: a tally zone as a celld Durable Object, its Tally and ZoneActivity cells" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +console_error_panic_hook = "0.1" +distributed = { path = "../../..", default-features = false, features = ["workers-rs"] } +distributed_game = { path = "../../../distributed_game", default-features = false, features = ["celld-zone"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +worker = { version = "0.8", features = ["queue"] } + +[package.metadata.wasm-pack.profile.release] +wasm-opt = false diff --git a/tests/celld/zone-worker/src/lib.rs b/tests/celld/zone-worker/src/lib.rs new file mode 100644 index 000000000..275382287 --- /dev/null +++ b/tests/celld/zone-worker/src/lib.rs @@ -0,0 +1,288 @@ +//! A test zone hosted by `distributed_game::celld_zone` and the cells its +//! facts go to. +//! +//! - `GET /rooms/{zone}` (WebSocket): `TallyRoom`, one object per zone +//! `room-*`. Input `[1, n]` counts `n` hits, each a `tally.hit` fact for +//! the player's `Tally` cell; `[2, c]` walks through a door into +//! `room-{c}` (handoff). On join the player gets event 1 with the zone's +//! total hits (u64 LE); after a hits input, event 2 with the new total. +//! The zone's snapshot is its total. +//! - `GET /rooms/{zone}/info`: the object's debug info. +//! - `GET|POST /tally/{principal}[/command]`, `/zone-activity/{zone}[/command]`: +//! the cells (internal secret). + +use distributed::cell_host::CelldOutbox; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use distributed_game::cell::session_stamp; +use distributed_game::celld_zone::{ + authenticate, cell_alarm, error_response, fact_sessions, forward_to_zone, json_status, + serve_cell, CelldZone, ObjectEnv, ObjectFactSink, ZoneActivityCell, +}; +use distributed_game::command_sink::FactRoute; +use distributed_game::{ConsumePolicy, Ctx, EntitySchema, PlayerId, Zone}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use worker::*; + +// ---------------------------------------------------------------- zone + +/// One counted hit (the cell counts it; the zone reports which hit). +#[derive(Debug, Clone, Serialize, Deserialize, distributed_game::FactCommand)] +#[fact(command = "tally.hit")] +pub struct TallyHit { + /// The zone's running hit number. + pub hit: u64, + /// Zone it happened in. + pub zone: String, +} + +/// The test zone. +pub struct TallyZone { + total: u64, +} + +pub enum TallyInput { + Hits(u8), + Door(u8), +} + +impl Zone for TallyZone { + type Config = (); + type Input = TallyInput; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + EntitySchema::new() + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self { total: 0 } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send_event(player, 1, self.total.to_le_bytes().to_vec()); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + match payload { + [1, n] => Some(TallyInput::Hits(*n)), + [2, c] if c.is_ascii_lowercase() => Some(TallyInput::Door(*c)), + _ => None, + } + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec = ctx.players().map(|p| p.id).collect(); + for player in players { + for input in ctx.take_inputs(player, ConsumePolicy::Drain) { + match input.input { + TallyInput::Hits(n) => { + for _ in 0..n { + self.total += 1; + let hit = TallyHit { + hit: self.total, + zone: ctx.zone_id().to_string(), + }; + let total = self.total; + let _ = ctx.emit_keyed(player, hit, &[&total]); + } + ctx.send_event(player, 2, self.total.to_le_bytes().to_vec()); + } + TallyInput::Door(c) => { + let target = format!("room-{}", c as char); + let _ = ctx.handoff(player, &target, Vec::new()); + } + } + } + } + } + + fn hibernate(&self) -> Option> { + Some(self.total.to_string().into_bytes()) + } + + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { + self.total = std::str::from_utf8(state) + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + } +} + +impl CelldZone for TallyZone { + fn object_config(zone_id: &str, _env: &ObjectEnv) -> std::result::Result<(), String> { + zone_id + .starts_with("room-") + .then_some(()) + .ok_or_else(|| format!("no such zone {zone_id}")) + } + + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink.route(FactRoute::by_principal::("tally")) + } +} + +distributed_game::celld_zone_object!(TallyRoom, TallyZone); + +// ---------------------------------------------------------------- Tally cell + +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct Tally { + entity: Entity, + hits: Vec, +} + +#[sourced(entity, aggregate_type = "Tally", events = "TallyEvent")] +impl Tally { + #[event("tally.counted", version = 1)] + fn counted(&mut self, principal: String, hit: String) { + if self.entity.id().is_empty() { + self.entity.set_id(principal); + } + self.hits.push(hit); + } +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +pub struct HitInput { + pub hit: u64, + pub zone: String, +} + +#[derive(Debug, Serialize, distributed::CommandOutput)] +pub struct Counted { + pub count: u32, +} + +struct RecordHit; +impl PortableCommand for RecordHit +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>("tally.hit")) + .handle(handle_hit) + } +} + +async fn handle_hit( + ctx: &CausalCommandContext<'_, Tally>, + input: HitInput, +) -> std::result::Result>, HandlerError> { + let principal = ctx.user_id()?.to_string(); + let stamp = session_stamp(ctx.session()) + .ok_or_else(|| HandlerError::Rejected("hits are facts".into()))?; + let repo = ctx.repo(); + let mut tally = match repo.get(&principal).await? { + Some(tally) => tally, + None => repo.create(), + }; + tally + .counted( + principal, + format!("{}#{}@{}", input.zone, input.hit, stamp.activation), + ) + .map_err(|e| HandlerError::Rejected(e.to_string()))?; + let count = tally.hits.len() as u32; + repo.commit(tally)?.succeeded(Counted { count }) +} + +async fn read_tally( + cell: &distributed::cell_host::AggregateCell, +) -> std::result::Result { + let tally = cell.load().await.map_err(|e| e.to_string())?; + let hits = tally.map(|t| t.hits).unwrap_or_default(); + Ok(json!({ "count": hits.len(), "hits": hits })) +} + +#[durable_object] +pub struct TallyCell { + cell: distributed::cell_host::AggregateCell, + env: Env, +} + +impl DurableObject for TallyCell { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let cell = + distributed::cell_host::AggregateCell::::from_state_with_snapshots(state, 50) + .expect("tally cell identity") + .mount(RecordHit) + .with_celld_outbox(CelldOutbox::from_env(&env, "OUTBOX").expect("OUTBOX Queue")); + Self { cell, env } + } + + async fn fetch(&self, req: Request) -> Result { + serve_cell(&self.env, &self.cell, req, read_tally, fact_sessions).await + } + + async fn alarm(&self) -> Result { + cell_alarm(&self.env, &self.cell).await + } +} + +#[durable_object] +pub struct ZoneActivityObject { + cell: ZoneActivityCell, +} + +impl DurableObject for ZoneActivityObject { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let outbox = CelldOutbox::from_env(&env, "OUTBOX").expect("OUTBOX Queue"); + Self { + cell: ZoneActivityCell::new(state, env, outbox), + } + } + + async fn fetch(&self, req: Request) -> Result { + self.cell.fetch(req).await + } + + async fn alarm(&self) -> Result { + self.cell.alarm().await + } +} + +// ---------------------------------------------------------------- entry + +#[event(fetch)] +async fn main(req: Request, env: Env, _ctx: Context) -> Result { + console_error_panic_hook::set_once(); + let path = req.url()?.path().to_string(); + if path == "/health" { + return Response::ok("ok"); + } + if path.starts_with("/rooms/") { + return match forward_to_zone(req, &env, "ROOM", "/rooms/").await? { + Some(response) => Ok(response), + None => Response::error("bad zone", 400), + }; + } + if let Err(error) = authenticate(&req, &env) { + return error_response(error); + } + let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); + let binding = match parts.first().copied() { + Some("tally") => "TALLY", + Some("zone-activity") => "ZONE_ACTIVITY", + _ => return json_status(json!({ "error": "unknown cell kind" }), 404), + }; + let Some(shard) = parts.get(1) else { + return json_status(json!({ "error": "missing shard" }), 400); + }; + let shard = worker::js_sys::decode_uri_component(shard) + .map(String::from) + .unwrap_or_else(|_| shard.to_string()); + let stub = env + .durable_object(binding)? + .id_from_name(&shard)? + .get_stub()?; + stub.fetch_with_request(req).await +} diff --git a/tests/celld/zone-worker/wrangler.jsonc b/tests/celld/zone-worker/wrangler.jsonc new file mode 100644 index 000000000..361dbb9ef --- /dev/null +++ b/tests/celld/zone-worker/wrangler.jsonc @@ -0,0 +1,29 @@ +// The celld zone host test worker. Test-only secrets (the harness may +// override them in .dev.vars or a generated copy of this file). +{ + "name": "celld-zone-test", + "main": "build/worker/shim.mjs", + "compatibility_date": "2026-01-01", + "durable_objects": { + "bindings": [ + { "name": "ROOM", "class_name": "TallyRoom" }, + { "name": "TALLY", "class_name": "TallyCell" }, + { "name": "ZONE_ACTIVITY", "class_name": "ZoneActivityObject" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["TallyRoom", "TallyCell", "ZoneActivityObject"] } + ], + // The zone-activity cell publishes `zone.activity_changed` to this Queue + // (no consumer here; the tests read the cell). + "queues": { + "producers": [{ "binding": "OUTBOX", "queue": "celld-zone-test-outbox" }] + }, + "vars": { + "DISTRIBUTED_INTERNAL_SECRET": "test-only-internal-secret-change-me-2026", + "GAME_TICKET_SECRET": "test-only-ticket-secret-change-me-2026", + "ZONE_PERSIST_MS": "1000", + "ZONE_HIBERNATE_AFTER_MS": "2000", + "ZONE_RECONNECT_GRACE_MS": "1000" + } +} From d6ce837ececc48f7ad2e775f73027013a070dc4d Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:43:53 -0500 Subject: [PATCH 262/484] feat(game): bots on any zone path, readable zone info MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bots append `{path}/{zone}` (default `/zones`), so they can join zones a celld worker routes elsewhere (`/rooms/{room}`). A celld zone object's `GET …/info` debug JSON allows any origin, so pages served elsewhere can show which node and isolate run the zone. [[tasks/gr-p43-celld-zone-host]] --- distributed_game/src/bots.rs | 15 +++++++++++++-- distributed_game/src/celld_zone/object.rs | 5 ++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/distributed_game/src/bots.rs b/distributed_game/src/bots.rs index 8f76e9a8e..d5c3ac662 100644 --- a/distributed_game/src/bots.rs +++ b/distributed_game/src/bots.rs @@ -113,8 +113,13 @@ pub fn encode_i8_pair(dir: [f32; 2]) -> Vec { /// Bot run settings. #[derive(Clone)] pub struct BotConfig { - /// Server base URL, e.g. `ws://127.0.0.1:2567` (`/zones/{zone}` is appended). + /// Server base URL, e.g. `ws://127.0.0.1:2567` (`{path}/{zone}` is + /// appended). pub url: String, + /// Path the zone id is appended to: `/zones` on the `net` server, + /// whatever the worker routes to its zone objects on celld (e.g. + /// `/rooms`). + pub path: String, /// Zone to join. pub zone: String, /// Number of bots. @@ -145,6 +150,7 @@ impl BotConfig { pub fn new(url: impl Into, zone: impl Into, ticket_key: TicketKey) -> Self { Self { url: url.into(), + path: "/zones".into(), zone: zone.into(), bots: 10, input_rate: 20.0, @@ -364,7 +370,12 @@ async fn drive( name: None, extensions: Default::default(), }); - let url = format!("{}/zones/{}", config.url.trim_end_matches('/'), config.zone); + let url = format!( + "{}/{}/{}", + config.url.trim_end_matches('/'), + config.path.trim_matches('/'), + config.zone + ); let (mut ws, _) = tokio_tungstenite::connect_async(url.as_str()) .await .map_err(|e| format!("connect: {e}"))?; diff --git a/distributed_game/src/celld_zone/object.rs b/distributed_game/src/celld_zone/object.rs index 3180fc9ca..9e3478529 100644 --- a/distributed_game/src/celld_zone/object.rs +++ b/distributed_game/src/celld_zone/object.rs @@ -560,7 +560,10 @@ impl ZoneObject { } let path = req.url()?.path().to_string(); if path.ends_with("/info") { - return Response::from_json(&self.info()); + // Debug JSON without secrets; pages on other origins may read it. + let response = Response::from_json(&self.info())?; + response.headers().set("access-control-allow-origin", "*")?; + return Ok(response); } if req.headers().get("upgrade")?.as_deref() != Some("websocket") { return Response::error("expected a WebSocket upgrade", 426); From 28b187fb36d7232aa478e5dd60d026496723f8ea Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:44:25 -0500 Subject: [PATCH 263/484] feat(game)!: Mob Pit rooms as celld objects, doorways, room grid Mob Pit becomes a near-infinite seeded grid of rooms (`pit..`), each one a celld Durable Object hosted by distributed_game's celld zone host. celld decides where rooms run; nothing in the game names a node. - game_sim::mobpit: `pit_room` (#[game_pure], biome from the Endless Grid's noise, danger, 6-12 mobs), doorway and arrival rules, `PIT_WORLD`; the page draws rooms with the same Rust as WASM. - mobpit_rooms (new, wasm32-portable): the room zone (doorway handoffs with carried position, hibernation snapshot of the mobs and the room's kills, profile loaded from the Crawler cell after joining) and its CelldZone hooks (kill facts to crawler cells, lifecycle facts to presence cells, object to object). - cells worker: PitRoom objects behind `/rooms/{room}`, ZoneActivity cells feeding the zone status read model through the outbox Queue. - game-demos mobpit is the services side only (dev room tickets, relay, crawler directory, room status, boards fed from the directory with idempotent max updates). Removed: the native zone, its fact sink, the slow-storage knob and the in-memory presence mirror. - Vite page: rooms through `/rooms` (proxied to celld), doorways, biome floor, live minimap of room status, restore toasts, debug overlay with the celld node/isolate per room. run.sh starts celld dev itself; `run.sh mobpit --fleet [N]` runs N production-mode nodes on one RustFS bucket (docker compose) behind a round-robin dev balancer. Tests: mobpit_rooms reference-host tests; mobpit_smoke on celld (bots in a room, dormant -> hibernated -> restored, celld kill -9 mid-fight, presence cells); mobpit + leaderboard headless; pit_room WASM = native. [[tasks/gr-p41-mobpit-rooms-zones]] --- examples/game/cells/Cargo.toml | 8 +- examples/game/cells/src/lib.rs | 56 +- examples/game/cells/wrangler.jsonc | 25 +- examples/game/client/leaderboard/index.html | 7 +- .../client/src/generated/mobpit/constants.ts | 11 +- .../client/src/generated/mobpit/events.ts | 217 +-- .../game/client/src/generated/mobpit/index.ts | 1 + .../game/client/src/generated/mobpit/pures.ts | 60 + .../client/src/generated/mobpit/schema.ts | 24 +- .../client/src/generated/mobpit/surface.json | 392 +++-- examples/game/client/src/leaderboard/main.ts | 32 +- examples/game/client/src/mobpit/client.ts | 191 ++- examples/game/client/src/mobpit/main.ts | 212 ++- examples/game/client/src/mobpit/style.css | 58 + examples/game/client/tests/helpers/celld.mjs | 15 +- examples/game/client/tests/helpers/mobpit.mjs | 51 +- .../tests/leaderboard-headless.test.mjs | 28 +- .../client/tests/mobpit-headless.test.mjs | 110 +- .../client/tests/prediction-wasm.test.mjs | 4 +- examples/game/client/vite.config.ts | 6 +- examples/game/run.sh | 218 ++- examples/game/scripts/round-robin.mjs | 36 + examples/game/server/Cargo.lock | 164 +- examples/game/server/Cargo.toml | 5 +- examples/game/server/rooms/Cargo.toml | 28 + examples/game/server/rooms/src/celld.rs | 51 + examples/game/server/rooms/src/lib.rs | 27 + examples/game/server/rooms/src/zone.rs | 1392 +++++++++++++++++ examples/game/server/rooms/tests/rooms.rs | 164 ++ .../game/server/service/tests/projection.rs | 2 +- examples/game/server/sim/src/mobpit.rs | 245 ++- examples/game/server/src/common/mod.rs | 2 +- .../game/server/src/common/zone_status.rs | 64 +- examples/game/server/src/devcelld.rs | 42 +- examples/game/server/src/grid/dev.rs | 1 + examples/game/server/src/mobpit/board.rs | 98 +- examples/game/server/src/mobpit/mod.rs | 187 +-- examples/game/server/src/mobpit/presence.rs | 167 -- examples/game/server/src/mobpit/routes.rs | 169 +- examples/game/server/src/mobpit/store.rs | 249 +-- examples/game/server/src/mobpit/world.rs | 239 ++- examples/game/server/src/mobpit/zone.rs | 1374 +--------------- examples/game/server/src/predict_trace.rs | 12 + examples/game/server/tests/mobpit_smoke.rs | 603 +++---- 44 files changed, 4027 insertions(+), 3020 deletions(-) create mode 100644 examples/game/client/src/generated/mobpit/pures.ts create mode 100644 examples/game/scripts/round-robin.mjs create mode 100644 examples/game/server/rooms/Cargo.toml create mode 100644 examples/game/server/rooms/src/celld.rs create mode 100644 examples/game/server/rooms/src/lib.rs create mode 100644 examples/game/server/rooms/src/zone.rs create mode 100644 examples/game/server/rooms/tests/rooms.rs delete mode 100644 examples/game/server/src/mobpit/presence.rs diff --git a/examples/game/cells/Cargo.toml b/examples/game/cells/Cargo.toml index 65545b171..5bc8471cd 100644 --- a/examples/game/cells/Cargo.toml +++ b/examples/game/cells/Cargo.toml @@ -1,5 +1,7 @@ # The game demos' durable cells on celld (workers-rs, wasm32): Mob Pit's -# per-player Crawler aggregate and per-player presence +# rooms (one Durable Object per room, `distributed_game::celld_zone`) and +# their zone-activity cells, Mob Pit's per-player Crawler aggregate and +# per-player presence # (with the outbox Queue consumer that relays Crawler domain events to the # zone server), and the zone lease and hibernation-state cells every # multi-host demo uses. @@ -22,8 +24,10 @@ crate-type = ["cdylib"] [dependencies] console_error_panic_hook = "0.1" distributed = { path = "../../..", default-features = false, features = ["workers-rs"] } -distributed_game = { path = "../../../distributed_game", default-features = false, features = ["cell", "workers-rs"] } +distributed_game = { path = "../../../distributed_game", default-features = false, features = ["cell", "workers-rs", "celld-zone"] } mobpit_crawler = { path = "../server/crawler" } +# Mob Pit's rooms, each one a Durable Object (`PitRoom`). +mobpit_rooms = { path = "../server/rooms", features = ["celld"] } serde = { version = "1", features = ["derive"] } serde_json = "1" worker = { version = "0.8", features = ["queue"] } diff --git a/examples/game/cells/src/lib.rs b/examples/game/cells/src/lib.rs index b7cfc59e7..fe4505f42 100644 --- a/examples/game/cells/src/lib.rs +++ b/examples/game/cells/src/lib.rs @@ -1,6 +1,17 @@ -//! The game demos' durable cells on celld. Mob Pit's are fed by the zone -//! server's `distributed_game::celld::CelldFactSink` over the internal HTTP -//! path; every multi-host demo keeps its zone ownership and hibernation +//! The game demos' durable cells on celld, and Mob Pit's rooms. +//! +//! - `GET /rooms/{room}` (WebSocket) and `/rooms/{room}/info`: `PitRoom`, +//! one Durable Object per Mob Pit room (`pit..`), hosted by +//! `distributed_game::celld_zone` (`mobpit_rooms::MobPit`). celld places +//! each room; its kill and lifecycle facts reach the Crawler and presence +//! cells below object to object, exactly once. +//! - `zone-activity/{room}` (`ZoneActivityObject`): each room's lifecycle +//! (active / dormant / hibernated); its `zone.activity_changed` events +//! leave through the outbox Queue for the zone status read model. +//! +//! The Freeze's cells are fed by its zone server's +//! `distributed_game::celld::CelldFactSink` over the internal HTTP path; +//! every native multi-host demo keeps its zone ownership and hibernation //! snapshots here. //! //! - `crawler/{principal}` (`CrawlerCell`): the `mobpit_crawler::Crawler` @@ -47,9 +58,11 @@ use distributed::microsvc::{ }; use distributed::{sourced, Aggregate, Entity}; use distributed_game::cell::{fact_session_from_headers, session_stamp}; +use distributed_game::celld_zone::{forward_to_zone, ZoneActivityCell}; use distributed_game::lifecycle::{ Lifecycle, CONNECTION_LOST, PLAYER_DISCONNECTED, PLAYER_JOINED, PLAYER_LEFT, PLAYER_RECONNECTED, }; +use distributed_game::world::zone_activity::ZONE_ACTIVITY_KIND; use distributed_game::world::zone_lease::{mount_zone_lease, ZoneLease}; use distributed_game::world::zone_state::{celld_worker, mount_zone_state, ZoneState}; use distributed_game::FactStamp; @@ -715,14 +728,48 @@ impl DurableObject for ZoneStateCell { } } +// ---------------------------------------------------------------- Rooms + +distributed_game::celld_zone_object!(PitRoom, mobpit_rooms::MobPit); + +#[durable_object] +pub struct ZoneActivityObject { + cell: ZoneActivityCell, +} + +impl DurableObject for ZoneActivityObject { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let outbox = outbox(&env); + Self { + cell: ZoneActivityCell::new(state, env, outbox), + } + } + + async fn fetch(&self, req: Request) -> Result { + self.cell.fetch(req).await + } + + async fn alarm(&self) -> Result { + self.cell.alarm().await + } +} + #[event(fetch)] async fn main(req: Request, env: Env, _ctx: Context) -> Result { console_error_panic_hook::set_once(); let url = req.url()?; - let path = url.path(); + let path = url.path().to_string(); if path == "/" || path == "/health" { return Response::ok("mobpit cells\n"); } + // A room is public: its WebSocket admits signed tickets only. + if path.starts_with("/rooms/") { + return match forward_to_zone(req, &env, "PIT_ROOM", "/rooms/").await? { + Some(response) => Ok(response), + None => json_status(json!({ "error": "no such room" }), 404), + }; + } if let Err(error) = authenticate(&req, &env) { return error_response(error); } @@ -734,6 +781,7 @@ async fn main(req: Request, env: Env, _ctx: Context) -> Result { Some("content-log") => "CONTENT_LOG", Some("zone-lease") => "ZONE_LEASE", Some("zone-state") => "ZONE_STATE", + Some(ZONE_ACTIVITY_KIND) => "ZONE_ACTIVITY", _ => return json_status(json!({ "error": "unknown cell kind" }), 404), }; let Some(shard) = parts.get(1) else { diff --git a/examples/game/cells/wrangler.jsonc b/examples/game/cells/wrangler.jsonc index c78fe9da8..e18bdd9b5 100644 --- a/examples/game/cells/wrangler.jsonc +++ b/examples/game/cells/wrangler.jsonc @@ -1,7 +1,8 @@ -// The game demos' cells for `celld dev` (and `celld deploy`). The launcher -// (`examples/game/run.sh`, the test harnesses) writes `.dev.vars` beside a -// copy of this file with DISTRIBUTED_INTERNAL_SECRET and -// CELLD_QUEUE_RELAY_URL (the zone server's `/internal/celld-queue/relay`). +// The game demos' cells and Mob Pit's rooms for `celld dev` (and `celld +// deploy`). The launcher (`examples/game/run.sh`, the test harnesses) writes +// `.dev.vars` beside a copy of this file with DISTRIBUTED_INTERNAL_SECRET, +// GAME_TICKET_SECRET (shared with whoever mints room tickets) and +// CELLD_QUEUE_RELAY_URL (the services' `/internal/celld-queue/relay`). { "name": "game-demo-cells", "main": "build/worker/shim.mjs", @@ -13,13 +14,16 @@ { "name": "ZONE_LEASE", "class_name": "ZoneLeaseCell" }, { "name": "ZONE_STATE", "class_name": "ZoneStateCell" }, { "name": "GEM_POUCH", "class_name": "GemPouchCell" }, - { "name": "CONTENT_LOG", "class_name": "ContentLogCell" } + { "name": "CONTENT_LOG", "class_name": "ContentLogCell" }, + { "name": "PIT_ROOM", "class_name": "PitRoom" }, + { "name": "ZONE_ACTIVITY", "class_name": "ZoneActivityObject" } ] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["CrawlerCell", "PresenceCell"] }, { "tag": "v2", "new_sqlite_classes": ["ZoneLeaseCell", "ZoneStateCell"] }, - { "tag": "v3", "new_sqlite_classes": ["GemPouchCell", "ContentLogCell"] } + { "tag": "v3", "new_sqlite_classes": ["GemPouchCell", "ContentLogCell"] }, + { "tag": "v4", "new_sqlite_classes": ["PitRoom", "ZoneActivityObject"] } ], // Hibernation snapshots above the inline limit (celld's object storage). "r2_buckets": [ @@ -41,6 +45,13 @@ ] }, "vars": { - "OUTBOX_DRAIN_INTERVAL_MS": "5000" + "OUTBOX_DRAIN_INTERVAL_MS": "5000", + // Mob Pit rooms (distributed_game::celld_zone). GAME_TICKET_SECRET comes + // from .dev.vars (the launcher shares it with the ticket issuer). + "ZONE_TICK_HZ": "30", + "ZONE_PATCH_HZ": "20", + "ZONE_PERSIST_MS": "5000", + "ZONE_HIBERNATE_AFTER_MS": "10000", + "ZONE_FACT_SERVICE": "mobpit-rooms" } } diff --git a/examples/game/client/leaderboard/index.html b/examples/game/client/leaderboard/index.html index 05d404dbd..a2b5d6693 100644 --- a/examples/game/client/leaderboard/index.html +++ b/examples/game/client/leaderboard/index.html @@ -12,8 +12,9 @@

      Mob Pit leaderboard

      - Kill facts committed to the Crawler cells are projected into two sorted-set boards (fire-and-forget, - idempotent apply keys). The top 10 is pushed over the zone connection (observer); your rank is read on each push. + Kills settle in the Crawler cells next to the rooms on celld; their events are projected into the crawler list + and from there into two sorted-set boards (idempotent `max` updates). The top 10 refreshes live; your rank is + read on each change. Play the pit ↗

      @@ -24,7 +25,7 @@

      Mob Pit leaderboard

      You

      —
      -

      Live pit

      +

      Entrance room (observer)

      diff --git a/examples/game/client/src/generated/mobpit/constants.ts b/examples/game/client/src/generated/mobpit/constants.ts index 0e96cb0ab..e01248b13 100644 --- a/examples/game/client/src/generated/mobpit/constants.ts +++ b/examples/game/client/src/generated/mobpit/constants.ts @@ -1,7 +1,7 @@ // @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Constants: static data defined once in Rust (`GameSurface::constant`). // Do not edit: change the Rust definitions and regenerate. -import type { PitRules } from './events.ts'; +import type { PitRules, PitWorld } from './events.ts'; /** `pit_rules`, as the client decodes it. */ export const PIT_RULES: PitRules = { @@ -15,3 +15,12 @@ export const PIT_RULES: PitRules = { attackHalfAngle: 1.0471975803375244, swingFrames: 6 }; + +/** `pit_world`, as the client decodes it. */ +export const PIT_WORLD: PitWorld = { + defaultSeed: 186474221, + half: 20, + doorHalf: 2.5, + maxRoom: 1000000, + biomes: ['highlands', 'steppe', 'forest', 'meadow'] +}; diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts index c748ce269..a3f5878ba 100644 --- a/examples/game/client/src/generated/mobpit/events.ts +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -3,124 +3,6 @@ // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; -/** Record `BackgroundStats` (`#[derive(GameRecord)]`). */ -export interface BackgroundStats { - readonly enqueued: number; - readonly applied: number; - readonly dropped: number; - readonly failed: number; -} - -const BACKGROUND_STATS_TYPE: WireType = { - type: 'record', - fields: [ - ['enqueued', { type: 'u64' }], - ['applied', { type: 'u64' }], - ['dropped', { type: 'u64' }], - ['failed', { type: 'u64' }], - ] -}; - -/** Record `BoardRow` (`#[derive(GameRecord)]`). */ -export interface BoardRow { - readonly rank: number; - readonly member: string; - readonly name: string; - readonly score: number; -} - -const BOARD_ROW_TYPE: WireType = { - type: 'record', - fields: [ - ['rank', { type: 'u32' }], - ['member', { type: 'short_str' }], - ['name', { type: 'short_str' }], - ['score', { type: 'f64' }], - ] -}; - -/** Record `Scores` (`#[derive(GameRecord)]`). */ -export interface Scores { - readonly kills: number; - readonly xp: number; -} - -const SCORES_TYPE: WireType = { - type: 'record', - fields: [ - ['kills', { type: 'f64' }], - ['xp', { type: 'f64' }], - ] -}; - -/** Record `Mismatch` (`#[derive(GameRecord)]`). */ -export interface Mismatch { - readonly member: string; - readonly cell: Scores; - readonly board: Scores; -} - -const MISMATCH_TYPE: WireType = { - type: 'record', - fields: [ - ['member', { type: 'short_str' }], - ['cell', SCORES_TYPE], - ['board', SCORES_TYPE], - ] -}; - -/** Record `RebuildReport` (`#[derive(GameRecord)]`). */ -export interface RebuildReport { - readonly backend: string; - readonly crawlers: number; - readonly events: number; - readonly applied: number; - readonly duplicates: number; - readonly identicalTop: boolean; - readonly matchesCells: boolean; - readonly mismatches: readonly Mismatch[]; - readonly tookMs: number; -} - -const REBUILD_REPORT_TYPE: WireType = { - type: 'record', - fields: [ - ['backend', { type: 'short_str' }], - ['crawlers', { type: 'u32' }], - ['events', { type: 'u32' }], - ['applied', { type: 'u32' }], - ['duplicates', { type: 'u32' }], - ['identicalTop', { type: 'bool' }], - ['matchesCells', { type: 'bool' }], - ['mismatches', { type: 'list', item: MISMATCH_TYPE }], - ['tookMs', { type: 'f64' }], - ] -}; - -/** Record `BoardSnapshot` (`#[derive(GameRecord)]`). */ -export interface BoardSnapshot { - readonly version: number; - readonly backend: string; - readonly members: number; - readonly kills: readonly BoardRow[]; - readonly xp: readonly BoardRow[]; - readonly background: BackgroundStats; - readonly lastRebuild: RebuildReport | undefined; -} - -const BOARD_SNAPSHOT_TYPE: WireType = { - type: 'record', - fields: [ - ['version', { type: 'u64' }], - ['backend', { type: 'short_str' }], - ['members', { type: 'u64' }], - ['kills', { type: 'list', item: BOARD_ROW_TYPE }], - ['xp', { type: 'list', item: BOARD_ROW_TYPE }], - ['background', BACKGROUND_STATS_TYPE], - ['lastRebuild', { type: 'optional', item: REBUILD_REPORT_TYPE }], - ] -}; - /** Record `MobTier` (`#[derive(GameRecord)]`). */ export interface MobTier { readonly tier: number; @@ -138,6 +20,27 @@ export interface MoveState { readonly cd: number; } +/** Record `PitRoomContext` (`#[derive(GameRecord)]`). */ +export interface PitRoomContext { + readonly seed: number; + readonly x: number; + readonly y: number; +} + +/** Record `RoomMob` (`#[derive(GameRecord)]`). */ +export interface RoomMob { + readonly tier: number; + readonly x: number; + readonly y: number; +} + +/** Record `PitRoomLayout` (`#[derive(GameRecord)]`). */ +export interface PitRoomLayout { + readonly biome: number; + readonly danger: number; + readonly mobs: readonly RoomMob[]; +} + /** Record `PitRules` (`#[derive(GameRecord)]`). */ export interface PitRules { readonly tiers: readonly MobTier[]; @@ -147,6 +50,15 @@ export interface PitRules { readonly swingFrames: number; } +/** Record `PitWorld` (`#[derive(GameRecord)]`). */ +export interface PitWorld { + readonly defaultSeed: number; + readonly half: number; + readonly doorHalf: number; + readonly maxRoom: number; + readonly biomes: readonly string[]; +} + /** Record `Profile` (`#[derive(GameRecord)]`). */ export interface Profile { readonly xp: number; @@ -173,17 +85,25 @@ const PROFILE_TYPE: WireType = { export interface HelloEvent { readonly entity: number; readonly half: number; - readonly boot: string; readonly attackRange: number; readonly attackArcCos: number; + readonly roomX: number; + readonly roomY: number; + readonly seed: number; + readonly restored: boolean; + readonly roomKills: number; } const HELLO_LAYOUT: PayloadLayout = [ ['entity', { type: 'u32' }], ['half', { type: 'f32' }], - ['boot', { type: 'short_str' }], ['attackRange', { type: 'f32' }], ['attackArcCos', { type: 'f32' }], + ['roomX', { type: 'i32' }], + ['roomY', { type: 'i32' }], + ['seed', { type: 'u32' }], + ['restored', { type: 'bool' }], + ['roomKills', { type: 'u32' }], ]; /** Event `profile` (id 2). */ @@ -243,11 +163,6 @@ const SAVED_LAYOUT: PayloadLayout = [ ['attempts', { type: 'u32' }], ]; -/** Event `board` (id 5). */ -export type BoardEvent = BoardSnapshot; - -const BOARD_PAYLOAD: WireType = BOARD_SNAPSHOT_TYPE; - /** Event `died` (id 6). */ export interface DiedEvent { readonly respawnMs: number; @@ -257,13 +172,27 @@ const DIED_LAYOUT: PayloadLayout = [ ['respawnMs', { type: 'u32' }], ]; +/** Message `loaded` (id 1). */ +export interface LoadedMessage { + readonly principal: string; + readonly xp: number; + readonly level: number; + readonly kills: number; +} + +const MESSAGE_LOADED_LAYOUT: PayloadLayout = [ + ['principal', { type: 'short_str' }], + ['xp', { type: 'u64' }], + ['level', { type: 'u32' }], + ['kills', { type: 'u32' }], +]; + /** Event type ids by name. */ export const EVENT = { hello: 1, profile: 2, kill: 3, saved: 4, - board: 5, died: 6, } as const; @@ -273,7 +202,6 @@ export interface Events { profile: ProfileEvent; kill: KillEvent; saved: SavedEvent; - board: BoardEvent; died: DiedEvent; } @@ -303,12 +231,6 @@ export const EVENTS: GameEventCodecs = { encode: (value) => encodePayload(SAVED_LAYOUT, value), decode: (payload) => decodePayload(SAVED_LAYOUT, payload) as unknown as SavedEvent }, - board: { - id: 5, - name: 'board', - encode: (value) => encodeValue(BOARD_PAYLOAD, value), - decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent - }, died: { id: 6, name: 'died', @@ -333,3 +255,32 @@ export function onEvent( ): () => void { return onGameEvent(client, EVENTS, name, handler); } + +/** Zone inbox message type ids by name. */ +export const MESSAGE = { + loaded: 1, +} as const; + +/** Zone inbox message payload types by name. */ +export interface Messages { + loaded: LoadedMessage; +} + +/** Codecs of every zone inbox message. */ +export const MESSAGES: GameEventCodecs = { + loaded: { + id: 1, + name: 'loaded', + encode: (value) => encodePayload(MESSAGE_LOADED_LAYOUT, value), + decode: (payload) => decodePayload(MESSAGE_LOADED_LAYOUT, payload) as unknown as LoadedMessage + }, +}; + +/** Encode a zone inbox message: `typeId` and `payload` of a `/admin/zone-message` body (base64url the payload). */ +export function encodeMessage( + name: K, + value: Messages[K] +): { readonly typeId: number; readonly payload: Uint8Array } { + const codec = MESSAGES[name]; + return { typeId: codec.id, payload: codec.encode(value) }; +} diff --git a/examples/game/client/src/generated/mobpit/index.ts b/examples/game/client/src/generated/mobpit/index.ts index 481102c6c..1bb1759f5 100644 --- a/examples/game/client/src/generated/mobpit/index.ts +++ b/examples/game/client/src/generated/mobpit/index.ts @@ -6,4 +6,5 @@ export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; +export * from './pures.ts'; export * from './schema.ts'; diff --git a/examples/game/client/src/generated/mobpit/pures.ts b/examples/game/client/src/generated/mobpit/pures.ts new file mode 100644 index 000000000..e2d25d5c2 --- /dev/null +++ b/examples/game/client/src/generated/mobpit/pures.ts @@ -0,0 +1,60 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPures, type WasmPures, type WasmSource, type WireType } from '@hops-ops/distributed/game'; + +import type { PitRoomContext, PitRoomLayout } from './events.ts'; + +const PIT_ROOM_CONTEXT_TYPE: WireType = { + type: 'record', + fields: [ + ['seed', { type: 'u32' }], + ['x', { type: 'i32' }], + ['y', { type: 'i32' }], + ] +}; + +const ROOM_MOB_TYPE: WireType = { + type: 'record', + fields: [ + ['tier', { type: 'u8' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ] +}; + +const PIT_ROOM_LAYOUT_TYPE: WireType = { + type: 'record', + fields: [ + ['biome', { type: 'u8' }], + ['danger', { type: 'u8' }], + ['mobs', { type: 'list', item: ROOM_MOB_TYPE }], + ] +}; + +/** The pure functions (`#[game_pure]`) of Cargo package `game_sim`: wrapper name → module export. */ +export const PURES = { + pitRoom: { export: 'pit_room', abi: 1 }, +} as const; + +/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */ +export const PURES_WASM_URL: URL = new URL('./wasm/mobpit.wasm', import.meta.url); + +/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */ +export interface MobpitPureFns { + /** `pit_room` (`dg_pure_pit_room`). */ + pitRoom(arg: PitRoomContext): PitRoomLayout; +} + +/** The `mobpit` pure functions plus `ready` / `loaded()` / `module()`. */ +export type MobpitPures = WasmPures; + +/** + * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by + * the predicted step too is instantiated once). + */ +export function createMobpitPures(source: WasmSource = PURES_WASM_URL): MobpitPures { + return createWasmPures(source, { + pitRoom: { exportName: 'pit_room', arg: PIT_ROOM_CONTEXT_TYPE, output: PIT_ROOM_LAYOUT_TYPE }, + }); +} diff --git a/examples/game/client/src/generated/mobpit/schema.ts b/examples/game/client/src/generated/mobpit/schema.ts index 3d9f5f004..8019b0b3f 100644 --- a/examples/game/client/src/generated/mobpit/schema.ts +++ b/examples/game/client/src/generated/mobpit/schema.ts @@ -131,18 +131,16 @@ export function pillarFields(entity: { readonly fields: EntityFields }): PillarF export interface PitFields { /** `u16` */ readonly pending: number; + /** `u32` */ + readonly committed: number; /** `u16` */ - readonly slowMs: number; + readonly backlog: number; /** `f32` */ readonly tickMs: number; /** `f32` */ readonly tickMaxMs: number; /** `u32` */ - readonly workUs: number; - /** `u32` */ - readonly committed: number; - /** `u16` */ - readonly backlog: number; + readonly kills: number; } /** True for a `pit` entity. */ @@ -155,12 +153,11 @@ export function pitFields(entity: { readonly fields: EntityFields }): PitFields const f = entity.fields; return { pending: fieldNumber(f, 'pending'), - slowMs: fieldNumber(f, 'slow_ms'), - tickMs: fieldNumber(f, 'tick_ms'), - tickMaxMs: fieldNumber(f, 'tick_max_ms'), - workUs: fieldNumber(f, 'work_us'), committed: fieldNumber(f, 'committed'), backlog: fieldNumber(f, 'backlog'), + tickMs: fieldNumber(f, 'tick_ms'), + tickMaxMs: fieldNumber(f, 'tick_max_ms'), + kills: fieldNumber(f, 'kills'), }; } @@ -196,12 +193,11 @@ export const FIELD_TYPES = { }, pit: { pending: { type: 'u16' }, - slow_ms: { type: 'u16' }, - tick_ms: { type: 'f32' }, - tick_max_ms: { type: 'f32' }, - work_us: { type: 'u32' }, committed: { type: 'u32' }, backlog: { type: 'u16' }, + tick_ms: { type: 'f32' }, + tick_max_ms: { type: 'f32' }, + kills: { type: 'u32' }, }, } as const satisfies Record>; diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json index 05ed196c4..6c0a39c71 100644 --- a/examples/game/client/src/generated/mobpit/surface.json +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -36,6 +36,25 @@ } ] } + }, + { + "name": "pit_world", + "type": { + "name": "PitWorld", + "type": "record" + }, + "value": { + "biomes": [ + "highlands", + "steppe", + "forest", + "meadow" + ], + "default_seed": 186474221, + "door_half": 2.5, + "half": 20.0, + "max_room": 1000000 + } } ], "events": [ @@ -57,21 +76,45 @@ } }, { - "name": "boot", + "name": "attack_range", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "attack_range", + "name": "attack_arc_cos", "type": { "type": "f32" } }, { - "name": "attack_arc_cos", + "name": "room_x", "type": { - "type": "f32" + "type": "i32" + } + }, + { + "name": "room_y", + "type": { + "type": "i32" + } + }, + { + "name": "seed", + "type": { + "type": "u32" + } + }, + { + "name": "restored", + "type": { + "type": "bool" + } + }, + { + "name": "room_kills", + "type": { + "type": "u32" } } ], @@ -224,17 +267,6 @@ "kind": "fields" } }, - { - "id": 5, - "name": "board", - "payload": { - "kind": "value", - "type": { - "name": "BoardSnapshot", - "type": "record" - } - } - }, { "id": 6, "name": "died", @@ -542,23 +574,23 @@ }, { "correction": null, - "name": "slow_ms", + "name": "committed", "priority": 1.0, "type": { - "type": "u16" + "type": "u32" } }, { "correction": null, - "name": "tick_ms", + "name": "backlog", "priority": 1.0, "type": { - "type": "f32" + "type": "u16" } }, { "correction": null, - "name": "tick_max_ms", + "name": "tick_ms", "priority": 1.0, "type": { "type": "f32" @@ -566,27 +598,19 @@ }, { "correction": null, - "name": "work_us", + "name": "tick_max_ms", "priority": 1.0, "type": { - "type": "u32" + "type": "f32" } }, { "correction": null, - "name": "committed", + "name": "kills", "priority": 1.0, "type": { "type": "u32" } - }, - { - "correction": null, - "name": "backlog", - "priority": 1.0, - "type": { - "type": "u16" - } } ], "id": 4, @@ -594,6 +618,41 @@ "priority": 1.0 } ], + "messages": [ + { + "id": 1, + "name": "loaded", + "payload": { + "fields": [ + { + "name": "principal", + "type": { + "type": "short_str" + } + }, + { + "name": "xp", + "type": { + "type": "u64" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], "name": "mobpit", "predict": { "abi": 1, @@ -603,213 +662,135 @@ "state": "MoveState" }, "protocolVersion": 1, - "records": [ + "pures": [ { - "fields": [ - { - "name": "enqueued", - "type": { - "type": "u64" - } - }, - { - "name": "applied", - "type": { - "type": "u64" - } - }, - { - "name": "dropped", - "type": { - "type": "u64" - } - }, - { - "name": "failed", - "type": { - "type": "u64" - } - } - ], - "name": "BackgroundStats" - }, + "abi": 1, + "arg": { + "name": "PitRoomContext", + "type": "record" + }, + "export": "pit_room", + "output": { + "name": "PitRoomLayout", + "type": "record" + }, + "package": "game_sim" + } + ], + "records": [ { "fields": [ { - "name": "rank", - "type": { - "type": "u32" - } - }, - { - "name": "member", + "name": "tier", "type": { - "type": "short_str" + "type": "u8" } }, { - "name": "name", + "name": "radius", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "score", + "name": "tele", "type": { - "type": "f64" + "type": "f32" } } ], - "name": "BoardRow" + "name": "MobTier" }, { "fields": [ { - "name": "version", - "type": { - "type": "u64" - } - }, - { - "name": "backend", + "name": "x", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "members", + "name": "y", "type": { - "type": "u64" + "type": "f32" } }, { - "name": "kills", + "name": "vx", "type": { - "item": { - "name": "BoardRow", - "type": "record" - }, - "type": "list" + "type": "f32" } }, { - "name": "xp", + "name": "vy", "type": { - "item": { - "name": "BoardRow", - "type": "record" - }, - "type": "list" + "type": "f32" } }, { - "name": "background", + "name": "dash", "type": { - "name": "BackgroundStats", - "type": "record" + "type": "u8" } }, { - "name": "last_rebuild", + "name": "cd", "type": { - "item": { - "name": "RebuildReport", - "type": "record" - }, - "type": "optional" + "type": "u8" } } ], - "name": "BoardSnapshot" + "name": "MoveState" }, { "fields": [ { - "name": "member", + "name": "seed", "type": { - "type": "short_str" + "type": "u32" } }, { - "name": "cell", + "name": "x", "type": { - "name": "Scores", - "type": "record" + "type": "i32" } }, { - "name": "board", + "name": "y", "type": { - "name": "Scores", - "type": "record" + "type": "i32" } } ], - "name": "Mismatch" + "name": "PitRoomContext" }, { "fields": [ { - "name": "tier", + "name": "biome", "type": { "type": "u8" } }, { - "name": "radius", - "type": { - "type": "f32" - } - }, - { - "name": "tele", - "type": { - "type": "f32" - } - } - ], - "name": "MobTier" - }, - { - "fields": [ - { - "name": "x", - "type": { - "type": "f32" - } - }, - { - "name": "y", - "type": { - "type": "f32" - } - }, - { - "name": "vx", - "type": { - "type": "f32" - } - }, - { - "name": "vy", - "type": { - "type": "f32" - } - }, - { - "name": "dash", + "name": "danger", "type": { "type": "u8" } }, { - "name": "cd", + "name": "mobs", "type": { - "type": "u8" + "item": { + "name": "RoomMob", + "type": "record" + }, + "type": "list" } } ], - "name": "MoveState" + "name": "PitRoomLayout" }, { "fields": [ @@ -856,123 +837,104 @@ { "fields": [ { - "name": "xp", - "type": { - "type": "u64" - } - }, - { - "name": "level", + "name": "default_seed", "type": { "type": "u32" } }, { - "name": "kills", + "name": "half", "type": { - "type": "u32" + "type": "f32" } }, { - "name": "level_xp", + "name": "door_half", "type": { - "type": "u64" + "type": "f32" } }, { - "name": "next_level_xp", + "name": "max_room", "type": { - "type": "u64" + "type": "i32" } }, { - "name": "source", + "name": "biomes", "type": { - "type": "short_str" + "item": { + "type": "short_str" + }, + "type": "list" } } ], - "name": "Profile" + "name": "PitWorld" }, { "fields": [ { - "name": "backend", - "type": { - "type": "short_str" - } - }, - { - "name": "crawlers", - "type": { - "type": "u32" - } - }, - { - "name": "events", + "name": "xp", "type": { - "type": "u32" + "type": "u64" } }, { - "name": "applied", + "name": "level", "type": { "type": "u32" } }, { - "name": "duplicates", + "name": "kills", "type": { "type": "u32" } }, { - "name": "identical_top", - "type": { - "type": "bool" - } - }, - { - "name": "matches_cells", + "name": "level_xp", "type": { - "type": "bool" + "type": "u64" } }, { - "name": "mismatches", + "name": "next_level_xp", "type": { - "item": { - "name": "Mismatch", - "type": "record" - }, - "type": "list" + "type": "u64" } }, { - "name": "took_ms", + "name": "source", "type": { - "type": "f64" + "type": "short_str" } } ], - "name": "RebuildReport" + "name": "Profile" }, { "fields": [ { - "name": "kills", + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "x", "type": { - "type": "f64" + "type": "f32" } }, { - "name": "xp", + "name": "y", "type": { - "type": "f64" + "type": "f32" } } ], - "name": "Scores" + "name": "RoomMob" } ], "schemaVersion": 3 diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts index 07e28d326..bf8be5d22 100644 --- a/examples/game/client/src/leaderboard/main.ts +++ b/examples/game/client/src/leaderboard/main.ts @@ -1,20 +1,29 @@ /** - * Leaderboard page: observes the pit zone (no avatar), renders the pushed - * top-10 snapshots, reads your rank and neighbours on every push, and - * triggers a rebuild from the cells' event history. + * Leaderboard page: renders the services' top-10 snapshots (a projection of + * the Crawler cells, polled), reads your rank and neighbours on every + * change, triggers a rebuild from the cells' event history, and observes + * the entrance room (no avatar) for a live mini map. */ import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { + createMobpitClient, isMob, isPillar, isPlayer, mobFields, pillarFields, - playerFields, + playerFields +} from '../generated/mobpit/index.ts'; +import { + createBoardWatcher, + DEFAULT_ZONE, + MobPitApi, + roomUrl, + TIERS, + type BoardPosition, type BoardRow, type BoardSnapshot -} from '../generated/mobpit/index.ts'; -import { createBoardWatcher, DEFAULT_ZONE, MobPitApi, TIERS, type BoardPosition } from '../mobpit/client.ts'; +} from '../mobpit/client.ts'; import { DevApi } from '../shared/dev-api.ts'; /** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ @@ -24,8 +33,13 @@ const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; const api = new DevApi(); const pitApi = new MobPitApi(); -const watcher = createBoardWatcher({ api }); -const { client } = watcher; +const watcher = createBoardWatcher(pitApi); +const { client } = createMobpitClient({ + url: (room) => roomUrl(room), + ticket: api.ticketSource(), + pingIntervalMs: 1000, + prediction: false +}); const $ = (k: string) => document.querySelector(`[data-k="${k}"]`) as HTMLElement; const status = $('status'); @@ -74,7 +88,7 @@ async function render(board: BoardSnapshot): Promise { table($('xp'), board.xp, 'XP', me); const bg = board.background; status.textContent = - `push #${pushes} · version ${board.version} · store ${board.backend} · ${board.members} ranked` + + `update #${pushes} · version ${board.version} · store ${board.backend} · ${board.members} ranked` + ` · background updates: ${bg.applied} applied, ${bg.dropped} dropped, ${bg.failed} failed`; status.classList.add('flash'); setTimeout(() => status.classList.remove('flash'), 120); diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts index 543ddfed3..42613f9d3 100644 --- a/examples/game/client/src/mobpit/client.ts +++ b/examples/game/client/src/mobpit/client.ts @@ -1,20 +1,48 @@ /** * Mob Pit networking without rendering (Node-testable): the generated * `createMobpitClient` (the own capsule predicted by `pit_step`, the Rust - * Arena movement compiled to WebAssembly), the zone's typed events folded into a small state object, and - * the `/dev/mobpit/*` routes. + * Arena movement compiled to WebAssembly), the room's typed events folded + * into a small state object, the rooms' generated contents + * (`createMobpitPures().pitRoom`, the Rust room generator as WebAssembly), + * and the `/dev/mobpit/*` routes. + * + * Every room (`pit..`) is a celld Durable Object reached at + * `/rooms/{room}`; celld forwards the socket to whichever node runs it. + * Walking through a doorway, the room hands the player to the next room + * (`Handoff`), and the SDK reconnects there with the transfer ticket. * * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the * fact is only *queued*) → `saved` (to the killer, when the durable cell - * commit settled; `waitedMs` shows the storage latency) → `profile`. + * commit settled) → `profile`. */ -import { GameClient, type GameSocketFactory } from '@hops-ops/distributed/game'; +import type { GameSocketFactory } from '@hops-ops/distributed/game'; import * as pit from '../generated/mobpit/index.ts'; -import { zoneUrl, type DevApi } from '../shared/dev-api.ts'; +import type { DevApi } from '../shared/dev-api.ts'; import { latest } from '../shared/latest.ts'; -export const DEFAULT_ZONE = 'pit-1'; +export const DEFAULT_ZONE = 'pit.0.0'; + +/** `pit..` → `[x, y]` (undefined for anything else). */ +export function parseRoom(zone: string): [number, number] | undefined { + const m = /^pit\.(-?\d+)\.(-?\d+)$/.exec(zone); + return m === null ? undefined : [Number(m[1]), Number(m[2])]; +} + +/** `[x, y]` → `pit..`. */ +export function roomZone(x: number, y: number): string { + return `pit.${x}.${y}`; +} + +/** + * WebSocket URL of a room. `base` is the http(s) origin rooms are reached + * at (celld, in Node tests); in the browser the page's own origin (Vite + * proxies `/rooms` to celld). + */ +export function roomUrl(zone: string, base?: string): string { + const origin = base ?? globalThis.location.origin; + return `${origin.replace(/^http/, 'ws')}/rooms/${encodeURIComponent(zone)}`; +} /** `state` names of the `mob` kind, by value (generated from the Rust `MOB_STATES`). */ export const MOB_STATE = pit.PIT_RULES.states; /** Presentation of each tier (client only). */ @@ -31,29 +59,89 @@ export const TIERS: Readonly [t.tier, { ...(TIER_LOOK[t.tier] ?? { name: `Tier ${t.tier}`, color: '#9ad16b' }), radius: t.radius, tele: t.tele }]) ); -/** `/dev/mobpit/leaderboard` neighbourhood (HTTP only, not a zone event). */ -export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: pit.BoardRow[] }>; +/** One leaderboard row (`/dev/mobpit/leaderboard`). */ +export type BoardRow = Readonly<{ rank: number; member: string; name: string; score: number }>; +/** The leaderboard snapshot the services keep (top-N, store, rebuilds). */ +export type BoardSnapshot = Readonly<{ + version: number; + backend: string; + members: number; + kills: BoardRow[]; + xp: BoardRow[]; + background: { enqueued: number; applied: number; dropped: number; failed: number }; + lastRebuild: RebuildReport | null; +}>; +export type RebuildReport = Readonly<{ + backend: string; + crawlers: number; + events: number; + applied: number; + duplicates: number; + identicalTop: boolean; + matchesCells: boolean; + mismatches: { member: string; cell: { kills: number; xp: number }; board: { kills: number; xp: number } }[]; + tookMs: number; +}>; +/** `/dev/mobpit/leaderboard` neighbourhood. */ +export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: BoardRow[] }>; + +/** A room as the `zone_status` read model knows it (`/dev/mobpit/rooms`). */ +export type RoomStatus = Readonly<{ + zone: string; + x: number; + y: number; + /** `active` · `dormant` · `hibernated` (unknown rooms are cold). */ + status: 'active' | 'dormant' | 'hibernated'; + players: number; + /** The current activation restored a snapshot. */ + restored: boolean; + activations: number; + /** celld node of the activation — a debug detail (empty when unknown). */ + node: string; + changedAtMs: number; +}>; + +/** A room object's debug JSON (`/rooms/{room}/info`). */ +export type RoomInfo = Readonly<{ + zone: string; + status: string; + awake: boolean; + activation: string; + restored: boolean; + wakes: number; + node: string; + isolate: string; + players: number; + tick: number; + hz: number; + lateMs: { p50: number; p99: number }; + droppedTicks: number; +}>; export type MobPitClient = pit.MobpitClient & Readonly<{ hello(): pit.HelloEvent | undefined; profile(): pit.Profile | undefined; - board(): pit.BoardSnapshot | undefined; + /** The room the player is in (authority zone). */ + room(): string | undefined; /** Kills by me whose fact has not settled yet (key → event). */ unsaved: ReadonlyMap; + /** The rooms' generated contents (the Rust generator as WASM). */ + pures: ReturnType; /** Resolves on the first hello, once the predicted step is loaded. */ ready: Promise; }>; export type MobPitClientOptions = Readonly<{ api: DevApi; - base?: string; + /** http(s) origin of the rooms (celld); default the page's origin. */ + roomsBase?: string; socket?: GameSocketFactory; }>; export function createMobPitClient(options: MobPitClientOptions): MobPitClient { const typed = pit.createMobpitClient({ - url: (zone) => zoneUrl(zone, options.base), + url: (zone) => roomUrl(zone, options.roomsBase), ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 500, @@ -65,54 +153,85 @@ export function createMobPitClient(options: MobPitClientOptions): MobPitClient { (value) => typed.client.setControlledEntity(value.entity) ); const profile = latest((h) => typed.on('profile', h)); - const board = latest((h) => typed.on('board', h)); const unsaved = new Map(); typed.on('kill', (kill) => { if (kill.killer === hello.get()?.entity) unsaved.set(kill.key, kill); }); typed.on('saved', (saved) => unsaved.delete(saved.key)); + const pures = pit.createMobpitPures(); return { ...typed, hello: hello.get, profile: profile.get, - board: board.get, + room: () => typed.client.authority?.zoneId, unsaved, - ready: Promise.all([hello.ready, typed.prediction?.ready]).then(([h]) => h) + pures, + ready: Promise.all([hello.ready, typed.prediction?.ready, pures.ready]).then(([h]) => h) }; } -/** Observer-only client for the leaderboard page (no prediction, no inputs). */ -export function createBoardWatcher(options: MobPitClientOptions): Readonly<{ - client: GameClient; - board(): pit.BoardSnapshot | undefined; - on(handler: (value: pit.BoardSnapshot) => void): () => void; +/** Polls the services' leaderboard snapshot (the board is a projection of the cells). */ +export function createBoardWatcher(pitApi: MobPitApi, everyMs = 500): Readonly<{ + board(): BoardSnapshot | undefined; + on(handler: (value: BoardSnapshot) => void): () => void; + stop(): void; }> { - const typed = pit.createMobpitClient({ - url: (zone) => zoneUrl(zone, options.base), - ticket: options.api.ticketSource(), - socket: options.socket, - pingIntervalMs: 1000, - prediction: false - }); - const board = latest((h) => typed.on('board', h)); - return { client: typed.client, board: board.get, on: (handler) => typed.on('board', handler) }; + let current: BoardSnapshot | undefined; + const handlers = new Set<(value: BoardSnapshot) => void>(); + let stopped = false; + const poll = async () => { + while (!stopped) { + try { + const { snapshot } = await pitApi.leaderboard(); + if (current === undefined || snapshot.version !== current.version) { + current = snapshot; + for (const h of handlers) h(snapshot); + } + } catch { + // Services restarting: try again. + } + await new Promise((r) => setTimeout(r, everyMs)); + } + }; + void poll(); + return { + board: () => current, + on: (handler) => { + handlers.add(handler); + return () => handlers.delete(handler); + }, + stop: () => { + stopped = true; + } + }; } /** `/dev/mobpit/*` (dev only; none of these take an identity or a reward). */ export class MobPitApi { readonly base: string; + readonly roomsBase: string; - constructor(base = '') { + /** `base`: the services' origin; `roomsBase`: celld's (both default to the page's). */ + constructor(base = '', roomsBase = base) { this.base = base; + this.roomsBase = roomsBase; + } + + /** Every room the zone status read model knows. */ + rooms(): Promise<{ rooms: RoomStatus[] }> { + return this.#json('/dev/mobpit/rooms'); } - storage(): Promise<{ latencyMs: number }> { - return this.#json('/dev/mobpit/storage'); + /** A room object's debug JSON, straight from the room on celld (does not wake it). */ + async roomInfo(zone: string): Promise { + const response = await fetch(`${this.roomsBase}/rooms/${encodeURIComponent(zone)}/info`); + if (!response.ok) throw new Error(`room info ${zone}: HTTP ${response.status}`); + return (await response.json()) as RoomInfo; } - /** Artificial latency in front of every durable commit (server-wide). */ - setStorage(latencyMs: number): Promise<{ latencyMs: number }> { - return this.#json('/dev/mobpit/storage', { latencyMs }); + /** The player's presence cell. */ + presence(principal: string): Promise<{ presence: { zone: string; status: string } | null }> { + return this.#json(`/dev/mobpit/presence?principal=${encodeURIComponent(principal)}`); } stats(): Promise> { @@ -123,12 +242,12 @@ export class MobPitApi { return this.#json('/dev/mobpit/crawlers'); } - leaderboard(member?: string): Promise<{ snapshot: pit.BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { + leaderboard(member?: string): Promise<{ snapshot: BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { const query = member === undefined ? '' : `?member=${encodeURIComponent(member)}`; return this.#json(`/dev/mobpit/leaderboard${query}`); } - rebuild(): Promise { + rebuild(): Promise { return this.#json('/dev/mobpit/leaderboard/rebuild', {}); } diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index 661a50e94..6cfd06246 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -1,12 +1,15 @@ /** * Mob Pit page: Babylon scene over `createMobPitClient`. * - * What to look at: kill a mob (Space) and watch the grey "saving…" popup - * turn into "+XP saved ✓" when the durable cell commit settles. Toggle - * *Slow storage* (L): every commit now takes 1.5 s — the pending-facts graph - * climbs while the tick graph stays flat at ~33 ms, because the zone never - * waits for storage. Kill the server (`kill -9`), restart it, reload: your - * XP and kills come back from the cell. + * What to look at: rooms are celld Durable Objects on a near-infinite + * seeded grid. Walk through a doorway (the gaps in the middle of each wall) + * into the next room; the minimap (bottom right) shows every known room + * live — active, dormant (just left), hibernated (asleep in storage) — from + * the `zone_status` read model. Come back to a room after it slept: it + * wakes from its snapshot with the mobs you left (toast). Kill a mob + * (Space): the grey "saving…" popup turns into "+XP saved ✓" when the kill + * settled in your Crawler cell. The debug overlay (O) shows which celld + * node and isolate run the room — celld decides, the game never does. */ import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; import { Color3 } from '@babylonjs/core/Maths/math.color'; @@ -18,6 +21,7 @@ import { ARENA_FLOOR } from '../generated/arena/constants.ts'; import { BUTTON, PIT_RULES, + PIT_WORLD, isMob, isPillar, isPit, @@ -25,7 +29,6 @@ import { pillarFields, pitFields, playerFields, - type BoardSnapshot, type PitFields, type PitInput } from '../generated/mobpit/index.ts'; @@ -33,7 +36,18 @@ import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; import { createStage, material, toWorld } from '../shared/scene.ts'; -import { createMobPitClient, DEFAULT_ZONE, MobPitApi, TIERS } from './client.ts'; +import { + createBoardWatcher, + createMobPitClient, + DEFAULT_ZONE, + MobPitApi, + parseRoom, + roomZone, + TIERS, + type BoardSnapshot, + type RoomInfo, + type RoomStatus +} from './client.ts'; /** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; @@ -41,7 +55,6 @@ const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; const { attackRange, attackHalfAngle: SWING_HALF, swingFrames: SWING_FRAMES } = PIT_RULES; const ATTACK_REACH = attackRange + PLAYER_RADIUS; -const SLOW_MS = 1500; const params = new URLSearchParams(location.search); const zone = params.get('zone') ?? DEFAULT_ZONE; const storedName = (() => { @@ -64,19 +77,12 @@ const { scene } = stage; const hud = new Hud({ title: 'Mob Pit', - hint: 'WASD move · Space attack · E dash · L slow storage. Kills are durable facts; the tick never waits for them.', + hint: 'WASD move · Space attack · E dash · walk through a doorway to the next room · O debug overlay. Rooms run on celld; kills are durable facts.', client, devApi: api }); -let slow = false; -hud.toggle(`Slow storage (${SLOW_MS} ms per commit)`, false, (on) => { - slow = on; - pitApi.setStorage(on ? SLOW_MS : 0).catch((e: unknown) => hud.row('Storage', `failed: ${String(e)}`)); -}, 'l'); -pitApi - .storage() - .then((s) => (slow = s.latencyMs > 0)) - .catch(() => undefined); +let debug = params.get('debug') !== '0'; +hud.toggle('Debug overlay (celld node per room)', debug, (on) => (debug = on), 'o'); // ---- side panels: XP bar, durable facts graph, mini leaderboard ---- const xpPanel = div('pit-xp', document.body); @@ -103,6 +109,109 @@ function div(className: string, parent: HTMLElement): HTMLDivElement { return d; } +// ---- rooms: minimap from the zone status read model, toasts, debug ---- +const roomsPanel = div('pit-rooms', document.body); +roomsPanel.innerHTML = `

      Rooms

      + +
      ■ active ■ dormant ■ asleep ■ never ran
      +
      `; +const roomsMap = roomsPanel.querySelector('canvas') as HTMLCanvasElement; +const roomsField = (k: string) => roomsPanel.querySelector(`[data-k="${k}"]`) as HTMLElement; +const toasts = div('pit-toasts', document.body); +const rooms = new Map(); +let roomInfo: RoomInfo | undefined; +const STATUS_COLOR: Record = { active: '#4caf50', dormant: '#f2c94c', hibernated: '#6c7aa0' }; +const BIOME_COLOR = ['#8a8f99', '#c9a86a', '#3f7d4e', '#7fbf6a']; + +function toast(text: string): void { + const t = div('pit-toast', toasts); + t.textContent = text; + setTimeout(() => t.remove(), 5000); +} + +async function pollRooms(): Promise { + for (;;) { + try { + const { rooms: rows } = await pitApi.rooms(); + for (const row of rows) { + const before = rooms.get(row.zone); + if (before !== undefined && before.status !== row.status) { + if (row.status === 'active' && row.restored && row.activations > before.activations) { + toast(`${row.zone} woke up from hibernation — its mobs are back`); + } else if (row.status === 'hibernated') { + toast(`${row.zone} went to sleep (snapshot in celld storage)`); + } + } + rooms.set(row.zone, row); + } + } catch { + // The services restarting: keep the last view. + } + await new Promise((r) => setTimeout(r, 500)); + } +} +void pollRooms(); + +async function pollRoomInfo(): Promise { + for (;;) { + const here = pit.room(); + if (debug && here !== undefined) roomInfo = await pitApi.roomInfo(here).catch(() => roomInfo); + await new Promise((r) => setTimeout(r, 1000)); + } +} +void pollRoomInfo(); + +function drawRooms(): void { + const ctx = roomsMap.getContext('2d'); + const here = parseRoom(pit.room() ?? DEFAULT_ZONE); + if (ctx === null || here === undefined) return; + const { width } = roomsMap; + const span = 7; + const cell = width / span; + ctx.clearRect(0, 0, width, width); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + for (let j = 0; j < span; j++) { + for (let i = 0; i < span; i++) { + const x = here[0] + i - 3; + const y = here[1] + (span - 1 - j) - 3; + const zone = roomZone(x, y); + const row = rooms.get(zone); + let color = '#20252e'; + if (row !== undefined) color = STATUS_COLOR[row.status] ?? color; + else if (pit.pures.loaded()) color = `${BIOME_COLOR[pit.pures.pitRoom({ seed, x, y }).biome] ?? '#333'}55`; + ctx.fillStyle = color; + ctx.fillRect(i * cell + 2, j * cell + 2, cell - 4, cell - 4); + if (x === here[0] && y === here[1]) { + ctx.strokeStyle = '#ffffff'; + ctx.lineWidth = 2; + ctx.strokeRect(i * cell + 1, j * cell + 1, cell - 2, cell - 2); + } + ctx.fillStyle = '#0e1116'; + ctx.font = '10px monospace'; + if (row !== undefined && row.players > 0) ctx.fillText(`${row.players}p`, i * cell + 5, j * cell + 13); + if (debug && row !== undefined && row.node !== '') ctx.fillText(row.node.replace(/^node-/, ''), i * cell + 5, j * cell + cell - 6); + } + } +} + +function renderDebug(): void { + const el = roomsField('debug'); + roomsField('here').textContent = pit.room() ?? ''; + if (!debug) { + el.textContent = ''; + return; + } + const info = roomInfo; + if (info === undefined || info.zone !== pit.room()) { + el.textContent = 'room object: …'; + return; + } + const node = info.node === '' ? 'unknown (celld does not tell code its node; set CELLD_ZONE_NODES)' : info.node; + el.innerHTML = `celld object ${info.zone}
      node ${node}
      isolate ${info.isolate} · activation ${info.activation}` + + `
      wakes ${info.wakes} · ${info.restored ? 'restored from snapshot' : 'fresh'} · ${info.players} players` + + `
      tick ${info.hz} Hz · late p50 ${info.lateMs.p50.toFixed(1)} / p99 ${info.lateMs.p99.toFixed(1)} ms`; +} + // ---- materials and templates ---- const mats = { me: material(scene, 'me', '#6cc4ff'), @@ -121,6 +230,49 @@ mats.blade.emissiveColor = new Color3(0.6, 0.6, 0.7); const tierMats = new Map(); for (const [tier, t] of Object.entries(TIERS)) tierMats.set(Number(tier), material(scene, `mob-${tier}`, t.color)); +// Doorways: a glowing gate in the middle of each wall, labelled with the +// room behind it; the floor takes the room's biome colour. +const doorMat = material(scene, 'door', '#4dd0e1', 0.55); +doorMat.emissiveColor = Color3.FromHexString('#4dd0e1'); +const DOORS: { dx: number; dy: number }[] = [ + { dx: 1, dy: 0 }, + { dx: -1, dy: 0 }, + { dx: 0, dy: 1 }, + { dx: 0, dy: -1 } +]; +const doorMeshes = DOORS.map(({ dx, dy }, i) => { + const gate = MeshBuilder.CreateBox( + `door-${i}`, + { width: dx === 0 ? PIT_WORLD.doorHalf * 2 : 0.3, depth: dy === 0 ? PIT_WORLD.doorHalf * 2 : 0.3, height: 0.2 }, + scene + ); + gate.material = doorMat; + gate.isPickable = false; + gate.position.copyFrom(toWorld(dx * HALF, dy * HALF, 0.1)); + return gate; +}); +const biomeFloor = MeshBuilder.CreateGround('biome', { width: HALF * 2, height: HALF * 2 }, scene); +biomeFloor.position.y = 0.01; +biomeFloor.isPickable = false; +const biomeMat = material(scene, 'biome', '#3f7d4e', 0.18); +biomeFloor.material = biomeMat; +let shownRoom = ''; + +function showRoom(zone: string): void { + const at = parseRoom(zone); + if (at === undefined || zone === shownRoom) return; + shownRoom = zone; + DOORS.forEach(({ dx, dy }, i) => { + stage.labels.set(`door-${i}`, doorMeshes[i]!, `→ ${roomZone(at[0] + dx, at[1] + dy)}`, 0.6, 'door'); + }); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + if (pit.pures.loaded()) { + const room = pit.pures.pitRoom({ seed, x: at[0], y: at[1] }); + biomeMat.diffuseColor = Color3.FromHexString(BIOME_COLOR[room.biome] ?? '#3f7d4e'); + hud.row('Room', `${zone} · ${PIT_WORLD.biomes[room.biome] ?? '?'} · danger ${room.danger} · ${room.mobs.length} mobs`); + } +} + type PlayerVisual = { kind: 'player'; body: Mesh; blade: Mesh; arc: Mesh; nose: Mesh }; type MobVisual = { kind: 'mob'; body: Mesh; hpBack: Mesh; hpFill: Mesh; ring: Mesh; fill: Mesh; tier: number }; type PillarVisual = { kind: 'pillar'; body: Mesh }; @@ -226,7 +378,11 @@ pit.on('died', (d) => { deathBanner.style.display = ''; setTimeout(() => (deathBanner.style.display = 'none'), d.respawnMs); }); -pit.on('board', (board) => renderBoard(board)); +pit.on('hello', (hello) => { + if (hello.restored) toast(`You entered ${roomZone(hello.roomX, hello.roomY)}: restored from hibernation (${hello.roomKills} kills here so far)`); +}); +const boards = createBoardWatcher(pitApi, 1000); +boards.on((board) => renderBoard(board)); function renderBoard(board: BoardSnapshot): void { const me = api.last?.principal; @@ -380,15 +536,13 @@ stage.onFrame((now, dtMs) => { const pending = stats?.pending ?? 0; const tickMs = stats?.tickMs ?? 0; const tickMax = stats?.tickMaxMs ?? 0; - const slowMs = stats?.slowMs ?? 0; hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); hud.row('HP', me === undefined ? '—' : me.dead ? 'dead' : String(me.hp)); hud.row('Facts pending (zone)', String(pending)); hud.row('Facts saved (zone)', String(stats?.committed ?? 0)); hud.row('My unsaved kills', String(pit.unsaved.size)); - hud.row('Storage latency', slowMs > 0 ? `${slowMs} ms (slow)` : 'normal'); - hud.row('Server tick interval', `${tickMs.toFixed(1)} ms avg · ${tickMax.toFixed(1)} max`); - hud.row('Tick work', `${stats?.workUs ?? 0} µs`); + hud.row('Kills in this room', String(stats?.kills ?? 0)); + hud.row('Room tick interval', `${tickMs.toFixed(1)} ms avg · ${tickMax.toFixed(1)} max`); const profile = pit.profile(); if (profile !== undefined) { const span = Math.max(1, profile.nextLevelXp - profile.levelXp); @@ -399,10 +553,12 @@ stage.onFrame((now, dtMs) => { } field('pending').textContent = String(pending); field('saved').textContent = String(savedCount); - field('note').textContent = slow || slowMs > 0 - ? `Storage is slow: each commit waits ${slowMs} ms. Pending climbs, the tick does not.` - : 'Storage is fast: facts settle within a tick or two.'; + field('note').textContent = 'Kills settle in your Crawler cell next to the room on celld; the tick never waits for them.'; + const here = pit.room(); + if (here !== undefined) showRoom(here); if (now - lastSampleAt > 250) { + drawRooms(); + renderDebug(); lastSampleAt = now; samples.push({ pending, tick: tickMs }); if (samples.length > 120) samples.shift(); @@ -415,6 +571,6 @@ declare global { mobpit?: unknown; } } -window.mobpit = { client, api, pitApi, pit, scene }; +window.mobpit = { client, api, pitApi, pit, scene, rooms, boards }; client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/mobpit/style.css b/examples/game/client/src/mobpit/style.css index 31836839c..bdec1b330 100644 --- a/examples/game/client/src/mobpit/style.css +++ b/examples/game/client/src/mobpit/style.css @@ -118,3 +118,61 @@ width: 220px; } } +/* Rooms minimap (zone status read model) and the debug overlay. */ +.pit-rooms { + position: fixed; + right: 12px; + bottom: 16px; + width: 234px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-rooms h2 { + margin: 0 0 6px; + font-size: 13px; +} +.pit-rooms h2 small { + color: var(--muted); + font-weight: normal; +} +.pit-rooms .c-active { + color: #4caf50; +} +.pit-rooms .c-dormant { + color: #f2c94c; +} +.pit-rooms .c-hibernated { + color: #6c7aa0; +} +.pit-rooms .c-cold { + color: #556070; +} +.pit-debug { + margin-top: 6px; + font: 11px/1.4 monospace; + color: var(--muted); + word-break: break-word; +} +.pit-toasts { + position: fixed; + top: 12px; + left: 50%; + transform: translateX(-50%); + display: flex; + flex-direction: column; + gap: 6px; + pointer-events: none; + z-index: 10; +} +.pit-toast { + padding: 8px 14px; + border-radius: 6px; + background: #1f3a4d; + color: #e8f4ff; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); +} +.label.door { + color: #4dd0e1; +} diff --git a/examples/game/client/tests/helpers/celld.mjs b/examples/game/client/tests/helpers/celld.mjs index e4de7bfcc..76ab13f01 100644 --- a/examples/game/client/tests/helpers/celld.mjs +++ b/examples/game/client/tests/helpers/celld.mjs @@ -34,9 +34,13 @@ export function freePort() { /** * Start celld. `relayPort`: the demo server port its outbox Queue relays - * domain events to (`/internal/celld-queue/relay`). + * domain events to (`/internal/celld-queue/relay`); `vars`: extra worker + * vars (e.g. `ZONE_HIBERNATE_AFTER_MS` for Mob Pit's rooms). The rooms' + * ticket secret (`GAME_TICKET_SECRET`) is generated here and returned as + * `ticketSecret` (and in `env` as `DISTRIBUTED_GAME_SECRET`, what + * `game-demos mobpit` signs room tickets with). */ -export async function startCelld({ relayPort } = {}) { +export async function startCelld({ relayPort, vars: extra = {} } = {}) { const bin = process.env.CELLD_BIN; if (!bin) throw new Error('CELLD_BIN is not set: the demos\' cells run on celld (the version in .celld-version); point CELLD_BIN at the celld binary'); if (!existsSync(join(CELLS, 'build/worker/shim.mjs'))) { @@ -46,8 +50,10 @@ export async function startCelld({ relayPort } = {}) { cpSync(join(CELLS, 'build'), join(project, 'build'), { recursive: true }); cpSync(join(CELLS, 'wrangler.jsonc'), join(project, 'wrangler.jsonc')); const secret = `test-only-${randomBytes(24).toString('hex')}`; - let vars = `DISTRIBUTED_INTERNAL_SECRET=${secret}\n`; + const ticketSecret = randomBytes(32).toString('hex'); + let vars = `DISTRIBUTED_INTERNAL_SECRET=${secret}\nGAME_TICKET_SECRET=${ticketSecret}\n`; if (relayPort) vars += `CELLD_QUEUE_RELAY_URL=http://127.0.0.1:${relayPort}${RELAY_PATH}\n`; + for (const [key, value] of Object.entries(extra)) vars += `${key}=${value}\n`; writeFileSync(join(project, '.dev.vars'), vars); const port = await freePort(); const child = spawn(bin, ['dev', project, '--host', '127.0.0.1', '--port', String(port), '--no-watch', '--logs'], { @@ -72,9 +78,10 @@ export async function startCelld({ relayPort } = {}) { return { url, secret, + ticketSecret, project, /** Env for `game-demos mobpit`. */ - env: { CELLD_URL: url, DISTRIBUTED_INTERNAL_SECRET: secret }, + env: { CELLD_URL: url, DISTRIBUTED_INTERNAL_SECRET: secret, DISTRIBUTED_GAME_SECRET: ticketSecret }, output: () => output, async stop() { if (child.exitCode !== null || child.signalCode !== null) return; diff --git a/examples/game/client/tests/helpers/mobpit.mjs b/examples/game/client/tests/helpers/mobpit.mjs index 0dec97c60..6acac3a99 100644 --- a/examples/game/client/tests/helpers/mobpit.mjs +++ b/examples/game/client/tests/helpers/mobpit.mjs @@ -1,7 +1,8 @@ /** - * Headless Mob Pit helpers: a server on its own `celld dev` (the Crawler - * and presence cells), a throwaway data dir and a scripted hunter - * that walks to the nearest mob, faces it and swings until `done()` is true. + * Headless Mob Pit helpers: the rooms and cells on their own `celld dev`, + * the services (`game-demos mobpit`) on a throwaway data dir, and a + * scripted hunter that walks to the nearest mob, faces it and swings until + * `done()` is true. */ import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -16,13 +17,14 @@ export function tempDataDir() { } /** - * celld + `game-demos ` (mobpit / leaderboard) on a fixed port that - * celld's outbox relay targets. `restart()` restarts only the game server - * (same port, data dir and cells); `stop()` stops both. + * celld (rooms + cells) + `game-demos ` (mobpit / leaderboard: the + * services) on a fixed port that celld's outbox relay targets. + * `roomsUrl` is where rooms are (celld). `restart()` restarts only the + * services (same port, data dir and cells); `stop()` stops both. */ -export async function startPit(demo = 'mobpit') { +export async function startPit(demo = 'mobpit', vars = {}) { const port = await freePort(); - const celld = await startCelld({ relayPort: port }); + const celld = await startCelld({ relayPort: port, vars: { ZONE_HIBERNATE_AFTER_MS: '1500', ...vars } }); const env = { ...celld.env, MOBPIT_DATA_DIR: tempDataDir() }; let server; try { @@ -33,6 +35,7 @@ export async function startPit(demo = 'mobpit') { } return { celld, + roomsUrl: celld.url, get httpUrl() { return server.httpUrl; }, @@ -47,6 +50,33 @@ export async function startPit(demo = 'mobpit') { }; } +/** Walk to the doorway on side `[dx, dy]` and push through it until the + * client's authority is another room (one command frame per tick). */ +export async function walkThroughDoor(pit, [dx, dy], timeoutMs = 30_000) { + const { client } = pit; + const from = pit.room(); + const deadline = Date.now() + timeoutMs; + while (pit.room() === from) { + if (Date.now() > deadline) throw new Error(`walk through door ${dx},${dy} timed out`); + const rendered = client.render(); + const meEntity = rendered.find((e) => e.id === pit.hello()?.entity && isPlayer(e) && e.zoneId === from); + const me = meEntity && playerFields(meEntity); + let input = { mx: 0, my: 0, buttons: 0 }; + if (me !== undefined) { + // Beside the pillar on the door's axis, then straight out. + const tx = dx !== 0 ? dx * 21 : 2; + const ty = dy !== 0 ? dy * 21 : 2; + const ddx = tx - me.x; + const ddy = ty - me.y; + const len = Math.max(Math.hypot(ddx, ddy), 1e-3); + input = { mx: Math.round((ddx / len) * 127), my: Math.round((ddy / len) * 127), buttons: 0 }; + } + client.sendInput(input); + await sleep(1000 / 30); + } + return pit.room(); +} + /** Hunt mobs (one command frame per 30 Hz tick) until `done()` or timeout. */ export async function hunt(pit, done, timeoutMs = 45_000) { const { client } = pit; @@ -54,9 +84,10 @@ export async function hunt(pit, done, timeoutMs = 45_000) { while (!done()) { if (Date.now() > deadline) throw new Error('hunt timed out'); const rendered = client.render(); - const meEntity = rendered.find((e) => e.id === pit.hello()?.entity && isPlayer(e)); + const room = pit.room?.(); + const meEntity = rendered.find((e) => e.id === pit.hello()?.entity && isPlayer(e) && (room === undefined || e.zoneId === room)); const me = meEntity && playerFields(meEntity); - const mobs = rendered.filter((e) => isMob(e) && !e.stale).map(mobFields); + const mobs = rendered.filter((e) => isMob(e) && !e.stale && (room === undefined || e.zoneId === room)).map(mobFields); let input = { mx: 0, my: 0, buttons: 0 }; if (me !== undefined && mobs.length > 0 && !me.dead) { const target = mobs diff --git a/examples/game/client/tests/leaderboard-headless.test.mjs b/examples/game/client/tests/leaderboard-headless.test.mjs index 4a72e22e8..379ea2a4a 100644 --- a/examples/game/client/tests/leaderboard-headless.test.mjs +++ b/examples/game/client/tests/leaderboard-headless.test.mjs @@ -1,7 +1,8 @@ /** - * Headless Leaderboard: a hunter scores kills in the pit, an observer - * receives pushed board snapshots whose scores equal the celld Crawler cells; - * rebuilding from the cells' events yields the identical board. + * Headless Leaderboard: a hunter scores kills in a room on celld; the + * services' board (a projection of the Crawler cells) follows, its scores + * equal the cells; rebuilding from the cells' events yields the identical + * board. */ import assert from 'node:assert/strict'; import test from 'node:test'; @@ -14,31 +15,29 @@ import { hunt, startPit } from './helpers/mobpit.mjs'; test('board pushes match the cells and rebuild is identical', { timeout: 600_000 }, async () => { const server = await startPit('leaderboard'); const clients = []; + let watcher; try { const storage = memoryStorage(); const api = new DevApi({ base: server.httpUrl, name: () => 'Ranker', storage }); - const pitApi = new MobPitApi(server.httpUrl); + const pitApi = new MobPitApi(server.httpUrl, server.roomsUrl); - // Observer page first: it gets the current (empty) snapshot on observe. - const watcher = createBoardWatcher({ api: new DevApi({ base: server.httpUrl, storage }), base: server.httpUrl }); - clients.push(watcher.client); + watcher = createBoardWatcher(pitApi, 200); const pushes = []; watcher.on((b) => pushes.push(b)); - await watcher.client.observe('pit-1'); - await until(() => pushes.length >= 1, 5_000, 'initial board push'); + await until(() => pushes.length >= 1, 5_000, 'initial board'); assert.equal(watcher.board().backend, 'memory'); - const pit = createMobPitClient({ api, base: server.httpUrl }); + const pit = createMobPitClient({ api, roomsBase: server.roomsUrl }); clients.push(pit.client); - await pit.client.connect('pit-1'); + await pit.client.connect('pit.0.0'); await pit.ready; const me = api.last.principal; await hunt(pit, () => (pit.profile()?.kills ?? 0) >= 2); const profile = pit.profile(); - // Pushed, not polled: the observer sees my kills without asking. + // The board follows the cells (via the projected crawler list). const row = (b, board) => b[board].find((r) => r.member === me); - await until(() => row(watcher.board(), 'kills')?.score === profile.kills, 10_000, 'pushed kills'); + await until(() => row(watcher.board(), 'kills')?.score === profile.kills, 20_000, 'board kills'); assert.equal(row(watcher.board(), 'kills').name, 'Ranker'); assert.equal(row(watcher.board(), 'xp').score, profile.xp); // The crawler list (and so the rebuild) is a projection of the cells' @@ -61,8 +60,9 @@ test('board pushes match the cells and rebuild is identical', { timeout: 600_000 assert.equal(report.identicalTop, true); const after = (await pitApi.leaderboard()).snapshot; assert.deepEqual([after.kills, after.xp], top, 'rebuild from events = live board'); - await until(() => watcher.board().lastRebuild?.events === profile.kills, 5_000, 'rebuild pushed'); + await until(() => watcher.board().lastRebuild?.events === profile.kills, 5_000, 'rebuild shown'); } finally { + watcher?.stop(); for (const c of clients) c.close(); await server.stop(); } diff --git a/examples/game/client/tests/mobpit-headless.test.mjs b/examples/game/client/tests/mobpit-headless.test.mjs index 2bb038757..711ac2eb6 100644 --- a/examples/game/client/tests/mobpit-headless.test.mjs +++ b/examples/game/client/tests/mobpit-headless.test.mjs @@ -1,99 +1,103 @@ /** - * Headless Mob Pit (Node, real `game-demos mobpit` binary on its own - * `celld dev`): join → profile read from the celld Crawler cell → kill a mob - * → the fact settles ("saved") with server-decided XP → slow storage makes - * the settlement wait while the tick stays flat → restart the server → XP is - * still there. + * Headless Mob Pit (Node): the rooms on their own `celld dev` (each room a + * Durable Object), the services binary (`game-demos mobpit`), a scripted + * player: + * + * join the entrance room → profile read from the celld Crawler cell → kill + * a mob → the fact settles ("saved") with server-decided XP → walk through + * a doorway into the next room → the left room goes dormant, then + * hibernated (zone status read model) → walk back → the room wakes from its + * snapshot with the mobs killed there still dead → restart the services: + * the profile is still there. */ import assert from 'node:assert/strict'; import test from 'node:test'; -import { isPit, pitFields } from '../src/generated/mobpit/index.ts'; +import { isMob, isPit, pitFields } from '../src/generated/mobpit/index.ts'; import { createMobPitClient, MobPitApi } from '../src/mobpit/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { eventually, memoryStorage, until } from './helpers/demo-server.mjs'; -import { hunt, startPit } from './helpers/mobpit.mjs'; +import { hunt, startPit, walkThroughDoor } from './helpers/mobpit.mjs'; const XP = new Set([10, 25, 60]); -test('kills become durable facts without stalling the tick, and survive a restart', { timeout: 600_000 }, async () => { +test('rooms on celld: kills settle, doorways hand over, left rooms sleep and restore', { timeout: 600_000 }, async () => { const storage = memoryStorage(); const server = await startPit('mobpit'); const clients = []; try { const api = new DevApi({ base: server.httpUrl, name: () => 'Hunter', storage }); - const pitApi = new MobPitApi(server.httpUrl); - const pit = createMobPitClient({ api, base: server.httpUrl }); + const pitApi = new MobPitApi(server.httpUrl, server.roomsUrl); + const pit = createMobPitClient({ api, roomsBase: server.roomsUrl }); clients.push(pit.client); - const welcome = await pit.client.connect('pit-1'); + const welcome = await pit.client.connect('pit.0.0'); assert.deepEqual(welcome.schema.kinds.map((k) => k.name), ['player', 'mob', 'pillar', 'pit']); - await pit.ready; - await until(() => pit.profile() !== undefined, 5_000, 'profile from the cell'); + const hello = await pit.ready; + assert.deepEqual([hello.roomX, hello.roomY, hello.restored], [0, 0, false]); + await until(() => pit.profile() !== undefined, 10_000, 'profile from the cell'); assert.equal(pit.profile().source, 'cell'); assert.equal(pit.profile().kills, 0); + // The room's own seeded contents, computed by the same Rust as WASM. + const layout = pit.pures.pitRoom({ seed: hello.seed, x: 0, y: 0 }); + const mobsHere = () => pit.client.render().filter((e) => isMob(e) && e.zoneId === 'pit.0.0' && !e.stale).length; + await until(() => mobsHere() === layout.mobs.length, 5_000, 'mobs of the generated layout'); - // First kill at normal speed. + // A kill settles in the Crawler cell. const saved = []; const kills = []; pit.on('saved', (s) => saved.push(s)); pit.on('kill', (k) => k.killer === pit.hello().entity && kills.push(k)); await hunt(pit, () => saved.length >= 1); assert.ok(saved[0].ok && XP.has(saved[0].xp), JSON.stringify(saved[0])); - assert.equal(saved[0].key, kills[0].key); - assert.match( - saved[0].key, - /^crawler\.record_kill:pit-1:\d+:m\d+:\d+$/, - '{command}:{zone}:{boot_epoch}:m{mob}:{generation}' - ); - // One swing can kill several mobs: wait until every own kill settled. - await until(() => pit.unsaved.size === 0 && saved.length === kills.length, 5_000, 'settlements'); - await until(() => pit.profile().source === 'settled' && pit.profile().kills === kills.length, 5_000, `profile after settlement ${JSON.stringify(pit.profile())}`); - - // Slow storage: the next kill stays unsaved for ~1.5 s, the tick does not slow down. - assert.equal((await pitApi.setStorage(1500)).latencyMs, 1500); + assert.match(saved[0].key, /^crawler\.record_kill:pit\.0\.0:\d+:m\d+:\d+$/, '{command}:{room}:{boot_epoch}:m{mob}:{generation}'); + await until(() => pit.unsaved.size === 0 && saved.length === kills.length, 10_000, 'settlements'); const pitStats = () => { - const entity = pit.client.render().find(isPit); + const entity = pit.client.render().find((e) => isPit(e) && e.zoneId === pit.room()); return entity && pitFields(entity); }; - const fastKills = kills.length; - await hunt(pit, () => kills.length > fastKills); - await until(() => (pitStats()?.pending ?? 0) >= 1, 2_000, 'pending fact replicated'); - assert.ok(pit.unsaved.size >= 1, 'kill not yet saved'); - const ticks = []; - const sampleUntil = Date.now() + 900; - while (Date.now() < sampleUntil) { - ticks.push(pitStats()?.tickMaxMs ?? 0); - await new Promise((r) => setTimeout(r, 100)); - } - assert.ok(Math.max(...ticks) < 80, `tick interval stays ~33 ms while storage is slow: ${ticks}`); - await until(() => saved.length === kills.length, 15_000, 'slow settlements'); - assert.ok(saved[fastKills].waitedMs >= 1400, `waited ${saved[fastKills].waitedMs} ms`); - await pitApi.setStorage(0); - await until(() => pit.profile().kills === kills.length, 5_000, 'profile'); - const before = pit.profile(); + await until(() => (pitStats()?.kills ?? 0) >= kills.length, 5_000, 'room kill count'); + const roomKills = pitStats().kills; - // Graceful restart on the same data dir (the smoke test covers kill -9): - // the guest token stays valid (secret persisted in the data dir) and - // the profile is read back from the cell. + // Through the east doorway: the room hands the player to pit.1.0. + const next = await walkThroughDoor(pit, [1, 0]); + assert.equal(next, 'pit.1.0'); + await until(() => pit.hello()?.roomX === 1, 10_000, 'hello of the next room'); + // The left room empties: dormant, then hibernated. + const status = async (zone) => (await pitApi.rooms()).rooms.find((r) => r.zone === zone)?.status; + await eventually(async () => (await status('pit.0.0')) === 'hibernated', 30_000, 'pit.0.0 hibernated'); + assert.equal((await pitApi.roomInfo('pit.0.0')).awake, false); + assert.equal(await status('pit.1.0'), 'active'); + + // Back west: the room wakes from its snapshot, the dead stay dead. + assert.equal(await walkThroughDoor(pit, [-1, 0]), 'pit.0.0'); + await until(() => pit.hello()?.roomX === 0, 10_000, 'hello of the entrance again'); + assert.equal(pit.hello().restored, true, 'restored from hibernation'); + assert.equal(pit.hello().roomKills, roomKills); + const restored = await eventually(async () => { + const row = (await pitApi.rooms()).rooms.find((r) => r.zone === 'pit.0.0'); + return row?.status === 'active' && row.restored && row; + }, 15_000, 'pit.0.0 active again, restored'); + assert.ok(restored.activations >= 2); + + // The services restart; the profile is read back from the cell. + const before = pit.profile(); pit.client.close(); await server.restart(); - const again = createMobPitClient({ api: new DevApi({ base: server.httpUrl, storage }), base: server.httpUrl }); + const again = createMobPitClient({ api: new DevApi({ base: server.httpUrl, storage }), roomsBase: server.roomsUrl }); clients.push(again.client); - await again.client.connect('pit-1'); - await until(() => again.profile() !== undefined, 5_000, 'profile after restart'); - assert.equal(again.profile().source, 'cell'); + await again.client.connect('pit.0.0'); + await until(() => again.profile() !== undefined, 10_000, 'profile after restart'); assert.equal(again.profile().kills, before.kills); assert.equal(again.profile().xp, before.xp); - // The crawler list is a projection of the cells' kill events. const crawlers = await eventually( async () => { const { crawlers } = await new MobPitApi(server.httpUrl).crawlers(); - return crawlers.length === 1 && crawlers[0].kills === kills.length && crawlers; + return crawlers.length === 1 && crawlers[0].kills === before.kills && crawlers; }, 15_000, 'crawler directory' ); - assert.equal(crawlers[0].kills, kills.length); + assert.equal(crawlers[0].kills, before.kills); } finally { for (const c of clients) c.close(); await server.stop(); diff --git a/examples/game/client/tests/prediction-wasm.test.mjs b/examples/game/client/tests/prediction-wasm.test.mjs index 42e6719b4..faa17c48b 100644 --- a/examples/game/client/tests/prediction-wasm.test.mjs +++ b/examples/game/client/tests/prediction-wasm.test.mjs @@ -117,7 +117,7 @@ const pureSurfaces = readdirSync(GENERATED) .map((name) => ({ name, pures: JSON.parse(readFileSync(new URL(`${name}/surface.json`, GENERATED), 'utf8')).pures })); test('every pure function has a native trace and every trace a surface', () => { - assert.deepEqual(pureSurfaces.map((s) => s.name), ['grid']); + assert.deepEqual(pureSurfaces.map((s) => s.name), ['grid', 'mobpit']); const declared = pureSurfaces.flatMap((s) => s.pures.map((p) => p.export)).sort(); assert.deepEqual(traces.pures.map((p) => p.export).sort(), declared); }); @@ -144,7 +144,7 @@ test('grid: the generated wrappers decode what the native generation encodes', a grid_cell: pureType(generated, 'grid_cell'), grid_sample: pureType(generated, 'grid_sample') }; - for (const pure of traces.pures) { + for (const pure of traces.pures.filter((p) => p.export in types)) { const { arg, output } = types[pure.export]; const wrapper = pure.export === 'grid_cell' ? pures.gridCell : pures.gridSample; for (const call of pure.calls.slice(0, 12)) { diff --git a/examples/game/client/vite.config.ts b/examples/game/client/vite.config.ts index 405dc7b43..384457ee3 100644 --- a/examples/game/client/vite.config.ts +++ b/examples/game/client/vite.config.ts @@ -1,12 +1,15 @@ // Multi-page Vite app: `/` lists the demos, `//` is one demo. // Add a demo: create `/index.html` + `src//main.ts` and list it // in DEMOS. In dev, game traffic is proxied to the Rust `game-demos` server -// (GAME_DEMOS_SERVER, default http://127.0.0.1:2567). +// (GAME_DEMOS_SERVER, default http://127.0.0.1:2567); Mob Pit's rooms +// (`/rooms/{room}`) to celld, which runs them (GAME_DEMOS_ROOMS, default +// http://127.0.0.1:2570). import { resolve } from 'node:path'; import { defineConfig } from 'vite'; const DEMOS = ['arena', 'mobpit', 'leaderboard', 'gallery', 'freeze', 'grid', 'ripple']; const server = process.env.GAME_DEMOS_SERVER ?? 'http://127.0.0.1:2567'; +const rooms = process.env.GAME_DEMOS_ROOMS ?? 'http://127.0.0.1:2570'; export default defineConfig({ server: { @@ -14,6 +17,7 @@ export default defineConfig({ strictPort: true, proxy: { '/zones': { target: server, ws: true }, + '/rooms': { target: rooms, ws: true }, '/dev': server, '/metrics': server }, diff --git a/examples/game/run.sh b/examples/game/run.sh index 51cd396b2..210b2b853 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -3,7 +3,15 @@ # # ./run.sh arena build what is needed, start the arena server # (dev routes on) + Vite, print the URL -# ./run.sh mobpit same for Mob Pit; `leaderboard` = same server, board page +# ./run.sh mobpit Mob Pit: its rooms run on celld (`celld dev`, the +# cells worker hosts one Durable Object per room), +# the services (tickets, read models, boards) and +# Vite; `leaderboard` = same, board page +# ./run.sh mobpit --fleet [N] +# same on a local multi-node celld: N nodes (default +# 3) in production mode on one RustFS bucket +# (docker compose), entered round-robin, so rooms +# land on different nodes (debug overlay shows which) # ./run.sh grid|ripple same with TWO hosts (A on GAME_DEMOS_PORT, B on # the next port), one process each # ./run.sh gen regenerate client/src/generated// from the @@ -14,7 +22,8 @@ # (`distributed game-wasm`, gitignored, stamped so # an unchanged module is not rebuilt); `gen --check` # verifies the TypeScript (and still builds WASM) -# ./run.sh sveltekit Mob Pit in SvelteKit (sveltekit/): dev sign-in, +# ./run.sh sveltekit [--fleet [N]] +# Mob Pit in SvelteKit (sveltekit/): dev sign-in, # session-minted tickets, game client generated by # the Vite plugin, Svelte HUD, and the settled # read model from mobpit-service over GraphQL @live @@ -33,11 +42,14 @@ # uses GAME_DEMOS_PORT, default 2967 there, and its read-model service # MOBPIT_SERVICE_PORT, default GAME_DEMOS_PORT + 2). # -# celld: the demos' durable cells (examples/game/cells: Mob Pit's Crawler -# and presence cells, The Freeze's gem and content cells, every -# multi-host demo's zone leases and hibernation snapshots) run on celld, -# never natively; state persists in .data//celld (Mob Pit: -# MOBPIT_DATA_DIR/celld). CELLD_BIN names the binary (default: `celld` on +# celld: Mob Pit's rooms and the demos' durable cells (examples/game/cells: +# Mob Pit's rooms, Crawler, presence and zone-activity cells, The Freeze's +# gem and content cells, every multi-host demo's zone leases and +# hibernation snapshots) run on celld, never natively; state persists in +# .data//celld (Mob Pit: MOBPIT_DATA_DIR/celld, the fleet's bucket in +# a RustFS volume of its compose project). Fleet ports: nodes' public +# listeners GAME_DEMOS_PORT + 10.., operators + 20.., RustFS + 30 +# (MOBPIT_FLEET_S3_PORT); `docker compose down -v` runs on exit. CELLD_BIN names the binary (default: `celld` on # PATH; the version pinned in .celld-version, checked by # scripts/celld.sh), CELLD_PORT its port (default # GAME_DEMOS_PORT + 3; cluster demos GAME_DEMOS_PORT + 4), @@ -142,6 +154,7 @@ kill_tree() { # worker in (its state persists in /.celld/dev), relaying # the outbox Queue to the game server on . Sets CELLD_PID, # CELLD_URL and DISTRIBUTED_INTERNAL_SECRET (persisted in the project). +# CELLD_EXTRA_VARS (newline-terminated `KEY=value` lines) adds worker vars. start_celld() { local project="$1" port="$2" relay_port="$3" ensure_celld @@ -154,8 +167,8 @@ start_celld() { (umask 077 && printf 'test-only-%s' "$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')" >"$project/internal-secret") fi DISTRIBUTED_INTERNAL_SECRET="$(cat "$project/internal-secret")" - printf 'DISTRIBUTED_INTERNAL_SECRET=%s\nCELLD_QUEUE_RELAY_URL=http://127.0.0.1:%s/internal/celld-queue/relay\n' \ - "$DISTRIBUTED_INTERNAL_SECRET" "$relay_port" >"$project/.dev.vars" + printf 'DISTRIBUTED_INTERNAL_SECRET=%s\nCELLD_QUEUE_RELAY_URL=http://127.0.0.1:%s/internal/celld-queue/relay\n%s' \ + "$DISTRIBUTED_INTERNAL_SECRET" "$relay_port" "${CELLD_EXTRA_VARS:-}" >"$project/.dev.vars" log "starting celld dev on :$port ($("$CELLD_BIN" --version 2>/dev/null | grep '^celld ' | head -1); state in $project/.celld/dev)" RUST_LOG=warn "$CELLD_BIN" dev "$project" --host 127.0.0.1 --port "$port" --no-watch --logs >"$project/celld.log" 2>&1 & CELLD_PID=$! @@ -232,6 +245,165 @@ ensure_wasm() { return "$status" } +# mobpit_secret : the rooms' ticket secret, persisted in (the +# services read the same file: guests keep their identity across restarts). +mobpit_secret() { + local file="$1/dev-ticket-secret" + mkdir -p "$1" + if [[ ! -s "$file" ]]; then + (umask 077 && od -An -N32 -tx1 /dev/urandom | tr -d ' \n' >"$file") + fi + cat "$file" +} + +# start_fleet : a local multi-node +# celld in production mode — one RustFS container (docker compose; Dory +# publishes ports for compose, not for plain `docker run`) holding the +# fleet bucket, the cells worker deployed to it (`celld deploy`, vars +# inlined), N nodes. Sets FLEET_PIDS, FLEET_PROJECT, FLEET_COMPOSE, +# CELLD_URL (node-a, for the services), ROOMS_URLS (a round-robin load +# balancer over every node, for browsers: scripts/round-robin.mjs) and +# DISTRIBUTED_INTERNAL_SECRET. +start_fleet() { + local dir="$1" relay_port="$2" nodes="$3" ticket_secret="$4" + local base="${GAME_DEMOS_PORT:-2567}" + local s3_port="${MOBPIT_FLEET_S3_PORT:-$((base + 30))}" + ensure_celld + ensure_cells + for tool in docker aws python3; do + command -v "$tool" >/dev/null || { echo "--fleet needs $tool" >&2; exit 1; } + done + mkdir -p "$dir" + export AWS_ACCESS_KEY_ID=mobpitfleet AWS_SECRET_ACCESS_KEY=mobpitfleetsecret AWS_REGION=us-east-1 + export S3_ENDPOINT="http://127.0.0.1:$s3_port" + FLEET_PROJECT="mobpit-fleet-$base" + FLEET_COMPOSE="$dir/s3-compose.yaml" + cat >"$FLEET_COMPOSE" </dev/null + for _ in $(seq 1 60); do + aws --endpoint-url "$S3_ENDPOINT" s3 mb s3://mobpit-fleet >/dev/null 2>&1 && break + aws --endpoint-url "$S3_ENDPOINT" s3 ls s3://mobpit-fleet >/dev/null 2>&1 && break + sleep 1 + done + if [[ ! -s "$dir/internal-secret" ]]; then + (umask 077 && printf 'test-only-%s' "$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')" >"$dir/internal-secret") + fi + DISTRIBUTED_INTERNAL_SECRET="$(cat "$dir/internal-secret")" + local names=(a b c d e f) nodes_var="" i + for ((i = 0; i < nodes; i++)); do + nodes_var+="${nodes_var:+,}node-${names[$i]}=127.0.0.1:$((base + 20 + i))" + done + rm -rf "$dir/worker" && mkdir -p "$dir/worker" + cp -R "$CELLS/build" "$dir/worker/build" + python3 - "$CELLS/wrangler.jsonc" "$dir/worker/wrangler.json" <&1 | grep -E "Version ID|rror" || true + FLEET_PIDS=() + ROOMS_URLS="" + for ((i = 0; i < nodes; i++)); do + local name="node-${names[$i]}" ndir="$dir/node-${names[$i]}" + mkdir -p "$ndir" + CELLD_NODE="$name" CELLD_WATCH="$ndir/watch" RUST_LOG="${RUST_LOG:-warn}" \ + CELLD_IDLE_EVICT_S="${CELLD_IDLE_EVICT_S:-60}" CELLD_READY_FLEET_GATE_MS=0 \ + "$CELLD_BIN" --bucket s3://mobpit-fleet/fleet --listen "127.0.0.1:$((base + 10 + i))" \ + --internal-listen "127.0.0.1:$((base + 20 + i))" --advertise "127.0.0.1:$((base + 20 + i))" \ + >"$ndir/celld.log" 2>&1 & + FLEET_PIDS+=($!) + ROOMS_URLS+="${ROOMS_URLS:+,}http://127.0.0.1:$((base + 10 + i))" + done + for ((i = 0; i < nodes; i++)); do + for _ in $(seq 1 120); do + curl -fsS "http://127.0.0.1:$((base + 10 + i))/health" >/dev/null 2>&1 && break + sleep 0.5 + done + curl -fsS "http://127.0.0.1:$((base + 10 + i))/health" >/dev/null || { + tail -20 "$dir/node-${names[$i]}/celld.log" + echo "fleet node-${names[$i]} did not start" >&2 + exit 1 + } + log "node-${names[$i]}: http://127.0.0.1:$((base + 10 + i)) (operator :$((base + 20 + i)), logs $dir/node-${names[$i]}/celld.log)" + done + CELLD_URL="http://127.0.0.1:$((base + 10))" + # One entry point for browsers, spreading connections over the nodes + # like a production load balancer would (placement stays celld's). + local lb_port="${MOBPIT_FLEET_LB_PORT:-$((base + 9))}" + node "$HERE/scripts/round-robin.mjs" "$lb_port" "$(echo "$ROOMS_URLS" | sed 's#http://##g')" >"$dir/lb.log" 2>&1 & + FLEET_PIDS+=($!) + for _ in $(seq 1 50); do grep -q LISTENING "$dir/lb.log" && break; sleep 0.1; done + log "load balancer: http://127.0.0.1:$lb_port → $ROOMS_URLS (round robin per connection)" + ROOMS_URLS="http://127.0.0.1:$lb_port" + export CELLD_URL DISTRIBUTED_INTERNAL_SECRET +} + +stop_fleet() { + [[ -n "${FLEET_PROJECT:-}" ]] || return 0 + kill "${FLEET_PIDS[@]}" 2>/dev/null || true + wait "${FLEET_PIDS[@]}" 2>/dev/null || true + docker compose -p "$FLEET_PROJECT" -f "$FLEET_COMPOSE" down -v >/dev/null 2>&1 || true +} + +# Mob Pit: rooms on celld (`celld dev`, or a local fleet with --fleet [N]), +# the services (`game-demos mobpit`: tickets, read models, boards) and Vite. +run_mobpit() { + local demo="$1" fleet="${2:-}" nodes="${3:-3}" + local port="${GAME_DEMOS_PORT:-2567}" + local client_port="${GAME_DEMOS_CLIENT_PORT:-5173}" + ensure_sdk + ensure_client + ensure_server + ensure_wasm + local secret + secret="$(mobpit_secret "$MOBPIT_DATA_DIR")" + CELLD_PID="" + FLEET_PROJECT="" + if [[ "$fleet" == --fleet ]]; then + start_fleet "$MOBPIT_DATA_DIR/fleet" "$port" "$nodes" "$secret" + else + CELLD_EXTRA_VARS="GAME_TICKET_SECRET=$secret"$'\n'"CELLD_ZONE_NODE=celld-dev"$'\n' + start_celld "$MOBPIT_DATA_DIR/celld" "${CELLD_PORT:-$((port + 3))}" "$port" + ROOMS_URLS="$CELLD_URL" + fi + local log_file + log_file="$(mktemp -t game-demos.XXXXXX)" + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --dev --port "$port" \ + --data-dir "$MOBPIT_DATA_DIR" --celld-url "$CELLD_URL" >"$log_file" 2>&1 & + local server_pid=$! + trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; [[ -z "$CELLD_PID" ]] || kill_tree "$CELLD_PID"; stop_fleet; rm -f "$log_file"' EXIT INT TERM + wait_listening "$log_file" "$server_pid" "game-demos mobpit" + sed -n '2p' "$log_file" + echo + log "open http://localhost:$client_port/$demo/ (services :$port, rooms on celld ${ROOMS_URLS}; dev routes ON — local only)" + echo + cd "$CLIENT" + GAME_DEMOS_SERVER="http://127.0.0.1:$port" GAME_DEMOS_ROOMS="$ROOMS_URLS" \ + GAME_DEMOS_CLIENT_PORT="$client_port" npx vite +} + run_demo() { local demo="$1" local port="${GAME_DEMOS_PORT:-2567}" @@ -356,6 +528,7 @@ require_redis() { # changes). run_sveltekit() { require_redis + local fleet="${1:-}" nodes="${2:-3}" local port="${GAME_DEMOS_PORT:-2967}" local ui_port="${SVELTEKIT_PORT:-5573}" local service_port="${MOBPIT_SERVICE_PORT:-$((port + 2))}" @@ -365,19 +538,28 @@ run_sveltekit() { ensure_server ensure_cli mkdir -p "$data" - start_celld "$data/celld" "${CELLD_PORT:-$((port + 3))}" "$port" - local log_file secret + local secret + secret="$(mobpit_secret "$data")" + CELLD_PID="" + FLEET_PROJECT="" + if [[ "$fleet" == --fleet ]]; then + GAME_DEMOS_PORT="$port" start_fleet "$data/fleet" "$port" "$nodes" "$secret" + else + CELLD_EXTRA_VARS="GAME_TICKET_SECRET=$secret"$'\n'"CELLD_ZONE_NODE=celld-dev"$'\n' + start_celld "$data/celld" "${CELLD_PORT:-$((port + 3))}" "$port" + ROOMS_URLS="$CELLD_URL" + fi + local log_file log_file="$(mktemp -t game-demos-sveltekit.XXXXXX)" - secret="${DISTRIBUTED_GAME_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" - DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --port "$port" \ + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" mobpit --port "$port" --celld-url "$CELLD_URL" \ --data-dir "$data" --projection-bus "sqlite:$data/bus.db" \ --redis-url "$REDIS_URL" >"$log_file" 2>&1 & local server_pid=$! - trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; kill_tree "$CELLD_PID"; rm -f "$log_file"' EXIT INT TERM + trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; [[ -z "$CELLD_PID" ]] || kill_tree "$CELLD_PID"; stop_fleet; rm -f "$log_file"' EXIT INT TERM wait_listening "$log_file" "$server_pid" "game-demos mobpit" api_keys echo - log "open http://localhost:$ui_port/ (sign in with any username; Mob Pit server :$port, read model :$service_port; dev sign-in — local only)" + log "open http://localhost:$ui_port/ (sign in with any username; rooms on celld ${ROOMS_URLS}, services :$port, read model :$service_port; dev sign-in — local only)" echo # mobpit-service (the lifecycle's runtime) and the UI share these. BIND="127.0.0.1:$service_port" UI_PORT="$ui_port" \ @@ -388,7 +570,7 @@ run_sveltekit() { MOBPIT_UI_ORIGINS="http://localhost:$ui_port,http://127.0.0.1:$ui_port" \ MOBPIT_GRAPHQL_URL="http://127.0.0.1:$service_port/graphql" \ GAME_DEV_AUTH=1 AUTH_SECRET="${AUTH_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" \ - GAME_TICKET_SECRET="$secret" GAME_ZONES_URL="ws://127.0.0.1:$port" \ + GAME_TICKET_SECRET="$secret" GAME_ZONES_URL="$(echo "$ROOMS_URLS" | sed 's#http://#ws://#g')" \ "$CLI" dev "$SERVER" } @@ -431,12 +613,14 @@ smoke() { case "${1:-}" in smoke) smoke ;; gen) gen "${2:-}" ;; - sveltekit) run_sveltekit ;; + sveltekit) run_sveltekit "${2:-}" "${3:-3}" ;; list) printf '%s\n' "${DEMOS[@]}" sveltekit ;; "" | -h | --help | help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0" ;; *) if [[ " ${CLUSTER_DEMOS[*]} " == *" $1 "* ]]; then run_cluster "$1" + elif [[ "$1" == mobpit || "$1" == leaderboard ]]; then + run_mobpit "$1" "${2:-}" "${3:-3}" elif [[ " ${DEMOS[*]} " == *" $1 "* ]]; then run_demo "$1" else diff --git a/examples/game/scripts/round-robin.mjs b/examples/game/scripts/round-robin.mjs new file mode 100644 index 000000000..7adb49c6f --- /dev/null +++ b/examples/game/scripts/round-robin.mjs @@ -0,0 +1,36 @@ +#!/usr/bin/env node +/** + * A dev TCP load balancer in front of a local celld fleet (`run.sh mobpit + * --fleet`): each new connection goes to the next node, round robin, the + * way a production load balancer spreads clients over celld's public + * listeners. It decides nothing about placement: celld places a room on + * the node that first receives it and forwards every later socket to the + * owner, wherever it entered. + * + * node scripts/round-robin.mjs [,…] + * + * Prints `LISTENING ` when ready. + */ +import { connect, createServer } from 'node:net'; + +const [port, list] = process.argv.slice(2); +const targets = (list ?? '').split(',').filter(Boolean).map((t) => { + const [host, p] = t.replace(/^\w+:\/\//, '').split(':'); + return { host, port: Number(p) }; +}); +if (!port || targets.length === 0) { + console.error('usage: round-robin.mjs [,…]'); + process.exit(2); +} +let next = 0; +createServer((client) => { + const target = targets[next++ % targets.length]; + const upstream = connect(target.port, target.host); + client.pipe(upstream).pipe(client); + const close = () => { + client.destroy(); + upstream.destroy(); + }; + client.on('error', close); + upstream.on('error', close); +}).listen(Number(port), '127.0.0.1', () => console.log(`LISTENING ${port}`)); diff --git a/examples/game/server/Cargo.lock b/examples/game/server/Cargo.lock index 7689c67b2..54d7518d7 100644 --- a/examples/game/server/Cargo.lock +++ b/examples/game/server/Cargo.lock @@ -162,7 +162,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "strum", + "strum 0.27.2", "syn 2.0.119", "thiserror", ] @@ -302,7 +302,7 @@ dependencies = [ "hyper", "hyper-util", "itoa", - "matchit", + "matchit 0.8.4", "memchr", "mime", "percent-encoding", @@ -474,6 +474,17 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "js-sys", + "num-traits", + "wasm-bindgen", +] + [[package]] name = "clap" version = "4.6.7" @@ -832,6 +843,7 @@ dependencies = [ "tokio", "tonic-build", "uuid", + "worker", ] [[package]] @@ -844,6 +856,7 @@ dependencies = [ "distributed_game_macros", "futures-util", "hmac 0.12.1", + "js-sys", "reqwest", "serde", "serde_json", @@ -851,6 +864,9 @@ dependencies = [ "tokio", "tokio-tungstenite 0.30.0", "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "worker", ] [[package]] @@ -1119,6 +1135,7 @@ dependencies = [ "game_sim", "http-body-util", "mobpit_crawler", + "mobpit_rooms", "reqwest", "serde", "serde_json", @@ -1665,6 +1682,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + [[package]] name = "matchit" version = "0.8.4" @@ -1714,6 +1737,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "mobpit_rooms" +version = "0.1.0" +dependencies = [ + "distributed_game", + "game_sim", + "mobpit_crawler", + "serde", + "serde_json", +] + [[package]] name = "mobpit_service" version = "0.1.0" @@ -1910,6 +1944,26 @@ dependencies = [ "pest", ] +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2424,6 +2478,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -2826,7 +2891,16 @@ version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" dependencies = [ - "strum_macros", + "strum_macros 0.27.2", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros 0.28.0", ] [[package]] @@ -2841,6 +2915,18 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3395,6 +3481,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94ce9bdac782bbca70d6ac48a3ba18b873c848a706d6dc3bd9a03c1b96f04693" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.106" @@ -3542,6 +3641,65 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "worker" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4057bce8ec66c80b7e270d884c312e2a4ff60eb997fd02936656106c06a964e5" +dependencies = [ + "async-trait", + "bytes", + "chrono", + "futures-channel", + "futures-util", + "http", + "http-body", + "js-sys", + "matchit 0.7.3", + "pin-project", + "serde", + "serde-wasm-bindgen", + "serde_json", + "serde_urlencoded", + "strum 0.28.0", + "tokio", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "worker-macros", + "worker-sys", +] + +[[package]] +name = "worker-macros" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d7389670b55aab89760be149007aeff773cdad7b650d807f7fb556d04bb304" +dependencies = [ + "async-trait", + "proc-macro2", + "quote", + "strum 0.28.0", + "syn 3.0.9", + "wasm-bindgen", + "wasm-bindgen-macro-support", + "worker-sys", +] + +[[package]] +name = "worker-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a440092e7ae7c5feb5507fbdc6aee0cc241d132757c83e1729766a24cddff82" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "writeable" version = "0.6.4" diff --git a/examples/game/server/Cargo.toml b/examples/game/server/Cargo.toml index 61c192142..7ee5b13d5 100644 --- a/examples/game/server/Cargo.toml +++ b/examples/game/server/Cargo.toml @@ -2,7 +2,7 @@ # Own workspace (like tests/gateway-native) so demo-only dependencies never # reach the framework's lockfile; excluded from the root workspace. [workspace] -members = [".", "sim", "crawler", "service"] +members = [".", "sim", "crawler", "rooms", "service"] resolver = "2" # `distributed build|dev examples/game/server` owns the SvelteKit demo's @@ -29,6 +29,9 @@ path = "src/main.rs" game_sim = { path = "sim" } # The Crawler aggregate + RecordKill (shared with the read-model service). mobpit_crawler = { path = "crawler" } +# Mob Pit's room zone (hosted on celld; linked here for the client surface, +# tests and bots). +mobpit_rooms = { path = "rooms" } distributed_game = { path = "../../../distributed_game", features = ["net", "cell", "celld"] } # Mob Pit: sorted-set leaderboards (Redis optional at runtime), the SQLite # projection bus and the modeled projector of the crawler directory diff --git a/examples/game/server/rooms/Cargo.toml b/examples/game/server/rooms/Cargo.toml new file mode 100644 index 000000000..31212d99b --- /dev/null +++ b/examples/game/server/rooms/Cargo.toml @@ -0,0 +1,28 @@ +# Mob Pit's rooms: the zone (combat, mobs, doorways, hibernation) on the +# seeded room grid. Portable: the celld cells worker hosts every room as a +# Durable Object (`celld` feature, wasm32); `game_demos` links the same zone +# natively for the client surface, unit tests and bots. +[package] +name = "mobpit_rooms" +version = "0.1.0" +edition = "2021" +publish = false +description = "Mob Pit rooms: the zone and its celld object hooks (dev demo)" + +[lib] +path = "src/lib.rs" + +[features] +default = [] +# `CelldZone` for the room zone (wasm32): what the cells worker needs. +celld = ["distributed_game/celld-zone"] + +[dependencies] +distributed_game = { path = "../../../../distributed_game" } +game_sim = { path = "../sim" } +mobpit_crawler = { path = "../crawler" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +distributed_game = { path = "../../../../distributed_game", features = ["cell"] } diff --git a/examples/game/server/rooms/src/celld.rs b/examples/game/server/rooms/src/celld.rs new file mode 100644 index 000000000..16b7dacfc --- /dev/null +++ b/examples/game/server/rooms/src/celld.rs @@ -0,0 +1,51 @@ +//! Rooms as celld Durable Objects: the [`CelldZone`] hooks of the room zone. +//! The cells worker declares the class with +//! `distributed_game::celld_zone_object!(PitRoom, MobPit)`. + +use distributed_game::celld_zone::{CelldZone, LocalFuture, ObjectEnv, ObjectFactSink}; +use distributed_game::command_sink::FactRoute; +use distributed_game::HostConfig; +use mobpit_crawler::{RecordKillInput, CRAWLER_KIND, PRESENCE_KIND}; + +use crate::zone::{MobPit, PitMessage, RoomConfig}; +use crate::{DEFAULT_SEED, SEED_VAR}; + +impl CelldZone for MobPit { + fn object_config(zone_id: &str, env: &ObjectEnv) -> Result { + let seed = env + .var(SEED_VAR) + .and_then(|seed| seed.trim().parse().ok()) + .unwrap_or(DEFAULT_SEED); + RoomConfig::for_zone(zone_id, seed).ok_or_else(|| format!("no room `{zone_id}`")) + } + + fn host_config(_zone_id: &str, _env: &ObjectEnv) -> HostConfig { + HostConfig { + // Joined / lost / reconnected / left facts for the presence cells. + lifecycle_facts: true, + max_players: 32, + ..HostConfig::default() + } + } + + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink.route(FactRoute::by_principal::(CRAWLER_KIND)) + .lifecycle_route(PRESENCE_KIND) + } + + /// Read the player's Crawler cell (off the tick) for its level and XP. + fn after_join(env: &ObjectEnv, principal: &str) -> Option>> { + let env = env.clone(); + let principal = principal.to_string(); + Some(Box::pin(async move { + let cell = env.read_cell(CRAWLER_KIND, &principal).await.ok()?; + let state = &cell["state"]; + Some(PitMessage::Loaded { + principal, + xp: state["xp"].as_u64().unwrap_or(0), + level: state["level"].as_u64().unwrap_or(1) as u32, + kills: state["kills"].as_u64().unwrap_or(0) as u32, + }) + })) + } +} diff --git a/examples/game/server/rooms/src/lib.rs b/examples/game/server/rooms/src/lib.rs new file mode 100644 index 000000000..6dd33c179 --- /dev/null +++ b/examples/game/server/rooms/src/lib.rs @@ -0,0 +1,27 @@ +//! **Mob Pit rooms**: a near-infinite seeded grid of rooms (`pit..`) +//! joined by doorways, one zone per room ([`zone`]). +//! +//! On celld every room is a Durable Object (`celld` feature: [`celld`] +//! implements `distributed_game::celld_zone::CelldZone` for the zone; the +//! cells worker declares the class). celld decides where each room runs; +//! the rooms neither know nor care. A room that empties goes dormant, then +//! hibernates with its mobs; coming back restores them. Kills settle as +//! facts in the killer's Crawler cell from any room. +//! +//! The room contents (biome, danger, mobs) come from +//! `game_sim::mobpit::pit_room`, the same code the browser runs as +//! WebAssembly. + +#[cfg(all(feature = "celld", target_arch = "wasm32"))] +pub mod celld; +pub mod zone; + +pub use game_sim::mobpit::{ + parse_room, pit_room, room_zone, PitRoomContext, PitRoomLayout, DEFAULT_SEED, DOOR_HALF, +}; +pub use zone::*; + +/// The room every player starts in. +pub const ENTRANCE: &str = "pit.0.0"; +/// Env var / CLI name of the rooms' world seed. +pub const SEED_VAR: &str = "MOBPIT_SEED"; diff --git a/examples/game/server/rooms/src/zone.rs b/examples/game/server/rooms/src/zone.rs new file mode 100644 index 000000000..ccf53a9fc --- /dev/null +++ b/examples/game/server/rooms/src/zone.rs @@ -0,0 +1,1392 @@ +//! One Mob Pit room: authoritative melee combat at 30 Hz. +//! +//! Movement is the Arena's step through [`pit_step`], the declared predicted +//! step the client runs as WebAssembly; combat is server-only. Entities: +//! +//! | kind | ids | fields | +//! |---|---|---| +//! | 1 `player` | 1000 + player | x y vx vy dash cd (predicted) · name hp face swing level dead | +//! | 2 `mob` | 1..=12 | x y face tier hp state tele | +//! | 3 `pillar` | 100 + i | x y r (global) | +//! | 4 `pit` | 900 | pending committed backlog tickMs tickMaxMs kills (global) | +//! +//! The room's mobs come from its seeded layout ([`pit_room`]: tiers and +//! homes); the rest of a room is the Arena floor with a doorway in the +//! middle of each wall. Pushing through a doorway hands the player to the +//! neighbouring room ([`Ctx::handoff`], carrying where along the wall it +//! went through); the client follows the Handoff to the next room's zone, +//! wherever it runs. +//! +//! Mob state machine (deterministic, zone RNG only for wander targets): +//! `idle` (wander near home) → `chase` (living player within aggro radius or +//! hit by one) → `windup` (in reach: stand still, telegraph ring for 0.8 s) → +//! damage everyone inside the ring → `recover` (0.6 s) → `chase`; beyond the +//! leash or target dead → `return` home → `idle`. Dead mobs respawn after 4 s +//! with a new generation. +//! +//! A kill emits a typed fact **without awaiting storage**: the Crawler +//! cell command's own input, `RecordKillInput { mob, tier, name }`, keyed by +//! `m{mob}` and its generation and emitted for the killer (the host binds +//! the verified principal; the cell decides the XP). The settlement arrives +//! in [`Zone::on_fact_settled`] on a later tick and is pushed to the killer +//! as [`PitEvent::Saved`] + [`PitEvent::Profile`]. +//! +//! **Hibernation.** [`Zone::hibernate`] keeps every mob (position, HP, +//! state, generation, respawn timer) and the room's kill count; a room that +//! wakes up restores them ([`Zone::on_restore`]) and tells joining players +//! ([`PitEvent::Hello::restored`]). + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::time::Duration; + +use distributed_game::{ + schema, ConsumePolicy, Ctx, EmitError, Entities, Entity, EntityId, EntitySchema, Fact, + FactOutcome, FactSettlement, GameEvent, GameInput, GameRecord, GameSurface, LeaveReason, + ObserverId, PlayerId, Project, Replicated, View, Zone, +}; +use game_sim::arena::{self as movement, MoveState, PILLARS, PLAYER_RADIUS}; +use game_sim::mobpit::{ + arrival, doorway, parse_room, pit_room, pit_world, room_zone, PitRoomContext, PitRoomFn, +}; +use mobpit_crawler::{level_floor, KillReceipt, RecordKillInput}; +use serde::{Deserialize, Serialize}; + +pub use game_sim::mobpit::{pit_step, PitInput, PitStep}; + +/// Entity id of the stats entity (the zone's own HUD view). +pub const PIT_ENTITY: EntityId = EntityId(900); + +/// A player: the Arena's predicted [`MoveState`] plus server-owned combat +/// state. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0, of = Player)] +pub struct PlayerView { + /// Position x. + #[field_type(movement::POS)] + #[correct(ease = 150)] + #[from(state.x)] + pub x: f32, + /// Position y. + #[field_type(movement::POS)] + #[correct(ease = 150)] + #[from(state.y)] + pub y: f32, + /// Velocity x. + #[field_type(movement::VEL)] + #[correct(snap)] + #[from(state.vx)] + pub vx: f32, + /// Velocity y. + #[field_type(movement::VEL)] + #[correct(snap)] + #[from(state.vy)] + pub vy: f32, + /// Remaining dash frames. + #[correct(snap)] + #[from(state.dash)] + pub dash: u8, + /// Remaining dash cooldown frames. + #[correct(snap)] + #[from(state.cd)] + pub cd: u8, + /// Display name. + #[priority(0.2)] + #[correct(replace)] + #[from] + pub name: String, + /// Hit points. + #[correct(replace)] + pub hp: u8, + /// Facing (rad). + #[angle(bits = 8)] + #[correct(replace)] + #[from] + pub face: f32, + /// Swing animation frames left. + #[correct(replace)] + pub swing: u8, + /// Level (from the durable cell). + #[correct(replace)] + pub level: u16, + /// Waiting to respawn. + #[correct(replace)] + pub dead: bool, +} + +/// A mob (dead mobs are not replicated). +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "mob", id = 2, of = Mob)] +pub struct MobView { + /// Position x. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + #[from] + pub x: f32, + /// Position y. + #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] + #[from] + pub y: f32, + /// Facing (rad). + #[angle(bits = 8)] + #[from] + pub face: f32, + /// 1 grunt · 2 brute · 3 elite. + #[from] + pub tier: u8, + /// HP percent. + pub hp: u8, + /// 0 idle · 1 chase · 2 windup · 3 recover · 4 return. + pub state: u8, + /// Telegraph progress 0..=255 during a windup. + pub tele: u8, +} + +/// A pillar of the floor (visible everywhere). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Pillar { + /// Entity id (100 + index). + pub id: EntityId, + /// Centre x. + pub x: f32, + /// Centre y. + pub y: f32, + /// Radius. + pub r: f32, +} + +impl Pillar { + /// Every pillar of the floor. + pub fn all() -> Vec { + PILLARS + .iter() + .enumerate() + .map(|(i, &(x, y, r))| Pillar { + id: EntityId(100 + i as u32), + x, + y, + r, + }) + .collect() + } +} + +impl Entity for Pillar { + fn entity_id(&self) -> EntityId { + self.id + } +} + +/// A pillar, projected as is. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pillar", id = 3, global, of = Pillar)] +pub struct PillarView { + /// Centre x. + #[from] + pub x: f32, + /// Centre y. + #[from] + pub y: f32, + /// Radius. + #[from] + pub r: f32, +} + +/// Room numbers for the HUD (global), projected from the zone itself. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "pit", id = 4, global, of = MobPit)] +pub struct PitView { + /// Facts emitted and not settled. + pub pending: u16, + /// Settlements received. + pub committed: u32, + /// Facts waiting for backpressure to clear. + pub backlog: u16, + /// Tick interval EMA (ms). + pub tick_ms: f32, + /// Longest tick interval of the last 30 ticks (ms). + pub tick_max_ms: f32, + /// Mobs killed in this room (kept across hibernation). + pub kills: u32, +} + +/// A player's durable progress (from the cell on join, after each settlement). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Profile { + /// Total XP. + pub xp: u64, + /// Level. + pub level: u32, + /// Kills. + pub kills: u32, + /// First XP of the level. + pub level_xp: u64, + /// First XP of the next level. + pub next_level_xp: u64, + /// `"cell"` (loaded on join) or `"settled"` (after a kill committed). + pub source: String, +} + +/// Mob Pit's events. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum PitEvent { + /// To a joining player. + #[game_event(id = 1)] + Hello { + /// Own entity id. + entity: u32, + /// Floor half extent (m). + half: f32, + /// Melee reach (m). + attack_range: f32, + /// Cosine of the half cone angle. + attack_arc_cos: f32, + /// Room x. + room_x: i32, + /// Room y. + room_y: i32, + /// World seed of the rooms. + seed: u32, + /// This activation of the room restored a hibernated snapshot. + restored: bool, + /// Mobs killed in this room so far. + room_kills: u32, + }, + /// Durable progress. + #[game_event(id = 2)] + Profile(Profile), + /// Broadcast the tick a mob dies (the fact is only queued). + #[game_event(id = 3)] + Kill { + /// Fact key. + key: String, + /// Mob entity id. + mob: u32, + /// Mob tier. + tier: u8, + /// Where it died. + x: f32, + /// Where it died. + y: f32, + /// Killer entity id. + killer: u32, + /// Killer display name. + killer_name: String, + }, + /// To the killer when its fact settled. + #[game_event(id = 4)] + Saved { + /// Fact key. + key: String, + /// Committed. + ok: bool, + /// The cell recognised the key (replayed receipt). + replayed: bool, + /// XP credited by this kill (decided by the cell). + xp: u32, + /// Total XP after it. + total_xp: u64, + /// Kills after it. + kills: u32, + /// Level after it. + level: u32, + /// Time from emit to settlement (ms). + waited_ms: u32, + /// Where the mob died. + x: f32, + /// Where the mob died. + y: f32, + /// Failure, if any. + error: Option, + /// Commit attempts (failures). + attempts: u32, + }, + /// To a player that died. + #[game_event(id = 6)] + Died { + /// Respawn delay (ms). + respawn_ms: u32, + }, +} + +/// What services deliver into a room. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum PitMessage { + /// A player's durable progress, read from its Crawler cell after it + /// joined (off the tick). + #[game_event(id = 1)] + Loaded { + /// The player's verified principal. + principal: String, + /// Total XP. + xp: u64, + /// Level. + level: u32, + /// Kills. + kills: u32, + }, +} + +/// Mob Pit's client surface (also used by the leaderboard page). +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("mobpit") + .events::() + .predict::() + .pure::() + .constant("pit_rules", &pit_rules()) + .constant("pit_world", &pit_world()) +} + +/// Input bit: attack (bit 0 is the Arena's dash). +pub const BUTTON_ATTACK: u8 = PitInput::ATTACK; +/// Melee reach (m, from the player's centre to the mob's edge). +pub const ATTACK_RANGE: f32 = 2.2; +/// Cosine of the half cone angle (60°). +pub const ATTACK_ARC_COS: f32 = 0.5; +/// Damage per swing. +pub const ATTACK_DAMAGE: i32 = 10; +/// Swing cooldown (ticks). +pub const SWING_COOLDOWN: u8 = 13; +/// Swing animation length (ticks). +const SWING_FRAMES: u8 = 6; +/// Player max HP. +pub const PLAYER_HP: i32 = 100; +const MAX_CREDITS: u8 = 4; +const VIEW_RADIUS: f32 = 40.0; +const AGGRO: f32 = 7.0; +const LEASH: f32 = 15.0; +const WINDUP_TICKS: u16 = 24; +const RECOVER_TICKS: u16 = 18; +const RESPAWN_TICKS: u64 = 120; +const PLAYER_RESPAWN_TICKS: u64 = 90; + +/// Mob tier stats: (max hp, speed m/s, damage, radius, telegraph radius). +fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { + match tier { + 3 => (100, 3.3, 24, 0.8, 2.6), + 2 => (60, 2.4, 16, 0.7, 2.2), + _ => (30, 3.0, 9, 0.5, 1.8), + } +} + +/// Mob tiers (1..=3). +pub const TIERS: [u8; 3] = [1, 2, 3]; +/// Names of the `mob` kind's `state` values, by value. +pub const MOB_STATES: [&str; 6] = ["idle", "chase", "windup", "recover", "return", "dead"]; + +/// What the page draws of a mob tier (from [`tier_stats`]). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct MobTier { + /// Tier (the `mob` kind's `tier`). + pub tier: u8, + /// Body radius (m). + pub radius: f32, + /// Telegraph radius (m). + pub tele: f32, +} + +/// Mob Pit rules the client draws with (generated `PIT_RULES`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct PitRules { + /// Every tier. + pub tiers: Vec, + /// `state` names by value. + pub states: Vec, + /// Melee reach (m, from the player's centre to the mob's edge). + pub attack_range: f32, + /// Half angle of the swing cone (radians). + pub attack_half_angle: f32, + /// Swing animation length (ticks; the player's `swing` counts down from it). + pub swing_frames: u8, +} + +/// The `PIT_RULES` constant. +pub fn pit_rules() -> PitRules { + PitRules { + tiers: TIERS + .iter() + .map(|&tier| { + let (_, _, _, radius, tele) = tier_stats(tier); + MobTier { tier, radius, tele } + }) + .collect(), + states: MOB_STATES.map(String::from).to_vec(), + attack_range: ATTACK_RANGE, + attack_half_angle: ATTACK_ARC_COS.acos(), + swing_frames: SWING_FRAMES, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum MobState { + Idle = 0, + Chase = 1, + Windup = 2, + Recover = 3, + Return = 4, + Dead = 5, +} + +struct Mob { + id: EntityId, + tier: u8, + home: (f32, f32), + x: f32, + y: f32, + face: f32, + hp: i32, + state: MobState, + timer: u16, + target: Option, + generation: u32, + respawn_at: u64, + wander: (f32, f32), +} + +struct Player { + id: EntityId, + principal: String, + name: String, + state: MoveState, + credits: u8, + hp: i32, + face: f32, + swing_cd: u8, + swing_anim: u8, + dead_until: Option, + level: u32, + regen: u8, + /// Stick of the last input (doorways need the push direction). + stick: (i8, i8), +} + +struct PendingKill { + principal: String, + x: f32, + y: f32, + emitted: Duration, +} + +/// Which room. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RoomConfig { + /// Room coordinates. + pub room: (i32, i32), + /// World seed. + pub seed: u32, +} + +impl RoomConfig { + /// The room of zone `pit..` in world `seed`. + pub fn for_zone(zone_id: &str, seed: u32) -> Option { + parse_room(zone_id).map(|room| Self { room, seed }) + } +} + +/// What a room keeps while it hibernates. +#[derive(Debug, Default, Serialize, Deserialize)] +struct Snapshot { + kills: u32, + mobs: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +struct SavedMob { + id: u32, + x: f32, + y: f32, + face: f32, + hp: i32, + dead: bool, + generation: u32, + /// Ticks until a dead mob respawns. + respawn_in: u64, +} + +/// The Mob Pit room zone. +pub struct MobPit { + room: RoomConfig, + players: BTreeMap, + mobs: Vec, + pillars: Vec, + pending: HashMap, + /// Facts refused by backpressure, retried each tick (oldest first). + backlog: VecDeque<(PlayerId, Fact, f32, f32)>, + last_tick: Option, + tick_ms: f32, + tick_max_ms: f32, + tick_max_window: f32, + window_ticks: u32, + committed: u32, + kills: u32, + restored: bool, + /// The last tick run (hibernation stores timers relative to it). + tick: u64, +} + +fn spawn_point(player: PlayerId) -> (f32, f32) { + const SPOTS: [(f32, f32); 6] = [ + (-4.5, -4.5), + (4.5, -4.5), + (4.5, 4.5), + (-4.5, 4.5), + (0.0, -5.5), + (0.0, 5.5), + ]; + SPOTS[player.0 as usize % SPOTS.len()] +} + +fn push_out_of_pillars(x: &mut f32, y: &mut f32, radius: f32) { + for (px, py, pr) in PILLARS { + let (ox, oy) = (*x - px, *y - py); + let d2 = ox * ox + oy * oy; + let min = radius + pr; + if d2 < min * min { + let d = d2.sqrt().max(1e-4); + *x = px + ox / d * min; + *y = py + oy / d * min; + } + } + let lim = movement::HALF - radius; + *x = x.clamp(-lim, lim); + *y = y.clamp(-lim, lim); +} + +fn step_toward(x: &mut f32, y: &mut f32, tx: f32, ty: f32, stride: f32) -> f32 { + let (dx, dy) = (tx - *x, ty - *y); + let d = (dx * dx + dy * dy).sqrt(); + if d > 1e-4 { + let s = stride.min(d); + *x += dx / d * s; + *y += dy / d * s; + } + dy.atan2(dx) +} + +fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { + ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() +} + +/// Carried through a doorway: the room offset it came from and where along +/// the wall it went through. +fn encode_carried(from: (i32, i32), along: f32) -> Vec { + let mut out = vec![from.0 as i8 as u8, from.1 as i8 as u8]; + out.extend_from_slice(&along.to_le_bytes()); + out +} + +fn decode_carried(bytes: &[u8]) -> Option<((i32, i32), f32)> { + let [dx, dy, a, b, c, d] = bytes else { + return None; + }; + Some(( + (i32::from(*dx as i8), i32::from(*dy as i8)), + f32::from_le_bytes([*a, *b, *c, *d]), + )) +} + +impl MobPit { + /// The room this zone is. + pub fn room(&self) -> RoomConfig { + self.room + } + + fn profile_event(xp: u64, level: u32, kills: u32, source: &str) -> PitEvent { + PitEvent::Profile(Profile { + xp, + level, + kills, + level_xp: level_floor(level), + next_level_xp: level_floor(level + 1), + source: source.into(), + }) + } + + fn player_by_principal(&self, principal: &str) -> Option { + self.players + .iter() + .find(|(_, p)| p.principal == principal) + .map(|(id, _)| *id) + } + + fn emit_kill(&mut self, ctx: &mut Ctx<'_, Self>, killer: PlayerId, mob: usize) { + let m = &self.mobs[mob]; + let (x, y, tier, id, generation) = (m.x, m.y, m.tier, m.id.get(), m.generation); + let Some(player) = self.players.get(&killer) else { + return; + }; + self.kills += 1; + // The cell command's own input: what died, never who or how much XP. + let input = RecordKillInput { + mob: format!("{}/m{id}", ctx.zone_id()), + tier, + name: player.name.clone(), + }; + let Ok(fact) = ctx.fact_with_key(&input, &[&format_args!("m{id}"), &generation]) else { + return; + }; + let key = fact.key().to_string(); + ctx.broadcast(&PitEvent::Kill { + key, + mob: id, + tier, + x, + y, + killer: player.id.get(), + killer_name: player.name.clone(), + }); + self.backlog.push_back((killer, fact, x, y)); + self.flush_backlog(ctx); + } + + /// Hand queued facts to the host; never blocks. Backpressure keeps the + /// rest for the next tick. + fn flush_backlog(&mut self, ctx: &mut Ctx<'_, Self>) { + while let Some((player, fact, x, y)) = self.backlog.pop_front() { + let key = fact.key().to_string(); + match ctx.emit_fact_for(player, fact.clone()) { + Ok(()) => { + let principal = self + .players + .get(&player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + self.pending.insert( + key, + PendingKill { + principal, + x, + y, + emitted: ctx.now(), + }, + ); + } + Err(EmitError::Backpressure) => { + self.backlog.push_front((player, fact, x, y)); + return; + } + // The killer left before the fact could be queued, or the key + // is already in flight: nothing durable to do. + Err(_) => {} + } + } + } + + fn step_players(&mut self, ctx: &mut Ctx<'_, Self>) -> Vec<(PlayerId, f32, f32, f32)> { + let tick = ctx.tick(); + let mut swings = Vec::new(); + for (id, p) in &mut self.players { + p.credits = (p.credits + 1).min(MAX_CREDITS); + p.swing_cd = p.swing_cd.saturating_sub(1); + p.swing_anim = p.swing_anim.saturating_sub(1); + if let Some(until) = p.dead_until { + // Dead: inputs are consumed but ignored. + let _ = ctx.take_inputs(*id, ConsumePolicy::Drain); + if tick >= until { + let (x, y) = spawn_point(*id); + p.state = MoveState { + x, + y, + ..MoveState::default() + }; + p.hp = PLAYER_HP; + p.dead_until = None; + } + continue; + } + while p.credits > 0 { + let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { + break; + }; + let input = input.input; + // The declared predicted step: what the client runs as WASM. + p.state = pit_step(&p.state, &input, &(), movement::DT); + p.credits -= 1; + p.stick = (input.mx, input.my); + let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); + if sx * sx + sy * sy > 20.0 * 20.0 { + p.face = sy.atan2(sx); + } + if input.attack() && p.swing_cd == 0 { + p.swing_cd = SWING_COOLDOWN; + p.swing_anim = SWING_FRAMES; + swings.push((*id, p.state.x, p.state.y, p.face)); + } + } + p.regen = p.regen.wrapping_add(1); + if p.regen % 15 == 0 && p.hp < PLAYER_HP { + p.hp += 1; + } + ctx.set_view(*id, View::new(p.state.x, p.state.y, VIEW_RADIUS)); + } + swings + } + + /// Players pushing through a doorway move to the neighbouring room. + fn walk_through_doorways(&mut self, ctx: &mut Ctx<'_, Self>) { + let (rx, ry) = self.room.room; + let leaving: Vec<(PlayerId, (i32, i32), f32)> = self + .players + .iter() + .filter(|(_, p)| p.dead_until.is_none()) + .filter_map(|(id, p)| { + let step = doorway(p.state.x, p.state.y, p.stick.0, p.stick.1)?; + let along = if step.0 != 0 { p.state.y } else { p.state.x }; + Some((*id, step, along)) + }) + .collect(); + for (player, (dx, dy), along) in leaving { + let target = room_zone((rx + dx, ry + dy)); + if parse_room(&target).is_none() { + continue; + } + // The neighbour sees where it came from (the opposite side). + let carried = encode_carried((-dx, -dy), along); + let _ = ctx.handoff(player, &target, carried); + } + } + + fn resolve_swings(&mut self, ctx: &mut Ctx<'_, Self>, swings: Vec<(PlayerId, f32, f32, f32)>) { + for (player, x, y, face) in swings { + let (fx, fy) = (face.cos(), face.sin()); + for i in 0..self.mobs.len() { + let m = &mut self.mobs[i]; + if m.state == MobState::Dead { + continue; + } + let (_, _, _, radius, _) = tier_stats(m.tier); + let (dx, dy) = (m.x - x, m.y - y); + let d = (dx * dx + dy * dy).sqrt(); + if d > ATTACK_RANGE + radius { + continue; + } + let cos = if d < 1e-3 { + 1.0 + } else { + (dx * fx + dy * fy) / d + }; + if cos < ATTACK_ARC_COS && d > radius + PLAYER_RADIUS { + continue; + } + m.hp -= ATTACK_DAMAGE; + if matches!(m.state, MobState::Idle | MobState::Return) { + m.state = MobState::Chase; + m.target = Some(player); + } + if m.hp <= 0 { + m.hp = 0; + m.state = MobState::Dead; + m.respawn_at = ctx.tick() + RESPAWN_TICKS; + m.target = None; + self.emit_kill(ctx, player, i); + } + } + } + } + + fn step_mobs(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + let tick = ctx.tick(); + let living: Vec<(PlayerId, f32, f32)> = self + .players + .iter() + .filter(|(_, p)| p.dead_until.is_none()) + .map(|(id, p)| (*id, p.state.x, p.state.y)) + .collect(); + let mut hits: Vec<(PlayerId, i32)> = Vec::new(); + for i in 0..self.mobs.len() { + let (max_hp, speed, damage, radius, tele) = tier_stats(self.mobs[i].tier); + let target_pos = |t: Option| { + t.and_then(|t| living.iter().find(|(id, _, _)| *id == t)) + .map(|(_, x, y)| (*x, *y)) + }; + let m = &mut self.mobs[i]; + match m.state { + MobState::Dead => { + if tick >= m.respawn_at { + m.generation += 1; + m.hp = max_hp; + (m.x, m.y) = m.home; + m.state = MobState::Idle; + } + continue; + } + MobState::Idle => { + let nearest = living + .iter() + .map(|(id, x, y)| (*id, dist((m.x, m.y), (*x, *y)))) + .filter(|(_, d)| *d < AGGRO) + .min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((id, _)) = nearest { + m.state = MobState::Chase; + m.target = Some(id); + } else if dist((m.x, m.y), m.wander) < 0.3 { + let a = ctx.rng().next_f32() * std::f32::consts::TAU; + let r = ctx.rng().next_f32() * 2.5; + let m = &mut self.mobs[i]; + m.wander = (m.home.0 + r * a.cos(), m.home.1 + r * a.sin()); + } else { + let (wx, wy) = m.wander; + m.face = step_toward(&mut m.x, &mut m.y, wx, wy, 1.0 * dt); + } + } + MobState::Chase => match target_pos(m.target) { + Some((tx, ty)) if dist(m.home, (m.x, m.y)) < LEASH => { + let reach = radius + PLAYER_RADIUS + 0.6; + if dist((m.x, m.y), (tx, ty)) <= reach { + m.state = MobState::Windup; + m.timer = WINDUP_TICKS; + m.face = (ty - m.y).atan2(tx - m.x); + } else { + m.face = step_toward(&mut m.x, &mut m.y, tx, ty, speed * dt); + } + } + _ => { + m.state = MobState::Return; + m.target = None; + } + }, + MobState::Windup => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + for (id, x, y) in &living { + if dist((m.x, m.y), (*x, *y)) <= tele + PLAYER_RADIUS * 0.5 { + hits.push((*id, damage)); + } + } + m.state = MobState::Recover; + m.timer = RECOVER_TICKS; + } + } + MobState::Recover => { + m.timer = m.timer.saturating_sub(1); + if m.timer == 0 { + m.state = MobState::Chase; + } + } + MobState::Return => { + let (hx, hy) = m.home; + m.face = step_toward(&mut m.x, &mut m.y, hx, hy, speed * 1.3 * dt); + m.hp = (m.hp + 1).min(max_hp); + if dist((m.x, m.y), m.home) < 0.3 { + m.state = MobState::Idle; + m.wander = m.home; + } + } + } + let m = &mut self.mobs[i]; + push_out_of_pillars(&mut m.x, &mut m.y, radius); + } + // Light separation so a pack does not stack on one spot. + for i in 0..self.mobs.len() { + for j in (i + 1)..self.mobs.len() { + let (a, b) = (&self.mobs[i], &self.mobs[j]); + if a.state == MobState::Dead || b.state == MobState::Dead { + continue; + } + let min = tier_stats(a.tier).3 + tier_stats(b.tier).3; + let (dx, dy) = (b.x - a.x, b.y - a.y); + let d = (dx * dx + dy * dy).sqrt(); + if d < min && d > 1e-4 { + let push = (min - d) * 0.5; + let (nx, ny) = (dx / d * push, dy / d * push); + self.mobs[i].x -= nx; + self.mobs[i].y -= ny; + self.mobs[j].x += nx; + self.mobs[j].y += ny; + } + } + } + for (id, damage) in hits { + let Some(p) = self.players.get_mut(&id) else { + continue; + }; + if p.dead_until.is_some() { + continue; + } + p.hp -= damage; + if p.hp <= 0 { + p.hp = 0; + p.state.vx = 0.0; + p.state.vy = 0.0; + p.dead_until = Some(tick + PLAYER_RESPAWN_TICKS); + for m in &mut self.mobs { + if m.target == Some(id) { + m.target = None; + } + } + ctx.send( + id, + &PitEvent::Died { + respawn_ms: (PLAYER_RESPAWN_TICKS * 1000 / 30) as u32, + }, + ); + } + } + } + + fn measure_tick(&mut self, now: Duration) { + if let Some(last) = self.last_tick { + let ms = now.saturating_sub(last).as_secs_f32() * 1000.0; + self.tick_ms = if self.tick_ms == 0.0 { + ms + } else { + self.tick_ms * 0.9 + ms * 0.1 + }; + self.tick_max_window = self.tick_max_window.max(ms); + self.window_ticks += 1; + if self.window_ticks >= 30 { + self.tick_max_ms = self.tick_max_window; + self.tick_max_window = 0.0; + self.window_ticks = 0; + } + } + self.last_tick = Some(now); + } + + /// Admit `player` at `(x, y)` and greet it. + fn admit(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId, (x, y): (f32, f32)) { + let (principal, name) = ctx + .player(player) + .map(|p| { + ( + p.principal.clone(), + p.name.clone().unwrap_or_else(|| p.principal.clone()), + ) + }) + .unwrap_or_default(); + let entity = EntityId(1000 + player.0); + self.players.insert( + player, + Player { + id: entity, + principal, + name, + state: MoveState { + x, + y, + ..MoveState::default() + }, + credits: MAX_CREDITS, + hp: PLAYER_HP, + face: 0.0, + swing_cd: 0, + swing_anim: 0, + dead_until: None, + level: 1, + regen: 0, + stick: (0, 0), + }, + ); + ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); + ctx.send( + player, + &PitEvent::Hello { + entity: entity.get(), + half: movement::HALF, + attack_range: ATTACK_RANGE, + attack_arc_cos: ATTACK_ARC_COS, + room_x: self.room.room.0, + room_y: self.room.room.1, + seed: self.room.seed, + restored: self.restored, + room_kills: self.kills, + }, + ); + } +} + +impl Zone for MobPit { + type Config = RoomConfig; + type Input = PitInput; + type Timer = (); + type Message = PitMessage; + + fn schema() -> EntitySchema { + schema![PlayerView, MobView, PillarView, PitView] + } + + fn entities() -> Entities { + Entities::new() + .each(|z: &Self| &z.players) + .each(|z: &Self| &z.mobs) + .each(|z: &Self| &z.pillars) + .one(|z: &Self| z) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, room: RoomConfig) -> Self { + let layout = pit_room(&PitRoomContext { + seed: room.seed, + x: room.room.0, + y: room.room.1, + }); + let mobs = layout + .mobs + .iter() + .enumerate() + .map(|(i, slot)| { + let home = (slot.x, slot.y); + Mob { + id: EntityId(i as u32 + 1), + tier: slot.tier, + home, + x: home.0, + y: home.1, + face: 0.0, + hp: tier_stats(slot.tier).0, + state: MobState::Idle, + timer: 0, + target: None, + generation: 0, + respawn_at: 0, + wander: home, + } + }) + .collect(); + Self { + room, + players: BTreeMap::new(), + mobs, + pillars: Pillar::all(), + pending: HashMap::new(), + backlog: VecDeque::new(), + last_tick: None, + tick_ms: 0.0, + tick_max_ms: 0.0, + tick_max_window: 0.0, + window_ticks: 0, + committed: 0, + kills: 0, + restored: false, + tick: 0, + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.admit(ctx, player, spawn_point(player)); + } + + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + _from_zone: &str, + carried: Vec, + ) { + let at = decode_carried(&carried) + .map(|(from, along)| arrival(from, along)) + .unwrap_or_else(|| spawn_point(player)); + // Still here inside its reconnect grace (a doorway bounce): replace. + self.players.remove(&player); + self.admit(ctx, player, at); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.players.remove(&player); + for m in &mut self.mobs { + if m.target == Some(player) { + m.target = None; + } + } + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + PitInput::from_payload(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.tick = ctx.tick(); + self.measure_tick(ctx.now()); + let swings = self.step_players(ctx); + self.resolve_swings(ctx, swings); + self.step_mobs(ctx); + self.walk_through_doorways(ctx); + self.flush_backlog(ctx); + } + + fn on_message(&mut self, ctx: &mut Ctx<'_, Self>, message: PitMessage) { + match message { + PitMessage::Loaded { + principal, + xp, + level, + kills, + } => { + let Some(id) = self.player_by_principal(&principal) else { + return; + }; + if let Some(p) = self.players.get_mut(&id) { + p.level = level.max(1); + } + ctx.send(id, &Self::profile_event(xp, level.max(1), kills, "cell")); + } + } + } + + fn on_fact_settled(&mut self, ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + // The host's own lifecycle facts (presence) are not kills. + if distributed_game::lifecycle::LIFECYCLE_COMMANDS.contains(&settlement.command.as_str()) { + return; + } + let pending = self.pending.remove(&settlement.key); + let now = ctx.now(); + let (principal, x, y, waited_ms) = match &pending { + Some(p) => ( + p.principal.clone(), + p.x, + p.y, + now.saturating_sub(p.emitted) + .as_millis() + .min(u128::from(u32::MAX)) as u32, + ), + None => (String::new(), 0.0, 0.0, 0), + }; + let player = self.player_by_principal(&principal); + match settlement.outcome { + FactOutcome::Committed(receipt) => { + self.committed += 1; + let Ok(kill) = receipt.payload_as::() else { + return; + }; + let Some(player) = player else { return }; + if let Some(p) = self.players.get_mut(&player) { + p.level = kill.level; + } + ctx.send( + player, + &PitEvent::Saved { + key: settlement.key, + ok: true, + replayed: receipt.replayed, + xp: kill.xp, + total_xp: kill.total_xp, + kills: kill.kills, + level: kill.level, + waited_ms, + x, + y, + error: None, + attempts: 0, + }, + ); + ctx.send( + player, + &Self::profile_event(kill.total_xp, kill.level, kill.kills, "settled"), + ); + } + FactOutcome::Failed { error, attempts } => { + if let Some(player) = player { + ctx.send( + player, + &PitEvent::Saved { + key: settlement.key, + ok: false, + replayed: false, + xp: 0, + total_xp: 0, + kills: 0, + level: 0, + waited_ms, + x, + y, + error: Some(format!("{error:?}")), + attempts, + }, + ); + } + } + } + } + + fn has_pending_work(&self) -> bool { + !self.backlog.is_empty() + } + + fn hibernate(&self) -> Option> { + // Called between ticks; timers are relative to the last tick. + let tick = self.tick; + let snapshot = Snapshot { + kills: self.kills, + mobs: self + .mobs + .iter() + .map(|m| SavedMob { + id: m.id.get(), + x: m.x, + y: m.y, + face: m.face, + hp: m.hp, + dead: m.state == MobState::Dead, + generation: m.generation, + respawn_in: m.respawn_at.saturating_sub(tick), + }) + .collect(), + }; + serde_json::to_vec(&snapshot).ok() + } + + fn on_restore(&mut self, ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { + let Ok(snapshot) = serde_json::from_slice::(state) else { + return; + }; + self.kills = snapshot.kills; + self.restored = true; + let tick = ctx.tick(); + for saved in snapshot.mobs { + let Some(m) = self.mobs.iter_mut().find(|m| m.id.get() == saved.id) else { + continue; + }; + m.generation = saved.generation; + m.face = saved.face; + if saved.dead { + m.state = MobState::Dead; + m.hp = 0; + m.respawn_at = tick + saved.respawn_in; + } else { + // Back home-side where it stood, calm again. + m.x = saved.x; + m.y = saved.y; + m.hp = saved.hp.clamp(1, tier_stats(m.tier).0); + m.state = MobState::Return; + } + } + } +} + +impl Entity for Player { + fn entity_id(&self) -> EntityId { + self.id + } +} + +impl Project for Player { + fn view(&self) -> Option { + Some(PlayerView::project( + self, + PlayerViewRest { + hp: self.hp.clamp(0, 255) as u8, + swing: self.swing_anim, + level: self.level.min(u32::from(u16::MAX)) as u16, + dead: self.dead_until.is_some(), + }, + )) + } +} + +impl Entity for Mob { + fn entity_id(&self) -> EntityId { + self.id + } +} + +impl Project for Mob { + fn view(&self) -> Option { + if self.state == MobState::Dead { + return None; + } + let max_hp = tier_stats(self.tier).0; + let tele = if self.state == MobState::Windup { + 255 - (u32::from(self.timer) * 255 / u32::from(WINDUP_TICKS)) + } else { + 0 + }; + Some(MobView::project( + self, + MobViewRest { + hp: (self.hp.max(0) * 100 / max_hp) as u8, + state: self.state as u8, + tele: tele as u8, + }, + )) + } +} + +impl Entity for MobPit { + fn entity_id(&self) -> EntityId { + PIT_ENTITY + } +} + +impl Project for MobPit { + fn view(&self) -> Option { + let clamp16 = |n: usize| n.min(65_535) as u16; + Some(PitView::project( + self, + PitViewRest { + pending: clamp16(self.pending.len()), + committed: self.committed, + backlog: clamp16(self.backlog.len()), + tick_ms: self.tick_ms, + tick_max_ms: self.tick_max_ms, + kills: self.kills, + }, + )) + } +} + +/// Room numbers for tests and tooling. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct PitStats { + /// Facts emitted and not yet settled (incl. backpressure backlog). + pub pending: usize, + /// Tick interval EMA (ms). + pub tick_ms: f32, + /// Longest tick interval of the last 30 ticks (ms). + pub tick_max_ms: f32, + /// Settlements received. + pub committed: u32, + /// Living mobs. + pub mobs_alive: usize, + /// Players. + pub players: usize, + /// Mobs killed in the room. + pub kills: u32, + /// The room came back from a snapshot. + pub restored: bool, +} + +impl MobPit { + /// Current numbers. + pub fn stats(&self) -> PitStats { + PitStats { + pending: self.pending.len() + self.backlog.len(), + tick_ms: self.tick_ms, + tick_max_ms: self.tick_max_ms, + committed: self.committed, + mobs_alive: self + .mobs + .iter() + .filter(|m| m.state != MobState::Dead) + .count(), + players: self.players.len(), + kills: self.kills, + restored: self.restored, + } + } + + /// Mob positions `(id, x, y, alive)` (tests and bots). + pub fn mob_positions(&self) -> Vec<(u32, f32, f32, bool)> { + self.mobs + .iter() + .map(|m| (m.id.get(), m.x, m.y, m.state != MobState::Dead)) + .collect() + } + + /// A player's position (tests and bots). + pub fn player_position(&self, player: PlayerId) -> Option<(f32, f32)> { + self.players.get(&player).map(|p| (p.state.x, p.state.y)) + } +} + +/// Bot payload: the direction as a move plus attack always held. +pub fn encode_bot_input(dir: [f32; 2]) -> Vec { + let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; + PitInput { + mx: axis(dir[0]), + my: axis(dir[1]), + buttons: PitInput::ATTACK, + } + .to_payload() +} diff --git a/examples/game/server/rooms/tests/rooms.rs b/examples/game/server/rooms/tests/rooms.rs new file mode 100644 index 000000000..474fdf450 --- /dev/null +++ b/examples/game/server/rooms/tests/rooms.rs @@ -0,0 +1,164 @@ +//! The room zone on the reference host (`ZoneHost`, manual clock): what a +//! celld room object runs, without celld. + +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::protocol::ServerMessage; +use distributed_game::{ + ClientId, FactQueue, GameEvent, HostConfig, ManualClock, Outbound, Role, TicketClaims, Viewer, + ZoneHost, +}; +use mobpit_rooms::{encode_bot_input, MobPit, PitEvent, PitInput, RoomConfig, DEFAULT_SEED}; + +fn host(zone: &str, clock: &ManualClock) -> ZoneHost { + let (facts, _script) = FactQueue::scripted(64); + ZoneHost::::new( + zone, + HostConfig { + boot_epoch: 7, + ..HostConfig::default() + }, + Arc::new(clock.clone()), + RoomConfig::for_zone(zone, DEFAULT_SEED).expect("room"), + ) + .with_facts(facts) + .with_transfer_issuer(|request| Some(format!("transfer:{}", request.target_zone))) +} + +fn join(host: &mut ZoneHost, who: &str) -> (ClientId, distributed_game::PlayerId) { + let claims = TicketClaims::new(who, host.zone_id(), u64::MAX, who, Role::Player).with_name(who); + let joined = host.join(&claims, 0, "").expect("join"); + let Viewer::Player(player) = joined.viewer else { + panic!("player") + }; + (joined.client, player) +} + +fn tick(host: &mut ZoneHost, clock: &ManualClock) -> Vec { + clock.advance(Duration::from_micros(33_334)); + host.advance(); + host.drain_outbound() +} + +fn messages(out: &[Outbound]) -> Vec { + out.iter() + .filter_map(|o| match o { + Outbound::Frame { frame, .. } => ServerMessage::decode(frame, &()).ok(), + _ => None, + }) + .collect() +} + +fn hellos(out: &[Outbound]) -> Vec { + messages(out) + .into_iter() + .filter_map(|m| match m { + ServerMessage::Event { + type_id, payload, .. + } => PitEvent::decode_event(type_id, &payload).ok().flatten(), + _ => None, + }) + .filter(|e| matches!(e, PitEvent::Hello { .. })) + .collect() +} + +#[test] +fn a_room_greets_with_its_coordinates_and_hands_off_through_doorways() { + let clock = ManualClock::new(); + let mut room = host("pit.0.0", &clock); + let (client, player) = join(&mut room, "ana"); + let out = tick(&mut room, &clock); + let hello = hellos(&out); + assert!(matches!( + hello.first(), + Some(PitEvent::Hello { + room_x: 0, + room_y: 0, + restored: false, + .. + }) + )); + // Walk to the east doorway (beside the pillar on its axis) and push + // through it, no attack, until the room hands the player over. + let mut target = None; + for seq in 1..600u32 { + let me = room.zone().player_position(player).expect("in the room"); + let (dx, dy) = (21.0 - me.0, 2.0 - me.1); + let len = (dx * dx + dy * dy).sqrt().max(1e-3); + let east = PitInput { + mx: (dx / len * 127.0) as i8, + my: (dy / len * 127.0) as i8, + buttons: 0, + }; + room.push_input( + client, + seq, + seq, + &distributed_game::GameInput::to_payload(&east), + ); + let out = tick(&mut room, &clock); + target = messages(&out).into_iter().find_map(|m| match m { + ServerMessage::Handoff { + target_zone, + transfer_ticket, + } => Some((target_zone, transfer_ticket)), + _ => None, + }); + if target.is_some() { + break; + } + } + let (target, ticket) = target.expect("walked through the east doorway"); + assert_eq!(target, "pit.1.0"); + assert_eq!(ticket, "transfer:pit.1.0"); + assert!(room.zone().player_position(player).is_none(), "left"); +} + +#[test] +fn kills_emit_facts_and_hibernation_keeps_the_mobs() { + let clock = ManualClock::new(); + let mut room = host("pit.2.1", &clock); + let (client, player) = join(&mut room, "bo"); + let mobs = room.zone().stats().mobs_alive; + // Chase and swing until something dies. + let mut seq = 0; + while room.zone().stats().kills == 0 && seq < 3000 { + seq += 1; + let me = room.zone().player_position(player).unwrap_or((0.0, 0.0)); + let nearest = room + .zone() + .mob_positions() + .into_iter() + .filter(|m| m.3) + .min_by(|a, b| { + let d = |m: &(u32, f32, f32, bool)| (m.1 - me.0).powi(2) + (m.2 - me.1).powi(2); + d(a).total_cmp(&d(b)) + }) + .map(|m| (m.1, m.2)) + .unwrap_or((0.0, 0.0)); + let (dx, dy) = (nearest.0 - me.0, nearest.1 - me.1); + let len = (dx * dx + dy * dy).sqrt().max(1e-3); + room.push_input(client, seq, seq, &encode_bot_input([dx / len, dy / len])); + tick(&mut room, &clock); + } + let stats = room.zone().stats(); + assert!(stats.kills >= 1, "a mob died"); + assert!(stats.pending >= 1, "its fact is in flight"); + assert_eq!(stats.mobs_alive, mobs - stats.kills as usize); + + // Sleep, wake: the dead stay dead, the count survives. + let snapshot = room.hibernate_state().expect("snapshot"); + let mut woke = host("pit.2.1", &clock); + woke.restore(&snapshot, ""); + let restored = woke.zone().stats(); + assert!(restored.restored); + assert_eq!(restored.kills, stats.kills); + assert_eq!(restored.mobs_alive, stats.mobs_alive); + join(&mut woke, "bo"); + let out = tick(&mut woke, &clock); + assert!(matches!( + hellos(&out).first(), + Some(PitEvent::Hello { restored: true, room_kills, .. }) if *room_kills == stats.kills + )); +} diff --git a/examples/game/server/service/tests/projection.rs b/examples/game/server/service/tests/projection.rs index 3f56fbfc8..af66f45eb 100644 --- a/examples/game/server/service/tests/projection.rs +++ b/examples/game/server/service/tests/projection.rs @@ -110,7 +110,7 @@ async fn settled_kills_project_into_live_player_stats() { let routes = game_demos::common::relay::relay_routes(world.celld().secret.clone(), world.projection()); tokio::spawn(async move { axum::serve(listener, routes).await.unwrap() }); - let sink = world.fact_sink(); + let sink = game_demos::mobpit::store::kill_sink(world.celld()).unwrap(); // A kill settled before the bus is attached waits in the Queue (the // relay answers 503 and the consumer retries). sink.commit(&kill("k0", "dev-ana", 2, "ana")).await.unwrap(); diff --git a/examples/game/server/sim/src/mobpit.rs b/examples/game/server/sim/src/mobpit.rs index 36a2e0f35..9d4b3033c 100644 --- a/examples/game/server/sim/src/mobpit.rs +++ b/examples/game/server/sim/src/mobpit.rs @@ -1,9 +1,19 @@ -//! Mob Pit's input frame and its client-predicted step (the Arena's -//! movement; combat is server-owned and never predicted). +//! Mob Pit's input frame, its client-predicted step (the Arena's +//! movement; combat is server-owned and never predicted) and its rooms. +//! +//! **Rooms.** Mob Pit is a near-infinite grid of rooms, room `(x, y)` being +//! zone `pit..` (canonical integers, |x|, |y| ≤ [`MAX_ROOM`]). Every +//! room is the Arena floor (same pillars, so the predicted step is the +//! Arena's) with a doorway in the middle of each wall leading to the +//! neighbour. What lives in a room — its biome, danger level and mobs — is +//! a pure function of `(seed, x, y)` ([`pit_room`], `#[game_pure]`) built on +//! the Endless Grid's seeded hashing and biomes ([`crate::grid`]); the page +//! runs the same code compiled to WebAssembly (minimap colours, floor). -use distributed_game::{predict, GameInput}; +use distributed_game::{game_pure, predict, GameInput, GameRecord}; use crate::arena::{self, MoveInput, MoveState}; +use crate::grid; /// Input: the Arena's 3-byte frame (`[mx, my, buttons]`) with an attack /// bit next to dash. @@ -42,3 +52,232 @@ impl PitInput { pub fn pit_step(state: &MoveState, input: &PitInput, _context: &(), _dt: f32) -> MoveState { arena::step(*state, input.movement()) } + +/// Largest |room coordinate|. +pub const MAX_ROOM: i32 = 1_000_000; +/// Half width of a doorway (m), centred on each wall. +pub const DOOR_HALF: f32 = 2.5; +/// Default world seed of the rooms. +pub const DEFAULT_SEED: u32 = 0x0B1D_5EED; +/// Mobs a room holds at most. +pub const MAX_MOBS: usize = 12; + +/// Unit directions of the 12 mob slots (angles `(k + 0.5) / 12 · τ`), as +/// literals so native and WebAssembly agree bit for bit (no `sin`/`cos`). +const SLOTS: [(f32, f32); 12] = [ + (0.9659258, 0.258819), + ( + std::f32::consts::FRAC_1_SQRT_2, + std::f32::consts::FRAC_1_SQRT_2, + ), + (0.258819, 0.9659258), + (-0.258819, 0.9659258), + ( + -std::f32::consts::FRAC_1_SQRT_2, + std::f32::consts::FRAC_1_SQRT_2, + ), + (-0.9659258, 0.258819), + (-0.9659258, -0.258819), + ( + -std::f32::consts::FRAC_1_SQRT_2, + -std::f32::consts::FRAC_1_SQRT_2, + ), + (-0.258819, -0.9659258), + (0.258819, -0.9659258), + ( + std::f32::consts::FRAC_1_SQRT_2, + -std::f32::consts::FRAC_1_SQRT_2, + ), + (0.9659258, -0.258819), +]; + +/// Hash salt of the room contents. +const SALT_ROOM: u32 = 900; + +/// Which room ([`pit_room`]'s input). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, GameRecord)] +pub struct PitRoomContext { + /// World seed. + pub seed: u32, + /// Room x. + pub x: i32, + /// Room y. + pub y: i32, +} + +/// One mob slot of a room: its tier and home. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct RoomMob { + /// 1 grunt · 2 brute · 3 elite. + pub tier: u8, + /// Home x (m, room-local). + pub x: f32, + /// Home y (m, room-local). + pub y: f32, +} + +/// What a room holds. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct PitRoomLayout { + /// Biome index into [`grid::BIOMES`] (the room's look). + pub biome: u8, + /// Danger 1..=3: grows with the distance from the entrance room. + pub danger: u8, + /// Mob slots (ids 1..). + pub mobs: Vec, +} + +/// The contents of room `(x, y)`: biome from the Endless Grid's noise, +/// danger from the distance to `pit.0.0`, 6–12 mobs on two rings between +/// the pillars with tiers weighted by danger. Pure and deterministic. +#[game_pure(PitRoomFn)] +pub fn pit_room(room: &PitRoomContext) -> PitRoomLayout { + let at = (room.x, room.y); + let biome = grid::biome(room.seed, at, (grid::CELL / 2.0, grid::CELL / 2.0)); + let distance = room.x.unsigned_abs().saturating_add(room.y.unsigned_abs()); + let danger = (1 + distance / 3).min(3) as u8; + let h = grid::mix(room.seed, SALT_ROOM, room.x, room.y); + let count = 6 + (h % 7) as usize; + let mut mobs = Vec::with_capacity(count); + for i in 0..count { + let roll = grid::hash32(h ^ (i as u32).wrapping_mul(0x9e37_79b9)); + let ring = if i % 2 == 0 { 11.5 } else { 16.0 }; + let (dx, dy) = SLOTS[i * SLOTS.len() / count]; + // Elites only where it is dangerous; brutes grow with danger. + let tier = match (roll % 100, danger) { + (r, 3) if r < 25 => 3, + (r, 2) if r < 8 => 3, + (r, d) if r < 15 + 20 * u32::from(d) => 2, + _ => 1, + }; + mobs.push(RoomMob { + tier, + x: ring * dx, + y: ring * dy, + }); + } + PitRoomLayout { + biome, + danger, + mobs, + } +} + +/// The rooms' world, for the page (generated `PIT_WORLD`). +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct PitWorld { + /// Default seed. + pub default_seed: u32, + /// Floor half extent (m). + pub half: f32, + /// Doorway half width (m). + pub door_half: f32, + /// Largest |room coordinate|. + pub max_room: i32, + /// Biome names by index. + pub biomes: Vec, +} + +/// The `PIT_WORLD` constant. +pub fn pit_world() -> PitWorld { + PitWorld { + default_seed: DEFAULT_SEED, + half: arena::HALF, + door_half: DOOR_HALF, + max_room: MAX_ROOM, + biomes: grid::BIOMES.map(String::from).to_vec(), + } +} + +/// `pit..`. +pub fn room_zone(room: (i32, i32)) -> String { + format!("pit.{}.{}", room.0, room.1) +} + +/// Parse `pit..` (canonical integers within [`MAX_ROOM`]). +pub fn parse_room(zone_id: &str) -> Option<(i32, i32)> { + let rest = zone_id.strip_prefix("pit.")?; + let (x, y) = rest.split_once('.')?; + let parse = |s: &str| -> Option { + let v: i32 = s.parse().ok()?; + (v.to_string() == s && v.abs() <= MAX_ROOM).then_some(v) + }; + Some((parse(x)?, parse(y)?)) +} + +/// The doorway a player at `(x, y)` pushing with stick `(mx, my)` walks +/// through, as a room offset: against the wall, inside the doorway span, +/// pushing outward. +pub fn doorway(x: f32, y: f32, mx: i8, my: i8) -> Option<(i32, i32)> { + let edge = arena::HALF - arena::PLAYER_RADIUS - 0.05; + if y.abs() < DOOR_HALF { + if x >= edge && mx > 30 { + return Some((1, 0)); + } + if x <= -edge && mx < -30 { + return Some((-1, 0)); + } + } + if x.abs() < DOOR_HALF { + if y >= edge && my > 30 { + return Some((0, 1)); + } + if y <= -edge && my < -30 { + return Some((0, -1)); + } + } + None +} + +/// Where a player arrives through the doorway it came in by (`from` is the +/// offset of the room it left, e.g. `(-1, 0)` = came from the west), +/// keeping its position along the wall. +pub fn arrival(from: (i32, i32), along: f32) -> (f32, f32) { + let inside = arena::HALF - 2.0; + let along = along.clamp(-(DOOR_HALF - 0.6), DOOR_HALF - 0.6); + match from { + (-1, 0) => (-inside, along), + (1, 0) => (inside, along), + (0, -1) => (along, -inside), + _ => (along, inside), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rooms_are_deterministic_and_vary() { + let ctx = |x, y| PitRoomContext { + seed: DEFAULT_SEED, + x, + y, + }; + assert_eq!(pit_room(&ctx(3, -2)), pit_room(&ctx(3, -2))); + let rooms: Vec<_> = (-3..=3).map(|x| pit_room(&ctx(x, 0))).collect(); + assert!(rooms.iter().all(|r| (6..=MAX_MOBS).contains(&r.mobs.len()))); + assert!(rooms.windows(2).any(|w| w[0] != w[1])); + assert_eq!(pit_room(&ctx(0, 0)).danger, 1); + assert_eq!(pit_room(&ctx(9, 9)).danger, 3); + assert!(rooms + .iter() + .all(|r| (r.biome as usize) < grid::BIOMES.len())); + } + + #[test] + fn room_ids_and_doorways() { + assert_eq!(room_zone((1, -2)), "pit.1.-2"); + assert_eq!(parse_room("pit.1.-2"), Some((1, -2))); + assert_eq!(parse_room("pit.01.2"), None); + assert_eq!(parse_room("pit-1"), None); + assert_eq!(parse_room("pit.2000000.0"), None); + let edge = arena::HALF - arena::PLAYER_RADIUS; + assert_eq!(doorway(edge, 0.5, 127, 0), Some((1, 0))); + assert_eq!(doorway(edge, 0.5, -127, 0), None, "pushing back in"); + assert_eq!(doorway(edge, 5.0, 127, 0), None, "wall, not doorway"); + assert_eq!(doorway(0.0, -edge, 0, -127), Some((0, -1))); + assert_eq!(arrival((-1, 0), 9.0).0, -(arena::HALF - 2.0)); + assert!(arrival((-1, 0), 9.0).1 < DOOR_HALF); + } +} diff --git a/examples/game/server/src/common/mod.rs b/examples/game/server/src/common/mod.rs index 4ef46cb8b..0d46c1b5e 100644 --- a/examples/game/server/src/common/mod.rs +++ b/examples/game/server/src/common/mod.rs @@ -10,7 +10,7 @@ pub mod celld; pub mod dev; -mod guests; +pub mod guests; pub mod relay; pub mod zone_status; diff --git a/examples/game/server/src/common/zone_status.rs b/examples/game/server/src/common/zone_status.rs index a5f466f5a..09fd0300a 100644 --- a/examples/game/server/src/common/zone_status.rs +++ b/examples/game/server/src/common/zone_status.rs @@ -4,10 +4,12 @@ //! this host, under a bus consumer group of its own. //! //! This is the consumer of `zone.activated` / `zone.released` / -//! `zone.lease_expired` and `zone_state.saved` / `zone_state.deleted`; the -//! grid's world map reads it to tell active, hibernated and cold zones apart -//! without opening one cell per zone (a read of a never-used cell would -//! create it). Eventually consistent: for views only. +//! `zone.lease_expired` and `zone_state.saved` / `zone_state.deleted` (the +//! native multi-host demos' zones) and of `zone.activity_changed` (zones +//! hosted as celld objects: Mob Pit's rooms); the grid's world map and Mob +//! Pit's minimap read it to tell active, dormant, hibernated and cold zones +//! apart without opening one cell per zone (a read of a never-used cell +//! would create it). Eventually consistent: for views only. use std::collections::HashMap; @@ -18,8 +20,8 @@ use distributed::microsvc::{ }; use distributed::SqliteRepository; use distributed_game::world::zone_status::{ - projectors, read_model_catalog, ZoneLeases, ZoneSnapshots, ZoneStatus, APPLICATION, - ZONE_LEASES, ZONE_SNAPSHOTS, + activity_projector, projectors, read_model_catalog, ZoneActivities, ZoneLeases, ZoneSnapshots, + ZoneStatus, APPLICATION, ZONE_ACTIVITIES, ZONE_LEASES, ZONE_SNAPSHOTS, }; /// See the module docs. @@ -42,6 +44,13 @@ async fn project_snapshots( projection.apply(ZONE_SNAPSHOTS, &context).await } +async fn project_activities( + context: CausalProjectorContext, + projection: ModeledProjection, +) -> Result<(), HandlerError> { + projection.apply(ZONE_ACTIVITIES, &context).await +} + /// `{select} WHERE zone_id IN (?, ?, …)` over `zones`. fn by_zone(select: &str, zones: &[String]) -> sqlx::QueryBuilder { let mut query = sqlx::QueryBuilder::new(select); @@ -80,7 +89,9 @@ impl ZoneStatusView { .modeled_projector(leases) .handle(project_leases) .modeled_projector(snapshots) - .handle(project_snapshots), + .handle(project_snapshots) + .modeled_projector(activity_projector()) + .handle(project_activities), ) .with_bus( SqliteBus::new_with_group(bus.clone(), group.clone()) @@ -90,6 +101,45 @@ impl ZoneStatusView { Ok(Self { repo }) } + /// Every `zone_activities` row whose zone id starts with `prefix` + /// (zones hosted as celld objects). + pub async fn activities(&self, prefix: &str) -> Result, String> { + let rows = sqlx::query_as::<_, (String, String, String, bool, i64, String, String, i64, i64)>( + "SELECT zone_id, status, activation, restored, players, node, isolate, activations, \ + changed_at_ms FROM zone_activities WHERE zone_id LIKE ? ORDER BY zone_id", + ) + .bind(format!("{prefix}%")) + .fetch_all(self.repo.pool()) + .await + .map_err(|e| format!("zone activities: {e}"))?; + Ok(rows + .into_iter() + .map( + |( + zone_id, + status, + activation, + restored, + players, + node, + isolate, + activations, + changed_at_ms, + )| ZoneActivities { + zone_id, + status, + activation, + restored, + players, + node, + isolate, + activations, + changed_at_ms, + }, + ) + .collect()) + } + /// The status of each of `zones` (`Cold` when the read model has no /// row). pub async fn statuses(&self, zones: &[String]) -> Result, String> { diff --git a/examples/game/server/src/devcelld.rs b/examples/game/server/src/devcelld.rs index 566904446..636812f3d 100644 --- a/examples/game/server/src/devcelld.rs +++ b/examples/game/server/src/devcelld.rs @@ -45,6 +45,8 @@ pub struct DevCelld { project: PathBuf, port: u16, secret: String, + ticket_secret: String, + vars: Vec<(String, String)>, relay_url: Option, child: Option, generation: u32, @@ -56,18 +58,33 @@ impl DevCelld { /// Queue consumer relays domain events (a demo server's /// `/internal/celld-queue/relay`); `None` keeps them queued. pub fn start(relay_url: Option) -> Result { + Self::start_with(relay_url, &[]) + } + + /// [`start`](Self::start) with extra worker vars (e.g. + /// `ZONE_HIBERNATE_AFTER_MS` for the rooms). + pub fn start_with(relay_url: Option, vars: &[(&str, &str)]) -> Result { let project = std::env::temp_dir().join(format!( "game-demo-celld-{}-{}", std::process::id(), crate::common::random_hex(8) )); - let mut celld = Self::in_project(&project, relay_url)?; + let mut celld = Self::in_project_with(&project, relay_url, vars)?; celld.keep = false; Ok(celld) } /// Start celld on `project` (created; existing state is reused). pub fn in_project(project: &Path, relay_url: Option) -> Result { + Self::in_project_with(project, relay_url, &[]) + } + + /// [`in_project`](Self::in_project) with extra worker vars. + pub fn in_project_with( + project: &Path, + relay_url: Option, + vars: &[(&str, &str)], + ) -> Result { let build = cells_dir().join("build"); if !build.join("worker/shim.mjs").exists() { return Err(format!( @@ -87,6 +104,11 @@ impl DevCelld { project: project.to_path_buf(), port: free_port(), secret: test_secret(), + ticket_secret: test_secret(), + vars: vars + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), relay_url, child: None, generation: 0, @@ -111,6 +133,16 @@ impl DevCelld { &self.secret } + /// The secret the rooms verify tickets with (`GAME_TICKET_SECRET`). + pub fn ticket_secret(&self) -> &str { + &self.ticket_secret + } + + /// `ws://127.0.0.1:{port}` (append `/rooms/{room}`). + pub fn ws_url(&self) -> String { + format!("ws://127.0.0.1:{}", self.port) + } + /// Project directory (holds `.celld/dev` and the logs). pub fn project(&self) -> &Path { &self.project @@ -124,7 +156,13 @@ impl DevCelld { .celld-version); point {CELLD_BIN_ENV} at the celld binary" ) })?; - let mut vars = format!("DISTRIBUTED_INTERNAL_SECRET={}\n", self.secret); + let mut vars = format!( + "DISTRIBUTED_INTERNAL_SECRET={}\nGAME_TICKET_SECRET={}\n", + self.secret, self.ticket_secret + ); + for (key, value) in &self.vars { + vars.push_str(&format!("{key}={value}\n")); + } if let Some(relay) = &self.relay_url { vars.push_str(&format!("CELLD_QUEUE_RELAY_URL={relay}\n")); } diff --git a/examples/game/server/src/grid/dev.rs b/examples/game/server/src/grid/dev.rs index a9202bca9..8dda2e934 100644 --- a/examples/game/server/src/grid/dev.rs +++ b/examples/game/server/src/grid/dev.rs @@ -103,6 +103,7 @@ async fn stored_cells(state: &MapState, zones: &[String]) -> serde_json::Map { json!({ "state": "hibernated", "bytes": bytes }) } + ZoneStatus::Dormant => json!({ "state": "dormant" }), ZoneStatus::Cold => json!({ "state": "cold" }), }; out.insert(zone, fact); diff --git a/examples/game/server/src/mobpit/board.rs b/examples/game/server/src/mobpit/board.rs index 3ae71fe0f..2bb8fc08d 100644 --- a/examples/game/server/src/mobpit/board.rs +++ b/examples/game/server/src/mobpit/board.rs @@ -2,15 +2,18 @@ //! //! - Store: `InMemoryLeaderboard`, or `RedisLeaderboard` when `REDIS_URL` //! is set (sorted sets; every idempotent write is one Lua script). -//! - Live path (fire-and-forget): after a kill commits, the fact sink calls -//! [`Leaderboards::submit_kill`], which enqueues one occurrence on a -//! `BackgroundLeaderboard` and returns immediately. A full queue or a Redis -//! outage drops the update (counted); a rebuild heals it. -//! - Idempotency: every kill becomes a `DomainEventOccurrence` whose id is -//! derived from `(producer, "Crawler:{principal}", event sequence, -//! "mob_killed")` — the same id whether it comes from the live receipt, a -//! ledger replay of the same fact, or the cell's event history. The -//! projector's apply keys (`"{id}#{change}"`) make every repeat a no-op. +//! - Live path (fire-and-forget): kills commit in the Crawler cells, next to +//! the rooms on celld; their `crawler.mob_killed` events reach this server +//! through the outbox Queue relay and the crawler directory +//! (`super::directory`). Every change of a crawler's totals there becomes +//! one [`CrawlerTotals`] occurrence ([`Leaderboards::submit_totals`]) on a +//! `BackgroundLeaderboard`: `Max` of kills and XP, so repeats, replays and +//! reordering are no-ops. A full queue or a Redis outage drops the update +//! (counted); the next change or a rebuild heals it. +//! - Idempotency of the rebuild: every kill in a cell's history becomes a +//! `DomainEventOccurrence` whose id is derived from `(producer, +//! "Crawler:{principal}", event sequence, "mob_killed")`; the projector's +//! apply keys (`"{id}#{change}"`) make every repeat a no-op. //! - Rebuild ([`Leaderboards::rebuild`]): read the durable event history //! of every crawler in the directory (`super::directory`) from its cell, //! project it into the *staging* boards and atomically promote them. @@ -36,7 +39,7 @@ use distributed_game::GameRecord; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use super::crawler::{KillReceipt, AGGREGATE_TYPE}; +use super::crawler::AGGREGATE_TYPE; use super::store::CrawlerCells; pub use mobpit_crawler::{KILLS_BOARD, XP_BOARD}; @@ -175,7 +178,37 @@ pub fn kill_occurrence( .map_err(|e| format!("capture kill occurrence: {e:?}")) } -/// kills += 1, xp += xp. +/// Live projection input: a crawler's totals after a kill (the post-kill +/// state its cell published), monotonic in `kills`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] +#[domain_event(name = "mobpit.crawler_totals", version = 1)] +pub struct CrawlerTotals { + /// Principal. + pub crawler: String, + /// Mobs killed. + pub kills: u32, + /// Total XP. + pub xp: u64, +} + +/// The occurrence of `principal` reaching `kills` kills (one id per total). +pub fn totals_occurrence(totals: &CrawlerTotals) -> Result { + DomainEventOccurrence::capture_external( + ExternalEventSource { + producer: PRODUCER.into(), + stream: format!("{AGGREGATE_TYPE}:{}", totals.crawler), + position: u64::from(totals.kills), + key: "totals".into(), + }, + UNIX_EPOCH, + Default::default(), + totals, + ) + .map_err(|e| format!("capture totals occurrence: {e:?}")) +} + +/// Rebuild: kills += 1, xp += xp per recorded kill. Live: the greater of +/// the stored and the reported totals. pub struct KillProjection { kills: Board, xp: Board, @@ -193,12 +226,32 @@ impl KillProjection { impl LeaderboardProjection for KillProjection { fn handles(&self, event_name: &str) -> bool { event_name == ::DESCRIPTOR.name + || event_name == ::DESCRIPTOR.name } fn project( &self, event: &DomainEventOccurrence, ) -> Result, LeaderboardError> { + if event.descriptor().name == ::DESCRIPTOR.name { + let totals: CrawlerTotals = event + .decode_body() + .map_err(|e| LeaderboardError::invalid(format!("crawler_totals body: {e:?}")))?; + return Ok(vec![ + LeaderboardChange::new( + self.kills.clone(), + ScoreSubmission::new( + &totals.crawler, + f64::from(totals.kills), + ScorePolicy::Max, + ), + ), + LeaderboardChange::new( + self.xp.clone(), + ScoreSubmission::new(&totals.crawler, totals.xp as f64, ScorePolicy::Max), + ), + ]); + } let kill: MobKilled = event .decode_body() .map_err(|e| LeaderboardError::invalid(format!("mob_killed body: {e:?}")))?; @@ -311,20 +364,15 @@ impl Leaderboards { (&self.kills, &self.xp) } - /// Fire-and-forget live update for a committed (or replayed) kill. - pub fn submit_kill(&self, kill: &KillReceipt) { - self.remember_name(&kill.crawler, &kill.name); - match kill_occurrence( - &kill.crawler, - kill.sequence, - kill.at_ms, - &MobKilled { - crawler: kill.crawler.clone(), - mob: kill.mob.clone(), - tier: kill.tier, - xp: kill.xp, - }, - ) { + /// Fire-and-forget live update: `principal` (shown as `name`) now has + /// these totals. + pub fn submit_totals(&self, principal: &str, name: &str, kills: u32, xp: u64) { + self.remember_name(principal, name); + match totals_occurrence(&CrawlerTotals { + crawler: principal.to_string(), + kills, + xp, + }) { Ok(occurrence) => { self.background.submit(occurrence); } diff --git a/examples/game/server/src/mobpit/mod.rs b/examples/game/server/src/mobpit/mod.rs index 988b3d690..7e826d735 100644 --- a/examples/game/server/src/mobpit/mod.rs +++ b/examples/game/server/src/mobpit/mod.rs @@ -1,63 +1,66 @@ -//! **Mob Pit** (+ **Leaderboard**) — non-blocking durable facts, crash -//! recovery and authoritative combat; kills projected into sorted-set -//! leaderboards. +//! **Mob Pit** (+ **Leaderboard**) — a near-infinite grid of rooms joined by +//! doorways, authoritative melee combat, kills settled exactly once in the +//! players' durable cells, and live room status. //! -//! - [`zone`]: the 30 Hz zone (players, 12 mobs with a telegraphed attack -//! state machine, melee cones). A kill emits a fact and keeps ticking. -//! - [`crawler`]: the per-player `Crawler` aggregate and its one command; -//! XP is decided there, the principal comes from the trusted session. -//! - [`store`]: the zone server's side of the celld cells -//! (`examples/game/cells`): the `FactSink` (with the "slow storage" -//! latency knob) that routes facts to them via -//! `distributed_game::celld::CelldFactSink`, and the cell reader. -//! - [`directory`]: the crawler list, a projection of the cells' domain -//! events (outbox → Queue → `crate::common::relay` → bus). -//! - [`board`]: kills/XP leaderboards (in-memory or Redis), fire-and-forget -//! live updates, idempotent apply keys, rebuild from the cells' events. -//! - [`presence`]: who is online where, projected from the runtime's player -//! lifecycle facts (`HostConfig::lifecycle_facts`), ordered by fact stamp. -//! - [`routes`]: dev routes (`/dev/mobpit/*`). +//! The rooms run on **celld**: every room (`pit..`) is a Durable +//! Object of the cells worker (`examples/game/cells`, zone code in +//! `mobpit_rooms`, hosted by `distributed_game::celld_zone`). celld decides +//! which node runs a room; the game never does. A room's kill facts go to +//! the killer's Crawler cell object to object; its lifecycle (active / +//! dormant / hibernated) goes to its zone-activity cell. //! -//! `game-demos mobpit` and `game-demos leaderboard` start the same server -//! (one process hosts the pit and the boards); they differ only in the page -//! `run.sh` opens. Durable state is in celld (`--celld-url` / `CELLD_URL`, -//! secret `DISTRIBUTED_INTERNAL_SECRET`); `run.sh` and the tests start -//! `celld dev` with `examples/game/cells`. `--data-dir` / `MOBPIT_DATA_DIR` -//! keeps the persisted ticket secret (so guests keep their identity across -//! a restart, the crash-recovery demo) and the default projection bus. +//! This process (`game-demos mobpit|leaderboard`) is the services side, no +//! room runs here: +//! - [`routes`]: the dev routes — `/dev/ticket` mints room tickets for +//! guests (signed with the secret the rooms verify), `/dev/mobpit/*`. +//! - [`world`]: the projection bus the cells' outbox Queue relays onto +//! (`crate::common::relay`), the crawler directory ([`directory`]), the +//! rooms' status (`zone_status`, for the minimap) and the leaderboards +//! ([`board`]) fed from the directory. +//! - [`store`]: reads of the Crawler and presence cells. +//! +//! `--data-dir` / `MOBPIT_DATA_DIR` keeps the dev ticket secret (shared +//! with the rooms through celld's `GAME_TICKET_SECRET`; guests keep their +//! identity across restarts) and the default projection bus. pub mod board; pub mod crawler; pub mod directory; -pub mod presence; pub mod routes; pub mod store; pub mod world; pub mod zone; use std::future::Future; +use std::net::SocketAddr; use std::path::PathBuf; use std::sync::Arc; -use distributed_game::net::{GameServer, ServerConfig}; +use distributed_game::net::TicketKey; -use crate::common::{self, random_hex, Demo, DemoArgs, DemoOptions, Guests, RunningDemo}; +use crate::common::relay::relay_routes; +use crate::common::{random_hex, shutdown_signal, DemoArgs}; pub use world::{MobPitWorld, WorldOptions}; pub use zone::{encode_bot_input, game_surface, MobPit}; +/// Room ids this demo admits (`pit..`). +pub fn hosts_zone(zone_id: &str) -> bool { + mobpit_rooms::parse_room(zone_id).is_some() +} + /// `game-demos mobpit|leaderboard` options. #[derive(Debug, Clone, clap::Args)] pub struct MobPitArgs { - /// Shared demo options. + /// Shared demo options (`--secret` / `DISTRIBUTED_GAME_SECRET` is the + /// rooms' ticket secret, `GAME_TICKET_SECRET` on celld). #[command(flatten)] pub common: DemoArgs, - /// celld serving `examples/game/cells` (the Crawler and presence - /// cells). The internal secret comes from - /// `DISTRIBUTED_INTERNAL_SECRET`. + /// celld serving `examples/game/cells` (the rooms and their cells). + /// The internal secret comes from `DISTRIBUTED_INTERNAL_SECRET`. #[arg(long, env = "CELLD_URL")] pub celld_url: String, /// Directory of local dev files: the persisted dev ticket secret, the - /// default projection bus and the crawler directory's read models. + /// default projection bus and this server's read models. /// Default: `$TMPDIR/game-demos-mobpit`. #[arg(long, env = "MOBPIT_DATA_DIR")] pub data_dir: Option, @@ -67,58 +70,54 @@ pub struct MobPitArgs { /// Redis key prefix of the boards (`mobpit-service` reads the same). #[arg(long, env = "MOBPIT_REDIS_PREFIX", default_value = mobpit_crawler::BOARD_REDIS_PREFIX)] pub redis_prefix: String, - /// Start with this artificial storage latency (ms). - #[arg(long, env = "MOBPIT_STORAGE_LATENCY_MS", default_value_t = 0)] - pub storage_latency_ms: u64, - /// SQLite bus (`sqlite:/path/bus.db`) the Crawler cells' - /// `crawler.mob_killed` domain events are published to (relayed from - /// celld's outbox Queue); `mobpit-service` and this server's crawler - /// directory project them. Default: `sqlite:{data-dir}/bus.db`. + /// SQLite bus the cells' domain events are published to (relayed from + /// celld's outbox Queue); `mobpit-service` and this server project it. + /// Default: `sqlite:{data-dir}/bus.db`. #[arg(long, env = "MOBPIT_PROJECTION_BUS")] pub projection_bus: Option, } -/// Demo registration. -pub struct MobPitDemo; - -impl Demo for MobPitDemo { - type Zone = MobPit; - const NAME: &'static str = "mobpit"; - const DEFAULT_ZONE: &'static str = "pit-1"; - - fn hosts_zone(zone_id: &str) -> bool { - zone_id.starts_with("pit-") - } +/// The services running on a Tokio task. +pub struct RunningServices { + /// Bound address. + pub addr: SocketAddr, + /// Resolves when the server stopped. + pub task: tokio::task::JoinHandle>, +} - /// Plain `common::spawn` gets a throwaway world (temp dir, in-memory - /// board, no routes of its own) on the celld named by `CELLD_URL` and - /// `DISTRIBUTED_INTERNAL_SECRET`; use [`spawn`] / [`run`] instead. - fn server(config: ServerConfig, guests: Guests) -> GameServer { - let celld = store::CelldOptions::from_env().expect("Mob Pit needs celld"); - let world = MobPitWorld::open(WorldOptions::temporary(celld)) - .expect("mobpit world (needs a Tokio runtime)"); - world.server(config, guests).0 +impl RunningServices { + /// `http://addr`. + pub fn http_url(&self) -> String { + format!("http://{}", self.addr) } } -/// Start Mob Pit over `world` (tests; dev routes need `options.dev`). +/// Serve `world` on `listener` until `signal` (tests): the internal relay +/// route always, the dev routes when `dev`. pub fn spawn( listener: tokio::net::TcpListener, - options: DemoOptions, + key: TicketKey, + dev: bool, world: Arc, signal: impl Future + Send + 'static, -) -> std::io::Result> { - common::spawn_with::( - listener, - options, - move |config, guests| world.server(config, guests), - signal, - ) +) -> std::io::Result { + let addr = listener.local_addr()?; + let mut app = relay_routes(world.celld().secret.clone(), world.projection()); + if dev { + app = app.merge(routes::routes(world, key)); + } + let task = tokio::spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(signal) + .await + }); + Ok(RunningServices { addr, task }) } -/// Dev ticket secret kept in the data dir, so guest tokens (and therefore -/// principals) survive a server restart. -fn persisted_secret(dir: &std::path::Path) -> std::io::Result { +/// The dev ticket secret kept in the data dir (`dev-ticket-secret`), so +/// guests keep their identity across restarts; `run.sh` gives the same +/// file to celld as the rooms' `GAME_TICKET_SECRET`. +pub fn persisted_secret(dir: &std::path::Path) -> std::io::Result { let path = dir.join("dev-ticket-secret"); if let Ok(secret) = std::fs::read_to_string(&path) { let secret = secret.trim().to_string(); @@ -126,6 +125,7 @@ fn persisted_secret(dir: &std::path::Path) -> std::io::Result { return Ok(secret); } } + std::fs::create_dir_all(dir)?; let secret = random_hex(64); std::fs::write(&path, &secret)?; #[cfg(unix)] @@ -136,8 +136,8 @@ fn persisted_secret(dir: &std::path::Path) -> std::io::Result { Ok(secret) } -/// CLI entry: connect to the cells, rebuild the board from them, serve. -pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { +/// CLI entry: open the services, rebuild the board from the cells, serve. +pub async fn run(args: MobPitArgs) -> std::io::Result<()> { let data_dir = args .data_dir .clone() @@ -155,15 +155,10 @@ pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { let world = MobPitWorld::start(options) .await .map_err(std::io::Error::other)?; - world - .sink_state() - .set_latency(std::time::Duration::from_millis(args.storage_latency_ms)); - if args.common.secret.is_none() { - args.common.secret = Some(persisted_secret(&data_dir)?); - } - // Board = projection of the cells: rebuild it from the crawler - // directory before accepting players (the in-memory board starts - // empty; Redis may have missed updates). + let ticket_secret = match args.common.secret.clone() { + Some(secret) => secret, + None => persisted_secret(&data_dir)?, + }; match world.rebuild_board().await { Ok(report) => eprintln!( "mobpit: leaderboard rebuilt from cells: {}", @@ -171,16 +166,24 @@ pub async fn run(mut args: MobPitArgs) -> std::io::Result<()> { ), Err(error) => eprintln!("mobpit: leaderboard rebuild failed (serving anyway): {error}"), } - let bus = world.bus_url().to_string(); - eprintln!( - "mobpit: celld {} · projection bus {bus} · data dir {} · boot {} · leaderboard {}", + let listener = + tokio::net::TcpListener::bind((args.common.host.as_str(), args.common.port)).await?; + let running = spawn( + listener, + TicketKey::new(ticket_secret), + args.common.dev, + world.clone(), + shutdown_signal(), + )?; + // Parsed by run.sh and the client tests: keep the format. + println!("LISTENING http://{}", running.addr); + println!( + "demo mobpit · rooms on celld {} (ws …/rooms/{}) · projection bus {} · leaderboard {} · dev routes {}", args.celld_url, - data_dir.display(), - world.boot(), - world.board().backend() + mobpit_rooms::ENTRANCE, + world.bus_url(), + world.board().backend(), + if args.common.dev { "ON" } else { "off" } ); - common::run_with::(args.common, move |config, guests| { - world.server(config, guests) - }) - .await + running.task.await.map_err(std::io::Error::other)? } diff --git a/examples/game/server/src/mobpit/presence.rs b/examples/game/server/src/mobpit/presence.rs deleted file mode 100644 index 960cff9c9..000000000 --- a/examples/game/server/src/mobpit/presence.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! Presence read model projected from the runtime's player lifecycle facts -//! (`HostConfig::lifecycle_facts`, `distributed_game::lifecycle`). -//! -//! The fact sink hands every lifecycle fact to [`Presence::apply`] instead -//! of a Crawler cell. Facts commit in per-principal order within one zone, -//! but across zones (a handoff, a reconnect elsewhere) commit order says -//! nothing: each entry keeps the [`FactStamp`] of the fact that set it and a -//! fact that was *emitted* earlier (`FactStamp::emission_order`) is ignored, -//! so "left pit-1" committed after "joined pit-2" cannot mark a player -//! offline. A retried fact (same key) applies idempotently. - -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::sync::Mutex; - -use distributed_game::lifecycle::Lifecycle; -use distributed_game::FactStamp; -use serde::Serialize; - -/// Where a player is. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum PresenceStatus { - /// Connected to `zone`. - Online, - /// Connection lost; `zone` keeps the slot for the reconnect grace. - Away, - /// Left `zone` (or its grace expired). - Offline, -} - -/// One player's presence. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct PresenceEntry { - /// Verified principal (the fact's binding, never its payload). - pub principal: String, - /// Zone of the latest transition. - pub zone: String, - /// Status after it. - pub status: PresenceStatus, - /// Host wall time of that transition (Unix ms). - pub since_ms: u64, - #[serde(skip)] - stamp: FactStamp, -} - -/// The projection. -#[derive(Debug, Default)] -pub struct Presence { - entries: Mutex>, -} - -impl Presence { - /// Apply one lifecycle fact of `principal`. False when an entry set by - /// a later-emitted fact already exists (stale, ignored). - pub fn apply(&self, principal: &str, stamp: &FactStamp, event: &Lifecycle) -> bool { - let status = match event { - Lifecycle::Joined(_) | Lifecycle::Reconnected(_) => PresenceStatus::Online, - Lifecycle::ConnectionLost(_) => PresenceStatus::Away, - Lifecycle::Left(_) | Lifecycle::Disconnected(_) => PresenceStatus::Offline, - }; - let mut entries = self.entries.lock().expect("presence"); - if let Some(current) = entries.get(principal) { - if current.stamp.emission_order(stamp) != Ordering::Less { - return false; - } - } - entries.insert( - principal.to_string(), - PresenceEntry { - principal: principal.to_string(), - zone: event.zone().to_string(), - status, - since_ms: stamp.emitted_at_ms, - stamp: stamp.clone(), - }, - ); - true - } - - /// One player. - pub fn get(&self, principal: &str) -> Option { - self.entries - .lock() - .expect("presence") - .get(principal) - .cloned() - } - - /// Everyone seen, by principal. - pub fn snapshot(&self) -> Vec { - self.entries - .lock() - .expect("presence") - .values() - .cloned() - .collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use distributed_game::lifecycle::{JoinVia, LeftReason, PlayerJoined, PlayerLeft}; - - fn stamp(zone: &str, activation: u64, tick: u64, at: u64) -> FactStamp { - FactStamp { - zone_id: zone.into(), - tick, - emitted_at_ms: at, - activation, - seq: tick, - ..FactStamp::default() - } - } - - #[test] - fn a_handoff_leave_committed_late_does_not_mark_the_player_offline() { - let presence = Presence::default(); - let joined_b = Lifecycle::Joined(PlayerJoined { - zone: "pit-2".into(), - via: JoinVia::Handoff, - from_zone: Some("pit-1".into()), - }); - let left_a = Lifecycle::Left(PlayerLeft { - zone: "pit-1".into(), - reason: LeftReason::Handoff, - }); - // pit-2 commits first; pit-1's departure (emitted earlier) after. - assert!(presence.apply("ana", &stamp("pit-2", 4, 2, 1_001), &joined_b)); - assert!(!presence.apply("ana", &stamp("pit-1", 3, 90, 1_000), &left_a)); - let ana = presence.get("ana").unwrap(); - assert_eq!( - (ana.zone.as_str(), ana.status), - ("pit-2", PresenceStatus::Online) - ); - // Replaying the same fact is a no-op. - assert!(!presence.apply("ana", &stamp("pit-2", 4, 2, 1_001), &joined_b)); - } - - #[test] - fn a_drop_in_the_join_tick_and_millisecond_still_marks_the_player_away() { - use distributed_game::lifecycle::{ConnectionLost, LostCause}; - let presence = Presence::default(); - let joined = Lifecycle::Joined(PlayerJoined { - zone: "pit-1".into(), - via: JoinVia::Ticket, - from_zone: None, - }); - let lost = Lifecycle::ConnectionLost(ConnectionLost { - zone: "pit-1".into(), - grace_ms: 15_000, - cause: LostCause::Dropped, - }); - // Same zone, activation, tick and wall time: only the host's - // emission sequence orders them. - let at = |seq| FactStamp { - seq, - ..stamp("pit-1", 3, 0, 1_000) - }; - assert!(presence.apply("bo", &at(1), &joined)); - assert!(presence.apply("bo", &at(2), &lost)); - assert_eq!(presence.get("bo").unwrap().status, PresenceStatus::Away); - assert!(!presence.apply("bo", &at(1), &joined), "stale join ignored"); - } -} diff --git a/examples/game/server/src/mobpit/routes.rs b/examples/game/server/src/mobpit/routes.rs index 8beeab242..cb051d3d9 100644 --- a/examples/game/server/src/mobpit/routes.rs +++ b/examples/game/server/src/mobpit/routes.rs @@ -1,35 +1,37 @@ -//! **Dev-only** Mob Pit routes (mounted with `--dev`, next to `/dev/ticket`). -//! None of them takes an identity or a reward from the caller. +//! **Dev-only** Mob Pit routes (mounted with `--dev`). None of them takes an +//! identity or a reward from the caller. //! -//! - `GET /dev/mobpit/storage`, `POST /dev/mobpit/storage {latencyMs}` — -//! artificial latency in front of every cell commit ("slow storage"). -//! - `GET /dev/mobpit/stats` — boot id, sink counters, pending facts, recent -//! commits (key, exact input, receipt). -//! - `GET /dev/mobpit/crawlers` — every crawler in the directory (the -//! `player_stats` projection of the cells' domain events; eventually -//! consistent). -//! - `GET /dev/mobpit/leaderboard[?member=principal]` — the pushed top-N -//! snapshot, plus rank / neighbours of `member` on both boards. +//! - `POST /dev/ticket` `{zone, name?, role?, guest?}` → a single-use room +//! ticket for a **server-generated** guest principal, signed with the +//! rooms' ticket secret (see `crate::common::dev` for the fields). Only +//! `pit..` rooms. A real game mints tickets from its sign-in (the +//! SvelteKit demo does). +//! - `GET /dev/mobpit/rooms` — every known room's status (`active` / +//! `dormant` / `hibernated`, players, restored, debug node), the +//! `zone_status` read model projected from the rooms' activity cells. +//! - `GET /dev/mobpit/stats` — boot id, celld, board backend. +//! - `GET /dev/mobpit/crawlers` — every crawler in the directory. +//! - `GET /dev/mobpit/leaderboard[?member=principal]` — the top-N snapshot, +//! plus rank / neighbours of `member` on both boards. //! - `POST /dev/mobpit/leaderboard/rebuild` — rebuild both boards from the -//! event history of every crawler in the directory (read from its cell); -//! reports whether the result matches the cells. -//! - `GET /dev/mobpit/presence` — who is online / away / offline where, -//! projected from the runtime's player lifecycle facts. -//! -//! The always-mounted internal relay route is `crate::common::relay`. +//! event history of every crawler in the directory. +//! - `GET /dev/mobpit/presence?principal=` — the player's presence cell. use std::collections::HashMap; use std::sync::Arc; -use std::time::Duration; +use std::time::{SystemTime, UNIX_EPOCH}; use axum::extract::{Query, State}; use axum::http::StatusCode; use axum::routing::{get, post}; use axum::{Json, Router}; -use serde::Deserialize; +use distributed_game::net::TicketKey; +use distributed_game::{Role, TicketClaims}; use serde_json::{json, Value}; use super::world::MobPitWorld; +use crate::common::dev::{TicketRequest, TicketResponse, TICKET_TTL_SECS}; +use crate::common::guests; type ApiResult = Result, (StatusCode, Json)>; @@ -40,79 +42,130 @@ fn internal(error: impl std::fmt::Display) -> (StatusCode, Json) { ) } +fn bad_request(message: &str) -> (StatusCode, Json) { + (StatusCode::BAD_REQUEST, Json(json!({ "error": message }))) +} + +#[derive(Clone)] +struct Dev { + world: Arc, + key: TicketKey, +} + /// The router. -pub fn routes(world: Arc) -> Router { +pub fn routes(world: Arc, key: TicketKey) -> Router { Router::new() - .route("/dev/mobpit/storage", get(get_storage).post(set_storage)) + .route("/dev/ticket", post(ticket)) + .route("/dev/mobpit/rooms", get(rooms)) .route("/dev/mobpit/stats", get(stats)) .route("/dev/mobpit/crawlers", get(crawlers)) .route("/dev/mobpit/leaderboard", get(leaderboard)) .route("/dev/mobpit/leaderboard/rebuild", post(rebuild)) .route("/dev/mobpit/presence", get(presence)) - .with_state(world) -} - -/// `POST /dev/mobpit/storage` body. -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct StorageBody { - latency_ms: u64, -} - -fn storage_json(world: &MobPitWorld) -> Value { - json!({ "latencyMs": world.sink_state().latency().as_millis() as u64 }) + .with_state(Dev { world, key }) } -async fn get_storage(State(world): State>) -> Json { - Json(storage_json(&world)) +async fn ticket( + State(dev): State, + Json(request): Json, +) -> Result, (StatusCode, Json)> { + if !super::hosts_zone(&request.zone) { + return Err(bad_request("not a Mob Pit room (pit..)")); + } + let role = match request.role.as_deref() { + None | Some("player") => Role::Player, + Some("observer") => Role::Observer, + Some(_) => return Err(bad_request("role must be player or observer")), + }; + // Identity: a verified guest token, else a brand-new principal. + let principal = request + .guest + .as_deref() + .and_then(|token| guests::verify_guest_token(&dev.key, token)) + .unwrap_or_else(guests::new_principal); + let name = request + .name + .as_deref() + .map(guests::sanitize_name) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| format!("Guest {}", principal.get(6..10).unwrap_or(""))); + let expires_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) + + TICKET_TTL_SECS; + let ticket = dev.key.sign( + &TicketClaims::new( + principal.clone(), + request.zone.clone(), + expires_at, + guests::random_hex(24), + role, + ) + .with_name(name.clone()), + ); + Ok(Json(TicketResponse { + ticket, + guest: guests::guest_token(&dev.key, &principal), + principal, + name, + zone: request.zone, + expires_at, + })) } -async fn set_storage( - State(world): State>, - Json(body): Json, -) -> Json { - world - .sink_state() - .set_latency(Duration::from_millis(body.latency_ms)); - Json(storage_json(&world)) +async fn rooms(State(dev): State) -> ApiResult { + Ok(Json( + json!({ "rooms": dev.world.rooms().await.map_err(internal)? }), + )) } -async fn stats(State(world): State>) -> Json { +async fn stats(State(dev): State) -> Json { + let world = &dev.world; Json(json!({ "boot": world.boot(), "dataDir": world.data_dir().display().to_string(), "celld": world.cells().url(), - "latencyMs": world.sink_state().latency().as_millis() as u64, - "pending": world.zone_pending(), - "sink": world.sink_state().stats(), - "recent": world.sink_state().recent(), "board": world.board().backend(), })) } -async fn crawlers(State(world): State>) -> ApiResult { +async fn crawlers(State(dev): State) -> ApiResult { Ok(Json( - json!({ "crawlers": world.crawlers().await.map_err(internal)? }), + json!({ "crawlers": dev.world.crawlers().await.map_err(internal)? }), )) } async fn leaderboard( - State(world): State>, + State(dev): State, Query(query): Query>, ) -> ApiResult { - let snapshot = (*world.board().snapshot()).clone(); + let board = dev.world.board(); + let snapshot = (*board.snapshot()).clone(); let me = match query.get("member").filter(|m| !m.is_empty()) { - Some(member) => world.board().around(member, 2).await.map_err(internal)?, + Some(member) => board.around(member, 2).await.map_err(internal)?, None => Value::Null, }; Ok(Json(json!({ "snapshot": snapshot, "me": me }))) } -async fn presence(State(world): State>) -> Json { - Json(json!({ "presence": world.presence().snapshot() })) +async fn rebuild(State(dev): State) -> ApiResult { + let report = dev.world.rebuild_board().await.map_err(internal)?; + Ok(Json(serde_json::to_value(report).map_err(internal)?)) } -async fn rebuild(State(world): State>) -> ApiResult { - let report = world.rebuild_board().await.map_err(internal)?; - Ok(Json(serde_json::to_value(report).map_err(internal)?)) +async fn presence( + State(dev): State, + Query(query): Query>, +) -> ApiResult { + let principal = query + .get("principal") + .filter(|p| !p.is_empty()) + .ok_or_else(|| bad_request("principal is required"))?; + let current = dev + .world + .cells() + .presence(principal) + .await + .map_err(internal)?; + Ok(Json(json!({ "principal": principal, "presence": current }))) } diff --git a/examples/game/server/src/mobpit/store.rs b/examples/game/server/src/mobpit/store.rs index 156bcfc8e..28a5d66c2 100644 --- a/examples/game/server/src/mobpit/store.rs +++ b/examples/game/server/src/mobpit/store.rs @@ -1,46 +1,38 @@ -//! Mob Pit's durable state lives in celld cells (`examples/game/cells`); -//! this module is the zone server's side of them. +//! Mob Pit's durable state lives in celld cells (`examples/game/cells`), +//! next to the rooms that feed them: a room's kill and lifecycle facts go +//! to the killer's `crawler/{principal}` and `presence/{principal}` cells +//! object to object (`mobpit_rooms`, `distributed_game::celld_zone`). //! -//! - [`MobPitFactSink`] is the game's `FactSink`: optional artificial -//! latency (the "slow storage" toggle), then -//! `distributed_game::celld::CelldFactSink` (the command fact sink over a -//! remote-only celld command host) sends the fact over the internal path -//! to its cell — `crawler.record_kill` to `crawler/{principal}` -//! (`FactRoute::by_principal`), the runtime's -//! player lifecycle facts to `presence/{principal}` (`lifecycle_route`) — -//! then a fire-and-forget leaderboard update. The command id comes from -//! the fact key, so a retry replays through the cell's command ledger -//! instead of crediting twice; celld slow or down keeps facts in the -//! zone's queue (`RetryPolicy::until_settled`), never in a local store. -//! - Each kill commit also writes the `crawler.mob_killed` domain event to -//! the cell's outbox in the same cell transaction. celld drains it to the -//! `game-demo-outbox` Queue; the worker's consumer relays every message to -//! this server's authenticated `/internal/celld-queue/relay` -//! (`crate::common::relay`), which publishes it onto the projection bus. -//! `mobpit-service` and this server's [`super::directory`] project it -//! (the crawler list). [`CrawlerCells`] reads one cell by principal -//! (profiles, the board rebuild's kill histories). +//! Each kill commit writes the `crawler.mob_killed` domain event to the +//! cell's outbox in the same cell transaction. celld drains it to the +//! `game-demo-outbox` Queue; the worker's consumer relays every message to +//! this server's authenticated `/internal/celld-queue/relay` +//! (`crate::common::relay`), which publishes it onto the projection bus. +//! `mobpit-service` and this server's [`super::directory`] project it (the +//! crawler list, which feeds the leaderboard). [`CrawlerCells`] reads one +//! cell by principal (the board rebuild's kill histories, presence). -use std::collections::VecDeque; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; use std::time::Duration; use distributed::cell_host::{InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER}; -use distributed_game::celld::{CelldFactSink, FactRoute}; -use distributed_game::lifecycle::Lifecycle; -use distributed_game::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use super::board::Leaderboards; -use super::crawler::{KillReceipt, RecordKillInput, CRAWLER_KIND, PRESENCE_KIND, RECORD_KILL}; -use super::presence::Presence; +use super::crawler::{RecordKillInput, CRAWLER_KIND, PRESENCE_KIND}; +use distributed_game::celld::{CelldFactSink, FactRoute}; -/// Command-ledger service id for game facts. -pub const SERVICE_ID: &str = "mobpit"; -/// Principal for facts without a player (none are emitted today). -pub const SYSTEM_PRINCIPAL: &str = "mobpit-zone"; +/// Kill facts into the Crawler cells over celld's internal HTTP path, the +/// route a room uses object to object (tests and tools; rooms send theirs +/// from inside celld). Command-ledger service `mobpit-tools`. +pub fn kill_sink(celld: &CelldOptions) -> Result { + Ok(CelldFactSink::celld( + celld.url.clone(), + celld.secret.clone(), + "mobpit-tools", + "mobpit-tools", + )? + .route(FactRoute::by_principal::(CRAWLER_KIND))) +} pub use crate::common::CelldOptions; @@ -158,192 +150,3 @@ fn encode_segment(segment: &str) -> String { } encoded } - -/// A committed kill as the dev routes report it. -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct CommittedFact { - /// Fact idempotency key. - pub key: String, - /// Command input as committed (needed to replay the exact command). - pub input: serde_json::Value, - /// Receipt. - pub receipt: KillReceipt, - /// True when the ledger replayed an earlier commit. - pub replayed: bool, -} - -/// Counters of the fact sink. -#[derive(Debug, Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SinkStats { - /// Commit attempts started. - pub attempts: u64, - /// First-time commits. - pub committed: u64, - /// Ledger replays (same key seen again). - pub replayed: u64, - /// Failed attempts (retryable or permanent). - pub errors: u64, - /// Facts currently inside `commit` (incl. the artificial latency). - pub in_sink: u64, - /// Lifecycle facts settled in presence cells (not counted above). - pub presence: u64, -} - -/// Shared sink state (lives in the world). -#[derive(Default)] -pub struct SinkState { - latency_ms: AtomicU64, - stats: Mutex, - recent: Mutex>, -} - -impl SinkState { - /// Artificial storage latency. - pub fn latency(&self) -> Duration { - Duration::from_millis(self.latency_ms.load(Ordering::Relaxed)) - } - - /// Set the artificial storage latency (clamped to 5 s). - pub fn set_latency(&self, latency: Duration) -> Duration { - let ms = latency.as_millis().min(5_000) as u64; - self.latency_ms.store(ms, Ordering::Relaxed); - Duration::from_millis(ms) - } - - /// Counter snapshot. - pub fn stats(&self) -> SinkStats { - self.stats.lock().expect("stats").clone() - } - - /// Most recent commits, newest last (at most 64). - pub fn recent(&self) -> Vec { - self.recent - .lock() - .expect("recent") - .iter() - .cloned() - .collect() - } - - fn update(&self, f: impl FnOnce(&mut SinkStats)) { - f(&mut self.stats.lock().expect("stats")); - } -} - -/// The game's fact sink (cloned into every zone's fact worker). -#[derive(Clone)] -pub struct MobPitFactSink { - celld: CelldFactSink, - state: Arc, - board: Arc, - presence: Arc, -} - -impl MobPitFactSink { - /// Sink into the cells at `celld`, reporting into `state`, feeding - /// `board`, mirroring settled lifecycle facts into `presence`. - pub fn new( - celld: &CelldOptions, - state: Arc, - board: Arc, - presence: Arc, - ) -> Result { - let sink = CelldFactSink::celld( - celld.url.clone(), - celld.secret.clone(), - SERVICE_ID, - SYSTEM_PRINCIPAL, - )? - .route(FactRoute::by_principal::(CRAWLER_KIND)) - .lifecycle_route(PRESENCE_KIND); - Ok(Self { - celld: sink, - state, - board, - presence, - }) - } - - async fn commit_kill(&self, fact: &Fact) -> Result { - let latency = self.state.latency(); - if !latency.is_zero() { - tokio::time::sleep(latency).await; - } - if fact.principal().is_none() { - return Err(FactError::Permanent( - "kill facts need a player principal".into(), - )); - } - let receipt = self.celld.commit(fact).await?; - if fact.command() == RECORD_KILL { - if let Ok(kill) = serde_json::from_value::(receipt.payload.clone()) { - // Fire-and-forget: never awaits the leaderboard store. - self.board.submit_kill(&kill); - let mut recent = self.state.recent.lock().expect("recent"); - if recent.len() == 64 { - recent.pop_front(); - } - recent.push_back(CommittedFact { - key: fact.key().to_string(), - input: fact.input().clone(), - receipt: kill, - replayed: receipt.replayed, - }); - } - } - Ok(receipt) - } -} - -impl FactSink for MobPitFactSink { - fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { - Box::pin(async move { - // Runtime lifecycle facts go to the player's presence cell, not - // a Crawler cell (and not the kill counters); the settled ones - // are mirrored into the in-process presence view. - if let (Some(event), Some(principal)) = (Lifecycle::of(fact), fact.principal()) { - let receipt = self.celld.commit(fact).await?; - self.presence.apply(principal, fact.stamp(), &event); - self.state.update(|s| s.presence += 1); - return Ok(receipt); - } - self.state.update(|s| { - s.attempts += 1; - s.in_sink += 1; - }); - let result = self.commit_kill(fact).await; - self.state.update(|s| { - s.in_sink -= 1; - match &result { - Ok(r) if r.replayed => s.replayed += 1, - Ok(_) => s.committed += 1, - Err(_) => s.errors += 1, - } - }); - result - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shards_cannot_add_path_segments() { - assert_eq!(encode_segment("guest-0a1b"), "guest-0a1b"); - assert_eq!(encode_segment("odd:name"), "odd:name"); - assert_eq!(encode_segment("a/b c"), "a%2Fb%20c"); - } - - #[test] - fn options_require_http_and_a_strong_secret() { - assert!(CelldOptions::new("ftp://x", "test-only-secret-0123456789abcdef").is_err()); - assert!(CelldOptions::new("http://127.0.0.1:1", "short").is_err()); - let ok = - CelldOptions::new("http://127.0.0.1:1/", "test-only-secret-0123456789abcdef").unwrap(); - assert_eq!(ok.url, "http://127.0.0.1:1"); - } -} diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs index c56f16785..61e913186 100644 --- a/examples/game/server/src/mobpit/world.rs +++ b/examples/game/server/src/mobpit/world.rs @@ -1,29 +1,26 @@ -//! Process-wide Mob Pit state shared by the zones, the fact worker and the -//! dev routes: the celld cells (fact sink and reader), the sink's -//! latency/counters, the leaderboards, the projection bus and the crawler -//! directory projected from it. +//! Mob Pit's services next to the rooms: the celld cells reader, the +//! projection bus the outbox Queue relays onto, the crawler directory and +//! the rooms' zone status projected from it, and the leaderboards fed by +//! the directory. The rooms themselves run on celld (`mobpit_rooms`); this +//! process never hosts one. +use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, OnceLock}; use std::time::Duration; -use distributed_game::net::{GameServer, ServerConfig, ZoneFactory}; -use distributed_game::RetryPolicy; use serde_json::{json, Value}; use super::board::Leaderboards; use super::directory::CrawlerDirectory; -use super::presence::Presence; -use super::store::{CelldOptions, CrawlerCells, MobPitFactSink, SinkState}; -use super::zone::{MobPit, MobPitConfig}; -use super::{routes, MobPitDemo}; -use crate::common::relay::{relay_routes, ProjectionBus, ProjectionPublisher}; -use crate::common::{random_hex, Demo, DemoRoutes, Guests}; +use super::store::{CelldOptions, CrawlerCells}; +use crate::common::random_hex; +use crate::common::relay::{ProjectionBus, ProjectionPublisher}; use distributed::leaderboard::LeaderboardChangePublisher; +use crate::common::zone_status::ZoneStatusView; -/// Unsettled facts one zone may hold before `emit_fact` reports backpressure. -pub const FACT_CAPACITY: usize = 256; +/// Bus consumer group of the rooms' zone status projection here. +pub const ZONE_STATUS_CONSUMER: &str = "mobpit-rooms"; /// How to open the world. #[derive(Clone)] @@ -31,7 +28,7 @@ pub struct WorldOptions { /// Directory of local dev files (the persisted ticket secret, the /// default projection bus). Durable game state is in celld. pub data_dir: PathBuf, - /// celld serving `examples/game/cells`. + /// celld serving `examples/game/cells` (the rooms and their cells). pub celld: CelldOptions, /// `redis://…` for a Redis leaderboard; None = in memory. pub redis_url: Option, @@ -41,7 +38,8 @@ pub struct WorldOptions { /// with `mobpit-service`). Default: `sqlite:{data_dir}/bus.db`. pub projection_bus: Option, /// SQLite database of this server's read models (the crawler - /// directory). Default: `sqlite:{data_dir}/read-models.db`. + /// directory, the rooms' status). Default: + /// `sqlite:{data_dir}/read-models.db`. pub read_models: Option, } @@ -82,31 +80,24 @@ impl WorldOptions { } } -/// A loaded profile: principal and `(xp, level, kills)` (None = no cell yet). -pub type LoadedProfile = (String, Option<(u64, u32, u32)>); - /// See the module docs. pub struct MobPitWorld { boot: String, data_dir: PathBuf, celld: CelldOptions, cells: Arc, - sink: Arc, - fact_sink: MobPitFactSink, board: Arc, - zone_pending: AtomicUsize, - profiles: Arc>>, projection: Arc>, directory: OnceLock, - presence: Arc, + rooms: OnceLock, bus_url: String, read_models_url: String, } impl MobPitWorld { - /// Open the world over celld and attach its projection bus and crawler - /// directory ([`Self::attach_projection`]). Does not rebuild the board: - /// call [`Self::rebuild_board`]. + /// Open the world over celld and attach its projection bus, crawler + /// directory and room status ([`Self::attach_projection`]). Does not + /// rebuild the board: call [`Self::rebuild_board`]. pub async fn start(options: WorldOptions) -> Result, String> { let world = Self::open(options)?; world.attach_projection().await?; @@ -114,9 +105,8 @@ impl MobPitWorld { } /// Open the world over celld without its projection (the relay answers - /// 503 and the crawler list is unavailable until - /// [`Self::attach_projection`]). Must be called inside a Tokio runtime. - /// Does not contact celld (cells are reached on first use). + /// 503 until [`Self::attach_projection`]). Must be called inside a + /// Tokio runtime. Does not contact celld. pub fn open(options: WorldOptions) -> Result, String> { std::fs::create_dir_all(&options.data_dir) .map_err(|e| format!("create {}: {e}", options.data_dir.display()))?; @@ -129,36 +119,21 @@ impl MobPitWorld { &options.redis_prefix, Some(notices.listener()), )?; - let sink = Arc::new(SinkState::default()); - let presence = Arc::new(Presence::default()); - let fact_sink = MobPitFactSink::new( - &options.celld, - sink.clone(), - board.clone(), - presence.clone(), - )?; - let bus_url = options.bus_url(); - let read_models_url = options.read_models_url(); Ok(Arc::new(Self { - bus_url, - read_models_url, + bus_url: options.bus_url(), + read_models_url: options.read_models_url(), directory: OnceLock::new(), + rooms: OnceLock::new(), boot: random_hex(8), data_dir: options.data_dir, cells: Arc::new(CrawlerCells::new(&options.celld)?), celld: options.celld, - sink, - fact_sink, board, - zone_pending: AtomicUsize::new(0), - profiles: Arc::default(), projection, - presence, })) } - /// Random id of this server process (shown by clients to spot restarts; - /// fact keys use `Ctx::fact_key` / the boot epoch). + /// Random id of this server process. pub fn boot(&self) -> &str { &self.boot } @@ -168,7 +143,7 @@ impl MobPitWorld { &self.data_dir } - /// Where the cells are. + /// Where the rooms and cells are. pub fn celld(&self) -> &CelldOptions { &self.celld } @@ -178,39 +153,35 @@ impl MobPitWorld { &self.cells } - /// Sink latency and counters. - pub fn sink_state(&self) -> &Arc { - &self.sink - } - /// Leaderboards. pub fn board(&self) -> &Arc { &self.board } - /// Presence mirrored from the lifecycle facts settled in presence cells. - pub fn presence(&self) -> &Arc { - &self.presence - } - - /// The game's fact sink. - pub fn fact_sink(&self) -> MobPitFactSink { - self.fact_sink.clone() - } - /// Open the projection bus the outbox Queue relay publishes onto /// (`/internal/celld-queue/relay`; 503 until this runs, so the Queue - /// keeps the messages) and start projecting it into the crawler - /// directory. Call once. - pub async fn attach_projection(&self) -> Result<(), String> { + /// keeps the messages), project it into the crawler directory and the + /// rooms' status, and feed the board from the directory. Call once. + pub async fn attach_projection(self: &Arc) -> Result<(), String> { let bus = ProjectionBus::open(&self.bus_url).await?; let directory = CrawlerDirectory::open(&self.read_models_url, bus.pool().clone()).await?; + let rooms = ZoneStatusView::open( + &self.read_models_url, + bus.pool().clone(), + ZONE_STATUS_CONSUMER, + ) + .await?; self.directory .set(directory) .map_err(|_| "projection already attached".to_string())?; + self.rooms + .set(rooms) + .map_err(|_| "projection already attached".to_string())?; self.projection .set(bus) - .map_err(|_| "projection already attached".to_string()) + .map_err(|_| "projection already attached".to_string())?; + tokio::spawn(feed_board(Arc::downgrade(self))); + Ok(()) } /// The attached projection bus, if any. @@ -235,43 +206,6 @@ impl MobPitWorld { .ok_or_else(|| "no projection attached: the crawler list is unavailable".into()) } - pub(crate) fn set_zone_pending(&self, n: usize) { - self.zone_pending.store(n, Ordering::Relaxed); - } - - /// Facts emitted by the zone and not yet settled (incl. backpressure backlog). - pub fn zone_pending(&self) -> usize { - self.zone_pending.load(Ordering::Relaxed) - } - - /// Load `principal`'s cell on a background task; the zone picks the - /// result up with [`Self::take_loaded_profiles`] on a later tick. - pub fn request_profile(&self, principal: &str) { - let cells = self.cells.clone(); - let profiles = self.profiles.clone(); - let principal = principal.to_string(); - let Ok(handle) = tokio::runtime::Handle::try_current() else { - return; - }; - handle.spawn(async move { - let state = match cells.crawler(&principal).await { - Ok(view) => view.state, - Err(error) => { - eprintln!("mobpit: load profile {principal}: {error}"); - None - } - }; - profiles - .lock() - .expect("profiles") - .push((principal, state.map(|c| (c.xp, c.level, c.kills)))); - }); - } - - pub(crate) fn take_loaded_profiles(&self) -> Vec { - std::mem::take(&mut *self.profiles.lock().expect("profiles")) - } - /// Rebuild the leaderboards from the event history of every crawler in /// the directory (read from each one's cell). pub async fn rebuild_board(&self) -> Result { @@ -302,40 +236,59 @@ impl MobPitWorld { .collect()) } - /// Game server for `config` plus the Mob Pit dev and internal routes. - pub fn server( - self: &Arc, - config: ServerConfig, - guests: Guests, - ) -> (GameServer, DemoRoutes) { - let world = self.clone(); - let mut config = config; - // Joined / connection lost / reconnected / disconnected / left facts - // for the presence cells. - config.host.lifecycle_facts = true; - let server = GameServer::new( - config, - ZoneFactory::sync(move |activation| { - let zone_id = activation.zone_id.as_str(); - MobPitDemo::hosts_zone(zone_id).then(|| MobPitConfig { - guests: guests.clone(), - world: world.clone(), - }) - }), - ) - // celld down or slow: facts stay in the zone's queue until they - // settle (backpressure at capacity), never in a local store. - .with_fact_sink( - self.fact_sink(), - FACT_CAPACITY, - RetryPolicy::until_settled(Duration::from_millis(50), Duration::from_secs(2)), - ); - ( - server, - DemoRoutes { - dev: routes::routes(self.clone()), - internal: relay_routes(self.celld.secret.clone(), self.projection.clone()), - }, - ) + /// Every room the read model knows (`zone_activities` rows of + /// `pit.*`): its status (`active` / `dormant` / `hibernated`), players, + /// whether the activation restored a snapshot, and — a debug detail — + /// the celld node running it. + pub async fn rooms(&self) -> Result, String> { + let view = self + .rooms + .get() + .ok_or("no projection attached: room status is unavailable")?; + Ok(view + .activities("pit.") + .await? + .into_iter() + .filter_map(|row| { + let (x, y) = mobpit_rooms::parse_room(&row.zone_id)?; + Some(json!({ + "zone": row.zone_id, "x": x, "y": y, "status": row.status, + "players": row.players, "restored": row.restored, + "activations": row.activations, "node": row.node, + "changedAtMs": row.changed_at_ms, + })) + }) + .collect()) + } +} + +/// Keep the boards in step with the crawler directory: every change of a +/// crawler's totals becomes one idempotent `Max` update. +async fn feed_board(world: std::sync::Weak) { + let mut seen: HashMap = HashMap::new(); + loop { + tokio::time::sleep(Duration::from_millis(250)).await; + let Some(world) = world.upgrade() else { + return; + }; + let Ok(directory) = world.directory() else { + continue; + }; + let Ok(rows) = directory.list().await else { + continue; + }; + for row in rows { + let totals = (row.kills, row.xp); + if seen.get(&row.player_id) == Some(&totals) { + continue; + } + world.board.submit_totals( + &row.player_id, + &row.name, + u32::try_from(row.kills).unwrap_or(0), + u64::try_from(row.xp).unwrap_or(0), + ); + seen.insert(row.player_id, totals); + } } } diff --git a/examples/game/server/src/mobpit/zone.rs b/examples/game/server/src/mobpit/zone.rs index 7946f5e84..6577fd771 100644 --- a/examples/game/server/src/mobpit/zone.rs +++ b/examples/game/server/src/mobpit/zone.rs @@ -1,1371 +1,5 @@ -//! The Mob Pit zone: authoritative melee combat at 30 Hz. -//! -//! Movement reuses the Arena's step ([`crate::arena::movement`], same floor -//! and pillars) through [`pit_step`], the declared predicted step the client -//! runs as WebAssembly; combat is server-only. Entities: -//! -//! | kind | ids | fields | -//! |---|---|---| -//! | 1 `player` | 1000 + player | x y vx vy dash cd (predicted) · name hp face swing level dead | -//! | 2 `mob` | 1..=12 | x y face tier hp state tele | -//! | 3 `pillar` | 100 + i | x y r (global) | -//! | 4 `pit` | 900 | pending slowMs tickMs tickMaxMs workUs committed backlog (global) | -//! -//! Mob state machine (deterministic, zone RNG only for wander targets): -//! `idle` (wander near home) → `chase` (living player within aggro radius or -//! hit by one) → `windup` (in reach: stand still, telegraph ring for 0.8 s) → -//! damage everyone inside the ring → `recover` (0.6 s) → `chase`; beyond the -//! leash or target dead → `return` home → `idle`. Dead mobs respawn after 4 s -//! with a new generation. -//! -//! The zone is the aggregate; players, mobs and pillars are its entities -//! (each with an [`EntityId`]), and the kinds are `#[derive(Replicated)]` -//! views *projected* from them (`of = Player`, `#[from]` fields copied, the -//! rest derived in `impl Project<..>`): a mob's HP becomes a percent, its -//! windup timer the `tele` ring, a dead mob no view at all. The zone -//! registers its collections once ([`Zone::entities`]) and projects its own -//! HUD numbers ([`PitView`]); there is no hand-written `replicate()`. -//! Events are the typed [`PitEvent`], input the `#[derive(GameInput)]` -//! [`PitInput`]; the browser client is generated from [`game_surface`]. -//! -//! A kill emits a typed fact **without awaiting storage**: the cell -//! command's own input, [`RecordKillInput`] `{mob, tier, name}`, keyed by -//! `ctx.fact_with_key(&input, &[m{mob}, generation])` and emitted with -//! `ctx.emit_fact_for(killer)` — the host binds the killer's verified -//! principal and the handler decides the XP. The key is -//! `crawler.record_kill:{zone}:{boot_epoch}:m{mob}:{generation}`: the boot -//! epoch grows across restarts, so keys never collide with an earlier run's -//! facts (generations and ticks restart at 0). The settlement arrives in -//! [`Zone::on_fact_settled`] on a later tick and is pushed to the killer as -//! [`PitEvent::Saved`] + [`PitEvent::Profile`]. +//! The Mob Pit room zone lives in `mobpit_rooms` (portable: the cells +//! worker hosts each room as a celld Durable Object). Re-exported here for +//! the client surface (`run.sh gen`), the native tests and the bots. -use std::collections::{BTreeMap, HashMap, VecDeque}; -use std::sync::Arc; -use std::time::Instant; - -use distributed_game::{ - schema, ConsumePolicy, Ctx, EmitError, Entities, Entity, EntityId, EntitySchema, Fact, - FactOutcome, FactSettlement, GameEvent, GameInput, GameRecord, GameSurface, LeaveReason, - ObserverId, PlayerId, Project, Replicated, View, Zone, -}; - -use super::board::BoardSnapshot; -use super::crawler::{level_floor, KillReceipt, RecordKillInput}; -use super::world::MobPitWorld; -use crate::arena::movement::{self, MoveState, PILLARS, PLAYER_RADIUS}; -use crate::arena::{Pillar, PillarView}; -use crate::common::Guests; - -/// Entity id of the stats entity (the zone's own HUD view). -pub const PIT_ENTITY: EntityId = EntityId(900); - -/// A player: the Arena's predicted [`MoveState`] plus server-owned combat -/// state (replaced, never predicted, on the client). Projected from the -/// zone's `Player` entity: the move state is flattened, HP and level are -/// clamped, and its principal, credits and timers stay on the server. -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "player", id = 1, priority = 2.0, of = Player)] -pub struct PlayerView { - /// Position x. - #[field_type(movement::POS)] - #[correct(ease = 150)] - #[from(state.x)] - pub x: f32, - /// Position y. - #[field_type(movement::POS)] - #[correct(ease = 150)] - #[from(state.y)] - pub y: f32, - /// Velocity x. - #[field_type(movement::VEL)] - #[correct(snap)] - #[from(state.vx)] - pub vx: f32, - /// Velocity y. - #[field_type(movement::VEL)] - #[correct(snap)] - #[from(state.vy)] - pub vy: f32, - /// Remaining dash frames. - #[correct(snap)] - #[from(state.dash)] - pub dash: u8, - /// Remaining dash cooldown frames. - #[correct(snap)] - #[from(state.cd)] - pub cd: u8, - /// Display name. - #[priority(0.2)] - #[correct(replace)] - #[from] - pub name: String, - /// Hit points. - #[correct(replace)] - pub hp: u8, - /// Facing (rad). - #[angle(bits = 8)] - #[correct(replace)] - #[from] - pub face: f32, - /// Swing animation frames left. - #[correct(replace)] - pub swing: u8, - /// Level (from the durable cell). - #[correct(replace)] - pub level: u16, - /// Waiting to respawn. - #[correct(replace)] - pub dead: bool, -} - -/// A mob (dead mobs are not replicated); its home, target, generation and -/// wander point stay on the server. -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "mob", id = 2, of = Mob)] -pub struct MobView { - /// Position x. - #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] - #[from] - pub x: f32, - /// Position y. - #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] - #[from] - pub y: f32, - /// Facing (rad). - #[angle(bits = 8)] - #[from] - pub face: f32, - /// 1 grunt · 2 brute · 3 elite. - #[from] - pub tier: u8, - /// HP percent. - pub hp: u8, - /// 0 idle · 1 chase · 2 windup · 3 recover · 4 return. - pub state: u8, - /// Telegraph progress 0..=255 during a windup. - pub tele: u8, -} - -/// Zone numbers for the HUD (global), projected from the zone itself. -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "pit", id = 4, global, of = MobPit)] -pub struct PitView { - /// Facts emitted and not settled. - pub pending: u16, - /// Artificial storage latency (ms). - pub slow_ms: u16, - /// Tick interval EMA (ms). - pub tick_ms: f32, - /// Longest tick interval of the last 30 ticks (ms). - pub tick_max_ms: f32, - /// Tick work EMA (µs). - pub work_us: u32, - /// Settlements received. - pub committed: u32, - /// Facts waiting for backpressure to clear. - pub backlog: u16, -} - -/// A player's durable progress (from the cell on join, after each settlement). -#[derive(Debug, Clone, PartialEq, GameRecord)] -pub struct Profile { - /// Total XP. - pub xp: u64, - /// Level. - pub level: u32, - /// Kills. - pub kills: u32, - /// First XP of the level. - pub level_xp: u64, - /// First XP of the next level. - pub next_level_xp: u64, - /// `"cell"` (loaded on join) or `"settled"` (after a kill committed). - pub source: String, -} - -/// Mob Pit's events. -#[derive(Debug, Clone, PartialEq, GameEvent)] -pub enum PitEvent { - /// To a joining player. - #[game_event(id = 1)] - Hello { - /// Own entity id. - entity: u32, - /// Floor half extent (m). - half: f32, - /// Process boot id (changes on restart). - boot: String, - /// Melee reach (m). - attack_range: f32, - /// Cosine of the half cone angle. - attack_arc_cos: f32, - }, - /// Durable progress. - #[game_event(id = 2)] - Profile(Profile), - /// Broadcast the tick a mob dies (the fact is only queued). - #[game_event(id = 3)] - Kill { - /// Fact key. - key: String, - /// Mob entity id. - mob: u32, - /// Mob tier. - tier: u8, - /// Where it died. - x: f32, - /// Where it died. - y: f32, - /// Killer entity id. - killer: u32, - /// Killer display name. - killer_name: String, - }, - /// To the killer when its fact settled. - #[game_event(id = 4)] - Saved { - /// Fact key. - key: String, - /// Committed. - ok: bool, - /// The cell recognised the key (replayed receipt). - replayed: bool, - /// XP credited by this kill (decided by the cell). - xp: u32, - /// Total XP after it. - total_xp: u64, - /// Kills after it. - kills: u32, - /// Level after it. - level: u32, - /// Time from emit to settlement (ms). - waited_ms: u32, - /// Where the mob died. - x: f32, - /// Where the mob died. - y: f32, - /// Failure, if any. - error: Option, - /// Commit attempts (failures). - attempts: u32, - }, - /// Leaderboard snapshot (on join and whenever it changes). - #[game_event(id = 5)] - Board(BoardSnapshot), - /// To a player that died. - #[game_event(id = 6)] - Died { - /// Respawn delay (ms). - respawn_ms: u32, - }, -} - -/// Mob Pit's client surface (also used by the leaderboard page). -pub fn game_surface() -> GameSurface { - GameSurface::for_zone::("mobpit") - .events::() - .predict::() - .constant("pit_rules", &pit_rules()) -} - -pub use game_sim::mobpit::{pit_step, PitInput, PitStep}; - -/// Input bit: attack (bit 0 is the Arena's dash). -pub const BUTTON_ATTACK: u8 = PitInput::ATTACK; -/// Melee reach (m, from the player's centre to the mob's edge). -pub const ATTACK_RANGE: f32 = 2.2; -/// Cosine of the half cone angle (60°). -pub const ATTACK_ARC_COS: f32 = 0.5; -/// Damage per swing. -pub const ATTACK_DAMAGE: i32 = 10; -/// Swing cooldown (ticks). -pub const SWING_COOLDOWN: u8 = 13; -/// Swing animation length (ticks). -const SWING_FRAMES: u8 = 6; -/// Player max HP. -pub const PLAYER_HP: i32 = 100; -/// Number of mobs. -pub const MOBS: usize = 12; -const MAX_CREDITS: u8 = 4; -const VIEW_RADIUS: f32 = 40.0; -const AGGRO: f32 = 7.0; -const LEASH: f32 = 15.0; -const WINDUP_TICKS: u16 = 24; -const RECOVER_TICKS: u16 = 18; -const RESPAWN_TICKS: u64 = 120; -const PLAYER_RESPAWN_TICKS: u64 = 90; - -/// Mob tier stats: (max hp, speed m/s, damage, radius, telegraph radius). -fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { - match tier { - 3 => (100, 3.3, 24, 0.8, 2.6), - 2 => (60, 2.4, 16, 0.7, 2.2), - _ => (30, 3.0, 9, 0.5, 1.8), - } -} - -/// Mob tiers (1..=3). -pub const TIERS: [u8; 3] = [1, 2, 3]; -/// Names of the `mob` kind's `state` values, by value. -pub const MOB_STATES: [&str; 6] = ["idle", "chase", "windup", "recover", "return", "dead"]; - -/// What the page draws of a mob tier (from [`tier_stats`]). -#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] -pub struct MobTier { - /// Tier (the `mob` kind's `tier`). - pub tier: u8, - /// Body radius (m). - pub radius: f32, - /// Telegraph radius (m). - pub tele: f32, -} - -/// Mob Pit rules the client draws with (generated `PIT_RULES`). -#[derive(Debug, Clone, PartialEq, GameRecord)] -pub struct PitRules { - /// Every tier. - pub tiers: Vec, - /// `state` names by value. - pub states: Vec, - /// Melee reach (m, from the player's centre to the mob's edge). - pub attack_range: f32, - /// Half angle of the swing cone (radians). - pub attack_half_angle: f32, - /// Swing animation length (ticks; the player's `swing` counts down from it). - pub swing_frames: u8, -} - -/// The `PIT_RULES` constant. -pub fn pit_rules() -> PitRules { - PitRules { - tiers: TIERS - .iter() - .map(|&tier| { - let (_, _, _, radius, tele) = tier_stats(tier); - MobTier { tier, radius, tele } - }) - .collect(), - states: MOB_STATES.map(String::from).to_vec(), - attack_range: ATTACK_RANGE, - attack_half_angle: ATTACK_ARC_COS.acos(), - swing_frames: SWING_FRAMES, - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum MobState { - Idle = 0, - Chase = 1, - Windup = 2, - Recover = 3, - Return = 4, - Dead = 5, -} - -struct Mob { - id: EntityId, - tier: u8, - home: (f32, f32), - x: f32, - y: f32, - face: f32, - hp: i32, - state: MobState, - timer: u16, - target: Option, - generation: u32, - respawn_at: u64, - wander: (f32, f32), -} - -struct Player { - id: EntityId, - principal: String, - name: String, - state: MoveState, - credits: u8, - hp: i32, - face: f32, - swing_cd: u8, - swing_anim: u8, - dead_until: Option, - level: u32, - regen: u8, -} - -struct PendingKill { - principal: String, - x: f32, - y: f32, - emitted: Instant, -} - -/// Zone construction parameters. -#[derive(Clone)] -pub struct MobPitConfig { - /// Display names from the dev ticket endpoint. - pub guests: Guests, - /// Durable cells, fact sink state and leaderboards. - pub world: Arc, -} - -/// The Mob Pit zone. -pub struct MobPit { - guests: Guests, - world: Arc, - players: BTreeMap, - mobs: Vec, - pillars: Vec, - pending: HashMap, - /// Facts refused by backpressure, retried each tick (oldest first). - backlog: VecDeque<(PlayerId, Fact, f32, f32)>, - board_version: u64, - last_tick: Option, - tick_ms: f32, - tick_max_ms: f32, - tick_max_window: f32, - window_ticks: u32, - work_us: f32, - committed: u32, -} - -/// Mob homes on two rings between the pillars, tiers by index. -fn mob_layout() -> Vec<(u8, (f32, f32))> { - let mut out = Vec::with_capacity(MOBS); - for i in 0..MOBS { - let ring = if i % 2 == 0 { 11.5 } else { 16.0 }; - let a = (i as f32 + 0.5) / MOBS as f32 * std::f32::consts::TAU; - let tier = match i { - 0 => 3, - 3 | 6 | 9 | 11 => 2, - _ => 1, - }; - out.push((tier, (ring * a.cos(), ring * a.sin()))); - } - out -} - -fn spawn_point(player: PlayerId) -> (f32, f32) { - const SPOTS: [(f32, f32); 6] = [ - (-4.5, -4.5), - (4.5, -4.5), - (4.5, 4.5), - (-4.5, 4.5), - (0.0, -5.5), - (0.0, 5.5), - ]; - SPOTS[player.0 as usize % SPOTS.len()] -} - -fn push_out_of_pillars(x: &mut f32, y: &mut f32, radius: f32) { - for (px, py, pr) in PILLARS { - let (ox, oy) = (*x - px, *y - py); - let d2 = ox * ox + oy * oy; - let min = radius + pr; - if d2 < min * min { - let d = d2.sqrt().max(1e-4); - *x = px + ox / d * min; - *y = py + oy / d * min; - } - } - let lim = movement::HALF - radius; - *x = x.clamp(-lim, lim); - *y = y.clamp(-lim, lim); -} - -fn step_toward(x: &mut f32, y: &mut f32, tx: f32, ty: f32, stride: f32) -> f32 { - let (dx, dy) = (tx - *x, ty - *y); - let d = (dx * dx + dy * dy).sqrt(); - if d > 1e-4 { - let s = stride.min(d); - *x += dx / d * s; - *y += dy / d * s; - } - dy.atan2(dx) -} - -fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { - ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() -} - -impl MobPit { - fn profile_event(xp: u64, level: u32, kills: u32, source: &str) -> PitEvent { - PitEvent::Profile(Profile { - xp, - level, - kills, - level_xp: level_floor(level), - next_level_xp: level_floor(level + 1), - source: source.into(), - }) - } - - fn player_by_principal(&self, principal: &str) -> Option { - self.players - .iter() - .find(|(_, p)| p.principal == principal) - .map(|(id, _)| *id) - } - - fn emit_kill(&mut self, ctx: &mut Ctx<'_, Self>, killer: PlayerId, mob: usize) { - let m = &self.mobs[mob]; - let (x, y, tier, id, generation) = (m.x, m.y, m.tier, m.id.get(), m.generation); - let Some(player) = self.players.get(&killer) else { - return; - }; - // The cell command's own input: what died, never who or how much XP. - let input = RecordKillInput { - mob: format!("{}/m{id}", ctx.zone_id()), - tier, - name: player.name.clone(), - }; - let Ok(fact) = ctx.fact_with_key(&input, &[&format_args!("m{id}"), &generation]) else { - return; - }; - let key = fact.key().to_string(); - ctx.broadcast(&PitEvent::Kill { - key, - mob: id, - tier, - x, - y, - killer: player.id.get(), - killer_name: player.name.clone(), - }); - self.backlog.push_back((killer, fact, x, y)); - self.flush_backlog(ctx); - } - - /// Hand queued facts to the host; never blocks. Backpressure keeps the - /// rest for the next tick. - fn flush_backlog(&mut self, ctx: &mut Ctx<'_, Self>) { - while let Some((player, fact, x, y)) = self.backlog.pop_front() { - let key = fact.key().to_string(); - match ctx.emit_fact_for(player, fact.clone()) { - Ok(()) => { - let principal = self - .players - .get(&player) - .map(|p| p.principal.clone()) - .unwrap_or_default(); - self.pending.insert( - key, - PendingKill { - principal, - x, - y, - emitted: Instant::now(), - }, - ); - } - Err(EmitError::Backpressure) => { - self.backlog.push_front((player, fact, x, y)); - return; - } - // The killer left before the fact could be queued, or the key - // is already in flight: nothing durable to do. - Err(_) => {} - } - } - } - - fn step_players(&mut self, ctx: &mut Ctx<'_, Self>) -> Vec<(PlayerId, f32, f32, f32)> { - let tick = ctx.tick(); - let mut swings = Vec::new(); - for (id, p) in &mut self.players { - p.credits = (p.credits + 1).min(MAX_CREDITS); - p.swing_cd = p.swing_cd.saturating_sub(1); - p.swing_anim = p.swing_anim.saturating_sub(1); - if let Some(until) = p.dead_until { - // Dead: inputs are consumed but ignored. - let _ = ctx.take_inputs(*id, ConsumePolicy::Drain); - if tick >= until { - let (x, y) = spawn_point(*id); - p.state = MoveState { - x, - y, - ..MoveState::default() - }; - p.hp = PLAYER_HP; - p.dead_until = None; - } - continue; - } - while p.credits > 0 { - let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { - break; - }; - let input = input.input; - // The declared predicted step: what the client runs as WASM. - p.state = pit_step(&p.state, &input, &(), movement::DT); - p.credits -= 1; - let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); - if sx * sx + sy * sy > 20.0 * 20.0 { - p.face = sy.atan2(sx); - } - if input.attack() && p.swing_cd == 0 { - p.swing_cd = SWING_COOLDOWN; - p.swing_anim = SWING_FRAMES; - swings.push((*id, p.state.x, p.state.y, p.face)); - } - } - p.regen = p.regen.wrapping_add(1); - if p.regen % 15 == 0 && p.hp < PLAYER_HP { - p.hp += 1; - } - ctx.set_view(*id, View::new(p.state.x, p.state.y, VIEW_RADIUS)); - } - swings - } - - fn resolve_swings(&mut self, ctx: &mut Ctx<'_, Self>, swings: Vec<(PlayerId, f32, f32, f32)>) { - for (player, x, y, face) in swings { - let (fx, fy) = (face.cos(), face.sin()); - for i in 0..self.mobs.len() { - let m = &mut self.mobs[i]; - if m.state == MobState::Dead { - continue; - } - let (_, _, _, radius, _) = tier_stats(m.tier); - let (dx, dy) = (m.x - x, m.y - y); - let d = (dx * dx + dy * dy).sqrt(); - if d > ATTACK_RANGE + radius { - continue; - } - let cos = if d < 1e-3 { - 1.0 - } else { - (dx * fx + dy * fy) / d - }; - if cos < ATTACK_ARC_COS && d > radius + PLAYER_RADIUS { - continue; - } - m.hp -= ATTACK_DAMAGE; - if matches!(m.state, MobState::Idle | MobState::Return) { - m.state = MobState::Chase; - m.target = Some(player); - } - if m.hp <= 0 { - m.hp = 0; - m.state = MobState::Dead; - m.respawn_at = ctx.tick() + RESPAWN_TICKS; - m.target = None; - self.emit_kill(ctx, player, i); - } - } - } - } - - fn step_mobs(&mut self, ctx: &mut Ctx<'_, Self>) { - let dt = ctx.dt_secs(); - let tick = ctx.tick(); - let living: Vec<(PlayerId, f32, f32)> = self - .players - .iter() - .filter(|(_, p)| p.dead_until.is_none()) - .map(|(id, p)| (*id, p.state.x, p.state.y)) - .collect(); - let mut hits: Vec<(PlayerId, i32)> = Vec::new(); - for i in 0..self.mobs.len() { - let (max_hp, speed, damage, radius, tele) = tier_stats(self.mobs[i].tier); - let target_pos = |t: Option| { - t.and_then(|t| living.iter().find(|(id, _, _)| *id == t)) - .map(|(_, x, y)| (*x, *y)) - }; - let m = &mut self.mobs[i]; - match m.state { - MobState::Dead => { - if tick >= m.respawn_at { - m.generation += 1; - m.hp = max_hp; - (m.x, m.y) = m.home; - m.state = MobState::Idle; - } - continue; - } - MobState::Idle => { - let nearest = living - .iter() - .map(|(id, x, y)| (*id, dist((m.x, m.y), (*x, *y)))) - .filter(|(_, d)| *d < AGGRO) - .min_by(|a, b| a.1.total_cmp(&b.1)); - if let Some((id, _)) = nearest { - m.state = MobState::Chase; - m.target = Some(id); - } else if dist((m.x, m.y), m.wander) < 0.3 { - let a = ctx.rng().next_f32() * std::f32::consts::TAU; - let r = ctx.rng().next_f32() * 2.5; - let m = &mut self.mobs[i]; - m.wander = (m.home.0 + r * a.cos(), m.home.1 + r * a.sin()); - } else { - let (wx, wy) = m.wander; - m.face = step_toward(&mut m.x, &mut m.y, wx, wy, 1.0 * dt); - } - } - MobState::Chase => match target_pos(m.target) { - Some((tx, ty)) if dist(m.home, (m.x, m.y)) < LEASH => { - let reach = radius + PLAYER_RADIUS + 0.6; - if dist((m.x, m.y), (tx, ty)) <= reach { - m.state = MobState::Windup; - m.timer = WINDUP_TICKS; - m.face = (ty - m.y).atan2(tx - m.x); - } else { - m.face = step_toward(&mut m.x, &mut m.y, tx, ty, speed * dt); - } - } - _ => { - m.state = MobState::Return; - m.target = None; - } - }, - MobState::Windup => { - m.timer = m.timer.saturating_sub(1); - if m.timer == 0 { - for (id, x, y) in &living { - if dist((m.x, m.y), (*x, *y)) <= tele + PLAYER_RADIUS * 0.5 { - hits.push((*id, damage)); - } - } - m.state = MobState::Recover; - m.timer = RECOVER_TICKS; - } - } - MobState::Recover => { - m.timer = m.timer.saturating_sub(1); - if m.timer == 0 { - m.state = MobState::Chase; - } - } - MobState::Return => { - let (hx, hy) = m.home; - m.face = step_toward(&mut m.x, &mut m.y, hx, hy, speed * 1.3 * dt); - m.hp = (m.hp + 1).min(max_hp); - if dist((m.x, m.y), m.home) < 0.3 { - m.state = MobState::Idle; - m.wander = m.home; - } - } - } - let m = &mut self.mobs[i]; - push_out_of_pillars(&mut m.x, &mut m.y, radius); - } - // Light separation so a pack does not stack on one spot. - for i in 0..self.mobs.len() { - for j in (i + 1)..self.mobs.len() { - let (a, b) = (&self.mobs[i], &self.mobs[j]); - if a.state == MobState::Dead || b.state == MobState::Dead { - continue; - } - let min = tier_stats(a.tier).3 + tier_stats(b.tier).3; - let (dx, dy) = (b.x - a.x, b.y - a.y); - let d = (dx * dx + dy * dy).sqrt(); - if d < min && d > 1e-4 { - let push = (min - d) * 0.5; - let (nx, ny) = (dx / d * push, dy / d * push); - self.mobs[i].x -= nx; - self.mobs[i].y -= ny; - self.mobs[j].x += nx; - self.mobs[j].y += ny; - } - } - } - for (id, damage) in hits { - let Some(p) = self.players.get_mut(&id) else { - continue; - }; - if p.dead_until.is_some() { - continue; - } - p.hp -= damage; - if p.hp <= 0 { - p.hp = 0; - p.state.vx = 0.0; - p.state.vy = 0.0; - p.dead_until = Some(tick + PLAYER_RESPAWN_TICKS); - for m in &mut self.mobs { - if m.target == Some(id) { - m.target = None; - } - } - ctx.send( - id, - &PitEvent::Died { - respawn_ms: (PLAYER_RESPAWN_TICKS * 1000 / 30) as u32, - }, - ); - } - } - } - - fn deliver_profiles(&mut self, ctx: &mut Ctx<'_, Self>) { - for (principal, crawler) in self.world.take_loaded_profiles() { - let Some(id) = self.player_by_principal(&principal) else { - continue; - }; - let (xp, level, kills) = crawler.unwrap_or((0, 1, 0)); - if let Some(p) = self.players.get_mut(&id) { - p.level = level; - } - ctx.send(id, &Self::profile_event(xp, level, kills, "cell")); - } - } - - fn push_board(&mut self, ctx: &mut Ctx<'_, Self>) { - let version = self.world.board().version(); - if version != self.board_version { - self.board_version = version; - let snapshot = self.world.board().snapshot(); - ctx.broadcast(&PitEvent::Board((*snapshot).clone())); - } - } - - fn measure_tick(&mut self) { - let now = Instant::now(); - if let Some(last) = self.last_tick { - let ms = now.duration_since(last).as_secs_f32() * 1000.0; - self.tick_ms = if self.tick_ms == 0.0 { - ms - } else { - self.tick_ms * 0.9 + ms * 0.1 - }; - self.tick_max_window = self.tick_max_window.max(ms); - self.window_ticks += 1; - if self.window_ticks >= 30 { - self.tick_max_ms = self.tick_max_window; - self.tick_max_window = 0.0; - self.window_ticks = 0; - } - } - self.last_tick = Some(now); - } -} - -impl Zone for MobPit { - type Config = MobPitConfig; - type Input = PitInput; - type Timer = (); - type Message = distributed_game::NoMessages; - - fn schema() -> EntitySchema { - schema![PlayerView, MobView, PillarView, PitView] - } - - fn entities() -> Entities { - Entities::new() - .each(|z: &Self| &z.players) - .each(|z: &Self| &z.mobs) - .each(|z: &Self| &z.pillars) - .one(|z: &Self| z) - } - - fn on_create(_ctx: &mut Ctx<'_, Self>, config: MobPitConfig) -> Self { - let mobs = mob_layout() - .into_iter() - .enumerate() - .map(|(i, (tier, home))| Mob { - id: EntityId(i as u32 + 1), - tier, - home, - x: home.0, - y: home.1, - face: 0.0, - hp: tier_stats(tier).0, - state: MobState::Idle, - timer: 0, - target: None, - generation: 0, - respawn_at: 0, - wander: home, - }) - .collect(); - Self { - guests: config.guests, - world: config.world, - players: BTreeMap::new(), - mobs, - pillars: Pillar::all(), - pending: HashMap::new(), - backlog: VecDeque::new(), - board_version: u64::MAX, - last_tick: None, - tick_ms: 0.0, - tick_max_ms: 0.0, - tick_max_window: 0.0, - window_ticks: 0, - work_us: 0.0, - committed: 0, - } - } - - fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { - let (principal, ticket_name) = ctx - .player(player) - .map(|p| (p.principal.clone(), p.name.clone())) - .unwrap_or_default(); - // A dev guest's registered name, else the name the ticket issuer - // vouched for (e.g. a SvelteKit session), else the principal. - let name = self - .guests - .name(&principal) - .or(ticket_name) - .unwrap_or_else(|| principal.clone()); - let (x, y) = spawn_point(player); - let entity = EntityId(1000 + player.0); - self.players.insert( - player, - Player { - id: entity, - principal: principal.clone(), - name, - state: MoveState { - x, - y, - ..MoveState::default() - }, - credits: MAX_CREDITS, - hp: PLAYER_HP, - face: 0.0, - swing_cd: 0, - swing_anim: 0, - dead_until: None, - level: 1, - regen: 0, - }, - ); - ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); - ctx.send( - player, - &PitEvent::Hello { - entity: entity.get(), - half: movement::HALF, - boot: self.world.boot().to_string(), - attack_range: ATTACK_RANGE, - attack_arc_cos: ATTACK_ARC_COS, - }, - ); - ctx.send( - player, - &PitEvent::Board((*self.world.board().snapshot()).clone()), - ); - // Read path: load the durable cell off the tick; delivered later. - self.world.request_profile(&principal); - } - - fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { - self.players.remove(&player); - for m in &mut self.mobs { - if m.target == Some(player) { - m.target = None; - } - } - } - - fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { - ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); - ctx.send( - observer, - &PitEvent::Board((*self.world.board().snapshot()).clone()), - ); - } - - fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - PitInput::from_payload(payload) - } - - fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { - self.measure_tick(); - let work = Instant::now(); - self.deliver_profiles(ctx); - let swings = self.step_players(ctx); - self.resolve_swings(ctx, swings); - self.step_mobs(ctx); - self.flush_backlog(ctx); - self.push_board(ctx); - self.world - .set_zone_pending(ctx.facts_in_flight() + self.backlog.len()); - let us = work.elapsed().as_secs_f32() * 1e6; - self.work_us = if self.work_us == 0.0 { - us - } else { - self.work_us * 0.9 + us * 0.1 - }; - } - - fn on_fact_settled(&mut self, ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { - // The host's own lifecycle facts (presence) are not kills. - if distributed_game::lifecycle::LIFECYCLE_COMMANDS.contains(&settlement.command.as_str()) { - return; - } - let pending = self.pending.remove(&settlement.key); - let (principal, x, y, waited_ms) = match &pending { - Some(p) => ( - p.principal.clone(), - p.x, - p.y, - p.emitted.elapsed().as_millis().min(u128::from(u32::MAX)) as u32, - ), - None => (String::new(), 0.0, 0.0, 0), - }; - let player = self.player_by_principal(&principal); - match settlement.outcome { - FactOutcome::Committed(receipt) => { - self.committed += 1; - let Ok(kill) = receipt.payload_as::() else { - return; - }; - let Some(player) = player else { return }; - if let Some(p) = self.players.get_mut(&player) { - p.level = kill.level; - } - ctx.send( - player, - &PitEvent::Saved { - key: settlement.key, - ok: true, - replayed: receipt.replayed, - xp: kill.xp, - total_xp: kill.total_xp, - kills: kill.kills, - level: kill.level, - waited_ms, - x, - y, - error: None, - attempts: 0, - }, - ); - ctx.send( - player, - &Self::profile_event(kill.total_xp, kill.level, kill.kills, "settled"), - ); - } - FactOutcome::Failed { error, attempts } => { - if let Some(player) = player { - ctx.send( - player, - &PitEvent::Saved { - key: settlement.key, - ok: false, - replayed: false, - xp: 0, - total_xp: 0, - kills: 0, - level: 0, - waited_ms, - x, - y, - error: Some(format!("{error:?}")), - attempts, - }, - ); - } - } - } - } - - fn has_pending_work(&self) -> bool { - !self.backlog.is_empty() - } -} - -impl Entity for Player { - fn entity_id(&self) -> EntityId { - self.id - } -} - -impl Project for Player { - fn view(&self) -> Option { - Some(PlayerView::project( - self, - PlayerViewRest { - hp: self.hp.clamp(0, 255) as u8, - swing: self.swing_anim, - level: self.level.min(u32::from(u16::MAX)) as u16, - dead: self.dead_until.is_some(), - }, - )) - } -} - -impl Entity for Mob { - fn entity_id(&self) -> EntityId { - self.id - } -} - -impl Project for Mob { - fn view(&self) -> Option { - if self.state == MobState::Dead { - return None; - } - let max_hp = tier_stats(self.tier).0; - let tele = if self.state == MobState::Windup { - 255 - (u32::from(self.timer) * 255 / u32::from(WINDUP_TICKS)) - } else { - 0 - }; - Some(MobView::project( - self, - MobViewRest { - hp: (self.hp.max(0) * 100 / max_hp) as u8, - state: self.state as u8, - tele: tele as u8, - }, - )) - } -} - -impl Entity for MobPit { - fn entity_id(&self) -> EntityId { - PIT_ENTITY - } -} - -impl Project for MobPit { - fn view(&self) -> Option { - let clamp16 = |n: usize| n.min(65_535) as u16; - Some(PitView::project( - self, - PitViewRest { - pending: clamp16(self.pending.len()), - slow_ms: self.world.sink_state().latency().as_millis().min(65_535) as u16, - tick_ms: self.tick_ms, - tick_max_ms: self.tick_max_ms, - work_us: self.work_us as u32, - committed: self.committed, - backlog: clamp16(self.backlog.len()), - }, - )) - } -} - -/// Zone numbers for tests and tooling (`GameServer::inspect`). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct PitStats { - /// Facts emitted and not yet settled (incl. backpressure backlog). - pub pending: usize, - /// Tick interval EMA (ms). - pub tick_ms: f32, - /// Longest tick interval of the last 30 ticks (ms). - pub tick_max_ms: f32, - /// Settlements received. - pub committed: u32, - /// Living mobs. - pub mobs_alive: usize, - /// Players. - pub players: usize, -} - -impl MobPit { - /// Current numbers. - pub fn stats(&self) -> PitStats { - PitStats { - pending: self.pending.len() + self.backlog.len(), - tick_ms: self.tick_ms, - tick_max_ms: self.tick_max_ms, - committed: self.committed, - mobs_alive: self - .mobs - .iter() - .filter(|m| m.state != MobState::Dead) - .count(), - players: self.players.len(), - } - } -} - -/// Bot payload: the direction as a move plus attack always held. -pub fn encode_bot_input(dir: [f32; 2]) -> Vec { - let axis = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8; - PitInput { - mx: axis(dir[0]), - my: axis(dir[1]), - buttons: PitInput::ATTACK, - } - .to_payload() -} - -/// Golden test for the projected views (gr-p16): the hand-written -/// `replicate()` loop Mob Pit used before its views were projected from -/// registered entity collections, kept verbatim as the reference. A real -/// host runs a fight (deaths, windups, respawns); every tick the world the -/// runtime projects must equal the legacy one, entity for entity, and the -/// Delta frames built from each must be byte-identical. -#[cfg(test)] -mod projection_golden { - use std::sync::Arc; - use std::time::Duration; - - use distributed_game::replication::{ClientReplica, EncodedWorld}; - use distributed_game::{ - HostConfig, InterestConfig, ManualClock, Role, TicketClaims, Viewer, WorldView, ZoneHost, - }; - - use super::*; - use crate::mobpit::{MobPitWorld, WorldOptions}; - - /// The pre-gr-p16 `MobPit::replicate`, unchanged. - fn legacy_replicate(pit: &MobPit, out: &mut WorldView) { - for p in pit.players.values() { - let s = p.state; - let view = PlayerView { - x: s.x, - y: s.y, - vx: s.vx, - vy: s.vy, - dash: s.dash, - cd: s.cd, - name: p.name.clone(), - hp: p.hp.clamp(0, 255) as u8, - face: p.face, - swing: p.swing_anim, - level: p.level.min(u32::from(u16::MAX)) as u16, - dead: p.dead_until.is_some(), - }; - out.add(u32::from(p.id), &view); - } - for m in &pit.mobs { - if m.state == MobState::Dead { - continue; - } - let max_hp = tier_stats(m.tier).0; - let tele = if m.state == MobState::Windup { - 255 - (u32::from(m.timer) * 255 / u32::from(WINDUP_TICKS)) - } else { - 0 - }; - let view = MobView { - x: m.x, - y: m.y, - face: m.face, - tier: m.tier, - hp: (m.hp.max(0) * 100 / max_hp) as u8, - state: m.state as u8, - tele: tele as u8, - }; - out.add(u32::from(m.id), &view); - } - for (i, (x, y, r)) in PILLARS.iter().enumerate() { - out.add( - 100 + i as u32, - &PillarView { - x: *x, - y: *y, - r: *r, - }, - ); - } - let clamp16 = |n: usize| n.min(65_535) as u16; - let stats = PitView { - pending: clamp16(pit.pending.len()), - slow_ms: pit.world.sink_state().latency().as_millis().min(65_535) as u16, - tick_ms: pit.tick_ms, - tick_max_ms: pit.tick_max_ms, - work_us: pit.work_us as u32, - committed: pit.committed, - backlog: clamp16(pit.backlog.len()), - }; - out.add(PIT_ENTITY, &stats); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn projected_world_and_delta_bytes_match_the_legacy_replicate() { - let celld = crate::mobpit::store::CelldOptions::new( - "http://127.0.0.1:9", - "test-only-unreachable-celld-0123456789", - ) - .unwrap(); - let world = MobPitWorld::open(WorldOptions::temporary(celld)).unwrap(); - let clock = ManualClock::new(); - let mut host = ZoneHost::::new( - "pit-1", - HostConfig { - boot_epoch: 7, - ..HostConfig::default() - }, - Arc::new(clock.clone()), - MobPitConfig { - guests: Guests::default(), - world, - }, - ); - let mut clients = Vec::new(); - for name in ["ana", "bo", "cy"] { - let claims = TicketClaims::new(name, "pit-1", u64::MAX, name, Role::Player); - let joined = host.join(&claims, 0, "").unwrap(); - let Viewer::Player(player) = joined.viewer else { - panic!("player") - }; - clients.push((joined.client, player)); - } - let schema = MobPit::schema(); - let interest = InterestConfig::default(); - let (mut legacy_replica, mut projected_replica) = - (ClientReplica::new(), ClientReplica::new()); - let (mut saw_dead, mut saw_windup, mut saw_hurt_player) = (false, false, false); - for tick in 0..900u32 { - for (i, (client, player)) in clients.iter().enumerate() { - // Walk toward the nearest living mob, swinging all the time. - let me = host.zone().players[player].state; - let target = host - .zone() - .mobs - .iter() - .filter(|m| m.state != MobState::Dead) - .min_by(|a, b| { - dist((me.x, me.y), (a.x, a.y)).total_cmp(&dist((me.x, me.y), (b.x, b.y))) - }) - .map(|m| (m.x, m.y)) - .unwrap_or((0.0, 0.0)); - let (dx, dy) = (target.0 - me.x, target.1 - me.y); - let d = (dx * dx + dy * dy).sqrt().max(1e-3); - let wobble = if (tick / 40 + i as u32).is_multiple_of(3) { - 0.4 - } else { - 1.0 - }; - let payload = PitInput { - mx: (dx / d * 127.0 * wobble) as i8, - my: (dy / d * 127.0 * wobble) as i8, - buttons: PitInput::ATTACK, - } - .to_payload(); - host.push_input(*client, tick + 1, tick, &payload); - } - clock.advance(Duration::from_micros(33_334)); - host.advance(); - host.drain_outbound(); - - let mut legacy = WorldView::default(); - legacy_replicate(host.zone(), &mut legacy); - let projected = host.world_view(); - assert_eq!(projected.entities(), legacy.entities(), "tick {tick}"); - - let view = host.zone().players[&clients[0].1].state; - let view = View::new(view.x, view.y, VIEW_RADIUS); - let frame = |replica: &mut ClientReplica, world: WorldView| { - let encoded = EncodedWorld::build(&schema, world, &interest); - replica - .build_delta(&schema, &encoded, &interest, &view, 1200, tick, tick) - .0 - }; - assert_eq!( - frame(&mut projected_replica, projected), - frame(&mut legacy_replica, legacy), - "delta bytes at tick {tick}" - ); - - let pit = host.zone(); - saw_dead |= pit.mobs.iter().any(|m| m.state == MobState::Dead); - saw_windup |= pit - .mobs - .iter() - .any(|m| m.state == MobState::Windup && m.timer > 0); - saw_hurt_player |= pit.players.values().any(|p| p.hp < PLAYER_HP); - } - assert!(saw_dead, "a mob died (its view is omitted)"); - assert!(saw_windup, "a mob telegraphed (derived `tele`)"); - assert!(saw_hurt_player, "a player took damage"); - } -} +pub use mobpit_rooms::*; diff --git a/examples/game/server/src/predict_trace.rs b/examples/game/server/src/predict_trace.rs index f532af6fe..e2082e794 100644 --- a/examples/game/server/src/predict_trace.rs +++ b/examples/game/server/src/predict_trace.rs @@ -321,6 +321,17 @@ fn grid_sample_args() -> Vec> { args } +/// `pit_room` for the content cells (as rooms), under two seeds. +fn pit_room_args() -> Vec> { + let mut args = Vec::new(); + for seed in [game_sim::mobpit::DEFAULT_SEED, 0xdead_beef] { + for (x, y) in content_cells() { + args.push(game_sim::mobpit::PitRoomContext { seed, x, y }.encode_context()); + } + } + args +} + /// Every demo step's and pure function's native trace (see the module docs). pub fn traces() -> Value { json!({ @@ -328,6 +339,7 @@ pub fn traces() -> Value { "pures": [ pure_trace::(grid_cell_args()), pure_trace::(grid_sample_args()), + pure_trace::(pit_room_args()), ], "steps": [ trace::(capsule_streams(0)), diff --git a/examples/game/server/tests/mobpit_smoke.rs b/examples/game/server/tests/mobpit_smoke.rs index aa07bd36f..4f24887ad 100644 --- a/examples/game/server/tests/mobpit_smoke.rs +++ b/examples/game/server/tests/mobpit_smoke.rs @@ -1,24 +1,27 @@ //! Mob Pit + Leaderboard smoke tests, every one against its own `celld dev` -//! serving `examples/game/cells` (`game_demos::devcelld`; `CELLD_BIN` must -//! name celld and the worker must be built — `run.sh smoke` does both). -//! celld relays its outbox Queue to the test's server, whose crawler -//! directory projects the relayed events (the crawler list is eventually -//! consistent with the cells). +//! serving `examples/game/cells` — the rooms (`mobpit_rooms`, one Durable +//! Object per room) and their cells (`game_demos::devcelld`; `CELLD_BIN` +//! must name celld and the worker must be built — `run.sh smoke` does +//! both). celld relays its outbox Queue to the test's services, whose +//! crawler directory and room status project the relayed events +//! (eventually consistent with the cells). //! -//! 1. Facts → celld Crawler cells exactly once (ledger replay), server-side -//! XP, trusted principal; leaderboard occurrences have the same ids live -//! and from history, so rebuild + replay never double count. celld down: -//! the fact is retryable, never stored locally. -//! 2. Bots fight in-process; with 1.5 s of storage latency the tick stays -//! flat while pending facts climb, then everything settles and the -//! boards equal the cells (and a rebuild changes nothing). -//! 3. Crash recovery with the real binary: `kill -9` mid-fight with facts in -//! flight, then celld crashes too; restart both, verify the cells and -//! that a replayed pre-crash fact key does not double-credit. +//! 1. Kill facts → Crawler cells exactly once (ledger replay), server-side +//! XP, trusted principal; the board follows the directory, a rebuild +//! from the cells' history matches it. celld down: the fact is +//! retryable, never stored locally. +//! 2. Bots fight in a room on celld: kills settle in the cells, boards and +//! rebuild equal the cells; the empty room goes dormant, then +//! hibernated, and a new player wakes it with its mobs restored. +//! 3. celld crashes mid-fight (kill -9 of its process tree) and restarts: +//! the room comes back from its snapshot, its unsettled kill facts +//! settle from its outbox, and the cells, the directory and the board +//! agree. +//! 4. Presence: the rooms' lifecycle facts reach the players' presence +//! cells (online, offline, away). use std::net::SocketAddr; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; +use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -26,15 +29,17 @@ use distributed::leaderboard::LeaderboardStore; use distributed_game::bots::{run_bots, Behaviour, BotConfig}; use distributed_game::net::TicketKey; use distributed_game::{Fact, FactError, FactSink, FactStamp, ZoneRng}; -use game_demos::common::{random_hex, DemoOptions, RunningDemo}; +use game_demos::common::random_hex; use game_demos::devcelld::DevCelld; use game_demos::mobpit::board::{kill_occurrence, MobKilled}; use game_demos::mobpit::crawler::RECORD_KILL; -use game_demos::mobpit::{self, encode_bot_input, MobPitDemo, MobPitWorld, WorldOptions}; +use game_demos::mobpit::store::kill_sink; +use game_demos::mobpit::{self, encode_bot_input, MobPitWorld, RunningServices, WorldOptions}; use serde_json::{json, Value}; -use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; -const SECRET: &str = "mobpit-smoke-secret-0123456789abcdef"; +/// The rooms' empty → hibernated delay in these tests. +const HIBERNATE_AFTER_MS: &str = "1500"; /// Walk slowly while turning: the swing cone sweeps around, chasing mobs get hit. struct Spin { @@ -59,7 +64,14 @@ async fn relayed_celld() -> (tokio::net::TcpListener, DevCelld) { listener.local_addr().unwrap(), distributed::bus::CELLD_QUEUE_RELAY_PATH ); - let celld = DevCelld::start(Some(relay)).unwrap_or_else(|error| panic!("celld dev: {error}")); + let celld = DevCelld::start_with( + Some(relay), + &[ + ("ZONE_HIBERNATE_AFTER_MS", HIBERNATE_AFTER_MS), + ("ZONE_PERSIST_MS", "1000"), + ], + ) + .unwrap_or_else(|error| panic!("celld dev: {error}")); (listener, celld) } @@ -155,8 +167,8 @@ async fn facts_commit_once_and_board_rebuilds_identically() { let world = MobPitWorld::start(WorldOptions::new(&dir, celld.options())) .await .unwrap(); - let (_demo, _stop) = start(listener, world.clone()).await; - let sink = world.fact_sink(); + let (_demo, _stop) = start(listener, &celld, world.clone()).await; + let sink = kill_sink(world.celld()).unwrap(); let input = json!({ "mob": "pit-1/m3", "tier": 2, "name": "Ana" }); let first = sink @@ -196,11 +208,6 @@ async fn facts_commit_once_and_board_rebuilds_identically() { )) .await; assert!(matches!(bad_tier, Err(FactError::Permanent(_)))); - let anonymous = Fact::trusted("k", RECORD_KILL, input.clone(), None, FactStamp::default()); - assert!(matches!( - sink.commit(&anonymous).await, - Err(FactError::Permanent(_)) - )); sink.commit(&kill_fact( "kill:t:pit-1:m6:0", "guest-bo", @@ -224,8 +231,8 @@ async fn facts_commit_once_and_board_rebuilds_identically() { // Listed by the directory once their kill events are projected. crawlers_settled(&world, &["guest-ana", "guest-bo"]).await; - // Live updates are fire-and-forget; the replay was deduplicated. - eventually("live board", Duration::from_secs(5), || async { + // The board follows the directory; the replay changed nothing. + eventually("live board", Duration::from_secs(10), || async { world.board().scores("guest-bo").await.unwrap() == (1.0, 60.0) }) .await; @@ -294,18 +301,28 @@ async fn facts_commit_once_and_board_rebuilds_identically() { async fn start( listener: tokio::net::TcpListener, + celld: &DevCelld, world: Arc, -) -> (RunningDemo, tokio::sync::oneshot::Sender<()>) { +) -> (RunningServices, tokio::sync::oneshot::Sender<()>) { let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); - let running = mobpit::spawn(listener, DemoOptions::dev(SECRET), world, async move { - let _ = stopped.await; - }) + let running = mobpit::spawn( + listener, + TicketKey::new(celld.ticket_secret()), + true, + world, + async move { + let _ = stopped.await; + }, + ) .unwrap(); (running, stop) } -fn bot_config(ws: String, bots: usize, duration: Duration) -> BotConfig { - let mut config = BotConfig::new(ws, "pit-1", TicketKey::new(SECRET)); +/// Bots in room `room` on celld (`/rooms/{room}`), with tickets the rooms +/// accept. +fn bot_config(celld: &DevCelld, room: &str, bots: usize, duration: Duration) -> BotConfig { + let mut config = BotConfig::new(celld.ws_url(), room, TicketKey::new(celld.ticket_secret())); + config.path = "/rooms".into(); config.bots = bots; config.input_rate = 30.0; config.duration = duration; @@ -320,140 +337,118 @@ fn spin(i: usize) -> Box { }) } +/// `GET {celld}/rooms/{room}/info` (the room object's debug JSON). +async fn room_info(celld: &DevCelld, room: &str) -> Value { + reqwest_get(&format!("{}/rooms/{room}/info", celld.url())).await +} + +async fn reqwest_get(url: &str) -> Value { + match reqwest::get(url).await { + Ok(response) => response.json().await.unwrap_or(Value::Null), + Err(_) => Value::Null, + } +} + +/// The room's row in the services' room status (`/dev/mobpit/rooms`). +async fn room_status(services: SocketAddr, room: &str) -> Value { + let (_, body) = http(services, "GET", "/dev/mobpit/rooms", None).await; + body["rooms"] + .as_array() + .and_then(|rooms| rooms.iter().find(|r| r["zone"] == room).cloned()) + .unwrap_or(Value::Null) +} + +/// Directory = cells, board = directory. +async fn settled_and_matching(world: &Arc) -> u64 { + let w = world.clone(); + eventually( + "directory equals the cells", + Duration::from_secs(60), + || { + let w = w.clone(); + async move { + let Ok(crawlers) = w.crawlers().await else { + return false; + }; + for c in &crawlers { + let principal = c["principal"].as_str().unwrap(); + let Ok(view) = w.cells().crawler(principal).await else { + return false; + }; + if view.state.map(|s| u64::from(s.kills)) != c["kills"].as_u64() { + return false; + } + } + !crawlers.is_empty() + } + }, + ) + .await; + let w = world.clone(); + eventually( + "board equals the directory", + Duration::from_secs(20), + || { + let w = w.clone(); + async move { + let mut ok = true; + for c in w.crawlers().await.unwrap() { + let (k, x) = w + .board() + .scores(c["principal"].as_str().unwrap()) + .await + .unwrap(); + ok &= k == c["kills"].as_f64().unwrap() && x == c["xp"].as_f64().unwrap(); + } + ok + } + }, + ) + .await; + assert_board_matches_cells(world).await +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn bots_fight_slow_storage_keeps_the_tick_flat_and_boards_match_cells() { +async fn bots_fight_in_a_room_on_celld_and_the_room_sleeps_and_restores() { let dir = temp_dir("bots"); let (listener, celld) = relayed_celld().await; let world = MobPitWorld::start(WorldOptions::new(&dir, celld.options())) .await .unwrap(); - let (demo, stop) = start(listener, world.clone()).await; + let (services, stop) = start(listener, &celld, world.clone()).await; + let room = "pit.0.0"; - // Unknown fields (e.g. an identity) are rejected on the dev routes too. - let (status, _) = http( - demo.addr, - "POST", - "/dev/mobpit/storage", - Some(json!({ "latencyMs": 1, "principal": "x" })), - ) - .await; - assert_eq!(status, 422); - - let server = demo.server.clone(); - let addr = demo.addr; - let probe = async move { - // Fight at full speed first, then make storage slow. - tokio::time::sleep(Duration::from_secs(4)).await; - let (_, storage) = http( - addr, - "POST", - "/dev/mobpit/storage", - Some(json!({ "latencyMs": 1500 })), - ) - .await; - assert_eq!(storage["latencyMs"], 1500); - let mut max_pending = 0; - let mut max_tick: f32 = 0.0; - let until = Instant::now() + Duration::from_secs(6); - while Instant::now() < until { - tokio::time::sleep(Duration::from_millis(250)).await; - if let Some(s) = server.inspect("pit-1", |h| h.zone().stats()).await { - max_pending = max_pending.max(s.pending); - if s.tick_max_ms > 0.0 { - max_tick = max_tick.max(s.tick_max_ms); - } - } - } - (max_pending, max_tick) - }; - let (summary, (max_pending, max_tick)) = tokio::join!( - run_bots(bot_config(demo.ws_url(), 8, Duration::from_secs(11)), spin), - probe - ); + let summary = run_bots(bot_config(&celld, room, 6, Duration::from_secs(10)), spin).await; assert_eq!( summary.joined(), - 8, + 6, "{:?}", summary.bots.iter().find(|b| b.error.is_some()) ); - eprintln!("slow storage: max pending {max_pending}, max tick interval {max_tick:.1} ms"); - assert!( - max_pending >= 1, - "slow storage: facts wait (max {max_pending})" - ); - assert!( - max_tick < 120.0, - "the 30 Hz tick never waits for storage (max interval {max_tick} ms)" - ); + let info = room_info(&celld, room).await; + assert!(info["iterations"].as_u64().unwrap() > 100, "{info}"); + assert!(info["tick"].as_u64().unwrap_or(0) > 0, "{info}"); - // Back to fast storage: everything settles. - http( - demo.addr, - "POST", - "/dev/mobpit/storage", - Some(json!({ "latencyMs": 0 })), - ) - .await; - let w = world.clone(); - eventually("facts settled", Duration::from_secs(60), || { - let w = w.clone(); - async move { w.zone_pending() == 0 && w.sink_state().stats().in_sink == 0 } - }) - .await; - let stats = world.sink_state().stats(); - assert!(stats.committed >= 3, "bots killed mobs: {stats:?}"); - assert_eq!(stats.errors, 0, "{stats:?}"); - - // Boards = cells (fire-and-forget updates have drained, the directory - // has projected every kill), rebuild = same. - let w = world.clone(); - eventually("directory caught up", Duration::from_secs(30), || { - let w = w.clone(); - async move { - let mut total = 0; - for c in w.crawlers().await.unwrap() { - total += c["kills"].as_u64().unwrap(); - } - total == w.sink_state().stats().committed - } + // The bots left: dormant, then hibernated (dropped from memory). + eventually("room hibernated", Duration::from_secs(30), || async { + room_status(services.addr, room).await["status"] == "hibernated" }) .await; - let w = world.clone(); - eventually("board caught up", Duration::from_secs(10), || { - let w = w.clone(); - async move { - let mut ok = true; - for c in w.crawlers().await.unwrap() { - let (k, _) = w - .board() - .scores(c["principal"].as_str().unwrap()) - .await - .unwrap(); - ok &= k == c["kills"].as_f64().unwrap(); - } - ok - } - }) - .await; - let total = assert_board_matches_cells(&world).await; - eprintln!("bots: {stats:?}, durable kills in the cells {total}"); - assert_eq!(total, stats.committed, "one kill per committed fact"); - let (_, rebuild) = http(demo.addr, "POST", "/dev/mobpit/leaderboard/rebuild", None).await; - assert_eq!(rebuild["matchesCells"], true, "{rebuild}"); - assert_eq!(rebuild["identicalTop"], true, "{rebuild}"); - assert_eq!(rebuild["events"].as_u64(), Some(total)); + assert_eq!(room_info(&celld, room).await["awake"], false); - // Read routes. - let (_, board) = http( - demo.addr, - "GET", - "/dev/mobpit/leaderboard?member=bot-0", + // Kills settled exactly once in the cells; boards and rebuild agree. + let total = settled_and_matching(&world).await; + assert!(total >= 1, "bots killed mobs: {total}"); + let (_, rebuild) = http( + services.addr, + "POST", + "/dev/mobpit/leaderboard/rebuild", None, ) .await; - assert_eq!(board["snapshot"]["backend"], "memory"); - assert!(!board["snapshot"]["kills"].as_array().unwrap().is_empty()); - let (_, crawlers) = http(demo.addr, "GET", "/dev/mobpit/crawlers", None).await; + assert_eq!(rebuild["matchesCells"], true, "{rebuild}"); + assert_eq!(rebuild["events"].as_u64(), Some(total)); + let (_, crawlers) = http(services.addr, "GET", "/dev/mobpit/crawlers", None).await; assert_eq!( crawlers["crawlers"] .as_array() @@ -464,190 +459,72 @@ async fn bots_fight_slow_storage_keeps_the_tick_flat_and_boards_match_cells() { total ); + // A new player wakes the room: restored from its snapshot. + let summary = run_bots(bot_config(&celld, room, 1, Duration::from_secs(2)), spin).await; + assert_eq!(summary.joined(), 1); + eventually("room restored", Duration::from_secs(20), || async { + let row = room_status(services.addr, room).await; + row["restored"] == true && row["activations"].as_i64().unwrap_or(0) >= 2 + }) + .await; + stop.send(()).unwrap(); - demo.task.await.unwrap().unwrap(); + services.task.await.unwrap().unwrap(); let _ = std::fs::remove_dir_all(dir); } -struct Binary { - child: Child, - addr: SocketAddr, -} - -async fn start_binary(dir: &Path, celld: &DevCelld, port: u16) -> Binary { - std::fs::create_dir_all(dir).expect("data dir"); - let mut child = Command::new(env!("CARGO_BIN_EXE_game-demos")) - .args(["mobpit", "--port", &port.to_string(), "--dev"]) - .args(["--secret", SECRET, "--data-dir"]) - .arg(dir) - .args(["--celld-url", &celld.url()]) - .env("DISTRIBUTED_INTERNAL_SECRET", celld.secret()) - .env_remove("REDIS_URL") - .stdout(Stdio::piped()) - // Kept in the data dir: the failure messages below point at it. - .stderr( - std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(dir.join("server.log")) - .expect("server log"), - ) - .spawn() - .expect("spawn game-demos"); - let stdout = child.stdout.take().unwrap(); - let mut lines = - tokio::io::BufReader::new(tokio::process::ChildStdout::from_std(stdout).unwrap()).lines(); - let addr = loop { - let line = tokio::time::timeout(Duration::from_secs(60), lines.next_line()) - .await - .expect("server start") - .unwrap() - .expect("server exited"); - if let Some(url) = line.strip_prefix("LISTENING http://") { - break url.parse().unwrap(); - } - }; - // Keep draining stdout so the child never blocks on a full pipe. - tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} }); - Binary { child, addr } -} - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn kill_dash_nine_mid_fight_keeps_settled_facts_exactly_once() { +async fn a_celld_crash_mid_fight_keeps_kills_exactly_once() { let dir = temp_dir("crash"); - // celld relays its outbox Queue to the server's fixed port (both runs). - let port = game_demos::devcelld::free_port(); - let relay = format!( - "http://127.0.0.1:{port}{}", - distributed::bus::CELLD_QUEUE_RELAY_PATH - ); - let mut celld = - DevCelld::start(Some(relay)).unwrap_or_else(|error| panic!("celld dev: {error}")); - let mut first = start_binary(&dir, &celld, port).await; - let ws = format!("ws://{}", first.addr); - // Settle some kills at full speed, then slow storage so facts are in - // flight at the moment of the crash. - let addr = first.addr; - let fight = tokio::spawn(run_bots(bot_config(ws, 5, Duration::from_secs(30)), spin)); - let start = Instant::now(); - let before = loop { - tokio::time::sleep(Duration::from_millis(200)).await; - let (_, stats) = http(addr, "GET", "/dev/mobpit/stats", None).await; - if stats["sink"]["committed"].as_u64().unwrap_or(0) >= 3 { - break stats; - } - assert!( - start.elapsed() < Duration::from_secs(25), - "no kills: {stats}" - ); - }; - http( - addr, - "POST", - "/dev/mobpit/storage", - Some(json!({ "latencyMs": 1500 })), - ) + let (listener, mut celld) = relayed_celld().await; + let world = MobPitWorld::start(WorldOptions::new(&dir, celld.options())) + .await + .unwrap(); + let (services, stop) = start(listener, &celld, world.clone()).await; + let room = "pit.1.0"; + let fight = tokio::spawn(run_bots( + bot_config(&celld, room, 5, Duration::from_secs(30)), + spin, + )); + // Fight until kills have settled (the fight goes on: more are in + // flight when celld dies). + let w = world.clone(); + eventually("first kills settled", Duration::from_secs(40), || { + let w = w.clone(); + async move { !w.crawlers().await.unwrap_or_default().is_empty() } + }) .await; - let start = Instant::now(); - let at_crash = loop { - tokio::time::sleep(Duration::from_millis(100)).await; - let (_, stats) = http(addr, "GET", "/dev/mobpit/stats", None).await; - if stats["sink"]["inSink"].as_u64().unwrap_or(0) >= 1 - || start.elapsed() > Duration::from_secs(10) - { - break stats; - } - }; - first.child.kill().unwrap(); // SIGKILL: no graceful drain - first.child.wait().unwrap(); - fight.abort(); - let settled_before = at_crash["sink"]["committed"].as_u64().unwrap(); - let in_flight = at_crash["pending"].as_u64().unwrap(); - assert!(settled_before >= before["sink"]["committed"].as_u64().unwrap()); - - // celld crashes too (kill -9 of its process group) and restarts on its - // state; then the server restarts on the same directory: the settled - // facts are all there; of the in-flight ones each either committed - // atomically or not at all. + // celld crashes (kill -9 of its process tree) and restarts on its state. celld.restart().unwrap(); - let mut second = start_binary(&dir, &celld, port).await; - // The directory (persisted in the data dir) catches up with the kill - // events the Queue relays; then it is stable. - let addr = second.addr; - let directory_total = || async move { - let (_, crawlers) = http(addr, "GET", "/dev/mobpit/crawlers", None).await; - crawlers["crawlers"] - .as_array() - .unwrap() - .iter() - .map(|c| c["kills"].as_u64().unwrap()) - .sum::() - }; - let mut total = 0; - let mut stable_since = Instant::now(); - let start = Instant::now(); - while stable_since.elapsed() < Duration::from_secs(3) || total < settled_before { - assert!( - start.elapsed() < Duration::from_secs(60), - "directory never settled: {total} kills, {settled_before} settled before the crash; \ - server log {}, celld logs in {}", - dir.join("server.log").display(), - celld.project().display() + fight.abort(); + // A player wakes the room again: its snapshot and its outbox come back. + let summary = run_bots(bot_config(&celld, room, 1, Duration::from_secs(2)), spin).await; + assert_eq!(summary.joined(), 1, "{:?}", summary.bots); + let total = settled_and_matching(&world).await; + eprintln!("crash: durable kills {total}"); + // Every principal's kill history holds each fact once: the recorded + // kills equal the cell's count (a replay records nothing). + for c in world.crawlers().await.unwrap() { + let view = world + .cells() + .crawler(c["principal"].as_str().unwrap()) + .await + .unwrap(); + assert_eq!( + view.kills.len() as u32, + view.state.unwrap().kills, + "one event per credited kill" ); - tokio::time::sleep(Duration::from_millis(200)).await; - let now = directory_total().await; - if now != total { - total = now; - stable_since = Instant::now(); - } } - eprintln!( - "crash: settled {settled_before}, in flight {in_flight}, durable after restart {total}" - ); - assert!( - total >= settled_before && total <= settled_before + in_flight, - "settled {settled_before} ≤ durable {total} ≤ settled + in flight ({in_flight})" - ); - // The board is rebuilt from the cells of every crawler in the directory - // (at boot, and again now that the directory has caught up). - let (_, rebuild) = http(second.addr, "POST", "/dev/mobpit/leaderboard/rebuild", None).await; + let (_, rebuild) = http( + services.addr, + "POST", + "/dev/mobpit/leaderboard/rebuild", + None, + ) + .await; assert_eq!(rebuild["matchesCells"], true, "{rebuild}"); - let (_, board) = http(second.addr, "GET", "/dev/mobpit/leaderboard", None).await; - let board_kills: f64 = board["snapshot"]["kills"] - .as_array() - .unwrap() - .iter() - .map(|r| r["score"].as_f64().unwrap()) - .sum(); - assert_eq!(board_kills as u64, total, "{board}"); - second.child.kill().unwrap(); - second.child.wait().unwrap(); - - // Replay a pre-crash fact (same key, same input) against the cells: the - // command ledger replays it, nothing is credited twice. - let recent = &before["recent"].as_array().unwrap()[0]; - let key = recent["key"].as_str().unwrap(); - let principal = recent["receipt"]["crawler"].as_str().unwrap(); - let world = MobPitWorld::open(WorldOptions::new(&dir, celld.options())).unwrap(); - let kills_of = |world: Arc| async move { - world - .cells() - .crawler(principal) - .await - .unwrap() - .state - .unwrap() - .kills - }; - let kills_before = kills_of(world.clone()).await; - let replay = world - .fact_sink() - .commit(&kill_fact(key, principal, recent["input"].clone())) - .await - .unwrap(); - assert!(replay.replayed, "pre-crash key replays after the restart"); - assert_eq!(replay.payload, recent["receipt"], "original receipt"); - assert_eq!(kills_of(world.clone()).await, kills_before); + let _ = stop.send(()); let _ = std::fs::remove_dir_all(dir); } @@ -665,9 +542,9 @@ async fn redis_board_projects_and_rebuilds_when_redis_url_is_set() { options.redis_url = Some(url); options.redis_prefix = format!("mobpit-test-{}", random_hex(8)); let world = MobPitWorld::start(options).await.unwrap(); - let (_demo, _stop) = start(listener, world.clone()).await; + let (_services, _stop) = start(listener, &celld, world.clone()).await; assert_eq!(world.board().backend(), "redis"); - let sink = world.fact_sink(); + let sink = kill_sink(world.celld()).unwrap(); for (i, tier) in [1u8, 3].into_iter().enumerate() { let input = json!({ "mob": format!("pit-1/m{i}"), "tier": tier, "name": "Rae" }); let fact = kill_fact(&format!("kill:r:pit-1:m{i}:0"), "guest-rae", input); @@ -690,11 +567,10 @@ async fn redis_board_projects_and_rebuilds_when_redis_url_is_set() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn presence_is_settled_in_presence_cells_from_the_lifecycle_facts() { +async fn presence_is_settled_in_presence_cells_from_the_rooms_lifecycle_facts() { use distributed_game::protocol::Hello; use distributed_game::{ClientMessage, ClientMirror, Role, ServerMessage, TicketClaims}; use futures_util::{SinkExt, StreamExt}; - use game_demos::mobpit::presence::PresenceStatus; use tokio_tungstenite::tungstenite::Message; let dir = temp_dir("presence"); @@ -702,14 +578,16 @@ async fn presence_is_settled_in_presence_cells_from_the_lifecycle_facts() { let world = MobPitWorld::start(WorldOptions::new(&dir, celld.options())) .await .unwrap(); - let (demo, stop) = start(listener, world.clone()).await; + let (services, stop) = start(listener, &celld, world.clone()).await; + let room = "pit.0.2"; let join = |principal: &'static str| { - let url = format!("{}/zones/pit-1", demo.ws_url()); + let url = format!("{}/rooms/{room}", celld.ws_url()); + let key = TicketKey::new(celld.ticket_secret()); async move { let (mut ws, _) = tokio_tungstenite::connect_async(url).await.unwrap(); - let ticket = TicketKey::new(SECRET).sign(&TicketClaims::new( + let ticket = key.sign(&TicketClaims::new( principal, - "pit-1", + room, 4_000_000_000, format!("presence-{principal}"), Role::Player, @@ -739,27 +617,25 @@ async fn presence_is_settled_in_presence_cells_from_the_lifecycle_facts() { } }; let status = |principal: &'static str| { - let world = world.clone(); - move || { - let world = world.clone(); - async move { - world - .presence() - .get(principal) - .map(|e| (e.zone.clone(), e.status)) - } + let addr = services.addr; + async move { + let (_, body) = http( + addr, + "GET", + &format!("/dev/mobpit/presence?principal={principal}"), + None, + ) + .await; + ( + body["presence"]["zone"].as_str().map(str::to_string), + body["presence"]["status"].as_str().map(str::to_string), + ) } }; let mut ana = join("guest-ana").await; let bo = join("guest-bo").await; - let online = Some(("pit-1".to_string(), PresenceStatus::Online)); - eventually("ana online", Duration::from_secs(20), { - let s = status("guest-ana"); - let online = online.clone(); - move || { - let (s, online) = (s.clone(), online.clone()); - async move { s().await == online } - } + eventually("ana online", Duration::from_secs(20), || async { + status("guest-ana").await == (Some(room.into()), Some("online".into())) }) .await; // Graceful leave → offline; a dropped socket → away (grace running). @@ -767,29 +643,14 @@ async fn presence_is_settled_in_presence_cells_from_the_lifecycle_facts() { .await .unwrap(); drop(bo); - eventually("ana offline, bo away", Duration::from_secs(20), { - let (a, b) = (status("guest-ana"), status("guest-bo")); - move || { - let (a, b) = (a.clone(), b.clone()); - async move { - a().await == Some(("pit-1".into(), PresenceStatus::Offline)) - && b().await == Some(("pit-1".into(), PresenceStatus::Away)) - } - } + eventually("ana offline, bo away", Duration::from_secs(20), || async { + status("guest-ana").await == (Some(room.into()), Some("offline".into())) + && matches!( + status("guest-bo").await.1.as_deref(), + Some("away") | Some("offline") + ) }) .await; - let (code, body) = http(demo.addr, "GET", "/dev/mobpit/presence", None).await; - assert_eq!(code, 200); - assert_eq!(body["presence"].as_array().unwrap().len(), 2, "{body}"); - // The transitions are durable in the players' presence cells. - let ana = world.cells().presence("guest-ana").await.unwrap(); - assert_eq!( - (ana["zone"].as_str(), ana["status"].as_str()), - (Some("pit-1"), Some("offline")), - "{ana}" - ); - let bo = world.cells().presence("guest-bo").await.unwrap(); - assert_eq!(bo["status"], "away", "{bo}"); // Lifecycle facts never touch the Crawler cells. assert!(world.crawlers().await.unwrap().is_empty()); let _ = stop.send(()); From b639f1c961c4c7eb4255c880e9dbbe1394efb2b1 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 19:52:11 -0500 Subject: [PATCH 264/484] feat(game): SvelteKit Mob Pit rooms, live minimap, celld overlay The SvelteKit Mob Pit joins the entrance room on celld and follows doorways from room to room; tickets admit the entrance or a room being rejoined (after a 1012 restart), never chosen by a node. - mobpit-service projects the rooms' zone-activity events into `zone_activities` next to `player_stats`, readable over GraphQL @live. - The page: a live minimap (Rooms.graphql @load @live: active, dormant, hibernated, never ran) with restore and sleep toasts, a debug overlay of the room object's node, isolate and activation, doorways drawn on the walls; the room entry points rotate per connection (celld forwards every socket to the room's node). - Playwright: two players on a 3-node production-mode celld fleet (RustFS via docker compose, tests/helpers/fleet.mjs): kill, live read model, doorways into a room on another node, the left room asleep on the minimap, restored on return, another kill settled live. [[tasks/gr-p41-mobpit-rooms-zones]] --- examples/game/client/tests/helpers/fleet.mjs | 131 ++++++ examples/game/server/service/Cargo.toml | 18 +- examples/game/server/service/src/lib.rs | 48 ++- examples/game/server/src/mobpit/world.rs | 2 +- .../src/lib/generated/mobpit/constants.ts | 11 +- .../src/lib/generated/mobpit/events.ts | 217 ++++------ .../src/lib/generated/mobpit/index.ts | 1 + .../src/lib/generated/mobpit/pures.ts | 60 +++ .../src/lib/generated/mobpit/schema.ts | 24 +- .../src/lib/generated/mobpit/surface.json | 392 ++++++++---------- .../game/sveltekit/src/lib/pit/Rooms.graphql | 15 + .../game/sveltekit/src/lib/pit/Rooms.svelte | 80 ++++ examples/game/sveltekit/src/lib/pit/loop.ts | 25 +- .../game/sveltekit/src/lib/server/game.ts | 33 +- .../sveltekit/src/routes/pit/+page.server.ts | 5 +- .../sveltekit/src/routes/pit/+page.svelte | 70 +++- examples/game/sveltekit/tests/pit.test.mjs | 156 +++++-- 17 files changed, 868 insertions(+), 420 deletions(-) create mode 100644 examples/game/client/tests/helpers/fleet.mjs create mode 100644 examples/game/sveltekit/src/lib/generated/mobpit/pures.ts create mode 100644 examples/game/sveltekit/src/lib/pit/Rooms.graphql create mode 100644 examples/game/sveltekit/src/lib/pit/Rooms.svelte diff --git a/examples/game/client/tests/helpers/fleet.mjs b/examples/game/client/tests/helpers/fleet.mjs new file mode 100644 index 000000000..ad07ba342 --- /dev/null +++ b/examples/game/client/tests/helpers/fleet.mjs @@ -0,0 +1,131 @@ +/** + * A local multi-node celld fleet for one Node test: one RustFS container + * (docker compose, a project and port of its own) holding the fleet + * bucket, the demos' cells worker (rooms + cells) deployed to it with + * `celld deploy`, and N nodes in production mode. `stop()` stops the nodes + * it started and removes the container (`docker compose down -v`). + * + * Returns null when docker, the aws CLI or celld is missing, unless + * `MOBPIT_FLEET_REQUIRED=1` (then it throws). + */ +import { spawn, spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { freePort } from './celld.mjs'; + +const CELLS = fileURLToPath(new URL('../../../cells/', import.meta.url)); +const RELAY_PATH = '/internal/celld-queue/relay'; + +function skip(reason) { + if (process.env.MOBPIT_FLEET_REQUIRED === '1') throw new Error(`fleet required: ${reason}`); + console.error(`no celld fleet: ${reason}`); + return null; +} + +async function waitFor(url, ms) { + const deadline = Date.now() + ms; + for (;;) { + try { + if ((await fetch(url)).ok) return; + } catch { + // not up yet + } + if (Date.now() > deadline) throw new Error(`${url} not ready`); + await new Promise((r) => setTimeout(r, 250)); + } +} + +export async function startFleet({ relayPort, nodes = 3, vars = {} } = {}) { + const bin = process.env.CELLD_BIN; + if (!bin) return skip('CELLD_BIN is not set'); + for (const tool of ['docker', 'aws']) { + if (spawnSync(tool, ['--version']).status !== 0) return skip(`${tool} is not available`); + } + const dir = mkdtempSync(join(tmpdir(), 'mobpit-fleet-js-')); + const s3Port = await freePort(); + const project = `mobpit-fleet-js-${process.pid}-${s3Port}`; + const aws = { + ...process.env, + AWS_ACCESS_KEY_ID: 'fleetjs', + AWS_SECRET_ACCESS_KEY: 'fleetjssecret123', + AWS_REGION: 'us-east-1', + S3_ENDPOINT: `http://127.0.0.1:${s3Port}` + }; + const compose = join(dir, 's3-compose.yaml'); + writeFileSync( + compose, + `services:\n s3:\n image: rustfs/rustfs:1.0.3\n command: ["/data"]\n environment:\n RUSTFS_ADDRESS: "0.0.0.0:9000"\n RUSTFS_ACCESS_KEY: ${aws.AWS_ACCESS_KEY_ID}\n RUSTFS_SECRET_KEY: ${aws.AWS_SECRET_ACCESS_KEY}\n ports: ["127.0.0.1:${s3Port}:9000"]\n` + ); + const children = []; + const down = () => { + for (const child of children) if (child.exitCode === null) child.kill('SIGKILL'); + spawnSync('docker', ['compose', '-p', project, '-f', compose, 'down', '-v'], { stdio: 'ignore' }); + }; + try { + const up = spawnSync('docker', ['compose', '-p', project, '-f', compose, 'up', '-d'], { encoding: 'utf8' }); + if (up.status !== 0) throw new Error(`docker compose up: ${up.stderr}`); + const deadline = Date.now() + 60_000; + for (;;) { + const mb = spawnSync('aws', ['--endpoint-url', aws.S3_ENDPOINT, 's3', 'mb', 's3://mobpit-fleet'], { env: aws, encoding: 'utf8' }); + if (mb.status === 0 || /BucketAlready/.test(mb.stderr)) break; + if (Date.now() > deadline) throw new Error(`bucket: ${mb.stderr}`); + await new Promise((r) => setTimeout(r, 500)); + } + const secret = `test-only-${randomBytes(24).toString('hex')}`; + const ticketSecret = randomBytes(32).toString('hex'); + const ports = []; + for (let i = 0; i < nodes; i++) ports.push({ name: `node-${'abcdef'[i]}`, pub: await freePort(), op: await freePort() }); + const worker = join(dir, 'worker'); + mkdirSync(worker, { recursive: true }); + cpSync(join(CELLS, 'build'), join(worker, 'build'), { recursive: true }); + const config = JSON.parse( + readFileSync(join(CELLS, 'wrangler.jsonc'), 'utf8') + .split('\n') + .filter((l) => !l.trimStart().startsWith('//')) + .join('\n') + ); + Object.assign(config.vars, { + DISTRIBUTED_INTERNAL_SECRET: secret, + GAME_TICKET_SECRET: ticketSecret, + CELLD_QUEUE_RELAY_URL: `http://127.0.0.1:${relayPort}${RELAY_PATH}`, + CELLD_ZONE_NODES: ports.map((p) => `${p.name}=127.0.0.1:${p.op}`).join(','), + ...vars + }); + writeFileSync(join(worker, 'wrangler.json'), JSON.stringify(config)); + const deploy = spawnSync(bin, ['deploy', worker, '--bucket', 's3://mobpit-fleet/fleet'], { env: aws, encoding: 'utf8' }); + if (deploy.status !== 0) throw new Error(`celld deploy: ${deploy.stdout}${deploy.stderr}`); + for (const p of ports) { + const ndir = join(dir, p.name); + mkdirSync(ndir, { recursive: true }); + const child = spawn( + bin, + ['--bucket', 's3://mobpit-fleet/fleet', '--listen', `127.0.0.1:${p.pub}`, '--internal-listen', `127.0.0.1:${p.op}`, '--advertise', `127.0.0.1:${p.op}`], + { + env: { ...aws, CELLD_NODE: p.name, CELLD_WATCH: join(ndir, 'watch'), CELLD_READY_FLEET_GATE_MS: '0', RUST_LOG: 'warn' }, + stdio: 'ignore' + } + ); + children.push(child); + } + await Promise.all(ports.map((p) => waitFor(`http://127.0.0.1:${p.pub}/health`, 90_000))); + const urls = ports.map((p) => `http://127.0.0.1:${p.pub}`); + return { + urls, + url: urls[0], + nodes: ports.map((p) => p.name), + ticketSecret, + env: { CELLD_URL: urls[0], DISTRIBUTED_INTERNAL_SECRET: secret, DISTRIBUTED_GAME_SECRET: ticketSecret }, + async stop() { + down(); + rmSync(dir, { recursive: true, force: true }); + } + }; + } catch (error) { + down(); + throw error; + } +} diff --git a/examples/game/server/service/Cargo.toml b/examples/game/server/service/Cargo.toml index ce1f902fb..7c664acb8 100644 --- a/examples/game/server/service/Cargo.toml +++ b/examples/game/server/service/Cargo.toml @@ -1,9 +1,10 @@ -# Mob Pit's business-side read model: a Distributed service that projects -# the Crawler cells' published `crawler.mob_killed` domain events (celld -# drains each cell outbox to a Queue; its consumer relays them through the -# zone server onto a SQLite bus) into a `player_stats` SQL table and -# serves it over GraphQL with `@live`. Read-only: it has no commands, so -# nothing here can credit XP. +# Mob Pit's business-side read models: a Distributed service that projects +# the Crawler cells' published `crawler.mob_killed` domain events and the +# rooms' `zone.activity_changed` events (celld drains each cell outbox to a +# Queue; its consumer relays them through the services onto a SQLite bus) +# into `player_stats` and `zone_activities` SQL tables and serves them over +# GraphQL with `@live`. Read-only: it has no commands, so nothing here can +# credit XP. [package] name = "mobpit_service" version = "0.1.0" @@ -23,6 +24,8 @@ mobpit_crawler = { path = "../crawler" } # `redis`: the Redis leaderboards the zone server writes, served as GraphQL # board roots (`xpLeaderboard`, `killsMyRank`, … with `@live`). distributed = { path = "../../../..", features = ["sqlite", "http", "graphql", "redis"] } +# The rooms' zone status read model (`zone_activities`, the minimap). +distributed_game = { path = "../../../../distributed_game", features = ["cell"] } axum = { version = "0.8", default-features = false, features = ["json", "tokio", "http1", "ws"] } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -30,9 +33,8 @@ sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "time", "sync"] } [dev-dependencies] -# The zone server's world: real Crawler cells + the fact sink + the bus drain. +# The services' world: real Crawler cells + the relay + the bus drain. game_demos = { path = ".." } -distributed_game = { path = "../../../../distributed_game", features = ["cell"] } async-graphql = "7" futures-util = { version = "0.3", default-features = false, features = ["std"] } diff --git a/examples/game/server/service/src/lib.rs b/examples/game/server/service/src/lib.rs index 57c281d7b..c7bdd0841 100644 --- a/examples/game/server/service/src/lib.rs +++ b/examples/game/server/service/src/lib.rs @@ -15,6 +15,10 @@ //! - [`PlayerStats`] is the table: one row per principal, the Crawler's //! post-kill state ([`mobpit_crawler::CrawlerState`]). The leaderboard is a //! query over it (`order_by: xp desc`). +//! - [`ZoneActivities`] (`zone_activities`): every room's lifecycle as its +//! zone-activity cell published it (`distributed_game::world::zone_status`): +//! active / dormant / hibernated, players, restored, and — a debug +//! detail — the celld node. The pages' minimap is a `@live` query over it. //! - [`PLAYER_STATS`] maps `CrawlerMobKilledDomainEvent` to the //! [`SavePlayerStats`] upsert. The projector runtime keeps the cursor, //! skips redelivered messages and commits each projection atomically. @@ -46,11 +50,22 @@ use distributed::{ Application, ApplicationManifest, RelationalReadModel, SqliteRepository, SurfaceSpec, }; +/// The rooms' status rows and their projection. +pub use distributed_game::world::zone_status::{ZoneActivities, ZONE_ACTIVITIES}; /// The read model and its projection (shared with the zone server). pub use mobpit_crawler::stats::{ - projector, read_model_catalog, PlayerStats, SavePlayerStats, APPLICATION, EPOCH, PLAYER_STATS, - PROJECTOR, + projector, PlayerStats, SavePlayerStats, APPLICATION, EPOCH, PLAYER_STATS, PROJECTOR, }; + +/// Both tables: `player_stats` and `zone_activities`. +pub fn read_model_catalog() -> distributed::ReadModelCatalog { + mobpit_crawler::stats::read_model_catalog().table_schema(ZoneActivities::schema().clone()) +} + +/// The projector of `zone_activities`, owned by this application. +pub fn rooms_projector() -> distributed::graphql::SurfaceProjector { + distributed_game::world::zone_status::activity_projector_for(APPLICATION) +} /// The one engine role. Every signed-in player reads the whole board. pub const ROLE: &str = "user"; /// Bus consumer group of this process's board change notices (every @@ -81,6 +96,11 @@ pub fn permissions() -> ModelPermissions { ModelPermissions::new().grant(ROLE, read().all_columns()) } +/// The rooms' status is public to signed-in players too. +pub fn room_permissions() -> ModelPermissions { + ModelPermissions::new().grant(ROLE, read().all_columns()) +} + async fn project( context: CausalProjectorContext, projection: ModeledProjection, @@ -88,6 +108,13 @@ async fn project( projection.apply(PLAYER_STATS, &context).await } +async fn project_rooms( + context: CausalProjectorContext, + projection: ModeledProjection, +) -> Result<(), HandlerError> { + projection.apply(ZONE_ACTIVITIES, &context).await +} + /// The consumer service (bus consumer identity = [`APPLICATION`]): the /// modeled projector over `read_models`. pub fn projection_service(read_models: SqliteRepository) -> Service { @@ -95,7 +122,9 @@ pub fn projection_service(read_models: SqliteRepository) -> Service { Routes::new() .with_read_model_store(read_models) .modeled_projector(projector()) - .handle(project), + .handle(project) + .modeled_projector(rooms_projector()) + .handle(project_rooms), ) } @@ -116,6 +145,12 @@ fn grants() -> BTreeMap> { .or_default() .insert(PlayerStats::schema().model_name.clone(), grant); } + for (role, grant) in room_permissions().surface_grants() { + grants + .entry(role) + .or_default() + .insert(ZoneActivities::schema().model_name.clone(), grant); + } grants } @@ -124,8 +159,8 @@ fn full_surface() -> Surface { .expect("mobpit Surface should build") .with_leaderboards(leaderboard_surfaces()) .expect("mobpit boards should attach") - .with_projection_owners([projector().into()]) - .expect("mobpit projector should bind") + .with_projection_owners([projector().into(), rooms_projector().into()]) + .expect("mobpit projectors should bind") } /// Logical application artifact (`distributed describe`, the lifecycle). @@ -191,7 +226,8 @@ pub fn build_engine( .roles(&[ROLE]) .client_application_surface(APPLICATION, [ROLE], [ROLE]) .model::(permissions()) - .client_projection_owners([projector().into()]) + .model::(room_permissions()) + .client_projection_owners([projector().into(), rooms_projector().into()]) .identity(identity.config()) .graphiql(false) .change_stream(repo.read_model_changes()) diff --git a/examples/game/server/src/mobpit/world.rs b/examples/game/server/src/mobpit/world.rs index 61e913186..2ea2845b2 100644 --- a/examples/game/server/src/mobpit/world.rs +++ b/examples/game/server/src/mobpit/world.rs @@ -16,8 +16,8 @@ use super::directory::CrawlerDirectory; use super::store::{CelldOptions, CrawlerCells}; use crate::common::random_hex; use crate::common::relay::{ProjectionBus, ProjectionPublisher}; -use distributed::leaderboard::LeaderboardChangePublisher; use crate::common::zone_status::ZoneStatusView; +use distributed::leaderboard::LeaderboardChangePublisher; /// Bus consumer group of the rooms' zone status projection here. pub const ZONE_STATUS_CONSUMER: &str = "mobpit-rooms"; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts index 0e96cb0ab..e01248b13 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts @@ -1,7 +1,7 @@ // @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). // Constants: static data defined once in Rust (`GameSurface::constant`). // Do not edit: change the Rust definitions and regenerate. -import type { PitRules } from './events.ts'; +import type { PitRules, PitWorld } from './events.ts'; /** `pit_rules`, as the client decodes it. */ export const PIT_RULES: PitRules = { @@ -15,3 +15,12 @@ export const PIT_RULES: PitRules = { attackHalfAngle: 1.0471975803375244, swingFrames: 6 }; + +/** `pit_world`, as the client decodes it. */ +export const PIT_WORLD: PitWorld = { + defaultSeed: 186474221, + half: 20, + doorHalf: 2.5, + maxRoom: 1000000, + biomes: ['highlands', 'steppe', 'forest', 'meadow'] +}; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts index c748ce269..a3f5878ba 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts @@ -3,124 +3,6 @@ // Do not edit: change the Rust definitions and regenerate. import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; -/** Record `BackgroundStats` (`#[derive(GameRecord)]`). */ -export interface BackgroundStats { - readonly enqueued: number; - readonly applied: number; - readonly dropped: number; - readonly failed: number; -} - -const BACKGROUND_STATS_TYPE: WireType = { - type: 'record', - fields: [ - ['enqueued', { type: 'u64' }], - ['applied', { type: 'u64' }], - ['dropped', { type: 'u64' }], - ['failed', { type: 'u64' }], - ] -}; - -/** Record `BoardRow` (`#[derive(GameRecord)]`). */ -export interface BoardRow { - readonly rank: number; - readonly member: string; - readonly name: string; - readonly score: number; -} - -const BOARD_ROW_TYPE: WireType = { - type: 'record', - fields: [ - ['rank', { type: 'u32' }], - ['member', { type: 'short_str' }], - ['name', { type: 'short_str' }], - ['score', { type: 'f64' }], - ] -}; - -/** Record `Scores` (`#[derive(GameRecord)]`). */ -export interface Scores { - readonly kills: number; - readonly xp: number; -} - -const SCORES_TYPE: WireType = { - type: 'record', - fields: [ - ['kills', { type: 'f64' }], - ['xp', { type: 'f64' }], - ] -}; - -/** Record `Mismatch` (`#[derive(GameRecord)]`). */ -export interface Mismatch { - readonly member: string; - readonly cell: Scores; - readonly board: Scores; -} - -const MISMATCH_TYPE: WireType = { - type: 'record', - fields: [ - ['member', { type: 'short_str' }], - ['cell', SCORES_TYPE], - ['board', SCORES_TYPE], - ] -}; - -/** Record `RebuildReport` (`#[derive(GameRecord)]`). */ -export interface RebuildReport { - readonly backend: string; - readonly crawlers: number; - readonly events: number; - readonly applied: number; - readonly duplicates: number; - readonly identicalTop: boolean; - readonly matchesCells: boolean; - readonly mismatches: readonly Mismatch[]; - readonly tookMs: number; -} - -const REBUILD_REPORT_TYPE: WireType = { - type: 'record', - fields: [ - ['backend', { type: 'short_str' }], - ['crawlers', { type: 'u32' }], - ['events', { type: 'u32' }], - ['applied', { type: 'u32' }], - ['duplicates', { type: 'u32' }], - ['identicalTop', { type: 'bool' }], - ['matchesCells', { type: 'bool' }], - ['mismatches', { type: 'list', item: MISMATCH_TYPE }], - ['tookMs', { type: 'f64' }], - ] -}; - -/** Record `BoardSnapshot` (`#[derive(GameRecord)]`). */ -export interface BoardSnapshot { - readonly version: number; - readonly backend: string; - readonly members: number; - readonly kills: readonly BoardRow[]; - readonly xp: readonly BoardRow[]; - readonly background: BackgroundStats; - readonly lastRebuild: RebuildReport | undefined; -} - -const BOARD_SNAPSHOT_TYPE: WireType = { - type: 'record', - fields: [ - ['version', { type: 'u64' }], - ['backend', { type: 'short_str' }], - ['members', { type: 'u64' }], - ['kills', { type: 'list', item: BOARD_ROW_TYPE }], - ['xp', { type: 'list', item: BOARD_ROW_TYPE }], - ['background', BACKGROUND_STATS_TYPE], - ['lastRebuild', { type: 'optional', item: REBUILD_REPORT_TYPE }], - ] -}; - /** Record `MobTier` (`#[derive(GameRecord)]`). */ export interface MobTier { readonly tier: number; @@ -138,6 +20,27 @@ export interface MoveState { readonly cd: number; } +/** Record `PitRoomContext` (`#[derive(GameRecord)]`). */ +export interface PitRoomContext { + readonly seed: number; + readonly x: number; + readonly y: number; +} + +/** Record `RoomMob` (`#[derive(GameRecord)]`). */ +export interface RoomMob { + readonly tier: number; + readonly x: number; + readonly y: number; +} + +/** Record `PitRoomLayout` (`#[derive(GameRecord)]`). */ +export interface PitRoomLayout { + readonly biome: number; + readonly danger: number; + readonly mobs: readonly RoomMob[]; +} + /** Record `PitRules` (`#[derive(GameRecord)]`). */ export interface PitRules { readonly tiers: readonly MobTier[]; @@ -147,6 +50,15 @@ export interface PitRules { readonly swingFrames: number; } +/** Record `PitWorld` (`#[derive(GameRecord)]`). */ +export interface PitWorld { + readonly defaultSeed: number; + readonly half: number; + readonly doorHalf: number; + readonly maxRoom: number; + readonly biomes: readonly string[]; +} + /** Record `Profile` (`#[derive(GameRecord)]`). */ export interface Profile { readonly xp: number; @@ -173,17 +85,25 @@ const PROFILE_TYPE: WireType = { export interface HelloEvent { readonly entity: number; readonly half: number; - readonly boot: string; readonly attackRange: number; readonly attackArcCos: number; + readonly roomX: number; + readonly roomY: number; + readonly seed: number; + readonly restored: boolean; + readonly roomKills: number; } const HELLO_LAYOUT: PayloadLayout = [ ['entity', { type: 'u32' }], ['half', { type: 'f32' }], - ['boot', { type: 'short_str' }], ['attackRange', { type: 'f32' }], ['attackArcCos', { type: 'f32' }], + ['roomX', { type: 'i32' }], + ['roomY', { type: 'i32' }], + ['seed', { type: 'u32' }], + ['restored', { type: 'bool' }], + ['roomKills', { type: 'u32' }], ]; /** Event `profile` (id 2). */ @@ -243,11 +163,6 @@ const SAVED_LAYOUT: PayloadLayout = [ ['attempts', { type: 'u32' }], ]; -/** Event `board` (id 5). */ -export type BoardEvent = BoardSnapshot; - -const BOARD_PAYLOAD: WireType = BOARD_SNAPSHOT_TYPE; - /** Event `died` (id 6). */ export interface DiedEvent { readonly respawnMs: number; @@ -257,13 +172,27 @@ const DIED_LAYOUT: PayloadLayout = [ ['respawnMs', { type: 'u32' }], ]; +/** Message `loaded` (id 1). */ +export interface LoadedMessage { + readonly principal: string; + readonly xp: number; + readonly level: number; + readonly kills: number; +} + +const MESSAGE_LOADED_LAYOUT: PayloadLayout = [ + ['principal', { type: 'short_str' }], + ['xp', { type: 'u64' }], + ['level', { type: 'u32' }], + ['kills', { type: 'u32' }], +]; + /** Event type ids by name. */ export const EVENT = { hello: 1, profile: 2, kill: 3, saved: 4, - board: 5, died: 6, } as const; @@ -273,7 +202,6 @@ export interface Events { profile: ProfileEvent; kill: KillEvent; saved: SavedEvent; - board: BoardEvent; died: DiedEvent; } @@ -303,12 +231,6 @@ export const EVENTS: GameEventCodecs = { encode: (value) => encodePayload(SAVED_LAYOUT, value), decode: (payload) => decodePayload(SAVED_LAYOUT, payload) as unknown as SavedEvent }, - board: { - id: 5, - name: 'board', - encode: (value) => encodeValue(BOARD_PAYLOAD, value), - decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent - }, died: { id: 6, name: 'died', @@ -333,3 +255,32 @@ export function onEvent( ): () => void { return onGameEvent(client, EVENTS, name, handler); } + +/** Zone inbox message type ids by name. */ +export const MESSAGE = { + loaded: 1, +} as const; + +/** Zone inbox message payload types by name. */ +export interface Messages { + loaded: LoadedMessage; +} + +/** Codecs of every zone inbox message. */ +export const MESSAGES: GameEventCodecs = { + loaded: { + id: 1, + name: 'loaded', + encode: (value) => encodePayload(MESSAGE_LOADED_LAYOUT, value), + decode: (payload) => decodePayload(MESSAGE_LOADED_LAYOUT, payload) as unknown as LoadedMessage + }, +}; + +/** Encode a zone inbox message: `typeId` and `payload` of a `/admin/zone-message` body (base64url the payload). */ +export function encodeMessage( + name: K, + value: Messages[K] +): { readonly typeId: number; readonly payload: Uint8Array } { + const codec = MESSAGES[name]; + return { typeId: codec.id, payload: codec.encode(value) }; +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/index.ts b/examples/game/sveltekit/src/lib/generated/mobpit/index.ts index 481102c6c..1bb1759f5 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/index.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/index.ts @@ -6,4 +6,5 @@ export * from './constants.ts'; export * from './events.ts'; export * from './input.ts'; export * from './predict.ts'; +export * from './pures.ts'; export * from './schema.ts'; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/pures.ts b/examples/game/sveltekit/src/lib/generated/mobpit/pures.ts new file mode 100644 index 000000000..e2d25d5c2 --- /dev/null +++ b/examples/game/sveltekit/src/lib/generated/mobpit/pures.ts @@ -0,0 +1,60 @@ +// @generated by `distributed game-client` from game surface `mobpit` (schema v3, protocol v1). +// Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPures, type WasmPures, type WasmSource, type WireType } from '@hops-ops/distributed/game'; + +import type { PitRoomContext, PitRoomLayout } from './events.ts'; + +const PIT_ROOM_CONTEXT_TYPE: WireType = { + type: 'record', + fields: [ + ['seed', { type: 'u32' }], + ['x', { type: 'i32' }], + ['y', { type: 'i32' }], + ] +}; + +const ROOM_MOB_TYPE: WireType = { + type: 'record', + fields: [ + ['tier', { type: 'u8' }], + ['x', { type: 'f32' }], + ['y', { type: 'f32' }], + ] +}; + +const PIT_ROOM_LAYOUT_TYPE: WireType = { + type: 'record', + fields: [ + ['biome', { type: 'u8' }], + ['danger', { type: 'u8' }], + ['mobs', { type: 'list', item: ROOM_MOB_TYPE }], + ] +}; + +/** The pure functions (`#[game_pure]`) of Cargo package `game_sim`: wrapper name → module export. */ +export const PURES = { + pitRoom: { export: 'pit_room', abi: 1 }, +} as const; + +/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */ +export const PURES_WASM_URL: URL = new URL('./wasm/mobpit.wasm', import.meta.url); + +/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */ +export interface MobpitPureFns { + /** `pit_room` (`dg_pure_pit_room`). */ + pitRoom(arg: PitRoomContext): PitRoomLayout; +} + +/** The `mobpit` pure functions plus `ready` / `loaded()` / `module()`. */ +export type MobpitPures = WasmPures; + +/** + * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by + * the predicted step too is instantiated once). + */ +export function createMobpitPures(source: WasmSource = PURES_WASM_URL): MobpitPures { + return createWasmPures(source, { + pitRoom: { exportName: 'pit_room', arg: PIT_ROOM_CONTEXT_TYPE, output: PIT_ROOM_LAYOUT_TYPE }, + }); +} diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts index 3d9f5f004..8019b0b3f 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts @@ -131,18 +131,16 @@ export function pillarFields(entity: { readonly fields: EntityFields }): PillarF export interface PitFields { /** `u16` */ readonly pending: number; + /** `u32` */ + readonly committed: number; /** `u16` */ - readonly slowMs: number; + readonly backlog: number; /** `f32` */ readonly tickMs: number; /** `f32` */ readonly tickMaxMs: number; /** `u32` */ - readonly workUs: number; - /** `u32` */ - readonly committed: number; - /** `u16` */ - readonly backlog: number; + readonly kills: number; } /** True for a `pit` entity. */ @@ -155,12 +153,11 @@ export function pitFields(entity: { readonly fields: EntityFields }): PitFields const f = entity.fields; return { pending: fieldNumber(f, 'pending'), - slowMs: fieldNumber(f, 'slow_ms'), - tickMs: fieldNumber(f, 'tick_ms'), - tickMaxMs: fieldNumber(f, 'tick_max_ms'), - workUs: fieldNumber(f, 'work_us'), committed: fieldNumber(f, 'committed'), backlog: fieldNumber(f, 'backlog'), + tickMs: fieldNumber(f, 'tick_ms'), + tickMaxMs: fieldNumber(f, 'tick_max_ms'), + kills: fieldNumber(f, 'kills'), }; } @@ -196,12 +193,11 @@ export const FIELD_TYPES = { }, pit: { pending: { type: 'u16' }, - slow_ms: { type: 'u16' }, - tick_ms: { type: 'f32' }, - tick_max_ms: { type: 'f32' }, - work_us: { type: 'u32' }, committed: { type: 'u32' }, backlog: { type: 'u16' }, + tick_ms: { type: 'f32' }, + tick_max_ms: { type: 'f32' }, + kills: { type: 'u32' }, }, } as const satisfies Record>; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json index 05ed196c4..6c0a39c71 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json +++ b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json @@ -36,6 +36,25 @@ } ] } + }, + { + "name": "pit_world", + "type": { + "name": "PitWorld", + "type": "record" + }, + "value": { + "biomes": [ + "highlands", + "steppe", + "forest", + "meadow" + ], + "default_seed": 186474221, + "door_half": 2.5, + "half": 20.0, + "max_room": 1000000 + } } ], "events": [ @@ -57,21 +76,45 @@ } }, { - "name": "boot", + "name": "attack_range", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "attack_range", + "name": "attack_arc_cos", "type": { "type": "f32" } }, { - "name": "attack_arc_cos", + "name": "room_x", "type": { - "type": "f32" + "type": "i32" + } + }, + { + "name": "room_y", + "type": { + "type": "i32" + } + }, + { + "name": "seed", + "type": { + "type": "u32" + } + }, + { + "name": "restored", + "type": { + "type": "bool" + } + }, + { + "name": "room_kills", + "type": { + "type": "u32" } } ], @@ -224,17 +267,6 @@ "kind": "fields" } }, - { - "id": 5, - "name": "board", - "payload": { - "kind": "value", - "type": { - "name": "BoardSnapshot", - "type": "record" - } - } - }, { "id": 6, "name": "died", @@ -542,23 +574,23 @@ }, { "correction": null, - "name": "slow_ms", + "name": "committed", "priority": 1.0, "type": { - "type": "u16" + "type": "u32" } }, { "correction": null, - "name": "tick_ms", + "name": "backlog", "priority": 1.0, "type": { - "type": "f32" + "type": "u16" } }, { "correction": null, - "name": "tick_max_ms", + "name": "tick_ms", "priority": 1.0, "type": { "type": "f32" @@ -566,27 +598,19 @@ }, { "correction": null, - "name": "work_us", + "name": "tick_max_ms", "priority": 1.0, "type": { - "type": "u32" + "type": "f32" } }, { "correction": null, - "name": "committed", + "name": "kills", "priority": 1.0, "type": { "type": "u32" } - }, - { - "correction": null, - "name": "backlog", - "priority": 1.0, - "type": { - "type": "u16" - } } ], "id": 4, @@ -594,6 +618,41 @@ "priority": 1.0 } ], + "messages": [ + { + "id": 1, + "name": "loaded", + "payload": { + "fields": [ + { + "name": "principal", + "type": { + "type": "short_str" + } + }, + { + "name": "xp", + "type": { + "type": "u64" + } + }, + { + "name": "level", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], "name": "mobpit", "predict": { "abi": 1, @@ -603,213 +662,135 @@ "state": "MoveState" }, "protocolVersion": 1, - "records": [ + "pures": [ { - "fields": [ - { - "name": "enqueued", - "type": { - "type": "u64" - } - }, - { - "name": "applied", - "type": { - "type": "u64" - } - }, - { - "name": "dropped", - "type": { - "type": "u64" - } - }, - { - "name": "failed", - "type": { - "type": "u64" - } - } - ], - "name": "BackgroundStats" - }, + "abi": 1, + "arg": { + "name": "PitRoomContext", + "type": "record" + }, + "export": "pit_room", + "output": { + "name": "PitRoomLayout", + "type": "record" + }, + "package": "game_sim" + } + ], + "records": [ { "fields": [ { - "name": "rank", - "type": { - "type": "u32" - } - }, - { - "name": "member", + "name": "tier", "type": { - "type": "short_str" + "type": "u8" } }, { - "name": "name", + "name": "radius", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "score", + "name": "tele", "type": { - "type": "f64" + "type": "f32" } } ], - "name": "BoardRow" + "name": "MobTier" }, { "fields": [ { - "name": "version", - "type": { - "type": "u64" - } - }, - { - "name": "backend", + "name": "x", "type": { - "type": "short_str" + "type": "f32" } }, { - "name": "members", + "name": "y", "type": { - "type": "u64" + "type": "f32" } }, { - "name": "kills", + "name": "vx", "type": { - "item": { - "name": "BoardRow", - "type": "record" - }, - "type": "list" + "type": "f32" } }, { - "name": "xp", + "name": "vy", "type": { - "item": { - "name": "BoardRow", - "type": "record" - }, - "type": "list" + "type": "f32" } }, { - "name": "background", + "name": "dash", "type": { - "name": "BackgroundStats", - "type": "record" + "type": "u8" } }, { - "name": "last_rebuild", + "name": "cd", "type": { - "item": { - "name": "RebuildReport", - "type": "record" - }, - "type": "optional" + "type": "u8" } } ], - "name": "BoardSnapshot" + "name": "MoveState" }, { "fields": [ { - "name": "member", + "name": "seed", "type": { - "type": "short_str" + "type": "u32" } }, { - "name": "cell", + "name": "x", "type": { - "name": "Scores", - "type": "record" + "type": "i32" } }, { - "name": "board", + "name": "y", "type": { - "name": "Scores", - "type": "record" + "type": "i32" } } ], - "name": "Mismatch" + "name": "PitRoomContext" }, { "fields": [ { - "name": "tier", + "name": "biome", "type": { "type": "u8" } }, { - "name": "radius", - "type": { - "type": "f32" - } - }, - { - "name": "tele", - "type": { - "type": "f32" - } - } - ], - "name": "MobTier" - }, - { - "fields": [ - { - "name": "x", - "type": { - "type": "f32" - } - }, - { - "name": "y", - "type": { - "type": "f32" - } - }, - { - "name": "vx", - "type": { - "type": "f32" - } - }, - { - "name": "vy", - "type": { - "type": "f32" - } - }, - { - "name": "dash", + "name": "danger", "type": { "type": "u8" } }, { - "name": "cd", + "name": "mobs", "type": { - "type": "u8" + "item": { + "name": "RoomMob", + "type": "record" + }, + "type": "list" } } ], - "name": "MoveState" + "name": "PitRoomLayout" }, { "fields": [ @@ -856,123 +837,104 @@ { "fields": [ { - "name": "xp", - "type": { - "type": "u64" - } - }, - { - "name": "level", + "name": "default_seed", "type": { "type": "u32" } }, { - "name": "kills", + "name": "half", "type": { - "type": "u32" + "type": "f32" } }, { - "name": "level_xp", + "name": "door_half", "type": { - "type": "u64" + "type": "f32" } }, { - "name": "next_level_xp", + "name": "max_room", "type": { - "type": "u64" + "type": "i32" } }, { - "name": "source", + "name": "biomes", "type": { - "type": "short_str" + "item": { + "type": "short_str" + }, + "type": "list" } } ], - "name": "Profile" + "name": "PitWorld" }, { "fields": [ { - "name": "backend", - "type": { - "type": "short_str" - } - }, - { - "name": "crawlers", - "type": { - "type": "u32" - } - }, - { - "name": "events", + "name": "xp", "type": { - "type": "u32" + "type": "u64" } }, { - "name": "applied", + "name": "level", "type": { "type": "u32" } }, { - "name": "duplicates", + "name": "kills", "type": { "type": "u32" } }, { - "name": "identical_top", - "type": { - "type": "bool" - } - }, - { - "name": "matches_cells", + "name": "level_xp", "type": { - "type": "bool" + "type": "u64" } }, { - "name": "mismatches", + "name": "next_level_xp", "type": { - "item": { - "name": "Mismatch", - "type": "record" - }, - "type": "list" + "type": "u64" } }, { - "name": "took_ms", + "name": "source", "type": { - "type": "f64" + "type": "short_str" } } ], - "name": "RebuildReport" + "name": "Profile" }, { "fields": [ { - "name": "kills", + "name": "tier", + "type": { + "type": "u8" + } + }, + { + "name": "x", "type": { - "type": "f64" + "type": "f32" } }, { - "name": "xp", + "name": "y", "type": { - "type": "f64" + "type": "f32" } } ], - "name": "Scores" + "name": "RoomMob" } ], "schemaVersion": 3 diff --git a/examples/game/sveltekit/src/lib/pit/Rooms.graphql b/examples/game/sveltekit/src/lib/pit/Rooms.graphql new file mode 100644 index 000000000..671a18129 --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/Rooms.graphql @@ -0,0 +1,15 @@ +# Every room the zone status read model knows (mobpit-service's +# zone_activities, projected from the rooms' zone-activity cells): the +# minimap. SSR seeds it, `@live` keeps it current as rooms wake, empty and +# sleep. `node` is a debug detail (which celld node ran the activation). +query Rooms @load @live { + zone_activities(order_by: [{ zone_id: asc }]) { + zone_id + status + players + restored + activations + node + changed_at_ms + } +} diff --git a/examples/game/sveltekit/src/lib/pit/Rooms.svelte b/examples/game/sveltekit/src/lib/pit/Rooms.svelte new file mode 100644 index 000000000..64f9e359c --- /dev/null +++ b/examples/game/sveltekit/src/lib/pit/Rooms.svelte @@ -0,0 +1,80 @@ + + +
      + {#each grid as line, j (j)} + {#each line as cell (cell.zone)} +
      + {#if cell.row && cell.row.players > 0}{cell.row.players}{/if} + {#if debug && cell.row?.node}{cell.row.node.replace(/^node-/, '')}{/if} +
      + {/each} + {/each} +
      +
      ■ active ■ dormant ■ asleep ■ never ran
      + + diff --git a/examples/game/sveltekit/src/lib/pit/loop.ts b/examples/game/sveltekit/src/lib/pit/loop.ts index ddec7fb60..f6c751541 100644 --- a/examples/game/sveltekit/src/lib/pit/loop.ts +++ b/examples/game/sveltekit/src/lib/pit/loop.ts @@ -9,6 +9,7 @@ import { InputPacer, type GameClient } from '@hops-ops/distributed/game'; import { BUTTON, PIT_RULES, + PIT_WORLD, isMob, isPillar, isPlayer, @@ -22,6 +23,7 @@ import { const TIER_COLOR: Record = { 1: '#9ad16b', 2: '#b48cf2', 3: '#ff6b6b' }; const TIER_RADIUS = Object.fromEntries(PIT_RULES.tiers.map((t) => [t.tier, t])); const PLAYER_RADIUS = 0.45; +const DOOR_HALF = PIT_WORLD.doorHalf; /** Swing cone, from the server's rules (reach to a mob's edge, plus the body). */ const SWING_REACH = PIT_RULES.attackRange + PLAYER_RADIUS; const SWING_HALF = PIT_RULES.attackHalfAngle; @@ -49,7 +51,8 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) const steer = (): PitInput => { const hello = options.hello(); - const rendered = client.render(); + const room = client.authority?.zoneId; + const rendered = client.render().filter((e) => room === undefined || e.zoneId === room); const me = rendered.find((e) => e.id === hello?.entity && isPlayer(e)); if (options.autoHunt() && me !== undefined) { const p = playerFields(me); @@ -79,6 +82,10 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) let frame = requestAnimationFrame(function draw(now) { pacer.update(now, () => client.sendInput(steer())); const half = options.hello()?.half ?? 12; + // Only the room the player is in (during a doorway handoff the + // client briefly holds both). + const room = client.authority?.zoneId; + if (room !== undefined) canvas.dataset.room = room; const { width, height } = canvas; const scale = Math.min(width, height) / (2 * half); const at = (x: number, y: number): [number, number] => [width / 2 + x * scale, height / 2 - y * scale]; @@ -97,7 +104,23 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) ctx.fillRect(0, 0, width, height); ctx.strokeStyle = '#2b2533'; ctx.strokeRect(...at(-half, half), 2 * half * scale, 2 * half * scale); + // Doorways: the middle of each wall leads to the neighbouring room. + ctx.strokeStyle = '#4dd0e1'; + ctx.lineWidth = 4; + for (const [x0, y0, x1, y1] of [ + [half, -DOOR_HALF, half, DOOR_HALF], + [-half, -DOOR_HALF, -half, DOOR_HALF], + [-DOOR_HALF, half, DOOR_HALF, half], + [-DOOR_HALF, -half, DOOR_HALF, -half] + ]) { + ctx.beginPath(); + ctx.moveTo(...at(x0!, y0!)); + ctx.lineTo(...at(x1!, y1!)); + ctx.stroke(); + } + ctx.lineWidth = 1; for (const entity of client.render()) { + if (room !== undefined && entity.zoneId !== room) continue; if (isPillar(entity)) { const p = pillarFields(entity); circle(p.x, p.y, p.r, '#3a3443'); diff --git a/examples/game/sveltekit/src/lib/server/game.ts b/examples/game/sveltekit/src/lib/server/game.ts index d8ec1c7dd..df887a769 100644 --- a/examples/game/sveltekit/src/lib/server/game.ts +++ b/examples/game/sveltekit/src/lib/server/game.ts @@ -2,10 +2,37 @@ import { env } from '$env/dynamic/private'; import type { RequestEvent } from '@sveltejs/kit'; import { createGameTicketHandler } from '@hops-ops/distributed/sveltekit/game/server'; -/** Zone admission: principal from the Auth.js session, zone chosen here. */ +/** The room every player starts in. */ +export const ENTRANCE = 'pit.0.0'; + +/** `pit..` with canonical integers (the rooms' grid). */ +export function isRoom(zone: string | undefined): zone is string { + const m = zone === undefined ? null : /^pit\.(-?\d+)\.(-?\d+)$/.exec(zone); + return m !== null && m.slice(1).every((v) => String(Number(v)) === v && Math.abs(Number(v)) <= 1_000_000); +} + +/** + * Room admission: principal from the Auth.js session, the room chosen here — + * the entrance for a fresh join; the room the client asks for when it + * rejoins one (a room that restarted closes sockets with 1012, a reload). + * Moving between rooms needs no ticket from here: a doorway hands the player + * over with a transfer ticket the room itself signs. + */ export const tickets = createGameTicketHandler({ secret: () => env.GAME_TICKET_SECRET, getSession: (event: RequestEvent) => event.locals.auth(), - // One shared pit; a real game picks the zone the player is in or owns. - zone: () => env.PIT_ZONE ?? 'pit-1' + zone: ({ requested }) => (isRoom(requested) ? requested : ENTRANCE) }); + +/** + * Where browsers reach the rooms: celld's public listeners (`ws://…`, + * comma separated for a local fleet; a load balancer in production). The + * page rotates over them per connection — an entry point, never a + * placement: celld forwards every socket to the node that runs the room. + */ +export function roomsUrls(): string[] { + return (env.GAME_ZONES_URL ?? 'ws://127.0.0.1:2970') + .split(',') + .map((u) => u.trim()) + .filter((u) => u.length > 0); +} diff --git a/examples/game/sveltekit/src/routes/pit/+page.server.ts b/examples/game/sveltekit/src/routes/pit/+page.server.ts index e987cd5fb..bdc482118 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.server.ts +++ b/examples/game/sveltekit/src/routes/pit/+page.server.ts @@ -1,8 +1,7 @@ import { redirect } from '@sveltejs/kit'; -import { env } from '$env/dynamic/private'; import { loadDistributedLeaderboard } from '@hops-ops/distributed/sveltekit'; import { XpLeaderboardLeaderboard, type XpLeaderboardData } from '$distributed'; -import { tickets } from '$lib/server/game'; +import { roomsUrls, tickets } from '$lib/server/game'; import { graphqlUrl } from '$lib/server/distributed'; export const load = async (event) => { @@ -23,7 +22,7 @@ export const load = async (event) => { } return { zone: joined.zone, - zonesUrl: env.GAME_ZONES_URL ?? 'ws://127.0.0.1:2967', + roomsUrls: roomsUrls(), principal: joined.principal, board }; diff --git a/examples/game/sveltekit/src/routes/pit/+page.svelte b/examples/game/sveltekit/src/routes/pit/+page.svelte index f3d8fde83..031f0025b 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.svelte +++ b/examples/game/sveltekit/src/routes/pit/+page.svelte @@ -3,16 +3,20 @@ import { createMobpitClient, EVENTS } from '$lib/generated/mobpit/index.ts'; import Leaderboard from '$lib/pit/Leaderboard.svelte'; import MyStats from '$lib/pit/MyStats.svelte'; + import Rooms from '$lib/pit/Rooms.svelte'; import { startPitLoop } from '$lib/pit/loop'; let { data } = $props(); - // Client built on mount (browser only), joins the server-chosen zone, + // Client built on mount (browser only), joins the server-chosen room, // closed on navigation. Tickets come from /api/game/ticket (session). + // Rooms are celld objects: any entry point reaches any room (celld + // forwards); the page rotates over the entry points it was given. + let entry = 0; const game = useGame( () => createMobpitClient({ - url: (zone) => `${data.zonesUrl}/zones/${encodeURIComponent(zone)}`, + url: (zone) => `${data.roomsUrls[entry++ % data.roomsUrls.length]}/rooms/${encodeURIComponent(zone)}`, ticket: gameTicketSource(), pingIntervalMs: 500, inputDtMs: 1000 / 30 @@ -22,7 +26,43 @@ const hello = game.latest('hello'); const kills = game.events('kill', { limit: 20 }); const saved = game.events('saved', { limit: 20 }); - game.on('hello', (h) => game.client?.setControlledEntity(h.entity)); + game.on('hello', (h) => { + game.client?.setControlledEntity(h.entity); + if (h.restored) toast(`pit.${h.roomX}.${h.roomY}: restored from hibernation (${h.roomKills} kills here so far)`); + }); + + // Toasts (room restores, sleeps). + let toasts = $state<{ id: number; text: string }[]>([]); + let toastSeq = 0; + function toast(text: string) { + const id = ++toastSeq; + toasts = [...toasts, { id, text }]; + setTimeout(() => (toasts = toasts.filter((t) => t.id !== id)), 6000); + } + + // Debug overlay: the room object's own view (which celld node runs it — + // celld decides; this only shows it). + let debug = $state(true); + type RoomInfo = { zone: string; node: string; isolate: string; activation: string; wakes: number; restored: boolean; players: number; hz: number; lateMs: { p50: number; p99: number } }; + let info = $state(); + $effect(() => { + const zone = game.zone; + if (!debug || zone === undefined) return; + const http = (data.roomsUrls[0] ?? '').replace(/^ws/, 'http'); + let stop = false; + const poll = async () => { + while (!stop) { + try { + info = await (await fetch(`${http}/rooms/${encodeURIComponent(zone)}/info`)).json(); + } catch { + // the room's node is moving; keep the last view + } + await new Promise((r) => setTimeout(r, 1000)); + } + }; + void poll(); + return () => (stop = true); + }); let canvas = $state(); let autoHunt = $state(false); @@ -43,12 +83,26 @@ +
      + {#each toasts as t (t.id)}
      {t.text}
      {/each} +
      - - - -

      - - - diff --git a/examples/game/zone-do-spike/run.sh b/examples/game/zone-do-spike/run.sh deleted file mode 100755 index 3db39e0c8..000000000 --- a/examples/game/zone-do-spike/run.sh +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env bash -# Spike gr-p42: Mob Pit rooms as celld Durable Objects on a local -# multi-node celld fleet (production mode, one shared S3 bucket). -# -# ./run.sh up [N] S3 container + bucket, build, deploy, N nodes (default 3) -# ./run.sh deploy rebuild and publish a new version (nodes adopt it live) -# ./run.sh nodes [N] start N nodes ./run.sh kill SIGKILL one node -# ./run.sh status per-node owned/resident cells (operator view) -# ./run.sh down stop nodes, remove the S3 container -# -# Nodes: node-a/b/c, public 127.0.0.1:18101-18103 (open any of them in a -# browser: /?room=pit-1&name=ana), operator 127.0.0.1:18201-18203. -# Needs: CELLD (celld >= 0.6.2), worker-build, esbuild (CELLD_ESBUILD), docker. -set -euo pipefail -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -STATE="${SPIKE_STATE:-$HERE/.run}" -CELLD="${CELLD:-celld}" -export CELLD_ESBUILD="${CELLD_ESBUILD:-$HERE/../client/node_modules/.bin/esbuild}" -export AWS_ACCESS_KEY_ID=spikeadmin AWS_SECRET_ACCESS_KEY=spikesecret123 AWS_REGION=us-east-1 -S3_PORT="${S3_PORT:-19400}" -export S3_ENDPOINT="http://127.0.0.1:$S3_PORT" -BUCKET="s3://zone-spike/zone" -NAMES=(a b c d) -mkdir -p "$STATE" - -s3_up() { - S3_PORT="$S3_PORT" docker compose -p zone-do-spike -f "$HERE/tools/s3-compose.yaml" up -d >/dev/null 2>&1 - for _ in $(seq 1 30); do curl -s -o /dev/null "$S3_ENDPOINT/" && break; sleep 1; done - aws --endpoint-url "$S3_ENDPOINT" s3 mb s3://zone-spike >/dev/null 2>&1 || true -} - -build() { - (cd "$HERE" && worker-build --release >/dev/null) - "$CELLD_ESBUILD" "$HERE/page/main.ts" --bundle --format=esm --target=es2022 \ - --outfile="$HERE/public/page.js" --log-level=warning -} - -deploy() { - build - (cd "$HERE" && "$CELLD" deploy . --bucket "$BUCKET" 2>&1 | grep -E "Version ID|rror") -} - -nodes() { - local n="${1:-3}" - for i in $(seq 0 $((n - 1))); do - local nm=${NAMES[$i]} dir="$STATE/node-${NAMES[$i]}" - mkdir -p "$dir" - [[ -f "$dir/pid" ]] && kill -0 "$(cat "$dir/pid")" 2>/dev/null && continue - CELLD_NODE="node-$nm" CELLD_WATCH="$dir/watch" RUST_LOG="${RUST_LOG:-warn}" \ - CELLD_IDLE_EVICT_S="${CELLD_IDLE_EVICT_S:-10}" \ - nohup "$CELLD" --bucket "$BUCKET" --listen "127.0.0.1:$((18101 + i))" \ - --internal-listen "127.0.0.1:$((18201 + i))" --advertise "127.0.0.1:$((18201 + i))" \ - >"$dir/celld.log" 2>&1 & - echo $! >"$dir/pid" - echo "node-$nm: http://127.0.0.1:$((18101 + i))/ (operator :$((18201 + i)), pid $!)" - done - for i in $(seq 0 $((n - 1))); do - for _ in $(seq 1 60); do curl -fs "http://127.0.0.1:$((18101 + i))/ticket" >/dev/null && break; sleep 0.5; done - done -} - -status() { - for i in 0 1 2 3; do - curl -s -m 2 "http://127.0.0.1:$((18201 + i))/state" 2>/dev/null | python3 -c ' -import json,sys -d=json.load(sys.stdin); l=d["node_load"] -print(sys.argv[1], "owned", d["owned_cells"], "resident", l["resident_cells"], "cpu%", l["cpu_percent_x100"]/100, "rebalanced", d["rebalanced"], "version", d["deployment"]["version"])' "node-${NAMES[$i]}" 2>/dev/null || true - done -} - -down() { - for nm in "${NAMES[@]}"; do - local f="$STATE/node-$nm/pid" - [[ -f $f ]] && { kill "$(cat "$f")" 2>/dev/null || true; rm -f "$f"; } - done - docker compose -p zone-do-spike -f "$HERE/tools/s3-compose.yaml" down -v >/dev/null 2>&1 || true -} - -case "${1:-}" in -up) s3_up; deploy; nodes "${2:-3}" ;; -deploy) deploy ;; -nodes) nodes "${2:-3}" ;; -kill) kill -9 "$(cat "$STATE/node-$2/pid")"; rm -f "$STATE/node-$2/pid"; echo "killed node-$2" ;; -status) status ;; -down) down ;; -*) sed -n '2,13p' "$0"; exit 1 ;; -esac diff --git a/examples/game/zone-do-spike/src/lib.rs b/examples/game/zone-do-spike/src/lib.rs deleted file mode 100644 index 8ae065785..000000000 --- a/examples/game/zone-do-spike/src/lib.rs +++ /dev/null @@ -1,755 +0,0 @@ -//! Spike gr-p42: a live Mob Pit room as a celld Durable Object. -//! -//! - `GET /ticket?room=&name=` (dev only): a signed join ticket, the same -//! HS256 format the native zone server admits (`distributed_game::ticket`). -//! - `GET /rooms/{room}` (WebSocket upgrade): the room object named `room`. -//! The client speaks the existing `distributed_game` wire protocol: Hello -//! with the ticket, then Input / Ping / Leave; the room answers Welcome, -//! Delta, Event, Pong. -//! - `GET /rooms/{room}/stats`: tick timing numbers of the room (JSON). -//! - `GET /placement?rooms=a,b`: which node owns each room (operator view). -//! - everything else: the static debug page (`public/`). -//! -//! The room (`PitRoom`) runs a `ZoneHost` in the object's memory. It -//! ticks with a `setTimeout` loop while any player is in it, writes its -//! hibernation snapshot to object storage every few seconds and when the -//! last player leaves, then stops; celld may then evict it. The next join -//! reactivates it on whichever node owns it and restores the snapshot. -//! -//! celld does not tell application code which node runs it, so the room -//! asks every node's operator listener (`NODES`) whether it holds the room. - -mod pit; - -use std::cell::RefCell; -use std::collections::{HashMap, HashSet, VecDeque}; -use std::rc::Rc; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::Duration; - -use distributed_game::protocol::{error, ClientMessage, ServerMessage, PROTOCOL_VERSION}; -use distributed_game::ticket::TicketKey; -use distributed_game::{Clock, HostConfig, Outbound, Role, TicketClaims, ZoneHost}; -use pit::Pit; -use serde::{Deserialize, Serialize}; -use serde_json::json; -use worker::*; - -const SNAPSHOT_KEY: &str = "pit-snapshot"; -const PERSIST_EVERY_MS: f64 = 5_000.0; - -// ------------------------------------------------------------------ time - -fn performance_now() -> f64 { - let global = js_sys::global(); - js_sys::Reflect::get(&global, &"performance".into()) - .ok() - .and_then(|p| { - let now = js_sys::Reflect::get(&p, &"now".into()).ok()?; - let now: js_sys::Function = now.into(); - now.call0(&p).ok()?.as_f64() - }) - .unwrap_or_else(js_sys::Date::now) -} - -/// Monotonic clock over `Date.now()` (`Instant` panics on wasm32). -struct JsClock { - origin_ms: f64, - last_us: AtomicU64, -} - -impl JsClock { - fn new() -> Self { - Self { - origin_ms: js_sys::Date::now(), - last_us: AtomicU64::new(0), - } - } -} - -impl Clock for JsClock { - fn now(&self) -> Duration { - let us = ((js_sys::Date::now() - self.origin_ms).max(0.0) * 1000.0) as u64; - let us = self.last_us.fetch_max(us, Ordering::Relaxed).max(us); - Duration::from_micros(us) - } - - fn unix_ms(&self) -> u64 { - self.origin_ms as u64 + self.now().as_millis() as u64 - } -} - -fn random_id() -> String { - format!( - "{:08x}", - (js_sys::Math::random() * f64::from(u32::MAX)) as u32 - ) -} - -thread_local! { - /// One id per V8 isolate (module instance). - static ISOLATE: String = random_id(); - /// Rooms alive in this isolate. - static ISOLATE_ROOMS: RefCell> = RefCell::new(HashSet::new()); -} - -// ------------------------------------------------------------------ stats - -/// Loop timing over the life of an activation. -#[derive(Default)] -struct TickStats { - /// How late each wake-up was against its deadline (ms). - late: VecDeque, - /// Interval between consecutive loop iterations (ms). - interval: VecDeque, - /// Work per iteration (ms; advance + sends). - work: VecDeque, - /// Fixed steps dropped by the catch-up cap. - dropped_ticks: u64, - /// Iterations that ran more than one fixed step (catch-up). - catch_up: u64, - iterations: u64, - last_wake: Option, - late_ema: f64, - work_ema: f64, - late_max_window: f64, - window: u32, - late_max: f64, -} - -const STAT_WINDOW: usize = 20_000; - -fn push(q: &mut VecDeque, v: f64) { - if q.len() == STAT_WINDOW { - q.pop_front(); - } - q.push_back(v); -} - -fn pct(q: &VecDeque, p: f64) -> f64 { - if q.is_empty() { - return 0.0; - } - let mut v: Vec = q.iter().copied().collect(); - v.sort_by(|a, b| a.total_cmp(b)); - v[((v.len() - 1) as f64 * p).round() as usize] -} - -// ------------------------------------------------------------------ room - -#[derive(Serialize, Deserialize)] -struct Attachment { - client: u32, - activation: String, -} - -struct Room { - name: String, - id_hex: String, - activation: String, - constructed_ms: f64, - host: Option>, - sockets: HashMap, - ticking: bool, - hz: u32, - key: TicketKey, - nonces: HashSet, - stats: TickStats, - first_tick_ms: Option, - restored: bool, - node: String, - welcome_ms: Vec, -} - -impl Room { - fn flush(&mut self) { - let Some(host) = self.host.as_mut() else { - return; - }; - for out in host.drain_outbound() { - match out { - Outbound::Frame { client, frame } => { - if let Some(ws) = self.sockets.get(&client.0) { - let _ = ws.send_with_bytes(frame); - } - } - Outbound::Close { client } => { - if let Some(ws) = self.sockets.remove(&client.0) { - let _ = ws.close(Some(1000), Some("closed by zone")); - } - } - } - } - } - - fn occupied(&self) -> bool { - self.host - .as_ref() - .is_some_and(|h| h.player_count() > 0 || h.client_count() > 0) - } - - fn snapshot(&self) -> Option { - let state = self.host.as_ref()?.hibernate_state()?; - String::from_utf8(state).ok() - } - - fn sync_host_info(&mut self) { - let isolate_rooms = ISOLATE_ROOMS.with(|r| r.borrow().len()) as u16; - let (late, late_max, work) = ( - self.stats.late_ema, - self.stats.late_max, - self.stats.work_ema, - ); - let wake_ms = self - .first_tick_ms - .map(|t| (t - self.constructed_ms).max(0.0) as u32) - .unwrap_or(0); - let (node, restored, hz) = (self.node.clone(), self.restored, self.hz as u8); - if let Some(host) = self.host.as_mut() { - let zone = host.zone_mut(); - let activations = zone.activations; - let info = &mut zone.host; - info.node = node; - info.restored = restored; - info.activations = activations; - info.hz = hz; - info.late_ms = late as f32; - info.late_max_ms = late_max as f32; - info.work_us = (work * 1000.0) as u32; - info.wake_ms = wake_ms; - info.isolate_rooms = isolate_rooms; - } - } -} - -#[durable_object] -pub struct PitRoom { - state: State, - env: Env, - room: Rc>, -} - -impl DurableObject for PitRoom { - fn new(state: State, env: Env) -> Self { - console_error_panic_hook::set_once(); - let constructed_ms = performance_now(); - let id_hex = state.id().to_string(); - let name = state.id().name().unwrap_or_default(); - let hz = env - .var("TICK_HZ") - .ok() - .and_then(|v| v.to_string().parse().ok()) - .unwrap_or(30); - let secret = env - .var("TICKET_SECRET") - .map(|v| v.to_string()) - .unwrap_or_default(); - let room = Room { - name, - id_hex, - activation: random_id(), - constructed_ms, - host: None, - sockets: HashMap::new(), - ticking: false, - hz, - key: TicketKey::new(secret.into_bytes()), - nonces: HashSet::new(), - stats: TickStats::default(), - first_tick_ms: None, - restored: false, - node: "?".into(), - welcome_ms: Vec::new(), - }; - Self { - state, - env, - room: Rc::new(RefCell::new(room)), - } - } - - async fn fetch(&self, req: Request) -> Result { - let url = req.url()?; - if let Some(name) = req.headers().get("x-room")? { - let mut room = self.room.borrow_mut(); - if room.name.is_empty() { - room.name = name; - } - } - self.ensure_host().await?; - if url.path().ends_with("/stats") { - if url.query_pairs().any(|(k, _)| k == "reset") { - self.room.borrow_mut().stats = TickStats::default(); - } - return Response::from_json(&self.stats_json()); - } - if req.headers().get("upgrade")?.as_deref() != Some("websocket") { - return Response::error("expected a WebSocket upgrade", 426); - } - let pair = WebSocketPair::new()?; - self.state.accept_web_socket(&pair.server); - Response::from_websocket(pair.client) - } - - async fn websocket_message( - &self, - ws: WebSocket, - message: WebSocketIncomingMessage, - ) -> Result<()> { - let WebSocketIncomingMessage::Binary(bytes) = message else { - let _ = ws.close(Some(1003), Some("binary frames only")); - return Ok(()); - }; - self.ensure_host().await?; - let msg = match ClientMessage::decode(&bytes) { - Ok(m) => m, - Err(_) => { - reject(&ws, error::BAD_MESSAGE, "bad message"); - return Ok(()); - } - }; - let attached: Option = ws.deserialize_attachment().ok().flatten(); - let activation = self.room.borrow().activation.clone(); - let client = match attached { - Some(a) if a.activation == activation => Some(a.client), - // The socket outlived the activation that admitted it (the room - // was evicted and woke up again): its player is gone. - Some(_) => { - let _ = ws.close(Some(1012), Some("room restarted; rejoin")); - return Ok(()); - } - None => None, - }; - match (client, msg) { - (None, ClientMessage::Hello(hello)) => { - let t0 = performance_now(); - if hello.protocol_version != PROTOCOL_VERSION { - reject(&ws, error::VERSION_MISMATCH, "protocol version"); - return Ok(()); - } - let joined = { - let mut room = self.room.borrow_mut(); - let now = (js_sys::Date::now() / 1000.0) as u64; - let claims = match room.key.verify(&hello.ticket, now) { - Ok(c) => c, - Err(e) => { - drop(room); - reject(&ws, error::UNAUTHORIZED, &format!("{e:?}")); - return Ok(()); - } - }; - if claims.zone != room.name || !room.nonces.insert(claims.nonce.clone()) { - drop(room); - reject(&ws, error::UNAUTHORIZED, "wrong room or replayed ticket"); - return Ok(()); - } - room.sync_host_info(); - let host = room.host.as_mut().expect("host loaded"); - match host.join(&claims, hello.capabilities, &hello.content_version) { - Ok(joined) => { - let client = joined.client.0; - ws.serialize_attachment(Attachment { - client, - activation: activation.clone(), - })?; - room.sockets.insert(client, ws.clone()); - room.flush(); - let elapsed = performance_now() - t0; - room.welcome_ms.push(elapsed); - Ok(()) - } - Err(e) => Err(e), - } - }; - match joined { - Ok(()) => self.start_loop(), - Err(e) => reject(&ws, e.code, &e.message), - } - } - ( - Some(client), - ClientMessage::Input { - seq, - client_tick, - payload, - }, - ) => { - let mut room = self.room.borrow_mut(); - if let Some(host) = room.host.as_mut() { - host.push_input( - distributed_game::ClientId(client), - seq, - client_tick, - &payload, - ); - } - } - (_, ClientMessage::Ping { client_time }) => { - let room = self.room.borrow(); - let server_time = room.host.as_ref().map_or(0.0, |h| h.server_time_ms()); - let pong = ServerMessage::Pong { - client_time, - server_time, - } - .encode(&()) - .expect("pong encodes"); - let _ = ws.send_with_bytes(pong); - } - (Some(client), ClientMessage::Leave) => { - let mut room = self.room.borrow_mut(); - room.sockets.remove(&client); - if let Some(host) = room.host.as_mut() { - host.disconnect(distributed_game::ClientId(client), true); - } - room.flush(); - let _ = ws.close(Some(1000), Some("left")); - } - _ => reject(&ws, error::BAD_MESSAGE, "unexpected message"), - } - Ok(()) - } - - async fn websocket_close( - &self, - ws: WebSocket, - _code: usize, - _reason: String, - _was_clean: bool, - ) -> Result<()> { - self.drop_socket(&ws); - Ok(()) - } - - async fn websocket_error(&self, ws: WebSocket, _error: Error) -> Result<()> { - self.drop_socket(&ws); - Ok(()) - } -} - -fn reject(ws: &WebSocket, code: u32, message: &str) { - if let Ok(frame) = (ServerMessage::Error { - code, - message: message.into(), - }) - .encode(&()) - { - let _ = ws.send_with_bytes(frame); - } - let _ = ws.close(Some(1008), Some(message)); -} - -impl PitRoom { - fn drop_socket(&self, ws: &WebSocket) { - let attached: Option = ws.deserialize_attachment().ok().flatten(); - let mut room = self.room.borrow_mut(); - if let Some(a) = attached.filter(|a| a.activation == room.activation) { - room.sockets.remove(&a.client); - if let Some(host) = room.host.as_mut() { - host.disconnect(distributed_game::ClientId(a.client), false); - } - } - } - - /// Create the zone host on first use: restore the stored snapshot and - /// find out which node this is. - async fn ensure_host(&self) -> Result<()> { - if self.room.borrow().host.is_some() { - return Ok(()); - } - let stored: Option = self.state.storage().get(SNAPSHOT_KEY).await?; - let mut room = self.room.borrow_mut(); - if room.host.is_some() { - return Ok(()); - } - // `name@20` runs the room at 20 Hz (measurements). - if let Some(hz) = room - .name - .split_once('@') - .and_then(|(_, hz)| hz.parse().ok()) - { - room.hz = hz; - } - let config = HostConfig { - tick_rate: room.hz, - patch_rate: room.hz.min(20), - // The Durable Object stops ticking when empty instead. - idle_tick_rate: None, - boot_epoch: (js_sys::Date::now() * 1000.0) as u64, - reconnect_grace: Duration::from_secs(5), - ..HostConfig::default() - }; - let name = room.name.clone(); - let mut host = ZoneHost::::new(name.clone(), config, Arc::new(JsClock::new()), ()) - .with_token_source(|| format!("{}{}", random_id(), random_id())); - if let Some(state) = stored { - host.restore(state.as_bytes(), ""); - room.restored = true; - } - { - let activation = room.activation.clone(); - let info = &mut host.zone_mut().host; - info.activation = activation; - info.isolate = ISOLATE.with(|i| i.clone()); - } - room.host = Some(host); - ISOLATE_ROOMS.with(|r| r.borrow_mut().insert(name)); - drop(room); - self.find_node(); - Ok(()) - } - - /// Ask each node's operator listener whether it holds this room. - fn find_node(&self) { - let nodes = self - .env - .var("NODES") - .map(|v| v.to_string()) - .unwrap_or_default(); - let room = self.room.clone(); - let id_hex = room.borrow().id_hex.clone(); - wasm_bindgen_futures::spawn_local(async move { - for entry in nodes.split(',').filter(|e| !e.is_empty()) { - let Some((node, addr)) = entry.split_once('=') else { - continue; - }; - let Ok(mut resp) = Fetch::Url( - format!("http://{addr}/state") - .parse() - .expect("operator url"), - ) - .send() - .await - else { - continue; - }; - let Ok(state) = resp.json::().await else { - continue; - }; - let mine = state["deployment"]["cells"] - .as_object() - .is_some_and(|cells| cells.keys().any(|k| k.ends_with(&id_hex))); - if mine { - let mut room = room.borrow_mut(); - room.node = node.to_string(); - room.sync_host_info(); - return; - } - } - }); - } - - fn start_loop(&self) { - { - let mut room = self.room.borrow_mut(); - if room.ticking { - return; - } - room.ticking = true; - } - let room = self.room.clone(); - let storage = self.state.storage(); - wasm_bindgen_futures::spawn_local(async move { - let step_ms = 1000.0 / f64::from(room.borrow().hz); - let start = performance_now(); - let mut k: u64 = 1; - let mut last_persist = start; - loop { - let deadline = start + k as f64 * step_ms; - let wait = (deadline - performance_now()).max(0.0); - Delay::from(Duration::from_micros((wait * 1000.0) as u64)).await; - let woke = performance_now(); - // Skip deadlines we already missed (the fixed timestep - // catches up with several steps in one advance). - k = (((woke - start) / step_ms).floor() as u64 + 1).max(k + 1); - let (stop, snapshot) = { - let mut room = room.borrow_mut(); - let late = (woke - deadline).max(0.0); - let interval = room.stats.last_wake.map(|l| woke - l); - let report = room.host.as_mut().map(|h| h.advance()); - if room.first_tick_ms.is_none() { - room.first_tick_ms = Some(woke); - } - room.flush(); - let work = performance_now() - woke; - let s = &mut room.stats; - s.iterations += 1; - s.last_wake = Some(woke); - push(&mut s.late, late); - if let Some(i) = interval { - push(&mut s.interval, i); - } - push(&mut s.work, work); - if let Some(r) = &report { - s.dropped_ticks += u64::from(r.dropped_ticks); - if r.ticks > 1 { - s.catch_up += 1; - } - } - s.late_ema = if s.iterations == 1 { - late - } else { - s.late_ema * 0.95 + late * 0.05 - }; - s.work_ema = if s.iterations == 1 { - work - } else { - s.work_ema * 0.95 + work * 0.05 - }; - s.late_max_window = s.late_max_window.max(late); - s.window += 1; - if s.window >= room.hz { - let s = &mut room.stats; - s.late_max = s.late_max_window; - s.late_max_window = 0.0; - s.window = 0; - } - room.sync_host_info(); - let stop = !room.occupied(); - let persist = stop || woke - last_persist >= PERSIST_EVERY_MS; - if stop { - room.ticking = false; - } - (stop, persist.then(|| room.snapshot()).flatten()) - }; - if let Some(snapshot) = snapshot { - last_persist = woke; - if let Err(e) = storage.put(SNAPSHOT_KEY, snapshot).await { - console_error!("persist failed: {e}"); - } - } - if stop { - return; - } - } - }); - } - - fn stats_json(&self) -> serde_json::Value { - let room = self.room.borrow(); - let s = &room.stats; - let host = room.host.as_ref(); - json!({ - "room": room.name, - "node": room.node, - "isolate": ISOLATE.with(|i| i.clone()), - "activation": room.activation, - "restored": room.restored, - "hz": room.hz, - "ticking": room.ticking, - "players": host.map_or(0, |h| h.player_count()), - "tick": host.map_or(0, |h| h.tick()), - "lifetime_ticks": host.map_or(0, |h| h.zone().ticks()), - "kills": host.map_or(0, |h| h.zone().kills), - "activations": host.map_or(0, |h| h.zone().activations), - "isolate_rooms": ISOLATE_ROOMS.with(|r| r.borrow().len()), - "wake_ms": room.first_tick_ms.map(|t| t - room.constructed_ms), - "welcome_ms": room.welcome_ms, - "iterations": s.iterations, - "dropped_ticks": s.dropped_ticks, - "catch_up_iterations": s.catch_up, - "late_ms": {"p50": pct(&s.late, 0.5), "p99": pct(&s.late, 0.99), "max": pct(&s.late, 1.0)}, - "interval_ms": {"p50": pct(&s.interval, 0.5), "p99": pct(&s.interval, 0.99), "max": pct(&s.interval, 1.0)}, - "work_ms": {"p50": pct(&s.work, 0.5), "p99": pct(&s.work, 0.99), "max": pct(&s.work, 1.0)}, - }) - } -} - -// ------------------------------------------------------------------ worker - -fn ticket(env: &Env, room: &str, name: &str) -> Result { - let secret = env.var("TICKET_SECRET")?.to_string(); - let key = TicketKey::new(secret.into_bytes()); - let exp = (js_sys::Date::now() / 1000.0) as u64 + 300; - let principal = format!("guest:{name}"); - let claims = TicketClaims::new( - principal, - room, - exp, - random_id() + &random_id(), - Role::Player, - ) - .with_name(name); - Ok(key.sign(&claims)) -} - -async fn placement(env: &Env, rooms: &str) -> Result { - let ns = env.durable_object("PIT_ROOM")?; - let mut ids = Vec::new(); - for room in rooms.split(',').filter(|r| !r.is_empty()) { - ids.push((room.to_string(), ns.id_from_name(room)?.to_string())); - } - let nodes = env.var("NODES")?.to_string(); - let mut out = serde_json::Map::new(); - let mut node_rows = Vec::new(); - for entry in nodes.split(',').filter(|e| !e.is_empty()) { - let Some((node, addr)) = entry.split_once('=') else { - continue; - }; - let state = match Fetch::Url(format!("http://{addr}/state").parse()?) - .send() - .await - { - Ok(mut r) => r.json::().await.ok(), - Err(_) => None, - }; - let Some(state) = state else { - node_rows.push(json!({"node": node, "up": false})); - continue; - }; - let cells = state["deployment"]["cells"] - .as_object() - .cloned() - .unwrap_or_default(); - for (room, id) in &ids { - if cells.keys().any(|k| k.ends_with(id.as_str())) { - out.insert(room.clone(), json!(node)); - } - } - node_rows.push(json!({ - "node": node, - "up": true, - "resident_cells": state["node_load"]["resident_cells"], - "owned_cells": state["owned_cells"], - "cpu_percent": state["node_load"]["cpu_percent_x100"].as_f64().map(|c| c / 100.0), - "rebalanced": state["rebalanced"], - })); - } - Response::from_json(&json!({"rooms": out, "nodes": node_rows})) -} - -#[event(fetch)] -async fn main(req: Request, env: Env, _ctx: Context) -> Result { - console_error_panic_hook::set_once(); - let url = req.url()?; - let path = url.path().to_string(); - let query: HashMap = url.query_pairs().into_owned().collect(); - if path == "/ticket" { - let room = query.get("room").cloned().unwrap_or_else(|| "pit-1".into()); - let name = query.get("name").cloned().unwrap_or_else(|| "guest".into()); - return Response::from_json(&json!({"ticket": ticket(&env, &room, &name)?})); - } - if path == "/placement" { - return placement(&env, query.get("rooms").map_or("", |s| s.as_str())).await; - } - if let Some(rest) = path.strip_prefix("/rooms/") { - let raw = rest.split('/').next().unwrap_or_default(); - let room: String = js_sys::decode_uri_component(raw) - .map(String::from) - .unwrap_or_else(|_| raw.to_string()); - if room.is_empty() { - return Response::error("room required", 400); - } - let ns = env.durable_object("PIT_ROOM")?; - let stub = ns.id_from_name(&room)?.get_stub()?; - // Name the room for the object (its id has no name on some paths). - let headers = req.headers().clone(); - headers.set("x-room", &room)?; - let mut init = RequestInit::new(); - init.with_method(req.method()).with_headers(headers); - let forwarded = Request::new_with_init(req.url()?.as_str(), &init)?; - return stub.fetch_with_request(forwarded).await; - } - let assets = env.assets("ASSETS")?; - assets.fetch_request(req).await -} diff --git a/examples/game/zone-do-spike/src/pit.rs b/examples/game/zone-do-spike/src/pit.rs deleted file mode 100644 index b7ae1ac1f..000000000 --- a/examples/game/zone-do-spike/src/pit.rs +++ /dev/null @@ -1,859 +0,0 @@ -//! Mob Pit, trimmed for the spike: the same players, mobs, pillars, melee -//! combat and the same replicated kinds/ids as -//! `examples/game/server/src/mobpit/zone.rs` (copied, not shared: that zone -//! lives in the native `game_demos` crate next to tokio, reqwest and the -//! Crawler fact sink, so it does not build for wasm32 as is). -//! -//! Left out: kill facts / Crawler XP settlement, leaderboard, profiles. -//! Added: the global `host` kind (which celld node, isolate and activation -//! run the room, tick numbers) and a hibernation snapshot (mobs, kill -//! counts) that the Durable Object keeps in its storage. - -use std::collections::BTreeMap; - -use distributed_game::{ - schema, ConsumePolicy, Ctx, Entities, Entity, EntityId, EntitySchema, GameEvent, GameInput, - LeaveReason, ObserverId, PlayerId, Project, Replicated, View, Zone, -}; -use game_sim::arena::{self as movement, MoveState, PILLARS, PLAYER_RADIUS}; -pub use game_sim::mobpit::{pit_step, PitInput}; -use serde::{Deserialize, Serialize}; - -/// Entity id of the zone's HUD view (as in Mob Pit). -pub const PIT_ENTITY: EntityId = EntityId(900); -/// Entity id of the host view (spike only). -pub const HOST_ENTITY: EntityId = EntityId(901); - -/// A player (Mob Pit's `player` kind, id 1). -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "player", id = 1, priority = 2.0, of = Player)] -pub struct PlayerView { - #[field_type(movement::POS)] - #[correct(ease = 150)] - #[from(state.x)] - pub x: f32, - #[field_type(movement::POS)] - #[correct(ease = 150)] - #[from(state.y)] - pub y: f32, - #[field_type(movement::VEL)] - #[correct(snap)] - #[from(state.vx)] - pub vx: f32, - #[field_type(movement::VEL)] - #[correct(snap)] - #[from(state.vy)] - pub vy: f32, - #[correct(snap)] - #[from(state.dash)] - pub dash: u8, - #[correct(snap)] - #[from(state.cd)] - pub cd: u8, - #[priority(0.2)] - #[correct(replace)] - #[from] - pub name: String, - #[correct(replace)] - pub hp: u8, - #[angle(bits = 8)] - #[correct(replace)] - #[from] - pub face: f32, - #[correct(replace)] - pub swing: u8, - /// Kills by this player in this room (persisted with the room). - #[correct(replace)] - pub level: u16, - #[correct(replace)] - pub dead: bool, -} - -/// A mob (Mob Pit's `mob` kind, id 2). -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "mob", id = 2, of = Mob)] -pub struct MobView { - #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] - #[from] - pub x: f32, - #[quant(min = -movement::HALF, max = movement::HALF, bits = 14)] - #[from] - pub y: f32, - #[angle(bits = 8)] - #[from] - pub face: f32, - #[from] - pub tier: u8, - pub hp: u8, - pub state: u8, - pub tele: u8, -} - -/// A pillar (the Arena's `pillar` kind, id 3). -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "pillar", id = 3, global, of = Pillar)] -pub struct PillarView { - #[from] - pub x: f32, - #[from] - pub y: f32, - #[from] - pub r: f32, -} - -/// Room numbers (global). -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "pit", id = 4, global, of = Pit)] -pub struct PitView { - /// Kills in this room since it was first created (persisted). - pub kills: u32, - /// Ticks this room has simulated across all activations (persisted). - pub ticks: u32, -} - -/// Where the room runs (global, spike only): set by the Durable Object. -#[derive(Debug, Clone, PartialEq, Replicated)] -#[replicated(kind = "host", id = 5, global, of = HostInfo)] -pub struct HostView { - /// celld node id (`CELLD_NODE`), found through the operator listeners. - #[from] - pub node: String, - /// Random id of the V8 isolate (module instance) running the room. - #[from] - pub isolate: String, - /// Random id of this activation of the object (new on every wake). - #[from] - pub activation: String, - /// Activations of this room so far (persisted). - #[from] - pub activations: u32, - /// The room was restored from storage on this activation. - #[from] - pub restored: bool, - /// Cold start: object constructor to first tick (ms). - #[from] - pub wake_ms: u32, - /// Tick rate (Hz). - #[from] - pub hz: u8, - /// Loop wake lateness EMA (ms; how late the timer fired). - #[from] - pub late_ms: f32, - /// Max lateness over the last second (ms). - #[from] - pub late_max_ms: f32, - /// Work per loop iteration EMA (µs: advance + sends). - #[from] - pub work_us: u32, - /// Rooms resident in the same isolate. - #[from] - pub isolate_rooms: u16, -} - -/// A static pillar (the Arena's floor). -pub struct Pillar { - id: EntityId, - pub x: f32, - pub y: f32, - pub r: f32, -} - -impl Pillar { - fn all() -> Vec { - PILLARS - .iter() - .enumerate() - .map(|(i, &(x, y, r))| Pillar { - id: EntityId(100 + i as u32), - x, - y, - r, - }) - .collect() - } -} - -impl Entity for Pillar { - fn entity_id(&self) -> EntityId { - self.id - } -} - -/// The host info the Durable Object keeps current. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct HostInfo { - pub node: String, - pub isolate: String, - pub activation: String, - pub activations: u32, - pub restored: bool, - pub wake_ms: u32, - pub hz: u8, - pub late_ms: f32, - pub late_max_ms: f32, - pub work_us: u32, - pub isolate_rooms: u16, -} - -impl Entity for HostInfo { - fn entity_id(&self) -> EntityId { - HOST_ENTITY - } -} - -/// Mob Pit's events (ids as in Mob Pit; `Kill` trimmed). -#[derive(Debug, Clone, PartialEq, GameEvent)] -pub enum PitEvent { - #[game_event(id = 1)] - Hello { - entity: u32, - half: f32, - boot: String, - attack_range: f32, - attack_arc_cos: f32, - }, - #[game_event(id = 3)] - Kill { - mob: u32, - tier: u8, - killer: u32, - killer_name: String, - /// The killer's kills in this room. - kills: u32, - }, - #[game_event(id = 6)] - Died { respawn_ms: u32 }, -} - -pub const ATTACK_RANGE: f32 = 2.2; -pub const ATTACK_ARC_COS: f32 = 0.5; -pub const ATTACK_DAMAGE: i32 = 10; -pub const SWING_COOLDOWN: u8 = 13; -const SWING_FRAMES: u8 = 6; -pub const PLAYER_HP: i32 = 100; -pub const MOBS: usize = 12; -const MAX_CREDITS: u8 = 4; -const VIEW_RADIUS: f32 = 40.0; -const AGGRO: f32 = 7.0; -const LEASH: f32 = 15.0; -const WINDUP_TICKS: u16 = 24; -const RECOVER_TICKS: u16 = 18; -const RESPAWN_TICKS: u64 = 120; -const PLAYER_RESPAWN_TICKS: u64 = 90; - -fn tier_stats(tier: u8) -> (i32, f32, i32, f32, f32) { - match tier { - 3 => (100, 3.3, 24, 0.8, 2.6), - 2 => (60, 2.4, 16, 0.7, 2.2), - _ => (30, 3.0, 9, 0.5, 1.8), - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum MobState { - Idle = 0, - Chase = 1, - Windup = 2, - Recover = 3, - Return = 4, - Dead = 5, -} - -#[derive(Serialize, Deserialize)] -struct Mob { - id: u32, - tier: u8, - home: (f32, f32), - x: f32, - y: f32, - face: f32, - hp: i32, - state: MobState, - timer: u16, - #[serde(skip)] - target: Option, - generation: u32, - respawn_at: u64, - wander: (f32, f32), -} - -struct Player { - id: EntityId, - principal: String, - name: String, - state: MoveState, - credits: u8, - hp: i32, - face: f32, - swing_cd: u8, - swing_anim: u8, - dead_until: Option, - regen: u8, - kills: u32, -} - -/// The persisted part of a room. -#[derive(Serialize, Deserialize)] -struct Snapshot { - mobs: Vec, - kills: u32, - ticks: u64, - activations: u32, - kills_by: BTreeMap, -} - -/// One Mob Pit room. -pub struct Pit { - players: BTreeMap, - mobs: Vec, - pillars: Vec, - /// Lifetime kills (persisted). - pub kills: u32, - /// Lifetime ticks (persisted; this activation adds `ctx.tick()`). - pub ticks_before: u64, - tick: u64, - /// Kills per principal (persisted). - pub kills_by: BTreeMap, - /// Activations including this one (persisted). - pub activations: u32, - /// Host info (set by the Durable Object). - pub host: HostInfo, -} - -fn mob_layout() -> Vec<(u8, (f32, f32))> { - (0..MOBS) - .map(|i| { - let ring = if i % 2 == 0 { 11.5 } else { 16.0 }; - let a = (i as f32 + 0.5) / MOBS as f32 * std::f32::consts::TAU; - let tier = match i { - 0 => 3, - 3 | 6 | 9 | 11 => 2, - _ => 1, - }; - (tier, (ring * a.cos(), ring * a.sin())) - }) - .collect() -} - -fn spawn_point(player: PlayerId) -> (f32, f32) { - const SPOTS: [(f32, f32); 6] = [ - (-4.5, -4.5), - (4.5, -4.5), - (4.5, 4.5), - (-4.5, 4.5), - (0.0, -5.5), - (0.0, 5.5), - ]; - SPOTS[player.0 as usize % SPOTS.len()] -} - -fn push_out_of_pillars(x: &mut f32, y: &mut f32, radius: f32) { - for (px, py, pr) in PILLARS { - let (ox, oy) = (*x - px, *y - py); - let d2 = ox * ox + oy * oy; - let min = radius + pr; - if d2 < min * min { - let d = d2.sqrt().max(1e-4); - *x = px + ox / d * min; - *y = py + oy / d * min; - } - } - let lim = movement::HALF - radius; - *x = x.clamp(-lim, lim); - *y = y.clamp(-lim, lim); -} - -fn step_toward(x: &mut f32, y: &mut f32, tx: f32, ty: f32, stride: f32) -> f32 { - let (dx, dy) = (tx - *x, ty - *y); - let d = (dx * dx + dy * dy).sqrt(); - if d > 1e-4 { - let s = stride.min(d); - *x += dx / d * s; - *y += dy / d * s; - } - dy.atan2(dx) -} - -fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { - ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() -} - -impl Pit { - /// Lifetime ticks. - pub fn ticks(&self) -> u64 { - self.ticks_before + self.tick - } - - /// Kills of one principal in this room. - pub fn kills_of(&self, principal: &str) -> u32 { - self.kills_by.get(principal).copied().unwrap_or(0) - } - - fn step_players(&mut self, ctx: &mut Ctx<'_, Self>) -> Vec<(PlayerId, f32, f32, f32)> { - let tick = ctx.tick(); - let mut swings = Vec::new(); - for (id, p) in &mut self.players { - p.credits = (p.credits + 1).min(MAX_CREDITS); - p.swing_cd = p.swing_cd.saturating_sub(1); - p.swing_anim = p.swing_anim.saturating_sub(1); - if let Some(until) = p.dead_until { - let _ = ctx.take_inputs(*id, ConsumePolicy::Drain); - if tick >= until { - let (x, y) = spawn_point(*id); - p.state = MoveState { - x, - y, - ..MoveState::default() - }; - p.hp = PLAYER_HP; - p.dead_until = None; - } - continue; - } - while p.credits > 0 { - let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { - break; - }; - let input = input.input; - p.state = pit_step(&p.state, &input, &(), movement::DT); - p.credits -= 1; - let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); - if sx * sx + sy * sy > 20.0 * 20.0 { - p.face = sy.atan2(sx); - } - if input.attack() && p.swing_cd == 0 { - p.swing_cd = SWING_COOLDOWN; - p.swing_anim = SWING_FRAMES; - swings.push((*id, p.state.x, p.state.y, p.face)); - } - } - p.regen = p.regen.wrapping_add(1); - if p.regen % 15 == 0 && p.hp < PLAYER_HP { - p.hp += 1; - } - ctx.set_view(*id, View::new(p.state.x, p.state.y, VIEW_RADIUS)); - } - swings - } - - fn resolve_swings(&mut self, ctx: &mut Ctx<'_, Self>, swings: Vec<(PlayerId, f32, f32, f32)>) { - for (player, x, y, face) in swings { - let (fx, fy) = (face.cos(), face.sin()); - for i in 0..self.mobs.len() { - let m = &mut self.mobs[i]; - if m.state == MobState::Dead { - continue; - } - let (_, _, _, radius, _) = tier_stats(m.tier); - let (dx, dy) = (m.x - x, m.y - y); - let d = (dx * dx + dy * dy).sqrt(); - if d > ATTACK_RANGE + radius { - continue; - } - let cos = if d < 1e-3 { - 1.0 - } else { - (dx * fx + dy * fy) / d - }; - if cos < ATTACK_ARC_COS && d > radius + PLAYER_RADIUS { - continue; - } - m.hp -= ATTACK_DAMAGE; - if matches!(m.state, MobState::Idle | MobState::Return) { - m.state = MobState::Chase; - m.target = Some(player); - } - if m.hp <= 0 { - m.hp = 0; - m.state = MobState::Dead; - m.respawn_at = ctx.tick() + RESPAWN_TICKS; - m.target = None; - let (mob, tier) = (m.id, m.tier); - self.kills += 1; - if let Some(p) = self.players.get_mut(&player) { - let kills = self.kills_by.entry(p.principal.clone()).or_default(); - *kills += 1; - let kills = *kills; - p.kills = kills; - ctx.broadcast(&PitEvent::Kill { - mob, - tier, - killer: p.id.get(), - killer_name: p.name.clone(), - kills, - }); - } - } - } - } - } - - fn step_mobs(&mut self, ctx: &mut Ctx<'_, Self>) { - let dt = ctx.dt_secs(); - let tick = ctx.tick(); - let living: Vec<(PlayerId, f32, f32)> = self - .players - .iter() - .filter(|(_, p)| p.dead_until.is_none()) - .map(|(id, p)| (*id, p.state.x, p.state.y)) - .collect(); - let mut hits: Vec<(PlayerId, i32)> = Vec::new(); - for i in 0..self.mobs.len() { - let (max_hp, speed, damage, radius, tele) = tier_stats(self.mobs[i].tier); - let target_pos = |t: Option| { - t.and_then(|t| living.iter().find(|(id, _, _)| *id == t)) - .map(|(_, x, y)| (*x, *y)) - }; - let m = &mut self.mobs[i]; - match m.state { - MobState::Dead => { - if tick >= m.respawn_at { - m.generation += 1; - m.hp = max_hp; - (m.x, m.y) = m.home; - m.state = MobState::Idle; - } - continue; - } - MobState::Idle => { - let nearest = living - .iter() - .map(|(id, x, y)| (*id, dist((m.x, m.y), (*x, *y)))) - .filter(|(_, d)| *d < AGGRO) - .min_by(|a, b| a.1.total_cmp(&b.1)); - if let Some((id, _)) = nearest { - m.state = MobState::Chase; - m.target = Some(id); - } else if dist((m.x, m.y), m.wander) < 0.3 { - let a = ctx.rng().next_f32() * std::f32::consts::TAU; - let r = ctx.rng().next_f32() * 2.5; - let m = &mut self.mobs[i]; - m.wander = (m.home.0 + r * a.cos(), m.home.1 + r * a.sin()); - } else { - let (wx, wy) = m.wander; - m.face = step_toward(&mut m.x, &mut m.y, wx, wy, 1.0 * dt); - } - } - MobState::Chase => match target_pos(m.target) { - Some((tx, ty)) if dist(m.home, (m.x, m.y)) < LEASH => { - let reach = radius + PLAYER_RADIUS + 0.6; - if dist((m.x, m.y), (tx, ty)) <= reach { - m.state = MobState::Windup; - m.timer = WINDUP_TICKS; - m.face = (ty - m.y).atan2(tx - m.x); - } else { - m.face = step_toward(&mut m.x, &mut m.y, tx, ty, speed * dt); - } - } - _ => { - m.state = MobState::Return; - m.target = None; - } - }, - MobState::Windup => { - m.timer = m.timer.saturating_sub(1); - if m.timer == 0 { - for (id, x, y) in &living { - if dist((m.x, m.y), (*x, *y)) <= tele + PLAYER_RADIUS * 0.5 { - hits.push((*id, damage)); - } - } - m.state = MobState::Recover; - m.timer = RECOVER_TICKS; - } - } - MobState::Recover => { - m.timer = m.timer.saturating_sub(1); - if m.timer == 0 { - m.state = MobState::Chase; - } - } - MobState::Return => { - let (hx, hy) = m.home; - m.face = step_toward(&mut m.x, &mut m.y, hx, hy, speed * 1.3 * dt); - m.hp = (m.hp + 1).min(max_hp); - if dist((m.x, m.y), m.home) < 0.3 { - m.state = MobState::Idle; - m.wander = m.home; - } - } - } - let m = &mut self.mobs[i]; - push_out_of_pillars(&mut m.x, &mut m.y, radius); - } - for i in 0..self.mobs.len() { - for j in (i + 1)..self.mobs.len() { - let (a, b) = (&self.mobs[i], &self.mobs[j]); - if a.state == MobState::Dead || b.state == MobState::Dead { - continue; - } - let min = tier_stats(a.tier).3 + tier_stats(b.tier).3; - let (dx, dy) = (b.x - a.x, b.y - a.y); - let d = (dx * dx + dy * dy).sqrt(); - if d < min && d > 1e-4 { - let push = (min - d) * 0.5; - let (nx, ny) = (dx / d * push, dy / d * push); - self.mobs[i].x -= nx; - self.mobs[i].y -= ny; - self.mobs[j].x += nx; - self.mobs[j].y += ny; - } - } - } - for (id, damage) in hits { - let Some(p) = self.players.get_mut(&id) else { - continue; - }; - if p.dead_until.is_some() { - continue; - } - p.hp -= damage; - if p.hp <= 0 { - p.hp = 0; - p.state.vx = 0.0; - p.state.vy = 0.0; - p.dead_until = Some(tick + PLAYER_RESPAWN_TICKS); - for m in &mut self.mobs { - if m.target == Some(id) { - m.target = None; - } - } - ctx.send( - id, - &PitEvent::Died { - respawn_ms: (PLAYER_RESPAWN_TICKS * 1000 / 30) as u32, - }, - ); - } - } - } -} - -impl Zone for Pit { - type Config = (); - type Input = PitInput; - type Timer = (); - type Message = distributed_game::NoMessages; - - fn schema() -> EntitySchema { - schema![PlayerView, MobView, PillarView, PitView, HostView] - } - - fn entities() -> Entities { - Entities::new() - .each(|z: &Self| &z.players) - .each(|z: &Self| &z.mobs) - .each(|z: &Self| &z.pillars) - .one(|z: &Self| z) - .one(|z: &Self| &z.host) - } - - fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { - let mobs = mob_layout() - .into_iter() - .enumerate() - .map(|(i, (tier, home))| Mob { - id: i as u32 + 1, - tier, - home, - x: home.0, - y: home.1, - face: 0.0, - hp: tier_stats(tier).0, - state: MobState::Idle, - timer: 0, - target: None, - generation: 0, - respawn_at: 0, - wander: home, - }) - .collect(); - Self { - players: BTreeMap::new(), - mobs, - pillars: Pillar::all(), - kills: 0, - ticks_before: 0, - tick: 0, - kills_by: BTreeMap::new(), - activations: 1, - host: HostInfo::default(), - } - } - - fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { - let (principal, name) = ctx - .player(player) - .map(|p| (p.principal.clone(), p.name.clone())) - .unwrap_or_default(); - let name = name.unwrap_or_else(|| principal.clone()); - let kills = self.kills_of(&principal); - let (x, y) = spawn_point(player); - let entity = EntityId(1000 + player.0); - self.players.insert( - player, - Player { - id: entity, - principal, - name, - state: MoveState { - x, - y, - ..MoveState::default() - }, - credits: MAX_CREDITS, - hp: PLAYER_HP, - face: 0.0, - swing_cd: 0, - swing_anim: 0, - dead_until: None, - regen: 0, - kills, - }, - ); - ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); - ctx.send( - player, - &PitEvent::Hello { - entity: entity.get(), - half: movement::HALF, - boot: self.host.activation.clone(), - attack_range: ATTACK_RANGE, - attack_arc_cos: ATTACK_ARC_COS, - }, - ); - } - - fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { - self.players.remove(&player); - for m in &mut self.mobs { - if m.target == Some(player) { - m.target = None; - } - } - } - - fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { - ctx.set_view(observer, View::new(0.0, 0.0, VIEW_RADIUS)); - } - - fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { - PitInput::from_payload(payload) - } - - fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { - self.tick = ctx.tick(); - let swings = self.step_players(ctx); - self.resolve_swings(ctx, swings); - self.step_mobs(ctx); - } - - fn hibernate(&self) -> Option> { - #[derive(Serialize)] - struct SnapshotRef<'a> { - mobs: &'a [Mob], - kills: u32, - ticks: u64, - activations: u32, - kills_by: &'a BTreeMap, - } - serde_json::to_vec(&SnapshotRef { - mobs: &self.mobs, - kills: self.kills, - ticks: self.ticks(), - activations: self.activations, - kills_by: &self.kills_by, - }) - .ok() - } - - fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], _saved_version: &str) { - let Ok(snapshot) = serde_json::from_slice::(state) else { - return; - }; - // Respawn timers are tick numbers of the old activation. - self.mobs = snapshot - .mobs - .into_iter() - .map(|mut m| { - m.respawn_at = m - .respawn_at - .saturating_sub(snapshot.ticks.min(m.respawn_at)); - if m.state != MobState::Dead { - m.state = MobState::Return; - } - m - }) - .collect(); - self.kills = snapshot.kills; - self.ticks_before = snapshot.ticks; - self.activations = snapshot.activations + 1; - self.kills_by = snapshot.kills_by; - } -} - -impl Entity for Player { - fn entity_id(&self) -> EntityId { - self.id - } -} - -impl Project for Player { - fn view(&self) -> Option { - Some(PlayerView::project( - self, - PlayerViewRest { - hp: self.hp.clamp(0, 255) as u8, - swing: self.swing_anim, - level: self.kills.min(u32::from(u16::MAX)) as u16, - dead: self.dead_until.is_some(), - }, - )) - } -} - -impl Entity for Mob { - fn entity_id(&self) -> EntityId { - EntityId(self.id) - } -} - -impl Project for Mob { - fn view(&self) -> Option { - if self.state == MobState::Dead { - return None; - } - let max_hp = tier_stats(self.tier).0; - let tele = if self.state == MobState::Windup { - 255 - (u32::from(self.timer) * 255 / u32::from(WINDUP_TICKS)) - } else { - 0 - }; - Some(MobView::project( - self, - MobViewRest { - hp: (self.hp.max(0) * 100 / max_hp) as u8, - state: self.state as u8, - tele: tele as u8, - }, - )) - } -} - -impl Entity for Pit { - fn entity_id(&self) -> EntityId { - PIT_ENTITY - } -} - -impl Project for Pit { - fn view(&self) -> Option { - Some(PitView::project( - self, - PitViewRest { - kills: self.kills, - ticks: self.ticks().min(u64::from(u32::MAX)) as u32, - }, - )) - } -} diff --git a/examples/game/zone-do-spike/tools/baseline.mjs b/examples/game/zone-do-spike/tools/baseline.mjs deleted file mode 100644 index 5809396a4..000000000 --- a/examples/game/zone-do-spike/tools/baseline.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// Noise floor: setTimeout 30 Hz loop lateness in a plain Node process. -const hz = Number(process.argv[2] ?? 30), secs = Number(process.argv[3] ?? 15), step = 1000 / hz; -const start = performance.now(); const late = []; let k = 1; -function tick() { const now = performance.now(); late.push(now - (start + (k - 1) * step)); k = Math.floor((now - start) / step) + 2; if (now - start < secs * 1000) setTimeout(tick, Math.max(0, start + (k - 1) * step - performance.now())); else { late.shift(); const s = late.sort((a, b) => a - b); console.log(JSON.stringify({ baselineNodeTimer: { hz, p50: +s[Math.floor(s.length / 2)].toFixed(2), p99: +s[Math.floor(s.length * 0.99)].toFixed(2), max: +s.at(-1).toFixed(2) } })); } } -setTimeout(tick, step); diff --git a/examples/game/zone-do-spike/tools/bench.ts b/examples/game/zone-do-spike/tools/bench.ts deleted file mode 100644 index ba5e61621..000000000 --- a/examples/game/zone-do-spike/tools/bench.ts +++ /dev/null @@ -1,219 +0,0 @@ -// Spike gr-p42 measurements with raw protocol bots (no rendering). -// -// node bench.mjs join join phase timings -// node bench.mjs rtt [n] Ping/Pong RTT through -// node bench.mjs load [hz] [pids] -// one bot per room (moves + attacks at 30 Hz); all rooms first touched -// through so celld places them on that node. Reports the -// rooms' own loop timing (/rooms//stats), Delta inter-arrival at -// the bots and the node processes' CPU (ps) while loaded. -import { execFileSync } from 'node:child_process'; -import { decodeServerMessage, encodeClientMessage, encodePayload, type PayloadLayout } from '../../../../js/src/game/index.ts'; - -const INPUT: PayloadLayout = [['mx', { type: 'i8' }], ['my', { type: 'i8' }], ['buttons', { type: 'u8' }]]; -const TAG_DELTA = 0x81; // GameMessageTag.DELTA -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -const q = (a: number[], p: number) => { if (!a.length) return NaN; const s = [...a].sort((x, y) => x - y); return +s[Math.round(p * (s.length - 1))].toFixed(2); }; -const summary = (a: number[]) => ({ n: a.length, p50: q(a, 0.5), p99: q(a, 0.99), max: q(a, 1) }); - -type Bot = { ws: WebSocket; deltas: number[]; pongs: Map void>; seq: number; timings: Record }; - -async function bot(base: string, room: string, name: string): Promise { - const t0 = performance.now(); - const r = await fetch(`${base}/ticket?room=${encodeURIComponent(room)}&name=${name}`); - const { ticket } = (await r.json()) as { ticket: string }; - const tTicket = performance.now(); - const ws = new WebSocket(`${base.replace(/^http/, 'ws')}/rooms/${encodeURIComponent(room)}`); - ws.binaryType = 'arraybuffer'; - const b: Bot = { ws, deltas: [], pongs: new Map(), seq: 0, timings: {} }; - await new Promise((ok, fail) => { ws.onopen = () => ok(); ws.onerror = () => fail(new Error(`ws error ${room}`)); }); - const tOpen = performance.now(); - ws.send(encodeClientMessage({ type: 'Hello', protocolVersion: 1, contentVersion: '', capabilities: 0, ticket, reconnectToken: '' })); - await new Promise((ok, fail) => { - let welcomed = false; - ws.onclose = (e) => { if (!welcomed) fail(new Error(`closed ${e.code} ${e.reason}`)); }; - ws.onmessage = (e) => { - const bytes = new Uint8Array(e.data as ArrayBuffer); - const now = performance.now(); - if (bytes[0] === TAG_DELTA) { b.deltas.push(now); if (!b.timings.firstDelta) b.timings.firstDelta = now - t0; return; } - const m = decodeServerMessage(bytes); - if (m.type === 'Welcome') { welcomed = true; b.timings.welcome = now - t0; ok(); } - if (m.type === 'Pong') b.pongs.get(m.clientTime)?.(now); - if (m.type === 'Error') fail(new Error(`error ${m.code} ${m.message}`)); - }; - }); - b.timings.ticket = tTicket - t0; - b.timings.open = tOpen - tTicket; - b.timings.hello = b.timings.welcome - (tOpen - t0); - return b; -} - -function ping(b: Bot): Promise { - const t = performance.now(); - return new Promise((ok) => { b.pongs.set(t, (now) => { b.pongs.delete(t); ok(now - t); }); b.ws.send(encodeClientMessage({ type: 'Ping', clientTime: t })); }); -} - -function drive(b: Bot, phase: number) { - let k = phase; - return setInterval(() => { - k++; - const a = k / 40; - b.seq++; - b.ws.send(encodeClientMessage({ type: 'Input', seq: b.seq, clientTick: b.seq, payload: encodePayload(INPUT, { mx: Math.round(Math.cos(a) * 100), my: Math.round(Math.sin(a) * 100), buttons: 2 }) })); - }, 1000 / 30); -} - -function cpu(pids: string[]) { - if (!pids.length) return []; - const out = execFileSync('ps', ['-o', 'pid=,%cpu=,rss=', '-p', pids.join(',')]).toString().trim().split('\n'); - return out.map((l) => { const [pid, c, rss] = l.trim().split(/\s+/); return { pid, cpu: +c, rssMb: Math.round(+rss / 1024) }; }); -} - -const [mode, base, room, ...rest] = process.argv.slice(2); -if (mode === 'join') { - // Warm the Node HTTP/WebSocket stack (its first use costs 50-500 ms). - const w = await bot(base, 'warmup', 'w'); - w.ws.close(); - for (const r of room.split(',')) { - const b = await bot(base, r, 'joiner'); - await sleep(200); - console.log(JSON.stringify({ room: r, via: base, ...Object.fromEntries(Object.entries(b.timings).map(([k, v]) => [k, +v.toFixed(1)])) })); - b.ws.close(); - } -} else if (mode === 'wake') { - // wake : create n rooms - // through the owner (fresh activation), leave, wait for eviction, then - // rejoin each (even through the owner, odd through ). - const [n, waitS, other] = rest; - const w = await bot(base, 'warmup', 'w'); w.ws.close(); - const w2 = await bot(other, 'warmup', 'w'); w2.ws.close(); - const tag = Date.now().toString(36); - const rooms = Array.from({ length: Number(n) }, (_, i) => `${room}-${tag}-${i}`); - const fresh: number[] = []; - const before: Record = {}; const after: Record = {}; const moved: string[] = []; - const ownerOf = async (r: string) => ((await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any).node as string; - const first: string[] = []; - for (const r of rooms) { const b = await bot(base, r, 'x'); fresh.push(b.timings.welcome); await sleep(300); const o = await ownerOf(r); first.push(o); before[o] = (before[o] ?? 0) + 1; b.ws.close(); } - await sleep(Number(waitS) * 1000); - const viaOwner: number[] = []; const viaOther: number[] = []; const restored: boolean[] = []; - for (const [i, r] of rooms.entries()) { - const b = await bot(i % 2 ? other : base, r, 'x'); - (i % 2 ? viaOther : viaOwner).push(b.timings.welcome); - b.ws.close(); - const st = await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json() as any; - restored.push(st.restored && st.activations === 2); - after[st.node] = (after[st.node] ?? 0) + 1; - if (st.node !== first[i]) moved.push(`${r}:${first[i]}->${st.node}`); - } - console.log(JSON.stringify({ fresh: summary(fresh), wakeViaOwner: summary(viaOwner), wakeViaOther: summary(viaOther), restoredAll: restored.every(Boolean), restored: restored.filter(Boolean).length, ownersBefore: before, ownersAfter: after, moved: moved.length, movedRooms: moved.slice(0, 5) })); -} else if (mode === 'rtt') { - const n = Number(rest[0] ?? 200); - const b = await bot(base, room, 'pinger'); - const rtts: number[] = []; - const t0 = performance.now(); const spikes: string[] = []; - for (let i = 0; i < n; i++) { const r = await ping(b); rtts.push(r); if (r > 15) spikes.push(`${((performance.now() - t0) / 1000).toFixed(2)}s:${r.toFixed(0)}`); await sleep(10); } - if (process.env.SPIKES) console.log('spikes', spikes.join(' ')); - const st = await (await fetch(`${base}/rooms/${encodeURIComponent(room)}/stats`)).json() as any; - console.log(JSON.stringify({ room, via: base, owner: st.node, rtt: summary(rtts) })); - b.ws.close(); -} else if (mode === 'crowd') { - // crowd [hz] [pids] [bases]: bots - // in ONE room, joins spread over [bases] (comma list, default ), so - // every bot not on the owner node is forwarded. Reports the room's loop - // timing, per-bot Delta size/interval/bandwidth, ping and node CPU. - const [count, secs, hz = '30', pidList = '', baseList = ''] = rest; - const pids = pidList ? pidList.split(',') : []; - const bases = baseList ? baseList.split(',') : [base]; - const r = `${room}@${hz}`; - const bots: Bot[] = []; - const bytes: number[][] = []; - const t0 = performance.now(); - for (let i = 0; i < Number(count); i += 10) { - const batch = await Promise.all(Array.from({ length: Math.min(10, Number(count) - i) }, (_, j) => bot(bases[(i + j) % bases.length], r, `p${i + j}`))); - for (const b of batch) { - const sizes: number[] = []; - bytes.push(sizes); - const prev = b.ws.onmessage!; - b.ws.onmessage = (e) => { const d = e.data as ArrayBuffer; if (new Uint8Array(d)[0] === TAG_DELTA) sizes.push(d.byteLength); (prev as any).call(b.ws, e); }; - bots.push(b); - } - } - const joinS = (performance.now() - t0) / 1000; - const welcome = bots.map((b) => b.timings.welcome); - const timers = bots.map((b, i) => drive(b, i * 7)); - await sleep(3000); - await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats?reset=1`).catch(() => undefined); - for (const b of bots) b.deltas.length = 0; - for (const s of bytes) s.length = 0; - const samples: ReturnType[] = []; - const end = Date.now() + Number(secs) * 1000; - while (Date.now() < end) { await sleep(1000); samples.push(cpu(pids)); } - const st = (await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any; - const rtts: number[] = []; - for (const b of bots.filter((_, i) => i % 5 === 0)) rtts.push(await ping(b)); - timers.forEach(clearInterval); - const arrivals = bots.flatMap((b) => b.deltas.slice(1).map((t, i) => t - b.deltas[i])); - const sizes = bytes.flat(); - const perBotKBps = bytes.map((s) => s.reduce((a, x) => a + x, 0) / 1024 / Number(secs)); - const cpuByPid: Record = {}; - for (const s of samples) for (const c of s) (cpuByPid[c.pid] ??= []).push(c.cpu); - console.log(JSON.stringify({ - room: r, players: bots.length, connected: bots.filter((b) => b.ws.readyState === 1).length, hz: Number(hz), secs: Number(secs), - joinS: +joinS.toFixed(1), welcome: summary(welcome), owner: st.node, - lateP50: st.late_ms?.p50, lateP99: st.late_ms?.p99, intervalP99: st.interval_ms?.p99, droppedTicks: st.dropped_ticks, - iterations: st.iterations, expectedIterations: Math.round(Number(hz) * Number(secs)), - deltaBytes: summary(sizes), deltaArrival: summary(arrivals), - perBotKBps: summary(perBotKBps), roomOutKBps: +perBotKBps.reduce((a, x) => a + x, 0).toFixed(1), - pingUnderLoad: summary(rtts), - cpu: Object.fromEntries(Object.entries(cpuByPid).map(([p, a]) => [p, { avg: +(a.reduce((x, y) => x + y, 0) / a.length).toFixed(1), max: Math.max(...a) }])) - })); - for (const b of bots) b.ws.close(); - await sleep(500); -} else if (mode === 'load') { - const [count, secs, hz = '30', pidList = ''] = rest; - const pids = pidList ? pidList.split(',') : []; - const rooms = Array.from({ length: Number(count) }, (_, i) => `${room}-${i}@${hz}`); - const bots: Bot[] = []; - const t0 = performance.now(); - for (let i = 0; i < rooms.length; i += 20) { - bots.push(...(await Promise.all(rooms.slice(i, i + 20).map((r, j) => bot(base, r, `b${i + j}`))))); - } - const joinS = (performance.now() - t0) / 1000; - const timers = bots.map((b, i) => drive(b, i * 7)); - await sleep(3000); - await Promise.all(rooms.map((r) => fetch(`${base}/rooms/${encodeURIComponent(r)}/stats?reset=1`).catch(() => undefined))); - for (const b of bots) b.deltas.length = 0; - const samples: ReturnType[] = []; - const end = Date.now() + Number(secs) * 1000; - while (Date.now() < end) { await sleep(1000); samples.push(cpu(pids)); } - const fetched = await Promise.all(rooms.map(async (r) => { try { return await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json() as any; } catch { return undefined; } })); - const stats = fetched.filter(Boolean); - if (stats.length < rooms.length) console.log(`stats unavailable for ${rooms.length - stats.length} rooms`); - const rtts: number[] = []; - for (const b of bots.slice(0, 10)) rtts.push(await ping(b)); - timers.forEach(clearInterval); - const late99 = stats.map((s) => s.late_ms.p99); - const late50 = stats.map((s) => s.late_ms.p50); - const interval = stats.map((s) => s.interval_ms.p99); - const dropped = stats.reduce((a, s) => a + s.dropped_ticks, 0); - const catchUp = stats.reduce((a, s) => a + s.catch_up_iterations, 0); - const iterations = stats.reduce((a, s) => a + s.iterations, 0); - const arrivals = bots.flatMap((b) => b.deltas.slice(1).map((t, i) => t - b.deltas[i])); - const nodes: Record = {}; - for (const s of stats) nodes[s.node] = (nodes[s.node] ?? 0) + 1; - const isolates = new Set(stats.map((s) => s.isolate)).size; - const cpuByPid: Record = {}; - for (const s of samples) for (const c of s) (cpuByPid[c.pid] ??= []).push(c.cpu); - console.log(JSON.stringify({ - rooms: rooms.length, hz: Number(hz), secs: Number(secs), joinS: +joinS.toFixed(1), nodes, isolates, - lateP50_median: q(late50, 0.5), lateP99_median: q(late99, 0.5), lateP99_worstRoom: q(late99, 1), - intervalP99_median: q(interval, 0.5), droppedTicks: dropped, catchUpIterations: catchUp, iterations, - expectedIterations: Math.round(rooms.length * Number(hz) * Number(secs)), - deltaArrival: summary(arrivals), pingUnderLoad: summary(rtts), - cpu: Object.fromEntries(Object.entries(cpuByPid).map(([p, a]) => [p, { avg: +(a.reduce((x, y) => x + y, 0) / a.length).toFixed(1), max: Math.max(...a) }])), - rss: samples.at(-1) - })); - for (const b of bots) b.ws.close(); - await sleep(500); -} -process.exit(0); diff --git a/examples/game/zone-do-spike/tools/drain.ts b/examples/game/zone-do-spike/tools/drain.ts deleted file mode 100644 index f5be9ae94..000000000 --- a/examples/game/zone-do-spike/tools/drain.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Graceful node stop: create rooms through , leave, wait for -// eviction, print READY (operator stops that node with SIGTERM), then -// rejoin each through and report where it runs now. -import { connectRoom } from '../page/room-client.ts'; -const [ownerBase, entry, n, waitS] = process.argv.slice(2); -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -const tag = Date.now().toString(36); -const rooms = Array.from({ length: Number(n) }, (_, i) => `dr-${tag}-${i}`); -const node = async (base: string, r: string) => ((await (await fetch(`${base}/rooms/${encodeURIComponent(r)}/stats`)).json()) as any); -const before: Record = {}; -for (const r of rooms) { - const rc = connectRoom(ownerBase, r, 'd'); await rc.welcome; await sleep(400); rc.close(); - const st = await node(ownerBase, r); before[st.node] = (before[st.node] ?? 0) + 1; -} -console.log('placed', JSON.stringify(before)); -await sleep(Number(waitS) * 1000); -console.log('READY'); -for (let i = 0; i < 200 && !(await fetch(`${ownerBase}/ticket`).then(() => false, () => true)); i++) await sleep(100); -const t0 = performance.now(); -const after: Record = {}; let restored = 0; const waits: number[] = []; -for (const r of rooms) { - const t = performance.now(); - for (;;) { try { const rc = connectRoom(entry, r, 'd'); await rc.welcome; rc.close(); break; } catch { await sleep(200); } } - waits.push(performance.now() - t); - const st = await node(entry, r); after[st.node] = (after[st.node] ?? 0) + 1; if (st.restored) restored++; -} -console.log('after stop', JSON.stringify({ owners: after, restored, rooms: rooms.length, firstRejoinMs: Math.round(waits[0]), allRejoinedS: +((performance.now() - t0) / 1000).toFixed(1) })); -process.exit(0); diff --git a/examples/game/zone-do-spike/tools/failover.ts b/examples/game/zone-do-spike/tools/failover.ts deleted file mode 100644 index 7809d5b4b..000000000 --- a/examples/game/zone-do-spike/tools/failover.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Node failure: a room placed on one node (first touch through ) -// with a player connected through another node (); the -// operator SIGKILLs the owner when this prints READY. The player then -// rejoins through until a room answers again. -// usage: node failover.mjs -import { connectRoom, ATTACK } from '../page/room-client.ts'; -const [ownerBase, entry, room] = process.argv.slice(2); -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -const log = (...a: unknown[]) => console.log(new Date().toISOString().slice(11, 23), ...a); -// First touch through the owner places the room there. -await (await fetch(`${ownerBase}/rooms/${encodeURIComponent(room)}/stats`)).json(); -const rc = connectRoom(entry, room, 'survivor'); -await rc.welcome; -for (let i = 0; i < 100 && !(rc.host()?.node && rc.host()!.node !== '?'); i++) await sleep(50); -log(`joined ${room} via ${entry}; runs on ${rc.host()?.node}`); -let closedAt = 0; -rc.client.on('zoneClosed', (_z, info) => { closedAt = performance.now(); log('connection closed', JSON.stringify(info)); }); -const fight = setInterval(() => { - const me = rc.me()?.fields as any; const mobs = rc.entities().filter((e) => e.kindName === 'mob').map((e) => e.fields as any); - if (!me || !mobs.length) return; - const t = mobs.sort((a, b) => Math.hypot(a.x - me.x, a.y - me.y) - Math.hypot(b.x - me.x, b.y - me.y))[0]; - const [dx, dy] = [t.x - me.x, t.y - me.y]; const d = Math.hypot(dx, dy) || 1; const s = d < 1.8 ? 30 : 127; - rc.input(Math.round(dx / d * s), Math.round(dy / d * s), ATTACK); -}, 33); -while (rc.kills.length < 3) await sleep(100); -await sleep(6000); // > the room's 5 s persist interval -const before = rc.kills.at(-1)!.kills; -log(`kills before failure: ${before} (persisted at most 5 s ago); READY`); -const t0 = performance.now(); -while (!closedAt && performance.now() - t0 < 60_000) await sleep(20); -clearInterval(fight); -const killDetected = closedAt; -let attempt = 0; -for (;;) { - attempt++; - try { - const r2 = connectRoom(entry, room, 'survivor'); - await r2.welcome; - for (let i = 0; i < 100 && !(r2.host()?.node && r2.host()!.node !== '?' && r2.me()); i++) await sleep(50); - const h = r2.host()!; const me = r2.me()?.fields as any; - log(`rejoined after ${((performance.now() - killDetected) / 1000).toFixed(2)} s (${attempt} attempts): node=${h.node} activation #${h.activations} restored=${h.restored}; my kills ${me?.level} (had ${before})`); - r2.close(); break; - } catch (e) { - if (attempt % 10 === 1) log(`attempt ${attempt}: ${String(e).slice(0, 120)}`); - await sleep(250); - } -} -process.exit(0); diff --git a/examples/game/zone-do-spike/tools/headless.ts b/examples/game/zone-do-spike/tools/headless.ts deleted file mode 100644 index 545a37e1a..000000000 --- a/examples/game/zone-do-spike/tools/headless.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Headless check of one room on celld: join, move, attack until a kill, -// leave, wait for eviction, rejoin (possibly via another node) and check -// the room restored its state in a new activation. -// usage: node headless.mjs [rejoin-base-url] [evict-wait-s] -import { connectRoom, ATTACK, type RoomClient } from '../page/room-client.ts'; - -const [base, room, rejoinBase = base, waitS = '25'] = process.argv.slice(2); -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -const until = async (f: () => T | undefined | false, ms: number, what: string): Promise => { - const end = Date.now() + ms; - for (;;) { const v = f(); if (v) return v; if (Date.now() > end) throw new Error(`timeout: ${what}`); await sleep(20); } -}; -const log = (...a: unknown[]) => console.log(new Date().toISOString().slice(11, 23), ...a); - -async function join(url: string, name: string) { - const t0 = performance.now(); - const rc = connectRoom(url, room, name); - await rc.welcome; - const welcomeMs = performance.now() - t0; - await until(() => rc.host()?.node && rc.host()!.node !== '?' && rc.me(), 5000, 'host node + own player'); - return { rc, welcomeMs }; -} - -async function fight(rc: RoomClient, kills: number) { - const start = rc.kills.length; - const end = Date.now() + 60_000; - let moved = 0; - const at0 = rc.me()!.fields as any; - while (rc.kills.length - start < kills) { - if (Date.now() > end) throw new Error('no kill within 60 s'); - const me = rc.me()?.fields as any; - const mobs = rc.entities().filter((e) => e.kindName === 'mob').map((e) => e.fields as any); - if (me && mobs.length) { - const t = mobs.sort((a, b) => Math.hypot(a.x - me.x, a.y - me.y) - Math.hypot(b.x - me.x, b.y - me.y))[0]; - const [dx, dy] = [t.x - me.x, t.y - me.y]; const d = Math.hypot(dx, dy) || 1; - const near = d < 1.8; - rc.input(near ? Math.round(dx / d * 30) : Math.round(dx / d * 127), near ? Math.round(dy / d * 30) : Math.round(dy / d * 127), ATTACK); - moved = Math.max(moved, Math.hypot(me.x - at0.x, me.y - at0.y)); - } - await sleep(33); - } - return { moved }; -} - -const { rc, welcomeMs } = await join(base, 'bot-ana'); -const h1 = { ...rc.host()! }; -log(`joined ${room} via ${base}: node=${h1.node} isolate=${h1.isolate} activation=${h1.activation} #${h1.activations} restored=${h1.restored} welcome=${welcomeMs.toFixed(1)}ms`); -const kills0 = (rc.entities().find((e) => e.kindName === 'pit')?.fields as any)?.kills; -const { moved } = await fight(rc, 1); -await sleep(500); -const k = rc.kills.at(-1)!; -log(`moved ${moved.toFixed(1)} m, killed mob ${k.mob}; my kills in room=${k.kills}; room kills ${kills0} -> ${(rc.entities().find((e) => e.kindName === 'pit')?.fields as any)?.kills}`); -rc.client.close(); -log(`left; waiting ${waitS}s for the room to persist, stop and be evicted`); -await sleep(Number(waitS) * 1000); -const r2 = await join(rejoinBase, 'bot-ana'); -const h2 = { ...r2.rc.host()! }; -const me2 = r2.rc.me()!.fields as any; -const pit2 = r2.rc.entities().find((e) => e.kindName === 'pit')?.fields as any; -log(`rejoined via ${rejoinBase}: node=${h2.node} isolate=${h2.isolate} activation=${h2.activation} #${h2.activations} restored=${h2.restored} wake=${(h2 as any).wake_ms}ms welcome=${r2.welcomeMs.toFixed(1)}ms`); -log(`restored state: my kills=${me2.level} (expected ${k.kills}), room kills=${pit2?.kills}, lifetime ticks=${pit2?.ticks}`); -const ok = h2.activation !== h1.activation && h2.restored && me2.level === k.kills && pit2?.kills >= k.kills; -r2.rc.client.close(); -log(ok ? 'PASS' : 'FAIL'); -process.exit(ok ? 0 : 1); diff --git a/examples/game/zone-do-spike/tools/peek.ts b/examples/game/zone-do-spike/tools/peek.ts deleted file mode 100644 index 2d4855b6c..000000000 --- a/examples/game/zone-do-spike/tools/peek.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Print one room's replicated host entity and stats. -import { connectRoom } from '../page/room-client.ts'; -const [base, room] = process.argv.slice(2); -const t0 = performance.now(); -const rc = connectRoom(base, room, 'peek'); -await rc.welcome; -const tw = performance.now() - t0; -for (let i = 0; i < 100 && !(rc.host() as any)?.node; i++) await new Promise((r) => setTimeout(r, 20)); -await new Promise((r) => setTimeout(r, 1500)); -console.log(JSON.stringify({ welcomeMs: +tw.toFixed(1), host: rc.host(), rtt: rc.rtt() })); -rc.client.close(); process.exit(0); diff --git a/examples/game/zone-do-spike/tools/s3-compose.yaml b/examples/game/zone-do-spike/tools/s3-compose.yaml deleted file mode 100644 index b0b1d8e91..000000000 --- a/examples/game/zone-do-spike/tools/s3-compose.yaml +++ /dev/null @@ -1,13 +0,0 @@ -# The spike's one S3-compatible store (RustFS) for the celld fleet bucket. -# Compose rather than `docker run`: Dory (this machine's Docker) published -# ports only for containers on a user-defined network. -services: - s3: - image: rustfs/rustfs:1.0.3 - container_name: zone-do-spike-s3 - command: ["/data"] - environment: - RUSTFS_ADDRESS: "0.0.0.0:9000" - RUSTFS_ACCESS_KEY: spikeadmin - RUSTFS_SECRET_KEY: spikesecret123 - ports: ["127.0.0.1:${S3_PORT:-19400}:9000"] diff --git a/examples/game/zone-do-spike/wrangler.jsonc b/examples/game/zone-do-spike/wrangler.jsonc deleted file mode 100644 index 70455c401..000000000 --- a/examples/game/zone-do-spike/wrangler.jsonc +++ /dev/null @@ -1,20 +0,0 @@ -// Spike gr-p42: Mob Pit rooms as celld Durable Objects. `./run.sh deploy` -// publishes this to the fleet bucket (`celld deploy`); every node runs it. -{ - "name": "zone-do-spike", - "main": "build/worker/shim.mjs", - "compatibility_date": "2026-01-01", - "durable_objects": { - "bindings": [{ "name": "PIT_ROOM", "class_name": "PitRoom" }] - }, - "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PitRoom"] }], - "assets": { "directory": "./public", "binding": "ASSETS" }, - "vars": { - // Dev-only ticket key (the spike's /ticket endpoint signs with it). - "TICKET_SECRET": "spike-only-ticket-secret-not-for-production", - "TICK_HZ": "30", - // Operator listeners, only to find out which node runs a room - // (celld does not tell application code its node id). - "NODES": "node-a=127.0.0.1:18201,node-b=127.0.0.1:18202,node-c=127.0.0.1:18203" - } -} From c50d9f1bcd6ddcf1db4e273481a33f827a143915 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 20:24:39 -0500 Subject: [PATCH 266/484] test(game): skip the local fleet when its RustFS is unreachable When Docker runs the RustFS container but its port never becomes reachable, the Playwright fleet helper now stops the container and falls back to `celld dev` (or fails with MOBPIT_FLEET_REQUIRED=1, as CI sets), instead of failing after a minute. [[tasks/gr-p41-mobpit-rooms-zones]] --- examples/game/client/tests/helpers/fleet.mjs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/game/client/tests/helpers/fleet.mjs b/examples/game/client/tests/helpers/fleet.mjs index ad07ba342..1baca9ffc 100644 --- a/examples/game/client/tests/helpers/fleet.mjs +++ b/examples/game/client/tests/helpers/fleet.mjs @@ -68,11 +68,15 @@ export async function startFleet({ relayPort, nodes = 3, vars = {} } = {}) { try { const up = spawnSync('docker', ['compose', '-p', project, '-f', compose, 'up', '-d'], { encoding: 'utf8' }); if (up.status !== 0) throw new Error(`docker compose up: ${up.stderr}`); - const deadline = Date.now() + 60_000; + const deadline = Date.now() + 30_000; for (;;) { const mb = spawnSync('aws', ['--endpoint-url', aws.S3_ENDPOINT, 's3', 'mb', 's3://mobpit-fleet'], { env: aws, encoding: 'utf8' }); if (mb.status === 0 || /BucketAlready/.test(mb.stderr)) break; - if (Date.now() > deadline) throw new Error(`bucket: ${mb.stderr}`); + if (Date.now() > deadline) { + // Docker ran the container but its port is not reachable here. + down(); + return skip(`RustFS unreachable on 127.0.0.1:${s3Port}: ${mb.stderr.trim()}`); + } await new Promise((r) => setTimeout(r, 500)); } const secret = `test-only-${randomBytes(24).toString('hex')}`; From 4a3edd35f064f2e629edd2c3bdd1086323fbf736 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 22:40:07 -0500 Subject: [PATCH 267/484] feat(game): predict through handoffs with handoffFrame GameClient used to hold the controlled entity still while a handoff was in flight and drop the inputs sampled meanwhile, so a border crossing showed a hold, then a hop. With prediction.handoffFrame (the predicted fields re-expressed in the target zone's frame) the client keeps predicting in the target's frame, sends the transfer's inputs to the target once it welcomes the player, and eases from what was drawn into the target's state. Predictor.bind keeps (and replays) inputs recorded while no entity or the same entity was bound, filtered by the delta's ack, instead of dropping them; new step() and easeFrom(). [[tasks/gr-p41-mobpit-rooms-zones]] --- js/README.md | 9 ++- js/src/game/client.ts | 71 +++++++++++++++++++++-- js/src/game/prediction.ts | 54 +++++++++++++++-- js/tests/game-replica-prediction.test.mjs | 14 +++++ js/tests/game-world.test.mjs | 59 +++++++++++++++++++ 5 files changed, 195 insertions(+), 12 deletions(-) diff --git a/js/README.md b/js/README.md index 371f9d8bb..3a09c1899 100644 --- a/js/README.md +++ b/js/README.md @@ -787,7 +787,14 @@ every Delta's `ack_seq`; per-field `ease`, `snap` or `replace` resolves the divergence. A server Handoff connects to the target zone with the transfer ticket (following `Redirect`s) and swaps authority while the previous world keeps rendering; if the target refuses or stays silent the same Hello goes -back to the source zone, then a fresh ticket. `Kick(RELOAD)` and handshake +back to the source zone, then a fresh ticket. Meanwhile the controlled +entity is held at its last predicted state; with `prediction.handoffFrame` +(its predicted fields re-expressed in the target zone's frame, e.g. a cell +offset for zone-local positions) it is predicted on instead, the inputs of +the transfer go to the target once it welcomes the player, and the switch +to the target's state is eased, so a border crossing shows no hold or jump. +Inputs recorded before the controlled entity is known are replayed when it +binds. `Kick(RELOAD)` and handshake `VERSION_MISMATCH` emit `reloadRequired`; supply `reloadContent` (or call `connection.resumeAfterReload(version)`) to rejoin with the new content. `client.contentVersion` follows the reload, so later handoff targets and diff --git a/js/src/game/client.ts b/js/src/game/client.ts index 4b945ffac..a74e44d96 100644 --- a/js/src/game/client.ts +++ b/js/src/game/client.ts @@ -78,6 +78,17 @@ export type GamePredictionOptions = PredictorOptions & * overrides it (e.g. from a game Event). */ controlledEntity?: ControlledEntityResolver; + /** + * Continue the controlled entity's prediction through a handoff: its + * predicted fields re-expressed in the target zone's frame (e.g. a + * cell offset when positions are zone-local), or undefined to hold + * it still as before. When given, inputs sampled while the handoff + * is in flight are predicted (with the target's frame) and sent to + * the target once it welcomes the player, and the switch to the + * target's own state is eased instead of snapped: the handoff's + * latency is hidden. + */ + handoffFrame?: (fields: EntityFields, from: string, to: string) => EntityFields | undefined; }>; /** What the player sees when an input is sampled (lag compensation). */ @@ -179,6 +190,13 @@ export class GameClient { #handoffBridge: RenderedEntity | undefined; /** The source zone's copy of the handed-off entity: never drawn again. */ #handedOff: Readonly<{ zoneId: string; id: number }> | undefined; + /** + * Handoff in flight with `handoffFrame`: the controlled entity predicted + * on in the target's frame, and the inputs not yet sent to the target. + */ + #carry: + | { zoneId: string; base: RenderedEntity; fields: EntityFields; unsent: { input: TInput; dtMs: number }[] } + | undefined; #closed = false; #contentVersion: string; #predictionEnabled: boolean; @@ -297,13 +315,28 @@ export class GameClient { const authority = this.#authority; const prediction = this.#options.prediction; if (authority === undefined || prediction === undefined) return undefined; + const connection = authority.connection; + const tickRate = connection.welcome?.tickRate || 30; + const dt = dtMs ?? this.#options.inputDtMs ?? 1000 / tickRate; + const carry = this.#carry; + if (carry !== undefined) { + // Handoff in flight: keep predicting what is drawn. + carry.fields = this.#predictor!.step(carry.fields, input, dt); + if (!connection.canSendInput()) { + carry.unsent.push({ input, dtMs: dt }); + return undefined; + } + } + return this.#send(authority, input, dt); + } + + #send(authority: Zone, input: TInput, dtMs: number): number | undefined { const connection = authority.connection; if (!connection.canSendInput()) return undefined; const context = this.inputContext(authority)!; - const seq = connection.sendInput(prediction.encodeInput(input, context), context.clientTick); + const seq = connection.sendInput(this.#options.prediction!.encodeInput(input, context), context.clientTick); if (seq === undefined) return undefined; - const tickRate = connection.welcome?.tickRate || 30; - this.#predictor!.record(seq, input, dtMs ?? this.#options.inputDtMs ?? 1000 / tickRate); + this.#predictor!.record(seq, input, dtMs); return seq; } @@ -361,7 +394,24 @@ export class GameClient { this.#predictionEnabled && predictor?.active === true && this.#authority !== undefined ? predictor.entityId : undefined; - if (controlled !== undefined) this.#handoffBridge = undefined; + let carry = this.#carry; + if (controlled !== undefined) { + this.#handoffBridge = undefined; + if (carry !== undefined && carry.zoneId === this.#authority?.zoneId) { + // The target bound the entity: ease from what was drawn. + predictor!.easeFrom(carry.fields, now); + this.#carry = carry = undefined; + } + } + if (carry !== undefined) { + this.#handoffBridge = { + ...carry.base, + key: `${carry.zoneId}:${carry.base.id}`, + zoneId: carry.zoneId, + fields: { ...carry.base.fields, ...carry.fields }, + stale: false + }; + } const gone = this.#handedOff; let goneSeen = false; let mine: RenderedEntity | undefined; @@ -513,7 +563,7 @@ export class GameClient { if (id !== undefined) { const entity = zone.replica.get(id); if (entity !== undefined && !this.#predictor.active) { - this.#predictor.bind(id, zone.replica.schema?.byId.get(entity.kind), entity.fields); + this.#predictor.bind(id, zone.replica.schema?.byId.get(entity.kind), entity.fields, delta.ackSeq); } const correction = this.#predictor.reconcile( delta.ackSeq, @@ -556,9 +606,13 @@ export class GameClient { const to = message.targetZone; this.#emitter.emit('handoff', { from, to, message }); const last = this.#lastControlled; + this.#carry = undefined; if (last !== undefined && last.zoneId === from) { this.#handoffBridge = { ...last, stale: false }; this.#handedOff = { zoneId: from, id: last.id }; + const predicted = this.#predictor?.predicted(); + const fields = predicted === undefined ? undefined : this.#options.prediction?.handoffFrame?.(predicted, from, to); + if (fields !== undefined) this.#carry = { zoneId: to, base: last, fields, unsent: [] }; } this.#controlledOverride = undefined; this.#predictor?.bind(undefined); @@ -591,6 +645,7 @@ export class GameClient { if (this.#closed || this.#authority !== target) return; this.#emitter.emit('handoffFailed', { from, to, stage, reason }); this.#handoffBridge = undefined; + this.#carry = undefined; connection.close({ leave: false }); // Keep the zone's replica rendering while the next attempt runs. this.#retire(target, true); @@ -609,6 +664,12 @@ export class GameClient { connection.on('welcome', () => { if (done) return; finish(); + // Inputs predicted while the handoff was in flight go to the + // target (recorded, so the target's state replays them). + const carry = this.#carry; + if (carry !== undefined && carry.zoneId === zoneId) { + for (const { input, dtMs } of carry.unsent.splice(0)) this.#send(target, input, dtMs); + } const off = connection.on('delta', () => { off(); this.#emitter.emit('handoffComplete', { from, to: zoneId }); diff --git a/js/src/game/prediction.ts b/js/src/game/prediction.ts index 5f2b29821..2b1467b0d 100644 --- a/js/src/game/prediction.ts +++ b/js/src/game/prediction.ts @@ -107,17 +107,59 @@ export class Predictor { } /** - * Bind (or rebind) the controlled entity. Clears pending inputs: they - * belonged to the previous binding or session. + * Bind (or rebind) the controlled entity. Switching from one entity to + * another clears pending inputs (they belonged to the previous binding); + * inputs recorded while no entity or this same entity was bound belong + * to it and are replayed onto `authoritative` (those after `ackSeq`, the + * last input `authoritative` includes, when known). */ - bind(entityId: number | undefined, kind?: GameKindDef, authoritative?: EntityFields): void { + bind(entityId: number | undefined, kind?: GameKindDef, authoritative?: EntityFields, ackSeq?: number): void { + if (entityId === undefined || (this.#entityId !== undefined && this.#entityId !== entityId)) { + this.#pending = []; + this.#lastAck = 0; + } + if (ackSeq !== undefined && ackSeq > this.#lastAck) this.#lastAck = ackSeq; + this.#pending = this.#pending.filter((p) => p.seq > this.#lastAck); this.#entityId = entityId; this.#kind = entityId === undefined ? undefined : kind; - this.#pending = []; this.#offsets.clear(); - this.#lastAck = 0; this.#authoritative = authoritative === undefined ? undefined : { ...authoritative }; - this.#predicted = authoritative === undefined ? undefined : { ...authoritative }; + let predicted: Record | undefined = authoritative === undefined ? undefined : { ...authoritative }; + if (predicted !== undefined) for (const p of this.#pending) predicted = this.#step(predicted, p.input, p.dtMs); + this.#predicted = predicted; + } + + /** + * One predicted step of `state` without recording it (e.g. continuing a + * prediction through a handoff, before the target knows the entity). + */ + step(state: EntityFields, input: TInput, dtMs: number): EntityFields { + return this.#step({ ...state }, input, dtMs); + } + + /** + * Show `shown` now and ease into the prediction (each `ease` field by its + * policy), e.g. what was drawn before a handoff rebound the entity. + */ + easeFrom(shown: EntityFields, now: number): void { + const predicted = this.#predicted; + const kind = this.#kind; + if (predicted === undefined || kind === undefined) return; + const epsilon = this.#options.epsilon ?? 1e-6; + for (const field of kind.fields) { + const policy = this.#policy(field.name); + const from = shown[field.name]; + const to = predicted[field.name]; + if (policy.mode !== 'ease' || typeof from !== 'number' || typeof to !== 'number') continue; + const angle = field.type === 'angle'; + const value = angle ? -angleDelta(from, to) : from - to; + const duration = policy.durationMs ?? 100; + if (Math.abs(value) > epsilon && duration > 0) { + this.#offsets.set(field.name, { value, start: now, durationMs: duration, angle }); + } else { + this.#offsets.delete(field.name); + } + } } /** New session (Welcome): sequence numbers restart, pending inputs are void. */ diff --git a/js/tests/game-replica-prediction.test.mjs b/js/tests/game-replica-prediction.test.mjs index 98305a5a6..cd7d23ffc 100644 --- a/js/tests/game-replica-prediction.test.mjs +++ b/js/tests/game-replica-prediction.test.mjs @@ -102,6 +102,20 @@ test('prediction replays unacked inputs over authoritative state', () => { assert.deepEqual(predictor.pending.map((p) => p.seq), [4, 5]); }); +test('inputs recorded before the entity is known are replayed when it binds', () => { + const predictor = new Predictor({ predict: moverPredict }); + predictor.bind(7); + predictor.record(1, 10, 100); + predictor.record(2, 10, 100); + assert.equal(predictor.active, false); + predictor.bind(7, ARENA_SCHEMA.byId.get(1), { x: 0, y: 0, yaw: 0, hp: 100, name: 'p' }); + close(predictor.predicted().x, 2, 1e-9, 'both replayed'); + // Another entity: the inputs were not its. + predictor.bind(8, ARENA_SCHEMA.byId.get(1), { x: 0, y: 0, yaw: 0, hp: 100, name: 'p' }); + close(predictor.predicted().x, 0, 1e-9); + assert.deepEqual(predictor.pending, []); +}); + test('ease blends the divergence out over time while snap jumps', () => { const authoritative = { x: 1, y: 0, yaw: 0, hp: 80, name: 'p' }; // server hit a wall const eased = boundPredictor({ mode: 'ease', durationMs: 200 }); diff --git a/js/tests/game-world.test.mjs b/js/tests/game-world.test.mjs index 4718c2e6f..228549dcf 100644 --- a/js/tests/game-world.test.mjs +++ b/js/tests/game-world.test.mjs @@ -235,6 +235,65 @@ test('handoff holds the predicted entity until the target binds it (no source co client.close(); }); +test('handoffFrame: the prediction continues through a handoff in the target frame, inputs reach the target, the switch eases', async () => { + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + const inputs = { z1: [], z2: [] }; + let welcomeZ2 = false; + network.onMessage = (conn, m) => { + if (m.type === 'Hello' && (conn.zoneId !== 'z2' || welcomeZ2)) conn.send(welcome({ zoneId: conn.zoneId })); + if (m.type === 'Input') inputs[conn.zoneId].push(m.seq); + }; + // Zone-local x; z2 starts 10 m further on (its x = world x − 10). + const client = new GameClient({ + url: (zone) => `ws://game.test/zones/${zone}`, + ticket: ({ zoneId }) => `fresh:${zoneId}`, + socket: network.factory, + scheduler, + pingIntervalMs: 60_000, + handoffRetainMs: 100, + handoffTimeoutMs: 2000, + prediction: { + encodeInput: (dx) => new Uint8Array([dx & 0xff]), + predict: (s, dx, dt) => ({ x: s.x + (dx * dt) / 1000 }), + controlledEntity: () => 1, + handoffFrame: (fields, from, to) => (from === 'z1' && to === 'z2' ? { ...fields, x: fields.x - 10 } : undefined) + } + }); + const world = (e) => (e.zoneId === 'z2' ? 10 : 0) + e.fields.x; + const own = () => client.render().filter((e) => e.id === 1); + await client.connect('z1'); + network.last('z1').send(delta({ creates: [avatar(1, 9.5)] })); + client.sendInput(10, 100); // +1 → 10.5 (lost: z1 hands off before applying it) + assert.ok(Math.abs(world(own()[0]) - 10.5) < 1e-3, `predicted: ${JSON.stringify(own())}`); + + network.last('z1').send({ type: 'Handoff', targetZone: 'z2', transferTicket: 'transfer:t1' }); + await scheduler.advance(10); + // Not welcomed yet: predicted on in z2's frame, the inputs kept. + client.sendInput(10, 100); + client.sendInput(10, 100); + let shown = own(); + assert.deepEqual(shown.map((e) => [e.key, e.predicted]), [['z2:1', true]]); + assert.ok(Math.abs(world(shown[0]) - 12.5) < 1e-3, `continued: ${world(shown[0])}`); + assert.deepEqual(inputs.z2, []); + + // Welcomed: the kept inputs go to the target. + welcomeZ2 = true; + network.last('z2').close(); + await scheduler.advance(2000); + assert.equal(inputs.z2.length >= 2, true, `sent to z2: ${inputs.z2}`); + // The target admitted the entity where z1 last had it (9.5 → z2's −0.5), + // without the lost input; it has not applied the two kept ones yet. + network.last('z2').send(delta({ ackSeq: 0, creates: [avatar(1, -0.5)] })); + network.last('z1').send(delta({ serverTick: 101, updates: [] })); + shown = own(); + assert.deepEqual(shown.map((e) => [e.key, e.predicted]), [['z2:1', true]]); + assert.ok(Math.abs(world(shown[0]) - 12.5) < 1e-3, `eases from what was shown: ${world(shown[0])}`); + await scheduler.advance(1000); + assert.ok(Math.abs(world(own()[0]) - 11.5) < 1e-3, `converged on the target's prediction: ${world(own()[0])}`); + client.close(); +}); + test('a silent handoff target times out into the return path', async () => { const network = new FakeNetwork(); const scheduler = new FakeScheduler(); From bbc15357b97b01562e3375deeb75c2d46241dece Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 22:40:09 -0500 Subject: [PATCH 268/484] feat(game)!: one continuous Mob Pit world across rooms Rooms sit at fixed world places (room (x, y) at (x, y) x 40 m) and a doorway is a passage: pit_step walks through the gap past the wall line, the room hands the player over 0.5 m past it (hysteresis) and the next room admits it at the same world point with its velocity (carried MoveState in the target frame) instead of 2 m inside the opposite wall. Player x/y widen to +-22 m on the wire. Both pages draw the world: the Vite page builds the 5x5 rooms around yours from pitRoom (biome floor, walls with doorways, pillars) under a floating origin; the SvelteKit canvas follows your world position over the 3x3 rooms around. Both predict through the handoff (handoffFrame). Tests: rooms test checks the arrival world point; headless and Playwright walks assert the own world position never moves more than one tick across a doorway. [[tasks/gr-p41-mobpit-rooms-zones]] --- examples/game/README.md | 22 +- .../client/src/generated/mobpit/constants.ts | 3 + .../client/src/generated/mobpit/events.ts | 3 + .../client/src/generated/mobpit/schema.ts | 8 +- .../client/src/generated/mobpit/surface.json | 31 +- examples/game/client/src/mobpit/client.ts | 57 +++- examples/game/client/src/mobpit/main.ts | 274 ++++++++++++++---- examples/game/client/tests/helpers/mobpit.mjs | 44 ++- .../client/tests/mobpit-headless.test.mjs | 31 +- examples/game/server/rooms/src/zone.rs | 122 +++++--- examples/game/server/rooms/tests/rooms.rs | 57 +++- examples/game/server/sim/src/arena.rs | 17 +- examples/game/server/sim/src/mobpit.rs | 239 ++++++++++++--- .../src/lib/generated/mobpit/constants.ts | 3 + .../src/lib/generated/mobpit/events.ts | 3 + .../src/lib/generated/mobpit/schema.ts | 8 +- .../src/lib/generated/mobpit/surface.json | 31 +- examples/game/sveltekit/src/lib/pit/loop.ts | 165 ++++++++--- .../sveltekit/src/routes/pit/+page.svelte | 6 +- examples/game/sveltekit/tests/pit.test.mjs | 32 +- 20 files changed, 905 insertions(+), 251 deletions(-) diff --git a/examples/game/README.md b/examples/game/README.md index 47f69ec31..0d7a53146 100644 --- a/examples/game/README.md +++ b/examples/game/README.md @@ -505,7 +505,10 @@ Controls: WASD / stick move (the Arena's movement, predicted by `pit_step`, same floor and pillars), **Space** attack (120° cone, 2.2 m), **E** dash, **O** debug overlay. Walk through a **doorway** — the glowing gap in the middle of each wall (go beside the pillar on its axis) — into the -neighbouring room. Mobs wander near home, aggro within 7 m, chase, stop and +neighbouring room. The rooms are **one continuous world**: room `(x, y)` +sits at world `(x, y) × 40 m` (they share walls), the rooms around yours +are drawn from their seeded layout, so you see into the next room, and +going through a doorway just carries on walking — no scene swap, no jump. Mobs wander near home, aggro within 7 m, chase, stop and show a red **telegraph ring** that fills for 0.8 s, then hit everyone inside it. Grunts (green, 10 XP), brutes (purple, 25 XP) and elites (red, 60 XP) respawn 4 s after dying. Level `n` starts at `40·(n−1)²` XP. @@ -518,10 +521,19 @@ the same Rust compiled to WebAssembly (`createMobpitPures().pitRoom`) for the floor colour and the minimap; nothing static is replicated. Seed: `MOBPIT_SEED` (worker var). -**Leaving and coming back.** A doorway hands the player over -(`ctx.handoff`, carrying where along the wall it went through); the room -signs a single-use transfer ticket and the SDK reconnects to the next -room's object, wherever it runs. A room that empties writes its snapshot +**Leaving and coming back.** A doorway is a passage: the predicted step +(`pit_step`) lets you walk through the gap past the wall line, and 0.5 m +past it (hysteresis, so dithering at the line does not bounce you back) the +room hands you over (`ctx.handoff`, carrying your movement state in the +next room's frame: the same world point and velocity); the room signs a +single-use transfer ticket and the SDK reconnects to the next room's +object, wherever it runs. The client keeps predicting through the +handoff (`prediction.handoffFrame`: the room offset), sends the inputs of +the transfer to the new room once it is in, and eases into the new room's +state, so the handoff's latency never shows. Positions on the wire stay +room-local; the page adds the room's offset and keeps a floating origin at +your room. Mobs of neighbouring rooms are not shown yet: observing a room +keeps it awake, which would defeat room hibernation. A room that empties writes its snapshot (`Zone::hibernate`: every mob's position, HP, state, generation and respawn timer, and the room's kill count) and goes **dormant**; after `ZONE_HIBERNATE_AFTER_MS` (10 s) it is **hibernated**: dropped from memory, diff --git a/examples/game/client/src/generated/mobpit/constants.ts b/examples/game/client/src/generated/mobpit/constants.ts index e01248b13..2b523df3e 100644 --- a/examples/game/client/src/generated/mobpit/constants.ts +++ b/examples/game/client/src/generated/mobpit/constants.ts @@ -21,6 +21,9 @@ export const PIT_WORLD: PitWorld = { defaultSeed: 186474221, half: 20, doorHalf: 2.5, + roomSize: 40, + passage: 2, + hysteresis: 0.5, maxRoom: 1000000, biomes: ['highlands', 'steppe', 'forest', 'meadow'] }; diff --git a/examples/game/client/src/generated/mobpit/events.ts b/examples/game/client/src/generated/mobpit/events.ts index a3f5878ba..b98152277 100644 --- a/examples/game/client/src/generated/mobpit/events.ts +++ b/examples/game/client/src/generated/mobpit/events.ts @@ -55,6 +55,9 @@ export interface PitWorld { readonly defaultSeed: number; readonly half: number; readonly doorHalf: number; + readonly roomSize: number; + readonly passage: number; + readonly hysteresis: number; readonly maxRoom: number; readonly biomes: readonly string[]; } diff --git a/examples/game/client/src/generated/mobpit/schema.ts b/examples/game/client/src/generated/mobpit/schema.ts index 8019b0b3f..cf619af1f 100644 --- a/examples/game/client/src/generated/mobpit/schema.ts +++ b/examples/game/client/src/generated/mobpit/schema.ts @@ -15,9 +15,9 @@ export type KindName = keyof typeof KIND; /** `player` (kind 1, priority 2). */ export interface PlayerFields { - /** `quant [-20, 19.999847] / 18 bits` */ + /** `quant [-22, 21.999832] / 18 bits` */ readonly x: number; - /** `quant [-20, 19.999847] / 18 bits` */ + /** `quant [-22, 21.999832] / 18 bits` */ readonly y: number; /** `quant [-16, 15.9921875] / 12 bits` */ readonly vx: number; @@ -164,8 +164,8 @@ export function pitFields(entity: { readonly fields: EntityFields }): PitFields /** Wire type of every replicated field, by kind and wire field name. */ export const FIELD_TYPES = { player: { - x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, - y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + x: { type: 'quant', min: -22, max: 21.999832153320313, bits: 18 }, + y: { type: 'quant', min: -22, max: 21.999832153320313, bits: 18 }, vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, dash: { type: 'u8' }, diff --git a/examples/game/client/src/generated/mobpit/surface.json b/examples/game/client/src/generated/mobpit/surface.json index 6c0a39c71..4299b39e5 100644 --- a/examples/game/client/src/generated/mobpit/surface.json +++ b/examples/game/client/src/generated/mobpit/surface.json @@ -53,7 +53,10 @@ "default_seed": 186474221, "door_half": 2.5, "half": 20.0, - "max_room": 1000000 + "hysteresis": 0.5, + "max_room": 1000000, + "passage": 2.0, + "room_size": 40.0 } } ], @@ -330,8 +333,8 @@ "priority": 1.0, "type": { "bits": 18, - "max": 19.999847, - "min": -20.0, + "max": 21.999832, + "min": -22.0, "type": "quant" } }, @@ -344,8 +347,8 @@ "priority": 1.0, "type": { "bits": 18, - "max": 19.999847, - "min": -20.0, + "max": 21.999832, + "min": -22.0, "type": "quant" } }, @@ -854,6 +857,24 @@ "type": "f32" } }, + { + "name": "room_size", + "type": { + "type": "f32" + } + }, + { + "name": "passage", + "type": { + "type": "f32" + } + }, + { + "name": "hysteresis", + "type": { + "type": "f32" + } + }, { "name": "max_room", "type": { diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts index 42613f9d3..641904279 100644 --- a/examples/game/client/src/mobpit/client.ts +++ b/examples/game/client/src/mobpit/client.ts @@ -11,11 +11,16 @@ * Walking through a doorway, the room hands the player to the next room * (`Handoff`), and the SDK reconnects there with the transfer ticket. * + * One continuous world: room `(x, y)` sits at world `(x, y) × ROOM_SIZE` + * and entity positions are room-local, so `worldOf` places anything from + * any room (the doorway arrival is the same world point, see + * `game_sim::mobpit`). + * * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the * fact is only *queued*) → `saved` (to the killer, when the durable cell * commit settled) → `profile`. */ -import type { GameSocketFactory } from '@hops-ops/distributed/game'; +import type { EntityFields, GameSocketFactory, RenderedEntity } from '@hops-ops/distributed/game'; import * as pit from '../generated/mobpit/index.ts'; import type { DevApi } from '../shared/dev-api.ts'; @@ -29,6 +34,34 @@ export function parseRoom(zone: string): [number, number] | undefined { return m === null ? undefined : [Number(m[1]), Number(m[2])]; } +/** Room edge length (m): room `(x, y)` is centred at world `(x, y) × ROOM_SIZE`. */ +export const ROOM_SIZE = pit.PIT_WORLD.roomSize; + +/** World position (m) of a room-local point of `zone` (undefined for a non-room zone). */ +export function toWorldXY(zone: string, x: number, y: number): { x: number; y: number } | undefined { + const room = parseRoom(zone); + return room === undefined ? undefined : { x: room[0] * ROOM_SIZE + x, y: room[1] * ROOM_SIZE + y }; +} + +/** World position (m) of a rendered entity (every Mob Pit kind has local `x` / `y`). */ +export function worldOf(entity: RenderedEntity): { x: number; y: number } | undefined { + const { x, y } = entity.fields as { x?: unknown; y?: unknown }; + return typeof x === 'number' && typeof y === 'number' ? toWorldXY(entity.zoneId, x, y) : undefined; +} + +/** + * The own player's predicted fields re-expressed in the next room's frame + * (the same world point): lets the SDK keep predicting through a doorway + * handoff instead of holding the player still (`handoffFrame`). + */ +export function pitHandoffFrame(fields: EntityFields, from: string, to: string): EntityFields | undefined { + const a = parseRoom(from); + const b = parseRoom(to); + const { x, y } = fields as { x?: unknown; y?: unknown }; + if (a === undefined || b === undefined || typeof x !== 'number' || typeof y !== 'number') return undefined; + return { ...fields, x: x + (a[0] - b[0]) * ROOM_SIZE, y: y + (a[1] - b[1]) * ROOM_SIZE }; +} + /** `[x, y]` → `pit..`. */ export function roomZone(x: number, y: number): string { return `pit.${x}.${y}`; @@ -124,6 +157,10 @@ export type MobPitClient = pit.MobpitClient & profile(): pit.Profile | undefined; /** The room the player is in (authority zone). */ room(): string | undefined; + /** The own player as rendered now (predicted; held through a handoff). */ + me(): RenderedEntity | undefined; + /** World position (m) of the own player as rendered now. */ + position(): { x: number; y: number } | undefined; /** Kills by me whose fact has not settled yet (key → event). */ unsaved: ReadonlyMap; /** The rooms' generated contents (the Rust generator as WASM). */ @@ -145,8 +182,10 @@ export function createMobPitClient(options: MobPitClientOptions): MobPitClient { ticket: options.api.ticketSource(), socket: options.socket, pingIntervalMs: 500, - inputDtMs: 1000 / 30 - // Prediction: the generated default, `pit_step` compiled to WASM. + inputDtMs: 1000 / 30, + // Prediction: the generated default, `pit_step` compiled to WASM, + // carried on through doorways in the next room's frame. + prediction: { handoffFrame: pitHandoffFrame } }); const hello = latest( (h) => typed.on('hello', h), @@ -159,11 +198,23 @@ export function createMobPitClient(options: MobPitClientOptions): MobPitClient { }); typed.on('saved', (saved) => unsaved.delete(saved.key)); const pures = pit.createMobpitPures(); + // The own player: the predicted entity, or (mid-handoff) the SDK's + // bridge, the last predicted state in the room just left. + const me = () => { + const id = hello.get()?.entity; + const rendered = typed.client.render().filter((e) => pit.isPlayer(e)); + return rendered.find((e) => e.predicted) ?? rendered.find((e) => e.id === id && e.zoneId === typed.client.authority?.zoneId) ?? rendered.find((e) => e.id === id); + }; return { ...typed, hello: hello.get, profile: profile.get, room: () => typed.client.authority?.zoneId, + me, + position: () => { + const entity = me(); + return entity === undefined ? undefined : worldOf(entity); + }, unsaved, pures, ready: Promise.all([hello.ready, typed.prediction?.ready, pures.ready]).then(([h]) => h) diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts index 6cfd06246..0c12e16a7 100644 --- a/examples/game/client/src/mobpit/main.ts +++ b/examples/game/client/src/mobpit/main.ts @@ -2,8 +2,13 @@ * Mob Pit page: Babylon scene over `createMobPitClient`. * * What to look at: rooms are celld Durable Objects on a near-infinite - * seeded grid. Walk through a doorway (the gaps in the middle of each wall) - * into the next room; the minimap (bottom right) shows every known room + * seeded grid, laid out as one continuous world (room `(x, y)` at + * `(x, y) × ROOM_SIZE`): the rooms around yours are drawn from the seeded + * layout (`pitRoom`, Rust as WASM: biome floor, walls, doorways, pillars), + * so you see into the next room before you go. Walk through a doorway (the + * gaps in the middle of each wall) and you are simply in the next room — + * the room hands you over at the same world point; nothing moves. A + * floating origin at your room keeps coordinates small. The minimap (bottom right) shows every known room * live — active, dormant (just left), hibernated (asleep in storage) — from * the `zone_status` read model. Come back to a room after it slept: it * wakes from its snapshot with the mobs you left (toast). Kill a mob @@ -12,9 +17,12 @@ * node and isolate run the room — celld decides, the game never does. */ import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture'; import { Color3 } from '@babylonjs/core/Maths/math.color'; +import { Vector3 } from '@babylonjs/core/Maths/math.vector'; import { Mesh } from '@babylonjs/core/Meshes/mesh'; import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import { TransformNode } from '@babylonjs/core/Meshes/transformNode'; import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; import { ARENA_FLOOR } from '../generated/arena/constants.ts'; @@ -26,7 +34,6 @@ import { isPillar, isPit, mobFields, - pillarFields, pitFields, playerFields, type PitFields, @@ -35,13 +42,14 @@ import { import { DevApi } from '../shared/dev-api.ts'; import { Hud } from '../shared/hud.ts'; import { cameraRelative, InputSampler, toAxis } from '../shared/input.ts'; -import { createStage, material, toWorld } from '../shared/scene.ts'; +import { createStage, material } from '../shared/scene.ts'; import { createBoardWatcher, createMobPitClient, DEFAULT_ZONE, MobPitApi, parseRoom, + ROOM_SIZE, roomZone, TIERS, type BoardSnapshot, @@ -50,7 +58,12 @@ import { } from './client.ts'; /** The Arena floor, generated from the simulation's constants (`game_sim::arena::arena_floor`). */ -const { half: HALF, playerRadius: PLAYER_RADIUS } = ARENA_FLOOR; +const { half: HALF, playerRadius: PLAYER_RADIUS, pillars: PILLARS } = ARENA_FLOOR; +/** Rooms drawn around yours (2 → 5×5). */ +const ROOM_VIEW = 2; +/** Wall thickness and height (m), drawn just outside each room's floor. */ +const WALL_T = 0.3; +const WALL_H = 0.6; /** Swing cone, from the server's rules: reach to a mob's edge, plus the body. */ const { attackRange, attackHalfAngle: SWING_HALF, swingFrames: SWING_FRAMES } = PIT_RULES; const ATTACK_REACH = attackRange + PLAYER_RADIUS; @@ -230,32 +243,162 @@ mats.blade.emissiveColor = new Color3(0.6, 0.6, 0.7); const tierMats = new Map(); for (const [tier, t] of Object.entries(TIERS)) tierMats.set(Number(tier), material(scene, `mob-${tier}`, t.color)); -// Doorways: a glowing gate in the middle of each wall, labelled with the -// room behind it; the floor takes the room's biome colour. -const doorMat = material(scene, 'door', '#4dd0e1', 0.55); -doorMat.emissiveColor = Color3.FromHexString('#4dd0e1'); +// ---- the world: rooms at fixed places, floating origin at your room ---- +// The stage's single floor and walls give way to one chunk per room. +for (const mesh of [...scene.meshes]) if (mesh.name === 'floor' || mesh.name === 'wall') mesh.dispose(); +type Room = readonly [number, number]; +let origin: Room = parseRoom(zone) ?? [0, 0]; + +/** Scene position of a room-local point of room `room`. */ +function place(room: Room, x: number, y: number, height = 0): Vector3 { + return new Vector3((room[0] - origin[0]) * ROOM_SIZE + x, height, (room[1] - origin[1]) * ROOM_SIZE + y); +} + +/** Scene position of a room-local point of zone `zoneId` (the origin room if it is not a room). */ +function placeIn(zoneId: string, x: number, y: number, height = 0): Vector3 { + return place(parseRoom(zoneId) ?? origin, x, y, height); +} + +/** Room templates, instanced per room: floor per biome, wall segment, doorway gate, pillar. */ +const templates = (() => { + const px = 1024; + const texture = new DynamicTexture('room-grid', { width: px, height: px }, scene, true); + const ctx = texture.getContext() as CanvasRenderingContext2D; + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, px, px); + const lines = HALF * 2; + for (let i = 0; i <= lines; i += 1) { + const p = (i / lines) * px; + ctx.strokeStyle = i % 5 === 0 ? '#9aa0aa' : '#c8ccd2'; + ctx.lineWidth = i % 5 === 0 ? 3 : 1.5; + ctx.beginPath(); + ctx.moveTo(p, 0); + ctx.lineTo(p, px); + ctx.moveTo(0, p); + ctx.lineTo(px, p); + ctx.stroke(); + } + texture.update(); + const floors = BIOME_COLOR.map((color, biome) => { + const m = material(scene, `floor-${biome}`, color); + m.diffuseTexture = texture; + m.diffuseColor = Color3.FromHexString(color).scale(0.42); + m.specularColor = Color3.Black(); + const ground = MeshBuilder.CreateGround(`floor-${biome}`, { width: HALF * 2, height: HALF * 2 }, scene); + ground.material = m; + ground.isPickable = false; + ground.setEnabled(false); + return ground; + }); + const wallMat = material(scene, 'room-wall', '#4b5668'); + const segment = HALF - PIT_WORLD.doorHalf; + const wall = MeshBuilder.CreateBox('room-wall', { width: segment, depth: WALL_T, height: WALL_H }, scene); + wall.material = wallMat; + wall.isPickable = false; + wall.setEnabled(false); + const doorMat = material(scene, 'door', '#4dd0e1', 0.55); + doorMat.emissiveColor = Color3.FromHexString('#4dd0e1'); + const gate = MeshBuilder.CreateBox('door', { width: PIT_WORLD.doorHalf * 2, depth: 0.3, height: 0.08 }, scene); + gate.material = doorMat; + gate.isPickable = false; + gate.setEnabled(false); + const pillar = MeshBuilder.CreateCylinder('room-pillar', { diameter: 1, height: 2.4, tessellation: 24 }, scene); + pillar.material = mats.pillar; + pillar.isPickable = false; + pillar.setEnabled(false); + return { floors, wall, segment, gate, pillar }; +})(); + +type Chunk = { room: Room; node: TransformNode; biome: number | undefined; seed: number }; +const chunks = new Map(); + +/** One room's static geometry under a node at the room's centre. */ +function createChunk(room: Room): Chunk { + const key = roomZone(room[0], room[1]); + const node = new TransformNode(`room-${key}`, scene); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + const biome = pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: room[0], y: room[1] }).biome : undefined; + const add = (mesh: Mesh, name: string, x: number, y: number, height: number, turn = 0) => { + const instance = mesh.createInstance(`${key}-${name}`); + instance.parent = node; + instance.position.set(x, height, y); + instance.rotation.y = turn; + instance.isPickable = false; + return instance; + }; + add(templates.floors[biome ?? 0]!, 'floor', 0, 0, 0); + // Each wall: two segments either side of its doorway gap, just outside + // the floor (the neighbour's wall stands right behind it). + const off = PIT_WORLD.doorHalf + templates.segment / 2; + const out = HALF + WALL_T / 2; + for (const side of [-1, 1]) { + for (const along of [-1, 1]) { + add(templates.wall, `wall-h${side}${along}`, along * off, side * out, WALL_H / 2); + add(templates.wall, `wall-v${side}${along}`, side * out, along * off, WALL_H / 2, Math.PI / 2); + } + add(templates.gate, `door-h${side}`, 0, side * HALF, 0.04); + add(templates.gate, `door-v${side}`, side * HALF, 0, 0.04, Math.PI / 2); + } + PILLARS.forEach(({ x, y, r }, i) => { + const instance = add(templates.pillar, `pillar-${i}`, x, y, 1.2); + instance.scaling.set(r * 2, 1, r * 2); + }); + return { room, node, biome, seed }; +} + +/** Keep the rooms within `ROOM_VIEW` of the origin built and placed. */ +function syncChunks(): void { + const wanted = new Set(); + for (let dy = -ROOM_VIEW; dy <= ROOM_VIEW; dy += 1) { + for (let dx = -ROOM_VIEW; dx <= ROOM_VIEW; dx += 1) { + const room: Room = [origin[0] + dx, origin[1] + dy]; + const key = roomZone(room[0], room[1]); + wanted.add(key); + const chunk = chunks.get(key); + // Built before the world module loaded or the seed was known: rebuild. + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + if (chunk !== undefined && chunk.seed === seed && (chunk.biome !== undefined || !pit.pures.loaded())) continue; + chunk?.node.dispose(); + chunks.set(key, createChunk(room)); + } + } + for (const [key, chunk] of chunks) { + if (!wanted.has(key)) { + chunk.node.dispose(); + chunks.delete(key); + continue; + } + chunk.node.position.copyFrom(place(chunk.room, 0, 0)); + } +} + +/** Re-centre on `to` without a visible move: the camera shifts with the world. */ +function moveOrigin(to: Room): void { + if (to[0] === origin[0] && to[1] === origin[1]) return; + const shift = new Vector3((to[0] - origin[0]) * ROOM_SIZE, 0, (to[1] - origin[1]) * ROOM_SIZE); + origin = to; + stage.camera.setTarget(stage.camera.target.subtract(shift), false, false, true); + syncChunks(); +} +syncChunks(); +pit.pures.ready.then(syncChunks, () => undefined); +pit.on('hello', () => syncChunks()); + +// Doorway labels of your room: anchors at its doors (the origin room, so +// they never move), named after the room behind each. const DOORS: { dx: number; dy: number }[] = [ { dx: 1, dy: 0 }, { dx: -1, dy: 0 }, { dx: 0, dy: 1 }, { dx: 0, dy: -1 } ]; -const doorMeshes = DOORS.map(({ dx, dy }, i) => { - const gate = MeshBuilder.CreateBox( - `door-${i}`, - { width: dx === 0 ? PIT_WORLD.doorHalf * 2 : 0.3, depth: dy === 0 ? PIT_WORLD.doorHalf * 2 : 0.3, height: 0.2 }, - scene - ); - gate.material = doorMat; - gate.isPickable = false; - gate.position.copyFrom(toWorld(dx * HALF, dy * HALF, 0.1)); - return gate; +const doorAnchors = DOORS.map(({ dx, dy }, i) => { + const anchor = MeshBuilder.CreateBox(`door-anchor-${i}`, { size: 0.01 }, scene); + anchor.isVisible = false; + anchor.isPickable = false; + anchor.position.set(dx * HALF, 0.1, dy * HALF); + return anchor; }); -const biomeFloor = MeshBuilder.CreateGround('biome', { width: HALF * 2, height: HALF * 2 }, scene); -biomeFloor.position.y = 0.01; -biomeFloor.isPickable = false; -const biomeMat = material(scene, 'biome', '#3f7d4e', 0.18); -biomeFloor.material = biomeMat; let shownRoom = ''; function showRoom(zone: string): void { @@ -263,20 +406,18 @@ function showRoom(zone: string): void { if (at === undefined || zone === shownRoom) return; shownRoom = zone; DOORS.forEach(({ dx, dy }, i) => { - stage.labels.set(`door-${i}`, doorMeshes[i]!, `→ ${roomZone(at[0] + dx, at[1] + dy)}`, 0.6, 'door'); + stage.labels.set(`door-${i}`, doorAnchors[i]!, `→ ${roomZone(at[0] + dx, at[1] + dy)}`, 0.6, 'door'); }); const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; if (pit.pures.loaded()) { const room = pit.pures.pitRoom({ seed, x: at[0], y: at[1] }); - biomeMat.diffuseColor = Color3.FromHexString(BIOME_COLOR[room.biome] ?? '#3f7d4e'); hud.row('Room', `${zone} · ${PIT_WORLD.biomes[room.biome] ?? '?'} · danger ${room.danger} · ${room.mobs.length} mobs`); } } type PlayerVisual = { kind: 'player'; body: Mesh; blade: Mesh; arc: Mesh; nose: Mesh }; type MobVisual = { kind: 'mob'; body: Mesh; hpBack: Mesh; hpFill: Mesh; ring: Mesh; fill: Mesh; tier: number }; -type PillarVisual = { kind: 'pillar'; body: Mesh }; -type Visual = PlayerVisual | MobVisual | PillarVisual; +type Visual = PlayerVisual | MobVisual; const visuals = new Map(); function flatDisc(id: string, radius: number, mat: StandardMaterial, arc = 1): Mesh { @@ -323,11 +464,6 @@ function visualFor(entity: RenderedEntity, mine: boolean): Visual { if (visual !== undefined) return visual; if (isMob(entity)) { visual = createMob(entity); - } else if (isPillar(entity)) { - const { r } = pillarFields(entity); - const body = MeshBuilder.CreateCylinder(entity.key, { diameter: r * 2, height: 2.4, tessellation: 24 }, scene); - body.material = mats.pillar; - visual = { kind: 'pillar', body }; } else { visual = createPlayer(entity, mine); } @@ -340,37 +476,42 @@ function dispose(visual: Visual): void { } // ---- kill / saved popups (DOM labels anchored to invisible meshes) ---- -type Popup = { mesh: Mesh; until: number }; +type Popup = { mesh: Mesh; until: number; zone: string; x: number; y: number }; const popups = new Map(); let popupSeq = 0; -function popup(key: string, x: number, y: number, text: string, className: string, ttlMs: number): void { +/** The room a kill happened in, from its fact key (`…:pit..:…`). */ +function killRoom(key: string, fallback: string): string { + return /:(pit\.-?\d+\.-?\d+):/.exec(key)?.[1] ?? fallback; +} + +function popup(key: string, zoneId: string, x: number, y: number, text: string, className: string, ttlMs: number): void { let p = popups.get(key); if (p === undefined) { const mesh = MeshBuilder.CreateBox(`popup-${popupSeq++}`, { size: 0.01 }, scene); mesh.isVisible = false; - mesh.position.copyFrom(toWorld(x, y, 1.2)); - p = { mesh, until: 0 }; + p = { mesh, until: 0, zone: killRoom(key, zoneId), x, y }; + mesh.position.copyFrom(placeIn(p.zone, x, y, 1.2)); popups.set(key, p); } p.until = performance.now() + ttlMs; stage.labels.set(`popup:${key}`, p.mesh, text, 0.6, `pit-pop ${className}`); } -pit.on('kill', (kill) => { +pit.on('kill', (kill, zoneId) => { const mine = kill.killer === pit.hello()?.entity; const tier = TIERS[kill.tier]?.name ?? 'Mob'; - if (mine) popup(kill.key, kill.x, kill.y, `${tier} slain · saving…`, 'pending', 60_000); - else popup(kill.key, kill.x, kill.y, `${kill.killerName} slew a ${tier}`, 'other', 2000); + if (mine) popup(kill.key, zoneId, kill.x, kill.y, `${tier} slain · saving…`, 'pending', 60_000); + else popup(kill.key, zoneId, kill.x, kill.y, `${kill.killerName} slew a ${tier}`, 'other', 2000); }); let savedCount = 0; -pit.on('saved', (saved) => { +pit.on('saved', (saved, zoneId) => { if (saved.ok) { savedCount += 1; const waited = saved.waitedMs >= 200 ? ` (${(saved.waitedMs / 1000).toFixed(1)} s)` : ''; - popup(saved.key, saved.x, saved.y, `+${saved.xp} XP saved ✓${waited}`, 'saved', 2500); + popup(saved.key, zoneId, saved.x, saved.y, `+${saved.xp} XP saved ✓${waited}`, 'saved', 2500); } else { - popup(saved.key, saved.x, saved.y, `save failed: ${saved.error ?? '?'}`, 'failed', 4000); + popup(saved.key, zoneId, saved.x, saved.y, `save failed: ${saved.error ?? '?'}`, 'failed', 4000); } }); pit.on('died', (d) => { @@ -451,42 +592,47 @@ function sendCommandFrame(): void { // ---- frame ---- stage.onFrame((now, dtMs) => { commandFrames.update(now, sendCommandFrame); + const here = pit.room(); + const hereRoom = here === undefined ? undefined : parseRoom(here); + if (hereRoom !== undefined) moveOrigin(hereRoom); const hello = pit.hello(); const authority = client.authority; const rendered = client.render(); const seen = new Set(); - let me: { x: number; y: number; hp: number; dead: boolean } | undefined; + let me: { at: Vector3; hp: number; dead: boolean } | undefined; let stats: PitFields | undefined; for (const entity of rendered) { if (isPit(entity)) { - stats = pitFields(entity); + if (entity.zoneId === here) stats = pitFields(entity); continue; } - const mine = authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity; + // Pillars are static: every room's are drawn with its chunk. + if (isPillar(entity)) continue; + // Yours: predicted, or the SDK's hold of it during a doorway handoff. + const mine = + entity.predicted || (authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity); + const at = (x: number, y: number, height: number) => placeIn(entity.zoneId, x, y, height); const visual = visualFor(entity, mine); seen.add(entity.key); - const visible = !entity.stale || visual.kind === 'pillar'; - if (visual.kind === 'pillar') { - const { x, y } = pillarFields(entity); - visual.body.position.copyFrom(toWorld(x, y, 1.2)); - } else if (visual.kind === 'mob') { + const visible = !entity.stale; + if (visual.kind === 'mob') { const mob = mobFields(entity); const { x, y } = mob; const height = visual.tier === 3 ? 1 : visual.tier === 2 ? 0.75 : 0.45; - visual.body.position.copyFrom(toWorld(x, y, height)); + visual.body.position.copyFrom(at(x, y, height)); visual.body.rotation.y = -mob.face; const hp = mob.hp / 100; const top = height * 2 + 0.35; - visual.hpBack.position.copyFrom(toWorld(x, y, top)); - visual.hpFill.position.copyFrom(toWorld(x, y, top)); + visual.hpBack.position.copyFrom(at(x, y, top)); + visual.hpFill.position.copyFrom(at(x, y, top)); visual.hpFill.scaling.x = Math.max(0.001, hp); const tele = mob.tele / 255; const winding = mob.state === 2; visual.ring.setEnabled(visible && winding); visual.fill.setEnabled(visible && winding); if (winding) { - visual.ring.position.copyFrom(toWorld(x, y, 0.03)); - visual.fill.position.copyFrom(toWorld(x, y, 0.04)); + visual.ring.position.copyFrom(at(x, y, 0.03)); + visual.fill.position.copyFrom(at(x, y, 0.04)); visual.fill.scaling.setAll(Math.max(0.05, tele)); } visual.body.scaling.setAll(winding ? 1 + 0.15 * tele : 1); @@ -494,19 +640,19 @@ stage.onFrame((now, dtMs) => { } else { const player = playerFields(entity); const { x, y, dead, face, swing } = player; - visual.body.position.copyFrom(toWorld(x, y, 0.9)); + visual.body.position.copyFrom(at(x, y, 0.9)); visual.body.material = dead ? mats.dead : mine ? mats.me : mats.other; - visual.nose.position.copyFrom(toWorld(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3)); + visual.nose.position.copyFrom(at(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3)); visual.nose.rotation.y = -face; // Blade sweeps through the swing cone while `swing` counts down to 0. const sweep = swing > 0 ? ((SWING_FRAMES - swing) / SWING_FRAMES) * 2 * SWING_HALF - SWING_HALF : -Math.PI / 2.5; const a = face + sweep; - visual.blade.position.copyFrom(toWorld(x + Math.cos(a) * 0.8, y + Math.sin(a) * 0.8, 1.0)); + visual.blade.position.copyFrom(at(x + Math.cos(a) * 0.8, y + Math.sin(a) * 0.8, 1.0)); visual.blade.rotation.y = -a; visual.blade.setEnabled(visible && !dead); visual.arc.setEnabled(visible && swing > 0); if (swing > 0) { - visual.arc.position.copyFrom(toWorld(x, y, 0.05)); + visual.arc.position.copyFrom(at(x, y, 0.05)); // Disc arcs start at +x and run counter-clockwise; centre it on `face`. visual.arc.rotation.y = -(face - SWING_HALF); } @@ -514,7 +660,7 @@ stage.onFrame((now, dtMs) => { stage.labels.set(entity.key, visual.body, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); visual.body.setEnabled(visible); visual.nose.setEnabled(visible && !dead); - if (mine) me = { x, y, hp: player.hp, dead }; + if (mine) me = { at: visual.body.position, hp: player.hp, dead }; } } for (const [key, visual] of visuals) { @@ -524,12 +670,13 @@ stage.onFrame((now, dtMs) => { visuals.delete(key); } for (const [key, p] of popups) { + p.mesh.position.copyFrom(placeIn(p.zone, p.x, p.y, 1.2)); if (now < p.until) continue; p.mesh.dispose(); stage.labels.delete(`popup:${key}`); popups.delete(key); } - if (me !== undefined) stage.follow(me.x, me.y, dtMs); + if (me !== undefined) stage.follow(me.at.x, me.at.z, dtMs); // ---- HUD ---- hud.frame({ entities: rendered.length }); @@ -554,7 +701,6 @@ stage.onFrame((now, dtMs) => { field('pending').textContent = String(pending); field('saved').textContent = String(savedCount); field('note').textContent = 'Kills settle in your Crawler cell next to the room on celld; the tick never waits for them.'; - const here = pit.room(); if (here !== undefined) showRoom(here); if (now - lastSampleAt > 250) { drawRooms(); @@ -571,6 +717,6 @@ declare global { mobpit?: unknown; } } -window.mobpit = { client, api, pitApi, pit, scene, rooms, boards }; +window.mobpit = { client, api, pitApi, pit, scene, rooms, boards, camera: stage.camera, origin: () => origin }; client.connect(zone).catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/tests/helpers/mobpit.mjs b/examples/game/client/tests/helpers/mobpit.mjs index 6acac3a99..2b73a521f 100644 --- a/examples/game/client/tests/helpers/mobpit.mjs +++ b/examples/game/client/tests/helpers/mobpit.mjs @@ -50,31 +50,49 @@ export async function startPit(demo = 'mobpit', vars = {}) { }; } -/** Walk to the doorway on side `[dx, dy]` and push through it until the - * client's authority is another room (one command frame per tick). */ +/** + * Walk to the doorway on side `[dx, dy]` and through it (one command frame + * per tick) until the client's authority is the next room and the own + * player is predicted there again. Returns the new room and the own world + * position sampled every frame on the way (`{ t, room, x, y }`). + */ export async function walkThroughDoor(pit, [dx, dy], timeoutMs = 30_000) { const { client } = pit; const from = pit.room(); const deadline = Date.now() + timeoutMs; - while (pit.room() === from) { + const trace = []; + const settled = () => pit.room() !== from && pit.me()?.predicted === true && pit.me()?.zoneId === pit.room(); + for (let after = 0; after < 10; after += settled() ? 1 : 0) { if (Date.now() > deadline) throw new Error(`walk through door ${dx},${dy} timed out`); - const rendered = client.render(); - const meEntity = rendered.find((e) => e.id === pit.hello()?.entity && isPlayer(e) && e.zoneId === from); - const me = meEntity && playerFields(meEntity); + const me = pit.me(); + const at = pit.position(); + if (at !== undefined) trace.push({ t: Date.now(), room: me.zoneId, predicted: me.predicted, ...at }); let input = { mx: 0, my: 0, buttons: 0 }; - if (me !== undefined) { - // Beside the pillar on the door's axis, then straight out. - const tx = dx !== 0 ? dx * 21 : 2; - const ty = dy !== 0 ? dy * 21 : 2; - const ddx = tx - me.x; - const ddy = ty - me.y; + if (at !== undefined) { + // Beside the pillar on the door's axis, through the gap, and on + // into the next room (world coordinates: the rooms are one world). + const [rx, ry] = from.split('.').slice(1).map(Number); + const size = 2 * 20; + const tx = rx * size + (dx !== 0 ? dx * 24 : 1.7); + const ty = ry * size + (dy !== 0 ? dy * 24 : 1.7); + const ddx = tx - at.x; + const ddy = ty - at.y; const len = Math.max(Math.hypot(ddx, ddy), 1e-3); input = { mx: Math.round((ddx / len) * 127), my: Math.round((ddy / len) * 127), buttons: 0 }; } client.sendInput(input); await sleep(1000 / 30); } - return pit.room(); + return { room: pit.room(), trace }; +} + +/** Largest move (m) between consecutive samples of a `walkThroughDoor` trace. */ +export function largestStep(trace) { + let max = 0; + for (let i = 1; i < trace.length; i += 1) { + max = Math.max(max, Math.hypot(trace[i].x - trace[i - 1].x, trace[i].y - trace[i - 1].y)); + } + return max; } /** Hunt mobs (one command frame per 30 Hz tick) until `done()` or timeout. */ diff --git a/examples/game/client/tests/mobpit-headless.test.mjs b/examples/game/client/tests/mobpit-headless.test.mjs index 711ac2eb6..7a343d1c6 100644 --- a/examples/game/client/tests/mobpit-headless.test.mjs +++ b/examples/game/client/tests/mobpit-headless.test.mjs @@ -5,7 +5,8 @@ * * join the entrance room → profile read from the celld Crawler cell → kill * a mob → the fact settles ("saved") with server-decided XP → walk through - * a doorway into the next room → the left room goes dormant, then + * a doorway into the next room, continuously (one world: the own world + * position never jumps across the handoff) → the left room goes dormant, then * hibernated (zone status read model) → walk back → the room wakes from its * snapshot with the mobs killed there still dead → restart the services: * the profile is still there. @@ -17,9 +18,23 @@ import { isMob, isPit, pitFields } from '../src/generated/mobpit/index.ts'; import { createMobPitClient, MobPitApi } from '../src/mobpit/client.ts'; import { DevApi } from '../src/shared/dev-api.ts'; import { eventually, memoryStorage, until } from './helpers/demo-server.mjs'; -import { hunt, startPit, walkThroughDoor } from './helpers/mobpit.mjs'; +import { hunt, largestStep, startPit, walkThroughDoor } from './helpers/mobpit.mjs'; const XP = new Set([10, 25, 60]); +/** One 30 Hz command frame of walking (5 m/s ≈ 0.167 m) plus float slack. */ +const STEP = 0.2; + +/** The own world position across a doorway: from room `a` into room `b`, never more than a step at once. */ +function assertContinuous(trace, a, b) { + const last = trace.findLast((s) => s.room === a); + const first = trace.find((s) => s.room === b && s.predicted); + assert.ok(last && first, `trace covers ${a} → ${b}`); + // Room-local positions would be a whole room (40 m) apart. + const across = Math.hypot(first.x - last.x, first.y - last.y); + console.error(`doorway ${a} → ${b}: ${across.toFixed(3)} m across, largest step ${largestStep(trace).toFixed(3)} m, ${trace.length} samples`); + assert.ok(across <= STEP, `${a} → ${b}: ${JSON.stringify(last)} → ${JSON.stringify(first)} (${across.toFixed(3)} m)`); + assert.ok(largestStep(trace) <= STEP, `largest step ${largestStep(trace).toFixed(3)} m`); +} test('rooms on celld: kills settle, doorways hand over, left rooms sleep and restore', { timeout: 600_000 }, async () => { const storage = memoryStorage(); @@ -58,9 +73,11 @@ test('rooms on celld: kills settle, doorways hand over, left rooms sleep and res await until(() => (pitStats()?.kills ?? 0) >= kills.length, 5_000, 'room kill count'); const roomKills = pitStats().kills; - // Through the east doorway: the room hands the player to pit.1.0. - const next = await walkThroughDoor(pit, [1, 0]); - assert.equal(next, 'pit.1.0'); + // Through the east doorway: the room hands the player to pit.1.0, + // at the same world point (no jump, no slide back across the room). + const east = await walkThroughDoor(pit, [1, 0]); + assert.equal(east.room, 'pit.1.0'); + assertContinuous(east.trace, 'pit.0.0', 'pit.1.0'); await until(() => pit.hello()?.roomX === 1, 10_000, 'hello of the next room'); // The left room empties: dormant, then hibernated. const status = async (zone) => (await pitApi.rooms()).rooms.find((r) => r.zone === zone)?.status; @@ -69,7 +86,9 @@ test('rooms on celld: kills settle, doorways hand over, left rooms sleep and res assert.equal(await status('pit.1.0'), 'active'); // Back west: the room wakes from its snapshot, the dead stay dead. - assert.equal(await walkThroughDoor(pit, [-1, 0]), 'pit.0.0'); + const west = await walkThroughDoor(pit, [-1, 0]); + assert.equal(west.room, 'pit.0.0'); + assertContinuous(west.trace, 'pit.1.0', 'pit.0.0'); await until(() => pit.hello()?.roomX === 0, 10_000, 'hello of the entrance again'); assert.equal(pit.hello().restored, true, 'restored from hibernation'); assert.equal(pit.hello().roomKills, roomKills); diff --git a/examples/game/server/rooms/src/zone.rs b/examples/game/server/rooms/src/zone.rs index ccf53a9fc..c566ca4c1 100644 --- a/examples/game/server/rooms/src/zone.rs +++ b/examples/game/server/rooms/src/zone.rs @@ -12,10 +12,13 @@ //! //! The room's mobs come from its seeded layout ([`pit_room`]: tiers and //! homes); the rest of a room is the Arena floor with a doorway in the -//! middle of each wall. Pushing through a doorway hands the player to the -//! neighbouring room ([`Ctx::handoff`], carrying where along the wall it -//! went through); the client follows the Handoff to the next room's zone, -//! wherever it runs. +//! middle of each wall. The rooms tile one continuous world (room `(x, y)` +//! at `(x, y) × ROOM_SIZE`): a doorway is a passage the predicted step walks +//! through, and a player [`HYSTERESIS`](game_sim::mobpit::HYSTERESIS) past +//! the wall line is handed to the neighbouring room ([`Ctx::handoff`], +//! carrying its [`MoveState`] in the neighbour's frame: the same world +//! point and velocity); the client follows the Handoff to the next room's +//! zone, wherever it runs, and draws it where it always was. //! //! Mob state machine (deterministic, zone RNG only for wander targets): //! `idle` (wander near home) → `chase` (living player within aggro radius or @@ -46,7 +49,8 @@ use distributed_game::{ }; use game_sim::arena::{self as movement, MoveState, PILLARS, PLAYER_RADIUS}; use game_sim::mobpit::{ - arrival, doorway, parse_room, pit_room, pit_world, room_zone, PitRoomContext, PitRoomFn, + self as rooms, admissible, crossing, into_neighbour, parse_room, pit_room, pit_world, + room_zone, PitRoomContext, PitRoomFn, }; use mobpit_crawler::{level_floor, KillReceipt, RecordKillInput}; use serde::{Deserialize, Serialize}; @@ -61,13 +65,13 @@ pub const PIT_ENTITY: EntityId = EntityId(900); #[derive(Debug, Clone, PartialEq, Replicated)] #[replicated(kind = "player", id = 1, priority = 2.0, of = Player)] pub struct PlayerView { - /// Position x. - #[field_type(movement::POS)] + /// Position x (room-local; past ±HALF in a doorway passage). + #[field_type(rooms::POS)] #[correct(ease = 150)] #[from(state.x)] pub x: f32, /// Position y. - #[field_type(movement::POS)] + #[field_type(rooms::POS)] #[correct(ease = 150)] #[from(state.y)] pub y: f32, @@ -454,8 +458,8 @@ struct Player { dead_until: Option, level: u32, regen: u8, - /// Stick of the last input (doorways need the push direction). - stick: (i8, i8), + /// Handed to a neighbouring room: no more steps here. + leaving: bool, } struct PendingKill { @@ -522,6 +526,15 @@ pub struct MobPit { tick: u64, } +fn spawn_state(player: PlayerId) -> MoveState { + let (x, y) = spawn_point(player); + MoveState { + x, + y, + ..MoveState::default() + } +} + fn spawn_point(player: PlayerId) -> (f32, f32) { const SPOTS: [(f32, f32); 6] = [ (-4.5, -4.5), @@ -565,22 +578,32 @@ fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() } -/// Carried through a doorway: the room offset it came from and where along -/// the wall it went through. -fn encode_carried(from: (i32, i32), along: f32) -> Vec { - let mut out = vec![from.0 as i8 as u8, from.1 as i8 as u8]; - out.extend_from_slice(&along.to_le_bytes()); +/// Carried through a doorway: the player's [`MoveState`] in the +/// neighbour's frame (x y vx vy as f32 LE, dash, cd). +fn encode_carried(s: &MoveState) -> Vec { + let mut out = Vec::with_capacity(18); + for v in [s.x, s.y, s.vx, s.vy] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&[s.dash, s.cd]); out } -fn decode_carried(bytes: &[u8]) -> Option<((i32, i32), f32)> { - let [dx, dy, a, b, c, d] = bytes else { +/// Inverse of [`encode_carried`]; None unless it is a place a player can be. +fn decode_carried(bytes: &[u8]) -> Option { + if bytes.len() != 18 { return None; + } + let f = |i: usize| f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("4 bytes")); + let state = MoveState { + x: f(0), + y: f(1), + vx: f(2), + vy: f(3), + dash: bytes[16], + cd: bytes[17], }; - Some(( - (i32::from(*dx as i8), i32::from(*dy as i8)), - f32::from_le_bytes([*a, *b, *c, *d]), - )) + admissible(&state).then(|| rooms::canonicalize(state)) } impl MobPit { @@ -692,6 +715,9 @@ impl MobPit { } continue; } + if p.leaving { + continue; + } while p.credits > 0 { let Some(input) = ctx.take_inputs(*id, ConsumePolicy::Next).pop() else { break; @@ -700,7 +726,6 @@ impl MobPit { // The declared predicted step: what the client runs as WASM. p.state = pit_step(&p.state, &input, &(), movement::DT); p.credits -= 1; - p.stick = (input.mx, input.my); let (sx, sy) = (f32::from(input.mx), f32::from(input.my)); if sx * sx + sy * sy > 20.0 * 20.0 { p.face = sy.atan2(sx); @@ -710,6 +735,10 @@ impl MobPit { p.swing_anim = SWING_FRAMES; swings.push((*id, p.state.x, p.state.y, p.face)); } + // Past a wall line: the neighbour takes the rest. + if crossing(p.state.x, p.state.y).is_some() { + break; + } } p.regen = p.regen.wrapping_add(1); if p.regen % 15 == 0 && p.hp < PLAYER_HP { @@ -720,27 +749,30 @@ impl MobPit { swings } - /// Players pushing through a doorway move to the neighbouring room. + /// Players past a wall line (through a doorway passage) move to the + /// neighbouring room, at the same world point. fn walk_through_doorways(&mut self, ctx: &mut Ctx<'_, Self>) { let (rx, ry) = self.room.room; - let leaving: Vec<(PlayerId, (i32, i32), f32)> = self + let crossing_now: Vec<(PlayerId, (i32, i32))> = self .players .iter() - .filter(|(_, p)| p.dead_until.is_none()) - .filter_map(|(id, p)| { - let step = doorway(p.state.x, p.state.y, p.stick.0, p.stick.1)?; - let along = if step.0 != 0 { p.state.y } else { p.state.x }; - Some((*id, step, along)) - }) + .filter(|(_, p)| p.dead_until.is_none() && !p.leaving) + .filter_map(|(id, p)| Some((*id, crossing(p.state.x, p.state.y)?))) .collect(); - for (player, (dx, dy), along) in leaving { + for (player, (dx, dy)) in crossing_now { let target = room_zone((rx + dx, ry + dy)); - if parse_room(&target).is_none() { - continue; + let p = self.players.get_mut(&player).expect("player"); + let carried = encode_carried(&into_neighbour((dx, dy), p.state)); + if parse_room(&target).is_some() && ctx.handoff(player, &target, carried).is_ok() { + p.leaving = true; + } else { + // The edge of the world: back inside the wall line. + let line = movement::HALF - PLAYER_RADIUS; + p.state.x = p.state.x.clamp(-line, line); + p.state.y = p.state.y.clamp(-line, line); + p.state.vx = 0.0; + p.state.vy = 0.0; } - // The neighbour sees where it came from (the opposite side). - let carried = encode_carried((-dx, -dy), along); - let _ = ctx.handoff(player, &target, carried); } } @@ -943,7 +975,7 @@ impl MobPit { } /// Admit `player` at `(x, y)` and greet it. - fn admit(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId, (x, y): (f32, f32)) { + fn admit(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId, state: MoveState) { let (principal, name) = ctx .player(player) .map(|p| { @@ -960,11 +992,7 @@ impl MobPit { id: entity, principal, name, - state: MoveState { - x, - y, - ..MoveState::default() - }, + state, credits: MAX_CREDITS, hp: PLAYER_HP, face: 0.0, @@ -973,10 +1001,10 @@ impl MobPit { dead_until: None, level: 1, regen: 0, - stick: (0, 0), + leaving: false, }, ); - ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); + ctx.set_view(player, View::new(state.x, state.y, VIEW_RADIUS)); ctx.send( player, &PitEvent::Hello { @@ -1061,7 +1089,7 @@ impl Zone for MobPit { } fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { - self.admit(ctx, player, spawn_point(player)); + self.admit(ctx, player, spawn_state(player)); } fn on_handoff_join( @@ -1071,9 +1099,7 @@ impl Zone for MobPit { _from_zone: &str, carried: Vec, ) { - let at = decode_carried(&carried) - .map(|(from, along)| arrival(from, along)) - .unwrap_or_else(|| spawn_point(player)); + let at = decode_carried(&carried).unwrap_or_else(|| spawn_state(player)); // Still here inside its reconnect grace (a doorway bounce): replace. self.players.remove(&player); self.admit(ctx, player, at); diff --git a/examples/game/server/rooms/tests/rooms.rs b/examples/game/server/rooms/tests/rooms.rs index 474fdf450..9ade8a84a 100644 --- a/examples/game/server/rooms/tests/rooms.rs +++ b/examples/game/server/rooms/tests/rooms.rs @@ -1,17 +1,23 @@ //! The room zone on the reference host (`ZoneHost`, manual clock): what a //! celld room object runs, without celld. -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use distributed_game::protocol::ServerMessage; use distributed_game::{ - ClientId, FactQueue, GameEvent, HostConfig, ManualClock, Outbound, Role, TicketClaims, Viewer, - ZoneHost, + ClientId, FactQueue, GameEvent, HandoffRequest, HostConfig, ManualClock, Outbound, Role, + TicketClaims, Transfer, Viewer, ZoneHost, }; use mobpit_rooms::{encode_bot_input, MobPit, PitEvent, PitInput, RoomConfig, DEFAULT_SEED}; +type Issued = Arc>>; + fn host(zone: &str, clock: &ManualClock) -> ZoneHost { + host_issuing(zone, clock, Issued::default()) +} + +fn host_issuing(zone: &str, clock: &ManualClock, issued: Issued) -> ZoneHost { let (facts, _script) = FactQueue::scripted(64); ZoneHost::::new( zone, @@ -23,7 +29,10 @@ fn host(zone: &str, clock: &ManualClock) -> ZoneHost { RoomConfig::for_zone(zone, DEFAULT_SEED).expect("room"), ) .with_facts(facts) - .with_transfer_issuer(|request| Some(format!("transfer:{}", request.target_zone))) + .with_transfer_issuer(move |request| { + *issued.lock().expect("issued") = Some(request.clone()); + Some(format!("transfer:{}", request.target_zone)) + }) } fn join(host: &mut ZoneHost, who: &str) -> (ClientId, distributed_game::PlayerId) { @@ -66,7 +75,8 @@ fn hellos(out: &[Outbound]) -> Vec { #[test] fn a_room_greets_with_its_coordinates_and_hands_off_through_doorways() { let clock = ManualClock::new(); - let mut room = host("pit.0.0", &clock); + let issued = Issued::default(); + let mut room = host_issuing("pit.0.0", &clock, issued.clone()); let (client, player) = join(&mut room, "ana"); let out = tick(&mut room, &clock); let hello = hellos(&out); @@ -82,8 +92,10 @@ fn a_room_greets_with_its_coordinates_and_hands_off_through_doorways() { // Walk to the east doorway (beside the pillar on its axis) and push // through it, no attack, until the room hands the player over. let mut target = None; + let mut last = (0.0, 0.0); for seq in 1..600u32 { let me = room.zone().player_position(player).expect("in the room"); + last = me; let (dx, dy) = (21.0 - me.0, 2.0 - me.1); let len = (dx * dx + dy * dy).sqrt().max(1e-3); let east = PitInput { @@ -113,6 +125,41 @@ fn a_room_greets_with_its_coordinates_and_hands_off_through_doorways() { assert_eq!(target, "pit.1.0"); assert_eq!(ticket, "transfer:pit.1.0"); assert!(room.zone().player_position(player).is_none(), "left"); + // Through the passage, past the wall line (x = 20) by the hysteresis. + assert!(last.0 > 19.5 && last.1.abs() < 2.5, "{last:?}"); + + // The neighbour admits the player at the same world point: room 1's + // local x is 40 m less (one step further at most). + let request = issued + .lock() + .expect("issued") + .take() + .expect("handoff request"); + let mut next = host("pit.1.0", &clock); + let claims = TicketClaims::new("ana", "pit.1.0", u64::MAX, "t2", Role::Player).with_name("ana"); + let transfer = Transfer { + claims, + source_zone: "pit.0.0".into(), + issuer: "test".into(), + generation: 0, + carried: request.carried, + departed_at_ms: 0, + }; + let joined = next.join_transfer(&transfer, 0, "").expect("transfer join"); + let Viewer::Player(arrived) = joined.viewer else { + panic!("player") + }; + let at = next.zone().player_position(arrived).expect("arrived"); + let world_before = (last.0, last.1); + let world_after = (40.0 + at.0, at.1); + let moved = ((world_after.0 - world_before.0).powi(2) + + (world_after.1 - world_before.1).powi(2)) + .sqrt(); + assert!( + moved < 0.5, + "same world point: {world_before:?} → {world_after:?}" + ); + assert!(at.0 < -19.0, "just inside the west wall of pit.1.0: {at:?}"); } #[test] diff --git a/examples/game/server/sim/src/arena.rs b/examples/game/server/sim/src/arena.rs index 5c11dd20f..aafd269a5 100644 --- a/examples/game/server/sim/src/arena.rs +++ b/examples/game/server/sim/src/arena.rs @@ -140,6 +140,13 @@ pub fn arena_step(state: &MoveState, input: &MoveInput, _context: &(), _dt: f32) /// Advance one command frame. pub fn step(s: MoveState, input: MoveInput) -> MoveState { + canonicalize(clamp_walls(advance(s, input))) +} + +/// One command frame of stick, dash and pillars, without the walls and +/// unsnapped: the part of [`step`] Mob Pit shares (its rooms have doorways +/// in the walls, see `mobpit::pit_step`). +pub fn advance(s: MoveState, input: MoveInput) -> MoveState { let mut s = s; // Stick direction, length clamped to 1. let mut dx = f32::from(input.mx) / 127.0; @@ -213,7 +220,12 @@ pub fn step(s: MoveState, input: MoveInput) -> MoveState { } } } + s +} +/// The Arena's closed walls. +fn clamp_walls(s: MoveState) -> MoveState { + let mut s = s; let lim = HALF - PLAYER_RADIUS; if s.x < -lim { s.x = -lim; @@ -229,10 +241,11 @@ pub fn step(s: MoveState, input: MoveInput) -> MoveState { s.y = lim; s.vy = s.vy.min(0.0); } - canonicalize(s) + s } -fn snap(ty: FieldType, v: f32) -> f32 { +/// Snap `v` to the precision of wire type `ty`. +pub fn snap(ty: FieldType, v: f32) -> f32 { match ty { FieldType::QuantF32 { min, max, bits } => FieldType::dequantize_linear( FieldType::quantize_linear(v, min, max, bits), diff --git a/examples/game/server/sim/src/mobpit.rs b/examples/game/server/sim/src/mobpit.rs index 9d4b3033c..a1fa45964 100644 --- a/examples/game/server/sim/src/mobpit.rs +++ b/examples/game/server/sim/src/mobpit.rs @@ -3,14 +3,23 @@ //! //! **Rooms.** Mob Pit is a near-infinite grid of rooms, room `(x, y)` being //! zone `pit..` (canonical integers, |x|, |y| ≤ [`MAX_ROOM`]). Every -//! room is the Arena floor (same pillars, so the predicted step is the -//! Arena's) with a doorway in the middle of each wall leading to the -//! neighbour. What lives in a room — its biome, danger level and mobs — is +//! room is the Arena floor (same pillars) with a doorway in the middle of +//! each wall leading to the neighbour. +//! +//! **One continuous world.** Room `(x, y)` sits at world `(x, y) ×` +//! [`ROOM_SIZE`]; neighbours share a wall. Positions on the wire are +//! room-local (centred), so world = room × [`ROOM_SIZE`] + local. A doorway +//! is a passage: [`pit_step`] lets the player walk through the gap past the +//! wall line (up to [`PASSAGE`] m); once it is [`HYSTERESIS`] m past the +//! line ([`crossing`]) the room hands it to the neighbour, which admits it +//! at the same world point with the same velocity ([`into_neighbour`]), so +//! nothing jumps and the client's prediction carries on (the Endless Grid's +//! model). What lives in a room — its biome, danger level and mobs — is //! a pure function of `(seed, x, y)` ([`pit_room`], `#[game_pure]`) built on //! the Endless Grid's seeded hashing and biomes ([`crate::grid`]); the page //! runs the same code compiled to WebAssembly (minimap colours, floor). -use distributed_game::{game_pure, predict, GameInput, GameRecord}; +use distributed_game::{game_pure, predict, FieldType, GameInput, GameRecord}; use crate::arena::{self, MoveInput, MoveState}; use crate::grid; @@ -47,10 +56,76 @@ impl PitInput { } /// The own capsule's predicted step: the Arena's movement of -/// [`PitInput::movement`]. +/// [`PitInput::movement`] inside walls with doorway passages. #[predict(PitStep, kind = "player")] pub fn pit_step(state: &MoveState, input: &PitInput, _context: &(), _dt: f32) -> MoveState { - arena::step(*state, input.movement()) + step(*state, *input) +} + +/// Room edge length (m): rooms tile the world, sharing walls. +pub const ROOM_SIZE: f32 = 2.0 * arena::HALF; +/// How far past the wall line a doorway passage reaches (m). +pub const PASSAGE: f32 = 2.0; +/// Handoff hysteresis (m): a player belongs to the neighbour once it is +/// this far past the wall line, and so arrives this far inside it. +pub const HYSTERESIS: f32 = 0.5; +/// Tolerance of the wall tests (m), far above the wire precision. +const SLACK: f32 = 0.01; +/// Wire type of player `x`/`y`: the room plus its passages, ≈ 0.17 mm steps. +pub const POS: FieldType = FieldType::quant_centered(22.0, 18); + +/// One command frame: [`arena::advance`] (stick, dash, pillars), then the +/// walls with their doorway passages, snapped to the wire precision. +pub fn step(s: MoveState, input: PitInput) -> MoveState { + let next = arena::advance(s, input.movement()); + canonicalize(walls(s, next)) +} + +/// Snap to the replicated precision of a Mob Pit player. +pub fn canonicalize(s: MoveState) -> MoveState { + MoveState { + x: arena::snap(POS, s.x), + y: arena::snap(POS, s.y), + vx: arena::snap(arena::VEL, s.vx), + vy: arena::snap(arena::VEL, s.vy), + ..s + } +} + +/// Clamp a coordinate to `±lim`, stopping the velocity into the wall. +fn clamp_axis(p: f32, v: f32, lim: f32) -> (f32, f32) { + if p > lim { + (lim, v.min(0.0)) + } else if p < -lim { + (-lim, v.max(0.0)) + } else { + (p, v) + } +} + +/// Keep `s` (one frame after `prev`) inside the room square or a doorway +/// passage. A player already in a passage stays between its jambs; one in +/// the room may enter a passage only through the gap. +fn walls(prev: MoveState, s: MoveState) -> MoveState { + let lim = arena::HALF - arena::PLAYER_RADIUS; + // Snapped to the wire, a player held at the wall may sit a hair past it. + let inside = lim + SLACK; + let gap = DOOR_HALF - arena::PLAYER_RADIUS; + let far = arena::HALF + PASSAGE; + let mut s = s; + let (lim_x, lim_y) = if prev.x.abs() > inside { + (far, gap) + } else if prev.y.abs() > inside { + (gap, far) + } else { + ( + if s.y.abs() <= gap { far } else { lim }, + if s.x.abs() <= gap { far } else { lim }, + ) + }; + (s.x, s.vx) = clamp_axis(s.x, s.vx, lim_x); + (s.y, s.vy) = clamp_axis(s.y, s.vy, lim_y); + s } /// Largest |room coordinate|. @@ -172,6 +247,12 @@ pub struct PitWorld { pub half: f32, /// Doorway half width (m). pub door_half: f32, + /// Room edge length (m): room `(x, y)` is centred at world `(x, y) × room_size`. + pub room_size: f32, + /// Doorway passage depth past the wall line (m). + pub passage: f32, + /// Handoff hysteresis past the wall line (m). + pub hysteresis: f32, /// Largest |room coordinate|. pub max_room: i32, /// Biome names by index. @@ -184,6 +265,9 @@ pub fn pit_world() -> PitWorld { default_seed: DEFAULT_SEED, half: arena::HALF, door_half: DOOR_HALF, + room_size: ROOM_SIZE, + passage: PASSAGE, + hysteresis: HYSTERESIS, max_room: MAX_ROOM, biomes: grid::BIOMES.map(String::from).to_vec(), } @@ -205,42 +289,45 @@ pub fn parse_room(zone_id: &str) -> Option<(i32, i32)> { Some((parse(x)?, parse(y)?)) } -/// The doorway a player at `(x, y)` pushing with stick `(mx, my)` walks -/// through, as a room offset: against the wall, inside the doorway span, -/// pushing outward. -pub fn doorway(x: f32, y: f32, mx: i8, my: i8) -> Option<(i32, i32)> { - let edge = arena::HALF - arena::PLAYER_RADIUS - 0.05; - if y.abs() < DOOR_HALF { - if x >= edge && mx > 30 { - return Some((1, 0)); - } - if x <= -edge && mx < -30 { - return Some((-1, 0)); - } - } - if x.abs() < DOOR_HALF { - if y >= edge && my > 30 { - return Some((0, 1)); - } - if y <= -edge && my < -30 { - return Some((0, -1)); - } +/// The neighbour a player at room-local `(x, y)` belongs to, as a room +/// offset: [`HYSTERESIS`] past a wall line (only reachable through a +/// doorway passage). +pub fn crossing(x: f32, y: f32) -> Option<(i32, i32)> { + let line = arena::HALF + HYSTERESIS; + if x > line { + Some((1, 0)) + } else if x < -line { + Some((-1, 0)) + } else if y > line { + Some((0, 1)) + } else if y < -line { + Some((0, -1)) + } else { + None } - None } -/// Where a player arrives through the doorway it came in by (`from` is the -/// offset of the room it left, e.g. `(-1, 0)` = came from the west), -/// keeping its position along the wall. -pub fn arrival(from: (i32, i32), along: f32) -> (f32, f32) { - let inside = arena::HALF - 2.0; - let along = along.clamp(-(DOOR_HALF - 0.6), DOOR_HALF - 0.6); - match from { - (-1, 0) => (-inside, along), - (1, 0) => (inside, along), - (0, -1) => (along, -inside), - _ => (along, inside), - } +/// The same player in the frame of the neighbour at room offset `step`: +/// the same world point and velocity (world = room × [`ROOM_SIZE`] + local). +pub fn into_neighbour(step: (i32, i32), s: MoveState) -> MoveState { + canonicalize(MoveState { + x: s.x - step.0 as f32 * ROOM_SIZE, + y: s.y - step.1 as f32 * ROOM_SIZE, + ..s + }) +} + +/// Whether `s` is a position a player can be in (the room or a passage). +pub fn admissible(s: &MoveState) -> bool { + let lim = arena::HALF - arena::PLAYER_RADIUS + SLACK; + let gap = DOOR_HALF - arena::PLAYER_RADIUS + SLACK; + let far = arena::HALF + PASSAGE + SLACK; + let (ax, ay) = (s.x.abs(), s.y.abs()); + s.x.is_finite() + && s.y.is_finite() + && s.vx.is_finite() + && s.vy.is_finite() + && ((ax <= lim && ay <= lim) || (ay <= gap && ax <= far) || (ax <= gap && ay <= far)) } #[cfg(test)] @@ -272,12 +359,72 @@ mod tests { assert_eq!(parse_room("pit.01.2"), None); assert_eq!(parse_room("pit-1"), None); assert_eq!(parse_room("pit.2000000.0"), None); - let edge = arena::HALF - arena::PLAYER_RADIUS; - assert_eq!(doorway(edge, 0.5, 127, 0), Some((1, 0))); - assert_eq!(doorway(edge, 0.5, -127, 0), None, "pushing back in"); - assert_eq!(doorway(edge, 5.0, 127, 0), None, "wall, not doorway"); - assert_eq!(doorway(0.0, -edge, 0, -127), Some((0, -1))); - assert_eq!(arrival((-1, 0), 9.0).0, -(arena::HALF - 2.0)); - assert!(arrival((-1, 0), 9.0).1 < DOOR_HALF); + } + + fn walk(mut s: MoveState, mx: i8, my: i8, frames: usize) -> MoveState { + for _ in 0..frames { + s = step(s, PitInput { mx, my, buttons: 0 }); + } + s + } + + #[test] + fn doorways_are_passages_and_walls_hold() { + let lim = arena::HALF - arena::PLAYER_RADIUS; + // Along the east door axis (y = 0.5): through the gap past the wall + // line, up to the passage's end. + let at = |x, y| MoveState { + x, + y, + ..MoveState::default() + }; + let s = walk(at(17.0, 0.5), 127, 0, 60); + assert!((s.x - (arena::HALF + PASSAGE)).abs() < 1e-3, "{s:?}"); + assert_eq!(crossing(s.x, s.y), Some((1, 0))); + // Beside the doorway the wall holds. + let s = walk(at(17.0, 6.0), 127, 0, 60); + assert!((s.x - lim).abs() < 1e-3, "{s:?}"); + assert_eq!(crossing(s.x, s.y), None); + // In the passage the jambs hold the player in the gap. + let s = walk(at(20.4, 0.0), 0, 127, 60); + assert!(s.y <= DOOR_HALF - arena::PLAYER_RADIUS + 1e-3, "{s:?}"); + assert!(admissible(&s)); + // Corners never open. + let s = walk(at(18.0, 18.0), 127, 127, 90); + assert!(s.x <= lim + 1e-3 && s.y <= lim + 1e-3, "{s:?}"); + } + + #[test] + fn crossing_keeps_the_world_point() { + let s = canonicalize(MoveState { + x: arena::HALF + HYSTERESIS + 0.1, + y: 1.25, + vx: 5.0, + ..MoveState::default() + }); + let step = crossing(s.x, s.y).expect("past the line"); + let n = into_neighbour(step, s); + // World x: room 0 + s.x == room 1 + n.x. + assert!((n.x + ROOM_SIZE - s.x).abs() < 1e-3, "{n:?}"); + assert_eq!((n.y, n.vx), (s.y, s.vx)); + assert!(admissible(&n)); + assert_eq!(crossing(n.x, n.y), None, "hysteresis: no bounce back"); + // West / south mirror. + let w = into_neighbour((-1, 0), MoveState { x: -21.0, ..s }); + assert!((w.x - 19.0).abs() < 1e-3, "{w:?}"); + let south = into_neighbour( + (0, -1), + MoveState { + x: 0.0, + y: -21.0, + ..s + }, + ); + assert!((south.y - 19.0).abs() < 1e-3, "{south:?}"); + assert!(!admissible(&MoveState { + x: 21.0, + y: 5.0, + ..s + })); } } diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts index e01248b13..2b523df3e 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/constants.ts @@ -21,6 +21,9 @@ export const PIT_WORLD: PitWorld = { defaultSeed: 186474221, half: 20, doorHalf: 2.5, + roomSize: 40, + passage: 2, + hysteresis: 0.5, maxRoom: 1000000, biomes: ['highlands', 'steppe', 'forest', 'meadow'] }; diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts index a3f5878ba..b98152277 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/events.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/events.ts @@ -55,6 +55,9 @@ export interface PitWorld { readonly defaultSeed: number; readonly half: number; readonly doorHalf: number; + readonly roomSize: number; + readonly passage: number; + readonly hysteresis: number; readonly maxRoom: number; readonly biomes: readonly string[]; } diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts index 8019b0b3f..cf619af1f 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts +++ b/examples/game/sveltekit/src/lib/generated/mobpit/schema.ts @@ -15,9 +15,9 @@ export type KindName = keyof typeof KIND; /** `player` (kind 1, priority 2). */ export interface PlayerFields { - /** `quant [-20, 19.999847] / 18 bits` */ + /** `quant [-22, 21.999832] / 18 bits` */ readonly x: number; - /** `quant [-20, 19.999847] / 18 bits` */ + /** `quant [-22, 21.999832] / 18 bits` */ readonly y: number; /** `quant [-16, 15.9921875] / 12 bits` */ readonly vx: number; @@ -164,8 +164,8 @@ export function pitFields(entity: { readonly fields: EntityFields }): PitFields /** Wire type of every replicated field, by kind and wire field name. */ export const FIELD_TYPES = { player: { - x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, - y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + x: { type: 'quant', min: -22, max: 21.999832153320313, bits: 18 }, + y: { type: 'quant', min: -22, max: 21.999832153320313, bits: 18 }, vx: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, vy: { type: 'quant', min: -16, max: 15.9921875, bits: 12 }, dash: { type: 'u8' }, diff --git a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json index 6c0a39c71..4299b39e5 100644 --- a/examples/game/sveltekit/src/lib/generated/mobpit/surface.json +++ b/examples/game/sveltekit/src/lib/generated/mobpit/surface.json @@ -53,7 +53,10 @@ "default_seed": 186474221, "door_half": 2.5, "half": 20.0, - "max_room": 1000000 + "hysteresis": 0.5, + "max_room": 1000000, + "passage": 2.0, + "room_size": 40.0 } } ], @@ -330,8 +333,8 @@ "priority": 1.0, "type": { "bits": 18, - "max": 19.999847, - "min": -20.0, + "max": 21.999832, + "min": -22.0, "type": "quant" } }, @@ -344,8 +347,8 @@ "priority": 1.0, "type": { "bits": 18, - "max": 19.999847, - "min": -20.0, + "max": 21.999832, + "min": -22.0, "type": "quant" } }, @@ -854,6 +857,24 @@ "type": "f32" } }, + { + "name": "room_size", + "type": { + "type": "f32" + } + }, + { + "name": "passage", + "type": { + "type": "f32" + } + }, + { + "name": "hysteresis", + "type": { + "type": "f32" + } + }, { "name": "max_room", "type": { diff --git a/examples/game/sveltekit/src/lib/pit/loop.ts b/examples/game/sveltekit/src/lib/pit/loop.ts index f6c751541..ae93a998a 100644 --- a/examples/game/sveltekit/src/lib/pit/loop.ts +++ b/examples/game/sveltekit/src/lib/pit/loop.ts @@ -3,11 +3,18 @@ * `requestAnimationFrame`, outside Svelte. It reads `client.render()` every * frame and sends one input per server tick; the Svelte page only starts it * and reads the slower facts (status, RTT, events) through `useGame`. + * + * One continuous world: room `(x, y)` sits at world `(x, y) × ROOM`, the + * view follows the own player's world position, and the rooms around are + * drawn from their seeded layout, so walking through a doorway just + * continues into the next room (the room hands the player over at the same + * world point). */ -import { InputPacer, type GameClient } from '@hops-ops/distributed/game'; +import { InputPacer, type EntityFields, type GameClient, type RenderedEntity } from '@hops-ops/distributed/game'; import { BUTTON, + createMobpitPures, PIT_RULES, PIT_WORLD, isMob, @@ -24,6 +31,39 @@ const TIER_COLOR: Record = { 1: '#9ad16b', 2: '#b48cf2', 3: '#ff const TIER_RADIUS = Object.fromEntries(PIT_RULES.tiers.map((t) => [t.tier, t])); const PLAYER_RADIUS = 0.45; const DOOR_HALF = PIT_WORLD.doorHalf; +const HALF = PIT_WORLD.half; +/** Room edge (m): room `(x, y)` is centred at world `(x, y) × ROOM`, one continuous world. */ +const ROOM = PIT_WORLD.roomSize; +/** Metres across the canvas: your room and a strip of each neighbour. */ +const VIEW = 2 * HALF + 12; +/** Floor tint per biome (`PIT_WORLD.biomes`). */ +const BIOME_COLOR = ['#8a8f99', '#c9a86a', '#3f7d4e', '#7fbf6a']; + +/** `pit..` → `[x, y]`. */ +function parseRoom(zone: string | undefined): [number, number] | undefined { + const m = zone === undefined ? null : /^pit\.(-?\d+)\.(-?\d+)$/.exec(zone); + return m === null ? undefined : [Number(m[1]), Number(m[2])]; +} + +/** + * The own player's predicted fields in the next room's frame (the same world + * point): the SDK keeps predicting through a doorway handoff (`handoffFrame`). + */ +export function pitHandoffFrame(fields: EntityFields, from: string, to: string): EntityFields | undefined { + const a = parseRoom(from); + const b = parseRoom(to); + const { x, y } = fields as { x?: unknown; y?: unknown }; + if (a === undefined || b === undefined || typeof x !== 'number' || typeof y !== 'number') return undefined; + return { ...fields, x: x + (a[0] - b[0]) * ROOM, y: y + (a[1] - b[1]) * ROOM }; +} + +/** World position (m) of an entity: its room's place plus its room-local x / y. */ +function worldOf(entity: RenderedEntity): { x: number; y: number } | undefined { + const room = parseRoom(entity.zoneId); + const { x, y } = entity.fields as { x?: unknown; y?: unknown }; + if (room === undefined || typeof x !== 'number' || typeof y !== 'number') return undefined; + return { x: room[0] * ROOM + x, y: room[1] * ROOM + y }; +} /** Swing cone, from the server's rules (reach to a mob's edge, plus the body). */ const SWING_REACH = PIT_RULES.attackRange + PLAYER_RADIUS; const SWING_HALF = PIT_RULES.attackHalfAngle; @@ -79,16 +119,41 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) }; }; + // The rooms around are drawn from their seeded layout (`pit_room`, the + // Rust generator as WASM): biome floor, walls, doorways, pillars. + const pures = createMobpitPures(); + /** Pillars are the same in every room: learned from the replicated ones. */ + let pillars: { x: number; y: number; r: number }[] = []; + let lastMe: { x: number; y: number } | undefined; + let lastFrame = 0; + let frame = requestAnimationFrame(function draw(now) { pacer.update(now, () => client.sendInput(steer())); - const half = options.hello()?.half ?? 12; - // Only the room the player is in (during a doorway handoff the - // client briefly holds both). + const hello = options.hello(); const room = client.authority?.zoneId; if (room !== undefined) canvas.dataset.room = room; + const here = parseRoom(room); + const rendered = client.render(); + // Yours: predicted, or the SDK's hold of it during a doorway handoff. + const mine = (e: RenderedEntity) => isPlayer(e) && (e.predicted || (e.id === hello?.entity && e.zoneId === room)); + const meEntity = rendered.find((e) => mine(e) && e.predicted) ?? rendered.find(mine); + const me = meEntity === undefined ? undefined : worldOf(meEntity); + // The view follows you through one continuous world. + const centre = me ?? (here === undefined ? { x: 0, y: 0 } : { x: here[0] * ROOM, y: here[1] * ROOM }); + if (me !== undefined) { + canvas.dataset.world = `${me.x.toFixed(3)},${me.y.toFixed(3)}`; + // Largest frame-to-frame move of the view (m), frames ≤ 50 ms + // apart; the headless test resets it to 0 before a doorway. + if (lastMe !== undefined && now - lastFrame <= 50) { + const jump = Math.hypot(me.x - lastMe.x, me.y - lastMe.y); + if (jump > Number(canvas.dataset.jump ?? 0)) canvas.dataset.jump = jump.toFixed(3); + } + lastMe = me; + } + lastFrame = now; const { width, height } = canvas; - const scale = Math.min(width, height) / (2 * half); - const at = (x: number, y: number): [number, number] => [width / 2 + x * scale, height / 2 - y * scale]; + const scale = Math.min(width, height) / VIEW; + const at = (x: number, y: number): [number, number] => [width / 2 + (x - centre.x) * scale, height / 2 - (y - centre.y) * scale]; const circle = (x: number, y: number, r: number, fill: string, stroke?: string) => { const [cx, cy] = at(x, y); ctx.beginPath(); @@ -100,48 +165,74 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) ctx.stroke(); } }; - ctx.fillStyle = '#120f14'; - ctx.fillRect(0, 0, width, height); - ctx.strokeStyle = '#2b2533'; - ctx.strokeRect(...at(-half, half), 2 * half * scale, 2 * half * scale); - // Doorways: the middle of each wall leads to the neighbouring room. - ctx.strokeStyle = '#4dd0e1'; - ctx.lineWidth = 4; - for (const [x0, y0, x1, y1] of [ - [half, -DOOR_HALF, half, DOOR_HALF], - [-half, -DOOR_HALF, -half, DOOR_HALF], - [-DOOR_HALF, half, DOOR_HALF, half], - [-DOOR_HALF, -half, DOOR_HALF, -half] - ]) { + const line = (x0: number, y0: number, x1: number, y1: number) => { ctx.beginPath(); - ctx.moveTo(...at(x0!, y0!)); - ctx.lineTo(...at(x1!, y1!)); + ctx.moveTo(...at(x0, y0)); + ctx.lineTo(...at(x1, y1)); ctx.stroke(); + }; + ctx.fillStyle = '#0b090d'; + ctx.fillRect(0, 0, width, height); + const seed = hello?.seed ?? PIT_WORLD.defaultSeed; + const [cx, cy] = [Math.round(centre.x / ROOM), Math.round(centre.y / ROOM)]; + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) { + const [rx, ry] = [cx + dx, cy + dy]; + const [ox, oy] = [rx * ROOM, ry * ROOM]; + const biome = pures.loaded() ? pures.pitRoom({ seed, x: rx, y: ry }).biome : undefined; + ctx.fillStyle = biome === undefined ? '#120f14' : `${BIOME_COLOR[biome] ?? '#333333'}30`; + ctx.fillRect(...at(ox - HALF, oy + HALF), 2 * HALF * scale, 2 * HALF * scale); + for (const p of pillars) circle(ox + p.x, oy + p.y, p.r, '#3a3443'); + // Walls with a doorway gap in the middle of each. + ctx.strokeStyle = '#4b5668'; + ctx.lineWidth = 3; + for (const s of [-1, 1]) { + line(ox - HALF, oy + s * HALF, ox - DOOR_HALF, oy + s * HALF); + line(ox + DOOR_HALF, oy + s * HALF, ox + HALF, oy + s * HALF); + line(ox + s * HALF, oy - HALF, ox + s * HALF, oy - DOOR_HALF); + line(ox + s * HALF, oy + DOOR_HALF, ox + s * HALF, oy + HALF); + } + ctx.strokeStyle = 'rgba(77,208,225,0.5)'; + ctx.lineWidth = 2; + for (const s of [-1, 1]) { + line(ox - DOOR_HALF, oy + s * HALF, ox + DOOR_HALF, oy + s * HALF); + line(ox + s * HALF, oy - DOOR_HALF, ox + s * HALF, oy + DOOR_HALF); + } + if (rx === here?.[0] && ry === here?.[1]) { + ctx.strokeStyle = 'rgba(255,255,255,0.25)'; + ctx.lineWidth = 1; + ctx.strokeRect(...at(ox - HALF, oy + HALF), 2 * HALF * scale, 2 * HALF * scale); + } + } } ctx.lineWidth = 1; - for (const entity of client.render()) { - if (room !== undefined && entity.zoneId !== room) continue; + for (const entity of rendered) { + const w = worldOf(entity); + if (w === undefined) continue; if (isPillar(entity)) { const p = pillarFields(entity); - circle(p.x, p.y, p.r, '#3a3443'); + if (!pillars.some((q) => q.x === p.x && q.y === p.y)) pillars = [...pillars, { x: p.x, y: p.y, r: p.r }]; } else if (isMob(entity)) { + if (entity.stale) continue; const m = mobFields(entity); const look = TIER_RADIUS[m.tier]; - if (m.tele > 0 && look !== undefined) circle(m.x, m.y, look.tele, 'rgba(255,80,80,0.12)', '#ff5050'); - circle(m.x, m.y, look?.radius ?? 0.5, TIER_COLOR[m.tier] ?? '#9ad16b'); + if (m.tele > 0 && look !== undefined) circle(w.x, w.y, look.tele, 'rgba(255,80,80,0.12)', '#ff5050'); + circle(w.x, w.y, look?.radius ?? 0.5, TIER_COLOR[m.tier] ?? '#9ad16b'); } else if (isPlayer(entity)) { + if (entity.stale) continue; const p = playerFields(entity); - const mine = entity.id === options.hello()?.entity; - // Own position for the headless test (a DOM attribute, not Svelte state). - if (mine) canvas.dataset.me = `${p.x.toFixed(2)},${p.y.toFixed(2)}`; + const isMe = entity === meEntity; + if (!isMe && mine(entity)) continue; + // Own room-local position for the headless test (a DOM attribute, not Svelte state). + if (isMe) canvas.dataset.me = `${p.x.toFixed(2)},${p.y.toFixed(2)}`; if (p.swing > 0 && !p.dead) { // The swing cone (blue), fading as `swing` counts down. const fade = p.swing / PIT_RULES.swingFrames; ctx.beginPath(); - ctx.moveTo(...at(p.x, p.y)); + ctx.moveTo(...at(w.x, w.y)); for (let i = 0; i <= 16; i += 1) { const a = p.face - SWING_HALF + (2 * SWING_HALF * i) / 16; - ctx.lineTo(...at(p.x + Math.cos(a) * SWING_REACH, p.y + Math.sin(a) * SWING_REACH)); + ctx.lineTo(...at(w.x + Math.cos(a) * SWING_REACH, w.y + Math.sin(a) * SWING_REACH)); } ctx.closePath(); ctx.fillStyle = `rgba(77,163,255,${0.12 + 0.25 * fade})`; @@ -149,19 +240,19 @@ export function startPitLoop(canvas: HTMLCanvasElement, options: PitLoopOptions) ctx.strokeStyle = '#4da3ff'; ctx.stroke(); // Frames that drew an own swing, for the headless test. - if (mine) canvas.dataset.swings = String(Number(canvas.dataset.swings ?? 0) + 1); + if (isMe) canvas.dataset.swings = String(Number(canvas.dataset.swings ?? 0) + 1); } - circle(p.x, p.y, PLAYER_RADIUS, p.dead ? '#555' : mine ? '#ffd166' : '#6ec3ff'); - const [nx, ny] = at(p.x + Math.cos(p.face) * 0.6, p.y + Math.sin(p.face) * 0.6); - const [cx, cy] = at(p.x, p.y); + circle(w.x, w.y, PLAYER_RADIUS, p.dead ? '#555' : isMe ? '#ffd166' : '#6ec3ff'); + const [nx, ny] = at(w.x + Math.cos(p.face) * 0.6, w.y + Math.sin(p.face) * 0.6); + const [px, py] = at(w.x, w.y); ctx.strokeStyle = '#fff'; ctx.beginPath(); - ctx.moveTo(cx, cy); + ctx.moveTo(px, py); ctx.lineTo(nx, ny); ctx.stroke(); ctx.fillStyle = '#ddd'; ctx.font = '11px system-ui'; - ctx.fillText(p.name, cx - 16, cy - 0.7 * scale); + ctx.fillText(p.name, px - 16, py - 0.7 * scale); } } frame = requestAnimationFrame(draw); diff --git a/examples/game/sveltekit/src/routes/pit/+page.svelte b/examples/game/sveltekit/src/routes/pit/+page.svelte index 031f0025b..5186741bd 100644 --- a/examples/game/sveltekit/src/routes/pit/+page.svelte +++ b/examples/game/sveltekit/src/routes/pit/+page.svelte @@ -4,7 +4,7 @@ import Leaderboard from '$lib/pit/Leaderboard.svelte'; import MyStats from '$lib/pit/MyStats.svelte'; import Rooms from '$lib/pit/Rooms.svelte'; - import { startPitLoop } from '$lib/pit/loop'; + import { pitHandoffFrame, startPitLoop } from '$lib/pit/loop'; let { data } = $props(); @@ -19,7 +19,9 @@ url: (zone) => `${data.roomsUrls[entry++ % data.roomsUrls.length]}/rooms/${encodeURIComponent(zone)}`, ticket: gameTicketSource(), pingIntervalMs: 500, - inputDtMs: 1000 / 30 + inputDtMs: 1000 / 30, + // One continuous world: keep predicting through doorways. + prediction: { handoffFrame: pitHandoffFrame } }), { zone: () => data.zone, events: EVENTS } ); diff --git a/examples/game/sveltekit/tests/pit.test.mjs b/examples/game/sveltekit/tests/pit.test.mjs index ca7b6dc58..fe47bf540 100644 --- a/examples/game/sveltekit/tests/pit.test.mjs +++ b/examples/game/sveltekit/tests/pit.test.mjs @@ -85,11 +85,39 @@ function start(command, args, options, ready) { }; } -/** Walk `page`'s player through the doorway on `side`; resolves with the new room. */ +/** Largest frame-to-frame move (m) of the own world position / view, ≈ one tick of walking. */ +const MAX_JUMP = 0.25; + +/** + * Walk `page`'s player through the doorway on `side`; resolves with the new + * room once the handoff completed. Asserts the world stays continuous: the + * own world position (= the view centre) never moves more than a tick's + * walk between frames, across the doorway too (room-local positions would + * jump by a whole room). + */ async function walkThrough(page, side) { - const goal = { east: [21, 2], west: [-21, 2], north: [2, 21], south: [2, -21] }[side]; + const goal = { east: [21, 1.7], west: [-21, 1.7], north: [1.7, 21], south: [1.7, -21] }[side]; const room = () => page.evaluate(() => document.querySelector('canvas')?.dataset.room); + const world = () => page.evaluate(() => document.querySelector('canvas')?.dataset.world?.split(',').map(Number)); const from = await room(); + await page.evaluate(() => (document.querySelector('canvas').dataset.jump = '0')); + const before = await world(); + const arrived = await walkInto(page, goal, room, from); + // The new room's first snapshot, then the held prediction resumes there. + await page.waitForSelector(`[data-testid=zone]:text-is("${arrived}")`, { timeout: 10_000 }); + await page.waitForTimeout(500); + const jump = Number(await page.evaluate(() => document.querySelector('canvas').dataset.jump)); + const after = await world(); + const [dx, dy] = { east: [1, 0], west: [-1, 0], north: [0, 1], south: [0, -1] }[side]; + console.error(`doorway ${from} → ${arrived}: largest frame move ${jump} m, world ${before} → ${after}`); + assert.ok(jump <= MAX_JUMP, `${from} → ${arrived}: the view jumped ${jump} m in one frame`); + // Moved on in the doorway's direction, a few metres, not a room. + const along = (after[0] - before[0]) * dx + (after[1] - before[1]) * dy; + assert.ok(along > 0 && Math.hypot(after[0] - before[0], after[1] - before[1]) < 40, `${before} → ${after}`); + return arrived; +} + +async function walkInto(page, goal, room, from) { const held = new Set(); const hold = async (keys) => { for (const k of [...held]) if (!keys.includes(k)) (await page.keyboard.up(k), held.delete(k)); From dcda004322ba41a6edfcb4483d8d34d1d6840080 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 23:03:59 -0500 Subject: [PATCH 269/484] fix(js): end a game connection attempt on a refused Hello A zone that refuses a Hello (expired reconnect token, bad ticket) sends Error and should close the socket. celld room objects send the Error but the close never reaches the client, so after a celld restart a connected page tried its void token and then hung in 'reconnecting' forever. The client now ends the attempt itself on a pre-Welcome Error: a resume falls back to a fresh ticket, a refused first connect rejects. Refs [[tasks/gr-p45-same-player-after-restarts]] --- js/src/game/connection.ts | 8 +++++++ js/tests/game-connection.test.mjs | 38 ++++++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/js/src/game/connection.ts b/js/src/game/connection.ts index 61a12614d..c7a4be5b2 100644 --- a/js/src/game/connection.ts +++ b/js/src/game/connection.ts @@ -585,6 +585,14 @@ export class GameConnection { break; case 'Error': this.#onError(attempt, message); + if (!attempt.welcomed && this.#attempt === attempt) { + // A refused Hello ends the attempt: nothing else follows it. + // Do not wait for the server's close (a host may never send + // one, e.g. a restarted zone refusing a void token). + this.#attempt = undefined; + attempt.socket.close(1000, 'refused'); + this.#onSocketClosed(attempt, 1008, message.message); + } break; } } diff --git a/js/tests/game-connection.test.mjs b/js/tests/game-connection.test.mjs index a678d3fc0..df489def7 100644 --- a/js/tests/game-connection.test.mjs +++ b/js/tests/game-connection.test.mjs @@ -20,7 +20,7 @@ import { } from './fixtures/game-harness.mjs'; /** A scripted zone: tickets `t::` admit; tokens rotate per Welcome. */ -function scriptedServer(network, { graceTokens = true } = {}) { +function scriptedServer(network, { graceTokens = true, closeOnError = true } = {}) { const tokens = new Set(); let issued = 0; network.onMessage = (conn, message) => { @@ -28,12 +28,12 @@ function scriptedServer(network, { graceTokens = true } = {}) { if (message.reconnectToken !== '') { if (!graceTokens || !tokens.delete(message.reconnectToken)) { conn.send({ type: 'Error', code: GameErrorCode.RECONNECT_FAILED, message: 'expired' }); - conn.close(1008); + if (closeOnError) conn.close(1008); return; } } else if (!message.ticket.startsWith(`t:${conn.zoneId}`) && !message.ticket.startsWith('transfer:')) { conn.send({ type: 'Error', code: GameErrorCode.UNAUTHORIZED, message: 'bad ticket' }); - conn.close(1008); + if (closeOnError) conn.close(1008); return; } issued += 1; @@ -215,6 +215,38 @@ test('reconnects with the token inside the grace window, then falls back to a fr conn.close(); }); +test('a refused Hello ends the attempt even when the server never closes the socket', async () => { + // E.g. a restarted zone refusing the old session's token: the error + // arrives, the close may not (seen with celld room objects). + const network = new FakeNetwork(); + const scheduler = new FakeScheduler(); + const tokens = scriptedServer(network, { closeOnError: false }); + const { conn, tickets } = connection(network, scheduler); + await conn.connect(); + tokens.clear(); + network.last().close(1006); + await scheduler.advance(10); + assert.equal(network.last().lastHello.reconnectToken, 'rt-1', 'tried the token'); + await scheduler.advance(1000); + const hello = network.last().lastHello; + assert.equal(hello.reconnectToken, '', 'then a fresh ticket'); + assert.equal(hello.ticket, `t:z1:${tickets.length}`); + assert.equal(conn.state, 'open'); + conn.close(); + + // A refused first Hello rejects connect() instead of hanging. + const refused = new GameConnection({ + url: 'ws://game.test/zones/z1', + zoneId: 'z1', + ticket: () => 'forged', + socket: network.factory, + scheduler, + reconnect: false + }); + await assert.rejects(refused.connect(), /bad ticket|rejected/); + assert.equal(refused.state, 'closed'); +}); + test('a zone that restarted (close 1012) is rejoined at once with a fresh ticket', async () => { const network = new FakeNetwork(); const scheduler = new FakeScheduler(); From bf01e20209aa7165be8aef64f589472311bf882b Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 23:04:06 -0500 Subject: [PATCH 270/484] fix(game): Arena and Endless Grid keep the body on a reload A page reload is a fresh ticket for a slot its principal still holds. The default Zone::on_rejoin (leave, then join) respawned the player, so every reload lost the body even inside the reconnect grace. Arena and Endless Grid now keep it and re-greet the new page; the on_rejoin docs say why a game wants that. Refs [[tasks/gr-p45-same-player-after-restarts]] --- distributed_game/src/zone.rs | 6 +- examples/game/server/src/arena/mod.rs | 85 ++++++++++++++++++++++++--- examples/game/server/src/grid/mod.rs | 60 +++++++++++++++++++ 3 files changed, 140 insertions(+), 11 deletions(-) diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs index a6e2710bd..984631dbd 100644 --- a/distributed_game/src/zone.rs +++ b/distributed_game/src/zone.rs @@ -249,8 +249,10 @@ pub trait Zone: Sized + Send + 'static { /// state the zone sent on join (own entity id, hello events…). /// /// Defaults to `on_leave(Rejoined)` then `on_join`, i.e. a fresh join in - /// the same [`PlayerId`]. Override to keep in-zone state and only resend - /// what the client needs. + /// the same [`PlayerId`]: the body is respawned. Override to keep + /// in-zone state and only resend what the client needs, so a reloaded + /// page takes over the same body (what players expect; the examples' + /// Mob Pit, Arena and Endless Grid do). fn on_rejoin(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { self.on_leave(ctx, player, LeaveReason::Rejoined); self.on_join(ctx, player); diff --git a/examples/game/server/src/arena/mod.rs b/examples/game/server/src/arena/mod.rs index b1507883e..8ffe5e1c6 100644 --- a/examples/game/server/src/arena/mod.rs +++ b/examples/game/server/src/arena/mod.rs @@ -206,6 +206,24 @@ pub struct ArenaConfig { pub guests: Guests, } +impl Arena { + /// Tell `player`'s client session its entity and set its view. + fn greet(&self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let Some(p) = self.players.get(&player) else { + return; + }; + ctx.set_view(player, View::new(p.state.x, p.state.y, VIEW_RADIUS)); + ctx.send( + player, + &ArenaEvent::Hello { + entity: p.entity, + view_radius: VIEW_RADIUS, + half: movement::HALF, + }, + ); + } +} + /// The Arena zone. pub struct Arena { guests: Guests, @@ -294,15 +312,17 @@ impl Zone for Arena { }, }, ); - ctx.set_view(player, View::new(x, y, VIEW_RADIUS)); - ctx.send( - player, - &ArenaEvent::Hello { - entity, - view_radius: VIEW_RADIUS, - half: movement::HALF, - }, - ); + self.greet(ctx, player); + } + + /// A reloaded page (fresh ticket for a slot it still holds): keep the + /// body where it is, greet the new client session. + fn on_rejoin(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + if self.players.contains_key(&player) { + self.greet(ctx, player); + } else { + self.on_join(ctx, player); + } } fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { @@ -395,3 +415,50 @@ impl Demo for ArenaDemo { ) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::Duration; + + use distributed_game::{HostConfig, ManualClock, Role, TicketClaims, Viewer, ZoneHost}; + + use super::*; + + #[test] + fn a_reload_keeps_the_body() { + let clock = ManualClock::new(); + let mut host = ZoneHost::::new( + "arena", + HostConfig::default(), + Arc::new(clock.clone()), + ArenaConfig { + guests: Guests::default(), + }, + ); + let claims = TicketClaims::new("ana", "arena", u64::MAX, "n1", Role::Player); + let joined = host.join(&claims, 0, "").expect("join"); + let Viewer::Player(player) = joined.viewer else { + panic!("player") + }; + for seq in 1..=20u32 { + let input = MoveInput { + mx: 127, + my: 0, + buttons: 0, + }; + host.push_input(joined.client, seq, seq, &input.to_payload()); + clock.advance(Duration::from_millis(33)); + host.advance(); + } + let before = host.zone().players[&player].state; + host.disconnect(joined.client, false); + let claims = TicketClaims::new("ana", "arena", u64::MAX, "n2", Role::Player); + let again = host.join(&claims, 0, "").expect("rejoin"); + assert_eq!(again.viewer, Viewer::Player(player)); + clock.advance(Duration::from_millis(33)); + host.advance(); + let after = host.zone().players[&player].state; + assert_eq!((before.x, before.y), (after.x, after.y), "same body"); + } +} diff --git a/examples/game/server/src/grid/mod.rs b/examples/game/server/src/grid/mod.rs index 55b774604..d778fd501 100644 --- a/examples/game/server/src/grid/mod.rs +++ b/examples/game/server/src/grid/mod.rs @@ -461,6 +461,21 @@ impl Zone for GridZone { } } + /// A reloaded page (fresh ticket for a slot it still holds): keep the + /// walker where it is, greet the new client session. + fn on_rejoin(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + match self.walkers.get(&player) { + Some(w) if !w.leaving => { + let hello = self.hello(ctx, Some(w.entity)); + ctx.send(player, &hello); + } + _ => { + self.walkers.remove(&player); + self.on_join(ctx, player); + } + } + } + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { self.walkers.remove(&player); } @@ -679,4 +694,49 @@ mod tests { assert_eq!(decode_carried(&encode_carried(99.0, 1.0, "x")), None); assert_eq!(decode_carried(&[1, 2, 3]), None); } + + #[test] + fn a_reload_keeps_the_walker() { + use distributed_game::{HostConfig, ManualClock, Role, TicketClaims, Viewer, ZoneHost}; + let clock = ManualClock::new(); + let mut host = ZoneHost::::new( + "cell.0.0", + HostConfig::default(), + std::sync::Arc::new(clock.clone()), + GridConfig { + guests: Guests::default(), + host_id: "A".into(), + seed: 7, + cell: (0, 0), + }, + ); + let claims = TicketClaims::new("guest-ana", "cell.0.0", u64::MAX, "n1", Role::Player); + let joined = host.join(&claims, 0, "").expect("join"); + let Viewer::Player(player) = joined.viewer else { + panic!("player") + }; + for seq in 1..=20u32 { + let input = MoveInput { + mx: 127, + my: 60, + buttons: 0, + }; + host.push_input(joined.client, seq, seq, &input.to_payload()); + clock.advance(std::time::Duration::from_millis(33)); + host.advance(); + } + let at = |host: &ZoneHost| { + let w = &host.zone().walkers[&player]; + (w.x, w.y) + }; + let before = at(&host); + assert_ne!(before, (CELL / 2.0, CELL / 2.0), "walked"); + host.disconnect(joined.client, false); + let claims = TicketClaims::new("guest-ana", "cell.0.0", u64::MAX, "n2", Role::Player); + let again = host.join(&claims, 0, "").expect("rejoin"); + assert_eq!(again.viewer, Viewer::Player(player)); + clock.advance(std::time::Duration::from_millis(33)); + host.advance(); + assert_eq!(at(&host), before, "same walker"); + } } From 60536d263eedfae629c86e99c6cafb0b65d8bff8 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 23:04:07 -0500 Subject: [PATCH 271/484] fix(game): keep dev ticket secrets across demo restarts run.sh gave Arena, Grid, Ripple, Gallery and Freeze a random ticket secret per run, so a returning browser's guest token no longer verified and it became a new player. Every demo now signs with a secret persisted in .data/ (SvelteKit also keeps its Auth.js secret), and the cells worker is rebuilt when the room or sim crates change. Refs [[tasks/gr-p45-same-player-after-restarts]] --- examples/game/run.sh | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/examples/game/run.sh b/examples/game/run.sh index 210b2b853..0fcd48b59 100755 --- a/examples/game/run.sh +++ b/examples/game/run.sh @@ -123,7 +123,7 @@ ensure_celld() { # sources changed. ensure_cells() { local marker="$CELLS/build/worker/shim.mjs" - if [[ ! -f "$marker" ]] || [[ -n "$(find "$CELLS/src" "$CELLS/Cargo.toml" "$SERVER/crawler" "$REPO/src" "$REPO/distributed_game/src" -newer "$marker" -name '*.rs' -print -quit 2>/dev/null)" ]] || + if [[ ! -f "$marker" ]] || [[ -n "$(find "$CELLS/src" "$CELLS/Cargo.toml" "$SERVER/crawler" "$SERVER/rooms" "$SERVER/sim" "$REPO/src" "$REPO/distributed_game/src" -newer "$marker" -name '*.rs' -print -quit 2>/dev/null)" ]] || [[ "$CELLS/Cargo.toml" -nt "$marker" ]]; then command -v worker-build >/dev/null || { echo "worker-build not found: cargo install worker-build --locked" >&2 @@ -245,10 +245,12 @@ ensure_wasm() { return "$status" } -# mobpit_secret : the rooms' ticket secret, persisted in (the -# services read the same file: guests keep their identity across restarts). -mobpit_secret() { - local file="$1/dev-ticket-secret" +# dev_secret [name]: a dev secret persisted in / (default +# dev-ticket-secret: the ticket secret; Mob Pit's services read the same +# file). Persisted so a returning browser is the same player after a +# restart: its guest token (or session cookie) still verifies. +dev_secret() { + local file="$1/${2:-dev-ticket-secret}" mkdir -p "$1" if [[ ! -s "$file" ]]; then (umask 077 && od -An -N32 -tx1 /dev/urandom | tr -d ' \n' >"$file") @@ -378,7 +380,7 @@ run_mobpit() { ensure_server ensure_wasm local secret - secret="$(mobpit_secret "$MOBPIT_DATA_DIR")" + secret="$(dev_secret "$MOBPIT_DATA_DIR")" CELLD_PID="" FLEET_PROJECT="" if [[ "$fleet" == --fleet ]]; then @@ -419,9 +421,11 @@ run_demo() { [[ "$demo" == mobpit || "$demo" == leaderboard ]] && project="$MOBPIT_DATA_DIR/celld" start_celld "$project" "${CELLD_PORT:-$((port + 3))}" "$port" fi - local log_file + local log_file secret log_file="$(mktemp -t game-demos.XXXXXX)" - "$BIN" "$demo" --dev --port "$port" >"$log_file" 2>&1 & + secret="${DISTRIBUTED_GAME_SECRET:-$(dev_secret "$HERE/.data/$demo")}" + [[ "$demo" == mobpit || "$demo" == leaderboard ]] && secret="$(dev_secret "$MOBPIT_DATA_DIR")" + DISTRIBUTED_GAME_SECRET="$secret" "$BIN" "$demo" --dev --port "$port" >"$log_file" 2>&1 & local server_pid=$! trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true; [[ -z "$CELLD_PID" ]] || kill_tree "$CELLD_PID"; rm -f "$log_file"' EXIT INT TERM for _ in $(seq 1 100); do @@ -470,7 +474,7 @@ run_cluster() { local dir secret dir="$(mktemp -d "${TMPDIR:-/tmp}/game-demos-$demo.XXXXXX")" # Both hosts must share the ticket secret (and derive the admin secret). - secret="${DISTRIBUTED_GAME_SECRET:-$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')}" + secret="${DISTRIBUTED_GAME_SECRET:-$(dev_secret "$HERE/.data/$demo")}" # The relay lands on host A; both hosts share the projection bus and keep # their zone status read models in .data/. DISTRIBUTED_GAME_SECRET="$secret" "$BIN" "$demo" --dev --port "$port_a" --host-id A \ @@ -539,7 +543,7 @@ run_sveltekit() { ensure_cli mkdir -p "$data" local secret - secret="$(mobpit_secret "$data")" + secret="$(dev_secret "$data")" CELLD_PID="" FLEET_PROJECT="" if [[ "$fleet" == --fleet ]]; then @@ -569,7 +573,7 @@ run_sveltekit() { MOBPIT_PROTOCOL_KEY="$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')" \ MOBPIT_UI_ORIGINS="http://localhost:$ui_port,http://127.0.0.1:$ui_port" \ MOBPIT_GRAPHQL_URL="http://127.0.0.1:$service_port/graphql" \ - GAME_DEV_AUTH=1 AUTH_SECRET="${AUTH_SECRET:-$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')}" \ + GAME_DEV_AUTH=1 AUTH_SECRET="${AUTH_SECRET:-$(dev_secret "$data" auth-secret)}" \ GAME_TICKET_SECRET="$secret" GAME_ZONES_URL="$(echo "$ROOMS_URLS" | sed 's#http://#ws://#g')" \ "$CLI" dev "$SERVER" } From 123fa992016c6aca85d5594b65f6e3c8b6991ac0 Mon Sep 17 00:00:00 2001 From: Patrick Lee Scott Date: Tue, 20 Oct 2026 23:10:18 -0500 Subject: [PATCH 272/484] feat(game): Mob Pit players come back where they were A reload, a new tab, closing the browser, or a services or celld restart put a returning Mob Pit player in a new body at the entrance spawn point: - the rooms used the default rejoin (leave + join), discarding the body; - nothing chose the player's last room (Vite joined ?zone= or pit.0.0, the SvelteKit ticket handler the entrance); - a room forgot a player's place when its slot ended; - the dev guest token lived in sessionStorage (one guest per tab). Rooms now keep the body on rejoin and park the place and HP of a player whose slot ends (and of connected players in every snapshot) by verified principal, so a fresh join resumes there after the room slept or celld restarted. Page loads start in the last room from the presence cell: POST /dev/mobpit/start (guest token verified) for Vite, the ticket handler's zone() for SvelteKit. The guest token moves to localStorage (?player=