cortexkit-bus-inmemory 0.3.2

Deterministic in-memory backend for the CortexKit NATS-shaped bus traits
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use async_trait::async_trait;
use cortexkit_bus_trait::{
    map_connection_failure, map_credential_sign_failure, terminally_dispose, BackendKind, BusError,
    ClaimOutcome, ConformanceBackend, ConnectionFailure, ContentDigest, CredentialSignFailure,
    DurableOwner, Headers, PropertyOutcome, PropertySpec, Register, RegisterUpdate, RegisterWatch,
    Stream, StreamCursor, WatchEvent, WorkQueue,
};

use crate::{BackendEvent, InMemoryBus, InMemoryConfig, WorkQueueConfig};

pub struct InMemoryConformance;

#[async_trait]
impl ConformanceBackend for InMemoryConformance {
    fn backend_kind(&self) -> BackendKind {
        BackendKind::InMemory
    }

    async fn probe(&self, property: PropertySpec) -> PropertyOutcome {
        let result = match property.name {
            "publish_ack_monotonic_sequence" => publish_ack_sequence().await,
            "consumer_replay_within_process_lifetime" => replay_from_cursor().await,
            "stream_delivery_count_rises_on_each_nak" => stream_delivery_count().await,
            "stream_term_is_never_redelivered" => stream_term().await,
            "stream_in_progress_extends_ack_wait" => stream_in_progress().await,
            "register_revision" => register_revision().await,
            "register_absent_vs_empty" => register_absent_vs_empty().await,
            "watch_snapshot_then_updates_with_connection_flag" => register_watch().await,
            "work_redelivery_count" => work_redelivery().await,
            "work_cap_exhaustion_and_dead_letter" => cap_exhaustion().await,
            "full_work_queue_names_exhausted_limit" => full_queue().await,
            "error_taxonomy_and_boundary_mapping" => error_taxonomy().await,
            other => Err(format!("in-memory has no parity probe named {other}")),
        };
        match result {
            Ok(()) => PropertyOutcome::Passed,
            Err(reason) => PropertyOutcome::Failed { reason },
        }
    }
}

async fn publish_ack_sequence() -> Result<(), String> {
    let bus = InMemoryBus::new(InMemoryConfig::default());
    let first = bus
        .publish("ck.box.room.a.post", "one", digest("one"), Headers::new())
        .await
        .map_err(debug)?;
    let second = bus
        .publish("ck.box.room.a.post", "two", digest("two"), Headers::new())
        .await
        .map_err(debug)?;
    require(
        !first.duplicate()
            && !second.duplicate()
            && second.stream_sequence() > first.stream_sequence(),
        "publish sequence did not increase",
    )
}

async fn replay_from_cursor() -> Result<(), String> {
    let bus =
        InMemoryBus::new(InMemoryConfig::default().with_durable(DurableOwner::Agent("agent")));
    let receipt = bus
        .publish(
            "ck.box.peer.agent.s.deliver",
            "m1",
            digest("m1"),
            Headers::new(),
        )
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let expected = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?
        .next()
        .await
        .map_err(debug)?
        .ok_or("first cursor saw no message")?;
    let mut reopened = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;
    let replayed = reopened
        .next()
        .await
        .map_err(debug)?
        .ok_or("reopened cursor saw no replay")?;
    require(
        expected.stream_seq == replayed.stream_seq,
        "cursor did not replay",
    )?;
    reopened.ack().await.map_err(debug)
}

const STREAM_SUBJECT: &str = "ck.box.peer.agent.s.deliver";

async fn stream_delivery_count() -> Result<(), String> {
    let bus =
        InMemoryBus::new(InMemoryConfig::default().with_durable(DurableOwner::Agent("agent")));
    let receipt = bus
        .publish(STREAM_SUBJECT, "m1", digest("m1"), Headers::new())
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let mut cursor = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;
    for expected in 1..=3 {
        let delivery = cursor
            .next()
            .await
            .map_err(debug)?
            .ok_or("a nak'd message was not redelivered")?;
        require(
            delivery.delivery_count == expected,
            &format!(
                "delivery {expected} reported count {}",
                delivery.delivery_count
            ),
        )?;
        if expected < 3 {
            cursor.nak(Duration::ZERO).await.map_err(debug)?;
        }
    }
    cursor.ack().await.map_err(debug)
}

async fn stream_term() -> Result<(), String> {
    let bus =
        InMemoryBus::new(InMemoryConfig::default().with_durable(DurableOwner::Agent("agent")));
    for id in ["m1", "m2"] {
        let receipt = bus
            .publish(STREAM_SUBJECT, id, digest(id), Headers::new())
            .await
            .map_err(debug)?;
        require(!receipt.duplicate(), "unexpected duplicate publish")?;
    }
    let mut cursor = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;
    let first = cursor
        .next()
        .await
        .map_err(debug)?
        .ok_or("first message was not delivered")?;
    require(first.message.id == "m1", "first delivery was not m1")?;
    cursor.term(Some("body_absent")).await.map_err(debug)?;
    let second = cursor
        .next()
        .await
        .map_err(debug)?
        .ok_or("the message after a term was not delivered")?;
    require(
        second.message.id == "m2" && second.delivery_count == 1,
        "a terminated message was redelivered",
    )?;
    cursor.ack().await.map_err(debug)?;
    let mut reopened = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;
    require(
        reopened.next().await.map_err(debug)?.is_none(),
        "a terminated message was redelivered to a reopened cursor",
    )?;
    require(
        bus.events().iter().any(|event| {
            matches!(
                event,
                BackendEvent::StreamTerminated { stream_seq, reason: Some(reason) }
                    if *stream_seq == first.stream_seq && reason == "body_absent"
            )
        }),
        "the termination and its reason were not recorded",
    )
}

async fn stream_in_progress() -> Result<(), String> {
    let ack_wait = Duration::from_millis(200);
    let clock = Arc::new(Mutex::new(Instant::now()));
    let mut bus = InMemoryBus::new(
        InMemoryConfig::default()
            .with_durable(DurableOwner::Agent("agent"))
            .with_stream_ack_wait(ack_wait),
    );
    // Only this bus's delivery clock advances, so scheduler delays cannot
    // carry the probe past the extended lease or affect other backends.
    bus.stream_clock = {
        let clock = Arc::clone(&clock);
        Arc::new(move || *clock.lock().expect("stream probe clock poisoned"))
    };
    for id in ["m1", "m2"] {
        let receipt = bus
            .publish(STREAM_SUBJECT, id, digest(id), Headers::new())
            .await
            .map_err(debug)?;
        require(!receipt.duplicate(), "unexpected duplicate publish")?;
    }
    let mut slow = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;
    let mut other = bus
        .consumer(DurableOwner::Agent("agent"))
        .await
        .map_err(debug)?;

    // Control: without a progress report the message comes back to another
    // cursor once the ack wait runs out.
    slow.next()
        .await
        .map_err(debug)?
        .ok_or("m1 was not delivered")?;
    *clock.lock().expect("stream probe clock poisoned") += ack_wait * 3 / 2;
    let redelivered = other
        .next()
        .await
        .map_err(debug)?
        .ok_or("m1 was not redelivered after the ack wait")?;
    require(
        redelivered.message.id == "m1" && redelivered.delivery_count == 2,
        "the ack-wait redelivery was not m1's second delivery",
    )?;
    other.ack().await.map_err(debug)?;
    let _ = slow.ack().await;

    // A progress report inside the window restarts the ack wait, so the
    // message is not redelivered past the original deadline.
    slow.next()
        .await
        .map_err(debug)?
        .ok_or("m2 was not delivered")?;
    *clock.lock().expect("stream probe clock poisoned") += ack_wait * 3 / 5;
    slow.in_progress().await.map_err(debug)?;
    *clock.lock().expect("stream probe clock poisoned") += ack_wait * 3 / 5;
    require(
        other.next().await.map_err(debug)?.is_none(),
        "a message reported in progress was redelivered past the original ack wait",
    )?;
    slow.ack().await.map_err(debug)?;
    require(
        other.next().await.map_err(debug)?.is_none(),
        "an acknowledged message was redelivered",
    )
}

async fn register_revision() -> Result<(), String> {
    let bus = InMemoryBus::new(InMemoryConfig::default());
    let first = bus.put("module", b"one".to_vec()).await.map_err(debug)?;
    let second = bus.put("module", b"two".to_vec()).await.map_err(debug)?;
    let read = bus.get("module").await.map_err(debug)?;
    require(second > first, "register revision did not increase")?;
    require(read.revision == second, "get returned the wrong revision")
}

async fn register_absent_vs_empty() -> Result<(), String> {
    let bus = InMemoryBus::new(InMemoryConfig::default());
    bus.put("empty", Vec::new()).await.map_err(debug)?;
    let empty = bus.get("empty").await.map_err(debug)?;
    require(empty.value.is_empty(), "empty value was not preserved")?;
    require(
        matches!(bus.get("missing").await, Err(BusError::Absent { .. })),
        "missing key was not Absent",
    )
}

async fn register_watch() -> Result<(), String> {
    let bus = InMemoryBus::new(InMemoryConfig::default());
    bus.put("module.a", b"v1".to_vec()).await.map_err(debug)?;
    let mut watch = bus.watch("module.").await.map_err(debug)?;
    require(
        !watch.has_snapshot(),
        "watch claimed a snapshot before delivery",
    )?;
    let snapshot = watch.next().await.map_err(debug)?;
    require(
        matches!(snapshot, WatchEvent::Snapshot { ref entries, .. } if entries.len() == 1),
        "watch did not deliver the complete initial snapshot",
    )?;
    require(
        watch.has_snapshot(),
        "watch did not record snapshot receipt",
    )?;
    bus.put("module.a", b"v2".to_vec()).await.map_err(debug)?;
    require(
        matches!(
            watch.next().await.map_err(debug)?,
            WatchEvent::Update(RegisterUpdate::Put(_))
        ),
        "watch did not distinguish an update",
    )
}

async fn work_redelivery() -> Result<(), String> {
    let bus = queue_bus(3, 4_096);
    let receipt = bus
        .publish(
            "ck.box.effect.a.s.intent",
            "m1",
            digest("m1"),
            Headers::new(),
        )
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let first = item(bus.claim().await.map_err(debug)?)?;
    bus.nak(first.token, Duration::ZERO).await.map_err(debug)?;
    let second = item(bus.claim().await.map_err(debug)?)?;
    require(
        first.delivery_count == 1,
        "first delivery count was not one",
    )?;
    require(second.delivery_count == 2, "redelivery count was not two")
}

async fn cap_exhaustion() -> Result<(), String> {
    let bus = queue_bus(1, 4_096);
    let receipt = bus
        .publish(
            "ck.box.effect.a.s.intent",
            "m1",
            digest("m1"),
            Headers::new(),
        )
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let first = item(bus.claim().await.map_err(debug)?)?;
    bus.nak(first.token, Duration::ZERO).await.map_err(debug)?;
    let exhausted = match bus.claim().await.map_err(debug)? {
        ClaimOutcome::MaxDeliveriesExceeded(exhausted) => exhausted,
        other => {
            return Err(format!(
                "cap did not report MaxDeliveriesExceeded: {other:?}"
            ))
        }
    };
    let dead_stream = InMemoryBus::new(InMemoryConfig::default());
    let queue = DeadLetterObservedQueue {
        queue: &bus,
        dead_stream: &dead_stream,
    };
    let receipt = terminally_dispose(
        &dead_stream,
        &queue,
        "box",
        &exhausted,
        digest("dead-record"),
    )
    .await
    .map_err(debug)?;
    require(!receipt.duplicate(), "dead letter was not stored")?;
    require(
        bus.events()
            .iter()
            .any(|event| matches!(event, BackendEvent::Terminated { .. })),
        "exhausted delivery was not terminated",
    )
}

/// Observes the separate dead-letter stream at termination time, so the probe
/// still detects a termination that incorrectly precedes the publish.
struct DeadLetterObservedQueue<'a> {
    queue: &'a InMemoryBus,
    dead_stream: &'a InMemoryBus,
}

#[async_trait]
impl WorkQueue for DeadLetterObservedQueue<'_> {
    async fn claim(&self) -> cortexkit_bus_trait::BusResult<ClaimOutcome> {
        self.queue.claim().await
    }

    async fn ack(
        &self,
        token: cortexkit_bus_trait::DeliveryToken,
    ) -> cortexkit_bus_trait::BusResult<()> {
        self.queue.ack(token).await
    }

    async fn nak(
        &self,
        token: cortexkit_bus_trait::DeliveryToken,
        delay: Duration,
    ) -> cortexkit_bus_trait::BusResult<()> {
        self.queue.nak(token, delay).await
    }

    async fn term(
        &self,
        token: cortexkit_bus_trait::DeliveryToken,
    ) -> cortexkit_bus_trait::BusResult<()> {
        if !self.dead_stream.events().iter().any(|event| {
            matches!(event, BackendEvent::Published { subject, .. } if subject == "ck.box.effect.dead")
        }) {
            return Err(BusError::denied("ck.box.effect.dead", "dead-letter publish did not precede term"));
        }
        self.queue.term(token).await
    }
}

async fn full_queue() -> Result<(), String> {
    let bus = queue_bus(5, 150);
    let receipt = bus
        .publish(
            "ck.box.effect.a.s.intent",
            "first",
            digest("first"),
            Headers::new(),
        )
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let error = bus
        .publish(
            "ck.box.effect.a.s.intent",
            "second",
            digest("second"),
            Headers::new(),
        )
        .await
        .expect_err("second publish should exceed max-bytes");
    require(
        matches!(error, BusError::Unavailable { exhausted_limit: Some(ref limit), .. } if limit == "max_bytes"),
        "full queue did not name max_bytes in Unavailable",
    )
}

async fn error_taxonomy() -> Result<(), String> {
    let denied_subject = "ck.box.room.denied.post";
    let bus = InMemoryBus::new(
        InMemoryConfig::default()
            .deny_subject(denied_subject)
            .with_work_queue(WorkQueueConfig {
                subject: "ck.box.effect.a.s.intent".into(),
                max_bytes: 4_096,
                max_deliveries: 5,
                max_nak_delay: Duration::from_millis(1),
            }),
    );
    require(
        matches!(bus.publish(denied_subject, "m", digest("m"), Headers::new()).await, Err(BusError::Denied { subject, .. }) if subject == denied_subject),
        "fixture denial was not Denied",
    )?;
    require(
        matches!(bus.get("missing").await, Err(BusError::Absent { .. })),
        "missing register key was not Absent",
    )?;
    let receipt = bus
        .publish(
            "ck.box.effect.a.s.intent",
            "work",
            digest("work"),
            Headers::new(),
        )
        .await
        .map_err(debug)?;
    require(!receipt.duplicate(), "unexpected duplicate publish")?;
    let claimed = item(bus.claim().await.map_err(debug)?)?;
    require(
        matches!(
            bus.nak(claimed.token, Duration::from_secs(1)).await,
            Err(BusError::Clamped {
                retry_after: Some(_),
                ..
            })
        ),
        "oversized delay was not reported Clamped",
    )?;
    require(
        matches!(
            map_connection_failure(ConnectionFailure::WriteOnSeveredSocket),
            BusError::Unavailable { .. }
        ),
        "severed write was not Unavailable",
    )?;
    require(
        matches!(
            map_connection_failure(ConnectionFailure::ServerClosedThenReauthenticationRefused {
                subject: denied_subject.into(),
                reason: "revoked".into()
            }),
            BusError::Denied { .. }
        ),
        "reconnect refusal was not Denied",
    )?;
    require(
        matches!(
            map_credential_sign_failure(CredentialSignFailure::RecordMissing {
                record: "nats.module.g1.e0".into()
            }),
            BusError::Absent { .. }
        ),
        "missing signing record was not Absent",
    )
}

fn queue_bus(max_deliveries: u32, max_bytes: usize) -> InMemoryBus {
    InMemoryBus::new(InMemoryConfig::default().with_work_queue(WorkQueueConfig {
        subject: "ck.box.effect.a.s.intent".into(),
        max_bytes,
        max_deliveries,
        max_nak_delay: Duration::from_secs(30),
    }))
}

fn item(outcome: ClaimOutcome) -> Result<cortexkit_bus_trait::WorkItem, String> {
    match outcome {
        ClaimOutcome::Item(item) => Ok(item),
        other => Err(format!("expected work item, got {other:?}")),
    }
}

fn digest(value: &str) -> ContentDigest {
    ContentDigest::of_bytes(value.as_bytes())
}

fn require(condition: bool, reason: &str) -> Result<(), String> {
    condition.then_some(()).ok_or_else(|| reason.into())
}

fn debug(error: impl std::fmt::Debug) -> String {
    format!("{error:?}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use cortexkit_bus_trait::{
        classify_properties, run_conformance, PropertyApplicability, PropertySet, SuiteBug,
        CONFORMANCE_PROPERTIES,
    };

    struct WeakenedNatsFixture;

    #[async_trait]
    impl ConformanceBackend for WeakenedNatsFixture {
        fn backend_kind(&self) -> BackendKind {
            BackendKind::Nats
        }

        async fn probe(&self, property: PropertySpec) -> PropertyOutcome {
            match property.set {
                PropertySet::Parity => InMemoryConformance.probe(property).await,
                PropertySet::NatsOnly => PropertyOutcome::Failed {
                    reason: "fixture deliberately has only process-local semantics".into(),
                },
            }
        }
    }

    #[tokio::test]
    async fn in_memory_passes_every_parity_property() {
        let report = run_conformance(&InMemoryConformance, PropertySet::Parity)
            .await
            .expect("parity is applicable to in-memory");

        assert_eq!(report.property_set_name, "parity");
        for (property, outcome) in &report.outcomes {
            assert_eq!(outcome, &PropertyOutcome::Passed, "{}", property.name);
        }
        assert!(report.passed());
    }

    #[tokio::test]
    async fn asserting_nats_only_against_in_memory_is_a_suite_bug() {
        let result = run_conformance(&InMemoryConformance, PropertySet::NatsOnly).await;
        assert_eq!(result, Err(SuiteBug::NatsOnlyAssertedAgainstInMemory));
    }

    #[tokio::test(start_paused = true)]
    async fn in_progress_probe_does_not_wait_for_wall_clock() {
        stream_in_progress().await.unwrap();
    }

    #[tokio::test]
    async fn weakened_backend_passes_real_parity_probes_but_fails_nats_only() {
        let parity = run_conformance(&WeakenedNatsFixture, PropertySet::Parity)
            .await
            .expect("parity run is valid");
        let nats_only = run_conformance(&WeakenedNatsFixture, PropertySet::NatsOnly)
            .await
            .expect("NATS-only run is valid for a NATS-labelled fixture");

        assert!(parity.passed());
        assert!(!nats_only.passed());
    }

    #[test]
    fn every_nats_only_property_is_not_applicable_not_passed() {
        let classifications = classify_properties(BackendKind::InMemory);
        let nats_only = classifications
            .iter()
            .filter(|row| row.property.set == PropertySet::NatsOnly)
            .collect::<Vec<_>>();

        assert_eq!(
            nats_only.len(),
            CONFORMANCE_PROPERTIES
                .iter()
                .filter(|property| property.set == PropertySet::NatsOnly)
                .count()
        );
        assert!(nats_only.iter().all(|row| matches!(
            row.applicability,
            PropertyApplicability::NotApplicable { .. }
        )));
    }
}