Framework
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:
persistent: false): Subscribers execute immediately when events are emitted, within the same request lifecyclepersistent: true): Events are queued and processed asynchronously by dedicated workers, providing reliability, retry capabilities, and scalabilityTip · When to use persistent events
Use persistent: true for events that:
For background job processing at scale, see the Queue & Workers documentation.
OM_EVENTS_SINGLE_DELIVERY is on by default. A persistent: true emit is delivered on exactly
one path:
event: '*')
persistent subscribers - workflow triggers, business-rule triggers, outbound webhooks - get
reached at all.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.
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).
packages/<pkg>/src/modules/<module>/subscribers/*.ts (or apps/mercato/src/modules/<module>/subscribers/*.ts for app-level overrides) and export:
export const metadata = { event: string, persistent?: boolean, id?: string }export default async function(payload, ctx) { /* ... */ }
ctx.resolve(name) resolves services from Awilix per-request container.yarn generate and registered into a global Event Bus via the core bootstrap (@open-mercato/core/bootstrap), which your app calls from apps/mercato/src/di.ts.eventBus.emitEvent(event, payload, { persistent? })..events/queue.json with state in .events/state.json.yarn mercato events process [--limit=N] replays unprocessed persistent events.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 variable | Default | Constraint | Purpose |
|---|---|---|---|
OM_EVENTS_SSE_AUTH_REVALIDATION_INTERVAL_MS | 30000 | 1000–2147483647 | How 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_MS | 300000 | 1000–2147483647 | Base 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.
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>".
From any handler with DI access:
const bus = container.resolve('eventBus')
await bus.emitEvent('order.created', { id: 123, total: 42 }, { persistent: true })
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')
// ...
})
}
EVENTS_STRATEGY=local|redis (default local).REDIS_URL or EVENTS_REDIS_URL..events/queue.json and .events/state.json in project root.events:last_id, events:queue (sorted set), events:last_processed_id.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.
# Check queue status (waiting, active, completed, failed counts)
yarn mercato queue status events
# Clear all events from the queue
yarn mercato queue clear events
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:
ctx.resolve.emitEvent, and also available for offline replay when persistent.The CRUD factory emits standard events for module entities:
<module>.<entity>.created<module>.<entity>.updated<module>.<entity>.deletedUse these to react to lifecycle changes without tightly coupling modules. Mark them persistent to support offline replay.
The app runtime also emits framework-level lifecycle events that modules can subscribe to:
application.bootstrap.startedapplication.bootstrap.completedapplication.bootstrap.failedapplication.request.receivedapplication.request.auth_resolvedapplication.request.authorization_deniedapplication.request.rate_limitedapplication.request.not_foundapplication.request.completedapplication.request.failedTypical payload fields:
requestId: Correlation ID for a single request flow.method: HTTP method.pathname: Requested API pathname.status: HTTP status when available.userId: Current authenticated user ID (or null).tenantId: Current tenant ID (or null).durationMs: Processing time in milliseconds.errorMessage: Failure message on error paths.source: Bootstrap event source (for example apps/mercato).emittedAt: ISO timestamp for bootstrap emissions.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)
}
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.