[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationRealtime

Realtime

Publish events on topics from the backend, and how page-bound topics reach the browsers viewing the page.

Overview

Realtime works on topics. A topic is a plain string that a page declares interest in, and any backend code can publish a message on it. RegisterPageTopic binds a topic to a page id. PublishMessage sends an event on that topic to every client session subscribed to it. SubscribeMessage is the read half. It lets backend code receive what is published, in addition to the streams the dashboard opens for its pages.

Everything on this page lives in @antelopejs/interface-dms/realtime.

How a page ends up subscribed

The page-topic registry derives the subscriptions. The publisher never requests them.

  1. A page, or a component on it, calls RegisterPageTopic(pageId, topic) at registration time. pageId is the page's fullId (Pages and modules), not its slug.
  2. A client opens a realtime session and reports which page it is on. The backend checks that the user may access that page. It then subscribes the session to every topic registered for that page id, and drops the topics the session no longer needs.
  3. PublishMessage(topic, type) delivers to the sessions subscribed to topic. With a tenantId, it delivers only to the sessions of that tenant (see Tenant-scoped messages).

A publisher never addresses a page or a user. It addresses a topic, and the page-topic registry decides who is listening.

A page's topics are a set, so registering the same topic for the same page twice has no further effect.

A binding belongs to the module that registered it. The DMS removes the binding when that module is unloaded. The binding survives a reload of the DMS module, which gets every binding back from the core. A registration from onCreated, as in the next example, makes the module whose page it is the owner.

Register a topic for a page

The usual caller is the onCreated callback of a component builder. The callback receives the page the component was declared on, typed CreatedPage: its target, and its pageInfo.fullId and pageInfo.fullSlug. At run time it is the page's PageMetadata (Components).

typescript
import { ComponentBuilder } from "@antelopejs/interface-dms/component";
import { RegisterPageTopic } from "@antelopejs/interface-dms/realtime";

export const STOCK_TOPIC = "catalog:stock";

export function StockCounter(options: { fetchUrl: string }) {
  return new ComponentBuilder<{ fetchUrl: string }>("acme-stock-counter")
    .options(options)
    .onCreated((page) => {
      const pageInfo = page.pageInfo;
      if (!pageInfo) return;
      RegisterPageTopic(pageInfo.fullId, STOCK_TOPIC);
    });
}

A registration from onCreated makes the binding follow the component, because every page the component is placed on gets the topic. The blocks of the Base domain that take a realtimeTopic option, such as the chart and KPI cards, work the same way. Each one registers its topics on the page it is placed on.

To bind a topic to a page you know when you write the code, call RegisterPageTopic with that page's fullId.

typescript
RegisterPageTopic(pageId: string, topic: string): void

Publish a message

typescript
import { Controller, Post } from "@antelopejs/interface-api";
import { PublishMessage } from "@antelopejs/interface-dms/realtime";
import { STOCK_TOPIC } from "../components/stock-counter";

export class StockController extends Controller("/api/stock") {
  @Post("/restock")
  async restock(): Promise<{ ok: boolean }> {
    await applyRestock();
    await PublishMessage(STOCK_TOPIC, "stock.updated", {
      payload: { warehouse: "eu-west" },
      actorId: "system",
    });
    return { ok: true };
  }
}
typescript
PublishMessage(
  topic: string,
  type: string,
  options?: PublishMessageOptions,
): Promise<void>
ParameterDescription
topicThe topic to publish on. The browser sessions that receive it are those on a page that registered this topic. Backend SubscribeMessage handlers on the topic receive it regardless.
typeThe event type carried with the message, for subscribers that tell apart several kinds of event on one topic.
optionsThe optional payload, actor and tenant.

PublishMessageOptions

OptionTypeDescription
payloadRecord<string, unknown>Data carried with the event.
actorIdstringWho caused the event, so a client can ignore an event it triggered itself.
tenantIdstringThe tenant the event is about. Only the sessions of that tenant receive it. Without it, the message is global and reaches every tenant.

PublishMessage resolves once the broker has the message. It does not report how many sessions received it. A message on a topic that no page registered is not an error. It reaches no browser session, and backend SubscribeMessage handlers on the topic still receive it.

Tenant-scoped messages

Every tenant shares the page topics, because a page registers the same topic whichever workspace views it. A message published without a tenantId reaches the sessions of every workspace on that page. Each of those pages refetches, and a paused live page counts the message in its "N new" banner. Publish the data of a workspace with the tenant it belongs to:

typescript
import { getRequestTenantId } from "@antelopejs/interface-dms/request-tenant";

await PublishMessage(CAMPAIGN_TOPIC, "campaign.sent", {
  payload: { count: sent.length },
  tenantId: getRequestTenantId(ctx), // or the tenant a job runs for
});

A session belongs to the tenant of the request that opened it. It receives the messages of that tenant and the global ones. When the browser switches workspace or account, the client opens a new session in the new one. The server ends a session whose page requests come from another workspace or account, so the messages of the previous workspace stop with it. The tabs of a browser share one connection, and the server ends the session of one tab alone. The sessions of the other tabs stay open. Keep messages without a tenant for data that is the same for every workspace, such as a platform-wide setting or a catalog that every tenant shares.

A platform page is a page of a module, which only the platform owner opens. A session on a platform page receives the messages of every tenant on that page's topics, whichever workspace the owner has open, because such a page lists the data of all of them.

The table views of the Base domain publish their row changes and presence for the tenant of the writer. When their rows live in the shared core schema, they publish for every tenant. Messages to one user (notifications) and the menu invalidations already name their audience in the topic.

Subscribe from the backend

SubscribeMessage receives every message published on a topic, whichever instance and whichever tenant published it. A handler that serves one tenant filters on message.tenantId itself. The subscription uses the same broker as PublishMessage, so what one instance publishes reaches the subscribers on every other instance.

typescript
import { SubscribeMessage } from "@antelopejs/interface-dms/realtime";
import { STOCK_TOPIC } from "../components/stock-counter";

const unsubscribe = SubscribeMessage(STOCK_TOPIC, (message) => {
  if (message.type !== "stock.updated") return;
  const warehouse = message.payload?.warehouse;
  if (typeof warehouse === "string") {
    void refreshWarehouseCache(warehouse);
  }
});
typescript
function SubscribeMessage(
  topic: string,
  handler: RealtimeMessageHandler,
): UnsubscribeMessage;

type RealtimeMessageHandler = (message: RealtimeMessage) => void;
type UnsubscribeMessage = () => void;

RealtimeMessage

FieldTypeDescription
topicstringThe topic the message was published on.
typestringThe event type given to PublishMessage.
payloadRecord<string, unknown>Data carried with the event, when the publisher sent any.
actorIdstringWho caused the event, when the publisher named an actor.
tenantIdstringThe tenant the message was published for. Absent on a global message.
tsnumberThe publication timestamp, in milliseconds since the epoch.

With PublishMessage and SubscribeMessage together, a module can run realtime channels of its own on the DMS broker. Its own endpoint subscribes here and the DMS carries the messages, so the module needs no second broker.

Design a subscriber around three properties:

  • Handlers must not throw. The DMS calls them on the event loop of the delivering instance. The broker catches a thrown error or a rejected promise and logs it, and the error never reaches the publisher.
  • Delivery is fire-and-forget. The broker keeps no message for later. A message published while nobody was subscribed is gone, so do not use a topic as a queue.
  • Unsubscribing is automatic when the registering module is unloaded. Call the returned UnsubscribeMessage to end a subscription earlier. A second call has no effect.

Next steps

Quick actions covers another way a module reaches the running dashboard: entries in the command palette.