@burdenoff/be-sdk 2026.1021.1 → 2026.1021.3
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/EventQueueFactory-JG7S6HOL.js +8 -0
- package/dist/{EventQueueFactory-ZHBJD3OD.js.map → EventQueueFactory-JG7S6HOL.js.map} +1 -1
- package/dist/{chunk-6VK53YR3.js → chunk-5OROGKQW.js} +3 -3
- package/dist/{chunk-6VK53YR3.js.map → chunk-5OROGKQW.js.map} +1 -1
- package/dist/{chunk-E5HKS7KD.js → chunk-7SOI4IHZ.js} +4 -4
- package/dist/{chunk-E5HKS7KD.js.map → chunk-7SOI4IHZ.js.map} +1 -1
- package/dist/{chunk-P67HNJGL.js → chunk-DNULGVN3.js} +14 -7
- package/dist/chunk-DNULGVN3.js.map +1 -0
- package/dist/{chunk-GJR6AQAL.js → chunk-F4R5AHSD.js} +4 -4
- package/dist/{chunk-GJR6AQAL.js.map → chunk-F4R5AHSD.js.map} +1 -1
- package/dist/chunk-GRGTUP44.js +394 -0
- package/dist/chunk-GRGTUP44.js.map +1 -0
- package/dist/{chunk-RTBCGUHC.js → chunk-GSIJ2DBJ.js} +6 -5
- package/dist/chunk-GSIJ2DBJ.js.map +1 -0
- package/dist/{chunk-XTIOBNT7.js → chunk-HEAQSZBX.js} +7 -6
- package/dist/chunk-HEAQSZBX.js.map +1 -0
- package/dist/chunk-JV7XNJP4.js +1334 -0
- package/dist/chunk-JV7XNJP4.js.map +1 -0
- package/dist/chunk-KS2HQCJR.js +56 -0
- package/dist/chunk-KS2HQCJR.js.map +1 -0
- package/dist/{chunk-NCC5UN3L.js → chunk-YCSIHUYP.js} +5 -365
- package/dist/chunk-YCSIHUYP.js.map +1 -0
- package/dist/env-4UWSUS64.js +4 -0
- package/dist/env-4UWSUS64.js.map +1 -0
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/event-queue/index.js +4 -3
- package/dist/explicit-activity-scope-CCoxVwAr.d.ts +3 -0
- package/dist/graph/index.js +6 -5
- package/dist/index-BVXRewdr.d.ts +1066 -0
- package/dist/{index-BSlifT21.d.ts → index-D0hKZ9e2.d.ts} +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +18 -16
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/prisma/index.js +5 -4
- package/dist/server/index.d.ts +15 -3
- package/dist/server/index.js +224 -1
- package/dist/server/index.js.map +1 -1
- package/dist/tracker/index.d.ts +2 -1
- package/dist/tracker/index.js +2 -1
- package/package.json +1 -1
- package/dist/EventQueueFactory-ZHBJD3OD.js +0 -7
- package/dist/chunk-NCC5UN3L.js.map +0 -1
- package/dist/chunk-P67HNJGL.js.map +0 -1
- package/dist/chunk-RTBCGUHC.js.map +0 -1
- package/dist/chunk-VD4B362H.js +0 -464
- package/dist/chunk-VD4B362H.js.map +0 -1
- package/dist/chunk-XTIOBNT7.js.map +0 -1
- package/dist/index-CpXKka7c.d.ts +0 -690
|
@@ -0,0 +1,1334 @@
|
|
|
1
|
+
import { resetGraphEventEmitter, getGraphEventEmitter, createMemoryPublisher, createGraphEventEmitter, createMemoryConsumer, createGraphEventEmitter2, MemoryEventQueue, MemoryEventPublisher, MemoryEventConsumer, MemoryEventBus, GraphEventEmitterImpl } from './chunk-HEAQSZBX.js';
|
|
2
|
+
import { RedisStreamsEventPublisher, RedisStreamsEventConsumer, QueueType, EventQueueFactory } from './chunk-DNULGVN3.js';
|
|
3
|
+
import { resolveGraphEventsUrlSource, resolveGraphEventsUrl, resolveEventStreamsUrlSource, resolveEventStreamsUrl, eventKeyScopeForUrl, GRAPH_EVENTS_URL_ENV_KEYS, EVENT_STREAMS_URL_ENV_KEYS } from './chunk-KS2HQCJR.js';
|
|
4
|
+
import { streamKey, dlqKey, RedisStreamsConnection, matchSubject } from './chunk-LKCBI6B2.js';
|
|
5
|
+
import { logger } from './chunk-RU266375.js';
|
|
6
|
+
import { __export, __name } from './chunk-XE4OXN2W.js';
|
|
7
|
+
import { randomUUID } from 'crypto';
|
|
8
|
+
|
|
9
|
+
// src/event-queue/index.ts
|
|
10
|
+
var event_queue_exports = {};
|
|
11
|
+
__export(event_queue_exports, {
|
|
12
|
+
EVENT_STREAMS_URL_ENV_KEYS: () => EVENT_STREAMS_URL_ENV_KEYS,
|
|
13
|
+
EVENT_TAXONOMY_BRAND: () => EVENT_TAXONOMY_BRAND,
|
|
14
|
+
EventPriority: () => EventPriority,
|
|
15
|
+
EventQueueFactory: () => EventQueueFactory,
|
|
16
|
+
EventsManager: () => EventsManager,
|
|
17
|
+
EventsModule: () => EventsModule,
|
|
18
|
+
GRAPH_EVENTS_URL_ENV_KEYS: () => GRAPH_EVENTS_URL_ENV_KEYS,
|
|
19
|
+
GraphEventEmitterImpl: () => GraphEventEmitterImpl,
|
|
20
|
+
LIFECYCLE_SUBJECTS: () => LIFECYCLE_SUBJECTS,
|
|
21
|
+
MemoryEventBus: () => MemoryEventBus,
|
|
22
|
+
MemoryEventConsumer: () => MemoryEventConsumer,
|
|
23
|
+
MemoryEventPublisher: () => MemoryEventPublisher,
|
|
24
|
+
MemoryEventQueue: () => MemoryEventQueue,
|
|
25
|
+
ModuleEventsService: () => ModuleEventsService,
|
|
26
|
+
PLATFORM_EVENT_TAXONOMY: () => PLATFORM_EVENT_TAXONOMY,
|
|
27
|
+
QueueType: () => QueueType,
|
|
28
|
+
REFERENCE_PRODUCT_EVENT_TAXONOMY: () => REFERENCE_PRODUCT_EVENT_TAXONOMY,
|
|
29
|
+
RedisStreamsConnection: () => RedisStreamsConnection,
|
|
30
|
+
RedisStreamsEventConsumer: () => RedisStreamsEventConsumer,
|
|
31
|
+
RedisStreamsEventPublisher: () => RedisStreamsEventPublisher,
|
|
32
|
+
WSPACE_GRAPH_EVENTS_STREAM: () => WSPACE_GRAPH_EVENTS_STREAM,
|
|
33
|
+
buildConsumerGroupName: () => buildConsumerGroupName,
|
|
34
|
+
createConsumer: () => createConsumer,
|
|
35
|
+
createEventsManagerSingleton: () => createEventsManagerSingleton,
|
|
36
|
+
createGraphEventEmitter: () => createGraphEventEmitter2,
|
|
37
|
+
createLifecycleConsumer: () => createLifecycleConsumer,
|
|
38
|
+
createMemoryConsumer: () => createMemoryConsumer,
|
|
39
|
+
createMemoryGraphEventEmitter: () => createGraphEventEmitter,
|
|
40
|
+
createMemoryPublisher: () => createMemoryPublisher,
|
|
41
|
+
createModuleEventsService: () => createModuleEventsService,
|
|
42
|
+
createPublisher: () => createPublisher,
|
|
43
|
+
defineEventTaxonomy: () => defineEventTaxonomy,
|
|
44
|
+
eventKeyScopeForUrl: () => eventKeyScopeForUrl,
|
|
45
|
+
eventSpec: () => eventSpec,
|
|
46
|
+
getGraphEventEmitter: () => getGraphEventEmitter,
|
|
47
|
+
isDefinedEventTaxonomy: () => isDefinedEventTaxonomy,
|
|
48
|
+
mergeEventTaxonomies: () => mergeEventTaxonomies,
|
|
49
|
+
parseOrganizationDeleted: () => parseOrganizationDeleted,
|
|
50
|
+
parseWorkspaceDeletedGraph: () => parseWorkspaceDeletedGraph,
|
|
51
|
+
parseWorkspaceDeletedStream: () => parseWorkspaceDeletedStream,
|
|
52
|
+
parseWorkspaceMemberRemoved: () => parseWorkspaceMemberRemoved,
|
|
53
|
+
publishTaxonomyEvent: () => publishTaxonomyEvent,
|
|
54
|
+
redisDlqKey: () => dlqKey,
|
|
55
|
+
redisStreamKey: () => streamKey,
|
|
56
|
+
resetGraphEventEmitter: () => resetGraphEventEmitter,
|
|
57
|
+
resolveEventStreamsUrl: () => resolveEventStreamsUrl,
|
|
58
|
+
resolveEventStreamsUrlSource: () => resolveEventStreamsUrlSource,
|
|
59
|
+
resolveGraphEventsUrl: () => resolveGraphEventsUrl,
|
|
60
|
+
resolveGraphEventsUrlSource: () => resolveGraphEventsUrlSource,
|
|
61
|
+
taxonomyEventNames: () => taxonomyEventNames,
|
|
62
|
+
taxonomyNameViolation: () => taxonomyNameViolation
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// src/event-queue/module-events.ts
|
|
66
|
+
var ModuleEventsService = class {
|
|
67
|
+
static {
|
|
68
|
+
__name(this, "ModuleEventsService");
|
|
69
|
+
}
|
|
70
|
+
productSource;
|
|
71
|
+
subjectPrefix;
|
|
72
|
+
loggerLabel;
|
|
73
|
+
publisher;
|
|
74
|
+
connected = false;
|
|
75
|
+
connecting = null;
|
|
76
|
+
constructor(config) {
|
|
77
|
+
this.productSource = config.moduleName;
|
|
78
|
+
this.subjectPrefix = config.subjectPrefix || config.moduleName;
|
|
79
|
+
this.loggerLabel = config.loggerLabel || `${config.moduleName.charAt(0).toUpperCase()}${config.moduleName.slice(1)}EventsService`;
|
|
80
|
+
if (process.env["REDIS_URL"]) {
|
|
81
|
+
this.publisher = EventQueueFactory.createPublisherFromEnv();
|
|
82
|
+
logger.info(`[${this.loggerLabel}] Using Redis Streams publisher`);
|
|
83
|
+
} else {
|
|
84
|
+
this.publisher = new MemoryEventPublisher();
|
|
85
|
+
logger.info(`[${this.loggerLabel}] Using in-memory publisher (REDIS_URL not configured)`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Ensure publisher is connected before publishing
|
|
90
|
+
*/
|
|
91
|
+
async ensureConnected() {
|
|
92
|
+
if (this.connected) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (this.connecting) {
|
|
96
|
+
await this.connecting;
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
this.connecting = this.publisher.connect().then(() => {
|
|
100
|
+
this.connected = true;
|
|
101
|
+
this.connecting = null;
|
|
102
|
+
logger.info(`[${this.loggerLabel}] Publisher connected`);
|
|
103
|
+
});
|
|
104
|
+
await this.connecting;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Publish an event to the queue
|
|
108
|
+
*/
|
|
109
|
+
async publish(subject, payload) {
|
|
110
|
+
await this.ensureConnected();
|
|
111
|
+
await this.publisher.publish({
|
|
112
|
+
subject,
|
|
113
|
+
data: payload
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Build event payload
|
|
118
|
+
*/
|
|
119
|
+
buildPayload(type, action, id, data, userId, tenantId, workspaceId, correlationId) {
|
|
120
|
+
return {
|
|
121
|
+
id,
|
|
122
|
+
type,
|
|
123
|
+
action,
|
|
124
|
+
data,
|
|
125
|
+
metadata: {
|
|
126
|
+
tenantId,
|
|
127
|
+
workspaceId,
|
|
128
|
+
userId,
|
|
129
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
130
|
+
productSource: this.productSource,
|
|
131
|
+
...correlationId && {
|
|
132
|
+
correlationId
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Build subject string
|
|
139
|
+
*/
|
|
140
|
+
buildSubject(entityType, action) {
|
|
141
|
+
const normalizedType = entityType.replace(/^Universal/, "").replace(/([A-Z])/g, (_match, p1, offset) => (offset > 0 ? "_" : "") + p1.toLowerCase()).replace(/^_/, "");
|
|
142
|
+
return `${this.subjectPrefix}.${normalizedType}.${action}`;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Publish entity created event
|
|
146
|
+
*/
|
|
147
|
+
async publishCreated(entityType, id, data, userId, tenantId, workspaceId) {
|
|
148
|
+
const payload = this.buildPayload(entityType, "created", id, data, userId, tenantId, workspaceId);
|
|
149
|
+
await this.publish(this.buildSubject(entityType, "created"), payload);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Publish entity updated event
|
|
153
|
+
*/
|
|
154
|
+
async publishUpdated(entityType, id, data, userId, tenantId, workspaceId) {
|
|
155
|
+
const payload = this.buildPayload(entityType, "updated", id, data, userId, tenantId, workspaceId);
|
|
156
|
+
await this.publish(this.buildSubject(entityType, "updated"), payload);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Publish entity deleted event
|
|
160
|
+
*/
|
|
161
|
+
async publishDeleted(entityType, id, userId, tenantId, workspaceId) {
|
|
162
|
+
const payload = this.buildPayload(entityType, "deleted", id, {}, userId, tenantId, workspaceId);
|
|
163
|
+
await this.publish(this.buildSubject(entityType, "deleted"), payload);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Publish custom action event
|
|
167
|
+
*/
|
|
168
|
+
async publishCustom(entityType, action, id, data, userId, tenantId, workspaceId) {
|
|
169
|
+
const payload = this.buildPayload(entityType, action, id, data, userId, tenantId, workspaceId);
|
|
170
|
+
await this.publish(this.buildSubject(entityType, action), payload);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Publish bulk created event
|
|
174
|
+
*/
|
|
175
|
+
async publishBulkCreated(_entityType, items, userId, tenantId, workspaceId) {
|
|
176
|
+
const payload = {
|
|
177
|
+
items,
|
|
178
|
+
metadata: {
|
|
179
|
+
tenantId,
|
|
180
|
+
workspaceId,
|
|
181
|
+
userId,
|
|
182
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
183
|
+
productSource: this.productSource
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
await this.publish(`${this.subjectPrefix}.bulk.created`, payload);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Close event queue connection
|
|
190
|
+
*/
|
|
191
|
+
async close() {
|
|
192
|
+
if (this.connected) {
|
|
193
|
+
await this.publisher.disconnect();
|
|
194
|
+
this.connected = false;
|
|
195
|
+
logger.info(`[${this.loggerLabel}] Publisher disconnected`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Get health check status
|
|
200
|
+
*/
|
|
201
|
+
async healthCheck() {
|
|
202
|
+
const result = await this.publisher.healthCheck();
|
|
203
|
+
const isHealthy = result.status === "healthy";
|
|
204
|
+
return {
|
|
205
|
+
healthy: isHealthy,
|
|
206
|
+
message: result.error || (isHealthy ? "Healthy" : "Unhealthy")
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
function createModuleEventsService(config) {
|
|
211
|
+
return new ModuleEventsService(config);
|
|
212
|
+
}
|
|
213
|
+
__name(createModuleEventsService, "createModuleEventsService");
|
|
214
|
+
|
|
215
|
+
// src/event-queue/events.ts
|
|
216
|
+
var EventPriority = /* @__PURE__ */ (function(EventPriority2) {
|
|
217
|
+
EventPriority2["LOW"] = "low";
|
|
218
|
+
EventPriority2["NORMAL"] = "normal";
|
|
219
|
+
EventPriority2["HIGH"] = "high";
|
|
220
|
+
EventPriority2["CRITICAL"] = "critical";
|
|
221
|
+
return EventPriority2;
|
|
222
|
+
})({});
|
|
223
|
+
var EventsModule = class {
|
|
224
|
+
static {
|
|
225
|
+
__name(this, "EventsModule");
|
|
226
|
+
}
|
|
227
|
+
client;
|
|
228
|
+
context;
|
|
229
|
+
constructor(client, context) {
|
|
230
|
+
this.client = client;
|
|
231
|
+
this.context = context;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Create stream
|
|
235
|
+
*/
|
|
236
|
+
async createStream(name, subjects, options) {
|
|
237
|
+
logger.debug("[Events] Creating stream", {
|
|
238
|
+
name,
|
|
239
|
+
subjects
|
|
240
|
+
});
|
|
241
|
+
const mutation = `
|
|
242
|
+
mutation CreateStream($input: CreateStreamInput!) {
|
|
243
|
+
createStream(input: $input) {
|
|
244
|
+
name
|
|
245
|
+
subjects
|
|
246
|
+
messageCount
|
|
247
|
+
byteCount
|
|
248
|
+
firstSequence
|
|
249
|
+
lastSequence
|
|
250
|
+
consumerCount
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
`;
|
|
254
|
+
const variables = {
|
|
255
|
+
input: {
|
|
256
|
+
name,
|
|
257
|
+
subjects,
|
|
258
|
+
maxMessages: options?.maxMessages,
|
|
259
|
+
maxBytes: options?.maxBytes,
|
|
260
|
+
maxAge: options?.maxAge,
|
|
261
|
+
storageType: options?.storageType || "file",
|
|
262
|
+
replicas: options?.replicas || 1
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const response = await this.client.query(mutation, variables, this.context);
|
|
266
|
+
logger.info("[Events] Stream created", {
|
|
267
|
+
name
|
|
268
|
+
});
|
|
269
|
+
return response.createStream;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Get stream info
|
|
273
|
+
*/
|
|
274
|
+
async getStreamInfo(name) {
|
|
275
|
+
logger.debug("[Events] Getting stream info", {
|
|
276
|
+
name
|
|
277
|
+
});
|
|
278
|
+
const query = `
|
|
279
|
+
query GetStreamInfo($name: String!) {
|
|
280
|
+
getStreamInfo(name: $name) {
|
|
281
|
+
name
|
|
282
|
+
subjects
|
|
283
|
+
messageCount
|
|
284
|
+
byteCount
|
|
285
|
+
firstSequence
|
|
286
|
+
lastSequence
|
|
287
|
+
consumerCount
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
`;
|
|
291
|
+
const response = await this.client.query(query, {
|
|
292
|
+
name
|
|
293
|
+
}, this.context);
|
|
294
|
+
return response.getStreamInfo;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Delete stream
|
|
298
|
+
*/
|
|
299
|
+
async deleteStream(name) {
|
|
300
|
+
logger.debug("[Events] Deleting stream", {
|
|
301
|
+
name
|
|
302
|
+
});
|
|
303
|
+
const mutation = `
|
|
304
|
+
mutation DeleteStream($name: String!) {
|
|
305
|
+
deleteStream(name: $name) {
|
|
306
|
+
success
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
`;
|
|
310
|
+
await this.client.query(mutation, {
|
|
311
|
+
name
|
|
312
|
+
}, this.context);
|
|
313
|
+
logger.info("[Events] Stream deleted", {
|
|
314
|
+
name
|
|
315
|
+
});
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Purge stream messages
|
|
320
|
+
*/
|
|
321
|
+
async purgeStream(name, options) {
|
|
322
|
+
logger.debug("[Events] Purging stream", {
|
|
323
|
+
name,
|
|
324
|
+
options
|
|
325
|
+
});
|
|
326
|
+
const mutation = `
|
|
327
|
+
mutation PurgeStream($name: String!, $subject: String, $sequence: Int) {
|
|
328
|
+
purgeStream(name: $name, subject: $subject, sequence: $sequence) {
|
|
329
|
+
purgedCount
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
`;
|
|
333
|
+
const response = await this.client.query(mutation, {
|
|
334
|
+
name,
|
|
335
|
+
subject: options?.subject,
|
|
336
|
+
sequence: options?.sequence
|
|
337
|
+
}, this.context);
|
|
338
|
+
logger.info("[Events] Stream purged", {
|
|
339
|
+
name,
|
|
340
|
+
purgedCount: response.purgeStream.purgedCount
|
|
341
|
+
});
|
|
342
|
+
return response.purgeStream.purgedCount;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Create consumer
|
|
346
|
+
*/
|
|
347
|
+
async createConsumer(streamName, consumerName, options) {
|
|
348
|
+
logger.debug("[Events] Creating consumer", {
|
|
349
|
+
streamName,
|
|
350
|
+
consumerName
|
|
351
|
+
});
|
|
352
|
+
const mutation = `
|
|
353
|
+
mutation CreateConsumer($input: CreateConsumerInput!) {
|
|
354
|
+
createConsumer(input: $input) {
|
|
355
|
+
name
|
|
356
|
+
pending
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
`;
|
|
360
|
+
const variables = {
|
|
361
|
+
input: {
|
|
362
|
+
streamName,
|
|
363
|
+
consumerName,
|
|
364
|
+
subject: options.subject,
|
|
365
|
+
queueGroup: options.queueGroup,
|
|
366
|
+
durableName: options.durableName,
|
|
367
|
+
startPosition: options.startPosition || "last",
|
|
368
|
+
ackMode: options.ackMode || "explicit",
|
|
369
|
+
maxDeliver: options.maxDeliver || 5,
|
|
370
|
+
ackWait: options.ackWait || 3e4
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
const response = await this.client.query(mutation, variables, this.context);
|
|
374
|
+
logger.info("[Events] Consumer created", {
|
|
375
|
+
consumerName
|
|
376
|
+
});
|
|
377
|
+
return response.createConsumer;
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Delete consumer
|
|
381
|
+
*/
|
|
382
|
+
async deleteConsumer(streamName, consumerName) {
|
|
383
|
+
logger.debug("[Events] Deleting consumer", {
|
|
384
|
+
streamName,
|
|
385
|
+
consumerName
|
|
386
|
+
});
|
|
387
|
+
const mutation = `
|
|
388
|
+
mutation DeleteConsumer($streamName: String!, $consumerName: String!) {
|
|
389
|
+
deleteConsumer(streamName: $streamName, consumerName: $consumerName) {
|
|
390
|
+
success
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
`;
|
|
394
|
+
await this.client.query(mutation, {
|
|
395
|
+
streamName,
|
|
396
|
+
consumerName
|
|
397
|
+
}, this.context);
|
|
398
|
+
logger.info("[Events] Consumer deleted", {
|
|
399
|
+
consumerName
|
|
400
|
+
});
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Acknowledge message
|
|
405
|
+
*/
|
|
406
|
+
async ackMessage(streamName, consumerName, sequence) {
|
|
407
|
+
logger.debug("[Events] Acknowledging message", {
|
|
408
|
+
streamName,
|
|
409
|
+
consumerName,
|
|
410
|
+
sequence
|
|
411
|
+
});
|
|
412
|
+
const mutation = `
|
|
413
|
+
mutation AckMessage($streamName: String!, $consumerName: String!, $sequence: Int!) {
|
|
414
|
+
ackMessage(streamName: $streamName, consumerName: $consumerName, sequence: $sequence) {
|
|
415
|
+
success
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
`;
|
|
419
|
+
await this.client.query(mutation, {
|
|
420
|
+
streamName,
|
|
421
|
+
consumerName,
|
|
422
|
+
sequence
|
|
423
|
+
}, this.context);
|
|
424
|
+
return true;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Negative acknowledge message (requeue)
|
|
428
|
+
*/
|
|
429
|
+
async nakMessage(streamName, consumerName, sequence) {
|
|
430
|
+
logger.debug("[Events] Negative acknowledging message", {
|
|
431
|
+
streamName,
|
|
432
|
+
consumerName,
|
|
433
|
+
sequence
|
|
434
|
+
});
|
|
435
|
+
const mutation = `
|
|
436
|
+
mutation NakMessage($streamName: String!, $consumerName: String!, $sequence: Int!) {
|
|
437
|
+
nakMessage(streamName: $streamName, consumerName: $consumerName, sequence: $sequence) {
|
|
438
|
+
success
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
`;
|
|
442
|
+
await this.client.query(mutation, {
|
|
443
|
+
streamName,
|
|
444
|
+
consumerName,
|
|
445
|
+
sequence
|
|
446
|
+
}, this.context);
|
|
447
|
+
return true;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Get consumer info
|
|
451
|
+
*/
|
|
452
|
+
async getConsumerInfo(streamName, consumerName) {
|
|
453
|
+
logger.debug("[Events] Getting consumer info", {
|
|
454
|
+
streamName,
|
|
455
|
+
consumerName
|
|
456
|
+
});
|
|
457
|
+
const query = `
|
|
458
|
+
query GetConsumerInfo($streamName: String!, $consumerName: String!) {
|
|
459
|
+
getConsumerInfo(streamName: $streamName, consumerName: $consumerName) {
|
|
460
|
+
name
|
|
461
|
+
pending
|
|
462
|
+
redelivered
|
|
463
|
+
numAckPending
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
`;
|
|
467
|
+
const response = await this.client.query(query, {
|
|
468
|
+
streamName,
|
|
469
|
+
consumerName
|
|
470
|
+
}, this.context);
|
|
471
|
+
return response.getConsumerInfo;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// src/event-queue/factories.ts
|
|
476
|
+
function createPublisher() {
|
|
477
|
+
if (resolveEventStreamsUrl()) {
|
|
478
|
+
return EventQueueFactory.createPublisherFromEnv();
|
|
479
|
+
}
|
|
480
|
+
return new MemoryEventPublisher();
|
|
481
|
+
}
|
|
482
|
+
__name(createPublisher, "createPublisher");
|
|
483
|
+
function createConsumer(stream, consumer) {
|
|
484
|
+
if (resolveEventStreamsUrl()) {
|
|
485
|
+
return EventQueueFactory.createConsumerFromEnv(stream, consumer);
|
|
486
|
+
}
|
|
487
|
+
return new MemoryEventConsumer(stream, consumer);
|
|
488
|
+
}
|
|
489
|
+
__name(createConsumer, "createConsumer");
|
|
490
|
+
var EVENT_TAXONOMY_BRAND = /* @__PURE__ */ Symbol.for("@burdenoff/be-sdk/event-taxonomy");
|
|
491
|
+
function eventSpec(spec) {
|
|
492
|
+
return spec;
|
|
493
|
+
}
|
|
494
|
+
__name(eventSpec, "eventSpec");
|
|
495
|
+
var SEGMENT = "[a-z][a-z0-9_]*";
|
|
496
|
+
var DOMAIN_SEGMENT = "[a-z][a-z0-9_-]*";
|
|
497
|
+
var FACT_OR_COMMAND_NAME = new RegExp(`^${DOMAIN_SEGMENT}(\\.${SEGMENT}){1,3}$`);
|
|
498
|
+
var GRAPH_NAME = /^graph\.[a-z][a-z0-9-]*\.[A-Za-z]\w*\.(created|updated|deleted)$/;
|
|
499
|
+
var SERVICE_NAME = /^[a-z][a-z0-9-]*[a-z0-9]$/;
|
|
500
|
+
function taxonomyNameViolation(name, kind) {
|
|
501
|
+
if (kind === "graph") {
|
|
502
|
+
return GRAPH_NAME.test(name) ? null : "graph events are graph.<module>.<Entity>.<created|updated|deleted>";
|
|
503
|
+
}
|
|
504
|
+
if (name.startsWith("graph.")) return "the graph. prefix is reserved for graph events (kind: graph)";
|
|
505
|
+
if (!FACT_OR_COMMAND_NAME.test(name)) {
|
|
506
|
+
return "names are {domain}.{entity}.{action}: 2-4 lower-case dot-separated segments";
|
|
507
|
+
}
|
|
508
|
+
return null;
|
|
509
|
+
}
|
|
510
|
+
__name(taxonomyNameViolation, "taxonomyNameViolation");
|
|
511
|
+
function defineEventTaxonomy(registry) {
|
|
512
|
+
for (const [name, spec] of Object.entries(registry)) {
|
|
513
|
+
const violation = taxonomyNameViolation(name, spec.kind);
|
|
514
|
+
if (violation) throw new Error(`[EventTaxonomy] Invalid event name "${name}": ${violation}`);
|
|
515
|
+
if (!SERVICE_NAME.test(spec.producer)) {
|
|
516
|
+
throw new Error(`[EventTaxonomy] Event "${name}" has an invalid producer "${spec.producer}"`);
|
|
517
|
+
}
|
|
518
|
+
if (!spec.description.trim()) throw new Error(`[EventTaxonomy] Event "${name}" needs a description`);
|
|
519
|
+
if (spec.stream !== void 0 && !/^[A-Za-z0-9_.:-]+$/.test(spec.stream)) {
|
|
520
|
+
throw new Error(`[EventTaxonomy] Event "${name}" has an invalid stream "${spec.stream}"`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const copy = {
|
|
524
|
+
...registry
|
|
525
|
+
};
|
|
526
|
+
Object.defineProperty(copy, EVENT_TAXONOMY_BRAND, {
|
|
527
|
+
value: true,
|
|
528
|
+
enumerable: false
|
|
529
|
+
});
|
|
530
|
+
return Object.freeze(copy);
|
|
531
|
+
}
|
|
532
|
+
__name(defineEventTaxonomy, "defineEventTaxonomy");
|
|
533
|
+
function isDefinedEventTaxonomy(registry) {
|
|
534
|
+
return typeof registry === "object" && registry !== null && registry[EVENT_TAXONOMY_BRAND] === true;
|
|
535
|
+
}
|
|
536
|
+
__name(isDefinedEventTaxonomy, "isDefinedEventTaxonomy");
|
|
537
|
+
function taxonomyEventNames(registry) {
|
|
538
|
+
return Object.keys(registry).sort((x, y) => x.localeCompare(y));
|
|
539
|
+
}
|
|
540
|
+
__name(taxonomyEventNames, "taxonomyEventNames");
|
|
541
|
+
function mergeEventTaxonomies(a, b) {
|
|
542
|
+
for (const name of Object.keys(b)) {
|
|
543
|
+
if (name in a && a[name] !== b[name]) {
|
|
544
|
+
throw new Error(`[EventTaxonomy] Event "${name}" is defined in both registries`);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return defineEventTaxonomy({
|
|
548
|
+
...a,
|
|
549
|
+
...b
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
__name(mergeEventTaxonomies, "mergeEventTaxonomies");
|
|
553
|
+
async function publishTaxonomyEvent(publisher, registry, name, payload, metadata, options = {}) {
|
|
554
|
+
const spec = registry[name];
|
|
555
|
+
if (!spec) throw new Error(`[EventTaxonomy] Event "${name}" is not registered`);
|
|
556
|
+
if (spec.kind === "graph") {
|
|
557
|
+
throw new Error(`[EventTaxonomy] "${name}" is a graph event; publish it through the module graph emitter`);
|
|
558
|
+
}
|
|
559
|
+
if (!metadata.source.trim()) throw new Error(`[EventTaxonomy] Event "${name}" needs metadata.source`);
|
|
560
|
+
return publisher.publish({
|
|
561
|
+
subject: name,
|
|
562
|
+
data: payload,
|
|
563
|
+
metadata: {
|
|
564
|
+
...metadata,
|
|
565
|
+
correlationId: metadata.correlationId ?? randomUUID()
|
|
566
|
+
},
|
|
567
|
+
options: spec.stream ? {
|
|
568
|
+
...options,
|
|
569
|
+
stream: spec.stream
|
|
570
|
+
} : options
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
__name(publishTaxonomyEvent, "publishTaxonomyEvent");
|
|
574
|
+
var WSPACE_GRAPH_EVENTS_STREAM = "WSPACE_GRAPH_EVENTS";
|
|
575
|
+
var PLATFORM_EVENT_TAXONOMY = defineEventTaxonomy({
|
|
576
|
+
"workspace.created": eventSpec({
|
|
577
|
+
kind: "fact",
|
|
578
|
+
layer: "wspace",
|
|
579
|
+
producer: "wspace-workspace-svc",
|
|
580
|
+
status: "published",
|
|
581
|
+
pii: "names",
|
|
582
|
+
description: "A workspace was created (also re-published when synced from the global layer)."
|
|
583
|
+
}),
|
|
584
|
+
"workspace.initialized": eventSpec({
|
|
585
|
+
kind: "fact",
|
|
586
|
+
layer: "wspace",
|
|
587
|
+
producer: "wspace-workspace-svc",
|
|
588
|
+
status: "published",
|
|
589
|
+
pii: "names",
|
|
590
|
+
description: "A new workspace finished provisioning its default resources."
|
|
591
|
+
}),
|
|
592
|
+
"workspace.member.added": eventSpec({
|
|
593
|
+
kind: "fact",
|
|
594
|
+
layer: "wspace",
|
|
595
|
+
producer: "wspace-workspace-svc",
|
|
596
|
+
status: "published",
|
|
597
|
+
description: "A user became a member of a workspace."
|
|
598
|
+
}),
|
|
599
|
+
"workspace.member.removed": eventSpec({
|
|
600
|
+
kind: "fact",
|
|
601
|
+
layer: "wspace",
|
|
602
|
+
producer: "wspace-workspace-svc",
|
|
603
|
+
status: "published",
|
|
604
|
+
description: "A user was removed from a workspace. Revoke what the user held in that workspace."
|
|
605
|
+
}),
|
|
606
|
+
"workspace.member.role_updated": eventSpec({
|
|
607
|
+
kind: "fact",
|
|
608
|
+
layer: "wspace",
|
|
609
|
+
producer: "wspace-workspace-svc",
|
|
610
|
+
status: "published",
|
|
611
|
+
description: "A member's workspace roles changed."
|
|
612
|
+
}),
|
|
613
|
+
"workspace.deleted": eventSpec({
|
|
614
|
+
kind: "fact",
|
|
615
|
+
layer: "wspace",
|
|
616
|
+
producer: "wspace-workspace-svc",
|
|
617
|
+
status: "planned",
|
|
618
|
+
description: "Reserved. Deletion is published today only as graph.module-workspace.Workspace.deleted; the lifecycle consumer reads both."
|
|
619
|
+
}),
|
|
620
|
+
"graph.module-workspace.Workspace.deleted": eventSpec({
|
|
621
|
+
kind: "graph",
|
|
622
|
+
layer: "wspace",
|
|
623
|
+
producer: "wspace-workspace-svc",
|
|
624
|
+
status: "published",
|
|
625
|
+
stream: WSPACE_GRAPH_EVENTS_STREAM,
|
|
626
|
+
description: "Graph event for a soft-deleted workspace (status DELETED, deletedAt set)."
|
|
627
|
+
}),
|
|
628
|
+
"organization.deleted": eventSpec({
|
|
629
|
+
kind: "fact",
|
|
630
|
+
layer: "global",
|
|
631
|
+
producer: "global-tenant-svc",
|
|
632
|
+
status: "published",
|
|
633
|
+
description: "An organization was deleted. Global-layer stream: wspace services cannot read it."
|
|
634
|
+
}),
|
|
635
|
+
"user.deleted": eventSpec({
|
|
636
|
+
kind: "fact",
|
|
637
|
+
layer: "global",
|
|
638
|
+
producer: "global-auth-svc",
|
|
639
|
+
status: "planned",
|
|
640
|
+
description: "Reserved. No producer yet: products must check user state lazily at read time."
|
|
641
|
+
}),
|
|
642
|
+
"subscription.created": eventSpec({
|
|
643
|
+
kind: "fact",
|
|
644
|
+
layer: "global",
|
|
645
|
+
producer: "global-billing-svc",
|
|
646
|
+
status: "planned",
|
|
647
|
+
description: "Reserved. No producer yet: entitlement is checked lazily at quota/usage time."
|
|
648
|
+
}),
|
|
649
|
+
"subscription.updated": eventSpec({
|
|
650
|
+
kind: "fact",
|
|
651
|
+
layer: "global",
|
|
652
|
+
producer: "global-billing-svc",
|
|
653
|
+
status: "planned",
|
|
654
|
+
description: "Reserved. No producer yet: entitlement is checked lazily at quota/usage time."
|
|
655
|
+
}),
|
|
656
|
+
"subscription.cancelled": eventSpec({
|
|
657
|
+
kind: "fact",
|
|
658
|
+
layer: "global",
|
|
659
|
+
producer: "global-billing-svc",
|
|
660
|
+
status: "planned",
|
|
661
|
+
description: "Reserved. No producer yet: entitlement is checked lazily at quota/usage time."
|
|
662
|
+
})
|
|
663
|
+
});
|
|
664
|
+
var REFERENCE_PRODUCT_EVENT_TAXONOMY = defineEventTaxonomy({
|
|
665
|
+
"vibecontrols.agent.connected": eventSpec({
|
|
666
|
+
kind: "fact",
|
|
667
|
+
layer: "wspace",
|
|
668
|
+
producer: "wspace-vibecontrols-svc",
|
|
669
|
+
status: "planned",
|
|
670
|
+
description: "An agent opened its control channel to VibeControls."
|
|
671
|
+
}),
|
|
672
|
+
"vibecontrols.agent.disconnected": eventSpec({
|
|
673
|
+
kind: "fact",
|
|
674
|
+
layer: "wspace",
|
|
675
|
+
producer: "wspace-vibecontrols-svc",
|
|
676
|
+
status: "planned",
|
|
677
|
+
description: "An agent control channel closed or timed out."
|
|
678
|
+
}),
|
|
679
|
+
"vibecontrols.session.started": eventSpec({
|
|
680
|
+
kind: "fact",
|
|
681
|
+
layer: "wspace",
|
|
682
|
+
producer: "wspace-vibecontrols-svc",
|
|
683
|
+
status: "planned",
|
|
684
|
+
description: "A VibeControls session started on an agent."
|
|
685
|
+
}),
|
|
686
|
+
"vibecontrols.session.ended": eventSpec({
|
|
687
|
+
kind: "fact",
|
|
688
|
+
layer: "wspace",
|
|
689
|
+
producer: "wspace-vibecontrols-svc",
|
|
690
|
+
status: "planned",
|
|
691
|
+
description: "A VibeControls session ended."
|
|
692
|
+
}),
|
|
693
|
+
"workflow.run.started": eventSpec({
|
|
694
|
+
kind: "fact",
|
|
695
|
+
layer: "wspace",
|
|
696
|
+
producer: "wspace-workflow-svc",
|
|
697
|
+
status: "planned",
|
|
698
|
+
description: "A FluidGrids workflow run started (fact; the internal run.run.status stays as is)."
|
|
699
|
+
}),
|
|
700
|
+
"workflow.run.completed": eventSpec({
|
|
701
|
+
kind: "fact",
|
|
702
|
+
layer: "wspace",
|
|
703
|
+
producer: "wspace-workflow-svc",
|
|
704
|
+
status: "planned",
|
|
705
|
+
description: "A FluidGrids workflow run completed successfully."
|
|
706
|
+
}),
|
|
707
|
+
"workflow.run.failed": eventSpec({
|
|
708
|
+
kind: "fact",
|
|
709
|
+
layer: "wspace",
|
|
710
|
+
producer: "wspace-workflow-svc",
|
|
711
|
+
status: "planned",
|
|
712
|
+
description: "A FluidGrids workflow run failed."
|
|
713
|
+
})
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
// src/event-queue/events-manager.ts
|
|
717
|
+
var SERVICE_NAME2 = /^[a-z][a-z0-9-]*[a-z0-9]$/;
|
|
718
|
+
function errorMessage(error) {
|
|
719
|
+
return error instanceof Error ? error.message : String(error);
|
|
720
|
+
}
|
|
721
|
+
__name(errorMessage, "errorMessage");
|
|
722
|
+
function encodePayload(payload) {
|
|
723
|
+
return new TextEncoder().encode(JSON.stringify(payload ?? null));
|
|
724
|
+
}
|
|
725
|
+
__name(encodePayload, "encodePayload");
|
|
726
|
+
function toMessage(event) {
|
|
727
|
+
return {
|
|
728
|
+
subject: event.subject,
|
|
729
|
+
data: encodePayload(event.data),
|
|
730
|
+
payload: event.data,
|
|
731
|
+
event,
|
|
732
|
+
ack() {
|
|
733
|
+
event.ack().catch((err) => logger.warn("[Events] ack failed", {
|
|
734
|
+
error: errorMessage(err)
|
|
735
|
+
}));
|
|
736
|
+
},
|
|
737
|
+
nak(delay) {
|
|
738
|
+
event.nak(delay).catch((err) => logger.warn("[Events] nak failed", {
|
|
739
|
+
error: errorMessage(err)
|
|
740
|
+
}));
|
|
741
|
+
},
|
|
742
|
+
term() {
|
|
743
|
+
event.term().catch((err) => logger.warn("[Events] term failed", {
|
|
744
|
+
error: errorMessage(err)
|
|
745
|
+
}));
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
__name(toMessage, "toMessage");
|
|
750
|
+
var EventsManager = class {
|
|
751
|
+
static {
|
|
752
|
+
__name(this, "EventsManager");
|
|
753
|
+
}
|
|
754
|
+
publisher = null;
|
|
755
|
+
publisherConnecting = null;
|
|
756
|
+
consumers = /* @__PURE__ */ new Map();
|
|
757
|
+
active = /* @__PURE__ */ new Map();
|
|
758
|
+
serviceName;
|
|
759
|
+
routes;
|
|
760
|
+
defaultStream;
|
|
761
|
+
maxDeliver;
|
|
762
|
+
strict;
|
|
763
|
+
requireRedisUrl;
|
|
764
|
+
publisherFactory;
|
|
765
|
+
consumerFactory;
|
|
766
|
+
constructor(options) {
|
|
767
|
+
if (!SERVICE_NAME2.test(options.serviceName)) {
|
|
768
|
+
throw new Error(`[Events] serviceName "${options.serviceName}" must be a kebab-case service name`);
|
|
769
|
+
}
|
|
770
|
+
const maxDeliver = options.maxDeliver ?? 5;
|
|
771
|
+
if (!Number.isInteger(maxDeliver) || maxDeliver < 1) {
|
|
772
|
+
throw new Error("[Events] maxDeliver must be a positive integer");
|
|
773
|
+
}
|
|
774
|
+
this.serviceName = options.serviceName;
|
|
775
|
+
this.routes = [
|
|
776
|
+
...options.streamRoutes ?? []
|
|
777
|
+
];
|
|
778
|
+
this.defaultStream = options.defaultStream;
|
|
779
|
+
this.maxDeliver = maxDeliver;
|
|
780
|
+
this.strict = options.strictSubjectFilter ?? true;
|
|
781
|
+
this.requireRedisUrl = options.requireRedisUrl ?? false;
|
|
782
|
+
this.publisherFactory = options.publisherFactory ?? createPublisher;
|
|
783
|
+
this.consumerFactory = options.consumerFactory ?? createConsumer;
|
|
784
|
+
}
|
|
785
|
+
/** Create and connect the shared publisher. Idempotent and safe to call concurrently. */
|
|
786
|
+
async connect() {
|
|
787
|
+
if (this.publisher?.isConnected()) return;
|
|
788
|
+
this.publisherConnecting ??= this.connectPublisher().finally(() => {
|
|
789
|
+
this.publisherConnecting = null;
|
|
790
|
+
});
|
|
791
|
+
await this.publisherConnecting;
|
|
792
|
+
}
|
|
793
|
+
assertBusConfigured() {
|
|
794
|
+
if (this.requireRedisUrl && !resolveEventStreamsUrl()) {
|
|
795
|
+
throw new Error(`[Events] ${this.serviceName}: neither REDIS_STREAMS_URL nor REDIS_URL is set, so events would go to an in-process bus. Point it at the same Valkey (and DB index) as the services it talks to.`);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
async connectPublisher() {
|
|
799
|
+
this.assertBusConfigured();
|
|
800
|
+
const publisher = this.publisher ?? this.publisherFactory();
|
|
801
|
+
await publisher.connect();
|
|
802
|
+
this.publisher = publisher;
|
|
803
|
+
const url = resolveEventStreamsUrl();
|
|
804
|
+
logger.info("[Events] Publisher connected", {
|
|
805
|
+
service: this.serviceName,
|
|
806
|
+
urlSource: resolveEventStreamsUrlSource() ?? "in-memory",
|
|
807
|
+
keyScope: eventKeyScopeForUrl(url) || "(none)"
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Publish a JSON-serialisable payload. The stream comes from the routes,
|
|
812
|
+
* else `defaultStream`, else the per-subject stream.
|
|
813
|
+
*/
|
|
814
|
+
async publish(subject, payload, metadata) {
|
|
815
|
+
await this.connect();
|
|
816
|
+
const publisher = this.publisher;
|
|
817
|
+
if (!publisher) throw new Error("[Events] publisher not initialized");
|
|
818
|
+
const stream = this.resolveStream(subject);
|
|
819
|
+
try {
|
|
820
|
+
await publisher.publish({
|
|
821
|
+
subject,
|
|
822
|
+
data: payload,
|
|
823
|
+
metadata: {
|
|
824
|
+
source: this.serviceName,
|
|
825
|
+
...metadata
|
|
826
|
+
},
|
|
827
|
+
...stream ? {
|
|
828
|
+
options: {
|
|
829
|
+
stream
|
|
830
|
+
}
|
|
831
|
+
} : {}
|
|
832
|
+
});
|
|
833
|
+
} catch (error) {
|
|
834
|
+
logger.error(`[Events] Failed to publish to ${subject}`, {
|
|
835
|
+
error: errorMessage(error)
|
|
836
|
+
});
|
|
837
|
+
throw error;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Subscribe with a durable consumer group. `consumerName` IS the Redis
|
|
842
|
+
* consumer-group name: replicas sharing it split the work (queue
|
|
843
|
+
* semantics); services that each need every entry must use distinct names.
|
|
844
|
+
* Omitted, it is derived as `<serviceName>-<subject>`.
|
|
845
|
+
*
|
|
846
|
+
* A throwing handler naks the entry; it is redelivered until `maxDeliver`,
|
|
847
|
+
* then dead-lettered. Returns an unsubscribe handle.
|
|
848
|
+
*/
|
|
849
|
+
async subscribe(subject, handler, consumerName, options = {}) {
|
|
850
|
+
this.assertBusConfigured();
|
|
851
|
+
const stream = options.stream ?? this.resolveStream(subject);
|
|
852
|
+
const group = consumerName ?? this.consumerNameFor(subject);
|
|
853
|
+
const streamLabel = stream ?? `subject:${subject}`;
|
|
854
|
+
const key = `${streamLabel}|${group}`;
|
|
855
|
+
if (this.active.has(key)) {
|
|
856
|
+
throw new Error(`[Events] ${group} already has a subscription on ${streamLabel}; a second one would split its entries. Use a distinct consumer name per subscription.`);
|
|
857
|
+
}
|
|
858
|
+
let consumer = this.consumers.get(group);
|
|
859
|
+
if (!consumer) {
|
|
860
|
+
consumer = this.consumerFactory(stream ?? subject, group);
|
|
861
|
+
await consumer.connect();
|
|
862
|
+
this.consumers.set(group, consumer);
|
|
863
|
+
}
|
|
864
|
+
const strict = this.strict;
|
|
865
|
+
const subscription = await consumer.subscribe({
|
|
866
|
+
subject,
|
|
867
|
+
handler: /* @__PURE__ */ __name(async (event) => {
|
|
868
|
+
if (strict && !matchSubject(subject, event.subject)) {
|
|
869
|
+
await event.ack();
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
try {
|
|
873
|
+
await handler(toMessage(event));
|
|
874
|
+
} catch (error) {
|
|
875
|
+
logger.error("[Events] Handler error", {
|
|
876
|
+
subject: event.subject,
|
|
877
|
+
error: errorMessage(error)
|
|
878
|
+
});
|
|
879
|
+
await event.nak();
|
|
880
|
+
}
|
|
881
|
+
}, "handler"),
|
|
882
|
+
options: {
|
|
883
|
+
consumer: group,
|
|
884
|
+
...stream ? {
|
|
885
|
+
stream
|
|
886
|
+
} : {},
|
|
887
|
+
maxDeliver: options.maxDeliver ?? this.maxDeliver,
|
|
888
|
+
ackPolicy: "explicit",
|
|
889
|
+
deliverPolicy: options.deliverPolicy ?? "new"
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
this.active.set(key, subscription);
|
|
893
|
+
logger.info("[Events] Subscribed", {
|
|
894
|
+
subject,
|
|
895
|
+
stream: streamLabel,
|
|
896
|
+
group
|
|
897
|
+
});
|
|
898
|
+
return async () => {
|
|
899
|
+
if (this.active.get(key) !== subscription) return;
|
|
900
|
+
this.active.delete(key);
|
|
901
|
+
try {
|
|
902
|
+
await subscription.unsubscribe();
|
|
903
|
+
} catch (error) {
|
|
904
|
+
logger.warn("[Events] unsubscribe failed", {
|
|
905
|
+
subject,
|
|
906
|
+
error: errorMessage(error)
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
/** Close every subscription, consumer and the publisher. */
|
|
912
|
+
async close() {
|
|
913
|
+
for (const subscription of this.active.values()) {
|
|
914
|
+
try {
|
|
915
|
+
await subscription.unsubscribe();
|
|
916
|
+
} catch (error) {
|
|
917
|
+
logger.warn("[Events] unsubscribe failed", {
|
|
918
|
+
error: errorMessage(error)
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
this.active.clear();
|
|
923
|
+
for (const consumer of this.consumers.values()) {
|
|
924
|
+
try {
|
|
925
|
+
await consumer.disconnect();
|
|
926
|
+
} catch (error) {
|
|
927
|
+
logger.warn("[Events] consumer disconnect failed", {
|
|
928
|
+
error: errorMessage(error)
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
this.consumers.clear();
|
|
933
|
+
if (this.publisherConnecting) {
|
|
934
|
+
await this.publisherConnecting.catch(() => void 0);
|
|
935
|
+
}
|
|
936
|
+
if (this.publisher) {
|
|
937
|
+
try {
|
|
938
|
+
await this.publisher.disconnect();
|
|
939
|
+
} catch (error) {
|
|
940
|
+
logger.warn("[Events] publisher disconnect failed", {
|
|
941
|
+
error: errorMessage(error)
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
this.publisher = null;
|
|
945
|
+
}
|
|
946
|
+
logger.info("[Events] Connections closed", {
|
|
947
|
+
service: this.serviceName
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
/** Publisher connection state only; consumers connect on their own. */
|
|
951
|
+
isConnected() {
|
|
952
|
+
return this.publisher?.isConnected() ?? false;
|
|
953
|
+
}
|
|
954
|
+
/** Number of active subscriptions (diagnostics). */
|
|
955
|
+
getSubscriptionCount() {
|
|
956
|
+
return this.active.size;
|
|
957
|
+
}
|
|
958
|
+
/** The aggregated stream for `subject`, or `undefined` for the per-subject stream. */
|
|
959
|
+
resolveStream(subject) {
|
|
960
|
+
for (const route of this.routes) {
|
|
961
|
+
if (matchSubject(route.subject, subject)) return route.stream;
|
|
962
|
+
}
|
|
963
|
+
return this.defaultStream;
|
|
964
|
+
}
|
|
965
|
+
/** Derived consumer-group name for `subject`. */
|
|
966
|
+
consumerNameFor(subject) {
|
|
967
|
+
return `${this.serviceName}-${subject.replace(/[^a-zA-Z0-9]+/g, "-").replace(/-$/, "")}`;
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
function createEventsManagerSingleton(options) {
|
|
971
|
+
let instance = null;
|
|
972
|
+
return {
|
|
973
|
+
get() {
|
|
974
|
+
instance ??= (async () => {
|
|
975
|
+
const manager = new EventsManager(options);
|
|
976
|
+
await manager.connect();
|
|
977
|
+
return manager;
|
|
978
|
+
})().catch((error) => {
|
|
979
|
+
instance = null;
|
|
980
|
+
throw error;
|
|
981
|
+
});
|
|
982
|
+
return instance;
|
|
983
|
+
},
|
|
984
|
+
async close() {
|
|
985
|
+
const pending = instance;
|
|
986
|
+
instance = null;
|
|
987
|
+
if (!pending) return;
|
|
988
|
+
const manager = await pending.catch(() => null);
|
|
989
|
+
await manager?.close();
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
__name(createEventsManagerSingleton, "createEventsManagerSingleton");
|
|
994
|
+
|
|
995
|
+
// src/event-queue/lifecycle-consumer.ts
|
|
996
|
+
var LIFECYCLE_SUBJECTS = {
|
|
997
|
+
workspaceDeleted: "workspace.deleted",
|
|
998
|
+
workspaceDeletedGraph: "graph.module-workspace.Workspace.deleted",
|
|
999
|
+
workspaceMemberRemoved: "workspace.member.removed",
|
|
1000
|
+
organizationDeleted: "organization.deleted"
|
|
1001
|
+
};
|
|
1002
|
+
var SERVICE_NAME3 = /^[a-z][a-z0-9-]*[a-z0-9]$/;
|
|
1003
|
+
var PURPOSE = /^[a-z][a-z0-9-]*$/;
|
|
1004
|
+
var ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
1005
|
+
var RESERVED_GROUPS = /* @__PURE__ */ new Set([
|
|
1006
|
+
"workflow_workers",
|
|
1007
|
+
"default-consumer",
|
|
1008
|
+
"default"
|
|
1009
|
+
]);
|
|
1010
|
+
var claimedGroups = /* @__PURE__ */ new Set();
|
|
1011
|
+
function buildConsumerGroupName(serviceName, purpose = "lifecycle") {
|
|
1012
|
+
if (!SERVICE_NAME3.test(serviceName)) {
|
|
1013
|
+
throw new Error(`[Lifecycle] serviceName "${serviceName}" must be a kebab-case service name`);
|
|
1014
|
+
}
|
|
1015
|
+
if (!PURPOSE.test(purpose)) {
|
|
1016
|
+
throw new Error(`[Lifecycle] purpose "${purpose}" must be lower-case kebab-case`);
|
|
1017
|
+
}
|
|
1018
|
+
const group = `${serviceName}.${purpose}`;
|
|
1019
|
+
if (RESERVED_GROUPS.has(serviceName) || RESERVED_GROUPS.has(group)) {
|
|
1020
|
+
throw new Error(`[Lifecycle] "${group}" is a shared or default consumer group; use the service's own name`);
|
|
1021
|
+
}
|
|
1022
|
+
return group;
|
|
1023
|
+
}
|
|
1024
|
+
__name(buildConsumerGroupName, "buildConsumerGroupName");
|
|
1025
|
+
function errorMessage2(error) {
|
|
1026
|
+
return error instanceof Error ? error.message : String(error);
|
|
1027
|
+
}
|
|
1028
|
+
__name(errorMessage2, "errorMessage");
|
|
1029
|
+
function isRecord(value) {
|
|
1030
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1031
|
+
}
|
|
1032
|
+
__name(isRecord, "isRecord");
|
|
1033
|
+
function readId(record, key) {
|
|
1034
|
+
const value = record[key];
|
|
1035
|
+
return typeof value === "string" && ID.test(value) ? value : void 0;
|
|
1036
|
+
}
|
|
1037
|
+
__name(readId, "readId");
|
|
1038
|
+
function readOptionalString(record, key) {
|
|
1039
|
+
const value = record[key];
|
|
1040
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1041
|
+
}
|
|
1042
|
+
__name(readOptionalString, "readOptionalString");
|
|
1043
|
+
function readTimestamp(value) {
|
|
1044
|
+
if (value instanceof Date) return value.toISOString();
|
|
1045
|
+
return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : void 0;
|
|
1046
|
+
}
|
|
1047
|
+
__name(readTimestamp, "readTimestamp");
|
|
1048
|
+
function parseWorkspaceDeletedStream(data) {
|
|
1049
|
+
if (!isRecord(data)) return null;
|
|
1050
|
+
const workspaceId = readId(data, "workspaceId");
|
|
1051
|
+
if (!workspaceId) return null;
|
|
1052
|
+
return {
|
|
1053
|
+
workspaceId,
|
|
1054
|
+
tenantId: readId(data, "tenantId"),
|
|
1055
|
+
deletedBy: readOptionalString(data, "deletedBy"),
|
|
1056
|
+
deletedAt: readTimestamp(data["deletedAt"])
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
__name(parseWorkspaceDeletedStream, "parseWorkspaceDeletedStream");
|
|
1060
|
+
function parseWorkspaceDeletedGraph(data) {
|
|
1061
|
+
if (!isRecord(data) || data["eventType"] !== "entity.deleted") return null;
|
|
1062
|
+
const entity = data["entity"];
|
|
1063
|
+
if (!isRecord(entity) || entity["type"] !== "Workspace") return null;
|
|
1064
|
+
const workspaceId = readId(entity, "id");
|
|
1065
|
+
if (!workspaceId) return null;
|
|
1066
|
+
const row = isRecord(entity["data"]) ? entity["data"] : {};
|
|
1067
|
+
const context = isRecord(data["context"]) ? data["context"] : {};
|
|
1068
|
+
return {
|
|
1069
|
+
workspaceId,
|
|
1070
|
+
tenantId: readId(row, "tenantId"),
|
|
1071
|
+
organizationId: readId(data, "organizationId"),
|
|
1072
|
+
deletedBy: readOptionalString(context, "actorId"),
|
|
1073
|
+
deletedAt: readTimestamp(row["deletedAt"]) ?? readTimestamp(data["timestamp"])
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
__name(parseWorkspaceDeletedGraph, "parseWorkspaceDeletedGraph");
|
|
1077
|
+
function parseWorkspaceMemberRemoved(data) {
|
|
1078
|
+
if (!isRecord(data)) return null;
|
|
1079
|
+
const workspaceId = readId(data, "workspaceId");
|
|
1080
|
+
const userId = readId(data, "userId");
|
|
1081
|
+
if (!workspaceId || !userId) return null;
|
|
1082
|
+
return {
|
|
1083
|
+
workspaceId,
|
|
1084
|
+
userId,
|
|
1085
|
+
tenantId: readId(data, "tenantId"),
|
|
1086
|
+
removedBy: readOptionalString(data, "removedBy"),
|
|
1087
|
+
previousRole: readOptionalString(data, "previousRole")
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
__name(parseWorkspaceMemberRemoved, "parseWorkspaceMemberRemoved");
|
|
1091
|
+
function parseOrganizationDeleted(data) {
|
|
1092
|
+
if (!isRecord(data)) return null;
|
|
1093
|
+
const organizationId = readId(data, "organizationId");
|
|
1094
|
+
if (!organizationId) return null;
|
|
1095
|
+
return {
|
|
1096
|
+
organizationId,
|
|
1097
|
+
tenantId: readId(data, "tenantId"),
|
|
1098
|
+
deletedBy: readOptionalString(data, "actorId"),
|
|
1099
|
+
deletedAt: readTimestamp(data["occurredAt"])
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
__name(parseOrganizationDeleted, "parseOrganizationDeleted");
|
|
1103
|
+
var DedupeWindow = class DedupeWindow2 {
|
|
1104
|
+
static {
|
|
1105
|
+
__name(this, "DedupeWindow");
|
|
1106
|
+
}
|
|
1107
|
+
windowMs;
|
|
1108
|
+
seen = /* @__PURE__ */ new Map();
|
|
1109
|
+
constructor(windowMs) {
|
|
1110
|
+
this.windowMs = windowMs;
|
|
1111
|
+
}
|
|
1112
|
+
/** True when `key` was seen inside the window; records it otherwise. */
|
|
1113
|
+
check(key) {
|
|
1114
|
+
if (this.windowMs <= 0) return false;
|
|
1115
|
+
const now = Date.now();
|
|
1116
|
+
for (const [k, at] of this.seen) {
|
|
1117
|
+
if (now - at < this.windowMs) break;
|
|
1118
|
+
this.seen.delete(k);
|
|
1119
|
+
}
|
|
1120
|
+
if (this.seen.has(key)) return true;
|
|
1121
|
+
this.seen.set(key, now);
|
|
1122
|
+
return false;
|
|
1123
|
+
}
|
|
1124
|
+
forget(key) {
|
|
1125
|
+
this.seen.delete(key);
|
|
1126
|
+
}
|
|
1127
|
+
};
|
|
1128
|
+
function createLifecycleConsumer(options) {
|
|
1129
|
+
const group = buildConsumerGroupName(options.serviceName, options.purpose);
|
|
1130
|
+
const { handlers, layer } = options;
|
|
1131
|
+
const maxDeliver = options.maxDeliver ?? 5;
|
|
1132
|
+
if (!Number.isInteger(maxDeliver) || maxDeliver < 1) {
|
|
1133
|
+
throw new Error("[Lifecycle] maxDeliver must be a positive integer");
|
|
1134
|
+
}
|
|
1135
|
+
if (layer === "wspace" && handlers.onOrganizationDeleted) {
|
|
1136
|
+
throw new Error("[Lifecycle] onOrganizationDeleted needs a global-layer service: organization.deleted is published on the global Valkey, which wspace services do not read");
|
|
1137
|
+
}
|
|
1138
|
+
if (layer === "global" && (handlers.onWorkspaceDeleted || handlers.onWorkspaceMemberRemoved)) {
|
|
1139
|
+
throw new Error("[Lifecycle] workspace lifecycle events are published on the wspace Valkey; use a wspace service");
|
|
1140
|
+
}
|
|
1141
|
+
const graphStream = options.graphStream ?? process.env["GRAPH_SYNC_STREAM_NAME"] ?? WSPACE_GRAPH_EVENTS_STREAM;
|
|
1142
|
+
const dedupe = new DedupeWindow(options.dedupeWindowMs ?? 10 * 60 * 1e3);
|
|
1143
|
+
const routes = [];
|
|
1144
|
+
const once = /* @__PURE__ */ __name(async (key, run) => {
|
|
1145
|
+
if (dedupe.check(key)) return "duplicate";
|
|
1146
|
+
try {
|
|
1147
|
+
await run();
|
|
1148
|
+
return "handled";
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
dedupe.forget(key);
|
|
1151
|
+
throw error;
|
|
1152
|
+
}
|
|
1153
|
+
}, "once");
|
|
1154
|
+
const { onWorkspaceDeleted, onWorkspaceMemberRemoved, onOrganizationDeleted } = handlers;
|
|
1155
|
+
if (onWorkspaceDeleted) {
|
|
1156
|
+
const sources = options.workspaceDeletedSources ?? [
|
|
1157
|
+
"graph",
|
|
1158
|
+
"stream"
|
|
1159
|
+
];
|
|
1160
|
+
if (sources.length === 0) throw new Error("[Lifecycle] workspaceDeletedSources must not be empty");
|
|
1161
|
+
const deliver = /* @__PURE__ */ __name((parse) => async (data, ctx) => {
|
|
1162
|
+
const fact = parse(data);
|
|
1163
|
+
if (!fact) return "invalid";
|
|
1164
|
+
return once(`workspace.deleted:${fact.workspaceId}`, () => onWorkspaceDeleted(fact, ctx));
|
|
1165
|
+
}, "deliver");
|
|
1166
|
+
if (sources.includes("graph")) {
|
|
1167
|
+
routes.push({
|
|
1168
|
+
subject: LIFECYCLE_SUBJECTS.workspaceDeletedGraph,
|
|
1169
|
+
stream: graphStream,
|
|
1170
|
+
source: "graph",
|
|
1171
|
+
dispatch: deliver(parseWorkspaceDeletedGraph)
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
if (sources.includes("stream")) {
|
|
1175
|
+
routes.push({
|
|
1176
|
+
subject: LIFECYCLE_SUBJECTS.workspaceDeleted,
|
|
1177
|
+
source: "stream",
|
|
1178
|
+
dispatch: deliver(parseWorkspaceDeletedStream)
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
if (onWorkspaceMemberRemoved) {
|
|
1183
|
+
routes.push({
|
|
1184
|
+
subject: LIFECYCLE_SUBJECTS.workspaceMemberRemoved,
|
|
1185
|
+
source: "stream",
|
|
1186
|
+
dispatch: /* @__PURE__ */ __name(async (data, ctx) => {
|
|
1187
|
+
const fact = parseWorkspaceMemberRemoved(data);
|
|
1188
|
+
if (!fact) return "invalid";
|
|
1189
|
+
return once(`workspace.member.removed:${fact.workspaceId}:${fact.userId}:${ctx.eventId}`, () => onWorkspaceMemberRemoved(fact, ctx));
|
|
1190
|
+
}, "dispatch")
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
if (onOrganizationDeleted) {
|
|
1194
|
+
routes.push({
|
|
1195
|
+
subject: LIFECYCLE_SUBJECTS.organizationDeleted,
|
|
1196
|
+
source: "stream",
|
|
1197
|
+
dispatch: /* @__PURE__ */ __name(async (data, ctx) => {
|
|
1198
|
+
const fact = parseOrganizationDeleted(data);
|
|
1199
|
+
if (!fact) return "invalid";
|
|
1200
|
+
return once(`organization.deleted:${fact.organizationId}`, () => onOrganizationDeleted(fact, ctx));
|
|
1201
|
+
}, "dispatch")
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
if (routes.length === 0) throw new Error("[Lifecycle] at least one handler is required");
|
|
1205
|
+
const consumerFactory = options.consumerFactory ?? createConsumer;
|
|
1206
|
+
let consumer = null;
|
|
1207
|
+
let subscriptions = [];
|
|
1208
|
+
let starting = null;
|
|
1209
|
+
const handle = /* @__PURE__ */ __name((route) => async (event) => {
|
|
1210
|
+
if (event.subject !== route.subject) {
|
|
1211
|
+
await event.ack();
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
const correlationId = event.metadata?.correlationId;
|
|
1215
|
+
const ctx = {
|
|
1216
|
+
eventId: event.id,
|
|
1217
|
+
subject: event.subject,
|
|
1218
|
+
source: route.source,
|
|
1219
|
+
deliveryAttempt: event.getDeliveryAttempt(),
|
|
1220
|
+
...typeof correlationId === "string" ? {
|
|
1221
|
+
correlationId
|
|
1222
|
+
} : {}
|
|
1223
|
+
};
|
|
1224
|
+
let outcome;
|
|
1225
|
+
try {
|
|
1226
|
+
outcome = await route.dispatch(event.data, ctx);
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
logger.error("[Lifecycle] handler failed; will retry", {
|
|
1229
|
+
group,
|
|
1230
|
+
subject: event.subject,
|
|
1231
|
+
eventId: event.id,
|
|
1232
|
+
attempt: ctx.deliveryAttempt,
|
|
1233
|
+
error: errorMessage2(error)
|
|
1234
|
+
});
|
|
1235
|
+
await event.nak();
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
if (outcome === "invalid") {
|
|
1239
|
+
logger.error("[Lifecycle] invalid payload; dead-lettering without running the handler", {
|
|
1240
|
+
group,
|
|
1241
|
+
subject: event.subject,
|
|
1242
|
+
eventId: event.id
|
|
1243
|
+
});
|
|
1244
|
+
await event.term();
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
await event.ack();
|
|
1248
|
+
logger.info("[Lifecycle] event processed", {
|
|
1249
|
+
group,
|
|
1250
|
+
subject: event.subject,
|
|
1251
|
+
eventId: event.id,
|
|
1252
|
+
outcome
|
|
1253
|
+
});
|
|
1254
|
+
}, "handle");
|
|
1255
|
+
const doStart = /* @__PURE__ */ __name(async () => {
|
|
1256
|
+
if (claimedGroups.has(group)) {
|
|
1257
|
+
throw new Error(`[Lifecycle] consumer group ${group} is already running in this process`);
|
|
1258
|
+
}
|
|
1259
|
+
claimedGroups.add(group);
|
|
1260
|
+
const created = consumerFactory(routes[0]?.stream ?? routes[0]?.subject ?? group, group);
|
|
1261
|
+
const opened = [];
|
|
1262
|
+
try {
|
|
1263
|
+
await created.connect();
|
|
1264
|
+
for (const route of routes) {
|
|
1265
|
+
opened.push(await created.subscribe({
|
|
1266
|
+
subject: route.subject,
|
|
1267
|
+
handler: handle(route),
|
|
1268
|
+
options: {
|
|
1269
|
+
consumer: group,
|
|
1270
|
+
// Must be on subscribe(): createConsumer() ignores the stream.
|
|
1271
|
+
...route.stream ? {
|
|
1272
|
+
stream: route.stream
|
|
1273
|
+
} : {},
|
|
1274
|
+
deliverPolicy: "new",
|
|
1275
|
+
ackPolicy: "explicit",
|
|
1276
|
+
maxDeliver
|
|
1277
|
+
}
|
|
1278
|
+
}));
|
|
1279
|
+
}
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
for (const sub of opened) await sub.unsubscribe().catch(() => void 0);
|
|
1282
|
+
await created.disconnect().catch(() => void 0);
|
|
1283
|
+
claimedGroups.delete(group);
|
|
1284
|
+
throw error;
|
|
1285
|
+
}
|
|
1286
|
+
consumer = created;
|
|
1287
|
+
subscriptions = opened;
|
|
1288
|
+
logger.info("[Lifecycle] consumer started", {
|
|
1289
|
+
group,
|
|
1290
|
+
subjects: routes.map((r) => r.stream ? `${r.subject} (${r.stream})` : r.subject),
|
|
1291
|
+
keyScope: eventKeyScopeForUrl(resolveEventStreamsUrl()) || "(none)"
|
|
1292
|
+
});
|
|
1293
|
+
}, "doStart");
|
|
1294
|
+
return {
|
|
1295
|
+
group,
|
|
1296
|
+
subjects: routes.map((r) => r.subject),
|
|
1297
|
+
async start() {
|
|
1298
|
+
if (consumer) return;
|
|
1299
|
+
starting ??= doStart().finally(() => {
|
|
1300
|
+
starting = null;
|
|
1301
|
+
});
|
|
1302
|
+
await starting;
|
|
1303
|
+
},
|
|
1304
|
+
async stop() {
|
|
1305
|
+
if (starting) await starting.catch(() => void 0);
|
|
1306
|
+
const current = consumer;
|
|
1307
|
+
if (!current) return;
|
|
1308
|
+
consumer = null;
|
|
1309
|
+
for (const sub of subscriptions) {
|
|
1310
|
+
await sub.unsubscribe().catch((error) => logger.warn("[Lifecycle] unsubscribe failed", {
|
|
1311
|
+
group,
|
|
1312
|
+
error: errorMessage2(error)
|
|
1313
|
+
}));
|
|
1314
|
+
}
|
|
1315
|
+
subscriptions = [];
|
|
1316
|
+
await current.disconnect().catch((error) => logger.warn("[Lifecycle] disconnect failed", {
|
|
1317
|
+
group,
|
|
1318
|
+
error: errorMessage2(error)
|
|
1319
|
+
}));
|
|
1320
|
+
claimedGroups.delete(group);
|
|
1321
|
+
logger.info("[Lifecycle] consumer stopped", {
|
|
1322
|
+
group
|
|
1323
|
+
});
|
|
1324
|
+
},
|
|
1325
|
+
isRunning() {
|
|
1326
|
+
return consumer !== null;
|
|
1327
|
+
}
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
__name(createLifecycleConsumer, "createLifecycleConsumer");
|
|
1331
|
+
|
|
1332
|
+
export { EVENT_TAXONOMY_BRAND, EventPriority, EventsManager, EventsModule, LIFECYCLE_SUBJECTS, ModuleEventsService, PLATFORM_EVENT_TAXONOMY, REFERENCE_PRODUCT_EVENT_TAXONOMY, WSPACE_GRAPH_EVENTS_STREAM, buildConsumerGroupName, createConsumer, createEventsManagerSingleton, createLifecycleConsumer, createModuleEventsService, createPublisher, defineEventTaxonomy, eventSpec, event_queue_exports, isDefinedEventTaxonomy, mergeEventTaxonomies, parseOrganizationDeleted, parseWorkspaceDeletedGraph, parseWorkspaceDeletedStream, parseWorkspaceMemberRemoved, publishTaxonomyEvent, taxonomyEventNames, taxonomyNameViolation };
|
|
1333
|
+
//# sourceMappingURL=chunk-JV7XNJP4.js.map
|
|
1334
|
+
//# sourceMappingURL=chunk-JV7XNJP4.js.map
|