Skip to main content

seiva_ports/
lib.rs

1//! Trait-only ports the application layer codes against.
2//!
3//! A module's `application` crate depends on this crate — never on
4//! `seiva` — to declare the outbound capabilities a use case needs.
5//! The `infrastructure` crate wires concrete implementations (DORM-backed or
6//! external); the framework resolves them at composition time. Keeping this
7//! crate free of any runtime, macro or data layer is what lets the application
8//! layer stay independent of both the framework and the ORM.
9//!
10//! This is the first cut of the boundary; its exact shape is fixed by the Seiva
11//! core ADR. The ports below are the ones a module relies on:
12//! [`UnitOfWork`], [`EventPublisher`], [`Clock`], [`IdGenerator`] and the durable
13//! [`IdempotencyStore`] (ADR 0011).
14
15#![forbid(unsafe_code)]
16
17use async_trait::async_trait;
18use std::future::Future;
19use std::pin::Pin;
20use std::time::{Duration, SystemTime};
21
22/// The error any port may surface, kept opaque and dependency-free: a boxed
23/// std error so this crate carries no error library. Adapters map their
24/// concrete errors (a DB error, a broker error) into this at the boundary, so
25/// the application layer sees one uniform failure type.
26pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
27
28/// Result returned by every port.
29pub type PortResult<T> = Result<T, BoxError>;
30
31/// A 128-bit opaque identifier. Rendered as a UUID or ULID by the framework and
32/// by adapters; this crate stays free of a UUID dependency so the boundary
33/// imposes no identifier library on downstream code.
34#[derive(Clone, Copy, PartialEq, Eq, Hash)]
35pub struct Id(pub [u8; 16]);
36
37impl std::fmt::Debug for Id {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(f, "Id({})", hex16(&self.0))
40    }
41}
42
43fn hex16(bytes: &[u8; 16]) -> String {
44    let mut s = String::with_capacity(32);
45    for b in bytes {
46        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
47        s.push(char::from_digit((b & 0x0f) as u32, 16).unwrap());
48    }
49    s
50}
51
52/// The tenant a unit of work is bound to (SG1, ADR 0021 of the data layer).
53///
54/// An opaque, non-empty identifier for one tenant. It is deliberately a distinct
55/// type — not a bare `String`/`Option<String>` — so the data-layer gateway can
56/// make the tenant **impossible to forget**: a session is opened for a [`Scope`],
57/// and a [`Scope`] is either a `TenantId` or an explicit, audited
58/// [`Scope::Global`]. There is no "no tenant" default to fall through.
59///
60/// This crate stays free of any data-layer dependency (the one-way Seiva → DORM
61/// boundary), so `TenantId` carries no `ToValue`/ORM coupling; the gateway maps it
62/// onto DORM's tenant scope at the edge.
63#[derive(Clone, PartialEq, Eq, Hash)]
64pub struct TenantId(String);
65
66impl TenantId {
67    /// Builds a tenant id from a non-empty string. Returns `None` for an empty or
68    /// whitespace-only value, so an absent tenant can never masquerade as one.
69    #[must_use]
70    pub fn new(value: impl Into<String>) -> Option<Self> {
71        let value = value.into();
72        if value.trim().is_empty() {
73            None
74        } else {
75            Some(Self(value))
76        }
77    }
78
79    /// The tenant id as a string slice.
80    #[must_use]
81    pub fn as_str(&self) -> &str {
82        &self.0
83    }
84
85    /// Consumes the id, returning the owned string (used by adapters to bind it to
86    /// the data layer).
87    #[must_use]
88    pub fn into_string(self) -> String {
89        self.0
90    }
91}
92
93impl std::fmt::Debug for TenantId {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        write!(f, "TenantId({})", self.0)
96    }
97}
98
99impl std::fmt::Display for TenantId {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(&self.0)
102    }
103}
104
105/// The isolation scope a unit of work / session runs under (SG1).
106///
107/// Every data-layer session is opened for an **explicit** scope. The common case
108/// is [`Tenant`](Scope::Tenant), which constrains every `tenant_scoped` model to
109/// that tenant automatically (the predicate on reads/updates/deletes, the column
110/// value on inserts) — a forgotten filter cannot cross tenants. The rare,
111/// deliberate cross-tenant case is [`Global`](Scope::Global), which the gateway
112/// maps onto DORM's **audited** system-scope escape (it emits a `tracing` event),
113/// so a global query is a visible choice on the record, never an accident.
114///
115/// `#[non_exhaustive]`: a consumer matches with a `_` arm, so a future scope kind
116/// (e.g. an organisation tier above tenant) is a non-breaking addition.
117#[derive(Clone, PartialEq, Eq, Hash)]
118#[non_exhaustive]
119pub enum Scope {
120    /// Constrain all `tenant_scoped` access to this tenant.
121    Tenant(TenantId),
122    /// Bypass tenant scoping deliberately (audited at the gateway). Use only for
123    /// genuine cross-tenant admin/maintenance work.
124    Global,
125}
126
127impl Scope {
128    /// Convenience constructor: a tenant scope from a non-empty string, or `None`.
129    #[must_use]
130    pub fn tenant(value: impl Into<String>) -> Option<Self> {
131        TenantId::new(value).map(Scope::Tenant)
132    }
133
134    /// The bound tenant, if this is a [`Tenant`](Scope::Tenant) scope.
135    #[must_use]
136    pub fn tenant_id(&self) -> Option<&TenantId> {
137        match self {
138            Scope::Tenant(t) => Some(t),
139            Scope::Global => None,
140        }
141    }
142}
143
144impl std::fmt::Debug for Scope {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        match self {
147            Scope::Tenant(t) => write!(f, "Scope::Tenant({t})"),
148            Scope::Global => f.write_str("Scope::Global"),
149        }
150    }
151}
152
153/// Reads the current time. Injected so use cases are deterministic under test:
154/// a fake clock returns a fixed instant with no real time involved.
155pub trait Clock: Send + Sync {
156    fn now(&self) -> SystemTime;
157}
158
159/// Mints new identifiers. Injected so a test double can hand out a predictable
160/// sequence instead of random values.
161pub trait IdGenerator: Send + Sync {
162    fn new_id(&self) -> Id;
163}
164
165/// Publishes a domain event. The payload is already serialized by the caller
166/// (the interface layer owns the envelope format, e.g. CloudEvents); this port
167/// only moves bytes to a topic, so no serialization library rides in here.
168///
169/// Whether the publish is transactional (outbox in the same transaction) or
170/// best-effort is a property of the implementation and of `seiva.toml`, not of
171/// this trait: the application layer asks to publish and the boundary decides
172/// how the guarantee is kept.
173#[async_trait]
174pub trait EventPublisher: Send + Sync {
175    async fn publish(&self, topic: &str, payload: &[u8]) -> PortResult<()>;
176}
177
178/// The transaction boundary — **scope-based** (ADR 0002, amended by ADR 0004 of
179/// the data-layer gateway).
180///
181/// The application decides where a transaction begins and ends, one per use
182/// case, by running the use-case body inside [`transaction`](UnitOfWork::transaction):
183/// the data layer **commits if the body returns `Ok` and rolls back if it
184/// returns `Err`**. Statements the body performs through the data layer join
185/// this transaction. To publish an event only after a successful commit (the
186/// outbox-relay wake), act on the `Ok` the call returns — no separate
187/// `on_commit` hook is needed.
188///
189/// Scope-based rather than handle-based (`begin`/`commit`) because the DORM
190/// executor is closure-scoped (`db::atomic`): a `commit()` called later could
191/// not drive a closure that had already returned. Used generically (a handler is
192/// generic over its ports), so this trait need not be object-safe.
193pub trait UnitOfWork: Send + Sync {
194    /// Runs `work` in a transaction **bound to `scope`** (SG1), committing on `Ok`
195    /// and rolling back on `Err`.
196    ///
197    /// `scope` is a **required** argument, not a default: every transaction names
198    /// the tenant it runs for ([`Scope::Tenant`]) or the deliberate, audited
199    /// cross-tenant case ([`Scope::Global`]). A data-layer implementation that
200    /// enforces tenant isolation (the DORM gateway) constrains every
201    /// `tenant_scoped` statement the body runs to this scope automatically, so a
202    /// forgotten filter cannot cross tenants — and the caller cannot forget to
203    /// choose, because the compiler requires the argument. A tenant-scoped handler
204    /// derives the scope from the request's authenticated tenant (`Ctx`), failing
205    /// closed when none is present.
206    ///
207    /// Returns a **boxed `Send` future** (`Pin<Box<dyn Future + Send>>`). The
208    /// `Send` bound is part of the contract, so a use case that awaits it stays
209    /// `Send` in a generic async context — an HTTP handler drives it directly,
210    /// with no `spawn_blocking` offload. Boxing (one allocation per transaction,
211    /// negligible against a database round-trip) erases the opaque future type,
212    /// which also sidesteps the higher-ranked-lifetime inference limits an
213    /// `impl Future` return hits with the generic `work` closure.
214    fn transaction<'a, T, F, Fut>(
215        &'a self,
216        scope: Scope,
217        work: F,
218    ) -> Pin<Box<dyn Future<Output = PortResult<T>> + Send + 'a>>
219    where
220        F: FnOnce() -> Fut + Send + 'a,
221        Fut: Future<Output = PortResult<T>> + Send + 'a,
222        T: Send + 'a;
223}
224
225/// What claiming an idempotency key found — the outcome of [`IdempotencyStore::begin`].
226///
227/// The key is already **scoped** by the caller (tenant + identity + operation +
228/// version folded in) before it reaches the store, so two tenants' keys can never
229/// collide here. The `fingerprint` the caller passes alongside pins the key to one
230/// request's semantically-relevant bytes; reusing the key with a different
231/// fingerprint is [`Mismatch`](IdempotencyOutcome::Mismatch) and must not execute.
232///
233/// `#[non_exhaustive]`: a consumer matches with a `_` arm, so a future outcome is a
234/// non-breaking addition.
235#[derive(Debug, Clone, PartialEq, Eq)]
236#[non_exhaustive]
237pub enum IdempotencyOutcome {
238    /// First claim: the caller performs the effect, then calls
239    /// [`finish`](IdempotencyStore::finish) with the response to persist.
240    Fresh,
241    /// Already completed: the stored response bytes — return them, perform **no**
242    /// effect. (The caller owns the encoding; the store moves opaque bytes.)
243    Replay(Vec<u8>),
244    /// A concurrent claim of the same key is still in flight: the caller waits a
245    /// bounded time or answers a conflict (`409`/`425`), never executing twice.
246    InProgress,
247    /// The key was reused with a **different** fingerprint — the same key must
248    /// mean the same operation. The caller answers `409` and does not execute.
249    Mismatch,
250}
251
252/// A durable, distributed idempotency store — the reusable guarantee behind a
253/// retried command, HTTP call, job or admin action (ADR 0011).
254///
255/// The base framework codes against this port and never against a specific
256/// database: an adapter (the DORM gateway, say) provides the durability and the
257/// cross-replica atomicity. The contract:
258///
259/// - [`begin`](Self::begin) atomically claims `scoped_key` for a request
260///   fingerprinted `fingerprint`, valid for `ttl`. It is the only arbiter of
261///   concurrency — a durable uniqueness/CAS, not an in-memory lock — so two
262///   replicas racing the same key resolve to exactly one [`Fresh`](IdempotencyOutcome::Fresh).
263/// - The caller performs the effect only on `Fresh`, then calls
264///   [`finish`](Self::finish) with the response. For true atomicity the
265///   reservation, the domain mutation and the outbox write run in **one**
266///   transaction, so a committed key always has its effect and vice versa.
267/// - [`finish`](Self::finish) persists the response so a later `begin` replays it
268///   without re-executing.
269#[async_trait]
270pub trait IdempotencyStore: Send + Sync {
271    /// Claims `scoped_key` for `fingerprint`, valid `ttl`. See [`IdempotencyOutcome`].
272    async fn begin(
273        &self,
274        scoped_key: &str,
275        fingerprint: &str,
276        ttl: Duration,
277    ) -> PortResult<IdempotencyOutcome>;
278
279    /// Persists `response` for `scoped_key` and marks it completed, so a later
280    /// [`begin`](Self::begin) returns [`Replay`](IdempotencyOutcome::Replay).
281    async fn finish(&self, scoped_key: &str, response: &[u8]) -> PortResult<()>;
282
283    /// Releases a claim taken by [`begin`](Self::begin) that will **not** be
284    /// [`finish`](Self::finish)ed, so a later `begin` for the same key is
285    /// [`Fresh`](IdempotencyOutcome::Fresh) again instead of
286    /// [`InProgress`](IdempotencyOutcome::InProgress).
287    ///
288    /// A caller invokes this when the effect it reserved the key for **failed**
289    /// before `finish`: without it the orphaned `InProgress` claim makes every
290    /// redelivery skip the effect until the TTL elapses, turning a transient
291    /// handler error into a lost effect (ADR 0028 — the at-least-once direction).
292    /// Where the reservation and the effect share one transaction, that
293    /// transaction's rollback is the compensation and this is not needed; this is
294    /// the compensating seam for stores/drivers that cannot wrap both in a single
295    /// transaction (the in-process dispatcher over a non-transactional store).
296    ///
297    /// Releasing a key that is already finished, already absent, or never claimed
298    /// is a no-op. The default is a no-op (returns `Ok`) for append-only stores
299    /// that expire records some other way; such a store keeps the pre-ADR-0028
300    /// skip-until-TTL behaviour until it overrides this.
301    async fn abort(&self, scoped_key: &str) -> PortResult<()> {
302        let _ = scoped_key;
303        Ok(())
304    }
305
306    /// Best-effort **synchronous** release of an in-flight claim — the
307    /// compensation seam for a caller that must release the claim from a context
308    /// where the async [`abort`](Self::abort) cannot be awaited: a `Drop` guard
309    /// running because the in-process dispatch future was **cancelled** between
310    /// the effect and [`finish`](Self::finish).
311    ///
312    /// It closes the *cancellation* leg of the same leak [`abort`](Self::abort)
313    /// closes on the *error* leg: without it, a claim taken by `begin` and then
314    /// abandoned by a dropped future stays [`InProgress`](IdempotencyOutcome::InProgress)
315    /// until the TTL, so every redelivery skips the effect — a transient
316    /// cancellation turned into a lost effect (ADR 0028, the at-least-once
317    /// direction).
318    ///
319    /// Releasing a key that is already finished, already absent, or never claimed
320    /// is a no-op. The default is a no-op: a store whose claim is released some
321    /// other way — a transactional store whose rollback compensates, or an
322    /// append-only store that expires by TTL — needs nothing here; the
323    /// non-transactional in-process store overrides it to drop the in-flight
324    /// record. It is synchronous on purpose (a `Drop` cannot await), so an
325    /// override **must not block**: it releases already-held in-memory/handle
326    /// state and never performs IO.
327    fn abort_blocking(&self, scoped_key: &str) {
328        let _ = scoped_key;
329    }
330
331    /// Deletes records whose TTL has elapsed; returns how many. A scheduled
332    /// worker calls this so the store does not grow without bound. The default is
333    /// a no-op (returns `0`) for stores that expire records some other way.
334    async fn purge_expired(&self) -> PortResult<u64> {
335        Ok(0)
336    }
337}
338
339/// An audit record of a sensitive — typically administrative — mutation
340/// (ADR 0013): who did what, to which object, with what result, and a
341/// correlation id. Field-level `details` are **redacted** of secrets before they
342/// ever reach a sink (see [`AuditEntry::redacted`]); the full request body with
343/// its secrets is never stored.
344///
345/// `#[non_exhaustive]`: build one from [`AuditEntry::default`] and set fields, never
346/// by exhaustive literal, so a new audit field is a non-breaking addition.
347#[derive(Debug, Clone, PartialEq, Eq, Default)]
348#[non_exhaustive]
349pub struct AuditEntry {
350    /// The acting principal's subject (empty for anonymous).
351    pub actor: String,
352    /// The tenant the action was scoped to, if any.
353    pub tenant: Option<String>,
354    /// The operation, e.g. `"POST /v1/accounts/create_user"`.
355    pub operation: String,
356    /// The target object's id, when the handler knows it.
357    pub object: Option<String>,
358    /// The result, e.g. the HTTP status as a string (`"201"`, `"403"`).
359    pub outcome: String,
360    /// The request's correlation id, for tracing.
361    pub request_id: Option<String>,
362    /// Redacted field-level detail (never the full body, never a secret value).
363    pub details: Vec<(String, String)>,
364}
365
366impl AuditEntry {
367    /// Starts an entry for `actor` performing `operation` with the given `outcome`
368    /// (e.g. an HTTP status as a string), then refined through the builder methods.
369    /// Build entries this way, not by field literal: [`AuditEntry`] is
370    /// `#[non_exhaustive]`, so a new field never breaks a caller.
371    #[must_use]
372    pub fn new(
373        actor: impl Into<String>,
374        operation: impl Into<String>,
375        outcome: impl Into<String>,
376    ) -> Self {
377        Self {
378            actor: actor.into(),
379            operation: operation.into(),
380            outcome: outcome.into(),
381            ..Self::default()
382        }
383    }
384
385    /// Scopes the entry to `tenant`.
386    #[must_use]
387    pub fn in_tenant(mut self, tenant: Option<impl Into<String>>) -> Self {
388        self.tenant = tenant.map(Into::into);
389        self
390    }
391
392    /// Records the target object's id.
393    #[must_use]
394    pub fn on_object(mut self, object: Option<impl Into<String>>) -> Self {
395        self.object = object.map(Into::into);
396        self
397    }
398
399    /// Attaches the request's correlation id.
400    #[must_use]
401    pub fn with_request_id(mut self, request_id: Option<impl Into<String>>) -> Self {
402        self.request_id = request_id.map(Into::into);
403        self
404    }
405
406    /// Appends one redactable detail pair (redaction happens in [`redacted`](Self::redacted)).
407    #[must_use]
408    pub fn with_detail(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
409        self.details.push((name.into(), value.into()));
410        self
411    }
412
413    /// Returns the entry with every sensitive `details` value replaced by
414    /// `"[redacted]"` ([`is_sensitive_field`]). Call this before recording so a
415    /// password, hash, token or key can never land in the audit log.
416    #[must_use]
417    pub fn redacted(mut self) -> Self {
418        for (name, value) in &mut self.details {
419            if is_sensitive_field(name) {
420                *value = "[redacted]".to_owned();
421            }
422        }
423        self
424    }
425}
426
427/// Whether a field name looks sensitive and so its value must be redacted from an
428/// audit record or a log: passwords, hashes, tokens, keys, secrets, credentials
429/// and authorization material (case-insensitive substring match — deliberately
430/// broad, since over-redacting an audit detail is safe and under-redacting leaks).
431#[must_use]
432pub fn is_sensitive_field(name: &str) -> bool {
433    const NEEDLES: &[&str] = &[
434        "password",
435        "passwd",
436        "secret",
437        "token",
438        "hash",
439        "apikey",
440        "api_key",
441        "credential",
442        "authorization",
443        "cookie",
444        "private",
445    ];
446    let lower = name.to_ascii_lowercase();
447    // A bare "key" is sensitive on its own, plus any of the needles as substrings.
448    lower == "key" || NEEDLES.iter().any(|needle| lower.contains(needle))
449}
450
451/// A persistent sink for [`AuditEntry`] records (ADR 0013). The base framework
452/// codes against this port; an adapter (the DORM gateway) persists the entries.
453#[async_trait]
454pub trait AuditSink: Send + Sync {
455    /// Persists one audit entry. Called with an already-[`redacted`](AuditEntry::redacted)
456    /// entry.
457    async fn record(&self, entry: &AuditEntry) -> PortResult<()>;
458}
459
460/// A filter over the audit trail, read back from an [`AuditLog`] (ADR 0013) and
461/// returned newest first. Every set field is **AND-combined**; a `None` or empty
462/// field matches anything, so the default (all `None`, `limit` 0) asks for the most
463/// recent [`DEFAULT_LIMIT`](AuditQuery::DEFAULT_LIMIT) entries.
464#[derive(Debug, Clone, Default, PartialEq, Eq)]
465pub struct AuditQuery {
466    /// Match only entries by this actor subject (exact; empty/`None` = any).
467    pub actor: Option<String>,
468    /// Match only entries scoped to this tenant (exact; empty/`None` = any). The
469    /// admin audit view is tenant-scoped, so a tenant operator reads only their own
470    /// trail.
471    pub tenant: Option<String>,
472    /// Match only entries on this object id (exact; empty/`None` = any).
473    pub object: Option<String>,
474    /// Match only entries with this outcome, e.g. `"201"`/`"403"` (exact; empty/`None` = any).
475    pub outcome: Option<String>,
476    /// The maximum number of entries to return; `0` means
477    /// [`DEFAULT_LIMIT`](AuditQuery::DEFAULT_LIMIT). An [`AuditLog`] must never return
478    /// more than this, so a history view cannot ask for an unbounded page.
479    pub limit: u32,
480}
481
482impl AuditQuery {
483    /// The page cap applied when [`limit`](Self::limit) is `0`.
484    pub const DEFAULT_LIMIT: u32 = 100;
485
486    /// The effective limit: [`limit`](Self::limit), or [`DEFAULT_LIMIT`](Self::DEFAULT_LIMIT)
487    /// when it is `0`.
488    #[must_use]
489    pub fn effective_limit(&self) -> u32 {
490        if self.limit == 0 {
491            Self::DEFAULT_LIMIT
492        } else {
493            self.limit
494        }
495    }
496
497    /// Whether `entry` satisfies every set filter. An unset or empty filter field
498    /// matches anything; a set one must match exactly. This is the pure predicate an
499    /// [`AuditLog`] applies, factored out so the matching is unit-testable without a
500    /// store.
501    #[must_use]
502    pub fn matches(&self, entry: &AuditEntry) -> bool {
503        let str_match = |filter: &Option<String>, value: &str| match filter.as_deref() {
504            None | Some("") => true,
505            Some(wanted) => wanted == value,
506        };
507        let opt_match = |filter: &Option<String>, value: &Option<String>| match filter.as_deref() {
508            None | Some("") => true,
509            Some(wanted) => value.as_deref() == Some(wanted),
510        };
511        str_match(&self.actor, &entry.actor)
512            && opt_match(&self.tenant, &entry.tenant)
513            && opt_match(&self.object, &entry.object)
514            && str_match(&self.outcome, &entry.outcome)
515    }
516}
517
518/// The **read** side of the audit trail (ADR 0013): the history view the admin
519/// surface needs, the twin of [`AuditSink`]'s write side. An implementation returns
520/// the entries matching an [`AuditQuery`], **newest first** and **bounded** by the
521/// query's [`effective_limit`](AuditQuery::effective_limit). The base framework codes
522/// against this port; an adapter (the DORM gateway) reads the persisted entries.
523#[async_trait]
524pub trait AuditLog: Send + Sync {
525    /// Returns the entries matching `query`, newest first, capped at the query's
526    /// effective limit.
527    async fn query(&self, query: &AuditQuery) -> PortResult<Vec<AuditEntry>>;
528}
529
530/// The outcome of a rate-limit check for one client (ADR 0015).
531///
532/// `#[non_exhaustive]`: a consumer matches with a `_` arm, so a future decision
533/// kind is a non-breaking addition.
534#[derive(Debug, Clone, PartialEq, Eq)]
535#[non_exhaustive]
536pub enum RateLimitDecision {
537    /// Within budget — serve the request.
538    Permitted,
539    /// Budget exhausted — reject (`429`); retry after this long.
540    Limited {
541        /// Time until the client's window rolls over.
542        retry_after: Duration,
543    },
544}
545
546/// A **distributed** rate-limit backend (ADR 0015): the authority a cluster
547/// shares so a client's budget is enforced across replicas, not per-process.
548///
549/// The base framework's default limiter is in-process (fine for a single
550/// instance, and documented as such); a deployment that runs several replicas
551/// behind a load balancer wires a shared store (e.g. Redis) through this port so
552/// one client cannot get `N × limit` by spreading requests across instances. The
553/// check must be **atomic** in the backend (a single round trip that increments
554/// and expires), not a read-modify-write, so concurrent replicas cannot race past
555/// the limit. Rate limiting is abuse-dampening, not a durable business guarantee,
556/// so a store that is briefly unavailable fails **open** at the call site by
557/// default. The call site may override this — a deployment fronting auth/OTP, for
558/// which an unthrottled window is worse than shedding load, can choose to fail
559/// **closed** (e.g. `seiva-http`'s `DistributedRateLimit::on_store_error`).
560#[async_trait]
561pub trait RateLimitStore: Send + Sync {
562    /// Records one hit for `key` and reports whether it is within `limit` per
563    /// `window`. Implementations increment-and-expire atomically.
564    async fn check(&self, key: &str, limit: u32, window: Duration)
565        -> PortResult<RateLimitDecision>;
566}
567
568/// The store key for **consumer-side inbox deduplication**: processing one event
569/// at most once per consumer (ADR 0011). Compose it from the consumer's name and
570/// the event id, then claim it through [`IdempotencyStore::begin`] **in the same
571/// transaction** as the effect — on [`Fresh`](IdempotencyOutcome::Fresh) apply
572/// the effect and [`finish`](IdempotencyStore::finish); on any other outcome the
573/// event was already handled, so skip it (and still ack after commit). A
574/// redelivery of the same event id resolves to the same key, so the effect never
575/// repeats even though the broker may deliver more than once.
576///
577/// ```
578/// use seiva_ports::inbox_key;
579/// assert_eq!(inbox_key("billing", "evt-123"), "inbox:billing:evt-123");
580/// ```
581#[must_use]
582pub fn inbox_key(consumer: &str, event_id: &str) -> String {
583    format!("inbox:{consumer}:{event_id}")
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589
590    #[test]
591    fn sensitive_fields_are_detected_case_insensitively() {
592        for name in [
593            "password", "Password", "api_key", "x-secret", "pwdHash", "key", "cookie",
594        ] {
595            assert!(is_sensitive_field(name), "{name} must be sensitive");
596        }
597        for name in ["username", "title", "amount", "keyboard_layout"] {
598            assert!(!is_sensitive_field(name), "{name} must not be sensitive");
599        }
600    }
601
602    #[test]
603    fn redacted_masks_only_sensitive_values() {
604        let entry = AuditEntry {
605            operation: "POST /x".to_owned(),
606            details: vec![
607                ("username".to_owned(), "alice".to_owned()),
608                ("password".to_owned(), "hunter2".to_owned()),
609            ],
610            ..AuditEntry::default()
611        }
612        .redacted();
613        assert_eq!(
614            entry.details[0],
615            ("username".to_owned(), "alice".to_owned())
616        );
617        assert_eq!(
618            entry.details[1],
619            ("password".to_owned(), "[redacted]".to_owned())
620        );
621    }
622
623    #[test]
624    fn tenant_id_rejects_empty_and_whitespace() {
625        assert!(TenantId::new("").is_none());
626        assert!(TenantId::new("   ").is_none());
627        let t = TenantId::new("acme").expect("non-empty is valid");
628        assert_eq!(t.as_str(), "acme");
629        assert_eq!(t.to_string(), "acme");
630    }
631
632    #[test]
633    fn scope_distinguishes_tenant_from_global() {
634        let tenant = Scope::tenant("acme").expect("non-empty");
635        assert_eq!(tenant.tenant_id().map(TenantId::as_str), Some("acme"));
636        assert!(Scope::Global.tenant_id().is_none());
637        assert!(Scope::tenant("  ").is_none());
638    }
639
640    #[test]
641    fn id_renders_as_lowercase_hex() {
642        let bytes = [0xde, 0xad, 0xbe, 0xef, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
643        let id = Id(bytes);
644        // Validate our dependency-free formatter against std's lowercase hex.
645        let expected: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
646        assert_eq!(format!("{id:?}"), format!("Id({expected})"));
647    }
648}