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
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
use std::fmt;
use std::time::{Duration, SystemTime};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde_json::Value;

use crate::projection_protocol::{
    ResolvedProjectionObligation, SameTransactionProjectionBatch, SameTransactionProjectionEvidence,
};
use crate::repository::CommitBatch;

use super::{
    ids::COMMAND_REPLAY_VERSION, state::validate_projection_obligation_semantics, AttemptToken,
    CanonicalInputHash, CausationId, CommandContractFingerprint, CommandId, CommandLedgerError,
    CommandLedgerKey, CommandLedgerState, TerminalCommandState, SHA256_BYTES,
};

/// One validated reservation request. Fresh candidate IDs lose a race safely:
/// only the inserted row keeps them; every retry reads the winner's causation.
pub(crate) struct CommandReservation {
    pub(super) key: CommandLedgerKey,
    pub(super) command_name: String,
    pub(super) contract_fingerprint: CommandContractFingerprint,
    pub(super) input_hash: CanonicalInputHash,
    pub(super) lease: Duration,
    pub(super) retention: Duration,
    pub(super) candidate_causation: CausationId,
    pub(super) candidate_attempt: AttemptToken,
}

impl CommandReservation {
    pub(crate) fn new(
        key: CommandLedgerKey,
        command_name: impl Into<String>,
        contract_fingerprint: CommandContractFingerprint,
        input_hash: CanonicalInputHash,
        lease: Duration,
        retention: Duration,
    ) -> Result<Self, CommandLedgerError> {
        let command_name = command_name.into();
        if command_name.trim().is_empty() {
            return Err(CommandLedgerError::Invalid(
                "command name must not be empty".into(),
            ));
        }
        validate_positive_duration("command attempt lease", lease)?;
        validate_positive_duration("command replay retention", retention)?;
        if retention <= lease {
            return Err(CommandLedgerError::Invalid(
                "command replay retention must be longer than the attempt lease".into(),
            ));
        }
        Ok(Self {
            key,
            command_name,
            contract_fingerprint,
            input_hash,
            lease,
            retention,
            candidate_causation: CausationId::new(),
            candidate_attempt: AttemptToken::new(),
        })
    }

    pub(crate) fn key(&self) -> &CommandLedgerKey {
        &self.key
    }

    pub(crate) fn command_name(&self) -> &str {
        &self.command_name
    }

    pub(crate) fn contract_fingerprint_bytes(&self) -> &[u8; SHA256_BYTES] {
        self.contract_fingerprint.as_bytes()
    }

    pub(crate) fn input_hash_bytes(&self) -> &[u8; SHA256_BYTES] {
        self.input_hash.as_bytes()
    }

    pub(crate) fn lease(&self) -> Duration {
        self.lease
    }

    pub(crate) fn retention(&self) -> Duration {
        self.retention
    }

    pub(crate) fn candidate_causation(&self) -> &CausationId {
        &self.candidate_causation
    }

    pub(crate) fn candidate_attempt(&self) -> &AttemptToken {
        &self.candidate_attempt
    }

    pub(crate) fn acquired_candidate_attempt(&self) -> CommandAttempt {
        CommandAttempt {
            key: self.key.clone(),
            contract_fingerprint: self.contract_fingerprint,
            input_hash: self.input_hash,
            causation_id: self.candidate_causation.clone(),
            attempt_token: self.candidate_attempt.clone(),
            attempt_number: 1,
        }
    }
}

fn validate_positive_duration(label: &str, duration: Duration) -> Result<(), CommandLedgerError> {
    if duration.is_zero() || !duration.as_secs_f64().is_finite() {
        return Err(CommandLedgerError::Invalid(format!(
            "{label} must be a finite positive duration"
        )));
    }
    Ok(())
}

/// Exclusive capability returned to the process that owns the current lease.
/// It is intentionally not `Clone`: one owned value must be consumed by either
/// terminal completion or the retryable-unknown transition.
pub(crate) struct CommandAttempt {
    pub(super) key: CommandLedgerKey,
    pub(super) contract_fingerprint: CommandContractFingerprint,
    pub(super) input_hash: CanonicalInputHash,
    pub(super) causation_id: CausationId,
    pub(super) attempt_token: AttemptToken,
    pub(super) attempt_number: u64,
}

impl CommandAttempt {
    pub(crate) fn key(&self) -> &CommandLedgerKey {
        &self.key
    }

    pub(crate) fn causation_id(&self) -> &CausationId {
        &self.causation_id
    }

    #[cfg(test)]
    pub(crate) fn attempt_token(&self) -> &AttemptToken {
        &self.attempt_token
    }

    #[cfg(test)]
    pub(crate) fn attempt_number(&self) -> u64 {
        self.attempt_number
    }

    /// Cloneable, read-only generation fence retained across a consuming
    /// causal commit. If commit acknowledgement is ambiguous, the dispatcher
    /// can look up the command and mark only this exact still-live attempt as
    /// retryable-unknown; it never needs to reconstruct secret fence material
    /// from strings.
    pub(crate) fn fence(&self) -> AttemptFence {
        AttemptFence {
            key: self.key.clone(),
            contract_fingerprint: self.contract_fingerprint,
            input_hash: self.input_hash,
            causation_id: self.causation_id.clone(),
            attempt_token: self.attempt_token.clone(),
            attempt_number: self.attempt_number,
        }
    }

    pub(crate) fn complete(
        self,
        state: TerminalCommandState,
        outcome: Value,
        retention: Duration,
    ) -> Result<CommandCompletion, CommandLedgerError> {
        self.complete_with_replay_metadata(state, outcome, Vec::new(), None, retention, None)
    }

    pub(crate) fn complete_with_obligations(
        self,
        state: TerminalCommandState,
        outcome: Value,
        projection_obligations: Vec<ResolvedProjectionObligation>,
        retention: Duration,
    ) -> Result<CommandCompletion, CommandLedgerError> {
        self.complete_with_replay_metadata(
            state,
            outcome,
            projection_obligations,
            None,
            retention,
            None,
        )
    }

    /// Complete a command with exact already-canonical role-safe projection
    /// metadata.
    ///
    /// The ledger intentionally treats the bytes as opaque. GraphQL validates
    /// the versioned delta/obligation schema before calling this method; the
    /// ledger preserves those bytes exactly and applies only generic size and
    /// state invariants.
    #[cfg(test)]
    pub(crate) fn complete_with_projection_metadata(
        self,
        state: TerminalCommandState,
        outcome: Value,
        projection_metadata: Vec<u8>,
        retention: Duration,
    ) -> Result<CommandCompletion, CommandLedgerError> {
        self.complete_with_replay_metadata(
            state,
            outcome,
            Vec::new(),
            Some(projection_metadata),
            retention,
            None,
        )
    }

    /// Complete a modeled command with the exact absolute retention boundary
    /// sealed into its authenticated projection metadata.
    ///
    /// The repository persists this same deadline atomically with the replay
    /// bytes, preventing a retained ledger tail whose metadata has already
    /// expired.
    pub(crate) fn complete_with_projection_metadata_until(
        self,
        state: TerminalCommandState,
        outcome: Value,
        projection_metadata: Vec<u8>,
        retention: Duration,
        retention_expires_at: SystemTime,
    ) -> Result<CommandCompletion, CommandLedgerError> {
        self.complete_with_replay_metadata(
            state,
            outcome,
            Vec::new(),
            Some(projection_metadata),
            retention,
            Some(retention_expires_at),
        )
    }

    fn complete_with_replay_metadata(
        self,
        state: TerminalCommandState,
        outcome: Value,
        projection_obligations: Vec<ResolvedProjectionObligation>,
        projection_metadata: Option<Vec<u8>>,
        retention: Duration,
        retention_expires_at: Option<SystemTime>,
    ) -> Result<CommandCompletion, CommandLedgerError> {
        validate_positive_duration("command replay retention", retention)?;
        if projection_metadata.is_none() {
            validate_projection_obligation_semantics(state.into(), &projection_obligations)
                .map_err(CommandLedgerError::Invalid)?;
        }
        validate_projection_metadata_bytes(state.into(), projection_metadata.as_deref())?;
        if projection_metadata.is_some() && !projection_obligations.is_empty() {
            return Err(CommandLedgerError::Invalid(
                "command replay cannot mix legacy and modeled projection obligations".into(),
            ));
        }
        let mut replay = serde_json::Map::from_iter([
            (
                "version".into(),
                Value::from(u64::from(COMMAND_REPLAY_VERSION)),
            ),
            ("outcome".into(), outcome),
            (
                "projection_obligations".into(),
                serde_json::to_value(projection_obligations).map_err(|error| {
                    CommandLedgerError::Invalid(format!(
                        "command replay obligations failed to serialize before commit: {error}"
                    ))
                })?,
            ),
        ]);
        if let Some(projection_metadata) = projection_metadata {
            replay.insert(
                "projection_metadata".into(),
                Value::String(URL_SAFE_NO_PAD.encode(projection_metadata)),
            );
        }
        let replay = serde_json::to_string(&Value::Object(replay)).map_err(|error| {
            CommandLedgerError::Invalid(format!(
                "command replay serialization failed before commit: {error}"
            ))
        })?;
        Ok(CommandCompletion {
            attempt: self,
            state,
            replay,
            direct_projection: None,
            retention,
            retention_expires_at,
        })
    }
}

/// Read-only snapshot of one attempt generation, safe to retain while the
/// owned [`CommandAttempt`] is consumed by completion.
#[derive(Clone, Debug)]
pub(crate) struct AttemptFence {
    pub(super) key: CommandLedgerKey,
    pub(super) contract_fingerprint: CommandContractFingerprint,
    pub(super) input_hash: CanonicalInputHash,
    pub(super) causation_id: CausationId,
    pub(super) attempt_token: AttemptToken,
    pub(super) attempt_number: u64,
}

impl AttemptFence {
    pub(crate) fn key(&self) -> &CommandLedgerKey {
        &self.key
    }

    pub(crate) fn causation_id(&self) -> &CausationId {
        &self.causation_id
    }

    pub(crate) fn attempt_token(&self) -> &AttemptToken {
        &self.attempt_token
    }

    pub(crate) fn attempt_number(&self) -> u64 {
        self.attempt_number
    }

    pub(crate) fn contract_fingerprint_bytes(&self) -> &[u8; SHA256_BYTES] {
        self.contract_fingerprint.as_bytes()
    }

    pub(crate) fn input_hash_bytes(&self) -> &[u8; SHA256_BYTES] {
        self.input_hash.as_bytes()
    }
}

/// Authorization scope for a command-ledger lookup.
///
/// Public status reads are bound to the selected command route. Ambiguous
/// commit recovery instead presents the private attempt fence retained by the
/// dispatcher, so it can recover a terminal outcome without trusting a route
/// name supplied by the caller.
#[derive(Clone, Copy, Debug)]
pub(crate) enum CommandLookupScope<'a> {
    CommandName(&'a str),
    CommandContract {
        command_name: &'a str,
        contract_fingerprint: &'a [u8; SHA256_BYTES],
    },
    Attempt(&'a AttemptFence),
}

impl fmt::Debug for CommandAttempt {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandAttempt")
            .field("key", &self.key)
            .field("causation_id", &self.causation_id)
            .field("attempt_token", &"[redacted]")
            .field("attempt_number", &self.attempt_number)
            .finish()
    }
}

/// A terminal command replay recovered without invoking application code.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CommandReplay {
    pub(crate) command_id: CommandId,
    /// Trusted command contract identity retained from the durable ledger row.
    ///
    /// Projection response/status classification uses this value to bind even
    /// structurally empty modeled metadata to the command that produced it.
    pub(crate) command_name: String,
    pub(crate) state: CommandLedgerState,
    pub(crate) causation_id: CausationId,
    pub(crate) outcome: Value,
    pub(crate) projection_obligations: Vec<ResolvedProjectionObligation>,
    /// Exact canonical role-safe delta and opaque obligation bytes.
    pub(crate) projection_metadata: Option<Vec<u8>>,
    /// Exact original direct-projection revision/change evidence.
    ///
    /// This is intentionally retained as the validated canonical replay value:
    /// clients replay the original command outcome, while framework recovery
    /// and diagnostics can prove which record version that transaction minted.
    pub(crate) direct_projection: Option<Value>,
}

pub(super) fn validate_projection_metadata_bytes(
    state: CommandLedgerState,
    projection_metadata: Option<&[u8]>,
) -> Result<(), CommandLedgerError> {
    let Some(bytes) = projection_metadata else {
        return Ok(());
    };
    if bytes.is_empty() || bytes.len() > crate::MAX_DOMAIN_EVENT_BODY_BYTES {
        return Err(CommandLedgerError::Invalid(format!(
            "command projection metadata must contain 1..={} bytes",
            crate::MAX_DOMAIN_EVENT_BODY_BYTES
        )));
    }
    if !matches!(
        state,
        CommandLedgerState::Succeeded
            | CommandLedgerState::SucceededPendingProjection
            | CommandLedgerState::ProjectionFailed
    ) {
        return Err(CommandLedgerError::Invalid(format!(
            "state `{}` cannot contain modeled projection metadata",
            state.as_str()
        )));
    }
    Ok(())
}

/// Result of one short reservation transaction.
#[derive(Debug)]
pub(crate) enum ReservationOutcome {
    Acquired(CommandAttempt),
    InProgress {
        /// Retained for the public receipt/status envelope added by the causal
        /// protocol layer; private dispatch currently exposes only the state.
        #[allow(dead_code)]
        causation_id: CausationId,
    },
    Replay(CommandReplay),
    Conflict,
    Expired,
}

/// Authorized status lookup result. Grant checks occur above this private
/// storage layer; a raw command ID alone never reaches this API.
#[derive(Clone, Debug, PartialEq)]
#[allow(
    clippy::large_enum_variant,
    reason = "this private result is consumed immediately; boxing the replay hot path would add allocation and touch every adapter"
)]
pub(crate) enum CommandLookup {
    InProgress { causation_id: CausationId },
    RetryableUnknown { causation_id: CausationId },
    Replay(CommandReplay),
    Expired,
    Unknown,
}

/// Exactly one fenced ledger completion attached to a domain commit.
pub(crate) struct CommandCompletion {
    pub(super) attempt: CommandAttempt,
    pub(super) state: TerminalCommandState,
    pub(super) replay: String,
    direct_projection: Option<Value>,
    pub(super) retention: Duration,
    retention_expires_at: Option<SystemTime>,
}

impl CommandCompletion {
    pub(crate) fn attempt(&self) -> &CommandAttempt {
        &self.attempt
    }

    pub(crate) fn state(&self) -> TerminalCommandState {
        self.state
    }

    pub(crate) fn replay_json(&self) -> &str {
        &self.replay
    }

    pub(crate) fn retention(&self) -> Duration {
        self.retention
    }

    pub(crate) fn retention_expires_at(&self) -> Option<SystemTime> {
        self.retention_expires_at
    }

    pub(crate) fn attempt_fence(&self) -> AttemptFence {
        self.attempt.fence()
    }

    /// Attach adapter-allocated same-transaction projection evidence before
    /// the ledger row is completed in that same transaction.
    pub(crate) fn attach_direct_projection(
        &mut self,
        evidence: &SameTransactionProjectionEvidence,
    ) -> Result<(), CommandLedgerError> {
        if self.state != TerminalCommandState::Atomic {
            return Err(CommandLedgerError::Invalid(
                "direct projection evidence may only complete a projected command".into(),
            ));
        }
        if self.direct_projection.is_some() {
            return Err(CommandLedgerError::Invalid(
                "command completion already contains direct projection evidence".into(),
            ));
        }
        let direct_projection = evidence.replay_value();
        SameTransactionProjectionEvidence::validate_replay_value(&direct_projection)
            .map_err(CommandLedgerError::Invalid)?;

        let replay: Value = serde_json::from_str(&self.replay).map_err(|error| {
            CommandLedgerError::Invalid(format!(
                "command replay could not be extended with direct projection evidence: {error}"
            ))
        })?;
        let Value::Object(mut replay) = replay else {
            return Err(CommandLedgerError::Invalid(
                "command replay envelope is not an object".into(),
            ));
        };
        if replay
            .insert("direct_projection".into(), direct_projection.clone())
            .is_some()
        {
            return Err(CommandLedgerError::Invalid(
                "command replay already has a direct projection field".into(),
            ));
        }
        self.replay = serde_json::to_string(&replay).map_err(|error| {
            CommandLedgerError::Invalid(format!(
                "command replay serialization failed after direct projection: {error}"
            ))
        })?;
        self.direct_projection = Some(direct_projection);
        Ok(())
    }

    pub(super) fn validate_direct_projection(&self) -> Result<(), CommandLedgerError> {
        match (self.state, self.direct_projection.is_some()) {
            (TerminalCommandState::Atomic, true)
            | (
                TerminalCommandState::Succeeded
                | TerminalCommandState::SucceededPendingProjection
                | TerminalCommandState::Rejected,
                false,
            ) => Ok(()),
            (TerminalCommandState::Atomic, false) => Err(CommandLedgerError::Invalid(
                "projected command completion has no exact direct projection evidence".into(),
            )),
            (_, true) => Err(CommandLedgerError::Invalid(
                "non-projected command completion contains direct projection evidence".into(),
            )),
        }
    }
}

/// Existing public domain batch plus exactly one private ledger completion.
pub(crate) struct CausalCommitBatch<'a> {
    pub(crate) domain: CommitBatch<'a>,
    pub(crate) completion: CommandCompletion,
    pub(crate) direct_projection: Option<SameTransactionProjectionBatch>,
}

impl<'a> CausalCommitBatch<'a> {
    pub(crate) fn new(domain: CommitBatch<'a>, completion: CommandCompletion) -> Self {
        Self::build(domain, completion, None)
    }

    pub(crate) fn with_direct_projection(
        domain: CommitBatch<'a>,
        completion: CommandCompletion,
        direct_projection: SameTransactionProjectionBatch,
    ) -> Self {
        Self::build(domain, completion, Some(direct_projection))
    }

    fn build(
        mut domain: CommitBatch<'a>,
        completion: CommandCompletion,
        direct_projection: Option<SameTransactionProjectionBatch>,
    ) -> Self {
        // The attempt's stable causation is authoritative at the final boundary:
        // handler metadata cannot accidentally (or deliberately) split the
        // event/outbox effects from their durable command identity.
        let causation_id = completion.attempt().causation_id().as_str();
        for stream in &mut domain.streams {
            stream.entity.overwrite_new_event_causation_id(causation_id);
        }
        for message in &mut domain.outbox_messages {
            message.overwrite_causation_id(causation_id);
        }
        Self {
            domain,
            completion,
            direct_projection,
        }
    }
}