Skip to main content

seiva_http/
bus.rs

1//! The two pipeline behaviors that bind to the **request context** (ADR 0020).
2//!
3//! [`seiva_cqrs`] ships the transport-free behaviors — [`Validate`] (keyed off the
4//! message's own [`Validated`] contract) and [`Transactional`] (keyed off an
5//! injected [`UnitOfWork`] port). The remaining two behaviors of ADR 0020 need
6//! state the *transport* supplies per request, so they live here, in the HTTP
7//! crate, next to the [`Ctx`] they are built from:
8//!
9//! - [`Authorize`] — the **pre-transaction**, fail-closed authorization check
10//!   (ADR 0019). It holds the caller's [`Principal`] and the operation's
11//!   [`RequiredPermission`] (the route policy from the facade descriptor) and
12//!   rejects a caller that lacks the permission *before* delegating — so no
13//!   transaction opens and the inner handler never observes an unauthorized call.
14//! - [`Idempotent`] — the **intra-transaction** durable-idempotency check
15//!   (ADR 0011). It holds an [`IdempotencyStore`] and the request's `scoped_key`
16//!   + `fingerprint`, claims the key, and runs the handler at most once per key.
17//!
18//! # These are the same shape as every other behavior
19//!
20//! A behavior is a handler that wraps an inner handler (exactly like
21//! [`Instrument`](seiva_cqrs::Instrument) / [`CacheQueries`](seiva_cqrs::CacheQueries)),
22//! so the four compose by **nesting** and stay fully typed and monomorphised — no
23//! runtime registry, no `dyn`. The write order ADR 0020 fixes is:
24//!
25//! ```text
26//! Authorize → Validate → Transactional{ Idempotent → handler }
27//! ```
28//!
29//! and in Rust that is written inside-out around the handler:
30//!
31//! ```text
32//! Mediator::new(
33//!     Authorize::new(
34//!         Validate::new(
35//!             Transactional::new(
36//!                 Idempotent::new(handler, store, scoped_key, fingerprint, ttl),
37//!                 uow, ctx.scope().ok_or(/* refuse: no tenant */)?,
38//!             ),
39//!         ),
40//!         principal, required,
41//!     ),
42//! )
43//! ```
44//!
45//! # Why the nesting order is a correctness invariant, not a preference
46//!
47//! [`Authorize`] and [`Validate`] sit **outside** [`Transactional`] on purpose: an
48//! unauthorized or malformed request must be rejected *before* a transaction opens,
49//! both to fail fast and so a denied call leaves no transactional trace.
50//! [`Idempotent`] sits **inside** [`Transactional`] for the opposite reason: the
51//! key reservation ([`begin`](IdempotencyStore::begin)/[`finish`](IdempotencyStore::finish)),
52//! the handler's mutation and the outbox write must commit as **one** atom, so a
53//! committed key always has its effect and a rolled-back one has none (ADR 0011
54//! rejected an *outer* idempotency middleware precisely because it runs above any
55//! transaction and cannot stay atomic). Reordering these breaks the guarantee; the
56//! integration test `tests/bus_pipeline.rs` pins the order by observation.
57//!
58//! # How each behavior gets its context
59//!
60//! Both are built **per request** from a [`Ctx`] (and, for `Idempotent`,
61//! the request body): the [`Principal`] and the operation path come from the `Ctx`;
62//! the required permission comes from the facade method's descriptor; the
63//! idempotency `scoped_key`/`fingerprint` are folded from the `Ctx` identity +
64//! coordinates + `Idempotency-Key` + body by [`scoped_key`] /
65//! [`fingerprint`] — the very helpers the HTTP idempotency path
66//! already uses, reused here rather than re-derived. The authorization rule itself
67//! is the shared [`require_permission`], the same
68//! fail-closed check the tower [`permission_guard`](crate::permission_guard) runs,
69//! so the guard and the behavior can never diverge.
70//!
71//! # Scope (Phase 2)
72//!
73//! This module proves the **composition** of the behaviors around the `Ctx`; it is
74//! driven by the integration test with doubles, not by a live HTTP server. Routing
75//! a real module (orders) through the bus instead of calling its service directly
76//! is **Phase 3** — nothing here forces an existing controller through the pipeline
77//! (opt-in is the adoption mechanism, ADR 0020).
78//!
79//! [`Validate`]: seiva_cqrs::Validate
80//! [`Validated`]: seiva_cqrs::Validated
81//! [`Transactional`]: seiva_cqrs::Transactional
82//! [`UnitOfWork`]: seiva_ports::UnitOfWork
83
84use std::time::Duration;
85
86use serde::de::DeserializeOwned;
87use serde::Serialize;
88
89use seiva_cqrs::{Command, CommandHandler, Query, QueryHandler};
90use seiva_identity::Principal;
91use seiva_ports::{BoxError, IdempotencyOutcome, IdempotencyStore, PortResult};
92
93use crate::ctx::Ctx;
94use crate::guard::require_permission;
95use crate::idempotency::{fingerprint, in_progress_problem, mismatch_problem, scoped_key};
96use crate::problem::Problem;
97use crate::RequiredPermission;
98
99/// The default reservation lifetime for an idempotency key when a caller does not
100/// choose one (24 hours). Long enough to absorb a client's retries and a transient
101/// outage, short enough that the store does not keep completed responses forever.
102pub const DEFAULT_IDEMPOTENCY_TTL: Duration = Duration::from_secs(24 * 60 * 60);
103
104/// A **pre-transaction**, fail-closed authorization behavior (ADR 0019).
105///
106/// It wraps an inner handler and holds the request's [`Principal`] and the
107/// operation's [`RequiredPermission`] (the facade method's `requires` policy). On
108/// dispatch it runs the shared [`require_permission`]
109/// check and **only** delegates when it passes; on denial it returns a `403`
110/// [`Problem`] boxed as the port error and **never calls the inner handler** — so a
111/// caller without the permission cannot reach the mutation and, because this
112/// behavior is composed *outside* [`Transactional`](seiva_cqrs::Transactional), no
113/// transaction is ever opened for the denied call.
114///
115/// It implements both [`CommandHandler`] and [`QueryHandler`], so the same guard
116/// serves a write (`Authorize → Validate → Transactional{…}`) and a read
117/// (`Authorize → CacheQueries → handler`). An empty requirement (an unguarded
118/// operation) always passes, matching the tower [`permission_guard`](crate::permission_guard).
119///
120/// The returned `403` is **status-bearing**: it travels inside the port's
121/// `BoxError` as a [`Problem`], and [`Problem::from`] recovers it verbatim at the
122/// edge (it is not remapped to `500`).
123pub struct Authorize<H> {
124    inner: H,
125    principal: Principal,
126    required: RequiredPermission,
127    /// The operation path (from the `Ctx`), used only to set the `403` problem's
128    /// `instance`; empty when the behavior was built without a request.
129    instance: String,
130}
131
132impl<H> Authorize<H> {
133    /// Wraps `inner`, checking `principal` against `required` before each dispatch.
134    ///
135    /// Use [`from_ctx`](Self::from_ctx) to build directly from a request
136    /// [`Ctx`]; this lower-level constructor is for a caller that
137    /// already holds the principal and policy (and leaves the problem `instance`
138    /// unset).
139    pub fn new(inner: H, principal: Principal, required: RequiredPermission) -> Self {
140        Self {
141            inner,
142            principal,
143            required,
144            instance: String::new(),
145        }
146    }
147
148    /// Builds the behavior from a request [`Ctx`] and the operation's
149    /// [`RequiredPermission`] (read from the facade descriptor): the caller's
150    /// [`Principal`] and the path for the `403` `instance` are taken from the `Ctx`.
151    /// This is the idiomatic per-request constructor.
152    pub fn from_ctx(inner: H, ctx: &Ctx, required: RequiredPermission) -> Self {
153        Self {
154            inner,
155            principal: ctx.principal().clone(),
156            required,
157            instance: ctx.path().to_owned(),
158        }
159    }
160
161    /// Borrows the wrapped inner handler/behavior.
162    pub fn inner(&self) -> &H {
163        &self.inner
164    }
165
166    /// Runs the fail-closed check, enriching the denial problem with the operation
167    /// path and boxing it as the port error so its status survives to the edge.
168    fn authorize(&self) -> PortResult<()> {
169        require_permission(&self.principal, self.required.0).map_err(|problem| {
170            let problem = if self.instance.is_empty() {
171                problem
172            } else {
173                problem.with_instance(self.instance.clone())
174            };
175            BoxError::from(problem)
176        })
177    }
178}
179
180impl<C, H> CommandHandler<C> for Authorize<H>
181where
182    C: Command,
183    H: CommandHandler<C>,
184{
185    async fn handle(&self, cmd: C) -> PortResult<C::Output> {
186        // Fail-closed: a denied caller never reaches the handler, and because this
187        // behavior sits outside `Transactional`, no transaction opens for it.
188        self.authorize()?;
189        self.inner.handle(cmd).await
190    }
191}
192
193impl<Q, H> QueryHandler<Q> for Authorize<H>
194where
195    Q: Query,
196    H: QueryHandler<Q>,
197{
198    async fn handle(&self, query: Q) -> PortResult<Q::Output> {
199        // Same guard on the read side (`Authorize → CacheQueries → handler`).
200        self.authorize()?;
201        self.inner.handle(query).await
202    }
203}
204
205/// An **intra-transaction**, durable-idempotency behavior (ADR 0011).
206///
207/// It wraps an inner handler and holds an [`IdempotencyStore`] `S`, the request's
208/// `scoped_key` and `fingerprint`, and the reservation `ttl`. On dispatch it claims
209/// the key through [`begin`](IdempotencyStore::begin) *before* delegating and then:
210///
211/// - [`Fresh`](IdempotencyOutcome::Fresh) — runs the inner handler, serialises its
212///   output to JSON, persists it with [`finish`](IdempotencyStore::finish), and
213///   returns the output. The handler runs **exactly once** for this key.
214/// - [`Replay`](IdempotencyOutcome::Replay) — deserialises and returns the stored
215///   response **without running the handler**, so a retried request produces one
216///   effect, not two.
217/// - [`InProgress`](IdempotencyOutcome::InProgress) /
218///   [`Mismatch`](IdempotencyOutcome::Mismatch) — returns a `409` [`Problem`]
219///   (the key is still in flight, or was reused for different content) and does
220///   **not** execute. The `409` is status-bearing: it rides inside the port's
221///   `BoxError` and [`Problem::from`] recovers it verbatim (it is not remapped).
222///
223/// # This behavior must be nested *inside* `Transactional`
224///
225/// `begin`/handler/`finish` and the outbox write have to commit as one atom
226/// (ADR 0011). Compose it as the innermost link of the transactional scope —
227/// `Transactional::new(Idempotent::new(handler, …), uow, ctx.scope())` — so the key reservation
228/// commits with the mutation it guards. Placed *outside* a transaction it would
229/// reserve a key that a later rollback could not release, which is exactly the
230/// failure mode ADR 0011 avoided by rejecting an outer idempotency middleware.
231///
232/// Only [`CommandHandler`] is implemented, by design: idempotency guards a
233/// *mutation*; a side-effect-free [`Query`] is neither reserved nor replayed.
234///
235/// # Bounds, and why
236///
237/// - `C::Output: Serialize` — the handler's result is stored as JSON for replay.
238/// - `C::Output: DeserializeOwned` — a replayed response is decoded from that JSON.
239///
240/// The response is carried as opaque bytes by the store ([`IdempotencyOutcome`]
241/// moves `Vec<u8>`); this behavior owns the (JSON) encoding, matching the HTTP
242/// idempotency path's canonicalisation.
243pub struct Idempotent<H, S> {
244    inner: H,
245    store: S,
246    scoped_key: String,
247    fingerprint: String,
248    ttl: Duration,
249}
250
251impl<H, S> Idempotent<H, S> {
252    /// Wraps `inner`, deduplicating on a precomputed `scoped_key`/`fingerprint`.
253    ///
254    /// Build the two values with [`scoped_key`] /
255    /// [`fingerprint`], or use [`from_ctx`](Self::from_ctx) to
256    /// derive them from a request [`Ctx`] and body.
257    pub fn new(inner: H, store: S, scoped_key: String, fingerprint: String, ttl: Duration) -> Self {
258        Self {
259            inner,
260            store,
261            scoped_key,
262            fingerprint,
263            ttl,
264        }
265    }
266
267    /// Builds the behavior from a request [`Ctx`] and the request
268    /// `body`, folding the `scoped_key` (caller tenant + subject + method + path +
269    /// `Idempotency-Key`) and the `fingerprint` (method + path + canonical JSON
270    /// body) with the shared [`scoped_key`] /
271    /// [`fingerprint`] helpers.
272    ///
273    /// Returns [`None`] when the `Ctx` carries **no** `Idempotency-Key`: idempotency
274    /// is opt-in per request (ADR 0011), so a caller that did not ask for it is
275    /// dispatched without this behavior rather than silently deduplicated. `query`
276    /// is `None` because the [`Ctx`] does not retain the query string;
277    /// a caller that fingerprints the query uses [`new`](Self::new) directly.
278    pub fn from_ctx(
279        inner: H,
280        store: S,
281        ctx: &Ctx,
282        body: &serde_json::Value,
283        ttl: Duration,
284    ) -> Option<Self> {
285        let key = ctx.idempotency_key()?;
286        let scoped = scoped_key(ctx.principal(), ctx.method(), ctx.path(), key);
287        let fp = fingerprint(ctx.method(), ctx.path(), None, body);
288        Some(Self::new(inner, store, scoped, fp, ttl))
289    }
290
291    /// Borrows the wrapped inner handler/behavior.
292    pub fn inner(&self) -> &H {
293        &self.inner
294    }
295
296    /// The store-facing scoped key this behavior claims.
297    #[must_use]
298    pub fn scoped_key(&self) -> &str {
299        &self.scoped_key
300    }
301
302    /// The request fingerprint pinned to this key.
303    #[must_use]
304    pub fn fingerprint(&self) -> &str {
305        &self.fingerprint
306    }
307}
308
309impl<C, H, S> CommandHandler<C> for Idempotent<H, S>
310where
311    C: Command,
312    C::Output: Serialize + DeserializeOwned,
313    H: CommandHandler<C>,
314    S: IdempotencyStore,
315{
316    async fn handle(&self, cmd: C) -> PortResult<C::Output> {
317        match self
318            .store
319            .begin(&self.scoped_key, &self.fingerprint, self.ttl)
320            .await?
321        {
322            IdempotencyOutcome::Fresh => {
323                // First claim: run the mutation once, then persist its response so a
324                // later claim replays it. All of this runs inside the surrounding
325                // `Transactional` scope, so the reservation commits with the effect.
326                let output = self.inner.handle(cmd).await?;
327                let bytes = serde_json::to_vec(&output)?;
328                self.store.finish(&self.scoped_key, &bytes).await?;
329                Ok(output)
330            }
331            IdempotencyOutcome::Replay(bytes) => {
332                // Already completed: return the stored response, run nothing.
333                let output = serde_json::from_slice(&bytes)?;
334                Ok(output)
335            }
336            // Status-bearing 409s: boxed as `Problem`, recovered verbatim at the edge.
337            IdempotencyOutcome::InProgress => Err(BoxError::from(in_progress_problem())),
338            IdempotencyOutcome::Mismatch => Err(BoxError::from(mismatch_problem())),
339            // A future outcome kind is treated as a conflict (fail-closed): refuse
340            // rather than silently re-run the mutation.
341            _ => Err(BoxError::from(in_progress_problem())),
342        }
343    }
344}
345
346// `Problem` is `Send + Sync + 'static` and implements `std::error::Error`, so the
347// blanket `From<E> for Box<dyn Error + Send + Sync>` boxes it into the port's
348// `BoxError`; the helpers above make that explicit for the reader.
349const _: fn() = || {
350    fn _assert_boxable<E: std::error::Error + Send + Sync + 'static>() {}
351    _assert_boxable::<Problem>();
352};