Realtime and the bell
Publish app events to users, records or the whole site, add bell entries, and listen in the browser.
Realtime messages go out after the transaction commits, on any node, and never after a rollback.
Publish an event
Cardinal.Realtime.publish(ctx, topic, event, payload) queues a message. It returns {:ok, :ok, effects}, so a hook passes the effects on. CRM tells a user's open pages to refetch notifications:
@impl true
def on_update(%{"to_user" => to} = rec, _old, ctx) when to not in [nil, ""] do
with {:ok, :ok, fx} <- Cardinal.Realtime.publish(ctx, "user:" <> to, "crm.notification"),
do: {:ok, rec, fx}
end| Topic | Who hears it |
|---|---|
user:<name> | Every session of that user |
rec:<rectype>/<name> | Sessions that subscribed to the record |
tenant | Every session of the site. Put nothing private in the payload |
The event name is <app>.<name>, starting with an installed app's name. Core's own events have no dot, so an app cannot send one. The payload is a flat map of scalars. publish/4 raises outside a transaction.
An open desk refetches its boot on each <app>.<name> event on tenant. Eden uses this to show or hide its panel when Eden Settings change:
{:ok, :ok, effects} = Cardinal.Realtime.publish(ctx, "tenant", "eden.settings")Listen in the browser
import { subscribe } from '@cardinal/sdk'
const sub = subscribe(`user:${user}`, {
message: (event, payload) => {
if (event === 'crm.notification') reload()
},
refetch: () => reload(),
})
// later
sub.leave()| Handler | Runs |
|---|---|
message(event, payload) | On each event, core's rec_update and list_update included |
joined() | Each time the server accepts the join |
refetch() | After a reconnect, when messages may have been missed |
refused(reason) | When the server refuses the topic, forbidden or unauthorized |
Bell entries
Cardinal.Notify.create(ctx, users, values) writes a Notification Log for each user and moves their bell count live.
{:ok, _names, fx} =
Cardinal.Notify.create(ctx, ["rep@acme.test"], %{
subject: "Deal Acme won",
type: "Alert",
document_type: "CRM Deal",
document_name: "CRM-DEAL-0001"
})| Key | Meaning |
|---|---|
subject | Required |
type | Alert (default), Mention, Assignment or Share |
document_type, document_name | The record the bell entry opens |
A disabled or unknown user gets nothing. The caller gets an entry only for type Alert. Return fx from the hook, or {:after_commit, value, fx} from a transaction.