@event-driven-io/emmett-esdb 0.36.0 → 0.38.0-alpha.1

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.cjs CHANGED
@@ -15,7 +15,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
15
15
  constructor(current, expected, message) {
16
16
  super({
17
17
  errorCode: 412,
18
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))
18
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))
19
19
  });
20
20
  this.current = current;
21
21
  this.expected = expected;
@@ -29,6 +29,7 @@ var _webstreamspolyfill = require('web-streams-polyfill');
29
29
 
30
30
 
31
31
 
32
+
32
33
  var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
33
34
 
34
35
 
@@ -60,7 +61,7 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
60
61
  };
61
62
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
62
63
  constructor(current, expected) {
63
- super(_optionalChain([current, 'optionalAccess', _3 => _3.toString, 'call', _4 => _4()]), _optionalChain([expected, 'optionalAccess', _5 => _5.toString, 'call', _6 => _6()]));
64
+ super(_optionalChain([current, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]), _optionalChain([expected, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]));
64
65
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
65
66
  }
66
67
  };
@@ -74,9 +75,9 @@ var NotifyAboutNoActiveReadersStream = (_class = class extends _webstreamspolyfi
74
75
  }
75
76
  });_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
76
77
  this.onNoActiveReaderCallback = onNoActiveReaderCallback;
77
- this.streamId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _7 => _7.streamId]), () => ( _uuid.v4.call(void 0, )));
78
+ this.streamId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.streamId]), () => ( _uuid.v4.call(void 0, )));
78
79
  this.onNoActiveReaderCallback = onNoActiveReaderCallback;
79
- this.startChecking(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.intervalCheckInMs]), () => ( 20)));
80
+ this.startChecking(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => ( 20)));
80
81
  }
81
82
  __init() {this.checkInterval = null}
82
83
 
@@ -102,14 +103,41 @@ var NotifyAboutNoActiveReadersStream = (_class = class extends _webstreamspolyfi
102
103
  }
103
104
  }
104
105
  }, _class);
106
+ var ParseError = class extends Error {
107
+ constructor(text) {
108
+ super(`Cannot parse! ${text}`);
109
+ }
110
+ };
111
+ var JSONParser = {
112
+ stringify: (value, options) => {
113
+ return JSON.stringify(
114
+ _optionalChain([options, 'optionalAccess', _10 => _10.map]) ? options.map(value) : value,
115
+ //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
116
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
117
+ (_, v) => typeof v === "bigint" ? v.toString() : v
118
+ );
119
+ },
120
+ parse: (text, options) => {
121
+ const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _11 => _11.reviver]));
122
+ if (_optionalChain([options, 'optionalAccess', _12 => _12.typeCheck]) && !_optionalChain([options, 'optionalAccess', _13 => _13.typeCheck, 'call', _14 => _14(parsed)]))
123
+ throw new ParseError(text);
124
+ return _optionalChain([options, 'optionalAccess', _15 => _15.map]) ? options.map(parsed) : parsed;
125
+ }
126
+ };
105
127
  var asyncRetry = async (fn, opts) => {
106
128
  if (opts === void 0 || opts.retries === 0) return fn();
107
129
  return _asyncretry2.default.call(void 0,
108
130
  async (bail) => {
109
131
  try {
110
- return await fn();
132
+ const result = await fn();
133
+ if (_optionalChain([opts, 'optionalAccess', _16 => _16.shouldRetryResult]) && opts.shouldRetryResult(result)) {
134
+ throw new EmmettError(
135
+ `Retrying because of result: ${JSONParser.stringify(result)}`
136
+ );
137
+ }
138
+ return result;
111
139
  } catch (error2) {
112
- if (_optionalChain([opts, 'optionalAccess', _9 => _9.shouldRetryError]) && !opts.shouldRetryError(error2)) {
140
+ if (_optionalChain([opts, 'optionalAccess', _17 => _17.shouldRetryError]) && !opts.shouldRetryError(error2)) {
113
141
  bail(error2);
114
142
  }
115
143
  throw error2;
@@ -348,7 +376,7 @@ var getEventStoreDBEventStore = (eventStore) => {
348
376
  return {
349
377
  async aggregateStream(streamName, options) {
350
378
  const { evolve, initialState, read } = options;
351
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _10 => _10.expectedStreamVersion]);
379
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _18 => _18.expectedStreamVersion]);
352
380
  let state = initialState();
353
381
  let currentStreamVersion = EventStoreDBEventStoreDefaultStreamVersion;
354
382
  let lastEventGlobalPosition = void 0;
@@ -360,7 +388,7 @@ var getEventStoreDBEventStore = (eventStore) => {
360
388
  if (!event) continue;
361
389
  state = evolve(state, mapFromESDBEvent(event));
362
390
  currentStreamVersion = event.revision;
363
- lastEventGlobalPosition = _optionalChain([event, 'access', _11 => _11.position, 'optionalAccess', _12 => _12.commit]);
391
+ lastEventGlobalPosition = _optionalChain([event, 'access', _19 => _19.position, 'optionalAccess', _20 => _20.commit]);
364
392
  }
365
393
  assertExpectedVersionMatchesCurrent(
366
394
  currentStreamVersion,
@@ -420,7 +448,7 @@ var getEventStoreDBEventStore = (eventStore) => {
420
448
  try {
421
449
  const serializedEvents = events.map(_dbclient.jsonEvent);
422
450
  const expectedRevision = toExpectedRevision(
423
- _optionalChain([options, 'optionalAccess', _13 => _13.expectedStreamVersion])
451
+ _optionalChain([options, 'optionalAccess', _21 => _21.expectedStreamVersion])
424
452
  );
425
453
  const appendResult = await eventStore.appendToStream(
426
454
  streamName,
@@ -490,45 +518,71 @@ var toStreamPosition = (startFrom) => startFrom === "BEGINNING" ? _dbclient.STAR
490
518
  var subscribe = (client, from, options) => from == void 0 || from.stream == $all ? client.subscribeToAll({
491
519
  fromPosition: toGlobalPosition(options.startFrom),
492
520
  filter: _dbclient.excludeSystemEvents.call(void 0, ),
493
- ..._nullishCoalesce(_optionalChain([from, 'optionalAccess', _14 => _14.options]), () => ( {}))
521
+ ..._nullishCoalesce(_optionalChain([from, 'optionalAccess', _22 => _22.options]), () => ( {}))
494
522
  }) : client.subscribeToStream(from.stream, {
495
523
  fromRevision: toStreamPosition(options.startFrom),
496
524
  ..._nullishCoalesce(from.options, () => ( {}))
497
525
  });
526
+ var isDatabaseUnavailableError = (error) => error instanceof Error && "type" in error && error.type === "unavailable" && "code" in error && error.code === 14;
527
+ var EventStoreDBResubscribeDefaultOptions = {
528
+ forever: true,
529
+ minTimeout: 100,
530
+ factor: 1.5,
531
+ shouldRetryError: (error) => !isDatabaseUnavailableError(error)
532
+ };
498
533
  var eventStoreDBSubscription = ({
499
534
  client,
500
535
  from,
501
536
  //batchSize,
502
- eachBatch
537
+ eachBatch,
538
+ resilience
503
539
  }) => {
504
540
  let isRunning = false;
505
541
  let start;
506
542
  let subscription;
507
- const pullMessages = async (options) => {
543
+ const resubscribeOptions = _nullishCoalesce(_optionalChain([resilience, 'optionalAccess', _23 => _23.resubscribeOptions]), () => ( {
544
+ ...EventStoreDBResubscribeDefaultOptions,
545
+ shouldRetryResult: () => isRunning,
546
+ shouldRetryError: (error) => isRunning && EventStoreDBResubscribeDefaultOptions.shouldRetryError(error)
547
+ }));
548
+ const pipeMessages = (options) => {
508
549
  subscription = subscribe(client, from, options);
509
- return new Promise((resolve, reject) => {
510
- _stream.finished.call(void 0,
511
- subscription.on("data", async (resolvedEvent) => {
512
- if (!resolvedEvent.event) return;
513
- const event = mapFromESDBEvent(
514
- resolvedEvent.event
515
- );
516
- const result = await eachBatch({ messages: [event] });
517
- if (result && result.type === "STOP") {
518
- await subscription.unsubscribe();
519
- }
520
- }),
521
- (error) => {
522
- if (!error) {
550
+ return asyncRetry(
551
+ () => new Promise((resolve, reject) => {
552
+ _stream.finished.call(void 0,
553
+ subscription.on("data", async (resolvedEvent) => {
554
+ if (!resolvedEvent.event) return;
555
+ const event = mapFromESDBEvent(
556
+ resolvedEvent.event
557
+ );
558
+ const result = await eachBatch({ messages: [event] });
559
+ if (result && result.type === "STOP") {
560
+ isRunning = false;
561
+ await subscription.unsubscribe();
562
+ }
563
+ from = {
564
+ stream: _nullishCoalesce(_optionalChain([from, 'optionalAccess', _24 => _24.stream]), () => ( $all)),
565
+ options: {
566
+ ..._nullishCoalesce(_optionalChain([from, 'optionalAccess', _25 => _25.options]), () => ( {})),
567
+ ...!from || _optionalChain([from, 'optionalAccess', _26 => _26.stream]) === $all ? {
568
+ fromPosition: resolvedEvent.event.position
569
+ } : { fromRevision: resolvedEvent.event.revision }
570
+ }
571
+ };
572
+ }),
573
+ (error) => {
574
+ if (error) {
575
+ console.error(`Received error: ${JSON.stringify(error)}.`);
576
+ reject(error);
577
+ return;
578
+ }
523
579
  console.info(`Stopping subscription.`);
524
580
  resolve();
525
- return;
526
581
  }
527
- console.error(`Received error: ${JSON.stringify(error)}.`);
528
- reject(error);
529
- }
530
- );
531
- });
582
+ );
583
+ }),
584
+ resubscribeOptions
585
+ );
532
586
  };
533
587
  return {
534
588
  get isRunning() {
@@ -538,14 +592,14 @@ var eventStoreDBSubscription = ({
538
592
  if (isRunning) return start;
539
593
  start = (async () => {
540
594
  isRunning = true;
541
- return pullMessages(options);
595
+ return pipeMessages(options);
542
596
  })();
543
597
  return start;
544
598
  },
545
599
  stop: async () => {
546
600
  if (!isRunning) return;
547
601
  isRunning = false;
548
- await _optionalChain([subscription, 'optionalAccess', _15 => _15.unsubscribe, 'call', _16 => _16()]);
602
+ await _optionalChain([subscription, 'optionalAccess', _27 => _27.unsubscribe, 'call', _28 => _28()]);
549
603
  await start;
550
604
  }
551
605
  };
@@ -579,7 +633,7 @@ var eventStoreDBEventStoreConsumer = (options) => {
579
633
  })
580
634
  );
581
635
  return result.some(
582
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _17 => _17.value, 'optionalAccess', _18 => _18.type]) !== "STOP"
636
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _29 => _29.value, 'optionalAccess', _30 => _30.type]) !== "STOP"
583
637
  ) ? void 0 : {
584
638
  type: "STOP"
585
639
  };
@@ -588,7 +642,8 @@ var eventStoreDBEventStoreConsumer = (options) => {
588
642
  client,
589
643
  from: options.from,
590
644
  eachBatch,
591
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _19 => _19.batchSize]), () => ( DefaultEventStoreDBEventStoreProcessorBatchSize))
645
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _31 => _31.batchSize]), () => ( DefaultEventStoreDBEventStoreProcessorBatchSize)),
646
+ resilience: options.resilience
592
647
  });
593
648
  const stop = async () => {
594
649
  if (!isRunning) return;
@@ -644,5 +699,7 @@ var eventStoreDBEventStoreConsumer = (options) => {
644
699
 
645
700
 
646
701
 
647
- exports.$all = $all; exports.DefaultEventStoreDBEventStoreProcessorBatchSize = DefaultEventStoreDBEventStoreProcessorBatchSize; exports.DefaultEventStoreDBEventStoreProcessorPullingFrequencyInMs = DefaultEventStoreDBEventStoreProcessorPullingFrequencyInMs; exports.EventStoreDBEventStoreDefaultStreamVersion = EventStoreDBEventStoreDefaultStreamVersion; exports.EventStoreDBEventStoreProcessor = EventStoreDBEventStoreProcessor; exports.eventStoreDBEventStoreConsumer = eventStoreDBEventStoreConsumer; exports.eventStoreDBEventStoreProcessor = eventStoreDBEventStoreProcessor; exports.eventStoreDBSubscription = eventStoreDBSubscription; exports.getEventStoreDBEventStore = getEventStoreDBEventStore; exports.mapFromESDBEvent = mapFromESDBEvent; exports.zipEventStoreDBEventStoreMessageBatchPullerStartFrom = zipEventStoreDBEventStoreMessageBatchPullerStartFrom;
702
+
703
+
704
+ exports.$all = $all; exports.DefaultEventStoreDBEventStoreProcessorBatchSize = DefaultEventStoreDBEventStoreProcessorBatchSize; exports.DefaultEventStoreDBEventStoreProcessorPullingFrequencyInMs = DefaultEventStoreDBEventStoreProcessorPullingFrequencyInMs; exports.EventStoreDBEventStoreDefaultStreamVersion = EventStoreDBEventStoreDefaultStreamVersion; exports.EventStoreDBEventStoreProcessor = EventStoreDBEventStoreProcessor; exports.EventStoreDBResubscribeDefaultOptions = EventStoreDBResubscribeDefaultOptions; exports.eventStoreDBEventStoreConsumer = eventStoreDBEventStoreConsumer; exports.eventStoreDBEventStoreProcessor = eventStoreDBEventStoreProcessor; exports.eventStoreDBSubscription = eventStoreDBSubscription; exports.getEventStoreDBEventStore = getEventStoreDBEventStore; exports.isDatabaseUnavailableError = isDatabaseUnavailableError; exports.mapFromESDBEvent = mapFromESDBEvent; exports.zipEventStoreDBEventStoreMessageBatchPullerStartFrom = zipEventStoreDBEventStoreMessageBatchPullerStartFrom;
648
705
  //# sourceMappingURL=index.cjs.map