Skip to main content

mako_engine/
outbox.rs

1//! Outbox pattern for reliable at-least-once outbound message delivery.
2//!
3//! # Why the outbox?
4//!
5//! When a process transition generates an outbound EDIFACT message (e.g. an
6//! APERAK acknowledgement), two writes must happen atomically:
7//!
8//! 1. Domain events are appended to the event store.
9//! 2. The EDIFACT payload is queued for delivery to the AS4 endpoint.
10//!
11//! Without the outbox, a crash between steps 1 and 2 silently loses the
12//! outbound message. With the outbox, both writes are part of the same
13//! database transaction — a background delivery worker then delivers pending
14//! messages, surviving crashes and transient AS4 failures transparently.
15//!
16//! # Usage
17//!
18//! ```rust,ignore
19//! // After a command dispatch that should trigger an outbound APERAK:
20//! let env = &aperak_envelopes[0];
21//! let msg = OutboxMessage::new(
22//!     process.stream_id().clone(),
23//!     env.process_id,
24//!     env.tenant_id,
25//!     env.correlation_id,
26//!     env.conversation_id,
27//!     env.event_id,
28//!     "APERAK",
29//!     &recipient_gln,
30//!     aperak_payload_json,
31//! );
32//! outbox_store.enqueue(&[msg]).await?;
33//!
34//! // Background delivery worker:
35//! let pending = outbox_store.pending_now(50).await?;
36//! for msg in pending {
37//!     as4_client.send(&msg).await?;
38//!     outbox_store.acknowledge(msg.message_id).await?;
39//! }
40//! ```
41//!
42//! # Atomicity contract
43//!
44//! `InMemoryOutboxStore` does **not** guarantee transactional atomicity
45//! with `InMemoryEventStore`. Persistent backend crates
46//! (`mako-event-store-slatedb`, `mako-event-store-postgres`) MUST enqueue
47//! messages in the same database transaction as the event append.
48
49use std::sync::Arc;
50
51#[cfg(any(test, feature = "testing"))]
52use std::collections::HashMap;
53#[cfg(any(test, feature = "testing"))]
54use tokio::sync::RwLock;
55
56use time::OffsetDateTime;
57
58use crate::{
59    error::EngineError,
60    ids::{ConversationId, CorrelationId, EventId, OutboxMessageId, ProcessId, StreamId, TenantId},
61};
62
63// ── PendingOutbox ─────────────────────────────────────────────────────────────
64
65/// A lightweight outbox message specification produced by [`Workflow::handle`].
66///
67/// [`Workflow::handle`] is a pure function: it cannot know the store-assigned
68/// fields (`event_id`, `stream_id`, `process_id`, etc.) of the events it is
69/// about to emit. `PendingOutbox` carries only the information the domain
70/// workflow can produce deterministically, without I/O or clock access.
71///
72/// The engine fills in the store-assigned fields after the event append
73/// succeeds, converting `PendingOutbox` into a fully materialised
74/// [`OutboxMessage`] inside [`SlateDbStore::append_with_outbox`].
75///
76/// # Example
77///
78/// ```rust,ignore
79/// // Inside Workflow::handle, when DispatchAperak succeeds:
80/// let outbox = vec![
81///     PendingOutbox::new("APERAK", &state.sender_party_id().to_string(), aperak_payload)
82///         .caused_by(0),  // caused by the first event in this batch
83/// ];
84/// Ok(WorkflowOutput { events, outbox })
85/// ```
86///
87/// [`Workflow::handle`]: crate::workflow::Workflow::handle
88/// [`SlateDbStore::append_with_outbox`]: crate::event_store::AtomicAppend::append_with_outbox
89#[derive(Debug, Clone)]
90pub struct PendingOutbox {
91    /// EDIFACT or XML message type (e.g. `"APERAK"`, `"CONTRL"`, `"REMADV"`).
92    pub message_type: Box<str>,
93    /// GLN or EIC code of the intended recipient market participant.
94    pub recipient: Box<str>,
95    /// Domain-level message payload (JSON).
96    ///
97    /// Typically encodes the intent (e.g. positive/negative APERAK reason)
98    /// rather than the final EDIFACT bytes. The delivery worker or AS4
99    /// gateway is responsible for rendering the final wire format.
100    pub payload: serde_json::Value,
101    /// Do not deliver before this time.
102    ///
103    /// `None` means deliver immediately (as soon as the delivery worker runs).
104    /// Must not use the wall clock inside `handle` — derive from domain data
105    /// only (e.g. a schedule date carried in the command).
106    pub deliver_after: Option<OffsetDateTime>,
107    /// BO4E JSON Schema URL that describes the `payload` shape.
108    ///
109    /// Set this to the canonical BO4E schema URL when the payload is a
110    /// BO4E-typed object (e.g. `Marktlokation`, `Messlokation`). Leave
111    /// `None` for raw EDIFACT or untyped payloads.
112    ///
113    /// Example:
114    /// `"https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas/bo/Marktlokation.json"`
115    pub payload_schema: Option<Box<str>>,
116    /// Zero-based index into the concurrent events batch that caused this
117    /// outbound message.
118    ///
119    /// Used by the engine to set `causation_event_id` on the materialised
120    /// [`OutboxMessage`] from the stamped [`EventEnvelope`] at the same index.
121    /// Clamped to `events.len() - 1` when out-of-range.
122    ///
123    /// [`EventEnvelope`]: crate::envelope::EventEnvelope
124    pub caused_by_event_index: usize,
125}
126
127impl PendingOutbox {
128    /// Construct a pending outbox message for immediate delivery.
129    ///
130    /// `caused_by_event_index` defaults to `0` (first event in the batch).
131    /// Chain [`caused_by`] to change it.
132    ///
133    /// [`caused_by`]: PendingOutbox::caused_by
134    #[must_use]
135    pub fn new(
136        message_type: impl Into<Box<str>>,
137        recipient: impl Into<Box<str>>,
138        payload: serde_json::Value,
139    ) -> Self {
140        Self {
141            message_type: message_type.into(),
142            recipient: recipient.into(),
143            payload,
144            deliver_after: None,
145            payload_schema: None,
146            caused_by_event_index: 0,
147        }
148    }
149
150    /// Set the zero-based index of the event that caused this outbox message.
151    #[must_use]
152    pub fn caused_by(mut self, index: usize) -> Self {
153        self.caused_by_event_index = index;
154        self
155    }
156
157    /// Set a deferred delivery time (must be derived from domain data, not
158    /// the wall clock, to preserve `Workflow::handle` purity).
159    #[must_use]
160    pub fn with_deliver_after(mut self, deliver_after: OffsetDateTime) -> Self {
161        self.deliver_after = Some(deliver_after);
162        self
163    }
164
165    /// Attach a BO4E JSON Schema URL to the payload.
166    ///
167    /// Use this when the payload is a BO4E-typed object so the ERP adapter
168    /// can deserialise it into the correct type without inspecting the JSON.
169    #[must_use]
170    pub fn with_schema(mut self, schema_url: &'static str) -> Self {
171        self.payload_schema = Some(schema_url.into());
172        self
173    }
174}
175
176// ── OutboxMessage ─────────────────────────────────────────────────────────────
177
178/// An outbound message queued for delivery via AS4 or another channel.
179///
180/// The message carries both routing information (`recipient`, `message_type`)
181/// and full correlation metadata so the delivery worker can trace every send
182/// back to the domain event that caused it.
183///
184/// Construct with [`OutboxMessage::new`] and optionally chain
185/// [`OutboxMessage::with_deliver_after`] for deferred delivery.
186#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
187pub struct OutboxMessage {
188    /// Stable unique identifier for this outbox entry.
189    pub message_id: OutboxMessageId,
190
191    /// The process stream that produced this outbound message.
192    pub stream_id: StreamId,
193
194    /// The MaKo process instance.
195    pub process_id: ProcessId,
196
197    /// The tenant sending this message.
198    pub tenant_id: TenantId,
199
200    /// Propagated correlation root from the triggering event.
201    pub correlation_id: CorrelationId,
202
203    /// Business conversation this message belongs to (e.g. UTILMD ↔ APERAK).
204    pub conversation_id: ConversationId,
205
206    /// The persisted event that directly caused this outbound message.
207    pub causation_event_id: EventId,
208
209    /// EDIFACT or XML message type (e.g. `"APERAK"`, `"CONTRL"`, `"UTILMD"`).
210    pub message_type: Box<str>,
211
212    /// GLN or EIC code of the intended recipient market participant.
213    pub recipient: Box<str>,
214
215    /// Serialized message payload.
216    ///
217    /// Typically a JSON-encoded string of EDIFACT bytes or a structured
218    /// JSON object for non-EDIFACT channels.
219    pub payload: serde_json::Value,
220
221    /// BO4E JSON Schema URL that validates `payload`, if present.
222    ///
223    /// `None` for raw EDIFACT or untyped payloads. Set by domain workflows
224    /// via [`PendingOutbox::with_schema`] when the payload is a BO4E object.
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub payload_schema: Option<Box<str>>,
227
228    /// When this entry was created.
229    pub created_at: OffsetDateTime,
230
231    /// Do not deliver before this time.
232    ///
233    /// `None` means deliver immediately (as soon as the delivery worker runs).
234    pub deliver_after: Option<OffsetDateTime>,
235
236    /// Number of delivery attempts so far. Starts at `0`, incremented by
237    /// [`OutboxStore::reschedule`].
238    pub attempt_count: u32,
239
240    /// Workflow family name that produced this message (e.g. `"gpke-sperrung"`).
241    ///
242    /// Stamped from the `EventEnvelope::workflow_id.name` at materialisation
243    /// time — the path every message a workflow emits takes. Used by the
244    /// `OutboxErpWorker` to populate the `makoworkflow` CloudEvents extension
245    /// attribute, which `marktd` maps to `marktrole` for role-scoped ERP
246    /// fan-out. Empty only on a message built directly with
247    /// [`OutboxMessage::new`], which no workflow does.
248    pub workflow_name: Box<str>,
249
250    /// W3C `traceparent` of the request that caused this message.
251    ///
252    /// Captured from [`crate::trace_ctx`] at creation time and injected into
253    /// outbound deliveries (ERP webhook header + CloudEvents `traceparent`
254    /// extension), so a trace started by the inbound transport continues
255    /// across the asynchronous outbox boundary.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub trace_context: Option<Box<str>>,
258}
259
260impl OutboxMessage {
261    /// Construct a new outbox message.
262    ///
263    /// `message_id` and `created_at` are generated automatically.
264    /// `attempt_count` is initialized to `0`.
265    ///
266    /// Call [`OutboxMessage::with_deliver_after`] to schedule deferred
267    /// delivery.
268    #[allow(clippy::too_many_arguments)]
269    #[must_use]
270    pub fn new(
271        stream_id: StreamId,
272        process_id: ProcessId,
273        tenant_id: TenantId,
274        correlation_id: CorrelationId,
275        conversation_id: ConversationId,
276        causation_event_id: EventId,
277        message_type: impl Into<Box<str>>,
278        recipient: impl Into<Box<str>>,
279        payload: serde_json::Value,
280    ) -> Self {
281        Self {
282            message_id: OutboxMessageId::new(),
283            stream_id,
284            process_id,
285            tenant_id,
286            correlation_id,
287            conversation_id,
288            causation_event_id,
289            message_type: message_type.into(),
290            recipient: recipient.into(),
291            payload,
292            payload_schema: None,
293            created_at: OffsetDateTime::now_utc(),
294            deliver_after: None,
295            attempt_count: 0,
296            workflow_name: "".into(),
297            trace_context: crate::trace_ctx::current().map(Into::into),
298        }
299    }
300
301    /// Set a deferred delivery time.
302    ///
303    /// The message will not appear in [`OutboxStore::pending`] results until
304    /// `now >= deliver_after`.
305    #[must_use]
306    pub fn with_deliver_after(mut self, deliver_after: OffsetDateTime) -> Self {
307        self.deliver_after = Some(deliver_after);
308        self
309    }
310}
311
312// ── OutboxStore ───────────────────────────────────────────────────────────────
313
314/// Storage contract for outbox messages.
315///
316/// ## Atomicity requirement
317///
318/// In production deployments, calls to [`OutboxStore::enqueue`] MUST be
319/// atomic with the corresponding [`EventStore::append`] — both writes MUST
320/// succeed or both MUST fail. Implement this by sharing the same database
321/// transaction across both operations.
322///
323/// ## Delivery worker contract
324///
325/// The delivery worker loop should:
326/// 1. Call [`OutboxStore::pending_now`] to retrieve ready messages.
327/// 2. Attempt delivery to the AS4 endpoint.
328/// 3. On success: call [`OutboxStore::acknowledge`] to remove the message.
329/// 4. On transient failure: call [`OutboxStore::reschedule`] with an
330///    exponential back-off delay.
331///
332/// ## Blanket `Arc` implementation
333///
334/// `Arc<S>` implements `OutboxStore` whenever `S: OutboxStore`, so you can
335/// share a store across a delivery worker and command handlers without
336/// additional wrapper types.
337///
338/// [`EventStore::append`]: crate::event_store::EventStore::append
339#[allow(async_fn_in_trait)]
340pub trait OutboxStore: Send + Sync {
341    /// Persist `messages` durably, ready for delivery.
342    ///
343    /// In a persistent backend this MUST be called within the same
344    /// transaction as the event append.
345    ///
346    /// # Errors
347    ///
348    /// Returns [`EngineError::Outbox`] on storage failure.
349    #[must_use = "dropping an enqueue Result silently loses outbound EDIFACT messages"]
350    async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError>;
351
352    /// Return up to `limit` messages ready for delivery as of `now`.
353    ///
354    /// A message is ready when `deliver_after` is `None` or `<= now`.
355    /// Results are ordered **oldest-first** by `created_at`.
356    ///
357    /// # Errors
358    ///
359    /// Returns [`EngineError::Outbox`] on storage failure.
360    #[must_use = "dropping a pending Result silently discards outbox delivery work"]
361    async fn pending(
362        &self,
363        limit: usize,
364        now: OffsetDateTime,
365    ) -> Result<Vec<OutboxMessage>, EngineError>;
366
367    /// Return up to `limit` messages ready for delivery right now.
368    ///
369    /// Convenience wrapper around [`OutboxStore::pending`] that uses
370    /// `OffsetDateTime::now_utc()` as the reference time.
371    ///
372    /// # Errors
373    ///
374    /// Returns [`EngineError::Outbox`] on storage failure.
375    async fn pending_now(&self, limit: usize) -> Result<Vec<OutboxMessage>, EngineError> {
376        self.pending(limit, OffsetDateTime::now_utc()).await
377    }
378
379    /// Remove a message from the outbox after successful delivery.
380    ///
381    /// Calling this with an unknown `id` is a no-op.
382    ///
383    /// # Errors
384    ///
385    /// Returns [`EngineError::Outbox`] on storage failure.
386    #[must_use = "dropping an acknowledge Result silently hides a store error"]
387    async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError>;
388
389    /// Reschedule a message for a future delivery attempt.
390    ///
391    /// Implementations MUST increment `attempt_count` on the stored record.
392    /// Calling this with an unknown `id` is a no-op.
393    ///
394    /// # Errors
395    ///
396    /// Returns [`EngineError::Outbox`] on storage failure.
397    #[must_use = "dropping a reschedule Result silently hides a store error"]
398    async fn reschedule(
399        &self,
400        id: OutboxMessageId,
401        deliver_after: OffsetDateTime,
402    ) -> Result<(), EngineError>;
403
404    /// Return the total number of messages currently in the outbox.
405    ///
406    /// # Errors
407    ///
408    /// Returns [`EngineError::Outbox`] on storage failure.
409    #[must_use = "dropping a len Result silently discards a store error"]
410    async fn len(&self) -> Result<usize, EngineError>;
411
412    /// Return `true` when the outbox contains no messages.
413    ///
414    /// # Errors
415    ///
416    /// Returns [`EngineError::Outbox`] on storage failure.
417    async fn is_empty(&self) -> Result<bool, EngineError> {
418        Ok(self.len().await? == 0)
419    }
420}
421
422// ── Arc<S> blanket impl ───────────────────────────────────────────────────────
423
424impl<S: OutboxStore> OutboxStore for Arc<S> {
425    async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError> {
426        self.as_ref().enqueue(messages).await
427    }
428
429    async fn pending(
430        &self,
431        limit: usize,
432        now: OffsetDateTime,
433    ) -> Result<Vec<OutboxMessage>, EngineError> {
434        self.as_ref().pending(limit, now).await
435    }
436
437    async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError> {
438        self.as_ref().acknowledge(id).await
439    }
440
441    async fn reschedule(
442        &self,
443        id: OutboxMessageId,
444        deliver_after: OffsetDateTime,
445    ) -> Result<(), EngineError> {
446        self.as_ref().reschedule(id, deliver_after).await
447    }
448
449    async fn len(&self) -> Result<usize, EngineError> {
450        self.as_ref().len().await
451    }
452}
453
454// ── NoopOutboxStore ───────────────────────────────────────────────────────────
455
456/// An [`OutboxStore`] that silently discards all messages.
457///
458/// Every `enqueue` succeeds without storing anything. `pending` always
459/// returns an empty list. Use this as the default when outbox delivery is
460/// managed elsewhere or not required.
461///
462/// # ⚠️ Data loss warning
463///
464/// `NoopOutboxStore` **discards every outbound message silently**. No APERAK,
465/// MSCONS, or UTILMD will ever be delivered to the AS4 endpoint. Do not use
466/// in production.
467///
468/// This type is available in all build configurations so it can serve as a
469/// default type parameter in [`EngineBuilder`]. However, `EngineBuilder::new`
470/// (which wires this as the default) is only available with the `testing`
471/// feature or in `cfg(test)`. Production code must call
472/// [`EngineBuilder::with_stores`] instead.
473///
474/// [`EngineBuilder`]: crate::builder::EngineBuilder
475/// [`EngineBuilder::with_stores`]: crate::builder::EngineBuilder::with_stores
476#[derive(Debug, Clone, Copy, Default)]
477#[must_use = "NoopOutboxStore discards all outbound messages silently — use a persistent OutboxStore in production"]
478#[cfg_attr(
479    not(any(test, feature = "testing")),
480    deprecated = "NoopOutboxStore must not be instantiated in production builds; use a durable OutboxStore instead"
481)]
482pub struct NoopOutboxStore;
483
484#[cfg(any(test, feature = "testing"))]
485impl OutboxStore for NoopOutboxStore {
486    async fn enqueue(&self, _messages: &[OutboxMessage]) -> Result<(), EngineError> {
487        Ok(())
488    }
489
490    async fn pending(
491        &self,
492        _limit: usize,
493        _now: OffsetDateTime,
494    ) -> Result<Vec<OutboxMessage>, EngineError> {
495        Ok(Vec::new())
496    }
497
498    async fn acknowledge(&self, _id: OutboxMessageId) -> Result<(), EngineError> {
499        Ok(())
500    }
501
502    async fn reschedule(
503        &self,
504        _id: OutboxMessageId,
505        _deliver_after: OffsetDateTime,
506    ) -> Result<(), EngineError> {
507        Ok(())
508    }
509
510    async fn len(&self) -> Result<usize, EngineError> {
511        Ok(0)
512    }
513}
514
515// ── InMemoryOutboxStore ───────────────────────────────────────────────────────
516
517/// An in-memory [`OutboxStore`] for tests and development.
518///
519/// Backed by a `HashMap` protected by a `RwLock`. Cloning shares the
520/// underlying data via `Arc` — all clones see the same outbox state.
521///
522/// **Not production-safe.** Use this for:
523/// - Unit and integration tests
524/// - Local development and examples
525/// - Verifying the outbox delivery loop without an external message broker
526///
527/// Only available in `#[cfg(test)]` or with the `testing` feature enabled.
528#[cfg(any(test, feature = "testing"))]
529#[derive(Debug, Default, Clone)]
530pub struct InMemoryOutboxStore {
531    inner: Arc<RwLock<HashMap<OutboxMessageId, OutboxMessage>>>,
532}
533
534#[cfg(any(test, feature = "testing"))]
535impl InMemoryOutboxStore {
536    /// Create an empty outbox store.
537    #[must_use]
538    pub fn new() -> Self {
539        Self::default()
540    }
541}
542
543#[cfg(any(test, feature = "testing"))]
544impl OutboxStore for InMemoryOutboxStore {
545    async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError> {
546        let mut map = self.inner.write().await;
547        for msg in messages {
548            map.insert(msg.message_id, msg.clone());
549        }
550        Ok(())
551    }
552
553    async fn pending(
554        &self,
555        limit: usize,
556        now: OffsetDateTime,
557    ) -> Result<Vec<OutboxMessage>, EngineError> {
558        let map = self.inner.read().await;
559        let mut ready: Vec<_> = map
560            .values()
561            .filter(|m| m.deliver_after.is_none_or(|d| d <= now))
562            .cloned()
563            .collect();
564        // Stable ordering: oldest first so the delivery worker processes in
565        // creation order, preserving causal ordering across messages.
566        ready.sort_by_key(|m| m.created_at);
567        ready.truncate(limit);
568        Ok(ready)
569    }
570
571    async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError> {
572        self.inner.write().await.remove(&id);
573        Ok(())
574    }
575
576    async fn reschedule(
577        &self,
578        id: OutboxMessageId,
579        deliver_after: OffsetDateTime,
580    ) -> Result<(), EngineError> {
581        let mut map = self.inner.write().await;
582        if let Some(msg) = map.get_mut(&id) {
583            msg.deliver_after = Some(deliver_after);
584            msg.attempt_count += 1;
585        }
586        Ok(())
587    }
588
589    async fn len(&self) -> Result<usize, EngineError> {
590        Ok(self.inner.read().await.len())
591    }
592}
593
594// ── Outbox idempotency key ────────────────────────────────────────────────────
595
596/// Compute a deterministic idempotency key for an outbound message.
597///
598/// The key is a UUID v5 (SHA-1 over a stable namespace) derived from the
599/// combination of process id, workflow step name, recipient partner id, and
600/// format version. Identical inputs always produce the same UUID.
601///
602/// # Usage
603///
604/// Store the key alongside the outbox entry and use it as a unique constraint
605/// in persistent backends so that re-dispatching the same command (e.g. after
606/// a retry) does not produce duplicate outbound messages:
607///
608/// ```rust
609/// use mako_engine::outbox::outbox_idempotency_key;
610/// use mako_engine::ids::ProcessId;
611///
612/// let process_id = ProcessId::new();
613/// let key = outbox_idempotency_key(process_id, "DispatchAperak", "4012345000023", "FV2025-10-01");
614/// println!("idempotency key: {key}");
615/// ```
616///
617/// # Key derivation
618///
619/// The key is `UUID_v5(MAKO_ENGINE_OUTBOX_NS, "{process_id}|{step}|{partner}|{fv}")`.
620///
621/// `MAKO_ENGINE_OUTBOX_NS` is a fixed namespace UUID (RFC 4122 §4.3, SHA-1
622/// variant) that scopes all mako-engine outbox keys to avoid collisions with
623/// UUIDs from other namespaces.
624#[must_use]
625pub fn outbox_idempotency_key(
626    process_id: ProcessId,
627    step: &str,
628    recipient: &str,
629    format_version: &str,
630) -> uuid::Uuid {
631    // A fixed namespace UUID for mako-engine outbox keys.
632    // Generated once by uuid::Uuid::new_v4() and hardcoded for stability.
633    // Changing this constant invalidates all existing keys — treat as immutable.
634    const MAKO_ENGINE_OUTBOX_NS: uuid::Uuid = uuid::Uuid::from_bytes([
635        0xd4, 0x7a, 0x2c, 0x9e, 0x5b, 0x31, 0x47, 0xf2, 0x89, 0x0a, 0x1e, 0x6c, 0x8a, 0x3d, 0x5f,
636        0x04,
637    ]);
638    let name = format!("{process_id}|{step}|{recipient}|{format_version}");
639    uuid::Uuid::new_v5(&MAKO_ENGINE_OUTBOX_NS, name.as_bytes())
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645    use crate::ids::{ConversationId, CorrelationId, EventId, ProcessId, TenantId};
646
647    fn make_msg() -> OutboxMessage {
648        OutboxMessage::new(
649            StreamId::new("process/test"),
650            ProcessId::new(),
651            TenantId::new(),
652            CorrelationId::new(),
653            ConversationId::new(),
654            EventId::new(),
655            "APERAK",
656            "4012345000023",
657            serde_json::json!({"positive": true}),
658        )
659    }
660
661    #[tokio::test]
662    async fn enqueue_appears_in_pending() {
663        let store = InMemoryOutboxStore::new();
664        let msg = make_msg();
665        let id = msg.message_id;
666
667        store.enqueue(&[msg]).await.unwrap();
668
669        assert_eq!(store.len().await.unwrap(), 1);
670        let pending = store.pending_now(10).await.unwrap();
671        assert_eq!(pending.len(), 1);
672        assert_eq!(pending[0].message_id, id);
673    }
674
675    #[tokio::test]
676    async fn acknowledge_removes_message() {
677        let store = InMemoryOutboxStore::new();
678        let msg = make_msg();
679        let id = msg.message_id;
680
681        store.enqueue(&[msg]).await.unwrap();
682        store.acknowledge(id).await.unwrap();
683
684        assert!(store.is_empty().await.unwrap());
685    }
686
687    #[tokio::test]
688    async fn deferred_message_not_in_pending_yet() {
689        let store = InMemoryOutboxStore::new();
690        let future = OffsetDateTime::now_utc() + time::Duration::hours(1);
691        let msg = make_msg().with_deliver_after(future);
692
693        store.enqueue(&[msg]).await.unwrap();
694
695        let pending = store.pending_now(10).await.unwrap();
696        assert!(
697            pending.is_empty(),
698            "deferred message must not appear before its time"
699        );
700    }
701
702    #[tokio::test]
703    async fn deferred_message_appears_after_deadline() {
704        let store = InMemoryOutboxStore::new();
705        let past = OffsetDateTime::now_utc() - time::Duration::seconds(1);
706        let msg = make_msg().with_deliver_after(past);
707
708        store.enqueue(&[msg]).await.unwrap();
709
710        let pending = store.pending_now(10).await.unwrap();
711        assert_eq!(pending.len(), 1);
712    }
713
714    #[tokio::test]
715    async fn reschedule_increments_attempt_count() {
716        let store = InMemoryOutboxStore::new();
717        let msg = make_msg();
718        let id = msg.message_id;
719        let new_time = OffsetDateTime::now_utc() + time::Duration::minutes(5);
720
721        store.enqueue(&[msg]).await.unwrap();
722        store.reschedule(id, new_time).await.unwrap();
723
724        let inner = store.inner.read().await;
725        let stored = inner.get(&id).unwrap();
726        assert_eq!(stored.attempt_count, 1);
727        assert_eq!(stored.deliver_after, Some(new_time));
728    }
729
730    #[tokio::test]
731    async fn pending_ordered_oldest_first() {
732        let store = InMemoryOutboxStore::new();
733        store.enqueue(&[make_msg()]).await.unwrap();
734        store.enqueue(&[make_msg()]).await.unwrap();
735
736        let pending = store.pending_now(10).await.unwrap();
737        assert_eq!(pending.len(), 2);
738        assert!(pending[0].created_at <= pending[1].created_at);
739    }
740
741    #[test]
742    fn outbox_idempotency_key_is_stable_and_deterministic() {
743        let pid = ProcessId::new();
744        let step = "ReceiveAperak";
745        let partner = "4012345000023";
746        let fv = "FV2025-10-01";
747
748        let k1 = outbox_idempotency_key(pid, step, partner, fv);
749        let k2 = outbox_idempotency_key(pid, step, partner, fv);
750        assert_eq!(k1, k2, "same inputs must produce the same key");
751        assert_eq!(k1.to_string().len(), 36, "UUID string is 36 chars");
752
753        // Different step → different key.
754        let k3 = outbox_idempotency_key(pid, "ReceiveContrl", partner, fv);
755        assert_ne!(k1, k3, "different step must produce different key");
756
757        // Different FV → different key.
758        let k4 = outbox_idempotency_key(pid, step, partner, "FV2026-10-01");
759        assert_ne!(k1, k4, "different FV must produce different key");
760    }
761}