Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 46 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ pub struct Todos {
pub status: String,
}

impl Todos {
pub fn permissions() -> ModelPermissions<Self> {
impl AuthorizedReadModel for Todos {
fn permissions() -> ModelPermissions<Self> {
ModelPermissions::new()
.grant(
"user",
Expand All @@ -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::<Todos>()
.model::<ChatMessages>()
.model::<BlobGames>()
.model::<AuthUsers>()
}
```

### 05 · Inferred query API
Expand Down Expand Up @@ -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<St: ServiceStores>(
stores: &St,
projections: &LocalProjectionMounts,
) -> Routes<AggregateDependencies<St, Todo>> {
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<St: ServiceStores>(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<St: SqlStores>(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.
Expand Down
49 changes: 11 additions & 38 deletions distributed_game/src/world/zone_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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).
Expand Down Expand Up @@ -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::<ZoneActivities, _>(
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::<ZoneLeases, _>(LEASES_PROJECTOR, ZONE_LEASES, LEASES_EPOCH)
.expect("zone leases mount")
.eventual_model::<ZoneSnapshots, _>(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),
)
}

Expand Down
71 changes: 53 additions & 18 deletions docs/application-composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down Expand Up @@ -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<St: ServiceStores>(stores: &St, projections: &LocalProjectionMounts)
-> Routes<AggregateDependencies<St, Todo>>
{
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::<Todos>().model::<ChatMessages>()…;

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
Expand Down Expand Up @@ -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<St: SqlStores>(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):
Expand Down Expand Up @@ -171,20 +206,20 @@ 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.

---

## 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/`.
Expand All @@ -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.
Expand Down
17 changes: 5 additions & 12 deletions examples/game/server/crawler/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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)]
Expand Down Expand Up @@ -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::<PlayerStats, _>(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)
}
2 changes: 1 addition & 1 deletion examples/game/server/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 5 additions & 13 deletions examples/game/server/tiers/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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")]
Expand Down Expand Up @@ -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::<Boroughs, _>(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)
}
5 changes: 5 additions & 0 deletions src/graphql/engine/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<M: RelationalReadModelIncludes>(mut self, perms: ModelPermissions<M>) -> Self {
let schema = M::schema().clone();
if let Err(e) = self.insert_catalog(schema.clone(), true) {
Expand Down
7 changes: 7 additions & 0 deletions src/graphql/engine/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ pub struct GraphqlPoolSource {
pub(crate) causal_storage_identity: Option<crate::command_ledger::CausalStorageIdentity>,
}

impl GraphqlPoolSource {
/// The pool queries read through.
pub fn pool(&self) -> &GraphqlPool {
&self.pool
}
}

impl From<GraphqlPool> for GraphqlPoolSource {
fn from(pool: GraphqlPool) -> Self {
Self {
Expand Down
2 changes: 1 addition & 1 deletion src/graphql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading