@event-driven-io/emmett-postgresql 0.43.0-alpha.4 → 0.43.0-beta.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
@@ -1,178 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/eventStore/schema/readLastMessageGlobalPosition.ts
2
- var _dumbo = require('@event-driven-io/dumbo');
3
-
4
- // src/eventStore/schema/typing.ts
5
- var emmettPrefix = "emt";
6
- var globalTag = "global";
7
- var defaultTag = `${emmettPrefix}:default`;
8
- var unknownTag = `${emmettPrefix}:unknown`;
9
- var globalNames = {
10
- module: `${emmettPrefix}:module:${globalTag}`,
11
- tenant: `${emmettPrefix}:tenant:${globalTag}`
12
- };
13
- var columns = {
14
- partition: {
15
- name: "partition"
16
- },
17
- isArchived: { name: "is_archived" }
18
- };
19
- var streamsTable = {
20
- name: `${emmettPrefix}_streams`,
21
- columns: {
22
- partition: columns.partition,
23
- isArchived: columns.isArchived
24
- }
25
- };
26
- var messagesTable = {
27
- name: `${emmettPrefix}_messages`,
28
- columns: {
29
- partition: columns.partition,
30
- isArchived: columns.isArchived
31
- }
32
- };
33
- var processorsTable = {
34
- name: `${emmettPrefix}_processors`
35
- };
36
- var projectionsTable = {
37
- name: `${emmettPrefix}_projections`
38
- };
39
-
40
- // src/eventStore/schema/readLastMessageGlobalPosition.ts
41
- var readLastMessageGlobalPosition = async (execute, options) => {
42
- const result = await _dumbo.singleOrNull.call(void 0,
43
- execute.query(
44
- _dumbo.SQL`SELECT global_position
45
- FROM ${_dumbo.SQL.identifier(messagesTable.name)}
46
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.partition]), () => ( defaultTag))} AND is_archived = FALSE AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())
47
- ORDER BY transaction_id, global_position
48
- LIMIT 1`
49
- )
50
- );
51
- return {
52
- currentGlobalPosition: result !== null ? BigInt(result.global_position) : null
53
- };
54
- };
55
-
56
- // src/eventStore/schema/readMessagesBatch.ts
57
-
58
- var readMessagesBatch = async (execute, options) => {
59
- const from = "from" in options ? options.from : "after" in options ? options.after + 1n : 0n;
60
- const batchSize = options && "batchSize" in options ? options.batchSize : options.to - options.from;
61
- const fromCondition = from !== -0n ? `AND global_position >= ${from}` : "";
62
- const toCondition = "to" in options ? `AND global_position <= ${options.to}` : "";
63
- const limitCondition = "batchSize" in options ? `LIMIT ${options.batchSize}` : "";
64
- const messages = await _dumbo.mapRows.call(void 0,
65
- execute.query(
66
- _dumbo.SQL`
67
- SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
68
- FROM ${_dumbo.SQL.identifier(messagesTable.name)}
69
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.partition]), () => ( defaultTag))} AND is_archived = FALSE AND transaction_id < pg_snapshot_xmin(pg_current_snapshot()) ${_dumbo.SQL.plain(fromCondition)} ${_dumbo.SQL.plain(toCondition)}
70
- ORDER BY transaction_id, global_position
71
- ${_dumbo.SQL.plain(limitCondition)}`
72
- ),
73
- (row) => {
74
- const rawEvent = {
75
- type: row.message_type,
76
- data: row.message_data,
77
- metadata: row.message_metadata
78
- };
79
- const metadata = {
80
- ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
81
- messageId: row.message_id,
82
- streamName: row.stream_id,
83
- streamPosition: BigInt(row.stream_position),
84
- globalPosition: BigInt(row.global_position)
85
- };
86
- return {
87
- ...rawEvent,
88
- kind: "Event",
89
- metadata
90
- };
91
- }
92
- );
93
- return messages.length > 0 ? {
94
- currentGlobalPosition: messages[messages.length - 1].metadata.globalPosition,
95
- messages,
96
- areMessagesLeft: messages.length === batchSize
97
- } : {
98
- currentGlobalPosition: "from" in options ? options.from : "after" in options ? options.after : 0n,
99
- messages: [],
100
- areMessagesLeft: false
101
- };
102
- };
103
-
104
- // src/eventStore/consumers/messageBatchProcessing/index.ts
105
- var DefaultPostgreSQLEventStoreProcessorBatchSize = 100;
106
- var DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs = 50;
107
- var postgreSQLEventStoreMessageBatchPuller = ({
108
- executor,
109
- batchSize,
110
- eachBatch,
111
- pullingFrequencyInMs,
112
- stopWhen,
113
- signal
114
- }) => {
115
- let isRunning = false;
116
- let start;
117
- const pullMessages = async (options) => {
118
- const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await readLastMessageGlobalPosition(executor)).currentGlobalPosition, async () => ( 0n)) : options.startFrom.lastCheckpoint;
119
- const readMessagesOptions = {
120
- after,
121
- batchSize
122
- };
123
- let waitTime = 100;
124
- while (isRunning && !_optionalChain([signal, 'optionalAccess', _4 => _4.aborted])) {
125
- const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
126
- if (messages.length > 0) {
127
- const result = await eachBatch(messages);
128
- if (result && result.type === "STOP") {
129
- isRunning = false;
130
- break;
131
- }
132
- }
133
- readMessagesOptions.after = currentGlobalPosition;
134
- await new Promise((resolve) => setTimeout(resolve, waitTime));
135
- if (_optionalChain([stopWhen, 'optionalAccess', _5 => _5.noMessagesLeft]) === true && !areMessagesLeft) {
136
- isRunning = false;
137
- break;
138
- }
139
- if (!areMessagesLeft) {
140
- waitTime = Math.min(waitTime * 2, 1e3);
141
- } else {
142
- waitTime = pullingFrequencyInMs;
143
- }
144
- }
145
- };
146
- return {
147
- get isRunning() {
148
- return isRunning;
149
- },
150
- start: (options) => {
151
- if (isRunning) return start;
152
- isRunning = true;
153
- start = (async () => {
154
- return pullMessages(options);
155
- })();
156
- return start;
157
- },
158
- stop: async () => {
159
- if (!isRunning) return;
160
- isRunning = false;
161
- await start;
162
- }
163
- };
164
- };
165
- var zipPostgreSQLEventStoreMessageBatchPullerStartFrom = (options) => {
166
- if (options.length === 0 || options.some((o) => o === void 0 || o === "BEGINNING"))
167
- return "BEGINNING";
168
- if (options.every((o) => o === "END")) return "END";
169
- return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
170
- };
171
-
172
- // src/eventStore/consumers/postgreSQLEventStoreConsumer.ts
173
-
174
-
175
- // ../emmett/dist/chunk-AZDDB5SF.js
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// ../emmett/dist/chunk-AZDDB5SF.js
176
2
  var isNumber = (val) => typeof val === "number" && val === val;
177
3
  var isBigint = (val) => typeof val === "bigint" && val === val;
178
4
  var isString = (val) => typeof val === "string";
@@ -213,7 +39,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
213
39
  constructor(current, expected, message) {
214
40
  super({
215
41
  errorCode: EmmettError.Codes.ConcurrencyError,
216
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])}`))
42
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))
217
43
  });
218
44
  this.current = current;
219
45
  this.expected = expected;
@@ -227,9 +53,9 @@ var _uuid = require('uuid');
227
53
  var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
228
54
 
229
55
 
230
- var emmettPrefix2 = "emt";
231
- var defaultTag2 = `${emmettPrefix2}:default`;
232
- var unknownTag2 = `${emmettPrefix2}:unknown`;
56
+ var emmettPrefix = "emt";
57
+ var defaultTag = `${emmettPrefix}:default`;
58
+ var unknownTag = `${emmettPrefix}:unknown`;
233
59
  var STREAM_EXISTS = "STREAM_EXISTS";
234
60
  var STREAM_DOES_NOT_EXIST = "STREAM_DOES_NOT_EXIST";
235
61
  var NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
@@ -246,7 +72,7 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
246
72
  };
247
73
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
248
74
  constructor(current, expected) {
249
- super(_optionalChain([current, 'optionalAccess', _8 => _8.toString, 'call', _9 => _9()]), _optionalChain([expected, 'optionalAccess', _10 => _10.toString, 'call', _11 => _11()]));
75
+ super(_optionalChain([current, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]), _optionalChain([expected, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]));
250
76
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
251
77
  }
252
78
  };
@@ -463,17 +289,17 @@ var ParseError = class extends Error {
463
289
  var JSONParser = {
464
290
  stringify: (value, options) => {
465
291
  return JSON.stringify(
466
- _optionalChain([options, 'optionalAccess', _12 => _12.map]) ? options.map(value) : value,
292
+ _optionalChain([options, 'optionalAccess', _8 => _8.map]) ? options.map(value) : value,
467
293
  //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
468
294
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
469
295
  (_, v) => typeof v === "bigint" ? v.toString() : v
470
296
  );
471
297
  },
472
298
  parse: (text, options) => {
473
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _13 => _13.reviver]));
474
- if (_optionalChain([options, 'optionalAccess', _14 => _14.typeCheck]) && !_optionalChain([options, 'optionalAccess', _15 => _15.typeCheck, 'call', _16 => _16(parsed)]))
299
+ const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _9 => _9.reviver]));
300
+ if (_optionalChain([options, 'optionalAccess', _10 => _10.typeCheck]) && !_optionalChain([options, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(parsed)]))
475
301
  throw new ParseError(text);
476
- return _optionalChain([options, 'optionalAccess', _17 => _17.map]) ? options.map(parsed) : parsed;
302
+ return _optionalChain([options, 'optionalAccess', _13 => _13.map]) ? options.map(parsed) : parsed;
477
303
  }
478
304
  };
479
305
  var asyncRetry = async (fn, opts) => {
@@ -482,14 +308,14 @@ var asyncRetry = async (fn, opts) => {
482
308
  async (bail) => {
483
309
  try {
484
310
  const result = await fn();
485
- if (_optionalChain([opts, 'optionalAccess', _18 => _18.shouldRetryResult]) && opts.shouldRetryResult(result)) {
311
+ if (_optionalChain([opts, 'optionalAccess', _14 => _14.shouldRetryResult]) && opts.shouldRetryResult(result)) {
486
312
  throw new EmmettError(
487
313
  `Retrying because of result: ${JSONParser.stringify(result)}`
488
314
  );
489
315
  }
490
316
  return result;
491
317
  } catch (error2) {
492
- if (_optionalChain([opts, 'optionalAccess', _19 => _19.shouldRetryError]) && !opts.shouldRetryError(error2)) {
318
+ if (_optionalChain([opts, 'optionalAccess', _15 => _15.shouldRetryError]) && !opts.shouldRetryError(error2)) {
493
319
  bail(error2);
494
320
  return void 0;
495
321
  }
@@ -534,190 +360,22 @@ var hashText = async (text) => {
534
360
  const view = new BigInt64Array(hashBuffer, 0, 1);
535
361
  return view[0];
536
362
  };
537
- var AssertionError = class extends Error {
538
- constructor(message2) {
539
- super(message2);
540
- }
541
- };
542
- var isSubset = (superObj, subObj) => {
543
- const sup = superObj;
544
- const sub = subObj;
545
- assertOk(sup);
546
- assertOk(sub);
547
- return Object.keys(sub).every((ele) => {
548
- if (typeof sub[ele] == "object") {
549
- return isSubset(sup[ele], sub[ele]);
550
- }
551
- return sub[ele] === sup[ele];
552
- });
363
+ var getCheckpoint = (message2) => {
364
+ return message2.metadata.checkpoint;
553
365
  };
554
- var assertFails = (message2) => {
555
- throw new AssertionError(_nullishCoalesce(message2, () => ( "That should not ever happened, right?")));
366
+ var wasMessageHandled = (message2, checkpoint) => {
367
+ const messageCheckpoint = getCheckpoint(message2);
368
+ return messageCheckpoint !== null && messageCheckpoint !== void 0 && checkpoint !== null && checkpoint !== void 0 && messageCheckpoint <= checkpoint;
556
369
  };
557
- var assertDeepEqual = (actual, expected, message2) => {
558
- if (!deepEquals(actual, expected))
559
- throw new AssertionError(
560
- _nullishCoalesce(message2, () => ( `subObj:
561
- ${JSONParser.stringify(expected)}
562
- is not equal to
563
- ${JSONParser.stringify(actual)}`))
564
- );
565
- };
566
- function assertTrue(condition, message2) {
567
- if (condition !== true)
568
- throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is false`)));
569
- }
570
- function assertOk(obj, message2) {
571
- if (!obj) throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is not truthy`)));
572
- }
573
- function assertEqual(expected, actual, message2) {
574
- if (expected !== actual)
575
- throw new AssertionError(
576
- `${_nullishCoalesce(message2, () => ( "Objects are not equal"))}:
577
- Expected: ${JSONParser.stringify(expected)}
578
- Actual: ${JSONParser.stringify(actual)}`
579
- );
580
- }
581
- function assertNotEqual(obj, other, message2) {
582
- if (obj === other)
583
- throw new AssertionError(
584
- _nullishCoalesce(message2, () => ( `Objects are equal: ${JSONParser.stringify(obj)}`))
585
- );
586
- }
587
- function assertIsNotNull(result) {
588
- assertNotEqual(result, null);
589
- assertOk(result);
590
- }
591
- var assertThatArray = (array) => {
592
- return {
593
- isEmpty: () => assertEqual(
594
- array.length,
595
- 0,
596
- `Array is not empty ${JSONParser.stringify(array)}`
597
- ),
598
- isNotEmpty: () => assertNotEqual(array.length, 0, `Array is empty`),
599
- hasSize: (length) => assertEqual(array.length, length),
600
- containsElements: (other) => {
601
- assertTrue(other.every((ts) => array.some((o) => deepEquals(ts, o))));
602
- },
603
- containsElementsMatching: (other) => {
604
- assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
605
- },
606
- containsOnlyElementsMatching: (other) => {
607
- assertEqual(array.length, other.length, `Arrays lengths don't match`);
608
- assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
609
- },
610
- containsExactlyInAnyOrder: (other) => {
611
- assertEqual(array.length, other.length);
612
- assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
613
- },
614
- containsExactlyInAnyOrderElementsOf: (other) => {
615
- assertEqual(array.length, other.length);
616
- assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
617
- },
618
- containsExactlyElementsOf: (other) => {
619
- assertEqual(array.length, other.length);
620
- for (let i = 0; i < array.length; i++) {
621
- assertTrue(deepEquals(array[i], other[i]));
622
- }
623
- },
624
- containsExactly: (elem) => {
625
- assertEqual(array.length, 1);
626
- assertTrue(deepEquals(array[0], elem));
627
- },
628
- contains: (elem) => {
629
- assertTrue(array.some((a) => deepEquals(a, elem)));
630
- },
631
- containsOnlyOnceElementsOf: (other) => {
632
- assertTrue(
633
- other.map((o) => array.filter((a) => deepEquals(a, o)).length).filter((a) => a === 1).length === other.length
634
- );
635
- },
636
- containsAnyOf: (other) => {
637
- assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));
638
- },
639
- allMatch: (matches) => {
640
- assertTrue(array.every(matches));
641
- },
642
- anyMatches: (matches) => {
643
- assertTrue(array.some(matches));
644
- },
645
- allMatchAsync: async (matches) => {
646
- for (const item of array) {
647
- assertTrue(await matches(item));
648
- }
649
- }
650
- };
651
- };
652
- var downcastRecordedMessage = (recordedMessage, options) => {
653
- if (!_optionalChain([options, 'optionalAccess', _20 => _20.downcast]))
654
- return recordedMessage;
655
- const downcasted = options.downcast(
656
- recordedMessage
657
- );
658
- return {
659
- ...recordedMessage,
660
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
661
- data: downcasted.data,
662
- ..."metadata" in recordedMessage || "metadata" in downcasted ? {
663
- metadata: {
664
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
665
- ..."metadata" in downcasted ? downcasted.metadata : {}
666
- }
667
- } : {}
668
- };
669
- };
670
- var downcastRecordedMessages = (recordedMessages, options) => {
671
- if (!_optionalChain([options, 'optionalAccess', _21 => _21.downcast]))
672
- return recordedMessages;
673
- return recordedMessages.map(
674
- (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
675
- );
676
- };
677
- var upcastRecordedMessage = (recordedMessage, options) => {
678
- if (!_optionalChain([options, 'optionalAccess', _22 => _22.upcast]))
679
- return recordedMessage;
680
- const upcasted = options.upcast(
681
- recordedMessage
682
- );
683
- return {
684
- ...recordedMessage,
685
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
686
- data: upcasted.data,
687
- ..."metadata" in recordedMessage || "metadata" in upcasted ? {
688
- metadata: {
689
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
690
- ..."metadata" in upcasted ? upcasted.metadata : {}
691
- }
692
- } : {}
693
- };
694
- };
695
- var getCheckpoint = (message2) => {
696
- return "checkpoint" in message2.metadata ? (
697
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
698
- message2.metadata.checkpoint
699
- ) : "globalPosition" in message2.metadata && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
700
- isBigint(message2.metadata.globalPosition) ? (
701
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
702
- message2.metadata.globalPosition
703
- ) : "streamPosition" in message2.metadata && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
704
- isBigint(message2.metadata.streamPosition) ? (
705
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
706
- message2.metadata.streamPosition
707
- ) : null;
708
- };
709
- var wasMessageHandled = (message2, checkpoint) => {
710
- const messageCheckpoint = getCheckpoint(message2);
711
- const checkpointBigint = checkpoint;
712
- return messageCheckpoint !== null && messageCheckpoint !== void 0 && checkpointBigint !== null && checkpointBigint !== void 0 && messageCheckpoint <= checkpointBigint;
713
- };
714
- var MessageProcessorType = {
715
- PROJECTOR: "projector",
716
- REACTOR: "reactor"
370
+ var MessageProcessorType = {
371
+ PROJECTOR: "projector",
372
+ REACTOR: "reactor"
717
373
  };
718
374
  var defaultProcessingMessageProcessingScope = (handler, partialContext) => handler(partialContext);
375
+ var bigIntProcessorCheckpoint = (value) => bigInt.toNormalizedString(value);
376
+ var parseBigIntProcessorCheckpoint = (value) => BigInt(value);
719
377
  var defaultProcessorVersion = 1;
720
- var defaultProcessorPartition = defaultTag2;
378
+ var defaultProcessorPartition = defaultTag;
721
379
  var getProcessorInstanceId = (processorId) => `${processorId}:${_uuid.v7.call(void 0, )}`;
722
380
  var getProjectorId = (options) => `emt:processor:projector:${options.projectionName}`;
723
381
  var reactor = (options) => {
@@ -781,7 +439,7 @@ var reactor = (options) => {
781
439
  }
782
440
  if (startFrom && startFrom !== "CURRENT") return startFrom;
783
441
  if (checkpoints) {
784
- const readResult = await _optionalChain([checkpoints, 'optionalAccess', _23 => _23.read, 'call', _24 => _24(
442
+ const readResult = await _optionalChain([checkpoints, 'optionalAccess', _16 => _16.read, 'call', _17 => _17(
785
443
  {
786
444
  processorId,
787
445
  partition
@@ -809,7 +467,7 @@ var reactor = (options) => {
809
467
  const upcasted = upcastRecordedMessage(
810
468
  // TODO: Make it smarter
811
469
  message2,
812
- _optionalChain([options, 'access', _25 => _25.messageOptions, 'optionalAccess', _26 => _26.schema, 'optionalAccess', _27 => _27.versioning])
470
+ _optionalChain([options, 'access', _18 => _18.messageOptions, 'optionalAccess', _19 => _19.schema, 'optionalAccess', _20 => _20.versioning])
813
471
  );
814
472
  if (canHandle !== void 0 && !canHandle.includes(upcasted.type))
815
473
  continue;
@@ -842,49 +500,381 @@ var reactor = (options) => {
842
500
  if (messageProcessingResult && messageProcessingResult.type === "SKIP")
843
501
  continue;
844
502
  }
845
- return result;
846
- }, partialContext);
503
+ return result;
504
+ }, partialContext);
505
+ }
506
+ };
507
+ };
508
+ var projector = (options) => {
509
+ const {
510
+ projection: projection2,
511
+ processorId = getProjectorId({
512
+ projectionName: _nullishCoalesce(projection2.name, () => ( "unknown"))
513
+ }),
514
+ ...rest
515
+ } = options;
516
+ return reactor({
517
+ ...rest,
518
+ type: MessageProcessorType.PROJECTOR,
519
+ canHandle: projection2.canHandle,
520
+ processorId,
521
+ messageOptions: options.projection.eventsOptions,
522
+ hooks: {
523
+ onInit: _optionalChain([options, 'access', _21 => _21.hooks, 'optionalAccess', _22 => _22.onInit]),
524
+ onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _23 => _23.hooks, 'optionalAccess', _24 => _24.onStart]) ? async (context) => {
525
+ if (options.truncateOnStart && options.projection.truncate)
526
+ await options.projection.truncate(context);
527
+ if (_optionalChain([options, 'access', _25 => _25.hooks, 'optionalAccess', _26 => _26.onStart])) await _optionalChain([options, 'access', _27 => _27.hooks, 'optionalAccess', _28 => _28.onStart, 'call', _29 => _29(context)]);
528
+ } : void 0,
529
+ onClose: _optionalChain([options, 'access', _30 => _30.hooks, 'optionalAccess', _31 => _31.onClose])
530
+ },
531
+ eachMessage: async (event2, context) => projection2.handle([event2], context)
532
+ });
533
+ };
534
+ var AssertionError = class extends Error {
535
+ constructor(message2) {
536
+ super(message2);
537
+ }
538
+ };
539
+ var isSubset = (superObj, subObj) => {
540
+ const sup = superObj;
541
+ const sub = subObj;
542
+ assertOk(sup);
543
+ assertOk(sub);
544
+ return Object.keys(sub).every((ele) => {
545
+ if (sub[ele] !== null && typeof sub[ele] == "object") {
546
+ return isSubset(sup[ele], sub[ele]);
547
+ }
548
+ return sub[ele] === sup[ele];
549
+ });
550
+ };
551
+ var assertFails = (message2) => {
552
+ throw new AssertionError(_nullishCoalesce(message2, () => ( "That should not ever happened, right?")));
553
+ };
554
+ var assertDeepEqual = (actual, expected, message2) => {
555
+ if (!deepEquals(actual, expected))
556
+ throw new AssertionError(
557
+ _nullishCoalesce(message2, () => ( `subObj:
558
+ ${JSONParser.stringify(expected)}
559
+ is not equal to
560
+ ${JSONParser.stringify(actual)}`))
561
+ );
562
+ };
563
+ function assertTrue(condition, message2) {
564
+ if (condition !== true)
565
+ throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is false`)));
566
+ }
567
+ function assertOk(obj, message2) {
568
+ if (!obj) throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is not truthy`)));
569
+ }
570
+ function assertEqual(expected, actual, message2) {
571
+ if (expected !== actual)
572
+ throw new AssertionError(
573
+ `${_nullishCoalesce(message2, () => ( "Objects are not equal"))}:
574
+ Expected: ${JSONParser.stringify(expected)}
575
+ Actual: ${JSONParser.stringify(actual)}`
576
+ );
577
+ }
578
+ function assertNotEqual(obj, other, message2) {
579
+ if (obj === other)
580
+ throw new AssertionError(
581
+ _nullishCoalesce(message2, () => ( `Objects are equal: ${JSONParser.stringify(obj)}`))
582
+ );
583
+ }
584
+ function assertIsNotNull(result) {
585
+ assertNotEqual(result, null);
586
+ assertOk(result);
587
+ }
588
+ var assertThatArray = (array) => {
589
+ return {
590
+ isEmpty: () => assertEqual(
591
+ array.length,
592
+ 0,
593
+ `Array is not empty ${JSONParser.stringify(array)}`
594
+ ),
595
+ isNotEmpty: () => assertNotEqual(array.length, 0, `Array is empty`),
596
+ hasSize: (length) => assertEqual(array.length, length),
597
+ containsElements: (other) => {
598
+ assertTrue(other.every((ts) => array.some((o) => deepEquals(ts, o))));
599
+ },
600
+ containsElementsMatching: (other) => {
601
+ assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
602
+ },
603
+ containsOnlyElementsMatching: (other) => {
604
+ assertEqual(array.length, other.length, `Arrays lengths don't match`);
605
+ assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
606
+ },
607
+ containsExactlyInAnyOrder: (other) => {
608
+ assertEqual(array.length, other.length);
609
+ assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
610
+ },
611
+ containsExactlyInAnyOrderElementsOf: (other) => {
612
+ assertEqual(array.length, other.length);
613
+ assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
614
+ },
615
+ containsExactlyElementsOf: (other) => {
616
+ assertEqual(array.length, other.length);
617
+ for (let i = 0; i < array.length; i++) {
618
+ assertTrue(deepEquals(array[i], other[i]));
619
+ }
620
+ },
621
+ containsExactly: (elem) => {
622
+ assertEqual(array.length, 1);
623
+ assertTrue(deepEquals(array[0], elem));
624
+ },
625
+ contains: (elem) => {
626
+ assertTrue(array.some((a) => deepEquals(a, elem)));
627
+ },
628
+ containsOnlyOnceElementsOf: (other) => {
629
+ assertTrue(
630
+ other.map((o) => array.filter((a) => deepEquals(a, o)).length).filter((a) => a === 1).length === other.length
631
+ );
632
+ },
633
+ containsAnyOf: (other) => {
634
+ assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));
635
+ },
636
+ allMatch: (matches) => {
637
+ assertTrue(array.every(matches));
638
+ },
639
+ anyMatches: (matches) => {
640
+ assertTrue(array.some(matches));
641
+ },
642
+ allMatchAsync: async (matches) => {
643
+ for (const item of array) {
644
+ assertTrue(await matches(item));
645
+ }
646
+ }
647
+ };
648
+ };
649
+ var downcastRecordedMessage = (recordedMessage, options) => {
650
+ if (!_optionalChain([options, 'optionalAccess', _32 => _32.downcast]))
651
+ return recordedMessage;
652
+ const downcasted = options.downcast(
653
+ recordedMessage
654
+ );
655
+ return {
656
+ ...recordedMessage,
657
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
658
+ data: downcasted.data,
659
+ ..."metadata" in recordedMessage || "metadata" in downcasted ? {
660
+ metadata: {
661
+ ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
662
+ ..."metadata" in downcasted ? downcasted.metadata : {}
663
+ }
664
+ } : {}
665
+ };
666
+ };
667
+ var downcastRecordedMessages = (recordedMessages, options) => {
668
+ if (!_optionalChain([options, 'optionalAccess', _33 => _33.downcast]))
669
+ return recordedMessages;
670
+ return recordedMessages.map(
671
+ (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
672
+ );
673
+ };
674
+ var upcastRecordedMessage = (recordedMessage, options) => {
675
+ if (!_optionalChain([options, 'optionalAccess', _34 => _34.upcast]))
676
+ return recordedMessage;
677
+ const upcasted = options.upcast(
678
+ recordedMessage
679
+ );
680
+ return {
681
+ ...recordedMessage,
682
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
683
+ data: upcasted.data,
684
+ ..."metadata" in recordedMessage || "metadata" in upcasted ? {
685
+ metadata: {
686
+ ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
687
+ ..."metadata" in upcasted ? upcasted.metadata : {}
688
+ }
689
+ } : {}
690
+ };
691
+ };
692
+ var projection = (definition) => definition;
693
+
694
+ // src/eventStore/schema/readLastMessageGlobalPosition.ts
695
+ var _dumbo = require('@event-driven-io/dumbo');
696
+
697
+ // src/eventStore/schema/typing.ts
698
+ var emmettPrefix2 = "emt";
699
+ var globalTag = "global";
700
+ var defaultTag2 = `${emmettPrefix2}:default`;
701
+ var unknownTag2 = `${emmettPrefix2}:unknown`;
702
+ var globalNames = {
703
+ module: `${emmettPrefix2}:module:${globalTag}`,
704
+ tenant: `${emmettPrefix2}:tenant:${globalTag}`
705
+ };
706
+ var columns = {
707
+ partition: {
708
+ name: "partition"
709
+ },
710
+ isArchived: { name: "is_archived" }
711
+ };
712
+ var streamsTable = {
713
+ name: `${emmettPrefix2}_streams`,
714
+ columns: {
715
+ partition: columns.partition,
716
+ isArchived: columns.isArchived
717
+ }
718
+ };
719
+ var messagesTable = {
720
+ name: `${emmettPrefix2}_messages`,
721
+ columns: {
722
+ partition: columns.partition,
723
+ isArchived: columns.isArchived
724
+ }
725
+ };
726
+ var processorsTable = {
727
+ name: `${emmettPrefix2}_processors`
728
+ };
729
+ var projectionsTable = {
730
+ name: `${emmettPrefix2}_projections`
731
+ };
732
+
733
+ // src/eventStore/schema/readLastMessageGlobalPosition.ts
734
+ var readLastMessageGlobalPosition = async (execute, options) => {
735
+ const result = await _dumbo.singleOrNull.call(void 0,
736
+ execute.query(
737
+ _dumbo.SQL`SELECT global_position
738
+ FROM ${_dumbo.SQL.identifier(messagesTable.name)}
739
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.partition]), () => ( defaultTag2))} AND is_archived = FALSE AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())
740
+ ORDER BY transaction_id, global_position
741
+ LIMIT 1`
742
+ )
743
+ );
744
+ return {
745
+ currentGlobalPosition: result !== null ? BigInt(result.global_position) : null
746
+ };
747
+ };
748
+
749
+ // src/eventStore/schema/readMessagesBatch.ts
750
+
751
+ var readMessagesBatch = async (execute, options) => {
752
+ const from = "from" in options ? options.from : void 0;
753
+ const after = "after" in options ? options.after : void 0;
754
+ const batchSize = "batchSize" in options ? options.batchSize : options.to - options.from;
755
+ const fromCondition = from !== void 0 ? _dumbo.SQL`AND global_position >= ${from}` : after !== void 0 ? _dumbo.SQL`AND global_position > ${after}` : _dumbo.SQL.EMPTY;
756
+ const toCondition = "to" in options ? _dumbo.SQL`AND global_position <= ${options.to}` : _dumbo.SQL.EMPTY;
757
+ const limitCondition = "batchSize" in options ? _dumbo.SQL`LIMIT ${options.batchSize}` : _dumbo.SQL.EMPTY;
758
+ const messages = await _dumbo.mapRows.call(void 0,
759
+ execute.query(
760
+ _dumbo.SQL`
761
+ SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
762
+ FROM ${_dumbo.SQL.identifier(messagesTable.name)}
763
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.partition]), () => ( defaultTag2))} AND is_archived = FALSE AND transaction_id < pg_snapshot_xmin(pg_current_snapshot()) ${fromCondition} ${toCondition}
764
+ ORDER BY transaction_id, global_position
765
+ ${limitCondition}`
766
+ ),
767
+ (row) => {
768
+ const rawEvent = {
769
+ type: row.message_type,
770
+ data: row.message_data,
771
+ metadata: row.message_metadata
772
+ };
773
+ const metadata = {
774
+ ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
775
+ messageId: row.message_id,
776
+ streamName: row.stream_id,
777
+ streamPosition: BigInt(row.stream_position),
778
+ globalPosition: BigInt(row.global_position),
779
+ checkpoint: bigIntProcessorCheckpoint(BigInt(row.global_position))
780
+ };
781
+ return {
782
+ ...rawEvent,
783
+ kind: "Event",
784
+ metadata
785
+ };
786
+ }
787
+ );
788
+ return messages.length > 0 ? {
789
+ currentGlobalPosition: messages[messages.length - 1].metadata.globalPosition,
790
+ messages,
791
+ areMessagesLeft: messages.length === batchSize
792
+ } : {
793
+ currentGlobalPosition: "from" in options ? options.from : "after" in options ? options.after : 0n,
794
+ messages: [],
795
+ areMessagesLeft: false
796
+ };
797
+ };
798
+
799
+ // src/eventStore/consumers/messageBatchProcessing/index.ts
800
+ var DefaultPostgreSQLEventStoreProcessorBatchSize = 100;
801
+ var DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs = 50;
802
+ var postgreSQLEventStoreMessageBatchPuller = ({
803
+ executor,
804
+ batchSize,
805
+ eachBatch,
806
+ pullingFrequencyInMs,
807
+ stopWhen,
808
+ signal
809
+ }) => {
810
+ let isRunning = false;
811
+ let start;
812
+ const pullMessages = async (options) => {
813
+ const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await readLastMessageGlobalPosition(executor)).currentGlobalPosition, async () => ( 0n)) : parseBigIntProcessorCheckpoint(options.startFrom.lastCheckpoint);
814
+ const readMessagesOptions = {
815
+ after,
816
+ batchSize
817
+ };
818
+ let waitTime = 100;
819
+ while (isRunning && !_optionalChain([signal, 'optionalAccess', _37 => _37.aborted])) {
820
+ const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
821
+ if (messages.length > 0) {
822
+ const result = await eachBatch(messages);
823
+ if (result && result.type === "STOP") {
824
+ isRunning = false;
825
+ break;
826
+ }
827
+ }
828
+ readMessagesOptions.after = currentGlobalPosition;
829
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
830
+ if (_optionalChain([stopWhen, 'optionalAccess', _38 => _38.noMessagesLeft]) === true && !areMessagesLeft) {
831
+ isRunning = false;
832
+ break;
833
+ }
834
+ if (!areMessagesLeft) {
835
+ waitTime = Math.min(waitTime * 2, 1e3);
836
+ } else {
837
+ waitTime = pullingFrequencyInMs;
838
+ }
847
839
  }
848
840
  };
849
- };
850
- var projector = (options) => {
851
- const {
852
- projection: projection2,
853
- processorId = getProjectorId({
854
- projectionName: _nullishCoalesce(projection2.name, () => ( "unknown"))
855
- }),
856
- ...rest
857
- } = options;
858
- return reactor({
859
- ...rest,
860
- type: MessageProcessorType.PROJECTOR,
861
- canHandle: projection2.canHandle,
862
- processorId,
863
- messageOptions: options.projection.eventsOptions,
864
- hooks: {
865
- onInit: _optionalChain([options, 'access', _28 => _28.hooks, 'optionalAccess', _29 => _29.onInit]),
866
- onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _30 => _30.hooks, 'optionalAccess', _31 => _31.onStart]) ? async (context) => {
867
- if (options.truncateOnStart && options.projection.truncate)
868
- await options.projection.truncate(context);
869
- if (_optionalChain([options, 'access', _32 => _32.hooks, 'optionalAccess', _33 => _33.onStart])) await _optionalChain([options, 'access', _34 => _34.hooks, 'optionalAccess', _35 => _35.onStart, 'call', _36 => _36(context)]);
870
- } : void 0,
871
- onClose: _optionalChain([options, 'access', _37 => _37.hooks, 'optionalAccess', _38 => _38.onClose])
841
+ return {
842
+ get isRunning() {
843
+ return isRunning;
872
844
  },
873
- eachMessage: async (event2, context) => projection2.handle([event2], context)
874
- });
845
+ start: (options) => {
846
+ if (isRunning) return start;
847
+ isRunning = true;
848
+ start = (async () => {
849
+ return pullMessages(options);
850
+ })();
851
+ return start;
852
+ },
853
+ stop: async () => {
854
+ if (!isRunning) return;
855
+ isRunning = false;
856
+ await start;
857
+ }
858
+ };
859
+ };
860
+ var zipPostgreSQLEventStoreMessageBatchPullerStartFrom = (options) => {
861
+ if (options.length === 0 || options.some((o) => o === void 0 || o === "BEGINNING"))
862
+ return "BEGINNING";
863
+ if (options.every((o) => o === "END")) return "END";
864
+ return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
875
865
  };
876
- var projection = (definition) => definition;
877
866
 
878
867
  // src/eventStore/consumers/postgreSQLEventStoreConsumer.ts
879
868
 
880
869
 
870
+
881
871
  // src/eventStore/consumers/postgreSQLProcessor.ts
882
872
 
883
873
 
884
- // src/eventStore/projections/locks/tryAcquireProcessorLock.ts
874
+ // src/eventStore/projections/locks/tryAcquireProjectionLock.ts
885
875
 
886
876
 
887
- // src/eventStore/schema/processors/processorsLocks.ts
877
+ // src/eventStore/schema/projections/projectionsLocks.ts
888
878
 
889
879
 
890
880
  // src/eventStore/schema/createFunctionIfDoesNotExist.ts
@@ -898,7 +888,91 @@ END IF;
898
888
  END $$;
899
889
  `;
900
890
 
891
+ // src/eventStore/schema/projections/projectionsLocks.ts
892
+ var tryAcquireProjectionLockSQL = createFunctionIfDoesNotExistSQL(
893
+ "emt_try_acquire_projection_lock",
894
+ _dumbo.SQL`
895
+ CREATE OR REPLACE FUNCTION emt_try_acquire_projection_lock(
896
+ p_lock_key BIGINT,
897
+ p_partition TEXT,
898
+ p_name TEXT,
899
+ p_version INT
900
+ )
901
+ RETURNS TABLE (acquired BOOLEAN, is_active BOOLEAN)
902
+ LANGUAGE plpgsql
903
+ AS $emt_try_acquire_projection_lock$
904
+ BEGIN
905
+ RETURN QUERY
906
+ WITH lock_check AS (
907
+ SELECT pg_try_advisory_xact_lock_shared(p_lock_key) AS acquired
908
+ ),
909
+ status_check AS (
910
+ SELECT status = 'active' AS is_active
911
+ FROM ${_dumbo.SQL.plain(projectionsTable.name)}
912
+ WHERE partition = p_partition AND name = p_name AND version = p_version
913
+ )
914
+ SELECT
915
+ COALESCE((SELECT lc.acquired FROM lock_check lc), false),
916
+ COALESCE((SELECT sc.is_active FROM status_check sc), true);
917
+ END;
918
+ $emt_try_acquire_projection_lock$;
919
+ `
920
+ );
921
+ var callTryAcquireProjectionLock = (params) => _dumbo.SQL`SELECT * FROM emt_try_acquire_projection_lock(${params.lockKey}, ${params.partition}, ${params.name}, ${params.version});`;
922
+
923
+ // src/eventStore/projections/locks/tryAcquireProjectionLock.ts
924
+ var tryAcquireProjectionLock = async (execute, {
925
+ lockKey,
926
+ projectionName,
927
+ partition,
928
+ version
929
+ }) => {
930
+ const lockKeyBigInt = isBigint(lockKey) ? lockKey : await hashText(lockKey);
931
+ const { acquired, is_active } = await _dumbo.single.call(void 0,
932
+ execute.query(
933
+ callTryAcquireProjectionLock({
934
+ lockKey: lockKeyBigInt.toString(),
935
+ partition,
936
+ name: projectionName,
937
+ version
938
+ })
939
+ )
940
+ );
941
+ return acquired === true && is_active === true;
942
+ };
943
+
944
+ // src/eventStore/projections/locks/postgreSQLProjectionLock.ts
945
+ var postgreSQLProjectionLock = (options) => {
946
+ let acquired = false;
947
+ const lockKey = _nullishCoalesce(options.lockKey, () => ( toProjectionLockKey(options)));
948
+ return {
949
+ tryAcquire: async (context) => {
950
+ if (acquired) {
951
+ return true;
952
+ }
953
+ acquired = await tryAcquireProjectionLock(context.execute, {
954
+ ...options,
955
+ lockKey
956
+ });
957
+ return acquired;
958
+ },
959
+ release: (_context) => {
960
+ if (!acquired) return;
961
+ acquired = false;
962
+ }
963
+ };
964
+ };
965
+ var toProjectionLockKey = ({
966
+ projectionName,
967
+ partition,
968
+ version
969
+ }) => `${partition}:${projectionName}:${version}`;
970
+
971
+ // src/eventStore/projections/locks/tryAcquireProcessorLock.ts
972
+
973
+
901
974
  // src/eventStore/schema/processors/processorsLocks.ts
975
+
902
976
  var tryAcquireProcessorLockSQL = createFunctionIfDoesNotExistSQL(
903
977
  "emt_try_acquire_processor_lock",
904
978
  _dumbo.SQL`
@@ -906,8 +980,8 @@ CREATE OR REPLACE FUNCTION emt_try_acquire_processor_lock(
906
980
  p_lock_key BIGINT,
907
981
  p_processor_id TEXT,
908
982
  p_version INT,
909
- p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
910
- p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag)}',
983
+ p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
984
+ p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag2)}',
911
985
  p_projection_name TEXT DEFAULT NULL,
912
986
  p_projection_type VARCHAR(1) DEFAULT NULL,
913
987
  p_projection_kind TEXT DEFAULT NULL,
@@ -940,7 +1014,7 @@ BEGIN
940
1014
  status = 'running',
941
1015
  last_updated = now()
942
1016
  WHERE ${_dumbo.SQL.plain(processorsTable.name)}.processor_instance_id = p_processor_instance_id
943
- OR ${_dumbo.SQL.plain(processorsTable.name)}.processor_instance_id = '${_dumbo.SQL.plain(unknownTag)}'
1017
+ OR ${_dumbo.SQL.plain(processorsTable.name)}.processor_instance_id = '${_dumbo.SQL.plain(unknownTag2)}'
944
1018
  OR ${_dumbo.SQL.plain(processorsTable.name)}.status = 'stopped'
945
1019
  OR ${_dumbo.SQL.plain(processorsTable.name)}.last_updated < now() - (p_lock_timeout_seconds || ' seconds')::interval
946
1020
  RETURNING last_processed_checkpoint
@@ -977,7 +1051,7 @@ CREATE OR REPLACE FUNCTION emt_release_processor_lock(
977
1051
  p_processor_id TEXT,
978
1052
  p_partition TEXT,
979
1053
  p_version INT,
980
- p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag)}',
1054
+ p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag2)}',
981
1055
  p_projection_name TEXT DEFAULT NULL
982
1056
  )
983
1057
  RETURNS BOOLEAN
@@ -997,7 +1071,7 @@ BEGIN
997
1071
 
998
1072
  UPDATE ${_dumbo.SQL.plain(processorsTable.name)}
999
1073
  SET status = 'stopped',
1000
- processor_instance_id = '${_dumbo.SQL.plain(unknownTag)}',
1074
+ processor_instance_id = '${_dumbo.SQL.plain(unknownTag2)}',
1001
1075
  last_updated = now()
1002
1076
  WHERE processor_id = p_processor_id
1003
1077
  AND partition = p_partition
@@ -1057,7 +1131,7 @@ var tryAcquireProcessorLock = async (execute, options) => {
1057
1131
  return acquired ? { acquired: true, checkpoint } : { acquired: false };
1058
1132
  };
1059
1133
  var tryAcquireProcessorLockWithRetry = async (execute, options) => {
1060
- const policy = _nullishCoalesce(options.lockPolicy, () => ( DefaultPostgreSQLProcessorLockPolicy));
1134
+ const policy = _nullishCoalesce(options.lockAcquisitionPolicy, () => ( DefaultPostgreSQLProcessorLockPolicy));
1061
1135
  if (policy.type === "retry") {
1062
1136
  return asyncRetry(() => tryAcquireProcessorLock(execute, options), {
1063
1137
  retries: policy.retries - 1,
@@ -1085,90 +1159,6 @@ var releaseProcessorLock = async (execute, options) => {
1085
1159
  return result;
1086
1160
  };
1087
1161
 
1088
- // src/eventStore/projections/locks/tryAcquireProjectionLock.ts
1089
-
1090
-
1091
- // src/eventStore/schema/projections/projectionsLocks.ts
1092
-
1093
- var tryAcquireProjectionLockSQL = createFunctionIfDoesNotExistSQL(
1094
- "emt_try_acquire_projection_lock",
1095
- _dumbo.SQL`
1096
- CREATE OR REPLACE FUNCTION emt_try_acquire_projection_lock(
1097
- p_lock_key BIGINT,
1098
- p_partition TEXT,
1099
- p_name TEXT,
1100
- p_version INT
1101
- )
1102
- RETURNS TABLE (acquired BOOLEAN, is_active BOOLEAN)
1103
- LANGUAGE plpgsql
1104
- AS $emt_try_acquire_projection_lock$
1105
- BEGIN
1106
- RETURN QUERY
1107
- WITH lock_check AS (
1108
- SELECT pg_try_advisory_xact_lock_shared(p_lock_key) AS acquired
1109
- ),
1110
- status_check AS (
1111
- SELECT status = 'active' AS is_active
1112
- FROM ${_dumbo.SQL.plain(projectionsTable.name)}
1113
- WHERE partition = p_partition AND name = p_name AND version = p_version
1114
- )
1115
- SELECT
1116
- COALESCE((SELECT lc.acquired FROM lock_check lc), false),
1117
- COALESCE((SELECT sc.is_active FROM status_check sc), true);
1118
- END;
1119
- $emt_try_acquire_projection_lock$;
1120
- `
1121
- );
1122
- var callTryAcquireProjectionLock = (params) => _dumbo.SQL`SELECT * FROM emt_try_acquire_projection_lock(${params.lockKey}, ${params.partition}, ${params.name}, ${params.version});`;
1123
-
1124
- // src/eventStore/projections/locks/tryAcquireProjectionLock.ts
1125
- var tryAcquireProjectionLock = async (execute, {
1126
- lockKey,
1127
- projectionName,
1128
- partition,
1129
- version
1130
- }) => {
1131
- const lockKeyBigInt = isBigint(lockKey) ? lockKey : await hashText(lockKey);
1132
- const { acquired, is_active } = await _dumbo.single.call(void 0,
1133
- execute.query(
1134
- callTryAcquireProjectionLock({
1135
- lockKey: lockKeyBigInt.toString(),
1136
- partition,
1137
- name: projectionName,
1138
- version
1139
- })
1140
- )
1141
- );
1142
- return acquired === true && is_active === true;
1143
- };
1144
-
1145
- // src/eventStore/projections/locks/postgreSQLProjectionLock.ts
1146
- var postgreSQLProjectionLock = (options) => {
1147
- let acquired = false;
1148
- const lockKey = _nullishCoalesce(options.lockKey, () => ( toProjectionLockKey(options)));
1149
- return {
1150
- tryAcquire: async (context) => {
1151
- if (acquired) {
1152
- return true;
1153
- }
1154
- acquired = await tryAcquireProjectionLock(context.execute, {
1155
- ...options,
1156
- lockKey
1157
- });
1158
- return acquired;
1159
- },
1160
- release: (_context) => {
1161
- if (!acquired) return;
1162
- acquired = false;
1163
- }
1164
- };
1165
- };
1166
- var toProjectionLockKey = ({
1167
- projectionName,
1168
- partition,
1169
- version
1170
- }) => `${partition}:${projectionName}:${version}`;
1171
-
1172
1162
  // src/eventStore/projections/locks/postgreSQLProcessorLock.ts
1173
1163
  var DefaultPostgreSQLProcessorLockPolicy = {
1174
1164
  type: "fail"
@@ -1185,7 +1175,7 @@ var postgreSQLProcessorLock = (options) => {
1185
1175
  ...options,
1186
1176
  lockKey
1187
1177
  });
1188
- if (!result.acquired && _optionalChain([options, 'access', _45 => _45.lockPolicy, 'optionalAccess', _46 => _46.type]) !== "skip") {
1178
+ if (!result.acquired && _optionalChain([options, 'access', _45 => _45.lockAcquisitionPolicy, 'optionalAccess', _46 => _46.type]) !== "skip") {
1189
1179
  throw new EmmettError(
1190
1180
  `Failed to acquire lock for processor '${options.processorId}'`
1191
1181
  );
@@ -1932,7 +1922,7 @@ var appendEventsRaw = (execute, streamId, streamType, messages, options) => _dum
1932
1922
  streamId,
1933
1923
  streamType,
1934
1924
  expectedStreamPosition: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _50 => _50.expectedStreamVersion]), () => ( null)),
1935
- partition: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _51 => _51.partition]), () => ( defaultTag))
1925
+ partition: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _51 => _51.partition]), () => ( defaultTag2))
1936
1926
  })
1937
1927
  )
1938
1928
  );
@@ -2427,7 +2417,7 @@ BEGIN
2427
2417
  END;
2428
2418
  $fnpar$ LANGUAGE plpgsql;
2429
2419
 
2430
- PERFORM emt_add_partition('${_dumbo.SQL.plain(defaultTag)}');
2420
+ PERFORM emt_add_partition('${_dumbo.SQL.plain(defaultTag2)}');
2431
2421
 
2432
2422
  -- 3. Copy data from old table to new table
2433
2423
  INSERT INTO "emt_processors"
@@ -2543,7 +2533,7 @@ BEGIN
2543
2533
  p_position TEXT,
2544
2534
  p_check_position TEXT,
2545
2535
  p_transaction_id xid8,
2546
- p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
2536
+ p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
2547
2537
  p_processor_instance_id TEXT DEFAULT 'emt:unknown'
2548
2538
  ) RETURNS INT AS $fn2$
2549
2539
  DECLARE
@@ -2678,7 +2668,7 @@ CREATE OR REPLACE FUNCTION emt_try_acquire_processor_lock(
2678
2668
  p_lock_key BIGINT,
2679
2669
  p_processor_id TEXT,
2680
2670
  p_version INT,
2681
- p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
2671
+ p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
2682
2672
  p_processor_instance_id TEXT DEFAULT 'emt:unknown',
2683
2673
  p_projection_name TEXT DEFAULT NULL,
2684
2674
  p_projection_type VARCHAR(1) DEFAULT NULL,
@@ -3457,8 +3447,8 @@ CREATE OR REPLACE FUNCTION store_processor_checkpoint(
3457
3447
  p_position TEXT,
3458
3448
  p_check_position TEXT,
3459
3449
  p_transaction_id xid8,
3460
- p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3461
- p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag)}'
3450
+ p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3451
+ p_processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag2)}'
3462
3452
  ) RETURNS INT AS $spc$
3463
3453
  DECLARE
3464
3454
  current_position TEXT;
@@ -3539,10 +3529,10 @@ var storeProcessorCheckpoint = async (execute, options) => {
3539
3529
  callStoreProcessorCheckpoint({
3540
3530
  processorId: options.processorId,
3541
3531
  version: _nullishCoalesce(options.version, () => ( 1)),
3542
- position: options.newCheckpoint !== null ? bigInt.toNormalizedString(options.newCheckpoint) : null,
3543
- checkPosition: options.lastProcessedCheckpoint !== null ? bigInt.toNormalizedString(options.lastProcessedCheckpoint) : null,
3544
- partition: _nullishCoalesce(options.partition, () => ( defaultTag)),
3545
- processorInstanceId: _nullishCoalesce(options.processorInstanceId, () => ( unknownTag))
3532
+ position: options.newCheckpoint !== null ? options.newCheckpoint : null,
3533
+ checkPosition: options.lastProcessedCheckpoint !== null ? options.lastProcessedCheckpoint : null,
3534
+ partition: _nullishCoalesce(options.partition, () => ( defaultTag2)),
3535
+ processorInstanceId: _nullishCoalesce(options.processorInstanceId, () => ( unknownTag2))
3546
3536
  })
3547
3537
  )
3548
3538
  );
@@ -3602,7 +3592,7 @@ IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'emt_subscriptions') THEN
3602
3592
  p_position TEXT,
3603
3593
  p_check_position TEXT,
3604
3594
  p_transaction_id xid8,
3605
- p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3595
+ p_partition TEXT DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3606
3596
  p_processor_instance_id TEXT DEFAULT 'emt:unknown'
3607
3597
  ) RETURNS INT AS $fn$
3608
3598
  DECLARE
@@ -3679,7 +3669,7 @@ var streamsTableSQL = _dumbo.SQL`
3679
3669
  CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(streamsTable.name)}(
3680
3670
  stream_id TEXT NOT NULL,
3681
3671
  stream_position BIGINT NOT NULL,
3682
- partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3672
+ partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3683
3673
  stream_type TEXT NOT NULL,
3684
3674
  stream_metadata JSONB NOT NULL,
3685
3675
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
@@ -3700,7 +3690,7 @@ var messagesTableSQL = _dumbo.SQL`
3700
3690
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
3701
3691
  message_kind VARCHAR(1) NOT NULL DEFAULT 'E',
3702
3692
  stream_id TEXT NOT NULL,
3703
- partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3693
+ partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3704
3694
  message_schema_version TEXT NOT NULL,
3705
3695
  message_id TEXT NOT NULL,
3706
3696
  message_type TEXT NOT NULL,
@@ -3713,10 +3703,10 @@ var processorsTableSQL = _dumbo.SQL`
3713
3703
  last_processed_transaction_id XID8 NOT NULL,
3714
3704
  version INT NOT NULL DEFAULT 1,
3715
3705
  processor_id TEXT NOT NULL,
3716
- partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3706
+ partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3717
3707
  status TEXT NOT NULL DEFAULT 'stopped',
3718
3708
  last_processed_checkpoint TEXT NOT NULL,
3719
- processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag)}',
3709
+ processor_instance_id TEXT DEFAULT '${_dumbo.SQL.plain(unknownTag2)}',
3720
3710
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
3721
3711
  last_updated TIMESTAMPTZ NOT NULL DEFAULT now(),
3722
3712
  PRIMARY KEY (processor_id, partition, version)
@@ -3727,7 +3717,7 @@ var projectionsTableSQL = _dumbo.SQL`
3727
3717
  version INT NOT NULL DEFAULT 1,
3728
3718
  type VARCHAR(1) NOT NULL,
3729
3719
  name TEXT NOT NULL,
3730
- partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag)}',
3720
+ partition TEXT NOT NULL DEFAULT '${_dumbo.SQL.plain(defaultTag2)}',
3731
3721
  kind TEXT NOT NULL,
3732
3722
  status TEXT NOT NULL,
3733
3723
  definition JSONB NOT NULL DEFAULT '{}'::jsonb,
@@ -3985,7 +3975,7 @@ var addTenantForAllModulesSQL = _dumbo.SQL`
3985
3975
  END;
3986
3976
  $$ LANGUAGE plpgsql;
3987
3977
  `;
3988
- var addDefaultPartitionSQL = _dumbo.SQL`SELECT emt_add_partition('${_dumbo.SQL.plain(defaultTag)}');`;
3978
+ var addDefaultPartitionSQL = _dumbo.SQL`SELECT emt_add_partition('${_dumbo.SQL.plain(defaultTag2)}');`;
3989
3979
 
3990
3980
  // src/eventStore/schema/readProcessorCheckpoint.ts
3991
3981
 
@@ -3994,12 +3984,12 @@ var readProcessorCheckpoint = async (execute, options) => {
3994
3984
  execute.query(
3995
3985
  _dumbo.SQL`SELECT last_processed_checkpoint
3996
3986
  FROM ${_dumbo.SQL.identifier(processorsTable.name)}
3997
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _52 => _52.partition]), () => ( defaultTag))} AND processor_id = ${options.processorId} AND version = ${_nullishCoalesce(options.version, () => ( 1))}
3987
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _52 => _52.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId} AND version = ${_nullishCoalesce(options.version, () => ( 1))}
3998
3988
  LIMIT 1`
3999
3989
  )
4000
3990
  );
4001
3991
  return {
4002
- lastProcessedCheckpoint: result !== null ? BigInt(result.last_processed_checkpoint) : null
3992
+ lastProcessedCheckpoint: result !== null ? result.last_processed_checkpoint : null
4003
3993
  };
4004
3994
  };
4005
3995
 
@@ -4015,7 +4005,7 @@ var readStream = async (execute, streamId, options) => {
4015
4005
  execute.query(
4016
4006
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
4017
4007
  FROM ${_dumbo.SQL.identifier(messagesTable.name)}
4018
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _56 => _56.partition]), () => ( defaultTag))} AND is_archived = FALSE ${_dumbo.SQL.plain(fromCondition)} ${_dumbo.SQL.plain(toCondition)}
4008
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _56 => _56.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${_dumbo.SQL.plain(fromCondition)} ${_dumbo.SQL.plain(toCondition)}
4019
4009
  ORDER BY stream_position ASC`
4020
4010
  ),
4021
4011
  (row) => {
@@ -4029,7 +4019,8 @@ var readStream = async (execute, streamId, options) => {
4029
4019
  messageId: row.message_id,
4030
4020
  streamName: streamId,
4031
4021
  streamPosition: BigInt(row.stream_position),
4032
- globalPosition: BigInt(row.global_position)
4022
+ globalPosition: BigInt(row.global_position),
4023
+ checkpoint: bigIntProcessorCheckpoint(BigInt(row.global_position))
4033
4024
  };
4034
4025
  const event = {
4035
4026
  ...rawEvent,
@@ -4057,7 +4048,7 @@ var streamExists = async (execute, streamId, options) => {
4057
4048
  _dumbo.SQL`SELECT EXISTS (
4058
4049
  SELECT 1
4059
4050
  from ${_dumbo.SQL.identifier(streamsTable.name)}
4060
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _59 => _59.partition]), () => ( defaultTag))} AND is_archived = FALSE)
4051
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _59 => _59.partition]), () => ( defaultTag2))} AND is_archived = FALSE)
4061
4052
  `
4062
4053
  );
4063
4054
  return _nullishCoalesce(_optionalChain([queryResult, 'access', _60 => _60.rows, 'access', _61 => _61[0], 'optionalAccess', _62 => _62.exists]), () => ( false));
@@ -4259,7 +4250,7 @@ var getPostgreSQLEventStore = (connectionString, options = defaultPostgreSQLOpti
4259
4250
  appendToStream: async (streamName, events, options2) => {
4260
4251
  await ensureSchemaExists();
4261
4252
  const [firstPart, ...rest] = streamName.split("-");
4262
- const streamType = firstPart && rest.length > 0 ? firstPart : unknownTag;
4253
+ const streamType = firstPart && rest.length > 0 ? firstPart : unknownTag2;
4263
4254
  const appendResult = await appendToStream(
4264
4255
  // TODO: Fix this when introducing more drivers
4265
4256
  pool,
@@ -4361,7 +4352,8 @@ var PostgreSQLProjectionSpec = {
4361
4352
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
4362
4353
  ]) {
4363
4354
  const metadata = {
4364
- globalPosition: ++globalPosition,
4355
+ checkpoint: bigIntProcessorCheckpoint(++globalPosition),
4356
+ globalPosition,
4365
4357
  streamPosition: globalPosition,
4366
4358
  streamName: `test-${_uuid.v4.call(void 0, )}`,
4367
4359
  messageId: _uuid.v4.call(void 0, )
@@ -4478,7 +4470,7 @@ var handleProjections = async (options) => {
4478
4470
  projections: allProjections,
4479
4471
  events,
4480
4472
  connection: { pool, transaction, connectionString },
4481
- partition = defaultTag
4473
+ partition = defaultTag2
4482
4474
  } = options;
4483
4475
  const eventTypes = events.map((e) => e.type);
4484
4476
  const projections = allProjections.filter(
@@ -4512,7 +4504,7 @@ var postgreSQLProjection = (definition) => projection({
4512
4504
  init: async (options) => {
4513
4505
  await registerProjection(options.context.execute, {
4514
4506
  // TODO: pass partition from options
4515
- partition: defaultTag,
4507
+ partition: defaultTag2,
4516
4508
  status: "active",
4517
4509
  registration: {
4518
4510
  type: "async",
@@ -4574,10 +4566,10 @@ var postgreSQLCheckpointer = () => ({
4574
4566
  return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _89 => _89.lastProcessedCheckpoint]) };
4575
4567
  },
4576
4568
  store: async (options, context) => {
4577
- const newPosition = getCheckpoint(options.message);
4569
+ const newCheckpoint = getCheckpoint(options.message);
4578
4570
  const result = await storeProcessorCheckpoint(context.execute, {
4579
4571
  lastProcessedCheckpoint: options.lastCheckpoint,
4580
- newCheckpoint: newPosition,
4572
+ newCheckpoint,
4581
4573
  processorId: options.processorId,
4582
4574
  partition: options.partition,
4583
4575
  version: options.version
@@ -4651,8 +4643,7 @@ var postgreSQLProjector = (options) => {
4651
4643
  processorInstanceId = getProcessorInstanceId(processorId),
4652
4644
  version = defaultProcessorVersion,
4653
4645
  partition = defaultProcessorPartition,
4654
- lockPolicy = DefaultPostgreSQLProcessorLockPolicy,
4655
- lockTimeoutSeconds
4646
+ lock
4656
4647
  } = options;
4657
4648
  const { pool, connectionString, close } = getProcessorPool(options);
4658
4649
  const processorLock = postgreSQLProcessorLock({
@@ -4661,18 +4652,18 @@ var postgreSQLProjector = (options) => {
4661
4652
  partition,
4662
4653
  processorInstanceId,
4663
4654
  projection: options.projection ? {
4664
- name: _nullishCoalesce(options.projection.name, () => ( unknownTag2)),
4665
- kind: _nullishCoalesce(options.projection.kind, () => ( unknownTag2)),
4655
+ name: _nullishCoalesce(options.projection.name, () => ( unknownTag)),
4656
+ kind: _nullishCoalesce(options.projection.kind, () => ( unknownTag)),
4666
4657
  version: _nullishCoalesce(options.projection.version, () => ( version)),
4667
4658
  handlingType: "async"
4668
4659
  } : void 0,
4669
- lockPolicy,
4670
- lockTimeoutSeconds
4660
+ lockAcquisitionPolicy: _nullishCoalesce(_optionalChain([lock, 'optionalAccess', _96 => _96.acquisitionPolicy]), () => ( DefaultPostgreSQLProcessorLockPolicy)),
4661
+ lockTimeoutSeconds: _optionalChain([lock, 'optionalAccess', _97 => _97.timeoutSeconds])
4671
4662
  });
4672
4663
  const hooks = wrapHooksWithProcessorLocks(
4673
4664
  {
4674
4665
  ..._nullishCoalesce(options.hooks, () => ( {})),
4675
- onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _96 => _96.hooks, 'optionalAccess', _97 => _97.onInit]) ? async (context) => {
4666
+ onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _98 => _98.hooks, 'optionalAccess', _99 => _99.onInit]) ? async (context) => {
4676
4667
  if (options.projection.init)
4677
4668
  await options.projection.init({
4678
4669
  version: _nullishCoalesce(options.projection.version, () => ( version)),
@@ -4683,16 +4674,16 @@ var postgreSQLProjector = (options) => {
4683
4674
  migrationOptions: options.migrationOptions
4684
4675
  }
4685
4676
  });
4686
- if (_optionalChain([options, 'access', _98 => _98.hooks, 'optionalAccess', _99 => _99.onInit]))
4677
+ if (_optionalChain([options, 'access', _100 => _100.hooks, 'optionalAccess', _101 => _101.onInit]))
4687
4678
  await options.hooks.onInit({
4688
4679
  ...context,
4689
4680
  migrationOptions: options.migrationOptions
4690
4681
  });
4691
- } : _optionalChain([options, 'access', _100 => _100.hooks, 'optionalAccess', _101 => _101.onInit]),
4682
+ } : _optionalChain([options, 'access', _102 => _102.hooks, 'optionalAccess', _103 => _103.onInit]),
4692
4683
  onClose: close ? async (context) => {
4693
- if (_optionalChain([options, 'access', _102 => _102.hooks, 'optionalAccess', _103 => _103.onClose])) await _optionalChain([options, 'access', _104 => _104.hooks, 'optionalAccess', _105 => _105.onClose, 'call', _106 => _106(context)]);
4684
+ if (_optionalChain([options, 'access', _104 => _104.hooks, 'optionalAccess', _105 => _105.onClose])) await _optionalChain([options, 'access', _106 => _106.hooks, 'optionalAccess', _107 => _107.onClose, 'call', _108 => _108(context)]);
4694
4685
  if (close) await close();
4695
- } : _optionalChain([options, 'access', _107 => _107.hooks, 'optionalAccess', _108 => _108.onClose])
4686
+ } : _optionalChain([options, 'access', _109 => _109.hooks, 'optionalAccess', _110 => _110.onClose])
4696
4687
  },
4697
4688
  processorLock
4698
4689
  );
@@ -4719,7 +4710,7 @@ var postgreSQLReactor = (options) => {
4719
4710
  processorInstanceId = getProcessorInstanceId(processorId),
4720
4711
  version = defaultProcessorVersion,
4721
4712
  partition = defaultProcessorPartition,
4722
- lockPolicy = DefaultPostgreSQLProcessorLockPolicy
4713
+ lock
4723
4714
  } = options;
4724
4715
  const { pool, connectionString, close } = getProcessorPool(options);
4725
4716
  const processorLock = postgreSQLProcessorLock({
@@ -4728,15 +4719,16 @@ var postgreSQLReactor = (options) => {
4728
4719
  partition,
4729
4720
  processorInstanceId,
4730
4721
  projection: void 0,
4731
- lockPolicy
4722
+ lockAcquisitionPolicy: _nullishCoalesce(_optionalChain([lock, 'optionalAccess', _111 => _111.acquisitionPolicy]), () => ( DefaultPostgreSQLProcessorLockPolicy)),
4723
+ lockTimeoutSeconds: _optionalChain([lock, 'optionalAccess', _112 => _112.timeoutSeconds])
4732
4724
  });
4733
4725
  const hooks = wrapHooksWithProcessorLocks(
4734
4726
  {
4735
4727
  ..._nullishCoalesce(options.hooks, () => ( {})),
4736
4728
  onClose: close ? async (context) => {
4737
- if (_optionalChain([options, 'access', _109 => _109.hooks, 'optionalAccess', _110 => _110.onClose])) await _optionalChain([options, 'access', _111 => _111.hooks, 'optionalAccess', _112 => _112.onClose, 'call', _113 => _113(context)]);
4729
+ if (_optionalChain([options, 'access', _113 => _113.hooks, 'optionalAccess', _114 => _114.onClose])) await _optionalChain([options, 'access', _115 => _115.hooks, 'optionalAccess', _116 => _116.onClose, 'call', _117 => _117(context)]);
4738
4730
  if (close) await close();
4739
- } : _optionalChain([options, 'access', _114 => _114.hooks, 'optionalAccess', _115 => _115.onClose])
4731
+ } : _optionalChain([options, 'access', _118 => _118.hooks, 'optionalAccess', _119 => _119.onClose])
4740
4732
  },
4741
4733
  processorLock
4742
4734
  );
@@ -4756,14 +4748,6 @@ var postgreSQLReactor = (options) => {
4756
4748
  checkpoints: postgreSQLCheckpointer()
4757
4749
  });
4758
4750
  };
4759
- var postgreSQLMessageProcessor = (options) => {
4760
- if ("projection" in options) {
4761
- return postgreSQLProjector(
4762
- options
4763
- );
4764
- }
4765
- return postgreSQLReactor(options);
4766
- };
4767
4751
 
4768
4752
  // src/eventStore/consumers/postgreSQLEventStoreConsumer.ts
4769
4753
  var postgreSQLEventStoreConsumer = (options) => {
@@ -4793,7 +4777,7 @@ var postgreSQLEventStoreConsumer = (options) => {
4793
4777
  })
4794
4778
  );
4795
4779
  return result.some(
4796
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _116 => _116.value, 'optionalAccess', _117 => _117.type]) !== "STOP"
4780
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _120 => _120.value, 'optionalAccess', _121 => _121.type]) !== "STOP"
4797
4781
  ) ? void 0 : {
4798
4782
  type: "STOP"
4799
4783
  };
@@ -4812,7 +4796,7 @@ var postgreSQLEventStoreConsumer = (options) => {
4812
4796
  if (!isRunning) return;
4813
4797
  isRunning = false;
4814
4798
  if (messagePuller) {
4815
- _optionalChain([abortController, 'optionalAccess', _118 => _118.abort, 'call', _119 => _119()]);
4799
+ _optionalChain([abortController, 'optionalAccess', _122 => _122.abort, 'call', _123 => _123()]);
4816
4800
  await messagePuller.stop();
4817
4801
  messagePuller = void 0;
4818
4802
  abortController = null;
@@ -4865,8 +4849,8 @@ var postgreSQLEventStoreConsumer = (options) => {
4865
4849
  stopWhen: options.stopWhen,
4866
4850
  executor: pool.execute,
4867
4851
  eachBatch,
4868
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _120 => _120.batchSize]), () => ( DefaultPostgreSQLEventStoreProcessorBatchSize)),
4869
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _121 => _121.pullingFrequencyInMs]), () => ( DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs)),
4852
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _124 => _124.batchSize]), () => ( DefaultPostgreSQLEventStoreProcessorBatchSize)),
4853
+ pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _125 => _125.pullingFrequencyInMs]), () => ( DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs)),
4870
4854
  signal: abortController.signal
4871
4855
  });
4872
4856
  start = (async () => {
@@ -4914,27 +4898,27 @@ var rebuildPostgreSQLProjections = (options) => {
4914
4898
  ...options,
4915
4899
  stopWhen: { noMessagesLeft: true }
4916
4900
  });
4901
+ const lock = { acquisitionPolicy: defaultRebuildLockPolicy, ...options.lock };
4917
4902
  const projections = "projections" in options ? options.projections.map(
4918
4903
  (p) => "projection" in p ? {
4919
- lockPolicy: defaultRebuildLockPolicy,
4920
4904
  truncateOnStart: true,
4921
4905
  processorId: getProjectorId({
4922
- projectionName: _nullishCoalesce(p.projection.name, () => ( unknownTag2))
4906
+ projectionName: _nullishCoalesce(p.projection.name, () => ( unknownTag))
4923
4907
  }),
4924
4908
  ...p
4925
4909
  } : {
4926
4910
  projection: p,
4927
4911
  processorId: getProjectorId({
4928
- projectionName: _nullishCoalesce(p.name, () => ( unknownTag2))
4912
+ projectionName: _nullishCoalesce(p.name, () => ( unknownTag))
4929
4913
  }),
4930
- truncateOnStart: true,
4931
- lockPolicy: defaultRebuildLockPolicy
4914
+ truncateOnStart: true
4932
4915
  }
4933
4916
  ) : [options];
4934
4917
  for (const projectionDefinition of projections) {
4935
4918
  consumer.projector({
4936
4919
  ...projectionDefinition,
4937
- truncateOnStart: _nullishCoalesce(projectionDefinition.truncateOnStart, () => ( true))
4920
+ truncateOnStart: _nullishCoalesce(projectionDefinition.truncateOnStart, () => ( true)),
4921
+ lock
4938
4922
  });
4939
4923
  }
4940
4924
  return consumer;
@@ -5030,6 +5014,5 @@ var rebuildPostgreSQLProjections = (options) => {
5030
5014
 
5031
5015
 
5032
5016
 
5033
-
5034
- exports.DefaultPostgreSQLEventStoreProcessorBatchSize = DefaultPostgreSQLEventStoreProcessorBatchSize; exports.DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs = DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs; exports.DefaultPostgreSQLProcessorLockPolicy = DefaultPostgreSQLProcessorLockPolicy; exports.PostgreSQLEventStoreDefaultStreamVersion = PostgreSQLEventStoreDefaultStreamVersion; exports.PostgreSQLProjectionSpec = PostgreSQLProjectionSpec; exports.activateProjection = activateProjection; exports.activateProjectionSQL = activateProjectionSQL; exports.addDefaultPartitionSQL = addDefaultPartitionSQL; exports.addModuleForAllTenantsSQL = addModuleForAllTenantsSQL; exports.addModuleSQL = addModuleSQL; exports.addPartitionSQL = addPartitionSQL; exports.addTablePartitions = addTablePartitions; exports.addTenantForAllModulesSQL = addTenantForAllModulesSQL; exports.addTenantSQL = addTenantSQL; exports.appendToStream = appendToStream; exports.appendToStreamSQL = appendToStreamSQL; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.callActivateProjection = callActivateProjection; exports.callAppendToStream = callAppendToStream; exports.callDeactivateProjection = callDeactivateProjection; exports.callRegisterProjection = callRegisterProjection; exports.callReleaseProcessorLock = callReleaseProcessorLock; exports.callStoreProcessorCheckpoint = callStoreProcessorCheckpoint; exports.callTryAcquireProcessorLock = callTryAcquireProcessorLock; exports.callTryAcquireProjectionLock = callTryAcquireProjectionLock; exports.cleanupLegacySubscriptionTables = cleanupLegacySubscriptionTables; exports.createEventStoreSchema = createEventStoreSchema; exports.deactivateProjection = deactivateProjection; exports.deactivateProjectionSQL = deactivateProjectionSQL; exports.defaultPostgreSQLOptions = defaultPostgreSQLOptions; exports.defaultTag = defaultTag; exports.documentDoesNotExist = documentDoesNotExist; exports.documentExists = documentExists; exports.documentMatchingExists = documentMatchingExists; exports.documentsAreTheSame = documentsAreTheSame; exports.documentsMatchingHaveCount = documentsMatchingHaveCount; exports.emmettPrefix = emmettPrefix; exports.eventInStream = eventInStream; exports.eventStoreSchemaMigrations = eventStoreSchemaMigrations; exports.eventsInStream = eventsInStream; exports.expectPongoDocuments = expectPongoDocuments; exports.expectSQL = expectSQL; exports.getPostgreSQLEventStore = getPostgreSQLEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.newEventsInStream = newEventsInStream; exports.pongoMultiStreamProjection = pongoMultiStreamProjection; exports.pongoProjection = pongoProjection; exports.pongoSingleStreamProjection = pongoSingleStreamProjection; exports.postgreSQLCheckpointer = postgreSQLCheckpointer; exports.postgreSQLEventStoreConsumer = postgreSQLEventStoreConsumer; exports.postgreSQLEventStoreMessageBatchPuller = postgreSQLEventStoreMessageBatchPuller; exports.postgreSQLMessageProcessor = postgreSQLMessageProcessor; exports.postgreSQLProcessorLock = postgreSQLProcessorLock; exports.postgreSQLProjection = postgreSQLProjection; exports.postgreSQLProjectionLock = postgreSQLProjectionLock; exports.postgreSQLProjector = postgreSQLProjector; exports.postgreSQLRawBatchSQLProjection = postgreSQLRawBatchSQLProjection; exports.postgreSQLRawSQLProjection = postgreSQLRawSQLProjection; exports.postgreSQLReactor = postgreSQLReactor; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readProjectionInfo = readProjectionInfo; exports.readStream = readStream; exports.rebuildPostgreSQLProjections = rebuildPostgreSQLProjections; exports.registerProjection = registerProjection; exports.registerProjectionSQL = registerProjectionSQL; exports.releaseProcessorLockSQL = releaseProcessorLockSQL; exports.sanitizeNameSQL = sanitizeNameSQL; exports.schemaMigration = schemaMigration; exports.schemaSQL = schemaSQL; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.storeSubscriptionCheckpointSQL = storeSubscriptionCheckpointSQL; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.toProcessorLockKey = toProcessorLockKey; exports.toProjectionLockKey = toProjectionLockKey; exports.transactionToPostgreSQLProjectionHandlerContext = transactionToPostgreSQLProjectionHandlerContext; exports.tryAcquireProcessorLockSQL = tryAcquireProcessorLockSQL; exports.tryAcquireProjectionLockSQL = tryAcquireProjectionLockSQL; exports.unknownTag = unknownTag; exports.zipPostgreSQLEventStoreMessageBatchPullerStartFrom = zipPostgreSQLEventStoreMessageBatchPullerStartFrom;
5017
+ exports.DefaultPostgreSQLEventStoreProcessorBatchSize = DefaultPostgreSQLEventStoreProcessorBatchSize; exports.DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs = DefaultPostgreSQLEventStoreProcessorPullingFrequencyInMs; exports.DefaultPostgreSQLProcessorLockPolicy = DefaultPostgreSQLProcessorLockPolicy; exports.PostgreSQLEventStoreDefaultStreamVersion = PostgreSQLEventStoreDefaultStreamVersion; exports.PostgreSQLProjectionSpec = PostgreSQLProjectionSpec; exports.activateProjection = activateProjection; exports.activateProjectionSQL = activateProjectionSQL; exports.addDefaultPartitionSQL = addDefaultPartitionSQL; exports.addModuleForAllTenantsSQL = addModuleForAllTenantsSQL; exports.addModuleSQL = addModuleSQL; exports.addPartitionSQL = addPartitionSQL; exports.addTablePartitions = addTablePartitions; exports.addTenantForAllModulesSQL = addTenantForAllModulesSQL; exports.addTenantSQL = addTenantSQL; exports.appendToStream = appendToStream; exports.appendToStreamSQL = appendToStreamSQL; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.callActivateProjection = callActivateProjection; exports.callAppendToStream = callAppendToStream; exports.callDeactivateProjection = callDeactivateProjection; exports.callRegisterProjection = callRegisterProjection; exports.callReleaseProcessorLock = callReleaseProcessorLock; exports.callStoreProcessorCheckpoint = callStoreProcessorCheckpoint; exports.callTryAcquireProcessorLock = callTryAcquireProcessorLock; exports.callTryAcquireProjectionLock = callTryAcquireProjectionLock; exports.cleanupLegacySubscriptionTables = cleanupLegacySubscriptionTables; exports.createEventStoreSchema = createEventStoreSchema; exports.deactivateProjection = deactivateProjection; exports.deactivateProjectionSQL = deactivateProjectionSQL; exports.defaultPostgreSQLOptions = defaultPostgreSQLOptions; exports.defaultTag = defaultTag2; exports.documentDoesNotExist = documentDoesNotExist; exports.documentExists = documentExists; exports.documentMatchingExists = documentMatchingExists; exports.documentsAreTheSame = documentsAreTheSame; exports.documentsMatchingHaveCount = documentsMatchingHaveCount; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventStoreSchemaMigrations = eventStoreSchemaMigrations; exports.eventsInStream = eventsInStream; exports.expectPongoDocuments = expectPongoDocuments; exports.expectSQL = expectSQL; exports.getPostgreSQLEventStore = getPostgreSQLEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.newEventsInStream = newEventsInStream; exports.pongoMultiStreamProjection = pongoMultiStreamProjection; exports.pongoProjection = pongoProjection; exports.pongoSingleStreamProjection = pongoSingleStreamProjection; exports.postgreSQLCheckpointer = postgreSQLCheckpointer; exports.postgreSQLEventStoreConsumer = postgreSQLEventStoreConsumer; exports.postgreSQLEventStoreMessageBatchPuller = postgreSQLEventStoreMessageBatchPuller; exports.postgreSQLProcessorLock = postgreSQLProcessorLock; exports.postgreSQLProjection = postgreSQLProjection; exports.postgreSQLProjectionLock = postgreSQLProjectionLock; exports.postgreSQLProjector = postgreSQLProjector; exports.postgreSQLRawBatchSQLProjection = postgreSQLRawBatchSQLProjection; exports.postgreSQLRawSQLProjection = postgreSQLRawSQLProjection; exports.postgreSQLReactor = postgreSQLReactor; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readProjectionInfo = readProjectionInfo; exports.readStream = readStream; exports.rebuildPostgreSQLProjections = rebuildPostgreSQLProjections; exports.registerProjection = registerProjection; exports.registerProjectionSQL = registerProjectionSQL; exports.releaseProcessorLockSQL = releaseProcessorLockSQL; exports.sanitizeNameSQL = sanitizeNameSQL; exports.schemaMigration = schemaMigration; exports.schemaSQL = schemaSQL; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.storeSubscriptionCheckpointSQL = storeSubscriptionCheckpointSQL; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.toProcessorLockKey = toProcessorLockKey; exports.toProjectionLockKey = toProjectionLockKey; exports.transactionToPostgreSQLProjectionHandlerContext = transactionToPostgreSQLProjectionHandlerContext; exports.tryAcquireProcessorLockSQL = tryAcquireProcessorLockSQL; exports.tryAcquireProjectionLockSQL = tryAcquireProjectionLockSQL; exports.unknownTag = unknownTag2; exports.zipPostgreSQLEventStoreMessageBatchPullerStartFrom = zipPostgreSQLEventStoreMessageBatchPullerStartFrom;
5035
5018
  //# sourceMappingURL=index.cjs.map