Subscribe to Database updates

import { DatabaseUpdate } from '@diana-db/odm';

/* 'user.post' = database 'user', collection 'post'
   'user' alone = every collection in the 'user' database */
const onPost = (databaseUpdate: DatabaseUpdate) => {
  // handle databaseUpdate
};
await dianaDb.subscribe('user.post', onPost);

// later
await dianaDb.unsubscribe('user.post', onPost); // or unsubscribe('user.post') for every subscriber of the key
  
  • Several subscribers per key are allowed; one that throws doesn't affect the others.
  • Subscriptions use one dedicated connection per client. It reconnects on its own, is closed by disconnect(), and is closed when the last subscriber is removed.
  • Updates are delivered only for databases the user can read.
  • Since ODM 4.7.10 the client tells the server which keys it subscribed to, and a server from 4.8.17 on sends only those changes. An older server sends every change of the readable databases and the client drops the rest, as before.

DatabaseUpdate contract

The subscriber receives the update itself (since ODM 3.0.0; earlier versions passed the whole server message, with the update under data).

FieldTypeDescription
databasestringName of the database
collectionstringName of the collection
action'insert' | 'update' | 'remove'Type of operation
affectedIdsstring[]Ids of the affected documents
dataobject Insert: the inserted document; for insertMany the array of documents, left out when there are more than 100. Update: the update as it was sent (values or operators), not the whole document

Subscriber authentication

Since 4.6.5 a subscriber connection authenticates with the same challenge and response as every other connection and marks itself as a subscriber in its first line. Nothing changes in your code.

With a server or an ODM older than 4.6.5 the earlier form is used: a subscriber connection never sends requests, so it proves it knows the password in its handshake line instead:

user:<name>:subscriber:<token>
// token = AES-256-GCM(sha256(password), "user:<name>:subscriber:<UTC date YYYY-MM-DD>"), base64
  

The ODM builds the token on every (re)connect. In this form the server accepts dates from yesterday to tomorrow (UTC), so clock skew of up to a day is tolerated, and closes subscriber connections without a valid token.