lazily 0.29.0

Lazy reactive signals with dependency tracking and cache invalidation
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
//! Generic causal receipt projection.
//!
//! Receipts record the outcome of a command or effect request keyed by a stable
//! causation id. This is deliberately not a transport ACK plane: `Observed` and
//! `Accepted` are non-terminal progress observations, while `Applied` and
//! `Rejected` are terminal outcomes.

use std::collections::{BTreeMap, BTreeSet};

/// Generic receipt outcomes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ReceiptOutcome {
    /// A peer/process observed the causation request.
    Observed,
    /// A peer/process accepted or queued the request.
    Accepted,
    /// The requested effect/state change was applied.
    Applied,
    /// The requested effect/state change was rejected.
    Rejected,
}

impl ReceiptOutcome {
    /// Whether this outcome completes the causation.
    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Applied | Self::Rejected)
    }
}

/// One receipt event for a command/effect causation id.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CausalReceipt {
    /// Idempotency key for this receipt event.
    pub receipt_id: String,
    /// Stable id of the command/effect request this receipt observes.
    pub causation_id: String,
    /// Peer, process, or subsystem that produced the receipt.
    pub observer: String,
    /// Producer/editor generation.
    pub generation: u64,
    /// Receipt outcome.
    pub outcome: ReceiptOutcome,
    /// Optional human/debug rejection reason.
    pub reason: Option<String>,
    /// Optional hash of the state/payload observed by the receipt.
    pub payload_hash: Option<String>,
}

impl CausalReceipt {
    /// Construct a receipt.
    #[must_use]
    pub fn new(
        receipt_id: impl Into<String>,
        causation_id: impl Into<String>,
        observer: impl Into<String>,
        generation: u64,
        outcome: ReceiptOutcome,
    ) -> Self {
        Self {
            receipt_id: receipt_id.into(),
            causation_id: causation_id.into(),
            observer: observer.into(),
            generation,
            outcome,
            reason: None,
            payload_hash: None,
        }
    }

    /// Construct an `observed` receipt.
    #[must_use]
    pub fn observed(
        receipt_id: impl Into<String>,
        causation_id: impl Into<String>,
        observer: impl Into<String>,
        generation: u64,
    ) -> Self {
        Self::new(
            receipt_id,
            causation_id,
            observer,
            generation,
            ReceiptOutcome::Observed,
        )
    }

    /// Construct an `accepted` receipt.
    #[must_use]
    pub fn accepted(
        receipt_id: impl Into<String>,
        causation_id: impl Into<String>,
        observer: impl Into<String>,
        generation: u64,
    ) -> Self {
        Self::new(
            receipt_id,
            causation_id,
            observer,
            generation,
            ReceiptOutcome::Accepted,
        )
    }

    /// Construct an `applied` receipt.
    #[must_use]
    pub fn applied(
        receipt_id: impl Into<String>,
        causation_id: impl Into<String>,
        observer: impl Into<String>,
        generation: u64,
    ) -> Self {
        Self::new(
            receipt_id,
            causation_id,
            observer,
            generation,
            ReceiptOutcome::Applied,
        )
    }

    /// Construct a `rejected` receipt.
    #[must_use]
    pub fn rejected(
        receipt_id: impl Into<String>,
        causation_id: impl Into<String>,
        observer: impl Into<String>,
        generation: u64,
    ) -> Self {
        Self::new(
            receipt_id,
            causation_id,
            observer,
            generation,
            ReceiptOutcome::Rejected,
        )
    }

    /// Attach a debug reason.
    #[must_use]
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Attach a payload hash.
    #[must_use]
    pub fn with_payload_hash(mut self, payload_hash: impl Into<String>) -> Self {
        self.payload_hash = Some(payload_hash.into());
        self
    }
}

/// Wire body for the externally-tagged `CausalReceipts` envelope.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CausalReceipts {
    /// Receipt batch.
    pub receipts: Vec<CausalReceipt>,
}

impl CausalReceipts {
    /// Construct a receipt batch.
    #[must_use]
    pub fn new(receipts: impl IntoIterator<Item = CausalReceipt>) -> Self {
        Self {
            receipts: receipts.into_iter().collect(),
        }
    }
}

/// Externally-tagged receipt wire message.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ReceiptMessage {
    /// Receipt batch envelope.
    CausalReceipts(CausalReceipts),
}

/// Result of applying a receipt to a projection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReceiptApplyStatus {
    /// Receipt was recorded.
    Recorded,
    /// Receipt id was already seen.
    Duplicate,
    /// Receipt generation does not match the current authority generation.
    StaleGeneration {
        /// Expected current generation.
        expected: u64,
        /// Generation carried by the receipt.
        actual: u64,
    },
    /// A different terminal outcome already exists for this causation id.
    TerminalConflict {
        /// Causation id with conflicting terminal receipts.
        causation_id: String,
        /// Existing terminal outcome.
        existing: ReceiptOutcome,
        /// Incoming conflicting terminal outcome.
        incoming: ReceiptOutcome,
    },
}

/// Folded receipt projection.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReceiptProjection {
    receipts_by_id: BTreeMap<String, CausalReceipt>,
    latest_by_causation: BTreeMap<String, CausalReceipt>,
    terminal_by_causation: BTreeMap<String, CausalReceipt>,
    stale_receipt_ids: BTreeSet<String>,
}

impl ReceiptProjection {
    /// Create an empty projection.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Apply one receipt.
    ///
    /// When `current_generation` is `Some`, receipts for any other generation are
    /// retained only as stale ids and do not update the current projection.
    pub fn observe(
        &mut self,
        current_generation: Option<u64>,
        receipt: CausalReceipt,
    ) -> ReceiptApplyStatus {
        if self.receipts_by_id.contains_key(&receipt.receipt_id)
            || self.stale_receipt_ids.contains(&receipt.receipt_id)
        {
            return ReceiptApplyStatus::Duplicate;
        }

        if let Some(expected) = current_generation
            && receipt.generation != expected
        {
            let actual = receipt.generation;
            self.stale_receipt_ids.insert(receipt.receipt_id);
            return ReceiptApplyStatus::StaleGeneration { expected, actual };
        }

        if receipt.outcome.is_terminal()
            && let Some(existing) = self.terminal_by_causation.get(&receipt.causation_id)
            && existing.outcome != receipt.outcome
        {
            return ReceiptApplyStatus::TerminalConflict {
                causation_id: receipt.causation_id,
                existing: existing.outcome,
                incoming: receipt.outcome,
            };
        }

        if receipt.outcome.is_terminal() {
            self.terminal_by_causation
                .entry(receipt.causation_id.clone())
                .or_insert_with(|| receipt.clone());
        }
        self.latest_by_causation
            .insert(receipt.causation_id.clone(), receipt.clone());
        self.receipts_by_id
            .insert(receipt.receipt_id.clone(), receipt);
        ReceiptApplyStatus::Recorded
    }

    /// Latest recorded receipt for a causation id, terminal or non-terminal.
    #[must_use]
    pub fn latest_for(&self, causation_id: &str) -> Option<&CausalReceipt> {
        self.latest_by_causation.get(causation_id)
    }

    /// Terminal receipt for a causation id.
    #[must_use]
    pub fn terminal_for(&self, causation_id: &str) -> Option<&CausalReceipt> {
        self.terminal_by_causation.get(causation_id)
    }

    /// Whether a receipt id has already been seen.
    #[must_use]
    pub fn contains_receipt(&self, receipt_id: &str) -> bool {
        self.receipts_by_id.contains_key(receipt_id) || self.stale_receipt_ids.contains(receipt_id)
    }

    /// Stale receipt ids observed by the projection.
    pub fn stale_receipt_ids(&self) -> impl Iterator<Item = &String> {
        self.stale_receipt_ids.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn receipt_outcome_terminality_is_explicit() {
        assert!(!ReceiptOutcome::Observed.is_terminal());
        assert!(!ReceiptOutcome::Accepted.is_terminal());
        assert!(ReceiptOutcome::Applied.is_terminal());
        assert!(ReceiptOutcome::Rejected.is_terminal());
    }

    #[test]
    fn projection_records_nonterminal_and_terminal_receipts() {
        let mut projection = ReceiptProjection::new();
        assert_eq!(
            projection.observe(
                Some(7),
                CausalReceipt::observed("receipt-observed", "patch-123", "editor", 7),
            ),
            ReceiptApplyStatus::Recorded
        );
        assert_eq!(
            projection.observe(
                Some(7),
                CausalReceipt::applied("receipt-applied", "patch-123", "editor", 7)
                    .with_payload_hash("sha256:abc"),
            ),
            ReceiptApplyStatus::Recorded
        );

        assert_eq!(
            projection.latest_for("patch-123").map(|r| r.outcome),
            Some(ReceiptOutcome::Applied)
        );
        assert_eq!(
            projection.terminal_for("patch-123").map(|r| r.outcome),
            Some(ReceiptOutcome::Applied)
        );
    }

    #[test]
    fn stale_generation_does_not_update_projection() {
        let mut projection = ReceiptProjection::new();
        assert_eq!(
            projection.observe(
                Some(7),
                CausalReceipt::rejected("receipt-stale", "patch-123", "editor", 6),
            ),
            ReceiptApplyStatus::StaleGeneration {
                expected: 7,
                actual: 6,
            }
        );

        assert!(projection.terminal_for("patch-123").is_none());
        assert!(projection.contains_receipt("receipt-stale"));
        assert_eq!(
            projection.stale_receipt_ids().cloned().collect::<Vec<_>>(),
            vec!["receipt-stale".to_string()]
        );
    }

    #[test]
    fn duplicate_receipt_id_is_noop() {
        let mut projection = ReceiptProjection::new();
        let receipt = CausalReceipt::accepted("receipt-1", "patch-123", "editor", 7);

        assert_eq!(
            projection.observe(Some(7), receipt.clone()),
            ReceiptApplyStatus::Recorded
        );
        assert_eq!(
            projection.observe(Some(7), receipt),
            ReceiptApplyStatus::Duplicate
        );
    }

    #[test]
    fn conflicting_terminal_receipts_fail_closed() {
        let mut projection = ReceiptProjection::new();
        assert_eq!(
            projection.observe(
                Some(7),
                CausalReceipt::applied("receipt-applied", "patch-123", "editor", 7),
            ),
            ReceiptApplyStatus::Recorded
        );

        assert_eq!(
            projection.observe(
                Some(7),
                CausalReceipt::rejected("receipt-rejected", "patch-123", "editor", 7),
            ),
            ReceiptApplyStatus::TerminalConflict {
                causation_id: "patch-123".to_string(),
                existing: ReceiptOutcome::Applied,
                incoming: ReceiptOutcome::Rejected,
            }
        );
        assert!(!projection.contains_receipt("receipt-rejected"));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn receipt_message_uses_externally_tagged_wire_shape() {
        let message =
            ReceiptMessage::CausalReceipts(CausalReceipts::new([CausalReceipt::applied(
                "receipt-applied",
                "patch-123",
                "editor",
                7,
            )]));

        let value = serde_json::to_value(&message).expect("receipt message serializes");
        assert_eq!(value["CausalReceipts"]["receipts"][0]["outcome"], "applied");
        assert_eq!(
            value["CausalReceipts"]["receipts"][0]["reason"],
            serde_json::Value::Null
        );
    }
}