diff --git a/README.md b/README.md index 25d353cff..5c924eae9 100644 --- a/README.md +++ b/README.md @@ -106,8 +106,8 @@ pub struct Todos { pub status: String, } -impl Todos { - pub fn permissions() -> ModelPermissions { +impl AuthorizedReadModel for Todos { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", @@ -118,6 +118,15 @@ impl Todos { .grant("admin", read().all_columns()) } } + +// One list feeds schema bootstrap, the GraphQL engine and client export. +pub fn read_models() -> ReadModels { + ReadModels::new("e2e-ui") + .model::() + .model::() + .model::() + .model::() +} ``` ### 05 · Inferred query API @@ -361,17 +370,41 @@ split. Topology is explicit composition — not a hidden matrix. [`tests/e2e-ui/crates/service/src/modules/compose.rs`](tests/e2e-ui/crates/service/src/modules/compose.rs) ```rust,ignore -// compose.rs (trimmed). Each routes(...) takes repo, locks, read models, -// and the projection owner for that module. -pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, chat::MODULE_ID, blob::MODULE_ID, "identity", -]; - -Service::new() - .named("e2e-ui") - .routes(todo::routes(repo.clone(), locks.clone(), read_models.clone(), projections.todo)) - .routes(chat::routes(repo.clone(), locks.clone(), read_models.clone(), projections.chat)) - .routes(blob::routes(repo, locks, read_models, projections.blob)) +// todo.rs: one bound for every store; the projection comes from its descriptor. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) + .mount(todo_domain::commands::create()) + // … + .consume_projection(projections.projector(TODOS)) +} + +// compose.rs (trimmed). The modules are the command namespaces; the +// application manifest is derived from this Service. +pub fn build_service(stores: &St) -> Service { + let projections = LocalProjectionMounts::builder("e2e-ui", "ordered-domain-events") + .eventual(TODOS) + .eventual(CHAT_MESSAGES) + .direct(BLOB_GAMES) + .eventual(AUTH_USERS) + .build() + .expect("e2e-ui projection catalog"); + Service::new() + .named("e2e-ui") + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections)) +} + +// host.rs: one host for SQLite and Postgres. +async fn host(stores: St, options: HostOptions) -> Result<(), BoxError> { + stores.bootstrap_read_models(read_models().catalog()).await?; + let service = build_service(&stores).with_bus(stores.bus("e2e-ui")); + // … GraphQL engine over stores.graphql_pool(), serve +} // Another crate can list the same modules, or only Eventual projectors. // You write that Service. You do not flip a Runtime::role flag. diff --git a/distributed_game/src/world/zone_status.rs b/distributed_game/src/world/zone_status.rs index 5ac3d4f12..65d016b3f 100644 --- a/distributed_game/src/world/zone_status.rs +++ b/distributed_game/src/world/zone_status.rs @@ -26,7 +26,7 @@ use distributed::graphql::SurfaceProjector; use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; use distributed::{ - mutation_file, LocalProjectionMountsBuilder, Mutation, ReadModel, ReadModelCatalog, + mutation_file, LocalProjectionMounts, Mutation, ReadModel, ReadModelCatalog, RelationalReadModel, }; use serde::{Deserialize, Serialize}; @@ -43,19 +43,6 @@ use super::zone_state::{ZoneStateDeletedDomainEvent, ZoneStateSavedDomainEvent}; /// Application of the read model (catalog and projector owner; the /// consumer service is named after it). pub const APPLICATION: &str = "zone-status"; -/// Projector of [`ZoneLeases`]. -pub const LEASES_PROJECTOR: &str = "project_zone_leases"; -/// Projector of [`ZoneSnapshots`]. -pub const SNAPSHOTS_PROJECTOR: &str = "project_zone_snapshots"; -/// Epoch of [`ZONE_LEASES`] (bump to rebuild from the bus log). -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 /// named after its table, as `mutation_file!` requires). @@ -202,39 +189,25 @@ pub fn activity_projector() -> SurfaceProjector { /// [`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") + LocalProjectionMounts::builder(application, "ordered-domain-events") + .eventual(ZONE_ACTIVITIES) .build() - .expect("projection catalog") - .projector(ACTIVITIES_PROJECTOR) - .expect("zone activities projector") + .expect("zone activities projection") + .projector(ZONE_ACTIVITIES) } /// The modeled projector mounts `(leases, snapshots)`: mount both on one /// consumer service named [`APPLICATION`], applying [`ZONE_LEASES`] and /// [`ZONE_SNAPSHOTS`] respectively. pub fn projectors() -> (SurfaceProjector, SurfaceProjector) { - let mounts = LocalProjectionMountsBuilder::new(APPLICATION, "ordered-domain-events") - .expect("projection source") - .eventual_model::(LEASES_PROJECTOR, ZONE_LEASES, LEASES_EPOCH) - .expect("zone leases mount") - .eventual_model::(SNAPSHOTS_PROJECTOR, ZONE_SNAPSHOTS, SNAPSHOTS_EPOCH) - .expect("zone snapshots mount") + let mounts = LocalProjectionMounts::builder(APPLICATION, "ordered-domain-events") + .eventual(ZONE_LEASES) + .eventual(ZONE_SNAPSHOTS) .build() - .expect("projection catalog"); + .expect("zone status projections"); ( - mounts - .projector(LEASES_PROJECTOR) - .expect("zone leases projector"), - mounts - .projector(SNAPSHOTS_PROJECTOR) - .expect("zone snapshots projector"), + mounts.projector(ZONE_LEASES), + mounts.projector(ZONE_SNAPSHOTS), ) } diff --git a/docs/application-composition.md b/docs/application-composition.md index 0dcc70652..4a1cca7a6 100644 --- a/docs/application-composition.md +++ b/docs/application-composition.md @@ -4,7 +4,7 @@ **Goal:** Make the same packages easy to run as a monolith or as microservices, with persistence/locks/transports as a separate, boring plane. **Non-goal:** Back-compat aliases or dual public APIs for the same concept. -Motivating pain (now resolved): e2e-ui once had a single `service.rs` holding the projection catalog, surfaces and command walls, and a runner that hand-wired SQLite/Postgres × API/outbox/consumer. Today the composition root is `tests/e2e-ui/crates/service/src/application.rs` (surfaces, module inventory), infrastructure is `host.rs`, each bounded context is a module under `modules/` (listed by `modules/compose.rs`), and `crates/runner/src/main.rs` is a short entrypoint. +Motivating pain (now resolved): e2e-ui once had a single `service.rs` holding the projection catalog, surfaces and command walls, and a runner that hand-wired SQLite/Postgres × API/outbox/consumer. Today the composition root is `tests/e2e-ui/crates/service/src/application.rs` (application name and client surfaces), infrastructure is `host.rs` (one path for SQLite and Postgres), each bounded context is a module under `modules/` (listed by `modules/compose.rs`), the application manifest is derived from the composed `Service`, and `crates/runner/src/main.rs` is a short entrypoint. --- @@ -44,16 +44,39 @@ readmodels/ schemas + grants ### Mounts (compose) +Each fact is stated once. A projection's name, epoch and model come from its +`projection!` descriptor; a read model's permissions live next to it +(`impl AuthorizedReadModel`); a module is generic over one `ServiceStores` +bound; the application's modules are the Service's command namespaces. + ```rust -// Sketch — names may evolve; intent is stable. -app.projection(TODOS).eventual().epoch("todos-v2"); -app.projection(BLOB_GAMES).atomic().epoch("blob-v2"); // collocated with blob commands +// modules/projections.rs +LocalProjectionMounts::builder("e2e-ui", "ordered-domain-events") + .eventual(TODOS) + .eventual(CHAT_MESSAGES) + .direct(BLOB_GAMES) // sealed by blob commands in their own transaction + .eventual(AUTH_USERS) + .build()?; + +// modules/todo.rs +pub fn routes(stores: &St, projections: &LocalProjectionMounts) + -> Routes> +{ + Routes::for_aggregate(stores) + .mount(todo_domain::commands::create()) + .consume_projection(projections.projector(TODOS)) +} -app.command(todo_create::def()); -app.command(blob_move::def()); +// readmodels: one list for schema bootstrap, the engine and client export +ReadModels::new("e2e-ui").model::().model::()…; -app.surface("e2e-ui").eligible(["user", "admin"]).schema(["user"]); -app.surface("e2e-ui-admin").roles(["admin"]); +// application.rs: each client surface declared once +pub const CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui", eligible_roles: &["admin", "user"], schema_roles: &["user"], +}; + +// the manifest: derived, never listed by hand +service.application("e2e-ui", SurfaceSpec::from_surface("e2e-ui", &surface)?)?; ``` ### Command defs co-located with handlers @@ -102,9 +125,21 @@ Application::new("e2e-ui").include(todo_system()).include(chat_system())… // F ### One dialect choice pairs store + locks + bus ```rust -let runtime = Runtime::sqlite(database_url).await?; -// Runtime::postgres(database_url).await? -// Runtime::in_memory() // client-manifest / unit tests +// host.rs: written once against SqlStores +if postgres_url { + host(PostgresStores::connect(database_url).await?, options).await +} else { + host(SqliteStores::connect(database_url).await?, options).await +} + +async fn host(stores: St, options: HostOptions) -> Result<(), BoxError> { + stores.bootstrap_read_models(read_models().catalog()).await?; + let service = build_service(&stores).with_bus(stores.bus("e2e-ui")); // also drains the outbox + // GraphQL over stores.graphql_pool(), spawn_service_consumer_loop, serve +} + +// client-manifest / unit tests +build_service(&Stores::new(InMemoryRepository::new(), InMemoryLockManager::new(), repo)); ``` Defaults from the same pool (e2e today): @@ -171,10 +206,10 @@ Primary write path for apps remains GraphQL commands. HTTP command routes stay o | Today | Target | |--------|--------| -| `projection_owners()` catalog ceremony | `projection_inventory!` / `ProjectionMount` defaults | -| 15-line `typed_command` walls in `build_service` | `.register(todo_create::def())` | -| Three surface helpers rebuilding InMemory | `app.surface(...).export()` | -| Runner: sqlite/postgres forks × outbox/consumer | `Runtime::from_env().role(Full).app(...).run()` | +| Done: projection mounts read name, epoch and model from the descriptor | `LocalProjectionMounts::builder(..).eventual(TODOS)` | +| Done: commands are `command!` declarations mounted with `.mount(..)` | — | +| Done: one `ReadModels` list and one `ClientSurface` table feed engine and export | — | +| Done: one host path over `SqlStores`; `with_bus` drains the outbox | `Runtime::from_env().role(Full).app(...).run()` (process roles) | Rough size: **~100–150 lines of product wiring** for logical app + a tiny deployable main — not ~950 lines of framework internals. @@ -182,9 +217,9 @@ Rough size: **~100–150 lines of product wiring** for logical app + a tiny depl ## Implementation order -1. **Projection mount / inventory** — hide catalog, topology digests, activation. +1. **Projection mount / inventory** — hide catalog, topology digests, activation. Done: `LocalProjectionMounts::builder`. 2. **CommandDef + `.register()`** — co-locate transitions/handlers with command modules. -3. **Runtime::{sqlite, postgres, in_memory}** — pair repo + locks + bus. +3. **Pair repo + locks + bus** — done: `Stores`, `SqliteStores`, `PostgresStores` (`SqlStores`). 4. **ProcessRole** — Full / CommandWriter / EventualProjector / QueryApi spawn policy. 5. **Atomic mount checks** — fail closed if Atomic is mounted without write path. 6. **Collapse e2e-ui `service.rs` + `runner`** onto the new APIs (no dual/legacy surface). Done: see `application.rs`, `host.rs` and `modules/` in `tests/e2e-ui/crates/service/src/`. @@ -198,7 +233,7 @@ of cache effects. - [ ] e2e-ui logical app does not mention partition codec, topology digests, or manual catalog activate. - [ ] Adding a command is “def next to handler + one register line,” not a 12-line block in a central file. -- [ ] Runner has one path for sqlite/postgres selected by URL/env. +- [x] Runner has one path for sqlite/postgres selected by URL/env. - [ ] A dual-process smoke (command writer + eventual projector) can share packages with Full e2e. - [ ] Atomic blob commands refuse projector-only process configuration. - [ ] Client gen still works from logical app (preview IR) without a live pool. diff --git a/examples/game/server/crawler/src/stats.rs b/examples/game/server/crawler/src/stats.rs index 92c08175d..86c911fc9 100644 --- a/examples/game/server/crawler/src/stats.rs +++ b/examples/game/server/crawler/src/stats.rs @@ -12,7 +12,7 @@ use distributed::graphql::SurfaceProjector; use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; use distributed::{ - mutation_file, LocalProjectionMountsBuilder, Mutation, ReadModel, ReadModelCatalog, + mutation_file, LocalProjectionMounts, Mutation, ReadModel, ReadModelCatalog, RelationalReadModel, }; use serde::{Deserialize, Serialize}; @@ -21,10 +21,6 @@ use crate::CrawlerMobKilledDomainEvent; /// Application of the read model (catalog and projector owner). 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"; /// One player's settled progress (a projection of their Crawler cell). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] @@ -70,12 +66,9 @@ pub fn read_model_catalog() -> ReadModelCatalog { /// 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") + LocalProjectionMounts::builder(APPLICATION, "ordered-domain-events") + .eventual(PLAYER_STATS) .build() - .expect("projection catalog") - .projector(PROJECTOR) - .expect("player stats projector") + .expect("player stats projection") + .projector(PLAYER_STATS) } diff --git a/examples/game/server/service/src/lib.rs b/examples/game/server/service/src/lib.rs index 196ce4b0d..3b8252fa5 100644 --- a/examples/game/server/service/src/lib.rs +++ b/examples/game/server/service/src/lib.rs @@ -56,7 +56,7 @@ use distributed_leaderboard::{ 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, PlayerStats, SavePlayerStats, APPLICATION, EPOCH, PLAYER_STATS, PROJECTOR, + projector, PlayerStats, SavePlayerStats, APPLICATION, PLAYER_STATS, }; /// The boroughs (bosses down, weather, the world event running) and their diff --git a/examples/game/server/tiers/src/events.rs b/examples/game/server/tiers/src/events.rs index 882cdc10c..93285bea6 100644 --- a/examples/game/server/tiers/src/events.rs +++ b/examples/game/server/tiers/src/events.rs @@ -7,7 +7,7 @@ use distributed::graphql::SurfaceProjector; use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; use distributed::{ - mutation_file, LocalProjectionMountsBuilder, Mutation, ReadModel, ReadModelCatalog, + mutation_file, LocalProjectionMounts, Mutation, ReadModel, ReadModelCatalog, RelationalReadModel, }; use serde::{Deserialize, Serialize}; @@ -18,11 +18,6 @@ use crate::{ BoroughChangedDomainEvent, BoroughEventEndedDomainEvent, BoroughEventStartedDomainEvent, }; -/// Projection name. -pub const PROJECTOR: &str = "project_boroughs"; -/// Projection epoch: bump to rebuild the table from the bus log. -pub const EPOCH: &str = "mobpit-boroughs-v1"; - /// One borough as its cell last published it. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] #[table("boroughs")] @@ -73,12 +68,9 @@ pub fn read_model_catalog(application: &str) -> ReadModelCatalog { /// The modeled projector mount for [`BOROUGHS`], owned by `application`. pub fn projector(application: &str) -> SurfaceProjector { - LocalProjectionMountsBuilder::new(application, "ordered-domain-events") - .expect("projection source") - .eventual_model::(PROJECTOR, BOROUGHS, EPOCH) - .expect("boroughs mount") + LocalProjectionMounts::builder(application, "ordered-domain-events") + .eventual(BOROUGHS) .build() - .expect("projection catalog") - .projector(PROJECTOR) - .expect("boroughs projector") + .expect("boroughs projection") + .projector(BOROUGHS) } diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index d199fa0bd..26fdd8a59 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -76,6 +76,11 @@ impl GraphqlEngineBuilder { self } + /// Expose every model of `models` with its own permissions. + pub fn read_models(self, models: &crate::graphql::ReadModels) -> Self { + models.register(self) + } + pub fn model(mut self, perms: ModelPermissions) -> Self { let schema = M::schema().clone(); if let Err(e) = self.insert_catalog(schema.clone(), true) { diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index c6774595d..40f2fc1d5 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -33,6 +33,13 @@ pub struct GraphqlPoolSource { pub(crate) causal_storage_identity: Option, } +impl GraphqlPoolSource { + /// The pool queries read through. + pub fn pool(&self) -> &GraphqlPool { + &self.pool + } +} + impl From for GraphqlPoolSource { fn from(pool: GraphqlPool) -> Self { Self { diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index 7013fe0cf..23c2d81b5 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -41,7 +41,7 @@ pub use surface::{ pub use filter::{ claim, col, lit, rel, ClaimRef, CmpOp, ColRef, FilterExpr, LitValue, Operand, Truth, }; -pub use permissions::{read, ModelPermissions, ReadPermission}; +pub use permissions::{read, AuthorizedReadModel, ModelPermissions, ReadModels, ReadPermission}; #[cfg(feature = "graphql")] mod compile; diff --git a/src/graphql/permissions.rs b/src/graphql/permissions.rs index b662e94e8..3c3f52500 100644 --- a/src/graphql/permissions.rs +++ b/src/graphql/permissions.rs @@ -129,3 +129,109 @@ impl ModelPermissions { self.entries.iter().cloned().collect() } } + +/// A read model whose read permissions are declared next to it. +/// +/// ```ignore +/// impl AuthorizedReadModel for Todos { +/// fn permissions() -> ModelPermissions { +/// ModelPermissions::new().grant("admin", read().all_columns()) +/// } +/// } +/// ``` +pub trait AuthorizedReadModel: crate::RelationalReadModelIncludes { + /// Who may read this model, which columns and which rows. + fn permissions() -> ModelPermissions; +} + +/// The read models one application serves, each with its permissions. +/// +/// The single list every consumer reads: schema bootstrap +/// ([`catalog`](Self::catalog)), the GraphQL engine +/// (`GraphqlEngineBuilder::read_models`), role grants for client export +/// ([`grants`](Self::grants)) and table names ([`table_names`](Self::table_names)). +#[derive(Clone)] +pub struct ReadModels { + catalog: crate::ReadModelCatalog, + models: Vec, +} + +#[derive(Clone)] +struct RegisteredReadModel { + model_name: String, + grants: Vec<(String, ReadPermission)>, + #[cfg(feature = "graphql")] + register: fn(super::GraphqlEngineBuilder) -> super::GraphqlEngineBuilder, +} + +#[cfg(feature = "graphql")] +fn register_model( + builder: super::GraphqlEngineBuilder, +) -> super::GraphqlEngineBuilder { + builder.model::(M::permissions()) +} + +impl ReadModels { + /// An empty catalog named `name`. + pub fn new(name: impl Into) -> Self { + Self { + catalog: crate::ReadModelCatalog::new(name), + models: Vec::new(), + } + } + + /// Serve `M` with its own permissions. + /// + /// # Panics + /// + /// When `M`'s schema is invalid or collides with a model already listed. + pub fn model(mut self) -> Self { + self.catalog = self.catalog.read_model::(); + self.models.push(RegisteredReadModel { + model_name: M::schema().model_name.clone(), + grants: M::permissions().entries, + #[cfg(feature = "graphql")] + register: register_model::, + }); + self + } + + /// The physical tables, for schema bootstrap and Surface building. + pub fn catalog(&self) -> &crate::ReadModelCatalog { + &self.catalog + } + + /// Grants by role, then model name. + pub fn grants(&self) -> BTreeMap> { + let mut grants = BTreeMap::>::new(); + for model in &self.models { + for (role, grant) in &model.grants { + grants + .entry(role.clone()) + .or_default() + .insert(model.model_name.clone(), grant.clone()); + } + } + grants + } + + /// The table names, in catalog order. + pub fn table_names(&self) -> Vec { + self.catalog + .tables + .iter() + .map(|table| table.table_name.clone()) + .collect() + } + + #[cfg(feature = "graphql")] + pub(crate) fn register( + &self, + mut builder: super::GraphqlEngineBuilder, + ) -> super::GraphqlEngineBuilder { + for model in &self.models { + builder = (model.register)(builder); + } + builder + } +} diff --git a/src/lock/in_memory.rs b/src/lock/in_memory.rs index d56ea663a..938851620 100644 --- a/src/lock/in_memory.rs +++ b/src/lock/in_memory.rs @@ -203,7 +203,9 @@ impl Lock for InMemoryLock { /// Lazily creates one [`InMemoryLock`] per unique key and returns the same /// `Arc` for repeated lookups. An entry is evicted on unlock once it is idle /// and no handle beyond the map's own remains, so the map does not grow -/// unboundedly with every aggregate id ever locked. +/// unboundedly with every aggregate id ever locked. Clones share one lock +/// table. +#[derive(Clone)] pub struct InMemoryLockManager { locks: Arc>>>, } diff --git a/src/microsvc/error.rs b/src/microsvc/error.rs index e52a2bb23..9253dae3a 100644 --- a/src/microsvc/error.rs +++ b/src/microsvc/error.rs @@ -134,6 +134,12 @@ impl From for HandlerError { } impl HandlerError { + /// The command was refused by a rule: `reason` is reported to the caller + /// (HTTP 422). + pub fn rejected(reason: impl fmt::Display) -> Self { + Self::Rejected(reason.to_string()) + } + /// Return the opaque operator repair handle carried by a durably recorded /// terminal projector failure. pub fn projection_repair_handle(&self) -> Option<&ProjectionRepairHandle> { diff --git a/src/microsvc/guards.rs b/src/microsvc/guards.rs new file mode 100644 index 000000000..6cc65f35b --- /dev/null +++ b/src/microsvc/guards.rs @@ -0,0 +1,20 @@ +//! Command guards for the `guard:` slot of `command!` and +//! [`TypedRouteBuilder::guarded`](crate::microsvc::TypedRouteBuilder::guarded). +//! +//! A guard admits a session before the handler runs; a refused command is +//! answered without loading its aggregate. + +use crate::microsvc::CausalCommandContext; + +/// The session names a user (`x-user-id`, from dev headers or an OIDC +/// subject). +pub fn authenticated(ctx: &CausalCommandContext<'_, A>) -> bool { + ctx.user_id().is_ok() +} + +/// An [`authenticated`] user holding the engine role `role`. +pub fn role( + role: &'static str, +) -> impl Fn(&CausalCommandContext<'_, A>) -> bool + Send + Sync + 'static { + move |ctx| authenticated(ctx) && ctx.session().has_role(role) +} diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index f060592c9..05c3a5546 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -71,6 +71,7 @@ mod dependencies; pub(crate) use dependencies::CausalHostProjections; mod descriptor; mod error; +pub mod guards; pub(crate) mod lifecycle; mod message_router; mod projector; @@ -78,6 +79,7 @@ mod runtime; pub mod schedule; mod service; mod session; +mod stores; // Worker loops need a Tokio runtime (spawn/sleep); only compile when a feature // that enables the optional `tokio` dep is active (default feature set does not). #[cfg(feature = "runtime-tokio")] @@ -134,6 +136,13 @@ pub(crate) mod wait_path; pub use session::{ Session, ROLE_KEY, TRANSPORT_MESSAGE_ID_CLAIM, TRANSPORT_ROLE, TRANSPORT_USER_ID, USER_ID_KEY, }; +#[cfg(feature = "postgres")] +pub use stores::PostgresStores; +#[cfg(any(feature = "sqlite", feature = "postgres"))] +pub use stores::SqlStores; +#[cfg(feature = "sqlite")] +pub use stores::SqliteStores; +pub use stores::{AggregateDependencies, ServiceStores, StoreDependencies, Stores}; /// Maximum accepted HTTP request body size for the microsvc ingresses, in bytes /// (1 MiB). diff --git a/src/microsvc/service/defaults.rs b/src/microsvc/service/defaults.rs index 45efd7963..5d43d1e15 100644 --- a/src/microsvc/service/defaults.rs +++ b/src/microsvc/service/defaults.rs @@ -16,36 +16,28 @@ impl Routes<()> { Self::from_dependencies(()) } - /// Framework helper: wire an aggregate repository + read-model store without - /// application code naming `QueuedRepository` / `RepoReadModelDependencies`. + /// Start one aggregate's routes over a service's stores: commands load + /// and commit `A` through the locked event store and write read models + /// to the read-model store. /// - /// Product modules should start here, then register `typed_command` mounts. - pub fn for_aggregate( - repo: R, - locks: L, - read_models: S, - ) -> Routes< - RepoReadModelDependencies, A>, S>, - > + /// Product modules start here, then `mount` their commands: + /// + /// ```ignore + /// pub fn routes(stores: &St) -> Routes> { + /// Routes::for_aggregate(stores).mount(todo_domain::commands::create()) + /// } + /// ``` + pub fn for_aggregate( + stores: &St, + ) -> Routes> where - R: crate::GetStream + crate::TransactionalCommit + Clone + Send + Sync + 'static, - L: crate::LockManager + Clone + 'static, A: crate::Aggregate + Send + Sync + 'static, - S: HasReadModelStore + Send + Sync + 'static, - crate::QueuedRepository: Clone - + crate::AggregateBuilder - + HasOutboxStore - + crate::TransactionalCommit - + Send - + Sync - + 'static, - crate::AggregateRepository, A>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, + St: crate::microsvc::ServiceStores, { - use crate::{AggregateBuilder, Queueable}; + use crate::AggregateBuilder; Routes::new() - .with_repo(repo.queued_with(locks).aggregate::()) - .with_read_model_store(read_models) + .with_repo(stores.queued().aggregate::()) + .with_read_model_store(stores.read_models().clone()) } /// Wire a repository and a read-model store with no aggregate, for diff --git a/src/microsvc/stores.rs b/src/microsvc/stores.rs new file mode 100644 index 000000000..bd6da11c3 --- /dev/null +++ b/src/microsvc/stores.rs @@ -0,0 +1,209 @@ +//! The stores one service runs on, named once. +//! +//! A module's routes need an event store, a lock manager and a read-model +//! store, and the framework needs a long list of capabilities from each. +//! [`ServiceStores`] states that list once: a module is generic over one +//! `St: ServiceStores` and starts its routes with +//! [`Routes::for_aggregate`](crate::microsvc::Routes::for_aggregate). +//! [`Stores`] is the value a host builds from its backend. + +use crate::microsvc::dependencies::{ + CausalProjectionStore, CausalRepositoryBackend, HasOutboxStore, RepoReadModelDependencies, +}; +use crate::{ + AggregateRepository, GetStream, LockManager, QueuedRepository, ReadModelWritePlanStore, + RelationalReadModelQueryStore, +}; + +/// An event store, its locks and a read-model store: what one service runs +/// on. A host builds it once from its backend and hands it to every module. +#[derive(Clone, Debug)] +pub struct Stores { + /// Event store: streams, the command ledger and the outbox. + pub events: R, + /// Locks that serialize aggregate commands per stream. + pub locks: L, + /// Read-model store the projections write and GraphQL reads. + pub read_models: S, +} + +impl Stores { + /// Name the event store, locks and read-model store of one service. + pub fn new(events: R, locks: L, read_models: S) -> Self { + Self { + events, + locks, + read_models, + } + } +} + +/// Every capability a module's routes need from its stores, in one bound. +/// +/// Implemented for [`Stores`] whenever its parts are framework stores (in +/// memory, SQLite, Postgres, …); applications never implement it. +pub trait ServiceStores: Clone + Send + Sync + 'static { + /// The event store, for commands that own no stream + /// ([`Routes::for_stores`](crate::microsvc::Routes::for_stores)). + type Events: CausalRepositoryBackend + GetStream + HasOutboxStore; + /// The event store behind the locks, for aggregate commands. + type Queued: CausalRepositoryBackend + GetStream + HasOutboxStore; + /// The read-model store. + type ReadModels: CausalProjectionStore + ReadModelWritePlanStore + RelationalReadModelQueryStore; + + /// The event store. + fn events(&self) -> &Self::Events; + /// The event store serialized by the locks. + fn queued(&self) -> Self::Queued; + /// The read-model store. + fn read_models(&self) -> &Self::ReadModels; +} + +impl ServiceStores for Stores +where + R: CausalRepositoryBackend + GetStream + HasOutboxStore, + L: LockManager + Clone + 'static, + S: CausalProjectionStore + ReadModelWritePlanStore + RelationalReadModelQueryStore, + QueuedRepository: CausalRepositoryBackend + GetStream + HasOutboxStore, +{ + type Events = R; + type Queued = QueuedRepository; + type ReadModels = S; + + fn events(&self) -> &R { + &self.events + } + + fn queued(&self) -> QueuedRepository { + QueuedRepository::with_lock_manager(self.events.clone(), self.locks.clone()) + } + + fn read_models(&self) -> &S { + &self.read_models + } +} + +/// Route dependencies of one aggregate's commands over `St` +/// ([`Routes::for_aggregate`](crate::microsvc::Routes::for_aggregate)). +pub type AggregateDependencies = RepoReadModelDependencies< + AggregateRepository<::Queued, A>, + ::ReadModels, +>; + +/// Route dependencies of commands that own no stream over `St` +/// (`Routes::for_stores(stores.events().clone(), stores.read_models().clone())`). +pub type StoreDependencies = RepoReadModelDependencies< + AggregateRepository<::Events, ()>, + ::ReadModels, +>; + +#[cfg(feature = "postgres")] +pub use sql::PostgresStores; +#[cfg(any(feature = "sqlite", feature = "postgres"))] +pub use sql::SqlStores; +#[cfg(feature = "sqlite")] +pub use sql::SqliteStores; + +#[cfg(any(feature = "sqlite", feature = "postgres"))] +mod sql { + use super::{ServiceStores, Stores}; + use crate::bus::{Bus, BusConsumer}; + use crate::ReadModelCatalog; + use std::error::Error; + use std::future::Future; + + type BoxError = Box; + + /// [`Stores`] kept in one SQL database: one connection pool is the + /// event store, the read-model store, the locks and the bus. + /// + /// A host written once against `SqlStores` runs on SQLite + /// ([`SqliteStores`]) and Postgres ([`PostgresStores`]) alike. + pub trait SqlStores: ServiceStores + Sized { + /// The bus kept in the same database. + type Bus: Bus + BusConsumer + 'static; + + /// Connect, apply the framework migrations and create the bus tables. + fn connect(database_url: &str) -> impl Future> + Send; + + /// Create the tables of `catalog` (development and tests; production + /// applies generated migrations instead). + fn bootstrap_read_models( + &self, + catalog: &ReadModelCatalog, + ) -> impl Future> + Send; + + /// The bus, consuming as `group`. + fn bus(&self, group: &str) -> Self::Bus; + + /// Committed read-model changes, for GraphQL live queries. + fn read_model_changes(&self) -> tokio::sync::broadcast::Receiver; + + /// The database GraphQL queries read through, carrying the + /// repository identity that proves `Projected` commands update the + /// database GraphQL reads. + #[cfg(feature = "graphql")] + fn graphql_pool(&self) -> crate::graphql::GraphqlPoolSource; + } + + macro_rules! sql_stores { + ($(#[$doc:meta])* $alias:ident, $repo:ty, $locks:ty, $bus:ty) => { + $(#[$doc])* + pub type $alias = Stores<$repo, $locks, $repo>; + + impl SqlStores for $alias { + type Bus = $bus; + + async fn connect(database_url: &str) -> Result { + let repo = <$repo>::connect_and_migrate(database_url).await?; + <$bus>::new(repo.pool().clone()).ensure_tables().await?; + let locks = <$locks>::new(repo.pool().clone()); + Ok(Stores::new(repo.clone(), locks, repo)) + } + + async fn bootstrap_read_models( + &self, + catalog: &ReadModelCatalog, + ) -> Result<(), BoxError> { + self.read_models + .bootstrap_table_schema_for_dev(&catalog.table_registry()?) + .await?; + Ok(()) + } + + fn bus(&self, group: &str) -> $bus { + <$bus>::new(self.events.pool().clone()).group(group) + } + + fn read_model_changes( + &self, + ) -> tokio::sync::broadcast::Receiver { + self.read_models.read_model_changes() + } + + #[cfg(feature = "graphql")] + fn graphql_pool(&self) -> crate::graphql::GraphqlPoolSource { + (&self.read_models).into() + } + } + }; + } + + #[cfg(feature = "sqlite")] + sql_stores!( + /// Every store of a service in one SQLite database. + SqliteStores, + crate::SqliteRepository, + crate::SqliteLockManager, + crate::bus::SqliteBus + ); + + #[cfg(feature = "postgres")] + sql_stores!( + /// Every store of a service in one Postgres database. + PostgresStores, + crate::PostgresRepository, + crate::PostgresLockManager, + crate::bus::PostgresBus + ); +} diff --git a/src/projection/local_mounts.rs b/src/projection/local_mounts.rs index 2dbc16bf6..cee53a747 100644 --- a/src/projection/local_mounts.rs +++ b/src/projection/local_mounts.rs @@ -17,8 +17,6 @@ use crate::projection::placement::{ PROJECTION_PARTITION_CODEC_VERSION, }; use crate::projection_protocol::ProjectorTopologyId; -use crate::table::TableSchema; -use crate::RelationalReadModel; use sha2::{Digest, Sha256}; const LOCAL_TOPOLOGY_DIGEST_DOMAIN: &[u8] = b"distributed.local-projection-topology\0"; @@ -45,20 +43,36 @@ pub struct LocalProjectionMounts { } impl LocalProjectionMounts { - pub fn projector(&self, owner: &str) -> Option { - self.eventual - .iter() - .find(|mount| mount.owner == owner) - .map(|mount| mount.projector.clone()) + /// Start mounting projection descriptors for `service_id`, consuming the + /// stable domain event stream `domain_source` (e.g. `ordered-domain-events`). + pub fn builder( + service_id: impl Into, + domain_source: impl Into, + ) -> LocalProjectionMountsBuilder { + LocalProjectionMountsBuilder::new(service_id, domain_source) } - pub fn direct_projection(&self, owner: &str) -> Option { - self.direct + /// The eventual projector compiled from `descriptor`. + /// + /// # Panics + /// + /// When `descriptor` was not mounted with + /// [`eventual`](LocalProjectionMountsBuilder::eventual): a composition + /// mistake, reported at startup with the projection's name. + pub fn projector(&self, descriptor: ProjectionDescriptor) -> SurfaceProjector { + self.eventual .iter() - .find(|mount| mount.owner == owner) - .map(|mount| mount.projection.clone()) + .find(|mount| mount.owner == descriptor.name()) + .map(|mount| mount.projector.clone()) + .unwrap_or_else(|| { + panic!( + "projection `{}` is not mounted eventually; add `.eventual(..)` for it to the LocalProjectionMountsBuilder", + descriptor.name() + ) + }) } + /// Every mounted projection as a Surface owner, eventual then direct. pub fn all_owners(&self) -> Vec { let mut owners = Vec::new(); for mount in &self.eventual { @@ -71,130 +85,138 @@ impl LocalProjectionMounts { } } -struct PendingEventual { - owner: String, - epoch: String, - binding: ProjectionBinding, - modeled_factory: Box< - dyn Fn( - &ProjectionCatalog, - &ActiveProjectionBindings, - &ProjectionBinding, - ) -> Result - + Send - + Sync, - >, -} +type ModeledFactory = Box< + dyn Fn( + &ProjectionCatalog, + &ActiveProjectionBindings, + &ProjectionBinding, + ) -> Result + + Send + + Sync, +>; -struct PendingDirect { +struct Pending { owner: String, epoch: String, binding: ProjectionBinding, - modeled_factory: Box< - dyn Fn( - &ProjectionCatalog, - &ActiveProjectionBindings, - &ProjectionBinding, - ) -> Result - + Send - + Sync, - >, + modeled_factory: ModeledFactory, } -/// Builder that materializes a shared catalog and Surface mounts for local hosting. +/// Builder that materializes a shared catalog and Surface mounts for local +/// hosting. +/// +/// Each projection is mounted from its `projection!` descriptor alone: the +/// owner is the descriptor's `name`, the binding epoch its `epoch` and the +/// outputs its `model`, so no identity is restated. Errors are kept until +/// [`build`](Self::build). pub struct LocalProjectionMountsBuilder { service_id: String, - source: ProjectionSourceBinding, - eventual: Vec, - direct: Vec, + source: Result, + eventual: Vec, + direct: Vec, + errors: Vec, } impl LocalProjectionMountsBuilder { /// `domain_source` is a stable domain event stream name (e.g. `ordered-domain-events`). - pub fn new( - service_id: impl Into, - domain_source: impl Into, - ) -> Result { + pub fn new(service_id: impl Into, domain_source: impl Into) -> Self { let service_id = service_id.into(); let source = ProjectionSourceBinding::try_new(format!("{service_id}-domain"), domain_source, 1) - .map_err(|error| error.to_string())?; - Ok(Self { + .map_err(|error| error.to_string()); + Self { service_id, source, eventual: Vec::new(), direct: Vec::new(), - }) + errors: Vec::new(), + } } - /// Register an eventual projection program targeting model `M`. - pub fn eventual_model( - mut self, - owner: impl Into, - descriptor: ProjectionDescriptor, - epoch: impl Into, - ) -> Result + /// Mount `descriptor` as an eventual projection (ordered domain-event + /// delivery). + pub fn eventual(mut self, descriptor: ProjectionDescriptor) -> Self where - M: RelationalReadModel, D: Copy + 'static, { - let owner = owner.into(); - let epoch = epoch.into(); - let digest = stable_topology_digest(&owner); - let binding = ProjectionBinding::materialize_eventual( - descriptor.eventual(), - self.source.clone(), - ProjectionOwner::try_new(owner.clone()).map_err(|e| e.to_string())?, - "distributed-projection-partition", - PROJECTION_PARTITION_CODEC_VERSION, - vec![projection_output_for::()?], - Vec::new(), - Some(physical_topology(&owner, digest)), - ) - .map_err(|error| error.to_string())?; - self.eventual.push(PendingEventual { - owner, - epoch, - binding, - modeled_factory: Box::new(move |catalog, active, binding| { - SurfaceModeledProjection::try_from_descriptor( - descriptor, - catalog, - active, - binding.id(), - ) - }), + let pending = self.pending(descriptor, |source, owner, outputs, topology| { + ProjectionBinding::materialize_eventual( + descriptor.eventual(), + source, + owner, + "distributed-projection-partition", + PROJECTION_PARTITION_CODEC_VERSION, + outputs, + Vec::new(), + Some(topology), + ) + .map_err(|error| error.to_string()) }); - Ok(self) + match pending { + Ok(pending) => self.eventual.push(pending), + Err(error) => self.errors.push(error), + } + self } - /// Register a direct projection program targeting model `M`. - pub fn direct_model( + /// Mount `descriptor` as a direct projection, sealed in the command's own + /// transaction. + pub fn direct( mut self, - owner: impl Into, descriptor: ProjectionDescriptor, - epoch: impl Into, - ) -> Result - where - M: RelationalReadModel, - { - let owner = owner.into(); - let epoch = epoch.into(); - let digest = stable_topology_digest(&owner); - let binding = ProjectionBinding::materialize_direct( - descriptor.direct(), - self.source.clone(), + ) -> Self { + let pending = self.pending(descriptor, |source, owner, outputs, topology| { + ProjectionBinding::materialize_direct( + descriptor.direct(), + source, + owner, + "distributed-projection-partition", + PROJECTION_PARTITION_CODEC_VERSION, + outputs, + Vec::new(), + Some(topology), + ) + .map_err(|error| error.to_string()) + }); + match pending { + Ok(pending) => self.direct.push(pending), + Err(error) => self.errors.push(error), + } + self + } + + fn pending( + &self, + descriptor: ProjectionDescriptor, + materialize: impl FnOnce( + ProjectionSourceBinding, + ProjectionOwner, + Vec, + ProjectionPhysicalTopology, + ) -> Result, + ) -> Result { + let owner = descriptor.name().to_string(); + let source = self.source.clone()?; + let outputs = descriptor + .output_inventory() + .map_err(|error| format!("projection `{owner}` outputs: {error}"))? + .models + .into_iter() + .map(|output| { + ProjectionOutput::try_new(output.model, output.storage, output.schema) + .map_err(|error| format!("projection `{owner}` output: {error}")) + }) + .collect::, _>>()?; + let binding = materialize( + source, ProjectionOwner::try_new(owner.clone()).map_err(|e| e.to_string())?, - "distributed-projection-partition", - PROJECTION_PARTITION_CODEC_VERSION, - vec![projection_output_for::()?], - Vec::new(), - Some(physical_topology(&owner, digest)), + outputs, + physical_topology(&owner, stable_topology_digest(&owner)), ) - .map_err(|error| error.to_string())?; - self.direct.push(PendingDirect { + .map_err(|error| format!("projection `{owner}`: {error}"))?; + Ok(Pending { owner, - epoch, + epoch: descriptor.epoch().to_string(), binding, modeled_factory: Box::new(move |catalog, active, binding| { SurfaceModeledProjection::try_from_descriptor( @@ -204,26 +226,26 @@ impl LocalProjectionMountsBuilder { binding.id(), ) }), - }); - Ok(self) + }) } + /// Compile every mounted projection into one catalog with its epochs + /// active, then package the Surface mounts. + /// + /// # Errors + /// + /// The first mount or catalog error, naming its projection. pub fn build(self) -> Result { - let mut bindings = Vec::new(); - for entry in &self.eventual { - bindings.push(entry.binding.clone()); - } - for entry in &self.direct { - bindings.push(entry.binding.clone()); - } - let catalog = ProjectionCatalog::try_new(bindings).map_err(|e| e.to_string())?; - let mut activations = Vec::new(); - for entry in &self.eventual { - activations.push(activation(&entry.binding, &entry.epoch, &self.service_id)?); - } - for entry in &self.direct { - activations.push(activation(&entry.binding, &entry.epoch, &self.service_id)?); + if let Some(error) = self.errors.into_iter().next() { + return Err(error); } + let pending = || self.eventual.iter().chain(&self.direct); + let catalog = + ProjectionCatalog::try_new(pending().map(|entry| entry.binding.clone()).collect()) + .map_err(|e| e.to_string())?; + let activations = pending() + .map(|entry| activation(&entry.binding, &entry.epoch, &self.service_id)) + .collect::, _>>()?; let active = catalog .activate(activations, None) .map_err(|e| e.to_string())?; @@ -261,12 +283,6 @@ fn activation( )) } -fn projection_output_for() -> Result { - let schema: TableSchema = M::schema().clone(); - ProjectionOutput::try_new(schema.model_name.clone(), schema.table_name.clone(), schema) - .map_err(|e| e.to_string()) -} - fn physical_topology(name: &str, digest: [u8; 32]) -> ProjectionPhysicalTopology { ProjectionPhysicalTopology::from_protocol( &ProjectorTopologyId::new(1, name, digest).expect("canonical local projection topology"), diff --git a/src/projection/source_snapshot_tests.rs b/src/projection/source_snapshot_tests.rs index b2ce77ca4..00d338e01 100644 --- a/src/projection/source_snapshot_tests.rs +++ b/src/projection/source_snapshot_tests.rs @@ -560,13 +560,11 @@ fn source_snapshots_reject_direct_materialization() { } fn rebuild_projector() -> crate::graphql::SurfaceProjector { - let mounts = crate::LocalProjectionMountsBuilder::new("snapshot-test", "events") - .unwrap() - .eventual_model::("rebuild-test", SNAPSHOTS, "snapshot-v1") - .unwrap() + crate::LocalProjectionMounts::builder("snapshot-test", "events") + .eventual(SNAPSHOTS) .build() - .unwrap(); - mounts.projector("rebuild-test").unwrap() + .unwrap() + .projector(SNAPSHOTS) } async fn rebuild_matrix(store: &impl ProjectionProtocolStore) { @@ -886,17 +884,11 @@ async fn snapshot_rebuild_original_private_log_coverage() { #[tokio::test] async fn snapshot_rebuild_external_sparse_members_and_mixed_origins() { let store = crate::InMemoryRepository::new(); - let mounts = crate::LocalProjectionMountsBuilder::new("external-test", "events") - .unwrap() - .eventual_model::( - "external-rebuild", - EXTERNAL_SNAPSHOTS, - "external-rebuild-v1", - ) - .unwrap() + let projector = crate::LocalProjectionMounts::builder("external-test", "events") + .eventual(EXTERNAL_SNAPSHOTS) .build() - .unwrap(); - let projector = mounts.projector("external-rebuild").unwrap(); + .unwrap() + .projector(EXTERNAL_SNAPSHOTS); async fn bootstrap( store: &crate::InMemoryRepository, projector: &crate::graphql::SurfaceProjector, diff --git a/tests/core/sourced/flat_preview.rs b/tests/core/sourced/flat_preview.rs index 39ea836b4..bedc5ae4d 100644 --- a/tests/core/sourced/flat_preview.rs +++ b/tests/core/sourced/flat_preview.rs @@ -187,7 +187,7 @@ mod client_contract { use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; use distributed::{ - AggregateRepository, InMemoryRepository, LocalProjectionMountsBuilder, Mutation, + AggregateRepository, InMemoryRepository, LocalProjectionMounts, Mutation, RelationalReadModel, }; use serde::{Deserialize, Serialize}; @@ -288,10 +288,8 @@ mod client_contract { compile_client, ClientCompileInput, ClientDocument, ClientSurfaceIdentity, }; - let mounts = LocalProjectionMountsBuilder::new("members", "events") - .unwrap() - .eventual_model::("flat_members", MEMBERS, MEMBERS.epoch()) - .unwrap() + let mounts = LocalProjectionMounts::builder("members", "events") + .eventual(MEMBERS) .build() .unwrap(); let mut previous = None; @@ -315,7 +313,7 @@ mod client_contract { &SurfaceOptions::postgres(), ) .unwrap() - .with_projectors([mounts.projector("flat_members").unwrap()]) + .with_projectors([mounts.projector(MEMBERS)]) .unwrap() .with_service(&service) .unwrap(); @@ -390,10 +388,8 @@ mod client_contract { #[test] fn an_event_mode_known_constant_reaches_projection_slots_without_applies() { - let mounts = LocalProjectionMountsBuilder::new("reviews", "events") - .unwrap() - .eventual_model::("flat_reviews", REVIEWS, REVIEWS.epoch()) - .unwrap() + let mounts = LocalProjectionMounts::builder("reviews", "events") + .eventual(REVIEWS) .build() .unwrap(); let service = Service::new().named("reviews").routes( @@ -412,7 +408,7 @@ mod client_contract { &SurfaceOptions::postgres(), ) .unwrap() - .with_projectors([mounts.projector("flat_reviews").unwrap()]) + .with_projectors([mounts.projector(REVIEWS)]) .unwrap() .with_service(&service) .unwrap(); @@ -438,10 +434,8 @@ mod client_contract { #[test] fn a_declared_event_constant_reaches_generated_projection_slots() { - let mounts = LocalProjectionMountsBuilder::new("reviews", "events") - .unwrap() - .eventual_model::("flat_reviews", REVIEWS, REVIEWS.epoch()) - .unwrap() + let mounts = LocalProjectionMounts::builder("reviews", "events") + .eventual(REVIEWS) .build() .unwrap(); let service = Service::new().named("reviews").routes( @@ -467,7 +461,7 @@ mod client_contract { &SurfaceOptions::postgres(), ) .unwrap() - .with_projectors([mounts.projector("flat_reviews").unwrap()]) + .with_projectors([mounts.projector(REVIEWS)]) .unwrap() .with_service(&service) .unwrap(); diff --git a/tests/e2e-celld/crates/blob-service/src/bounds.rs b/tests/e2e-celld/crates/blob-service/src/bounds.rs deleted file mode 100644 index dbaf42fe0..000000000 --- a/tests/e2e-celld/crates/blob-service/src/bounds.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, LockManager, ReadModelWritePlanStore, RelationalReadModelQueryStore, - TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait Locks: LockManager + Clone + 'static {} -impl Locks for T where T: LockManager + Clone + 'static {} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-celld/crates/blob-service/src/lib.rs b/tests/e2e-celld/crates/blob-service/src/lib.rs index 8da26b142..badc4ac11 100644 --- a/tests/e2e-celld/crates/blob-service/src/lib.rs +++ b/tests/e2e-celld/crates/blob-service/src/lib.rs @@ -1,6 +1,5 @@ //! Blob Atomic command service crate (in-process; not a cell). -mod bounds; mod routes; -pub use routes::{routes, MODULE_ID}; +pub use routes::routes; diff --git a/tests/e2e-celld/crates/blob-service/src/routes.rs b/tests/e2e-celld/crates/blob-service/src/routes.rs index ed2c5d85b..b9b9252e8 100644 --- a/tests/e2e-celld/crates/blob-service/src/routes.rs +++ b/tests/e2e-celld/crates/blob-service/src/routes.rs @@ -1,43 +1,12 @@ -//! Blob game module: Atomic command mounts (direct projection seal). +//! Blob game module: Atomic command mounts. Their `BLOB_GAMES` projection is +//! direct: each command seals its row in its own transaction. use blob_domain::BlobGame; -use distributed::graphql::SurfaceDirectProjection; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; - -use crate::bounds::{EventStore, Locks, ReadStore}; - -/// Logical module id for composition inventories. -pub const MODULE_ID: &str = "blob"; - -type BlobRoutes = - Routes, BlobGame>, S>>; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; /// Mount blob Atomic commands from blob-domain. -pub fn routes( - repo: R, - locks: L, - read_models: S, - _blob_direct: SurfaceDirectProjection, -) -> BlobRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, BlobGame>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let _ = _blob_direct; - Routes::for_aggregate::(repo, locks, read_models) +pub fn routes(stores: &St) -> Routes> { + Routes::for_aggregate(stores) .mount(blob_domain::commands::start()) .mount(blob_domain::commands::move_dir()) .mount(blob_domain::commands::start_level()) diff --git a/tests/e2e-celld/crates/chat-service/src/bounds.rs b/tests/e2e-celld/crates/chat-service/src/bounds.rs deleted file mode 100644 index dbaf42fe0..000000000 --- a/tests/e2e-celld/crates/chat-service/src/bounds.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, LockManager, ReadModelWritePlanStore, RelationalReadModelQueryStore, - TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait Locks: LockManager + Clone + 'static {} -impl Locks for T where T: LockManager + Clone + 'static {} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-celld/crates/chat-service/src/handlers/events/mod.rs b/tests/e2e-celld/crates/chat-service/src/handlers/events/mod.rs deleted file mode 100644 index 561692bf9..000000000 --- a/tests/e2e-celld/crates/chat-service/src/handlers/events/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod project_chat_messages; diff --git a/tests/e2e-celld/crates/chat-service/src/handlers/events/project_chat_messages.rs b/tests/e2e-celld/crates/chat-service/src/handlers/events/project_chat_messages.rs deleted file mode 100644 index 89d15e440..000000000 --- a/tests/e2e-celld/crates/chat-service/src/handlers/events/project_chat_messages.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Apply the ChatMessages projection for matching domain events. - -use distributed::microsvc::{CausalProjectorContext, HandlerError, ModeledProjection}; -use e2e_projections::CHAT_MESSAGES; - -pub async fn handle( - context: CausalProjectorContext, - projection: ModeledProjection, -) -> Result<(), HandlerError> { - projection.apply(CHAT_MESSAGES, &context).await -} diff --git a/tests/e2e-celld/crates/chat-service/src/handlers/mod.rs b/tests/e2e-celld/crates/chat-service/src/handlers/mod.rs deleted file mode 100644 index a9970c28f..000000000 --- a/tests/e2e-celld/crates/chat-service/src/handlers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod events; diff --git a/tests/e2e-celld/crates/chat-service/src/lib.rs b/tests/e2e-celld/crates/chat-service/src/lib.rs index 7e7e43b13..dd711e10e 100644 --- a/tests/e2e-celld/crates/chat-service/src/lib.rs +++ b/tests/e2e-celld/crates/chat-service/src/lib.rs @@ -4,10 +4,8 @@ //! `chat.post` through [`distributed::cell_host::CelldCommandHost`]. GraphQL //! `@live` stays here. -mod bounds; -mod handlers; mod host; mod routes; pub use host::celld_route; -pub use routes::{routes, MODULE_ID}; +pub use routes::routes; diff --git a/tests/e2e-celld/crates/chat-service/src/routes.rs b/tests/e2e-celld/crates/chat-service/src/routes.rs index 9389dfc37..68e33ac48 100644 --- a/tests/e2e-celld/crates/chat-service/src/routes.rs +++ b/tests/e2e-celld/crates/chat-service/src/routes.rs @@ -1,42 +1,16 @@ -//! Chat room messages + eventual projector. +//! Chat room messages + eventual projection. use chat_domain::ChatMessage; -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; +use distributed::LocalProjectionMounts; +use e2e_projections::CHAT_MESSAGES; -use crate::bounds::{EventStore, Locks, ReadStore}; -use crate::handlers; - -pub const MODULE_ID: &str = "chat"; - -type ChatRoutes = - Routes, ChatMessage>, S>>; - -pub fn routes( - repo: R, - locks: L, - read_models: S, - chat_projector: SurfaceProjector, -) -> ChatRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, ChatMessage>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - Routes::for_aggregate::(repo, locks, read_models) +/// Mount chat commands and the chat projection. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(chat_domain::commands::post()) - .modeled_projector(chat_projector) - .handle(handlers::events::project_chat_messages::handle) + .consume_projection(projections.projector(CHAT_MESSAGES)) } diff --git a/tests/e2e-celld/crates/graphql-service/src/application.rs b/tests/e2e-celld/crates/graphql-service/src/application.rs index 96dc01d18..48e5d1443 100644 --- a/tests/e2e-celld/crates/graphql-service/src/application.rs +++ b/tests/e2e-celld/crates/graphql-service/src/application.rs @@ -1,33 +1,41 @@ //! e2e-ui application composition root. //! -//! This is the review-visible product declaration: surface identities, module -//! inventory, and re-exports of the composed host APIs. Infrastructure -//! (dialect, outbox, OIDC serve) stays in `host`; handlers stay in modules. - -use crate::modules::compose; -use e2e_celld_blob as blob; -use e2e_celld_chat as chat; -use e2e_celld_identity as identity; -use e2e_celld_todo as todo; - -/// Stable normal-application surface shared by user and admin sessions. -pub const DISTRIBUTED_CLIENT_SURFACE: &str = "e2e-ui"; -/// Stable elevated surface for routes that intentionally include admin-only fields. -pub const DISTRIBUTED_ADMIN_CLIENT_SURFACE: &str = "e2e-ui-admin"; -/// Unauthenticated public surface (lobby message peek). -pub const DISTRIBUTED_PUBLIC_CLIENT_SURFACE: &str = "e2e-ui-public"; +//! This is the review-visible product declaration: the application name and +//! its generated client surfaces. Modules are the Service's command +//! namespaces (`modules::compose`); infrastructure stays in `host`. /// Logical application name used for manifest / plan identity. pub const E2E_UI_APPLICATION: &str = "e2e-ui"; -/// Explicit module identities owned by the e2e application. -pub const E2E_UI_MODULE_IDS: &[&str] = compose::MODULE_IDS; +/// One generated client surface: who may open it, and whose grants shape its +/// schema. Declared once; the GraphQL engine registers it and the client +/// export selects it. +#[derive(Clone, Copy, Debug)] +pub struct ClientSurface { + pub name: &'static str, + pub eligible_roles: &'static [&'static str], + pub schema_roles: &'static [&'static str], +} + +/// Normal-application surface shared by user and admin sessions. +pub const CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui", + eligible_roles: &["admin", "user"], + schema_roles: &["user"], +}; +/// Elevated surface for routes that intentionally include admin-only fields. +pub const ADMIN_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-admin", + eligible_roles: &["admin"], + schema_roles: &["admin"], +}; +/// Unauthenticated public surface (lobby message peek). +pub const PUBLIC_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-public", + eligible_roles: &["anonymous"], + schema_roles: &["anonymous"], +}; -/// Compile-time proof that module inventory matches bounded-context crates. -#[allow(dead_code)] -pub const MODULE_DECLARATIONS: &[(&str, &str)] = &[ - (todo::MODULE_ID, "todo commands + projector"), - (chat::MODULE_ID, "chat commands + projector"), - (blob::MODULE_ID, "blob Atomic commands"), - (identity::MODULE_ID, "Zitadel ingress + AuthUsers projector"), -]; +/// Every client surface the application serves. +pub const CLIENT_SURFACES: [ClientSurface; 3] = + [CLIENT_SURFACE, ADMIN_CLIENT_SURFACE, PUBLIC_CLIENT_SURFACE]; diff --git a/tests/e2e-celld/crates/graphql-service/src/bounds.rs b/tests/e2e-celld/crates/graphql-service/src/bounds.rs deleted file mode 100644 index dbaf42fe0..000000000 --- a/tests/e2e-celld/crates/graphql-service/src/bounds.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, LockManager, ReadModelWritePlanStore, RelationalReadModelQueryStore, - TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait Locks: LockManager + Clone + 'static {} -impl Locks for T where T: LockManager + Clone + 'static {} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-celld/crates/graphql-service/src/host.rs b/tests/e2e-celld/crates/graphql-service/src/host.rs index 78f8a5e34..c683eba4b 100644 --- a/tests/e2e-celld/crates/graphql-service/src/host.rs +++ b/tests/e2e-celld/crates/graphql-service/src/host.rs @@ -4,7 +4,6 @@ //! and Eventual projectors stay in this process. use std::sync::Arc; -use std::time::Duration; use distributed::bus::celld_queue_relay_handler; use distributed::bus::NatsBus; @@ -12,15 +11,14 @@ use distributed::cell_host::{CelldCommandHost, InternalHttpSecret}; use distributed::command_dispatch::SharedCommandHost; use distributed::graphql::IdentityConfig; use distributed::microsvc::{ - spawn_outbox_publish_loop, spawn_service_consumer_loop, LifecycleGate, Service, + spawn_service_consumer_loop, LifecycleGate, PostgresStores, Service, SqlStores, }; use distributed::BusPublisher; -use distributed::{PostgresLockManager, PostgresRepository}; use crate::http::serve; use crate::{ - build_graphql_engine, build_service, distributed_manifest, spawn_scrape_loop, - ZitadelScrapeConfig, E2E_UI_APPLICATION, + build_graphql_engine, build_service, read_models, spawn_scrape_loop, ZitadelScrapeConfig, + E2E_UI_APPLICATION, }; const BUS_GROUP: &str = "e2e-celld"; @@ -55,21 +53,24 @@ async fn run_postgres( options: HostOptions, celld_url: String, ) -> Result<(), Box> { - let repo = PostgresRepository::connect_and_migrate(database_url).await?; - let registry = distributed_manifest() - .table_registry() - .map_err(|e| format!("manifest: {e}"))?; - repo.bootstrap_table_schema_for_dev(®istry).await?; - let locks = PostgresLockManager::new(repo.pool().clone()); + let stores = PostgresStores::connect(database_url).await?; + stores + .bootstrap_read_models(read_models().catalog()) + .await?; let nats = connect_nats(&options.nats_url).await?; - let change_rx = repo.read_model_changes(); + let change_rx = stores.read_model_changes(); // Under `distributed dev`, only the active generation may write. let lifecycle = LifecycleGate::from_env(); - let service = build_service(repo.clone(), locks.clone(), repo.clone()) + let service = build_service(&stores) .with_lifecycle(lifecycle.clone()) .with_bus(nats.clone()); - let gql = build_graphql_engine(&repo, &service, options.identity.clone(), Some(change_rx))?; + let gql = build_graphql_engine( + stores.graphql_pool(), + &service, + options.identity.clone(), + Some(change_rx), + )?; let service = Arc::new(service.try_with_graphql(gql)?); let publisher = BusPublisher::new(Arc::new(nats.clone())); let celld_host = celld_command_host( @@ -80,19 +81,11 @@ async fn run_postgres( let queue_relay = celld_queue_relay_handler(publisher); let host: SharedCommandHost = Arc::new(celld_host); - spawn_outbox_publish_loop( - repo.outbox_store(), - Arc::new(nats.clone()), - "e2e-celld", - Duration::from_secs(30), - 5, - ); + // `with_bus` also drains the outbox, so the consumer is the only loop. { - let repo = repo.clone(); - let locks = locks.clone(); let nats = nats.clone(); spawn_service_consumer_loop(move || { - build_service(repo.clone(), locks.clone(), repo.clone()) + build_service(&stores) .with_lifecycle(lifecycle.clone()) .with_bus(nats.clone()) }); diff --git a/tests/e2e-celld/crates/graphql-service/src/lib.rs b/tests/e2e-celld/crates/graphql-service/src/lib.rs index adfd1584e..3ff90a7fb 100644 --- a/tests/e2e-celld/crates/graphql-service/src/lib.rs +++ b/tests/e2e-celld/crates/graphql-service/src/lib.rs @@ -4,21 +4,20 @@ //! in-process via their service crates. Domain crates are the e2e-ui ones. mod application; -mod bounds; mod host; 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, + ClientSurface, ADMIN_CLIENT_SURFACE, CLIENT_SURFACE, CLIENT_SURFACES, E2E_UI_APPLICATION, + PUBLIC_CLIENT_SURFACE, }; pub use e2e_celld_identity::{spawn_scrape_loop, ZitadelScrapeConfig}; -pub use e2e_readmodels::distributed_manifest; +pub use e2e_readmodels::read_models; pub use host::{run, HostOptions}; pub use modules::compose::build_service; pub use modules::graphql::{ - application_manifest, build_graphql_engine, dev_identity, distributed_admin_client_surface, - distributed_client_surface, distributed_public_client_surface, identity_from_env, - oidc_bearer_config, + application, application_manifest, build_graphql_engine, dev_identity, + distributed_admin_client_surface, distributed_client_surface, + distributed_public_client_surface, identity_from_env, oidc_bearer_config, }; diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs b/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs index e23dbe448..6415658c9 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs @@ -1,78 +1,33 @@ //! Compose bounded-context modules into one e2e-ui Service. -use blob_domain::BlobGame; -use chat_domain::ChatMessage; -use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Service}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; -use todo_domain::Todo; +use distributed::microsvc::{Service, ServiceStores}; -use crate::bounds::{EventStore, Locks, ReadStore}; -use crate::modules::projections; +use crate::modules::projections::projections; +use crate::E2E_UI_APPLICATION; use e2e_celld_blob as blob; use e2e_celld_chat as chat; use e2e_celld_identity as identity; use e2e_celld_identity::handlers::ingestors::{zitadel, zitadel_scrape}; use e2e_celld_todo as todo; -/// Explicit module inventory for the celld example (same ids as e2e-ui so the UI client matches). -pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, - chat::MODULE_ID, - blob::MODULE_ID, - identity::MODULE_ID, -]; - /// Compose todo + chat + blob + identity into one Service. /// /// This is the review-visible application wiring: list modules, do not invent -/// infrastructure. Dialect runners and workers live in `host`. -pub fn build_service(repo: R, locks: L, read_models: S) -> Service -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, Todo>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository, ChatMessage>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository, BlobGame>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let projections = projections::projection_owners(); - let todos = todo::routes( - repo.clone(), - locks.clone(), - read_models.clone(), - projections.todo, - ); - let chat = chat::routes( - repo.clone(), - locks.clone(), - read_models.clone(), - projections.chat, - ); - let blob = blob::routes(repo.clone(), locks, read_models.clone(), projections.blob); - let identity = identity::routes(repo, read_models, projections.auth); +/// infrastructure. The application's modules are the command namespaces +/// (`todo.*`, `chat.*`, `blob.*`, `zitadel.*`); the host lives in `host`. +pub fn build_service(stores: &St) -> Service { + let projections = projections(); // GraphQL-only public write surface. POST /todo.* stays 404 (suite T0). // Zitadel Action ingress is the identity crate: its two commands are // exposed through edges that check the shared secret and run as the // ingestor (`http::serve` also requires the cell internal secret). Service::new() - .named("e2e-ui") - .routes(todos) - .routes(chat) - .routes(blob) - .routes(identity) + .named(E2E_UI_APPLICATION) + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections)) .with_http_command(zitadel::COMMAND, zitadel::http_edge) .with_http_command(zitadel_scrape::COMMAND, zitadel_scrape::http_edge) } diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs index 1d7ae8a10..ce5a54930 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs @@ -1,38 +1,25 @@ -use std::sync::Arc; - -use distributed::application::CommandDefinition; use distributed::graphql::{ build_surface, surface_for_application, DistributedClientSurfaceExport, GraphqlEngine, GraphqlPoolSource, IdentityConfig, OidcConfig, Surface, SurfaceOptions, }; -use distributed::microsvc::Service; +use distributed::microsvc::{Service, Stores}; use distributed::{ - Application, ApplicationManifest, InMemoryLockManager, InMemoryRepository, LockError, - LockManager, Module, SurfaceSpec, + Application, ApplicationError, ApplicationManifest, InMemoryLockManager, InMemoryRepository, + SurfaceSpec, }; -use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; +use e2e_readmodels::read_models; use crate::application::{ - DISTRIBUTED_ADMIN_CLIENT_SURFACE, DISTRIBUTED_CLIENT_SURFACE, - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, E2E_UI_APPLICATION, E2E_UI_MODULE_IDS, + ClientSurface, ADMIN_CLIENT_SURFACE, CLIENT_SURFACE, CLIENT_SURFACES, E2E_UI_APPLICATION, + PUBLIC_CLIENT_SURFACE, }; -use crate::modules::projections; +use crate::modules::compose::build_service; +use crate::modules::projections::projections; // Stable only for this local copyable fixture. Real deployments must inject // their own per-deployment key rather than copying this development value. const E2E_PROTOCOL_TOKEN_KEY: [u8; 32] = [0xe2; 32]; -#[derive(Clone, Default)] -pub(crate) struct ClientSurfaceLocks(Arc); - -impl LockManager for ClientSurfaceLocks { - type Lock = distributed::InMemoryLock; - - fn get_lock(&self, id: &str) -> Result, LockError> { - self.0.get_lock(id) - } -} - /// GraphQL over todos + chat + blob + AuthUsers. pub fn build_graphql_engine( pool: impl Into, @@ -50,151 +37,92 @@ pub(crate) fn build_graphql_engine_with_graphiql( change_rx: Option>, graphiql: bool, ) -> Result { - let projections = projections::projection_owners(); let mut b = GraphqlEngine::builder(pool) .protocol_token_key(E2E_PROTOCOL_TOKEN_KEY) .roles(&["user", "admin", "anonymous"]) - .client_application_surface(DISTRIBUTED_CLIENT_SURFACE, ["admin", "user"], ["user"]) - .client_application_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, ["admin"], ["admin"]) - .client_application_surface( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - ["anonymous"], - ["anonymous"], - ) - .model::(Todos::permissions()) - .model::(ChatMessages::permissions()) - .model::(BlobGames::permissions()) - .model::(AuthUsers::permissions()) + .read_models(&read_models()) .service(service) - .client_projection_owners([ - projections.todo.into(), - projections.chat.into(), - projections.blob.into(), - projections.auth.into(), - ]) + .client_projection_owners(projections().all_owners()) .identity(identity) .graphiql(graphiql); + for surface in CLIENT_SURFACES { + b = b.client_application_surface( + surface.name, + surface.eligible_roles.iter().copied(), + surface.schema_roles.iter().copied(), + ); + } if let Some(rx) = change_rx { b = b.change_stream(rx); } b.build().map_err(|e| e.to_string()) } -fn pool_free_client_surface(application: &str, roles: &[&str]) -> DistributedClientSurfaceExport { - pool_free_client_surface_contract(application, roles, roles) +/// The application's full Surface: every read model, projection and command. +fn full_surface(service: &Service) -> Result { + build_surface(&read_models().catalog().tables, &SurfaceOptions::sqlite()) + .and_then(|surface| surface.with_projection_owners(projections().all_owners())) + .and_then(|surface| surface.with_service(service)) + .map_err(ApplicationError::InvalidSpec) } -fn pool_free_client_surface_contract( - application: &str, - eligible_roles: &[&str], - schema_roles: &[&str], -) -> DistributedClientSurfaceExport { - let full = pool_free_full_surface(); - let eligible = eligible_roles - .iter() - .map(|role| (*role).to_string()) - .collect::>(); - let schema = schema_roles - .iter() - .map(|role| (*role).to_string()) - .collect::>(); - let grants = e2e_readmodels::application_grants(); - let selected = surface_for_application(&full, application, &eligible, &schema, &grants) - .expect("e2e-ui application Surface should select"); - DistributedClientSurfaceExport::from_selected("e2e-ui", selected) - .expect("e2e-ui application Surface should export") -} - -fn pool_free_full_surface() -> Surface { - let project = e2e_readmodels::distributed_manifest(); - let service = pool_free_service(); - let projections = projections::projection_owners(); - build_surface(&project.tables, &SurfaceOptions::sqlite()) - .expect("e2e-celld client Surface should build") - .with_projection_owners([ - projections.todo.into(), - projections.chat.into(), - projections.blob.into(), - projections.auth.into(), - ]) - .expect("e2e-celld projector topology should bind") - .with_service(&service) - .expect("e2e-celld typed Service inventory should bind") +/// The logical application: the Service's command namespaces as modules, +/// bound to the full Surface. +pub fn application(service: &Service) -> Result { + let surface = SurfaceSpec::from_surface(E2E_UI_APPLICATION, &full_surface(service)?)?; + service.application(E2E_UI_APPLICATION, surface) } +/// A Service with in-memory stores: its command inventory without a database. fn pool_free_service() -> Service { let repository = InMemoryRepository::new(); - crate::modules::compose::build_service( + build_service(&Stores::new( repository.clone(), - ClientSurfaceLocks::default(), + InMemoryLockManager::new(), repository, - ) + )) } -/// Logical application artifact consumed by `distributed build` and `dev`. -/// Runtime repositories, celld transport, and NATS connections are erased. +/// Logical application artifact consumed by `distributed describe` and the +/// coherent lifecycle builder. Runtime handlers and repositories are erased. pub fn application_manifest() -> ApplicationManifest { - let surface = SurfaceSpec::from_surface(E2E_UI_APPLICATION, &pool_free_full_surface()) - .expect("e2e-celld full Surface should compile into an application artifact"); - - let commands = pool_free_service() - .command_specs() - .expect("e2e-celld typed commands should compile into portable specs") - .into_iter() - .map(|command| { - let exposed = surface - .contract - .commands - .iter() - .find(|exposed| exposed.id == command.id) - .expect("full e2e-celld Surface should expose every application command"); - command - .with_surface_binding(exposed) - .expect("e2e-celld Surface command should bind to its portable declaration") - }) - .collect::>(); - let modules = E2E_UI_MODULE_IDS - .iter() - .map(|module_id| { - // A module's commands are named `{module}.…`; the identity - // module's are named for their provider. - let prefix = match *module_id { - e2e_celld_identity::MODULE_ID => e2e_celld_identity::COMMAND_PREFIX.to_string(), - module_id => format!("{module_id}."), - }; - let definitions = commands - .iter() - .filter(|command| command.id.starts_with(&prefix)) - .cloned() - .map(CommandDefinition::contract) - .collect::>(); - Module::new(*module_id) - .command_definitions(definitions) - .build() - .expect("e2e-celld application module should compile") - }) - .collect::>(); - - Application::new(E2E_UI_APPLICATION) - .modules(modules) - .surface(surface) - .build() - .expect("e2e-celld application manifest should compile") + application(&pool_free_service()) + .expect("e2e-ui application manifest should compile") .manifest() .clone() } +fn client_surface(surface: ClientSurface) -> DistributedClientSurfaceExport { + let full = full_surface(&pool_free_service()).expect("e2e-ui client Surface should build"); + let roles = |roles: &[&str]| { + roles + .iter() + .map(|role| (*role).to_string()) + .collect::>() + }; + let selected = surface_for_application( + &full, + surface.name, + &roles(surface.eligible_roles), + &roles(surface.schema_roles), + &read_models().grants(), + ) + .expect("e2e-ui application Surface should select"); + DistributedClientSurfaceExport::from_selected(E2E_UI_APPLICATION, selected) + .expect("e2e-ui application Surface should export") +} + /// Pool-free normal application export consumed by `distributed client-manifest`. pub fn distributed_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface_contract(DISTRIBUTED_CLIENT_SURFACE, &["admin", "user"], &["user"]) + client_surface(CLIENT_SURFACE) } pub fn distributed_admin_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, &["admin"]) + client_surface(ADMIN_CLIENT_SURFACE) } pub fn distributed_public_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface(DISTRIBUTED_PUBLIC_CLIENT_SURFACE, &["anonymous"]) + client_surface(PUBLIC_CLIENT_SURFACE) } pub fn dev_identity() -> IdentityConfig { @@ -274,9 +202,6 @@ pub fn oidc_bearer_config( #[cfg(test)] mod client_surface_tests { use super::*; - use crate::application::{DISTRIBUTED_CLIENT_SURFACE, DISTRIBUTED_PUBLIC_CLIENT_SURFACE}; - use crate::modules::compose::build_service; - use distributed::InMemoryRepository; #[test] fn application_manifest_compiles_real_modules_and_surfaces() { @@ -287,7 +212,7 @@ mod client_surface_tests { assert_eq!(manifest.name, "e2e-ui"); assert_eq!( manifest.module_ids(), - vec!["blob", "chat", "identity", "todo"] + vec!["blob", "chat", "todo", "zitadel"] ); assert_eq!(manifest.surfaces.len(), 1); assert!(!manifest.commands.is_empty()); @@ -593,13 +518,7 @@ mod client_surface_tests { .expect("Blob direct owner should be exported"); assert!(owner.facts.is_empty()); - let repository = InMemoryRepository::new(); - let service = build_service( - repository.clone(), - crate::modules::graphql::ClientSurfaceLocks::default(), - repository, - ); - let plan = service.subscription_plan(); + let plan = pool_free_service().subscription_plan(); for event in [ "todo.created", "todo.renamed", @@ -635,11 +554,11 @@ mod client_surface_tests { .connect_lazy("postgres://postgres:postgres@localhost/distributed") .unwrap(); let repository = distributed::PostgresRepository::new(pool.clone()); - let service = build_service( + let service = build_service(&Stores::new( repository.clone(), distributed::PostgresLockManager::new(pool), repository.clone(), - ); + )); let engine = crate::modules::graphql::build_graphql_engine_with_graphiql( &repository, &service, @@ -650,9 +569,9 @@ mod client_surface_tests { .expect("engine"); let runtime = engine .client_manifest_for_application( - DISTRIBUTED_CLIENT_SURFACE, - &["admin", "user"], - &["user"], + CLIENT_SURFACE.name, + CLIENT_SURFACE.eligible_roles, + CLIENT_SURFACE.schema_roles, ) .unwrap(); @@ -666,9 +585,9 @@ mod client_surface_tests { "client": { "surface": { "kind": "application", - "name": DISTRIBUTED_CLIENT_SURFACE, - "eligible_roles": ["admin", "user"], - "schema_roles": ["user"] + "name": CLIENT_SURFACE.name, + "eligible_roles": CLIENT_SURFACE.eligible_roles, + "schema_roles": CLIENT_SURFACE.schema_roles }, "schemaHash": generated.schema_fingerprint } @@ -716,28 +635,23 @@ mod client_surface_tests { assert_eq!( generated.surface, distributed::graphql::ClientSurfaceIdentity::application( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - ["anonymous"], - ["anonymous"], + PUBLIC_CLIENT_SURFACE.name, + PUBLIC_CLIENT_SURFACE.eligible_roles.iter().copied(), + PUBLIC_CLIENT_SURFACE.schema_roles.iter().copied(), ) ); - let repository = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + use distributed::microsvc::{SqlStores, SqliteStores}; + + let stores = SqliteStores::connect("sqlite::memory:") .await - .expect("sqlite memory repo"); - let registry = e2e_readmodels::distributed_manifest() - .table_registry() - .expect("registry"); - repository - .bootstrap_table_schema_for_dev(®istry) + .expect("sqlite memory stores"); + stores + .bootstrap_read_models(read_models().catalog()) .await .expect("bootstrap tables"); - let service = build_service( - repository.clone(), - crate::modules::graphql::ClientSurfaceLocks::default(), - repository.clone(), - ); + let service = build_service(&stores); let engine = crate::modules::graphql::build_graphql_engine_with_graphiql( - &repository, + stores.graphql_pool(), &service, dev_identity(), None, @@ -746,9 +660,9 @@ mod client_surface_tests { .expect("engine"); let runtime = engine .client_manifest_for_application( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - &["anonymous"], - &["anonymous"], + PUBLIC_CLIENT_SURFACE.name, + PUBLIC_CLIENT_SURFACE.eligible_roles, + PUBLIC_CLIENT_SURFACE.schema_roles, ) .expect("public surface registered"); assert_eq!(generated.schema_fingerprint, runtime.schema_fingerprint); @@ -760,9 +674,9 @@ mod client_surface_tests { "client": { "surface": { "kind": "application", - "name": DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - "eligible_roles": ["anonymous"], - "schema_roles": ["anonymous"] + "name": PUBLIC_CLIENT_SURFACE.name, + "eligible_roles": PUBLIC_CLIENT_SURFACE.eligible_roles, + "schema_roles": PUBLIC_CLIENT_SURFACE.schema_roles }, "schemaHash": generated.schema_fingerprint } @@ -793,13 +707,4 @@ mod client_surface_tests { let envelope = serde_json::to_value(envelope).expect("serialized protocol envelope"); assert_eq!(envelope["schemaHash"], generated.schema_fingerprint); } - - #[test] - fn module_inventory_lists_todo_chat_blob_identity() { - assert_eq!( - crate::E2E_UI_MODULE_IDS, - &["todo", "chat", "blob", "identity"] - ); - assert_eq!(crate::application::MODULE_DECLARATIONS.len(), 4); - } } diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs b/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs index cc42d236d..87f16d9a8 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs @@ -1,47 +1,19 @@ //! e2e-ui projection mounts — product declaration only. //! -//! Topology, catalog activation, and Surface packaging come from -//! [`distributed::LocalProjectionMountsBuilder`]. +//! Each projection is mounted from its `projection!` descriptor, which names +//! it, pins its epoch and its model. Topology, catalog activation, and Surface +//! packaging come from [`distributed::LocalProjectionMounts`]. -use distributed::graphql::{SurfaceDirectProjection, SurfaceProjector}; -use distributed::LocalProjectionMountsBuilder; +use distributed::LocalProjectionMounts; use e2e_projections::{AUTH_USERS, BLOB_GAMES, CHAT_MESSAGES, TODOS}; -use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; -/// Projection surface mounts used by compose + GraphQL. -#[derive(Clone)] -pub struct ProjectionOwners { - pub todo: SurfaceProjector, - pub chat: SurfaceProjector, - pub blob: SurfaceDirectProjection, - pub auth: SurfaceProjector, -} - -/// Compile local projection mounts for the e2e-ui application. -pub fn projection_owners() -> ProjectionOwners { - let mounts = LocalProjectionMountsBuilder::new("e2e-ui", "ordered-domain-events") - .expect("projection source") - .eventual_model::("project_todos", TODOS, "e2e-ui-todos-v2") - .expect("todo mount") - .eventual_model::("project_chat_messages", CHAT_MESSAGES, "e2e-ui-chat-v2") - .expect("chat mount") - .direct_model::("project_blob", BLOB_GAMES, "e2e-ui-blob-v2") - .expect("blob mount") - .eventual_model::("project_auth_users", AUTH_USERS, "e2e-ui-auth-users-v1") - .expect("auth users mount") +/// Every projection of the application, mounted for one local process. +pub fn projections() -> LocalProjectionMounts { + LocalProjectionMounts::builder("e2e-ui", "ordered-domain-events") + .eventual(TODOS) + .eventual(CHAT_MESSAGES) + .direct(BLOB_GAMES) + .eventual(AUTH_USERS) .build() - .expect("projection catalog"); - - ProjectionOwners { - todo: mounts.projector("project_todos").expect("todo projector"), - chat: mounts - .projector("project_chat_messages") - .expect("chat projector"), - blob: mounts - .direct_projection("project_blob") - .expect("blob direct"), - auth: mounts - .projector("project_auth_users") - .expect("auth users projector"), - } + .expect("e2e-ui projection catalog") } diff --git a/tests/e2e-celld/crates/identity-service/src/bounds.rs b/tests/e2e-celld/crates/identity-service/src/bounds.rs deleted file mode 100644 index 4d23dca1f..000000000 --- a/tests/e2e-celld/crates/identity-service/src/bounds.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, ReadModelWritePlanStore, RelationalReadModelQueryStore, TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-celld/crates/identity-service/src/deps.rs b/tests/e2e-celld/crates/identity-service/src/deps.rs deleted file mode 100644 index 9d0534046..000000000 --- a/tests/e2e-celld/crates/identity-service/src/deps.rs +++ /dev/null @@ -1,6 +0,0 @@ -use distributed::microsvc::RepoReadModelDependencies; -use distributed::AggregateRepository; - -/// Stores, no aggregate: the commands publish user profiles, which the -/// auth_users projection writes. -pub type AuthDeps = RepoReadModelDependencies, S>; diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs b/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs index 033e0cc13..948e10260 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs @@ -1,2 +1 @@ pub mod ingestors; -pub mod util; diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/util.rs b/tests/e2e-celld/crates/identity-service/src/handlers/util.rs deleted file mode 100644 index 1f4e6aca9..000000000 --- a/tests/e2e-celld/crates/identity-service/src/handlers/util.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! Shared handler helpers. -//! -//! **Admission vs domain** -//! - [`session_has_user`] / [`session_is_admin`] / [`causal_has_user`] / -//! [`causal_is_admin`] — command **guards** (session admission only). -//! - Handler bodies bind the principal and call the domain; they do not re-check -//! “am I logged in?” when a guard already did. -//! - Domain owns entity invariants (empty title, ownership, board rules). - -use distributed::microsvc::{CausalCommandContext, HandlerError, Session}; -use distributed::Aggregate; - -pub fn rejected(err: impl std::fmt::Display) -> HandlerError { - HandlerError::Rejected(err.to_string()) -} - -/// Authenticated user from session (`x-user-id` via DevHeaders or OIDC claim map). -pub fn require_user(session: &Session) -> Result { - session - .user_id() - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .ok_or_else(|| HandlerError::Unauthorized("missing x-user-id".into())) -} - -/// Session has a non-empty user id (for `guard` — bool, not Result). -pub fn session_has_user(session: &Session) -> bool { - session.user_id().is_some_and(|s| !s.is_empty()) -} - -/// Engine role set contains `admin` (`x-roles` / OIDC claim map). For `guard`. -pub fn session_is_admin(session: &Session) -> bool { - session.has_role("admin") -} - -/// Typed causal guard: non-empty session user id. -pub fn causal_has_user(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - session_has_user(ctx.session()) -} - -/// Typed causal guard: session user present and carries `admin`. -pub fn causal_is_admin(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - session_has_user(ctx.session()) && session_is_admin(ctx.session()) -} - -/// Principal after a user-session guard (for domain `owner_id` / author args). -pub fn principal(ctx: &CausalCommandContext<'_, A>) -> Result -where - A: Aggregate + Send + Sync + 'static, -{ - ctx.user_id().map(str::to_string) -} - -/// Require engine role `admin` (handler-path Result form). -pub fn require_admin(session: &Session) -> Result<(), HandlerError> { - if session.has_role("admin") { - return Ok(()); - } - let roles = session.roles(); - if roles.is_empty() { - Err(HandlerError::Unauthorized("missing x-roles".into())) - } else { - Err(HandlerError::Rejected(format!( - "admin role required, got `{}`", - roles.join(",") - ))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; - - #[test] - fn session_has_user_requires_nonempty_id() { - let mut s = Session::new(); - assert!(!session_has_user(&s)); - s.set(USER_ID_KEY, ""); - assert!(!session_has_user(&s)); - s.set(USER_ID_KEY, "alice"); - assert!(session_has_user(&s)); - } - - #[test] - fn session_is_admin_exact_role() { - let mut s = Session::new(); - assert!(!session_is_admin(&s)); - s.set(ROLE_KEY, "user"); - assert!(!session_is_admin(&s)); - s.set(ROLE_KEY, "admin"); - assert!(session_is_admin(&s)); - } - - #[test] - fn require_admin_errors() { - let mut s = Session::new(); - assert!(require_admin(&s).is_err()); - s.set(ROLE_KEY, "user"); - assert!(require_admin(&s).is_err()); - s.set(ROLE_KEY, "admin"); - assert!(require_admin(&s).is_ok()); - } - - #[test] - fn require_user_errors_and_returns_id() { - let mut s = Session::new(); - assert!(require_user(&s).is_err()); - s.set(USER_ID_KEY, "bob"); - assert_eq!(require_user(&s).unwrap(), "bob"); - } - - #[test] - fn session_is_admin_requires_user_for_causal_admin_guard_semantics() { - // Admin role without a user id is not a usable principal for force_archive. - let mut s = Session::new(); - s.set(ROLE_KEY, "admin"); - assert!(session_is_admin(&s)); - assert!(!session_has_user(&s)); - } -} diff --git a/tests/e2e-celld/crates/identity-service/src/lib.rs b/tests/e2e-celld/crates/identity-service/src/lib.rs index 1c732c625..5de4882d3 100644 --- a/tests/e2e-celld/crates/identity-service/src/lib.rs +++ b/tests/e2e-celld/crates/identity-service/src/lib.rs @@ -3,10 +3,8 @@ //! Not a cell and no aggregate. Chat and Blob stay in their own crates; this //! only owns IdP import so AuthUsers joins are not mounted on the chat aggregate. -mod bounds; -mod deps; pub mod handlers; mod routes; pub use handlers::ingestors::zitadel::{spawn_scrape_loop, ZitadelScrapeConfig}; -pub use routes::{routes, COMMAND_PREFIX, MODULE_ID}; +pub use routes::routes; diff --git a/tests/e2e-celld/crates/identity-service/src/routes.rs b/tests/e2e-celld/crates/identity-service/src/routes.rs index a39d9748a..44548fcb8 100644 --- a/tests/e2e-celld/crates/identity-service/src/routes.rs +++ b/tests/e2e-celld/crates/identity-service/src/routes.rs @@ -3,35 +3,23 @@ //! No aggregate: the commands publish user profiles as external facts, which //! commit with their ledger receipts; the `AUTH_USERS` projection writes them. -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Routes}; -use distributed::AggregateRepository; +use distributed::microsvc::{Routes, ServiceStores, StoreDependencies}; +use distributed::LocalProjectionMounts; +use e2e_projections::AUTH_USERS; -use crate::bounds::{EventStore, ReadStore}; -use crate::deps::AuthDeps; use crate::handlers::ingestors::{zitadel, zitadel_scrape}; -pub const MODULE_ID: &str = "identity"; - -/// Prefix of this module's command names (they are named for the provider). -pub const COMMAND_PREFIX: &str = "zitadel."; - -pub fn routes( - repo: R, - read_models: S, - auth_projector: SurfaceProjector, -) -> Routes> -where - R: EventStore, - S: ReadStore, - AggregateRepository: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let scrape = zitadel_scrape::Scrape(read_models.clone()); - Routes::for_stores(repo, read_models) +/// Mount the Zitadel ingress and scrape commands and the auth_users +/// projection. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + let scrape = zitadel_scrape::Scrape(stores.read_models().clone()); + Routes::for_stores(stores.events().clone(), stores.read_models().clone()) .typed_command(zitadel::command()) .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) .handle(scrape) - .consume_projection(auth_projector) + .consume_projection(projections.projector(AUTH_USERS)) } diff --git a/tests/e2e-celld/crates/todo-service/src/bounds.rs b/tests/e2e-celld/crates/todo-service/src/bounds.rs deleted file mode 100644 index dbaf42fe0..000000000 --- a/tests/e2e-celld/crates/todo-service/src/bounds.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, LockManager, ReadModelWritePlanStore, RelationalReadModelQueryStore, - TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait Locks: LockManager + Clone + 'static {} -impl Locks for T where T: LockManager + Clone + 'static {} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-celld/crates/todo-service/src/handlers/mod.rs b/tests/e2e-celld/crates/todo-service/src/handlers/mod.rs deleted file mode 100644 index a5bc70692..000000000 --- a/tests/e2e-celld/crates/todo-service/src/handlers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod project_todos; diff --git a/tests/e2e-celld/crates/todo-service/src/handlers/project_todos.rs b/tests/e2e-celld/crates/todo-service/src/handlers/project_todos.rs deleted file mode 100644 index 4e13f8fe0..000000000 --- a/tests/e2e-celld/crates/todo-service/src/handlers/project_todos.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Apply the Todos projection for matching domain events. - -use distributed::microsvc::{CausalProjectorContext, HandlerError, ModeledProjection}; -use e2e_projections::TODOS; - -pub async fn handle( - context: CausalProjectorContext, - projection: ModeledProjection, -) -> Result<(), HandlerError> { - projection.apply(TODOS, &context).await -} diff --git a/tests/e2e-celld/crates/todo-service/src/lib.rs b/tests/e2e-celld/crates/todo-service/src/lib.rs index 294e3b8c7..349f4ffc6 100644 --- a/tests/e2e-celld/crates/todo-service/src/lib.rs +++ b/tests/e2e-celld/crates/todo-service/src/lib.rs @@ -3,10 +3,8 @@ //! Domain commands stay in `todo-domain`. Every Todo aggregate transition is //! wait-dispatched to celld through [`distributed::cell_host::CelldCommandHost`]. -mod bounds; -mod handlers; mod host; mod routes; pub use host::celld_route; -pub use routes::{routes, MODULE_ID}; +pub use routes::routes; diff --git a/tests/e2e-celld/crates/todo-service/src/routes.rs b/tests/e2e-celld/crates/todo-service/src/routes.rs index 4e20d90cf..0f7b29d84 100644 --- a/tests/e2e-celld/crates/todo-service/src/routes.rs +++ b/tests/e2e-celld/crates/todo-service/src/routes.rs @@ -1,41 +1,16 @@ -//! Todo command mounts + eventual projector (SQL list dual-write). +//! Todo command mounts + eventual projection. -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; +use distributed::LocalProjectionMounts; +use e2e_projections::TODOS; use todo_domain::Todo; -use crate::bounds::{EventStore, Locks, ReadStore}; -use crate::handlers; - -pub const MODULE_ID: &str = "todo"; - -type TodoRoutes = - Routes, Todo>, S>>; - -pub fn routes( - repo: R, - locks: L, - read_models: S, - todo_projector: SurfaceProjector, -) -> TodoRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, Todo>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - Routes::for_aggregate::(repo, locks, read_models) +/// Mount todo commands and the todo projection. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(todo_domain::commands::create()) .mount(todo_domain::commands::rename()) .mount(todo_domain::commands::complete()) @@ -43,6 +18,5 @@ where .mount(todo_domain::commands::archive()) .mount(todo_domain::commands::force_archive()) .mount(todo_domain::commands::purge()) - .modeled_projector(todo_projector) - .handle(handlers::project_todos::handle) + .consume_projection(projections.projector(TODOS)) } diff --git a/tests/e2e-ui/README.md b/tests/e2e-ui/README.md index bb616a0e9..c4fcdce31 100644 --- a/tests/e2e-ui/README.md +++ b/tests/e2e-ui/README.md @@ -320,9 +320,10 @@ the single relationship declaration; `AuthUsers` does not need reverse collections for every model that references it. Read RBAC is attached to those same query models through -`Todos::permissions()`, `BlobGames::permissions()`, and their peers. The -runtime GraphQL engine and generated application surfaces reuse those -declarations; the service crate does not recreate the grants. +`impl AuthorizedReadModel for Todos`, `BlobGames`, and their peers. +`e2e_readmodels::read_models()` lists each model once; schema bootstrap, the +runtime GraphQL engine and generated application surfaces all read that list, +so the service crate neither recreates the grants nor repeats the models. ## Outcomes @@ -342,23 +343,22 @@ the normal GraphQL command result. | `crates/*-domain/` | Aggregates, replay events, and outward domain-state contracts. | | `crates/readmodels/` | Query shapes, relationships, and model-owned read RBAC. | | `crates/projections/` | Todo, Chat, and Blob event-to-read-model programs. | -| `crates/service/src/handlers/events/` | Explicit projector handlers that apply modeled programs. | | `crates/*-domain/src/commands/` | `command!` handlers: repository → get/create → domain operation → fluent commit. | -| `crates/service/src/application.rs` | Composition root: client surfaces and the module inventory. | -| `crates/service/src/modules/` | One module per bounded context (`todo`, `chat`, `blob`) mounting its typed commands and projectors; `compose.rs` lists them. | -| `crates/service/src/host.rs` | Infrastructure: SQL dialect, outbox, OIDC, serving. | +| `crates/service/src/application.rs` | Composition root: application name and client surfaces (declared once). | +| `crates/service/src/modules/` | One module per bounded context (`todo`, `chat`, `blob`, `identity`) mounting its typed commands and projections; `compose.rs` lists them, and the application manifest is derived from that Service. | +| `crates/service/src/host.rs` | Infrastructure: one host for SQLite and Postgres (`SqlStores`), OIDC, serving. | | `ui/src/routes/*/+page.graphql` | Co-located SSR/live reads. | | `ui/src/routes/*/+page.svelte` | `*.use()` and ordinary typed command calls. | | `.distributed/lifecycle/generations//ui/src/lib/generated/` | Immutable lifecycle-owned user/admin/public clients. | -Todo and Chat mount catalog-pinned local causal executors through explicit -`modeled_projector(...).handle(...)` event handlers. Those handlers apply the +Todo and Chat mount catalog-pinned local causal executors with +`consume_projection(projections.projector(TODOS))`: the runtime applies the shared plan without repeating its mapping — that is why the waiting client only has `.applies` previews until obligations complete. Blob has a catalog-pinned direct owner and no asynchronous event route or second writer: the command handler applies the same mutation IR and returns the row. The Zitadel provider ingestor remains an integration adapter, while its provider-event-to-`AuthUsers` -mapping also lives in `e2e-projections` and runs from an explicit event handler. +mapping also lives in `e2e-projections` and is consumed the same way. ## Application composition (framework direction) 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 4d744a450..62b9c2105 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,10 +1,10 @@ use distributed::command; use distributed::command::{Atomic, CommandProjectionPureReduce, PreparedCommand}; -use distributed::microsvc::{CausalCommandContext, HandlerError}; +use distributed::microsvc::{guards, CausalCommandContext, HandlerError}; use e2e_readmodels::BlobGames; use serde::Deserialize; -use super::support::{authenticated_user, principal, rejected, sealed_row}; +use super::support::sealed_row; use crate::{domain_commands, BlobGame, Direction}; #[derive(Debug, Deserialize, distributed::CommandInput)] @@ -17,7 +17,7 @@ pub async fn handle_move( ctx: &CausalCommandContext<'_, BlobGame>, input: BlobMoveInput, ) -> Result>, HandlerError> { - let owner = principal(ctx)?; + let owner = ctx.user_id()?.to_string(); let direction = Direction::parse(&input.direction).ok_or_else(|| { HandlerError::Rejected(format!( "invalid direction `{}` (use up|down|left|right)", @@ -29,7 +29,8 @@ pub async fn handle_move( .get(&input.game_id) .await? .ok_or_else(|| HandlerError::NotFound(input.game_id.clone()))?; - game.move_dir(&owner, direction).map_err(rejected)?; + game.move_dir(&owner, direction) + .map_err(HandlerError::rejected)?; let row = sealed_row(&*game)?; repo.readmodel(row).publish_events().commit(game)?.atomic() } @@ -63,7 +64,7 @@ command! { field: "blob_games_move", constructor: move_dir, preview_reduce_known_record: blob_preview(), - guard: authenticated_user, + guard: guards::authenticated, handle: handle_move, } 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 daf1900d0..190dae636 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/start.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/start.rs @@ -1,10 +1,10 @@ use distributed::command; use distributed::command::{Atomic, PreparedCommand}; -use distributed::microsvc::{CausalCommandContext, HandlerError}; +use distributed::microsvc::{guards, CausalCommandContext, HandlerError}; use e2e_readmodels::BlobGames; use serde::Deserialize; -use super::support::{authenticated_user, principal, rejected, sealed_row}; +use super::support::sealed_row; use crate::{domain_commands, BlobGame}; #[derive(Debug, Deserialize, distributed::CommandInput)] @@ -16,7 +16,7 @@ pub async fn handle_start( ctx: &CausalCommandContext<'_, BlobGame>, input: BlobStartInput, ) -> Result>, HandlerError> { - let owner = principal(ctx)?; + let owner = ctx.user_id()?.to_string(); let repo = ctx.repo(); if repo.get(&input.game_id).await?.is_some() { return Err(HandlerError::Rejected(format!( @@ -26,7 +26,7 @@ pub async fn handle_start( } let mut game = repo.create(); game.start_with_demo(&input.game_id, &owner) - .map_err(rejected)?; + .map_err(HandlerError::rejected)?; let row = sealed_row(&*game)?; repo.readmodel(row).publish_events().commit(game)?.atomic() } @@ -40,6 +40,6 @@ command! { shard: |input| input.game_id.clone(), roles: ["user", "admin"], field: "blob_games_start", - guard: authenticated_user, + guard: guards::authenticated, handle: handle_start, } 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 d157a426c..39bd28a07 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,10 +1,10 @@ use distributed::command; use distributed::command::{Atomic, PreparedCommand}; -use distributed::microsvc::{CausalCommandContext, HandlerError}; +use distributed::microsvc::{guards, CausalCommandContext, HandlerError}; use e2e_readmodels::BlobGames; use serde::Deserialize; -use super::support::{authenticated_user, principal, rejected, sealed_row}; +use super::support::sealed_row; use crate::{domain_commands, BlobGame}; #[derive(Debug, Deserialize, distributed::CommandInput)] @@ -16,13 +16,14 @@ pub async fn handle_start_level( ctx: &CausalCommandContext<'_, BlobGame>, input: BlobStartLevelInput, ) -> Result>, HandlerError> { - let owner = principal(ctx)?; + let owner = ctx.user_id()?.to_string(); let repo = ctx.repo(); let mut game = repo .get(&input.game_id) .await? .ok_or_else(|| HandlerError::NotFound(input.game_id.clone()))?; - game.start_next_generated_level(&owner).map_err(rejected)?; + game.start_next_generated_level(&owner) + .map_err(HandlerError::rejected)?; let row = sealed_row(&*game)?; repo.readmodel(row).publish_events().commit(game)?.atomic() } @@ -36,6 +37,6 @@ command! { shard: |input| input.game_id.clone(), roles: ["user", "admin"], field: "blob_games_start_level", - guard: authenticated_user, + guard: guards::authenticated, handle: handle_start_level, } diff --git a/tests/e2e-ui/crates/blob-domain/src/commands/support.rs b/tests/e2e-ui/crates/blob-domain/src/commands/support.rs index 0359480fc..a8ed8fbed 100644 --- a/tests/e2e-ui/crates/blob-domain/src/commands/support.rs +++ b/tests/e2e-ui/crates/blob-domain/src/commands/support.rs @@ -1,27 +1,9 @@ -use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::{mutation_file, Aggregate, Mutation}; +use distributed::microsvc::HandlerError; +use distributed::{mutation_file, Mutation}; use e2e_readmodels::BlobGames; use crate::{BlobGame, BlobGameState}; -pub(super) fn rejected(err: impl std::fmt::Display) -> HandlerError { - HandlerError::Rejected(err.to_string()) -} - -pub(super) fn principal(ctx: &CausalCommandContext<'_, A>) -> Result -where - A: Aggregate + Send + Sync + 'static, -{ - ctx.user_id().map(str::to_string) -} - -pub(super) fn authenticated_user(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - ctx.session().user_id().is_some_and(|id| !id.is_empty()) -} - #[allow(non_snake_case)] fn SaveBlobGame() -> Mutation<()> { mutation_file!("src/mutations/save_blob_game.mutation.graphql") 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 c2841786d..41b83e742 100644 --- a/tests/e2e-ui/crates/chat-domain/src/commands/post.rs +++ b/tests/e2e-ui/crates/chat-domain/src/commands/post.rs @@ -1,22 +1,10 @@ use distributed::command; use distributed::command::{Eventual, PreparedCommand}; -use distributed::microsvc::{CausalCommandContext, HandlerError}; +use distributed::microsvc::{guards, CausalCommandContext, HandlerError}; use serde::{Deserialize, Serialize}; use crate::{domain_commands, ChatMessage, ChatMessagePostedDomainEvent, ChatMessageState}; -fn rejected(err: impl std::fmt::Display) -> HandlerError { - HandlerError::Rejected(err.to_string()) -} - -fn principal(ctx: &CausalCommandContext<'_, ChatMessage>) -> Result { - ctx.user_id().map(str::to_string) -} - -fn authenticated_user(ctx: &CausalCommandContext<'_, ChatMessage>) -> bool { - ctx.session().user_id().is_some_and(|id| !id.is_empty()) -} - #[derive(Debug, Deserialize, distributed::CommandInput)] pub struct ChatPostInput { pub message_id: String, @@ -40,7 +28,7 @@ pub async fn handle_post( ctx: &CausalCommandContext<'_, ChatMessage>, input: ChatPostInput, ) -> Result>, HandlerError> { - let author = principal(ctx)?; + let author = ctx.user_id()?.to_string(); let created_at = canonical_near_unix_millis(&input.created_at)?; let repo = ctx.repo(); @@ -60,7 +48,7 @@ pub async fn handle_post( &input.body, &created_at, ) - .map_err(rejected)?; + .map_err(HandlerError::rejected)?; let state = ChatMessageState::from(&*message); repo.publish_events() @@ -83,9 +71,9 @@ pub async fn handle_post( pub fn canonical_near_unix_millis(value: &str) -> Result { let millis = value .parse::() - .map_err(|_| rejected("created_at must be canonical unix milliseconds"))?; + .map_err(|_| HandlerError::rejected("created_at must be canonical unix milliseconds"))?; if millis.to_string() != value { - return Err(rejected( + return Err(HandlerError::rejected( "created_at must be canonical unix milliseconds within five minutes of server time", )); } @@ -97,7 +85,7 @@ pub fn canonical_near_unix_millis(value: &str) -> Result { .unwrap_or_default() .as_millis(); if millis.abs_diff(now) > 300_000 { - return Err(rejected( + return Err(HandlerError::rejected( "created_at must be canonical unix milliseconds within five minutes of server time", )); } @@ -119,7 +107,7 @@ command! { ChatMessageState, "author_id" ), - guard: authenticated_user, + guard: guards::authenticated, handle: handle_post, } diff --git a/tests/e2e-ui/crates/readmodels/src/lib.rs b/tests/e2e-ui/crates/readmodels/src/lib.rs index 7383cc993..790a89835 100644 --- a/tests/e2e-ui/crates/readmodels/src/lib.rs +++ b/tests/e2e-ui/crates/readmodels/src/lib.rs @@ -7,47 +7,14 @@ pub mod models; pub use models::{AuthUsers, BlobGames, ChatMessages, Todos}; -pub fn distributed_manifest() -> distributed::ReadModelCatalog { - use distributed::RelationalReadModel; - - // Schema-only catalog (physical tables). ApplicationManifest is the logical - // application contract and is composed separately. - distributed::ReadModelCatalog::new("e2e-ui") - .table_schema(Todos::schema().clone()) - .table_schema(ChatMessages::schema().clone()) - .table_schema(BlobGames::schema().clone()) - .table_schema(AuthUsers::schema().clone()) -} - -/// Role grants compiled from the authorization attached to each read model. -pub fn application_grants() -> std::collections::BTreeMap< - String, - std::collections::BTreeMap, -> { - use distributed::graphql::ModelPermissions; - use distributed::RelationalReadModel; - - fn add( - grants: &mut std::collections::BTreeMap< - String, - std::collections::BTreeMap, - >, - permissions: ModelPermissions, - ) { - for (role, grant) in permissions.by_role() { - grants - .entry(role) - .or_default() - .insert(M::schema().model_name.clone(), grant); - } - } - - let mut grants = std::collections::BTreeMap::new(); - add(&mut grants, Todos::permissions()); - add(&mut grants, ChatMessages::permissions()); - add(&mut grants, BlobGames::permissions()); - add(&mut grants, AuthUsers::permissions()); - grants +/// Every read model the application serves, with its permissions: the one +/// list schema bootstrap, the GraphQL engine and client export read. +pub fn read_models() -> distributed::graphql::ReadModels { + distributed::graphql::ReadModels::new("e2e-ui") + .model::() + .model::() + .model::() + .model::() } #[cfg(test)] @@ -79,9 +46,8 @@ mod tests { assert!(AuthUsers::schema().relationships.is_empty()); - let project = distributed_manifest(); let surface = distributed::graphql::build_surface( - &project.tables, + &read_models().catalog().tables, &distributed::graphql::SurfaceOptions::sqlite(), ) .unwrap(); @@ -115,7 +81,7 @@ mod tests { #[test] fn model_owned_permissions_compile_the_application_grants() { - let grants = application_grants(); + let grants = read_models().grants(); let user = &grants["user"]; let admin = &grants["admin"]; let anonymous = &grants["anonymous"]; diff --git a/tests/e2e-ui/crates/readmodels/src/models/auth_users.rs b/tests/e2e-ui/crates/readmodels/src/models/auth_users.rs index 794eb8050..ce6d3c8ca 100644 --- a/tests/e2e-ui/crates/readmodels/src/models/auth_users.rs +++ b/tests/e2e-ui/crates/readmodels/src/models/auth_users.rs @@ -1,6 +1,6 @@ //! Auth users imported from Zitadel Action ingress. -use distributed::graphql::{read, ModelPermissions}; +use distributed::graphql::{read, AuthorizedReadModel, ModelPermissions}; use distributed::ReadModel; use serde::{Deserialize, Serialize}; @@ -23,9 +23,9 @@ pub struct AuthUsers { pub updated_at: String, } -impl AuthUsers { +impl AuthorizedReadModel for AuthUsers { /// Read authorization attached to the imported identity query model. - pub fn permissions() -> ModelPermissions { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant("user", read().all_columns()) .grant("admin", read().all_columns()) diff --git a/tests/e2e-ui/crates/readmodels/src/models/blob_games.rs b/tests/e2e-ui/crates/readmodels/src/models/blob_games.rs index ea04a76ca..38ca18d39 100644 --- a/tests/e2e-ui/crates/readmodels/src/models/blob_games.rs +++ b/tests/e2e-ui/crates/readmodels/src/models/blob_games.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{claim, col, read, ModelPermissions}; +use distributed::graphql::{claim, col, read, AuthorizedReadModel, ModelPermissions}; use distributed::ReadModel; use serde::{Deserialize, Serialize}; @@ -22,9 +22,9 @@ pub struct BlobGames { pub owner: Option, } -impl BlobGames { +impl AuthorizedReadModel for BlobGames { /// Read authorization attached to the Blob game query model. - pub fn permissions() -> ModelPermissions { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", diff --git a/tests/e2e-ui/crates/readmodels/src/models/chat_messages.rs b/tests/e2e-ui/crates/readmodels/src/models/chat_messages.rs index 380260674..38eb37018 100644 --- a/tests/e2e-ui/crates/readmodels/src/models/chat_messages.rs +++ b/tests/e2e-ui/crates/readmodels/src/models/chat_messages.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{read, ModelPermissions}; +use distributed::graphql::{read, AuthorizedReadModel, ModelPermissions}; use distributed::ReadModel; use serde::{Deserialize, Serialize}; @@ -18,9 +18,9 @@ pub struct ChatMessages { pub author: Option, } -impl ChatMessages { +impl AuthorizedReadModel for ChatMessages { /// Read authorization attached to the Chat query model. - pub fn permissions() -> ModelPermissions { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant("user", read().all_columns()) .grant("admin", read().all_columns()) diff --git a/tests/e2e-ui/crates/readmodels/src/models/todos.rs b/tests/e2e-ui/crates/readmodels/src/models/todos.rs index 73e42832a..90dfa923e 100644 --- a/tests/e2e-ui/crates/readmodels/src/models/todos.rs +++ b/tests/e2e-ui/crates/readmodels/src/models/todos.rs @@ -1,4 +1,4 @@ -use distributed::graphql::{claim, col, read, ModelPermissions}; +use distributed::graphql::{claim, col, read, AuthorizedReadModel, ModelPermissions}; use distributed::ReadModel; use serde::{Deserialize, Serialize}; @@ -19,9 +19,9 @@ pub struct Todos { pub owner: Option, } -impl Todos { +impl AuthorizedReadModel for Todos { /// Read authorization attached to the Todo query model. - pub fn permissions() -> ModelPermissions { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", diff --git a/tests/e2e-ui/crates/service/src/application.rs b/tests/e2e-ui/crates/service/src/application.rs index 77c620138..48e5d1443 100644 --- a/tests/e2e-ui/crates/service/src/application.rs +++ b/tests/e2e-ui/crates/service/src/application.rs @@ -1,20 +1,41 @@ //! e2e-ui application composition root. //! -//! This is the review-visible product declaration: surface identities, module -//! inventory, and re-exports of the composed host APIs. Infrastructure -//! (dialect, outbox, OIDC serve) stays in `host`; handlers stay in modules. - -use crate::modules::compose; - -/// Stable normal-application surface shared by user and admin sessions. -pub const DISTRIBUTED_CLIENT_SURFACE: &str = "e2e-ui"; -/// Stable elevated surface for routes that intentionally include admin-only fields. -pub const DISTRIBUTED_ADMIN_CLIENT_SURFACE: &str = "e2e-ui-admin"; -/// Unauthenticated public surface (lobby message peek). -pub const DISTRIBUTED_PUBLIC_CLIENT_SURFACE: &str = "e2e-ui-public"; +//! This is the review-visible product declaration: the application name and +//! its generated client surfaces. Modules are the Service's command +//! namespaces (`modules::compose`); infrastructure stays in `host`. /// Logical application name used for manifest / plan identity. pub const E2E_UI_APPLICATION: &str = "e2e-ui"; -/// Explicit module identities owned by the e2e application. -pub const E2E_UI_MODULE_IDS: &[&str] = compose::MODULE_IDS; +/// One generated client surface: who may open it, and whose grants shape its +/// schema. Declared once; the GraphQL engine registers it and the client +/// export selects it. +#[derive(Clone, Copy, Debug)] +pub struct ClientSurface { + pub name: &'static str, + pub eligible_roles: &'static [&'static str], + pub schema_roles: &'static [&'static str], +} + +/// Normal-application surface shared by user and admin sessions. +pub const CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui", + eligible_roles: &["admin", "user"], + schema_roles: &["user"], +}; +/// Elevated surface for routes that intentionally include admin-only fields. +pub const ADMIN_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-admin", + eligible_roles: &["admin"], + schema_roles: &["admin"], +}; +/// Unauthenticated public surface (lobby message peek). +pub const PUBLIC_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-public", + eligible_roles: &["anonymous"], + schema_roles: &["anonymous"], +}; + +/// Every client surface the application serves. +pub const CLIENT_SURFACES: [ClientSurface; 3] = + [CLIENT_SURFACE, ADMIN_CLIENT_SURFACE, PUBLIC_CLIENT_SURFACE]; diff --git a/tests/e2e-ui/crates/service/src/bounds.rs b/tests/e2e-ui/crates/service/src/bounds.rs deleted file mode 100644 index dbaf42fe0..000000000 --- a/tests/e2e-ui/crates/service/src/bounds.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Trait aliases for generic handler storage parameters. - -use distributed::microsvc::{CausalProjectionStore, CausalRepositoryBackend}; -use distributed::{ - GetStream, LockManager, ReadModelWritePlanStore, RelationalReadModelQueryStore, - TransactionalCommit, -}; - -pub trait EventStore: - CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} -impl EventStore for T where - T: CausalRepositoryBackend + GetStream + TransactionalCommit + Clone + Send + Sync + 'static -{ -} - -pub trait Locks: LockManager + Clone + 'static {} -impl Locks for T where T: LockManager + Clone + 'static {} - -pub trait ReadStore: - CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} -impl ReadStore for T where - T: CausalProjectionStore - + ReadModelWritePlanStore - + RelationalReadModelQueryStore - + Clone - + Send - + Sync - + 'static -{ -} diff --git a/tests/e2e-ui/crates/service/src/deps.rs b/tests/e2e-ui/crates/service/src/deps.rs deleted file mode 100644 index f1206c57b..000000000 --- a/tests/e2e-ui/crates/service/src/deps.rs +++ /dev/null @@ -1,5 +0,0 @@ -use distributed::microsvc::RepoReadModelDependencies; -use distributed::AggregateRepository; - -/// Zitadel ingress/scrape + the auth_users projection: stores, no aggregate. -pub type AuthDeps = RepoReadModelDependencies, S>; diff --git a/tests/e2e-ui/crates/service/src/handlers/commands/mod.rs b/tests/e2e-ui/crates/service/src/handlers/commands/mod.rs deleted file mode 100644 index c79fda52f..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/commands/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -// Command handlers for Todo/Chat/Blob live in domain crates. -// This module remains for service-only integration commands if any are added. diff --git a/tests/e2e-ui/crates/service/src/handlers/events/mod.rs b/tests/e2e-ui/crates/service/src/handlers/events/mod.rs deleted file mode 100644 index 28f3be14c..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/events/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod project_chat_messages; -pub mod project_todos; diff --git a/tests/e2e-ui/crates/service/src/handlers/events/project_chat_messages.rs b/tests/e2e-ui/crates/service/src/handlers/events/project_chat_messages.rs deleted file mode 100644 index 89d15e440..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/events/project_chat_messages.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Apply the ChatMessages projection for matching domain events. - -use distributed::microsvc::{CausalProjectorContext, HandlerError, ModeledProjection}; -use e2e_projections::CHAT_MESSAGES; - -pub async fn handle( - context: CausalProjectorContext, - projection: ModeledProjection, -) -> Result<(), HandlerError> { - projection.apply(CHAT_MESSAGES, &context).await -} diff --git a/tests/e2e-ui/crates/service/src/handlers/events/project_todos.rs b/tests/e2e-ui/crates/service/src/handlers/events/project_todos.rs deleted file mode 100644 index 4e13f8fe0..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/events/project_todos.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Apply the Todos projection for matching domain events. - -use distributed::microsvc::{CausalProjectorContext, HandlerError, ModeledProjection}; -use e2e_projections::TODOS; - -pub async fn handle( - context: CausalProjectorContext, - projection: ModeledProjection, -) -> Result<(), HandlerError> { - projection.apply(TODOS, &context).await -} diff --git a/tests/e2e-ui/crates/service/src/handlers/mod.rs b/tests/e2e-ui/crates/service/src/handlers/mod.rs index fae5fbddb..948e10260 100644 --- a/tests/e2e-ui/crates/service/src/handlers/mod.rs +++ b/tests/e2e-ui/crates/service/src/handlers/mod.rs @@ -1,3 +1 @@ -pub mod commands; -pub mod events; pub mod ingestors; diff --git a/tests/e2e-ui/crates/service/src/host.rs b/tests/e2e-ui/crates/service/src/host.rs index ab8978f32..eb8d10d0f 100644 --- a/tests/e2e-ui/crates/service/src/host.rs +++ b/tests/e2e-ui/crates/service/src/host.rs @@ -4,158 +4,75 @@ //! add extra e2e-ui process topologies here. Optional celld+NATS is //! `tests/e2e-ui/celld-nats-profile/` (`DCS-DEC-001`). //! -//! Dialect selection and identity remain here. Outbox/consumer loops use -//! framework worker helpers. +//! Backend selection and identity remain here; the host body is written once +//! against [`SqlStores`]. The consumer loop is a framework worker helper. use std::sync::Arc; -use std::time::Duration; -use distributed::bus::{PostgresBus, SqliteBus}; +use distributed::gateway::DeliveryCapabilities; +use distributed::graphql::delivery::GatewayVersionStore; use distributed::graphql::IdentityConfig; use distributed::microsvc::{ - spawn_outbox_publish_loop, spawn_service_consumer_loop, LifecycleGate, Service, + spawn_service_consumer_loop, LifecycleGate, PostgresStores, Service, SqlStores, SqliteStores, }; -use distributed::{PostgresLockManager, PostgresRepository, SqliteLockManager, SqliteRepository}; +use crate::modules::graphql::build_graphql_engine_with_delivery; use crate::{ - build_service, distributed_manifest, serve, spawn_scrape_loop, ZitadelScrapeConfig, - E2E_UI_APPLICATION, + build_service, read_models, serve, spawn_scrape_loop, ZitadelScrapeConfig, E2E_UI_APPLICATION, }; const BUS_GROUP: &str = "e2e-ui"; +type BoxError = Box; + /// Bind address and identity for one local process host. pub struct HostOptions { pub bind: String, pub identity: IdentityConfig, pub public_origin: String, pub ui_origin: String, - pub delivery: distributed::gateway::DeliveryCapabilities, + pub delivery: DeliveryCapabilities, } /// Start the e2e-ui full-local process for SQLite or Postgres from `DATABASE_URL`. -pub async fn run( - database_url: &str, - options: HostOptions, -) -> Result<(), Box> { +pub async fn run(database_url: &str, options: HostOptions) -> Result<(), BoxError> { eprintln!( "e2e-ui host application=`{}` bind={}", E2E_UI_APPLICATION, options.bind ); if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") { - run_postgres(database_url, options).await + host(PostgresStores::connect(database_url).await?, options).await } else { - run_sqlite(database_url, options).await - } -} - -async fn run_sqlite( - database_url: &str, - options: HostOptions, -) -> Result<(), Box> { - let repo = SqliteRepository::connect_and_migrate(database_url).await?; - let registry = distributed_manifest() - .table_registry() - .map_err(|e| format!("manifest: {e}"))?; - repo.bootstrap_table_schema_for_dev(®istry).await?; - let locks = SqliteLockManager::new(repo.pool().clone()); - let bus = SqliteBus::new(repo.pool().clone()).group(BUS_GROUP); - bus.ensure_tables().await?; - - let change_rx = repo.read_model_changes(); - // Under `distributed dev`, only the active generation may write. - let lifecycle = LifecycleGate::from_env(); - let service = build_service(repo.clone(), locks.clone(), repo.clone()) - .with_lifecycle(lifecycle.clone()) - .with_bus(SqliteBus::new(repo.pool().clone()).group(BUS_GROUP)); - 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)?); - - spawn_outbox_publish_loop( - repo.outbox_store(), - Arc::new(SqliteBus::new(repo.pool().clone()).group(BUS_GROUP)), - "e2e-ui", - Duration::from_secs(30), - 5, - ); - { - let repo = repo.clone(); - let locks = locks.clone(); - spawn_service_consumer_loop(move || { - let bus = SqliteBus::new(repo.pool().clone()).group(BUS_GROUP); - build_service(repo.clone(), locks.clone(), repo.clone()) - .with_lifecycle(lifecycle.clone()) - .with_bus(bus) - }); + host(SqliteStores::connect(database_url).await?, options).await } - spawn_zitadel_scrape(service.clone()); - - eprintln!("e2e-ui (sqlite) listening on http://{}", options.bind); - serve(service, &options).await?; - Ok(()) } -async fn run_postgres( - database_url: &str, - options: HostOptions, -) -> Result<(), Box> { - let repo = PostgresRepository::connect_and_migrate(database_url).await?; - let registry = distributed_manifest() - .table_registry() - .map_err(|e| format!("manifest: {e}"))?; - repo.bootstrap_table_schema_for_dev(®istry).await?; - let locks = PostgresLockManager::new(repo.pool().clone()); - let bus = PostgresBus::new(repo.pool().clone()).group(BUS_GROUP); - bus.ensure_tables().await?; +/// One host path for every SQL backend: the stores, the bus and the GraphQL +/// pool all come from the one database. +async fn host(stores: St, options: HostOptions) -> Result<(), BoxError> { + let read_models = read_models(); + stores.bootstrap_read_models(read_models.catalog()).await?; - let change_rx = repo.read_model_changes(); + let change_rx = stores.read_model_changes(); // Under `distributed dev`, only the active generation may write. let lifecycle = LifecycleGate::from_env(); - let service = build_service(repo.clone(), locks.clone(), repo.clone()) + let service = build_service(&stores) .with_lifecycle(lifecycle.clone()) - .with_bus(PostgresBus::new(repo.pool().clone()).group(BUS_GROUP)); - let versions = if options.delivery != distributed::gateway::DeliveryCapabilities::default() { + .with_bus(stores.bus(BUS_GROUP)); + let versions = if options.delivery != DeliveryCapabilities::default() { Some( - distributed::graphql::delivery::GatewayVersionStore::install( - &distributed::graphql::GraphqlPool::from(repo.pool().clone()), + GatewayVersionStore::install( + stores.graphql_pool().pool(), "e2e-ui-gateway-v1", - [ - "todos".into(), - "chat_messages".into(), - "blob_games".into(), - "auth_users".into(), - ], + read_models.table_names(), ) .await?, ) } else { None }; - let gql = crate::modules::graphql::build_graphql_engine_with_delivery( - &repo, + let gql = build_graphql_engine_with_delivery( + stores.graphql_pool(), &service, options.identity.clone(), Some(change_rx), @@ -163,26 +80,15 @@ async fn run_postgres( )?; let service = Arc::new(service.try_with_graphql(gql)?); - spawn_outbox_publish_loop( - repo.outbox_store(), - Arc::new(PostgresBus::new(repo.pool().clone()).group(BUS_GROUP)), - "e2e-ui", - Duration::from_secs(30), - 5, - ); - { - let repo = repo.clone(); - let locks = locks.clone(); - spawn_service_consumer_loop(move || { - let bus = PostgresBus::new(repo.pool().clone()).group(BUS_GROUP); - build_service(repo.clone(), locks.clone(), repo.clone()) - .with_lifecycle(lifecycle.clone()) - .with_bus(bus) - }); - } + // `with_bus` also drains the outbox, so the consumer is the only loop. + spawn_service_consumer_loop(move || { + build_service(&stores) + .with_lifecycle(lifecycle.clone()) + .with_bus(stores.bus(BUS_GROUP)) + }); spawn_zitadel_scrape(service.clone()); - eprintln!("e2e-ui (postgres) listening on http://{}", options.bind); + eprintln!("e2e-ui listening on http://{}", options.bind); 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 cec92e66d..023b7b6f9 100644 --- a/tests/e2e-ui/crates/service/src/http.rs +++ b/tests/e2e-ui/crates/service/src/http.rs @@ -66,14 +66,8 @@ pub fn gateway_router( } .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"))?; // The application declares the public gateway it is served through. - service - .application(crate::E2E_UI_APPLICATION, surface) + crate::application(&service) .map_err(std::io::Error::other)? .with_gateway("public", &gateway) .map_err(std::io::Error::other)?; diff --git a/tests/e2e-ui/crates/service/src/lib.rs b/tests/e2e-ui/crates/service/src/lib.rs index 7d352d0e6..d9d0d88ce 100644 --- a/tests/e2e-ui/crates/service/src/lib.rs +++ b/tests/e2e-ui/crates/service/src/lib.rs @@ -2,33 +2,31 @@ //! //! # Authoring story //! -//! - [`application`] — surface names and module inventory -//! - [`modules`] — todo / chat / blob mounts + compose + GraphQL +//! - [`application`] — application name and client surfaces +//! - [`modules`] — todo / chat / blob / identity mounts + compose + GraphQL //! - [`host`] — one-screen process bootstrap (`run`) -//! - [`handlers`] — command/event bodies (domain-adjacent, not infrastructure) +//! - [`handlers`] — command bodies of the Zitadel ingress (domain-adjacent) //! //! Domain crates stay pure aggregates; read models live in `e2e-readmodels`; //! portable projections in `e2e-projections`. mod application; -mod bounds; -mod deps; pub mod handlers; mod host; 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, + ClientSurface, ADMIN_CLIENT_SURFACE, CLIENT_SURFACE, CLIENT_SURFACES, E2E_UI_APPLICATION, + PUBLIC_CLIENT_SURFACE, }; -pub use e2e_readmodels::distributed_manifest; +pub use e2e_readmodels::read_models; pub use handlers::ingestors::zitadel::{spawn_scrape_loop, ZitadelScrapeConfig}; pub use host::{run, HostOptions}; 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, - distributed_client_surface, distributed_public_client_surface, identity_from_env, - oidc_bearer_config, + application, application_manifest, build_graphql_engine, dev_identity, + distributed_admin_client_surface, distributed_client_surface, + distributed_public_client_surface, identity_from_env, oidc_bearer_config, }; diff --git a/tests/e2e-ui/crates/service/src/modules/blob.rs b/tests/e2e-ui/crates/service/src/modules/blob.rs index ed2c5d85b..b9b9252e8 100644 --- a/tests/e2e-ui/crates/service/src/modules/blob.rs +++ b/tests/e2e-ui/crates/service/src/modules/blob.rs @@ -1,43 +1,12 @@ -//! Blob game module: Atomic command mounts (direct projection seal). +//! Blob game module: Atomic command mounts. Their `BLOB_GAMES` projection is +//! direct: each command seals its row in its own transaction. use blob_domain::BlobGame; -use distributed::graphql::SurfaceDirectProjection; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; - -use crate::bounds::{EventStore, Locks, ReadStore}; - -/// Logical module id for composition inventories. -pub const MODULE_ID: &str = "blob"; - -type BlobRoutes = - Routes, BlobGame>, S>>; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; /// Mount blob Atomic commands from blob-domain. -pub fn routes( - repo: R, - locks: L, - read_models: S, - _blob_direct: SurfaceDirectProjection, -) -> BlobRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, BlobGame>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let _ = _blob_direct; - Routes::for_aggregate::(repo, locks, read_models) +pub fn routes(stores: &St) -> Routes> { + Routes::for_aggregate(stores) .mount(blob_domain::commands::start()) .mount(blob_domain::commands::move_dir()) .mount(blob_domain::commands::start_level()) diff --git a/tests/e2e-ui/crates/service/src/modules/chat.rs b/tests/e2e-ui/crates/service/src/modules/chat.rs index b400f5773..0f237ca0a 100644 --- a/tests/e2e-ui/crates/service/src/modules/chat.rs +++ b/tests/e2e-ui/crates/service/src/modules/chat.rs @@ -1,44 +1,16 @@ -//! Chat module: room messages and their projector. +//! Chat module: room messages and their projection. use chat_domain::ChatMessage; -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; +use distributed::LocalProjectionMounts; +use e2e_projections::CHAT_MESSAGES; -use crate::bounds::{EventStore, Locks, ReadStore}; -use crate::handlers; - -/// Logical module id for composition inventories. -pub const MODULE_ID: &str = "chat"; - -type ChatRoutes = - Routes, ChatMessage>, S>>; - -/// Mount chat commands and the chat projector. -pub fn routes( - repo: R, - locks: L, - read_models: S, - chat_projector: SurfaceProjector, -) -> ChatRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, ChatMessage>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - Routes::for_aggregate::(repo, locks, read_models) +/// Mount chat commands and the chat projection. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(chat_domain::commands::post()) - .modeled_projector(chat_projector) - .handle(handlers::events::project_chat_messages::handle) + .consume_projection(projections.projector(CHAT_MESSAGES)) } diff --git a/tests/e2e-ui/crates/service/src/modules/compose.rs b/tests/e2e-ui/crates/service/src/modules/compose.rs index 05eb4c1ff..8d11edc8a 100644 --- a/tests/e2e-ui/crates/service/src/modules/compose.rs +++ b/tests/e2e-ui/crates/service/src/modules/compose.rs @@ -1,73 +1,29 @@ //! Compose bounded-context modules into one e2e-ui Service. -use blob_domain::BlobGame; -use chat_domain::ChatMessage; -use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Service}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; -use todo_domain::Todo; +use distributed::microsvc::{Service, ServiceStores}; -use crate::bounds::{EventStore, Locks, ReadStore}; use crate::handlers::ingestors::{zitadel, zitadel_scrape}; -use crate::modules::{blob, chat, identity, projections, todo}; - -/// Explicit module inventory for the e2e-ui application. -pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, - chat::MODULE_ID, - blob::MODULE_ID, - identity::MODULE_ID, -]; +use crate::modules::projections::projections; +use crate::modules::{blob, chat, identity, todo}; +use crate::E2E_UI_APPLICATION; /// Compose todo + chat + blob + identity modules into one Service. /// /// This is the review-visible application wiring: list modules, do not invent -/// infrastructure. Dialect runners and workers live in `host`. -pub fn build_service(repo: R, locks: L, read_models: S) -> Service -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, Todo>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository, ChatMessage>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository, BlobGame>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, - AggregateRepository: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let projections = projections::projection_owners(); - let todos = todo::routes( - repo.clone(), - locks.clone(), - read_models.clone(), - projections.todo, - ); - let chat = chat::routes( - repo.clone(), - locks.clone(), - read_models.clone(), - projections.chat, - ); - let blob = blob::routes(repo.clone(), locks, read_models.clone(), projections.blob); - let identity = identity::routes(repo, read_models, projections.auth); +/// infrastructure. The application's modules are the command namespaces +/// (`todo.*`, `chat.*`, `blob.*`, `zitadel.*`); the host lives in `host`. +pub fn build_service(stores: &St) -> Service { + let projections = projections(); // GraphQL-only public write surface. POST /todo.* stays 404 (suite T0). // Zitadel Action ingress still needs HTTP: its two commands are exposed // through edges that check the shared secret and run as the ingestor. Service::new() - .named("e2e-ui") - .routes(todos) - .routes(chat) - .routes(blob) - .routes(identity) + .named(E2E_UI_APPLICATION) + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections)) .with_http_command(zitadel::COMMAND, zitadel::http_edge) .with_http_command(zitadel_scrape::COMMAND, zitadel_scrape::http_edge) } diff --git a/tests/e2e-ui/crates/service/src/modules/graphql.rs b/tests/e2e-ui/crates/service/src/modules/graphql.rs index bc19149be..1acb2bf11 100644 --- a/tests/e2e-ui/crates/service/src/modules/graphql.rs +++ b/tests/e2e-ui/crates/service/src/modules/graphql.rs @@ -1,38 +1,25 @@ -use std::sync::Arc; - -use distributed::application::CommandDefinition; use distributed::graphql::{ build_surface, surface_for_application, DistributedClientSurfaceExport, GraphqlEngine, GraphqlPoolSource, IdentityConfig, OidcConfig, Surface, SurfaceOptions, }; -use distributed::microsvc::Service; +use distributed::microsvc::{Service, Stores}; use distributed::{ - Application, ApplicationManifest, InMemoryLockManager, InMemoryRepository, LockError, - LockManager, Module, SurfaceSpec, + Application, ApplicationError, ApplicationManifest, InMemoryLockManager, InMemoryRepository, + SurfaceSpec, }; -use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; +use e2e_readmodels::read_models; use crate::application::{ - DISTRIBUTED_ADMIN_CLIENT_SURFACE, DISTRIBUTED_CLIENT_SURFACE, - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, E2E_UI_APPLICATION, E2E_UI_MODULE_IDS, + ClientSurface, ADMIN_CLIENT_SURFACE, CLIENT_SURFACE, CLIENT_SURFACES, E2E_UI_APPLICATION, + PUBLIC_CLIENT_SURFACE, }; -use crate::modules::{identity, projections}; +use crate::modules::compose::build_service; +use crate::modules::projections::projections; // Stable only for this local copyable fixture. Real deployments must inject // their own per-deployment key rather than copying this development value. const E2E_PROTOCOL_TOKEN_KEY: [u8; 32] = [0xe2; 32]; -#[derive(Clone, Default)] -pub(crate) struct ClientSurfaceLocks(Arc); - -impl LockManager for ClientSurfaceLocks { - type Lock = distributed::InMemoryLock; - - fn get_lock(&self, id: &str) -> Result, LockError> { - self.0.get_lock(id) - } -} - /// GraphQL over todos + chat + blob + AuthUsers. pub fn build_graphql_engine( pool: impl Into, @@ -78,30 +65,21 @@ fn build_engine( graphiql: bool, versions: Option, ) -> Result { - let projections = projections::projection_owners(); let mut b = GraphqlEngine::builder(pool) .protocol_token_key(E2E_PROTOCOL_TOKEN_KEY) .roles(&["user", "admin", "anonymous"]) - .client_application_surface(DISTRIBUTED_CLIENT_SURFACE, ["admin", "user"], ["user"]) - .client_application_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, ["admin"], ["admin"]) - .client_application_surface( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - ["anonymous"], - ["anonymous"], - ) - .model::(Todos::permissions()) - .model::(ChatMessages::permissions()) - .model::(BlobGames::permissions()) - .model::(AuthUsers::permissions()) + .read_models(&read_models()) .service(service) - .client_projection_owners([ - projections.todo.into(), - projections.chat.into(), - projections.blob.into(), - projections.auth.into(), - ]) + .client_projection_owners(projections().all_owners()) .identity(identity) .graphiql(graphiql); + for surface in CLIENT_SURFACES { + b = b.client_application_surface( + surface.name, + surface.eligible_roles.iter().copied(), + surface.schema_roles.iter().copied(), + ); + } if let Some(rx) = change_rx { b = b.change_stream(rx); } @@ -111,121 +89,71 @@ fn build_engine( b.build().map_err(|e| e.to_string()) } -fn pool_free_client_surface(application: &str, roles: &[&str]) -> DistributedClientSurfaceExport { - pool_free_client_surface_contract(application, roles, roles) -} - -fn pool_free_client_surface_contract( - application: &str, - eligible_roles: &[&str], - schema_roles: &[&str], -) -> DistributedClientSurfaceExport { - let full = pool_free_full_surface(); - let eligible = eligible_roles - .iter() - .map(|role| (*role).to_string()) - .collect::>(); - let schema = schema_roles - .iter() - .map(|role| (*role).to_string()) - .collect::>(); - let grants = e2e_readmodels::application_grants(); - let selected = surface_for_application(&full, application, &eligible, &schema, &grants) - .expect("e2e-ui application Surface should select"); - DistributedClientSurfaceExport::from_selected("e2e-ui", selected) - .expect("e2e-ui application Surface should export") +/// The application's full Surface: every read model, projection and command. +fn full_surface(service: &Service) -> Result { + build_surface(&read_models().catalog().tables, &SurfaceOptions::sqlite()) + .and_then(|surface| surface.with_projection_owners(projections().all_owners())) + .and_then(|surface| surface.with_service(service)) + .map_err(ApplicationError::InvalidSpec) } -fn pool_free_full_surface() -> Surface { - let project = e2e_readmodels::distributed_manifest(); - let service = pool_free_service(); - let projections = projections::projection_owners(); - build_surface(&project.tables, &SurfaceOptions::sqlite()) - .expect("e2e-ui client Surface should build") - .with_projection_owners([ - projections.todo.into(), - projections.chat.into(), - projections.blob.into(), - projections.auth.into(), - ]) - .expect("e2e-ui projector topology should bind") - .with_service(&service) - .expect("e2e-ui typed Service inventory should bind") +/// The logical application: the Service's command namespaces as modules, +/// bound to the full Surface. +pub fn application(service: &Service) -> Result { + let surface = SurfaceSpec::from_surface(E2E_UI_APPLICATION, &full_surface(service)?)?; + service.application(E2E_UI_APPLICATION, surface) } +/// A Service with in-memory stores: its command inventory without a database. fn pool_free_service() -> Service { let repository = InMemoryRepository::new(); - crate::modules::compose::build_service( + build_service(&Stores::new( repository.clone(), - ClientSurfaceLocks::default(), + InMemoryLockManager::new(), repository, - ) + )) } /// Logical application artifact consumed by `distributed describe` and the /// coherent lifecycle builder. Runtime handlers and repositories are erased. pub fn application_manifest() -> ApplicationManifest { - let surface = SurfaceSpec::from_surface(E2E_UI_APPLICATION, &pool_free_full_surface()) - .expect("e2e-ui full Surface should compile into an application artifact"); - - let commands = pool_free_service() - .command_specs() - .expect("e2e-ui typed commands should compile into portable specs") - .into_iter() - .map(|command| { - let exposed = surface - .contract - .commands - .iter() - .find(|exposed| exposed.id == command.id) - .expect("full e2e-ui Surface should expose every application command"); - command - .with_surface_binding(exposed) - .expect("e2e-ui Surface command should bind to its portable declaration") - }) - .collect::>(); - let modules = E2E_UI_MODULE_IDS - .iter() - .map(|module_id| { - // A module's commands are named `{module}.…`; the identity - // module's are named for their provider. - let prefix = match *module_id { - identity::MODULE_ID => identity::COMMAND_PREFIX.to_string(), - module_id => format!("{module_id}."), - }; - let definitions = commands - .iter() - .filter(|command| command.id.starts_with(&prefix)) - .cloned() - .map(CommandDefinition::contract) - .collect::>(); - Module::new(*module_id) - .command_definitions(definitions) - .build() - .expect("e2e-ui application module should compile") - }) - .collect::>(); - - Application::new(E2E_UI_APPLICATION) - .modules(modules) - .surface(surface) - .build() + application(&pool_free_service()) .expect("e2e-ui application manifest should compile") .manifest() .clone() } +fn client_surface(surface: ClientSurface) -> DistributedClientSurfaceExport { + let full = full_surface(&pool_free_service()).expect("e2e-ui client Surface should build"); + let roles = |roles: &[&str]| { + roles + .iter() + .map(|role| (*role).to_string()) + .collect::>() + }; + let selected = surface_for_application( + &full, + surface.name, + &roles(surface.eligible_roles), + &roles(surface.schema_roles), + &read_models().grants(), + ) + .expect("e2e-ui application Surface should select"); + DistributedClientSurfaceExport::from_selected(E2E_UI_APPLICATION, selected) + .expect("e2e-ui application Surface should export") +} + /// Pool-free normal application export consumed by `distributed client-manifest`. pub fn distributed_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface_contract(DISTRIBUTED_CLIENT_SURFACE, &["admin", "user"], &["user"]) + client_surface(CLIENT_SURFACE) } pub fn distributed_admin_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, &["admin"]) + client_surface(ADMIN_CLIENT_SURFACE) } pub fn distributed_public_client_surface() -> DistributedClientSurfaceExport { - pool_free_client_surface(DISTRIBUTED_PUBLIC_CLIENT_SURFACE, &["anonymous"]) + client_surface(PUBLIC_CLIENT_SURFACE) } pub fn dev_identity() -> IdentityConfig { @@ -305,9 +233,6 @@ pub fn oidc_bearer_config( #[cfg(test)] mod client_surface_tests { use super::*; - use crate::application::{DISTRIBUTED_CLIENT_SURFACE, DISTRIBUTED_PUBLIC_CLIENT_SURFACE}; - use crate::modules::compose::build_service; - use distributed::InMemoryRepository; #[test] fn application_manifest_compiles_real_modules_and_surfaces() { @@ -318,7 +243,7 @@ mod client_surface_tests { assert_eq!(manifest.name, "e2e-ui"); assert_eq!( manifest.module_ids(), - vec!["blob", "chat", "identity", "todo"] + vec!["blob", "chat", "todo", "zitadel"] ); assert_eq!(manifest.surfaces.len(), 1); assert!(!manifest.commands.is_empty()); @@ -624,13 +549,7 @@ mod client_surface_tests { .expect("Blob direct owner should be exported"); assert!(owner.facts.is_empty()); - let repository = InMemoryRepository::new(); - let service = build_service( - repository.clone(), - crate::modules::graphql::ClientSurfaceLocks::default(), - repository, - ); - let plan = service.subscription_plan(); + let plan = pool_free_service().subscription_plan(); for event in [ "todo.created", "todo.renamed", @@ -666,11 +585,11 @@ mod client_surface_tests { .connect_lazy("postgres://postgres:postgres@localhost/distributed") .unwrap(); let repository = distributed::PostgresRepository::new(pool.clone()); - let service = build_service( + let service = build_service(&Stores::new( repository.clone(), distributed::PostgresLockManager::new(pool), repository.clone(), - ); + )); let engine = crate::modules::graphql::build_graphql_engine_with_graphiql( &repository, &service, @@ -681,9 +600,9 @@ mod client_surface_tests { .expect("engine"); let runtime = engine .client_manifest_for_application( - DISTRIBUTED_CLIENT_SURFACE, - &["admin", "user"], - &["user"], + CLIENT_SURFACE.name, + CLIENT_SURFACE.eligible_roles, + CLIENT_SURFACE.schema_roles, ) .unwrap(); @@ -697,9 +616,9 @@ mod client_surface_tests { "client": { "surface": { "kind": "application", - "name": DISTRIBUTED_CLIENT_SURFACE, - "eligible_roles": ["admin", "user"], - "schema_roles": ["user"] + "name": CLIENT_SURFACE.name, + "eligible_roles": CLIENT_SURFACE.eligible_roles, + "schema_roles": CLIENT_SURFACE.schema_roles }, "schemaHash": generated.schema_fingerprint } @@ -747,28 +666,23 @@ mod client_surface_tests { assert_eq!( generated.surface, distributed::graphql::ClientSurfaceIdentity::application( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - ["anonymous"], - ["anonymous"], + PUBLIC_CLIENT_SURFACE.name, + PUBLIC_CLIENT_SURFACE.eligible_roles.iter().copied(), + PUBLIC_CLIENT_SURFACE.schema_roles.iter().copied(), ) ); - let repository = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + use distributed::microsvc::{SqlStores, SqliteStores}; + + let stores = SqliteStores::connect("sqlite::memory:") .await - .expect("sqlite memory repo"); - let registry = e2e_readmodels::distributed_manifest() - .table_registry() - .expect("registry"); - repository - .bootstrap_table_schema_for_dev(®istry) + .expect("sqlite memory stores"); + stores + .bootstrap_read_models(read_models().catalog()) .await .expect("bootstrap tables"); - let service = build_service( - repository.clone(), - crate::modules::graphql::ClientSurfaceLocks::default(), - repository.clone(), - ); + let service = build_service(&stores); let engine = crate::modules::graphql::build_graphql_engine_with_graphiql( - &repository, + stores.graphql_pool(), &service, dev_identity(), None, @@ -777,9 +691,9 @@ mod client_surface_tests { .expect("engine"); let runtime = engine .client_manifest_for_application( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - &["anonymous"], - &["anonymous"], + PUBLIC_CLIENT_SURFACE.name, + PUBLIC_CLIENT_SURFACE.eligible_roles, + PUBLIC_CLIENT_SURFACE.schema_roles, ) .expect("public surface registered"); assert_eq!(generated.schema_fingerprint, runtime.schema_fingerprint); @@ -791,9 +705,9 @@ mod client_surface_tests { "client": { "surface": { "kind": "application", - "name": DISTRIBUTED_PUBLIC_CLIENT_SURFACE, - "eligible_roles": ["anonymous"], - "schema_roles": ["anonymous"] + "name": PUBLIC_CLIENT_SURFACE.name, + "eligible_roles": PUBLIC_CLIENT_SURFACE.eligible_roles, + "schema_roles": PUBLIC_CLIENT_SURFACE.schema_roles }, "schemaHash": generated.schema_fingerprint } diff --git a/tests/e2e-ui/crates/service/src/modules/identity.rs b/tests/e2e-ui/crates/service/src/modules/identity.rs index f7b61e90d..87c11ed0d 100644 --- a/tests/e2e-ui/crates/service/src/modules/identity.rs +++ b/tests/e2e-ui/crates/service/src/modules/identity.rs @@ -4,48 +4,32 @@ //! No aggregate: the commands publish user profiles as external facts, which //! commit with their ledger receipts; the `AUTH_USERS` projection writes them. -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Routes}; -use distributed::AggregateRepository; +use distributed::microsvc::{Routes, ServiceStores, StoreDependencies}; +use distributed::LocalProjectionMounts; +use e2e_projections::AUTH_USERS; -use crate::bounds::{EventStore, ReadStore}; -use crate::deps::AuthDeps; use crate::handlers::ingestors::{zitadel, zitadel_scrape}; -/// Logical module id for composition inventories. -pub const MODULE_ID: &str = "identity"; - -/// Prefix of this module's command names (they are named for the provider). -pub const COMMAND_PREFIX: &str = "zitadel."; - /// Mount the Zitadel ingress and scrape commands and the auth_users /// projection. -pub fn routes( - repo: R, - read_models: S, - auth_projector: SurfaceProjector, -) -> Routes> -where - R: EventStore, - S: ReadStore, - AggregateRepository: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - let scrape = zitadel_scrape::Scrape(read_models.clone()); - Routes::for_stores(repo, read_models) +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + let scrape = zitadel_scrape::Scrape(stores.read_models().clone()); + Routes::for_stores(stores.events().clone(), stores.read_models().clone()) .typed_command(zitadel::command()) .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) .handle(scrape) - .consume_projection(auth_projector) + .consume_projection(projections.projector(AUTH_USERS)) } #[cfg(test)] mod tests { use distributed::bus::{InMemoryBus, RunOptions}; - use distributed::{ - ReadModelWorkspaceExt, RowKey, RowValue, SqliteLockManager, SqliteRepository, - }; + use distributed::microsvc::{SqlStores, SqliteStores}; + use distributed::{ReadModelWorkspaceExt, RowKey, RowValue}; use e2e_readmodels::AuthUsers; use serde_json::json; @@ -56,17 +40,13 @@ mod tests { #[tokio::test] async fn an_ingested_profile_reaches_auth_users_through_the_projection() { - let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") - .await - .unwrap(); - let registry = crate::distributed_manifest().table_registry().unwrap(); - repo.bootstrap_table_schema_for_dev(®istry) + let stores = SqliteStores::connect("sqlite::memory:").await.unwrap(); + stores + .bootstrap_read_models(e2e_readmodels::read_models().catalog()) .await .unwrap(); - let locks = SqliteLockManager::new(repo.pool().clone()); let bus = InMemoryBus::new(); - let service = - || build_service(repo.clone(), locks.clone(), repo.clone()).with_bus(bus.clone()); + let service = || build_service(&stores).with_bus(bus.clone()); let input = normalize_ingress_body(&json!({ "event_id": "evt-1", @@ -86,7 +66,8 @@ mod tests { .unwrap(); service().run(RunOptions::until_idle()).await.unwrap(); - let row = repo + let row = stores + .read_models .workspace() .load::(RowKey::new([("user_id", RowValue::String("sub-1".into()))])) .one() diff --git a/tests/e2e-ui/crates/service/src/modules/projections.rs b/tests/e2e-ui/crates/service/src/modules/projections.rs index cc42d236d..87f16d9a8 100644 --- a/tests/e2e-ui/crates/service/src/modules/projections.rs +++ b/tests/e2e-ui/crates/service/src/modules/projections.rs @@ -1,47 +1,19 @@ //! e2e-ui projection mounts — product declaration only. //! -//! Topology, catalog activation, and Surface packaging come from -//! [`distributed::LocalProjectionMountsBuilder`]. +//! Each projection is mounted from its `projection!` descriptor, which names +//! it, pins its epoch and its model. Topology, catalog activation, and Surface +//! packaging come from [`distributed::LocalProjectionMounts`]. -use distributed::graphql::{SurfaceDirectProjection, SurfaceProjector}; -use distributed::LocalProjectionMountsBuilder; +use distributed::LocalProjectionMounts; use e2e_projections::{AUTH_USERS, BLOB_GAMES, CHAT_MESSAGES, TODOS}; -use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; -/// Projection surface mounts used by compose + GraphQL. -#[derive(Clone)] -pub struct ProjectionOwners { - pub todo: SurfaceProjector, - pub chat: SurfaceProjector, - pub blob: SurfaceDirectProjection, - pub auth: SurfaceProjector, -} - -/// Compile local projection mounts for the e2e-ui application. -pub fn projection_owners() -> ProjectionOwners { - let mounts = LocalProjectionMountsBuilder::new("e2e-ui", "ordered-domain-events") - .expect("projection source") - .eventual_model::("project_todos", TODOS, "e2e-ui-todos-v2") - .expect("todo mount") - .eventual_model::("project_chat_messages", CHAT_MESSAGES, "e2e-ui-chat-v2") - .expect("chat mount") - .direct_model::("project_blob", BLOB_GAMES, "e2e-ui-blob-v2") - .expect("blob mount") - .eventual_model::("project_auth_users", AUTH_USERS, "e2e-ui-auth-users-v1") - .expect("auth users mount") +/// Every projection of the application, mounted for one local process. +pub fn projections() -> LocalProjectionMounts { + LocalProjectionMounts::builder("e2e-ui", "ordered-domain-events") + .eventual(TODOS) + .eventual(CHAT_MESSAGES) + .direct(BLOB_GAMES) + .eventual(AUTH_USERS) .build() - .expect("projection catalog"); - - ProjectionOwners { - todo: mounts.projector("project_todos").expect("todo projector"), - chat: mounts - .projector("project_chat_messages") - .expect("chat projector"), - blob: mounts - .direct_projection("project_blob") - .expect("blob direct"), - auth: mounts - .projector("project_auth_users") - .expect("auth users projector"), - } + .expect("e2e-ui projection catalog") } diff --git a/tests/e2e-ui/crates/service/src/modules/todo.rs b/tests/e2e-ui/crates/service/src/modules/todo.rs index c73ff618f..d7457157b 100644 --- a/tests/e2e-ui/crates/service/src/modules/todo.rs +++ b/tests/e2e-ui/crates/service/src/modules/todo.rs @@ -1,43 +1,16 @@ -//! Todo bounded-context module: command mounts + eventual projector. +//! Todo bounded-context module: command mounts + eventual projection. -use distributed::graphql::SurfaceProjector; -use distributed::microsvc::{ - ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, RepoReadModelDependencies, Routes, -}; -use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; +use distributed::microsvc::{AggregateDependencies, Routes, ServiceStores}; +use distributed::LocalProjectionMounts; +use e2e_projections::TODOS; use todo_domain::Todo; -use crate::bounds::{EventStore, Locks, ReadStore}; -use crate::handlers; - -/// Logical module id for composition inventories. -pub const MODULE_ID: &str = "todo"; - -type TodoRoutes = - Routes, Todo>, S>>; - -/// Mount todo commands and the todo projector. -pub fn routes( - repo: R, - locks: L, - read_models: S, - todo_projector: SurfaceProjector, -) -> TodoRoutes -where - R: EventStore, - L: Locks, - S: ReadStore, - QueuedRepository: Clone - + AggregateBuilder - + HasOutboxStore - + distributed::TransactionalCommit - + Send - + Sync - + 'static, - AggregateRepository, Todo>: - HasRepo + HasOutboxStore + ConfigurableOutboxPublisher + Send + Sync + 'static, -{ - Routes::for_aggregate::(repo, locks, read_models) +/// Mount todo commands and the todo projection. +pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(todo_domain::commands::create()) .mount(todo_domain::commands::rename()) .mount(todo_domain::commands::complete()) @@ -45,6 +18,5 @@ where .mount(todo_domain::commands::archive()) .mount(todo_domain::commands::force_archive()) .mount(todo_domain::commands::purge()) - .modeled_projector(todo_projector) - .handle(handlers::events::project_todos::handle) + .consume_projection(projections.projector(TODOS)) } diff --git a/tests/e2e-ui/crates/suite/src/lib.rs b/tests/e2e-ui/crates/suite/src/lib.rs index 6709418be..2d8167c1e 100644 --- a/tests/e2e-ui/crates/suite/src/lib.rs +++ b/tests/e2e-ui/crates/suite/src/lib.rs @@ -80,11 +80,7 @@ fn with_identity( if OFFLINE_OIDC_ENABLED.load(Ordering::Acquire) { request.bearer_auth(offline_bearer(user_id, role)) } else { - let roles = if role == "admin" { - "admin,user" - } else { - role - }; + let roles = if role == "admin" { "admin,user" } else { role }; request .header("x-user-id", user_id) .header("x-roles", roles) @@ -145,33 +141,20 @@ fn default_application_surface( role: &str, ) -> Result<(&'static str, Vec<&'static str>, Vec<&'static str>, String), String> { use e2e_service::{ - distributed_admin_client_surface, distributed_client_surface, DISTRIBUTED_ADMIN_CLIENT_SURFACE, - DISTRIBUTED_CLIENT_SURFACE, + distributed_admin_client_surface, distributed_client_surface, ADMIN_CLIENT_SURFACE, + CLIENT_SURFACE, }; - match role { - "admin" => { - let manifest = distributed_admin_client_surface() - .manifest() - .map_err(|e| e.to_string())?; - Ok(( - DISTRIBUTED_ADMIN_CLIENT_SURFACE, - vec!["admin"], - vec!["admin"], - manifest.schema_fingerprint, - )) - } - _ => { - let manifest = distributed_client_surface() - .manifest() - .map_err(|e| e.to_string())?; - Ok(( - DISTRIBUTED_CLIENT_SURFACE, - vec!["admin", "user"], - vec!["user"], - manifest.schema_fingerprint, - )) - } - } + let (surface, export) = match role { + "admin" => (ADMIN_CLIENT_SURFACE, distributed_admin_client_surface()), + _ => (CLIENT_SURFACE, distributed_client_surface()), + }; + let manifest = export.manifest().map_err(|e| e.to_string())?; + Ok(( + surface.name, + surface.eligible_roles.to_vec(), + surface.schema_roles.to_vec(), + manifest.schema_fingerprint, + )) } pub async fn graphql_for_application( diff --git a/tests/e2e-ui/crates/suite/tests/behavioral.rs b/tests/e2e-ui/crates/suite/tests/behavioral.rs index 3ccdf9916..7b52a6158 100644 --- a/tests/e2e-ui/crates/suite/tests/behavioral.rs +++ b/tests/e2e-ui/crates/suite/tests/behavioral.rs @@ -8,10 +8,9 @@ use std::time::Duration; use distributed::bus::{InMemoryBus, RunOptions}; use distributed::microsvc::serve; -use distributed::{SqliteLockManager, SqliteRepository}; +use distributed::microsvc::{SqlStores, SqliteStores}; use e2e_service::{ - build_graphql_engine, build_service, distributed_client_surface, distributed_manifest, - DISTRIBUTED_CLIENT_SURFACE, + build_graphql_engine, build_service, distributed_client_surface, read_models, CLIENT_SURFACE, }; use e2e_suite::{ assert_http_commands_disabled, cases, graphql, graphql_for_application, graphql_raw, @@ -37,42 +36,40 @@ async fn ensure_target() -> String { let base = format!("http://{bind}"); // Always in-memory SQLite for offline suite (ignore compose DATABASE_URL=postgres). - let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") + let stores = SqliteStores::connect("sqlite::memory:") .await - .expect("repo"); - let registry = distributed_manifest().table_registry().expect("registry"); - repo.bootstrap_table_schema_for_dev(®istry) + .expect("stores"); + stores + .bootstrap_read_models(read_models().catalog()) .await .expect("bootstrap"); - let locks = SqliteLockManager::new(repo.pool().clone()); let bus = InMemoryBus::new(); - let change_rx = repo.read_model_changes(); + let change_rx = stores.read_model_changes(); // Offline suite uses a synthetic signed static-JWKS bearer. Durable command // tests exercise the same VerifiedPrincipal fence as production. - let service = build_service(repo.clone(), locks.clone(), repo.clone()).with_bus(bus.clone()); - let gql = build_graphql_engine(&repo, &service, offline_oidc_identity(), Some(change_rx)) - .expect("gql"); + let service = build_service(&stores).with_bus(bus.clone()); + let gql = build_graphql_engine( + stores.graphql_pool(), + &service, + offline_oidc_identity(), + Some(change_rx), + ) + .expect("gql"); let service = Arc::new(service.try_with_graphql(gql).expect("bind gql")); // Projector consumer (eventual consistency path — no command-side dual-write). - let consumer_repo = repo.clone(); - let consumer_locks = locks.clone(); + let consumer_stores = stores.clone(); let bus_c = bus.clone(); tokio::spawn(async move { loop { - let service = build_service( - consumer_repo.clone(), - consumer_locks.clone(), - consumer_repo.clone(), - ) - .with_bus(bus_c.clone()); + let service = build_service(&consumer_stores).with_bus(bus_c.clone()); if let Err(error) = service.run(RunOptions::until_idle()).await { eprintln!("offline projector loop: {error}"); if let Ok(Some((code, detail))) = sqlx::query_as::<_, (String, Vec)>( "SELECT failure_code, failure_bytes FROM projection_failures LIMIT 1", ) - .fetch_optional(consumer_repo.pool()) + .fetch_optional(consumer_stores.events.pool()) .await { eprintln!( @@ -161,9 +158,9 @@ async fn t1a_application_surface_returns_actual_todo_upsert_and_causal_obligatio &mutation, "alice", "user", - DISTRIBUTED_CLIENT_SURFACE, - &["admin", "user"], - &["user"], + CLIENT_SURFACE.name, + CLIENT_SURFACE.eligible_roles, + CLIENT_SURFACE.schema_roles, &manifest.schema_fingerprint, ) .await @@ -397,16 +394,21 @@ async fn t2c_admin_force_archive() { /// Role SDL: force-archive only on admin schema (engine source of truth). #[tokio::test] async fn t2d_sdl_role_split_force_archive() { - let repo = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + let stores = SqliteStores::connect("sqlite::memory:") .await - .expect("repo"); - let registry = distributed_manifest().table_registry().expect("registry"); - repo.bootstrap_table_schema_for_dev(®istry) + .expect("stores"); + stores + .bootstrap_read_models(read_models().catalog()) .await .expect("bootstrap"); - let locks = distributed::SqliteLockManager::new(repo.pool().clone()); - let service = build_service(repo.clone(), locks, repo.clone()); - let engine = build_graphql_engine(&repo, &service, offline_oidc_identity(), None).expect("gql"); + let service = build_service(&stores); + let engine = build_graphql_engine( + stores.graphql_pool(), + &service, + offline_oidc_identity(), + None, + ) + .expect("gql"); let user_sdl = engine.sdl_for_role("user").expect("user sdl"); let admin_sdl = engine.sdl_for_role("admin").expect("admin sdl"); assert!( 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 f3dcdc951..575b47b7d 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/create.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/create.rs @@ -3,8 +3,8 @@ use distributed::command::Eventual; use distributed::command_input_defaults; use serde::{Deserialize, Serialize}; -use super::support::authenticated_user; use crate::{domain_commands, Todo, TodoState}; +use distributed::microsvc::guards; #[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoCreateInput { @@ -30,7 +30,7 @@ command! { roles: ["user", "admin"], field: "todos_create", load: create, - guard: authenticated_user, + guard: guards::authenticated, invoke: |todo, input, principal| todo.create(&input.todo_id, principal, &input.title), payload: |todo, _principal| { let state = TodoState::from(&**todo); 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 905d5375a..77413373f 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 @@ -2,8 +2,8 @@ use distributed::command; use distributed::command::Eventual; use serde::{Deserialize, Serialize}; -use super::support::admin_user; use crate::{domain_commands, Todo, TodoState}; +use distributed::microsvc::guards; #[derive(Debug, Deserialize, distributed::CommandInput)] pub struct TodoForceArchiveInput { @@ -28,7 +28,7 @@ command! { roles: ["admin"], field: "todos_force_archive", load: required, - guard: admin_user, + guard: guards::role("admin"), invoke: |todo, _input, _principal| todo.force_archive(), payload: |todo, principal| { let state = TodoState::from(&**todo); diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/mod.rs b/tests/e2e-ui/crates/todo-domain/src/commands/mod.rs index 2dc447755..3fa67d243 100644 --- a/tests/e2e-ui/crates/todo-domain/src/commands/mod.rs +++ b/tests/e2e-ui/crates/todo-domain/src/commands/mod.rs @@ -10,7 +10,6 @@ mod force_archive; mod purge; mod rename; mod reopen; -mod support; pub use archive::{archive, Archive, TodoArchiveInput, TodoArchivePayload}; pub use complete::{complete, Complete, TodoCompleteInput, TodoStatusPayload}; diff --git a/tests/e2e-ui/crates/todo-domain/src/commands/support.rs b/tests/e2e-ui/crates/todo-domain/src/commands/support.rs deleted file mode 100644 index 908c4146a..000000000 --- a/tests/e2e-ui/crates/todo-domain/src/commands/support.rs +++ /dev/null @@ -1,16 +0,0 @@ -use distributed::microsvc::CausalCommandContext; -use distributed::Aggregate; - -pub(super) fn authenticated_user(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - ctx.session().user_id().is_some_and(|id| !id.is_empty()) -} - -pub(super) fn admin_user(ctx: &CausalCommandContext<'_, A>) -> bool -where - A: Aggregate + Send + Sync + 'static, -{ - authenticated_user(ctx) && ctx.session().has_role("admin") -} diff --git a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts index 01d20c8da..4dd05c7e5 100644 --- a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts +++ b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts @@ -16,7 +16,7 @@ import type { DemoWalkthrough, WalkthroughSample } from './types'; * Query tabs must include the read-model struct, not only permissions or GraphQL. * * Service tab must always show: - * - this demo modules/*.rs slice (MODULE_ID + routes) + * - this demo modules/*.rs slice (routes) * - compose.build_service (how modules join one Service) * - host.run (database, bus, workers, GraphQL serve) * - runner main (environment → run) @@ -40,17 +40,20 @@ pub async fn run( database_url: &str, options: HostOptions, // bind, identity, origins, gateway delivery ) -> Result<(), Box> { - // postgres:// → run_postgres, else run_sqlite. Each one: - // connect, create tables, open the bus. - let service = build_service(repo.clone(), locks.clone(), repo.clone()) - .with_bus(bus); + // postgres:// → PostgresStores, else SqliteStores; one host for both. + host(SqliteStores::connect(database_url).await?, options).await +} + +async fn host(stores: St, options: HostOptions) -> Result<(), BoxError> { + stores.bootstrap_read_models(read_models().catalog()).await?; + // with_bus also drains the outbox to the bus. + let service = build_service(&stores).with_bus(stores.bus("e2e-ui")); let gql = build_graphql_engine_with_delivery( - &repo, &service, options.identity.clone(), Some(change_rx), versions, + stores.graphql_pool(), &service, options.identity.clone(), Some(change_rx), versions, )?; let service = Arc::new(service.try_with_graphql(gql)?); - spawn_outbox_publish_loop(/* outbox → bus */); - spawn_service_consumer_loop(move || build_service(/* … */).with_bus(bus)); + spawn_service_consumer_loop(move || build_service(&stores).with_bus(stores.bus("e2e-ui"))); spawn_zitadel_scrape(service.clone()); // only when Zitadel env is set serve(service, &options).await @@ -128,8 +131,8 @@ pub struct Todos { { file: 'readmodels/models/todos.rs · permissions', caption: 'A user can read only the rows that the user owns. An admin can read all rows.', - code: `impl Todos { - pub fn permissions() -> ModelPermissions { + code: `impl AuthorizedReadModel for Todos { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", @@ -185,7 +188,7 @@ await commands.todo.complete({ todo_id });` { file: 'modules/todo.rs · mount', caption: 'The service (or cell) mounts the same domain values. Roles and handlers live in todo-domain.', - code: `Routes::for_aggregate::(repo, locks, read_models) + code: `Routes::for_aggregate(stores) .mount(todo_domain::commands::create()) .mount(todo_domain::commands::complete()) .mount(todo_domain::commands::force_archive())` @@ -350,38 +353,37 @@ mutation DeleteTodo { principle: 'Compose modules into one Service. Let the host start the process. Keep the runner small.', samples: [ { - file: 'modules/todo.rs · MODULE_ID + routes()', - caption: 'This module lists the Todo commands and the Eventual projector. Both hosts call the same mounts.', - code: `pub const MODULE_ID: &str = "todo"; - -pub fn routes(...) -> TodoRoutes { - Routes::for_aggregate::(repo, locks, read_models) + file: 'modules/todo.rs · routes()', + caption: 'This module lists the Todo commands and the Eventual projection. Both hosts call the same mounts.', + code: `pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(todo_domain::commands::create()) .mount(todo_domain::commands::complete()) // … rename, reopen, archive, force_archive, purge … - .modeled_projector(todo_projector) - .handle(handlers::events::project_todos::handle) + .consume_projection(projections.projector(TODOS)) }` }, { file: 'modules/compose.rs · build_service', caption: 'List each module here. Do not hide composition in infrastructure code.', - code: `let todos = todo::routes(repo.clone(), locks.clone(), read_models.clone(), projections.todo); -let chat = chat::routes(/* … */); -let blob = blob::routes(/* … */); - -Service::new() + code: `Service::new() .named("e2e-ui") - .routes(todos) - .routes(chat) - .routes(blob)` + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections))` }, { - file: 'application.rs · inventory', - caption: 'The surface names and the module list live at the service root.', - code: `pub const E2E_UI_APPLICATION: &str = "e2e-ui"; -pub const E2E_UI_MODULE_IDS: &[&str] = compose::MODULE_IDS; -// todo | chat | blob | identity` + file: 'graphql.rs · application', + caption: 'The application manifest is derived from the Service. Its modules are the command namespaces. Do not list them by hand.', + code: `pub fn application(service: &Service) -> Result { + let surface = SurfaceSpec::from_surface(E2E_UI_APPLICATION, &full_surface(service)?)?; + service.application(E2E_UI_APPLICATION, surface) +} +// modules: blob | chat | todo | zitadel` }, ...hostAndRunnerSamples, { @@ -461,8 +463,8 @@ pub struct ChatMessages { { file: 'readmodels/models/chat_messages.rs · permissions', caption: 'Users, admins, and anonymous guests can read all columns.', - code: `impl ChatMessages { - pub fn permissions() -> ModelPermissions { + code: `impl AuthorizedReadModel for ChatMessages { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant("user", read().all_columns()) .grant("admin", read().all_columns()) @@ -681,23 +683,19 @@ mutation SaveChatMessage { { file: 'modules/chat.rs · routes()', caption: 'This module mounts ChatMessage commands and the chat projector.', - code: `pub const MODULE_ID: &str = "chat"; - -pub fn routes(...) -> ChatRoutes { - Routes::for_aggregate::(repo, locks, read_models) + code: `pub fn routes( + stores: &St, + projections: &LocalProjectionMounts, +) -> Routes> { + Routes::for_aggregate(stores) .mount(chat_domain::commands::post()) - .modeled_projector(chat_projector) - .handle(project_chat_messages::handle) + .consume_projection(projections.projector(CHAT_MESSAGES)) }` }, { - file: 'modules/compose.rs · MODULE_IDS + build_service', + file: 'modules/compose.rs · build_service', caption: 'The module list is explicit: todo, chat, blob, and identity.', - code: `pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, chat::MODULE_ID, blob::MODULE_ID, identity::MODULE_ID, -]; - -Service::new() + code: `Service::new() .named("e2e-ui") .routes(todo::routes(/* … */)) .routes(chat::routes(/* … */)) // ← this module @@ -772,8 +770,8 @@ pub struct BlobGames { { file: 'readmodels/models/blob_games.rs · permissions', caption: 'A user can read only owned rows. An admin can read all rows. This is the same claim pattern as todos.', - code: `impl BlobGames { - pub fn permissions() -> ModelPermissions { + code: `impl AuthorizedReadModel for BlobGames { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", @@ -1027,12 +1025,10 @@ mutation SaveBlobGame { principle: 'Compose modules into one Service. Let the host start the process. Keep the runner small.', samples: [ { - file: 'modules/blob.rs · MODULE_ID + routes()', + file: 'modules/blob.rs · routes()', caption: 'This module mounts start, move, and start_level. All three are Atomic. Move declares the WASM pure function.', - code: `pub const MODULE_ID: &str = "blob"; - -pub fn routes(...) -> BlobRoutes { - Routes::for_aggregate::(repo, locks, read_models) + code: `pub fn routes(stores: &St) -> Routes> { + Routes::for_aggregate(stores) .mount(blob_domain::commands::start()) .mount(blob_domain::commands::move_dir()) .mount(blob_domain::commands::start_level()) @@ -1041,13 +1037,12 @@ pub fn routes(...) -> BlobRoutes { { file: 'modules/compose.rs · blob routes', caption: 'This is the same Service composition as todos and chat.', - code: `let blob = blob::routes(repo, locks, read_models, projections.blob); - -Service::new() + code: `Service::new() .named("e2e-ui") - .routes(todos) - .routes(chat) - .routes(blob) // ← this module` + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) // ← this module + .routes(identity::routes(stores, &projections))` }, ...hostAndRunnerSamples ] @@ -1097,8 +1092,8 @@ pub struct Todos { { file: 'readmodels/models/todos.rs · admin grant', caption: 'The `e2e-ui-admin` privilege pack uses the admin grant. That grant reads all rows.', - code: `impl Todos { - pub fn permissions() -> ModelPermissions { + code: `impl AuthorizedReadModel for Todos { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", @@ -1112,18 +1107,14 @@ pub struct Todos { }, { file: 'modules/graphql.rs · build_engine surfaces', - caption: 'One engine opens three surfaces: user, admin, and public. Each surface names its eligible roles and its privilege pack.', - code: `.client_application_surface( - DISTRIBUTED_CLIENT_SURFACE, // "e2e-ui" - ["admin", "user"], // eligible - ["user"], // portable privilege pack -) -.client_application_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, ["admin"], ["admin"]) -.client_application_surface( - DISTRIBUTED_PUBLIC_CLIENT_SURFACE, // "e2e-ui-public" - ["anonymous"], - ["anonymous"], -)` + caption: 'One engine opens three surfaces: user, admin, and public. Each surface names its eligible roles and its privilege pack. Client export reads the same table.', + code: `for surface in CLIENT_SURFACES { + b = b.client_application_surface( + surface.name, // "e2e-ui" | "e2e-ui-admin" | "e2e-ui-public" + surface.eligible_roles.iter().copied(), + surface.schema_roles.iter().copied(), // portable privilege pack + ); +}` } ] }, @@ -1323,11 +1314,17 @@ mutation DeleteTodo { .client_application_surface("e2e-ui-public", ["anonymous"])` }, { - file: 'application.rs · surface constants', - caption: 'These names are stable. Client generation and host identity use them.', - code: `pub const DISTRIBUTED_CLIENT_SURFACE: &str = "e2e-ui"; -pub const DISTRIBUTED_ADMIN_CLIENT_SURFACE: &str = "e2e-ui-admin"; -pub const DISTRIBUTED_PUBLIC_CLIENT_SURFACE: &str = "e2e-ui-public";` + file: 'application.rs · client surfaces', + caption: 'Each surface is declared once. The engine, client generation and host identity use it.', + code: `pub const CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui", eligible_roles: &["admin", "user"], schema_roles: &["user"], +}; +pub const ADMIN_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-admin", eligible_roles: &["admin"], schema_roles: &["admin"], +}; +pub const PUBLIC_CLIENT_SURFACE: ClientSurface = ClientSurface { + name: "e2e-ui-public", eligible_roles: &["anonymous"], schema_roles: &["anonymous"], +};` }, ...hostAndRunnerSamples ] @@ -1478,28 +1475,28 @@ IdentityConfig::oidc_bearer(oidc)` { id: 'service', label: '5 · Service + host', - lede: 'Identity is not a domain aggregate. Identity is service-crate wiring. That wiring includes OIDC or dev headers, claim maps, and the identity module Zitadel ingress. The ingress fills `AuthUsers`. The host starts the Service. The host also starts the scrape, outbox, and consumer loops. The runner only supplies `DATABASE_URL`, `BIND`, and OIDC environment variables.', + lede: 'Identity is not a domain aggregate. Identity is service-crate wiring. That wiring includes OIDC or dev headers, claim maps, and the identity module Zitadel ingress. The ingress fills `AuthUsers`. The host starts the Service. The host also starts the scrape and consumer loops; the bus drains the outbox. The runner only supplies `DATABASE_URL`, `BIND`, and OIDC environment variables.', principle: 'Keep identity on the transport. Compose modules. Keep domain crates pure.', samples: [ { - file: 'modules/compose.rs · MODULE_IDS', - caption: 'Identity is a module with no aggregate. It mounts the Zitadel commands and the `AuthUsers` projection.', - code: `pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, - chat::MODULE_ID, - blob::MODULE_ID, - identity::MODULE_ID, -];` + file: 'modules/compose.rs · build_service', + caption: 'Identity is a module with no aggregate. It mounts the Zitadel commands and the `AuthUsers` projection. Its commands are `zitadel.*`, so the derived manifest names that module `zitadel`.', + code: `Service::new() + .named("e2e-ui") + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections))` }, { file: 'modules/identity.rs · Zitadel ingress', caption: 'These are typed commands with no aggregate. Each user profile they publish commits with its command ledger receipt. Each command has its own HTTP edge: it checks the shared secret and dispatches as the ingestor. No user role can call them, and every other command path stays closed.', - code: `Routes::for_stores(repo, read_models) + code: `Routes::for_stores(stores.events().clone(), stores.read_models().clone()) .typed_command(zitadel::command()) .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) - .handle(zitadel_scrape::Scrape(read_models.clone())) - .consume_projection(auth_projector) + .handle(zitadel_scrape::Scrape(stores.read_models().clone())) + .consume_projection(projections.projector(AUTH_USERS)) // compose.rs Service::new() diff --git a/tests/e2e-ui/ui/src/routes/+page.svelte b/tests/e2e-ui/ui/src/routes/+page.svelte index a47090cd1..8e9749765 100644 --- a/tests/e2e-ui/ui/src/routes/+page.svelte +++ b/tests/e2e-ui/ui/src/routes/+page.svelte @@ -78,8 +78,8 @@ pub struct Todos { pub status: String, } -impl Todos { - pub fn permissions() -> ModelPermissions { +impl AuthorizedReadModel for Todos { + fn permissions() -> ModelPermissions { ModelPermissions::new() .grant( "user", @@ -195,17 +195,18 @@ query Todos @load { todos { todo_id title status } }`; - const codeService = `// compose.rs (trimmed). Each routes(...) takes repo, locks, -// read models, and the projection owner for that module. -pub const MODULE_IDS: &[&str] = &[ - todo::MODULE_ID, chat::MODULE_ID, blob::MODULE_ID, "identity", -]; - -Service::new() - .named("e2e-ui") - .routes(todo::routes(repo.clone(), locks.clone(), read_models.clone(), projections.todo)) - .routes(chat::routes(repo.clone(), locks.clone(), read_models.clone(), projections.chat)) - .routes(blob::routes(repo, locks, read_models, projections.blob)) + const codeService = `// compose.rs (trimmed). Each module takes the stores and the +// projections mounted from their descriptors. +pub fn build_service(stores: &St) -> Service { + let projections = projections(); + Service::new() + .named("e2e-ui") + .routes(todo::routes(stores, &projections)) + .routes(chat::routes(stores, &projections)) + .routes(blob::routes(stores)) + .routes(identity::routes(stores, &projections)) +} +// The application manifest's modules are derived from this Service. // Another crate can list the same modules, or only Eventual projectors. // You write that Service. You do not flip a Runtime::role flag.`;