@relaybus/nestjs 0.2.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
1
  import 'reflect-metadata';
2
- import { RelayBus, systemClock, ConfigurationError, describeCatalog, consume } from '@relaybus/core';
2
+ import { RelayBus, systemClock, TransactionRequiredError, ConfigurationError, describeCatalog, consume, produce } from '@relaybus/core';
3
3
  export { RelayBus } from '@relaybus/core';
4
4
  import { Injectable, Inject, ConfigurableModuleBuilder, Module, Logger } from '@nestjs/common';
5
- import { DiscoveryService, MetadataScanner, DiscoveryModule } from '@nestjs/core';
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) => {
@@ -14,7 +14,7 @@ var __decorateClass = (decorators, target, key, kind) => {
14
14
  };
15
15
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
16
16
  var EVENT_CONSUMER_METADATA_KEY = /* @__PURE__ */ Symbol.for("relaybus.nestjs.event-consumer");
17
- function EventConsumer(catalog, {
17
+ function RelayBusCatalogConsumer(catalog, {
18
18
  events,
19
19
  ...options
20
20
  } = {}) {
@@ -24,7 +24,7 @@ function EventConsumer(catalog, {
24
24
  const existing = Reflect.getOwnMetadata(EVENT_CONSUMER_METADATA_KEY, target) ?? [];
25
25
  if (existing.some((metadata) => metadata.catalog === catalog)) {
26
26
  throw new ConfigurationError(
27
- `@EventConsumer(${name ?? "catalog"}) is declared twice on ${target.name}; merge the declarations into one`
27
+ `@RelayBusCatalogConsumer(${name ?? "catalog"}) is declared twice on ${target.name}; merge the declarations into one`
28
28
  );
29
29
  }
30
30
  Reflect.defineMetadata(
@@ -34,7 +34,8 @@ function EventConsumer(catalog, {
34
34
  );
35
35
  };
36
36
  }
37
- function readEventConsumerMetadata(target) {
37
+ var EventConsumer = RelayBusCatalogConsumer;
38
+ function readCatalogConsumerMetadata(target) {
38
39
  const lineage = [];
39
40
  for (let current = target; current !== Function.prototype; ) {
40
41
  lineage.unshift(current);
@@ -49,8 +50,69 @@ function readEventConsumerMetadata(target) {
49
50
  }
50
51
  return [...byCatalog.values()];
51
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
+ }
52
114
  var SUBSCRIBE_METADATA_KEY = /* @__PURE__ */ Symbol.for("relaybus.nestjs.subscribe");
53
- function Subscribe(event, options = {}) {
115
+ function RelayBusConsumer(event, options = {}) {
54
116
  return (target, propertyKey) => {
55
117
  const existing = Reflect.getOwnMetadata(SUBSCRIBE_METADATA_KEY, target, propertyKey) ?? [];
56
118
  Reflect.defineMetadata(
@@ -61,72 +123,144 @@ function Subscribe(event, options = {}) {
61
123
  );
62
124
  };
63
125
  }
64
- function readSubscribeMetadata(prototype, propertyKey) {
126
+ var Subscribe = RelayBusConsumer;
127
+ function readConsumerMetadata(prototype, propertyKey) {
65
128
  return Reflect.getMetadata(SUBSCRIBE_METADATA_KEY, prototype, propertyKey) ?? [];
66
129
  }
67
130
 
68
131
  // src/handler-explorer.ts
69
132
  var RelayBusHandlerExplorer = class {
70
- constructor(discovery, metadataScanner, bus) {
133
+ constructor(discovery, metadataScanner, bus, modules) {
71
134
  this.discovery = discovery;
72
135
  this.metadataScanner = metadataScanner;
73
136
  this.bus = bus;
137
+ this.modules = modules;
74
138
  }
75
139
  discovery;
76
140
  metadataScanner;
77
141
  bus;
142
+ modules;
78
143
  onModuleInit() {
79
- const registeredBy = /* @__PURE__ */ new Map();
80
- const visited = /* @__PURE__ */ new Map();
81
- const consumers = /* @__PURE__ */ new WeakSet();
144
+ const discovery = {
145
+ registeredBy: /* @__PURE__ */ new Map(),
146
+ visited: /* @__PURE__ */ new Map(),
147
+ consumers: /* @__PURE__ */ new WeakSet(),
148
+ consumedByModule: /* @__PURE__ */ new Map()
149
+ };
82
150
  for (const wrapper of this.discovery.getProviders()) {
83
- if (wrapper.isTransient || !wrapper.isDependencyTreeStatic()) {
84
- this.assertNoHandlers(wrapper);
85
- continue;
86
- }
87
- const instance = wrapper.instance;
88
- if (typeof instance !== "object" || instance === null) {
89
- continue;
90
- }
91
- const prototype = Object.getPrototypeOf(instance);
92
- if (prototype === null) {
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 = [];
161
+ for (const wrapper of this.discovery.getProviders()) {
162
+ const contract = wrapper.instance;
163
+ if (!(contract instanceof RelayBusFeatureContract)) {
93
164
  continue;
94
165
  }
95
- const className = instance.constructor.name;
96
- for (const { methodName, declarations } of this.subscribedMethods(prototype)) {
97
- const seen = visited.get(instance) ?? /* @__PURE__ */ new Set();
98
- visited.set(instance, seen);
99
- if (seen.has(methodName)) {
100
- 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`);
101
170
  }
102
- seen.add(methodName);
103
- const method = instance[methodName];
104
- const location = `${className}.${methodName}`;
105
- for (const { event, options } of declarations) {
106
- const id = options.id ?? location;
107
- const previous = registeredBy.get(id);
108
- if (previous !== void 0) {
109
- throw new ConfigurationError(
110
- `Handler id '${id}' is used by both ${previous} and ${location}; pass a unique { id } to @Subscribe`
111
- );
112
- }
113
- registeredBy.set(id, location);
114
- this.bus.subscribe(
115
- event,
116
- (envelope, context) => method.call(instance, envelope, context),
117
- { ...options, id }
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`
118
174
  );
119
175
  }
120
176
  }
121
- if (!consumers.has(instance)) {
122
- consumers.add(instance);
123
- this.registerEventConsumers(instance, className, registeredBy);
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);
197
+ }
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);
124
203
  }
125
204
  }
126
205
  }
127
- registerEventConsumers(instance, className, registeredBy) {
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
+ }) {
128
262
  const lookup = instance;
129
- for (const { catalog, options, selectedEntries } of readEventConsumerMetadata(
263
+ for (const { catalog, options, selectedEntries } of readCatalogConsumerMetadata(
130
264
  instance.constructor
131
265
  )) {
132
266
  const { name, entries } = describeCatalog(catalog);
@@ -135,12 +269,12 @@ var RelayBusHandlerExplorer = class {
135
269
  const missing = handlers.filter((entry) => !isMethod(lookup, entry));
136
270
  if (missing.length > 0) {
137
271
  throw new ConfigurationError(
138
- `${className} uses @EventConsumer(${label}) but lacks the handler methods of events it consumes: ${missing.map((entry) => entry.handlerName).join(", ")}`
272
+ `${className} uses @RelayBusCatalogConsumer(${label}) but lacks the handler methods of events it consumes: ${missing.map((entry) => entry.handlerName).join(", ")}`
139
273
  );
140
274
  }
141
275
  if (handlers.length === 0) {
142
276
  throw new ConfigurationError(
143
- `${className} uses @EventConsumer(${label}) but defines none of its handler methods (${entries.map((entry) => entry.handlerName).join(", ")})`
277
+ `${className} uses @RelayBusCatalogConsumer(${label}) but defines none of its handler methods (${entries.map((entry) => entry.handlerName).join(", ")})`
144
278
  );
145
279
  }
146
280
  for (const entry of handlers) {
@@ -148,7 +282,7 @@ var RelayBusHandlerExplorer = class {
148
282
  const previous = registeredBy.get(id);
149
283
  if (previous !== void 0) {
150
284
  throw new ConfigurationError(
151
- `Handler id '${id}' of @EventConsumer(${label}) is already used by ${previous}; give the @Subscribe a unique { id } or drop it`
285
+ `Handler id '${id}' of @RelayBusCatalogConsumer(${label}) is already used by ${previous}; give the @RelayBusConsumer a unique { id } or drop it`
152
286
  );
153
287
  }
154
288
  registeredBy.set(id, `${className}.${entry.handlerName}`);
@@ -164,7 +298,7 @@ var RelayBusHandlerExplorer = class {
164
298
  subscribedMethods(prototype) {
165
299
  const methods = [];
166
300
  for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {
167
- const declarations = readSubscribeMetadata(prototype, methodName);
301
+ const declarations = readConsumerMetadata(prototype, methodName);
168
302
  if (declarations.length > 0) {
169
303
  methods.push({ methodName, declarations });
170
304
  }
@@ -178,16 +312,16 @@ var RelayBusHandlerExplorer = class {
178
312
  */
179
313
  assertNoHandlers(wrapper) {
180
314
  const type = wrapper.isFactory ? wrapper.token : wrapper.metatype;
181
- if (typeof type === "function" && readEventConsumerMetadata(type).length > 0) {
315
+ if (typeof type === "function" && readCatalogConsumerMetadata(type).length > 0) {
182
316
  throw new ConfigurationError(
183
- `${type.name} uses @EventConsumer but its provider is request-scoped or transient (directly or through a dependency); handlers must be singleton providers`
317
+ `${type.name} uses @RelayBusCatalogConsumer but its provider is request-scoped or transient (directly or through a dependency); handlers must be singleton providers`
184
318
  );
185
319
  }
186
320
  const prototype = typeof type === "function" ? type.prototype : null;
187
321
  const [first] = prototype === null ? [] : this.subscribedMethods(prototype);
188
322
  if (first !== void 0) {
189
323
  throw new ConfigurationError(
190
- `${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`
191
325
  );
192
326
  }
193
327
  }
@@ -196,7 +330,8 @@ RelayBusHandlerExplorer = __decorateClass([
196
330
  Injectable(),
197
331
  __decorateParam(0, Inject(DiscoveryService)),
198
332
  __decorateParam(1, Inject(MetadataScanner)),
199
- __decorateParam(2, Inject(RelayBus))
333
+ __decorateParam(2, Inject(RelayBus)),
334
+ __decorateParam(3, Inject(ModulesContainer))
200
335
  ], RelayBusHandlerExplorer);
201
336
  function isMethod(instance, entry) {
202
337
  return typeof instance[entry.handlerName] === "function";
@@ -257,18 +392,86 @@ var RelayBusLifecycle = class {
257
392
  this.bus = bus;
258
393
  }
259
394
  bus;
395
+ onModuleInit() {
396
+ registerBus(this.bus);
397
+ }
260
398
  async onApplicationBootstrap() {
261
399
  await this.bus.start();
262
400
  }
263
401
  async beforeApplicationShutdown() {
264
402
  await this.bus.stop();
265
403
  }
404
+ /** After the bus stopped, so handlers still draining at shutdown can open transactions. */
405
+ onApplicationShutdown() {
406
+ unregisterBus(this.bus);
407
+ }
266
408
  };
267
409
  RelayBusLifecycle = __decorateClass([
268
410
  Injectable(),
269
411
  __decorateParam(0, Inject(RelayBus))
270
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
271
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
+ }
272
475
  };
273
476
  RelayBusModule = __decorateClass([
274
477
  Module({
@@ -281,12 +484,31 @@ RelayBusModule = __decorateClass([
281
484
  },
282
485
  RelayBusHandlerExplorer,
283
486
  RelayBusLifecycle,
284
- RelayBusHealth
487
+ RelayBusHealth,
488
+ RelayBusTransactionHost
285
489
  ],
286
- exports: [RelayBus, RelayBusHealth]
490
+ exports: [RelayBus, RelayBusHealth, RelayBusTransactionHost]
287
491
  })
288
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
+ }
289
511
 
290
- export { EventConsumer, RelayBusHandlerExplorer, RelayBusHealth, RelayBusLifecycle, RelayBusModule, Subscribe };
512
+ export { EventConsumer, RelayBusCatalogConsumer, RelayBusConsumer, RelayBusFeatureContract, RelayBusFeatureModule, RelayBusHandlerExplorer, RelayBusHealth, RelayBusLifecycle, RelayBusModule, RelayBusTransaction, RelayBusTransactionHost, Subscribe };
291
513
  //# sourceMappingURL=index.js.map
292
514
  //# sourceMappingURL=index.js.map