Skip to content

Message contracts for library authors

This page is for anyone writing a Snodra library, in any language: it fixes what a library declares to a hub with its schema catalogue on, and how it must generate, compare and send the versions and schemas. After reading it you can give message types a version, produce the JSON Schema of a payload and of a response exactly as every other library does, fill Register.contracts and Register.event_contracts, put the version headers on every request and event, and react to the hub’s refusals. The hub’s side of the same rules (what it checks, stores and routes by) is in the hub protocol, Message contracts and, for operators, in the server’s schema catalogue page.

Status. This page is the specification, and every official library implements it. The rules are part of feature level 1: the conformance runner (contract version 2, runner v0.6.0 or later) checks the contract of every type a service declares (L1-CONTRACTS, L1-CONTRACT-VERSIONS), the version headers on every request (L1-VERSION-HEADERS), the empty Register of a drain (L1-EMPTY-CONTRACTS), the refusal of a contract (L1-CONTRACT-REFUSED) and what a hub’s catalogue shows (L1-CATALOGUE). The generated documents themselves are asserted by each library’s own tests against the golden schema, not by the runner.

Services in different languages. The libraries generate different documents for one type, so services in different languages that serve one type must declare the same checked-in schema for it (below).

A contract is (type, payload version, response version) for one command or query type, with the JSON Schema of the payload and of the response. An event contract is (type, payload version) and one schema.

  • Every message type has a version, a positive integer, 1 by default. A library declares it beside the type name (see the official libraries’ API).
  • A version below 1 is a registration error, found before the library connects.
  • A version is on the wire as ASCII [1-9][0-9]* that fits an unsigned 32-bit integer; a library never writes a leading zero, a sign or whitespace.
  • The version of a type is a promise about its schema: a changed schema needs a new version, because a hub refuses a Register whose contract is live with another schema (Refusals).

A handler’s payload is its request type. Its response depends on the kind of handler:

Handler Payload Response
command the command type the reply type
query (point or shared) the query type the reply type
streaming query the query type the item type of the stream
subscription query the query type the initial type and the update type together, in one document (below)

For each handled type the library declares one MessageContract:

Field Content
MessageContract.type, MessageContract.kind the type name of the request, and ContractKind.CONTRACT_KIND_COMMAND or ContractKind.CONTRACT_KIND_QUERY, the list the type is registered in
MessageContract.shared, MessageContract.subscription true exactly when the type is in Register.shared_query_types, respectively Register.subscription_query_types: the flags equal the lists
MessageContract.payload_version the version of the request type
MessageContract.response_version the version of the response type: of the reply type, the item type, or the initial type
MessageContract.payload_schema, MessageContract.response_schema the schemas, generated or overridden (The generated schema, Overrides)
MessageContract.schema_override true when the payload or the response schema is a checked-in one (Overrides)

A reply (or item, or initial) type that has no message-type name, for example a plain data class, has version 1.

The title of a document is what the schema’s title says, and the version is the one the contract carries. Both are fixed by what the type is:

Document Title Version
a payload the name of the request type the version of the request type
a reply or item type that has a message-type name its own name its own version
any other reply or item type: no content, a list, a plain structure <request type>.Response 1
a subscription response <request type>.Response, always the version of the initial type (1 when the initial type is a list or has no message-type name)

The override lookup uses the same title and the same version: the override of a document is the one registered for that title at that version.

A subscription handler answers with an initial result and then updates, each with its own type. Its response schema holds both, as nested schemas under $defs:

{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"…","type":"object",
"$defs":{"initial":{…},"update":{…}}}

The document describes the pair, not one type, so its title is always <request type>.Response.

initial and update are the nested forms of the two types (nested objects: no $schema, no title). The response version is the version of the initial type. initial and update describe the value, never null: a nullable initial or update type is written without its nullability.

A library declares one EventContract for each event type consumed by any of its processors and sagas, once per type:

  • the version and the schema come from the event type, by the same rules as a payload;
  • two handlers of one event type that disagree on the version or on the schema are a registration error, found before the library connects, naming the type and both handlers;
  • a service that only publishes an event type declares nothing for it.

Events are catalogued and never routed through the hub; the hub’s view is in the server’s schema catalogue page.

A library generates the schema of a type from its definition unless the type has an override. The document of a type named N is:

{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"N","type":"object","properties":{…},"required":[…]}
  • The document is the envelope {"$schema":…,"title":…} merged with the body of the type. A top-level type that is not an object keeps the body of its own type: a list reply is {"$schema":…,"title":…,"type":"array","items":X}. A top-level nullable type drops its nullability: the document describes the value, never null. A top-level any-JSON value is only $schema and title.
  • required lists every property that is not optional, sorted (by code point), and is omitted when empty.
  • There is no additionalProperties keyword on an object that comes from a type.
  • Property names are the wire names the library’s default codec writes for the type, not the names in the source (a renamed or camel-cased field appears under its renamed or camel-cased name).
  • A nullable field is also optional. A field with a default value is optional too (in Go, a field tagged omitempty or omitzero). So is a field the codec may leave out of the output, for example one annotated to skip nulls, empty values or default values.

Field schemas:

The field is Its schema
a string, a single character, a character array {"type":"string"}
any integer, of any width, signed, unsigned or big {"type":"integer"}
any float, any decimal, any untyped number {"type":"number"}
a boolean {"type":"boolean"}
a timestamp (below) {"type":"string","format":"date-time"}
a UUID {"type":"string","format":"uuid"}
bytes {"type":"string","contentEncoding":"base64"}
a list or array of X {"type":"array","items":X}
a set of X {"type":"array","items":X,"uniqueItems":true}
a map from string to X {"type":"object","additionalProperties":X}
a string enum, including an enum of the platform such as a day of the week {"type":"string","enum":[…]}, the values the codec writes for the constants, in declaration order
a nested object {"type":"object","properties":…,"required":…}, with no $schema and no title
any JSON value {}
nullable X {"anyOf":[X,{"type":"null"}]} (in Python, `X
nullable any-JSON {"anyOf":[{},{"type":"null"}]}, and the field is optional
a transparent wrapper of X the schema of X

A timestamp is the one date-and-time type of each language that the codec writes as an ISO 8601 string:

Language Timestamp types
Kotlin java.time.Instant, java.time.OffsetDateTime, java.time.ZonedDateTime
Rust chrono::DateTime
Go time.Time
Python datetime.datetime, written in UTC with a trailing Z

A type that a language’s own date and time library provides is a timestamp only when it is in this table and the codec writes it as a string. In Kotlin, kotlin.time.Instant is not: the default codec writes it as an object, so it is refused. Every other date, time, zone, offset or duration type is refused: local dates and times, zone and offset types, and durations, including Python’s date, time and timedelta. A duration that is a named wrapper of a number (Go’s time.Duration) is refused too: the refusal wins over the transparent wrapper rule. An enum that the platform provides for dates and times, for example a day of the week, is an enum, not a time type.

Maps have string keys. A map keyed by an enum, an integer or any other non-string type is refused. Enum values are the wire names the codec writes, not the names in the source: a library encodes each constant with its default codec and uses the string it gets; an enum the codec writes as anything but a string is refused, naming the constant.

A transparent wrapper is a type the codec writes as the single value it wraps: a Kotlin value class, a Rust struct marked #[serde(transparent)], a Go named type such as type OrderID string. It takes the schema of the wrapped type, nullability included.

Any-JSON values are what the library’s default codec keeps as an untyped JSON tree: Kotlin’s JsonNode, Rust’s serde_json::Value, Go’s json.RawMessage and any, Python’s RawJson and Any.

Special cases:

  • A payload that is itself any JSON value at the top level is {"$schema":…,"title":"N"}, with neither type nor properties.
  • A reply with no content (Kotlin’s Unit, Rust’s (), Go’s Empty, Python’s None) is {"$schema":…,"title":"<request type>.Response","type":"object"}.
  • Any other reply, item or initial type without a message-type name takes the title <request type>.Response; one with a name takes it as its title (Titles and versions).

Wire names and the field set. The names, and the set of fields, are those of the library’s real default codec, not a reading of the source: the properties of a document are exactly the fields the codec writes for the constructor or declared fields of the type. A property the codec computes (a getter with no field behind it) is not described, and a field the codec never writes (ignored, skipped) is not either. A library’s tests encode a value with the codec and compare the keys to the schema’s properties.

What cannot be generated. These fail registration, before the library connects, and so does anything else outside the table above:

  • a recursive type, directly or through a field, a list or a map;
  • an abstract, sealed, union or otherwise polymorphic type (an interface, a sealed hierarchy, a Rust enum with data, a Go interface, a Python union of several types), because the schema would depend on the value written. A Python X | None or Optional[X] is not a union in this sense: it is a nullable X. Any other Python union is refused;
  • a result wrapper (Kotlin’s kotlin.Result);
  • every date, time, zone, offset and duration type that is not a timestamp;
  • a map whose keys are not strings;
  • a type of the host platform that is not in the table (a Java class, a Go channel or function).

The error names the type, the dotted path of the field (address.zip), the reason, and the location of the override that describes the type instead.

Which rule applies first. A library decides the schema of a type by taking the first of these that matches:

  1. an entry of the field table (strings, numbers, booleans, timestamps, UUIDs, bytes, any-JSON, no-content);
  2. any other date, time, zone, offset or duration type: refused;
  3. an enum;
  4. an array, set or list, then a map;
  5. any other collection type: refused;
  6. a polymorphic type (abstract, sealed, union, interface): refused;
  7. a type of the host platform that is not in the table: refused;
  8. an object, from its constructor or declared fields.

A transparent wrapper is unwrapped before this list is applied, except where a refusal above names the wrapper itself (a duration).

A library’s tests must assert that its generator produces these documents canonically equal to the ones below: the same JSON value, compared with every object’s keys sorted and no insignificant whitespace (the form the hub stores and hashes). Property order and layout are free.

The type is fixtures.PlaceOrder, version 2, with these fields (wire names):

Field Type
orderId string
quantity integer
price float
express boolean, with a default value
note nullable string
tags list of string
attributes map from string to string
placedAt timestamp
address nested object: street string, city string, zip nullable string
extra any JSON value

Its payload document:

{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"fixtures.PlaceOrder","type":"object",
"properties":{"orderId":{"type":"string"},"quantity":{"type":"integer"},"price":{"type":"number"},
"express":{"type":"boolean"},"note":{"anyOf":[{"type":"string"},{"type":"null"}]},
"tags":{"type":"array","items":{"type":"string"}},
"attributes":{"type":"object","additionalProperties":{"type":"string"}},
"placedAt":{"type":"string","format":"date-time"},
"address":{"type":"object","properties":{"street":{"type":"string"},"city":{"type":"string"},
"zip":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["city","street"]},
"extra":{}},
"required":["address","attributes","extra","orderId","placedAt","price","quantity","tags"]}

express, note and address.zip are not in required: the first has a default, the others are nullable.

The reply is fixtures.OrderPlaced, version 1, with no override and one field, orderId (string). Its response document:

{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"fixtures.OrderPlaced","type":"object",
"properties":{"orderId":{"type":"string"}},"required":["orderId"]}

A checked-in schema replaces generation for one type and version: for a payload, a response, or an event. A library offers a way to give it (see the official libraries’ API); then:

  • the contract sets MessageContract.schema_override (for an event, EventContract.schema_override) to true, which is informational for the hub and shown in its catalogue;
  • the document is sent as written, byte for byte, after the same local checks as a generated one: a library does not reformat it, reorder its keys or rewrite its numbers (1e2, 1.50 and -0.0 stay as they are; the hub canonicalises on its side);
  • an override is the only way to describe a recursive type, a custom wire format or anything the generated subset does not cover.

Two libraries do not generate the same JSON Schema for the same type: field order, the way a number or a date is described and a title written by one generator and not another all differ. A hub with its catalogue on refuses a Register whose contract is live with another schema at the same (type, payload version, response version) (FAILED_PRECONDITION, Refusals). So services in different languages that serve one type, or one service that runs on two libraries during a migration, must declare the same checked-in schema for it, as an override, with the same version. Write the document once, keep it in one place that every service builds from or copies byte for byte, and let each library send it as written; a service in a single language needs no override.

The conformance suite is the worked example: its services in Rust, Kotlin, Go and Python serve the same conformance.* types on one hub, each declaring the shared schemas from the runner’s contract/overrides/ as its overrides.

A library checks every schema, generated or overridden, before it connects, with the hub’s limits. A schema outside them fails registration with an error that names the type, not a hub refusal after connecting. The same applies to every version and to the conflict between two handlers of one event type.

  • Encoding. The document is UTF-8. Bytes that are not valid UTF-8, or a byte order mark at the start, are refused.
  • Size. At most 64 KiB, measured on the raw UTF-8 bytes of the document as it is sent.
  • Shape. One JSON value, an object, with no content after it and no repeated key in an object.
  • Depth. At most 100 levels, counting each { and [ outside strings, with the root object at level 1. A bracket inside a string does not count.
  • Values the hub cannot read. The hub parses each document as standard JSON with 64-bit floating-point numbers: a number too large for that (such as 1e400) or an escaped unpaired surrogate (such as "\ud800") is refused by the hub with INVALID_ARGUMENT. The official libraries do not check these two locally yet; keep overrides to ordinary numbers and characters.

A library checks an override in this order, and the first failure is reported with the type name:

  1. a byte order mark at the start is refused;
  2. the bytes must be valid UTF-8;
  3. the size is measured on the raw bytes;
  4. the first character that is not white space must be {;
  5. the depth is counted by scanning the brackets outside strings;
  6. the document is parsed strictly: no repeated key, no content after the value;
  7. the document is sent unchanged, byte for byte.

Every request a library sends carries both headers, always explicit, also for version 1:

Header Value
snodra-schema-version the version of the request type
snodra-response-schema-version the version of the response the caller expects: the reply type of a command or query, the item type of a streaming query, the initial type of a subscription query
  • This holds in every mode: unary, scatter-gather, streaming and subscription, and on the in-process (local) path, where a handler of the same instance answers without the hub, with the same versions.
  • A saga records both headers with the dispatch when it records the typed command, and the relay forwards them unchanged when it sends the command later.
  • The two names are reserved: a call that sets either through the generic header option, in any letter case (Snodra-Schema-Version included), is refused before anything is sent, not silently overwritten (messages.md, Request headers).

Every event a library publishes, including the ones a saga publishes, carries the header snodra-schema-version, the version of the event type, in addition to the seven event headers. The value has the same grammar as on a request.

A consumer applies this rule after it has decided it is interested in the event’s type:

  • the header names another version than the one registered for that type: the consumer skips the record and acknowledges it, counted as skipped. It is never retried and never dead-lettered, and the processor’s position advances. A newer publisher and an older consumer coexist this way;
  • the header is absent: the record reads as version 1;
  • the header is malformed (anything but [1-9][0-9]* in an unsigned 32-bit range): the record is invalid, and goes down the library’s existing invalid-record path.

An event the library takes from outside, through a partner source or a webhook ingress, carries the version of the type the library translates it into.

A record is judged by its own header, whenever it is read. A replay or a reset of a processor, and a retry of a dead letter, read records that were published earlier: after a version change, the ones of the older version are skipped like any other record of another version (a dead letter of another version is deleted without running its handlers). Nothing re-reads them as the new version. A processor consumes one version of an event type, and so does a service. To migrate, either publish the changed shape under a new event type name and consume that, or finish consuming the older records before the new version is deployed. A library says so once per processor, type and version, the first time it skips one, so a skipped replay is visible in the log.

A Register that carries no types (the empty Register of a drain, a rollover or a shutdown) carries no contracts and no event contracts either. The next Register with types carries the full set again: a revived instance declares everything it serves.

A hub with the catalogue on answers a Register it cannot accept with a gRPC status, and records nothing of it:

Status Meaning for the library
INVALID_ARGUMENT a missing, extra, duplicate or disagreeing contract, or a schema outside the limits
FAILED_PRECONDITION a contract that is live with a different schema: the version number is taken

Both are refusals, and a library treats FAILED_PRECONDITION on a Register like INVALID_ARGUMENT (the hub protocol, Refusals): it does not reconnect in a tight loop (at most one Register to that hub within a second), it reports the hub’s message as the reason, and it fails startup or marks the connection rejected, as the library does for any other refusal. A conflict is fixed by a new version of the changed type, or by stopping the instances that serve the old one.

The official libraries declare a version and an override as follows. Each library generates the documents above from its own type definitions; for a type that services in another language serve too, give every one the same override (Services in different languages).

Kotlin. The version is the version attribute of the type annotation; an override is a classpath resource named after the type and version.

@MessageType("orders.PlaceOrder", version = 2)
data class PlaceOrder(val orderId: String, val quantity: Int)
// override: a resource on the classpath
// snodra/schemas/orders.PlaceOrder.v2.schema.json

Rust. message_type! takes the version and an override; a derive generates the schema.

#[derive(Serialize, Deserialize, MessageSchema)]
#[serde(rename_all = "camelCase")]
struct PlaceOrder { order_id: String, quantity: i32 }
message_type!(PlaceOrder, "orders.PlaceOrder", version = 2);
// with a checked-in schema instead of the generated one
message_type!(
PlaceOrder, "orders.PlaceOrder", version = 2,
schema = include_str!("../schemas/orders.PlaceOrder.v2.schema.json")
);

Go. Optional methods on the message type; a type without them is version 1 and generated by reflection.

func (PlaceOrder) MessageVersion() uint32 { return 2 }
// override: returns the whole document
func (PlaceOrder) JSONSchema() []byte { return placeOrderSchema }
// a string type lists its values, in declaration order
func (Priority) EnumValues() []string { return []string{"low", "normal", "high"} }

Python. The decorator takes the version and an override (a dict or a path to a JSON file).

@message_type("orders.PlaceOrder", version=2)
@dataclass
class PlaceOrder:
order_id: str
quantity: int
# with a checked-in schema (a dict, or the path of a JSON file) instead of the generated one
@message_type("orders.PlaceOrder", version=2, schema="schemas/orders.PlaceOrder.v2.schema.json")
@dataclass
class PlaceOrder:
order_id: str
quantity: int