Skip to main content

mako_engine/
builder.rs

1//! [`EngineModule`] trait, [`EngineBuilder`], and [`EngineContext`].
2//!
3// Allow using deprecated Noop stores as *type-level defaults* in EngineBuilder / EngineContext
4// generic parameters.  The types are deprecated to prevent instantiation in production code,
5// but using them as default type parameters in struct definitions (not instantiating them) is
6// the intended pattern for the type-state builder API.
7#![allow(deprecated)]
8//!
9//! # Summary
10//!
11//! `EngineBuilder` assembles all engine infrastructure into a single
12//! [`EngineContext`] value. Domain modules (GPKE, WiM, GeLi Gas, …) register
13//! themselves at startup via the [`EngineModule`] trait, making their names
14//! visible in diagnostics and health checks.
15//!
16//! # Type-state guarantee
17//!
18//! [`EngineBuilder::build`] is only available when the event store type
19//! parameter `ES` implements [`EventStore`]. Forgetting to call
20//! [`with_event_store`] is a **compile-time error**, not a runtime panic.
21//!
22//! All other stores default to their respective `Noop` implementations:
23//!
24//! | Store | Default |
25//! |-------|---------|
26//! | Snapshot store | [`NoopSnapshotStore`] |
27//! | Outbox store | [`NoopOutboxStore`] |
28//! | Deadline store | [`NoopDeadlineStore`] |
29//! | Process registry | [`NoopProcessRegistry`] |
30//!
31//! # Assembly example
32//!
33//! ```rust,ignore
34//! use mako_engine::builder::{EngineBuilder, EngineModule};
35//! use mako_engine::event_store::InMemoryEventStore;
36//! use mako_engine::outbox::InMemoryOutboxStore;
37//! use mako_engine::deadline::InMemoryDeadlineStore;
38//! use mako_engine::registry::InMemoryProcessRegistry;
39//! use mako_engine::snapshot::InMemorySnapshotStore;
40//!
41//! struct GpkeModule;
42//! impl EngineModule for GpkeModule { fn name(&self) -> &'static str { "gpke" } }
43//!
44//! let ctx = EngineBuilder::new()
45//!     .with_event_store(InMemoryEventStore::new())
46//!     .with_snapshot_store(InMemorySnapshotStore::new())
47//!     .with_outbox_store(InMemoryOutboxStore::new())
48//!     .with_deadline_store(InMemoryDeadlineStore::new())
49//!     .with_registry(InMemoryProcessRegistry::new())
50//!     .register(Box::new(GpkeModule))
51//!     .build();
52//!
53//! // Spawn a fresh process:
54//! let p = ctx.spawn::<SupplierChangeWorkflow>(tenant_id, workflow_id);
55//! p.execute(ReceiveUtilmd { .. }).await?;
56//!
57//! // Resume an existing process from a persisted identity:
58//! let identity = ctx.registry.lookup(&conv_id.to_string()).await?.unwrap();
59//! let p = ctx.resume::<SupplierChangeWorkflow>(identity);
60//!
61//! // Access stores for delivery workers / schedulers:
62//! let pending = ctx.outbox_store.pending_now(50).await?;
63//! let overdue = ctx.deadline_store.due_now(50).await?;
64//! ```
65//!
66//! [`with_event_store`]: EngineBuilder::with_event_store
67
68// Type-state generics can produce long signatures that trip up the
69// `type_complexity` lint; suppress it for this module only.
70#![allow(clippy::type_complexity)]
71
72// The Noop* types are marked #[deprecated] to guard against accidental
73// production use.  The builder is the only place they're instantiated as
74// defaults; suppress the lint here explicitly.
75#[allow(deprecated)]
76use crate::{
77    dead_letter::{DeadLetterSink, LogDeadLetterSink},
78    deadline::{Deadline, DeadlineStore, NoopDeadlineStore},
79    error::EngineError,
80    event_store::EventStore,
81    ids::{ProcessIdentity, TenantId},
82    marktrolle::DeploymentRoles,
83    outbox::{NoopOutboxStore, OutboxMessage, OutboxStore},
84    pid_router::PidRouter,
85    process::Process,
86    registry::{NoopProcessRegistry, ProcessRegistry},
87    snapshot::{NoopSnapshotStore, SnapshotStore},
88    version::WorkflowId,
89    workflow::Workflow,
90};
91
92use std::sync::Arc;
93
94// ── EngineModule ──────────────────────────────────────────────────────────────
95
96/// A self-contained domain module that registers with the engine at startup.
97///
98/// Domain crates implement this trait to declare their presence in the engine.
99/// The module name is surfaced in [`EngineContext::registered_modules`] for
100/// diagnostics, health checks, and log output.
101///
102/// ## Startup validation
103///
104/// Override [`configure`] to perform adapter coverage checks at engine startup
105/// time. The engine calls [`configure`] for every registered module during
106/// [`EngineBuilder::build`] and panics with an actionable message if any
107/// module returns `Err`. This surfaces missing adapter registrations as a
108/// startup failure rather than a silent runtime error.
109///
110/// ## Example
111///
112/// ```rust,ignore
113/// pub struct GpkeModule;
114///
115/// impl EngineModule for GpkeModule {
116///     fn name(&self) -> &'static str { "gpke" }
117///
118///     fn configure(&self) -> Result<(), String> {
119///         // Validate that every known BDEW format version has an adapter:
120///         GPKE_ADAPTER_REGISTRY
121///             .validate_policy(&GpkeWorkflow::version_policy(), &KNOWN_FVS)
122///             .map_err(|uncovered| format!(
123///                 "gpke: missing adapters for format versions: {:?}",
124///                 uncovered
125///             ))
126///     }
127/// }
128///
129/// let ctx = EngineBuilder::new()
130///     .with_event_store(my_store)
131///     .register(Box::new(GpkeModule))
132///     .build(); // panics if GpkeModule::configure returns Err
133///
134/// assert_eq!(ctx.registered_modules(), &["gpke"]);
135/// ```
136///
137/// [`configure`]: EngineModule::configure
138pub trait EngineModule: Send + 'static {
139    /// Stable, unique name for this domain module.
140    ///
141    /// Used in diagnostics, health checks, and structured log output.
142    /// Choose a short lowercase identifier (e.g. `"gpke"`, `"wim"`,
143    /// `"geli"`).
144    fn name(&self) -> &'static str;
145
146    /// Register all PIDs this module handles into the shared [`PidRouter`].
147    ///
148    /// # Mutability contract
149    ///
150    /// This method is called **exactly once** by [`EngineBuilder::build`],
151    /// before the resulting [`EngineContext`] is handed to the caller. The
152    /// `&mut PidRouter` reference is only available here, at build time.
153    /// After `build` returns the router is **sealed** — the engine provides
154    /// only a shared `&PidRouter` reference, with no mutation path at runtime.
155    ///
156    /// Consequence: **all PIDs a module will ever need must be registered
157    /// here**. Do not attempt to register PIDs lazily from async handlers or
158    /// after the engine has started — there is no API for that by design.
159    ///
160    /// Duplicate registrations (same PID from two modules) silently overwrite
161    /// the previous mapping; the last module to register wins. Use
162    /// `cargo xtask validate-pruefids` to catch accidental PID conflicts
163    /// between modules before they reach production.
164    ///
165    /// For role-conditional registration (PIDs that should only be active for
166    /// specific BDEW Marktrollen), override [`register_pids_with_roles`] instead.
167    ///
168    /// # Example
169    ///
170    /// ```rust,ignore
171    /// fn register_pids(&self, router: &mut PidRouter) {
172    ///     // GPKE Lieferantenwechsel / Lieferbeginn (BK6-22-024, PIDs 55001, 55002, 55017)
173    ///     for &pid in &[55001_u32, 55002, 55017] {
174    ///         router.register(pid, "gpke-supplier-change");
175    ///     }
176    /// }
177    /// ```
178    ///
179    /// [`register_pids_with_roles`]: EngineModule::register_pids_with_roles
180    fn register_pids(&self, _router: &mut PidRouter) {}
181
182    /// Register PIDs with role-context awareness.
183    ///
184    /// This is the **preferred override** for modules that have role-conditional
185    /// PID registrations — PIDs that should only be active when this `makod`
186    /// instance holds a specific [`Marktrolle`].
187    ///
188    /// The default implementation calls [`register_pids`] (role-agnostic) so
189    /// existing modules that override `register_pids` continue to work without
190    /// changes.
191    ///
192    /// Override this method instead of `register_pids` when any PID registration
193    /// should be conditional on the deployment role:
194    ///
195    /// ```rust,ignore
196    /// use mako_engine::marktrolle::Marktrolle;
197    ///
198    /// fn register_pids_with_roles(&self, router: &mut PidRouter, roles: &DeploymentRoles) {
199    ///     // Always register: 55001, 55002 (not role-specific)
200    ///     for pid in [55001_u32, 55002] { router.register_with_module(pid, "gpke-supplier-change", self.name()); }
201    ///
202    ///     // Only when NB role: 19001/19002 inbound ORDRSP from MSB
203    ///     if roles.contains(Marktrolle::Nb) {
204    ///         for pid in [19001_u32, 19002] { router.register_with_module(pid, "gpke-konfiguration", self.name()); }
205    ///     }
206    /// }
207    /// ```
208    ///
209    /// # Conflict guard
210    ///
211    /// Use [`PidRouter::register_with_module`] (not `register`) inside this
212    /// method. The conflict guard panics at build time if two modules register
213    /// the same PID to different workflows — this makes role misconfigurations
214    /// visible at startup rather than silently misrouting messages.
215    ///
216    /// [`Marktrolle`]: crate::marktrolle::Marktrolle
217    /// [`register_pids`]: EngineModule::register_pids
218    fn register_pids_with_roles(&self, router: &mut PidRouter, _roles: &DeploymentRoles) {
219        self.register_pids(router);
220    }
221
222    /// Workflow names this module handles for deadline dispatch.
223    ///
224    /// Return the same name strings that [`register_pids`] maps PIDs to.
225    /// These names are stored in [`EngineContext::registered_workflows`] and
226    /// used to validate that every workflow that has deadlines scheduled is
227    /// covered by the deadline scheduler dispatch function at runtime.
228    ///
229    /// The default implementation returns an empty slice. Override it to
230    /// declare all workflow names that may fire deadlines:
231    ///
232    /// ```rust,ignore
233    /// fn workflow_names(&self) -> &'static [&'static str] {
234    ///     &["gpke-supplier-change", "gpke-abrechnung"]
235    /// }
236    /// ```
237    ///
238    /// [`register_pids`]: EngineModule::register_pids
239    /// [`EngineContext::registered_workflows`]: crate::builder::EngineContext::registered_workflows
240    fn workflow_names(&self) -> &'static [&'static str] {
241        &[]
242    }
243
244    /// Declare the EDIFACT profile types this module requires at runtime.
245    ///
246    /// Returning a non-empty slice causes [`EngineBuilder::build`] to call the
247    /// registered profile validator for each requirement.  If no active profile
248    /// exists for a required message type, `build` panics with an actionable
249    /// error so deployment fails fast rather than silently.
250    ///
251    /// **This replaces the previous pattern** of calling
252    /// `edi_energy::registry::ReleaseRegistry::global()` inside `configure()`.
253    /// Domain crates no longer need `edi-energy` in their production
254    /// `[dependencies]` — they just declare their requirements here.
255    ///
256    /// ```rust,ignore
257    /// fn profile_requirements(&self) -> &'static [ProfileRequirement] {
258    ///     &[
259    ///         ProfileRequirement { message_type: "UTILMD", label: "UTILMD Strom (GPKE)" },
260    ///         ProfileRequirement { message_type: "INVOIC", label: "INVOIC Abrechnung (GPKE)" },
261    ///     ]
262    /// }
263    /// ```
264    ///
265    /// [`ProfileRequirement`]: crate::profile::ProfileRequirement
266    fn profile_requirements(&self) -> &'static [crate::profile::ProfileRequirement] {
267        &[]
268    }
269
270    /// Validate adapter coverage and configuration at engine startup.
271    ///
272    /// Called by [`EngineBuilder::build`] after all modules are registered.
273    /// Return `Ok(())` when the module is fully configured. Return `Err(msg)`
274    /// with an actionable description when an adapter or configuration is
275    /// missing — the engine will panic with that message so the deployment
276    /// fails early rather than silently.
277    ///
278    /// The default implementation is a no-op (always returns `Ok(())`).
279    /// Override it in domain crates to call
280    /// [`AdapterRegistry::validate_policy`] and emit structured errors.
281    ///
282    /// Note: if your validation needs access to the edi-energy profile
283    /// registry, use [`profile_requirements`] instead — it does not require
284    /// importing `edi-energy` in domain crates.
285    ///
286    /// [`AdapterRegistry::validate_policy`]: crate::message_adapter::AdapterRegistry::validate_policy
287    /// [`profile_requirements`]: EngineModule::profile_requirements
288    ///
289    /// # Errors
290    ///
291    /// Returns a descriptive error string when the module's configuration is invalid.
292    fn configure(&self) -> Result<(), String> {
293        Ok(())
294    }
295}
296
297// ── EngineContext ─────────────────────────────────────────────────────────────
298
299/// Assembled engine infrastructure returned by [`EngineBuilder::build`].
300///
301/// `EngineContext` bundles all stores and the process registry into a single
302/// value. It is the root dependency for:
303///
304/// - Spawning new processes ([`spawn`])
305/// - Resuming existing processes ([`resume`])
306/// - Running outbox delivery workers (`outbox_store.pending_now(…)`)
307/// - Driving the deadline scheduler (`deadline_store.due_now(…)`)
308///
309/// ## Generic parameters
310///
311/// | Param | Role | Default |
312/// |-------|------|---------|
313/// | `ES`  | [`EventStore`] backend | — (required) |
314/// | `SS`  | [`SnapshotStore`] backend | [`NoopSnapshotStore`] |
315/// | `OS`  | [`OutboxStore`] backend  | [`NoopOutboxStore`]   |
316/// | `DS`  | [`DeadlineStore`] backend | [`NoopDeadlineStore`] |
317/// | `PR`  | [`ProcessRegistry`] backend | [`NoopProcessRegistry`] |
318///
319/// In most codebases all type parameters are inferred from the builder calls.
320///
321/// [`spawn`]: EngineContext::spawn
322/// [`resume`]: EngineContext::resume
323pub struct EngineContext<
324    ES,
325    SS = NoopSnapshotStore,
326    OS = NoopOutboxStore,
327    DS = NoopDeadlineStore,
328    PR = NoopProcessRegistry,
329> {
330    event_store: Arc<ES>,
331    snapshot_store: SS,
332    outbox_store: OS,
333    deadline_store: DS,
334    registry: PR,
335    /// Dead-letter sink for unroutable or unprocessable inbound messages.
336    ///
337    /// Stored as `Arc<dyn DeadLetterSink>` so callers can share it across
338    /// tasks without an extra type parameter on `EngineContext`.
339    pub dead_letter_sink: Arc<dyn DeadLetterSink>,
340    /// PID-to-workflow routing table, populated from all registered modules.
341    pid_router: PidRouter,
342    registered_modules: Vec<&'static str>,
343    /// Workflow names declared by all registered modules via
344    /// [`EngineModule::workflow_names`]. Used to validate deadline scheduler
345    /// coverage at runtime (see [`EngineContext::registered_workflows`]).
346    registered_workflows: Vec<&'static str>,
347}
348
349// ── Type aliases ──────────────────────────────────────────────────────────────
350
351/// An [`EngineContext`] with all optional subsystems disabled.
352///
353/// Uses `NoopSnapshotStore` and, in `testing`-enabled builds, Noop
354/// implementations for outbox, deadline, and process registry. Suitable for
355/// tests and minimal deployments where only a durable event store is required.
356///
357/// All five type parameters are inferred from context when used with
358/// [`EngineBuilder`]:
359///
360/// ```rust,ignore
361/// // Only available in test / testing-feature builds:
362/// use mako_engine::builder::{EngineBuilder, MinimalEngine};
363/// use mako_engine::event_store::InMemoryEventStore;
364///
365/// let ctx: MinimalEngine<InMemoryEventStore> = EngineBuilder::new()
366///     .with_event_store(InMemoryEventStore::new())
367///     .build();
368/// ```
369pub type MinimalEngine<ES> = EngineContext<ES>;
370
371impl<ES, SS, OS, DS, PR> EngineContext<ES, SS, OS, DS, PR>
372where
373    ES: EventStore,
374{
375    /// Spawn a new process and return a typed `Process<W, Arc<ES>>` handle.
376    ///
377    /// No `ES: Clone` bound is required — the engine stores the event store
378    /// behind an `Arc` so spawning is always a cheap pointer clone.
379    ///
380    /// ```rust,ignore
381    /// let p = ctx.spawn::<SupplierChangeWorkflow>(tenant_id, workflow_id);
382    /// p.execute(ReceiveUtilmd { .. }).await?;
383    /// ```
384    #[must_use]
385    pub fn spawn<W: Workflow>(
386        &self,
387        tenant_id: TenantId,
388        workflow_id: WorkflowId,
389    ) -> Process<W, Arc<ES>> {
390        Process::new(Arc::clone(&self.event_store), tenant_id, workflow_id)
391    }
392
393    /// Resume an existing process from a [`ProcessIdentity`].
394    ///
395    /// ```rust,ignore
396    /// let identity = ctx.registry()
397    ///     .lookup(tenant_id, &conv_id.to_string())
398    ///     .await?
399    ///     .ok_or(EngineError::Registry("unknown conversation".into()))?;
400    /// let p = ctx.resume::<SupplierChangeWorkflow>(identity);
401    /// p.execute(HandleAperak { .. }).await?;
402    /// ```
403    #[must_use]
404    pub fn resume<W: Workflow>(&self, identity: ProcessIdentity) -> Process<W, Arc<ES>> {
405        Process::from_identity(Arc::clone(&self.event_store), identity)
406    }
407
408    /// Names of all domain modules registered with the builder, in
409    /// registration order.
410    #[must_use]
411    pub fn registered_modules(&self) -> &[&'static str] {
412        &self.registered_modules
413    }
414
415    /// Workflow names declared by all registered modules, in registration order.
416    ///
417    /// Use this in the deadline scheduler dispatch function to detect unknown
418    /// workflow names at startup. If a deadline fires for a workflow name that
419    /// is not in this list, the scheduler's dispatch function should emit an
420    /// error rather than silently dropping the deadline:
421    ///
422    /// ```rust,ignore
423    /// let known = ctx.registered_workflows().iter().copied().collect::<HashSet<_>>();
424    /// let scheduler = ctx.run_deadline_scheduler(
425    ///     move |deadline| {
426    ///         let wf = deadline.workflow_id().name.as_ref();
427    ///         if !known.contains(wf) {
428    ///             tracing::error!(workflow = %wf, "deadline fired for unregistered workflow");
429    ///             return Box::pin(async { Ok(()) });
430    ///         }
431    ///         // dispatch by workflow name …
432    ///         Box::pin(async { Ok(()) })
433    ///     },
434    ///     100,
435    ///     Duration::from_secs(30),
436    /// );
437    /// ```
438    #[must_use]
439    pub fn registered_workflows(&self) -> &[&'static str] {
440        &self.registered_workflows
441    }
442
443    /// The event store backend (behind an `Arc`).
444    #[must_use]
445    pub fn event_store(&self) -> &Arc<ES> {
446        &self.event_store
447    }
448
449    /// The snapshot store backend.
450    #[must_use]
451    pub fn snapshot_store(&self) -> &SS {
452        &self.snapshot_store
453    }
454
455    /// The outbox store backend.
456    ///
457    /// Poll `outbox_store().pending_now(limit)` in a background task to drain
458    /// the delivery queue.
459    #[must_use]
460    pub fn outbox_store(&self) -> &OS {
461        &self.outbox_store
462    }
463
464    /// The deadline store backend.
465    ///
466    /// Poll `deadline_store().due_now(limit)` in a background scheduler to
467    /// fire overdue process timers.
468    #[must_use]
469    pub fn deadline_store(&self) -> &DS {
470        &self.deadline_store
471    }
472
473    /// The process routing registry.
474    ///
475    /// Register a [`ProcessIdentity`] under a `(tenant_id, key)` pair at
476    /// process creation, then `lookup` it when routing inbound messages.
477    #[must_use]
478    pub fn registry(&self) -> &PR {
479        &self.registry
480    }
481
482    /// The dead-letter sink for unroutable or unprocessable messages.
483    ///
484    /// Call [`DeadLetterSink::reject`] when an inbound message cannot be
485    /// dispatched to any workflow. The default sink emits `tracing::warn!`
486    /// so rejections are always visible in the log output.
487    #[must_use]
488    pub fn dead_letter_sink(&self) -> &Arc<dyn DeadLetterSink> {
489        &self.dead_letter_sink
490    }
491
492    /// Assert that no Noop store is active — call this during production startup.
493    ///
494    /// Checks the type names of `OS`, `DS`, and `PR` against the string `"Noop"`.
495    /// Panics with a human-readable message if any match, directing the operator
496    /// to configure a persistent backend.
497    ///
498    /// # When to call
499    ///
500    /// Call this early in `makod`'s startup path (and `--check` mode) to catch
501    /// deployments where a Noop store was accidentally wired — e.g. the
502    /// `[outbox]`, `[deadline]`, or `[registry]` configuration section was
503    /// omitted from `makod.toml`.  The check is defence-in-depth: in release
504    /// builds without the `testing` feature, Noop stores cannot implement the
505    /// required traits at all and the compiler would have already rejected them.
506    ///
507    /// # Panics
508    ///
509    /// Panics when any of `OS`, `DS`, or `PR` is a Noop implementation.
510    pub fn assert_production_stores(&self) {
511        let checks: &[(&str, &str)] = &[
512            ("OutboxStore", std::any::type_name::<OS>()),
513            ("DeadlineStore", std::any::type_name::<DS>()),
514            ("ProcessRegistry", std::any::type_name::<PR>()),
515        ];
516        for (trait_name, type_name) in checks {
517            assert!(
518                !type_name.contains("Noop"),
519                "makod: Noop{trait_name} is active — \
520                 configure a persistent {trait_name} backend in makod.toml. \
521                 Type resolved to: {type_name}"
522            );
523        }
524    }
525
526    /// The PID-to-workflow routing table.
527    ///
528    /// Populated **once** during [`EngineBuilder::build`] by calling
529    /// [`EngineModule::register_pids`] on every registered module in
530    /// registration order. After `build` returns the table is **sealed** —
531    /// it is read-only for the lifetime of the `EngineContext` and may be
532    /// freely shared across async tasks without synchronisation.
533    ///
534    /// # Mutability contract
535    ///
536    /// There is intentionally no `pid_router_mut()` accessor. Adding PIDs
537    /// after the engine is built would create a TOCTOU race between the
538    /// dispatch path (which calls `route(pid)`) and any hypothetical
539    /// concurrent mutator. Instead, register all PIDs during the build phase
540    /// via `EngineModule::register_pids`.
541    ///
542    /// If a new process family needs to be added without restarting the
543    /// binary, rebuild and restart `makod` — hot-swap of PID routing is not
544    /// supported.
545    ///
546    /// # Example — dispatch at the AS4 reception boundary
547    ///
548    /// ```rust,ignore
549    /// let workflow_name = ctx.pid_router().route(pid)
550    ///     .ok_or_else(|| EngineError::Workflow(WorkflowError::InvalidCommand(
551    ///         format!("no workflow registered for PID {pid}").into()
552    ///     )))?;
553    ///
554    /// match workflow_name {
555    ///     "gpke-supplier-change" => dispatch::<GpkeSupplierChangeWorkflow>(&ctx, pid, payload).await,
556    ///     "wim-device-change"    => dispatch::<WimDeviceChangeWorkflow>(&ctx, pid, payload).await,
557    ///     other => Err(EngineError::Workflow(WorkflowError::InvalidCommand(
558    ///         format!("unhandled workflow name: {other}").into()
559    ///     ))),
560    /// }
561    /// ```
562    #[must_use]
563    pub fn pid_router(&self) -> &PidRouter {
564        &self.pid_router
565    }
566}
567
568// ── As4Sender ─────────────────────────────────────────────────────────────────
569
570/// Sends a single AS4 / EDIINT-over-HTTP outbound message.
571///
572/// Implement this trait for your AS4 gateway client and pass it to
573/// [`EngineContext::run_outbox_worker`].
574///
575/// # Contract
576///
577/// Return `Ok(())` only after the message has been **durably accepted** by the
578/// receiving MSH.  Return `Err(…)` on transient or permanent failure — the
579/// outbox worker calls [`OutboxStore::reschedule`] so the message is retried.
580pub trait As4Sender: Send + Sync + 'static {
581    /// Transmit `msg` and return when the remote MSH has accepted it.
582    fn send(
583        &self,
584        msg: &OutboxMessage,
585    ) -> impl std::future::Future<Output = Result<(), EngineError>> + Send;
586}
587
588// ── OutboxWorker ──────────────────────────────────────────────────────────────
589
590/// A background worker that drains the outbox by polling pending
591/// [`OutboxMessage`]s and dispatching them via an [`As4Sender`].
592///
593/// Obtain via [`EngineContext::run_outbox_worker`] and drive by spawning
594/// [`OutboxWorker::run`] in a Tokio task.
595///
596/// # Polling behaviour
597///
598/// When the poll returns an empty batch the worker sleeps for `poll_interval`
599/// before polling again.  Non-empty batches are processed immediately.
600///
601/// # Error handling
602///
603/// Successful sends are acknowledged via [`OutboxStore::acknowledge`].
604/// Failed sends are rescheduled via [`OutboxStore::reschedule`] using
605/// **full-jitter exponential backoff**: `delay = rand(0, min(MAX, BASE * 2^n))`
606/// where `n = attempt_count`. This avoids thundering-herd when multiple
607/// `makod` instances restart simultaneously after a receiver outage.
608///
609/// When `attempt_count >= max_attempts`, the message is **acknowledged** (removed
610/// from the outbox) and a [`DeadLetterReason::OutboxExhausted`] record is written
611/// to the dead-letter sink. This prevents permanently-undeliverable messages
612/// from clogging the outbox forever.
613///
614/// All errors are emitted as structured `tracing` events at `warn` / `error`
615/// level rather than `eprintln!`, so they appear in the application's log
616/// pipeline with full context (message_id, error).
617///
618/// # Example
619///
620/// ```rust,ignore
621/// use std::time::Duration;
622///
623/// let worker = ctx.run_outbox_worker(my_sender, 50, Duration::from_secs(1));
624/// tokio::spawn(async move { worker.run().await });
625/// ```
626///
627/// [`DeadLetterReason::OutboxExhausted`]: crate::dead_letter::DeadLetterReason::OutboxExhausted
628pub struct OutboxWorker<OS: OutboxStore, S: As4Sender> {
629    store: OS,
630    sender: S,
631    batch_size: usize,
632    poll_interval: std::time::Duration,
633    /// Maximum total delivery attempts before a message is dead-lettered.
634    ///
635    /// Default: 48 (covers ~4 hours at the 300 s backoff cap).
636    /// Set to `u32::MAX` to disable the cap (not recommended for production).
637    max_attempts: u32,
638    /// Sink for messages that exceed `max_attempts`.
639    dead_letter_sink: std::sync::Arc<dyn crate::dead_letter::DeadLetterSink>,
640    /// Optional liveness heartbeat — stores the current UTC Unix timestamp
641    /// (seconds) after each poll cycle so health probes can detect stale workers.
642    heartbeat: Option<std::sync::Arc<std::sync::atomic::AtomicI64>>,
643}
644
645/// Compute a full-jitter exponential backoff delay.
646///
647/// `attempt` is the number of prior attempts (0 = first retry).
648/// `entropy` provides randomness; derive from a stable message identifier
649/// (e.g. hash of `message_id`) rather than the current timestamp — a
650/// timestamp-derived value is deterministic within a single batch, which
651/// defeats jitter when multiple messages fail simultaneously.
652///
653/// | attempt | window (s) | expected delay (s) |
654/// |---------|------------|-------------------|
655/// | 0       | 5          | 2.5               |
656/// | 1       | 10         | 5                 |
657/// | 2       | 20         | 10                |
658/// | 3       | 40         | 20                |
659/// | 4       | 80         | 40                |
660/// | 5+      | 300 (cap)  | 150               |
661fn backoff_delay(attempt: u32, entropy: u64) -> std::time::Duration {
662    const BASE_SECS: u64 = 5;
663    const MAX_SECS: u64 = 300;
664    // Exponential window: BASE * 2^attempt, capped at MAX.
665    let window = BASE_SECS
666        .saturating_mul(1u64.wrapping_shl(attempt.min(5)))
667        .min(MAX_SECS);
668    // Full jitter: uniform random in [0, window).
669    let jitter_secs = if window == 0 { 0 } else { entropy % window };
670    std::time::Duration::from_secs(jitter_secs)
671}
672
673impl<OS: OutboxStore, S: As4Sender> OutboxWorker<OS, S> {
674    /// Run the outbox drain loop until the task is cancelled.
675    ///
676    /// # Panics
677    ///
678    /// Panics if `time::Duration::try_from(delay)` overflows (unreachable for
679    /// the delay values produced by `backoff_delay`).
680    #[allow(clippy::too_many_lines)]
681    pub async fn run(self) {
682        loop {
683            let batch = match self.store.pending_now(self.batch_size).await {
684                Ok(b) => b,
685                Err(e) => {
686                    tracing::warn!(error = %e, "outbox worker: store error polling pending messages (will retry)");
687                    tokio::time::sleep(self.poll_interval).await;
688                    continue;
689                }
690            };
691
692            if batch.is_empty() {
693                tokio::time::sleep(self.poll_interval).await;
694                continue;
695            }
696
697            for msg in batch {
698                // ── Max-attempt cap ───────────────────────────────────
699                // `attempt_count` starts at 0 and is incremented on each
700                // `reschedule` call.  When it reaches `max_attempts` the
701                // message is considered permanently undeliverable: acknowledge
702                // it (remove from outbox) and dead-letter it so the regulatory
703                // audit trail is preserved.
704                if msg.attempt_count >= self.max_attempts {
705                    tracing::error!(
706                        message_id   = %msg.message_id,
707                        message_type = %msg.message_type,
708                        recipient    = %msg.recipient,
709                        attempts     = msg.attempt_count,
710                        max_attempts = self.max_attempts,
711                        "outbox worker: max delivery attempts reached; dead-lettering message",
712                    );
713                    self.dead_letter_sink.reject(
714                        &crate::dead_letter::DeadLetterReason::OutboxExhausted {
715                            message_id: msg.message_id,
716                            message_type: msg.message_type.to_string(),
717                            recipient: msg.recipient.to_string(),
718                            last_error: format!(
719                                "delivery exhausted after {} attempts",
720                                msg.attempt_count
721                            ),
722                            attempts: msg.attempt_count,
723                        },
724                    );
725                    if let Err(e) = self.store.acknowledge(msg.message_id).await {
726                        tracing::error!(
727                            message_id = %msg.message_id,
728                            error = %e,
729                            "outbox worker: acknowledge after exhaust failed; message may reappear",
730                        );
731                    }
732                    continue;
733                }
734
735                match self.sender.send(&msg).await {
736                    Ok(()) => {
737                        if let Err(e) = self.store.acknowledge(msg.message_id).await {
738                            tracing::warn!(
739                                message_id = %msg.message_id,
740                                error = %e,
741                                "outbox worker: acknowledge failed",
742                            );
743                        }
744                        // CONTRL AHB 1.0 §1.2: the CONTRL must be delivered
745                        // within 6 wall-clock hours of interchange receipt.
746                        // `msg.created_at` is when the PendingOutbox was
747                        // materialised (which should equal the ingest timestamp
748                        // for transport-layer CONTRL obligations).
749                        if msg.message_type.as_ref() == "CONTRL" {
750                            let elapsed = time::OffsetDateTime::now_utc() - msg.created_at;
751                            if elapsed > time::Duration::hours(crate::fristen::CONTRL_FRIST_HOURS) {
752                                tracing::warn!(
753                                    message_id   = %msg.message_id,
754                                    elapsed_secs = elapsed.whole_seconds(),
755                                    max_secs     = crate::fristen::CONTRL_FRIST_HOURS * 3600,
756                                    "outbox worker: CONTRL delivered OUTSIDE the 6h Übertragungsfrist \
757                                     (CONTRL AHB 1.0 §1.2) — this is a BNetzA compliance violation"
758                                );
759                            }
760                        }
761                        // APERAK AHB 1.0 §2.4.1: Strom UTILMD/ORDERS APERAK must be
762                        // delivered within 45 minutes on weekdays, or by Sunday 12:00
763                        // if received on Saturday.  Log a compliance warning if the
764                        // delivery window was missed so operators can investigate.
765                        if msg.message_type.as_ref() == "APERAK" {
766                            let elapsed = time::OffsetDateTime::now_utc() - msg.created_at;
767                            if elapsed
768                                > time::Duration::minutes(
769                                    crate::fristen::APERAK_STROM_WEEKDAY_MINUTES,
770                                )
771                            {
772                                tracing::warn!(
773                                    message_id   = %msg.message_id,
774                                    elapsed_mins = elapsed.whole_minutes(),
775                                    "outbox worker: APERAK delivered after the 45-minute Strom \
776                                     sending window (APERAK AHB 1.0 §2.4.1) — \
777                                     check OutboxWorker and AS4 transport health"
778                                );
779                            }
780                        }
781                    }
782                    // Permanent error: dead-letter immediately without retrying.
783                    // PartnerUnknown requires operator intervention (add --as4-partner);
784                    // Serialization errors will never succeed on retry.
785                    Err(ref e)
786                        if e.is_partner_unknown() || matches!(e, EngineError::Serialization(_)) =>
787                    {
788                        tracing::error!(
789                            message_id   = %msg.message_id,
790                            message_type = %msg.message_type,
791                            recipient    = %msg.recipient,
792                            error        = %e,
793                            "outbox worker: permanent send failure; dead-lettering without retry",
794                        );
795                        self.dead_letter_sink.reject(
796                            &crate::dead_letter::DeadLetterReason::OutboxExhausted {
797                                message_id: msg.message_id,
798                                message_type: msg.message_type.to_string(),
799                                recipient: msg.recipient.to_string(),
800                                last_error: e.to_string(),
801                                attempts: msg.attempt_count,
802                            },
803                        );
804                        if let Err(re) = self.store.acknowledge(msg.message_id).await {
805                            tracing::error!(
806                                message_id = %msg.message_id,
807                                error = %re,
808                                "outbox worker: acknowledge after permanent failure failed",
809                            );
810                        }
811                    }
812                    Err(e) => {
813                        // Stable jitter entropy derived from the UUID bytes of
814                        // `message_id`.  Using the last 8 bytes as a `u64` gives
815                        // uniform entropy across message IDs (UUIDs are random in
816                        // all 128 bits for v4) and is stable across Rust versions —
817                        // unlike `DefaultHasher`, whose algorithm is explicitly
818                        // documented as unstable.
819                        let entropy = {
820                            let uuid = msg.message_id.as_uuid();
821                            let bytes = uuid.as_bytes();
822                            u64::from_le_bytes(bytes[8..16].try_into().unwrap())
823                        };
824                        let delay = backoff_delay(msg.attempt_count, entropy);
825                        let retry_at = time::OffsetDateTime::now_utc()
826                            + time::Duration::try_from(delay).unwrap_or(time::Duration::minutes(5));
827                        tracing::warn!(
828                            message_id   = %msg.message_id,
829                            attempt      = msg.attempt_count,
830                            max_attempts = self.max_attempts,
831                            retry_in     = ?delay,
832                            error        = %e,
833                            "outbox worker: send failed; rescheduling with backoff",
834                        );
835                        if let Err(re) = self.store.reschedule(msg.message_id, retry_at).await {
836                            tracing::error!(
837                                message_id = %msg.message_id,
838                                error      = %re,
839                                "outbox worker: reschedule failed; message may be stuck",
840                            );
841                        }
842                    }
843                }
844            }
845            // Tick liveness heartbeat at the end of every poll cycle so the
846            // health endpoint can detect a stale (hung) outbox worker.
847            if let Some(ref hb) = self.heartbeat {
848                hb.store(
849                    time::OffsetDateTime::now_utc().unix_timestamp(),
850                    std::sync::atomic::Ordering::Relaxed,
851                );
852            }
853        }
854    }
855}
856
857impl<ES, SS, OS, DS, PR> EngineContext<ES, SS, OS, DS, PR>
858where
859    ES: EventStore,
860    OS: OutboxStore + Clone,
861{
862    /// Construct an [`OutboxWorker`] that drains the outbox via `sender`.
863    ///
864    /// `batch_size` — messages fetched per poll cycle.
865    /// `poll_interval` — sleep duration when the batch is empty.
866    ///
867    /// `max_attempts` — maximum total delivery attempts before dead-lettering.
868    /// Pass `48` for a ~4-hour retry budget at the 300 s backoff cap, or
869    /// `u32::MAX` to disable the cap (not recommended for production).
870    ///
871    /// ```rust,ignore
872    /// use std::time::Duration;
873    ///
874    /// let worker = ctx.run_outbox_worker(my_sender, 50, Duration::from_secs(1), 48);
875    /// tokio::spawn(async move { worker.run().await });
876    /// ```
877    #[must_use]
878    pub fn run_outbox_worker<S: As4Sender>(
879        &self,
880        sender: S,
881        batch_size: usize,
882        poll_interval: std::time::Duration,
883        max_attempts: u32,
884    ) -> OutboxWorker<OS, S> {
885        OutboxWorker {
886            store: self.outbox_store.clone(),
887            sender,
888            batch_size,
889            poll_interval,
890            max_attempts,
891            dead_letter_sink: self.dead_letter_sink.clone(),
892            heartbeat: None,
893        }
894    }
895}
896
897impl<OS: OutboxStore, S: As4Sender> OutboxWorker<OS, S> {
898    /// Attach a liveness heartbeat to this worker.
899    ///
900    /// The worker will store the current UTC Unix timestamp (seconds) into
901    /// `heartbeat` at the end of every poll cycle.  Pass the same
902    /// `Arc<AtomicI64>` to the health endpoint so it can detect stale workers.
903    #[must_use]
904    pub fn with_heartbeat(
905        mut self,
906        heartbeat: std::sync::Arc<std::sync::atomic::AtomicI64>,
907    ) -> Self {
908        self.heartbeat = Some(heartbeat);
909        self
910    }
911}
912
913impl<ES, SS, OS, DS, PR> std::fmt::Debug for EngineContext<ES, SS, OS, DS, PR>
914where
915    ES: std::fmt::Debug,
916    SS: std::fmt::Debug,
917    OS: std::fmt::Debug,
918    DS: std::fmt::Debug,
919    PR: std::fmt::Debug,
920{
921    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
922        f.debug_struct("EngineContext")
923            .field("registered_modules", &self.registered_modules)
924            .field("registered_workflows", &self.registered_workflows)
925            .field("pid_router_len", &self.pid_router.len())
926            .finish_non_exhaustive()
927    }
928}
929
930// ── NoopAs4Sender / LogAs4Sender ──────────────────────────────────────────────
931
932/// An [`As4Sender`] that succeeds immediately without sending anything.
933///
934/// Use in tests and environments where outbound AS4 delivery is not yet
935/// wired. All outbox messages are acknowledged (removed from the queue)
936/// without being transmitted.
937///
938/// # ⚠️ Data loss warning
939///
940/// Every outbox message is **silently discarded** — no EDIFACT message is
941/// sent to any counterparty. Do not use in production.
942#[derive(Debug, Clone, Copy, Default)]
943#[must_use = "NoopAs4Sender discards all outbound messages silently — use a real AS4 gateway in production"]
944pub struct NoopAs4Sender;
945
946impl As4Sender for NoopAs4Sender {
947    async fn send(&self, _msg: &OutboxMessage) -> Result<(), EngineError> {
948        Ok(())
949    }
950}
951
952/// An [`As4Sender`] that logs every outbound message at `warn` level and
953/// succeeds without transmitting.
954///
955/// Useful for development and integration-testing environments where the
956/// full AS4 stack is not yet available but message visibility is desired.
957/// All outbox messages are acknowledged (removed from the queue) after logging.
958///
959/// # ⚠️ Data loss warning
960///
961/// No EDIFACT message is sent to any counterparty. Do not use in production.
962#[derive(Debug, Clone, Copy, Default)]
963#[must_use = "LogAs4Sender discards all outbound messages — use a real AS4 gateway in production"]
964pub struct LogAs4Sender;
965
966impl As4Sender for LogAs4Sender {
967    async fn send(&self, msg: &OutboxMessage) -> Result<(), EngineError> {
968        tracing::warn!(
969            message_id   = %msg.message_id,
970            message_type = %msg.message_type,
971            recipient    = %msg.recipient,
972            "LogAs4Sender: outbox message dropped — configure a real AS4 gateway for production",
973        );
974        Ok(())
975    }
976}
977
978// ── DeadlineScheduler ─────────────────────────────────────────────────────────
979
980/// A background task that polls [`DeadlineStore::due_now`] and dispatches
981/// deadline commands to the owning processes via a caller-supplied function.
982///
983/// Obtain via [`EngineContext::run_deadline_scheduler`] and drive by spawning
984/// [`DeadlineScheduler::run`] in a Tokio task.
985///
986/// # Dispatch function
987///
988/// The `dispatch` function receives a fired [`Deadline`] and returns a future
989/// that dispatches the appropriate timeout command to the process. The function
990/// is responsible for resuming the correct workflow and calling `execute`.
991/// After the future completes, the scheduler cancels the deadline from the
992/// store regardless of the dispatch outcome (to prevent re-firing).
993///
994/// ```rust,ignore
995/// use std::time::Duration;
996///
997/// let scheduler = ctx.run_deadline_scheduler(
998///     |deadline| async move {
999///         tracing::warn!(
1000///             deadline_id = %deadline.deadline_id(),
1001///             label = %deadline.label(),
1002///             "deadline fired",
1003///         );
1004///         Ok(())
1005///     },
1006///     100,
1007///     Duration::from_secs(30),
1008/// );
1009/// tokio::spawn(async move { scheduler.run().await });
1010/// ```
1011pub struct DeadlineScheduler<DS: DeadlineStore> {
1012    store: DS,
1013    dispatch: Box<
1014        dyn Fn(
1015                Deadline,
1016            ) -> std::pin::Pin<
1017                Box<dyn std::future::Future<Output = Result<(), EngineError>> + Send>,
1018            > + Send
1019            + Sync,
1020    >,
1021    batch_size: usize,
1022    poll_interval: std::time::Duration,
1023    /// Optional liveness heartbeat — stores the current UTC Unix timestamp
1024    /// (seconds) after each poll cycle.
1025    heartbeat: Option<std::sync::Arc<std::sync::atomic::AtomicI64>>,
1026}
1027
1028impl<DS: DeadlineStore> DeadlineScheduler<DS> {
1029    /// Run the deadline poll loop until the task is cancelled.
1030    pub async fn run(self) {
1031        loop {
1032            let result = match self.store.due_now(self.batch_size).await {
1033                Ok(r) => r,
1034                Err(e) => {
1035                    tracing::warn!(
1036                        error = %e,
1037                        "deadline scheduler: store error polling due deadlines (will retry)",
1038                    );
1039                    tokio::time::sleep(self.poll_interval).await;
1040                    continue;
1041                }
1042            };
1043
1044            if result.deadlines.is_empty() {
1045                tokio::time::sleep(self.poll_interval).await;
1046                continue;
1047            }
1048
1049            for deadline in result.deadlines {
1050                let id = deadline.deadline_id();
1051                let label = deadline.label().to_owned();
1052                let should_cancel = match (self.dispatch)(deadline).await {
1053                    Ok(()) => true,
1054                    Err(ref e) if e.is_version_conflict() => {
1055                        // The process was modified concurrently; the timeout
1056                        // command will be retried on the next poll cycle.
1057                        // Do NOT cancel — let the deadline remain due so it
1058                        // fires again until a non-conflict dispatch succeeds.
1059                        tracing::warn!(
1060                            deadline_id = %id,
1061                            label       = %label,
1062                            "deadline scheduler: VersionConflict; will retry on next poll",
1063                        );
1064                        false
1065                    }
1066                    Err(e) => {
1067                        tracing::warn!(
1068                            deadline_id = %id,
1069                            label       = %label,
1070                            error       = %e,
1071                            "deadline scheduler: dispatch failed (permanent); cancelling",
1072                        );
1073                        true
1074                    }
1075                };
1076                if should_cancel && let Err(e) = self.store.cancel(id).await {
1077                    tracing::error!(
1078                        deadline_id = %id,
1079                        error       = %e,
1080                        "deadline scheduler: cancel failed; deadline may fire again",
1081                    );
1082                }
1083            }
1084
1085            // If has_more, loop immediately to drain the batch.
1086
1087            // Tick liveness heartbeat at the end of every poll cycle so the
1088            // health endpoint can detect a stale (hung) deadline scheduler.
1089            if let Some(ref hb) = self.heartbeat {
1090                hb.store(
1091                    time::OffsetDateTime::now_utc().unix_timestamp(),
1092                    std::sync::atomic::Ordering::Relaxed,
1093                );
1094            }
1095        }
1096    }
1097}
1098
1099impl<DS: DeadlineStore> DeadlineScheduler<DS> {
1100    /// Attach a liveness heartbeat to this scheduler.
1101    ///
1102    /// The scheduler will store the current UTC Unix timestamp (seconds) into
1103    /// `heartbeat` at the end of every poll cycle.
1104    #[must_use]
1105    pub fn with_heartbeat(
1106        mut self,
1107        heartbeat: std::sync::Arc<std::sync::atomic::AtomicI64>,
1108    ) -> Self {
1109        self.heartbeat = Some(heartbeat);
1110        self
1111    }
1112}
1113
1114impl<ES, SS, OS, DS, PR> EngineContext<ES, SS, OS, DS, PR>
1115where
1116    ES: EventStore,
1117    DS: DeadlineStore + Clone,
1118{
1119    /// Construct a [`DeadlineScheduler`] that polls the deadline store and
1120    /// dispatches fired deadlines via `dispatch`.
1121    ///
1122    /// The `dispatch` function is called for every fired deadline. It should
1123    /// resume the owning process and execute the appropriate timeout command.
1124    ///
1125    /// `batch_size` — deadlines fetched per poll cycle.
1126    /// `poll_interval` — sleep duration when no deadlines are due.
1127    ///
1128    /// ```rust,ignore
1129    /// use std::time::Duration;
1130    ///
1131    /// let scheduler = ctx.run_deadline_scheduler(
1132    ///     |d| async move {
1133    ///         tracing::info!(label = %d.label(), "firing deadline");
1134    ///         Ok(())
1135    ///     },
1136    ///     100,
1137    ///     Duration::from_secs(30),
1138    /// );
1139    /// tokio::spawn(async move { scheduler.run().await });
1140    /// ```
1141    #[must_use]
1142    pub fn run_deadline_scheduler<F, Fut>(
1143        &self,
1144        dispatch: F,
1145        batch_size: usize,
1146        poll_interval: std::time::Duration,
1147    ) -> DeadlineScheduler<DS>
1148    where
1149        F: Fn(Deadline) -> Fut + Send + Sync + 'static,
1150        Fut: std::future::Future<Output = Result<(), EngineError>> + Send + 'static,
1151    {
1152        DeadlineScheduler {
1153            store: self.deadline_store.clone(),
1154            dispatch: Box::new(move |d| Box::pin(dispatch(d))),
1155            batch_size,
1156            poll_interval,
1157            heartbeat: None,
1158        }
1159    }
1160}
1161
1162// ── EngineBuilder ─────────────────────────────────────────────────────────────
1163
1164/// Assembles engine infrastructure and produces an [`EngineContext`].
1165///
1166/// Uses type-state to enforce that an event store is provided before
1167/// [`build`] can be called. All other stores default to `Noop`
1168/// implementations.
1169///
1170/// ## Quick start
1171///
1172/// ```rust,ignore
1173/// // Minimal — event store only, all others are Noop:
1174/// let ctx = EngineBuilder::new()
1175///     .with_event_store(InMemoryEventStore::new())
1176///     .build();
1177///
1178/// // Full infrastructure:
1179/// let ctx = EngineBuilder::new()
1180///     .with_event_store(InMemoryEventStore::new())
1181///     .with_snapshot_store(InMemorySnapshotStore::new())
1182///     .with_outbox_store(InMemoryOutboxStore::new())
1183///     .with_deadline_store(InMemoryDeadlineStore::new())
1184///     .with_registry(InMemoryProcessRegistry::new())
1185///     .register(Box::new(GpkeModule))
1186///     .build();
1187/// ```
1188///
1189/// [`build`]: EngineBuilder::build
1190pub struct EngineBuilder<
1191    ES = (),
1192    SS = NoopSnapshotStore,
1193    OS = NoopOutboxStore,
1194    DS = NoopDeadlineStore,
1195    PR = NoopProcessRegistry,
1196> {
1197    event_store: ES,
1198    snapshot_store: SS,
1199    outbox_store: OS,
1200    deadline_store: DS,
1201    registry: PR,
1202    dead_letter_sink: Arc<dyn DeadLetterSink>,
1203    modules: Vec<Box<dyn EngineModule>>,
1204    /// Active [`DeploymentRoles`] for this engine instance.
1205    ///
1206    /// Controls role-conditional PID registration via
1207    /// [`EngineModule::register_pids_with_roles`]. Defaults to
1208    /// [`DeploymentRoles::all()`] for backward compatibility.
1209    deployment_roles: DeploymentRoles,
1210    /// Optional profile validator injected by `makod` or callers that have
1211    /// access to `edi-energy`.  When `Some`, called for each
1212    /// [`ProfileRequirement`] declared by registered modules.  When `None`,
1213    /// profile requirements are not validated (safe in unit tests).
1214    ///
1215    /// Signature: `fn(message_type: &str) -> bool`
1216    ///
1217    /// [`ProfileRequirement`]: crate::profile::ProfileRequirement
1218    profile_validator: Option<Box<dyn Fn(&str) -> bool + Send + Sync>>,
1219}
1220#[cfg(any(test, feature = "testing"))]
1221impl Default
1222    for EngineBuilder<
1223        (),
1224        NoopSnapshotStore,
1225        NoopOutboxStore,
1226        NoopDeadlineStore,
1227        NoopProcessRegistry,
1228    >
1229{
1230    fn default() -> Self {
1231        Self {
1232            event_store: (),
1233            snapshot_store: NoopSnapshotStore,
1234            outbox_store: NoopOutboxStore,
1235            deadline_store: NoopDeadlineStore,
1236            registry: NoopProcessRegistry,
1237            dead_letter_sink: Arc::new(LogDeadLetterSink),
1238            modules: Vec::new(),
1239            deployment_roles: DeploymentRoles::all(),
1240            profile_validator: None,
1241        }
1242    }
1243}
1244
1245#[cfg(any(test, feature = "testing"))]
1246impl EngineBuilder {
1247    /// Create a new builder with all `Noop` defaults.
1248    ///
1249    /// Only available in `#[cfg(test)]` or with the `testing` feature enabled,
1250    /// because the Noop defaults silently discard outbox messages, deadlines,
1251    /// and process registry entries. Production binaries must wire real stores
1252    /// via the `with_*` builder methods.
1253    ///
1254    /// Call [`with_event_store`] before [`build`] — the event store is
1255    /// **required**.
1256    ///
1257    /// [`with_event_store`]: EngineBuilder::with_event_store
1258    /// [`build`]: EngineBuilder::build
1259    #[must_use]
1260    pub fn new() -> Self {
1261        Self::default()
1262    }
1263}
1264
1265impl<OS, DS, PR> EngineBuilder<(), NoopSnapshotStore, OS, DS, PR>
1266where
1267    OS: OutboxStore,
1268    DS: DeadlineStore,
1269    PR: ProcessRegistry,
1270{
1271    /// Create a production-ready builder with explicit stores for outbox,
1272    /// deadline, and process registry.
1273    ///
1274    /// This constructor is available in all build configurations including
1275    /// production binaries. It enforces that the three stores that can cause
1276    /// silent data loss (`OutboxStore`, `DeadlineStore`, `ProcessRegistry`)
1277    /// are provided explicitly — there is no Noop fallback.
1278    ///
1279    /// `NoopSnapshotStore` is used as the snapshot default because it is safe
1280    /// for production: skipping snapshots means full replay, but no data loss.
1281    /// Override with [`with_snapshot_store`] to enable snapshot-accelerated
1282    /// replay.
1283    ///
1284    /// Call [`with_event_store`] before [`build`] — the event store is
1285    /// **required**.
1286    ///
1287    /// ```rust,ignore
1288    /// let ctx = EngineBuilder::with_stores(outbox, deadline, registry)
1289    ///     .with_event_store(store.clone())
1290    ///     .with_snapshot_store(InMemorySnapshotStore::new())
1291    ///     .build();
1292    /// ```
1293    ///
1294    /// [`with_snapshot_store`]: EngineBuilder::with_snapshot_store
1295    /// [`with_event_store`]: EngineBuilder::with_event_store
1296    /// [`build`]: EngineBuilder::build
1297    #[must_use]
1298    pub fn with_stores(outbox_store: OS, deadline_store: DS, registry: PR) -> Self {
1299        Self {
1300            event_store: (),
1301            snapshot_store: NoopSnapshotStore,
1302            outbox_store,
1303            deadline_store,
1304            registry,
1305            dead_letter_sink: Arc::new(LogDeadLetterSink),
1306            modules: Vec::new(),
1307            deployment_roles: DeploymentRoles::all(),
1308            profile_validator: None,
1309        }
1310    }
1311}
1312
1313impl<ES, SS, OS, DS, PR> EngineBuilder<ES, SS, OS, DS, PR> {
1314    /// Set the event store. **Required** — `build()` is only available once
1315    /// this has been called with a type that implements [`EventStore`].
1316    ///
1317    /// Replaces any previously set event store (type-state transition).
1318    #[must_use]
1319    pub fn with_event_store<ES2: EventStore>(
1320        self,
1321        store: ES2,
1322    ) -> EngineBuilder<ES2, SS, OS, DS, PR> {
1323        EngineBuilder {
1324            event_store: store,
1325            snapshot_store: self.snapshot_store,
1326            outbox_store: self.outbox_store,
1327            deadline_store: self.deadline_store,
1328            registry: self.registry,
1329            dead_letter_sink: self.dead_letter_sink,
1330            modules: self.modules,
1331            deployment_roles: self.deployment_roles,
1332            profile_validator: self.profile_validator,
1333        }
1334    }
1335
1336    /// Set the snapshot store (default: [`NoopSnapshotStore`]).
1337    ///
1338    /// ## Default: `NoopSnapshotStore`
1339    ///
1340    /// Without calling this method the builder uses [`NoopSnapshotStore`],
1341    /// which silently discards all snapshot writes and returns `None` for
1342    /// every snapshot read.  The engine still functions correctly — every
1343    /// command handling call replays the full event log from the beginning
1344    /// instead of starting from a stored snapshot.  For low-volume processes
1345    /// this is fine; for long-lived processes with many events the replay cost
1346    /// can become significant.
1347    ///
1348    /// Enable snapshotting in production by providing a real [`SnapshotStore`]
1349    /// implementation (e.g. the SlateDB-backed store in `makod`).  In tests,
1350    /// `InMemorySnapshotStore` is available behind the `testing` feature flag.
1351    ///
1352    /// Note: [`Process::state_with_snapshot`][crate::process::Process::state_with_snapshot]
1353    /// is a compile-time no-op when the snapshot store is `NoopSnapshotStore`
1354    /// — it never calls the store and always returns `None`, so no snapshot is
1355    /// ever saved or loaded.
1356    #[must_use]
1357    pub fn with_snapshot_store<SS2: SnapshotStore>(
1358        self,
1359        store: SS2,
1360    ) -> EngineBuilder<ES, SS2, OS, DS, PR> {
1361        EngineBuilder {
1362            event_store: self.event_store,
1363            snapshot_store: store,
1364            outbox_store: self.outbox_store,
1365            deadline_store: self.deadline_store,
1366            registry: self.registry,
1367            dead_letter_sink: self.dead_letter_sink,
1368            modules: self.modules,
1369            deployment_roles: self.deployment_roles,
1370            profile_validator: self.profile_validator,
1371        }
1372    }
1373
1374    /// Set the outbox store (default: [`NoopOutboxStore`]).
1375    #[must_use]
1376    pub fn with_outbox_store<OS2: OutboxStore>(
1377        self,
1378        store: OS2,
1379    ) -> EngineBuilder<ES, SS, OS2, DS, PR> {
1380        EngineBuilder {
1381            event_store: self.event_store,
1382            snapshot_store: self.snapshot_store,
1383            outbox_store: store,
1384            deadline_store: self.deadline_store,
1385            registry: self.registry,
1386            dead_letter_sink: self.dead_letter_sink,
1387            modules: self.modules,
1388            deployment_roles: self.deployment_roles,
1389            profile_validator: self.profile_validator,
1390        }
1391    }
1392
1393    /// Set the deadline store (default: [`NoopDeadlineStore`]).
1394    #[must_use]
1395    pub fn with_deadline_store<DS2: DeadlineStore>(
1396        self,
1397        store: DS2,
1398    ) -> EngineBuilder<ES, SS, OS, DS2, PR> {
1399        EngineBuilder {
1400            event_store: self.event_store,
1401            snapshot_store: self.snapshot_store,
1402            outbox_store: self.outbox_store,
1403            deadline_store: store,
1404            registry: self.registry,
1405            dead_letter_sink: self.dead_letter_sink,
1406            modules: self.modules,
1407            deployment_roles: self.deployment_roles,
1408            profile_validator: self.profile_validator,
1409        }
1410    }
1411
1412    /// Set the process registry (default: [`NoopProcessRegistry`]).
1413    #[must_use]
1414    pub fn with_registry<PR2: ProcessRegistry>(
1415        self,
1416        registry: PR2,
1417    ) -> EngineBuilder<ES, SS, OS, DS, PR2> {
1418        EngineBuilder {
1419            event_store: self.event_store,
1420            snapshot_store: self.snapshot_store,
1421            outbox_store: self.outbox_store,
1422            deadline_store: self.deadline_store,
1423            registry,
1424            dead_letter_sink: self.dead_letter_sink,
1425            modules: self.modules,
1426            deployment_roles: self.deployment_roles,
1427            profile_validator: self.profile_validator,
1428        }
1429    }
1430
1431    /// Set the dead-letter sink (default: [`LogDeadLetterSink`]).
1432    ///
1433    /// The dead-letter sink receives every message that cannot be routed to a
1434    /// workflow. The default [`LogDeadLetterSink`] emits `tracing::warn!`
1435    /// events, making rejections visible in log output without configuration.
1436    ///
1437    /// Override with a persistent DLQ implementation in production:
1438    ///
1439    /// ```rust,ignore
1440    /// use mako_engine::dead_letter::LogDeadLetterSink;
1441    ///
1442    /// let ctx = EngineBuilder::new()
1443    ///     .with_event_store(my_store)
1444    ///     .with_dead_letter_sink(MyPersistentDlq::new())
1445    ///     .build();
1446    /// ```
1447    ///
1448    /// [`LogDeadLetterSink`]: crate::dead_letter::LogDeadLetterSink
1449    #[must_use]
1450    pub fn with_dead_letter_sink(mut self, sink: impl DeadLetterSink) -> Self {
1451        self.dead_letter_sink = Arc::new(sink);
1452        self
1453    }
1454
1455    /// Register an `edi-energy` profile validator for startup profile checks.
1456    ///
1457    /// The closure receives a message-type string (e.g. `"UTILMD"`) and must
1458    /// return `true` if at least one active profile for that message type is
1459    /// registered for today's date.
1460    ///
1461    /// Wire this in `makod` using the `edi-energy` global registry:
1462    ///
1463    /// ```rust,ignore
1464    /// use edi_energy::registry::ReleaseRegistry;
1465    ///
1466    /// let today = time::OffsetDateTime::now_utc().date();
1467    /// builder.with_profile_validator(move |msg_type| {
1468    ///     ReleaseRegistry::global()
1469    ///         .profiles_for_str(msg_type)
1470    ///         .any(|p| match (p.valid_from(), p.valid_until()) {
1471    ///             (Some(f), Some(u)) => f <= today && today <= u,
1472    ///             (Some(f), None)    => f <= today,
1473    ///             (None, _)          => true,
1474    ///         })
1475    /// })
1476    /// ```
1477    ///
1478    /// Domain crates do **not** need to call this — they only declare
1479    /// [`profile_requirements`].
1480    ///
1481    /// [`profile_requirements`]: EngineModule::profile_requirements
1482    #[must_use]
1483    pub fn with_profile_validator(
1484        mut self,
1485        validator: impl Fn(&str) -> bool + Send + Sync + 'static,
1486    ) -> Self {
1487        self.profile_validator = Some(Box::new(validator));
1488        self
1489    }
1490
1491    /// Register a domain module.
1492    ///
1493    /// The module name becomes visible in
1494    /// [`EngineContext::registered_modules`] after [`build`] is called.
1495    ///
1496    /// [`build`]: EngineBuilder::build
1497    #[must_use]
1498    pub fn register(mut self, module: Box<dyn EngineModule>) -> Self {
1499        self.modules.push(module);
1500        self
1501    }
1502
1503    /// Register multiple [`EngineModule`]s at once from a pre-built `Vec`.
1504    ///
1505    /// Equivalent to calling [`register`] in a loop. Useful when the set of
1506    /// modules is assembled conditionally (e.g. via `#[cfg]`-gated pushes to a
1507    /// `Vec<Box<dyn EngineModule>>`) before the builder chain starts.
1508    ///
1509    /// [`register`]: EngineBuilder::register
1510    #[must_use]
1511    pub fn register_many(mut self, modules: Vec<Box<dyn EngineModule>>) -> Self {
1512        self.modules.extend(modules);
1513        self
1514    }
1515
1516    /// Set the active [`DeploymentRoles`] for this engine instance.
1517    ///
1518    /// Controls role-conditional PID registration in [`EngineModule::register_pids_with_roles`].
1519    ///
1520    /// The default is [`DeploymentRoles::all()`], which registers every PID unconditionally
1521    /// — identical to the pre-role-aware behavior. Providing an explicit role set
1522    /// restricts role-conditional blocks to only the declared roles:
1523    ///
1524    /// - **NB-only** (`DeploymentRoles::nb()`): 19001/19002 route to `gpke-konfiguration`;
1525    ///   WiM nMSB blocks are skipped.
1526    /// - **nMSB-only** (`DeploymentRoles::nmsb()`): 19001/19002 route to `wim-geraeteubernahme`;
1527    ///   GPKE NB blocks are skipped.
1528    /// - **NB + gMSB** (`DeploymentRoles::nb_msb()`): most common Stadtwerke combination.
1529    ///
1530    /// # Conflict guard
1531    ///
1532    /// When two modules would register the same PID to **different** workflows, the
1533    /// engine panics during [`build`]. Set explicit roles to prevent both modules from
1534    /// activating the same PID simultaneously:
1535    ///
1536    /// ```rust,ignore
1537    /// use mako_engine::marktrolle::DeploymentRoles;
1538    ///
1539    /// let ctx = EngineBuilder::with_stores(outbox, deadline, registry)
1540    ///     .with_event_store(store)
1541    ///     .with_deployment_roles(DeploymentRoles::nb())  // only NB: GPKE gets 19001/19002
1542    ///     .register(Box::new(GpkeModule))
1543    ///     .register(Box::new(WimModule))  // nMSB block skipped — no conflict
1544    ///     .build();
1545    /// ```
1546    ///
1547    /// [`build`]: EngineBuilder::build
1548    #[must_use]
1549    pub fn with_deployment_roles(mut self, roles: DeploymentRoles) -> Self {
1550        self.deployment_roles = roles;
1551        self
1552    }
1553}
1554
1555impl<ES, SS, OS, DS, PR> EngineBuilder<ES, SS, OS, DS, PR>
1556where
1557    ES: EventStore,
1558    SS: SnapshotStore,
1559    OS: OutboxStore,
1560    DS: DeadlineStore,
1561    PR: ProcessRegistry,
1562{
1563    /// Build the [`EngineContext`].
1564    ///
1565    /// Consumes the builder. All registered modules and configured stores are
1566    /// moved into the returned [`EngineContext`].
1567    ///
1568    /// This method is only available when `ES` implements [`EventStore`].
1569    /// If you have not called [`with_event_store`], this will not compile.
1570    ///
1571    /// # Panics
1572    ///
1573    /// Panics when any registered module returns `Err` from
1574    /// [`EngineModule::configure`]. The panic message includes the module
1575    /// name and the error string so the deployment failure is actionable.
1576    ///
1577    /// [`with_event_store`]: EngineBuilder::with_event_store
1578    #[must_use]
1579    #[allow(clippy::too_many_lines)]
1580    pub fn build(self) -> EngineContext<ES, SS, OS, DS, PR> {
1581        // ── Noop store safety checks ──────────────────────────────────────────
1582        //
1583        // Noop stores lose data silently: NoopDeadlineStore drops every APERAK
1584        // deadline (BNetzA violation), NoopOutboxStore discards all outbound
1585        // messages, NoopProcessRegistry loses conversation routing on restart.
1586        //
1587        // In production builds (no `testing` feature, not running under
1588        // `#[test]`), the Noop constructors are cfg-gated out so this branch
1589        // is dead code and compiles away. In test/testing/tracing builds we
1590        // emit warnings so test harnesses see the configuration in log output.
1591        //
1592        // IMPORTANT: if you are reading this because a panic fired in production,
1593        // it means the `testing` feature was accidentally enabled in the binary.
1594        // Remove it from the production Cargo.toml feature list immediately.
1595        {
1596            let os_name = std::any::type_name::<OS>();
1597            let ds_name = std::any::type_name::<DS>();
1598            let pr_name = std::any::type_name::<PR>();
1599
1600            // Regulatory-critical stores: panic in any build context if these
1601            // are noop. OutboxStore and DeadlineStore must be durable in
1602            // production; ProcessRegistry must survive restarts.
1603            #[cfg(not(any(test, feature = "testing")))]
1604            {
1605                assert!(
1606                    !ds_name.contains("NoopDeadlineStore"),
1607                    "EngineBuilder::build: NoopDeadlineStore is active in a \
1608                     non-testing build. This silently discards all APERAK deadlines, \
1609                     which is an immediately reportable BNetzA violation \
1610                     (BK6-22-024 §5, BK7-24-01-009). \
1611                     Call .with_deadline_store(SlateDbStore::as_deadline_store()) \
1612                     in your production engine assembly. \
1613                     If this is a test, enable the 'testing' feature."
1614                );
1615                assert!(
1616                    !os_name.contains("NoopOutboxStore"),
1617                    "EngineBuilder::build: NoopOutboxStore is active in a \
1618                     non-testing build. This silently discards all outbound \
1619                     APERAK, CONTRL, and UTILMD messages. \
1620                     Call .with_outbox_store(SlateDbStore::as_outbox_store()) \
1621                     in your production engine assembly. \
1622                     If this is a test, enable the 'testing' feature."
1623                );
1624                assert!(
1625                    !pr_name.contains("NoopProcessRegistry"),
1626                    "EngineBuilder::build: NoopProcessRegistry is active in a \
1627                     non-testing build. This means conversation routing \
1628                     (PID → stream_id lookup) is lost on every restart, \
1629                     breaking all WiM, GeLi Gas, and GPKE in-flight processes. \
1630                     Call .with_registry(SlateDbStore::as_process_registry()) \
1631                     in your production engine assembly. \
1632                     If this is a test, enable the 'testing' feature."
1633                );
1634            }
1635
1636            // In test/testing/tracing builds: emit warnings instead of panicking.
1637            #[cfg(any(test, feature = "testing", feature = "tracing"))]
1638            {
1639                let ss_name = std::any::type_name::<SS>();
1640                if ss_name.contains("NoopSnapshotStore") {
1641                    tracing::warn!(
1642                        store = ss_name,
1643                        "EngineBuilder: NoopSnapshotStore is active — snapshots will not be \
1644                         persisted. Use SlateDbStore::as_snapshot_store() in production."
1645                    );
1646                }
1647                if os_name.contains("NoopOutboxStore") {
1648                    tracing::warn!(
1649                        store = os_name,
1650                        "EngineBuilder: NoopOutboxStore is active — outbound messages will be \
1651                         silently discarded. Use SlateDbStore::as_outbox_store() in production."
1652                    );
1653                }
1654                if ds_name.contains("NoopDeadlineStore") {
1655                    tracing::warn!(
1656                        store = ds_name,
1657                        "EngineBuilder: NoopDeadlineStore is active — scheduled deadlines will \
1658                         not fire after restart. Use SlateDbStore::as_deadline_store() in production."
1659                    );
1660                }
1661                if pr_name.contains("NoopProcessRegistry") {
1662                    tracing::warn!(
1663                        store = pr_name,
1664                        "EngineBuilder: NoopProcessRegistry is active — process routing will be \
1665                         lost on restart. Use SlateDbStore::as_process_registry() in production."
1666                    );
1667                }
1668            }
1669        }
1670        // Validate every module before assembling the context.
1671        // A missing adapter or misconfigured module fails at startup (not at
1672        // first inbound message), making deployment failures observable immediately.
1673        for module in &self.modules {
1674            if let Err(msg) = module.configure() {
1675                panic!(
1676                    "EngineBuilder::build: module '{}' failed configuration validation: {}",
1677                    module.name(),
1678                    msg
1679                );
1680            }
1681            // Validate profile requirements via the injected validator.
1682            // Domain crates declare requirements; only the binary crate (makod)
1683            // injects the edi-energy registry — domain crates need no edi-energy
1684            // import for this check.
1685            if let Some(ref validator) = self.profile_validator {
1686                for req in module.profile_requirements() {
1687                    assert!(
1688                        validator(req.message_type),
1689                        "EngineBuilder::build: module '{}' requires an active edi-energy \
1690                             profile for '{}' ({}) but none is registered for today's date. \
1691                             Run `cargo xtask codegen` to add the missing profile.",
1692                        module.name(),
1693                        req.message_type,
1694                        req.label,
1695                    );
1696                }
1697            }
1698        }
1699        // Build the PID router from all registered modules.
1700        // Also assert that no two modules claim the same PID — a PID overlap
1701        // is always a configuration error: one module's messages would be
1702        // silently swallowed by another's workflow, producing missing-process
1703        // errors or incorrect audit trails.
1704        let mut pid_router = PidRouter::new();
1705        let mut pid_owners: std::collections::HashMap<u32, &str> = std::collections::HashMap::new();
1706        // Keep each module's scratch router so we can build `pid_router` from
1707        // them in a second pass with the resolved ownership table.
1708        let mut module_scratches: Vec<PidRouter> = Vec::with_capacity(self.modules.len());
1709
1710        // Pass 1 — detect conflicts, determine PID ownership (first-wins for
1711        // explicit roles, last-wins for DeploymentRoles::all()).
1712        for module in &self.modules {
1713            // Temporarily build a scratch router to read this module's PIDs
1714            // for cross-module overlap detection (module-ownership level).
1715            let mut scratch = PidRouter::new();
1716            module.register_pids_with_roles(&mut scratch, &self.deployment_roles);
1717            for pid in scratch.registered_pids() {
1718                if let Some(prev) = pid_owners.insert(pid, module.name()) {
1719                    if self.deployment_roles.is_all() {
1720                        // With DeploymentRoles::all() (the default), role-conditional PIDs
1721                        // are registered by all modules that claim them, producing last-wins
1722                        // semantics. This is acceptable for single-role and dev/test deployments.
1723                        //
1724                        // In production multi-role deployments where both an NB and nMSB role
1725                        // are served by the same instance, set explicit roles via
1726                        // `EngineBuilder::with_deployment_roles` to prevent silent misrouting.
1727                        //
1728                        // We emit a debug-level log here (not warn) because the vast majority
1729                        // of deployments are single-role and this overlap is expected/harmless.
1730                        #[cfg(feature = "tracing")]
1731                        tracing::debug!(
1732                            pid,
1733                            previous_module = prev,
1734                            current_module = module.name(),
1735                            "PID registered by multiple modules with DeploymentRoles::all(); \
1736                             last module wins (use with_deployment_roles for strict routing)",
1737                        );
1738                        let _ = prev; // suppress unused-variable warning when tracing is off
1739                    } else {
1740                        // Explicit roles: the FIRST module to register a PID retains ownership.
1741                        // Restore the previous (first) owner and emit a warning so the operator
1742                        // can investigate.  A panic would be too strict: some shared PIDs
1743                        // (e.g. REMADV 33001/33002) are legitimately claimed by both GPKE and
1744                        // WiM billing; conversation-ID routing is the long-term solution, but
1745                        // first-wins gives correct behaviour for all current deployments.
1746                        pid_owners.insert(pid, prev); // restore first owner
1747                        #[cfg(feature = "tracing")]
1748                        tracing::warn!(
1749                            pid,
1750                            first_module = prev,
1751                            second_module = module.name(),
1752                            "PID {pid} claimed by both '{prev}' and '{}' with explicit \
1753                             DeploymentRoles; first module ('{prev}') retains ownership. \
1754                             Verify PID registration is correct for this deployment.",
1755                            module.name(),
1756                        );
1757                        #[cfg(not(feature = "tracing"))]
1758                        let _ = prev; // suppress unused-variable warning when tracing is off
1759                    }
1760                }
1761            }
1762            module_scratches.push(scratch);
1763        }
1764
1765        // Pass 2 — build the real `pid_router` from the scratch pads, respecting
1766        // the ownership table built in pass 1.
1767        for (module, scratch) in self.modules.iter().zip(module_scratches.iter()) {
1768            // Unambiguous (Sparte-agnostic) entries: only register if this module
1769            // owns the PID in the resolved ownership table.
1770            for pid in scratch.registered_pids() {
1771                if pid_owners.get(&pid).copied() == Some(module.name())
1772                    && let Some(wf) = scratch.route(pid)
1773                {
1774                    pid_router.register(pid, wf);
1775                }
1776            }
1777            // Commodity (Sparte-qualified) entries use distinct (pid, Sparte) keys
1778            // and never conflict across modules; register them all unconditionally.
1779            for (pid, sparte, wf) in scratch.registered_commodity_entries() {
1780                pid_router.register_with_sparte(pid, sparte, wf);
1781            }
1782        }
1783        let registered_modules = self.modules.iter().map(|m| m.name()).collect();
1784        let registered_workflows = self
1785            .modules
1786            .iter()
1787            .flat_map(|m| m.workflow_names().iter().copied())
1788            .collect();
1789        EngineContext {
1790            event_store: Arc::new(self.event_store),
1791            snapshot_store: self.snapshot_store,
1792            outbox_store: self.outbox_store,
1793            deadline_store: self.deadline_store,
1794            registry: self.registry,
1795            dead_letter_sink: self.dead_letter_sink,
1796            pid_router,
1797            registered_modules,
1798            registered_workflows,
1799        }
1800    }
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805    use super::*;
1806    use crate::{
1807        deadline::InMemoryDeadlineStore,
1808        error::WorkflowError,
1809        event_store::InMemoryEventStore,
1810        ids::TenantId,
1811        outbox::InMemoryOutboxStore,
1812        pid_router::PidRouter,
1813        registry::InMemoryProcessRegistry,
1814        snapshot::InMemorySnapshotStore,
1815        version::WorkflowId,
1816        workflow::{CommandPayload, EventPayload, Workflow},
1817    };
1818
1819    // ── Minimal workflow for spawn/resume tests ───────────────────────────────
1820
1821    #[derive(serde::Serialize, serde::Deserialize)]
1822    struct PingEvent;
1823
1824    impl EventPayload for PingEvent {
1825        fn event_type(&self) -> &'static str {
1826            "Ping"
1827        }
1828    }
1829
1830    struct PingCommand;
1831
1832    impl CommandPayload for PingCommand {}
1833
1834    #[derive(Default, Clone)]
1835    struct PingState;
1836
1837    struct PingWorkflow;
1838
1839    impl Workflow for PingWorkflow {
1840        type State = PingState;
1841        type Event = PingEvent;
1842        type Command = PingCommand;
1843
1844        fn apply(state: PingState, _: &PingEvent) -> PingState {
1845            state
1846        }
1847
1848        fn handle(
1849            _: &PingState,
1850            _: PingCommand,
1851        ) -> Result<crate::workflow::WorkflowOutput<PingEvent>, WorkflowError> {
1852            Ok(vec![PingEvent].into())
1853        }
1854    }
1855
1856    struct TestModule;
1857
1858    impl EngineModule for TestModule {
1859        fn name(&self) -> &'static str {
1860            "test-module"
1861        }
1862    }
1863
1864    // ── Tests ─────────────────────────────────────────────────────────────────
1865
1866    #[test]
1867    fn build_with_event_store_only() {
1868        let ctx = EngineBuilder::new()
1869            .with_event_store(InMemoryEventStore::new())
1870            .build();
1871        assert!(ctx.registered_modules().is_empty());
1872    }
1873
1874    #[test]
1875    fn build_with_all_stores_and_module() {
1876        let ctx = EngineBuilder::new()
1877            .with_event_store(InMemoryEventStore::new())
1878            .with_snapshot_store(InMemorySnapshotStore::new())
1879            .with_outbox_store(InMemoryOutboxStore::new())
1880            .with_deadline_store(InMemoryDeadlineStore::new())
1881            .with_registry(InMemoryProcessRegistry::new())
1882            .register(Box::new(TestModule))
1883            .build();
1884        assert_eq!(ctx.registered_modules(), &["test-module"]);
1885    }
1886
1887    #[test]
1888    fn multiple_modules_ordered() {
1889        struct ModA;
1890        impl EngineModule for ModA {
1891            fn name(&self) -> &'static str {
1892                "mod-a"
1893            }
1894        }
1895        struct ModB;
1896        impl EngineModule for ModB {
1897            fn name(&self) -> &'static str {
1898                "mod-b"
1899            }
1900        }
1901
1902        let ctx = EngineBuilder::new()
1903            .with_event_store(InMemoryEventStore::new())
1904            .register(Box::new(ModA))
1905            .register(Box::new(ModB))
1906            .build();
1907        assert_eq!(ctx.registered_modules(), &["mod-a", "mod-b"]);
1908    }
1909
1910    #[tokio::test]
1911    async fn spawn_creates_independent_processes() {
1912        let ctx = EngineBuilder::new()
1913            .with_event_store(InMemoryEventStore::new())
1914            .build();
1915        let wf_id = WorkflowId::new("ping", "FV2024-10-01");
1916
1917        let p1 = ctx.spawn::<PingWorkflow>(TenantId::new(), wf_id.clone());
1918        let p2 = ctx.spawn::<PingWorkflow>(TenantId::new(), wf_id);
1919
1920        assert_ne!(p1.process_id(), p2.process_id());
1921    }
1922
1923    #[tokio::test]
1924    async fn resume_sees_previously_appended_events() {
1925        let store = InMemoryEventStore::new();
1926        let ctx = EngineBuilder::new().with_event_store(store).build();
1927
1928        let p = ctx.spawn::<PingWorkflow>(TenantId::new(), WorkflowId::new("ping", "FV2024-10-01"));
1929        p.execute(PingCommand).await.unwrap();
1930
1931        let identity = p.identity();
1932        let resumed = ctx.resume::<PingWorkflow>(identity);
1933        assert_eq!(resumed.event_count().await.unwrap(), 1);
1934    }
1935
1936    #[tokio::test]
1937    async fn registry_routes_process_via_conversation_key() {
1938        use crate::registry::RegistryKey;
1939        let ctx = EngineBuilder::new()
1940            .with_event_store(InMemoryEventStore::new())
1941            .with_registry(InMemoryProcessRegistry::new())
1942            .build();
1943
1944        let p = ctx.spawn::<PingWorkflow>(TenantId::new(), WorkflowId::new("ping", "FV2024-10-01"));
1945        let tenant = p.tenant_id();
1946        let conv_key = RegistryKey::parse("conv:test-conversation-123").expect("valid key");
1947        ctx.registry()
1948            .register(tenant, &conv_key, p.identity())
1949            .await
1950            .unwrap();
1951
1952        let found = ctx
1953            .registry()
1954            .lookup(tenant, &conv_key)
1955            .await
1956            .unwrap()
1957            .expect("must be registered");
1958        let resumed = ctx.resume::<PingWorkflow>(found);
1959        assert_eq!(resumed.process_id(), p.process_id());
1960    }
1961
1962    #[test]
1963    fn pid_router_populated_by_module_register_pids() {
1964        struct PidModule;
1965        impl EngineModule for PidModule {
1966            fn name(&self) -> &'static str {
1967                "pid-module"
1968            }
1969            fn register_pids(&self, router: &mut PidRouter) {
1970                router.register(55001, "gpke-supplier-change");
1971                router.register(55002, "gpke-supplier-change");
1972            }
1973        }
1974
1975        let ctx = EngineBuilder::new()
1976            .with_event_store(InMemoryEventStore::new())
1977            .register(Box::new(PidModule))
1978            .build();
1979
1980        assert_eq!(ctx.pid_router().route(55001), Some("gpke-supplier-change"));
1981        assert_eq!(ctx.pid_router().route(55002), Some("gpke-supplier-change"));
1982        assert!(ctx.pid_router().route(99999).is_none());
1983        assert_eq!(ctx.pid_router().len(), 2);
1984    }
1985
1986    /// Verify that `register_pids_with_roles` gates PIDs behind role checks.
1987    ///
1988    /// Scenario: two modules share PID 19001.
1989    /// - ModuleA registers 19001 → "workflow-a" when role `Nb` is present.
1990    /// - ModuleB registers 19001 → "workflow-b" when role `Nmsb` is explicitly set
1991    ///   (not on `all()`).
1992    ///
1993    /// - `all()`: ModuleA fires (Nb ∈ all), ModuleB does NOT (is_all → skip).
1994    ///   → 19001 routes to "workflow-a".
1995    /// - `from_roles([Nb])`: ModuleA fires, ModuleB skips.
1996    ///   → 19001 routes to "workflow-a".
1997    /// - `from_roles([Nmsb])`: ModuleA skips, ModuleB fires.
1998    ///   → 19001 routes to "workflow-b".
1999    #[test]
2000    fn register_pids_with_roles_gates_pids_correctly() {
2001        use crate::marktrolle::{DeploymentRoles, Marktrolle};
2002
2003        struct ModuleA;
2004        impl EngineModule for ModuleA {
2005            fn name(&self) -> &'static str {
2006                "module-a"
2007            }
2008            fn register_pids_with_roles(&self, router: &mut PidRouter, roles: &DeploymentRoles) {
2009                if roles.contains(Marktrolle::Nb) {
2010                    router.register(19_001, "workflow-a");
2011                }
2012            }
2013        }
2014
2015        struct ModuleB;
2016        impl EngineModule for ModuleB {
2017            fn name(&self) -> &'static str {
2018                "module-b"
2019            }
2020            fn register_pids_with_roles(&self, router: &mut PidRouter, roles: &DeploymentRoles) {
2021                // Only fires on explicit Nmsb, not on all() (backward-compat sentinel).
2022                if !roles.is_all() && roles.contains(Marktrolle::Nmsb) {
2023                    router.register(19_001, "workflow-b");
2024                    router.register(19_015, "workflow-b");
2025                }
2026            }
2027        }
2028
2029        let build = |roles: DeploymentRoles| {
2030            EngineBuilder::new()
2031                .with_event_store(InMemoryEventStore::new())
2032                .with_deployment_roles(roles)
2033                .register(Box::new(ModuleA))
2034                .register(Box::new(ModuleB))
2035                .build()
2036        };
2037
2038        // all() → backward compat: ModuleA registers 19001 (Nb ∈ all), ModuleB skips.
2039        let ctx = build(DeploymentRoles::all());
2040        assert_eq!(ctx.pid_router().route(19_001), Some("workflow-a"));
2041        assert!(ctx.pid_router().route(19_015).is_none());
2042
2043        // Explicit Nb → same result: ModuleA registers, ModuleB (nMSB) skips.
2044        let ctx = build(DeploymentRoles::nb());
2045        assert_eq!(ctx.pid_router().route(19_001), Some("workflow-a"));
2046        assert!(ctx.pid_router().route(19_015).is_none());
2047
2048        // Explicit Nmsb → ModuleA skips (Nb ∉ roles), ModuleB registers.
2049        let ctx = build(DeploymentRoles::nmsb());
2050        assert_eq!(ctx.pid_router().route(19_001), Some("workflow-b"));
2051        assert_eq!(ctx.pid_router().route(19_015), Some("workflow-b"));
2052    }
2053
2054    /// Verify that explicit roles with two conflicting modules use first-wins semantics
2055    /// (the first module to register a PID retains ownership; the second is silently skipped).
2056    #[test]
2057    fn register_pids_with_roles_conflict_uses_first_wins_with_explicit_roles() {
2058        use crate::marktrolle::{DeploymentRoles, Marktrolle};
2059
2060        struct ConflictA;
2061        impl EngineModule for ConflictA {
2062            fn name(&self) -> &'static str {
2063                "conflict-a"
2064            }
2065            fn register_pids_with_roles(&self, router: &mut PidRouter, roles: &DeploymentRoles) {
2066                if roles.contains(Marktrolle::Nb) {
2067                    router.register(19_001, "workflow-a");
2068                }
2069            }
2070        }
2071
2072        struct ConflictB;
2073        impl EngineModule for ConflictB {
2074            fn name(&self) -> &'static str {
2075                "conflict-b"
2076            }
2077            fn register_pids_with_roles(&self, router: &mut PidRouter, roles: &DeploymentRoles) {
2078                if !roles.is_all() && roles.contains(Marktrolle::Nmsb) {
2079                    router.register(19_001, "workflow-b"); // same PID, different workflow
2080                }
2081            }
2082        }
2083
2084        // from_roles([Nb, Nmsb]): both modules fire for PID 19_001.
2085        // First-wins: ConflictA (registered first) retains ownership → "workflow-a".
2086        let ctx = EngineBuilder::new()
2087            .with_event_store(InMemoryEventStore::new())
2088            .with_deployment_roles(DeploymentRoles::from_roles([
2089                Marktrolle::Nb,
2090                Marktrolle::Nmsb,
2091            ]))
2092            .register(Box::new(ConflictA))
2093            .register(Box::new(ConflictB))
2094            .build();
2095        assert_eq!(
2096            ctx.pid_router().route(19_001),
2097            Some("workflow-a"),
2098            "first module should win on PID conflict with explicit roles"
2099        );
2100    }
2101}