Every app on the homelab's message queue publishes under its own name. Messages's events go to the NATS JetStream stream EVENTS_MESSAGES on the subject events.messages.<category>.<type>, as JSON. Business events are notes and files, technical events are everything else, so events.messages.business.> takes Messages's notes and files, and events.*.business.> every app's.
Events carry ids, never content: read the note or file through the API. The stream keeps them for 7 days. Delivery is at least once and not always in order, so make handling an event twice harmless (its id is unique) and read current state.
Connecting takes a login on the message queue from the person who runs this server. Every app shares one account there, which is how apps integrate. An API key doesn't open it, and anything connected sees every account's events.
events.messages.business.note.createdA note was written · userId, noteId
events.messages.business.note.updatedA note was edited · userId, noteId
events.messages.business.note.deletedA note was deleted · userId, noteId
events.messages.business.attachment.uploadedA file was uploaded; noteId names its note, or is null for a file on its own · userId, attachmentId, noteId
events.messages.business.attachment.deletedA file was deleted · userId, attachmentId
events.messages.business.conversation.startedSomeone started a conversation; conversationId names it, never its content · userId, conversationId
events.messages.business.conversation.deletedSomeone deleted a conversation, for both people in it · userId, conversationId
events.messages.business.message.sentA message was sent; its content is encrypted and never in the event · userId, conversationId, messageId
events.messages.business.message.editedA message was edited by its sender · userId, conversationId, messageId
events.messages.business.message.deletedA message was deleted by its sender · userId, conversationId, messageId
events.messages.business.call.startedSomeone rang the other person in a conversation; callId names the call · userId, conversationId, callId
events.messages.business.call.answeredThe person called took the call · userId, conversationId, callId
events.messages.business.call.endedAn answered call ended: someone hung up, or both apps went quiet · userId, conversationId, callId
events.messages.business.call.declinedThe person called turned the call down · userId, conversationId, callId
events.messages.business.call.cancelledThe caller stopped ringing before anyone answered · userId, conversationId, callId
events.messages.business.call.missedNobody answered before the call stopped ringing · userId, conversationId, callId
events.messages.technical.user.signed_inSomeone signed in to the web or admin app · userId, client
events.messages.technical.user.signed_outSomeone signed out of the web or admin app · userId, client
events.messages.technical.appearance.updatedSomeone changed the appearance · userId, client
events.messages.technical.servers.updatedSomeone changed their server list · userId
events.messages.technical.avatar.updatedSomeone set a profile photo · userId
events.messages.technical.avatar.removedSomeone removed their profile photo · userId
events.messages.technical.profile.updatedSomeone changed their Messages handle or status · userId
events.messages.technical.encryption.set_upSomeone set up end-to-end encryption · userId
events.messages.technical.encryption.changedSomeone changed their encryption passphrase · userId
events.messages.technical.encryption.resetSomeone reset their encryption: their earlier messages are unreadable to them · userId
events.messages.technical.api_key.createdAn API key was created · userId, apiKeyId
events.messages.technical.api_key.deletedAn API key was revoked · userId, apiKeyId
events.messages.technical.device.renamedA device was renamed · userId, deviceId
events.messages.technical.device.signed_outA device was signed out from another one · userId, deviceId
events.messages.technical.ai.chat_requestedSomeone chatted with AI; model is null when unknown · userId, model
events.messages.technical.ai.note_summarizedA note was summarized with AI · userId, noteId
events.messages.technical.ai.audio_transcribedAudio was transcribed with AI · userId
events.messages.technical.ai.command_interpretedA spoken or typed command was understood with AI (built-in phrases aren't announced) · userId
events.messages.technical.user.suspendedAn administrator suspended an account · userId, adminId
events.messages.technical.user.restoredAn administrator restored an account · userId, adminId
events.messages.technical.user.data_deletedAn administrator deleted an account's notes and files · userId, adminId
note-created-logger ← events.messages.business.note.created
Reads the new note and logs its length: the example of a processor
attachment-uploaded-notifier ← events.messages.business.attachment.uploaded
Tells the file's owner File uploaded: the example of a notification raised from the bus
A Node script to copy into your service or another app. It reads any app's events (EVENTS_APP), creates a durable consumer, retries a failed event, and stops cleanly; put your logic in handle().
#!/usr/bin/env node
/**
* A consumer to start from, for the events of any app built from the Messages
* template: the smallest service, or the first half of an integration between
* two apps, that reacts to them. Copy this file into your own service, install
* its two packages, and put your logic in handle().
*
* npm install @nats-io/transport-node @nats-io/jetstream
* NATS_URL=nats://<broker>:4222 NATS_USER=<user> NATS_PASSWORD=<password> \
* node events-consumer.mjs
*
* In the Messages repo: pnpm events:consume (NATS_* from apps/api/.env).
*
* Every app publishes on the homelab's shared NATS account under its own
* name, events.<app>.<category>.<type>, into its own stream, EVENTS_<APP>.
*
* EVENTS_APP whose events to read; default messages. Its stream is
* EVENTS_<APP>: upper case, with - as _
* EVENTS_FILTER the subjects to take; default events.<app>.> (all of
* them), events.<app>.business.> for notes and files
* only, or one type such as
* events.messages.technical.user.signed_in
* EVENTS_CONSUMER the durable consumer's name; default events-consumer.
* Every app reading a stream shares its consumer names,
* so name it after your app and its job
* (notes2-note-indexer). It remembers its place, so a
* restart resumes where it stopped. A new name starts at
* the oldest event the stream holds, up to 7 days back.
* Remove one you no longer need with:
* nats consumer rm EVENTS_<APP> <name>
*
* Delivery is at least once and not always in order: handling one event
* twice must be harmless (its id is unique). Events carry ids, never content:
* read what you need through the publishing app's API, never its database.
*/
import {
AckPolicy,
DeliverPolicy,
JetStreamApiCodes,
JetStreamApiError,
jetstream,
jetstreamManager
} from "@nats-io/jetstream"
import { connect, nanos } from "@nats-io/transport-node"
const APP = process.env.EVENTS_APP || "messages"
const STREAM = `EVENTS_${APP.toUpperCase().replaceAll("-", "_")}`
const FILTER = process.env.EVENTS_FILTER || `events.${APP}.>`
const CONSUMER = process.env.EVENTS_CONSUMER || "events-consumer"
const MAX_DELIVER = 5
const RETRY_DELAY_MS = 10_000
/**
* Your logic. Throw to have the event delivered again 10 s later, up to 5
* deliveries in all.
*/
async function handle(event) {
console.log(`${event.occurredAt} ${event.type}`, JSON.stringify(event.data))
}
/** The event in a message, or null when it isn't one of APP's. */
function readEvent(message) {
try {
const event = JSON.parse(message.string())
return event?.app === APP && typeof event.type === "string"
? event
: null
} catch {
return null
}
}
function isApiError(error, code) {
return error instanceof JetStreamApiError && error.code === code
}
if (!process.env.NATS_URL) {
console.error(
"Set NATS_URL, and NATS_USER and NATS_PASSWORD when the broker asks for a login"
)
process.exit(1)
}
// Once connected, it reconnects forever, so a broker restart needs no restart
// here.
const nc = await connect({
servers: process.env.NATS_URL,
user: process.env.NATS_USER || undefined,
pass: process.env.NATS_PASSWORD || undefined,
name: CONSUMER,
maxReconnectAttempts: -1
}).catch((error) => {
console.error(
`Can't reach NATS at ${process.env.NATS_URL}: ${error.message}`
)
process.exit(1)
})
// Create the durable consumer, or point an existing one at FILTER; it keeps
// its place either way.
const jsm = await jetstreamManager(nc)
const settings = {
filter_subject: FILTER,
ack_wait: nanos(60_000),
max_deliver: MAX_DELIVER
}
try {
await jsm.consumers.info(STREAM, CONSUMER)
await jsm.consumers.update(STREAM, CONSUMER, settings)
} catch (error) {
if (isApiError(error, JetStreamApiCodes.StreamNotFound)) {
console.error(
`No ${STREAM} stream: ${APP} hasn't published to this broker yet, or this login is for another account`
)
await nc.close()
process.exit(1)
}
if (!isApiError(error, JetStreamApiCodes.ConsumerNotFound)) throw error
await jsm.consumers.add(STREAM, {
durable_name: CONSUMER,
ack_policy: AckPolicy.Explicit,
deliver_policy: DeliverPolicy.All,
...settings
})
}
const consumer = await jetstream(nc).consumers.get(STREAM, CONSUMER)
const messages = await consumer.consume()
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, () => messages.close())
}
console.log(`[${CONSUMER}] consuming ${FILTER}; Ctrl+C stops`)
for await (const message of messages) {
const event = readEvent(message)
if (!event) {
console.error(
`skipped a message on ${message.subject}: not a ${APP} event`
)
message.term(`not a ${APP} event`)
continue
}
try {
await handle(event)
message.ack()
} catch (error) {
const attempt = message.info.deliveryCount
console.error(
`${event.id}: attempt ${attempt}/${MAX_DELIVER} failed`,
error
)
if (attempt >= MAX_DELIVER) message.term(`failed ${attempt} times`)
else message.nak(RETRY_DELAY_MS)
}
}
await nc.drain()