Live updates
How admin pages update by themselves while they are open: a message appearing in the list as it is accepted, a recipient's state changing as it is delivered, an open recorded as it happens. This page is the design the live pages follow; the pages that use it are marked "live" in Admin interface: the server overview, the messages list and the message page, the received list and the received message page, the routes and endpoints lists and a route's and an endpoint's page, the suppressions list, the webhooks list, a webhook and a delivery, the organisation overview, the domains list and the domain page.
The model in one paragraph
When the core changes something a page may show, it announces the change after the database transaction commits: on a Phoenix.PubSub topic of the record it belongs to, with the kind of change and the ids involved, never content. A LiveView that shows such records subscribes after it has loaded them for the user, and on an announcement it reads the records again through the same scoped query it renders from, at most about once a second. The announcement only says "look again"; what the page shows always comes from a query that applies the user's access, as on first render.
core (after commit) PubSub (all nodes) LiveView of a user
─────────────────── ───────────────── ───────────────────
Messages.mark_accepted ─┐ mount: Authorize loads org/server
Deliverer (recording) ├─► Changes.broadcast ─► "server:<id>" ──────► LiveUpdates (connected): subscribe
Tracking.record ────────┘ %Change{kind, "message:<id>" %Change{} → mark dirty,
ids} "organisation:<id>" schedule :refresh (≤ 1 s)
:refresh → scope, access again →
page's refresh/2 (scoped query)Topics
Topics are named after the record whose pages show the change, from ids the core already has. A page subscribes to the topic of the record it loaded, so it can only ever hear about that record's changes.
| Topic | Kind (ids) | Announced by | Heard by |
|---|---|---|---|
server:<server_id> | :message_accepted (message ids) | Karta.Messages.mark_accepted/1: every way in (the sending APIs, a batch at once, SMTP submission and the MX listener, a delivery status notification) | the messages list, the server overview |
:recipients (message ids) | Karta.Outbound.Deliverer recording a delivery run | the messages list, the server overview | |
:tracking (message ids) | Karta.Tracking.record/5 (an open or a click) | nothing yet (the list and the overview do not show them) | |
:messages_removed (message ids) | Karta.Messages.discard/3 of accepted messages (retention) | the messages list, the server overview | |
:server (its id) | Karta.Servers: changed, suspended, resumed | the messages list and the server overview (its state, its settings, the suspended notice) | |
:webhooks (webhook ids) | Karta.Webhooks: added, changed, switched off or on, secret rotated, removed; Karta.Webhooks.Sender: switched off because it kept failing | the webhooks list, a webhook's page, a delivery's page | |
:webhook_deliveries (delivery ids) | Karta.Webhooks.Sender: a request made, or a delivery failed because its webhook is off | a webhook's page (its deliveries), a delivery's page (its requests) | |
:routes, :endpoints (route, endpoint ids) | Karta.Inbound: a route or an endpoint added, changed or removed | the routes list, a route's page, the endpoints list, an endpoint's page | |
:inbound_deliveries (message ids) | Karta.Inbound.Dispatcher: a run recorded what became of a received message's deliveries | the received list, the received message page | |
:suppressions (suppression ids) | Karta.Suppressions: an address suppressed or freed (a page, the API, a bounce, an unsubscribe) | the suppressions list | |
message:<message_id> | :recipients, :tracking, :messages_removed (its id) | as above, for one message | the message page |
:inbound_deliveries (its id) | Karta.Inbound.Dispatcher, for a received message | the received message page | |
organisation:<organisation_id> | :servers (server ids) | Karta.Servers: created, changed, suspended, resumed | the organisation overview |
:domains (domain ids) | Karta.Domains: added, verified, unverified, removed | the organisation overview, the domains list | |
domain:<domain_id> | :domain (its id) | Karta.Domains: verified, unverified, its ownership record checked (check_ownership/2), removed; Karta.DNS.Publish.publish/2: its records published (or the attempt failed); Karta.Domains.TLSReporting.update/2: its TLS reports' address set | the domain page |
:dkim_keys (its id) | Karta.Domains: a key generated, activated, rotated or retired; Karta.Domains.Rotation.advance/2: a rotation's key looked up | the domain page | |
:dns_checks (its id) | Karta.Domains.Health.run/2 (the hourly job, Check now) | the domain page | |
:tracking_host (its id) | Karta.Tracking.Hosts: its tracking host added, checked, removed | the domain page | |
:mta_sts (its id) | Karta.MTASTS.Hosting: the policy Karta serves for it saved, its CNAME record checked, removed | the domain page | |
:bimi (its id) | Karta.BIMI: its logo uploaded, its certificate's URL set, removed | the domain page | |
later: instance | a node, an import | the instance's pages |
The instance's IP pools and Warm-up plans pages
(/instance/…) poll instead, every five seconds: whether a node holds an
address is that node's own view of its network interfaces, which nothing
announces, and a warm-up count is computed from deliveries. They read the
pools again through the page's own queries, and every event is checked
against the instance administrator's scope as usual; nothing is
subscribed.
Sessions keep their own mechanism: ending a session broadcasts
"disconnect" to its live_socket_id (KartaWeb.UserAuth), which closes
that session's pages. The pages of a member whose role is changed, or who
is removed, are disconnected the same way
(KartaWeb.UserAuth.disconnect_user/1, from the members page), so that
they mount again under the new scope.
What is announced
Karta.Changes (the module the core broadcasts through) sends one struct:
%Karta.Changes.Change{
topic: "server:01938…",
kind: :recipients, # :message_accepted, :recipients, :tracking, …
ids: ["01939…"] # the records concerned (message ids here)
}- Ids and kinds only. No addresses, subjects, reply texts or anything else from a message: what a page shows it reads itself, through the query that applies the user's access. A broadcast reaches every node and every subscriber; it must be harmless to anyone who receives it.
- One announcement per transaction, topic and kind, with all the ids
it touched (a batch of messages accepted together is one
:message_accepted; a delivery run that also accepts a notification to the sender announces:recipientsand:message_acceptedon the server's topic). - The core calls
Karta.Changes.broadcast({:server, id}, kind, ids); a page callsKarta.Changes.subscribe(record)with a record it loaded (%Server{},%Message{},%Organisation{},%Domain{}), never with an id from the request.
After the commit, never before
A page that reads on an announcement made inside a transaction would read before the commit and see nothing new (or, after a rollback, announce something that never happened). So:
Karta.Changes.broadcast/3called outside a transaction sends at once.- Called inside a transaction it queues the announcement in the
process, and the transaction is run through
Karta.Changes.transaction/2(a wrapper ofKarta.Repo.transaction/2, for a function or anEcto.Multi), which sends the queue after the outermost transaction commits and drops it when it rolls back, fails or raises. - A broadcast inside a plain
Repo.transaction, orKarta.Changes.transaction/2inside one, is a programming error: withconfig :karta, Karta.Changes, strict: true(the test configuration) it raises, so the test suite finds it; in production it is sent at once and logged as a warning. - Every transaction that may announce runs through it: accepting a
message (
Karta.Outbound.accept/3and the batch acceptance of the sending APIs), recording a delivery run (Karta.Outbound.Deliverer, which accepts the notification to the sender in the same transaction). Later areas announce where their transaction ends, the same way.
The LiveView side
A page loads its record with KartaWeb.Authorize and then names it to
KartaWeb.LiveUpdates, which does the rest of this section:
on_mount {KartaWeb.Authorize, :server}
on_mount {KartaWeb.LiveUpdates, {:server, kinds: [:message_accepted, :recipients]}}
@behaviour KartaWeb.LiveUpdates
@impl KartaWeb.LiveUpdates
def refresh(socket, %{kinds: kinds, ids: ids}) do
# socket.assigns.current_scope, .organisation and .server were read again;
# read what the page shows through its own scoped query.
endThe rules:
- Subscribe after authorising, in
mount, when connected. The topic comes from the recordKartaWeb.Authorizeloaded (:organisation,:server,:domainor:message). - Never render what was announced. Re-read through the page's own
scoped query: the messages list runs its search again
(
Karta.Messages.search/3, orKarta.Messages.matching/3for the rows it shows, on its server with the search from its query string); the message page reloads its message within its server (Karta.Messages.get/2) and the recipients, deliveries and events of that message. An id that the scoped query does not return is ignored, so a wrong or hostile announcement changes nothing. - Coalesce. An announcement of a kind the page shows (
kinds:; the others wake nothing) marks its ids dirty and schedules one:refreshan interval later if none is scheduled (config :karta, KartaWeb.LiveUpdates, interval:, 1 second by default); the refresh reads all dirty records at once. A page does at most one query batch an interval however busy its server is. Above 100 dirty ids the page getsids: :alland reads its whole view instead. The server overview waits five intervals (every: 5). - Keep the user's place. The messages list on its first page, while
the top of the list is in view (a colocated hook,
.Follow, tells the page with anIntersectionObserver), runs its search again and shows new messages that match it at the top (the page stays 50 rows). On a later page, or scrolled down, it reads the rows it shows again in place (a row the search no longer finds, or that was removed, goes) and counts the messages that arrived since it was read (Karta.Messages.count_since/3): "3 new messages" in a button at the bottom of the window, which goes to the first page with the same search and moves the focus to the top of the list. The search form, the page and the scroll are never reset by an update; forms on live pages are left as they are. - Show that it is live, quietly.
<.live_badge>("Live") in the panel header; it shows only while the page is connected (LiveView'sphx-connectedclass), so it goes when the connection is lost. A row that changed getschanged_class(@refreshes)(k-changed-aandk-changed-b, alternating, so that a row that changes again lights up again): a short tint, none withprefers-reduced-motion. The "new messages" button is in a polite live region; tables and counters that change every few seconds are not, so that a screen reader is not interrupted all the time. - Access counts at every refresh. Before the page's
refresh/2,KartaWeb.UserAuthreads the session and the scope again (an ended session leaves for/login), andKartaWeb.LiveUpdatesloads the page's organisation and server again for that scope: a user who may no longer see them leaves for/("That page is no longer available to you."). A message removed while its page is open shows a notice instead of its content.
Reconnecting, nodes, load
- Reconnect: a LiveView that reconnects mounts again and reads everything fresh, so announcements missed while disconnected do not matter; nothing is replayed.
- Several replicas:
Karta.Relaydelivers an announcement on the replica that made it, over the Erlang cluster when the replicas are clustered, and through PostgresLISTEN/NOTIFY(Oban's notifier) for the replicas that are not connected, so a page open on any replica sees the change once, clustered or not. A reconnect to another replica mounts fresh. See Running several replicas. - Load: an announcement is a small struct to the subscribers of one record; nothing is sent when no page is open on that record. Removing accepted messages announces each on its own topic too (for an open message page), at most a retention batch at a time. The cost is in the refresh queries, which the coalescing bounds per page.
Testing
The tests never wait for the clock: config/test.exs sets the interval
to an hour, and a test sends the refresh itself (send(view.pid, :refresh), then render(view)). KartaWeb.ConnCase helps:
refresh_timer/1 (the milliseconds until a page's scheduled refresh),
queries_by/2 (the queries a page's process makes, from the telemetry
of [:karta, :repo, :query]) and assert_self_contained/1 (the content
security policy check). Each live page's test module covers:
- An announcement leads to a re-read: a message accepted for the page's server (through the core function, so the broadcast is the real one) appears after the refresh, with the state the database holds.
- Another organisation's server never reaches the page: the same
change on another server, and a forged
%Change{}with another server's message id sent straight to the view, change nothing in the rendered page. - The scoped query decides: an announced id that the search excludes does not appear; a message that was removed disappears.
- Coalescing: many announcements before a refresh give the same
queries as one; one refresh is scheduled an interval after the first
(
refresh_timer/1); kinds the page does not show schedule nothing. - Access: after the member was removed, the refresh leaves the page.
- The policy: the page after an update still has no inline style or script.
test/karta/changes_test.exs covers the after-commit rule (nested
transactions, rollbacks, failures, raises, the strict check), and
test/karta/changes_announced_test.exs what each core function
announces.