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