libtracer 0.9.1

Rust binding for libtracer — a lightweight decentralized graph-based networking protocol.
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC

/*!
 * @brief Protocol ERROR registry + STATUS (Unit 3).
 *
 * The frozen RFC-0002 `tr::<concept>::<error>` registry — the 15-entry
 * code ⇄ path table mirrored from `core/include/libtracer/error.hpp` — plus
 * ERROR-TLV (`0x08`) parse/encode in both identity forms (registered u16 code /
 * string `tr::…` path) and STATUS-TLV (`0x09`) helpers.
 *
 * This registry is deliberately SEPARATE from the codec-fault [`crate::Error`]:
 * that enum names wire *framing* faults for the fuzz harness; this one is the
 * protocol *semantic* error model that rides inside STATUS/FWD replies.
 * Vector-pinned: `error-registered-code`, `error-registered-detail`,
 * `error-string-form`, `empty-status-ok`.
 */

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::tlv_builders::{value_u16, BuildError};
use crate::{type_code, Opt, Tlv};

/**
 * @brief A registered protocol error code (RFC-0002 §D) — the u16 wire identity of a
 * built-in `tr::…` error path, carried LE in the ERROR TLV's first-child VALUE.
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum ErrCode {
    /** @brief `tr::frame::truncated` */
    FrameTruncated = 0x0001,
    /** @brief `tr::frame::invalid` */
    FrameInvalid = 0x0002,
    /** @brief `tr::frame::crc_fail` */
    FrameCrcFail = 0x0003,
    /** @brief `tr::tlv::nesting_too_deep` */
    TlvNestingTooDeep = 0x0010,
    /** @brief `tr::path::not_found` */
    PathNotFound = 0x0020,
    /** @brief `tr::path::invalid` */
    PathInvalid = 0x0021,
    /** @brief `tr::path::in_use` */
    PathInUse = 0x0022,
    /** @brief `tr::schema::type_mismatch` */
    SchemaTypeMismatch = 0x0030,
    /** @brief `tr::schema::not_found` */
    SchemaNotFound = 0x0031,
    /** @brief `tr::flow::backpressure` */
    FlowBackpressure = 0x0040,
    /** @brief `tr::flow::timeout` */
    FlowTimeout = 0x0041,
    /** @brief `tr::flow::address_shift_gap` */
    FlowAddressShiftGap = 0x0042,
    /** @brief `tr::access::denied` */
    AccessDenied = 0x0050,
    /** @brief `tr::transport::down` */
    TransportDown = 0x0060,
    /** @brief `tr::version::mismatch` */
    VersionMismatch = 0x0070,
}

/**
 * @brief Registry-side severity of a protocol error (RFC-0002 §D) — advisory metadata
 * that never travels on the wire.
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /** @brief Expected-in-operation outcome (e.g. a missing path). */
    Warn,
    /** @brief A genuine protocol-level failure. */
    Error,
    /** @brief The peer relationship itself is unsound. */
    Critical,
}

/**
 * @brief Registry-side disposition of a protocol error (RFC-0002 §D) — what the caller
 * should do next; never travels on the wire.
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Disposition {
    /** @brief Retry may succeed (congestion, timing, lossy link). */
    Transient,
    /** @brief Don't retry this request as-is. */
    Permanent,
    /** @brief Tear down the peer relationship. */
    Fatal,
}

/**
 * @brief The 15-entry registry table: `(code enum, u16 code, tr:: path, severity,
 * disposition)`, in code order. Single source of truth for the lookups below.
 */
const REGISTRY: [(ErrCode, u16, &str, Severity, Disposition); 15] = [
    (
        ErrCode::FrameTruncated,
        0x0001,
        "tr::frame::truncated",
        Severity::Error,
        Disposition::Transient,
    ),
    (
        ErrCode::FrameInvalid,
        0x0002,
        "tr::frame::invalid",
        Severity::Error,
        Disposition::Permanent,
    ),
    (
        ErrCode::FrameCrcFail,
        0x0003,
        "tr::frame::crc_fail",
        Severity::Error,
        Disposition::Transient,
    ),
    (
        ErrCode::TlvNestingTooDeep,
        0x0010,
        "tr::tlv::nesting_too_deep",
        Severity::Error,
        Disposition::Permanent,
    ),
    (
        ErrCode::PathNotFound,
        0x0020,
        "tr::path::not_found",
        Severity::Warn,
        Disposition::Permanent,
    ),
    (
        ErrCode::PathInvalid,
        0x0021,
        "tr::path::invalid",
        Severity::Warn,
        Disposition::Permanent,
    ),
    (
        ErrCode::PathInUse,
        0x0022,
        "tr::path::in_use",
        Severity::Warn,
        Disposition::Permanent,
    ),
    (
        ErrCode::SchemaTypeMismatch,
        0x0030,
        "tr::schema::type_mismatch",
        Severity::Error,
        Disposition::Permanent,
    ),
    (
        ErrCode::SchemaNotFound,
        0x0031,
        "tr::schema::not_found",
        Severity::Warn,
        Disposition::Permanent,
    ),
    (
        ErrCode::FlowBackpressure,
        0x0040,
        "tr::flow::backpressure",
        Severity::Warn,
        Disposition::Transient,
    ),
    (
        ErrCode::FlowTimeout,
        0x0041,
        "tr::flow::timeout",
        Severity::Warn,
        Disposition::Transient,
    ),
    (
        ErrCode::FlowAddressShiftGap,
        0x0042,
        "tr::flow::address_shift_gap",
        Severity::Error,
        Disposition::Permanent,
    ),
    (
        ErrCode::AccessDenied,
        0x0050,
        "tr::access::denied",
        Severity::Error,
        Disposition::Permanent,
    ),
    (
        ErrCode::TransportDown,
        0x0060,
        "tr::transport::down",
        Severity::Error,
        Disposition::Transient,
    ),
    (
        ErrCode::VersionMismatch,
        0x0070,
        "tr::version::mismatch",
        Severity::Critical,
        Disposition::Fatal,
    ),
];

impl ErrCode {
    /** @brief The u16 wire code of this error (the ERROR TLV's VALUE payload, LE). */
    pub const fn code(self) -> u16 {
        self as u16
    }

    /** @brief The registered code for a raw u16, or `None` if unregistered. */
    pub fn from_code(code: u16) -> Option<ErrCode> {
        REGISTRY.iter().find(|e| e.1 == code).map(|e| e.0)
    }

    /** @brief The registered code for a `tr::…` path, or `None` if unregistered. */
    pub fn from_path(path: &str) -> Option<ErrCode> {
        REGISTRY.iter().find(|e| e.2 == path).map(|e| e.0)
    }

    /** @brief The canonical `tr::<concept>::<error>` path (the string-form identity). */
    pub fn path(self) -> &'static str {
        REGISTRY[self.index()].2
    }

    /** @brief The registry severity of this error. */
    pub fn severity(self) -> Severity {
        REGISTRY[self.index()].3
    }

    /** @brief The registry disposition of this error. */
    pub fn disposition(self) -> Disposition {
        REGISTRY[self.index()].4
    }

    fn index(self) -> usize {
        // Small linear scan (15 entries) — the registry is order-stable.
        REGISTRY.iter().position(|e| e.0 == self).unwrap_or(0)
    }
}

/** @brief The two identity forms of an ERROR TLV's first child (RFC-0002 §C). */
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorId {
    /**
     * @brief A registered code (`VALUE` first child, u16 LE). Carries the raw u16 so an
     * unrecognized-but-numeric code round-trips; use [`ErrCode::from_code`] to
     * resolve it to a known entry.
     */
    Code(u16),
    /**
     * @brief A string-form identity (`NAME` first child, UTF-8 `tr::…` path) — used by
     * third-party extensions outside the frozen registry.
     */
    Path(String),
}

/** @brief A decoded ERROR TLV: its identity plus any optional human `DESCRIPTION` detail. */
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedError {
    /** @brief The error identity (registered code or string path). */
    pub id: ErrorId,
    /** @brief The optional human-readable `DESCRIPTION` (`0x03`) detail, if present. */
    pub description: Option<String>,
}

impl ParsedError {
    /**
     * @brief The resolved registry code, when the identity is a registered numeric code
     * (or a `tr::…` path that maps into the registry).
     */
    pub fn err_code(&self) -> Option<ErrCode> {
        match &self.id {
            ErrorId::Code(c) => ErrCode::from_code(*c),
            ErrorId::Path(p) => ErrCode::from_path(p),
        }
    }
}

/**
 * @brief Build an ERROR TLV (`type=0x08`, `PL=1`) in registered-code form:
 * `ERROR{ VALUE u16=code [, DESCRIPTION detail] }`. Vector-pinned:
 * `error-registered-code`, `error-registered-detail`.
 */
pub fn error_code(code: ErrCode, description: Option<&str>) -> Tlv {
    error_with_id_value(value_u16(code.code()), description)
}

/**
 * @brief Build an ERROR TLV in raw registered-code form from an arbitrary u16 (for a
 * code not in the frozen registry).
 */
pub fn error_raw_code(code: u16, description: Option<&str>) -> Tlv {
    error_with_id_value(value_u16(code), description)
}

/**
 * @brief Build an ERROR TLV (`type=0x08`, `PL=1`) in string form:
 * `ERROR{ NAME tr::… [, DESCRIPTION detail] }`. Vector-pinned:
 * `error-string-form`.
 */
pub fn error_string(path: &str, description: Option<&str>) -> Tlv {
    let id = Tlv {
        type_code: type_code::NAME,
        opt: Opt::default(),
        payload: path.as_bytes().to_vec(),
        children: Vec::new(),
        trailer: None,
    };
    error_with_id_value(id, description)
}

fn error_with_id_value(id: Tlv, description: Option<&str>) -> Tlv {
    let mut children = alloc::vec![id];
    if let Some(text) = description {
        children.push(Tlv {
            type_code: type_code::DESCRIPTION,
            opt: Opt::default(),
            payload: text.as_bytes().to_vec(),
            children: Vec::new(),
            trailer: None,
        });
    }
    Tlv {
        type_code: type_code::ERROR,
        opt: Opt::structured(),
        payload: Vec::new(),
        children,
        trailer: None,
    }
}

/**
 * @brief Parse an ERROR TLV into its identity and optional description.
 *
 * # Errors
 * [`BuildError::TypeMismatch`] if the TLV is not an ERROR or its first child is
 * neither a registered-code VALUE (≥2 bytes) nor a string NAME.
 */
pub fn parse_error(tlv: &Tlv) -> Result<ParsedError, BuildError> {
    if tlv.type_code != type_code::ERROR {
        return Err(BuildError::TypeMismatch);
    }
    let first = tlv.children.first().ok_or(BuildError::TypeMismatch)?;
    let id = match first.type_code {
        type_code::VALUE => {
            if first.payload.len() < 2 {
                return Err(BuildError::TypeMismatch);
            }
            ErrorId::Code(first.payload[0] as u16 | ((first.payload[1] as u16) << 8))
        }
        type_code::NAME => ErrorId::Path(first.payload_str()?.to_string()),
        _ => return Err(BuildError::TypeMismatch),
    };
    let description = tlv
        .children
        .iter()
        .find(|c| c.type_code == type_code::DESCRIPTION)
        .map(|c| c.payload_str().map(|s| s.to_string()))
        .transpose()?;
    Ok(ParsedError { id, description })
}

/* ------------------------------------------------------------------ status --- */

/**
 * @brief Build the empty STATUS=OK TLV (`09 00 00 00`) — `opt.PL=0`, zero length. The
 * smallest valid frame and the implicit OK reply. Vector-pinned: `empty-status-ok`.
 */
pub fn status_ok() -> Tlv {
    Tlv {
        type_code: type_code::STATUS,
        opt: Opt::default(),
        payload: Vec::new(),
        children: Vec::new(),
        trailer: None,
    }
}

/**
 * @brief Build a non-empty STATUS TLV (`type=0x09`, `PL=1`) carrying one or more ERROR
 * children (and optional DESCRIPTION siblings appended by the caller).
 */
pub fn status_with_errors(errors: &[Tlv]) -> Tlv {
    Tlv {
        type_code: type_code::STATUS,
        opt: Opt::structured(),
        payload: Vec::new(),
        children: errors.to_vec(),
        trailer: None,
    }
}

/**
 * @brief The ERROR children of a STATUS TLV (empty for STATUS=OK).
 *
 * # Errors
 * [`BuildError::TypeMismatch`] if the TLV is not a STATUS.
 */
pub fn status_errors(tlv: &Tlv) -> Result<Vec<ParsedError>, BuildError> {
    if tlv.type_code != type_code::STATUS {
        return Err(BuildError::TypeMismatch);
    }
    tlv.children
        .iter()
        .filter(|c| c.type_code == type_code::ERROR)
        .map(parse_error)
        .collect()
}