sim-codec-bridge 0.1.1

BRIDGE packet line codec for SIM.
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
use std::collections::BTreeSet;

use sim_kernel::{ContentId, Error, Expr, Result, Symbol};
use sim_value::build::entry as field;

use crate::warrant::parse_content_id_string;
use crate::{BridgeWarrant, content_id_string};

/// One BRIDGE packet, carrying a header, ordered typed parts, and optional warrant.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BridgePacket {
    /// Fixed packet header.
    pub header: BridgeHeader,
    /// Ordered packet body parts.
    pub body: Vec<BridgePart>,
    /// Optional cross-trust warrant for book and spec content ids.
    pub warrant: Option<BridgeWarrant>,
}

/// Fixed, fast-scan BRIDGE packet header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BridgeHeader {
    /// Packet content id as rendered text, or `None` while canonicalizing.
    pub cid: Option<String>,
    /// Dialogue move intent.
    pub move_kind: Symbol,
    /// Sender seat.
    pub from: String,
    /// Receiver seats.
    pub to: Vec<String>,
    /// Sender role for this packet.
    pub role: Symbol,
    /// Parent packet content ids.
    pub parents: Vec<String>,
    /// Header task part id.
    pub task: Symbol,
    /// Header output/return part id.
    pub output: Symbol,
    /// Capability ceiling names, resolved by later bridge runtime code.
    pub ceiling: Vec<Symbol>,
    /// Context part ids available to this packet.
    pub context: Vec<Symbol>,
    /// Packet provenance.
    pub provenance: BridgeProvenance,
}

/// Provenance carried in the BRIDGE header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BridgeProvenance {
    /// Author seat or system symbol.
    pub author: Symbol,
    /// Optional card id or descriptor.
    pub card: Option<String>,
}

/// One typed body part in a BRIDGE packet.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BridgePart {
    /// Part id, referenced by header fields and other parts.
    pub id: Symbol,
    /// Registered part kind.
    pub kind: Symbol,
    /// Part payload expression.
    pub payload: Expr,
}

impl BridgePacket {
    /// Returns this packet with its header cid cleared for canonical hashing.
    pub fn canonicalized(&self) -> Self {
        let mut packet = self.clone();
        packet.header.cid = None;
        packet
    }
}

impl Default for BridgeProvenance {
    fn default() -> Self {
        Self {
            author: Symbol::new("sim"),
            card: None,
        }
    }
}

/// Project a packet to the canonical expression record used by `codec:bridge`.
pub fn packet_to_expr(packet: &BridgePacket) -> Expr {
    Expr::Map(vec![
        field("bridge", Expr::String("1".to_owned())),
        field("header", header_to_expr(&packet.header)),
        field(
            "body",
            Expr::Vector(packet.body.iter().map(part_to_expr).collect()),
        ),
        field(
            "warrant",
            packet
                .warrant
                .as_ref()
                .map(warrant_to_expr)
                .unwrap_or(Expr::Nil),
        ),
    ])
}

/// Validate a canonical packet expression back into a typed packet.
pub fn expr_to_packet(expr: &Expr) -> Result<BridgePacket> {
    let fields = map_fields(expr, "BRIDGE packet")?;
    reject_unknown(fields, &["bridge", "header", "body", "warrant"])?;
    match required_field(fields, "bridge")? {
        Expr::String(version) if version == "1" => {}
        _ => {
            return Err(Error::Eval(
                "BRIDGE packet must declare bridge version 1".to_owned(),
            ));
        }
    }
    Ok(BridgePacket {
        header: header_from_expr(required_field(fields, "header")?)?,
        body: vector_field(required_field(fields, "body")?, "body")?
            .iter()
            .map(part_from_expr)
            .collect::<Result<Vec<_>>>()?,
        warrant: match required_field(fields, "warrant")? {
            Expr::Nil => None,
            value => Some(warrant_from_expr(value)?),
        },
    })
}

fn header_to_expr(header: &BridgeHeader) -> Expr {
    Expr::Map(vec![
        field(
            "cid",
            header
                .cid
                .as_ref()
                .map(|cid| Expr::String(cid.clone()))
                .unwrap_or(Expr::Nil),
        ),
        field("move", Expr::Symbol(header.move_kind.clone())),
        field("from", Expr::String(header.from.clone())),
        field(
            "to",
            Expr::Vector(
                header
                    .to
                    .iter()
                    .map(|value| Expr::String(value.clone()))
                    .collect(),
            ),
        ),
        field("role", Expr::Symbol(header.role.clone())),
        field(
            "parents",
            Expr::Vector(
                header
                    .parents
                    .iter()
                    .map(|value| Expr::String(value.clone()))
                    .collect(),
            ),
        ),
        field("task", Expr::Symbol(header.task.clone())),
        field("output", Expr::Symbol(header.output.clone())),
        field(
            "ceiling",
            Expr::Vector(
                header
                    .ceiling
                    .iter()
                    .map(|symbol| Expr::Symbol(symbol.clone()))
                    .collect(),
            ),
        ),
        field(
            "context",
            Expr::Vector(
                header
                    .context
                    .iter()
                    .map(|symbol| Expr::Symbol(symbol.clone()))
                    .collect(),
            ),
        ),
        field("provenance", provenance_to_expr(&header.provenance)),
    ])
}

fn header_from_expr(expr: &Expr) -> Result<BridgeHeader> {
    let fields = map_fields(expr, "BRIDGE header")?;
    reject_unknown(
        fields,
        &[
            "cid",
            "move",
            "from",
            "to",
            "role",
            "parents",
            "task",
            "output",
            "ceiling",
            "context",
            "provenance",
        ],
    )?;
    Ok(BridgeHeader {
        cid: optional_string_or_nil(fields, "cid")?,
        move_kind: required_symbol(fields, "move")?,
        from: required_string(fields, "from")?,
        to: required_string_vector(fields, "to")?,
        role: required_symbol(fields, "role")?,
        parents: required_string_vector(fields, "parents")?,
        task: required_symbol(fields, "task")?,
        output: required_symbol(fields, "output")?,
        ceiling: required_symbol_vector(fields, "ceiling")?,
        context: required_symbol_vector(fields, "context")?,
        provenance: provenance_from_expr(required_field(fields, "provenance")?)?,
    })
}

fn part_to_expr(part: &BridgePart) -> Expr {
    Expr::Map(vec![
        field("id", Expr::Symbol(part.id.clone())),
        field("kind", Expr::Symbol(part.kind.clone())),
        field("payload", part.payload.clone()),
    ])
}

fn part_from_expr(expr: &Expr) -> Result<BridgePart> {
    let fields = map_fields(expr, "BRIDGE part")?;
    reject_unknown(fields, &["id", "kind", "payload"])?;
    Ok(BridgePart {
        id: required_symbol(fields, "id")?,
        kind: required_symbol(fields, "kind")?,
        payload: required_field(fields, "payload")?.clone(),
    })
}

fn provenance_to_expr(provenance: &BridgeProvenance) -> Expr {
    Expr::Map(vec![
        field("author", Expr::Symbol(provenance.author.clone())),
        field(
            "card",
            provenance
                .card
                .as_ref()
                .map(|card| Expr::String(card.clone()))
                .unwrap_or(Expr::Nil),
        ),
    ])
}

fn provenance_from_expr(expr: &Expr) -> Result<BridgeProvenance> {
    let fields = map_fields(expr, "BRIDGE provenance")?;
    reject_unknown(fields, &["author", "card"])?;
    Ok(BridgeProvenance {
        author: required_symbol(fields, "author")?,
        card: optional_string_or_nil(fields, "card")?,
    })
}

fn warrant_to_expr(warrant: &BridgeWarrant) -> Expr {
    Expr::Map(vec![
        field("moves", content_id_expr(&warrant.moves)),
        field("frames", content_id_expr(&warrant.frames)),
        field(
            "parts",
            Expr::Vector(
                warrant
                    .parts
                    .iter()
                    .map(|(kind, id)| {
                        Expr::Map(vec![
                            field("kind", Expr::Symbol(kind.clone())),
                            field("cid", content_id_expr(id)),
                        ])
                    })
                    .collect(),
            ),
        ),
    ])
}

fn warrant_from_expr(expr: &Expr) -> Result<BridgeWarrant> {
    let fields = map_fields(expr, "BRIDGE warrant")?;
    reject_unknown(fields, &["moves", "frames", "parts"])?;
    Ok(BridgeWarrant {
        moves: required_content_id(fields, "moves")?,
        frames: required_content_id(fields, "frames")?,
        parts: vector_field(required_field(fields, "parts")?, "parts")?
            .iter()
            .map(warrant_part_from_expr)
            .collect::<Result<Vec<_>>>()?,
    })
}

fn warrant_part_from_expr(expr: &Expr) -> Result<(Symbol, ContentId)> {
    let fields = map_fields(expr, "BRIDGE warrant part")?;
    reject_unknown(fields, &["kind", "cid"])?;
    Ok((
        required_symbol(fields, "kind")?,
        required_content_id(fields, "cid")?,
    ))
}

fn content_id_expr(id: &ContentId) -> Expr {
    Expr::String(content_id_string(id))
}

fn required_content_id(fields: &[(Expr, Expr)], name: &str) -> Result<ContentId> {
    match required_field(fields, name)? {
        Expr::String(value) => parse_content_id_string(value),
        _ => Err(Error::TypeMismatch {
            expected: "content id string",
            found: "non-string",
        }),
    }
}

fn required_symbol(fields: &[(Expr, Expr)], name: &str) -> Result<Symbol> {
    match required_field(fields, name)? {
        Expr::Symbol(symbol) => Ok(symbol.clone()),
        _ => Err(Error::TypeMismatch {
            expected: "symbol",
            found: "non-symbol",
        }),
    }
}

fn required_string(fields: &[(Expr, Expr)], name: &str) -> Result<String> {
    match required_field(fields, name)? {
        Expr::String(value) => Ok(value.clone()),
        _ => Err(Error::TypeMismatch {
            expected: "string",
            found: "non-string",
        }),
    }
}

fn optional_string_or_nil(fields: &[(Expr, Expr)], name: &str) -> Result<Option<String>> {
    match required_field(fields, name)? {
        Expr::Nil => Ok(None),
        Expr::String(value) => Ok(Some(value.clone())),
        _ => Err(Error::TypeMismatch {
            expected: "string or nil",
            found: "invalid optional string",
        }),
    }
}

fn required_string_vector(fields: &[(Expr, Expr)], name: &str) -> Result<Vec<String>> {
    vector_field(required_field(fields, name)?, name)?
        .iter()
        .map(|value| match value {
            Expr::String(value) => Ok(value.clone()),
            _ => Err(Error::TypeMismatch {
                expected: "string vector",
                found: "non-string item",
            }),
        })
        .collect()
}

fn required_symbol_vector(fields: &[(Expr, Expr)], name: &str) -> Result<Vec<Symbol>> {
    vector_field(required_field(fields, name)?, name)?
        .iter()
        .map(|value| match value {
            Expr::Symbol(symbol) => Ok(symbol.clone()),
            _ => Err(Error::TypeMismatch {
                expected: "symbol vector",
                found: "non-symbol item",
            }),
        })
        .collect()
}

fn vector_field<'a>(expr: &'a Expr, name: &str) -> Result<&'a [Expr]> {
    match expr {
        Expr::Vector(items) | Expr::List(items) => Ok(items),
        _ => Err(Error::Eval(format!("BRIDGE {name} field must be a vector"))),
    }
}

fn required_field<'a>(fields: &'a [(Expr, Expr)], name: &str) -> Result<&'a Expr> {
    optional_field(fields, name)
        .ok_or_else(|| Error::Eval(format!("BRIDGE record is missing {name}")))
}

fn optional_field<'a>(fields: &'a [(Expr, Expr)], name: &str) -> Option<&'a Expr> {
    fields
        .iter()
        .find_map(|(key, value)| (field_name(key).ok()?.as_str() == name).then_some(value))
}

fn reject_unknown(fields: &[(Expr, Expr)], allowed: &[&str]) -> Result<()> {
    let mut seen = BTreeSet::new();
    for (key, _) in fields {
        let name = field_name(key)?;
        if !seen.insert(name.clone()) {
            return Err(Error::Eval(format!("duplicate BRIDGE field {name}")));
        }
        if !allowed.contains(&name.as_str()) {
            return Err(Error::Eval(format!("unknown BRIDGE field {name}")));
        }
    }
    Ok(())
}

fn field_name(expr: &Expr) -> Result<String> {
    match expr {
        Expr::Symbol(symbol) if symbol.namespace.is_none() => Ok(symbol.name.to_string()),
        Expr::String(value) => Ok(value.clone()),
        _ => Err(Error::TypeMismatch {
            expected: "BRIDGE field symbol",
            found: "invalid field key",
        }),
    }
}

use sim_value::access::map_entries as map_fields;