sui-spec 0.1.15

Declarative Lisp-authored specs for CppNix-parity behaviors. Rust types are the hard boundary; Lisp forms are the free-middle authoring surface. Both engines (tree-walker + VM) drive the same spec, so they cannot drift.
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
//! Typed border for the nix-daemon worker protocol.
//!
//! When a nix client (`nix build`, `nix-env`, `nix-store --realise`)
//! needs to mutate the store, it doesn't write `/nix/store` itself
//! — it connects to the `nix-daemon` over a unix socket and speaks
//! the *worker protocol*.  cppnix's `libstore/worker-protocol.cc`
//! defines ~30 opcodes covering the full read+write surface of the
//! store.
//!
//! Today sui-daemon implements this protocol in Rust; this module
//! names the wire contract as a typed Lisp spec so any future client
//! (or any third-party daemon) rides on the same authored shape.
//! Both engines (sui's client side + sui-daemon's server side) drive
//! the same spec — they cannot drift.
//!
//! ## Authoring surface
//!
//! Two keyword forms compose:
//!
//! - `(defworker-protocol ...)` declares the protocol version +
//!   handshake (magic bytes, version negotiation).
//! - `(defworker-opcode ...)` declares ONE opcode per form: numeric
//!   code, direction, request-field types, response-field types,
//!   feature gate.  ~30 opcodes today; new ones land as additional
//!   `(defworker-opcode)` forms.
//!
//! Example:
//!
//! ```lisp
//! (defworker-protocol
//!   :name "cppnix-worker-protocol"
//!   :version 35
//!   :magic-client "0x6e697863"   ;; "nixc"
//!   :magic-server "0x6478696f")  ;; "dxio"
//!
//! (defworker-opcode
//!   :name "QueryPathInfo"
//!   :code 29
//!   :direction ClientToDaemon
//!   :request-fields  (StorePath)
//!   :response-fields (PathInfo)
//!   :since-version 17)
//! ```

use serde::{Deserialize, Serialize};
use tatara_lisp::DeriveTataraDomain;

use crate::SpecError;

// ── Typed border — protocol envelope ──────────────────────────────

/// One worker-protocol version.  Typically there's one entry per
/// major nix release (v23, v25, v27, v33, v35).
#[derive(DeriveTataraDomain, Serialize, Deserialize, Debug, Clone)]
#[tatara(keyword = "defworker-protocol")]
pub struct WorkerProtocol {
    pub name: String,
    pub version: u32,
    /// Client→daemon handshake magic, hex literal.
    #[serde(rename = "magicClient")]
    pub magic_client: String,
    /// Daemon→client handshake magic, hex literal.
    #[serde(rename = "magicServer")]
    pub magic_server: String,
}

// ── Typed border — opcodes ─────────────────────────────────────────

/// One worker-protocol opcode.
#[derive(DeriveTataraDomain, Serialize, Deserialize, Debug, Clone)]
#[tatara(keyword = "defworker-opcode")]
pub struct WorkerOpcode {
    pub name: String,
    pub code: u32,
    pub direction: OpcodeDirection,
    /// Field types serialised in the request body (in order).
    #[serde(rename = "requestFields")]
    pub request_fields: Vec<WireType>,
    /// Field types serialised in the response body (in order).
    #[serde(default, rename = "responseFields")]
    pub response_fields: Vec<WireType>,
    /// Earliest protocol version that supports this opcode.
    #[serde(default, rename = "sinceVersion")]
    pub since_version: u32,
    /// `true` if cppnix has deprecated this opcode.
    #[serde(default)]
    pub deprecated: bool,
}

/// Direction of an opcode call.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OpcodeDirection {
    /// Client initiates; daemon responds.
    ClientToDaemon,
    /// Daemon initiates a callback (rare; used for build progress).
    DaemonToClient,
}

/// Wire-level field type — the primitive types the worker protocol
/// can serialise.  Length-prefixed strings + 8-byte LE integers
/// per cppnix's `worker-protocol.cc` `WORKER_MAGIC` framing.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireType {
    /// 8-byte little-endian unsigned integer.
    U64,
    /// Length-prefixed UTF-8 string (8-byte LE length + padded bytes).
    Str,
    /// Length-prefixed byte array.
    Bytes,
    /// 0 = false, 1 = true; encoded as U64.
    Bool,
    /// Store path — Str semantically, but the spec calls it out
    /// so the type checker can validate path-shape.
    StorePath,
    /// List of strings (8-byte LE count + N Str entries).
    StringList,
    /// List of store paths (8-byte LE count + N StorePath).
    StorePathList,
    /// `PathInfo` structured response (multi-field).
    PathInfo,
    /// `ValidPathInfo` (a richer PathInfo variant).
    ValidPathInfo,
    /// `DerivationOutputs` map (output-name → output-path).
    DerivationOutputs,
    /// `RealisationsMap`.
    RealisationsMap,
    /// `KeyedBuildResult` (status enum + log + per-output info).
    KeyedBuildResult,
    /// `Substitutables` — the substituter-side path-info map.
    Substitutables,
    /// Free-form attrset of key=value lines.
    KeyValueAttrs,
    /// Build-mode enum (Normal / Repair / Check).
    BuildMode,
}

// ── Canonical spec ─────────────────────────────────────────────────

pub const CANONICAL_WORKER_PROTOCOL_LISP: &str =
    include_str!("../specs/worker_protocol.lisp");

/// Compile the canonical worker-protocol version envelope(s).
///
/// # Errors
///
/// Returns an error if the Lisp source fails to parse.
pub fn load_canonical_protocols() -> Result<Vec<WorkerProtocol>, SpecError> {
    crate::loader::load_all::<WorkerProtocol>(CANONICAL_WORKER_PROTOCOL_LISP)
}

/// Compile every authored opcode.
///
/// # Errors
///
/// Returns an error if the Lisp source fails to parse.
pub fn load_canonical_opcodes() -> Result<Vec<WorkerOpcode>, SpecError> {
    crate::loader::load_all::<WorkerOpcode>(CANONICAL_WORKER_PROTOCOL_LISP)
}

/// Return the opcode whose `name` matches.
///
/// # Errors
///
/// Returns an error if the spec fails to parse or `name` is missing.
pub fn load_opcode_named(name: &str) -> Result<WorkerOpcode, SpecError> {
    load_canonical_opcodes()?
        .into_iter()
        .find(|o| o.name == name)
        .ok_or_else(|| SpecError::Load(format!("no (defworker-opcode) with :name {name:?}")))
}

/// Return the opcode with the given `code`.
///
/// # Errors
///
/// Returns an error if the spec fails to parse or `code` doesn't
/// match any authored opcode.
pub fn load_opcode_by_code(code: u32) -> Result<WorkerOpcode, SpecError> {
    load_canonical_opcodes()?
        .into_iter()
        .find(|o| o.code == code)
        .ok_or_else(|| SpecError::Load(format!("no (defworker-opcode) with :code {code}")))
}

// ── M3.0 dispatch interpreter ──────────────────────────────────────

/// Result of dispatching a worker-protocol opcode against a handler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchOutcome {
    /// The opcode that was dispatched.
    pub opcode_name: String,
    /// The numeric code.
    pub opcode_code: u32,
    /// Response body bytes the handler produced.  Empty for
    /// opcodes with no `response_fields`.
    pub response_body: Vec<u8>,
}

/// Abstract handler for the worker protocol's server side.  Each
/// opcode dispatches to a corresponding method here; the default
/// implementation returns a typed `unhandled-opcode` error so an
/// incomplete handler surfaces missing opcodes loudly.
///
/// In production, sui-daemon implements this trait against its
/// real store.  Tests can provide a mock that records dispatched
/// opcodes for verification.
pub trait WorkerProtocolHandler {
    /// Catch-all handler.  Default returns `unhandled-opcode`
    /// error.  Concrete impls override per opcode they support.
    ///
    /// # Errors
    ///
    /// Default impl always.  Concrete handlers return per-opcode
    /// errors.
    fn dispatch(&self, opcode: &WorkerOpcode, body: &[u8])
        -> Result<Vec<u8>, String>
    {
        Err(format!(
            "unhandled opcode `{}` (code {}) — handler must override dispatch \
             or implement an explicit case",
            opcode.name, opcode.code,
        ))
    }
}

/// Dispatch one wire-arriving opcode against a handler.  Looks up
/// the opcode by code in the canonical catalog, then routes to
/// `handler.dispatch`.
///
/// # Errors
///
/// - `unknown-opcode` if `code` doesn't appear in the canonical
///   opcode set.
/// - `dispatch-failed` if the handler returns an error.
pub fn apply<H: WorkerProtocolHandler>(
    code: u32,
    body: &[u8],
    handler: &H,
) -> Result<DispatchOutcome, SpecError> {
    let opcode = load_opcode_by_code(code).map_err(|_| SpecError::Interp {
        phase: "unknown-opcode".into(),
        message: format!(
            "received opcode {code} but no (defworker-opcode :code {code}) \
             is authored in the canonical worker-protocol spec",
        ),
    })?;
    let response_body = handler.dispatch(&opcode, body).map_err(|e| SpecError::Interp {
        phase: "dispatch-failed".into(),
        message: format!("opcode `{}` (code {code}): {e}", opcode.name),
    })?;
    Ok(DispatchOutcome {
        opcode_name: opcode.name,
        opcode_code: code,
        response_body,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{HashMap, HashSet};

    #[test]
    fn canonical_protocol_parses() {
        let protos = load_canonical_protocols().unwrap();
        assert!(!protos.is_empty());
    }

    #[test]
    fn canonical_opcodes_parse() {
        let opcodes = load_canonical_opcodes().unwrap();
        assert!(
            opcodes.len() >= 25,
            "canonical worker protocol must declare at least 25 opcodes, got {}",
            opcodes.len(),
        );
    }

    #[test]
    fn opcodes_have_unique_codes() {
        let opcodes = load_canonical_opcodes().unwrap();
        let mut by_code: HashMap<u32, Vec<&str>> = HashMap::new();
        for op in &opcodes {
            by_code.entry(op.code).or_default().push(op.name.as_str());
        }
        for (code, names) in &by_code {
            assert_eq!(
                names.len(),
                1,
                "opcode {code} has multiple authored entries: {names:?}",
            );
        }
    }

    #[test]
    fn essential_opcodes_present() {
        let opcodes = load_canonical_opcodes().unwrap();
        let names: HashSet<&str> = opcodes.iter().map(|o| o.name.as_str()).collect();
        // The opcodes every client speaks at least once per session.
        for required in [
            "IsValidPath",
            "QueryPathInfo",
            "AddToStore",
            "BuildPaths",
            "BuildDerivation",
            "QueryReferrers",
            "QueryValidPaths",
            "CollectGarbage",
            "NarFromPath",
            "AddTempRoot",
        ] {
            assert!(
                names.contains(required),
                "canonical worker protocol missing opcode `{required}`",
            );
        }
    }

    #[test]
    fn query_path_info_has_correct_shape() {
        let op = load_opcode_named("QueryPathInfo").unwrap();
        assert_eq!(op.code, 26);
        assert_eq!(op.direction, OpcodeDirection::ClientToDaemon);
        assert_eq!(op.request_fields, vec![WireType::StorePath]);
    }

    #[test]
    fn ca_realisation_opcodes_present() {
        // CA-drv realisation lookup landed in protocol v32+.
        let names: HashSet<String> = load_canonical_opcodes()
            .unwrap()
            .into_iter()
            .map(|o| o.name)
            .collect();
        assert!(names.contains("QueryRealisation"));
        assert!(names.contains("RegisterDrvOutput"));
    }

    // ── M3.0 dispatch tests ────────────────────────────────────

    use std::cell::RefCell;

    struct LoggingHandler {
        seen: RefCell<Vec<(String, u32)>>,
        response_for: HashMap<u32, Vec<u8>>,
    }

    impl LoggingHandler {
        fn new() -> Self {
            Self {
                seen: RefCell::new(Vec::new()),
                response_for: HashMap::new(),
            }
        }
        fn responds(mut self, code: u32, body: &[u8]) -> Self {
            self.response_for.insert(code, body.to_vec());
            self
        }
    }

    impl WorkerProtocolHandler for LoggingHandler {
        fn dispatch(&self, opcode: &WorkerOpcode, _body: &[u8])
            -> Result<Vec<u8>, String>
        {
            self.seen.borrow_mut().push((opcode.name.clone(), opcode.code));
            self.response_for
                .get(&opcode.code)
                .cloned()
                .ok_or_else(|| format!("no response configured for code {}", opcode.code))
        }
    }

    #[test]
    fn dispatch_known_opcode_succeeds() {
        let handler = LoggingHandler::new().responds(1, b"\x01");  // IsValidPath
        let outcome = apply(1, b"", &handler).unwrap();
        assert_eq!(outcome.opcode_name, "IsValidPath");
        assert_eq!(outcome.opcode_code, 1);
        assert_eq!(outcome.response_body, vec![1u8]);
        let log = handler.seen.borrow();
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].0, "IsValidPath");
    }

    #[test]
    fn dispatch_unknown_opcode_errors() {
        let handler = LoggingHandler::new();
        let err = apply(9999, b"", &handler).unwrap_err();
        match err {
            SpecError::Interp { phase, message } => {
                assert_eq!(phase, "unknown-opcode");
                assert!(message.contains("9999"));
            }
            _ => panic!("expected unknown-opcode"),
        }
    }

    #[test]
    fn dispatch_handler_failure_surfaces_as_dispatch_failed() {
        // LoggingHandler returns Err when no response is configured.
        let handler = LoggingHandler::new();  // no responses
        let err = apply(1, b"", &handler).unwrap_err();
        match err {
            SpecError::Interp { phase, message } => {
                assert_eq!(phase, "dispatch-failed");
                assert!(message.contains("IsValidPath"));
            }
            _ => panic!("expected dispatch-failed"),
        }
    }

    #[test]
    fn load_opcode_by_code_finds_known() {
        let op = load_opcode_by_code(26).unwrap();  // QueryPathInfo
        assert_eq!(op.name, "QueryPathInfo");
    }

    #[test]
    fn load_opcode_by_code_errors_on_missing() {
        let err = load_opcode_by_code(99999).unwrap_err();
        match err {
            SpecError::Load(msg) => assert!(msg.contains("99999")),
            _ => panic!("expected Load error"),
        }
    }

    #[test]
    fn default_handler_returns_unhandled() {
        struct Empty;
        impl WorkerProtocolHandler for Empty {}
        let err = apply(1, b"", &Empty).unwrap_err();
        match err {
            SpecError::Interp { phase, .. } => assert_eq!(phase, "dispatch-failed"),
            _ => panic!("expected dispatch-failed"),
        }
    }
}