Open MercatoDocsSearch docsAPI reference

Framework

Events and Subscribers

When an order is confirmed, bookkeeping and the dispatch board may both care. The Sales module can announce the event once and let each subscriber own its reaction. Decide how each reaction should behave if no worker is available when the event arrives.

Open Mercato provides a comprehensive event/subscriber system with module auto-discovery, DI integration, and offline processing. The system supports two processing modes:

  1. Inline Events (persistent: false): Subscribers execute immediately when events are emitted, within the same request lifecycle
  2. Async Events (persistent: true): Events are queued and processed asynchronously by dedicated workers, providing reliability, retry capabilities, and scalability

Tip · When to use persistent events

Use persistent: true for events that:

For background job processing at scale, see the Queue & Workers documentation.

Single delivery of persistent events

OM_EVENTS_SINGLE_DELIVERY is on by default. A persistent: true emit is delivered on exactly one path:

Set OM_EVENTS_SINGLE_DELIVERY=false to run persistent subscribers inline instead. This is not the old dual-dispatch: the producer stamps the queued job with what it already delivered, so the worker skips it. Either way a persistent emit runs its subscribers exactly once.

No worker yet is not the same as lost

Persistent jobs sit in a durable queue. If no worker is running, delivery is delayed, not dropped - start a worker and the backlog drains. The bus therefore never falls back to inline delivery on its own; doing so would move the work onto the caller's request path, which is what a split app/worker deployment sets AUTO_SPAWN_WORKERS=false to avoid.

Warning · Split app and worker services

Run at least one process that drains the events queue. mercato server start auto-spawns one unless AUTO_SPAWN_WORKERS=false; if you run workers as their own service, make sure that service actually starts them (a bare next start does not).

Overview

Browser event stream authorization

Events declared with clientBroadcast: true can reach the browser through the authenticated GET /api/events/stream Server-Sent Events endpoint. The server filters every frame against the connection's tenant, organization, user, and roles. It also re-resolves canonical authorization from the original request credentials every 30 seconds. Both the opening request and every periodic check pass the authenticated principal plus that request's selection cookies through Directory's request-scoped organization resolver. The resolver's normalized tenant must exactly equal the normalized canonical authenticated tenant, and its ACL-approved selected organization becomes the stream audience. When no organization is selected (the All organizations option), the stream falls back to the caller's home organization (auth.orgId), which must still be in the allowed set; it does not widen to every organization the caller can see. A rejected or out-of-scope selection cannot open or preserve a stream. If the session or user disappears, the lookup fails, or the canonical user, tenant, organization, or role set changes, the stream closes and removes its connection, listener, heartbeat, validation, and lifetime state before any later event can be delivered.

The browser endpoint accepts staff session cookies and staff Bearer tokens. It rejects x-api-key and Authorization: ApiKey credentials before opening a stream; API clients should consume event APIs through bounded requests rather than a browser DOM-event connection. When the active tenant or organization changes, the browser closes the current EventSource and immediately opens a new one, so the request carries the current selection cookies instead of waiting for the lifetime cap.

Every stream also has a server maximum age (five minutes by default, jittered by ±15% per connection so clients do not reconnect in synchronized waves). Closing is intentional: the browser bridge (useEventBridge) treats the close as an error, closes its EventSource, and opens a new one with its own exponential backoff (1 second doubling up to 30 seconds, reset after a successful open). The new request passes through normal authentication again, and once it opens the bridge dispatches an om:bridge:reconnected app event so components can refetch anything they may have missed. Heartbeats still run every 30 seconds, and the browser watchdog still reconnects when one is missing for 45 seconds.

Environment variableDefaultConstraintPurpose
OM_EVENTS_SSE_AUTH_REVALIDATION_INTERVAL_MS300001000–2147483647How often an open stream re-checks its credentials: the DOM Event Bridge re-resolves canonical identity, organization scope and roles; the Portal Event Bridge re-checks the customer session.
OM_EVENTS_SSE_CONNECTION_MAX_AGE_MS3000001000–2147483647Base maximum age of one DOM or Portal Event Bridge stream before a forced reconnect; each connection applies ±15% jitter within the same bounds.

Invalid values and values below the minimum use the default. Larger finite values are capped at Node's maximum safe timer delay (2^31-1 milliseconds), preventing timer overflow from turning a long interval into rapid reconnect churn. Keep the revalidation interval below the maximum age when periodic revocation detection should happen before the mandatory reconnect.

File Structure

Example subscriber file packages/my-module/src/modules/my_module/subscribers/order-created.ts:

export const metadata = {
  event: 'order.created',
  persistent: true, // optional, default false
}

export default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {
  const em = ctx.resolve('em')
  // ... do something with payload using DI services
}

IDs are optional; default is "<module>:<nested_path>".

Emitting Events

From any handler with DI access:

const bus = container.resolve('eventBus')
await bus.emitEvent('order.created', { id: 123, total: 42 }, { persistent: true })

Programmatic Registration

Modules can register subscribers in di.ts:

import type { AppContainer } from '@/lib/di/container'

export function register(container: AppContainer) {
  const bus = container.resolve<any>('eventBus')
  bus.on('custom.event', async (payload, ctx) => {
    const em = ctx.resolve('em')
    // ...
  })
}

Strategy & Persistence

Processing Persistent Events

Persistent events are processed by running a dedicated queue worker:

# Start a worker to process events from the queue
yarn mercato queue worker events

# With custom concurrency (default is 1)
yarn mercato queue worker events --concurrency=5

The worker connects to Redis (or uses local storage) and continuously processes queued events. It uses the DI container, so subscriber handlers can resolve services.

Queue Management

# Check queue status (waiting, active, completed, failed counts)
yarn mercato queue status events

# Clear all events from the queue
yarn mercato queue clear events

Emit via CLI

Quickly emit an event from the terminal (useful for testing subscribers or seeding flows):

yarn mercato events emit <event> [jsonPayload] [--persistent|-p]

Examples:

# Simple event without payload (non-persistent)
yarn mercato events emit example.event

# Emit with JSON payload (remember to quote it)
yarn mercato events emit order.created '{"id":123,"total":42.5}'

# Emit a persistent event so it is queued for async processing
yarn mercato events emit order.created '{"id":124}' --persistent

# Shorthand for persistent flag
yarn mercato events emit order.created '{"id":125}' -p

Notes:

Notes

CRUD Events

The CRUD factory emits standard events for module entities:

Use these to react to lifecycle changes without tightly coupling modules. Mark them persistent to support offline replay.

Application Lifecycle Events

The app runtime also emits framework-level lifecycle events that modules can subscribe to:

Typical payload fields:

Example subscriber:

export const metadata = {
  event: 'application.request.failed',
  persistent: false,
}

export default async function onRequestFailed(payload: any, ctx: { resolve: <T = any>(name: string) => T }) {
  const logger = ctx.resolve<any>('logger')
  logger?.error?.('Request failed', payload)
}

Choose the event by the business transition

For Sales, sales.order.created means an order record was created and sales.order.confirmed means it was confirmed. Use the module's declared event ID when connecting a workflow. A similar-looking name with a plural entity segment can leave the workflow waiting indefinitely.

Previous: JSONB indexing layer · Next: Queue & Workers