distributed 4.2.0

CQRS/ES framework for Rust using Plain Old Rust Structs — append-only events, replay, snapshots, outbox, service bus, and pluggable infrastructure
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Bus integration for [`Service`]: `with_bus` (a builder step) and `run`.
//!
//! Attaching a bus does not change the service's type. `with_bus` is a plain
//! builder step on [`Service`] that (1) installs an outbox publisher on the
//! repository, so `repo.outbox(msg).commit(agg)` publishes immediately, and
//! (2) captures the bus's consume behavior as a type-erased closure on the
//! service. `run` drives that closure. There is no separate runtime type.

use std::future::{poll_fn, Future};
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;

use super::service::DynBusPublisher;
use super::Service;
use crate::bus::{Bus, BusConsumer, RunOptions, TransportError};

/// Default lease for an immediate after-commit outbox publish. Short by design:
/// it only needs to cover commit → publish, so a crash before the publish
/// completes hands the row back to a separately operated polling worker
/// quickly.
pub const DEFAULT_PUBLISH_LEASE: Duration = Duration::from_secs(5);

/// Default publish-failure ceiling before an outbox row is permanently failed.
pub const DEFAULT_MAX_PUBLISH_ATTEMPTS: u32 = 5;

impl Service {
    /// Attach a bus — a builder step that returns the same [`Service`].
    ///
    /// Two effects, both composing with the rest of the builder:
    /// - installs an outbox publisher on the repository, so
    ///   `repo.outbox(msg).commit(agg)` claims the row in the commit transaction
    ///   and publishes it immediately after commit through this bus (a polling
    ///   worker may be operated as the crash/retry backstop);
    /// - captures how to consume, so [`run`](Self::run) listens for the
    ///   registered command names (competing) and subscribes to the event names
    ///   (fan-out).
    ///
    /// `with_bus` and [`run`](Self::run) do not start the drain loop. Spawn
    /// [`crate::OutboxDrainRunner`] (or `microsvc::spawn_outbox_publish_loop`)
    /// next to `run` when durable recovery after a commit-to-publish crash is
    /// required.
    pub fn with_bus<B>(mut self, bus: B) -> Self
    where
        B: Bus + BusConsumer + 'static,
    {
        let bus = Arc::new(bus);

        self.configure_outbox_publishers(
            DynBusPublisher::new(Arc::clone(&bus)),
            format!("microsvc-immediate:{}", std::process::id()),
            DEFAULT_PUBLISH_LEASE,
            DEFAULT_MAX_PUBLISH_ATTEMPTS,
        );

        self.set_runner(Box::new(
            move |service: Arc<Service>, options: RunOptions| {
                let bus = Arc::clone(&bus);
                Box::pin(async move { run_consumers(&*bus, service, options).await })
            },
        ));
        self
    }

    /// Run against the bus attached with [`with_bus`](Self::with_bus): consume
    /// the registered command names (competing `listen`) and event names
    /// (fan-out `subscribe`) concurrently on the caller's runtime. Returns when
    /// the consumers stop (a pull source that drains, or the first error).
    ///
    /// Producing is handled on the commit path — `repo.outbox(msg).commit(agg)`
    /// publishes immediately once a bus is attached.
    ///
    /// # Errors
    /// Returns a permanent [`TransportError`] if no bus was attached — call
    /// [`with_bus`](Self::with_bus) first.
    pub async fn run(mut self, options: RunOptions) -> Result<(), TransportError> {
        let Some(runner) = self.take_runner() else {
            return Err(TransportError::permanent(
                "Service::run requires a bus; call `with_bus` first",
            ));
        };
        self.bootstrap_projectors()
            .await
            .map_err(TransportError::from)?;
        runner(Arc::new(self), options).await
    }

    /// Build a drain runner over `store` that publishes through `publisher`.
    ///
    /// Worker id is `drain:<pid>` so claims never collide with the immediate
    /// hook's `microsvc-immediate:<pid>`. Spawn it next to [`run`](Self::run);
    /// this does not start a task.
    #[cfg(any(
        feature = "http",
        feature = "grpc",
        feature = "postgres",
        feature = "sqlite",
        feature = "nats",
        feature = "rabbitmq",
        feature = "kafka",
        test,
    ))]
    pub fn outbox_drain<S, P>(
        store: S,
        publisher: P,
        max_attempts: u32,
    ) -> crate::OutboxDrainRunner<S, P>
    where
        S: crate::OutboxStore,
        P: crate::bus::MessagePublisher,
    {
        crate::OutboxDrainRunner::for_store(store, publisher, max_attempts)
    }
}

/// A running transport consumer (a `listen` or `subscribe` loop), borrowing the
/// bus for `'b`.
type ConsumerFuture<'b> = Pin<Box<dyn Future<Output = Result<(), TransportError>> + Send + 'b>>;

/// Drive a service's command/event consumers concurrently on the caller's
/// runtime — no spawn, no timer. Returns on the first error; finishes when all
/// consumers stop.
async fn run_consumers<'b, B>(
    bus: &'b B,
    service: Arc<Service>,
    options: RunOptions,
) -> Result<(), TransportError>
where
    B: Bus + BusConsumer,
{
    let plan = service.subscription_plan();
    let mut consumers: Vec<ConsumerFuture<'b>> = Vec::new();
    if !plan.commands.is_empty() {
        consumers.push(Box::pin(bus.listen(Arc::clone(&service), options.clone())));
    }
    if !plan.events.is_empty() {
        consumers.push(Box::pin(bus.subscribe(Arc::clone(&service), options)));
    }

    poll_fn(move |cx| {
        let mut index = 0;
        while index < consumers.len() {
            match consumers[index].as_mut().poll(cx) {
                Poll::Ready(Ok(())) => {
                    // Drop the finished consumer future; nothing left to poll.
                    let _finished = consumers.remove(index);
                }
                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
                Poll::Pending => index += 1,
            }
        }
        if consumers.is_empty() {
            Poll::Ready(Ok(()))
        } else {
            Poll::Pending
        }
    })
    .await
}

#[cfg(test)]
mod tests {
    use serde_json::{json, Value};

    use crate::bus::{Bus, InMemoryBus, RunOptions};
    use crate::microsvc::{Context, HandlerError, Routes, Service, Session};
    use crate::outbox_worker::OutboxStore;
    use crate::{
        sourced, AggregateBuilder, AggregateRepository, Entity, InMemoryRepository, OutboxMessage,
        OutboxMessageStatus, Queueable, QueuedRepository, Snapshot, TransactionalCommit,
    };

    #[derive(Default)]
    struct Dummy {
        entity: Entity,
    }

    #[sourced(entity)]
    impl Dummy {
        #[event("touched")]
        fn touch(&mut self) {
            if self.entity.id().is_empty() {
                self.entity.set_id("dummy-1");
            }
        }
    }

    #[tokio::test]
    async fn run_without_a_bus_is_a_permanent_error_not_a_panic() {
        let err = Service::new()
            .run(RunOptions::idempotent())
            .await
            .unwrap_err();

        assert!(err.is_permanent());
        assert!(
            err.message().contains("with_bus"),
            "error should point at the missing builder step, got: {}",
            err.message()
        );
    }

    #[tokio::test]
    async fn with_bus_configures_outbox_for_all_eligible_route_bundles() {
        let repo_a = InMemoryRepository::new();
        let store_a = repo_a.outbox_store();
        let repo_b = InMemoryRepository::new();
        let store_b = repo_b.outbox_store();
        let service = Service::new()
            .routes(
                Routes::new()
                    .with_repo(repo_a.queued().aggregate::<Dummy>())
                    .command("dummy.touch.a")
                    .handle(touch_and_publish),
            )
            .routes(
                Routes::new()
                    .with_repo(repo_b.queued().aggregate::<Dummy>())
                    .command("dummy.touch.b")
                    .handle(touch_and_publish),
            )
            .with_bus(InMemoryBus::new());

        service
            .dispatch("dummy.touch.a", json!({}), Session::new())
            .await
            .unwrap();
        service
            .dispatch("dummy.touch.b", json!({}), Session::new())
            .await
            .unwrap();

        let published_a = store_a
            .messages_by_status(OutboxMessageStatus::Published, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            published_a.len(),
            1,
            "first route bundle should publish at commit time"
        );
        assert_eq!(published_a[0].id(), "evt-1");
        assert!(store_a.pending(usize::MAX).await.unwrap().is_empty());

        let published_b = store_b
            .messages_by_status(OutboxMessageStatus::Published, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            published_b.len(),
            1,
            "second route bundle should publish at commit time"
        );
        assert_eq!(published_b[0].id(), "evt-1");
        assert!(store_b.pending(usize::MAX).await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn with_bus_keeps_non_outbox_route_bundles_runnable() {
        let service = Service::new()
            .routes(
                Routes::new()
                    .with_dependencies(String::from("pong"))
                    .command("ping")
                    .handle(|ctx: &Context<String>| {
                        let reply = ctx.dependencies().clone();
                        async move { Ok(json!({ "reply": reply })) }
                    }),
            )
            .with_bus(InMemoryBus::new());

        let result = service
            .dispatch("ping", json!({}), Session::new())
            .await
            .unwrap();

        assert_eq!(result, json!({ "reply": "pong" }));
    }

    type TouchRepo = AggregateRepository<QueuedRepository<InMemoryRepository>, Dummy>;

    // A named fn (not a closure) so the higher-ranked `Handler` bound resolves.
    async fn touch_and_publish(ctx: &Context<'_, TouchRepo>) -> Result<Value, HandlerError> {
        let mut dummy = Dummy::default();
        dummy.touch()?;
        let message = OutboxMessage::create("evt-1", "dummy.touched", b"{}".to_vec())?;
        // The good old API — commit publishes immediately because a bus is attached.
        ctx.repo().outbox(message).commit(&mut dummy).await?;
        Ok(json!({ "ok": true }))
    }

    #[tokio::test]
    async fn dispatch_through_a_handler_publishes_immediately() {
        let repo = InMemoryRepository::new();
        let store = repo.outbox_store();
        let service = Service::new()
            .routes(
                Routes::new()
                    .with_repo(repo.queued().aggregate::<Dummy>())
                    .command("dummy.touch")
                    .handle(touch_and_publish),
            )
            .with_bus(InMemoryBus::new());

        // The handler runs `outbox().commit()`: claim-in-transaction, then
        // immediate publish through the attached bus.
        service
            .dispatch("dummy.touch", json!({}), Session::new())
            .await
            .unwrap();

        let published = store
            .messages_by_status(OutboxMessageStatus::Published, usize::MAX)
            .await
            .unwrap();
        assert_eq!(published.len(), 1, "row should be published immediately");
        assert_eq!(published[0].id(), "evt-1");
        assert!(store.pending(usize::MAX).await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn run_consumes_registered_commands_from_the_bus() {
        let bus = InMemoryBus::new();
        let repo = InMemoryRepository::new();
        let store = repo.outbox_store();
        let service = Service::new()
            .routes(
                Routes::new()
                    .with_repo(repo.queued().aggregate::<Dummy>())
                    .command("dummy.touch")
                    .handle(touch_and_publish),
            )
            .with_bus(bus.clone());

        // Enqueue a command on the bus, then run: `listen` is derived from the
        // registered command, drains the message, and the handler publishes.
        // `run` returns once the queue is empty (InMemoryBus yields `None`).
        bus.send("dummy.touch", b"{}".to_vec()).await.unwrap();
        service.run(RunOptions::idempotent()).await.unwrap();

        let published = store
            .messages_by_status(OutboxMessageStatus::Published, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            published.len(),
            1,
            "run() should consume the command and publish its outbox row"
        );
    }

    #[tokio::test]
    async fn outbox_drain_sugar_publishes_rows_the_hook_never_saw() {
        let repo = InMemoryRepository::new();
        let store = repo.outbox_store();
        let mut batch = crate::CommitBatch::empty();
        batch
            .outbox_messages
            .push(OutboxMessage::create("evt-left", "dummy.touched", b"{}".to_vec()).unwrap());
        repo.commit_batch(batch).await.unwrap();

        let handle = Service::outbox_drain(
            store,
            crate::BusPublisher::new(std::sync::Arc::new(InMemoryBus::new())),
            5,
        )
        .with_poll_interval(std::time::Duration::from_millis(5))
        .spawn();
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                if repo
                    .outbox_store()
                    .messages_by_status(OutboxMessageStatus::Published, 8)
                    .await
                    .unwrap()
                    .len()
                    == 1
                {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("Service::outbox_drain should publish leftover rows");
        handle.stop().await.unwrap();
    }

    #[derive(Default, Snapshot)]
    struct SnapCounter {
        entity: Entity,
        value: i64,
    }

    #[sourced(entity, aggregate_type = "snap_counter")]
    impl SnapCounter {
        #[event("touched")]
        fn touch(&mut self, id: String) {
            self.entity.set_id(&id);
            self.value += 1;
        }
    }

    // Snapshots are a transparent optimization: the repo type is unchanged.
    type SnapRepo = AggregateRepository<QueuedRepository<InMemoryRepository>, SnapCounter>;

    async fn touch_snap(ctx: &Context<'_, SnapRepo>) -> Result<Value, HandlerError> {
        let mut counter = SnapCounter::default();
        counter.touch("s1".to_string())?;
        let message = OutboxMessage::create("evt-s1", "snap.touched", b"{}".to_vec())?;
        ctx.repo().outbox(message).commit(&mut counter).await?;
        Ok(json!({}))
    }

    #[tokio::test]
    async fn outbox_commit_publishes_with_snapshot_backed_repo() {
        // `outbox().commit()` must work for a snapshot-backed repository too: the
        // outbox row and the snapshot commit together in one transaction, then
        // the row publishes immediately.
        let repo = InMemoryRepository::new();
        let store = repo.outbox_store();
        let service = Service::new()
            .routes(
                Routes::new()
                    .with_repo(repo.queued().aggregate::<SnapCounter>().with_snapshots(1))
                    .command("snap.touch")
                    .handle(touch_snap),
            )
            .with_bus(InMemoryBus::new());

        service
            .dispatch("snap.touch", json!({}), Session::new())
            .await
            .unwrap();

        let published = store
            .messages_by_status(OutboxMessageStatus::Published, usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            published.len(),
            1,
            "snapshot-backed outbox commit should publish immediately"
        );
        assert_eq!(published[0].id(), "evt-s1");
    }
}