@open-mercato/events 0.11.1-develop.8414.1.68213d4403 → 0.11.1-develop.8418.1.8ddb502575
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bus.js +36 -10
- package/dist/bus.js.map +2 -2
- package/package.json +3 -3
- package/src/__tests__/scoped-bus.test.ts +64 -0
- package/src/bus.ts +48 -12
package/dist/bus.js
CHANGED
|
@@ -172,20 +172,45 @@ function registerBroadcastCoalescerShutdownHook() {
|
|
|
172
172
|
});
|
|
173
173
|
globalThis[BROADCAST_COALESCER_SHUTDOWN_KEY] = true;
|
|
174
174
|
}
|
|
175
|
+
function createEventBusGenerationState() {
|
|
176
|
+
return { listeners: /* @__PURE__ */ new Map(), persistentSubscribers: /* @__PURE__ */ new Set(), queue: null };
|
|
177
|
+
}
|
|
175
178
|
function createEventBus(opts) {
|
|
179
|
+
return createEventBusWithState(opts, createEventBusGenerationState());
|
|
180
|
+
}
|
|
181
|
+
function createScopedEventBusFactory(options = {}) {
|
|
182
|
+
const state = createEventBusGenerationState();
|
|
183
|
+
return Object.assign(
|
|
184
|
+
(resolve) => createEventBusWithState({ ...options, resolve }, createEventBusGenerationState(), state),
|
|
185
|
+
{
|
|
186
|
+
definitions: createEventBusWithState({
|
|
187
|
+
...options,
|
|
188
|
+
resolve: () => {
|
|
189
|
+
throw new Error("[internal] Event definitions cannot resolve caller services");
|
|
190
|
+
}
|
|
191
|
+
}, state)
|
|
192
|
+
}
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
function createEventBusWithState(opts, state, definitions) {
|
|
176
196
|
registerBroadcastCoalescerShutdownHook();
|
|
177
|
-
const listeners =
|
|
178
|
-
const persistentSubscribers =
|
|
197
|
+
const listeners = state.listeners;
|
|
198
|
+
const persistentSubscribers = state.persistentSubscribers;
|
|
199
|
+
const queueState = definitions ?? state;
|
|
200
|
+
function* listenerEntries() {
|
|
201
|
+
if (definitions) yield* definitions.listeners;
|
|
202
|
+
yield* listeners;
|
|
203
|
+
}
|
|
204
|
+
const isPersistentSubscriber = (subscriber) => persistentSubscribers.has(subscriber) || definitions?.persistentSubscribers.has(subscriber) === true;
|
|
179
205
|
const queueStrategy = opts.queueStrategy ?? (process.env.QUEUE_STRATEGY === "async" ? "async" : "local");
|
|
180
|
-
let queue = null;
|
|
181
206
|
function getQueue() {
|
|
182
207
|
if (queueStrategy !== "async" || !isSharedProducerEnabled()) {
|
|
183
|
-
if (!queue) {
|
|
184
|
-
queue = queueStrategy === "async" ? createQueue(EVENTS_QUEUE_NAME, "async", {
|
|
208
|
+
if (!queueState.queue) {
|
|
209
|
+
queueState.queue = queueStrategy === "async" ? createQueue(EVENTS_QUEUE_NAME, "async", {
|
|
185
210
|
connection: { url: getRedisUrlOrThrow("QUEUE") }
|
|
186
211
|
}) : createQueue(EVENTS_QUEUE_NAME, "local");
|
|
187
212
|
}
|
|
188
|
-
return queue;
|
|
213
|
+
return queueState.queue;
|
|
189
214
|
}
|
|
190
215
|
const redisUrl = getRedisUrlOrThrow("QUEUE");
|
|
191
216
|
const registry = getProducerQueueRegistry();
|
|
@@ -202,11 +227,11 @@ function createEventBus(opts) {
|
|
|
202
227
|
}
|
|
203
228
|
async function deliver(event, payload, options, skipPersistent = false) {
|
|
204
229
|
let persistentFailures = 0;
|
|
205
|
-
for (const [pattern, handlers] of
|
|
230
|
+
for (const [pattern, handlers] of listenerEntries()) {
|
|
206
231
|
if (!matchEventPattern(event, pattern)) continue;
|
|
207
232
|
if (!handlers || handlers.size === 0) continue;
|
|
208
233
|
for (const subscriber of handlers) {
|
|
209
|
-
if (skipPersistent &&
|
|
234
|
+
if (skipPersistent && isPersistentSubscriber(subscriber)) continue;
|
|
210
235
|
try {
|
|
211
236
|
const moduleId = subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id);
|
|
212
237
|
await withModuleResourceUsage(
|
|
@@ -224,7 +249,7 @@ function createEventBus(opts) {
|
|
|
224
249
|
})
|
|
225
250
|
);
|
|
226
251
|
} catch (error) {
|
|
227
|
-
if (
|
|
252
|
+
if (isPersistentSubscriber(subscriber)) {
|
|
228
253
|
persistentFailures += 1;
|
|
229
254
|
}
|
|
230
255
|
logger.error("Handler error", { event, pattern, err: error });
|
|
@@ -238,7 +263,7 @@ function createEventBus(opts) {
|
|
|
238
263
|
}
|
|
239
264
|
function selectQueuedSubscribers(event) {
|
|
240
265
|
const matched = [];
|
|
241
|
-
for (const [pattern, handlers] of
|
|
266
|
+
for (const [pattern, handlers] of listenerEntries()) {
|
|
242
267
|
if (!matchEventPattern(event, pattern)) {
|
|
243
268
|
continue;
|
|
244
269
|
}
|
|
@@ -378,6 +403,7 @@ function createEventBus(opts) {
|
|
|
378
403
|
export {
|
|
379
404
|
CROSS_PROCESS_EVENT_INSTANCE_ID,
|
|
380
405
|
createEventBus,
|
|
406
|
+
createScopedEventBusFactory,
|
|
381
407
|
registerCrossProcessEventListener,
|
|
382
408
|
registerGlobalEventTap
|
|
383
409
|
};
|
package/dist/bus.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bus.ts"],
|
|
4
|
-
"sourcesContent": ["import { createQueue } from '@open-mercato/queue'\nimport type { Queue } from '@open-mercato/queue'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isSingleDeliveryRequested } from './single-delivery'\nimport { matchEventPattern } from '@open-mercato/shared/lib/events/patterns'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport {\n isBroadcastEvent,\n isCoalescedBroadcastEvent,\n isCrossProcessBroadcastEvent,\n isPortalBroadcastEvent,\n isPrivateCrossProcessBroadcastEvent,\n isPrivateCrossProcessEventEmitter,\n} from '@open-mercato/shared/modules/events'\nimport {\n BROADCAST_FLUSH_DEADLINE_MS,\n flushPendingBroadcasts,\n resolveBroadcastCoalesceIntervalMs,\n submitBroadcast,\n} from './broadcast-coalescer'\nimport {\n inferModuleIdFromResourceId,\n withModuleResourceUsage,\n} from '@open-mercato/shared/lib/modules/resource-usage'\nexport { registerCrossProcessEventListener, CROSS_PROCESS_EVENT_INSTANCE_ID } from './bridge'\nimport { publishCrossProcessEvent } from './bridge'\nimport type {\n EventBus,\n CreateBusOptions,\n SubscriberHandler,\n SubscriberDescriptor,\n EventPayload,\n EmitOptions,\n QueuedDispatchResult,\n} from './types'\n\n/** Queue name for persistent events */\nconst EVENTS_QUEUE_NAME = 'events'\n\nconst logger = createLogger('events')\n\ntype RegisteredSubscriber = {\n id?: string\n moduleId?: string\n event: string\n handler: SubscriberHandler\n persistent?: boolean\n}\n\n/**\n * When enabled, a persistent emit delivers each subscriber on exactly one path:\n * persistent-marked subscribers are skipped inline (the events worker dispatches\n * them via pattern match, so wildcard persistent subscribers are reached), while\n * ephemeral subscribers keep running inline. Defaults ON.\n *\n * The bus never second-guesses this against \"is a worker running\": the queue is\n * durable, so a persistent emit with no worker yet is delayed, not lost, and a\n * worker started later drains the backlog. Delivering inline instead would move\n * the work back onto the caller's request path \u2014 exactly what a split app/worker\n * deployment sets `AUTO_SPAWN_WORKERS=false` to avoid.\n *\n * The events worker asks this same bus for its subscribers via `dispatchQueued`,\n * so both halves of single-delivery read one decision.\n */\nfunction isSingleDeliveryEnabled(): boolean {\n return isSingleDeliveryRequested()\n}\n\ntype GlobalEventTap = (event: string, payload: EventPayload, options?: EmitOptions) => void | Promise<void>\nconst GLOBAL_EVENT_TAPS_KEY = '__openMercatoEventBusGlobalTaps__'\n\nfunction hasTrustedTenantScope(options?: EmitOptions): boolean {\n return typeof options?.tenantId === 'string' && options.tenantId.trim().length > 0\n}\n\nfunction normalizePayloadScope(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\nfunction isBrowserBroadcastEvent(event: string): boolean {\n return isBroadcastEvent(event) || isPortalBroadcastEvent(event)\n}\n\n/** Relayed over the bridge: both browser audiences plus private coordination; each consumer filters by its own flag. */\nfunction shouldPublishCrossProcess(event: string): boolean {\n return isCrossProcessBroadcastEvent(event) || isPortalBroadcastEvent(event)\n}\n\nfunction resolveCrossProcessEmitOptions(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n): EmitOptions | undefined {\n if (hasTrustedTenantScope(options)) return options\n // Preserve the public raw EventBus contract for legacy clientBroadcast and\n // portalBroadcast emitters. These callers are trusted server code and\n // historically supplied their scope in the typed payload. Tenant-managed\n // workflow execution passes scope in options, while private cross-process\n // events never take this path.\n if (!isBrowserBroadcastEvent(event) || isPrivateCrossProcessBroadcastEvent(event)) return options\n const tenantId = normalizePayloadScope((payload as Record<string, unknown>)?.tenantId)\n if (!tenantId) return options\n const organizationId = normalizePayloadScope((payload as Record<string, unknown>)?.organizationId)\n const organizationIdsValue = (payload as Record<string, unknown>)?.organizationIds\n const organizationIds = Array.isArray(organizationIdsValue)\n ? organizationIdsValue.filter((value): value is string => typeof value === 'string')\n : []\n return {\n ...options,\n tenantId,\n ...(organizationId ? { organizationId } : {}),\n ...(organizationIds.length > 0 ? { organizationIds } : {}),\n }\n}\n\nfunction collectStringScopes(input: unknown): string[] {\n if (!Array.isArray(input)) return []\n const values: string[] = []\n for (const value of input) {\n if (typeof value !== 'string') continue\n const trimmed = value.trim()\n if (!trimmed) continue\n values.push(trimmed)\n }\n return values\n}\n\n// Sorted so an audience keys identically however the caller ordered it, and\n// explicitly comparator-ed per the #3620 guard.\nfunction sortScopes(scopes: Set<string>): string[] {\n return Array.from(scopes).sort((left, right) => left.localeCompare(right))\n}\n\n/**\n * Coalescing key for the browser dispatch of one event.\n *\n * Built from the raw union of every dimension the SSE audience filter\n * (`matchesAudience` in `events/api/stream/route.ts`) reads \u2014 tenant,\n * organization, recipient user and recipient role \u2014 taken from BOTH the\n * trusted `options` and the payload, without calling `resolveCrossProcessEmitOptions`\n * or any other resolver. Those resolvers pick one source to trust for delivery\n * semantics; the key instead has to key on every dimension a connection can be\n * filtered by, or one audience's emit would silently replace another\n * audience's pending delivery \u2014 recipient/role targeting and a portal-only\n * event (which carries no trusted `options` scope at all) included.\n *\n * Options and payload scope stay in separate segments, never merged: the three\n * filters each read a different source, so `options` org A + payload org B must\n * not key like the reverse. The options tenant segment encodes PRESENCE, not\n * just value \u2014 the backoffice `hasTrustedScope` is a presence test, so `{}` and\n * `{ tenantId: undefined }` take different filter branches and must not share\n * a key.\n *\n * Scope is part of the key by necessity, not for granularity: a key with no\n * scope segments would let a burst in one tenant suppress another tenant's\n * delivery and then deliver the first tenant's payload in its place.\n */\nfunction buildBroadcastCoalesceKey(event: string, payload: EventPayload, options?: EmitOptions): string {\n const data = (payload ?? {}) as Record<string, unknown>\n\n const payloadTenantId = normalizePayloadScope(data.tenantId) ?? ''\n const optionsTenantToken = options && Object.prototype.hasOwnProperty.call(options, 'tenantId')\n ? `=${normalizePayloadScope(options.tenantId) ?? ''}`\n : 'absent'\n\n const optionsOrganizationScopes = new Set<string>()\n const optionsOrganizationId = normalizePayloadScope(options?.organizationId)\n if (optionsOrganizationId) optionsOrganizationScopes.add(optionsOrganizationId)\n for (const organizationId of collectStringScopes(options?.organizationIds)) {\n optionsOrganizationScopes.add(organizationId)\n }\n\n const payloadOrganizationScopes = new Set<string>()\n const payloadOrganizationId = normalizePayloadScope(data.organizationId)\n if (payloadOrganizationId) payloadOrganizationScopes.add(payloadOrganizationId)\n for (const organizationId of collectStringScopes(data.organizationIds)) {\n payloadOrganizationScopes.add(organizationId)\n }\n\n const recipientUserScopes = new Set<string>()\n const recipientUserId = normalizePayloadScope(data.recipientUserId)\n if (recipientUserId) recipientUserScopes.add(recipientUserId)\n for (const userId of collectStringScopes(data.recipientUserIds)) {\n recipientUserScopes.add(userId)\n }\n\n const recipientRoleScopes = new Set<string>()\n const recipientRoleId = normalizePayloadScope(data.recipientRoleId)\n if (recipientRoleId) recipientRoleScopes.add(recipientRoleId)\n for (const roleId of collectStringScopes(data.recipientRoleIds)) {\n recipientRoleScopes.add(roleId)\n }\n\n return [\n event,\n payloadTenantId,\n optionsTenantToken,\n sortScopes(payloadOrganizationScopes).join(','),\n sortScopes(optionsOrganizationScopes).join(','),\n sortScopes(recipientUserScopes).join(','),\n sortScopes(recipientRoleScopes).join(','),\n ].join('::')\n}\n\nfunction getGlobalEventTaps(): Set<GlobalEventTap> {\n const existing = (globalThis as Record<string, unknown>)[GLOBAL_EVENT_TAPS_KEY]\n if (existing instanceof Set) {\n return existing as Set<GlobalEventTap>\n }\n const created = new Set<GlobalEventTap>()\n ;(globalThis as Record<string, unknown>)[GLOBAL_EVENT_TAPS_KEY] = created\n return created\n}\n\nexport function registerGlobalEventTap(handler: GlobalEventTap): () => void {\n const taps = getGlobalEventTaps()\n taps.add(handler)\n return () => {\n taps.delete(handler)\n }\n}\n\n/** Job data structure for queued events */\ntype EventJobData = {\n event: string\n payload: EventPayload\n options?: EmitOptions\n /**\n * Set by the producer when it already ran the persistent subscribers inline\n * (single-delivery reconciled off). The worker skips such jobs, so the app and\n * the worker staying exactly-once no longer depends on both processes agreeing\n * about `OM_EVENTS_SINGLE_DELIVERY`. Absent on jobs queued before this field\n * existed, which keeps their behavior unchanged.\n */\n persistentDeliveredInline?: boolean\n}\n\n// Process-wide cache of the async (BullMQ) persistent-events producer queue.\n// Each authenticated request builds a fresh DI container and event bus, so a\n// per-bus producer queue opened a new ioredis connection per write request that\n// was never closed \u2014 leaking one Redis connection per request until maxclients\n// exhaustion. Memoizing the producer on `globalThis` (keyed by Redis URL, so a\n// reconfigured URL still gets its own queue) keeps it at one connection per\n// process, mirroring the `GLOBAL_EVENT_TAPS_KEY` and `getCachedRateLimiterService`\n// patterns. The local (file-based) strategy holds no pooled connection and its\n// base dir is cwd-relative, so it stays per-bus.\nconst EVENTS_PRODUCER_QUEUE_KEY = '__openMercatoEventsProducerQueues__'\nconst EVENTS_PRODUCER_SHUTDOWN_KEY = '__openMercatoEventsProducerShutdown__'\nconst BROADCAST_COALESCER_SHUTDOWN_KEY = '__openMercatoBroadcastCoalescerShutdown__'\n\nfunction isSharedProducerEnabled(): boolean {\n return parseBooleanWithDefault(process.env.OM_EVENTS_SHARED_PRODUCER, true)\n}\n\nfunction getProducerQueueRegistry(): Map<string, Queue<EventJobData>> {\n const existing = (globalThis as Record<string, unknown>)[EVENTS_PRODUCER_QUEUE_KEY]\n if (existing instanceof Map) {\n return existing as Map<string, Queue<EventJobData>>\n }\n const created = new Map<string, Queue<EventJobData>>()\n ;(globalThis as Record<string, unknown>)[EVENTS_PRODUCER_QUEUE_KEY] = created\n return created\n}\n\nfunction registerProducerShutdownHook(): void {\n if ((globalThis as Record<string, unknown>)[EVENTS_PRODUCER_SHUTDOWN_KEY]) return\n const shutdown = () => {\n const registry = getProducerQueueRegistry()\n for (const sharedQueue of registry.values()) {\n Promise.resolve(sharedQueue.close()).catch(() => {})\n }\n registry.clear()\n }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as Record<string, unknown>)[EVENTS_PRODUCER_SHUTDOWN_KEY] = true\n}\n\n/**\n * Deliver the tail of any in-flight coalesced burst on the way out, so stopping\n * a worker mid-import does not leave browsers a window behind. Registered\n * independently of the producer hook: coalescing is in play whether or not this\n * process ever opened an async producer queue.\n *\n * `beforeExit` matters as much as the signals here. The trailing timer is\n * unref'd so a pending browser delivery never holds a process open, which means\n * a short-lived emitter \u2014 a CLI import, a one-shot script \u2014 reaches a natural\n * exit with the tail still queued and no signal ever fired. `beforeExit` runs\n * exactly when the loop has drained, which is precisely that case.\n *\n * `createEventBus` calls this in every process that bootstraps DI \u2014 the app,\n * every worker, and every `mercato` CLI command \u2014 so a bare `process.once`\n * listener here would take away Node's default SIGINT/SIGTERM exit process-wide:\n * once ANY listener is registered for a signal, Node stops exiting on it, and\n * this listener only flushes, never exits. A one-shot CLI command (seed,\n * import, reindex) with no graceful-shutdown handler of its own would then\n * swallow the first Ctrl+C or SIGTERM and keep running until SIGKILL. The\n * per-signal handler below flushes, then restores the default behavior itself\n * \u2014 by re-raising the signal \u2014 but only when it was the last listener\n * (`once` already removed itself before this body runs): a process with its\n * own graceful-shutdown handler (the queue worker, `mercato server`) keeps\n * that handler in charge of the actual exit, and this hook just adds the flush\n * alongside it. Every flush here is capped at BROADCAST_FLUSH_DEADLINE_MS, so a\n * hung dispatch cannot hold a stop until SIGKILL.\n */\nfunction registerBroadcastCoalescerShutdownHook(): void {\n if ((globalThis as Record<string, unknown>)[BROADCAST_COALESCER_SHUTDOWN_KEY]) return\n const handleSignal = (signal: NodeJS.Signals) => {\n void flushPendingBroadcasts({ deadlineMs: BROADCAST_FLUSH_DEADLINE_MS })\n .catch(() => {})\n .finally(() => {\n if (process.listenerCount(signal) === 0) {\n process.kill(process.pid, signal)\n }\n })\n }\n process.once('SIGTERM', () => handleSignal('SIGTERM'))\n process.once('SIGINT', () => handleSignal('SIGINT'))\n process.once('beforeExit', () => {\n void flushPendingBroadcasts({ deadlineMs: BROADCAST_FLUSH_DEADLINE_MS }).catch(() => {})\n })\n ;(globalThis as Record<string, unknown>)[BROADCAST_COALESCER_SHUTDOWN_KEY] = true\n}\n\n/**\n * Creates an event bus instance.\n *\n * The event bus provides:\n * - In-memory event delivery to registered handlers\n * - Optional persistence via the queue package when `persistent: true`\n *\n * @param opts - Configuration options\n * @returns An EventBus instance\n *\n * @example\n * ```typescript\n * const bus = createEventBus({\n * resolve: container.resolve.bind(container),\n * queueStrategy: 'local', // or 'async' for BullMQ\n * })\n *\n * // Register a handler\n * bus.on('user.created', async (payload, ctx) => {\n * const userService = ctx.resolve('userService')\n * await userService.sendWelcomeEmail(payload.userId)\n * })\n *\n * // Emit an event (immediate delivery)\n * await bus.emit('user.created', { userId: '123' })\n *\n * // Emit with persistence (for async worker processing)\n * await bus.emit('order.placed', { orderId: '456' }, { persistent: true })\n * ```\n */\nexport function createEventBus(opts: CreateBusOptions): EventBus {\n registerBroadcastCoalescerShutdownHook()\n\n // In-memory listeners for immediate event delivery\n const listeners = new Map<string, Set<RegisteredSubscriber>>()\n // Subscribers registered as persistent (worker-dispatched). Used by the\n // single-delivery path to skip them inline on a persistent emit.\n const persistentSubscribers = new Set<RegisteredSubscriber>()\n\n // Determine queue strategy from options or environment\n const queueStrategy = opts.queueStrategy ??\n (process.env.QUEUE_STRATEGY === 'async' ? 'async' : 'local')\n\n // Lazy-initialized queue for persistent events\n let queue: Queue<EventJobData> | null = null\n\n /**\n * Gets or creates the queue instance for persistent events.\n *\n * The async (BullMQ) producer is memoized process-wide so the per-request\n * event bus reuses one Redis connection instead of leaking one per write\n * request. The local strategy stays per-bus (no pooled connection, cwd-relative\n * base dir). Set `OM_EVENTS_SHARED_PRODUCER=0` to fall back to per-bus producers.\n */\n function getQueue(): Queue<EventJobData> {\n if (queueStrategy !== 'async' || !isSharedProducerEnabled()) {\n if (!queue) {\n queue = queueStrategy === 'async'\n ? createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'async', {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n : createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'local')\n }\n return queue\n }\n\n const redisUrl = getRedisUrlOrThrow('QUEUE')\n const registry = getProducerQueueRegistry()\n const cacheKey = `async:${redisUrl}`\n let shared = registry.get(cacheKey)\n if (!shared) {\n shared = createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'async', {\n connection: { url: redisUrl },\n })\n registry.set(cacheKey, shared)\n registerProducerShutdownHook()\n }\n return shared\n }\n\n /**\n * Delivers an event to all registered in-memory handlers.\n * Supports wildcard pattern matching for event patterns.\n *\n * Handler errors are logged and delivery continues - one bad subscriber must\n * not stop the others. The count of failed PERSISTENT handlers is returned so\n * the caller can decide whether the inline run may be recorded as complete:\n * a persistent subscriber that threw inline has no retry of its own, so the\n * queued job must stay unstamped and let the worker run it again.\n */\n async function deliver(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n skipPersistent = false,\n ): Promise<{ persistentFailures: number }> {\n let persistentFailures = 0\n // Check all registered patterns (including wildcards)\n for (const [pattern, handlers] of listeners) {\n if (!matchEventPattern(event, pattern)) continue\n if (!handlers || handlers.size === 0) continue\n\n for (const subscriber of handlers) {\n // Single-delivery: persistent subscribers are dispatched by the worker,\n // so skip them inline to avoid double execution.\n if (skipPersistent && persistentSubscribers.has(subscriber)) continue\n try {\n // Pass eventName in context for wildcard handlers\n const moduleId = subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id)\n await withModuleResourceUsage(\n {\n moduleId,\n surface: 'subscriber',\n operation: `${event} -> ${subscriber.id ?? subscriber.event}`,\n resourceId: subscriber.id ?? subscriber.event,\n },\n () => subscriber.handler(payload, {\n resolve: opts.resolve,\n eventName: event,\n tenantId: options?.tenantId ?? null,\n organizationId: options?.organizationId ?? null,\n }),\n )\n } catch (error) {\n if (persistentSubscribers.has(subscriber)) {\n persistentFailures += 1\n }\n logger.error('Handler error', { event, pattern, err: error })\n if (options?.rethrowHandlerErrors) {\n throw error\n }\n }\n }\n }\n return { persistentFailures }\n }\n\n /**\n * Selects the subscribers the events worker owns for a queued event: every\n * pattern matching `event`, keeping persistent subscribers only, so wildcard\n * (`event: '*'`) persistent subscribers are reached exactly once here.\n *\n * Deliberately does NOT read `OM_EVENTS_SINGLE_DELIVERY`. Whether inline\n * delivery already happened is carried by the job's `persistentDeliveredInline`\n * stamp, so the producer owns that decision entirely and the worker cannot\n * disagree with it across processes. Reading the flag here would reintroduce\n * exactly that skew: a worker whose env has the flag off would fall back to\n * exact-match, re-running ephemeral subscribers the producer already ran inline\n * and never reaching wildcard persistent subscribers - the failure this whole\n * change exists to remove.\n *\n * Every job that reaches this point wants persistent-pattern selection: a job\n * is only dispatched when its stamp is false, which means either the producer\n * had single-delivery on, or the emit was enqueue-only (`deliverInline: false`,\n * documented as \"every subscriber to the event is persistent\").\n */\n function selectQueuedSubscribers(event: string): RegisteredSubscriber[] {\n const matched: RegisteredSubscriber[] = []\n for (const [pattern, handlers] of listeners) {\n if (!matchEventPattern(event, pattern)) {\n continue\n }\n for (const subscriber of handlers) {\n if (subscriber.persistent) {\n matched.push(subscriber)\n }\n }\n }\n return matched\n }\n\n /**\n * Dispatches a queued event on behalf of the events worker.\n *\n * Handler failures are returned instead of logged-and-swallowed the way\n * `deliver()` does them: the worker needs them to propagate so the queue retries\n * the job and eventually dead-letters it.\n *\n * Subscribers run against the caller's `resolve` when one is given, falling back\n * to the bus's own. The events worker passes its per-job `ctx.resolve`, which is\n * the container `createPerJobWorkerHandler` built for that job - the handle the\n * queue contract already hands it. Defaulting to `opts.resolve` instead would\n * bind subscribers to whichever container built the bus; that is the same object\n * on the default configuration, but not under `OM_BOOTSTRAP_CACHE`, where the\n * cached bus is replayed into later containers while its captured resolver stays\n * bound to the first.\n */\n async function dispatchQueued(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n resolve?: <T = unknown>(name: string) => T,\n ): Promise<QueuedDispatchResult[]> {\n const subscribers = selectQueuedSubscribers(event)\n if (subscribers.length === 0) {\n return []\n }\n\n const resolver = resolve ?? opts.resolve\n\n const settled = await Promise.allSettled(\n subscribers.map((subscriber) =>\n withModuleResourceUsage(\n {\n moduleId: subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id),\n surface: 'subscriber',\n operation: `${event} -> ${subscriber.id ?? subscriber.event}`,\n resourceId: subscriber.id ?? subscriber.event,\n },\n () => subscriber.handler(payload, {\n resolve: resolver,\n eventName: event,\n tenantId: options?.tenantId ?? null,\n organizationId: options?.organizationId ?? null,\n }),\n ),\n ),\n )\n\n return settled.map((result, index) => {\n const subscriberId = subscribers[index].id ?? subscribers[index].event\n return result.status === 'rejected'\n ? { subscriberId, ok: false, error: result.reason }\n : { subscriberId, ok: true }\n })\n }\n\n /**\n * Registers a handler for an event. Pass `moduleId` whenever the subscribing\n * module is known (e.g. a module reacting to another module's event) so\n * resource-usage telemetry attributes the handler correctly instead of\n * guessing a module id from the event name.\n */\n function on(\n event: string,\n handler: SubscriberHandler,\n options?: { persistent?: boolean; moduleId?: string; id?: string },\n ): void {\n if (!listeners.has(event)) {\n listeners.set(event, new Set())\n }\n const subscriber: RegisteredSubscriber = {\n id: options?.id,\n moduleId: options?.moduleId,\n event,\n handler,\n persistent: options?.persistent,\n }\n listeners.get(event)!.add(subscriber)\n if (options?.persistent) {\n persistentSubscribers.add(subscriber)\n }\n }\n\n /**\n * Registers multiple module subscribers at once.\n */\n function registerModuleSubscribers(subs: SubscriberDescriptor[]): void {\n for (const sub of subs) {\n on(sub.event, sub.handler, { persistent: sub.persistent, moduleId: sub.moduleId, id: sub.id })\n }\n }\n\n /**\n * Emits an event to all registered handlers.\n *\n * If `persistent: true`, also enqueues the event for async processing.\n */\n async function emit(\n event: string,\n payload: EventPayload,\n options?: EmitOptions\n ): Promise<void> {\n const runGlobalTaps = async (): Promise<void> => {\n const taps = getGlobalEventTaps()\n for (const tap of taps) {\n try {\n await Promise.resolve(tap(event, payload, options))\n } catch (error) {\n logger.error('Global tap error', { event, err: error })\n }\n }\n }\n\n // Resolved at call time, never hoisted. Private coordination always requires\n // trusted envelope scope and module provenance. Legacy declared browser events\n // may promote their typed scope for raw EventBus compatibility; tenant-managed\n // workflow adapters pass authoritative scope in options, which always wins over\n // payload values. Computing it lazily keeps the non-coalesced path resolving\n // scope at exactly the point it always did \u2014 after inline delivery \u2014 so an\n // event that did not opt in cannot observe this change at all.\n const publishToOtherProcesses = async (): Promise<void> => {\n const crossProcessOptions = resolveCrossProcessEmitOptions(event, payload, options)\n if (\n !shouldPublishCrossProcess(event)\n || !hasTrustedTenantScope(crossProcessOptions)\n || !isPrivateCrossProcessEventEmitter(event, crossProcessOptions?.emitterModuleId)\n ) return\n try {\n await publishCrossProcessEvent(event, payload, crossProcessOptions)\n } catch (error) {\n logger.error('Cross-process publish error', { event, err: error })\n }\n }\n\n // Global taps are not a browser-only sink \u2014 `registerGlobalEventTap` is a\n // public export that any process-local listener can use (the create-app\n // template's qa-events route captures events for integration tests through\n // it, and third-party modules can too), not just the two SSE endpoints. What\n // both taps and the SSE bridges have in common is that neither carries domain\n // meaning on its own, so an opted-in event may coalesce this dispatch \u2014 and\n // with it every tap's delivery \u2014 without touching subscriber, webhook or\n // queue semantics below. A tap on a coalesced event sees the same suppressed,\n // trailing-flush-guaranteed stream the browser does, not one call per record.\n const coalesceBrowserDelivery = isCoalescedBroadcastEvent(event)\n && resolveBroadcastCoalesceIntervalMs() > 0\n if (coalesceBrowserDelivery) {\n await submitBroadcast(\n buildBroadcastCoalesceKey(event, payload, options),\n async () => {\n await runGlobalTaps()\n await publishToOtherProcesses()\n },\n )\n } else {\n await runGlobalTaps()\n }\n\n // Deliver to in-memory handlers first. Under single-delivery, persistent\n // subscribers are skipped inline on a persistent emit because the events\n // worker will dispatch them from the queue.\n //\n // `deliverInline: false` on a persistent emit is enqueue-only: skip inline\n // delivery entirely so a heavy persistent job runs solely in the events\n // worker, off the caller's request path (the queued enqueue below still\n // happens). Without this, a persistent emit dual-dispatches by default and\n // runs the subscriber inline in the caller's request too.\n const enqueueOnly = Boolean(options?.persistent) && options?.deliverInline === false\n // Read the mode once so the inline skip and the stamp below cannot disagree.\n const singleDelivery = isSingleDeliveryEnabled()\n const skipPersistentInline = options?.skipPersistentSubscribersInline === true\n || (Boolean(options?.persistent) && singleDelivery)\n let inlinePersistentFailed = false\n if (!enqueueOnly) {\n const delivered = await deliver(event, payload, options, skipPersistentInline)\n inlinePersistentFailed = delivered.persistentFailures > 0\n }\n\n // Already dispatched with the taps when this event coalesces its browser\n // delivery; otherwise it publishes here, exactly where it always has.\n if (!coalesceBrowserDelivery) {\n await publishToOtherProcesses()\n }\n\n // If persistent, also enqueue for async processing\n if (options?.persistent) {\n const q = getQueue()\n await q.enqueue({\n event,\n payload,\n options,\n // Only record the inline run as complete when every persistent\n // subscriber actually succeeded. Inline delivery logs-and-continues, so a\n // handler that threw has no retry of its own; leaving the job unstamped\n // hands it to the worker, where a failure gets queue retry and\n // dead-lettering. Without this, flipping the flag off (which the\n // `mercato server` guard can do automatically) silently downgrades\n // persistent delivery to at-most-once.\n persistentDeliveredInline: !enqueueOnly && !skipPersistentInline && !inlinePersistentFailed,\n })\n }\n }\n\n /**\n * Clears all events from the persistent queue.\n */\n async function clearQueue(): Promise<{ removed: number }> {\n const q = getQueue()\n return q.clear()\n }\n\n // Backward compatibility alias\n const emitEvent = emit\n\n return {\n emit,\n emitEvent, // Alias for backward compatibility\n on,\n registerModuleSubscribers,\n dispatchQueued,\n clearQueue,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,+BAA+B;AACxC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,mCAAmC,uCAAuC;AACnF,SAAS,gCAAgC;AAYzC,MAAM,oBAAoB;AAE1B,MAAM,SAAS,aAAa,QAAQ;AAyBpC,SAAS,0BAAmC;AAC1C,SAAO,0BAA0B;AACnC;AAGA,MAAM,wBAAwB;AAE9B,SAAS,sBAAsB,SAAgC;AAC7D,SAAO,OAAO,SAAS,aAAa,YAAY,QAAQ,SAAS,KAAK,EAAE,SAAS;AACnF;AAEA,SAAS,sBAAsB,OAA+B;AAC5D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,SAAS,wBAAwB,OAAwB;AACvD,SAAO,iBAAiB,KAAK,KAAK,uBAAuB,KAAK;AAChE;AAGA,SAAS,0BAA0B,OAAwB;AACzD,SAAO,6BAA6B,KAAK,KAAK,uBAAuB,KAAK;AAC5E;AAEA,SAAS,+BACP,OACA,SACA,SACyB;AACzB,MAAI,sBAAsB,OAAO,EAAG,QAAO;AAM3C,MAA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EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EACzF,CAAC;AACA,EAAC,WAAuC,gCAAgC,IAAI;AAC/E;AAgCO,SAAS,eAAe,MAAkC;AAC/D,yCAAuC;AAGvC,QAAM,YAAY,
|
|
4
|
+
"sourcesContent": ["import { createQueue } from '@open-mercato/queue'\nimport type { Queue } from '@open-mercato/queue'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isSingleDeliveryRequested } from './single-delivery'\nimport { matchEventPattern } from '@open-mercato/shared/lib/events/patterns'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport {\n isBroadcastEvent,\n isCoalescedBroadcastEvent,\n isCrossProcessBroadcastEvent,\n isPortalBroadcastEvent,\n isPrivateCrossProcessBroadcastEvent,\n isPrivateCrossProcessEventEmitter,\n} from '@open-mercato/shared/modules/events'\nimport {\n BROADCAST_FLUSH_DEADLINE_MS,\n flushPendingBroadcasts,\n resolveBroadcastCoalesceIntervalMs,\n submitBroadcast,\n} from './broadcast-coalescer'\nimport {\n inferModuleIdFromResourceId,\n withModuleResourceUsage,\n} from '@open-mercato/shared/lib/modules/resource-usage'\nexport { registerCrossProcessEventListener, CROSS_PROCESS_EVENT_INSTANCE_ID } from './bridge'\nimport { publishCrossProcessEvent } from './bridge'\nimport type {\n EventBus,\n CreateBusOptions,\n SubscriberHandler,\n SubscriberDescriptor,\n EventPayload,\n EmitOptions,\n QueuedDispatchResult,\n} from './types'\n\n/** Queue name for persistent events */\nconst EVENTS_QUEUE_NAME = 'events'\n\nconst logger = createLogger('events')\n\ntype RegisteredSubscriber = {\n id?: string\n moduleId?: string\n event: string\n handler: SubscriberHandler\n persistent?: boolean\n}\n\n/**\n * When enabled, a persistent emit delivers each subscriber on exactly one path:\n * persistent-marked subscribers are skipped inline (the events worker dispatches\n * them via pattern match, so wildcard persistent subscribers are reached), while\n * ephemeral subscribers keep running inline. Defaults ON.\n *\n * The bus never second-guesses this against \"is a worker running\": the queue is\n * durable, so a persistent emit with no worker yet is delayed, not lost, and a\n * worker started later drains the backlog. Delivering inline instead would move\n * the work back onto the caller's request path \u2014 exactly what a split app/worker\n * deployment sets `AUTO_SPAWN_WORKERS=false` to avoid.\n *\n * The events worker asks this same bus for its subscribers via `dispatchQueued`,\n * so both halves of single-delivery read one decision.\n */\nfunction isSingleDeliveryEnabled(): boolean {\n return isSingleDeliveryRequested()\n}\n\ntype GlobalEventTap = (event: string, payload: EventPayload, options?: EmitOptions) => void | Promise<void>\nconst GLOBAL_EVENT_TAPS_KEY = '__openMercatoEventBusGlobalTaps__'\n\nfunction hasTrustedTenantScope(options?: EmitOptions): boolean {\n return typeof options?.tenantId === 'string' && options.tenantId.trim().length > 0\n}\n\nfunction normalizePayloadScope(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\nfunction isBrowserBroadcastEvent(event: string): boolean {\n return isBroadcastEvent(event) || isPortalBroadcastEvent(event)\n}\n\n/** Relayed over the bridge: both browser audiences plus private coordination; each consumer filters by its own flag. */\nfunction shouldPublishCrossProcess(event: string): boolean {\n return isCrossProcessBroadcastEvent(event) || isPortalBroadcastEvent(event)\n}\n\nfunction resolveCrossProcessEmitOptions(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n): EmitOptions | undefined {\n if (hasTrustedTenantScope(options)) return options\n // Preserve the public raw EventBus contract for legacy clientBroadcast and\n // portalBroadcast emitters. These callers are trusted server code and\n // historically supplied their scope in the typed payload. Tenant-managed\n // workflow execution passes scope in options, while private cross-process\n // events never take this path.\n if (!isBrowserBroadcastEvent(event) || isPrivateCrossProcessBroadcastEvent(event)) return options\n const tenantId = normalizePayloadScope((payload as Record<string, unknown>)?.tenantId)\n if (!tenantId) return options\n const organizationId = normalizePayloadScope((payload as Record<string, unknown>)?.organizationId)\n const organizationIdsValue = (payload as Record<string, unknown>)?.organizationIds\n const organizationIds = Array.isArray(organizationIdsValue)\n ? organizationIdsValue.filter((value): value is string => typeof value === 'string')\n : []\n return {\n ...options,\n tenantId,\n ...(organizationId ? { organizationId } : {}),\n ...(organizationIds.length > 0 ? { organizationIds } : {}),\n }\n}\n\nfunction collectStringScopes(input: unknown): string[] {\n if (!Array.isArray(input)) return []\n const values: string[] = []\n for (const value of input) {\n if (typeof value !== 'string') continue\n const trimmed = value.trim()\n if (!trimmed) continue\n values.push(trimmed)\n }\n return values\n}\n\n// Sorted so an audience keys identically however the caller ordered it, and\n// explicitly comparator-ed per the #3620 guard.\nfunction sortScopes(scopes: Set<string>): string[] {\n return Array.from(scopes).sort((left, right) => left.localeCompare(right))\n}\n\n/**\n * Coalescing key for the browser dispatch of one event.\n *\n * Built from the raw union of every dimension the SSE audience filter\n * (`matchesAudience` in `events/api/stream/route.ts`) reads \u2014 tenant,\n * organization, recipient user and recipient role \u2014 taken from BOTH the\n * trusted `options` and the payload, without calling `resolveCrossProcessEmitOptions`\n * or any other resolver. Those resolvers pick one source to trust for delivery\n * semantics; the key instead has to key on every dimension a connection can be\n * filtered by, or one audience's emit would silently replace another\n * audience's pending delivery \u2014 recipient/role targeting and a portal-only\n * event (which carries no trusted `options` scope at all) included.\n *\n * Options and payload scope stay in separate segments, never merged: the three\n * filters each read a different source, so `options` org A + payload org B must\n * not key like the reverse. The options tenant segment encodes PRESENCE, not\n * just value \u2014 the backoffice `hasTrustedScope` is a presence test, so `{}` and\n * `{ tenantId: undefined }` take different filter branches and must not share\n * a key.\n *\n * Scope is part of the key by necessity, not for granularity: a key with no\n * scope segments would let a burst in one tenant suppress another tenant's\n * delivery and then deliver the first tenant's payload in its place.\n */\nfunction buildBroadcastCoalesceKey(event: string, payload: EventPayload, options?: EmitOptions): string {\n const data = (payload ?? {}) as Record<string, unknown>\n\n const payloadTenantId = normalizePayloadScope(data.tenantId) ?? ''\n const optionsTenantToken = options && Object.prototype.hasOwnProperty.call(options, 'tenantId')\n ? `=${normalizePayloadScope(options.tenantId) ?? ''}`\n : 'absent'\n\n const optionsOrganizationScopes = new Set<string>()\n const optionsOrganizationId = normalizePayloadScope(options?.organizationId)\n if (optionsOrganizationId) optionsOrganizationScopes.add(optionsOrganizationId)\n for (const organizationId of collectStringScopes(options?.organizationIds)) {\n optionsOrganizationScopes.add(organizationId)\n }\n\n const payloadOrganizationScopes = new Set<string>()\n const payloadOrganizationId = normalizePayloadScope(data.organizationId)\n if (payloadOrganizationId) payloadOrganizationScopes.add(payloadOrganizationId)\n for (const organizationId of collectStringScopes(data.organizationIds)) {\n payloadOrganizationScopes.add(organizationId)\n }\n\n const recipientUserScopes = new Set<string>()\n const recipientUserId = normalizePayloadScope(data.recipientUserId)\n if (recipientUserId) recipientUserScopes.add(recipientUserId)\n for (const userId of collectStringScopes(data.recipientUserIds)) {\n recipientUserScopes.add(userId)\n }\n\n const recipientRoleScopes = new Set<string>()\n const recipientRoleId = normalizePayloadScope(data.recipientRoleId)\n if (recipientRoleId) recipientRoleScopes.add(recipientRoleId)\n for (const roleId of collectStringScopes(data.recipientRoleIds)) {\n recipientRoleScopes.add(roleId)\n }\n\n return [\n event,\n payloadTenantId,\n optionsTenantToken,\n sortScopes(payloadOrganizationScopes).join(','),\n sortScopes(optionsOrganizationScopes).join(','),\n sortScopes(recipientUserScopes).join(','),\n sortScopes(recipientRoleScopes).join(','),\n ].join('::')\n}\n\nfunction getGlobalEventTaps(): Set<GlobalEventTap> {\n const existing = (globalThis as Record<string, unknown>)[GLOBAL_EVENT_TAPS_KEY]\n if (existing instanceof Set) {\n return existing as Set<GlobalEventTap>\n }\n const created = new Set<GlobalEventTap>()\n ;(globalThis as Record<string, unknown>)[GLOBAL_EVENT_TAPS_KEY] = created\n return created\n}\n\nexport function registerGlobalEventTap(handler: GlobalEventTap): () => void {\n const taps = getGlobalEventTaps()\n taps.add(handler)\n return () => {\n taps.delete(handler)\n }\n}\n\n/** Job data structure for queued events */\ntype EventJobData = {\n event: string\n payload: EventPayload\n options?: EmitOptions\n /**\n * Set by the producer when it already ran the persistent subscribers inline\n * (single-delivery reconciled off). The worker skips such jobs, so the app and\n * the worker staying exactly-once no longer depends on both processes agreeing\n * about `OM_EVENTS_SINGLE_DELIVERY`. Absent on jobs queued before this field\n * existed, which keeps their behavior unchanged.\n */\n persistentDeliveredInline?: boolean\n}\n\n// Process-wide cache of the async (BullMQ) persistent-events producer queue.\n// Each authenticated request builds a fresh DI container and event bus, so a\n// per-bus producer queue opened a new ioredis connection per write request that\n// was never closed \u2014 leaking one Redis connection per request until maxclients\n// exhaustion. Memoizing the producer on `globalThis` (keyed by Redis URL, so a\n// reconfigured URL still gets its own queue) keeps it at one connection per\n// process, mirroring the `GLOBAL_EVENT_TAPS_KEY` and `getCachedRateLimiterService`\n// patterns. The local (file-based) strategy holds no pooled connection and its\n// base dir is cwd-relative, so it stays per-bus.\nconst EVENTS_PRODUCER_QUEUE_KEY = '__openMercatoEventsProducerQueues__'\nconst EVENTS_PRODUCER_SHUTDOWN_KEY = '__openMercatoEventsProducerShutdown__'\nconst BROADCAST_COALESCER_SHUTDOWN_KEY = '__openMercatoBroadcastCoalescerShutdown__'\n\nfunction isSharedProducerEnabled(): boolean {\n return parseBooleanWithDefault(process.env.OM_EVENTS_SHARED_PRODUCER, true)\n}\n\nfunction getProducerQueueRegistry(): Map<string, Queue<EventJobData>> {\n const existing = (globalThis as Record<string, unknown>)[EVENTS_PRODUCER_QUEUE_KEY]\n if (existing instanceof Map) {\n return existing as Map<string, Queue<EventJobData>>\n }\n const created = new Map<string, Queue<EventJobData>>()\n ;(globalThis as Record<string, unknown>)[EVENTS_PRODUCER_QUEUE_KEY] = created\n return created\n}\n\nfunction registerProducerShutdownHook(): void {\n if ((globalThis as Record<string, unknown>)[EVENTS_PRODUCER_SHUTDOWN_KEY]) return\n const shutdown = () => {\n const registry = getProducerQueueRegistry()\n for (const sharedQueue of registry.values()) {\n Promise.resolve(sharedQueue.close()).catch(() => {})\n }\n registry.clear()\n }\n process.once('SIGTERM', shutdown)\n process.once('SIGINT', shutdown)\n ;(globalThis as Record<string, unknown>)[EVENTS_PRODUCER_SHUTDOWN_KEY] = true\n}\n\n/**\n * Deliver the tail of any in-flight coalesced burst on the way out, so stopping\n * a worker mid-import does not leave browsers a window behind. Registered\n * independently of the producer hook: coalescing is in play whether or not this\n * process ever opened an async producer queue.\n *\n * `beforeExit` matters as much as the signals here. The trailing timer is\n * unref'd so a pending browser delivery never holds a process open, which means\n * a short-lived emitter \u2014 a CLI import, a one-shot script \u2014 reaches a natural\n * exit with the tail still queued and no signal ever fired. `beforeExit` runs\n * exactly when the loop has drained, which is precisely that case.\n *\n * `createEventBus` calls this in every process that bootstraps DI \u2014 the app,\n * every worker, and every `mercato` CLI command \u2014 so a bare `process.once`\n * listener here would take away Node's default SIGINT/SIGTERM exit process-wide:\n * once ANY listener is registered for a signal, Node stops exiting on it, and\n * this listener only flushes, never exits. A one-shot CLI command (seed,\n * import, reindex) with no graceful-shutdown handler of its own would then\n * swallow the first Ctrl+C or SIGTERM and keep running until SIGKILL. The\n * per-signal handler below flushes, then restores the default behavior itself\n * \u2014 by re-raising the signal \u2014 but only when it was the last listener\n * (`once` already removed itself before this body runs): a process with its\n * own graceful-shutdown handler (the queue worker, `mercato server`) keeps\n * that handler in charge of the actual exit, and this hook just adds the flush\n * alongside it. Every flush here is capped at BROADCAST_FLUSH_DEADLINE_MS, so a\n * hung dispatch cannot hold a stop until SIGKILL.\n */\nfunction registerBroadcastCoalescerShutdownHook(): void {\n if ((globalThis as Record<string, unknown>)[BROADCAST_COALESCER_SHUTDOWN_KEY]) return\n const handleSignal = (signal: NodeJS.Signals) => {\n void flushPendingBroadcasts({ deadlineMs: BROADCAST_FLUSH_DEADLINE_MS })\n .catch(() => {})\n .finally(() => {\n if (process.listenerCount(signal) === 0) {\n process.kill(process.pid, signal)\n }\n })\n }\n process.once('SIGTERM', () => handleSignal('SIGTERM'))\n process.once('SIGINT', () => handleSignal('SIGINT'))\n process.once('beforeExit', () => {\n void flushPendingBroadcasts({ deadlineMs: BROADCAST_FLUSH_DEADLINE_MS }).catch(() => {})\n })\n ;(globalThis as Record<string, unknown>)[BROADCAST_COALESCER_SHUTDOWN_KEY] = true\n}\n\ntype EventBusGenerationState = {\n listeners: Map<string, Set<RegisteredSubscriber>>\n persistentSubscribers: Set<RegisteredSubscriber>\n queue: Queue<EventJobData> | null\n}\n\nfunction createEventBusGenerationState(): EventBusGenerationState {\n return { listeners: new Map(), persistentSubscribers: new Set(), queue: null }\n}\n\n/**\n * Creates an event bus instance.\n *\n * The event bus provides:\n * - In-memory event delivery to registered handlers\n * - Optional persistence via the queue package when `persistent: true`\n *\n * @param opts - Configuration options\n * @returns An EventBus instance\n *\n * @example\n * ```typescript\n * const bus = createEventBus({\n * resolve: container.resolve.bind(container),\n * queueStrategy: 'local', // or 'async' for BullMQ\n * })\n *\n * // Register a handler\n * bus.on('user.created', async (payload, ctx) => {\n * const userService = ctx.resolve('userService')\n * await userService.sendWelcomeEmail(payload.userId)\n * })\n *\n * // Emit an event (immediate delivery)\n * await bus.emit('user.created', { userId: '123' })\n *\n * // Emit with persistence (for async worker processing)\n * await bus.emit('order.placed', { orderId: '456' }, { persistent: true })\n * ```\n */\nexport function createEventBus(opts: CreateBusOptions): EventBus {\n return createEventBusWithState(opts, createEventBusGenerationState())\n}\n\nexport function createScopedEventBusFactory(options: Omit<CreateBusOptions, 'resolve'> = {}) {\n const state = createEventBusGenerationState()\n return Object.assign(\n (resolve: CreateBusOptions['resolve']): EventBus =>\n createEventBusWithState({ ...options, resolve }, createEventBusGenerationState(), state),\n {\n definitions: createEventBusWithState({\n ...options,\n resolve: () => { throw new Error('[internal] Event definitions cannot resolve caller services') },\n }, state),\n },\n )\n}\n\nfunction createEventBusWithState(\n opts: CreateBusOptions,\n state: EventBusGenerationState,\n definitions?: EventBusGenerationState,\n): EventBus {\n registerBroadcastCoalescerShutdownHook()\n\n // In-memory listeners for immediate event delivery\n const listeners = state.listeners\n // Subscribers registered as persistent (worker-dispatched). Used by the\n // single-delivery path to skip them inline on a persistent emit.\n const persistentSubscribers = state.persistentSubscribers\n const queueState = definitions ?? state\n function* listenerEntries() {\n if (definitions) yield* definitions.listeners\n yield* listeners\n }\n const isPersistentSubscriber = (subscriber: RegisteredSubscriber) =>\n persistentSubscribers.has(subscriber) || definitions?.persistentSubscribers.has(subscriber) === true\n\n // Determine queue strategy from options or environment\n const queueStrategy = opts.queueStrategy ??\n (process.env.QUEUE_STRATEGY === 'async' ? 'async' : 'local')\n\n /**\n * Gets or creates the queue instance for persistent events.\n *\n * The async (BullMQ) producer is memoized process-wide so the per-request\n * event bus reuses one Redis connection instead of leaking one per write\n * request. The local strategy stays per-bus (no pooled connection, cwd-relative\n * base dir). Set `OM_EVENTS_SHARED_PRODUCER=0` to fall back to per-bus producers.\n */\n function getQueue(): Queue<EventJobData> {\n if (queueStrategy !== 'async' || !isSharedProducerEnabled()) {\n if (!queueState.queue) {\n queueState.queue = queueStrategy === 'async'\n ? createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'async', {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n : createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'local')\n }\n return queueState.queue\n }\n\n const redisUrl = getRedisUrlOrThrow('QUEUE')\n const registry = getProducerQueueRegistry()\n const cacheKey = `async:${redisUrl}`\n let shared = registry.get(cacheKey)\n if (!shared) {\n shared = createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'async', {\n connection: { url: redisUrl },\n })\n registry.set(cacheKey, shared)\n registerProducerShutdownHook()\n }\n return shared\n }\n\n /**\n * Delivers an event to all registered in-memory handlers.\n * Supports wildcard pattern matching for event patterns.\n *\n * Handler errors are logged and delivery continues - one bad subscriber must\n * not stop the others. The count of failed PERSISTENT handlers is returned so\n * the caller can decide whether the inline run may be recorded as complete:\n * a persistent subscriber that threw inline has no retry of its own, so the\n * queued job must stay unstamped and let the worker run it again.\n */\n async function deliver(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n skipPersistent = false,\n ): Promise<{ persistentFailures: number }> {\n let persistentFailures = 0\n // Check all registered patterns (including wildcards)\n for (const [pattern, handlers] of listenerEntries()) {\n if (!matchEventPattern(event, pattern)) continue\n if (!handlers || handlers.size === 0) continue\n\n for (const subscriber of handlers) {\n // Single-delivery: persistent subscribers are dispatched by the worker,\n // so skip them inline to avoid double execution.\n if (skipPersistent && isPersistentSubscriber(subscriber)) continue\n try {\n // Pass eventName in context for wildcard handlers\n const moduleId = subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id)\n await withModuleResourceUsage(\n {\n moduleId,\n surface: 'subscriber',\n operation: `${event} -> ${subscriber.id ?? subscriber.event}`,\n resourceId: subscriber.id ?? subscriber.event,\n },\n () => subscriber.handler(payload, {\n resolve: opts.resolve,\n eventName: event,\n tenantId: options?.tenantId ?? null,\n organizationId: options?.organizationId ?? null,\n }),\n )\n } catch (error) {\n if (isPersistentSubscriber(subscriber)) {\n persistentFailures += 1\n }\n logger.error('Handler error', { event, pattern, err: error })\n if (options?.rethrowHandlerErrors) {\n throw error\n }\n }\n }\n }\n return { persistentFailures }\n }\n\n /**\n * Selects the subscribers the events worker owns for a queued event: every\n * pattern matching `event`, keeping persistent subscribers only, so wildcard\n * (`event: '*'`) persistent subscribers are reached exactly once here.\n *\n * Deliberately does NOT read `OM_EVENTS_SINGLE_DELIVERY`. Whether inline\n * delivery already happened is carried by the job's `persistentDeliveredInline`\n * stamp, so the producer owns that decision entirely and the worker cannot\n * disagree with it across processes. Reading the flag here would reintroduce\n * exactly that skew: a worker whose env has the flag off would fall back to\n * exact-match, re-running ephemeral subscribers the producer already ran inline\n * and never reaching wildcard persistent subscribers - the failure this whole\n * change exists to remove.\n *\n * Every job that reaches this point wants persistent-pattern selection: a job\n * is only dispatched when its stamp is false, which means either the producer\n * had single-delivery on, or the emit was enqueue-only (`deliverInline: false`,\n * documented as \"every subscriber to the event is persistent\").\n */\n function selectQueuedSubscribers(event: string): RegisteredSubscriber[] {\n const matched: RegisteredSubscriber[] = []\n for (const [pattern, handlers] of listenerEntries()) {\n if (!matchEventPattern(event, pattern)) {\n continue\n }\n for (const subscriber of handlers) {\n if (subscriber.persistent) {\n matched.push(subscriber)\n }\n }\n }\n return matched\n }\n\n /**\n * Dispatches a queued event on behalf of the events worker.\n *\n * Handler failures are returned instead of logged-and-swallowed the way\n * `deliver()` does them: the worker needs them to propagate so the queue retries\n * the job and eventually dead-letters it.\n *\n * Subscribers run against the caller's `resolve` when one is given, falling back\n * to the bus's own. The events worker passes its per-job `ctx.resolve`, which is\n * the container `createPerJobWorkerHandler` built for that job - the handle the\n * queue contract already hands it. Defaulting to `opts.resolve` instead would\n * bind subscribers to whichever container built the bus; that is the same object\n * on the default configuration, but not under `OM_BOOTSTRAP_CACHE`, where the\n * cached bus is replayed into later containers while its captured resolver stays\n * bound to the first.\n */\n async function dispatchQueued(\n event: string,\n payload: EventPayload,\n options?: EmitOptions,\n resolve?: <T = unknown>(name: string) => T,\n ): Promise<QueuedDispatchResult[]> {\n const subscribers = selectQueuedSubscribers(event)\n if (subscribers.length === 0) {\n return []\n }\n\n const resolver = resolve ?? opts.resolve\n\n const settled = await Promise.allSettled(\n subscribers.map((subscriber) =>\n withModuleResourceUsage(\n {\n moduleId: subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id),\n surface: 'subscriber',\n operation: `${event} -> ${subscriber.id ?? subscriber.event}`,\n resourceId: subscriber.id ?? subscriber.event,\n },\n () => subscriber.handler(payload, {\n resolve: resolver,\n eventName: event,\n tenantId: options?.tenantId ?? null,\n organizationId: options?.organizationId ?? null,\n }),\n ),\n ),\n )\n\n return settled.map((result, index) => {\n const subscriberId = subscribers[index].id ?? subscribers[index].event\n return result.status === 'rejected'\n ? { subscriberId, ok: false, error: result.reason }\n : { subscriberId, ok: true }\n })\n }\n\n /**\n * Registers a handler for an event. Pass `moduleId` whenever the subscribing\n * module is known (e.g. a module reacting to another module's event) so\n * resource-usage telemetry attributes the handler correctly instead of\n * guessing a module id from the event name.\n */\n function on(\n event: string,\n handler: SubscriberHandler,\n options?: { persistent?: boolean; moduleId?: string; id?: string },\n ): void {\n if (!listeners.has(event)) {\n listeners.set(event, new Set())\n }\n const subscriber: RegisteredSubscriber = {\n id: options?.id,\n moduleId: options?.moduleId,\n event,\n handler,\n persistent: options?.persistent,\n }\n listeners.get(event)!.add(subscriber)\n if (options?.persistent) {\n persistentSubscribers.add(subscriber)\n }\n }\n\n /**\n * Registers multiple module subscribers at once.\n */\n function registerModuleSubscribers(subs: SubscriberDescriptor[]): void {\n for (const sub of subs) {\n on(sub.event, sub.handler, { persistent: sub.persistent, moduleId: sub.moduleId, id: sub.id })\n }\n }\n\n /**\n * Emits an event to all registered handlers.\n *\n * If `persistent: true`, also enqueues the event for async processing.\n */\n async function emit(\n event: string,\n payload: EventPayload,\n options?: EmitOptions\n ): Promise<void> {\n const runGlobalTaps = async (): Promise<void> => {\n const taps = getGlobalEventTaps()\n for (const tap of taps) {\n try {\n await Promise.resolve(tap(event, payload, options))\n } catch (error) {\n logger.error('Global tap error', { event, err: error })\n }\n }\n }\n\n // Resolved at call time, never hoisted. Private coordination always requires\n // trusted envelope scope and module provenance. Legacy declared browser events\n // may promote their typed scope for raw EventBus compatibility; tenant-managed\n // workflow adapters pass authoritative scope in options, which always wins over\n // payload values. Computing it lazily keeps the non-coalesced path resolving\n // scope at exactly the point it always did \u2014 after inline delivery \u2014 so an\n // event that did not opt in cannot observe this change at all.\n const publishToOtherProcesses = async (): Promise<void> => {\n const crossProcessOptions = resolveCrossProcessEmitOptions(event, payload, options)\n if (\n !shouldPublishCrossProcess(event)\n || !hasTrustedTenantScope(crossProcessOptions)\n || !isPrivateCrossProcessEventEmitter(event, crossProcessOptions?.emitterModuleId)\n ) return\n try {\n await publishCrossProcessEvent(event, payload, crossProcessOptions)\n } catch (error) {\n logger.error('Cross-process publish error', { event, err: error })\n }\n }\n\n // Global taps are not a browser-only sink \u2014 `registerGlobalEventTap` is a\n // public export that any process-local listener can use (the create-app\n // template's qa-events route captures events for integration tests through\n // it, and third-party modules can too), not just the two SSE endpoints. What\n // both taps and the SSE bridges have in common is that neither carries domain\n // meaning on its own, so an opted-in event may coalesce this dispatch \u2014 and\n // with it every tap's delivery \u2014 without touching subscriber, webhook or\n // queue semantics below. A tap on a coalesced event sees the same suppressed,\n // trailing-flush-guaranteed stream the browser does, not one call per record.\n const coalesceBrowserDelivery = isCoalescedBroadcastEvent(event)\n && resolveBroadcastCoalesceIntervalMs() > 0\n if (coalesceBrowserDelivery) {\n await submitBroadcast(\n buildBroadcastCoalesceKey(event, payload, options),\n async () => {\n await runGlobalTaps()\n await publishToOtherProcesses()\n },\n )\n } else {\n await runGlobalTaps()\n }\n\n // Deliver to in-memory handlers first. Under single-delivery, persistent\n // subscribers are skipped inline on a persistent emit because the events\n // worker will dispatch them from the queue.\n //\n // `deliverInline: false` on a persistent emit is enqueue-only: skip inline\n // delivery entirely so a heavy persistent job runs solely in the events\n // worker, off the caller's request path (the queued enqueue below still\n // happens). Without this, a persistent emit dual-dispatches by default and\n // runs the subscriber inline in the caller's request too.\n const enqueueOnly = Boolean(options?.persistent) && options?.deliverInline === false\n // Read the mode once so the inline skip and the stamp below cannot disagree.\n const singleDelivery = isSingleDeliveryEnabled()\n const skipPersistentInline = options?.skipPersistentSubscribersInline === true\n || (Boolean(options?.persistent) && singleDelivery)\n let inlinePersistentFailed = false\n if (!enqueueOnly) {\n const delivered = await deliver(event, payload, options, skipPersistentInline)\n inlinePersistentFailed = delivered.persistentFailures > 0\n }\n\n // Already dispatched with the taps when this event coalesces its browser\n // delivery; otherwise it publishes here, exactly where it always has.\n if (!coalesceBrowserDelivery) {\n await publishToOtherProcesses()\n }\n\n // If persistent, also enqueue for async processing\n if (options?.persistent) {\n const q = getQueue()\n await q.enqueue({\n event,\n payload,\n options,\n // Only record the inline run as complete when every persistent\n // subscriber actually succeeded. Inline delivery logs-and-continues, so a\n // handler that threw has no retry of its own; leaving the job unstamped\n // hands it to the worker, where a failure gets queue retry and\n // dead-lettering. Without this, flipping the flag off (which the\n // `mercato server` guard can do automatically) silently downgrades\n // persistent delivery to at-most-once.\n persistentDeliveredInline: !enqueueOnly && !skipPersistentInline && !inlinePersistentFailed,\n })\n }\n }\n\n /**\n * Clears all events from the persistent queue.\n */\n async function clearQueue(): Promise<{ removed: number }> {\n const q = getQueue()\n return q.clear()\n }\n\n // Backward compatibility alias\n const emitEvent = emit\n\n return {\n emit,\n emitEvent, // Alias for backward compatibility\n on,\n registerModuleSubscribers,\n dispatchQueued,\n clearQueue,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,+BAA+B;AACxC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,mCAAmC,uCAAuC;AACnF,SAAS,gCAAgC;AAYzC,MAAM,oBAAoB;AAE1B,MAAM,SAAS,aAAa,QAAQ;AAyBpC,SAAS,0BAAmC;AAC1C,SAAO,0BAA0B;AACnC;AAGA,MAAM,wBAAwB;AAE9B,SAAS,sBAAsB,SAAgC;AAC7D,SAAO,OAAO,SAAS,aAAa,YAAY,QAAQ,SAAS,KAAK,EAAE,SAAS;AACnF;AAEA,SAAS,sBAAsB,OAA+B;AAC5D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,SAAS,wBAAwB,OAAwB;AACvD,SAAO,iBAAiB,KAAK,KAAK,uBAAuB,KAAK;AAChE;AAGA,SAAS,0BAA0B,OAAwB;AACzD,SAAO,6BAA6B,KAAK,KAAK,uBAAuB,KAAK;AAC5E;AAEA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0.11.1-develop.8418.1.8ddb502575",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
}
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@open-mercato/queue": "0.11.1-develop.
|
|
37
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
36
|
+
"@open-mercato/queue": "0.11.1-develop.8418.1.8ddb502575",
|
|
37
|
+
"@open-mercato/shared": "0.11.1-develop.8418.1.8ddb502575",
|
|
38
38
|
"pg": "8.23.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createScopedEventBusFactory } from '../bus'
|
|
2
|
+
import type { CreateBusOptions } from '../types'
|
|
3
|
+
|
|
4
|
+
function resolver(services: Record<string, unknown>): CreateBusOptions['resolve'] {
|
|
5
|
+
return <Service>(name: string) => services[name] as Service
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
it('shares definitions while retaining the exact caller through interleaved delivery', async () => {
|
|
9
|
+
const createBus = createScopedEventBusFactory({ queueStrategy: 'local' })
|
|
10
|
+
const first = createBus(resolver({ em: 'first-em', auth: 'first-user' }))
|
|
11
|
+
const second = createBus(resolver({ em: 'second-em', auth: 'second-user' }))
|
|
12
|
+
let releaseFirst = () => {}
|
|
13
|
+
const firstBlocked = new Promise<void>((resolve) => { releaseFirst = resolve })
|
|
14
|
+
const observed: string[] = []
|
|
15
|
+
createBus.definitions.on('probe.created', async (payload, context) => {
|
|
16
|
+
if (payload === 'first') await firstBlocked
|
|
17
|
+
observed.push(`${context.resolve('em')}:${context.resolve('auth')}`)
|
|
18
|
+
})
|
|
19
|
+
const firstDelivery = first.emit('probe.created', 'first')
|
|
20
|
+
await second.emit('probe.created', 'second')
|
|
21
|
+
releaseFirst()
|
|
22
|
+
await firstDelivery
|
|
23
|
+
expect(observed).toEqual(['second-em:second-user', 'first-em:first-user'])
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('does not multiply listeners when creating caller facades and respects an explicit worker resolver', async () => {
|
|
27
|
+
const createBus = createScopedEventBusFactory()
|
|
28
|
+
const definitionBus = createBus.definitions
|
|
29
|
+
const seen: string[] = []
|
|
30
|
+
definitionBus.on('probe.*', (_payload, context) => { seen.push(context.resolve('em')) }, { persistent: true })
|
|
31
|
+
for (let index = 0; index < 20; index += 1) createBus(resolver({ em: `caller-${index}` }))
|
|
32
|
+
const caller = createBus(resolver({ em: 'caller' }))
|
|
33
|
+
await caller.dispatchQueued!('probe.created', {}, undefined, resolver({ em: 'worker' }))
|
|
34
|
+
expect(seen).toEqual(['worker'])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('a replacement generation drops old subscribers including an empty replacement', async () => {
|
|
38
|
+
const createOldBus = createScopedEventBusFactory()
|
|
39
|
+
const oldBus = createOldBus(resolver({}))
|
|
40
|
+
const handler = jest.fn()
|
|
41
|
+
oldBus.on('probe.created', handler)
|
|
42
|
+
const newBus = createScopedEventBusFactory()(resolver({}))
|
|
43
|
+
await newBus.emit('probe.created', {})
|
|
44
|
+
expect(handler).not.toHaveBeenCalled()
|
|
45
|
+
await oldBus.emit('probe.created', {})
|
|
46
|
+
expect(handler).toHaveBeenCalledTimes(1)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
it('keeps runtime subscriptions local while sharing generation definitions', async () => {
|
|
51
|
+
const createBus = createScopedEventBusFactory()
|
|
52
|
+
const shared = jest.fn()
|
|
53
|
+
createBus.definitions.on('probe.created', shared)
|
|
54
|
+
const first = createBus(resolver({ em: 'first' }))
|
|
55
|
+
const second = createBus(resolver({ em: 'second' }))
|
|
56
|
+
const firstOnly = jest.fn()
|
|
57
|
+
first.on('probe.created', firstOnly)
|
|
58
|
+
await second.emit('probe.created', {})
|
|
59
|
+
expect(shared).toHaveBeenCalledTimes(1)
|
|
60
|
+
expect(firstOnly).not.toHaveBeenCalled()
|
|
61
|
+
await first.emit('probe.created', {})
|
|
62
|
+
expect(shared).toHaveBeenCalledTimes(2)
|
|
63
|
+
expect(firstOnly).toHaveBeenCalledTimes(1)
|
|
64
|
+
})
|
package/src/bus.ts
CHANGED
|
@@ -323,6 +323,16 @@ function registerBroadcastCoalescerShutdownHook(): void {
|
|
|
323
323
|
;(globalThis as Record<string, unknown>)[BROADCAST_COALESCER_SHUTDOWN_KEY] = true
|
|
324
324
|
}
|
|
325
325
|
|
|
326
|
+
type EventBusGenerationState = {
|
|
327
|
+
listeners: Map<string, Set<RegisteredSubscriber>>
|
|
328
|
+
persistentSubscribers: Set<RegisteredSubscriber>
|
|
329
|
+
queue: Queue<EventJobData> | null
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function createEventBusGenerationState(): EventBusGenerationState {
|
|
333
|
+
return { listeners: new Map(), persistentSubscribers: new Set(), queue: null }
|
|
334
|
+
}
|
|
335
|
+
|
|
326
336
|
/**
|
|
327
337
|
* Creates an event bus instance.
|
|
328
338
|
*
|
|
@@ -354,21 +364,47 @@ function registerBroadcastCoalescerShutdownHook(): void {
|
|
|
354
364
|
* ```
|
|
355
365
|
*/
|
|
356
366
|
export function createEventBus(opts: CreateBusOptions): EventBus {
|
|
367
|
+
return createEventBusWithState(opts, createEventBusGenerationState())
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function createScopedEventBusFactory(options: Omit<CreateBusOptions, 'resolve'> = {}) {
|
|
371
|
+
const state = createEventBusGenerationState()
|
|
372
|
+
return Object.assign(
|
|
373
|
+
(resolve: CreateBusOptions['resolve']): EventBus =>
|
|
374
|
+
createEventBusWithState({ ...options, resolve }, createEventBusGenerationState(), state),
|
|
375
|
+
{
|
|
376
|
+
definitions: createEventBusWithState({
|
|
377
|
+
...options,
|
|
378
|
+
resolve: () => { throw new Error('[internal] Event definitions cannot resolve caller services') },
|
|
379
|
+
}, state),
|
|
380
|
+
},
|
|
381
|
+
)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function createEventBusWithState(
|
|
385
|
+
opts: CreateBusOptions,
|
|
386
|
+
state: EventBusGenerationState,
|
|
387
|
+
definitions?: EventBusGenerationState,
|
|
388
|
+
): EventBus {
|
|
357
389
|
registerBroadcastCoalescerShutdownHook()
|
|
358
390
|
|
|
359
391
|
// In-memory listeners for immediate event delivery
|
|
360
|
-
const listeners =
|
|
392
|
+
const listeners = state.listeners
|
|
361
393
|
// Subscribers registered as persistent (worker-dispatched). Used by the
|
|
362
394
|
// single-delivery path to skip them inline on a persistent emit.
|
|
363
|
-
const persistentSubscribers =
|
|
395
|
+
const persistentSubscribers = state.persistentSubscribers
|
|
396
|
+
const queueState = definitions ?? state
|
|
397
|
+
function* listenerEntries() {
|
|
398
|
+
if (definitions) yield* definitions.listeners
|
|
399
|
+
yield* listeners
|
|
400
|
+
}
|
|
401
|
+
const isPersistentSubscriber = (subscriber: RegisteredSubscriber) =>
|
|
402
|
+
persistentSubscribers.has(subscriber) || definitions?.persistentSubscribers.has(subscriber) === true
|
|
364
403
|
|
|
365
404
|
// Determine queue strategy from options or environment
|
|
366
405
|
const queueStrategy = opts.queueStrategy ??
|
|
367
406
|
(process.env.QUEUE_STRATEGY === 'async' ? 'async' : 'local')
|
|
368
407
|
|
|
369
|
-
// Lazy-initialized queue for persistent events
|
|
370
|
-
let queue: Queue<EventJobData> | null = null
|
|
371
|
-
|
|
372
408
|
/**
|
|
373
409
|
* Gets or creates the queue instance for persistent events.
|
|
374
410
|
*
|
|
@@ -379,14 +415,14 @@ export function createEventBus(opts: CreateBusOptions): EventBus {
|
|
|
379
415
|
*/
|
|
380
416
|
function getQueue(): Queue<EventJobData> {
|
|
381
417
|
if (queueStrategy !== 'async' || !isSharedProducerEnabled()) {
|
|
382
|
-
if (!queue) {
|
|
383
|
-
queue = queueStrategy === 'async'
|
|
418
|
+
if (!queueState.queue) {
|
|
419
|
+
queueState.queue = queueStrategy === 'async'
|
|
384
420
|
? createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'async', {
|
|
385
421
|
connection: { url: getRedisUrlOrThrow('QUEUE') },
|
|
386
422
|
})
|
|
387
423
|
: createQueue<EventJobData>(EVENTS_QUEUE_NAME, 'local')
|
|
388
424
|
}
|
|
389
|
-
return queue
|
|
425
|
+
return queueState.queue
|
|
390
426
|
}
|
|
391
427
|
|
|
392
428
|
const redisUrl = getRedisUrlOrThrow('QUEUE')
|
|
@@ -421,14 +457,14 @@ export function createEventBus(opts: CreateBusOptions): EventBus {
|
|
|
421
457
|
): Promise<{ persistentFailures: number }> {
|
|
422
458
|
let persistentFailures = 0
|
|
423
459
|
// Check all registered patterns (including wildcards)
|
|
424
|
-
for (const [pattern, handlers] of
|
|
460
|
+
for (const [pattern, handlers] of listenerEntries()) {
|
|
425
461
|
if (!matchEventPattern(event, pattern)) continue
|
|
426
462
|
if (!handlers || handlers.size === 0) continue
|
|
427
463
|
|
|
428
464
|
for (const subscriber of handlers) {
|
|
429
465
|
// Single-delivery: persistent subscribers are dispatched by the worker,
|
|
430
466
|
// so skip them inline to avoid double execution.
|
|
431
|
-
if (skipPersistent &&
|
|
467
|
+
if (skipPersistent && isPersistentSubscriber(subscriber)) continue
|
|
432
468
|
try {
|
|
433
469
|
// Pass eventName in context for wildcard handlers
|
|
434
470
|
const moduleId = subscriber.moduleId ?? inferModuleIdFromResourceId(subscriber.id)
|
|
@@ -447,7 +483,7 @@ export function createEventBus(opts: CreateBusOptions): EventBus {
|
|
|
447
483
|
}),
|
|
448
484
|
)
|
|
449
485
|
} catch (error) {
|
|
450
|
-
if (
|
|
486
|
+
if (isPersistentSubscriber(subscriber)) {
|
|
451
487
|
persistentFailures += 1
|
|
452
488
|
}
|
|
453
489
|
logger.error('Handler error', { event, pattern, err: error })
|
|
@@ -481,7 +517,7 @@ export function createEventBus(opts: CreateBusOptions): EventBus {
|
|
|
481
517
|
*/
|
|
482
518
|
function selectQueuedSubscribers(event: string): RegisteredSubscriber[] {
|
|
483
519
|
const matched: RegisteredSubscriber[] = []
|
|
484
|
-
for (const [pattern, handlers] of
|
|
520
|
+
for (const [pattern, handlers] of listenerEntries()) {
|
|
485
521
|
if (!matchEventPattern(event, pattern)) {
|
|
486
522
|
continue
|
|
487
523
|
}
|