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.0.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. Used by the `OutboxErpWorker` to populate the `makoworkflow`
244 /// CloudEvents extension attribute, which `marktd` maps to `marktrole` for
245 /// role-scoped ERP fan-out.
246 ///
247 /// Empty string for messages materialised before this field was introduced
248 /// (backward-compatible deserialisation via `#[serde(default)]`).
249 #[serde(default)]
250 pub workflow_name: Box<str>,
251}
252
253impl OutboxMessage {
254 /// Construct a new outbox message.
255 ///
256 /// `message_id` and `created_at` are generated automatically.
257 /// `attempt_count` is initialized to `0`.
258 ///
259 /// Call [`OutboxMessage::with_deliver_after`] to schedule deferred
260 /// delivery.
261 #[allow(clippy::too_many_arguments)]
262 #[must_use]
263 pub fn new(
264 stream_id: StreamId,
265 process_id: ProcessId,
266 tenant_id: TenantId,
267 correlation_id: CorrelationId,
268 conversation_id: ConversationId,
269 causation_event_id: EventId,
270 message_type: impl Into<Box<str>>,
271 recipient: impl Into<Box<str>>,
272 payload: serde_json::Value,
273 ) -> Self {
274 Self {
275 message_id: OutboxMessageId::new(),
276 stream_id,
277 process_id,
278 tenant_id,
279 correlation_id,
280 conversation_id,
281 causation_event_id,
282 message_type: message_type.into(),
283 recipient: recipient.into(),
284 payload,
285 payload_schema: None,
286 created_at: OffsetDateTime::now_utc(),
287 deliver_after: None,
288 attempt_count: 0,
289 workflow_name: "".into(),
290 }
291 }
292
293 /// Set a deferred delivery time.
294 ///
295 /// The message will not appear in [`OutboxStore::pending`] results until
296 /// `now >= deliver_after`.
297 #[must_use]
298 pub fn with_deliver_after(mut self, deliver_after: OffsetDateTime) -> Self {
299 self.deliver_after = Some(deliver_after);
300 self
301 }
302}
303
304// ── OutboxStore ───────────────────────────────────────────────────────────────
305
306/// Storage contract for outbox messages.
307///
308/// ## Atomicity requirement
309///
310/// In production deployments, calls to [`OutboxStore::enqueue`] MUST be
311/// atomic with the corresponding [`EventStore::append`] — both writes MUST
312/// succeed or both MUST fail. Implement this by sharing the same database
313/// transaction across both operations.
314///
315/// ## Delivery worker contract
316///
317/// The delivery worker loop should:
318/// 1. Call [`OutboxStore::pending_now`] to retrieve ready messages.
319/// 2. Attempt delivery to the AS4 endpoint.
320/// 3. On success: call [`OutboxStore::acknowledge`] to remove the message.
321/// 4. On transient failure: call [`OutboxStore::reschedule`] with an
322/// exponential back-off delay.
323///
324/// ## Blanket `Arc` implementation
325///
326/// `Arc<S>` implements `OutboxStore` whenever `S: OutboxStore`, so you can
327/// share a store across a delivery worker and command handlers without
328/// additional wrapper types.
329///
330/// [`EventStore::append`]: crate::event_store::EventStore::append
331#[allow(async_fn_in_trait)]
332pub trait OutboxStore: Send + Sync {
333 /// Persist `messages` durably, ready for delivery.
334 ///
335 /// In a persistent backend this MUST be called within the same
336 /// transaction as the event append.
337 ///
338 /// # Errors
339 ///
340 /// Returns [`EngineError::Outbox`] on storage failure.
341 #[must_use = "dropping an enqueue Result silently loses outbound EDIFACT messages"]
342 async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError>;
343
344 /// Return up to `limit` messages ready for delivery as of `now`.
345 ///
346 /// A message is ready when `deliver_after` is `None` or `<= now`.
347 /// Results are ordered **oldest-first** by `created_at`.
348 ///
349 /// # Errors
350 ///
351 /// Returns [`EngineError::Outbox`] on storage failure.
352 #[must_use = "dropping a pending Result silently discards outbox delivery work"]
353 async fn pending(
354 &self,
355 limit: usize,
356 now: OffsetDateTime,
357 ) -> Result<Vec<OutboxMessage>, EngineError>;
358
359 /// Return up to `limit` messages ready for delivery right now.
360 ///
361 /// Convenience wrapper around [`OutboxStore::pending`] that uses
362 /// `OffsetDateTime::now_utc()` as the reference time.
363 ///
364 /// # Errors
365 ///
366 /// Returns [`EngineError::Outbox`] on storage failure.
367 async fn pending_now(&self, limit: usize) -> Result<Vec<OutboxMessage>, EngineError> {
368 self.pending(limit, OffsetDateTime::now_utc()).await
369 }
370
371 /// Remove a message from the outbox after successful delivery.
372 ///
373 /// Calling this with an unknown `id` is a no-op.
374 ///
375 /// # Errors
376 ///
377 /// Returns [`EngineError::Outbox`] on storage failure.
378 #[must_use = "dropping an acknowledge Result silently hides a store error"]
379 async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError>;
380
381 /// Reschedule a message for a future delivery attempt.
382 ///
383 /// Implementations MUST increment `attempt_count` on the stored record.
384 /// Calling this with an unknown `id` is a no-op.
385 ///
386 /// # Errors
387 ///
388 /// Returns [`EngineError::Outbox`] on storage failure.
389 #[must_use = "dropping a reschedule Result silently hides a store error"]
390 async fn reschedule(
391 &self,
392 id: OutboxMessageId,
393 deliver_after: OffsetDateTime,
394 ) -> Result<(), EngineError>;
395
396 /// Return the total number of messages currently in the outbox.
397 ///
398 /// # Errors
399 ///
400 /// Returns [`EngineError::Outbox`] on storage failure.
401 #[must_use = "dropping a len Result silently discards a store error"]
402 async fn len(&self) -> Result<usize, EngineError>;
403
404 /// Return `true` when the outbox contains no messages.
405 ///
406 /// # Errors
407 ///
408 /// Returns [`EngineError::Outbox`] on storage failure.
409 async fn is_empty(&self) -> Result<bool, EngineError> {
410 Ok(self.len().await? == 0)
411 }
412}
413
414// ── Arc<S> blanket impl ───────────────────────────────────────────────────────
415
416impl<S: OutboxStore> OutboxStore for Arc<S> {
417 async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError> {
418 self.as_ref().enqueue(messages).await
419 }
420
421 async fn pending(
422 &self,
423 limit: usize,
424 now: OffsetDateTime,
425 ) -> Result<Vec<OutboxMessage>, EngineError> {
426 self.as_ref().pending(limit, now).await
427 }
428
429 async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError> {
430 self.as_ref().acknowledge(id).await
431 }
432
433 async fn reschedule(
434 &self,
435 id: OutboxMessageId,
436 deliver_after: OffsetDateTime,
437 ) -> Result<(), EngineError> {
438 self.as_ref().reschedule(id, deliver_after).await
439 }
440
441 async fn len(&self) -> Result<usize, EngineError> {
442 self.as_ref().len().await
443 }
444}
445
446// ── NoopOutboxStore ───────────────────────────────────────────────────────────
447
448/// An [`OutboxStore`] that silently discards all messages.
449///
450/// Every `enqueue` succeeds without storing anything. `pending` always
451/// returns an empty list. Use this as the default when outbox delivery is
452/// managed elsewhere or not required.
453///
454/// # ⚠️ Data loss warning
455///
456/// `NoopOutboxStore` **discards every outbound message silently**. No APERAK,
457/// MSCONS, or UTILMD will ever be delivered to the AS4 endpoint. Do not use
458/// in production.
459///
460/// This type is available in all build configurations so it can serve as a
461/// default type parameter in [`EngineBuilder`]. However, `EngineBuilder::new`
462/// (which wires this as the default) is only available with the `testing`
463/// feature or in `cfg(test)`. Production code must call
464/// [`EngineBuilder::with_stores`] instead.
465///
466/// [`EngineBuilder`]: crate::builder::EngineBuilder
467/// [`EngineBuilder::with_stores`]: crate::builder::EngineBuilder::with_stores
468#[derive(Debug, Clone, Copy, Default)]
469#[must_use = "NoopOutboxStore discards all outbound messages silently — use a persistent OutboxStore in production"]
470#[cfg_attr(
471 not(any(test, feature = "testing")),
472 deprecated = "NoopOutboxStore must not be instantiated in production builds; use a durable OutboxStore instead"
473)]
474pub struct NoopOutboxStore;
475
476#[cfg(any(test, feature = "testing"))]
477impl OutboxStore for NoopOutboxStore {
478 async fn enqueue(&self, _messages: &[OutboxMessage]) -> Result<(), EngineError> {
479 Ok(())
480 }
481
482 async fn pending(
483 &self,
484 _limit: usize,
485 _now: OffsetDateTime,
486 ) -> Result<Vec<OutboxMessage>, EngineError> {
487 Ok(Vec::new())
488 }
489
490 async fn acknowledge(&self, _id: OutboxMessageId) -> Result<(), EngineError> {
491 Ok(())
492 }
493
494 async fn reschedule(
495 &self,
496 _id: OutboxMessageId,
497 _deliver_after: OffsetDateTime,
498 ) -> Result<(), EngineError> {
499 Ok(())
500 }
501
502 async fn len(&self) -> Result<usize, EngineError> {
503 Ok(0)
504 }
505}
506
507// ── InMemoryOutboxStore ───────────────────────────────────────────────────────
508
509/// An in-memory [`OutboxStore`] for tests and development.
510///
511/// Backed by a `HashMap` protected by a `RwLock`. Cloning shares the
512/// underlying data via `Arc` — all clones see the same outbox state.
513///
514/// **Not production-safe.** Use this for:
515/// - Unit and integration tests
516/// - Local development and examples
517/// - Verifying the outbox delivery loop without an external message broker
518///
519/// Only available in `#[cfg(test)]` or with the `testing` feature enabled.
520#[cfg(any(test, feature = "testing"))]
521#[derive(Debug, Default, Clone)]
522pub struct InMemoryOutboxStore {
523 inner: Arc<RwLock<HashMap<OutboxMessageId, OutboxMessage>>>,
524}
525
526#[cfg(any(test, feature = "testing"))]
527impl InMemoryOutboxStore {
528 /// Create an empty outbox store.
529 #[must_use]
530 pub fn new() -> Self {
531 Self::default()
532 }
533}
534
535#[cfg(any(test, feature = "testing"))]
536impl OutboxStore for InMemoryOutboxStore {
537 async fn enqueue(&self, messages: &[OutboxMessage]) -> Result<(), EngineError> {
538 let mut map = self.inner.write().await;
539 for msg in messages {
540 map.insert(msg.message_id, msg.clone());
541 }
542 Ok(())
543 }
544
545 async fn pending(
546 &self,
547 limit: usize,
548 now: OffsetDateTime,
549 ) -> Result<Vec<OutboxMessage>, EngineError> {
550 let map = self.inner.read().await;
551 let mut ready: Vec<_> = map
552 .values()
553 .filter(|m| m.deliver_after.is_none_or(|d| d <= now))
554 .cloned()
555 .collect();
556 // Stable ordering: oldest first so the delivery worker processes in
557 // creation order, preserving causal ordering across messages.
558 ready.sort_by_key(|m| m.created_at);
559 ready.truncate(limit);
560 Ok(ready)
561 }
562
563 async fn acknowledge(&self, id: OutboxMessageId) -> Result<(), EngineError> {
564 self.inner.write().await.remove(&id);
565 Ok(())
566 }
567
568 async fn reschedule(
569 &self,
570 id: OutboxMessageId,
571 deliver_after: OffsetDateTime,
572 ) -> Result<(), EngineError> {
573 let mut map = self.inner.write().await;
574 if let Some(msg) = map.get_mut(&id) {
575 msg.deliver_after = Some(deliver_after);
576 msg.attempt_count += 1;
577 }
578 Ok(())
579 }
580
581 async fn len(&self) -> Result<usize, EngineError> {
582 Ok(self.inner.read().await.len())
583 }
584}
585
586// ── Outbox idempotency key ────────────────────────────────────────────────────
587
588/// Compute a deterministic idempotency key for an outbound message.
589///
590/// The key is a UUID v5 (SHA-1 over a stable namespace) derived from the
591/// combination of process id, workflow step name, recipient partner id, and
592/// format version. Identical inputs always produce the same UUID.
593///
594/// # Usage
595///
596/// Store the key alongside the outbox entry and use it as a unique constraint
597/// in persistent backends so that re-dispatching the same command (e.g. after
598/// a retry) does not produce duplicate outbound messages:
599///
600/// ```rust
601/// use mako_engine::outbox::outbox_idempotency_key;
602/// use mako_engine::ids::ProcessId;
603///
604/// let process_id = ProcessId::new();
605/// let key = outbox_idempotency_key(process_id, "DispatchAperak", "4012345000023", "FV2025-10-01");
606/// println!("idempotency key: {key}");
607/// ```
608///
609/// # Key derivation
610///
611/// The key is `UUID_v5(MAKO_ENGINE_OUTBOX_NS, "{process_id}|{step}|{partner}|{fv}")`.
612///
613/// `MAKO_ENGINE_OUTBOX_NS` is a fixed namespace UUID (RFC 4122 §4.3, SHA-1
614/// variant) that scopes all mako-engine outbox keys to avoid collisions with
615/// UUIDs from other namespaces.
616#[must_use]
617pub fn outbox_idempotency_key(
618 process_id: ProcessId,
619 step: &str,
620 recipient: &str,
621 format_version: &str,
622) -> uuid::Uuid {
623 // A fixed namespace UUID for mako-engine outbox keys.
624 // Generated once by uuid::Uuid::new_v4() and hardcoded for stability.
625 // Changing this constant invalidates all existing keys — treat as immutable.
626 const MAKO_ENGINE_OUTBOX_NS: uuid::Uuid = uuid::Uuid::from_bytes([
627 0xd4, 0x7a, 0x2c, 0x9e, 0x5b, 0x31, 0x47, 0xf2, 0x89, 0x0a, 0x1e, 0x6c, 0x8a, 0x3d, 0x5f,
628 0x04,
629 ]);
630 let name = format!("{process_id}|{step}|{recipient}|{format_version}");
631 uuid::Uuid::new_v5(&MAKO_ENGINE_OUTBOX_NS, name.as_bytes())
632}
633
634#[cfg(test)]
635mod tests {
636 use super::*;
637 use crate::ids::{ConversationId, CorrelationId, EventId, ProcessId, TenantId};
638
639 fn make_msg() -> OutboxMessage {
640 OutboxMessage::new(
641 StreamId::new("process/test"),
642 ProcessId::new(),
643 TenantId::new(),
644 CorrelationId::new(),
645 ConversationId::new(),
646 EventId::new(),
647 "APERAK",
648 "4012345000023",
649 serde_json::json!({"positive": true}),
650 )
651 }
652
653 #[tokio::test]
654 async fn enqueue_appears_in_pending() {
655 let store = InMemoryOutboxStore::new();
656 let msg = make_msg();
657 let id = msg.message_id;
658
659 store.enqueue(&[msg]).await.unwrap();
660
661 assert_eq!(store.len().await.unwrap(), 1);
662 let pending = store.pending_now(10).await.unwrap();
663 assert_eq!(pending.len(), 1);
664 assert_eq!(pending[0].message_id, id);
665 }
666
667 #[tokio::test]
668 async fn acknowledge_removes_message() {
669 let store = InMemoryOutboxStore::new();
670 let msg = make_msg();
671 let id = msg.message_id;
672
673 store.enqueue(&[msg]).await.unwrap();
674 store.acknowledge(id).await.unwrap();
675
676 assert!(store.is_empty().await.unwrap());
677 }
678
679 #[tokio::test]
680 async fn deferred_message_not_in_pending_yet() {
681 let store = InMemoryOutboxStore::new();
682 let future = OffsetDateTime::now_utc() + time::Duration::hours(1);
683 let msg = make_msg().with_deliver_after(future);
684
685 store.enqueue(&[msg]).await.unwrap();
686
687 let pending = store.pending_now(10).await.unwrap();
688 assert!(
689 pending.is_empty(),
690 "deferred message must not appear before its time"
691 );
692 }
693
694 #[tokio::test]
695 async fn deferred_message_appears_after_deadline() {
696 let store = InMemoryOutboxStore::new();
697 let past = OffsetDateTime::now_utc() - time::Duration::seconds(1);
698 let msg = make_msg().with_deliver_after(past);
699
700 store.enqueue(&[msg]).await.unwrap();
701
702 let pending = store.pending_now(10).await.unwrap();
703 assert_eq!(pending.len(), 1);
704 }
705
706 #[tokio::test]
707 async fn reschedule_increments_attempt_count() {
708 let store = InMemoryOutboxStore::new();
709 let msg = make_msg();
710 let id = msg.message_id;
711 let new_time = OffsetDateTime::now_utc() + time::Duration::minutes(5);
712
713 store.enqueue(&[msg]).await.unwrap();
714 store.reschedule(id, new_time).await.unwrap();
715
716 let inner = store.inner.read().await;
717 let stored = inner.get(&id).unwrap();
718 assert_eq!(stored.attempt_count, 1);
719 assert_eq!(stored.deliver_after, Some(new_time));
720 }
721
722 #[tokio::test]
723 async fn pending_ordered_oldest_first() {
724 let store = InMemoryOutboxStore::new();
725 store.enqueue(&[make_msg()]).await.unwrap();
726 store.enqueue(&[make_msg()]).await.unwrap();
727
728 let pending = store.pending_now(10).await.unwrap();
729 assert_eq!(pending.len(), 2);
730 assert!(pending[0].created_at <= pending[1].created_at);
731 }
732
733 #[test]
734 fn outbox_idempotency_key_is_stable_and_deterministic() {
735 let pid = ProcessId::new();
736 let step = "ReceiveAperak";
737 let partner = "4012345000023";
738 let fv = "FV2025-10-01";
739
740 let k1 = outbox_idempotency_key(pid, step, partner, fv);
741 let k2 = outbox_idempotency_key(pid, step, partner, fv);
742 assert_eq!(k1, k2, "same inputs must produce the same key");
743 assert_eq!(k1.to_string().len(), 36, "UUID string is 36 chars");
744
745 // Different step → different key.
746 let k3 = outbox_idempotency_key(pid, "ReceiveContrl", partner, fv);
747 assert_ne!(k1, k3, "different step must produce different key");
748
749 // Different FV → different key.
750 let k4 = outbox_idempotency_key(pid, step, partner, "FV2026-10-01");
751 assert_ne!(k1, k4, "different FV must produce different key");
752 }
753}