@relaybus/nestjs 0.1.0 → 0.3.0

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/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { Injectable, Inject, ConfigurableModuleBuilder, Module, Logger } from '@nestjs/common';
2
- import { DiscoveryService, MetadataScanner, DiscoveryModule } from '@nestjs/core';
3
- import { RelayBus, systemClock, ConfigurationError } from '@relaybus/core';
4
- export { RelayBus } from '@relaybus/core';
5
1
  import 'reflect-metadata';
2
+ import { RelayBus, systemClock, TransactionRequiredError, ConfigurationError, describeCatalog, consume, produce } from '@relaybus/core';
3
+ export { RelayBus } from '@relaybus/core';
4
+ import { Injectable, Inject, ConfigurableModuleBuilder, Module, Logger } from '@nestjs/common';
5
+ import { DiscoveryService, MetadataScanner, ModulesContainer, DiscoveryModule } from '@nestjs/core';
6
6
 
7
7
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
8
  var __decorateClass = (decorators, target, key, kind) => {
@@ -13,8 +13,106 @@ var __decorateClass = (decorators, target, key, kind) => {
13
13
  return result;
14
14
  };
15
15
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
16
+ var EVENT_CONSUMER_METADATA_KEY = /* @__PURE__ */ Symbol.for("relaybus.nestjs.event-consumer");
17
+ function RelayBusCatalogConsumer(catalog, {
18
+ events,
19
+ ...options
20
+ } = {}) {
21
+ const { name } = describeCatalog(catalog);
22
+ const selectedEntries = events === void 0 ? void 0 : consume(catalog, { events }).entries;
23
+ return (target) => {
24
+ const existing = Reflect.getOwnMetadata(EVENT_CONSUMER_METADATA_KEY, target) ?? [];
25
+ if (existing.some((metadata) => metadata.catalog === catalog)) {
26
+ throw new ConfigurationError(
27
+ `@RelayBusCatalogConsumer(${name ?? "catalog"}) is declared twice on ${target.name}; merge the declarations into one`
28
+ );
29
+ }
30
+ Reflect.defineMetadata(
31
+ EVENT_CONSUMER_METADATA_KEY,
32
+ [...existing, { catalog, options, selectedEntries }],
33
+ target
34
+ );
35
+ };
36
+ }
37
+ var EventConsumer = RelayBusCatalogConsumer;
38
+ function readCatalogConsumerMetadata(target) {
39
+ const lineage = [];
40
+ for (let current = target; current !== Function.prototype; ) {
41
+ lineage.unshift(current);
42
+ current = Object.getPrototypeOf(current);
43
+ }
44
+ const byCatalog = /* @__PURE__ */ new Map();
45
+ for (const type of lineage) {
46
+ const own = Reflect.getOwnMetadata(EVENT_CONSUMER_METADATA_KEY, type) ?? [];
47
+ for (const metadata of own) {
48
+ byCatalog.set(metadata.catalog, metadata);
49
+ }
50
+ }
51
+ return [...byCatalog.values()];
52
+ }
53
+ var RelayBusFeatureContract = class {
54
+ consumes;
55
+ produces;
56
+ /** @throws ConfigurationError for a `produce(...)` in `consumes`, a `consume(...)` in `produces`, or something that is not a catalog. */
57
+ constructor(options) {
58
+ this.consumes = contractEvents(options.consumes ?? [], "consume");
59
+ this.produces = contractEvents(options.produces ?? [], "produce");
60
+ }
61
+ };
62
+ function contractEvents(items, role) {
63
+ return items.flatMap((item) => {
64
+ const declaration = isDeclaration(item) ? item : role === "consume" ? consume(item) : produce(item);
65
+ const name = describeCatalog(declaration.catalog).name ?? "catalog";
66
+ if (declaration.role !== role) {
67
+ throw new ConfigurationError(
68
+ `RelayBusModule.forFeature ${role}s takes catalogs and ${role}(...) declarations, received ${declaration.role}(${name})`
69
+ );
70
+ }
71
+ return declaration.entries.map((entry) => ({
72
+ label: `${name}.${entry.name}`,
73
+ type: entry.eventClass.type
74
+ }));
75
+ });
76
+ }
77
+ function isDeclaration(item) {
78
+ return typeof item["role"] === "string" && Array.isArray(item["entries"]);
79
+ }
80
+ var runningBuses = /* @__PURE__ */ new Set();
81
+ var busOfInstance = /* @__PURE__ */ new WeakMap();
82
+ function registerBus(bus) {
83
+ runningBuses.add(bus);
84
+ }
85
+ function unregisterBus(bus) {
86
+ runningBuses.delete(bus);
87
+ }
88
+ function bindInstance(instance, bus) {
89
+ busOfInstance.set(instance, bus);
90
+ }
91
+ function resolveBus(instance, method) {
92
+ const bound = typeof instance === "object" && instance !== null ? busOfInstance.get(instance) : void 0;
93
+ if (bound !== void 0) {
94
+ if (!runningBuses.has(bound)) {
95
+ throw new ConfigurationError(
96
+ `@RelayBusTransaction() ${method} was called after its application shut down`
97
+ );
98
+ }
99
+ return bound;
100
+ }
101
+ const [only, ...others] = runningBuses;
102
+ if (only === void 0) {
103
+ throw new ConfigurationError(
104
+ `@RelayBusTransaction() ${method} found no running RelayBusModule: import RelayBusModule.forRoot(...) and call the method after the application initialised (app.init() or app.listen())`
105
+ );
106
+ }
107
+ if (others.length > 0) {
108
+ throw new ConfigurationError(
109
+ `@RelayBusTransaction() ${method} cannot tell which of ${runningBuses.size} running applications it belongs to; call it on a singleton provider of one of them`
110
+ );
111
+ }
112
+ return only;
113
+ }
16
114
  var SUBSCRIBE_METADATA_KEY = /* @__PURE__ */ Symbol.for("relaybus.nestjs.subscribe");
17
- function Subscribe(event, options = {}) {
115
+ function RelayBusConsumer(event, options = {}) {
18
116
  return (target, propertyKey) => {
19
117
  const existing = Reflect.getOwnMetadata(SUBSCRIBE_METADATA_KEY, target, propertyKey) ?? [];
20
118
  Reflect.defineMetadata(
@@ -25,68 +123,182 @@ function Subscribe(event, options = {}) {
25
123
  );
26
124
  };
27
125
  }
28
- function readSubscribeMetadata(prototype, propertyKey) {
126
+ var Subscribe = RelayBusConsumer;
127
+ function readConsumerMetadata(prototype, propertyKey) {
29
128
  return Reflect.getMetadata(SUBSCRIBE_METADATA_KEY, prototype, propertyKey) ?? [];
30
129
  }
31
130
 
32
131
  // src/handler-explorer.ts
33
132
  var RelayBusHandlerExplorer = class {
34
- constructor(discovery, metadataScanner, bus) {
133
+ constructor(discovery, metadataScanner, bus, modules) {
35
134
  this.discovery = discovery;
36
135
  this.metadataScanner = metadataScanner;
37
136
  this.bus = bus;
137
+ this.modules = modules;
38
138
  }
39
139
  discovery;
40
140
  metadataScanner;
41
141
  bus;
142
+ modules;
42
143
  onModuleInit() {
43
- const registeredBy = /* @__PURE__ */ new Map();
44
- const visited = /* @__PURE__ */ new Map();
144
+ const discovery = {
145
+ registeredBy: /* @__PURE__ */ new Map(),
146
+ visited: /* @__PURE__ */ new Map(),
147
+ consumers: /* @__PURE__ */ new WeakSet(),
148
+ consumedByModule: /* @__PURE__ */ new Map()
149
+ };
150
+ for (const wrapper of this.discovery.getProviders()) {
151
+ this.registerProvider(wrapper, discovery);
152
+ }
153
+ this.assertModuleContracts(discovery.consumedByModule);
154
+ }
155
+ /** Checks the `RelayBusModule.forFeature` contract of every module that imports one. */
156
+ assertModuleContracts(consumedByModule) {
157
+ const routed = new Set(
158
+ this.bus.handlers().filter((handler) => handler.forwardsToTransport).map((handler) => handler.eventType)
159
+ );
160
+ const violations = [];
45
161
  for (const wrapper of this.discovery.getProviders()) {
46
- if (wrapper.isTransient || !wrapper.isDependencyTreeStatic()) {
47
- this.assertNoHandlers(wrapper);
162
+ const contract = wrapper.instance;
163
+ if (!(contract instanceof RelayBusFeatureContract)) {
48
164
  continue;
49
165
  }
50
- const instance = wrapper.instance;
51
- if (typeof instance !== "object" || instance === null) {
52
- continue;
166
+ for (const module of this.importersOf(wrapper.host)) {
167
+ const consumed = consumedByModule.get(module);
168
+ for (const event of contract.consumes.filter(({ type }) => !consumed.has(type))) {
169
+ violations.push(`${module.name}: ${event.label} (${event.type}) has no consumer`);
170
+ }
171
+ for (const event of contract.produces.filter(({ type }) => !routed.has(type))) {
172
+ violations.push(
173
+ `${module.name}: ${event.label} (${event.type}) has no route to a transport`
174
+ );
175
+ }
53
176
  }
54
- const prototype = Object.getPrototypeOf(instance);
55
- if (prototype === null) {
56
- continue;
177
+ }
178
+ if (violations.length > 0) {
179
+ throw new ConfigurationError(
180
+ `[RelayBusHandlerExplorer](assertModuleContracts) ${violations.join("; ")}`
181
+ );
182
+ }
183
+ }
184
+ importersOf(contractModule) {
185
+ return [...this.modules.values()].filter((module) => module.imports.has(contractModule));
186
+ }
187
+ /** Records the event types the provider of `wrapper` consumes under the provider's module. */
188
+ recordConsumedTypes(wrapper, { instance, discovery }) {
189
+ const types = discovery.consumedByModule.get(wrapper.host) ?? /* @__PURE__ */ new Set();
190
+ discovery.consumedByModule.set(wrapper.host, types);
191
+ const lookup = instance;
192
+ for (const { declarations } of this.subscribedMethods(
193
+ Object.getPrototypeOf(instance)
194
+ )) {
195
+ for (const { event } of declarations) {
196
+ types.add(typeof event === "string" ? event : event.type);
57
197
  }
58
- const className = instance.constructor.name;
59
- for (const { methodName, declarations } of this.subscribedMethods(prototype)) {
60
- const seen = visited.get(instance) ?? /* @__PURE__ */ new Set();
61
- visited.set(instance, seen);
62
- if (seen.has(methodName)) {
63
- continue;
64
- }
65
- seen.add(methodName);
66
- const method = instance[methodName];
67
- const location = `${className}.${methodName}`;
68
- for (const { event, options } of declarations) {
69
- const id = options.id ?? location;
70
- const previous = registeredBy.get(id);
71
- if (previous !== void 0) {
72
- throw new ConfigurationError(
73
- `Handler id '${id}' is used by both ${previous} and ${location}; pass a unique { id } to @Subscribe`
74
- );
75
- }
76
- registeredBy.set(id, location);
77
- this.bus.subscribe(
78
- event,
79
- (envelope, context) => method.call(instance, envelope, context),
80
- { ...options, id }
198
+ }
199
+ for (const { catalog, selectedEntries } of readCatalogConsumerMetadata(instance.constructor)) {
200
+ const entries = selectedEntries ?? describeCatalog(catalog).entries.filter((entry) => isMethod(lookup, entry));
201
+ for (const entry of entries) {
202
+ types.add(entry.eventClass.type);
203
+ }
204
+ }
205
+ }
206
+ registerProvider(wrapper, discovery) {
207
+ if (wrapper.isTransient || !wrapper.isDependencyTreeStatic()) {
208
+ this.assertNoHandlers(wrapper);
209
+ return;
210
+ }
211
+ const instance = wrapper.instance;
212
+ if (typeof instance !== "object" || instance === null) {
213
+ return;
214
+ }
215
+ const prototype = Object.getPrototypeOf(instance);
216
+ if (prototype === null) {
217
+ return;
218
+ }
219
+ bindInstance(instance, this.bus);
220
+ this.recordConsumedTypes(wrapper, { instance, discovery });
221
+ const className = instance.constructor.name;
222
+ for (const subscribed of this.subscribedMethods(prototype)) {
223
+ this.registerSubscribedMethod(instance, { subscribedMethod: subscribed, discovery });
224
+ }
225
+ if (!discovery.consumers.has(instance)) {
226
+ discovery.consumers.add(instance);
227
+ this.registerEventConsumers(instance, { className, registeredBy: discovery.registeredBy });
228
+ }
229
+ }
230
+ registerSubscribedMethod(instance, {
231
+ subscribedMethod: { methodName, declarations },
232
+ discovery: { registeredBy, visited }
233
+ }) {
234
+ const seen = visited.get(instance) ?? /* @__PURE__ */ new Set();
235
+ visited.set(instance, seen);
236
+ if (seen.has(methodName)) {
237
+ return;
238
+ }
239
+ seen.add(methodName);
240
+ const method = instance[methodName];
241
+ const location = `${instance.constructor.name}.${methodName}`;
242
+ for (const { event, options } of declarations) {
243
+ const id = options.id ?? location;
244
+ const previous = registeredBy.get(id);
245
+ if (previous !== void 0) {
246
+ throw new ConfigurationError(
247
+ `Handler id '${id}' is used by both ${previous} and ${location}; pass a unique { id } to @RelayBusConsumer`
248
+ );
249
+ }
250
+ registeredBy.set(id, location);
251
+ this.bus.subscribe(
252
+ event,
253
+ (envelope, context) => method.call(instance, envelope, context),
254
+ { ...options, id }
255
+ );
256
+ }
257
+ }
258
+ registerEventConsumers(instance, {
259
+ className,
260
+ registeredBy
261
+ }) {
262
+ const lookup = instance;
263
+ for (const { catalog, options, selectedEntries } of readCatalogConsumerMetadata(
264
+ instance.constructor
265
+ )) {
266
+ const { name, entries } = describeCatalog(catalog);
267
+ const label = name ?? "catalog";
268
+ const handlers = selectedEntries ?? entries.filter((entry) => isMethod(lookup, entry));
269
+ const missing = handlers.filter((entry) => !isMethod(lookup, entry));
270
+ if (missing.length > 0) {
271
+ throw new ConfigurationError(
272
+ `${className} uses @RelayBusCatalogConsumer(${label}) but lacks the handler methods of events it consumes: ${missing.map((entry) => entry.handlerName).join(", ")}`
273
+ );
274
+ }
275
+ if (handlers.length === 0) {
276
+ throw new ConfigurationError(
277
+ `${className} uses @RelayBusCatalogConsumer(${label}) but defines none of its handler methods (${entries.map((entry) => entry.handlerName).join(", ")})`
278
+ );
279
+ }
280
+ for (const entry of handlers) {
281
+ const id = `${className}.${entry.handlerName}`;
282
+ const previous = registeredBy.get(id);
283
+ if (previous !== void 0) {
284
+ throw new ConfigurationError(
285
+ `Handler id '${id}' of @RelayBusCatalogConsumer(${label}) is already used by ${previous}; give the @RelayBusConsumer a unique { id } or drop it`
81
286
  );
82
287
  }
288
+ registeredBy.set(id, `${className}.${entry.handlerName}`);
289
+ const method = lookup[entry.handlerName];
290
+ this.bus.subscribe(
291
+ entry.eventClass,
292
+ (envelope, context) => method.call(instance, envelope, context),
293
+ { ...options, id }
294
+ );
83
295
  }
84
296
  }
85
297
  }
86
298
  subscribedMethods(prototype) {
87
299
  const methods = [];
88
300
  for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {
89
- const declarations = readSubscribeMetadata(prototype, methodName);
301
+ const declarations = readConsumerMetadata(prototype, methodName);
90
302
  if (declarations.length > 0) {
91
303
  methods.push({ methodName, declarations });
92
304
  }
@@ -100,11 +312,16 @@ var RelayBusHandlerExplorer = class {
100
312
  */
101
313
  assertNoHandlers(wrapper) {
102
314
  const type = wrapper.isFactory ? wrapper.token : wrapper.metatype;
315
+ if (typeof type === "function" && readCatalogConsumerMetadata(type).length > 0) {
316
+ throw new ConfigurationError(
317
+ `${type.name} uses @RelayBusCatalogConsumer but its provider is request-scoped or transient (directly or through a dependency); handlers must be singleton providers`
318
+ );
319
+ }
103
320
  const prototype = typeof type === "function" ? type.prototype : null;
104
321
  const [first] = prototype === null ? [] : this.subscribedMethods(prototype);
105
322
  if (first !== void 0) {
106
323
  throw new ConfigurationError(
107
- `${prototype.constructor.name}.${first.methodName} uses @Subscribe but its provider is request-scoped or transient (directly or through a dependency); handlers must be singleton providers`
324
+ `${prototype.constructor.name}.${first.methodName} uses @RelayBusConsumer but its provider is request-scoped or transient (directly or through a dependency); handlers must be singleton providers`
108
325
  );
109
326
  }
110
327
  }
@@ -113,8 +330,12 @@ RelayBusHandlerExplorer = __decorateClass([
113
330
  Injectable(),
114
331
  __decorateParam(0, Inject(DiscoveryService)),
115
332
  __decorateParam(1, Inject(MetadataScanner)),
116
- __decorateParam(2, Inject(RelayBus))
333
+ __decorateParam(2, Inject(RelayBus)),
334
+ __decorateParam(3, Inject(ModulesContainer))
117
335
  ], RelayBusHandlerExplorer);
336
+ function isMethod(instance, entry) {
337
+ return typeof instance[entry.handlerName] === "function";
338
+ }
118
339
  var {
119
340
  ConfigurableModuleClass: RelayBusConfigurableModule,
120
341
  MODULE_OPTIONS_TOKEN: RELAYBUS_MODULE_OPTIONS
@@ -171,18 +392,86 @@ var RelayBusLifecycle = class {
171
392
  this.bus = bus;
172
393
  }
173
394
  bus;
395
+ onModuleInit() {
396
+ registerBus(this.bus);
397
+ }
174
398
  async onApplicationBootstrap() {
175
399
  await this.bus.start();
176
400
  }
177
401
  async beforeApplicationShutdown() {
178
402
  await this.bus.stop();
179
403
  }
404
+ /** After the bus stopped, so handlers still draining at shutdown can open transactions. */
405
+ onApplicationShutdown() {
406
+ unregisterBus(this.bus);
407
+ }
180
408
  };
181
409
  RelayBusLifecycle = __decorateClass([
182
410
  Injectable(),
183
411
  __decorateParam(0, Inject(RelayBus))
184
412
  ], RelayBusLifecycle);
413
+ var RelayBusFeatureModule = class {
414
+ };
415
+ RelayBusFeatureModule = __decorateClass([
416
+ Module({})
417
+ ], RelayBusFeatureModule);
418
+ var RelayBusTransactionHost = class {
419
+ constructor(bus) {
420
+ this.bus = bus;
421
+ }
422
+ bus;
423
+ /**
424
+ * The active transaction.
425
+ *
426
+ * @throws TransactionRequiredError when the caller runs outside every transaction.
427
+ */
428
+ current() {
429
+ const transaction = this.bus.currentTransaction();
430
+ if (transaction === void 0) {
431
+ throw new TransactionRequiredError(
432
+ "No relaybus transaction is active: call the repository from a @RelayBusTransaction() method or inside bus.transaction()"
433
+ );
434
+ }
435
+ return transaction;
436
+ }
437
+ /** The active transaction, or undefined outside every transaction. */
438
+ find() {
439
+ return this.bus.currentTransaction();
440
+ }
441
+ };
442
+ RelayBusTransactionHost = __decorateClass([
443
+ Injectable(),
444
+ __decorateParam(0, Inject(RelayBus))
445
+ ], RelayBusTransactionHost);
446
+
447
+ // src/relay-bus.module.ts
185
448
  var RelayBusModule = class extends RelayBusConfigurableModule {
449
+ /**
450
+ * The relaybus contract of a feature module: import it in the module whose providers consume
451
+ * and produce the events. When the application initialises, every consumed event needs a
452
+ * `@RelayBusConsumer` method (or a `@RelayBusCatalogConsumer` class) among the providers of
453
+ * that module, spread over any classes and method names, and every produced event needs a
454
+ * route to a transport; otherwise the application fails to start naming the module and each
455
+ * missing event. Needs `RelayBusModule.forRoot` in the application.
456
+ *
457
+ * ```ts
458
+ * @Module({
459
+ * imports: [RelayBusModule.forFeature({ consumes: [OrderEvents], produces: [produce(BillingEvents)] })],
460
+ * providers: [OrderPlacedHandlers, OrderCancelledHandlers],
461
+ * })
462
+ * export class BillingModule {}
463
+ * ```
464
+ *
465
+ * @throws ConfigurationError for a `produce(...)` in `consumes` or a `consume(...)` in `produces`.
466
+ */
467
+ static forFeature(options) {
468
+ return {
469
+ module: RelayBusFeatureModule,
470
+ providers: [
471
+ { provide: RelayBusFeatureContract, useValue: new RelayBusFeatureContract(options) }
472
+ ]
473
+ };
474
+ }
186
475
  };
187
476
  RelayBusModule = __decorateClass([
188
477
  Module({
@@ -195,12 +484,31 @@ RelayBusModule = __decorateClass([
195
484
  },
196
485
  RelayBusHandlerExplorer,
197
486
  RelayBusLifecycle,
198
- RelayBusHealth
487
+ RelayBusHealth,
488
+ RelayBusTransactionHost
199
489
  ],
200
- exports: [RelayBus, RelayBusHealth]
490
+ exports: [RelayBus, RelayBusHealth, RelayBusTransactionHost]
201
491
  })
202
492
  ], RelayBusModule);
493
+ function RelayBusTransaction() {
494
+ return (target, propertyKey, descriptor) => {
495
+ const original = descriptor.value;
496
+ const label = `${target.constructor.name}.${String(propertyKey)}`;
497
+ const transactional = async function(...args) {
498
+ const bus = resolveBus(this, label);
499
+ if (bus.currentTransaction() !== void 0) {
500
+ return original.apply(this, args);
501
+ }
502
+ return bus.transaction(() => original.apply(this, args));
503
+ };
504
+ Object.defineProperty(transactional, "name", { value: original.name });
505
+ for (const key of Reflect.getOwnMetadataKeys(original)) {
506
+ Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, original), transactional);
507
+ }
508
+ descriptor.value = transactional;
509
+ };
510
+ }
203
511
 
204
- export { RelayBusHandlerExplorer, RelayBusHealth, RelayBusLifecycle, RelayBusModule, Subscribe };
512
+ export { EventConsumer, RelayBusCatalogConsumer, RelayBusConsumer, RelayBusFeatureContract, RelayBusFeatureModule, RelayBusHandlerExplorer, RelayBusHealth, RelayBusLifecycle, RelayBusModule, RelayBusTransaction, RelayBusTransactionHost, Subscribe };
205
513
  //# sourceMappingURL=index.js.map
206
514
  //# sourceMappingURL=index.js.map