Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Event mocks from AsyncAPI

What an OpenAPI mock does for a request and response API, an event mock does for an event-driven one. Give Rustybin an AsyncAPI document and it serves the document's channels: it publishes valid messages on them, validates what clients publish, and shows the traffic. A gateway that proxies WebSockets, server-sent events or webhooks gets an upstream to demo against.

An event mock is a mock like any other: the same list, drafts and deploys, revisions, projects, exports and rustybin.yaml. It has channels where an OpenAPI mock has operations. Create one the way you create any mock, with an AsyncAPI 2.x or 3.0 document (JSON or YAML) in place of the OpenAPI one; the kind is detected.

# An event mock as code: a rustybin.yaml with one mock whose spec is an
# AsyncAPI document (docs/src/mocks/asyncapi.md). Apply it with
# `rustybin mocks apply order-events.yaml`.
version: 2
mocks:
  - name: order-events
    channels:
      orders-created:
        every_ms: 500                # one orderCreated every half second
    spec_inline:
      asyncapi: 3.0.0
      info:
        title: Order events
        version: 1.0.0
        description: What an order service says and hears.
      channels:
        orderCreated:
          address: orders/created
          messages:
            orderCreated:
              $ref: '#/components/messages/OrderCreated'
        orderCancel:
          address: orders/cancel
          messages:
            orderCancel:
              $ref: '#/components/messages/OrderCancel'
        quotes:
          address: quotes
          messages:
            quoteRequest:
              $ref: '#/components/messages/QuoteRequest'
            quote:
              $ref: '#/components/messages/Quote'
      operations:
        announceOrder:
          action: send               # Rustybin publishes these
          channel:
            $ref: '#/channels/orderCreated'
        cancelOrder:
          action: receive            # a client publishes these
          channel:
            $ref: '#/channels/orderCancel'
        askForQuote:
          action: receive
          channel:
            $ref: '#/channels/quotes'
          messages:
            - $ref: '#/channels/quotes/messages/quoteRequest'
          reply:                     # answered with a quote
            channel:
              $ref: '#/channels/quotes'
            messages:
              - $ref: '#/channels/quotes/messages/quote'
      components:
        messages:
          OrderCreated:
            name: orderCreated
            payload:
              $ref: '#/components/schemas/Order'
            examples:
              - payload: { id: 1001, total: 59.9, status: new }
              - payload: { id: 1002, total: 12.5, status: paid }
          OrderCancel:
            name: orderCancel
            payload:
              type: object
              required: [id, reason]
              additionalProperties: false
              properties:
                id: { type: integer }
                reason: { type: string, minLength: 3 }
          QuoteRequest:
            name: quoteRequest
            payload:
              type: object
              required: [sku]
              properties:
                sku: { type: string }
                quantity: { type: integer, minimum: 1 }
          Quote:
            name: quote
            payload:
              type: object
              required: [sku, price]
              properties:
                sku: { type: string }
                price: { type: number, minimum: 0 }
        schemas:
          Order:
            type: object
            required: [id, total]
            properties:
              id: { type: integer, minimum: 1 }
              total: { type: number }
              status: { type: string, enum: [new, paid, shipped] }
POST {{base_url}}/_rustybin/mocks/apply
Authorization: Bearer {{admin_token}}
Content-Type: application/yaml
file,order-events.yaml;
HTTP 200
[Asserts]
jsonpath "$.created" contains "order-events"

What Rustybin plays

An AsyncAPI document describes an application. Rustybin plays that application:

In the documentRustybin
A send operation (3.0), or a subscribe one (2.x: what a client may subscribe to)Publishes the operation's messages on the channel
A receive operation (3.0), or a publish one (2.x)Accepts those messages from clients and validates them
A reply on a receive operation (3.0)Answers each valid message with the reply's message

Both versions become the same channels. A channel's id is its address as a slug (orders/created is orders-created); it names the channel in URLs, settings and commands.

GET {{base_url}}/_rustybin/mocks/order-events/channels
HTTP 200
[Asserts]
jsonpath "$.asyncapi" == "3.0.0"
jsonpath "$.count" == 3
jsonpath "$.channels[0].id" == "orders-created"
jsonpath "$.channels[0].address" == "orders/created"
jsonpath "$.channels[0].pattern" == "every"
jsonpath "$.channels[0].settings.every_ms" == 500
jsonpath "$.channels[0].send[0].name" == "orderCreated"
jsonpath "$.channels[0].path" == "/events/order-events/orders-created"
jsonpath "$.channels[2].pattern" == "on_receive"
jsonpath "$.channels[2].sample.message" == "quoteRequest"

Connecting to a channel

Each channel answers at /events/{mock}/{channel}, three ways:

HowWhat you get
A WebSocketEach published message as a text frame (the payload); send a frame to publish as a client
GET with Accept: text/event-streamServer-sent events: event is the message's name, id its number on the channel, data the payload
POST a messagePublished as a client: 202 when valid, 422 with the issues

A plain GET describes the channel. The same channel also answers below the mock's own root, at /mock/{mock}/_rustybin/events/{channel}, which is where a self-service mock on its own domain serves it.

# Rustybin publishes an orderCreated every half second while you listen.
sleep 3 | websocat "$WS/events/order-events/orders-created"
curl -sN --max-time 3 -H 'Accept: text/event-stream' \
  "$BASE/events/order-events/orders-created" || true
GET {{base_url}}/events/order-events/orders-created
HTTP 200
[Asserts]
jsonpath "$.address" == "orders/created"
jsonpath "$.pattern" == "every"
jsonpath "$.send[0].name" == "orderCreated"

Every subscriber of a channel gets the same messages, whichever way it listens. A channel publishes only while somebody listens (a connection or a webhook subscriber), and a connection is closed after an hour (the asyncapi.session_minutes setting). When the mock is deleted or turned off, its connections are closed.

What is published

A channel's messages are published in turn. Each payload comes from, in order:

  1. the message's examples in the document, in turn;
  2. the examples stored with the mock (channels.<id>.examples), in turn;
  3. the payload schema, through the generator of the OpenAPI mocks (the mock's responses.seed decides the values: the same seed, the same messages).

When they are published is the channel's pattern:

patternPublishes
everyOne message every every_ms (1000 by default, at least 100). The default
burstburst messages (5 by default, at most 20) at once every every_ms
on_receiveOne message for each valid message a client publishes: request and reply. The default on a channel whose document declares a reply
offNothing by itself: only what you publish by hand. The default on a channel that only receives

Publish by hand at any time, on any pattern: the channel's next message, several, or a payload of your own.

POST {{base_url}}/_rustybin/mocks/order-events/channels/orders-created/publish
Authorization: Bearer {{admin_token}}
Content-Type: application/json
{}
HTTP 200
[Asserts]
jsonpath "$.published" == 1
jsonpath "$.messages[0].direction" == "sent"
jsonpath "$.messages[0].message" == "orderCreated"
jsonpath "$.messages[0].source" == "example"
jsonpath "$.messages[0].payload.id" == 1001
jsonpath "$.messages[0].delivered.ws" == 0
POST {{base_url}}/_rustybin/mocks/order-events/channels/orders-created/publish
Authorization: Bearer {{admin_token}}
Content-Type: application/json
{"payload": {"id": 4242, "total": 0.5, "status": "shipped"}}
HTTP 200
[Asserts]
jsonpath "$.messages[0].source" == "given"
jsonpath "$.messages[0].payload.id" == 4242

Faults

A channel's settings can spoil what the pattern publishes, to show what a gateway or a client does about it:

SettingEffect
delay_msWaited before each message is published
drop_percentThat share of messages reaches nobody (the log marks them dropped)
malformed_percentThat share is sent cut short, so it is not valid JSON (malformed)

Which messages are hit follows from the seed, so a run repeats. A message you publish by hand is never spoiled.

What clients publish

A message a client publishes is checked against the channel's receive messages: it is valid when it meets the payload schema of one of them. A valid message is accepted without an answer (or with the reply, on on_receive); an invalid one is answered with an error, and both are kept with the verdict.

POST {{base_url}}/events/order-events/orders-cancel
Content-Type: application/json
{"id": 1001, "reason": "ordered twice"}
HTTP 202
[Asserts]
jsonpath "$.accepted" == true
jsonpath "$.message" == "orderCancel"
POST {{base_url}}/events/order-events/orders-cancel
Content-Type: application/json
{"id": "1001", "reason": "no"}
HTTP 422
[Asserts]
jsonpath "$.error.type" == "invalid_message"
jsonpath "$.error.issues" count == 2
jsonpath "$.error.issues[0].pointer" == "/id"

Over a WebSocket the error is an event on the same connection:

# A message that is not valid is answered with an error event.
(
  echo '{"id": 1001}'
  sleep 1
) | websocat "$WS/events/order-events/orders-cancel"

A channel whose document declares a reply answers a valid request:

POST {{base_url}}/events/order-events/quotes
Content-Type: application/json
{"sku": "SKU-7", "quantity": 2}
HTTP 202
[Asserts]
jsonpath "$.message" == "quoteRequest"
jsonpath "$.reply.message" == "quote"
jsonpath "$.reply.payload.price" isNumber
# The document declares a reply: a quoteRequest is answered with a quote.
(
  echo '{"sku": "SKU-7"}'
  sleep 1
) | websocat "$WS/events/order-events/quotes"

One connection may publish 50 messages a second, each of at most 256 KiB.

The messages of a channel

Everything published and received is kept in the mock's log, bounded like its requests (the oldest go first) and cleared with them. A message's payload is kept up to 8 KiB.

GET {{base_url}}/_rustybin/mocks/order-events/channels/orders-cancel/messages?limit=10
Authorization: Bearer {{admin_token}}
HTTP 200
[Asserts]
jsonpath "$.count" == 2
jsonpath "$.messages[0].direction" == "received"
jsonpath "$.messages[0].transport" == "http"
jsonpath "$.messages[0].valid" == false
jsonpath "$.messages[0].issues[0].pointer" == "/id"
jsonpath "$.messages[1].valid" == true
jsonpath "$.messages[1].message" == "orderCancel"

after asks for what came after a sequence number, which is how the console's feed and rustybin mocks events --follow keep up:

# Only what came after a sequence number: how a feed asks again.
GET {{base_url}}/_rustybin/mocks/order-events/channels/quotes/messages?after=4
Authorization: Bearer {{admin_token}}
HTTP 200
[Asserts]
jsonpath "$.messages[0].direction" == "sent"
jsonpath "$.messages[0].message" == "quote"
jsonpath "$.messages[1].direction" == "received"

On a public instance a caller without a credential reads what Rustybin published and what they published themselves, never another caller's messages, as with a mock's requests.

Webhook subscribers

A webhook subscriber is a URL every message of a channel is posted to: the payload as the body, with X-Rustybin-Event (the message's name), X-Rustybin-Event-Id, X-Rustybin-Mock and X-Rustybin-Channel, plus the headers the document gives the message.

Posting to a URL reaches out, so it follows the rules of everything that does: it needs mocks.write, and goes through the outbound policy under the purpose events, which has no default. Add the receiver's host to RUSTYBIN_EGRESS_ALLOW; a host that is not allowed is refused when the subscriber is added, before anything is sent:

POST {{base_url}}/_rustybin/mocks/order-events/subscribers
Authorization: Bearer {{admin_token}}
Content-Type: application/json
{"channel": "orders-created", "url": "https://hooks.example.com/orders"}
HTTP 403
[Asserts]
jsonpath "$.reason" == "egress_refused"
jsonpath "$.purpose" == "events"
GET {{base_url}}/_rustybin/mocks/order-events/subscribers
HTTP 200
[Asserts]
jsonpath "$.count" == 0
DELETE {{base_url}}/_rustybin/mocks/order-events/subscribers/0a1b2c3d4e5f6a7b
Authorization: Bearer {{admin_token}}
HTTP 404

A subscriber lives an hour by default (ttl_seconds, at most a day), is removed after ten failed deliveries in a row, and is never part of a document or an export: it lives in memory and is gone at a restart. A URL's query is never shown again (it may hold the receiver's credential). A mock has at most 10 subscribers, the instance 50 (the asyncapi.max_subscribers setting). Self-service mocks have none.

The deploy report

The deploy checks build each channel's messages once and validate them against their own schemas. What Rustybin cannot serve or generate is a warning, never an error, so the mock still deploys:

FindingWhen
A binding or protocol that is not servedThe document names kafka, mqtt, amqp or another binding: the channels are served over WebSocket, server-sent events and webhooks all the same
A schema format that is not generatedA message's schemaFormat is Avro, Protobuf or another format: give the message an example, which is published as it is
An example that does not matchA document or stored example breaks the message's own schema
No payload schema and no exampleAn empty object is published
Security settingsThey do not apply to channels, which answer without a credential
GET {{base_url}}/_rustybin/mocks/order-events/report
HTTP 200
[Asserts]
jsonpath "$.ok" == true
jsonpath "$.channels" count == 3
jsonpath "$.channels[0].send[0].source" == "example"
jsonpath "$.channels[1].receive[0].message" == "orderCancel"

The routes of this page are for event mocks only:

# An OpenAPI mock has operations, not channels.
GET {{base_url}}/_rustybin/mocks/petstore/channels
HTTP 409
[Asserts]
jsonpath "$.reason" == "not_asyncapi"

Limits

LimitValue
Connections to channels at once128 (the asyncapi.max_connections setting, 1 to 1024); one more is refused with 429
Longest connection60 minutes (asyncapi.session_minutes)
A message a client publishes256 KiB; 50 a second on one connection
Channels of a documentThe mock's operation limit (500)
Webhook subscribers10 a mock, 50 an instance (asyncapi.max_subscribers); a delivery waits 5 seconds

An event mock has no operations, so the parts of a mock built on them do not apply to it: its MCP server has no tools, and mocked security, stateful data, drift checks and collections have nothing to work on. Asking for a collection of one is answered 409 with the reason asyncapi, never an empty file.

On the dev portal

Published on the dev portal, an event mock is an event API (mock:<name>, kind event, under Event APIs). Its page is its channels: each one's address and URL, what Rustybin publishes on it and how often, what it accepts, an example of every message, and how to connect (a WebSocket, server-sent events with curl -N, a POST of a valid message). There is no Try it, no collection and no API reference viewer, which are made from operations.

# On the dev portal an event mock is an event API: its channels, what each
# publishes and accepts, and how to connect.
PUT {{base_url}}/_rustybin/portal/items/mock:order-events
Authorization: Bearer {{admin_token}}
Content-Type: application/json
{
  "summary": "What happens to an order, as events."
}
HTTP 201

GET {{base_url}}/portal/api/catalog
HTTP 200
[Asserts]
jsonpath "$.kinds[?(@.id == 'event')].title" contains "Event APIs"
jsonpath "$.items[?(@.id == 'mock:order-events')].kind" contains "event"
jsonpath "$.items[?(@.id == 'mock:order-events')].detail.asyncapi" contains "3.0.0"
jsonpath "$.items[?(@.id == 'mock:order-events')].detail.channels[0].address" contains "orders/created"
jsonpath "$.items[?(@.id == 'mock:order-events')].detail.channels[0].send[0].name" contains "orderCreated"
jsonpath "$.items[?(@.id == 'mock:order-events')].detail.channels[0].connect.sse" contains "text/event-stream"
# A collection is made from operations: an event mock has none, and says so.
GET {{base_url}}/_rustybin/mocks/order-events/collections/hurl
HTTP 409
[Asserts]
jsonpath "$.reason" == "asyncapi"

GET {{base_url}}/portal/api/items/mock:order-events/collections/hurl
HTTP 404
[Asserts]
jsonpath "$.reason" == "event_api"

A channel answers whoever connects (mocked security guards operations), so an event API cannot be closed on the portal: the publish answers 409 with the reason open_channels. The exception is an instance that asks every data-plane call for an API key (RUSTYBIN_REQUIRE_KEY or shared mode); there a closed event API shows its channels and messages to everyone and its connection snippets to signed-in readers.

On every surface

SurfaceWhere
APIA mock's create, PATCH and apply take an AsyncAPI document and channels; /events/{name}/{channel} (WebSocket, SSE, POST); GET /_rustybin/mocks/{name}/channels, GET .../channels/{channel}/messages, POST .../channels/{channel}/publish; GET and POST /_rustybin/mocks/{name}/subscribers, DELETE .../subscribers/{id}
Dev portalPublish mock:<name>: an event API with its channels (above)
ConsoleMock APIs: drop an AsyncAPI file. The mock's Channels tab: each channel's URL, what it publishes and accepts, its pattern and faults (Save to the draft), Publish the next message, a composer that publishes a valid message as a client, the live feed of messages, and the webhook subscribers. Deploy report lists the channels. Management, General has the caps under Event mocks
CLIrustybin mocks create <name> --spec <asyncapi file>, rustybin mocks channels <name>, rustybin mocks events <name> <channel> [--follow], rustybin mocks publish <name> <channel> [--data JSON] [--count N], rustybin mocks subscribers <name>, rustybin mocks subscribe <name> <channel> --webhook URL, rustybin mocks unsubscribe <name> <id> (reference)
Management MCPcreate_mock and update_mock take an AsyncAPI document and channels; list_channels, list_channel_messages (payloads under untrusted_*), publish_event, list_event_subscribers, add_event_subscriber (confirmed: it sends messages out), remove_event_subscriber
rustybin.yamlAn AsyncAPI document as a mock's spec or spec_inline, its channels:; settings: with asyncapi.max_connections, asyncapi.session_minutes and asyncapi.max_subscribers