@reventlessdev/reventless-postgres 3.0.0-alpha.2 → 3.0.0-alpha.200

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.
Files changed (170) hide show
  1. package/CHANGELOG.md +1584 -0
  2. package/README.md +83 -0
  3. package/lib/bs/.compiler.log +2 -2
  4. package/lib/bs/ReventlessPostgres.cmi +0 -0
  5. package/lib/bs/ReventlessPostgres.cmt +0 -0
  6. package/lib/bs/ReventlessPostgres.mlmap +4 -1
  7. package/lib/bs/compiler-info.json +4 -4
  8. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  9. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  10. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  11. package/lib/bs/src/DcbEventLogStorage_Postgres.ast +0 -0
  12. package/lib/bs/src/DcbEventLogStorage_Postgres.res +25 -340
  13. package/lib/bs/src/DcbEventLogStorage_Postgres.res.mjs +38 -348
  14. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  15. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  16. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  17. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.ast +0 -0
  18. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res +422 -0
  19. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res.mjs +437 -0
  20. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  21. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  22. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  23. package/lib/bs/src/EventLogChangeFeed.ast +0 -0
  24. package/lib/bs/src/EventLogChangeFeed.res +193 -0
  25. package/lib/bs/src/EventLogChangeFeed.res.mjs +134 -0
  26. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  27. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  28. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  29. package/lib/bs/src/EventLogStorage_Postgres.ast +0 -0
  30. package/lib/bs/src/EventLogStorage_Postgres.res +12 -170
  31. package/lib/bs/src/EventLogStorage_Postgres.res.mjs +23 -186
  32. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  33. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  34. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  35. package/lib/bs/src/EventLogStorage_Postgres_Ops.ast +0 -0
  36. package/lib/bs/src/EventLogStorage_Postgres_Ops.res +240 -0
  37. package/lib/bs/src/EventLogStorage_Postgres_Ops.res.mjs +232 -0
  38. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  39. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  40. package/lib/bs/src/PgChangeFeed.ast +0 -0
  41. package/lib/bs/src/PgChangeFeed.res +21 -9
  42. package/lib/bs/src/PgChangeFeed.res.mjs +6 -6
  43. package/lib/bs/src/PgDriver-ReventlessPostgres.cmi +0 -0
  44. package/lib/bs/src/PgDriver-ReventlessPostgres.cmt +0 -0
  45. package/lib/bs/src/PgDriver-ReventlessPostgres.cmti +0 -0
  46. package/lib/bs/src/PgDriver.ast +0 -0
  47. package/lib/bs/src/PgDriver.iast +0 -0
  48. package/lib/bs/src/PgDriver.res +1 -2
  49. package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
  50. package/lib/bs/src/PgSchema-ReventlessPostgres.cmt +0 -0
  51. package/lib/bs/src/PgSchema.ast +0 -0
  52. package/lib/bs/src/PgSchema.res +44 -2
  53. package/lib/bs/src/PgSchema.res.mjs +13 -3
  54. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  55. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  56. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  57. package/lib/bs/src/QueryDbStorage_Postgres.ast +0 -0
  58. package/lib/bs/src/QueryDbStorage_Postgres.res +16 -213
  59. package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +27 -191
  60. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  61. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  62. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  63. package/lib/bs/src/QueryDbStorage_Postgres_Ops.ast +0 -0
  64. package/lib/bs/src/QueryDbStorage_Postgres_Ops.res +229 -0
  65. package/lib/bs/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
  66. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  67. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  68. package/lib/bs/src/QueryEnginePostgres.ast +0 -0
  69. package/lib/bs/src/QueryEnginePostgres.res +372 -14
  70. package/lib/bs/src/QueryEnginePostgres.res.mjs +203 -15
  71. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  72. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  73. package/lib/bs/tests/PostgresIntegrationTest.ast +0 -0
  74. package/lib/bs/tests/PostgresIntegrationTest.res +168 -47
  75. package/lib/bs/tests/PostgresIntegrationTest.res.mjs +50 -1
  76. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
  77. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
  78. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
  79. package/lib/bs/tests/QueryEnginePostgresListPageTest.ast +0 -0
  80. package/lib/bs/tests/QueryEnginePostgresListPageTest.res +335 -0
  81. package/lib/bs/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
  82. package/lib/ocaml/.compiler.log +2 -2
  83. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  84. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  85. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  86. package/lib/ocaml/DcbEventLogStorage_Postgres.ast +0 -0
  87. package/lib/ocaml/DcbEventLogStorage_Postgres.res +25 -340
  88. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  89. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  90. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  91. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.ast +0 -0
  92. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.res +422 -0
  93. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  94. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  95. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  96. package/lib/ocaml/EventLogChangeFeed.ast +0 -0
  97. package/lib/ocaml/EventLogChangeFeed.res +193 -0
  98. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  99. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  100. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  101. package/lib/ocaml/EventLogStorage_Postgres.ast +0 -0
  102. package/lib/ocaml/EventLogStorage_Postgres.res +12 -170
  103. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  104. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  105. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  106. package/lib/ocaml/EventLogStorage_Postgres_Ops.ast +0 -0
  107. package/lib/ocaml/EventLogStorage_Postgres_Ops.res +240 -0
  108. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  109. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  110. package/lib/ocaml/PgChangeFeed.ast +0 -0
  111. package/lib/ocaml/PgChangeFeed.res +21 -9
  112. package/lib/ocaml/PgDriver-ReventlessPostgres.cmi +0 -0
  113. package/lib/ocaml/PgDriver-ReventlessPostgres.cmt +0 -0
  114. package/lib/ocaml/PgDriver-ReventlessPostgres.cmti +0 -0
  115. package/lib/ocaml/PgDriver.ast +0 -0
  116. package/lib/ocaml/PgDriver.iast +0 -0
  117. package/lib/ocaml/PgDriver.res +1 -2
  118. package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
  119. package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
  120. package/lib/ocaml/PgSchema.ast +0 -0
  121. package/lib/ocaml/PgSchema.res +44 -2
  122. package/lib/ocaml/PostgresIntegrationTest.res +168 -47
  123. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  124. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  125. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  126. package/lib/ocaml/QueryDbStorage_Postgres.ast +0 -0
  127. package/lib/ocaml/QueryDbStorage_Postgres.res +16 -213
  128. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  129. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  130. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  131. package/lib/ocaml/QueryDbStorage_Postgres_Ops.ast +0 -0
  132. package/lib/ocaml/QueryDbStorage_Postgres_Ops.res +229 -0
  133. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  134. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  135. package/lib/ocaml/QueryEnginePostgres.ast +0 -0
  136. package/lib/ocaml/QueryEnginePostgres.res +372 -14
  137. package/lib/ocaml/QueryEnginePostgresListPageTest.res +335 -0
  138. package/lib/ocaml/ReventlessPostgres.cmi +0 -0
  139. package/lib/ocaml/ReventlessPostgres.cmt +0 -0
  140. package/lib/ocaml/ReventlessPostgres.mlmap +5 -0
  141. package/package.json +14 -14
  142. package/rescript.json +2 -1
  143. package/src/DcbEventLogStorage_Postgres.res +25 -340
  144. package/src/DcbEventLogStorage_Postgres.res.mjs +38 -348
  145. package/src/DcbEventLogStorage_Postgres_Ops.res +422 -0
  146. package/src/DcbEventLogStorage_Postgres_Ops.res.mjs +437 -0
  147. package/src/EventLogChangeFeed.res +193 -0
  148. package/src/EventLogChangeFeed.res.mjs +134 -0
  149. package/src/EventLogStorage_Postgres.res +12 -170
  150. package/src/EventLogStorage_Postgres.res.mjs +23 -186
  151. package/src/EventLogStorage_Postgres_Ops.res +240 -0
  152. package/src/EventLogStorage_Postgres_Ops.res.mjs +232 -0
  153. package/src/PgChangeFeed.res +21 -9
  154. package/src/PgChangeFeed.res.mjs +6 -6
  155. package/src/PgDriver.res +1 -2
  156. package/src/PgSchema.res +44 -2
  157. package/src/PgSchema.res.mjs +13 -3
  158. package/src/QueryDbStorage_Postgres.res +16 -213
  159. package/src/QueryDbStorage_Postgres.res.mjs +27 -191
  160. package/src/QueryDbStorage_Postgres_Ops.res +229 -0
  161. package/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
  162. package/src/QueryEnginePostgres.res +372 -14
  163. package/src/QueryEnginePostgres.res.mjs +203 -15
  164. package/tests/PostgresIntegrationTest.res +168 -47
  165. package/tests/QueryEnginePostgresListPageTest.res +335 -0
  166. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  167. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmj +0 -0
  168. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  169. package/lib/ocaml/PostgresIntegrationTest.ast +0 -0
  170. package/tests/PostgresIntegrationTest.res.mjs +0 -328
@@ -0,0 +1,437 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Stream from "@reventlessdev/rescript-effect/src/Stream.res.mjs";
4
+ import * as Stdlib_Int from "@rescript/runtime/lib/es6/Stdlib_Int.js";
5
+ import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
6
+ import * as Stdlib_Float from "@rescript/runtime/lib/es6/Stdlib_Float.js";
7
+ import * as Stdlib_JsExn from "@rescript/runtime/lib/es6/Stdlib_JsExn.js";
8
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.js";
11
+ import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
12
+ import * as Message$Reventless from "@reventlessdev/reventless-spec/src/types/Message.res.mjs";
13
+ import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
14
+ import * as Util_Sury$Reventless from "@reventlessdev/reventless-spec/src/util/Util_Sury.res.mjs";
15
+ import * as PgDriver$ReventlessPostgres from "./PgDriver.res.mjs";
16
+
17
+ function strategyParam(s) {
18
+ if (s === "AdvisoryLocks") {
19
+ return "advisory";
20
+ } else {
21
+ return "rows";
22
+ }
23
+ }
24
+
25
+ function noTracking(param) {
26
+
27
+ }
28
+
29
+ let selectColumns = "\n lpad(transaction_id::text, 20, '0') || ':' || lpad(position::text, 20, '0') AS cursor,\n event_type,\n tags,\n data,\n meta,\n to_char(recorded_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS recorded_at\n";
30
+
31
+ function decodeTag(s) {
32
+ let i = s.indexOf("=");
33
+ if (i !== -1) {
34
+ return {
35
+ key: s.slice(0, i),
36
+ value: s.slice(i + 1 | 0, s.length)
37
+ };
38
+ } else {
39
+ return {
40
+ key: s,
41
+ value: ""
42
+ };
43
+ }
44
+ }
45
+
46
+ function decodeTags(v) {
47
+ if (v !== undefined) {
48
+ if (Array.isArray(v)) {
49
+ return Stdlib_Array.filterMap(v, x => {
50
+ if (typeof x === "string") {
51
+ return decodeTag(x);
52
+ }
53
+ });
54
+ } else {
55
+ return [];
56
+ }
57
+ } else {
58
+ return [];
59
+ }
60
+ }
61
+
62
+ function rowToEvent(row) {
63
+ let str = key => {
64
+ let match = row[key];
65
+ if (typeof match === "string") {
66
+ return match;
67
+ } else {
68
+ return "";
69
+ }
70
+ };
71
+ let metaJson = row["meta"];
72
+ let meta = metaJson !== undefined ? Util_Sury$Reventless.fromJson(metaJson, Message$Reventless.metaSchema) : Stdlib_JsError.throwWithMessage("missing meta column in dcb_event row");
73
+ return {
74
+ position: str("cursor"),
75
+ eventType: str("event_type"),
76
+ data: Stdlib_Option.getOr(row["data"], null),
77
+ tags: decodeTags(row["tags"]),
78
+ meta: meta,
79
+ recordedAt: str("recorded_at")
80
+ };
81
+ }
82
+
83
+ function mkBuilder() {
84
+ return {
85
+ params: []
86
+ };
87
+ }
88
+
89
+ function param(b, v) {
90
+ b.params.push(v);
91
+ return "$" + b.params.length.toString();
92
+ }
93
+
94
+ function buildReadWhere(b, name, query, after, applyFence) {
95
+ let parts = [`log_name = ` + param(b, name)];
96
+ if (applyFence) {
97
+ parts.push("transaction_id < pg_snapshot_xmin(pg_current_snapshot())");
98
+ }
99
+ if (after !== undefined) {
100
+ let txP = param(b, after[0]);
101
+ let posP = param(b, after[1]);
102
+ parts.push(`(transaction_id > ` + txP + `::xid8 OR (transaction_id = ` + txP + `::xid8 AND position > ` + posP + `::bigint))`);
103
+ }
104
+ if (query.length !== 0) {
105
+ let clauseSqls = query.map(clause => {
106
+ let clauseParts = [];
107
+ let types = clause.eventTypes;
108
+ if (types !== undefined) {
109
+ if (types.length !== 0) {
110
+ let ph = types.map(t => param(b, t)).join(",");
111
+ clauseParts.push(`event_type IN (` + ph + `)`);
112
+ } else {
113
+ clauseParts.push("FALSE");
114
+ }
115
+ }
116
+ let tags = clause.tags;
117
+ if (tags !== undefined && tags.length !== 0) {
118
+ let arr = tags.map(t => param(b, t.key + "=" + t.value)).join(",");
119
+ clauseParts.push(`tags @> ARRAY[` + arr + `]::text[]`);
120
+ }
121
+ if (clauseParts.length === 0) {
122
+ return "TRUE";
123
+ } else {
124
+ return "(" + clauseParts.join(" AND ") + ")";
125
+ }
126
+ });
127
+ parts.push("(" + clauseSqls.join(" OR ") + ")");
128
+ }
129
+ return parts.join(" AND ");
130
+ }
131
+
132
+ function stripZeros(s) {
133
+ let t = s.replace(/^0+/, "");
134
+ if (t === "") {
135
+ return "0";
136
+ } else {
137
+ return t;
138
+ }
139
+ }
140
+
141
+ function decodeCursor(pos) {
142
+ let match = pos.split(":");
143
+ if (match.length !== 2) {
144
+ return;
145
+ }
146
+ let tx = match[0];
147
+ let p = match[1];
148
+ return [
149
+ stripZeros(tx),
150
+ stripZeros(p)
151
+ ];
152
+ }
153
+
154
+ function isConflict(exn) {
155
+ let msg = Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn), Stdlib_JsExn.message), "");
156
+ if (msg.includes("dcb_conflict") || msg.includes("duplicate key")) {
157
+ return true;
158
+ } else {
159
+ return msg.includes("23505");
160
+ }
161
+ }
162
+
163
+ async function countAll(pool) {
164
+ let row = await PgDriver$ReventlessPostgres.queryOne(pool, "SELECT COUNT(*)::bigint AS c FROM dcb_event", []);
165
+ if (row === undefined) {
166
+ return 0;
167
+ }
168
+ let match = row["c"];
169
+ if (match === undefined) {
170
+ return 0;
171
+ }
172
+ switch (typeof match) {
173
+ case "string" :
174
+ return Stdlib_Option.getOr(Stdlib_Int.fromString(match, undefined), 0);
175
+ case "number" :
176
+ return match | 0;
177
+ default:
178
+ return 0;
179
+ }
180
+ }
181
+
182
+ async function readBackwards(pool, name, bound, limit, correlationId) {
183
+ let b = {
184
+ params: []
185
+ };
186
+ let parts = [`log_name = ` + param(b, name)];
187
+ if (bound !== undefined) {
188
+ if (bound.TAG === "Below") {
189
+ parts.push(`position < ` + param(b, bound._0) + `::bigint`);
190
+ } else {
191
+ parts.push(`position <= ` + param(b, bound._0) + `::bigint`);
192
+ }
193
+ }
194
+ if (correlationId !== undefined) {
195
+ parts.push(`(meta->>'correlationId') = ` + param(b, correlationId));
196
+ }
197
+ let limitP = param(b, limit);
198
+ return (await PgDriver$ReventlessPostgres.query(pool, `SELECT ` + selectColumns + `, position::text AS pos_raw FROM dcb_event WHERE ` + parts.join(" AND ") + ` ORDER BY position DESC LIMIT ` + limitP + `::int`, b.params)).map(row => {
199
+ let match = row["pos_raw"];
200
+ let tmp;
201
+ tmp = match !== undefined ? (
202
+ typeof match === "string" ? Stdlib_Option.getOr(Stdlib_Float.fromString(match), 0) : 0
203
+ ) : 0;
204
+ return [
205
+ tmp,
206
+ rowToEvent(row)
207
+ ];
208
+ });
209
+ }
210
+
211
+ async function positionsOfAppend(pool, name, cursor) {
212
+ let match = decodeCursor(cursor);
213
+ if (match !== undefined) {
214
+ return Stdlib_Array.filterMap(await PgDriver$ReventlessPostgres.query(pool, "SELECT position::text AS pos, meta->>'msgId' AS msg_id FROM dcb_event WHERE log_name = $1 AND transaction_id = $2::xid8", [
215
+ name,
216
+ match[0]
217
+ ]), row => {
218
+ let match = row["msg_id"];
219
+ let match$1 = row["pos"];
220
+ if (typeof match === "string" && typeof match$1 === "string") {
221
+ return Stdlib_Option.map(Stdlib_Float.fromString(match$1), p => [
222
+ match,
223
+ p
224
+ ]);
225
+ }
226
+ });
227
+ } else {
228
+ return [];
229
+ }
230
+ }
231
+
232
+ function makeOps(pool, name, param, param$1, param$2, param$3, lockStrategyOpt, onAppendedOpt) {
233
+ let lockStrategy = lockStrategyOpt !== undefined ? lockStrategyOpt : "AdvisoryLocks";
234
+ let onAppended = onAppendedOpt !== undefined ? onAppendedOpt : noTracking;
235
+ let currentHead = async () => {
236
+ let row = await PgDriver$ReventlessPostgres.queryOne(pool, "SELECT lpad(transaction_id::text, 20, '0') || ':' || lpad(position::text, 20, '0') AS head\n FROM dcb_event\n WHERE log_name = $1 AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())\n ORDER BY transaction_id DESC, position DESC\n LIMIT 1", [name]);
237
+ if (row === undefined) {
238
+ return;
239
+ }
240
+ let match = row["head"];
241
+ if (typeof match === "string") {
242
+ return match;
243
+ }
244
+ };
245
+ let runQuery = async (query, after) => {
246
+ let b = {
247
+ params: []
248
+ };
249
+ let where = buildReadWhere(b, name, query, after, true);
250
+ let sql = `SELECT ` + selectColumns + ` FROM dcb_event WHERE ` + where + ` ORDER BY transaction_id ASC, position ASC`;
251
+ return (await PgDriver$ReventlessPostgres.query(pool, sql, b.params)).map(rowToEvent);
252
+ };
253
+ let read = async (query, after) => {
254
+ let afterCols = Stdlib_Option.flatMap(after, decodeCursor);
255
+ let events = await runQuery(query, afterCols);
256
+ let head = await currentHead();
257
+ if (head !== undefined) {
258
+ return {
259
+ events: events,
260
+ headPosition: head
261
+ };
262
+ } else {
263
+ return {
264
+ events: events
265
+ };
266
+ }
267
+ };
268
+ let append = async (newEvents, condition) => {
269
+ let eventsJson = newEvents.map(ev => (Object.fromEntries([
270
+ [
271
+ "event_type",
272
+ ev.eventType
273
+ ],
274
+ [
275
+ "tags",
276
+ ev.tags.map(t => t.key + "=" + t.value)
277
+ ],
278
+ [
279
+ "data",
280
+ ev.data
281
+ ],
282
+ [
283
+ "meta",
284
+ Util_Sury$Reventless.toJson(ev.meta, Message$Reventless.metaSchema)
285
+ ]
286
+ ])));
287
+ let conditionParam;
288
+ if (condition !== undefined) {
289
+ let queryJson = condition.query.map(clause => {
290
+ let types = clause.eventTypes;
291
+ let tags = clause.tags;
292
+ return Object.fromEntries([
293
+ [
294
+ "eventTypes",
295
+ types !== undefined ? types.map(prim => prim) : null
296
+ ],
297
+ [
298
+ "tags",
299
+ tags !== undefined ? tags.map(t => t.key + "=" + t.value) : null
300
+ ]
301
+ ]);
302
+ });
303
+ let fields = [[
304
+ "query",
305
+ queryJson
306
+ ]];
307
+ let a = condition.after;
308
+ if (a !== undefined) {
309
+ fields.push([
310
+ "after",
311
+ a
312
+ ]);
313
+ }
314
+ conditionParam = JSON.stringify(Object.fromEntries(fields));
315
+ } else {
316
+ conditionParam = null;
317
+ }
318
+ try {
319
+ let rows = await PgDriver$ReventlessPostgres.query(pool, "SELECT dcb_append($1, $2::jsonb, $3::jsonb, $4) AS pos", [
320
+ name,
321
+ JSON.stringify(eventsJson),
322
+ conditionParam,
323
+ strategyParam(lockStrategy)
324
+ ]);
325
+ let match = Stdlib_Option.flatMap(rows[0], r => r["pos"]);
326
+ if (match === undefined) {
327
+ return {
328
+ TAG: "Error",
329
+ _0: {
330
+ TAG: "StorageFailure",
331
+ _0: "dcb_append returned no position"
332
+ }
333
+ };
334
+ }
335
+ if (typeof match !== "string") {
336
+ return {
337
+ TAG: "Error",
338
+ _0: {
339
+ TAG: "StorageFailure",
340
+ _0: "dcb_append returned no position"
341
+ }
342
+ };
343
+ }
344
+ onAppended(Stdlib_Array.filterMap(newEvents, ev => {
345
+ let match$1 = decodeCursor(match);
346
+ if (match$1 !== undefined) {
347
+ return Stdlib_Option.map(Stdlib_Int.fromString(match$1[1], undefined), p => [
348
+ ev.meta.msgId,
349
+ p
350
+ ]);
351
+ }
352
+ }));
353
+ return {
354
+ TAG: "Ok",
355
+ _0: match
356
+ };
357
+ } catch (raw_exn) {
358
+ let exn = Primitive_exceptions.internalToException(raw_exn);
359
+ if (isConflict(exn)) {
360
+ return {
361
+ TAG: "Error",
362
+ _0: "Conflict"
363
+ };
364
+ } else {
365
+ return {
366
+ TAG: "Error",
367
+ _0: {
368
+ TAG: "StorageFailure",
369
+ _0: Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(exn), Stdlib_JsExn.message), "storage error")
370
+ }
371
+ };
372
+ }
373
+ }
374
+ };
375
+ let readStream = (query, after, param) => Stream.paginateEffect(Stdlib_Option.flatMap(after, decodeCursor), cursor => Effect.map(Effect.promise(() => {
376
+ let b = {
377
+ params: []
378
+ };
379
+ let where = buildReadWhere(b, name, query, cursor, true);
380
+ let sql = `SELECT ` + selectColumns + `, transaction_id::text AS tx_raw, position::text AS pos_raw FROM dcb_event WHERE ` + where + ` ORDER BY transaction_id ASC, position ASC LIMIT ` + (500).toString();
381
+ return PgDriver$ReventlessPostgres.query(pool, sql, b.params);
382
+ }), rows => {
383
+ let events = rows.map(rowToEvent);
384
+ let next;
385
+ if (rows.length < 500) {
386
+ next = undefined;
387
+ } else {
388
+ let lastRow = rows[rows.length - 1 | 0];
389
+ if (lastRow !== undefined) {
390
+ let match = lastRow["tx_raw"];
391
+ let match$1 = lastRow["pos_raw"];
392
+ next = typeof match === "string" && typeof match$1 === "string" ? Primitive_option.some([
393
+ match,
394
+ match$1
395
+ ]) : undefined;
396
+ } else {
397
+ next = undefined;
398
+ }
399
+ }
400
+ return [
401
+ events,
402
+ next
403
+ ];
404
+ }));
405
+ let ops = {
406
+ read: read,
407
+ append: append,
408
+ readStream: readStream
409
+ };
410
+ return [
411
+ name,
412
+ ops
413
+ ];
414
+ }
415
+
416
+ let pageSize = 500;
417
+
418
+ export {
419
+ strategyParam,
420
+ noTracking,
421
+ selectColumns,
422
+ decodeTag,
423
+ decodeTags,
424
+ rowToEvent,
425
+ mkBuilder,
426
+ param,
427
+ buildReadWhere,
428
+ stripZeros,
429
+ decodeCursor,
430
+ pageSize,
431
+ isConflict,
432
+ countAll,
433
+ readBackwards,
434
+ positionsOfAppend,
435
+ makeOps,
436
+ }
437
+ /* Stream Not a pure module */
@@ -0,0 +1,193 @@
1
+ // Classic `event_log` change feed (B2.5) — the aggregate-path analogue of
2
+ // `PgChangeFeed` (which serves the DCB `dcb_event` log).
3
+ //
4
+ // Like the DCB feed this is NOT logical decoding: classic events are already
5
+ // durably queryable in-table, so the feed is an xmin-fenced read over `event_log`
6
+ // plus an `event_log_subscription` checkpoint. A statement-level AFTER INSERT
7
+ // trigger (`event_log_notify`, see PgSchema) issues `pg_notify('evlog_<log>')`,
8
+ // turning polling into near-real-time wakeup; a low-frequency fallback tick in the
9
+ // consumer covers missed notifications.
10
+ //
11
+ // Cursor semantics mirror the DCB feed exactly: the opaque `<xid8>:<global_seq>`
12
+ // string (zero-padded so string order == numeric order). Reads apply the xmin
13
+ // barrier (`transaction_id < pg_snapshot_xmin(pg_current_snapshot())`), so a
14
+ // returned cursor is stable forever — an event committed late (lower global_seq,
15
+ // later commit) is never skipped by a checkpointing reader. `global_seq` alone,
16
+ // being an IDENTITY assigned at INSERT, could NOT provide that guarantee.
17
+
18
+ // Reuse the shared `<a>:<b>` cursor codec from the DCB storage — identical
19
+ // format. Point at the runtime-pure `_Ops` module (no `@pulumi/pulumi`): this
20
+ // feed is drained by the deployed change-feed relay Lambda, whose cold-start
21
+ // graph must stay Pulumi-free.
22
+ module Dcb = DcbEventLogStorage_Postgres_Ops
23
+
24
+ // One classic event as the feed surfaces it. `payload` is the stored event JSON
25
+ // verbatim; a bus/topic relay transforms it into its target shape (e.g. the AWS
26
+ // EventCollector `{id, meta, event}` body) — that transform is not this package's
27
+ // concern.
28
+ type classicEvent = {
29
+ cursor: string,
30
+ aggregateId: string,
31
+ seqNr: int,
32
+ payload: JSON.t,
33
+ msgId: option<string>,
34
+ }
35
+
36
+ // One page of the feed. `events` are in (transaction_id, global_seq) order;
37
+ // `cursor` is the checkpoint to persist and to pass as the next `after` (None when
38
+ // the page was empty — nothing new).
39
+ type batch = {
40
+ events: array<classicEvent>,
41
+ cursor: option<string>,
42
+ }
43
+
44
+ let selectColumns = "
45
+ lpad(transaction_id::text, 20, '0') || ':' || lpad(global_seq::text, 20, '0') AS cursor,
46
+ aggregate_id,
47
+ seq_nr,
48
+ payload,
49
+ msg_id
50
+ "
51
+
52
+ let coerceInt = (v: JSON.t): int =>
53
+ switch v {
54
+ | JSON.Number(n) => Float.toInt(n)
55
+ | JSON.String(s) => s->Int.fromString->Option.getOr(0)
56
+ | _ => 0
57
+ }
58
+
59
+ let rowToEvent = (row: dict<JSON.t>): classicEvent => {
60
+ let str = key =>
61
+ switch row->Dict.get(key) {
62
+ | Some(JSON.String(s)) => s
63
+ | _ => ""
64
+ }
65
+ {
66
+ cursor: str("cursor"),
67
+ aggregateId: str("aggregate_id"),
68
+ seqNr: row->Dict.get("seq_nr")->Option.map(coerceInt)->Option.getOr(0),
69
+ payload: row->Dict.get("payload")->Option.getOr(JSON.Encode.null),
70
+ msgId: switch row->Dict.get("msg_id") {
71
+ | Some(JSON.String(s)) => Some(s)
72
+ | _ => None
73
+ },
74
+ }
75
+ }
76
+
77
+ // Read up to `limit` events after `after` (the xmin-fenced feed query — whole log).
78
+ // Returns the events and the cursor of the last one.
79
+ let readBatch = async (
80
+ pool: PgDriver.pool,
81
+ ~logName: string,
82
+ ~after: option<string>=?,
83
+ ~limit: int=500,
84
+ ): batch => {
85
+ let params = [JSON.Encode.string(logName)]
86
+ let where = ref("log_name = $1 AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())")
87
+ switch after->Option.flatMap(Dcb.decodeCursor) {
88
+ | Some((tx, pos)) =>
89
+ // $2 = tx (referenced twice), $3 = global_seq.
90
+ params->Array.push(JSON.Encode.string(tx))
91
+ params->Array.push(JSON.Encode.string(pos))
92
+ where :=
93
+ where.contents ++ " AND (transaction_id > $2::xid8 OR (transaction_id = $2::xid8 AND global_seq > $3::bigint))"
94
+ | None => ()
95
+ }
96
+ let sql = `SELECT ${selectColumns} FROM event_log WHERE ${where.contents} ORDER BY transaction_id ASC, global_seq ASC LIMIT ${Int.toString(
97
+ limit,
98
+ )}`
99
+ let rows = await pool->PgDriver.query(sql, params)
100
+ let events = rows->Array.map(rowToEvent)
101
+ let cursor = switch events->Array.get(events->Array.length - 1) {
102
+ | Some(last) => Some(last.cursor)
103
+ | None => None
104
+ }
105
+ {events, cursor}
106
+ }
107
+
108
+ // --- Checkpoint contract (event_log_subscription) ---
109
+
110
+ // The persisted checkpoint for `subscriber`, encoded as a cursor, or None if the
111
+ // subscriber has never committed (→ replay from the beginning).
112
+ let loadCheckpoint = async (pool: PgDriver.pool, ~subscriber: string): option<string> =>
113
+ switch await pool->PgDriver.queryOne(
114
+ "SELECT lpad(last_tx::text, 20, '0') || ':' || lpad(last_global_seq::text, 20, '0') AS cursor
115
+ FROM event_log_subscription WHERE subscriber = $1 AND last_global_seq > 0",
116
+ [JSON.Encode.string(subscriber)],
117
+ ) {
118
+ | Some(row) =>
119
+ switch row->Dict.get("cursor") {
120
+ | Some(JSON.String(s)) => Some(s)
121
+ | _ => None
122
+ }
123
+ | None => None
124
+ }
125
+
126
+ // Persist the checkpoint. Idempotent upsert; decodes the cursor to its two columns
127
+ // so a later `loadCheckpoint` round-trips exactly.
128
+ let saveCheckpoint = async (pool: PgDriver.pool, ~subscriber: string, ~cursor: string): unit =>
129
+ switch Dcb.decodeCursor(cursor) {
130
+ | Some((tx, pos)) =>
131
+ let _ = await pool->PgDriver.query(
132
+ "INSERT INTO event_log_subscription(subscriber, last_tx, last_global_seq)
133
+ VALUES ($1, $2::xid8, $3::bigint)
134
+ ON CONFLICT (subscriber)
135
+ DO UPDATE SET last_tx = EXCLUDED.last_tx, last_global_seq = EXCLUDED.last_global_seq",
136
+ [JSON.Encode.string(subscriber), JSON.Encode.string(tx), JSON.Encode.string(pos)],
137
+ )
138
+ | None => ()
139
+ }
140
+
141
+ // --- Wakeup ---
142
+
143
+ // LISTEN on `evlog_<logName>`; `onWake` fires on every notification. Returns the
144
+ // dedicated client (caller owns it — release via unlisten). Pair with a
145
+ // low-frequency fallback tick so a missed NOTIFY only adds latency, never a stall.
146
+ let listen = (pool: PgDriver.pool, ~logName: string, ~onWake: unit => unit): promise<
147
+ PgDriver.client,
148
+ > => pool->PgDriver.listen(~channel="evlog_" ++ logName, ~onNotify=_ => onWake())
149
+
150
+ let unlisten = (client: PgDriver.client, ~logName: string): promise<unit> =>
151
+ client->PgDriver.unlisten(~channel="evlog_" ++ logName)
152
+
153
+ // --- Reference consumer driver ---
154
+
155
+ // Drain the feed for `subscriber` from its checkpoint: repeatedly readBatch →
156
+ // `handle` the events → saveCheckpoint, until a short page. `handle` must be
157
+ // idempotent (a crash between handle and checkpoint replays the last batch).
158
+ // Returns the number of events processed.
159
+ let drain = async (
160
+ pool: PgDriver.pool,
161
+ ~logName: string,
162
+ ~subscriber: string,
163
+ ~limit: int=500,
164
+ ~handle: array<classicEvent> => promise<unit>,
165
+ ): int => {
166
+ let processed = ref(0)
167
+ let cursor = ref(await loadCheckpoint(pool, ~subscriber))
168
+ let continue = ref(true)
169
+ while continue.contents {
170
+ let {events, cursor: newCursor} = await readBatch(
171
+ pool,
172
+ ~logName,
173
+ ~after=?cursor.contents,
174
+ ~limit,
175
+ )
176
+ if events->Array.length == 0 {
177
+ continue := false
178
+ } else {
179
+ await handle(events)
180
+ switch newCursor {
181
+ | Some(c) =>
182
+ await saveCheckpoint(pool, ~subscriber, ~cursor=c)
183
+ cursor := Some(c)
184
+ | None => ()
185
+ }
186
+ processed := processed.contents + events->Array.length
187
+ if events->Array.length < limit {
188
+ continue := false
189
+ }
190
+ }
191
+ }
192
+ processed.contents
193
+ }