haematite-cli 0.21.1

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
//! Bounded frames carry exact serialized bytes; only a verified whole receipt escapes.

use super::protocol::{WirePacket, WireRefusal};
use super::receipt_wire::WireReceipt;
use haematite::BatchReceipt;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use sha2::{Digest, Sha256};
use std::collections::TryReserveError;
use std::fmt;

#[derive(Debug)]
pub enum ReceiptCodecError {
    IndexOverflow,
    Utf8 { cause: std::string::FromUtf8Error },
    Allocation { cause: TryReserveError },
    Encode { cause: serde_json::Error },
    Decode { cause: serde_json::Error },
    InvalidId,
    FrameTooSmall { offered: u32, minimum: usize },
    FrameLimit { size: usize, limit: u32 },
    Identity,
    Sequence { expected: u64, actual: u64 },
    ExtentOverflow,
    Extent { expected: u64, actual: u64 },
    Count { expected: u64, actual: u64 },
    Digest,
    Hex,
    Incomplete,
    ConnectionClosed,
    Finished,
}

impl ReceiptCodecError {
    pub(super) const fn allocation(cause: TryReserveError) -> Self {
        Self::Allocation { cause }
    }
}
impl fmt::Display for ReceiptCodecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IndexOverflow => f.write_str("receipt_index_overflow"),
            Self::Utf8 { cause } => write!(f, "receipt_utf8_invalid: {cause}"),
            Self::Allocation { cause } => write!(f, "receipt_allocation_failed: {cause}"),
            Self::Encode { cause } => write!(f, "receipt_encode_failed: {cause}"),
            Self::Decode { cause } => write!(f, "receipt_decode_failed: {cause}"),
            Self::InvalidId => f.write_str("receipt_invalid_request_id"),
            Self::FrameTooSmall { offered, minimum } => write!(
                f,
                "receipt_frame_too_small: offered {offered}, minimum {minimum}"
            ),
            Self::FrameLimit { size, limit } => {
                write!(f, "receipt_frame_limit: size {size}, limit {limit}")
            }
            Self::Identity => f.write_str("receipt_request_id_mismatch"),
            Self::Sequence { expected, actual } => write!(
                f,
                "receipt_fragment_sequence: expected {expected}, actual {actual}"
            ),
            Self::ExtentOverflow => f.write_str("receipt_extent_overflow"),
            Self::Extent { expected, actual } => write!(
                f,
                "receipt_extent_mismatch: expected {expected}, actual {actual}"
            ),
            Self::Count { expected, actual } => write!(
                f,
                "receipt_count_mismatch: expected {expected}, actual {actual}"
            ),
            Self::Digest => f.write_str("receipt_digest_mismatch"),
            Self::Hex => f.write_str("receipt_hex_invalid"),
            Self::Incomplete => f.write_str("receipt_incomplete"),
            Self::ConnectionClosed => f.write_str("receipt_connection_closed"),
            Self::Finished => f.write_str("receipt_already_finished"),
        }
    }
}
impl std::error::Error for ReceiptCodecError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Allocation { cause } => Some(cause),
            Self::Utf8 { cause } => Some(cause),
            Self::Encode { cause } | Self::Decode { cause } => Some(cause),
            _ => None,
        }
    }
}

pub(super) fn reserve_bytes(
    bytes: &mut Vec<u8>,
    additional: usize,
) -> Result<(), ReceiptCodecError> {
    bytes
        .len()
        .checked_add(additional)
        .ok_or(ReceiptCodecError::ExtentOverflow)?;
    bytes
        .try_reserve_exact(additional)
        .map_err(ReceiptCodecError::allocation)
}

pub(super) fn encode_hex(bytes: &[u8]) -> Result<String, ReceiptCodecError> {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let length = bytes
        .len()
        .checked_mul(2)
        .ok_or(ReceiptCodecError::ExtentOverflow)?;
    let mut hex = String::new();
    hex.try_reserve_exact(length)
        .map_err(ReceiptCodecError::allocation)?;
    for byte in bytes {
        hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
        hex.push(char::from(DIGITS[usize::from(byte & 15)]));
    }
    Ok(hex)
}

fn decode_hex(hex: &str) -> Result<Vec<u8>, ReceiptCodecError> {
    if !hex.len().is_multiple_of(2) {
        return Err(ReceiptCodecError::Hex);
    }
    let mut result = Vec::new();
    reserve_bytes(&mut result, hex.len() / 2)?;
    for pair in hex.as_bytes().as_chunks::<2>().0 {
        let high = char::from(pair[0])
            .to_digit(16)
            .ok_or(ReceiptCodecError::Hex)?;
        let low = char::from(pair[1])
            .to_digit(16)
            .ok_or(ReceiptCodecError::Hex)?;
        result.push(u8::try_from(high * 16 + low).map_err(|_| ReceiptCodecError::Hex)?);
    }
    Ok(result)
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FragmentEnvelope {
    pub id: String,
    #[serde(rename = "receipt")]
    pub part: FragmentPart,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum FragmentPart {
    Chunk {
        sequence: u64,
        hex: String,
    },
    End {
        fragments: u64,
        outcomes: u64,
        bytes: u64,
        digest: String,
    },
}

fn encode(envelope: &FragmentEnvelope) -> Result<Vec<u8>, ReceiptCodecError> {
    serde_json::to_vec(envelope).map_err(|cause| ReceiptCodecError::Encode { cause })
}
const fn check_id(id: &str) -> Result<(), ReceiptCodecError> {
    if id.is_empty() || id.len() > 512 {
        Err(ReceiptCodecError::InvalidId)
    } else {
        Ok(())
    }
}

/// Derive the mandatory envelope floor from the actual serializer and maximum valid identity.
///
/// # Errors
///
/// Propagates envelope encoding failure.
pub fn minimum_cap() -> Result<usize, ReceiptCodecError> {
    let id = "\0".repeat(512);
    let chunk = encode(&FragmentEnvelope {
        id: id.clone(),
        part: FragmentPart::Chunk {
            sequence: u64::MAX,
            hex: "ff".into(),
        },
    })?;
    let end = encode(&FragmentEnvelope {
        id,
        part: FragmentPart::End {
            fragments: u64::MAX,
            outcomes: u64::MAX,
            bytes: u64::MAX,
            digest: "f".repeat(64),
        },
    })?;
    Ok(chunk.len().max(end.len()))
}
fn check_cap(cap: u32) -> Result<(), ReceiptCodecError> {
    let minimum = minimum_cap()?;
    if u64::from(cap) < u64::try_from(minimum).map_err(|_| ReceiptCodecError::ExtentOverflow)? {
        Err(ReceiptCodecError::FrameTooSmall {
            offered: cap,
            minimum,
        })
    } else {
        Ok(())
    }
}

#[derive(Debug)]
pub struct EncodedReceipt {
    bytes: Vec<u8>,
    outcomes: u64,
    digest: String,
}
impl EncodedReceipt {
    /// Project and serialize the complete receipt exactly once, hashing those same bytes.
    ///
    /// # Errors
    ///
    /// Propagates projection, serialization, index and allocation failures.
    pub fn project(
        receipt: &BatchReceipt,
        refusal: Option<WireRefusal>,
    ) -> Result<Self, ReceiptCodecError> {
        Self::seal(&WirePacket::Receipt {
            receipt: Box::new(WireReceipt::project(receipt)?),
            refusal,
        })
    }

    pub(crate) fn refusal(
        receipt: Option<&BatchReceipt>,
        refusal: WireRefusal,
    ) -> Result<Self, ReceiptCodecError> {
        let packet = match receipt {
            Some(receipt) => return Self::project(receipt, Some(refusal)),
            None => WirePacket::Refusal { refusal },
        };
        Self::seal(&packet)
    }

    fn seal(packet: &WirePacket) -> Result<Self, ReceiptCodecError> {
        let outcomes = u64::try_from(packet.receipt().map_or(0, |receipt| receipt.outcomes.len()))
            .map_err(|_| ReceiptCodecError::IndexOverflow)?;
        let bytes =
            serde_json::to_vec(packet).map_err(|cause| ReceiptCodecError::Encode { cause })?;
        let digest = encode_hex(&Sha256::digest(&bytes))?;
        Ok(Self {
            bytes,
            outcomes,
            digest,
        })
    }
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Produce ordered ordinary-cap envelopes without changing the serialized receipt.
    ///
    /// # Errors
    ///
    /// Refuses invalid identity, insufficient cap, overflow, allocation or encoding failure.
    pub fn frames(&self, id: &str, cap: u32) -> Result<Vec<Vec<u8>>, ReceiptCodecError> {
        check_id(id)?;
        check_cap(cap)?;
        let overhead = encode(&FragmentEnvelope {
            id: id.to_owned(),
            part: FragmentPart::Chunk {
                sequence: u64::MAX,
                hex: String::new(),
            },
        })?
        .len();
        let limit = usize::try_from(cap).map_err(|_| ReceiptCodecError::ExtentOverflow)?;
        let chunk_size = limit
            .checked_sub(overhead)
            .ok_or(ReceiptCodecError::ExtentOverflow)?
            / 2;
        if chunk_size == 0 {
            return Err(ReceiptCodecError::Incomplete);
        }
        let count = self.bytes.len().div_ceil(chunk_size);
        let mut frames = Vec::new();
        frames
            .try_reserve_exact(
                count
                    .checked_add(1)
                    .ok_or(ReceiptCodecError::ExtentOverflow)?,
            )
            .map_err(ReceiptCodecError::allocation)?;
        for (sequence, chunk) in self.bytes.chunks(chunk_size).enumerate() {
            let sequence =
                u64::try_from(sequence).map_err(|_| ReceiptCodecError::ExtentOverflow)?;
            let frame = encode(&FragmentEnvelope {
                id: id.to_owned(),
                part: FragmentPart::Chunk {
                    sequence,
                    hex: encode_hex(chunk)?,
                },
            })?;
            if frame.len() > limit {
                return Err(ReceiptCodecError::FrameLimit {
                    size: frame.len(),
                    limit: cap,
                });
            }
            frames.push(frame);
        }
        let final_frame = encode(&FragmentEnvelope {
            id: id.to_owned(),
            part: FragmentPart::End {
                fragments: u64::try_from(count).map_err(|_| ReceiptCodecError::ExtentOverflow)?,
                outcomes: self.outcomes,
                bytes: u64::try_from(self.bytes.len())
                    .map_err(|_| ReceiptCodecError::ExtentOverflow)?,
                digest: self.digest.clone(),
            },
        })?;
        if final_frame.len() > limit {
            return Err(ReceiptCodecError::FrameLimit {
                size: final_frame.len(),
                limit: cap,
            });
        }
        frames.push(final_frame);
        Ok(frames)
    }
}

/// A complete typed receipt owns the exact bytes whose digest and extent were verified.
///
/// `bytes` are those bytes as they arrived, whitespace included; `raw` is the
/// same JSON value as text, without the whitespace around it that a
/// [`RawValue`] does not keep.
#[derive(Debug)]
pub struct VerifiedReceipt {
    packet: WirePacket,
    bytes: Vec<u8>,
    raw: Box<RawValue>,
}
impl VerifiedReceipt {
    #[must_use]
    pub const fn packet(&self) -> &WirePacket {
        &self.packet
    }
    #[must_use]
    pub fn receipt(&self) -> Option<&WireReceipt> {
        self.packet.receipt()
    }
    #[must_use]
    pub const fn refusal(&self) -> Option<&WireRefusal> {
        self.packet.refusal()
    }
    #[must_use]
    pub fn raw(&self) -> &RawValue {
        &self.raw
    }
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }
}

pub struct Assembler {
    id: String,
    cap: u32,
    next: u64,
    bytes: Vec<u8>,
    digest: Sha256,
    failed: bool,
    finished: bool,
}
impl Assembler {
    /// Own one complete response under its actual correlation identity and frame cap.
    ///
    /// # Errors
    ///
    /// Refuses invalid identity or an insufficient envelope cap.
    pub fn new(id: &str, cap: u32) -> Result<Self, ReceiptCodecError> {
        check_id(id)?;
        check_cap(cap)?;
        Ok(Self {
            id: id.to_owned(),
            cap,
            next: 0,
            bytes: Vec::new(),
            digest: Sha256::new(),
            failed: false,
            finished: false,
        })
    }
    /// Admit a frame, returning a receipt only after whole-byte and outcome verification.
    ///
    /// # Errors
    ///
    /// Any malformed, missing, repeated, unassociated or unverifiable part poisons assembly.
    pub fn accept(&mut self, frame: &[u8]) -> Result<Option<VerifiedReceipt>, ReceiptCodecError> {
        if self.finished {
            return Err(ReceiptCodecError::Finished);
        }
        if self.failed {
            return Err(ReceiptCodecError::Incomplete);
        }
        let result = self.accept_part(frame);
        if result.is_err() {
            self.failed = true;
            self.bytes.clear();
        }
        result
    }
    fn accept_part(&mut self, frame: &[u8]) -> Result<Option<VerifiedReceipt>, ReceiptCodecError> {
        let limit = usize::try_from(self.cap).map_err(|_| ReceiptCodecError::ExtentOverflow)?;
        if frame.len() > limit {
            return Err(ReceiptCodecError::FrameLimit {
                size: frame.len(),
                limit: self.cap,
            });
        }
        let envelope: FragmentEnvelope =
            serde_json::from_slice(frame).map_err(|cause| ReceiptCodecError::Decode { cause })?;
        if envelope.id != self.id {
            return Err(ReceiptCodecError::Identity);
        }
        match envelope.part {
            FragmentPart::Chunk { sequence, hex } => {
                if sequence != self.next {
                    return Err(ReceiptCodecError::Sequence {
                        expected: self.next,
                        actual: sequence,
                    });
                }
                let bytes = decode_hex(&hex)?;
                if bytes.is_empty() {
                    return Err(ReceiptCodecError::Incomplete);
                }
                let next = self
                    .next
                    .checked_add(1)
                    .ok_or(ReceiptCodecError::ExtentOverflow)?;
                reserve_bytes(&mut self.bytes, bytes.len())?;
                self.bytes.extend_from_slice(&bytes);
                self.digest.update(&bytes);
                self.next = next;
                Ok(None)
            }
            FragmentPart::End {
                fragments,
                outcomes,
                bytes,
                digest,
            } => {
                if self.next == 0 {
                    return Err(ReceiptCodecError::Incomplete);
                }
                if fragments != self.next {
                    return Err(ReceiptCodecError::Sequence {
                        expected: self.next,
                        actual: fragments,
                    });
                }
                let actual = u64::try_from(self.bytes.len())
                    .map_err(|_| ReceiptCodecError::ExtentOverflow)?;
                if bytes != actual {
                    return Err(ReceiptCodecError::Extent {
                        expected: bytes,
                        actual,
                    });
                }
                let expected_digest = decode_hex(&digest)?;
                let actual_digest = self.digest.clone().finalize();
                if expected_digest.as_slice() != &actual_digest[..] {
                    return Err(ReceiptCodecError::Digest);
                }
                let packet: WirePacket = serde_json::from_slice(&self.bytes)
                    .map_err(|cause| ReceiptCodecError::Decode { cause })?;
                let actual =
                    u64::try_from(packet.receipt().map_or(0, |receipt| receipt.outcomes.len()))
                        .map_err(|_| ReceiptCodecError::ExtentOverflow)?;
                if outcomes != actual {
                    return Err(ReceiptCodecError::Count {
                        expected: outcomes,
                        actual,
                    });
                }
                let exact = std::mem::take(&mut self.bytes);
                let mut text = Vec::new();
                reserve_bytes(&mut text, exact.len())?;
                text.extend_from_slice(&exact);
                let text =
                    String::from_utf8(text).map_err(|cause| ReceiptCodecError::Utf8 { cause })?;
                let raw = RawValue::from_string(text)
                    .map_err(|cause| ReceiptCodecError::Decode { cause })?;
                self.finished = true;
                Ok(Some(VerifiedReceipt {
                    packet,
                    bytes: exact,
                    raw,
                }))
            }
        }
    }
    /// Record an ended connection without ever exposing an unfinished receipt.
    ///
    /// # Errors
    ///
    /// Returns a named connection closure unless a whole receipt was already delivered.
    pub fn connection_closed(&mut self) -> Result<(), ReceiptCodecError> {
        if self.finished {
            return Ok(());
        }
        self.failed = true;
        self.bytes.clear();
        Err(ReceiptCodecError::ConnectionClosed)
    }
}