Skip to main content

bynk_check/wire_format/
reference.rs

1//! #1969: renders `reference/wire-format.md`, the published reference for wire
2//! format version 1.
3//!
4//! Every fact the page states that the compiler also uses is read from the
5//! compiler: the version, headers and check order from [`super`], the base-type
6//! encodings from [`crate::wire`], and the contract hash from
7//! [`crate::contract`], computed on [`EXAMPLE_SOURCE`]. The page's examples
8//! ([`EXAMPLES`]) are executed: `bynk-tests/tests/wire_reference.rs` compiles
9//! [`EXAMPLE_SOURCE`] to Workers, runs every example through the generated
10//! codecs on Node, and checks the emitted hashes and dispatch against this page.
11//! Regenerate the page with
12//! `BYNK_BLESS=1 cargo test -p bynk-tests --test it wire_reference::`.
13
14use std::collections::HashMap;
15use std::fmt::Write as _;
16use std::sync::Arc;
17
18use bynk_syntax::ast::{BaseType, CommonsItem, SourceUnit, TypeDecl};
19
20use super::{
21    ACCEPTED_WIRE_VERSIONS, CALL_CHECKS, CALL_METHOD, CALL_PATH_PREFIX, CALLER_HEADER,
22    CONTRACT_HEADER, EDGE_FROM_PREFIX, EDGE_TO_PREFIX, HEADERS, MAX_BODY_BYTES, SIGNATURE_HEADER,
23    SIGNATURE_WINDOW_SECONDS, SIGNING_SCHEME, TIMESTAMP_HEADER, WIRE_HEADER, WIRE_VERSION,
24    edge_key_from, edge_key_to, signing_input,
25};
26use crate::contract::{FNV1A64_OFFSET, FNV1A64_PRIME, contract_hash, service_normal_form};
27use crate::resolver::cross_context_service_for;
28use crate::wire::{
29    BaseGuard, JsonKind, MAX_RECURSIVE_NESTING, WIRE_DISCRIMINANT, field_base_guards, json_kind_of,
30};
31
32/// The context the page's examples and worked hash are computed on.
33pub const EXAMPLE_SOURCE: &str = r#"context wire.sample
34
35type Qty = Int where NonNegative
36
37type Shape =
38  | Circle(radius: Float)
39  | Dot
40
41type Line = {
42  sku: String,
43  qty: Int where Positive,
44  wait: Duration,
45  delay: Option[Duration],
46  at: Instant,
47  blob: Bytes,
48  note: Option[String],
49  tags: List[String],
50  stock: Map[String, Int],
51  rush: Bool,
52}
53
54type Price = Decimal where Positive
55
56service cost {
57  on call(unit: Price) -> Effect[Result[Price, String]] by Caller {
58    Ok(unit)
59  }
60}
61
62service quote {
63  on call(line: Line, size: Qty) -> Effect[Result[Shape, String]] by Caller {
64    Ok(Dot)
65  }
66}
67
68type Tagged[T] = {
69  n: Int where Positive,
70  v: T,
71}
72
73service who {
74  on call(t: Tagged[String]) -> Effect[Result[String, String]] by c: Caller {
75    Ok(c.identity)
76  }
77}
78
79service ping {
80  on call() -> Effect[Result[(), String]] by Caller {
81    Ok(())
82  }
83}
84
85actor Legacy { auth = Foreign(secret = "LEGACY_CALL_KEY") }
86
87service legacy {
88  on call(n: Int) -> Effect[Result[Int, String]] by Legacy {
89    Ok(n)
90  }
91}
92"#;
93
94/// What decoding an example's JSON does.
95pub enum Outcome {
96    /// Decodes, and the decoded value encodes back as this JSON.
97    Accepted { encodes_as: &'static str },
98    /// Refused with this error `kind` at this `path`.
99    Rejected {
100        kind: &'static str,
101        path: &'static str,
102    },
103}
104
105/// One executed example: `json` decoded as `ty`.
106pub struct Example {
107    /// The Bynk type, as the page shows it.
108    pub ty: &'static str,
109    /// The generated codec suffix the test drives (`__deserialise_<codec>`).
110    pub codec: &'static str,
111    pub json: &'static str,
112    pub outcome: Outcome,
113    pub note: &'static str,
114}
115
116const LINE: &str = r#"{"sku":"A-1","qty":2,"wait":1500,"delay":{"kind":"Some","value":250},"at":1767225600000,"blob":"aGk=","note":{"kind":"Some","value":"gift"},"tags":["new"],"stock":[["lon",3]],"rush":false}"#;
117
118/// The page's examples, each run through the generated codecs by
119/// `bynk-tests/tests/wire_reference.rs`.
120pub const EXAMPLES: &[Example] = &[
121    Example {
122        ty: "Line",
123        codec: "Line",
124        json: LINE,
125        outcome: Outcome::Accepted { encodes_as: LINE },
126        note: "Every field present. A record is an object keyed by field name.",
127    },
128    Example {
129        ty: "Line",
130        codec: "Line",
131        json: r#"{"sku":"A-1","qty":2,"wait":1500,"at":1767225600000,"blob":"","tags":[],"stock":[],"rush":true,"extra":1}"#,
132        outcome: Outcome::Accepted {
133            encodes_as: r#"{"sku":"A-1","qty":2,"wait":1500,"delay":{"kind":"None"},"at":1767225600000,"blob":"","note":{"kind":"None"},"tags":[],"stock":[],"rush":true}"#,
134        },
135        note: "An absent `Option` field is `None`. An unknown key is ignored.",
136    },
137    Example {
138        ty: "Line",
139        codec: "Line",
140        json: r#"{"sku":"A-1","qty":2,"wait":1500,"at":1767225600000,"blob":"","note":"gift","tags":[],"stock":[],"rush":true}"#,
141        outcome: Outcome::Accepted {
142            encodes_as: r#"{"sku":"A-1","qty":2,"wait":1500,"delay":{"kind":"None"},"at":1767225600000,"blob":"","note":{"kind":"Some","value":"gift"},"tags":[],"stock":[],"rush":true}"#,
143        },
144        note: "A bare value where an `Option` is expected is `Some`.",
145    },
146    Example {
147        ty: "Line",
148        codec: "Line",
149        json: r#"{"sku":"A-1","qty":0,"wait":1500,"at":1767225600000,"blob":"","tags":[],"stock":[],"rush":true}"#,
150        outcome: Outcome::Rejected {
151            kind: "RefinementViolation",
152            path: "$.qty",
153        },
154        note: "An inline field refinement (`qty: Int where Positive`) is checked.",
155    },
156    Example {
157        ty: "Line",
158        codec: "Line",
159        json: r#"{"sku":"A-1","qty":1.5,"wait":1500,"at":1767225600000,"blob":"","tags":[],"stock":[],"rush":true}"#,
160        outcome: Outcome::Rejected {
161            kind: "StructuralMismatch",
162            path: "$.qty",
163        },
164        note: "An `Int` is a whole number.",
165    },
166    Example {
167        ty: "Line",
168        codec: "Line",
169        json: r#"{"sku":"A-1","qty":2,"wait":1.5,"at":1767225600000,"blob":"","tags":[],"stock":[],"rush":true}"#,
170        outcome: Outcome::Rejected {
171            kind: "StructuralMismatch",
172            path: "$.wait",
173        },
174        note: "A `Duration` is whole milliseconds.",
175    },
176    Example {
177        ty: "Line",
178        codec: "Line",
179        json: r#"{"sku":"A-1","qty":2,"wait":1500,"delay":{"kind":"Some","value":0.5},"at":1767225600000,"blob":"","tags":[],"stock":[],"rush":true}"#,
180        outcome: Outcome::Rejected {
181            kind: "StructuralMismatch",
182            path: "$.delay.value",
183        },
184        note: "So is a `Duration` inside an `Option`, a `List` or a variant.",
185    },
186    Example {
187        ty: "Line",
188        codec: "Line",
189        json: r#"{"sku":"A-1","qty":2,"wait":1500,"at":1767225600000,"blob":"%%","tags":[],"stock":[],"rush":true}"#,
190        outcome: Outcome::Rejected {
191            kind: "StructuralMismatch",
192            path: "$.blob",
193        },
194        note: "`Bytes` is padded base64.",
195    },
196    Example {
197        ty: "Line",
198        codec: "Line",
199        json: r#"{"sku":"A-1","qty":2,"wait":1500,"at":1767225600000,"blob":"","tags":[],"stock":{"lon":3},"rush":true}"#,
200        outcome: Outcome::Rejected {
201            kind: "StructuralMismatch",
202            path: "$.stock",
203        },
204        note: "A `Map` is an array of pairs, never an object.",
205    },
206    Example {
207        ty: "Qty",
208        codec: "Qty",
209        json: "-1",
210        outcome: Outcome::Rejected {
211            kind: "RefinementViolation",
212            path: "$",
213        },
214        note: "A named refined type is its base value, checked against its predicates.",
215    },
216    Example {
217        ty: "Price",
218        codec: "Price",
219        json: r#""12.50""#,
220        outcome: Outcome::Accepted {
221            encodes_as: r#""12.50""#,
222        },
223        note: "A `Decimal` is its canonical text, and keeps its scale: `\"12.50\"` re-encodes as `\"12.50\"`, not `\"12.5\"`.",
224    },
225    Example {
226        ty: "Price",
227        codec: "Price",
228        json: r#""1e3""#,
229        outcome: Outcome::Rejected {
230            kind: "StructuralMismatch",
231            path: "$",
232        },
233        note: "No exponent form: a `Decimal` is plain digits, so every client reads it exactly.",
234    },
235    Example {
236        ty: "Price",
237        codec: "Price",
238        json: r#""007""#,
239        outcome: Outcome::Rejected {
240            kind: "StructuralMismatch",
241            path: "$",
242        },
243        note: "The wire form is canonical, so a leading zero is refused. `Decimal.parse` in a program is lenient about it.",
244    },
245    Example {
246        ty: "Price",
247        codec: "Price",
248        json: "12.5",
249        outcome: Outcome::Rejected {
250            kind: "StructuralMismatch",
251            path: "$",
252        },
253        note: "A JSON number is refused: parsing it as a float is how money loses precision.",
254    },
255    Example {
256        ty: "Price",
257        codec: "Price",
258        json: r#""0.00""#,
259        outcome: Outcome::Rejected {
260            kind: "RefinementViolation",
261            path: "$",
262        },
263        note: "The text parses, then the refinement is checked on the decoded value.",
264    },
265    Example {
266        ty: "Tagged[String]",
267        codec: "Tagged_String",
268        json: r#"{"n":0,"v":"x"}"#,
269        outcome: Outcome::Rejected {
270            kind: "RefinementViolation",
271            path: "$.n",
272        },
273        note: "A generic record's inline refinements are checked in every instantiation.",
274    },
275    Example {
276        ty: "Shape",
277        codec: "Shape",
278        json: r#"{"kind":"Circle","radius":0.5}"#,
279        outcome: Outcome::Accepted {
280            encodes_as: r#"{"kind":"Circle","radius":0.5}"#,
281        },
282        note: "A variant's payload fields sit beside `kind`.",
283    },
284    Example {
285        ty: "Shape",
286        codec: "Shape",
287        json: r#"{"kind":"Circle","radius":1e999}"#,
288        outcome: Outcome::Rejected {
289            kind: "StructuralMismatch",
290            path: "$.radius",
291        },
292        note: "A `Float` is finite; `1e999` parses as infinity.",
293    },
294    Example {
295        ty: "Shape",
296        codec: "Shape",
297        json: r#"{"kind":"Square"}"#,
298        outcome: Outcome::Rejected {
299            kind: "StructuralMismatch",
300            path: "$",
301        },
302        note: "An unknown variant is refused.",
303    },
304    Example {
305        ty: "Result[Shape, String]",
306        codec: "Result_Shape_String",
307        json: r#"{"kind":"Ok","value":{"kind":"Dot"}}"#,
308        outcome: Outcome::Accepted {
309            encodes_as: r#"{"kind":"Ok","value":{"kind":"Dot"}}"#,
310        },
311        note: "",
312    },
313    Example {
314        ty: "Result[Shape, String]",
315        codec: "Result_Shape_String",
316        json: r#"{"kind":"Err","error":"sold out"}"#,
317        outcome: Outcome::Accepted {
318            encodes_as: r#"{"kind":"Err","error":"sold out"}"#,
319        },
320        note: "A domain error is a `200` carrying `Err`.",
321    },
322    Example {
323        ty: "Result[(), String]",
324        codec: "Result_Unit_String",
325        json: r#"{"kind":"Ok","value":null}"#,
326        outcome: Outcome::Accepted {
327            encodes_as: r#"{"kind":"Ok","value":null}"#,
328        },
329        note: "`()` is `null`.",
330    },
331];
332
333/// The page's worked contract-hash example: each `on call` service of
334/// [`EXAMPLE_SOURCE`] with its normal form and hash, in source order.
335pub fn example_contracts() -> Vec<(String, String, String)> {
336    let tokens = bynk_syntax::lexer::tokenize(EXAMPLE_SOURCE).expect("the example source lexes");
337    let unit = match bynk_syntax::parser::parse_unit(&tokens, EXAMPLE_SOURCE) {
338        Ok(SourceUnit::Context(c)) => c,
339        other => panic!("the example source is a context: {other:?}"),
340    };
341    let types: HashMap<String, Arc<TypeDecl>> = unit
342        .items
343        .iter()
344        .filter_map(|i| match i {
345            CommonsItem::Type(t) => Some((t.name.name.clone(), Arc::new(t.clone()))),
346            _ => None,
347        })
348        .collect();
349    unit.items
350        .iter()
351        .filter_map(|i| match i {
352            CommonsItem::Service(s) => cross_context_service_for(&s.name.name, s),
353            _ => None,
354        })
355        .map(|svc| {
356            let form = service_normal_form(&svc, &types);
357            let hash = contract_hash(&form);
358            (svc.name, form, hash)
359        })
360        .collect()
361}
362
363fn json_kind_name(k: JsonKind) -> &'static str {
364    match k {
365        JsonKind::Number => "number",
366        JsonKind::String => "string",
367        JsonKind::Boolean => "boolean",
368        JsonKind::Object => "object",
369        JsonKind::Array => "array",
370        JsonKind::Null => "null",
371    }
372}
373
374/// The base-type rows of the encoding table, read off [`crate::wire`]'s model:
375/// the JSON kind each base type wires as and the guards its decode applies.
376fn base_type_rows(out: &mut String) {
377    const BASES: [(BaseType, &str); 8] = [
378        (BaseType::Int, "an integer"),
379        (BaseType::Float, "a number"),
380        (BaseType::Bool, "`true` or `false`"),
381        (BaseType::String, "a string"),
382        (
383            BaseType::Bytes,
384            "standard base64 with padding (RFC 4648 §4)",
385        ),
386        (BaseType::Decimal, "plain decimal text, such as `\"12.50\"`"),
387        (BaseType::Duration, "whole milliseconds"),
388        (BaseType::Instant, "milliseconds since the Unix epoch"),
389    ];
390    for (base, value) in BASES {
391        let kind = json_kind_of(base);
392        let rule = if base == BaseType::Bytes {
393            "valid base64; anything else is `StructuralMismatch` (`expected: \"base64 string\"`)"
394                .to_string()
395        } else if base == BaseType::Decimal {
396            "an optional `-`, digits with no leading zero (`0` or `1`-`9` first), and optionally `.` and digits (at most 1000 characters and 100 fraction digits, the most any `Decimal` has); an exponent, a leading `+`, a leading zero (`007`), whitespace, `.5` or `5.` is `StructuralMismatch` (`expected: \"decimal string\"`), and so is a JSON number. The scale is the number of fraction digits written, and is kept"
397                .to_string()
398        } else {
399            let mut rule = format!("JSON {}", json_kind_name(kind));
400            for guard in field_base_guards(base) {
401                rule.push_str(match guard {
402                    BaseGuard::Integral => {
403                        ", and `Number.isSafeInteger` (whole, within ±(2^53 − 1)); otherwise `StructuralMismatch` (`expected: \"safe integer\"`)"
404                    }
405                    BaseGuard::Finite => {
406                        ", and finite; otherwise `StructuralMismatch` (`expected: \"finite number\"`)"
407                    }
408                });
409            }
410            rule
411        };
412        let encode = match base {
413            BaseType::Int | BaseType::Duration | BaseType::Instant => {
414                "an unsafe value throws in the sender (a `500`), never a lossy number"
415            }
416            BaseType::Float => "a non-finite value throws in the sender",
417            _ => "as is",
418        };
419        let _ = writeln!(
420            out,
421            "| `{}` | {} ({value}) | {rule} | {encode} |",
422            base.name(),
423            json_kind_name(kind),
424        );
425    }
426}
427
428fn status_rows(out: &mut String) {
429    for (i, check) in CALL_CHECKS.iter().enumerate() {
430        let response = check.response();
431        let _ = writeln!(
432            out,
433            "| {} | {} | `{}` | {response} |",
434            i + 1,
435            check.condition(),
436            check.status(),
437        );
438    }
439}
440
441/// The whole page, in mdBook form (`# H1` title, relative `.md` links).
442pub fn render_reference() -> String {
443    let mut out = String::new();
444    let accepted = ACCEPTED_WIRE_VERSIONS
445        .iter()
446        .map(|v| format!("`{v}`"))
447        .collect::<Vec<_>>()
448        .join(", ");
449
450    let from_example = edge_key_from("shop.orders").unwrap_or_default();
451    let to_example = edge_key_to("shop.payment").unwrap_or_default();
452    let input_example = signing_input(
453        "shop.orders",
454        "shop.payment",
455        CALL_METHOD,
456        &format!("{CALL_PATH_PREFIX}authorise"),
457        "0123456789abcdef",
458        "1",
459        "1760000000",
460        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
461    );
462    let _ = write!(
463        out,
464        r#"# Wire format (version {WIRE_VERSION})
465
466<!-- GENERATED FILE — do not edit by hand.
467     Source: bynk-check/src/wire_format.rs and wire_format/reference.rs, via bynk-tests/tests/wire_reference.rs.
468     Regenerate with: BYNK_BLESS=1 cargo test -p bynk-tests --test it wire_reference:: -->
469
470How one Bynk context calls another context's `on call` service over a
471Cloudflare Service Binding: the request, the checks the callee makes, the
472responses, the JSON encoding of every type that can cross, and the contract
473hash. Code that is not Bynk can call a Bynk service by speaking this format.
474
475This page is generated from the compiler. The header names, the check order
476and the status codes are the constants the emitter builds the call dispatch
477from; the encoding table is read from the compiler's wire model; and every
478example below is run through the codecs the compiler generates for the
479example context, by `bynk-tests/tests/wire_reference.rs`.
480
481## Version and stability
482
483This is wire format version **{WIRE_VERSION}**. It is versioned on its own, not
484with the compiler: a compiler release changes it only by adding a new wire
485version.
486
487- **Within a version, changes are additive only.** A new status code, a new
488  error `kind` or a new optional header may appear. A caller must treat an
489  error `kind` it does not know as an error.
490- **Anything else is a new version:** changing an encoding, a check, a status,
491  an existing error body, or the contract hash's normal form or function.
492- **The caller states its version** in `{WIRE_HEADER}`; an absent header means
493  `1`. **The callee accepts a range** (this compiler's callees accept
494  {accepted}) and refuses any other version with the versions it accepts, so a
495  version is retired after an overlap window, not on a flag day.
496- **The signature is part of the version:** its headers, its signing input
497  and its window. The keys are not; they belong to a deployment.
498
499What the format does **not** cover: the TypeScript the compiler emits, the
500in-memory representation of values, and the Worker's other entry points
501(`from http` routes, events, queues). Those follow the compiler's own version.
502
503## Request
504
505```text
506{CALL_METHOD} {CALL_PATH_PREFIX}<service>
507```
508
509`<service>` is the service's name as declared (`service quote` is
510`{CALL_PATH_PREFIX}quote`). The host is ignored: a Bynk caller sends
511`http://internal{CALL_PATH_PREFIX}<service>` over the Service Binding.
512
513| Header | Required | Meaning |
514|---|---|---|
515"#
516    );
517    for h in HEADERS {
518        let _ = writeln!(out, "| `{}` | {} | {} |", h.name, h.required, h.meaning);
519    }
520    let _ = write!(
521        out,
522        r#"
523**Body.** JSON, encoding the handler's parameters:
524
525- **no parameters:** any JSON value; Bynk callers send `{{}}`;
526- **one parameter:** the parameter's value itself, not wrapped;
527- **two or more:** an object keyed by parameter name. Unknown keys are ignored.
528
529So `on call(line: Line, size: Qty)` takes `{{"line": {{…}}, "size": 3}}`, and
530`on call(size: Qty)` takes `3`. Renaming or reordering parameters is a contract
531change (see [Contract hash](#contract-hash)).
532
533## Checks and responses
534
535The callee makes these checks in this order. The first that fails answers the
536request.
537
538| # | Check | Status on failure | Body on failure |
539|---|---|---|---|
540"#
541    );
542    status_rows(&mut out);
543    let _ = write!(
544        out,
545        r#"
546If every check passes, the handler runs:
547
548- **`200`**, `content-type: application/json`, with the handler's return value
549  encoded as below. A domain error is a `200` too: `Result[T, E]`'s `Err` is a
550  value, not a status.
551- **`500`**, text `Internal Server Error`, if the handler faults (including
552  encoding a value the format cannot carry, such as an unsafe `Int`). The
553  callee logs the fault; the body says nothing more. The response carries
554  `X-Bynk-Fault: <context>`, the callee's qualified name, so the caller can
555  say which Worker faulted. Only a `/_bynk/call/` fault is marked.
556
557A status not listed here (a platform error between the Workers, for example)
558is a transport failure. A Bynk caller reports a `409` `ContractMismatch` and a
559marked `500` `CalleeFaulted` by name, and every other non-`2xx` as
560`Transport`, with the status.
561
562### Error bodies
563
564Every JSON error body is an object with a `kind`:
565
566| `kind` | Status | Fields |
567|---|---|---|
568| `UnsupportedWireVersion` | `400` | `accepted`: the wire versions the callee accepts |
569| `ContractMismatch` | `409` | `service`, `expected` (the callee's hash), `actual` (the header as received) |
570| `MalformedJson` | `400` | `details` |
571| `StructuralMismatch` | `400` | `path`, `expected`, `actual`: the value had the wrong shape |
572| `RefinementViolation` | `400` | `path`, `violation`: `{{"field", "message", "value"}}`, a value of the right shape broke a predicate |
573
574`path` is a JSONPath-like location in the body: `$` is the whole body (one
575parameter), `$.<param>` a parameter (several), then `.<field>` or `[<index>]`
576inward. An unknown variant fails at the sum's own `path`, with
577`expected: "sum variant kind"` and the `kind` that was sent as `actual`.
578
579## Encoding
580
581Each type has one JSON encoding, the same in both directions. A value is
582decoded by checking its shape, then any predicates.
583
584### Base types
585
586| Type | JSON | Decode accepts | Encode |
587|---|---|---|---|
588"#
589    );
590    base_type_rows(&mut out);
591    let _ = write!(
592        out,
593        r#"| `()` | `null` | anything; the value is not inspected | `null` |
594
595`Int`, `Duration` and `Instant` are limited to JavaScript's safe-integer range
596on the wire, so every JSON parser reads them exactly.
597
598### Composite types
599
600| Type | JSON |
601|---|---|
602| record | an object keyed by field name. A missing field decodes as its default when it has one, as `None` when it is an `Option`, and otherwise fails. Unknown keys are ignored. |
603| sum (`enum` included) | an object with `"{WIRE_DISCRIMINANT}"`: the variant's name, beside the variant's payload fields: `{{"{WIRE_DISCRIMINANT}":"Circle","radius":0.5}}`, `{{"{WIRE_DISCRIMINANT}":"Dot"}}` |
604| `Result[T, E]` | `{{"{WIRE_DISCRIMINANT}":"Ok","value":<T>}}` or `{{"{WIRE_DISCRIMINANT}":"Err","error":<E>}}` |
605| `Option[T]` | `{{"{WIRE_DISCRIMINANT}":"Some","value":<T>}}` or `{{"{WIRE_DISCRIMINANT}":"None"}}`. A sender may also send `null` or leave the field out for `None`, or send the bare value for `Some`; Bynk encodes the tagged form, except in a plain HTTP route and for `Json.encodePlain`, which write `v` / `null` (`Option[Option[T]]` is refused there) |
606| `List[T]` | an array |
607| `Map[K, V]` | an array of `[key, value]` pairs, in insertion order |
608| refined type (`type Qty = Int where NonNegative`) | its base type's encoding. The decoder checks the predicates, refusing with `RefinementViolation` |
609| opaque type | its base type's encoding. A caller cannot see the predicate, so only the owning context checks it |
610| inline field refinement (`qty: Int where Positive`) | the field's encoding. The decoder checks the predicates, like a refined type's |
611| generic instantiation (`Page[Line]`) | the declaration's encoding with the arguments substituted |
612
613The in-memory discriminant of a Bynk sum is `tag`; on the wire it is
614`"{WIRE_DISCRIMINANT}"`. The encoding never depends on the in-memory layout.
615
616**Recursive types.** A type that contains itself, directly or through other
617types, `Option`, `List` or `Map` (`type Tree = | Leaf | Node(left: Tree,
618right: Tree)`), has its declaration's encoding at every level. Nesting is
619bounded: each value of a recursive type on the way down from the outermost one
620is one level (a value of a non-recursive type is not counted, and below one the
621count starts again), and a value nested more than {MAX_RECURSIVE_NESTING} levels deep is refused with
622`StructuralMismatch` at the path where it crosses the bound, with
623`expected: "a value nested at most {MAX_RECURSIVE_NESTING} levels deep"`. A Bynk sender throws
624rather than encode such a value, so it never sends one.
625
626### Examples
627
628Each row is decoded by the codec the compiler generates for `wire.sample`
629below, then encoded again. Rejections show the error's `kind` and `path`.
630
631```bynk
632"#
633    );
634    out.push_str(EXAMPLE_SOURCE.trim_end());
635    out.push_str("\n```\n\n| Type | JSON sent | Outcome | Note |\n|---|---|---|---|\n");
636    for ex in EXAMPLES {
637        let outcome = match &ex.outcome {
638            Outcome::Accepted { encodes_as } if *encodes_as == ex.json => {
639                "accepted; encodes back the same".to_string()
640            }
641            Outcome::Accepted { encodes_as } => {
642                format!("accepted; encodes back as `{encodes_as}`")
643            }
644            Outcome::Rejected { kind, path } => format!("`{kind}` at `{path}`"),
645        };
646        let _ = writeln!(
647            out,
648            "| `{}` | `{}` | {outcome} | {} |",
649            ex.ty, ex.json, ex.note
650        );
651    }
652
653    let contracts = example_contracts();
654    let _ = write!(
655        out,
656        r#"
657## Contract hash
658
659`X-Bynk-Contract` carries a hash of the service's signature, so a callee can
660refuse a caller that was compiled against a different version of it (`409`).
661It detects skew; it is not a credential and not a security control.
662
663**Normal form.** One line per service:
664
665```text
666<service>(<param>: <type>, …) -> <type>
667```
668
669- Parameters keep their names and order. `Effect[T]` is written as `T`.
670- Base types are their names; `()` is `()`; `List[T]`, `Option[T]`,
671  `Map[K, V]`, `Result[T, E]` keep their arguments in order.
672- A named type is its name followed by its structure, so both a rename and a
673  change of shape change the hash:
674  - a record is `Name{{f: T, …}}`, each field written `f: T` (or
675    `f: T where P, …` with an inline refinement), the fields sorted by that
676    text's UTF-8 bytes and joined with `, `;
677  - a sum is `Name|A|B(f: T, …)`: each variant written as its name, followed
678    by its payload fields in parentheses if it has any, each written `f: T`
679    and sorted by that text's UTF-8 bytes (the wire keys a payload by field
680    name, so a renamed field changes the hash and a reordered one does not),
681    the variants sorted by that text's UTF-8 bytes, each preceded by `|`;
682  - a refined type is its name and base run together, then its predicates:
683    `type Qty = Int where NonNegative` is `QtyInt where NonNegative` (with no
684    predicates, `QtyInt ` with a trailing space);
685  - an opaque type is `NameBase opaque`, without its predicates;
686  - a generic instantiation is the declaration's form with the arguments
687    substituted, followed by `[A, …]`;
688  - a type met again inside its own expansion is `@Name`.
689- Predicates are a set: written as below, sorted by their UTF-8 bytes, with
690  duplicates removed, and joined with `, `. They are `Positive`,
691  `NonNegative`, `InRange(a, b)`, `InRangeF(a, b)`, `MinLength(n)`,
692  `MaxLength(n)`, `Length(n)`, `IsoDate` and `Matches("…")`; `NonEmpty` is written
693  `MinLength(1)`. Bounds are written as decimal numbers in their shortest
694  round-trip form (`01` is `1`). A `Matches` pattern is quoted, with `\`, `"`
695  and control characters backslash-escaped.
696- No spaces other than those shown; no doc comments, defaults, `given` or
697  `by` clauses.
698
699**Hash.** FNV-1a, 64-bit, over the normal form's UTF-8 bytes: start from the
700offset basis `0x{FNV1A64_OFFSET:016x}`; for each byte, XOR it in, then
701multiply by the prime `0x{FNV1A64_PRIME:016x}` modulo 2^64. The result is
702written as 16 lowercase hex digits.
703
704For `wire.sample` above, each service's normal form, byte for byte, and its
705hash:
706"#
707    );
708    for (name, form, hash) in &contracts {
709        let _ = write!(out, "\n`{name}`, hash `{hash}`:\n\n```text\n{form}\n```\n");
710    }
711    let _ = write!(
712        out,
713        r#"
714| Changes the hash | Does not |
715|---|---|
716| the service's name; a parameter's name, order or type; the return type | field order; variant order; predicate order or duplicates |
717| a field added, removed, renamed or retyped; a variant added, removed, renamed or re-shaped | an opaque type's predicates |
718| a refined type's or an inline field refinement's predicates | doc comments; `given`; `by c: Caller` |
719| renaming a named type | a default, or whether a field has one |
720
721The normal form and the hash function are part of the wire version: a client
722built once embeds hashes, so they change only with a new wire version.
723
724A field added with a default still changes the hash, but it is a **compatible**
725change: an old caller's body lacks the key, which the callee decodes to the
726default, and an unknown key is ignored the other way. `bynk deploy` classifies it
727as such ([Contract skew](/book/guides/projects-build-and-deployment/contract-skew/)).
728
729## Authentication
730
731Every call is signed. The callee refuses a call whose signature does not verify
732with a bare `401`, before it looks at anything but the method and the body's
733size, so a sender without a key learns nothing: not which services exist, not
734a contract hash.
735
736**Keys.** One key per *edge*, a caller and a callee. The callee holds it as
737`{EDGE_FROM_PREFIX}<CALLER>` and the caller as `{EDGE_TO_PREFIX}<CALLEE>`, where
738`<CALLER>` and `<CALLEE>` are the qualified context names upper-cased with each
739dot written `__` (`shop.orders` → `{from_example}`, `shop.payment` →
740`{to_example}`). A name the key can be named from is dot-separated segments of
741lowercase letters and digits, each starting with a letter, with single
742underscores between runs. `bynk deploy` mints each key and sets it on both
743Workers; `bynk dev` uses a fixed local key.
744
745**Signing.** The caller sends `{CALLER_HEADER}` (its qualified name),
746`{TIMESTAMP_HEADER}` (whole seconds since the Unix epoch) and `{SIGNATURE_HEADER}`:
747HMAC-SHA256, under the edge's key, of the *signing input*, written as 64
748lowercase hex digits. The signing input is these fields, one per line,
749separated by `\n` with no trailing newline:
750
7511. `{SIGNING_SCHEME}`
7522. the caller, as sent in `{CALLER_HEADER}`
7533. the callee's qualified context name
7544. the method
7555. the URL's pathname exactly as sent, with no query string and no
756   percent-normalisation
7576. `{CONTRACT_HEADER}` as sent, empty when absent
7587. `{WIRE_HEADER}` as sent, `1` when absent
7598. `{TIMESTAMP_HEADER}` as sent
7609. the SHA-256 of the body's bytes, 64 lowercase hex digits
761
762For example, `shop.orders` calling `authorise` on `shop.payment` with an empty
763body signs:
764
765```text
766{input_example}
767```
768
769**Verifying.** The callee reads the body under its cap (1 MiB, {MAX_BODY_BYTES}
770bytes, else `413`), picks the key it holds for the edge from `{CALLER_HEADER}`,
771and refuses (`401`) when it holds none, when `{TIMESTAMP_HEADER}` is more than
772{SIGNATURE_WINDOW_SECONDS} seconds from its clock either way, or when the
773signature does not match, compared in constant time. So:
774
775- **A key's holder can claim only its own name.** A caller's name is the
776  handler's `c.identity`, proved by the key, not claimed.
777- **A key binds one callee.** The callee's name is signed, so a request cannot
778  be replayed against another callee, even one that holds the same key.
779- **Every header the callee acts on is signed**, so none can be changed in
780  flight: not the contract, not the wire version.
781- **A captured call can be replayed inside the window.** The timestamp bounds
782  replay; nothing stops it within those {SIGNATURE_WINDOW_SECONDS} seconds. An
783  `on call` handler with side effects that must happen once should make itself
784  idempotent (the `Idempotency` capability).
785- **An undeclared caller cannot call.** Without a key on the callee there is
786  nothing to verify against, whether or not the handler reads its caller.
787
788### Foreign callers
789
790Code that is not Bynk calls a context the same way, once the context declares
791it as a **foreign caller**:
792
793```text
794actor Legacy {{ auth = Foreign(secret = "LEGACY_CALL_KEY") }}
795
796service legacy {{
797  on call(n: Int) -> Effect[Result[Int, String]] by Legacy {{ Ok(n) }}
798}}
799```
800
801The foreign caller sends its actor's name (`Legacy`) as `{CALLER_HEADER}` and
802signs exactly as above, under the declared secret, which the callee holds as
803`LEGACY_CALL_KEY`. `bynk deploy` mints that secret and prints the
804`wrangler secret put` that hands it to the foreign Worker's operator. An
805actor's name starts with a capital letter, so it is never a context's: a
806foreign caller is checked under its own secret and can never pass for a Bynk
807context, nor a context for it.
808
809A verified caller still has to be one the service's handler admits. A Bynk
810context is admitted by `Caller` (the explicit "any consuming context"), a foreign caller
811only by its own actor; `by who: Caller | Legacy` admits both and tells them
812apart. Anyone else gets a bare `403`. A refinement over `Caller` (`actor Admin = Caller where IsContext(shop.admin)`) narrows which contexts that is: the handler admits the proven caller only if the refinement's predicate holds for it, and a context it does not name gets the same bare `403` even though its signature verifies. The compiler also refuses such a call where it is written, but this check stays, because the keys are per pair of contexts and a caller from before the restriction may still be deployed.
813
814A TypeScript Worker need not speak any of this by hand. For each context with
815a foreign caller the build emits a typed client, `bynk-client.ts`, which
816signs, stamps the contract hash and encodes exactly as this page describes;
817see [TypeScript client](/reference/typescript-client/).
818"#
819    );
820    out
821}