ic-wire 0.31.1

Bounded Serde/Postcard encoding with schema and TypeScript generation
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
//! Metadata and TypeScript declarations for bounded branch recovery.
#![cfg(feature = "typescript")]

use ic_wire::typescript::{GenerationError, SchemaLimits, ValidatedRegistry};
use serde_json::{Value, json};
use std::collections::BTreeMap;

fn registry(value: Value) -> Result<ValidatedRegistry, GenerationError> {
    ValidatedRegistry::from_metadata(
        &BTreeMap::from([("Root".into(), value)]),
        SchemaLimits::default(),
    )
}

#[test]
fn bounded_optional_and_required_open_roundtrip_with_different_presence_semantics() {
    let value = json!({"k":"recover","item":{"k":"open-variant","required":true,"variants":[
        {"name":"Active","id":1,"value":{"k":"unit"}}
    ]}});
    let graph = registry(value.clone()).unwrap();
    let exported: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
    assert_eq!(exported, json!({"Root":value}));
    assert_eq!(
        graph.declarations().unwrap(),
        "export type Root = null | { readonly some: /* id 1 */ { readonly tag: \"Active\"; readonly value: null } };\n"
    );
    assert_eq!(
        registry(json!({"k":"open-variant","variants":[]}))
            .unwrap()
            .declarations()
            .unwrap(),
        "export type Root = null;\n"
    );
    assert_eq!(
        registry(json!({"k":"open-variant","required":true,"variants":[]}))
            .unwrap()
            .declarations()
            .unwrap(),
        "export type Root = never;\n"
    );
}

#[test]
fn recovery_metadata_requires_explicit_well_formed_kinds() {
    for value in [
        json!({"k":"recover"}),
        json!({"k":"option","item":{"k":"bool"},"required":true}),
        json!({"k":"open-variant","required":"true","variants":[]}),
        json!({"k":"open-variant","required":true,"variants":[
            {"name":"Zero","id":0,"value":{"k":"unit"}}
        ]}),
        json!({"k":"open-variant","required":true,"variants":[
            {"name":"TooLarge","id":2147483648_u32,"value":{"k":"unit"}}
        ]}),
    ] {
        assert_eq!(registry(value).unwrap_err(), GenerationError::Schema);
    }
}

#[test]
fn extension_tuple_admits_only_contiguous_optional_tail_slots() {
    let slot = |id: u32, name: &str, required: bool| json!({"id":id,"name":name,"required":required,"value":{"k":"unit"}});
    let schema = |extensions| {
        json!({
            "k": "extension-tuple",
            "items": [{"k": "u", "bits": 8}],
            "extensions": extensions,
        })
    };
    let value = schema(vec![slot(2, "seen", false), slot(3, "confirmed", false)]);
    let graph = registry(value.clone()).unwrap();
    let exported: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
    assert_eq!(exported, json!({"Root":value}));
    assert_eq!(
        graph.declarations().unwrap(),
        "export type Root = readonly [/* u8 */ number, null | { readonly some: null }, null | { readonly some: null }];\n"
    );
    for extensions in [
        vec![slot(1, "overlap", false)],
        vec![slot(3, "gap", false)],
        vec![slot(2, "required", true)],
        vec![slot(2, "duplicate_id", false), slot(2, "other", false)],
        vec![
            slot(2, "duplicate_name", false),
            slot(3, "duplicate_name", false),
        ],
        vec![slot(2, "first", false), slot(4, "gap", false)],
    ] {
        assert_eq!(
            registry(schema(extensions)).unwrap_err(),
            GenerationError::Schema
        );
    }
    assert_eq!(
        registry(json!({"k":"extension-tuple","items":[],"extensions":[slot(1, "unit", false)]}))
            .unwrap()
            .declarations()
            .unwrap(),
        "export type Root = readonly [null | { readonly some: null }];\n"
    );
}

#[test]
fn fixed_annotations_roundtrip_without_changing_type_declarations() {
    for mut value in [
        json!({"k":"record","fields":[{"name":"flag","value":{"k":"bool"}}]}),
        json!({"k":"tuple","items":[{"k":"bool"},{"k":"unit"}]}),
    ] {
        let declaration = registry(value.clone()).unwrap().declarations().unwrap();
        value["fixed"] = json!(true);
        let graph = registry(value.clone()).unwrap();
        assert_eq!(graph.declarations().unwrap(), declaration);
        let exported: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
        assert_eq!(exported, json!({"Root":value}));
        for malformed in [json!(false), json!("true")] {
            value["fixed"] = malformed;
            assert_eq!(
                registry(value.clone()).unwrap_err(),
                GenerationError::Schema
            );
        }
    }
    assert_eq!(
        registry(json!({"k":"extension-record","fields":[],"extensions":[],"fixed":true}))
            .unwrap_err(),
        GenerationError::Schema
    );
}

#[test]
fn projected_annotations_apply_only_to_extension_layouts() {
    for mut value in [
        json!({"k":"extension-record","fields":[],"extensions":[]}),
        json!({"k":"extension-tuple","items":[],"extensions":[]}),
    ] {
        let declarations = registry(value.clone()).unwrap().declarations().unwrap();
        value["projected"] = json!(true);
        let graph = registry(value.clone()).unwrap();
        assert_eq!(graph.declarations().unwrap(), declarations);
        let exported: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
        assert_eq!(exported, json!({"Root":value}));
        value["projected"] = json!(false);
        assert_eq!(registry(value).unwrap_err(), GenerationError::Schema);
    }
    assert_eq!(
        registry(json!({"k":"record","fields":[],"projected":true})).unwrap_err(),
        GenerationError::Schema
    );
}

#[cfg(feature = "derive")]
#[test]
fn fixed_derive_marks_local_aggregates_without_implicit_claims_about_children() {
    use ic_wire::typescript::Wire;

    struct Child;
    impl Wire for Child {
        fn schema(_: &mut ic_wire::typescript::SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"record","fields":[{"name":"value","value":{"k":"bool"}}]}))
        }
    }

    #[allow(dead_code)]
    #[derive(Wire)]
    #[wire(fixed)]
    enum Layout {
        Named { child: Child },
        Tuple(bool, ()),
        Wrapped(Child),
    }

    let graph = ValidatedRegistry::from_type::<Layout>("Root", SchemaLimits::default()).unwrap();
    let exported: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
    let variants = exported["Root"]["variants"].as_array().unwrap();
    assert_eq!(variants[0]["value"]["fixed"], true);
    assert_eq!(variants[1]["value"]["fixed"], true);
    assert!(
        variants[0]["value"]["fields"][0]["value"]
            .get("fixed")
            .is_none()
    );
    assert!(variants[2]["value"].get("fixed").is_none());
}

#[cfg(feature = "evolution")]
mod typed_methods {
    use super::*;
    use core::marker::PhantomData;
    use ic_wire::{
        Limits,
        evolution::{__private::EvolvingSchema, Method},
        typescript::{PayloadLimits, SchemaContext, SchemaRegistry, Wire},
    };

    const RUST_LIMITS: Limits = Limits {
        bytes: 42,
        allocation: 1024,
        nodes: 80,
        depth: 6,
    };
    const BROWSER_LIMITS: PayloadLimits = PayloadLimits {
        bytes: 31,
        nodes: 8,
        depth: 3,
    };

    struct Root<T>(PhantomData<T>);
    impl<T: Wire> EvolvingSchema for Root<T> {
        fn describe(context: &mut SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"extension-record","fields":[],"extensions":[{
                "name":"details","id":2,"required":false,"value":context.describe::<T>()?
            }]}))
        }
    }

    struct PlainRoot;
    impl EvolvingSchema for PlainRoot {
        fn describe(context: &mut SchemaContext) -> Result<Value, GenerationError> {
            context.describe::<Fixed>()
        }
    }

    struct Nested<T>(PhantomData<T>);
    impl<T: Wire> Wire for Nested<T> {
        fn schema(context: &mut SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"enum","variants":[{
                "name":"Values","id":0,"value":context.describe::<Result<Vec<Option<T>>, ()>>()?
            }]}))
        }
    }

    struct Fixed;
    impl Wire for Fixed {
        fn schema(context: &mut SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"record","fixed":true,"fields":[{
                "name":"next","value":context.describe::<Option<Box<Self>>>()?
            }]}))
        }
    }

    struct Unmarked;
    impl Wire for Unmarked {
        fn schema(_: &mut SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"tuple","items":[{"k":"bool"},{"k":"unit"}]}))
        }
    }

    struct Opaque;
    impl Wire for Opaque {
        fn schema(_: &mut SchemaContext) -> Result<Value, GenerationError> {
            Ok(json!({"k":"record","fixed":true,"fields":[{
                "name":"recover","value":{"k":"recover","item":{"k":"unit"}}
            }]}))
        }
    }

    struct Extension<const PROJECTED: bool>;
    impl<const PROJECTED: bool> Wire for Extension<PROJECTED> {
        fn schema(_: &mut SchemaContext) -> Result<Value, GenerationError> {
            let mut shape = json!({"k":"extension-record","fields":[],"extensions":[]});
            if PROJECTED {
                shape["projected"] = json!(true);
            }
            Ok(shape)
        }
    }

    struct BothPaths;
    impl EvolvingSchema for BothPaths {
        fn describe(context: &mut SchemaContext) -> Result<Value, GenerationError> {
            let item = context.describe::<Vec<Option<Extension<true>>>>()?;
            Ok(json!({"k":"extension-record","fields":[
                {"name":"fixed","value":{"k":"record","fixed":true,"fields":[
                    {"name":"items","value":item}
                ]}},
                {"name":"projected","value":item}
            ],"extensions":[]}))
        }
    }

    fn collected<T: EvolvingSchema>(
        method: &Method<T, T>,
    ) -> Result<ValidatedRegistry, GenerationError> {
        let mut registry = SchemaRegistry::new(SchemaLimits::default())?;
        // Ordinary registration remains available and does not impose typed rules.
        registry.register::<Unmarked>("Unrelated")?;
        let descriptor = registry.register_evolving_method(
            method,
            "client",
            ("Both", BROWSER_LIMITS),
            ("Both", BROWSER_LIMITS),
        )?;
        assert_eq!(descriptor.export, "client");
        assert_eq!(descriptor.id, method.id());
        assert_eq!(descriptor.request_limits.nodes, BROWSER_LIMITS.nodes);
        let graph = registry.finish()?;
        assert!(
            graph
                .method_module(&[descriptor], "./runtime.ts", &BTreeMap::new(), |_| {})?
                .contains("export const client")
        );
        Ok(graph)
    }

    #[test]
    fn typed_roots_allow_fixed_recursion_and_reject_unprojected_nested_layouts() {
        collected(&Method::<Root<Nested<Fixed>>, _>::new(
            "canister_export",
            RUST_LIMITS,
            RUST_LIMITS,
        ))
        .unwrap();
        assert_eq!(
            collected(&Method::<Root<Nested<Unmarked>>, _>::new(
                "a",
                RUST_LIMITS,
                RUST_LIMITS
            ))
            .unwrap_err(),
            GenerationError::Schema
        );
        assert_eq!(
            collected(&Method::<Root<Nested<Opaque>>, _>::new(
                "a",
                RUST_LIMITS,
                RUST_LIMITS
            ))
            .unwrap_err(),
            GenerationError::Schema
        );
        assert_eq!(
            collected(&Method::<PlainRoot, _>::new("a", RUST_LIMITS, RUST_LIMITS)).unwrap_err(),
            GenerationError::Schema
        );
    }

    #[test]
    fn typed_roots_project_nested_containers_but_preserve_fixed_boundaries() {
        type Containers<const PROJECTED: bool> =
            Root<Result<Vec<Option<Extension<PROJECTED>>>, ()>>;
        collected(&Method::<Containers<true>, _>::new(
            "a",
            RUST_LIMITS,
            RUST_LIMITS,
        ))
        .unwrap();

        assert_eq!(
            collected(&Method::<Containers<false>, _>::new(
                "a",
                RUST_LIMITS,
                RUST_LIMITS,
            ))
            .unwrap_err(),
            GenerationError::Schema
        );
        assert_eq!(
            collected(&Method::<BothPaths, _>::new("a", RUST_LIMITS, RUST_LIMITS)).unwrap_err(),
            GenerationError::Schema
        );
        assert_eq!(
            collected(&Method::<Root<Nested<Extension<true>>>, _>::new(
                "a",
                RUST_LIMITS,
                RUST_LIMITS,
            ))
            .unwrap_err(),
            GenerationError::Schema
        );
    }

    #[test]
    fn typed_method_aliases_cannot_bind_different_layouts() {
        let mut registry = SchemaRegistry::new(SchemaLimits::default()).unwrap();
        let method = Method::<Root<bool>, Root<()>>::new("a", RUST_LIMITS, RUST_LIMITS);
        assert_eq!(
            registry
                .register_evolving_method(
                    &method,
                    "client",
                    ("Both", BROWSER_LIMITS),
                    ("Both", BROWSER_LIMITS),
                )
                .unwrap_err(),
            GenerationError::Schema
        );
        assert_eq!(registry.finish().unwrap_err(), GenerationError::Schema);
    }

    #[cfg(all(
        feature = "platform-types",
        any(feature = "derive", feature = "evolution-derive")
    ))]
    #[test]
    fn typed_method_uses_the_published_account_layout_as_fixed() {
        use ic_platform_types::{Account, Principal};
        #[derive(ic_wire::Wire)]
        struct Payment {
            account: Account,
        }

        let limits = Limits {
            allocation: 8192,
            ..RUST_LIMITS
        };
        let method = Method::<Payment, Payment>::new("pay", limits, limits);
        let graph = collected(&method).unwrap();
        let metadata: Value = serde_json::from_str(&graph.metadata_json().unwrap()).unwrap();
        assert_eq!(
            metadata[SchemaRegistry::type_label::<Account>()]["fixed"],
            true
        );

        let payment = Payment {
            account: Account {
                owner: Principal::anonymous(),
                subaccount: None,
            },
        };
        let mut output = Vec::new();
        method
            .encode_request(&payment, &mut output, &mut [])
            .unwrap();
        assert_eq!(&output[11..], &[1, 4, 0, 0]);
        let decoded = method.decode_request(&output).unwrap();
        assert_eq!(decoded.account.owner, payment.account.owner);
        assert_eq!(decoded.account.subaccount, None);
    }
}