ezlogs-nextjs 0.2.0 → 0.3.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/README.md +53 -16
- package/bin/install-triggers.cjs +73 -11
- package/dist/actors/index.cjs +5 -37
- package/dist/actors/index.js +2 -34
- package/dist/chunk-C5OSM557.js +39 -0
- package/dist/chunk-CE3R7DVB.js +1127 -0
- package/dist/chunk-CU45I2WR.js +498 -0
- package/dist/chunk-DKRNNI4I.js +180 -0
- package/dist/chunk-SIAA4J6H.js +17 -0
- package/dist/chunk-UQHEW6ER.js +119 -0
- package/dist/chunk-UWHYJH4M.cjs +126 -0
- package/dist/chunk-V5YNKKTG.cjs +42 -0
- package/dist/chunk-WASXTDLW.cjs +1151 -0
- package/dist/chunk-Y5NSHKWQ.cjs +182 -0
- package/dist/chunk-YX2XPLOA.cjs +508 -0
- package/dist/chunk-ZDSQYCYV.cjs +21 -0
- package/dist/db/drizzle.cjs +6 -713
- package/dist/db/drizzle.js +5 -712
- package/dist/db/prisma.cjs +52 -763
- package/dist/db/prisma.d.cts +3 -1
- package/dist/db/prisma.d.ts +3 -1
- package/dist/db/prisma.js +38 -749
- package/dist/db/supabase.cjs +21 -728
- package/dist/db/supabase.js +14 -721
- package/dist/index.cjs +204 -2181
- package/dist/index.js +107 -2090
- package/dist/jobs/bullmq.cjs +61 -552
- package/dist/jobs/bullmq.d.cts +8 -3
- package/dist/jobs/bullmq.d.ts +8 -3
- package/dist/jobs/bullmq.js +58 -549
- package/dist/jobs/inngest.cjs +23 -561
- package/dist/jobs/inngest.d.cts +7 -5
- package/dist/jobs/inngest.d.ts +7 -5
- package/dist/jobs/inngest.js +19 -557
- package/dist/jobs/supabase-queues.cjs +17 -603
- package/dist/jobs/supabase-queues.js +12 -598
- package/dist/jobs/trigger.cjs +18 -587
- package/dist/jobs/trigger.js +16 -585
- package/dist/jobs/upstash-workflow.cjs +62 -584
- package/dist/jobs/upstash-workflow.d.cts +17 -2
- package/dist/jobs/upstash-workflow.d.ts +17 -2
- package/dist/jobs/upstash-workflow.js +59 -582
- package/dist/nextjs-plugin/index.cjs +1 -1
- package/dist/nextjs-plugin/index.js +1 -1
- package/dist/nextjs-plugin/loader.cjs +21 -25
- package/dist/nextjs-plugin/loader.js +1 -5
- package/dist/triggers/index.cjs +40 -1234
- package/dist/triggers/index.d.cts +7 -2
- package/dist/triggers/index.d.ts +7 -2
- package/dist/triggers/index.js +6 -1221
- package/package.json +4 -1
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { createScopedStorage, runWithCorrelation, runWithActorScope, current, generate, emitDbEvent } from './chunk-CE3R7DVB.js';
|
|
2
|
+
import { logger } from './chunk-C5OSM557.js';
|
|
3
|
+
|
|
4
|
+
// src/triggers/emit-dedup.ts
|
|
5
|
+
var storage = createScopedStorage(
|
|
6
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
|
|
7
|
+
);
|
|
8
|
+
function currentEmittedAuditIds() {
|
|
9
|
+
return storage.read();
|
|
10
|
+
}
|
|
11
|
+
function runWithEmittedAuditIdsScope(callback) {
|
|
12
|
+
const existing = storage.read();
|
|
13
|
+
if (existing !== null) return callback();
|
|
14
|
+
return storage.run(/* @__PURE__ */ new Set(), callback);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/triggers/reader.ts
|
|
18
|
+
var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
|
|
19
|
+
var ORPHAN_AGE = "5 minutes";
|
|
20
|
+
var PRUNE_AGE = "24 hours";
|
|
21
|
+
var SWEEP_BATCH = 100;
|
|
22
|
+
var PRUNE_BATCH = 2e3;
|
|
23
|
+
var SWEEP_INTERVAL_MS = 1e4;
|
|
24
|
+
var PRUNE_INTERVAL_MS = 10 * 6e4;
|
|
25
|
+
var lastSweepAt = 0;
|
|
26
|
+
var lastPruneAt = 0;
|
|
27
|
+
var deleteDenied = false;
|
|
28
|
+
var txCorrelation = /* @__PURE__ */ new Map();
|
|
29
|
+
var UNTAGGED_STRIKES = 5;
|
|
30
|
+
var UNTAGGED_CHECK_BUDGET = 50;
|
|
31
|
+
var untaggedCheckIntervalMs = 1e4;
|
|
32
|
+
var untaggedMinSpanMs = 2 * 6e4;
|
|
33
|
+
var UNTAGGED_WINDOW_MAX_MS = 5 * 6e4;
|
|
34
|
+
var UNTAGGED_CLOCK_SKEW_MS = 1e3;
|
|
35
|
+
var taggedRowSeen = false;
|
|
36
|
+
var untaggedStrikes = 0;
|
|
37
|
+
var untaggedChecks = 0;
|
|
38
|
+
var lastUntaggedCheckAt = 0;
|
|
39
|
+
var firstUntaggedStrikeAt = 0;
|
|
40
|
+
var untaggedWarned = false;
|
|
41
|
+
async function readAuditRows(exec, correlationId, since = null) {
|
|
42
|
+
const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
|
|
43
|
+
const params = since ? [correlationId, since.toISOString()] : [correlationId];
|
|
44
|
+
try {
|
|
45
|
+
if (!deleteDenied) {
|
|
46
|
+
try {
|
|
47
|
+
return sortById(
|
|
48
|
+
extractRows(
|
|
49
|
+
await exec(
|
|
50
|
+
`DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
|
|
51
|
+
params
|
|
52
|
+
)
|
|
53
|
+
).map(normalizeAuditRow)
|
|
54
|
+
);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
if (!isPermissionDenied(err)) throw err;
|
|
57
|
+
deleteDenied = true;
|
|
58
|
+
logger.warn(
|
|
59
|
+
"the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const result = await exec(
|
|
64
|
+
`SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
|
|
65
|
+
params
|
|
66
|
+
);
|
|
67
|
+
return extractRows(result).map(normalizeAuditRow);
|
|
68
|
+
} catch (err) {
|
|
69
|
+
logger.debug(
|
|
70
|
+
`readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
|
|
71
|
+
);
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function sweepAuditLog(exec) {
|
|
76
|
+
if (deleteDenied) return 0;
|
|
77
|
+
try {
|
|
78
|
+
const rows = sortById(
|
|
79
|
+
extractRows(
|
|
80
|
+
await exec(
|
|
81
|
+
`DELETE FROM ezlogs_audit_log
|
|
82
|
+
WHERE id IN (
|
|
83
|
+
SELECT id FROM ezlogs_audit_log
|
|
84
|
+
WHERE (correlation_id IS NULL
|
|
85
|
+
OR captured_at < now() - interval '${ORPHAN_AGE}')
|
|
86
|
+
-- Never resurface history: past the retention cap a
|
|
87
|
+
-- row is pruned, not sent as new activity.
|
|
88
|
+
AND captured_at > now() - interval '${PRUNE_AGE}'
|
|
89
|
+
ORDER BY id
|
|
90
|
+
LIMIT ${SWEEP_BATCH}
|
|
91
|
+
FOR UPDATE SKIP LOCKED)
|
|
92
|
+
RETURNING ${COLUMNS}`,
|
|
93
|
+
[]
|
|
94
|
+
)
|
|
95
|
+
).map(normalizeAuditRow)
|
|
96
|
+
);
|
|
97
|
+
await loadTableMeta(exec, rows);
|
|
98
|
+
for (const row of rows) {
|
|
99
|
+
const correlationId = row.correlation_id ?? correlationForTx(row.txid);
|
|
100
|
+
runWithCorrelation(
|
|
101
|
+
correlationId,
|
|
102
|
+
() => runWithActorScope(() => emitOne(row))
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return rows.length;
|
|
106
|
+
} catch (err) {
|
|
107
|
+
logger.debug(
|
|
108
|
+
`sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
|
|
109
|
+
);
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function pruneAuditLog(exec) {
|
|
114
|
+
if (deleteDenied) return;
|
|
115
|
+
try {
|
|
116
|
+
await exec(
|
|
117
|
+
`DELETE FROM ezlogs_audit_log
|
|
118
|
+
WHERE id IN (
|
|
119
|
+
SELECT id FROM ezlogs_audit_log
|
|
120
|
+
WHERE captured_at < now() - interval '${PRUNE_AGE}'
|
|
121
|
+
LIMIT ${PRUNE_BATCH})`,
|
|
122
|
+
[]
|
|
123
|
+
);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
logger.debug(
|
|
126
|
+
`pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function auditLogInstalled(exec) {
|
|
131
|
+
try {
|
|
132
|
+
const rows = extractRows(
|
|
133
|
+
await exec(
|
|
134
|
+
`SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
|
|
135
|
+
[]
|
|
136
|
+
)
|
|
137
|
+
);
|
|
138
|
+
const installed = rows[0]?.installed;
|
|
139
|
+
return typeof installed === "boolean" ? installed : null;
|
|
140
|
+
} catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function checkAuditLogAccess(exec) {
|
|
145
|
+
try {
|
|
146
|
+
const rows = extractRows(
|
|
147
|
+
await exec(
|
|
148
|
+
`SELECT current_user AS role
|
|
149
|
+
FROM pg_class c
|
|
150
|
+
JOIN pg_roles r ON r.rolname = current_user
|
|
151
|
+
WHERE c.oid = 'public.ezlogs_audit_log'::regclass
|
|
152
|
+
AND c.relrowsecurity
|
|
153
|
+
AND NOT r.rolsuper
|
|
154
|
+
AND NOT r.rolbypassrls
|
|
155
|
+
AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
|
|
156
|
+
AND NOT EXISTS (SELECT 1 FROM pg_policies p
|
|
157
|
+
WHERE p.schemaname = 'public'
|
|
158
|
+
AND p.tablename = 'ezlogs_audit_log')`,
|
|
159
|
+
[]
|
|
160
|
+
)
|
|
161
|
+
);
|
|
162
|
+
const role = rows[0]?.role;
|
|
163
|
+
if (typeof role !== "string") return false;
|
|
164
|
+
logger.warn(
|
|
165
|
+
`the database role "${role}" is not the owner of ezlogs_audit_log, which has row-level security, so the agent reads 0 rows and no DB changes are sent. As the table owner, run: GRANT SELECT, DELETE ON ezlogs_audit_log TO "${role}"; CREATE POLICY ezlogs_reader ON ezlogs_audit_log TO "${role}" USING (true);`
|
|
166
|
+
);
|
|
167
|
+
return true;
|
|
168
|
+
} catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async function detectTriggerTrackedTables(exec) {
|
|
173
|
+
try {
|
|
174
|
+
const result = await exec(
|
|
175
|
+
`SELECT event_object_table AS table_name
|
|
176
|
+
FROM information_schema.triggers
|
|
177
|
+
WHERE trigger_name = 'ezlogs_audit'
|
|
178
|
+
AND trigger_schema = 'public'`,
|
|
179
|
+
[]
|
|
180
|
+
);
|
|
181
|
+
const rows = extractRows(result);
|
|
182
|
+
const tables = /* @__PURE__ */ new Set();
|
|
183
|
+
for (const row of rows) {
|
|
184
|
+
const r = row ?? {};
|
|
185
|
+
if (typeof r.table_name === "string" && r.table_name.length > 0) {
|
|
186
|
+
tables.add(r.table_name);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return tables;
|
|
190
|
+
} catch (err) {
|
|
191
|
+
logger.debug(
|
|
192
|
+
`detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
|
|
193
|
+
);
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function emitAuditRows(rows) {
|
|
198
|
+
for (const row of rows) {
|
|
199
|
+
emitOne(row);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function flushAuditLog(exec, options = {}) {
|
|
203
|
+
if (!exec) return;
|
|
204
|
+
const correlationId = current();
|
|
205
|
+
if (!correlationId) return;
|
|
206
|
+
const rows = await readAuditRows(exec, correlationId, options.since ?? null);
|
|
207
|
+
await loadTableMeta(exec, rows);
|
|
208
|
+
emitFresh(rows);
|
|
209
|
+
if (rows.length > 0) taggedRowSeen = true;
|
|
210
|
+
else await checkUntaggedWrites(exec, correlationId, options.since ?? null);
|
|
211
|
+
const now = Date.now();
|
|
212
|
+
if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
|
|
213
|
+
lastPruneAt = now;
|
|
214
|
+
await pruneAuditLog(exec);
|
|
215
|
+
}
|
|
216
|
+
if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
|
|
217
|
+
lastSweepAt = now;
|
|
218
|
+
await sweepAuditLog(exec);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async function checkUntaggedWrites(exec, correlationId, since) {
|
|
222
|
+
if (taggedRowSeen || untaggedWarned || untaggedChecks >= UNTAGGED_CHECK_BUDGET) return;
|
|
223
|
+
const now = Date.now();
|
|
224
|
+
if (now - lastUntaggedCheckAt < untaggedCheckIntervalMs) return;
|
|
225
|
+
const idMs = Number(/^ezl_(\d{13})_/.exec(correlationId)?.[1] ?? NaN);
|
|
226
|
+
const startMs = Math.max((since?.getTime() ?? idMs) - UNTAGGED_CLOCK_SKEW_MS, now - UNTAGGED_WINDOW_MAX_MS);
|
|
227
|
+
if (!Number.isFinite(startMs)) return;
|
|
228
|
+
lastUntaggedCheckAt = now;
|
|
229
|
+
untaggedChecks++;
|
|
230
|
+
try {
|
|
231
|
+
const rows = extractRows(
|
|
232
|
+
await exec(
|
|
233
|
+
`SELECT 1 FROM ezlogs_audit_log WHERE correlation_id IS NULL AND captured_at >= $1 LIMIT 1`,
|
|
234
|
+
[new Date(startMs).toISOString()]
|
|
235
|
+
)
|
|
236
|
+
);
|
|
237
|
+
if (rows.length === 0) return;
|
|
238
|
+
} catch {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (untaggedStrikes++ === 0) firstUntaggedStrikeAt = now;
|
|
242
|
+
if (untaggedStrikes < UNTAGGED_STRIKES || now - firstUntaggedStrikeAt < untaggedMinSpanMs) return;
|
|
243
|
+
if (untaggedWarned) return;
|
|
244
|
+
untaggedWarned = true;
|
|
245
|
+
const where = since ? "background jobs" : "requests";
|
|
246
|
+
logger.warn(
|
|
247
|
+
`database writes made while ${where} ran in this process reached ezlogs_audit_log with no request tag, and this process has never sent a tagged row. They show up as separate actions with no actor (they are never guessed onto a request). Most likely the database client this app writes with is not tagged (or another process wrote them during these windows). Prisma: \`new PrismaClient().$extends(ezlogsPrisma())\` (from "ezlogs-nextjs/prisma"). Drizzle / node-postgres: let the agent patch \`pg\` (set DATABASE_URL, or \`ezlogs.init({ patchDatabaseClient: pg })\` with your app's \`pg\`). In a worker process (BullMQ, \u2026), call \`ezlogs.init\` there too and build the client the same way. Writes inside your own \`prisma.$transaction(...)\` stay untagged either way. See README, "Database changes".`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
var tableMeta = /* @__PURE__ */ new Map();
|
|
251
|
+
var META_RETRY_MS = 6e4;
|
|
252
|
+
var metaRetryAt = 0;
|
|
253
|
+
async function loadTableMeta(exec, rows) {
|
|
254
|
+
if (Date.now() < metaRetryAt) return;
|
|
255
|
+
const tables = [
|
|
256
|
+
...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
|
|
257
|
+
];
|
|
258
|
+
if (tables.length === 0) return;
|
|
259
|
+
const list = tables.join(",");
|
|
260
|
+
try {
|
|
261
|
+
const fkRows = extractRows(
|
|
262
|
+
await exec(
|
|
263
|
+
`SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
|
|
264
|
+
FROM pg_constraint c
|
|
265
|
+
JOIN pg_class cl ON cl.oid = c.conrelid
|
|
266
|
+
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
|
267
|
+
JOIN pg_class rf ON rf.oid = c.confrelid
|
|
268
|
+
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
|
|
269
|
+
WHERE c.contype = 'f'
|
|
270
|
+
AND n.nspname = 'public'
|
|
271
|
+
AND array_length(c.conkey, 1) = 1
|
|
272
|
+
AND cl.relname = ANY(string_to_array($1, ','))
|
|
273
|
+
ORDER BY cl.relname, a.attnum`,
|
|
274
|
+
[list]
|
|
275
|
+
)
|
|
276
|
+
);
|
|
277
|
+
const tsRows = extractRows(
|
|
278
|
+
await exec(
|
|
279
|
+
`SELECT cl.relname AS table_name, a.attname AS column_name
|
|
280
|
+
FROM pg_attribute a
|
|
281
|
+
JOIN pg_class cl ON cl.oid = a.attrelid
|
|
282
|
+
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
|
283
|
+
WHERE n.nspname = 'public'
|
|
284
|
+
AND cl.relname = ANY(string_to_array($1, ','))
|
|
285
|
+
AND a.attnum > 0
|
|
286
|
+
AND NOT a.attisdropped
|
|
287
|
+
AND a.atttypid = 'timestamp'::regtype`,
|
|
288
|
+
[list]
|
|
289
|
+
)
|
|
290
|
+
);
|
|
291
|
+
const fks = /* @__PURE__ */ new Map();
|
|
292
|
+
for (const raw of fkRows) {
|
|
293
|
+
const r = raw ?? {};
|
|
294
|
+
if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
|
|
298
|
+
}
|
|
299
|
+
const timestamps = /* @__PURE__ */ new Map();
|
|
300
|
+
for (const raw of tsRows) {
|
|
301
|
+
const r = raw ?? {};
|
|
302
|
+
if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
|
|
303
|
+
timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
|
|
304
|
+
}
|
|
305
|
+
for (const table of tables) {
|
|
306
|
+
tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
|
|
307
|
+
}
|
|
308
|
+
} catch (err) {
|
|
309
|
+
metaRetryAt = Date.now() + META_RETRY_MS;
|
|
310
|
+
logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
function relatedResourceIds(table, row) {
|
|
314
|
+
const out = [];
|
|
315
|
+
for (const fk of tableMeta.get(table)?.fks ?? []) {
|
|
316
|
+
const value = row[fk.column];
|
|
317
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
318
|
+
out.push({ resource_type: fk.refTable, resource_id: String(value) });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
function emitFresh(rows) {
|
|
324
|
+
if (rows.length === 0) return;
|
|
325
|
+
const emitted = currentEmittedAuditIds();
|
|
326
|
+
if (emitted === null) {
|
|
327
|
+
emitAuditRows(rows);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const fresh = [];
|
|
331
|
+
for (const row of rows) {
|
|
332
|
+
if (row.id === "" || emitted.has(row.id)) continue;
|
|
333
|
+
emitted.add(row.id);
|
|
334
|
+
fresh.push(row);
|
|
335
|
+
}
|
|
336
|
+
emitAuditRows(fresh);
|
|
337
|
+
}
|
|
338
|
+
function correlationForTx(txid) {
|
|
339
|
+
if (!txid) return generate();
|
|
340
|
+
let id = txCorrelation.get(txid);
|
|
341
|
+
if (!id) {
|
|
342
|
+
if (txCorrelation.size >= 1e3) txCorrelation.clear();
|
|
343
|
+
id = generate();
|
|
344
|
+
txCorrelation.set(txid, id);
|
|
345
|
+
}
|
|
346
|
+
return id;
|
|
347
|
+
}
|
|
348
|
+
function isPermissionDenied(err) {
|
|
349
|
+
return err?.code === "42501";
|
|
350
|
+
}
|
|
351
|
+
function sortById(rows) {
|
|
352
|
+
return rows.sort(
|
|
353
|
+
(a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
function emitOne(row) {
|
|
357
|
+
const op = mapOp(row.op);
|
|
358
|
+
if (!op) return;
|
|
359
|
+
const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
|
|
360
|
+
const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
|
|
361
|
+
const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
|
|
362
|
+
const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
|
|
363
|
+
if (op === "create" && newRow) {
|
|
364
|
+
emitDbEvent({
|
|
365
|
+
modelClass: row.table_name,
|
|
366
|
+
operation: "create",
|
|
367
|
+
resourceId: row.resource_id,
|
|
368
|
+
initialAttributes: newRow,
|
|
369
|
+
modelInstance: newRow,
|
|
370
|
+
displayName: null,
|
|
371
|
+
timestamp: row.captured_at ?? null,
|
|
372
|
+
relatedResourceIds: related,
|
|
373
|
+
_fromTrigger: true
|
|
374
|
+
});
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (op === "update" && oldRow && newRow) {
|
|
378
|
+
const changes = computeChanges(oldRow, newRow);
|
|
379
|
+
if (changes.length === 0) {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
emitDbEvent({
|
|
383
|
+
modelClass: row.table_name,
|
|
384
|
+
operation: "update",
|
|
385
|
+
resourceId: row.resource_id,
|
|
386
|
+
changes,
|
|
387
|
+
// Prefer the post-state for the display name — that's what the
|
|
388
|
+
// user just told the system to call this row.
|
|
389
|
+
modelInstance: newRow,
|
|
390
|
+
displayName: null,
|
|
391
|
+
timestamp: row.captured_at ?? null,
|
|
392
|
+
relatedResourceIds: related,
|
|
393
|
+
_fromTrigger: true
|
|
394
|
+
});
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (op === "destroy" && oldRow) {
|
|
398
|
+
emitDbEvent({
|
|
399
|
+
modelClass: row.table_name,
|
|
400
|
+
operation: "destroy",
|
|
401
|
+
resourceId: row.resource_id,
|
|
402
|
+
initialAttributes: oldRow,
|
|
403
|
+
modelInstance: oldRow,
|
|
404
|
+
displayName: null,
|
|
405
|
+
timestamp: row.captured_at ?? null,
|
|
406
|
+
relatedResourceIds: related,
|
|
407
|
+
_fromTrigger: true
|
|
408
|
+
});
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
|
|
413
|
+
function withUtcTimestamps(row, naiveColumns) {
|
|
414
|
+
if (!row) return row;
|
|
415
|
+
const out = {};
|
|
416
|
+
for (const [key, value] of Object.entries(row)) {
|
|
417
|
+
const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
|
|
418
|
+
out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
|
|
419
|
+
}
|
|
420
|
+
return out;
|
|
421
|
+
}
|
|
422
|
+
function mapOp(op) {
|
|
423
|
+
if (op === "INSERT") return "create";
|
|
424
|
+
if (op === "UPDATE") return "update";
|
|
425
|
+
if (op === "DELETE") return "destroy";
|
|
426
|
+
return null;
|
|
427
|
+
}
|
|
428
|
+
function computeChanges(oldRow, newRow) {
|
|
429
|
+
const out = [];
|
|
430
|
+
for (const key of Object.keys(newRow)) {
|
|
431
|
+
const before = oldRow[key];
|
|
432
|
+
const after = newRow[key];
|
|
433
|
+
if (deepEqual(before, after)) continue;
|
|
434
|
+
out.push({ attribute: key, from: before, to: after });
|
|
435
|
+
}
|
|
436
|
+
return out;
|
|
437
|
+
}
|
|
438
|
+
function deepEqual(a, b) {
|
|
439
|
+
if (a === b) return true;
|
|
440
|
+
if (a === null || b === null) return false;
|
|
441
|
+
if (typeof a !== typeof b) return false;
|
|
442
|
+
if (typeof a !== "object") return false;
|
|
443
|
+
try {
|
|
444
|
+
return stableStringify(a) === stableStringify(b);
|
|
445
|
+
} catch {
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function stableStringify(value) {
|
|
450
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
451
|
+
if (Array.isArray(value)) {
|
|
452
|
+
return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
|
|
453
|
+
}
|
|
454
|
+
const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
|
|
455
|
+
return "{" + entries.join(",") + "}";
|
|
456
|
+
}
|
|
457
|
+
function extractRows(result) {
|
|
458
|
+
if (!result) return [];
|
|
459
|
+
if (Array.isArray(result)) return result;
|
|
460
|
+
if (typeof result === "object" && Array.isArray(result.rows)) {
|
|
461
|
+
return result.rows;
|
|
462
|
+
}
|
|
463
|
+
return [];
|
|
464
|
+
}
|
|
465
|
+
function toDate(value) {
|
|
466
|
+
if (value == null) return null;
|
|
467
|
+
const d = value instanceof Date ? value : new Date(String(value));
|
|
468
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
469
|
+
}
|
|
470
|
+
function normalizeAuditRow(raw) {
|
|
471
|
+
const r = raw ?? {};
|
|
472
|
+
return {
|
|
473
|
+
id: r.id == null ? "" : String(r.id),
|
|
474
|
+
table_name: String(r.table_name ?? ""),
|
|
475
|
+
op: r.op,
|
|
476
|
+
old_row: r.old_row ?? null,
|
|
477
|
+
new_row: r.new_row ?? null,
|
|
478
|
+
resource_id: r.resource_id == null ? null : String(r.resource_id),
|
|
479
|
+
correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
|
|
480
|
+
txid: r.txid == null ? null : String(r.txid),
|
|
481
|
+
captured_at: toDate(r.captured_at)
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function coerceJsonb(value) {
|
|
485
|
+
if (value === null || value === void 0) return null;
|
|
486
|
+
if (typeof value === "string") {
|
|
487
|
+
try {
|
|
488
|
+
const parsed = JSON.parse(value);
|
|
489
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
490
|
+
} catch {
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (typeof value === "object" && !Array.isArray(value)) return value;
|
|
495
|
+
return null;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export { auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, pruneAuditLog, readAuditRows, runWithEmittedAuditIdsScope, sweepAuditLog };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { getCurrentActor, current } from './chunk-CE3R7DVB.js';
|
|
2
|
+
import { logger } from './chunk-C5OSM557.js';
|
|
3
|
+
|
|
4
|
+
// src/triggers/patch-pg.ts
|
|
5
|
+
var txState = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
function patchPgClient(pgModule) {
|
|
7
|
+
if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
|
|
8
|
+
logger.debug("patchPgClient: not a recognized pg module shape, skipping");
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const proto = pgModule.Client.prototype;
|
|
12
|
+
if (proto._ezlogsPatched) return;
|
|
13
|
+
const originalQuery = proto.query;
|
|
14
|
+
proto.query = function patchedQuery(config, values, callback) {
|
|
15
|
+
return runPatchedQuery(
|
|
16
|
+
this,
|
|
17
|
+
originalQuery,
|
|
18
|
+
config,
|
|
19
|
+
values,
|
|
20
|
+
callback
|
|
21
|
+
);
|
|
22
|
+
};
|
|
23
|
+
proto._ezlogsPatched = true;
|
|
24
|
+
}
|
|
25
|
+
function runPatchedQuery(client, original, config, values, callback) {
|
|
26
|
+
const state = ensureState(client);
|
|
27
|
+
const text = extractQueryText(config);
|
|
28
|
+
const verb = leadingVerb(text);
|
|
29
|
+
if (verb === "BEGIN" || verb === "START") {
|
|
30
|
+
state.inTx = true;
|
|
31
|
+
state.injected = false;
|
|
32
|
+
return original.call(client, config, values, callback);
|
|
33
|
+
}
|
|
34
|
+
if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
|
|
35
|
+
const result = original.call(client, config, values, callback);
|
|
36
|
+
state.inTx = false;
|
|
37
|
+
state.injected = false;
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
if (state.inTx) {
|
|
41
|
+
if (state.injected) {
|
|
42
|
+
return original.call(client, config, values, callback);
|
|
43
|
+
}
|
|
44
|
+
const ctx2 = snapshotContext();
|
|
45
|
+
if (!ctx2.actorId && !ctx2.correlationId) {
|
|
46
|
+
state.injected = true;
|
|
47
|
+
return original.call(client, config, values, callback);
|
|
48
|
+
}
|
|
49
|
+
state.injected = true;
|
|
50
|
+
return injectAndRun(client, original, config, values, callback, ctx2);
|
|
51
|
+
}
|
|
52
|
+
const ctx = snapshotContext();
|
|
53
|
+
if (!ctx.actorId && !ctx.correlationId) {
|
|
54
|
+
return original.call(client, config, values, callback);
|
|
55
|
+
}
|
|
56
|
+
return wrapInTx(client, original, config, values, callback, ctx);
|
|
57
|
+
}
|
|
58
|
+
function snapshotContext() {
|
|
59
|
+
const actor = getCurrentActor();
|
|
60
|
+
return {
|
|
61
|
+
actorId: actor && actor.id ? actor.id : null,
|
|
62
|
+
correlationId: current()
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
async function injectAndRun(client, original, config, values, callback, ctx) {
|
|
66
|
+
if (ctx.actorId) {
|
|
67
|
+
await safeSet(client, original, {
|
|
68
|
+
text: "SELECT set_config('ezlogs.actor_id', $1, true)",
|
|
69
|
+
values: [ctx.actorId]
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (ctx.correlationId) {
|
|
73
|
+
await safeSet(client, original, {
|
|
74
|
+
text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
|
|
75
|
+
values: [ctx.correlationId]
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return original.call(client, config, values, callback);
|
|
79
|
+
}
|
|
80
|
+
async function safeSet(client, original, cfg) {
|
|
81
|
+
try {
|
|
82
|
+
const result = original.call(client, cfg);
|
|
83
|
+
if (result && typeof result.then === "function") {
|
|
84
|
+
await result;
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
logger.debug(
|
|
88
|
+
`patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function wrapInTx(client, original, config, values, callback, ctx) {
|
|
93
|
+
const state = ensureState(client);
|
|
94
|
+
let userCb = null;
|
|
95
|
+
let realValues = values;
|
|
96
|
+
if (typeof callback === "function") {
|
|
97
|
+
userCb = callback;
|
|
98
|
+
} else if (typeof values === "function") {
|
|
99
|
+
userCb = values;
|
|
100
|
+
realValues = void 0;
|
|
101
|
+
}
|
|
102
|
+
const begin = original.call(client, "BEGIN");
|
|
103
|
+
if (!begin || typeof begin.then !== "function") {
|
|
104
|
+
return original.call(client, config, values, callback);
|
|
105
|
+
}
|
|
106
|
+
const wrapped = begin.then(async () => {
|
|
107
|
+
state.inTx = true;
|
|
108
|
+
state.injected = true;
|
|
109
|
+
if (ctx.actorId) {
|
|
110
|
+
await original.call(client, {
|
|
111
|
+
text: "SELECT set_config('ezlogs.actor_id', $1, true)",
|
|
112
|
+
values: [ctx.actorId]
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
if (ctx.correlationId) {
|
|
116
|
+
await original.call(client, {
|
|
117
|
+
text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
|
|
118
|
+
values: [ctx.correlationId]
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}).then(
|
|
122
|
+
() => (
|
|
123
|
+
// Run the user's actual query in promise mode — DO NOT forward
|
|
124
|
+
// the caller's callback. See comment above.
|
|
125
|
+
original.call(client, config, realValues)
|
|
126
|
+
)
|
|
127
|
+
).then(
|
|
128
|
+
async (result) => {
|
|
129
|
+
await original.call(client, "COMMIT");
|
|
130
|
+
state.inTx = false;
|
|
131
|
+
state.injected = false;
|
|
132
|
+
return result;
|
|
133
|
+
},
|
|
134
|
+
async (err) => {
|
|
135
|
+
try {
|
|
136
|
+
await original.call(client, "ROLLBACK");
|
|
137
|
+
} catch {
|
|
138
|
+
}
|
|
139
|
+
state.inTx = false;
|
|
140
|
+
state.injected = false;
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
);
|
|
144
|
+
if (userCb) {
|
|
145
|
+
wrapped.then(
|
|
146
|
+
(result) => userCb(null, result),
|
|
147
|
+
(err) => userCb(err instanceof Error ? err : new Error(String(err)))
|
|
148
|
+
);
|
|
149
|
+
return void 0;
|
|
150
|
+
}
|
|
151
|
+
return wrapped;
|
|
152
|
+
}
|
|
153
|
+
function ensureState(client) {
|
|
154
|
+
let s = txState.get(client);
|
|
155
|
+
if (!s) {
|
|
156
|
+
s = { inTx: false, injected: false };
|
|
157
|
+
txState.set(client, s);
|
|
158
|
+
}
|
|
159
|
+
return s;
|
|
160
|
+
}
|
|
161
|
+
function extractQueryText(config) {
|
|
162
|
+
if (typeof config === "string") return config;
|
|
163
|
+
if (config && typeof config === "object" && typeof config.text === "string") {
|
|
164
|
+
return config.text;
|
|
165
|
+
}
|
|
166
|
+
return "";
|
|
167
|
+
}
|
|
168
|
+
function leadingVerb(text) {
|
|
169
|
+
let s = text;
|
|
170
|
+
while (true) {
|
|
171
|
+
const before = s.length;
|
|
172
|
+
s = s.replace(/^\s+/, "");
|
|
173
|
+
s = s.replace(/^--[^\n]*\n?/, "");
|
|
174
|
+
if (s.length === before) break;
|
|
175
|
+
}
|
|
176
|
+
const m = /^[A-Za-z]+/.exec(s);
|
|
177
|
+
return m ? m[0].toUpperCase() : "";
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export { patchPgClient };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export { __commonJS, __export, __require };
|