myrmic-common 0.7.0

Wire types shared across the Myrmic WASM host/guest boundary (db, cells, BLE, web), plus the host-only code generator behind myrmic-sdk-macros and the cell build tooling.
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
use super::*;
use crate::codegen::bridge_api::{UserHttpBridgeApi, UserMqttBridge};

/// Pretty-prints a generated token stream, asserting it is syntactically valid
/// Rust in the process.
fn render(tokens: Ts) -> String {
    let file: syn::File =
        syn::parse2(tokens).expect("generated tokens should be a valid Rust file");
    prettyplease::unparse(&file)
}

fn root() -> Ts {
    quote! { ::myrmic_sdk }
}

/// Asserts the generated code is self-contained: every `std`/`serde` path is
/// routed through `myrmic_sdk::codegen::exports`, and no bare `alloc`-prelude type
/// names survive — so a cell needs no dependency beyond `myrmic-sdk`.
fn assert_self_contained(out: &str) {
    assert!(
        out.contains("::myrmic_sdk::codegen::exports::serde::Serialize"),
        "serde derive not routed through exports:\n{out}"
    );
    assert!(
        out.contains("#[serde(crate = \""),
        "missing #[serde(crate = ...)] attr:\n{out}"
    );
    // Strip the legitimate routed prefixes; anything left pointing at ::std /
    // ::serde would fail to compile in a cell.
    let stripped = out
        .replace("codegen::exports::std", "")
        .replace("codegen::exports::serde", "")
        .replace("codegen::exports::chrono", "")
        .replace("codegen::exports::uuid", "");
    assert!(!stripped.contains("::std::"), "unrouted ::std path:\n{out}");
    assert!(
        !stripped.contains("::serde"),
        "unrouted ::serde path:\n{out}"
    );
    assert!(
        !stripped.contains("::chrono"),
        "unrouted ::chrono path:\n{out}"
    );
    assert!(!stripped.contains("::uuid"), "unrouted ::uuid path:\n{out}");
    // typify's ConversionError boilerplate uses bare `String` (trait arg + fn
    // param); both must have been qualified.
    assert!(
        !out.contains("From<String>"),
        "bare String (trait arg):\n{out}"
    );
    assert!(
        !out.contains("value: String"),
        "bare String (fn param):\n{out}"
    );
}

const HTTP_SPEC: &str = r#"
name: http
base_url: http://localhost:10000
types:
  definitions:
    SendMessageRequest:
      type: object
      required: [message]
      properties:
        message:
          type: string
    TestResponse:
      type: object
      required: [body]
      properties:
        body:
          type: string
endpoints:
  - id: send_message
    request:
      method: POST
      path: /messages
      body: "${json:SendMessageRequest}"
    response:
      200: "${json:TestResponse}"
  - id: test
    request:
      method: GET
      path: /test
    response:
      200: "${json:TestResponse}"
"#;

const MQTT_SPEC: &str = r#"
name: mqtt
broker_url: mqtt://localhost:11000
ingress:
  - id: receive_request
    topic: e2e/test/ingress
    payload: "${json:data}"
egress:
  - id: publish_response
    topic: "${db:e2e/test/data@topic}"
    payload: "${json:data}"
"#;

#[test]
fn http_bridge_generates_typify_types_and_a_method_per_endpoint() {
    let api: UserHttpBridgeApi = serde_yaml::from_str(HTTP_SPEC).expect("parse http spec");
    let out = render(http_bridge(&root(), api).expect("generate http bridge"));

    // Types come from the JSON Schema, generated by typify.
    assert!(out.contains("pub struct SendMessageRequest"), "{out}");
    assert!(out.contains("pub struct TestResponse"), "{out}");
    // String is routed through our re-export, not `::std`/`::alloc` directly.
    assert!(
        out.contains("pub message: ::myrmic_sdk::codegen::exports::std::string::String"),
        "{out}"
    );

    // One client, one method per endpoint. The request body is a positional
    // arg; every method ends in a callback typed to the endpoint's Reply.
    assert!(out.contains("pub struct HttpClient"), "{out}");
    assert!(out.contains("pub fn send_message("), "{out}");
    assert!(out.contains("body: &SendMessageRequest"), "{out}");
    assert!(
        out.contains("cb: ::myrmic_sdk::Callback<SendMessageReply>"),
        "{out}"
    );
    // The no-arg endpoint still takes a callback.
    assert!(out.contains("pub fn test("), "{out}");
    assert!(
        out.contains("cb: ::myrmic_sdk::Callback<TestReply>"),
        "{out}"
    );

    // Each endpoint gets a Reply enum: one variant per status code (`200` -> `Ok`)
    // carrying that status's body, plus an `Unknown(u16)` catch-all.
    assert!(out.contains("pub enum SendMessageReply"), "{out}");
    assert!(out.contains("pub enum TestReply"), "{out}");
    assert!(out.contains("Ok(TestResponse)"), "{out}");
    assert!(out.contains("Unknown(u16)"), "{out}");

    // The command carries the generated wire payload, not the body directly.
    assert!(
        out.contains("send(sri, \"send_message\", &__payload)"),
        "{out}"
    );

    assert_self_contained(&out);
}

#[test]
fn http_request_payload_is_json_keyed_by_name_not_postcard() {
    let api: UserHttpBridgeApi = serde_yaml::from_str(HTTP_SPEC).expect("parse http spec");
    let out = render(http_bridge(&root(), api).expect("generate http bridge"));

    // The request wire payload is a JSON object (the `#[derive(Message)]` default
    // codec), not a postcard tuple: the runtime decodes it by placeholder name.
    assert!(
        !out.contains("Postcard"),
        "request payload must not use the postcard codec:\n{out}"
    );

    // A `json` body rides as a nested JSON value (serialised via `to_value`) so
    // the runtime reads it back as an object — not a pre-stringified string.
    assert!(
        out.contains("to_value"),
        "json body should be stored via to_value:\n{out}"
    );
    assert!(
        !out.contains("to_string(body)"),
        "json body must not be pre-stringified:\n{out}"
    );

    // The body travels under the fixed `body` key (not the schema type name), so
    // the runtime — which resolves the HTTP body by that reserved key — matches.
    assert!(
        out.contains("body: ::myrmic_sdk::JsonValue"),
        "payload body field should be keyed `body`:\n{out}"
    );

    // The caller's callback command name rides as a reserved field in the object.
    assert!(out.contains("__callback"), "{out}");
}

#[test]
fn a_request_placeholder_named_callback_is_rejected() {
    // `__callback` is the reserved wire key for the caller's callback command;
    // a user placeholder of that name would collide with it, so it's an error.
    let spec = r#"
name: http
base_url: http://localhost
endpoints:
  - id: go
    request:
      method: GET
      path: "/go/${string:__callback}"
    response: {}
"#;
    let api: UserHttpBridgeApi = serde_yaml::from_str(spec).expect("parse spec");
    let err =
        http_bridge(&root(), api).expect_err("a placeholder named __callback must be rejected");
    assert!(err.contains("__callback"), "got: {err}");
}

#[test]
fn mqtt_bridge_generates_client_events_and_command_methods() {
    let api: UserMqttBridge = serde_yaml::from_str(MQTT_SPEC).expect("parse mqtt spec");
    let out = render(mqtt_bridge(&root(), api).expect("generate mqtt bridge"));

    assert!(out.contains("pub struct MqttClient"), "{out}");
    // Ingress -> event payload type with a CellEvent impl.
    assert!(out.contains("pub struct ReceiveRequest"), "{out}");
    assert!(
        out.contains("impl ::myrmic_sdk::CellEvent for ReceiveRequest"),
        "{out}"
    );
    // Egress -> fire-and-forget method carrying its payload type.
    assert!(out.contains("pub struct PublishResponse"), "{out}");
    assert!(
        out.contains("pub fn publish_response(&self, value: PublishResponse)"),
        "{out}"
    );
    assert_self_contained(&out);
}

const TYPED_HTTP_SPEC: &str = r##"
name: weather
base_url: "https://api.example.com"
types:
  definitions:
    Coordinates:
      type: object
      required: [lat, lon]
      properties:
        lat: { type: number, format: double }
        lon: { type: number, format: double }
    ForecastRequest:
      type: object
      required: [where, units]
      properties:
        where:
          $ref: "#/definitions/Coordinates"
        units:
          type: string
          enum: [metric, imperial]
    ForecastResponse:
      type: object
      required: [station_id, observed_at, summary, temp_c]
      properties:
        station_id: { type: string, format: uuid }
        observed_at: { type: string, format: date-time }
        summary: { type: string }
        temp_c: { type: number, format: double }
        humidity: { type: integer, format: uint32 }
endpoints:
  - id: get_forecast
    request:
      method: POST
      path: "/v1/forecast"
      body: "${json:ForecastRequest}"
      timeout_ms: 5000
    response:
      200: "${json:ForecastResponse}"
"##;

#[test]
fn richer_schema_bridge_spec_generates() {
    // A richer schema than HTTP_SPEC: a nested `$ref`, a string `enum`, and
    // integer/number formats.
    let api: UserHttpBridgeApi = serde_yaml::from_str(TYPED_HTTP_SPEC).expect("parse example spec");
    let out = render(http_bridge(&root(), api).expect("generate example bridge"));

    assert!(out.contains("pub struct Coordinates"), "{out}");
    assert!(out.contains("pub struct ForecastRequest"), "{out}");
    assert!(out.contains("pub struct ForecastResponse"), "{out}");
    assert!(out.contains("pub struct WeatherClient"), "{out}");
    assert!(out.contains("pub fn get_forecast("), "{out}");
    assert!(out.contains("body: &ForecastRequest"), "{out}");
    assert!(
        out.contains("cb: ::myrmic_sdk::Callback<GetForecastReply>"),
        "{out}"
    );
    // The response template becomes the Reply enum: `200` -> `Ok(ForecastResponse)`,
    // plus `Unknown(u16)`.
    assert!(out.contains("pub enum GetForecastReply"), "{out}");
    assert!(out.contains("Ok(ForecastResponse)"), "{out}");
    assert!(out.contains("Unknown(u16)"), "{out}");
    // Nested `$ref` resolves to the generated type, not an inline anon type.
    assert!(
        out.contains("pub whereField: Coordinates") || out.contains(": Coordinates"),
        "{out}"
    );
    // The enum became a real Rust enum.
    assert!(out.contains("pub enum") && out.contains("Metric"), "{out}");
    // `format: uuid` / `date-time` map to uuid/chrono, routed via exports.
    assert!(
        out.contains("::myrmic_sdk::codegen::exports::uuid::Uuid"),
        "uuid format not routed:\n{out}"
    );
    assert!(
        out.contains("::myrmic_sdk::codegen::exports::chrono::"),
        "date-time format not routed:\n{out}"
    );
    assert_self_contained(&out);
}

#[test]
fn json_body_without_a_matching_definition_falls_back_to_jsonvalue() {
    // A `${json:...}` body whose name is not a schema definition is an untyped
    // JSON passthrough — the method takes a `JsonValue`, not a named type.
    let spec = r"
name: http
base_url: http://localhost
types:
  definitions:
    Known:
      type: object
      properties:
        x: { type: string }
endpoints:
  - id: go
    request:
      method: POST
      path: /go
      body: '${json:not_a_definition}'
    response: {}
";
    let api: UserHttpBridgeApi = serde_yaml::from_str(spec).expect("parse spec");
    let out = render(http_bridge(&root(), api).expect("generate"));
    assert!(out.contains("pub fn go("), "{out}");
    assert!(out.contains("body: &::myrmic_sdk::JsonValue"), "{out}");
    assert!(out.contains("cb: ::myrmic_sdk::Callback<GoReply>"), "{out}");
}

#[test]
fn response_statuses_become_reply_enum_variants() {
    // A status with headers -> struct variant; a body-string shorthand -> tuple
    // variant; an empty entry -> unit variant; plus the `Unknown(u16)` catch-all.
    let spec = r#"
name: http
base_url: http://localhost
types:
  definitions:
    Ship:
      type: object
      properties:
        id: { type: string }
endpoints:
  - id: list_ships
    request:
      method: GET
      path: /ships
    response:
      200:
        headers:
          x-api-time: "${string:time}"
        body: "${json:Ship}"
      404: "${string:message}"
      204: {}
"#;
    let api: UserHttpBridgeApi = serde_yaml::from_str(spec).expect("parse spec");
    let out = render(http_bridge(&root(), api).expect("generate"));

    assert!(out.contains("pub enum ListShipsReply"), "{out}");
    // 200 with headers -> struct variant: a `String` header field, then `body`.
    assert!(out.contains("Ok {"), "{out}");
    assert!(out.contains("time: ::myrmic_sdk::String"), "{out}");
    assert!(out.contains("body: Ship"), "{out}");
    // 404 body-string shorthand -> tuple variant carrying the body.
    assert!(out.contains("NotFound(::myrmic_sdk::String)"), "{out}");
    // 204 empty entry -> unit variant.
    assert!(out.contains("NoContent"), "{out}");
    // Always an `Unknown(u16)` catch-all.
    assert!(out.contains("Unknown(u16)"), "{out}");
}

const HTTP_PARAMS_SPEC: &str = r#"
name: spacetraders
base_url: https://api.spacetraders.io
endpoints:
  - id: negotiate_contract
    request:
      method: POST
      path: "/my/ships/${string:ship}/negotiate/contract"
      headers:
        authorization: "Bearer ${db:keys/secrets/spacetraders@token}"
    response:
      200: "${json:body}"
"#;

#[test]
fn http_endpoint_with_path_param_generates_positional_arg_and_typed_callback() {
    let api: UserHttpBridgeApi = serde_yaml::from_str(HTTP_PARAMS_SPEC).expect("parse spec");
    let out = render(http_bridge(&root(), api).expect("generate http bridge"));

    // The response template becomes a generated `<Endpoint>Reply` enum: the `200`
    // entry is an `Ok` variant carrying the body which — `${json:body}` not being a
    // schema definition here — falls back to `JsonValue`; plus `Unknown(u16)`.
    assert!(out.contains("pub enum NegotiateContractReply"), "{out}");
    assert!(out.contains("Ok(::myrmic_sdk::JsonValue)"), "{out}");
    assert!(out.contains("Unknown(u16)"), "{out}");

    // The `${string:ship}` path placeholder becomes a positional `&str` arg
    // named `ship`; the db-only `authorization` header contributes no arg. The
    // callback is typed to the generated Reply.
    assert!(out.contains("pub fn negotiate_contract("), "{out}");
    assert!(out.contains("ship: &str"), "{out}");
    assert!(
        out.contains("cb: ::myrmic_sdk::Callback<NegotiateContractReply>"),
        "{out}"
    );

    assert_self_contained(&out);
}