Skip to content
Merged
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
31 changes: 29 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,10 @@ Service::new()
```

HTTP `POST /{command}` is **off by default**. Browser writes use the
GraphQL command proxy. Call `.with_http_command_routes()` only for an
intentional non-GraphQL ingress.
GraphQL command proxy. For an intentional non-GraphQL ingress (a provider
webhook), expose that one command with `.with_http_command(command, edge)`:
its edge authenticates the request and returns what to dispatch. Call
`.with_http_command_routes()` only behind a trusted proxy.

### 08 · Browser replica

Expand Down Expand Up @@ -1679,6 +1681,31 @@ curl -X POST http://localhost:3000/counter.initialize \
curl http://localhost:3000/health
```

To expose one command without trusting any header, give it an edge with `Service::with_http_command`. The edge sees the request headers and JSON body (`null` when empty) and returns an `HttpCommandDispatch { command_id, input, session, principal }`, or a `CausalDispatchError` (a 401 for a bad secret). The command runs through the ledger like any other dispatch, with only the session the edge built, and answers `{ payload, receipt }`. No other command path is mounted. Behind a gateway, `Service::command_gateway_routes(binding)` (feature `gateway`) gives every command path to the service binding, so an unexposed one is the service's 404 rather than a UI page:

```rust,ignore
fn webhook_edge(
headers: &HeaderMap,
body: Value,
) -> Result<HttpCommandDispatch, CausalDispatchError> {
verify_shared_secret(headers)?;
Ok(HttpCommandDispatch {
command_id: delivery_command_id(&body),
input: body,
session: webhook_session(),
principal: VerifiedPrincipal::internal("system:webhook").expect("a subject"),
})
}

let service = Service::new()
.named("identity")
.routes(routes)
.with_http_command("webhook.receive", webhook_edge);
gateway_routes.extend(service.command_gateway_routes("service"));
```

`microsvc::command_router(service)` is the command paths alone, to compose under your own router and middleware.

The command ID is a client-created UUIDv7: retrying a request with the same ID
replays the committed receipt. A command needs an authenticated user
(`x-user-id`), and a role its declaration grants.
Expand Down
9 changes: 6 additions & 3 deletions distributed_cli/skills/distributed-graphql/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,12 @@ let service = service.try_with_graphql(engine)?;
// GET /graphql — GraphiQL IDE when `.graphiql(true)`
```

`POST /{command}` stays off unless you call `with_http_command_routes()`.
Call that only for an intentional, independently authenticated ingress.
GraphQL mutations do not need it.
`POST /{command}` stays off. For an intentional, independently authenticated
ingress, expose that one command with `with_http_command(command, edge)`: the
edge checks the request and returns the dispatch (command ID, input, session,
principal). `with_http_command_routes()` opens every command to trusted-proxy
headers. Behind a gateway, `command_gateway_routes(binding)` keeps every
command path on the service. GraphQL mutations need none of these.

Build the executable `Service` first and pass that exact instance to
`GraphqlEngineBuilder::service`. For `Atomic<M>`, pass the repository handle
Expand Down
6 changes: 4 additions & 2 deletions distributed_cli/skills/distributed-usage/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,10 @@ command ledger under its command ID, whichever ingress delivers it:
projection atomicity;
- for a browser-facing GraphQL service, bind that exact `Service` through
`GraphqlEngineBuilder::service` and configure public OIDC. HTTP command
routes stay off; browser writes use only the GraphQL command proxy. Call
`.with_http_command_routes()` only for an intentional non-GraphQL ingress;
routes stay off; browser writes use only the GraphQL command proxy. Expose
one command for an intentional non-GraphQL ingress with
`.with_http_command(command, edge)` (the edge authenticates the request);
call `.with_http_command_routes()` only behind a trusted proxy;
- generate the strictly typed client with `distributed client`.

Use the `distributed-graphql` skill for the complete route, consistency,
Expand Down
2 changes: 1 addition & 1 deletion docs/application-composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ Outbox dispatcher and eventual consumer are **role-selected**, not copy-pasted p
| HTTP command routes | Optional / ingress only (e.g. Zitadel) |
| OIDC / identity | API-facing processes |

Primary write path for apps remains GraphQL commands. HTTP command routes stay off unless a process calls `with_http_command_routes`.
Primary write path for apps remains GraphQL commands. HTTP command routes stay off: a process exposes one command with `with_http_command(command, edge)` (the edge authenticates the request), or every command with `with_http_command_routes` behind a trusted proxy. `command_gateway_routes` keeps every command path on the service binding of a gateway.

---

Expand Down
2 changes: 1 addition & 1 deletion src/in_memory_repo/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ impl InMemoryRepository {

for message in &batch.outbox_messages {
if outbox_storage.contains_key(message.id()) {
return Err(RepositoryError::DuplicateOutboxMessageInBatch {
return Err(RepositoryError::DuplicateOutboxMessage {
id: message.id().to_string(),
}
.into());
Expand Down
24 changes: 24 additions & 0 deletions src/microsvc/causal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ pub(crate) struct AggregatePublication {
struct WorkspaceState {
aggregates: Vec<StagedAggregate>,
identities: HashSet<StreamIdentity>,
external_events: Vec<crate::DomainEventOccurrence>,
outbox_messages: Vec<OutboxMessage>,
read_model_plans: Vec<TableWritePlan>,
snapshots: Vec<SnapshotWrite>,
Expand Down Expand Up @@ -458,6 +459,20 @@ where
}

impl<A> CausalWorkspace<'_, A> {
/// Stage one external fact. Its causation is the ledger's, applied in
/// [`CausalWorkspaceParts::prepare_domain_publications`].
pub(crate) fn stage_external_event(
&self,
occurrence: crate::DomainEventOccurrence,
) -> Result<(), CausalWorkspaceError> {
self.state
.lock()
.map_err(|_| CausalWorkspaceError::Poisoned)?
.external_events
.push(occurrence);
Ok(())
}

pub(crate) fn stage_outbox(&self, message: OutboxMessage) -> Result<(), CausalWorkspaceError> {
self.state
.lock()
Expand Down Expand Up @@ -600,6 +615,7 @@ impl<A> CausalWorkspace<'_, A> {
.map_err(|_| CausalWorkspaceError::Poisoned)?;
Ok(CausalWorkspaceParts {
aggregates: state.aggregates,
external_events: state.external_events,
outbox_messages: state.outbox_messages,
read_model_plans: state.read_model_plans,
snapshots: state.snapshots,
Expand All @@ -618,6 +634,8 @@ impl<A> CausalWorkspace<'_, A> {
/// construction of the ledger-fenced commit batch.
pub(crate) struct CausalWorkspaceParts {
aggregates: Vec<StagedAggregate>,
/// External facts staged by the handler, causation not yet applied.
external_events: Vec<crate::DomainEventOccurrence>,
outbox_messages: Vec<OutboxMessage>,
read_model_plans: Vec<TableWritePlan>,
snapshots: Vec<SnapshotWrite>,
Expand Down Expand Up @@ -697,6 +715,12 @@ impl CausalWorkspaceParts {
.push(OutboxMessage::from_domain_event_occurrence(&occurrence)?);
}
}
for mut occurrence in std::mem::take(&mut self.external_events) {
occurrence.overwrite_causation_id(causation_id);
self.outbox_messages
.push(OutboxMessage::from_domain_event_occurrence(&occurrence)?);
self.domain_event_occurrences.push(occurrence);
}
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion src/microsvc/cell_host/sql_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ impl CellSqlRepository {
)
.await?;
if !existing.is_empty() {
return Err(RepositoryError::DuplicateOutboxMessageInBatch {
return Err(RepositoryError::DuplicateOutboxMessage {
id: message.id().into(),
}
.into());
Expand Down
139 changes: 120 additions & 19 deletions src/microsvc/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
//!
//! ## Routes
//!
//! - `POST /{command}` — dispatch a typed command when
//! [`Service::with_http_command_routes`] is set. Body =
//! `{ "commandId", "input" }`, request headers → Session. A body without a
//! `commandId` is a 400.
//! - `POST /{command}` for a command exposed with
//! [`Service::with_http_command`]: its edge authenticates the request and
//! says what to dispatch. No other command path is answered.
//! - `POST /{command}` for every command when
//! [`Service::with_http_command_routes`] is set (trusted-proxy ingress).
//! Body = `{ "commandId", "input" }`, request headers → Session. A body
//! without a `commandId` is a 400.
//! - `GET /health` — health check returning `{ "ok": true, "commands": [...] }`.
//! - `GET /metrics` — Prometheus text metrics (requires the `metrics` feature);
//! unauthenticated by design and intended for private scrape networks only.
Expand Down Expand Up @@ -39,27 +42,49 @@

use std::sync::Arc;

use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::routing::get;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde_json::{json, Value};

use super::error::HandlerError;
use super::service::Service;
use super::service::{CausalDispatchError, CausalDispatchResult, Service};
use super::session::Session;
use super::MAX_HTTP_BODY_BYTES;
use crate::command_dispatch::VerifiedPrincipal;

/// What a command's HTTP edge ([`Service::with_http_command`]) dispatches
/// for one authenticated request.
#[derive(Debug)]
pub struct HttpCommandDispatch {
/// The ledger command ID. A redelivery with the same ID replays the
/// stored receipt.
pub command_id: String,
/// The command input.
pub input: Value,
/// The session the command runs with. Request headers reach the command
/// only through what the edge puts here.
pub session: Session,
/// The principal the edge verified.
pub principal: VerifiedPrincipal,
}

/// A command's HTTP edge: request headers and JSON body in, dispatch out.
pub(crate) type HttpCommandEdge = Arc<
dyn Fn(&HeaderMap, Value) -> Result<HttpCommandDispatch, CausalDispatchError> + Send + Sync,
>;

/// Build an axum `Router` that dispatches commands via the given service.
///
/// Does not mount `POST /{command}` unless [`Service::with_http_command_routes`]
/// was called. Health, metrics, and GraphQL stay available either way.
/// Mounts [`command_router`], `GET /health`, metrics, and GraphQL when the
/// service has an engine.
pub fn router(service: Arc<Service>) -> Router {
let mut router = Router::new().route("/health", get(health_handler));
if service.http_command_routes_enabled() {
router = router.route("/{command}", axum::routing::post(command_handler));
}
// Only metrics and GraphQL add routes after this.
#[cfg_attr(not(any(feature = "metrics", feature = "graphql")), allow(unused_mut))]
let mut router = command_router(Arc::clone(&service)).route("/health", get(health_handler));
#[cfg(feature = "metrics")]
{
router = router.route("/metrics", get(metrics_handler));
Expand All @@ -86,11 +111,78 @@ pub fn router(service: Arc<Service>) -> Router {

router
// Pin the body limit explicitly rather than relying on axum's default;
// the command handler buffers the JSON body into memory.
// the command handlers buffer the JSON body into memory.
.layer(DefaultBodyLimit::max(MAX_HTTP_BODY_BYTES))
.with_state(service)
}

/// The command paths of `service`, and nothing else: `POST /{command}` for
/// each command exposed with [`Service::with_http_command`], and for every
/// command when [`Service::with_http_command_routes`] is set. A command path
/// it does not expose is not mounted, so it is a 404.
///
/// [`router`] includes it; mount it alone to compose the command paths into
/// another router (with that router's own health route or middleware). It
/// needs its state, so finish it with `.with_state(service)` there, or call
/// [`router`].
///
/// # Panics
/// When an edge names a command the service does not register.
pub fn command_router(service: Arc<Service>) -> Router<Arc<Service>> {
let mut router = Router::new();
if service.http_command_routes_enabled() {
router = router.route("/{command}", post(command_handler));
}
let registered = service.command_names();
for (command, edge) in service.http_commands() {
assert!(
registered.contains(&command),
"HTTP edge for `{command}`, which the service does not register"
);
let command = command.to_string();
let edge = Arc::clone(edge);
router = router.route(
&format!("/{command}"),
post(
move |State(service): State<Arc<Service>>, headers: HeaderMap, body: Bytes| {
let command = command.clone();
let edge = Arc::clone(&edge);
async move {
let result = match request_json(&body) {
Ok(body) => match edge(&headers, body) {
Ok(dispatch) => {
service
.dispatch_causal_with_receipt(
&command,
&dispatch.command_id,
dispatch.input,
dispatch.session,
dispatch.principal,
)
.await
}
Err(error) => Err(error),
},
Err(error) => Err(error),
};
command_response(&command, result)
}
},
),
);
}
router
}

/// The JSON of a request body; `null` when it is empty.
fn request_json(body: &[u8]) -> Result<Value, CausalDispatchError> {
if body.iter().all(u8::is_ascii_whitespace) {
return Ok(Value::Null);
}
serde_json::from_slice(body)
.map_err(|_| CausalDispatchError::BadRequest("request body is not JSON".into()))
}

/// Serve the service over HTTP at the given address (e.g. `"0.0.0.0:3000"`).
pub async fn serve(service: Arc<Service>, addr: &str) -> Result<(), std::io::Error> {
let app = router(service);
Expand Down Expand Up @@ -147,21 +239,30 @@ async fn command_handler(
.into_response();
}
};
match super::wait_path::dispatch_wait_path(
let result = super::wait_path::dispatch_wait_path(
service.as_ref(),
&command,
&command_id,
input,
session,
)
.await
{
.await;
command_response(&command, result)
}

/// The HTTP answer of one dispatched command: the wait-path response, or its
/// error with the error's status.
fn command_response(
command: &str,
result: Result<CausalDispatchResult, CausalDispatchError>,
) -> Response {
match result {
Ok(result) => (
StatusCode::OK,
Json(super::wait_path::wait_path_response(&result)),
)
.into_response(),
Err(super::CausalDispatchError::Handler(HandlerError::ApplicationReloading)) => {
Err(CausalDispatchError::Handler(HandlerError::ApplicationReloading)) => {
reloading_response()
}
Err(err) => {
Expand All @@ -178,7 +279,7 @@ async fn command_handler(

/// The response to a command refused by the service's
/// [`LifecycleGate`](super::LifecycleGate).
fn reloading_response() -> axum::response::Response {
fn reloading_response() -> Response {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({
Expand Down
2 changes: 1 addition & 1 deletion src/microsvc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ mod http;
#[allow(unused_imports)]
pub(crate) use http::session_from_headers;
#[cfg(feature = "http")]
pub use http::{router, serve};
pub use http::{command_router, router, serve, HttpCommandDispatch};

// Knative / CloudEvents HTTP ingress (Service-coupled; the bus keeps only the
// produce/manifest helpers).
Expand Down
Loading
Loading