splicer 2.4.1

Plan and generate middleware splice operations for WebAssembly component composition graphs.
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
//! Demo: splicer rule application and type-compatibility checking.
//!
//! Run with:
//!   cargo run --example demo
//!
//! Tests (also exercised by `cargo test --all-targets`):
//!   cargo test --example demo
//!
//! ## Phase 1 — Basic splice
//! Shows WAC generation for `before` and `between` rules on a simple
//! log-interface chain (no type information required).
//!
//! ## Phase 2 — Type-compatibility checking
//! Demonstrates all three `ContractResult` outcomes:
//!   Warn  — middleware has no path; type safety unconfirmed but injection proceeds
//!   Ok    — fingerprints match; injection confirmed safe
//!   Error — fingerprints differ; types are structurally incompatible
//!
//! ## Phase 3 — Full pipeline with real WAT
//! Compiles WAT middleware sources from `demo/wat/`, writes them to temp files,
//! and calls `validate_contract` via the real `discover_middleware_exports` path:
//!   Ok    — compatible WAT middleware (same `log` signature as chain)
//!   Error — incompatible WAT middleware (different `log` signature)

use cviz::model::ExportInfo;
use cviz::parse::component::parse_component;
use cviz::parse::json::parse_json_str;
use splicer::lowlevel::{generate_wac, parse_yaml, validate_contract, Injection};
use splicer::types::ContractResult;
use std::collections::{BTreeMap, HashMap};

// ─── JSON graph fixtures ──────────────────────────────────────────────────
// Two-node log chain:  log-provider  →  app
const JSON_LOG_SHORT: &str = r#"
{
  "version": 1,
  "nodes": [
    { "id": 11, "name": "log-provider", "component_index": 0, "component_num": 0, "imports": [] },
    {
      "id": 13, "name": "app", "component_index": 1, "component_num": 1,
      "imports": [
        { "interface": "wasi:logging/log@0.1.0", "short": "log",
          "source_instance": 11, "is_host_import": false }
      ]
    }
  ],
  "exports": [{ "interface": "wasi:logging/log@0.1.0", "source_instance": 13 }]
}
"#;

// Three-node log chain:  log-provider-inner  →  log-provider  →  app
const JSON_LOG_LONG: &str = r#"
{
  "version": 1,
  "nodes": [
    { "id": 11, "name": "log-provider-inner", "component_index": 0, "component_num": 0, "imports": [] },
    {
      "id": 12, "name": "log-provider", "component_index": 1, "component_num": 1,
      "imports": [
        { "interface": "wasi:logging/log@0.1.0", "short": "log",
          "source_instance": 11, "is_host_import": false }
      ]
    },
    {
      "id": 13, "name": "app", "component_index": 2, "component_num": 2,
      "imports": [
        { "interface": "wasi:logging/log@0.1.0", "short": "log",
          "source_instance": 12, "is_host_import": false }
      ]
    }
  ],
  "exports": [{ "interface": "wasi:logging/log@0.1.0", "source_instance": 13 }]
}
"#;

const LOG_IFACE: &str = "wasi:logging/log@0.1.0";

// ─── Phase 1 scenario functions ───────────────────────────────────────────

/// 1a: inject `mw-a` before `log-provider` in a two-node chain.
pub fn scenario_1a_before_on_short_chain() -> String {
    let yaml = r#"
version: 1
rules:
  - before:
      interface: wasi:logging/log@0.1.0
      provider:
        name: log-provider
    inject:
      - name: mw-a
"#;
    let cfg = parse_yaml(yaml).unwrap();
    let graph = parse_json_str(JSON_LOG_SHORT).unwrap();
    generate_wac(
        HashMap::new(),
        "placeholder",
        &graph,
        &cfg,
        None,
        "example:composition",
    )
    .unwrap()
    .wac
}

/// 1b: inject `mw-a` before `log-provider-inner` (the deepest node) in a three-node chain.
pub fn scenario_1b_before_on_long_chain() -> String {
    let yaml = r#"
version: 1
rules:
  - before:
      interface: wasi:logging/log@0.1.0
      provider:
        name: log-provider-inner
    inject:
      - name: mw-a
"#;
    let cfg = parse_yaml(yaml).unwrap();
    let graph = parse_json_str(JSON_LOG_LONG).unwrap();
    generate_wac(
        HashMap::new(),
        "placeholder",
        &graph,
        &cfg,
        None,
        "example:composition",
    )
    .unwrap()
    .wac
}

/// 1c: inject `mw-a` and `mw-b` between `log-provider-inner` and `log-provider`.
pub fn scenario_1c_between_on_long_chain() -> String {
    let yaml = r#"
version: 1
rules:
  - between:
      interface: wasi:logging/log@0.1.0
      inner:
        name: log-provider-inner
      outer:
        name: log-provider
    inject:
      - name: mw-a
      - name: mw-b
"#;
    let cfg = parse_yaml(yaml).unwrap();
    let graph = parse_json_str(JSON_LOG_LONG).unwrap();
    generate_wac(
        HashMap::new(),
        "placeholder",
        &graph,
        &cfg,
        None,
        "example:composition",
    )
    .unwrap()
    .wac
}

// ─── Phase 2 helpers ─────────────────────────────────────────────────────

const CHAIN_FP: &str = "sha256-abc123-fake-fingerprint";

fn injection(name: &str) -> Injection {
    Injection::from_name(name)
}

fn cache_with_fp(mw: &str, fp: &str) -> HashMap<String, BTreeMap<String, ExportInfo>> {
    let mut exports = BTreeMap::new();
    exports.insert(
        LOG_IFACE.to_string(),
        ExportInfo {
            source_instance: 0,
            fingerprint: Some(fp.to_string()),
            ty: None,
        },
    );
    let mut cache = HashMap::new();
    cache.insert(mw.to_string(), exports);
    cache
}

// ─── Phase 2 scenario functions ───────────────────────────────────────────

/// 2a: Warn — middleware has no path; discovery returns empty; cannot validate.
pub fn scenario_2a_warn_no_path() -> Vec<ContractResult> {
    let mut cache = HashMap::new();
    validate_contract(
        &[injection("mw")],
        LOG_IFACE,
        &Some(CHAIN_FP.to_string()),
        &mut cache,
    )
}

/// 2b: Ok — middleware exports the interface with a matching fingerprint.
pub fn scenario_2b_ok_compatible() -> Vec<ContractResult> {
    let mut cache = cache_with_fp("mw", CHAIN_FP);
    validate_contract(
        &[injection("mw")],
        LOG_IFACE,
        &Some(CHAIN_FP.to_string()),
        &mut cache,
    )
}

/// 2c: Error — middleware exports the interface but with an incompatible fingerprint.
pub fn scenario_2c_error_incompatible() -> Vec<ContractResult> {
    let mut cache = cache_with_fp("mw", "sha256-zzz999-different-type");
    validate_contract(
        &[injection("mw")],
        LOG_IFACE,
        &Some(CHAIN_FP.to_string()),
        &mut cache,
    )
}

// ─── Phase 3 helpers ─────────────────────────────────────────────────────

// Chain WAT used solely to derive the fingerprint for wasi:logging/log@0.1.0.
// The interface exports a single `log(level: u32, message: string)` function.
const CHAIN_WAT: &str = r#"(component
    (import "wasi:logging/log@0.1.0" (instance $host
        (export "log" (func (param "level" u32) (param "message" string)))
    ))
    (alias export $host "log" (func $f))
    (instance $out (export "log" (func $f)))
    (export "wasi:logging/log@0.1.0" (instance $out))
)"#;

/// Derive the fingerprint for `wasi:logging/log@0.1.0` from the chain WAT.
fn chain_log_fingerprint() -> Option<String> {
    let bytes = wat::parse_str(CHAIN_WAT).expect("compile chain WAT");
    let graph = parse_component(&bytes).expect("parse chain component");
    graph
        .component_exports
        .get(LOG_IFACE)
        .and_then(|e| e.fingerprint.clone())
}

/// Compile `mw_wat`, write the WASM bytes to a temp file, then run
/// `validate_contract` — exercising the real `discover_middleware_exports` path.
fn run_type_check_full(mw_wat: &str, temp_name: &str) -> Vec<ContractResult> {
    let chain_fp = chain_log_fingerprint();

    let mw_bytes = wat::parse_str(mw_wat).expect("compile middleware WAT");
    let tmp_path = std::env::temp_dir().join(temp_name);
    std::fs::write(&tmp_path, &mw_bytes).expect("write temp wasm");

    let inj = Injection::from_path("mw", tmp_path.to_str().unwrap());

    let mut cache = HashMap::new();
    validate_contract(&[inj], LOG_IFACE, &chain_fp, &mut cache)
}

// ─── Phase 3 scenario functions ───────────────────────────────────────────

/// 3a: compatible WAT middleware (same signature as chain) → Ok.
pub fn scenario_3a_ok_compatible_wat() -> Vec<ContractResult> {
    let mw_wat = include_str!("../demo/wat/log-middleware-compatible.wat");
    run_type_check_full(mw_wat, "splicer-demo-mw-compatible.wasm")
}

/// 3b: incompatible WAT middleware (different `log` signature) → Error.
pub fn scenario_3b_error_incompatible_wat() -> Vec<ContractResult> {
    let mw_wat = include_str!("../demo/wat/log-middleware-incompatible.wat");
    run_type_check_full(mw_wat, "splicer-demo-mw-incompatible.wasm")
}

// ─── Printing helpers ─────────────────────────────────────────────────────

fn header(title: &str) {
    let bar = "".repeat(64);
    println!("\n{bar}");
    println!("  {title}");
    println!("{bar}");
}

fn subheader(label: &str) {
    println!("\n  ── {label} ──");
}

fn show_contract_result(result: &ContractResult) {
    match result {
        ContractResult::Ok => println!("  ✔  Ok — types are compatible, injection confirmed safe"),
        ContractResult::Warn(msg) => println!("  ⚠  Warn — {msg}"),
        ContractResult::Error(msg) => println!("  ✘  Error — {msg}"),
        ContractResult::Tier1Compatible(ifaces) => {
            println!("  ↪  Tier1Compatible — middleware is type-erased; adapter component will be generated (hooks: {ifaces:?})")
        }
        ContractResult::Tier2Compatible(ifaces) => {
            println!("  ↪  Tier2Compatible — middleware observes lifted values; adapter component will be generated (hooks: {ifaces:?})")
        }
    }
}

// ─── main ─────────────────────────────────────────────────────────────────

fn main() {
    // ── Phase 1 ──────────────────────────────────────────────────────────
    header("Phase 1 — Basic Splice  (no type checking)");

    subheader("1a · before rule on a two-node log chain");
    println!("{}", scenario_1a_before_on_short_chain());

    subheader("1b · before rule on a three-node log chain  (targets innermost provider)");
    println!("{}", scenario_1b_before_on_long_chain());

    subheader("1c · between rule on a three-node log chain  (two middlewares)");
    println!("{}", scenario_1c_between_on_long_chain());

    // ── Phase 2 ──────────────────────────────────────────────────────────
    header("Phase 2 — Type-Compatibility Checking");
    println!();
    println!("  Chain fingerprint: {CHAIN_FP}");

    subheader("2a · Warn — middleware has no path; cannot validate type safety");
    for r in scenario_2a_warn_no_path() {
        show_contract_result(&r);
    }

    subheader("2b · Ok — middleware exports the interface with matching fingerprint");
    for r in scenario_2b_ok_compatible() {
        show_contract_result(&r);
    }

    subheader("2c · Error — middleware exports the interface with a DIFFERENT fingerprint");
    for r in scenario_2c_error_incompatible() {
        show_contract_result(&r);
    }

    // ── Phase 3 ──────────────────────────────────────────────────────────
    header("Phase 3 — Full Pipeline with Real WAT");
    println!();
    println!("  Interface : {LOG_IFACE}");
    println!("  Chain WAT : log(level: u32, message: string)");

    subheader("3a · Ok — compatible WAT middleware  (same log signature)");
    for r in scenario_3a_ok_compatible_wat() {
        show_contract_result(&r);
    }

    subheader("3b · Error — incompatible WAT middleware  (level: string vs u32)");
    for r in scenario_3b_error_incompatible_wat() {
        show_contract_result(&r);
    }

    let bar = "".repeat(64);
    println!("\n{bar}");
}

// ─── Tests ────────────────────────────────────────────────────────────────
// Run with: cargo test --example demo   (or cargo test --all-targets)

#[test]
fn test_1a_middleware_wraps_log_provider() {
    let wac = scenario_1a_before_on_short_chain();
    assert!(
        wac.contains("let mw-a = new my:mw-a {"),
        "mw-a should be instantiated"
    );
    assert!(
        wac.contains(&format!(r#""{LOG_IFACE}": log-provider["{LOG_IFACE}"]"#)),
        "mw-a should be wired from log-provider"
    );
    assert!(
        wac.contains(&format!(r#""{LOG_IFACE}": mw-a["{LOG_IFACE}"]"#)),
        "app should receive log through mw-a"
    );
}

#[test]
fn test_1b_middleware_inserted_before_innermost() {
    let wac = scenario_1b_before_on_long_chain();
    assert!(
        wac.contains("let mw-a = new my:mw-a {"),
        "mw-a should be instantiated"
    );
    assert!(
        wac.contains(&format!(
            r#""{LOG_IFACE}": log-provider-inner["{LOG_IFACE}"]"#
        )),
        "mw-a should be wired from log-provider-inner"
    );
    // log-provider wired through mw-a, not directly from log-provider-inner
    assert!(
        wac.contains(&format!(r#""{LOG_IFACE}": mw-a["{LOG_IFACE}"]"#)),
        "log-provider should receive log through mw-a"
    );
}

#[test]
fn test_1c_two_middlewares_between_nodes() {
    let wac = scenario_1c_between_on_long_chain();
    assert!(
        wac.contains("let mw-a = new my:mw-a {"),
        "mw-a should be instantiated"
    );
    assert!(
        wac.contains("let mw-b = new my:mw-b {"),
        "mw-b should be instantiated"
    );
    // Both middlewares wired on the log interface
    let mw_a_line = format!(r#""{LOG_IFACE}": mw-a["{LOG_IFACE}"]"#);
    let mw_b_line = format!(r#""{LOG_IFACE}": mw-b["{LOG_IFACE}"]"#);
    assert!(wac.contains(&mw_a_line), "mw-a should be in the chain");
    assert!(wac.contains(&mw_b_line), "mw-b should be in the chain");
    // log-provider-inner is still present as the chain root
    assert!(wac.contains("let log-provider-inner = new my:log-provider-inner {"));
}

#[test]
fn test_2a_produces_warn() {
    let results = scenario_2a_warn_no_path();
    assert_eq!(results.len(), 1);
    assert!(
        matches!(results[0], ContractResult::Warn(_)),
        "expected Warn, got {:?}",
        results[0]
    );
}

#[test]
fn test_2b_produces_ok() {
    let results = scenario_2b_ok_compatible();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0], ContractResult::Ok);
}

#[test]
fn test_2c_produces_error() {
    let results = scenario_2c_error_incompatible();
    assert_eq!(results.len(), 1);
    assert!(
        matches!(results[0], ContractResult::Error(_)),
        "expected Error, got {:?}",
        results[0]
    );
}

#[test]
fn test_3a_compatible_wat_produces_ok() {
    let results = scenario_3a_ok_compatible_wat();
    assert_eq!(results.len(), 1);
    assert_eq!(
        results[0],
        ContractResult::Ok,
        "compatible WAT middleware should produce Ok"
    );
}

#[test]
fn test_3b_incompatible_wat_produces_error() {
    let results = scenario_3b_error_incompatible_wat();
    assert_eq!(results.len(), 1);
    assert!(
        matches!(results[0], ContractResult::Error(_)),
        "incompatible WAT middleware should produce Error, got {:?}",
        results[0]
    );
}