syncbat 0.9.0

Sync-first runtime layer for batpak-family operation kits.
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use std::collections::BTreeMap;
use std::sync::Arc;

use batpak::coordinate::{Coordinate, EventCategory};
use batpak::store::Freshness;

use crate::operation::MAX_DESCRIPTOR_REF_BYTES;
use crate::operation_name::OperationName;
use crate::operation_status_sink::operation_status_entity;

use super::error::SubscriptionRuntimeError;
use super::projector::{ProjectionProjector, ProjectionRouteBinding};

const MAX_SUBSCRIPTION_ID_BYTES: usize = 128;

/// Binding fields needed to open an operation-status subscription session.
#[derive(Clone, Debug)]
pub struct OperationStatusRouteBinding {
    /// Globally unique subscription id.
    pub subscription_id: String,
    /// Route-declared operation name.
    pub operation: OperationName,
    /// Entity coordinate bound to the operation-status facts.
    pub entity: String,
    /// Wire payload schema ref token.
    pub wire_payload_schema_ref: String,
    /// Optional inner status schema ref.
    pub inner_status_schema_ref: Option<String>,
    /// Freshness mode for status materialization.
    pub freshness: Freshness,
    /// Optional route-specific queue clamp.
    pub backpressure_capacity: Option<usize>,
}

/// Binding fields needed to open an entity-stream subscription session.
#[derive(Clone, Debug)]
pub struct EntityStreamRouteBinding {
    /// Globally unique subscription id.
    pub subscription_id: String,
    /// Entity coordinate bound to the stream.
    pub entity: String,
    /// Scope coordinate bound to the stream.
    pub scope: String,
    /// Wire payload schema ref token.
    pub wire_payload_schema_ref: String,
    /// Optional inner event payload schema ref.
    pub inner_event_payload_schema_ref: Option<String>,
    /// Optional route-specific queue clamp.
    pub backpressure_capacity: Option<usize>,
}

/// Binding fields needed to open a receipt-stream subscription session.
#[derive(Clone, Debug)]
pub struct ReceiptStreamRouteBinding {
    /// Globally unique subscription id.
    pub subscription_id: String,
    /// Route-declared receipt kind filter.
    pub receipt_kind: String,
    /// Wire payload schema ref token.
    pub wire_payload_schema_ref: String,
    /// Optional inner receipt schema ref.
    pub inner_receipt_schema_ref: Option<String>,
    /// Optional route-specific queue clamp.
    pub backpressure_capacity: Option<usize>,
}

/// Globally unique subscription id (`orders.open.v1` grammar).
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubscriptionId(String);

impl SubscriptionId {
    /// Construct and validate a subscription id.
    ///
    /// # Errors
    /// [`SubscriptionRuntimeError::InvalidSubscriptionId`].
    pub fn new(id: impl Into<String>) -> Result<Self, SubscriptionRuntimeError> {
        let id = id.into();
        validate_subscription_id(&id)
            .map_err(|reason| SubscriptionRuntimeError::InvalidSubscriptionId { reason })?;
        Ok(Self(id))
    }

    /// Borrow the id string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Declared route for one subscription id.
#[derive(Clone)]
pub enum SubscriptionRoute {
    /// Category-wide event stream.
    EventCategory {
        /// Exported 4-bit event category filter.
        category: u8,
        /// Wire `payload_schema_ref` token for stream envelopes.
        wire_payload_schema_ref: String,
        /// Optional inner payload schema ref carried inside the envelope.
        inner_event_payload_schema_ref: Option<String>,
        /// Optional route-specific queue clamp.
        backpressure_capacity: Option<usize>,
    },
    /// Exact coordinate event stream.
    EntityStream {
        /// Entity coordinate bound to the stream.
        entity: String,
        /// Scope coordinate bound to the stream.
        scope: String,
        /// Wire `payload_schema_ref` token for stream envelopes.
        wire_payload_schema_ref: String,
        /// Optional inner payload schema ref carried inside the envelope.
        inner_event_payload_schema_ref: Option<String>,
        /// Optional route-specific queue clamp.
        backpressure_capacity: Option<usize>,
    },
    /// Entity-scoped projection stream.
    Projection {
        /// Route-declared projection id.
        projection_id: String,
        /// Entity coordinate bound to the projection.
        entity: String,
        /// Wire `payload_schema_ref` token for stream envelopes.
        wire_payload_schema_ref: String,
        /// Optional inner projection schema ref carried inside the envelope.
        inner_projection_schema_ref: Option<String>,
        /// Freshness mode for projection materialization.
        freshness: Freshness,
        /// Optional route-specific queue clamp.
        backpressure_capacity: Option<usize>,
        /// syncbat-owned projector that opens typed projection sessions.
        projector: Arc<dyn ProjectionProjector>,
    },
    /// Operation-scoped status stream.
    OperationStatus {
        /// Route-declared operation name.
        operation: OperationName,
        /// Entity coordinate bound to the operation-status facts.
        entity: String,
        /// Wire `payload_schema_ref` token for stream envelopes.
        wire_payload_schema_ref: String,
        /// Optional inner status schema ref carried inside the envelope.
        inner_status_schema_ref: Option<String>,
        /// Freshness mode for status materialization.
        freshness: Freshness,
        /// Optional route-specific queue clamp.
        backpressure_capacity: Option<usize>,
    },
    /// Receipt-kind filtered append stream.
    ReceiptStream {
        /// Receipt kind whose durable append events form the stream.
        receipt_kind: String,
        /// Wire `payload_schema_ref` token for stream envelopes.
        wire_payload_schema_ref: String,
        /// Optional inner receipt schema ref carried inside the envelope.
        inner_receipt_schema_ref: Option<String>,
        /// Optional route-specific queue clamp.
        backpressure_capacity: Option<usize>,
    },
}

impl SubscriptionRoute {
    /// Return the event category for an event-category route.
    #[must_use]
    pub fn event_category(&self) -> Option<u8> {
        match self {
            Self::EventCategory { category, .. } => Some(*category),
            Self::Projection { .. }
            | Self::OperationStatus { .. }
            | Self::ReceiptStream { .. }
            | Self::EntityStream { .. } => None,
        }
    }

    /// Build an entity-stream route binding for session open.
    #[must_use]
    pub fn entity_stream_binding(&self, subscription_id: &str) -> Option<EntityStreamRouteBinding> {
        match self {
            Self::EntityStream {
                entity,
                scope,
                wire_payload_schema_ref,
                inner_event_payload_schema_ref,
                backpressure_capacity,
            } => Some(EntityStreamRouteBinding {
                subscription_id: subscription_id.to_owned(),
                entity: entity.clone(),
                scope: scope.clone(),
                wire_payload_schema_ref: wire_payload_schema_ref.clone(),
                inner_event_payload_schema_ref: inner_event_payload_schema_ref.clone(),
                backpressure_capacity: *backpressure_capacity,
            }),
            Self::EventCategory { .. }
            | Self::Projection { .. }
            | Self::OperationStatus { .. }
            | Self::ReceiptStream { .. } => None,
        }
    }

    /// Build a projection route binding for session open.
    #[must_use]
    pub fn projection_binding(&self, subscription_id: &str) -> Option<ProjectionRouteBinding> {
        match self {
            Self::Projection {
                projection_id,
                entity,
                wire_payload_schema_ref,
                inner_projection_schema_ref,
                freshness,
                backpressure_capacity,
                ..
            } => Some(ProjectionRouteBinding {
                subscription_id: subscription_id.to_owned(),
                projection_id: projection_id.clone(),
                entity: entity.clone(),
                wire_payload_schema_ref: wire_payload_schema_ref.clone(),
                inner_projection_schema_ref: inner_projection_schema_ref.clone(),
                freshness: freshness.clone(),
                backpressure_capacity: *backpressure_capacity,
            }),
            Self::EventCategory { .. } => None,
            Self::EntityStream { .. } => None,
            Self::OperationStatus { .. } | Self::ReceiptStream { .. } => None,
        }
    }

    /// Build an operation-status route binding for session open.
    #[must_use]
    pub fn operation_status_binding(
        &self,
        subscription_id: &str,
    ) -> Option<OperationStatusRouteBinding> {
        match self {
            Self::OperationStatus {
                operation,
                entity,
                wire_payload_schema_ref,
                inner_status_schema_ref,
                freshness,
                backpressure_capacity,
            } => Some(OperationStatusRouteBinding {
                subscription_id: subscription_id.to_owned(),
                operation: operation.clone(),
                entity: entity.clone(),
                wire_payload_schema_ref: wire_payload_schema_ref.clone(),
                inner_status_schema_ref: inner_status_schema_ref.clone(),
                freshness: freshness.clone(),
                backpressure_capacity: *backpressure_capacity,
            }),
            Self::EventCategory { .. }
            | Self::Projection { .. }
            | Self::ReceiptStream { .. }
            | Self::EntityStream { .. } => None,
        }
    }

    /// Build a receipt-stream route binding for session open.
    #[must_use]
    pub fn receipt_stream_binding(
        &self,
        subscription_id: &str,
    ) -> Option<ReceiptStreamRouteBinding> {
        match self {
            Self::ReceiptStream {
                receipt_kind,
                wire_payload_schema_ref,
                inner_receipt_schema_ref,
                backpressure_capacity,
            } => Some(ReceiptStreamRouteBinding {
                subscription_id: subscription_id.to_owned(),
                receipt_kind: receipt_kind.clone(),
                wire_payload_schema_ref: wire_payload_schema_ref.clone(),
                inner_receipt_schema_ref: inner_receipt_schema_ref.clone(),
                backpressure_capacity: *backpressure_capacity,
            }),
            Self::EventCategory { .. }
            | Self::Projection { .. }
            | Self::OperationStatus { .. }
            | Self::EntityStream { .. } => None,
        }
    }
}

impl std::fmt::Debug for SubscriptionRoute {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EventCategory {
                category,
                wire_payload_schema_ref,
                inner_event_payload_schema_ref,
                backpressure_capacity,
            } => f
                .debug_struct("EventCategory")
                .field("category", category)
                .field("wire_payload_schema_ref", wire_payload_schema_ref)
                .field(
                    "inner_event_payload_schema_ref",
                    inner_event_payload_schema_ref,
                )
                .field("backpressure_capacity", backpressure_capacity)
                .finish(),
            Self::EntityStream {
                entity,
                scope,
                wire_payload_schema_ref,
                inner_event_payload_schema_ref,
                backpressure_capacity,
            } => f
                .debug_struct("EntityStream")
                .field("entity", entity)
                .field("scope", scope)
                .field("wire_payload_schema_ref", wire_payload_schema_ref)
                .field(
                    "inner_event_payload_schema_ref",
                    inner_event_payload_schema_ref,
                )
                .field("backpressure_capacity", backpressure_capacity)
                .finish(),
            Self::Projection {
                projection_id,
                entity,
                wire_payload_schema_ref,
                inner_projection_schema_ref,
                freshness,
                backpressure_capacity,
                ..
            } => f
                .debug_struct("Projection")
                .field("projection_id", projection_id)
                .field("entity", entity)
                .field("wire_payload_schema_ref", wire_payload_schema_ref)
                .field("inner_projection_schema_ref", inner_projection_schema_ref)
                .field("freshness", freshness)
                .field("backpressure_capacity", backpressure_capacity)
                .field("projector", &"Arc<dyn ProjectionProjector>")
                .finish(),
            Self::OperationStatus {
                operation,
                entity,
                wire_payload_schema_ref,
                inner_status_schema_ref,
                freshness,
                backpressure_capacity,
            } => f
                .debug_struct("OperationStatus")
                .field("operation", operation)
                .field("entity", entity)
                .field("wire_payload_schema_ref", wire_payload_schema_ref)
                .field("inner_status_schema_ref", inner_status_schema_ref)
                .field("freshness", freshness)
                .field("backpressure_capacity", backpressure_capacity)
                .finish(),
            Self::ReceiptStream {
                receipt_kind,
                wire_payload_schema_ref,
                inner_receipt_schema_ref,
                backpressure_capacity,
            } => f
                .debug_struct("ReceiptStream")
                .field("receipt_kind", receipt_kind)
                .field("wire_payload_schema_ref", wire_payload_schema_ref)
                .field("inner_receipt_schema_ref", inner_receipt_schema_ref)
                .field("backpressure_capacity", backpressure_capacity)
                .finish(),
        }
    }
}

impl PartialEq for SubscriptionRoute {
    fn eq(&self, other: &Self) -> bool {
        self.event_category_eq(other)
            || self.entity_stream_eq(other)
            || self.projection_eq(other)
            || self.operation_status_eq(other)
            || self.receipt_stream_eq(other)
    }
}

impl Eq for SubscriptionRoute {}

impl SubscriptionRoute {
    fn event_category_eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::EventCategory {
                    category: left_category,
                    wire_payload_schema_ref: left_wire,
                    inner_event_payload_schema_ref: left_inner,
                    backpressure_capacity: left_cap,
                },
                Self::EventCategory {
                    category: right_category,
                    wire_payload_schema_ref: right_wire,
                    inner_event_payload_schema_ref: right_inner,
                    backpressure_capacity: right_cap,
                },
            ) => {
                left_category == right_category
                    && left_wire == right_wire
                    && left_inner == right_inner
                    && left_cap == right_cap
            }
            _ => false,
        }
    }

    fn entity_stream_eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::EntityStream {
                    entity: left_entity,
                    scope: left_scope,
                    wire_payload_schema_ref: left_wire,
                    inner_event_payload_schema_ref: left_inner,
                    backpressure_capacity: left_cap,
                },
                Self::EntityStream {
                    entity: right_entity,
                    scope: right_scope,
                    wire_payload_schema_ref: right_wire,
                    inner_event_payload_schema_ref: right_inner,
                    backpressure_capacity: right_cap,
                },
            ) => {
                left_entity == right_entity
                    && left_scope == right_scope
                    && left_wire == right_wire
                    && left_inner == right_inner
                    && left_cap == right_cap
            }
            _ => false,
        }
    }

    fn projection_eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::Projection {
                    projection_id: left_projection,
                    entity: left_entity,
                    wire_payload_schema_ref: left_wire,
                    inner_projection_schema_ref: left_inner,
                    freshness: left_freshness,
                    backpressure_capacity: left_cap,
                    ..
                },
                Self::Projection {
                    projection_id: right_projection,
                    entity: right_entity,
                    wire_payload_schema_ref: right_wire,
                    inner_projection_schema_ref: right_inner,
                    freshness: right_freshness,
                    backpressure_capacity: right_cap,
                    ..
                },
            ) => {
                left_projection == right_projection
                    && left_entity == right_entity
                    && left_wire == right_wire
                    && left_inner == right_inner
                    && freshness_same(left_freshness, right_freshness)
                    && left_cap == right_cap
            }
            _ => false,
        }
    }

    fn operation_status_eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::OperationStatus {
                    operation: left_operation,
                    entity: left_entity,
                    wire_payload_schema_ref: left_wire,
                    inner_status_schema_ref: left_inner,
                    freshness: left_freshness,
                    backpressure_capacity: left_cap,
                },
                Self::OperationStatus {
                    operation: right_operation,
                    entity: right_entity,
                    wire_payload_schema_ref: right_wire,
                    inner_status_schema_ref: right_inner,
                    freshness: right_freshness,
                    backpressure_capacity: right_cap,
                },
            ) => {
                left_operation == right_operation
                    && left_entity == right_entity
                    && left_wire == right_wire
                    && left_inner == right_inner
                    && freshness_same(left_freshness, right_freshness)
                    && left_cap == right_cap
            }
            _ => false,
        }
    }

    fn receipt_stream_eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::ReceiptStream {
                    receipt_kind: left_kind,
                    wire_payload_schema_ref: left_wire,
                    inner_receipt_schema_ref: left_inner,
                    backpressure_capacity: left_cap,
                },
                Self::ReceiptStream {
                    receipt_kind: right_kind,
                    wire_payload_schema_ref: right_wire,
                    inner_receipt_schema_ref: right_inner,
                    backpressure_capacity: right_cap,
                },
            ) => {
                left_kind == right_kind
                    && left_wire == right_wire
                    && left_inner == right_inner
                    && left_cap == right_cap
            }
            _ => false,
        }
    }
}

fn freshness_same(left: &Freshness, right: &Freshness) -> bool {
    match (left, right) {
        (Freshness::Consistent, Freshness::Consistent) => true,
        (
            Freshness::MaybeStale {
                max_stale_ms: left_ms,
            },
            Freshness::MaybeStale {
                max_stale_ms: right_ms,
            },
        ) => left_ms == right_ms,
        _ => false,
    }
}

/// Typed subscription route table for the runtime engine.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SubscriptionRegistry {
    routes: BTreeMap<String, SubscriptionRoute>,
}

impl SubscriptionRegistry {
    /// Empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            routes: BTreeMap::new(),
        }
    }

    /// Register one route.
    ///
    /// # Errors
    /// [`SubscriptionRuntimeError::DuplicateSubscription`] or
    /// [`SubscriptionRuntimeError::InvalidRoute`].
    pub fn insert(
        &mut self,
        id: SubscriptionId,
        route: SubscriptionRoute,
    ) -> Result<(), SubscriptionRuntimeError> {
        validate_route(&route)?;
        if self.routes.contains_key(id.as_str()) {
            return Err(SubscriptionRuntimeError::DuplicateSubscription { id: id.0 });
        }
        self.routes.insert(id.0, route);
        Ok(())
    }

    /// Look up a route by subscription id text.
    #[must_use]
    pub fn get(&self, subscription_id: &str) -> Option<&SubscriptionRoute> {
        self.routes.get(subscription_id)
    }
}

fn validate_route(route: &SubscriptionRoute) -> Result<(), SubscriptionRuntimeError> {
    match route {
        SubscriptionRoute::EventCategory {
            category,
            wire_payload_schema_ref,
            backpressure_capacity,
            ..
        } => {
            validate_event_category_route(*category, wire_payload_schema_ref, backpressure_capacity)
        }
        SubscriptionRoute::Projection {
            projection_id,
            entity,
            wire_payload_schema_ref,
            backpressure_capacity,
            ..
        } => validate_projection_route(
            projection_id,
            entity,
            wire_payload_schema_ref,
            backpressure_capacity,
        ),
        SubscriptionRoute::OperationStatus {
            operation,
            entity,
            wire_payload_schema_ref,
            backpressure_capacity,
            ..
        } => validate_operation_status_route(
            operation,
            entity,
            wire_payload_schema_ref,
            backpressure_capacity,
        ),
        SubscriptionRoute::EntityStream {
            entity,
            scope,
            wire_payload_schema_ref,
            backpressure_capacity,
            ..
        } => validate_entity_stream_route(
            entity,
            scope,
            wire_payload_schema_ref,
            backpressure_capacity,
        ),
        SubscriptionRoute::ReceiptStream {
            receipt_kind,
            wire_payload_schema_ref,
            backpressure_capacity,
            ..
        } => validate_receipt_stream_route(
            receipt_kind,
            wire_payload_schema_ref,
            backpressure_capacity,
        ),
    }
}

fn validate_event_category_route(
    category: u8,
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    EventCategory::new(category).map_err(|_| SubscriptionRuntimeError::InvalidRoute {
        reason: "event category out of range",
    })?;
    validate_wire_and_backpressure(wire_payload_schema_ref, backpressure_capacity)
}

fn validate_projection_route(
    projection_id: &str,
    entity: &str,
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    if projection_id.is_empty() {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "projection id is empty",
        });
    }
    if entity.is_empty() {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "entity is empty",
        });
    }
    validate_wire_and_backpressure(wire_payload_schema_ref, backpressure_capacity)
}

fn validate_operation_status_route(
    operation: &OperationName,
    entity: &str,
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    if entity.is_empty() {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "entity is empty",
        });
    }
    let expected = operation_status_entity(operation.as_str()).map_err(|_| {
        SubscriptionRuntimeError::InvalidRoute {
            reason: "operation name produces invalid status entity",
        }
    })?;
    if entity != expected {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "entity does not match operation-status entity helper",
        });
    }
    validate_wire_and_backpressure(wire_payload_schema_ref, backpressure_capacity)
}

fn validate_entity_stream_route(
    entity: &str,
    scope: &str,
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    Coordinate::new(entity, scope).map_err(|_| SubscriptionRuntimeError::InvalidRoute {
        reason: "entity coordinate is invalid",
    })?;
    validate_wire_and_backpressure(wire_payload_schema_ref, backpressure_capacity)
}

fn validate_receipt_stream_route(
    receipt_kind: &str,
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    validate_receipt_kind(receipt_kind)?;
    validate_wire_and_backpressure(wire_payload_schema_ref, backpressure_capacity)
}

fn validate_wire_and_backpressure(
    wire_payload_schema_ref: &str,
    backpressure_capacity: &Option<usize>,
) -> Result<(), SubscriptionRuntimeError> {
    if let Err(reason) = validate_wire_payload_schema_ref(wire_payload_schema_ref) {
        return Err(SubscriptionRuntimeError::InvalidRoute { reason });
    }
    if matches!(backpressure_capacity, Some(0)) {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "backpressure capacity is zero",
        });
    }
    Ok(())
}

fn validate_wire_payload_schema_ref(reference: &str) -> Result<(), &'static str> {
    if reference.is_empty() {
        return Err("wire payload schema ref is empty");
    }
    if reference.len() > MAX_DESCRIPTOR_REF_BYTES {
        return Err("wire payload schema ref longer than 256 bytes");
    }
    if reference.contains(char::is_whitespace) {
        return Err("wire payload schema ref contains whitespace");
    }
    if !reference.bytes().all(|byte| {
        byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'_' | b'-')
    }) {
        return Err("wire payload schema ref has characters outside [a-z0-9._-]");
    }
    Ok(())
}

fn validate_receipt_kind(value: &str) -> Result<(), SubscriptionRuntimeError> {
    if value.is_empty() {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "receipt kind is empty",
        });
    }
    if value.len() > MAX_DESCRIPTOR_REF_BYTES {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "receipt kind is too long",
        });
    }
    if value
        .bytes()
        .any(|byte| !matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-'))
    {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "receipt kind has invalid characters",
        });
    }
    if value.starts_with('.') || value.ends_with('.') || value.contains("..") {
        return Err(SubscriptionRuntimeError::InvalidRoute {
            reason: "receipt kind has invalid dot placement",
        });
    }
    Ok(())
}

/// Validate subscription id grammar:
/// `^[a-z0-9][a-z0-9._-]*\.v[1-9][0-9]*$` with length and dot rules.
fn validate_subscription_id(id: &str) -> Result<(), &'static str> {
    if id.is_empty() {
        return Err("empty subscription id");
    }
    if id.len() > MAX_SUBSCRIPTION_ID_BYTES {
        return Err("subscription id longer than 128 bytes");
    }
    if id.starts_with('.') || id.ends_with('.') {
        return Err("subscription id has a leading or trailing '.'");
    }
    if id.contains("..") {
        return Err("subscription id has a doubled '.'");
    }
    let Some(dot_v) = id.rfind(".v") else {
        return Err("subscription id must contain a .v version suffix");
    };
    let name = &id[..dot_v];
    let version = &id[dot_v + 2..];
    if name.is_empty() {
        return Err("subscription id name prefix is empty");
    }
    if !name
        .bytes()
        .next()
        .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
    {
        return Err("subscription id must start with [a-z0-9]");
    }
    if !name
        .bytes()
        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-'))
    {
        return Err("subscription id has characters outside [a-z0-9._-]");
    }
    if version.is_empty() {
        return Err("subscription id missing version digits after .v");
    }
    let first = version.as_bytes()[0];
    if !first.is_ascii_digit() || first == b'0' {
        return Err("subscription id version must start with 1-9");
    }
    if !version.chars().all(|c| c.is_ascii_digit()) {
        return Err("subscription id version must be digits only");
    }
    Ok(())
}