# Examples: Kafka, RabbitMQ, MQTT, Avro, NATS, AMQP 1.0

> The whole path of Publishing and consuming on a broker on Kafka: a publication door, also an MCP tool; an SSE fan-out or acknowledged WebSocket stream, bound…

Example - Since version 1.5.0 - Flexway v1.6.3 - https://flexway.io/en/docs/operations-examples-brokers/

> Operations guide: configure, deploy and observe the gateway. What the capability does, product side: [product guide](https://flexway.io/en/docs/product-overview/); calling it: [developer guide](https://flexway.io/en/docs/developer-overview/).

## Kafka: publish, stream, deliver

The whole path of [Publishing and consuming on a broker](https://flexway.io/en/docs/operations-async/) on Kafka: a publication door, also
an MCP tool; an SSE fan-out or acknowledged WebSocket stream, bound to the tenant; `acme`'s events delivered
as signed webhooks, dead letters in `orders.dead`. The gateway authenticates with SASL SCRAM over TLS.

<!-- example: examples/async-kafka/flexway.yaml -->

```yaml
# Kafka behind the gateway's controls (1.5.0): an HTTP door and an MCP tool publish, a
# browser streams its tenant's events in SSE or WebSocket, a partner receives them as signed webhooks.
# flexway.yaml lists no channel - they come from the AsyncAPI contract.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml                      # AsyncAPI 3.0.0 or 3.1.0
upstreams:
  events:
    protocol: kafka
    brokers: [kafka-0.kafka:9093, kafka-1.kafka:9093]
    tls: { server_name: kafka.internal }          # TLS, system roots; ca_file, cert_file and key_file for a private CA or mTLS
    sasl: { mechanism: SCRAM-SHA-512, username: flexway, password: "file:/etc/flexway-secrets/kafka/password" }
    timeout: 2s                                  # one publication's budget, the acknowledgement included
    max_in_flight: 512                           # bounded buffer: past it, 503 overloaded
  partner-hook:
    protocol: webhook
    url: https://hooks.partner.example/orders
    secrets: ["file:/etc/flexway-secrets/hooks/current", "file:/etc/flexway-secrets/hooks/next"]
    retries: { max: 8, max_delay: 10m }
auth:
  issuers:
    - name: customers
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: api
      tenant_claim: org                          # the tenant every channel below is bound to
agents:
  mcp:
    resources:
      api.example.com: https://api.example.com/mcp
```

```yaml
# examples/async-kafka/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Orders events, version: 1.0.0 }
channels:
  orderCreated:
    address: "orders.{tenant}.created"           # one topic per tenant
    parameters:
      tenant: { x-flexway-bind: tenant }         # bound to the verified identity, never read from the request
    messages:
      created:
        contentType: application/json
        payload:
          type: object
          required: [orderId]
          properties:
            orderId: { type: string, minLength: 1 }
operations:
  publishOrderCreated:
    action: send
    channel: { $ref: "#/channels/orderCreated" }
    x-flexway-upstream: events
    x-flexway-key: /orderId                      # ordered per key, and per key only
  receiveOrderCreated:
    action: receive
    channel: { $ref: "#/channels/orderCreated" }
    x-flexway-upstream: events
    x-flexway-deliver:                           # acme's events to its webhook; what fails ends in orders.dead
      - { upstream: partner-hook, tenant: acme, dead_letter: orders.dead }
```

```yaml
# examples/async-kafka/openapi.yaml
openapi: 3.1.0
info: { title: Orders events, version: "1.0.0" }
components:
  securitySchemes:
    customers: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /orders/events:
    post:
      operationId: emitOrderCreated
      summary: Publish an order-created event for the caller's tenant
      x-flexway-publish: { operation: publishOrderCreated, idempotency: required }
      x-flexway-tool: { name: emit_order_created }   # the same door, offered to agents as an MCP tool
      security: [ { customers: [orders:write] } ]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [orderId], properties: { orderId: { type: string, minLength: 1 } } }
      responses: { "202": { description: Acknowledged by the broker } }
  /orders/stream:
    get:
      operationId: streamOrderCreated
      x-flexway-subscribe: { operation: receiveOrderCreated, transport: [sse, websocket], max_streams: 2, ack_timeout: 30s, buffer: 256, history: 64 }
      security: [ { customers: [orders:read] } ]
      responses: { "200": { description: The caller's tenant's events } }
```

| Case | What the gateway does |
| --- | --- |
| `POST /orders/events` or the `emit_order_created` tool | `202` after `acks=all`; `Idempotency-Key` required (`428` otherwise), becoming the `id`; ordered by `orderId` |
| `GET /orders/stream` in SSE | One consumer per channel and replica; `Last-Event-ID` resumed from the last 64 messages, `412 precondition_failed` beyond |
| `GET /orders/stream` in WebSocket | A group of the subscriber's own, `{"ack": "<id>"}` within 30 s, otherwise a `1008` close and a new delivery |
| Delivery to `partner-hook` | A group shared by the replicas, Standard Webhooks, position committed after the `2xx`, dead letters in `orders.dead` |
| mTLS instead of SASL | `tls.cert_file` and `tls.key_file` mounted, no `sasl` |

## RabbitMQ in AMQP 0-9-1: a channel per person, a public feed

Each player publishes and reads **its own** notifications - the channel is bound to the token's verified
subject -; the scoreboard is a **public** feed, read without a token, resumed over 128 messages. A producer
outside the gateway writes it as `application/cloudevents+json`: read in structured mode. The gateway
connects with its own user, on its own virtual host (`/games`, the URL's path).

<!-- example: examples/async-amqp/flexway.yaml -->

```yaml
# RabbitMQ in AMQP 0-9-1 behind the gateway's controls (1.5.0): each player reads its
# own notifications only (bound to the verified subject), anyone - anonymous included - reads the
# declared public feed. The gateway authenticates itself: its own user, its own virtual host.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  bus:
    protocol: amqp                               # AMQP 0-9-1 (protocol_version: 0-9-1, the default)
    brokers: ["amqps://rabbitmq.internal:5671/games"]   # the path is the virtual host; never a password in the URL
    sasl: { mechanism: PLAIN, username: flexway, password: "file:/etc/flexway-secrets/rabbitmq/password" }
    timeout: 2s                                  # publisher confirm included
auth:
  issuers:
    - name: players
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: games
      tenant_claim: org
```

```yaml
# examples/async-amqp/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Game events, version: 1.0.0 }
channels:
  notifications:
    # A topic exchange the broker already has: the gateway never declares one.
    address: "players.{sub}.notifications"
    parameters:
      sub: { x-flexway-bind: subject }           # the verified subject: a player reads its own channel only
    bindings:
      amqp: { is: routingKey, exchange: { name: notifications, type: topic } }
    messages:
      note:
        contentType: application/json
        payload: { type: object, required: [text], properties: { text: { type: string } } }
  scoreboard:
    address: scores.public                       # binds nothing, filters nothing: declared public below
    bindings:
      amqp: { is: routingKey, exchange: { name: scores, type: topic } }
    messages:
      # Written by a producer outside the gateway (an outbox) as application/cloudevents+json: read in
      # structured mode; any other content type is read in binary mode.
      score:
        payload: { type: object, required: [match], properties: { match: { type: string }, score: { type: string } } }
operations:
  publishNotification: { action: send, channel: { $ref: "#/channels/notifications" }, x-flexway-upstream: bus }
  receiveNotifications: { action: receive, channel: { $ref: "#/channels/notifications" }, x-flexway-upstream: bus }
  receiveScores:
    action: receive
    channel: { $ref: "#/channels/scoreboard" }
    x-flexway-upstream: bus
    x-flexway-public: true                       # read by anyone, anonymous included
```

```yaml
# examples/async-amqp/openapi.yaml
openapi: 3.1.0
info: { title: Game events, version: "1.0.0" }
components:
  securitySchemes:
    players: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /me/notifications:
    post:
      operationId: notifyMe
      x-flexway-publish: { operation: publishNotification }
      security: [ { players: [] } ]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [text], properties: { text: { type: string } } }
      responses: { "202": { description: Confirmed by the broker } }
    get:
      operationId: streamMyNotifications
      # WebSocket: at least once - the client acknowledges {"ack": "<id>"} within ack_timeout.
      x-flexway-subscribe: { operation: receiveNotifications, transport: [sse, websocket], max_streams: 3, ack_timeout: 20s }
      security: [ { players: [] } ]
      responses: { "200": { description: The caller's own notifications } }
  /scores:
    get:
      operationId: streamScores
      # SSE only; one consumer per replica whatever the audience, 128 messages kept for Last-Event-ID.
      x-flexway-subscribe: { operation: receiveScores, transport: [sse], max_streams: 2, max_anonymous_streams: 500, history: 128 }
      security: []                               # anonymous door: only toward a public operation
      responses: { "200": { description: The public scoreboard } }
```

| Case | What the gateway does |
| --- | --- |
| `POST /me/notifications` | Published on `players.<sub>.notifications` of the `notifications` exchange, `202` after the confirm |
| `GET /me/notifications` | The subject's own channel only; a value outside letters, digits, `_` and `-` is refused (`403`) |
| `GET /scores` without a token | Declared public: up to 500 anonymous callers together, 2 streams per address; a subscriber too slow is closed, the others go on |
| Webhook | The same declaration as in [Kafka: publish, stream, deliver](#kafka-publish-stream-deliver): a named queue shared by the replicas |

## MQTT 5: a claim, the tenant attribute, a webhook

An operator reads the telemetry of **its own** site - the channel is bound to the token's `site` claim -,
without resumption (`history: 0`); every tenant's alerts go through **one** shared topic, each carrying the
`tenant` attribute: consumption is filtered on it, and `acme`'s alerts leave as webhooks through an MQTT 5
**shared** subscription (one replica per message).

<!-- example: examples/async-mqtt/flexway.yaml -->

```yaml
# An MQTT 5 broker behind the gateway's controls (1.5.0): an operator's screen reads
# the telemetry of its own site (bound to a claim of its token), alerts carry the tenant attribute
# and are delivered to the tenant's webhook through a shared subscription - one replica per message.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  plant:
    protocol: mqtt
    protocol_version: "5"                        # the default; 3.1.1 has no shared subscription, so no webhook
    brokers: ["mqtts://mqtt.internal:8883"]
    sasl: { mechanism: PLAIN, username: flexway, password: "file:/etc/flexway-secrets/mqtt/password" }
    timeout: 2s                                  # PUBACK at QoS 1 included
  ops-hook:
    protocol: webhook
    url: https://ops.acme.example/flexway/alerts
    secrets: ["file:/etc/flexway-secrets/hooks/ops"]
    retries: { max: 5, max_delay: 5m }
auth:
  issuers:
    - name: operators
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: plant
      tenant_claim: org
```

```yaml
# examples/async-mqtt/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Plant telemetry, version: 1.0.0 }
channels:
  siteTelemetry:
    address: "sites/{site}/telemetry"
    parameters:
      site: { x-flexway-bind: "claim:site" }     # a claim of the verified token: an operator reads its own site
    messages:
      reading:
        payload: { type: object, required: [sensor, value], properties: { sensor: { type: string }, value: { type: number } } }
  alerts:
    address: plant/alerts                        # one topic for every tenant ...
    messages:
      alert:
        headers:                                 # ... kept apart by the tenant attribute every message declares
          type: object
          properties: { tenant: { type: string } }
        payload: { type: object, required: [code], properties: { code: { type: string } } }
operations:
  publishReading: { action: send, channel: { $ref: "#/channels/siteTelemetry" }, x-flexway-upstream: plant }
  receiveReadings: { action: receive, channel: { $ref: "#/channels/siteTelemetry" }, x-flexway-upstream: plant }
  publishAlert: { action: send, channel: { $ref: "#/channels/alerts" }, x-flexway-upstream: plant }
  receiveAlerts:
    action: receive
    channel: { $ref: "#/channels/alerts" }
    x-flexway-upstream: plant
    x-flexway-deliver:                           # acme's alerts only; what cannot be delivered ends in plant/alerts-dead
      - { upstream: ops-hook, tenant: acme, dead_letter: plant/alerts-dead }
```

```yaml
# examples/async-mqtt/openapi.yaml
openapi: 3.1.0
info: { title: Plant telemetry, version: "1.0.0" }
components:
  securitySchemes:
    operators: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /telemetry:
    post:
      operationId: postReading
      x-flexway-publish: { operation: publishReading, idempotency: required }
      security: [ { operators: [telemetry:write] } ]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [sensor, value], properties: { sensor: { type: string }, value: { type: number } } }
      responses: { "202": { description: Acknowledged by the broker (PUBACK) } }
    get:
      operationId: streamReadings
      x-flexway-subscribe: { operation: receiveReadings, transport: [sse], history: 0 }   # no resumption
      security: [ { operators: [telemetry:read] } ]
      responses: { "200": { description: The telemetry of the caller's site } }
  /alerts:
    post:
      operationId: raiseAlert
      x-flexway-publish: { operation: publishAlert }
      security: [ { operators: [alerts:write] } ]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [code], properties: { code: { type: string } } }
      responses: { "202": { description: Acknowledged by the broker (PUBACK) } }
```

| Case | What the gateway does |
| --- | --- |
| `POST /telemetry` | `202` after the QoS 1 `PUBACK`; `Idempotency-Key` required |
| `GET /telemetry` | The token's `sites/<site>/telemetry` channel only; without a `site` claim, refused |
| `POST /alerts` | The `tenant` attribute comes from the identity, never from the body |
| Delivery to `ops-hook` | A shared subscription, filtered on `tenant` = `acme`, dead letters in `plant/alerts-dead`; refused at load on MQTT 3.1.1 |
| mTLS instead of the password | `tls.cert_file` and `tls.key_file` mounted, no `sasl` |

## Avro payloads under schema, schema registry

A shop publishes its orders in **Avro** from HTTP: the body is decoded under `order.avsc`, compiled at
load, before it reaches Kafka; a dashboard reads them over SSE **in JSON**, a service reads them over a
WebSocket **in Avro, as they are**. The audit channel carries **Confluent's wire format**: each schema
id is read from the registry, and must be registered there under the tenant's subject
(`<tenant>.orders.audit-value`) - another tenant never publishes under that schema.

<!-- example: examples/async-binary/flexway.yaml -->

```yaml
# Avro orders through the asynchronous plane (1.6.0): an HTTP caller publishes an Avro
# body - checked under its schema, compiled at load -, a subscriber over SSE or a webhook reads it in
# JSON, a WebSocket that declares binary frames reads it as it is. The audit channel carries Confluent's
# wire format: each schema id is read in the registry and must be registered under the tenant's subject.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  orders-brokers:
    protocol: kafka
    brokers: [kafka-0.internal:9092, kafka-1.internal:9092]
schema_registry:
  url: https://registry.internal:8081                # read, never written - the Confluent API
  auth:
    username: flexway
    password: ${REGISTRY_PASSWORD}                    # a reference, resolved at each request
  timeout: 2s                                         # a lookup holds the message that needs it
  max_schemas: 1000                                   # compiled once each, kept by id
auth:
  issuers:
    - name: customers
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: api
      tenant_claim: org
```

```yaml
# examples/async-binary/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Shop orders, version: "1.0.0" }
channels:
  orders:
    address: "{tenant}.orders"
    parameters:
      tenant: { x-flexway-bind: tenant }
    messages:
      order:
        contentType: application/vnd.apache.avro+binary
        payload: { schemaFormat: "application/vnd.apache.avro;version=1.9.0", schema: { $ref: "./order.avsc" } }
  audit:
    address: "{tenant}.orders.audit"
    parameters:
      tenant: { x-flexway-bind: tenant }
    messages:
      audited:
        contentType: application/vnd.apache.avro+binary
        payload: { schemaFormat: "application/vnd.apache.avro;version=1.9.0", schema: { $ref: "./order.avsc" } }
        bindings:
          kafka: { schemaIdLocation: payload, schemaIdPayloadEncoding: confluent, schemaLookupStrategy: TopicIdStrategy }
operations:
  publishOrder:
    action: send
    channel: { $ref: "#/channels/orders" }
    x-flexway-upstream: orders-brokers
    x-flexway-validation: full          # decode every body under order.avsc - opt-in for a binary message
    x-flexway-key: /orderId             # read in the payload's JSON form
  receiveOrder:
    action: receive
    channel: { $ref: "#/channels/orders" }
    x-flexway-upstream: orders-brokers
  publishAudit:
    action: send
    channel: { $ref: "#/channels/audit" }
    x-flexway-upstream: orders-brokers
    x-flexway-validation: full          # the schema id in the registry, under <tenant>.orders.audit-value
  receiveAudit:
    # Records of an ordinary Kafka producer (a Confluent serializer, no CloudEvents header) are read
    # too: the channel is bound to the tenant and its only message is in the registry's wire format,
    # so the gateway builds each envelope - id <topic>/<partition>/<offset>, the record's timestamp.
    action: receive
    channel: { $ref: "#/channels/audit" }
    x-flexway-upstream: orders-brokers
```

```yaml
# examples/async-binary/openapi.yaml
openapi: 3.1.0
info: { title: Shop orders, version: "1.0.0" }
components:
  securitySchemes:
    customers: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
security: [{ customers: [] }]
paths:
  /orders/events:
    post:
      operationId: emitOrder
      x-flexway-publish: { operation: publishOrder, idempotency: required }
      requestBody:
        required: true
        content: { application/vnd.apache.avro+binary: { schema: { type: string, format: binary } } }
      responses: { "202": { description: published, after the broker's acknowledgement } }
  /orders/audit:
    post:
      operationId: emitAudit
      x-flexway-publish: { operation: publishAudit }
      requestBody:
        required: true
        content: { application/vnd.apache.avro+binary: { schema: { type: string, format: binary } } }
      responses: { "202": { description: published } }
  /orders/stream:
    get:
      operationId: streamOrders
      x-flexway-subscribe: { operation: receiveOrder, transport: [sse] }
      responses: { "200": { description: the tenant's orders, in JSON } }
  /orders/frames:
    get:
      operationId: framesOrders
      x-flexway-subscribe: { operation: receiveOrder, transport: [websocket], frames: binary }
      responses: { "200": { description: the tenant's orders, the Avro payload in binary frames } }
  /orders/audit/stream:
    get:
      operationId: streamAudit
      x-flexway-subscribe: { operation: receiveAudit, transport: [sse] }
      responses: { "200": { description: the tenant's audit records in JSON, ordinary producers' included } }
```

| Case | What the gateway does |
| --- | --- |
| `POST /orders/events`, a conforming Avro body | `202` after the acknowledgement; the Kafka key read at `/orderId` of the message's JSON form |
| A body that does not decode under `order.avsc` | `422 invalid_request`, the rule alone, never a value of the message |
| Another `Content-Type` | `422 invalid_request` (the door declares Avro only); a door without `requestBody` answers `415 unsupported_media_type` |
| `POST /orders/audit`, an id registered under `acme.orders.audit-value` | `202`; the schema read once per id, kept in memory (`max_schemas`) |
| An unknown id, or one registered under another subject | `422 invalid_request` |
| The registry unreachable or failing | `503 upstream_unavailable` with `Retry-After`: never a message published unvalidated; a breaker of the registry's own |
| `GET /orders/stream` (SSE) | Each event in JSON (Avro's JSON encoding), `datacontenttype: application/json`; a message that does not decode is not handed on (`flexway_async_deliver_total{outcome="invalid"}`) |
| `GET /orders/frames` (WebSocket) | A text frame (the attributes, the `id` to acknowledge among them), then a **binary** frame: the Avro payload as it is |
| Webhook (`x-flexway-deliver`) | A CloudEvent body with the data transcoded to JSON; the registry unreachable: the message is neither delivered nor acknowledged, it comes again |
| Protobuf | `schemaFormat: "application/vnd.google.protobuf;version=3"` and `schema: { $ref: "./reading.binpb#acme.Reading" }` - a compiled descriptor set (`protoc --descriptor_set_out --include_imports`, `buf build`), the message by its name; inline `.proto` sources are refused |
| CBOR | `contentType: application/cbor` and a JSON schema: the payload is read in CBOR's JSON model (RFC 8949 section 6.1) and checked against that schema |
| `GET /orders/audit/stream`, a record of an **ordinary Kafka producer** (wire format, no CloudEvents header) | Handed on in the envelope the gateway builds: `id` = `acme.orders.audit/<partition>/<offset>` (the same on every replica: the SSE `id` and `Last-Event-ID`, the `id` a WebSocket acknowledges, the `webhook-id`), `source` = `/flexway/orders-brokers/audit`, `type` = `audited`, `time` = the Kafka timestamp, `datacontenttype: application/json` after transcoding; **no** `tenant` attribute: the tenant is the bound channel's, never a header nor the message's content |
| A record without attributes on another channel, or one that carries a `ce_*` attribute without being an event | Not an event, as in `1.5.0`: not handed on (`flexway_async_deliver_total{outcome="invalid"}`) |
| The registry's writer schema differs from the contract's | **Resolved** to the contract's schema by Avro's standard rules (a field added with a default, a field removed, `int` -> `long`, aliases, an enum's default symbol): the same JSON as a message written under the contract's schema; resolved once per pair (schema id, contract schema), `max_schemas` pairs kept. Identical schemas (one canonical form) cost nothing more |
| The writer schema does not resolve to the contract's (a field without a default, an incompatible type) | Refused whole, never handed on in part: `422 invalid_request` on publication; on consumption not handed on, as a payload that does not decode - SSE at most once, WebSocket acknowledged, webhook dead-lettered -, the consumption goes on; counted `outcome="incompatible"` |
| `x-flexway-key` on a binary message | The key is read in the message's **JSON** form: **one decoding per publication**, even with `x-flexway-validation: off` (a payload that does not decode is then refused with `422`) - a cost to weigh at a high rate; without a key, a payload not validated is relayed unread |

**Refused at load**: an unknown `schemaFormat` (RAML, OpenAPI's, Avro `2.x`), an Avro schema that is
invalid, recursive, or with an array whose items take no byte, a message absent from the descriptor
set, a binary schema `$ref` outside the AsyncAPI document's directory, the wire format without
`schema_registry` or on a broker that is not Kafka, `x-flexway-validation: off` on a JSON message (always
checked), `frames: binary` without a WebSocket or on a JSON message, a consumption of a wire-format
channel isolated by the `tenant` attribute alone (neither bound nor public): an ordinary producer writes
no attribute, and a tenant is never read from a message.

**Measure**: `flexway_async_payloads_total{operation, format, step, outcome}` - `step` is `validate` or
`transcode`, `outcome` `ok`, `invalid`, `not_attached`, `incompatible` or `unavailable`; never a value of the message
nor a schema id.

## NATS JetStream: publish from HTTP or an MCP tool

> Available since `1.6.0`; the example is validated by the binary and pinned by the tests.

An HTTP service or an agent publishes into a JetStream stream **without a NATS client**; `202` only after
the stream's `PubAck`, the `Idempotency-Key` becoming `Nats-Msg-Id` - the stream deduplicates a resend after a `504`.
The gateway creates **no** stream: an existing stream must capture the subject, otherwise `502 upstream_error`.

<!-- example: examples/async-nats-jetstream/flexway.yaml -->

```yaml
# NATS JetStream behind the gateway's controls (1.6.0): an HTTP door and an MCP tool publish
# to a stream without a NATS client - 202 only after the stream's PubAck, the Idempotency-Key as
# Nats-Msg-Id. The gateway creates no stream: a subject no stream captures answers 502.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  orders-nats:
    protocol: nats
    brokers: ["tls://nats-0.nats:4222", "tls://nats-1.nats:4222"]   # nats:// or tls://, never a credential in the URL
    tls: { server_name: nats.internal }
    nats:
      credentials: "file:/etc/flexway-secrets/nats/flexway.creds"   # the gateway's NATS user: JWT and nkey seed
      jetstream: true                            # 202 after the stream's PubAck; false (NATS Core) refuses a publication
    timeout: 2s                                  # one publication's budget, the PubAck included
    max_in_flight: 512                           # bounded buffer: past it, 503 overloaded
auth:
  issuers:
    - name: customers
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: api
      tenant_claim: org                          # the tenant every subject below is bound to
agents:
  mcp:
    resources:
      api.example.com: https://api.example.com/mcp
```

```yaml
# examples/async-nats-jetstream/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Orders, version: 1.0.0 }
channels:
  orderCreated:
    address: "orders.{tenant}.created"          # captured by the ORDERS stream (orders.>): the gateway creates no stream
    parameters:
      tenant: { x-flexway-bind: tenant }
    messages:
      created:
        contentType: application/json
        payload: { type: object, required: [orderId], properties: { orderId: { type: string } } }
operations:
  publishOrderCreated:
    action: send
    channel: { $ref: "#/channels/orderCreated" }
    x-flexway-upstream: orders-nats
```

```yaml
# examples/async-nats-jetstream/openapi.yaml
openapi: 3.1.0
info: { title: Orders, version: "1.0.0" }
components:
  securitySchemes:
    customers: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /orders/events:
    post:
      operationId: emitOrderCreated
      x-flexway-publish: { operation: publishOrderCreated, idempotency: required }   # Idempotency-Key -> Nats-Msg-Id
      x-flexway-tool: { name: emit_order_created }   # the same door, offered to agents as an MCP tool
      security: [ { customers: [orders:write] } ]
      requestBody:
        required: true
        content:
          application/json: { schema: { type: object, required: [orderId], properties: { orderId: { type: string } } } }
      responses: { "202": { description: Acknowledged by the stream } }
```

| What happens | NATS JetStream |
| --- | --- |
| `POST /orders/events` | Admission, body checked, CloudEvents in binary mode (`ce-*` headers), published on `orders.acme.created`, `202` after the `PubAck` |
| The same call as an MCP tool (`emit_order_created`) | The same decision, the same acknowledgement |
| `jetstream: false` (NATS Core) | **Refused at load**: Core acknowledges nothing, a `202` would lie |
| No stream captures the subject | `502 upstream_error` ("no responders"), never a `202` |

## NATS: SSE and WebSocket bound to the tenant, wildcards, NATS Core

> Available since `1.6.0`; the example is validated by the binary and pinned by the tests.

A dashboard reads **every** order event of its tenant from one stream, thanks to a wildcard **inside the
channel** after the bound segment; an operator reads the metrics of **its own** site on a NATS Core server
(SSE only, at most once); a public screen reads the status without a token. Each message received is checked against the
channel's pattern, segment by segment: a broker that sent too much never leaks a tenant (RG-70).

<!-- example: examples/async-nats-streams/flexway.yaml -->

```yaml
# NATS in server-sent events and WebSocket (1.6.0): a dashboard reads every order event of
# its tenant through a wildcard written in the channel after the bound segment; an operator reads its
# own site's readings from NATS Core (server-sent events only, at most once); a public status is read
# without a token. Two brokers, two identities.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  orders-nats:
    protocol: nats
    brokers: ["tls://nats-0.nats:4222"]
    tls: { server_name: nats.internal }
    nats:
      token: "file:/etc/flexway-secrets/nats/token"   # a token, by reference - over TLS only
      jetstream: true
  metrics-core:
    protocol: nats
    brokers: ["nats://nats-edge.plant:4222"]
    sasl: { mechanism: PLAIN, username: flexway, password: "file:/etc/flexway-secrets/nats-edge/password" }
    tls: { server_name: nats-edge.plant }
    nats:
      jetstream: false                           # NATS Core: server-sent events only - no publication, WebSocket nor webhook
auth:
  issuers:
    - name: operators
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: api
      tenant_claim: org
```

```yaml
# examples/async-nats-streams/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Orders and metrics, version: 1.0.0 }
channels:
  orderFeed:
    address: "orders.{tenant}.>"                # the wildcard IN the channel, after the segment bound to the tenant
    parameters:
      tenant: { x-flexway-bind: tenant }
    messages:
      any:
        payload: { type: object, required: [orderId], properties: { orderId: { type: string } } }
  siteMetrics:
    address: "sites.{site}.metrics.*"           # bound to a claim of the token: an operator reads its own site
    parameters:
      site: { x-flexway-bind: "claim:site" }
    messages:
      # Written as application/cloudevents+json by a producer outside the gateway: read in structured mode.
      reading:
        payload: { type: object, required: [value], properties: { value: { type: number } } }
  status:
    address: status.public                       # binds nothing, filters nothing: declared public below
    messages:
      state:
        payload: { type: object, required: [state], properties: { state: { type: string } } }
operations:
  receiveOrders: { action: receive, channel: { $ref: "#/channels/orderFeed" }, x-flexway-upstream: orders-nats }
  receiveMetrics: { action: receive, channel: { $ref: "#/channels/siteMetrics" }, x-flexway-upstream: metrics-core }
  receiveStatus:
    action: receive
    channel: { $ref: "#/channels/status" }
    x-flexway-upstream: orders-nats
    x-flexway-public: true                       # read by anyone, anonymous included
```

```yaml
# examples/async-nats-streams/openapi.yaml
openapi: 3.1.0
info: { title: Orders and metrics, version: "1.0.0" }
components:
  securitySchemes:
    operators: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /orders/stream:
    get:
      operationId: streamOrders
      # SSE: one ordered consumer per channel and replica; WebSocket: one durable consumer per subscriber, AckWait = ack_timeout
      x-flexway-subscribe: { operation: receiveOrders, transport: [sse, websocket], max_streams: 2, ack_timeout: 30s, history: 64 }
      security: [ { operators: [orders:read] } ]
      responses: { "200": { description: The caller's tenant's orders } }
  /metrics/stream:
    get:
      operationId: streamMetrics
      x-flexway-subscribe: { operation: receiveMetrics, transport: [sse], history: 0 }   # NATS Core: SSE only
      security: [ { operators: [metrics:read] } ]
      responses: { "200": { description: The readings of the caller's site } }
  /status:
    get:
      operationId: streamStatus
      x-flexway-subscribe: { operation: receiveStatus, transport: [sse], max_anonymous_streams: 1000 }
      security: []
      responses: { "200": { description: The public status } }
```

| Rule | Behaviour |
| --- | --- |
| Wildcard | `*` and `>` only in a channel that is read, **after** the bound segments, `>` last - `orders.>.{tenant}` is refused; a bound value never holds `.`, `*` or `>`. The same rule for `+` and `#` in MQTT, and for `*` and `#` in the AMQP 0-9-1 binding key of an exchange (`audit.{tenant}.#`, served since `1.5.0`) |
| SSE | One JetStream ordered consumer (or one Core subscription) per channel and replica, whatever the number of subscribers; `Last-Event-ID` resumed from the channel's history, `id` = the stream sequence |
| WebSocket | A durable consumer per subscriber, `AckWait` = `ack_timeout`; refused at load on NATS Core |
| CloudEvents | Binary (`ce-*`) or structured by content type; the `tenant` attribute filtered in the headers, never in `data` |

## NATS JetStream: a webhook from a durable consumer

> Available since `1.6.0`; the example is validated by the binary and pinned by the tests.

A partner receives **its** tenant's invoices as signed webhooks, with no access to NATS: a durable consumer
**shared** by the replicas (one replica per message), acknowledged after the `2xx`, a declared dead-letter
channel once the retries are spent. No HTTP door: no OpenAPI contract is needed.

<!-- example: examples/async-nats-webhook/flexway.yaml -->

```yaml
# NATS JetStream delivered by webhook (1.6.0): a partner receives its tenant's invoices as
# signed webhooks, without access to NATS - a durable consumer the replicas share (one replica per
# message), acknowledged after the 2xx, the declared dead letter once the retries are spent. No HTTP
# door: no OpenAPI contract. Refused on NATS Core, which redelivers nothing.
version: 1
contracts:
  asyncapi: ./asyncapi.yaml
upstreams:
  billing-nats:
    protocol: nats
    brokers: ["tls://nats-0.nats:4222"]
    tls: { server_name: nats.internal }
    nats:
      nkey_seed: "file:/etc/flexway-secrets/nats/flexway.nk"   # an nkey seed alone, by reference
      jetstream: true                            # a delivery needs JetStream: a durable consumer the replicas share
  partner-hook:
    protocol: webhook
    url: https://hooks.partner.example/invoices
    secrets: ["file:/etc/flexway-secrets/hooks/current"]
    retries: { max: 8, max_delay: 10m }
```

```yaml
# examples/async-nats-webhook/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Invoices, version: 1.0.0 }
channels:
  invoiceIssued:
    address: "invoices.{tenant}.issued"
    parameters:
      tenant: { x-flexway-bind: tenant }       # a delivery has no caller: bound to the tenant only
    messages:
      issued:
        payload: { type: object, required: [invoiceId], properties: { invoiceId: { type: string } } }
operations:
  receiveInvoices:
    action: receive
    channel: { $ref: "#/channels/invoiceIssued" }
    x-flexway-upstream: billing-nats
    x-flexway-deliver:
      - { upstream: partner-hook, tenant: acme, dead_letter: invoices.dead }   # a subject a stream captures
```

On NATS Core, the same delivery is **refused at load**: nothing delivers again a message the target did not take.

## AMQP 1.0: publish to Azure Service Bus, deliver from a subscription

> Available since `1.6.0`; the example is validated by the binary and pinned by the tests.

An HTTP service publishes into its tenant's Service Bus topic (`202` after the `accepted` disposition);
a partner receives, as webhooks, what the subscription the operator created reads. Two channels, one to
write, one to read: no extension. The gateway authenticates with a **SAS key** over SASL PLAIN.

<!-- example: examples/async-amqp1-servicebus/flexway.yaml -->

```yaml
# AMQP 1.0 toward Azure Service Bus (1.6.0): an HTTP service publishes to its tenant's
# topic - 202 after the disposition accepted -, a partner receives by webhook what the subscription the
# operator created reads. Two channels, one to write, one to read: no extension. The gateway
# authenticates with a SAS key over SASL PLAIN.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  billing-bus:
    protocol: amqp
    protocol_version: "1.0"                      # AMQP 1.0; 0-9-1 stays the default
    brokers: ["amqps://acme-billing.servicebus.windows.net"]
    sasl: { mechanism: PLAIN, username: flexway-send, password: "file:/etc/flexway-secrets/servicebus/key" }   # SAS key name and key
    amqp1: { broker: servicebus }                # publication and webhook; server-sent events and WebSocket refused
    timeout: 3s                                  # the disposition accepted included
  partner-hook:
    protocol: webhook
    url: https://hooks.partner.example/invoices
    secrets: ["file:/etc/flexway-secrets/hooks/current"]
auth:
  issuers:
    - name: customers
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: api
      tenant_claim: org
```

```yaml
# examples/async-amqp1-servicebus/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Invoices, version: 1.0.0 }
servers:
  servicebus: { host: acme-billing.servicebus.windows.net, protocol: amqp, protocolVersion: "1.0" }
channels:
  invoices:
    address: "invoices-{tenant}"                # the tenant's Service Bus topic, created by the operator
    parameters:
      tenant: { x-flexway-bind: tenant }
    bindings: { amqp1: {} }
    messages:
      issued:
        payload: { type: object, required: [invoiceId], properties: { invoiceId: { type: string } } }
  invoicesForPartner:
    address: "invoices-{tenant}/Subscriptions/flexway-partner"   # the subscription, created by the operator
    parameters:
      tenant: { x-flexway-bind: tenant }
    bindings: { amqp1: {} }
    messages:
      issued:
        payload: { type: object, required: [invoiceId], properties: { invoiceId: { type: string } } }
operations:
  publishInvoice: { action: send, channel: { $ref: "#/channels/invoices" }, x-flexway-upstream: billing-bus }
  deliverInvoices:
    action: receive
    channel: { $ref: "#/channels/invoicesForPartner" }
    x-flexway-upstream: billing-bus
    x-flexway-deliver:
      - { upstream: partner-hook, tenant: acme, dead_letter: invoices-dead }   # a dead-letter queue of its own, with problemcode
```

```yaml
# examples/async-amqp1-servicebus/openapi.yaml
openapi: 3.1.0
info: { title: Invoices, version: "1.0.0" }
components:
  securitySchemes:
    customers: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /invoices:
    post:
      operationId: issueInvoice
      x-flexway-publish: { operation: publishInvoice, idempotency: required }   # Idempotency-Key -> the message-id
      security: [ { customers: [invoices:write] } ]
      requestBody:
        required: true
        content:
          application/json: { schema: { type: object, required: [invoiceId], properties: { invoiceId: { type: string } } } }
      responses: { "202": { description: Accepted by Service Bus } }
```

| What happens | AMQP 1.0 |
| --- | --- |
| `POST /invoices` | The broker settles the message: `accepted` -> `202`; `rejected` -> `502 upstream_error`; past the budget -> `504`, unknown outcome |
| Delivery | Competing receivers on the subscription (one replica per message), `accepted` after the `2xx`; retries spent: the event in `invoices-dead` with `problemcode`, never the broker's own dead-letter queue |
| SSE or WebSocket on Service Bus | **Refused at load**: no non-competing source without a broker-specific means |
| Entra ID token (CBS) | Out of the scope of `1.6.0`: SAS key only |

## AMQP 1.0: consume RabbitMQ 4 in SSE and WebSocket

> Available since `1.6.0`; the example is validated by the binary and pinned by the tests.

RabbitMQ 4 speaks AMQP 1.0 natively. Each player reads **its own** notifications (a channel bound to the
verified subject), in SSE or acknowledged WebSocket; everyone reads the public scoreboard. `amqp1.broker: rabbitmq`
says how to open a **non-competing** source: an exclusive queue bound to the exchange, as the AMQP 0-9-1
adapter already does; a webhook delivery reads a `/queues/...` queue as it is. The gateway authenticates over SASL PLAIN
on TLS; `EXTERNAL` takes its client certificate (`tls.cert_file`), `ANONYMOUS` is admitted with mTLS or inside a declared
mesh only. SSE or WebSocket on a `/queues/...` queue: **refused at load** (its consumers share it).

<!-- example: examples/async-amqp1-rabbitmq/flexway.yaml -->

```yaml
# AMQP 1.0 toward RabbitMQ 4 (1.6.0): each player reads its own notifications (bound to the
# verified subject) in server-sent events or an acknowledged WebSocket; anyone reads the public
# scoreboard. amqp1.broker: rabbitmq says how to read without competing: a queue of the gateway's own,
# bound to the exchange through RabbitMQ 4's management node. The gateway authenticates as its own
# user (SASL PLAIN over TLS); EXTERNAL takes its client certificate instead.
version: 1
contracts:
  openapi: ./openapi.yaml
  asyncapi: ./asyncapi.yaml
upstreams:
  games-bus:
    protocol: amqp
    protocol_version: "1.0"
    brokers: ["amqps://rabbitmq.internal:5671"]
    tls: { server_name: rabbitmq.internal }      # cert_file and key_file with sasl EXTERNAL: the certificate is the identity
    sasl: { mechanism: PLAIN, username: flexway, password: "file:/etc/flexway-secrets/rabbitmq/password" }
    amqp1: { broker: rabbitmq }                  # an exclusive queue bound through the management node
auth:
  issuers:
    - name: players
      discovery: https://login.example.net/.well-known/openid-configuration
      audience: games
      tenant_claim: org
```

```yaml
# examples/async-amqp1-rabbitmq/asyncapi.yaml
asyncapi: 3.0.0
info: { title: Game events, version: 1.0.0 }
channels:
  notifications:
    address: "/exchanges/notifications/players.{sub}"   # a RabbitMQ 4 v2 address: exchange and routing key
    parameters:
      sub: { x-flexway-bind: subject }         # a player reads its own channel, and only it
    bindings: { amqp1: {} }
    messages:
      note:
        payload: { type: object, required: [text], properties: { text: { type: string } } }
  scores:
    address: "/exchanges/scores/public"
    bindings: { amqp1: {} }
    messages:
      # Written as application/cloudevents+json by an outbox: read in structured mode.
      score:
        payload: { type: object, required: [match], properties: { match: { type: string } } }
operations:
  receiveNotifications: { action: receive, channel: { $ref: "#/channels/notifications" }, x-flexway-upstream: games-bus }
  receiveScores:
    action: receive
    channel: { $ref: "#/channels/scores" }
    x-flexway-upstream: games-bus
    x-flexway-public: true                       # read by anyone, anonymous included
```

```yaml
# examples/async-amqp1-rabbitmq/openapi.yaml
openapi: 3.1.0
info: { title: Game events, version: "1.0.0" }
components:
  securitySchemes:
    players: { type: openIdConnect, openIdConnectUrl: https://login.example.net/.well-known/openid-configuration }
paths:
  /me/notifications:
    get:
      operationId: streamMyNotifications
      # WebSocket: settled accepted after {"ack": "<id>"}, released past ack_timeout - delivered again
      x-flexway-subscribe: { operation: receiveNotifications, transport: [sse, websocket], max_streams: 3, ack_timeout: 20s }
      security: [ { players: [] } ]
      responses: { "200": { description: The caller's own notifications } }
  /scores:
    get:
      operationId: streamScores
      x-flexway-subscribe: { operation: receiveScores, transport: [sse], max_anonymous_streams: 500, history: 128 }
      security: []
      responses: { "200": { description: The public scoreboard } }
```

With Artemis (`broker: artemis`, a multicast attach) or Solace (`broker: solace`, `topic://`), the same
declaration; with `generic` or `servicebus`, SSE and WebSocket are **refused at load**.
