syncbat 0.10.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
//! Generic operation metadata for syncbat handlers.

use std::hash::{Hash, Hasher};
use std::sync::Arc;

use crate::effect::OperationEffectRow;
use crate::handler::HandlerFn;
use crate::operation_name::{OperationName, OperationNameError};

/// Runtime-facing side-effect classification for an operation receipt.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum EffectClass {
    /// Reads or inspects data without intending to mutate durable state.
    Inspect,
    /// Computes output from input without intending to touch durable state.
    Compute,
    /// Mutates local durable state.
    Persist,
    /// Produces an externally visible side effect.
    Emit,
    /// Changes runtime control flow or runtime-owned bookkeeping.
    Control,
}

impl EffectClass {
    /// Stable lowercase catalog spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Inspect => "inspect",
            Self::Compute => "compute",
            Self::Persist => "persist",
            Self::Emit => "emit",
            Self::Control => "control",
        }
    }

    /// Parse a stable lowercase catalog spelling.
    #[must_use]
    pub fn from_catalog_str(value: &str) -> Option<Self> {
        match value {
            "inspect" => Some(Self::Inspect),
            "compute" => Some(Self::Compute),
            "persist" => Some(Self::Persist),
            "emit" => Some(Self::Emit),
            "control" => Some(Self::Control),
            _ => None,
        }
    }
}

/// Byte input passed into a syncbat handler.
pub type OperationInput = Vec<u8>;

/// Byte output returned by a syncbat handler.
pub type OperationOutput = Vec<u8>;

/// Maximum bytes accepted for a stable operation name.
pub const MAX_OPERATION_NAME_BYTES: usize = 128;
/// Maximum bytes accepted for schema and receipt string references.
pub const MAX_DESCRIPTOR_REF_BYTES: usize = 256;

/// Stable metadata that describes a byte-oriented operation.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct OperationDescriptor {
    /// Stable operation name used for routing and receipts.
    name: DescriptorText,
    /// Optional human-readable title.
    title: Option<DescriptorText>,
    /// Runtime-facing effect class for receipt classification.
    pub effect: EffectClass,
    /// Stable string reference for the operation input schema.
    input_schema_ref: DescriptorText,
    /// Stable string reference for the operation output schema.
    output_schema_ref: DescriptorText,
    /// Stable receipt kind emitted for this operation.
    receipt_kind: DescriptorText,
    /// Declared fine-grained effect row enforced at dispatch.
    // Boxed so a descriptor stays small (the inline row is six Vecs + a bool):
    // an unboxed row pushed `OperationDescriptor` past the clippy
    // large-enum/large-Err thresholds wherever it is embedded. `None` == empty,
    // which keeps `new`/`new_with_title` `const`.
    effect_row: Option<Box<OperationEffectRow>>,
}

#[derive(Clone, Debug, Eq)]
enum DescriptorText {
    Static(&'static str),
    Owned(Arc<str>),
}

impl DescriptorText {
    const fn static_str(value: &'static str) -> Self {
        Self::Static(value)
    }

    fn owned(value: impl Into<String>) -> Self {
        Self::Owned(Arc::from(value.into()))
    }

    fn as_str(&self) -> &str {
        match self {
            Self::Static(value) => value,
            Self::Owned(value) => value.as_ref(),
        }
    }
}

impl PartialEq for DescriptorText {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}

impl Hash for DescriptorText {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

impl OperationDescriptor {
    /// Construct an operation descriptor from stable string references.
    #[must_use]
    pub const fn new(
        name: &'static str,
        effect: EffectClass,
        input_schema_ref: &'static str,
        output_schema_ref: &'static str,
        receipt_kind: &'static str,
    ) -> Self {
        Self {
            name: DescriptorText::static_str(name),
            title: None,
            effect,
            input_schema_ref: DescriptorText::static_str(input_schema_ref),
            output_schema_ref: DescriptorText::static_str(output_schema_ref),
            receipt_kind: DescriptorText::static_str(receipt_kind),
            effect_row: None,
        }
    }

    /// Construct an operation descriptor from stable string references with a
    /// human-readable title.
    #[must_use]
    pub const fn new_with_title(
        name: &'static str,
        effect: EffectClass,
        input_schema_ref: &'static str,
        output_schema_ref: &'static str,
        receipt_kind: &'static str,
        title: &'static str,
    ) -> Self {
        Self {
            name: DescriptorText::static_str(name),
            title: Some(DescriptorText::static_str(title)),
            effect,
            input_schema_ref: DescriptorText::static_str(input_schema_ref),
            output_schema_ref: DescriptorText::static_str(output_schema_ref),
            receipt_kind: DescriptorText::static_str(receipt_kind),
            effect_row: None,
        }
    }

    /// Construct an operation descriptor from owned strings rebuilt from
    /// durable catalog rows.
    #[must_use]
    pub fn owned(
        name: impl Into<String>,
        effect: EffectClass,
        input_schema_ref: impl Into<String>,
        output_schema_ref: impl Into<String>,
        receipt_kind: impl Into<String>,
    ) -> Self {
        Self {
            name: DescriptorText::owned(name),
            title: None,
            effect,
            input_schema_ref: DescriptorText::owned(input_schema_ref),
            output_schema_ref: DescriptorText::owned(output_schema_ref),
            receipt_kind: DescriptorText::owned(receipt_kind),
            effect_row: None,
        }
    }

    /// Return a copy of this descriptor with an owned human-readable title
    /// attached.
    #[must_use]
    pub fn with_owned_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(DescriptorText::owned(title));
        self
    }

    /// Return a copy of this descriptor with an explicit fine-grained effect row.
    #[must_use]
    pub fn with_effect_row(mut self, effect_row: OperationEffectRow) -> Self {
        self.effect_row = if effect_row.is_empty() {
            None
        } else {
            Some(Box::new(effect_row))
        };
        self
    }

    /// Stable operation name used for routing and receipts.
    #[must_use]
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Optional human-readable title.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        self.title.as_ref().map(DescriptorText::as_str)
    }

    /// Stable string reference for the operation input schema.
    #[must_use]
    pub fn input_schema_ref(&self) -> &str {
        self.input_schema_ref.as_str()
    }

    /// Stable string reference for the operation output schema.
    #[must_use]
    pub fn output_schema_ref(&self) -> &str {
        self.output_schema_ref.as_str()
    }

    /// Stable receipt kind emitted for this operation.
    #[must_use]
    pub fn receipt_kind(&self) -> &str {
        self.receipt_kind.as_str()
    }

    /// Fine-grained declared effects enforced against handler observations.
    #[must_use]
    pub fn effect_row(&self) -> &OperationEffectRow {
        // `None` is the empty row; hand out a shared empty so callers always
        // see a `&OperationEffectRow` regardless of the boxed representation.
        static EMPTY_EFFECT_ROW: OperationEffectRow = OperationEffectRow::empty();
        self.effect_row.as_deref().unwrap_or(&EMPTY_EFFECT_ROW)
    }

    /// Validate descriptor fields before insertion into a live runtime catalog.
    ///
    /// # Errors
    /// Returns [`DescriptorValidationError`] when any stable identifier is
    /// empty, too long, or contains bytes outside syncbat's descriptor grammar.
    pub fn validate(&self) -> Result<(), DescriptorValidationError> {
        // Run the operation-name grammar through the single
        // [`OperationName`] constructor so every layer agrees on the rules.
        OperationName::new(self.name()).map_err(|error| {
            DescriptorValidationError::from_operation_name_error("name", self.name(), &error)
        })?;
        validate_stable_ref(
            self.name(),
            "input_schema_ref",
            self.input_schema_ref(),
            MAX_DESCRIPTOR_REF_BYTES,
        )?;
        validate_stable_ref(
            self.name(),
            "output_schema_ref",
            self.output_schema_ref(),
            MAX_DESCRIPTOR_REF_BYTES,
        )?;
        validate_stable_ref(
            self.name(),
            "receipt_kind",
            self.receipt_kind(),
            MAX_DESCRIPTOR_REF_BYTES,
        )?;
        self.effect_row()
            .validate_for_descriptor(self.effect, self.receipt_kind())
    }
}

/// Macro-generated operation registration item.
///
/// This is data plus a function pointer. It does not own runtime dispatch,
/// store setup, or receipt persistence; callers still choose when to register
/// it with a [`crate::CoreBuilder`].
#[derive(Clone)]
pub struct OperationRegisterItem {
    descriptor: OperationDescriptor,
    handler: HandlerFn,
}

impl OperationRegisterItem {
    /// Build an operation registration item.
    #[must_use]
    pub fn new(descriptor: OperationDescriptor, handler: HandlerFn) -> Self {
        Self {
            descriptor,
            handler,
        }
    }

    /// Descriptor emitted for this operation.
    #[must_use]
    pub fn descriptor(&self) -> &OperationDescriptor {
        &self.descriptor
    }

    /// Function-pointer handler emitted for this operation.
    #[must_use]
    pub fn handler(&self) -> HandlerFn {
        self.handler
    }

    /// Consume the item and return descriptor plus handler.
    #[must_use]
    pub fn into_parts(self) -> (OperationDescriptor, HandlerFn) {
        (self.descriptor, self.handler)
    }
}

/// Descriptor shape validation failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DescriptorValidationError {
    /// Field that failed validation.
    pub field: &'static str,
    /// Invalid field value.
    pub value: String,
    /// Stable validation message.
    pub message: &'static str,
}

impl DescriptorValidationError {
    pub(crate) fn new(
        field: &'static str,
        value: impl Into<String>,
        message: &'static str,
    ) -> Self {
        Self {
            field,
            value: value.into(),
            message,
        }
    }

    /// Map an [`OperationNameError`] from the substrate-wide newtype into the
    /// descriptor-layer error shape so existing callers keep observing the
    /// same `field` + stable `message` columns.
    fn from_operation_name_error(
        field: &'static str,
        value: &str,
        error: &OperationNameError,
    ) -> Self {
        let message = match error {
            OperationNameError::Empty => "empty",
            OperationNameError::TooLong { .. } => "too long",
            OperationNameError::LeadingOrTrailingDot | OperationNameError::ConsecutiveDots => {
                "dot-separated tokens must be non-empty"
            }
            OperationNameError::IllegalCharacter { .. } => {
                "expected ASCII letters, digits, '.', '_' or '-'"
            }
        };
        Self::new(field, value, message)
    }
}

impl std::fmt::Display for DescriptorValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} `{}` is invalid: {}",
            self.field, self.value, self.message
        )
    }
}

impl std::error::Error for DescriptorValidationError {}

fn validate_stable_ref(
    operation_name: &str,
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), DescriptorValidationError> {
    validate_stable_ref_token(field, value, max).map_err(|error| DescriptorValidationError {
        field: error.field,
        value: format!("{operation_name}:{}", error.value),
        message: error.message,
    })
}

/// Schema/receipt-ref grammar check.
///
/// Shares the operation-name grammar by intent but applies to a different
/// field with a larger byte bound. The operation-name path goes through
/// [`OperationName`] in `operation_name.rs` instead.
fn validate_stable_ref_token(
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), DescriptorValidationError> {
    if value.is_empty() {
        return Err(DescriptorValidationError::new(field, value, "empty"));
    }
    if value.len() > max {
        return Err(DescriptorValidationError::new(field, value, "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(DescriptorValidationError::new(
            field,
            value,
            "expected ASCII letters, digits, '.', '_' or '-'",
        ));
    }
    if value.starts_with('.') || value.ends_with('.') || value.contains("..") {
        return Err(DescriptorValidationError::new(
            field,
            value,
            "dot-separated tokens must be non-empty",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod effect_class_tests {
    use super::EffectClass;

    #[test]
    fn every_variant_round_trips_through_catalog_str() {
        // Pins each `from_catalog_str` arm against its `as_str` spelling so a
        // deleted arm (e.g. "persist") is caught as a broken round-trip rather
        // than silently parsing to None.
        for class in [
            EffectClass::Inspect,
            EffectClass::Compute,
            EffectClass::Persist,
            EffectClass::Emit,
            EffectClass::Control,
        ] {
            assert_eq!(
                EffectClass::from_catalog_str(class.as_str()),
                Some(class),
                "round-trip failed for {}",
                class.as_str()
            );
        }
        assert_eq!(
            EffectClass::from_catalog_str("persist"),
            Some(EffectClass::Persist)
        );
        assert_eq!(EffectClass::from_catalog_str("nonsense"), None);
    }
}