WebSocket & SSE

Change streams

RESTHeart Ulabase
Note
Change streams can be consumed via WebSocket or SSE. This page covers the stream definition format. For the SSE transport see SSE API Overview.

The "streams" collection metadata

A collection has properties of its own, as a document does. RESTHeart reads some of them as metadata, which change how it serves the collection.

The metadata property streams declares the change streams of the collection. Each one is bound to a URI, and a client that opens it is notified of the changes to the documents.

A client can open only the streams declared here. The developers write and test them, and the client cannot write one of its own.

streams is an array of stream definitions.

Stream definition format

{ "streams": [
    {
        "uri": <uri>,
        "stages": [
            "<stage_1>",
            "<stage_2>",
            ...
        ]
    }
]}
Property Description Mandatory

uri

specifies the URI when the stream is bound under the path /<db>/<collection>/_streams

yes

stages

the MongoDB aggregation pipeline stages. For more information refer to Aggregation Pipeline on MongoDb documentation.

yes

Note
The input of the stages is a Change Event, which wraps the document. After a PATCH, for example, the modified document is in the fullDocument property of the event. See the examples.

Optional Stages

A stream can have optional stages, applied only when the client binds one or more variables. They work as in aggregations: see Optional stages.

Note
An optional stage puts a variable in the stages, so it opens one MongoDB cursor per distinct binding, as explained under notify_when. For a selection that differs per client, use notify_when.

Escaped stage properties

MongoDB, up to v5, refuses to store a field whose name starts with $ or contains a dot.

A stage has both. RESTHeart escapes the keys when it stores the definition:

  • the $ prefix is "underscore escaped", e.g. $exists is stored as _$exists

  • if the dot notation has to be used in a key name, dots are replaced with :: e.g. SD.prop is stored as SD::prop

Per-client filtering: notify_when

Available from RESTHeart 9.4.

notify_when is an optional field of a stream definition. It decides which connected clients receive each change event.

Every client of the stream shares one MongoDB cursor, whatever value it binds. A { "$var": …​ } in a stage works differently: it changes the pipeline, and RESTHeart opens one cursor per distinct set of bound variables. A thousand users who filter in the stages are a thousand change streams on MongoDB. Keep the stages fixed, and put the variables the client binds in notify_when.

{
  "streams": [{
    "uri": "by-tenant",
    "stages": [
      { "_$match": { "operationType": { "_$in": ["insert", "update"] } } }
    ],
    "notify_when": {
      "fullDocument::tenantId": { "$var": "tid" }
    }
  }]
}

The client passes its variable value as a query parameter when connecting:

# SSE — only receives events where fullDocument.tenantId == "acme"
curl -N \
  -H 'Accept: text/event-stream' \
  -H 'Authorization: Basic YWRtaW46c2VjcmV0' \
  'http://localhost:8080/mydb/mycoll/_streams/by-tenant?tid=acme'

The variable is bound like any other stream variable (see Using Variables): ?tid=acme and ?avars={"tid":"acme"} are equivalent, and when both are given the avars value wins. Before 9.12.2 notify_when read only the plain query parameter.

Since v9.17 the variable of notify_when goes through the same operator check as the stage variables: ?tid={"$ne":null} gets 400. See Security considerations.

Events per user: notify_when on @user

Since v9.16 notify_when also accepts the variables the server resolves for the caller, @user._id and @user.<property>. Each client then receives only the events of its own documents, on the one cursor of the stream:

{
  "uri": "mine",
  "stages": [ { "_$match": { "operationType": { "_$in": ["insert", "update", "replace"] } } } ],
  "notify_when": { "fullDocument::owner": { "$var": "@user._id" } }
}

The server resolves the variable when the session opens. It never reads it from the request, so a client cannot pick another user’s events with a query parameter. If the variable is not bound for the caller, the connection is refused with 400: a JWT account, for instance, has @user.sub and no @user._id (see Identifying the caller).

The comparison is between values of the same type: an ObjectId owner matches an ObjectId _id, and does not match its string form.

Field path notation

The notify_when key uses :: to separate the top-level change event field from the dotted path within it:

"fullDocument::tenantId"       # fullDocument.tenantId
"fullDocument::org.department" # fullDocument.org.department (nested)
"documentKey::_id"             # documentKey._id

Supported predicates

Form Description Example

Scalar equality

Field value equals the bound variable. A variable from the request is a string; one the server resolves keeps its type, as an ObjectId

{ "fullDocument::tenantId": { "$var": "tid" } }

Array membership

Bound variable value is contained in an array field

{ "fullDocument::recipients": { "$var": "userId" } }

Design notes

  • stages are sent to MongoDB and applied once on the shared cursor. Keep them fixed (e.g. operationType, fullDocument.status): a variable there means one cursor per distinct binding.

  • notify_when is evaluated server-side per event × per connected client. Use it for conditions that depend on per-client variables.

  • Without notify_when, every client receives every event.

  • If a client connects without binding the variable, neither as a query parameter nor in avars, the request fails with 400 and variable not bound, as for an unbound stage variable. Before 9.12.2 such a client received every event of the stream (pass-through).

Warning

notify_when on a variable of the request does not keep users apart. The client binds ?tid= itself, and can bind any value it can name. To keep users apart, use notify_when on a @user variable (see Events per user: notify_when on @user), or a stage that matches on one.

Change streams and permissions

Since v9.16 change streams do not apply the readFilter and projectResponse of the permission, as aggregations do not (see Aggregations and permissions). The stream segregates the events itself, so that every client of a stream shares one cursor:

  • with notify_when on a @user variable;

  • or with stages that use @user or @mongoPermissions.

To hide fields, the stages use $project, the same for every client.

A stream allowed by a permission with a readFilter, which segregates in neither way, is refused with 403. The client gets Cannot open change stream: not allowed, and the log of RESTHeart says why, at WARN. Before v9.16 such a stream sent each user only the events the readFilter allowed. Without the check, after the upgrade it would send every event to everyone, with no error. A stream meant for every event declares it:

{ "uri": "all", "stages": [], "segregation": "none" }

Last-Event-ID limitation

With notify_when, Last-Event-ID is ignored on reconnect and a warning is logged: the shared cursor cannot go back for one client. A client that reconnects reads the events it missed through the REST API, as described in Recovering missed events.

Keeping a WebSocket alive

The server sends a ping on an idle stream every change-streams-keep-alive-ms (20 seconds by default), and since 9.9.2 answers the client’s pings with a pong. Anything else the client sends is ignored.

A connection can die without a close reaching the client, for instance while its computer sleeps: the socket stays open and no event ever arrives. A client that wants to know sends pings and reconnects when the pong does not come back. With websocat:

websocat --ping-interval 20 --ping-timeout 60 autoreconnect:wss://example.com/coll/_streams/all -

Recovering missed events

A WebSocket delivers events only while connected. After a reconnection, ask the REST API for what changed since the last event seen: every write through RESTHeart gives the document a new _etag, an ObjectId that grows with time, so

GET /coll?filter={"_etag":{"$gt":{"$oid":"<last _etag seen>"}}}&sort={"_etag":1}

returns the documents inserted or updated since then, in order. Deleted documents do not show up.

See SSE API Overview for details on the SSE transport and event format.