@reventlessdev/reventless-postgres 3.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/LICENSE +202 -0
- package/__mocks__/emptyModule.js +1 -0
- package/lib/bs/.compiler.log +2 -0
- package/lib/bs/ReventlessPostgres.cmi +0 -0
- package/lib/bs/ReventlessPostgres.cmj +0 -0
- package/lib/bs/ReventlessPostgres.cmt +0 -0
- package/lib/bs/ReventlessPostgres.mlmap +9 -0
- package/lib/bs/build.ninja +0 -0
- package/lib/bs/compiler-info.json +8 -0
- 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 +352 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres.res.mjs +385 -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 +176 -0
- package/lib/bs/src/EventLogStorage_Postgres.res.mjs +207 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgChangeFeed.ast +0 -0
- package/lib/bs/src/PgChangeFeed.res +145 -0
- package/lib/bs/src/PgChangeFeed.res.mjs +90 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmti +0 -0
- package/lib/bs/src/PgDriver.ast +0 -0
- package/lib/bs/src/PgDriver.iast +0 -0
- package/lib/bs/src/PgDriver.res +111 -0
- package/lib/bs/src/PgDriver.res.mjs +85 -0
- package/lib/bs/src/PgDriver.resi +68 -0
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmj +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 +256 -0
- package/lib/bs/src/PgSchema.res.mjs +46 -0
- 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 +244 -0
- package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +225 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmj +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 +127 -0
- package/lib/bs/src/QueryEnginePostgres.res.mjs +172 -0
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmj +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 +236 -0
- package/lib/bs/tests/PostgresIntegrationTest.res.mjs +328 -0
- package/lib/ocaml/.compiler.log +2 -0
- 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 +352 -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 +176 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgChangeFeed.ast +0 -0
- package/lib/ocaml/PgChangeFeed.res +145 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmti +0 -0
- package/lib/ocaml/PgDriver.ast +0 -0
- package/lib/ocaml/PgDriver.iast +0 -0
- package/lib/ocaml/PgDriver.res +111 -0
- package/lib/ocaml/PgDriver.resi +68 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgSchema.ast +0 -0
- package/lib/ocaml/PgSchema.res +256 -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
- package/lib/ocaml/PostgresIntegrationTest.res +236 -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 +244 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryEnginePostgres.ast +0 -0
- package/lib/ocaml/QueryEnginePostgres.res +127 -0
- package/lib/ocaml/ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/ReventlessPostgres.mlmap +9 -0
- package/package.json +56 -0
- package/rescript.json +36 -0
- package/src/DcbEventLogStorage_Postgres.res +352 -0
- package/src/DcbEventLogStorage_Postgres.res.mjs +385 -0
- package/src/EventLogStorage_Postgres.res +176 -0
- package/src/EventLogStorage_Postgres.res.mjs +207 -0
- package/src/PgChangeFeed.res +145 -0
- package/src/PgChangeFeed.res.mjs +90 -0
- package/src/PgDriver.res +111 -0
- package/src/PgDriver.res.mjs +85 -0
- package/src/PgDriver.resi +68 -0
- package/src/PgSchema.res +256 -0
- package/src/PgSchema.res.mjs +46 -0
- package/src/QueryDbStorage_Postgres.res +244 -0
- package/src/QueryDbStorage_Postgres.res.mjs +225 -0
- package/src/QueryEnginePostgres.res +127 -0
- package/src/QueryEnginePostgres.res.mjs +172 -0
- package/tests/PostgresIntegrationTest.res +236 -0
- package/tests/PostgresIntegrationTest.res.mjs +328 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// node-postgres (`pg`) binding. See PgDriver.resi for the contract.
|
|
2
|
+
|
|
3
|
+
type pool
|
|
4
|
+
type client
|
|
5
|
+
|
|
6
|
+
// TLS options passed straight to node's tls. RDS Postgres (PG15+) defaults to
|
|
7
|
+
// `rds.force_ssl=1`, so a managed-Postgres pool must enable SSL. Verifying the
|
|
8
|
+
// RDS CA needs the bundle wired in (`ca`); `rejectUnauthorized: false` encrypts
|
|
9
|
+
// without CA verification — acceptable for v1, tighten later.
|
|
10
|
+
type sslConfig = {rejectUnauthorized: bool}
|
|
11
|
+
|
|
12
|
+
// pg calls the password provider (with no args) each time it opens a physical
|
|
13
|
+
// connection, so a rotated secret is picked up on the next new connection
|
|
14
|
+
// without rebuilding the pool.
|
|
15
|
+
type passwordProvider = unit => promise<string>
|
|
16
|
+
|
|
17
|
+
type poolConfig = {
|
|
18
|
+
// Either supply a full `connectionString`, or the discrete fields below (used
|
|
19
|
+
// by the AWS adapter, where the password comes from a Secrets Manager
|
|
20
|
+
// provider and cannot be baked into a static string).
|
|
21
|
+
connectionString?: string,
|
|
22
|
+
host?: string,
|
|
23
|
+
port?: int,
|
|
24
|
+
database?: string,
|
|
25
|
+
user?: string,
|
|
26
|
+
password?: passwordProvider,
|
|
27
|
+
ssl?: sslConfig,
|
|
28
|
+
max?: int,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// pg is CJS (`module.exports = { Pool, Client, ... }`); Node's ESM interop
|
|
32
|
+
// exposes `Pool` as a named import.
|
|
33
|
+
@module("pg") @new external makePool: poolConfig => pool = "Pool"
|
|
34
|
+
|
|
35
|
+
@send external _end: pool => promise<unit> = "end"
|
|
36
|
+
let endPool = pool => _end(pool)
|
|
37
|
+
|
|
38
|
+
// pg's `query` resolves to a result object; `.rows` is the payload we want.
|
|
39
|
+
type queryResult = {rows: array<dict<JSON.t>>}
|
|
40
|
+
|
|
41
|
+
@send external _query: (pool, string, array<JSON.t>) => promise<queryResult> = "query"
|
|
42
|
+
@send external _queryText: (pool, string) => promise<queryResult> = "query"
|
|
43
|
+
@send external _connect: pool => promise<client> = "connect"
|
|
44
|
+
@send external _release: client => unit = "release"
|
|
45
|
+
@send external _clientQuery: (client, string, array<JSON.t>) => promise<queryResult> = "query"
|
|
46
|
+
@send external _clientQueryText: (client, string) => promise<queryResult> = "query"
|
|
47
|
+
|
|
48
|
+
let query = async (pool, sql, params) => (await _query(pool, sql, params)).rows
|
|
49
|
+
|
|
50
|
+
let queryOne = async (pool, sql, params) =>
|
|
51
|
+
(await _query(pool, sql, params)).rows->Array.get(0)
|
|
52
|
+
|
|
53
|
+
let exec = async (pool, sql) => {
|
|
54
|
+
let _ = await _queryText(pool, sql)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let queryOn = async (client, sql, params) => (await _clientQuery(client, sql, params)).rows
|
|
58
|
+
let execOn = async (client, sql) => {
|
|
59
|
+
let _ = await _clientQueryText(client, sql)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let transaction = async (pool, fn) => {
|
|
63
|
+
let client = await _connect(pool)
|
|
64
|
+
try {
|
|
65
|
+
let _ = await _clientQueryText(client, "BEGIN")
|
|
66
|
+
let result = await fn(client)
|
|
67
|
+
let _ = await _clientQueryText(client, "COMMIT")
|
|
68
|
+
_release(client)
|
|
69
|
+
result
|
|
70
|
+
} catch {
|
|
71
|
+
| exn =>
|
|
72
|
+
// Roll back and release, but never let a failing ROLLBACK mask the original
|
|
73
|
+
// error (the original is the diagnostic one). Always return the connection.
|
|
74
|
+
try {
|
|
75
|
+
let _ = await _clientQueryText(client, "ROLLBACK")
|
|
76
|
+
} catch {
|
|
77
|
+
| _ => ()
|
|
78
|
+
}
|
|
79
|
+
_release(client)
|
|
80
|
+
throw(exn)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// LISTEN/NOTIFY on a dedicated connection. `notification` events carry
|
|
85
|
+
// `{channel, payload}`; we forward the payload string.
|
|
86
|
+
type notification = {payload: Nullable.t<string>}
|
|
87
|
+
@send
|
|
88
|
+
external _onNotification: (client, @as("notification") _, notification => unit) => unit = "on"
|
|
89
|
+
|
|
90
|
+
let listen = async (pool, ~channel, ~onNotify) => {
|
|
91
|
+
let client = await _connect(pool)
|
|
92
|
+
client->_onNotification(n =>
|
|
93
|
+
switch n.payload->Nullable.toOption {
|
|
94
|
+
| Some(p) => onNotify(p)
|
|
95
|
+
| None => ()
|
|
96
|
+
}
|
|
97
|
+
)
|
|
98
|
+
// Channel identifiers can't be parameterised; the caller supplies a
|
|
99
|
+
// framework-controlled name (`dcb_<log>`), never user input.
|
|
100
|
+
let _ = await _clientQueryText(client, `LISTEN "${channel}"`)
|
|
101
|
+
client
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let unlisten = async (client, ~channel) => {
|
|
105
|
+
try {
|
|
106
|
+
let _ = await _clientQueryText(client, `UNLISTEN "${channel}"`)
|
|
107
|
+
} catch {
|
|
108
|
+
| _ => ()
|
|
109
|
+
}
|
|
110
|
+
_release(client)
|
|
111
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Sealed wrapper around node-postgres (`pg`).
|
|
2
|
+
//
|
|
3
|
+
// Unlike SqliteDriver (node:sqlite, synchronous), every operation here is
|
|
4
|
+
// asynchronous — there is no synchronous Postgres client in Node. Storage
|
|
5
|
+
// makers stay synchronous (they only close over a `pool`); the async cost lands
|
|
6
|
+
// where the adapter operations already are (`append`/`read` return promises).
|
|
7
|
+
// Schema setup (`PgSchema.ensureSchema`) is therefore a distinct async step run
|
|
8
|
+
// once before any maker, not an inline `ensureSchema` inside the maker.
|
|
9
|
+
//
|
|
10
|
+
// The interface is kept tight so a different driver could be dropped in later
|
|
11
|
+
// without callers changing.
|
|
12
|
+
|
|
13
|
+
type pool
|
|
14
|
+
type client
|
|
15
|
+
|
|
16
|
+
// TLS options. Required for RDS/managed Postgres (PG15+ defaults to
|
|
17
|
+
// `rds.force_ssl=1`). `rejectUnauthorized: false` encrypts without CA
|
|
18
|
+
// verification.
|
|
19
|
+
type sslConfig = {rejectUnauthorized: bool}
|
|
20
|
+
|
|
21
|
+
// Invoked by pg per physical connection, so a rotated secret is picked up on the
|
|
22
|
+
// next new connection without rebuilding the pool.
|
|
23
|
+
type passwordProvider = unit => promise<string>
|
|
24
|
+
|
|
25
|
+
type poolConfig = {
|
|
26
|
+
// Supply either a full `connectionString` (local/dev) or the discrete fields
|
|
27
|
+
// (AWS adapter — password comes from a Secrets Manager provider that can't be
|
|
28
|
+
// baked into a static string).
|
|
29
|
+
connectionString?: string,
|
|
30
|
+
host?: string,
|
|
31
|
+
port?: int,
|
|
32
|
+
database?: string,
|
|
33
|
+
user?: string,
|
|
34
|
+
password?: passwordProvider,
|
|
35
|
+
ssl?: sslConfig,
|
|
36
|
+
// Upper bound on pooled connections. Defaults to pg's own default (10).
|
|
37
|
+
max?: int,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let makePool: poolConfig => pool
|
|
41
|
+
let endPool: pool => promise<unit>
|
|
42
|
+
|
|
43
|
+
// Parameterised query (extended protocol — exactly one statement). Returns the
|
|
44
|
+
// result rows. Postgres returns `bigint`/`xid8` as strings, `jsonb` already
|
|
45
|
+
// parsed, and `text[]` as a JS array — all directly usable as `JSON.t`.
|
|
46
|
+
let query: (pool, string, array<JSON.t>) => promise<array<dict<JSON.t>>>
|
|
47
|
+
|
|
48
|
+
// Parameterised query returning the first row, or None.
|
|
49
|
+
let queryOne: (pool, string, array<JSON.t>) => promise<option<dict<JSON.t>>>
|
|
50
|
+
|
|
51
|
+
// Simple-protocol statement with no parameters — allows multi-statement DDL and
|
|
52
|
+
// dollar-quoted function bodies. Used by PgSchema.
|
|
53
|
+
let exec: (pool, string) => promise<unit>
|
|
54
|
+
|
|
55
|
+
// Run `fn` inside BEGIN/COMMIT on a single checked-out connection. Rolls back on
|
|
56
|
+
// any rejected promise or thrown exception, then always releases the connection.
|
|
57
|
+
// Transaction-scoped advisory locks require this single-connection guarantee.
|
|
58
|
+
let transaction: (pool, client => promise<'a>) => promise<'a>
|
|
59
|
+
|
|
60
|
+
// Same as `query`, but on an explicit transaction connection.
|
|
61
|
+
let queryOn: (client, string, array<JSON.t>) => promise<array<dict<JSON.t>>>
|
|
62
|
+
let execOn: (client, string) => promise<unit>
|
|
63
|
+
|
|
64
|
+
// Open a dedicated long-lived connection issuing `LISTEN <channel>`, invoking
|
|
65
|
+
// `onNotify` with each notification payload. The returned client is caller-owned
|
|
66
|
+
// (call `unlisten` to `UNLISTEN` + release). Used by the change feed (Phase D).
|
|
67
|
+
let listen: (pool, ~channel: string, ~onNotify: string => unit) => promise<client>
|
|
68
|
+
let unlisten: (client, ~channel: string) => promise<unit>
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// Idempotent schema + migration runner for the Postgres backend.
|
|
2
|
+
//
|
|
3
|
+
// `ensureSchema(pool)` is callable from any deploy-time context or standalone.
|
|
4
|
+
// The package depends on no IaC/provider SDK; a platform that embeds this
|
|
5
|
+
// storage is responsible for emitting the deploy-time resource that runs it.
|
|
6
|
+
//
|
|
7
|
+
// It creates:
|
|
8
|
+
// event_log / snapshot — classic OCC log (Phase A)
|
|
9
|
+
// dcb_event — DCB log; positions are a global IDENTITY sequence,
|
|
10
|
+
// rows stamped with the committing xid8 (Phase B)
|
|
11
|
+
// dcb_scope — companion table for the #RowLocks strategy (B4)
|
|
12
|
+
// dcb_subscription — change-feed checkpoints (Phase D)
|
|
13
|
+
// dcb_condition_where(...) — compiles a DcbTag.query jsonb AST → SQL WHERE
|
|
14
|
+
// dcb_append(...) — the concurrency-critical append (B1): scoped
|
|
15
|
+
// advisory locks + exact check + insert + NOTIFY,
|
|
16
|
+
// one round trip, transaction-scoped.
|
|
17
|
+
|
|
18
|
+
// Table / index DDL. Every statement is individually idempotent so ensureSchema
|
|
19
|
+
// is safe to run on every startup and concurrently across processes.
|
|
20
|
+
let tableStatements = [
|
|
21
|
+
// --- Classic event log (Phase A) ---
|
|
22
|
+
"CREATE TABLE IF NOT EXISTS event_log (
|
|
23
|
+
log_name text NOT NULL,
|
|
24
|
+
aggregate_id text NOT NULL,
|
|
25
|
+
seq_nr bigint NOT NULL,
|
|
26
|
+
payload jsonb NOT NULL,
|
|
27
|
+
msg_id text,
|
|
28
|
+
global_seq bigint GENERATED ALWAYS AS IDENTITY,
|
|
29
|
+
PRIMARY KEY (log_name, aggregate_id, seq_nr)
|
|
30
|
+
)",
|
|
31
|
+
"CREATE TABLE IF NOT EXISTS snapshot (
|
|
32
|
+
log_name text NOT NULL,
|
|
33
|
+
aggregate_id text NOT NULL,
|
|
34
|
+
seq_nr bigint NOT NULL,
|
|
35
|
+
state jsonb NOT NULL,
|
|
36
|
+
schema_hash text NOT NULL,
|
|
37
|
+
PRIMARY KEY (log_name, aggregate_id)
|
|
38
|
+
)",
|
|
39
|
+
// --- DCB event log (Phase B) ---
|
|
40
|
+
"CREATE TABLE IF NOT EXISTS dcb_event (
|
|
41
|
+
log_name text NOT NULL,
|
|
42
|
+
position bigint GENERATED ALWAYS AS IDENTITY,
|
|
43
|
+
transaction_id xid8 NOT NULL DEFAULT pg_current_xact_id(),
|
|
44
|
+
event_type text NOT NULL,
|
|
45
|
+
tags text[] NOT NULL DEFAULT '{}',
|
|
46
|
+
data jsonb NOT NULL,
|
|
47
|
+
meta jsonb NOT NULL,
|
|
48
|
+
recorded_at timestamptz NOT NULL DEFAULT now(),
|
|
49
|
+
PRIMARY KEY (log_name, position)
|
|
50
|
+
)",
|
|
51
|
+
"CREATE INDEX IF NOT EXISTS dcb_event_tags_gin ON dcb_event USING gin (tags)",
|
|
52
|
+
"CREATE INDEX IF NOT EXISTS dcb_event_type_pos ON dcb_event (log_name, event_type, position)",
|
|
53
|
+
"CREATE INDEX IF NOT EXISTS dcb_event_tx_pos ON dcb_event (log_name, transaction_id, position)",
|
|
54
|
+
// --- Row-lock companion (B4) ---
|
|
55
|
+
"CREATE TABLE IF NOT EXISTS dcb_scope (
|
|
56
|
+
log_name text NOT NULL,
|
|
57
|
+
scope_hash bigint NOT NULL,
|
|
58
|
+
PRIMARY KEY (log_name, scope_hash)
|
|
59
|
+
)",
|
|
60
|
+
// --- Change-feed checkpoints (Phase D) ---
|
|
61
|
+
"CREATE TABLE IF NOT EXISTS dcb_subscription (
|
|
62
|
+
subscriber text PRIMARY KEY,
|
|
63
|
+
last_tx xid8 NOT NULL DEFAULT '0'::xid8,
|
|
64
|
+
last_position bigint NOT NULL DEFAULT 0
|
|
65
|
+
)",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
// Compiles a DcbTag.query jsonb AST to a SQL WHERE fragment against `dcb_event`.
|
|
69
|
+
// The AST is `[ {eventTypes: [text]|null, tags: [text]|null}, ... ]` — an OR of
|
|
70
|
+
// clauses; within a clause the tags array is `@>`-contained and event types are
|
|
71
|
+
// an IN list. All embedded values pass through quote_literal (the values are
|
|
72
|
+
// framework-controlled tag/event strings, but escaping is non-negotiable for
|
|
73
|
+
// EXECUTE'd SQL). Tags are encoded 'key=value' to match the dcb_event.tags column.
|
|
74
|
+
//
|
|
75
|
+
// `after` is the two-column cursor decoded to (p_after_tx, p_after_pos); the
|
|
76
|
+
// generated fragment is the exact `(transaction_id, position) > (tx, pos)`
|
|
77
|
+
// comparison reads use, so read → decide → conditional-append is exact.
|
|
78
|
+
let dcbConditionWhereFn = "
|
|
79
|
+
CREATE OR REPLACE FUNCTION dcb_after_frag(p_tx xid8, p_pos bigint) RETURNS text
|
|
80
|
+
LANGUAGE sql IMMUTABLE AS $af$
|
|
81
|
+
SELECT CASE WHEN p_tx IS NULL THEN NULL ELSE
|
|
82
|
+
'(transaction_id > ' || quote_literal(p_tx::text) || '::xid8 OR (transaction_id = '
|
|
83
|
+
|| quote_literal(p_tx::text) || '::xid8 AND position > ' || p_pos::text || '))'
|
|
84
|
+
END;
|
|
85
|
+
$af$;
|
|
86
|
+
|
|
87
|
+
CREATE OR REPLACE FUNCTION dcb_condition_where(
|
|
88
|
+
p_log_name text,
|
|
89
|
+
p_query jsonb,
|
|
90
|
+
p_after_tx xid8,
|
|
91
|
+
p_after_pos bigint
|
|
92
|
+
) RETURNS text
|
|
93
|
+
LANGUAGE plpgsql IMMUTABLE AS $fn$
|
|
94
|
+
DECLARE
|
|
95
|
+
v_clauses text[] := '{}';
|
|
96
|
+
v_parts text[];
|
|
97
|
+
v_types text;
|
|
98
|
+
v_tags text;
|
|
99
|
+
v_after text := dcb_after_frag(p_after_tx, p_after_pos);
|
|
100
|
+
qi jsonb;
|
|
101
|
+
BEGIN
|
|
102
|
+
IF p_query IS NULL OR jsonb_array_length(p_query) = 0 THEN
|
|
103
|
+
v_types := 'log_name = ' || quote_literal(p_log_name);
|
|
104
|
+
IF v_after IS NOT NULL THEN
|
|
105
|
+
v_types := v_types || ' AND ' || v_after;
|
|
106
|
+
END IF;
|
|
107
|
+
RETURN v_types;
|
|
108
|
+
END IF;
|
|
109
|
+
|
|
110
|
+
FOR qi IN SELECT * FROM jsonb_array_elements(p_query) LOOP
|
|
111
|
+
v_parts := ARRAY['log_name = ' || quote_literal(p_log_name)];
|
|
112
|
+
IF v_after IS NOT NULL THEN
|
|
113
|
+
v_parts := array_append(v_parts, v_after);
|
|
114
|
+
END IF;
|
|
115
|
+
|
|
116
|
+
IF jsonb_typeof(qi->'eventTypes') = 'array'
|
|
117
|
+
AND jsonb_array_length(qi->'eventTypes') > 0 THEN
|
|
118
|
+
SELECT string_agg(quote_literal(t), ',')
|
|
119
|
+
INTO v_types
|
|
120
|
+
FROM jsonb_array_elements_text(qi->'eventTypes') t;
|
|
121
|
+
v_parts := array_append(v_parts, 'event_type IN (' || v_types || ')');
|
|
122
|
+
END IF;
|
|
123
|
+
|
|
124
|
+
IF jsonb_typeof(qi->'tags') = 'array'
|
|
125
|
+
AND jsonb_array_length(qi->'tags') > 0 THEN
|
|
126
|
+
SELECT string_agg(quote_literal(t), ',')
|
|
127
|
+
INTO v_tags
|
|
128
|
+
FROM jsonb_array_elements_text(qi->'tags') t;
|
|
129
|
+
v_parts := array_append(v_parts, 'tags @> ARRAY[' || v_tags || ']::text[]');
|
|
130
|
+
END IF;
|
|
131
|
+
|
|
132
|
+
v_clauses := array_append(v_clauses, '(' || array_to_string(v_parts, ' AND ') || ')');
|
|
133
|
+
END LOOP;
|
|
134
|
+
|
|
135
|
+
RETURN array_to_string(v_clauses, ' OR ');
|
|
136
|
+
END;
|
|
137
|
+
$fn$;
|
|
138
|
+
"
|
|
139
|
+
|
|
140
|
+
// The append. Called as `SELECT dcb_append($1,$2::jsonb,$3::jsonb,$4)` — a single
|
|
141
|
+
// simple statement, so the implicit transaction holds every advisory lock until
|
|
142
|
+
// the insert commits. Returns the encoded cursor `<xid8>:<position>` (both
|
|
143
|
+
// zero-padded to 20 digits so string order == numeric order) of the last event.
|
|
144
|
+
//
|
|
145
|
+
// Lock scope (advisory strategy): a deterministic hashtextextended() of every
|
|
146
|
+
// tag carried by the written events OR referenced in the condition query,
|
|
147
|
+
// namespaced per log_name, acquired in sorted order (deadlock-free). Lock scope
|
|
148
|
+
// controls only *what serializes*; the check itself is exact, so a coarse scope
|
|
149
|
+
// (hash collision) can only delay an append, never wrongly reject it.
|
|
150
|
+
let dcbAppendFn = "
|
|
151
|
+
CREATE OR REPLACE FUNCTION dcb_append(
|
|
152
|
+
p_log_name text,
|
|
153
|
+
p_events jsonb,
|
|
154
|
+
p_condition jsonb DEFAULT NULL,
|
|
155
|
+
p_lock_strategy text DEFAULT 'advisory'
|
|
156
|
+
) RETURNS text
|
|
157
|
+
LANGUAGE plpgsql AS $fn$
|
|
158
|
+
DECLARE
|
|
159
|
+
v_lock_keys bigint[];
|
|
160
|
+
v_after_raw text;
|
|
161
|
+
v_after_tx xid8;
|
|
162
|
+
v_after_pos bigint;
|
|
163
|
+
v_where text;
|
|
164
|
+
v_conflict boolean;
|
|
165
|
+
v_last_pos bigint;
|
|
166
|
+
v_key bigint;
|
|
167
|
+
BEGIN
|
|
168
|
+
-- 1. Lock keys: every tag in written events UNION every tag in the condition.
|
|
169
|
+
SELECT array_agg(DISTINCT k ORDER BY k) INTO v_lock_keys
|
|
170
|
+
FROM (
|
|
171
|
+
SELECT hashtextextended(p_log_name || '=' || tag, 0) AS k
|
|
172
|
+
FROM jsonb_array_elements(p_events) ev,
|
|
173
|
+
jsonb_array_elements_text(ev->'tags') tag
|
|
174
|
+
UNION
|
|
175
|
+
SELECT hashtextextended(p_log_name || '=' || tag, 0) AS k
|
|
176
|
+
FROM jsonb_array_elements(COALESCE(p_condition->'query', '[]'::jsonb)) qi,
|
|
177
|
+
jsonb_array_elements_text(COALESCE(qi->'tags', '[]'::jsonb)) tag
|
|
178
|
+
) s;
|
|
179
|
+
|
|
180
|
+
-- 2. Acquire in sorted order.
|
|
181
|
+
IF v_lock_keys IS NOT NULL THEN
|
|
182
|
+
IF p_lock_strategy = 'rows' THEN
|
|
183
|
+
INSERT INTO dcb_scope(log_name, scope_hash)
|
|
184
|
+
SELECT p_log_name, k FROM unnest(v_lock_keys) k
|
|
185
|
+
ON CONFLICT DO NOTHING;
|
|
186
|
+
PERFORM 1 FROM dcb_scope
|
|
187
|
+
WHERE log_name = p_log_name AND scope_hash = ANY(v_lock_keys)
|
|
188
|
+
ORDER BY scope_hash
|
|
189
|
+
FOR UPDATE;
|
|
190
|
+
ELSE
|
|
191
|
+
FOREACH v_key IN ARRAY v_lock_keys LOOP
|
|
192
|
+
PERFORM pg_advisory_xact_lock(v_key);
|
|
193
|
+
END LOOP;
|
|
194
|
+
END IF;
|
|
195
|
+
END IF;
|
|
196
|
+
|
|
197
|
+
-- 3. Exact condition check under the held locks (READ COMMITTED is race-free
|
|
198
|
+
-- here: a conflicting concurrent writer is either committed+visible or
|
|
199
|
+
-- blocked on our lock).
|
|
200
|
+
IF p_condition IS NOT NULL THEN
|
|
201
|
+
v_after_raw := NULLIF(p_condition->>'after', '');
|
|
202
|
+
IF v_after_raw IS NOT NULL THEN
|
|
203
|
+
-- Cursor is '<xid8>:<position>', each zero-padded to 20 digits. Strip the
|
|
204
|
+
-- padding before casting (bigint tolerates leading zeros; be explicit for
|
|
205
|
+
-- xid8, guarding the all-zeros case).
|
|
206
|
+
v_after_tx := COALESCE(NULLIF(ltrim(split_part(v_after_raw, ':', 1), '0'), ''), '0')::xid8;
|
|
207
|
+
v_after_pos := split_part(v_after_raw, ':', 2)::bigint;
|
|
208
|
+
END IF;
|
|
209
|
+
v_where := dcb_condition_where(p_log_name, p_condition->'query', v_after_tx, v_after_pos);
|
|
210
|
+
EXECUTE 'SELECT EXISTS (SELECT 1 FROM dcb_event WHERE ' || v_where || ')'
|
|
211
|
+
INTO v_conflict;
|
|
212
|
+
IF v_conflict THEN
|
|
213
|
+
RAISE EXCEPTION 'dcb_conflict' USING ERRCODE = 'P0001';
|
|
214
|
+
END IF;
|
|
215
|
+
END IF;
|
|
216
|
+
|
|
217
|
+
-- 4. Insert every event in array order; positions come from the IDENTITY seq.
|
|
218
|
+
WITH ins AS (
|
|
219
|
+
INSERT INTO dcb_event(log_name, event_type, tags, data, meta)
|
|
220
|
+
SELECT p_log_name,
|
|
221
|
+
ev->>'event_type',
|
|
222
|
+
ARRAY(SELECT jsonb_array_elements_text(ev->'tags')),
|
|
223
|
+
ev->'data',
|
|
224
|
+
ev->'meta'
|
|
225
|
+
FROM jsonb_array_elements(p_events) WITH ORDINALITY AS t(ev, ord)
|
|
226
|
+
ORDER BY ord
|
|
227
|
+
RETURNING position
|
|
228
|
+
)
|
|
229
|
+
SELECT max(position) INTO v_last_pos FROM ins;
|
|
230
|
+
|
|
231
|
+
-- 5. Wake the change feed (Phase D). No-op if nobody is LISTENing.
|
|
232
|
+
PERFORM pg_notify('dcb_' || p_log_name, v_last_pos::text);
|
|
233
|
+
|
|
234
|
+
RETURN lpad(pg_current_xact_id()::text, 20, '0') || ':' || lpad(v_last_pos::text, 20, '0');
|
|
235
|
+
END;
|
|
236
|
+
$fn$;
|
|
237
|
+
"
|
|
238
|
+
|
|
239
|
+
let functionStatements = [dcbConditionWhereFn, dcbAppendFn]
|
|
240
|
+
|
|
241
|
+
let ensureSchema = async (pool: PgDriver.pool): unit => {
|
|
242
|
+
for i in 0 to tableStatements->Array.length - 1 {
|
|
243
|
+
await pool->PgDriver.exec(tableStatements->Array.getUnsafe(i))
|
|
244
|
+
}
|
|
245
|
+
for i in 0 to functionStatements->Array.length - 1 {
|
|
246
|
+
await pool->PgDriver.exec(functionStatements->Array.getUnsafe(i))
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// resetOnStart support: TRUNCATE (never DROP) so the schema/functions survive.
|
|
251
|
+
// Mirrors the reventless-local contract that reset wipes data, not structure.
|
|
252
|
+
let truncateAll = async (pool: PgDriver.pool): unit => {
|
|
253
|
+
await pool->PgDriver.exec(
|
|
254
|
+
"TRUNCATE event_log, snapshot, dcb_event, dcb_scope, dcb_subscription RESTART IDENTITY",
|
|
255
|
+
)
|
|
256
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|