@reventlessdev/reventless-postgres 3.0.0-alpha.2 → 3.0.0-alpha.21
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/CHANGELOG.md +149 -0
- package/README.md +83 -0
- package/lib/bs/.compiler.log +2 -2
- package/lib/bs/ReventlessPostgres.cmi +0 -0
- package/lib/bs/ReventlessPostgres.cmt +0 -0
- package/lib/bs/ReventlessPostgres.mlmap +4 -1
- package/lib/bs/compiler-info.json +2 -2
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres.ast +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres.res +25 -340
- package/lib/bs/src/DcbEventLogStorage_Postgres.res.mjs +32 -348
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res +350 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogChangeFeed.ast +0 -0
- package/lib/bs/src/EventLogChangeFeed.res +184 -0
- package/lib/bs/src/EventLogChangeFeed.res.mjs +134 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogStorage_Postgres.ast +0 -0
- package/lib/bs/src/EventLogStorage_Postgres.res +12 -170
- package/lib/bs/src/EventLogStorage_Postgres.res.mjs +20 -186
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.res +180 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.res.mjs +202 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgSchema.ast +0 -0
- package/lib/bs/src/PgSchema.res +36 -2
- package/lib/bs/src/PgSchema.res.mjs +9 -2
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres.ast +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres.res +10 -212
- package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +27 -191
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.res +229 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryEnginePostgres.ast +0 -0
- package/lib/bs/src/QueryEnginePostgres.res +259 -0
- package/lib/bs/src/QueryEnginePostgres.res.mjs +165 -0
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
- package/lib/bs/tests/PostgresIntegrationTest.ast +0 -0
- package/lib/bs/tests/PostgresIntegrationTest.res +68 -0
- package/lib/bs/tests/PostgresIntegrationTest.res.mjs +49 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.ast +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.res +312 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
- package/lib/ocaml/.compiler.log +2 -2
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres.ast +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres.res +25 -340
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.res +350 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogChangeFeed.ast +0 -0
- package/lib/ocaml/EventLogChangeFeed.res +184 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogStorage_Postgres.ast +0 -0
- package/lib/ocaml/EventLogStorage_Postgres.res +12 -170
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops.res +180 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgSchema.ast +0 -0
- package/lib/ocaml/PgSchema.res +36 -2
- package/lib/ocaml/PostgresIntegrationTest.res +68 -0
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres.ast +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres.res +10 -212
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops.res +229 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryEnginePostgres.ast +0 -0
- package/lib/ocaml/QueryEnginePostgres.res +259 -0
- package/lib/ocaml/QueryEnginePostgresListPageTest.res +312 -0
- package/lib/ocaml/ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/ReventlessPostgres.mlmap +5 -0
- package/package.json +9 -9
- package/rescript.json +2 -1
- package/src/DcbEventLogStorage_Postgres.res +25 -340
- package/src/DcbEventLogStorage_Postgres.res.mjs +32 -348
- package/src/DcbEventLogStorage_Postgres_Ops.res +350 -0
- package/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
- package/src/EventLogChangeFeed.res +184 -0
- package/src/EventLogChangeFeed.res.mjs +134 -0
- package/src/EventLogStorage_Postgres.res +12 -170
- package/src/EventLogStorage_Postgres.res.mjs +20 -186
- package/src/EventLogStorage_Postgres_Ops.res +180 -0
- package/src/EventLogStorage_Postgres_Ops.res.mjs +202 -0
- package/src/PgSchema.res +36 -2
- package/src/PgSchema.res.mjs +9 -2
- package/src/QueryDbStorage_Postgres.res +10 -212
- package/src/QueryDbStorage_Postgres.res.mjs +27 -191
- package/src/QueryDbStorage_Postgres_Ops.res +229 -0
- package/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
- package/src/QueryEnginePostgres.res +259 -0
- package/src/QueryEnginePostgres.res.mjs +165 -0
- package/tests/PostgresIntegrationTest.res +68 -0
- package/tests/PostgresIntegrationTest.res.mjs +49 -0
- package/tests/QueryEnginePostgresListPageTest.res +312 -0
- package/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PostgresIntegrationTest.ast +0 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// Runtime-pure DCB event-log operations for the Postgres backend.
|
|
2
|
+
//
|
|
3
|
+
// Holds everything the DEPLOYED Lambda runtime needs and imports NO
|
|
4
|
+
// `@pulumi/pulumi` (deploy-time only). The deployed DCB command entry point pulls
|
|
5
|
+
// these ops in unconditionally at cold start, so a deploy-time dependency here
|
|
6
|
+
// would leak into the Lambda import graph and fail resolution on real Lambda. The
|
|
7
|
+
// thin `DcbEventLogStorage_Postgres` wrapper `include`s this and adds the
|
|
8
|
+
// deploy-time `Pulumi.Output`-shaped adapter for local/deploy consumers.
|
|
9
|
+
// See docs/plans/deployed-lambda-esm-self-containment.md (Rung-3 finding).
|
|
10
|
+
|
|
11
|
+
open ReventlessCore
|
|
12
|
+
open Reventless
|
|
13
|
+
|
|
14
|
+
// Lock strategy for concurrent appends (B4). Advisory (default) is safe under
|
|
15
|
+
// PgBouncer transaction mode; RowLocks avoids advisory-lock connection pinning
|
|
16
|
+
// on RDS Proxy at the cost of a companion `dcb_scope` table.
|
|
17
|
+
type lockStrategy = [#AdvisoryLocks | #RowLocks]
|
|
18
|
+
let strategyParam = s =>
|
|
19
|
+
switch s {
|
|
20
|
+
| #AdvisoryLocks => "advisory"
|
|
21
|
+
| #RowLocks => "rows"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Injected by reventless-local to feed the projection-checkpoint low-watermark
|
|
25
|
+
// (ProjectionPending, Dcb axis). Standalone/deploy use passes nothing.
|
|
26
|
+
type onAppended = array<(string, int)> => unit
|
|
27
|
+
let noTracking: onAppended = _ => ()
|
|
28
|
+
|
|
29
|
+
// SELECT list shared by read and readStream. `data`/`meta` are jsonb (returned
|
|
30
|
+
// already parsed); `tags` is text[] (a JS array); the cursor and recorded_at are
|
|
31
|
+
// computed in SQL so the row maps straight to a rawSequencedEvent.
|
|
32
|
+
let selectColumns = "
|
|
33
|
+
lpad(transaction_id::text, 20, '0') || ':' || lpad(position::text, 20, '0') AS cursor,
|
|
34
|
+
event_type,
|
|
35
|
+
tags,
|
|
36
|
+
data,
|
|
37
|
+
meta,
|
|
38
|
+
to_char(recorded_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS recorded_at
|
|
39
|
+
"
|
|
40
|
+
|
|
41
|
+
// Decode a 'key=value' tag string (split on the first '=') back to a DcbTag.tag.
|
|
42
|
+
let decodeTag = (s: string): DcbTag.tag =>
|
|
43
|
+
switch s->String.indexOf("=") {
|
|
44
|
+
| -1 => {key: s, value: ""}
|
|
45
|
+
| i => {
|
|
46
|
+
key: s->String.slice(~start=0, ~end=i),
|
|
47
|
+
value: s->String.slice(~start=i + 1, ~end=s->String.length),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let decodeTags = (v: option<JSON.t>): array<DcbTag.tag> =>
|
|
52
|
+
switch v {
|
|
53
|
+
| Some(JSON.Array(arr)) =>
|
|
54
|
+
arr->Array.filterMap(x =>
|
|
55
|
+
switch x {
|
|
56
|
+
| JSON.String(s) => Some(decodeTag(s))
|
|
57
|
+
| _ => None
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
| _ => []
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let rowToEvent = (row: dict<JSON.t>): DcbEventLog_Adapter.rawSequencedEvent => {
|
|
64
|
+
let str = key =>
|
|
65
|
+
switch row->Dict.get(key) {
|
|
66
|
+
| Some(JSON.String(s)) => s
|
|
67
|
+
| _ => ""
|
|
68
|
+
}
|
|
69
|
+
let meta = switch row->Dict.get("meta") {
|
|
70
|
+
| Some(metaJson) => metaJson->S.parseJsonOrThrow(Reventless.Message.metaSchema)
|
|
71
|
+
| None => JsError.throwWithMessage("missing meta column in dcb_event row")
|
|
72
|
+
}
|
|
73
|
+
{
|
|
74
|
+
DcbEventLog_Adapter.position: str("cursor"),
|
|
75
|
+
eventType: str("event_type"),
|
|
76
|
+
data: row->Dict.get("data")->Option.getOr(JSON.Encode.null),
|
|
77
|
+
tags: decodeTags(row->Dict.get("tags")),
|
|
78
|
+
meta,
|
|
79
|
+
recordedAt: str("recorded_at"),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// A tiny positional-parameter builder. Postgres uses `$1, $2, …` (not `?`), so we
|
|
84
|
+
// accumulate params and mint tokens as we build the WHERE. A token may be reused
|
|
85
|
+
// (same `$N`) to reference one param twice — used for the `after` cursor columns.
|
|
86
|
+
type paramBuilder = {mutable params: array<JSON.t>}
|
|
87
|
+
let mkBuilder = () => {params: []}
|
|
88
|
+
let param = (b: paramBuilder, v: JSON.t): string => {
|
|
89
|
+
b.params->Array.push(v)
|
|
90
|
+
"$" ++ Int.toString(b.params->Array.length)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Build the read WHERE + params for a query. `applyFence` gates the xmin read
|
|
94
|
+
// barrier (true for consumer reads, so cursors are stable). `after` is the
|
|
95
|
+
// decoded (tx, pos) cursor pair as numeric strings.
|
|
96
|
+
let buildReadWhere = (
|
|
97
|
+
b: paramBuilder,
|
|
98
|
+
~name: string,
|
|
99
|
+
~query: DcbTag.query,
|
|
100
|
+
~after: option<(string, string)>,
|
|
101
|
+
~applyFence: bool,
|
|
102
|
+
): string => {
|
|
103
|
+
let parts = [`log_name = ${b->param(JSON.Encode.string(name))}`]
|
|
104
|
+
if applyFence {
|
|
105
|
+
parts->Array.push("transaction_id < pg_snapshot_xmin(pg_current_snapshot())")
|
|
106
|
+
}
|
|
107
|
+
switch after {
|
|
108
|
+
| Some((tx, pos)) =>
|
|
109
|
+
let txP = b->param(JSON.Encode.string(tx))
|
|
110
|
+
let posP = b->param(JSON.Encode.string(pos))
|
|
111
|
+
parts->Array.push(
|
|
112
|
+
`(transaction_id > ${txP}::xid8 OR (transaction_id = ${txP}::xid8 AND position > ${posP}::bigint))`,
|
|
113
|
+
)
|
|
114
|
+
| None => ()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if query->Array.length > 0 {
|
|
118
|
+
let clauseSqls = query->Array.map(clause => {
|
|
119
|
+
let clauseParts = []
|
|
120
|
+
switch clause.eventTypes {
|
|
121
|
+
| Some(types) if types->Array.length > 0 =>
|
|
122
|
+
let ph = types->Array.map(t => b->param(JSON.Encode.string(t)))->Array.join(",")
|
|
123
|
+
clauseParts->Array.push(`event_type IN (${ph})`)
|
|
124
|
+
| _ => ()
|
|
125
|
+
}
|
|
126
|
+
switch clause.tags {
|
|
127
|
+
| Some(tags) if tags->Array.length > 0 =>
|
|
128
|
+
let arr =
|
|
129
|
+
tags
|
|
130
|
+
->Array.map(t => b->param(JSON.Encode.string(t.key ++ "=" ++ t.value)))
|
|
131
|
+
->Array.join(",")
|
|
132
|
+
clauseParts->Array.push(`tags @> ARRAY[${arr}]::text[]`)
|
|
133
|
+
| _ => ()
|
|
134
|
+
}
|
|
135
|
+
clauseParts->Array.length == 0 ? "TRUE" : "(" ++ clauseParts->Array.join(" AND ") ++ ")"
|
|
136
|
+
})
|
|
137
|
+
parts->Array.push("(" ++ clauseSqls->Array.join(" OR ") ++ ")")
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
parts->Array.join(" AND ")
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Strip the zero-padding a cursor carries for string-sortability, leaving a
|
|
144
|
+
// plain decimal both `::xid8` and `::bigint` parse unambiguously ("0" if empty).
|
|
145
|
+
let stripZeros = (s: string): string => {
|
|
146
|
+
let t = s->String.replaceRegExp(%re("/^0+/"), "")
|
|
147
|
+
t == "" ? "0" : t
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Split a '<xid8>:<position>' cursor into its two numeric-string columns.
|
|
151
|
+
let decodeCursor = (pos: DcbTag.sequencePosition): option<(string, string)> =>
|
|
152
|
+
switch pos->String.split(":") {
|
|
153
|
+
| [tx, p] => Some((stripZeros(tx), stripZeros(p)))
|
|
154
|
+
| _ => None
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Rows-per-page for readStream keyset pagination.
|
|
158
|
+
let pageSize = 500
|
|
159
|
+
|
|
160
|
+
let isConflict = (exn: exn): bool => {
|
|
161
|
+
let msg = exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("")
|
|
162
|
+
msg->String.includes("dcb_conflict") ||
|
|
163
|
+
msg->String.includes("duplicate key") ||
|
|
164
|
+
msg->String.includes("23505")
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
let countAll = async (pool: PgDriver.pool): int =>
|
|
168
|
+
switch await pool->PgDriver.queryOne("SELECT COUNT(*)::bigint AS c FROM dcb_event", []) {
|
|
169
|
+
| Some(row) =>
|
|
170
|
+
switch row->Dict.get("c") {
|
|
171
|
+
| Some(JSON.String(s)) => s->Int.fromString->Option.getOr(0)
|
|
172
|
+
| Some(JSON.Number(n)) => Float.toInt(n)
|
|
173
|
+
| _ => 0
|
|
174
|
+
}
|
|
175
|
+
| None => 0
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Builds the DCB runtime op set bound to `pool`. Returns `(name, ops)`; the
|
|
179
|
+
// deploy-time `DcbEventLog_Adapter` wrapper lives in `DcbEventLogStorage_Postgres`.
|
|
180
|
+
let makeOps = (
|
|
181
|
+
~pool: PgDriver.pool,
|
|
182
|
+
~name: string,
|
|
183
|
+
~indexes as _,
|
|
184
|
+
~partitionTag as _,
|
|
185
|
+
~crossPartitionTagKeys as _=?,
|
|
186
|
+
~opts as _,
|
|
187
|
+
~lockStrategy: lockStrategy=#AdvisoryLocks,
|
|
188
|
+
~onAppended=noTracking,
|
|
189
|
+
): (string, DcbEventLog_Adapter.operations) => {
|
|
190
|
+
// Fenced head cursor: the highest (transaction_id, position) visible under the
|
|
191
|
+
// xmin barrier. Stable across reads, so it is a safe consistency marker.
|
|
192
|
+
let currentHead = async (): option<string> =>
|
|
193
|
+
switch await pool->PgDriver.queryOne(
|
|
194
|
+
"SELECT lpad(transaction_id::text, 20, '0') || ':' || lpad(position::text, 20, '0') AS head
|
|
195
|
+
FROM dcb_event
|
|
196
|
+
WHERE log_name = $1 AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())
|
|
197
|
+
ORDER BY transaction_id DESC, position DESC
|
|
198
|
+
LIMIT 1",
|
|
199
|
+
[JSON.Encode.string(name)],
|
|
200
|
+
) {
|
|
201
|
+
| Some(row) =>
|
|
202
|
+
switch row->Dict.get("head") {
|
|
203
|
+
| Some(JSON.String(s)) => Some(s)
|
|
204
|
+
| _ => None
|
|
205
|
+
}
|
|
206
|
+
| None => None
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let runQuery = async (~query, ~after): array<DcbEventLog_Adapter.rawSequencedEvent> => {
|
|
210
|
+
let b = mkBuilder()
|
|
211
|
+
let where = buildReadWhere(b, ~name, ~query, ~after, ~applyFence=true)
|
|
212
|
+
let sql = `SELECT ${selectColumns} FROM dcb_event WHERE ${where} ORDER BY transaction_id ASC, position ASC`
|
|
213
|
+
(await pool->PgDriver.query(sql, b.params))->Array.map(rowToEvent)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let read = async (~query: DcbTag.query, ~after=?): DcbEventLog_Adapter.rawReadResult => {
|
|
217
|
+
let afterCols = after->Option.flatMap(decodeCursor)
|
|
218
|
+
let events = await runQuery(~query, ~after=afterCols)
|
|
219
|
+
switch await currentHead() {
|
|
220
|
+
| Some(head) => {DcbEventLog_Adapter.events, headPosition: head}
|
|
221
|
+
| None => ({DcbEventLog_Adapter.events: events}: DcbEventLog_Adapter.rawReadResult)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
let append = async (
|
|
226
|
+
newEvents: array<DcbEventLog_Adapter.rawStoredEvent>,
|
|
227
|
+
~condition=?,
|
|
228
|
+
): result<DcbTag.sequencePosition, ReventlessInfra.DcbEventLog.appendError> => {
|
|
229
|
+
let eventsJson = JSON.Array(
|
|
230
|
+
newEvents->Array.map(ev =>
|
|
231
|
+
JSON.Object(
|
|
232
|
+
Dict.fromArray([
|
|
233
|
+
("event_type", JSON.Encode.string(ev.eventType)),
|
|
234
|
+
(
|
|
235
|
+
"tags",
|
|
236
|
+
JSON.Array(ev.tags->Array.map(t => JSON.Encode.string(t.key ++ "=" ++ t.value))),
|
|
237
|
+
),
|
|
238
|
+
("data", ev.data),
|
|
239
|
+
("meta", ev.meta->S.reverseConvertToJsonOrThrow(Reventless.Message.metaSchema)),
|
|
240
|
+
]),
|
|
241
|
+
)
|
|
242
|
+
),
|
|
243
|
+
)
|
|
244
|
+
let conditionParam = switch condition {
|
|
245
|
+
| Some(cond: DcbTag.appendCondition) =>
|
|
246
|
+
let queryJson = JSON.Array(
|
|
247
|
+
cond.query->Array.map(clause =>
|
|
248
|
+
JSON.Object(
|
|
249
|
+
Dict.fromArray([
|
|
250
|
+
(
|
|
251
|
+
"eventTypes",
|
|
252
|
+
switch clause.eventTypes {
|
|
253
|
+
| Some(types) => JSON.Array(types->Array.map(JSON.Encode.string))
|
|
254
|
+
| None => JSON.Encode.null
|
|
255
|
+
},
|
|
256
|
+
),
|
|
257
|
+
(
|
|
258
|
+
"tags",
|
|
259
|
+
switch clause.tags {
|
|
260
|
+
| Some(tags) =>
|
|
261
|
+
JSON.Array(tags->Array.map(t => JSON.Encode.string(t.key ++ "=" ++ t.value)))
|
|
262
|
+
| None => JSON.Encode.null
|
|
263
|
+
},
|
|
264
|
+
),
|
|
265
|
+
]),
|
|
266
|
+
)
|
|
267
|
+
),
|
|
268
|
+
)
|
|
269
|
+
let fields = [("query", queryJson)]
|
|
270
|
+
switch cond.after {
|
|
271
|
+
| Some(a) => fields->Array.push(("after", JSON.Encode.string(a)))
|
|
272
|
+
| None => ()
|
|
273
|
+
}
|
|
274
|
+
JSON.Encode.string(JSON.stringify(JSON.Object(Dict.fromArray(fields))))
|
|
275
|
+
| None => JSON.Encode.null
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
try {
|
|
279
|
+
let rows = await pool->PgDriver.query(
|
|
280
|
+
"SELECT dcb_append($1, $2::jsonb, $3::jsonb, $4) AS pos",
|
|
281
|
+
[
|
|
282
|
+
JSON.Encode.string(name),
|
|
283
|
+
JSON.Encode.string(JSON.stringify(eventsJson)),
|
|
284
|
+
conditionParam,
|
|
285
|
+
JSON.Encode.string(strategyParam(lockStrategy)),
|
|
286
|
+
],
|
|
287
|
+
)
|
|
288
|
+
switch rows->Array.get(0)->Option.flatMap(r => r->Dict.get("pos")) {
|
|
289
|
+
| Some(JSON.String(cursor)) =>
|
|
290
|
+
// Feed the projection checkpoint (Dcb axis): (msgId, numeric position).
|
|
291
|
+
onAppended(
|
|
292
|
+
newEvents->Array.filterMap(ev =>
|
|
293
|
+
switch decodeCursor(cursor) {
|
|
294
|
+
| Some((_, pos)) =>
|
|
295
|
+
pos->Int.fromString->Option.map(p => (ev.meta.Reventless.Message.msgId, p))
|
|
296
|
+
| None => None
|
|
297
|
+
}
|
|
298
|
+
),
|
|
299
|
+
)
|
|
300
|
+
Ok(cursor)
|
|
301
|
+
| _ => Error(ReventlessInfra.DcbEventLog.StorageFailure("dcb_append returned no position"))
|
|
302
|
+
}
|
|
303
|
+
} catch {
|
|
304
|
+
| exn =>
|
|
305
|
+
isConflict(exn)
|
|
306
|
+
? Error(ReventlessInfra.DcbEventLog.Conflict)
|
|
307
|
+
: Error(
|
|
308
|
+
ReventlessInfra.DcbEventLog.StorageFailure(
|
|
309
|
+
exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("storage error"),
|
|
310
|
+
),
|
|
311
|
+
)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ~strongConsistency is a genuine no-op here: every read applies the xmin
|
|
316
|
+
// barrier, so it is always safely consistent (at the cost of a few ms lag).
|
|
317
|
+
//
|
|
318
|
+
// Keyset pagination on (transaction_id, position): one ordered SQL source, no
|
|
319
|
+
// per-clause fan-out / k-way merge / dedup (the DynamoDB runtime's layers have
|
|
320
|
+
// no Postgres counterpart). Each page reads strictly after the previous page's
|
|
321
|
+
// last row; a short page ends the stream.
|
|
322
|
+
let readStream = (~query: DcbTag.query, ~after=?, ~strongConsistency as _=?) =>
|
|
323
|
+
Stream.paginateEffect(after->Option.flatMap(decodeCursor), cursor =>
|
|
324
|
+
Effect.promise(() => {
|
|
325
|
+
let b = mkBuilder()
|
|
326
|
+
let where = buildReadWhere(b, ~name, ~query, ~after=cursor, ~applyFence=true)
|
|
327
|
+
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 ${Int.toString(pageSize)}`
|
|
328
|
+
pool->PgDriver.query(sql, b.params)
|
|
329
|
+
})->Effect.map(rows => {
|
|
330
|
+
let events = rows->Array.map(rowToEvent)
|
|
331
|
+
// Continue only on a full page; the next `after` is this page's last row.
|
|
332
|
+
let next = if rows->Array.length < pageSize {
|
|
333
|
+
None
|
|
334
|
+
} else {
|
|
335
|
+
switch rows->Array.get(rows->Array.length - 1) {
|
|
336
|
+
| Some(lastRow) =>
|
|
337
|
+
switch (lastRow->Dict.get("tx_raw"), lastRow->Dict.get("pos_raw")) {
|
|
338
|
+
| (Some(JSON.String(tx)), Some(JSON.String(p))) => Some(Some((tx, p)))
|
|
339
|
+
| _ => None
|
|
340
|
+
}
|
|
341
|
+
| None => None
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
(events, next)
|
|
345
|
+
})
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
let ops: DcbEventLog_Adapter.operations = {read, append, readStream}
|
|
349
|
+
(name, ops)
|
|
350
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,184 @@
|
|
|
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 format.
|
|
19
|
+
module Dcb = DcbEventLogStorage_Postgres
|
|
20
|
+
|
|
21
|
+
// One classic event as the feed surfaces it. `payload` is the stored event JSON
|
|
22
|
+
// verbatim; a bus/topic relay transforms it into its target shape (e.g. the AWS
|
|
23
|
+
// EventCollector `{id, meta, event}` body) — that transform is not this package's
|
|
24
|
+
// concern.
|
|
25
|
+
type classicEvent = {
|
|
26
|
+
cursor: string,
|
|
27
|
+
aggregateId: string,
|
|
28
|
+
seqNr: int,
|
|
29
|
+
payload: JSON.t,
|
|
30
|
+
msgId: option<string>,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// One page of the feed. `events` are in (transaction_id, global_seq) order;
|
|
34
|
+
// `cursor` is the checkpoint to persist and to pass as the next `after` (None when
|
|
35
|
+
// the page was empty — nothing new).
|
|
36
|
+
type batch = {
|
|
37
|
+
events: array<classicEvent>,
|
|
38
|
+
cursor: option<string>,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let selectColumns = "
|
|
42
|
+
lpad(transaction_id::text, 20, '0') || ':' || lpad(global_seq::text, 20, '0') AS cursor,
|
|
43
|
+
aggregate_id,
|
|
44
|
+
seq_nr,
|
|
45
|
+
payload,
|
|
46
|
+
msg_id
|
|
47
|
+
"
|
|
48
|
+
|
|
49
|
+
let coerceInt = (v: JSON.t): int =>
|
|
50
|
+
switch v {
|
|
51
|
+
| JSON.Number(n) => Float.toInt(n)
|
|
52
|
+
| JSON.String(s) => s->Int.fromString->Option.getOr(0)
|
|
53
|
+
| _ => 0
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let rowToEvent = (row: dict<JSON.t>): classicEvent => {
|
|
57
|
+
let str = key =>
|
|
58
|
+
switch row->Dict.get(key) {
|
|
59
|
+
| Some(JSON.String(s)) => s
|
|
60
|
+
| _ => ""
|
|
61
|
+
}
|
|
62
|
+
{
|
|
63
|
+
cursor: str("cursor"),
|
|
64
|
+
aggregateId: str("aggregate_id"),
|
|
65
|
+
seqNr: row->Dict.get("seq_nr")->Option.map(coerceInt)->Option.getOr(0),
|
|
66
|
+
payload: row->Dict.get("payload")->Option.getOr(JSON.Encode.null),
|
|
67
|
+
msgId: switch row->Dict.get("msg_id") {
|
|
68
|
+
| Some(JSON.String(s)) => Some(s)
|
|
69
|
+
| _ => None
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Read up to `limit` events after `after` (the xmin-fenced feed query — whole log).
|
|
75
|
+
// Returns the events and the cursor of the last one.
|
|
76
|
+
let readBatch = async (
|
|
77
|
+
pool: PgDriver.pool,
|
|
78
|
+
~logName: string,
|
|
79
|
+
~after: option<string>=?,
|
|
80
|
+
~limit: int=500,
|
|
81
|
+
): batch => {
|
|
82
|
+
let params = [JSON.Encode.string(logName)]
|
|
83
|
+
let where = ref("log_name = $1 AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())")
|
|
84
|
+
switch after->Option.flatMap(Dcb.decodeCursor) {
|
|
85
|
+
| Some((tx, pos)) =>
|
|
86
|
+
// $2 = tx (referenced twice), $3 = global_seq.
|
|
87
|
+
params->Array.push(JSON.Encode.string(tx))
|
|
88
|
+
params->Array.push(JSON.Encode.string(pos))
|
|
89
|
+
where :=
|
|
90
|
+
where.contents ++
|
|
91
|
+
" AND (transaction_id > $2::xid8 OR (transaction_id = $2::xid8 AND global_seq > $3::bigint))"
|
|
92
|
+
| None => ()
|
|
93
|
+
}
|
|
94
|
+
let sql = `SELECT ${selectColumns} FROM event_log WHERE ${where.contents} ORDER BY transaction_id ASC, global_seq ASC LIMIT ${Int.toString(limit)}`
|
|
95
|
+
let rows = await pool->PgDriver.query(sql, params)
|
|
96
|
+
let events = rows->Array.map(rowToEvent)
|
|
97
|
+
let cursor = switch events->Array.get(events->Array.length - 1) {
|
|
98
|
+
| Some(last) => Some(last.cursor)
|
|
99
|
+
| None => None
|
|
100
|
+
}
|
|
101
|
+
{events, cursor}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// --- Checkpoint contract (event_log_subscription) ---
|
|
105
|
+
|
|
106
|
+
// The persisted checkpoint for `subscriber`, encoded as a cursor, or None if the
|
|
107
|
+
// subscriber has never committed (→ replay from the beginning).
|
|
108
|
+
let loadCheckpoint = async (pool: PgDriver.pool, ~subscriber: string): option<string> =>
|
|
109
|
+
switch await pool->PgDriver.queryOne(
|
|
110
|
+
"SELECT lpad(last_tx::text, 20, '0') || ':' || lpad(last_global_seq::text, 20, '0') AS cursor
|
|
111
|
+
FROM event_log_subscription WHERE subscriber = $1 AND last_global_seq > 0",
|
|
112
|
+
[JSON.Encode.string(subscriber)],
|
|
113
|
+
) {
|
|
114
|
+
| Some(row) =>
|
|
115
|
+
switch row->Dict.get("cursor") {
|
|
116
|
+
| Some(JSON.String(s)) => Some(s)
|
|
117
|
+
| _ => None
|
|
118
|
+
}
|
|
119
|
+
| None => None
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Persist the checkpoint. Idempotent upsert; decodes the cursor to its two columns
|
|
123
|
+
// so a later `loadCheckpoint` round-trips exactly.
|
|
124
|
+
let saveCheckpoint = async (pool: PgDriver.pool, ~subscriber: string, ~cursor: string): unit =>
|
|
125
|
+
switch Dcb.decodeCursor(cursor) {
|
|
126
|
+
| Some((tx, pos)) =>
|
|
127
|
+
let _ = await pool->PgDriver.query(
|
|
128
|
+
"INSERT INTO event_log_subscription(subscriber, last_tx, last_global_seq)
|
|
129
|
+
VALUES ($1, $2::xid8, $3::bigint)
|
|
130
|
+
ON CONFLICT (subscriber)
|
|
131
|
+
DO UPDATE SET last_tx = EXCLUDED.last_tx, last_global_seq = EXCLUDED.last_global_seq",
|
|
132
|
+
[JSON.Encode.string(subscriber), JSON.Encode.string(tx), JSON.Encode.string(pos)],
|
|
133
|
+
)
|
|
134
|
+
| None => ()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// --- Wakeup ---
|
|
138
|
+
|
|
139
|
+
// LISTEN on `evlog_<logName>`; `onWake` fires on every notification. Returns the
|
|
140
|
+
// dedicated client (caller owns it — release via unlisten). Pair with a
|
|
141
|
+
// low-frequency fallback tick so a missed NOTIFY only adds latency, never a stall.
|
|
142
|
+
let listen = (pool: PgDriver.pool, ~logName: string, ~onWake: unit => unit): promise<
|
|
143
|
+
PgDriver.client,
|
|
144
|
+
> => pool->PgDriver.listen(~channel="evlog_" ++ logName, ~onNotify=_ => onWake())
|
|
145
|
+
|
|
146
|
+
let unlisten = (client: PgDriver.client, ~logName: string): promise<unit> =>
|
|
147
|
+
client->PgDriver.unlisten(~channel="evlog_" ++ logName)
|
|
148
|
+
|
|
149
|
+
// --- Reference consumer driver ---
|
|
150
|
+
|
|
151
|
+
// Drain the feed for `subscriber` from its checkpoint: repeatedly readBatch →
|
|
152
|
+
// `handle` the events → saveCheckpoint, until a short page. `handle` must be
|
|
153
|
+
// idempotent (a crash between handle and checkpoint replays the last batch).
|
|
154
|
+
// Returns the number of events processed.
|
|
155
|
+
let drain = async (
|
|
156
|
+
pool: PgDriver.pool,
|
|
157
|
+
~logName: string,
|
|
158
|
+
~subscriber: string,
|
|
159
|
+
~limit: int=500,
|
|
160
|
+
~handle: array<classicEvent> => promise<unit>,
|
|
161
|
+
): int => {
|
|
162
|
+
let processed = ref(0)
|
|
163
|
+
let cursor = ref(await loadCheckpoint(pool, ~subscriber))
|
|
164
|
+
let continue = ref(true)
|
|
165
|
+
while continue.contents {
|
|
166
|
+
let {events, cursor: newCursor} = await readBatch(pool, ~logName, ~after=?cursor.contents, ~limit)
|
|
167
|
+
if events->Array.length == 0 {
|
|
168
|
+
continue := false
|
|
169
|
+
} else {
|
|
170
|
+
await handle(events)
|
|
171
|
+
switch newCursor {
|
|
172
|
+
| Some(c) =>
|
|
173
|
+
await saveCheckpoint(pool, ~subscriber, ~cursor=c)
|
|
174
|
+
cursor := Some(c)
|
|
175
|
+
| None => ()
|
|
176
|
+
}
|
|
177
|
+
processed := processed.contents + events->Array.length
|
|
178
|
+
if events->Array.length < limit {
|
|
179
|
+
continue := false
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
processed.contents
|
|
184
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|