@kici-dev/shared 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/db-admin.js CHANGED
@@ -2,7 +2,6 @@ import "./rolldown-runtime-ClRpJifh.js";
2
2
  import { createPool } from "./db.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import pg from "pg";
5
- import { HoldType, unknownContributorHoldReason } from "@kici-dev/engine";
6
5
  //#region src/db-admin.ts
7
6
  /**
8
7
  * Admin/DB-operations helpers shared between `kici-admin` (orchestrator DB)
@@ -63,23 +62,6 @@ async function withAdminPool(adminUrl, fn) {
63
62
  }
64
63
  }
65
64
  /**
66
- * DROP `dbName` (if it exists). Terminates existing backend connections
67
- * so the DROP doesn't block. Idempotent — drops are IF EXISTS.
68
- *
69
- * Used by e2e cleanup after a full-lifecycle service-deploy test tears
70
- * down its isolated database. Shares the same admin-URL + identifier-
71
- * validation + backend-termination scaffolding as dropAndCreateDatabase
72
- * so the two helpers cannot drift.
73
- */
74
- async function dropDatabaseDirect(databaseUrl) {
75
- const { adminUrl, dbName } = parseDatabaseUrl(databaseUrl);
76
- assertValidIdentifier(dbName, "database name");
77
- await withAdminPool(adminUrl, async (pool) => {
78
- await pool.query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()", [dbName]);
79
- await pool.query(`DROP DATABASE IF EXISTS "${dbName}"`);
80
- });
81
- }
82
- /**
83
65
  * Drop `dbName` (if it exists), then recreate it owned by `owner`. Terminates
84
66
  * existing backend connections so the DROP doesn't block.
85
67
  */
@@ -870,24 +852,6 @@ async function showExecutionRunDirect(databaseUrl, opts) {
870
852
  }
871
853
  }
872
854
  /**
873
- * READ-ONLY: list execution_jobs for a given execution_runs.id. Ordered by
874
- * created_at ASC so downstream diffs show timeline order.
875
- */
876
- async function listExecutionJobsDirect(databaseUrl, opts) {
877
- const pool = createPool(databaseUrl);
878
- try {
879
- return { jobs: (await pool.query(`SELECT j.id, j.run_id, j.job_id, j.job_name, j.status, j.agent_id,
880
- j.started_at, j.completed_at, j.duration_ms, j.created_at, j.error_message,
881
- j.contexts
882
- FROM execution_jobs j
883
- INNER JOIN execution_runs r ON r.run_id = j.run_id
884
- WHERE r.run_id::text = $1 OR r.id::text = $1
885
- ORDER BY j.created_at ASC`, [opts.runId])).rows };
886
- } finally {
887
- await pool.end();
888
- }
889
- }
890
- /**
891
855
  * READ-ONLY: list workflow_registrations with optional filters. Also returns
892
856
  * the latest registry_versions.version so callers can assert registry bumps
893
857
  * without a second round trip.
@@ -1097,48 +1061,6 @@ async function emitKiciEventDirect(databaseUrl, opts) {
1097
1061
  }
1098
1062
  }
1099
1063
  /**
1100
- * Upsert a row into `generic_webhook_sources`. Uses
1101
- * `ON CONFLICT (routing_key) DO UPDATE` so warm-start mode (where the source
1102
- * may already exist from a prior run) is idempotent.
1103
- *
1104
- * IMPORTANT: callers must invoke this BEFORE the orchestrator starts, because
1105
- * GenericSourceManager caches sources at boot and does not reload them later.
1106
- * This helper supersedes seedGenericWebhookSource() in
1107
- * e2e/helpers/local-webhook.ts.
1108
- */
1109
- async function seedGenericWebhookSourceDirect(databaseUrl, opts) {
1110
- const pool = createPool(databaseUrl);
1111
- try {
1112
- await pool.query(`INSERT INTO generic_webhook_sources (
1113
- id, customer_id, name, routing_key,
1114
- verification_method, verification_config,
1115
- event_type_header, dedup_window_seconds,
1116
- max_payload_bytes, rate_limit_rpm, enabled,
1117
- provider_type, git_config
1118
- ) VALUES ($1, $2, $3, $4, $5, '{}', 'x-event-type', 300, 10485760, 600, true, $6, $7::jsonb)
1119
- ON CONFLICT (routing_key) DO UPDATE SET
1120
- customer_id = EXCLUDED.customer_id,
1121
- name = EXCLUDED.name,
1122
- verification_method = EXCLUDED.verification_method,
1123
- verification_config = EXCLUDED.verification_config,
1124
- provider_type = EXCLUDED.provider_type,
1125
- git_config = EXCLUDED.git_config,
1126
- enabled = true,
1127
- deleted_at = NULL,
1128
- updated_at = NOW()`, [
1129
- opts.sourceId,
1130
- opts.orgId,
1131
- opts.name,
1132
- opts.routingKey,
1133
- opts.verificationMethod ?? "none",
1134
- opts.providerType ?? "generic",
1135
- opts.gitConfig ? JSON.stringify(opts.gitConfig) : null
1136
- ]);
1137
- } finally {
1138
- await pool.end();
1139
- }
1140
- }
1141
- /**
1142
1064
  * Return `{ current: true }` if the applied migration count matches the
1143
1065
  * provider's migration count AND the content hash in `_migration_content_hash`
1144
1066
  * matches the provider's current hash. Otherwise return `{ current: false,
@@ -1190,434 +1112,6 @@ async function purgeSecretBackendsDirect(databaseUrl) {
1190
1112
  }
1191
1113
  }
1192
1114
  /**
1193
- * Check if an API key exists in the Platform DB (api_keys table — orchestrator-
1194
- * managed, NOT user_api_keys). Returns true when a row matches the hashed key.
1195
- */
1196
- async function apiKeyExistsDirect(databaseUrl, apiKey) {
1197
- const keyHash = createHash("sha256").update(apiKey).digest("hex");
1198
- const pool = createPool(databaseUrl);
1199
- try {
1200
- return (await pool.query("SELECT 1 FROM api_keys WHERE key_hash = $1", [keyHash])).rows.length > 0;
1201
- } finally {
1202
- await pool.end();
1203
- }
1204
- }
1205
- /**
1206
- * Insert an api_keys row (Platform-side orchestrator credential). Used by
1207
- * e2e setup to seed an orchestrator authentication token. Returns the id.
1208
- */
1209
- async function seedApiKeyInlineDirect(databaseUrl, opts) {
1210
- const keyHash = createHash("sha256").update(opts.fullKey).digest("hex");
1211
- const keyPrefix = opts.fullKey.slice(0, 16);
1212
- const pool = createPool(databaseUrl);
1213
- try {
1214
- return { keyId: (await pool.query(`INSERT INTO api_keys (key_hash, key_prefix, name, org_id)
1215
- VALUES ($1, $2, $3, $4)
1216
- RETURNING id`, [
1217
- keyHash,
1218
- keyPrefix,
1219
- opts.keyName,
1220
- opts.orgId
1221
- ])).rows[0].id };
1222
- } finally {
1223
- await pool.end();
1224
- }
1225
- }
1226
- /**
1227
- * Lookup a `platform_connections` row by connection_id. Returns true when
1228
- * present. Used by the orphan-sweeper e2e test.
1229
- */
1230
- async function platformConnectionExistsDirect(databaseUrl, connectionId) {
1231
- const pool = createPool(databaseUrl);
1232
- try {
1233
- const res = await pool.query(`SELECT 1 FROM platform_connections WHERE connection_id = $1 LIMIT 1`, [connectionId]);
1234
- return res.rowCount !== null && res.rowCount > 0;
1235
- } finally {
1236
- await pool.end();
1237
- }
1238
- }
1239
- /**
1240
- * Count `webhook_sources` rows for a given orchestrator_connection_id.
1241
- * Used by the orphan-sweeper e2e test to assert the FK CASCADE introduced
1242
- * by Platform migration 017 actually fires when the parent
1243
- * `platform_connections` row is deleted.
1244
- */
1245
- /**
1246
- * Look up a Platform-side `webhook_sources` row by routing key. Returns the
1247
- * row (org_id + provider + connection) or null. Used by E2E to assert that a
1248
- * source added at runtime on the orchestrator propagated to the Platform's
1249
- * `webhook_sources` table (the dashboard-visible source list) without a
1250
- * restart.
1251
- */
1252
- async function getWebhookSourceByRoutingKeyDirect(databaseUrl, routingKey) {
1253
- const pool = createPool(databaseUrl);
1254
- try {
1255
- const row = (await pool.query(`SELECT routing_key, org_id, provider
1256
- FROM webhook_sources
1257
- WHERE routing_key = $1
1258
- LIMIT 1`, [routingKey])).rows[0];
1259
- return row ? {
1260
- routing_key: String(row.routing_key),
1261
- org_id: String(row.org_id),
1262
- provider: String(row.provider)
1263
- } : null;
1264
- } finally {
1265
- await pool.end();
1266
- }
1267
- }
1268
- async function countWebhookSourcesByConnectionIdDirect(databaseUrl, connectionId) {
1269
- const pool = createPool(databaseUrl);
1270
- try {
1271
- const res = await pool.query(`SELECT COUNT(*)::int AS cnt
1272
- FROM webhook_sources
1273
- WHERE orchestrator_connection_id = $1`, [connectionId]);
1274
- return Number(res.rows[0]?.cnt ?? 0);
1275
- } finally {
1276
- await pool.end();
1277
- }
1278
- }
1279
- /**
1280
- * Find a `user_api_keys.id` preferring rows scoped to `preferredOrgId`, else
1281
- * any row in the table. Used by orphan-sweeper test to get a realistic
1282
- * `key_id` for platform_connections seeding.
1283
- */
1284
- async function findAnyUserApiKeyIdDirect(databaseUrl, preferredOrgId) {
1285
- const pool = createPool(databaseUrl);
1286
- try {
1287
- const scoped = await pool.query(`SELECT id FROM user_api_keys WHERE org_id = $1 LIMIT 1`, [preferredOrgId]);
1288
- if (scoped.rows.length > 0) return String(scoped.rows[0].id);
1289
- const any = await pool.query(`SELECT id FROM user_api_keys LIMIT 1`);
1290
- return any.rows.length > 0 ? String(any.rows[0].id) : null;
1291
- } finally {
1292
- await pool.end();
1293
- }
1294
- }
1295
- /**
1296
- * Seed or refresh a synthetic GitHub webhook source on the Platform DB.
1297
- * Used by HMAC E2E tests that post to `/webhook/:orgId/github`.
1298
- * Idempotent — refreshes the secret/org_id via ON CONFLICT DO UPDATE,
1299
- * and clears stale rows with a different routing_key under the same
1300
- * (org_id, provider, connection_id) triple.
1301
- */
1302
- async function seedSyntheticGithubSourceDirect(databaseUrl, opts) {
1303
- const pool = createPool(databaseUrl);
1304
- try {
1305
- await pool.query(`INSERT INTO platform_connections (
1306
- org_id, instance_id, connection_id, key_id, routing_keys
1307
- )
1308
- VALUES ($1, 'e2e-synthetic-instance', 'e2e-synthetic',
1309
- '00000000-0000-4000-8000-000000000000', $2::text)
1310
- ON CONFLICT (connection_id) DO UPDATE
1311
- SET org_id = $1,
1312
- routing_keys = $2::text,
1313
- last_heartbeat_at = NOW()`, [opts.orgId, JSON.stringify([opts.routingKey])]);
1314
- await pool.query(`DELETE FROM webhook_sources
1315
- WHERE org_id = $1 AND provider = 'github'
1316
- AND orchestrator_connection_id = 'e2e-synthetic'
1317
- AND routing_key != $2`, [opts.orgId, opts.routingKey]);
1318
- await pool.query(`INSERT INTO webhook_sources (routing_key, provider, orchestrator_connection_id, org_id, name, subtype, slug)
1319
- VALUES ($1, 'github', 'e2e-synthetic', $2, $3, $4, $5)
1320
- ON CONFLICT (routing_key, orchestrator_connection_id)
1321
- DO UPDATE SET org_id = $2, name = $3, subtype = $4, slug = $5`, [
1322
- opts.routingKey,
1323
- opts.orgId,
1324
- opts.name ?? null,
1325
- opts.subtype ?? null,
1326
- opts.slug ?? null
1327
- ]);
1328
- } finally {
1329
- await pool.end();
1330
- }
1331
- }
1332
- /**
1333
- * Seed a webhook secret into the orchestrator's `scoped_secrets` table,
1334
- * encrypted with the caller-supplied key. Ensures a `sources` row exists
1335
- * for the routing_key. Used by e2e setup on the orchestrator DB side.
1336
- *
1337
- * encryptFn takes plaintext + AAD and returns ciphertext bytes. The
1338
- * caller owns the crypto primitive so this helper stays decoupled from
1339
- * the orchestrator's PgSecretStore crypto module.
1340
- */
1341
- async function seedWebhookSecretDirect(databaseUrl, opts) {
1342
- const { randomBytes } = await import("node:crypto");
1343
- const pool = createPool(databaseUrl);
1344
- try {
1345
- let sourceId;
1346
- const sourceResult = await pool.query("SELECT id FROM sources WHERE routing_key = $1", [opts.routingKey]);
1347
- if (sourceResult.rows.length > 0) sourceId = sourceResult.rows[0].id;
1348
- else {
1349
- sourceId = randomBytes(16).toString("hex");
1350
- const [provider, appId] = opts.routingKey.split(":");
1351
- await pool.query(`INSERT INTO sources (id, provider, name, routing_key, config)
1352
- VALUES ($1, $2, $3, $4, $5)
1353
- ON CONFLICT (routing_key) DO NOTHING`, [
1354
- sourceId,
1355
- provider || "github",
1356
- `e2e-${appId}`,
1357
- opts.routingKey,
1358
- JSON.stringify({ appId: appId || "" })
1359
- ]);
1360
- sourceId = (await pool.query("SELECT id FROM sources WHERE routing_key = $1", [opts.routingKey])).rows[0].id;
1361
- }
1362
- const scope = `__source__/${sourceId}`;
1363
- const orgId = "__system__";
1364
- const aad = `${orgId}:${scope}:webhookSecret`;
1365
- const encrypted = opts.encryptFn(opts.webhookSecret, aad);
1366
- await pool.query(`INSERT INTO scoped_secrets (org_id, scope, key, encrypted_value, backend_type, key_version)
1367
- VALUES ($1, $2, 'webhookSecret', $3, 'pg', 1)
1368
- ON CONFLICT (org_id, scope, key) DO UPDATE SET encrypted_value = $3, updated_at = now()`, [
1369
- orgId,
1370
- scope,
1371
- encrypted
1372
- ]);
1373
- return { sourceId };
1374
- } finally {
1375
- await pool.end();
1376
- }
1377
- }
1378
- /**
1379
- * Seed a source private key into the orchestrator's `scoped_secrets` table.
1380
- * encryptFn signature matches seedWebhookSecretDirect. Returns null if the
1381
- * sources row is missing (matches legacy warning-and-skip behaviour).
1382
- */
1383
- async function seedSourcePrivateKeyDirect(databaseUrl, opts) {
1384
- const pool = createPool(databaseUrl);
1385
- try {
1386
- const sourceResult = await pool.query("SELECT id FROM sources WHERE routing_key = $1", [opts.routingKey]);
1387
- if (sourceResult.rows.length === 0) return null;
1388
- const sourceId = sourceResult.rows[0].id;
1389
- const scope = `__source__/${sourceId}`;
1390
- const orgId = "__system__";
1391
- const aad = `${orgId}:${scope}:privateKey`;
1392
- const encrypted = opts.encryptFn(opts.privateKey, aad);
1393
- await pool.query(`INSERT INTO scoped_secrets (org_id, scope, key, encrypted_value, backend_type, key_version)
1394
- VALUES ($1, $2, 'privateKey', $3, 'pg', 1)
1395
- ON CONFLICT (org_id, scope, key) DO UPDATE SET encrypted_value = $3, updated_at = now()`, [
1396
- orgId,
1397
- scope,
1398
- encrypted
1399
- ]);
1400
- return { sourceId };
1401
- } finally {
1402
- await pool.end();
1403
- }
1404
- }
1405
- /**
1406
- * Bump `registry_versions.version` for the default registry and return the
1407
- * new value. Used by cron-scheduler e2e to retrigger index after a manual
1408
- * workflow change.
1409
- */
1410
- async function bumpRegistryVersionDirect(databaseUrl) {
1411
- const pool = createPool(databaseUrl);
1412
- try {
1413
- return (await pool.query(`UPDATE registry_versions
1414
- SET version = version + 1, updated_at = NOW()
1415
- WHERE id = 'default'
1416
- RETURNING version`)).rows[0].version;
1417
- } finally {
1418
- await pool.end();
1419
- }
1420
- }
1421
- /**
1422
- * Poll `kici_events` for an event matching `eventName` created after `since`.
1423
- * Returns the newest match, or throws on timeout. Used by e2e event-routing tests.
1424
- */
1425
- async function pollKiciEventsDirect(databaseUrl, opts) {
1426
- const timeoutMs = opts.timeoutMs ?? 6e4;
1427
- const pollInterval = opts.pollIntervalMs ?? 2e3;
1428
- const deadline = Date.now() + timeoutMs;
1429
- const pool = createPool(databaseUrl);
1430
- try {
1431
- while (Date.now() < deadline) {
1432
- const filter = opts.payloadFilter;
1433
- const result = filter ? await pool.query(`SELECT * FROM kici_events
1434
- WHERE event_name = $1 AND created_at > $2 AND payload->>$3 = $4
1435
- ORDER BY created_at DESC
1436
- LIMIT 1`, [
1437
- opts.eventName,
1438
- opts.since.toISOString(),
1439
- filter.key,
1440
- filter.value
1441
- ]) : await pool.query(`SELECT * FROM kici_events
1442
- WHERE event_name = $1 AND created_at > $2
1443
- ORDER BY created_at DESC
1444
- LIMIT 1`, [opts.eventName, opts.since.toISOString()]);
1445
- if (result.rows.length > 0) return result.rows[0];
1446
- await new Promise((r) => setTimeout(r, pollInterval));
1447
- }
1448
- throw new Error(`Timed out after ${timeoutMs}ms waiting for kici_event '${opts.eventName}' since ${opts.since.toISOString()}`);
1449
- } finally {
1450
- await pool.end();
1451
- }
1452
- }
1453
- /**
1454
- * Ping a PostgreSQL database; retries until `SELECT 1` succeeds or the
1455
- * timeout expires. Used by e2e startup to wait for Postgres readiness.
1456
- */
1457
- async function waitForPostgresDirect(databaseUrl, opts) {
1458
- const timeout = opts?.timeoutMs ?? 3e4;
1459
- const interval = opts?.intervalMs ?? 2e3;
1460
- const deadline = Date.now() + timeout;
1461
- while (Date.now() < deadline) {
1462
- const pool = createPool(databaseUrl);
1463
- try {
1464
- await pool.query("SELECT 1");
1465
- await pool.end();
1466
- return;
1467
- } catch {
1468
- await pool.end();
1469
- }
1470
- await new Promise((r) => setTimeout(r, interval));
1471
- }
1472
- throw new Error(`PostgreSQL at ${databaseUrl} did not become available within ${timeout}ms`);
1473
- }
1474
- /**
1475
- * Wait for a specific execution_runs row to reach a terminal status.
1476
- * Used by test-pipeline e2e to gate on run completion. Terminal statuses
1477
- * are success / failed / cancelled / timed_out_stale.
1478
- */
1479
- async function waitForRunCompletionDirect(databaseUrl, runId, opts) {
1480
- const timeoutMs = opts?.timeoutMs ?? 12e4;
1481
- const intervalMs = opts?.intervalMs ?? 2e3;
1482
- const terminalStatuses = [
1483
- "success",
1484
- "failed",
1485
- "cancelled",
1486
- "timed_out_stale"
1487
- ];
1488
- const deadline = Date.now() + timeoutMs;
1489
- const pool = createPool(databaseUrl);
1490
- try {
1491
- while (Date.now() < deadline) {
1492
- const result = await pool.query(`SELECT status FROM execution_runs WHERE run_id = $1 LIMIT 1`, [runId]);
1493
- if (result.rows.length > 0) {
1494
- const status = result.rows[0].status;
1495
- if (terminalStatuses.includes(status)) return { status };
1496
- }
1497
- await new Promise((r) => setTimeout(r, intervalMs));
1498
- }
1499
- throw new Error(`Run ${runId} did not complete within ${timeoutMs}ms`);
1500
- } finally {
1501
- await pool.end();
1502
- }
1503
- }
1504
- /**
1505
- * DELETE from execution_jobs + execution_runs where started_at > since.
1506
- * Used by e2e cleanup for tests that want explicit post-test row cleanup.
1507
- */
1508
- async function cleanupExecutionRowsDirect(databaseUrl, since) {
1509
- const pool = createPool(databaseUrl);
1510
- try {
1511
- const jobsResult = await pool.query(`DELETE FROM execution_jobs WHERE run_id IN (
1512
- SELECT run_id FROM execution_runs WHERE started_at > $1
1513
- )`, [since]);
1514
- return {
1515
- runs: (await pool.query(`DELETE FROM execution_runs WHERE started_at > $1`, [since])).rowCount ?? 0,
1516
- jobs: jobsResult.rowCount ?? 0
1517
- };
1518
- } finally {
1519
- await pool.end();
1520
- }
1521
- }
1522
- /**
1523
- * Check whether the schema is "current" by comparing applied migration count
1524
- * and content hash against a caller-supplied set of migration files.
1525
- * Returns false if the migration table is missing, counts mismatch, or the
1526
- * stored hash differs from the caller-supplied hash. Used by e2e warm-start.
1527
- */
1528
- async function isSchemaCurrentFromFilesDirect(databaseUrl, opts) {
1529
- const tableName = opts.tableName ?? "kysely_migration";
1530
- const pool = createPool(databaseUrl);
1531
- try {
1532
- try {
1533
- if (((await pool.query(`SELECT COUNT(*)::int AS count FROM "${tableName}"`)).rows[0]?.count ?? 0) !== opts.expectedCount) return false;
1534
- const hashResult = await pool.query(`SELECT hash FROM ${MIGRATION_HASH_TABLE} WHERE table_name = $1`, [tableName]);
1535
- if (hashResult.rows.length === 0 || hashResult.rows[0].hash !== opts.expectedContentHash) return false;
1536
- return true;
1537
- } catch {
1538
- return false;
1539
- }
1540
- } finally {
1541
- await pool.end();
1542
- }
1543
- }
1544
- /**
1545
- * Store a migration content hash in the `_migration_content_hash` marker
1546
- * table. Creates the table if missing. Used by e2e freshDatabase() after
1547
- * migrations run so warm-start detection can compare on next run.
1548
- */
1549
- async function storeMigrationContentHashInTableDirect(databaseUrl, opts) {
1550
- const tableName = opts.tableName ?? "kysely_migration";
1551
- const pool = createPool(databaseUrl);
1552
- try {
1553
- await pool.query(`
1554
- CREATE TABLE IF NOT EXISTS ${MIGRATION_HASH_TABLE} (
1555
- table_name text PRIMARY KEY,
1556
- hash text NOT NULL
1557
- )
1558
- `);
1559
- await pool.query(`INSERT INTO ${MIGRATION_HASH_TABLE} (table_name, hash) VALUES ($1, $2)
1560
- ON CONFLICT (table_name) DO UPDATE SET hash = $2`, [tableName, opts.contentHash]);
1561
- } finally {
1562
- await pool.end();
1563
- }
1564
- }
1565
- /**
1566
- * Insert a join_tokens row (orchestrator DB) for cluster peer auth.
1567
- * Used by cluster e2e helpers to provision a shared secret the second
1568
- * orchestrator will use when joining the cluster.
1569
- */
1570
- async function createJoinTokenDirect(databaseUrl, opts) {
1571
- const pool = createPool(databaseUrl);
1572
- try {
1573
- await pool.query(`INSERT INTO join_tokens (id, token_hash, routing_info, role, created_by, expires_at)
1574
- VALUES ($1, $2, $3, $4, $5, $6)`, [
1575
- opts.id,
1576
- opts.tokenHash,
1577
- JSON.stringify(opts.routingInfo),
1578
- opts.role,
1579
- opts.createdBy,
1580
- opts.expiresAt
1581
- ]);
1582
- } finally {
1583
- await pool.end();
1584
- }
1585
- }
1586
- /**
1587
- * Delete join_tokens rows by `created_by` (orchestrator DB). Used by cluster
1588
- * E2E tests to clean up test-provisioned tokens between runs.
1589
- */
1590
- async function deleteJoinTokensByCreatedByDirect(databaseUrl, opts) {
1591
- const pool = createPool(databaseUrl);
1592
- try {
1593
- await pool.query(`DELETE FROM join_tokens WHERE created_by = $1`, [opts.createdBy]);
1594
- } finally {
1595
- await pool.end();
1596
- }
1597
- }
1598
- /**
1599
- * Update the routing_key on `sources` rows for a given provider. Used by
1600
- * cluster e2e to swap the staging routing key for an isolated test key
1601
- * (and to restore it on teardown).
1602
- *
1603
- * `whereRoutingKey`: optional filter on the current routing_key. When
1604
- * present only rows matching it are updated; when absent the provider
1605
- * filter alone is used (with an implicit `!= newRoutingKey` guard so the
1606
- * update is idempotent).
1607
- */
1608
- async function updateSourceRoutingKeyDirect(databaseUrl, opts) {
1609
- const pool = createPool(databaseUrl);
1610
- try {
1611
- return { updated: (opts.whereRoutingKey ? await pool.query(`UPDATE sources SET routing_key = $1 WHERE provider = $2 AND routing_key = $3`, [
1612
- opts.newRoutingKey,
1613
- opts.provider,
1614
- opts.whereRoutingKey
1615
- ]) : await pool.query(`UPDATE sources SET routing_key = $1 WHERE provider = $2 AND routing_key != $1`, [opts.newRoutingKey, opts.provider])).rowCount ?? 0 };
1616
- } finally {
1617
- await pool.end();
1618
- }
1619
- }
1620
- /**
1621
1115
  * Delete peer_credentials rows whose instance_id does NOT match a pattern.
1622
1116
  * Used by cluster e2e to wipe stale staging peer credentials while leaving
1623
1117
  * e2e-* peers intact.
@@ -1630,1244 +1124,7 @@ async function prunePeerCredentialsDirect(databaseUrl, opts) {
1630
1124
  await pool.end();
1631
1125
  }
1632
1126
  }
1633
- /**
1634
- * Poll Platform until at least `minRegistrations` distinct orchestrator
1635
- * connections are BOTH registered for the routing key (row in webhook_sources)
1636
- * AND live (row in platform_connections with status='connected'). The live-
1637
- * connection join is critical — Platform's webhook_sources rows persist after
1638
- * a connection disconnects (the orphan sweeper eventually reaps them), so a
1639
- * naive COUNT(DISTINCT) on webhook_sources alone would inflate the number
1640
- * and mask a missing coordinator registration.
1641
- */
1642
- async function waitForPlatformRegistrationsDirect(platformDbUrl, routingKey, opts) {
1643
- const minRegistrations = opts?.minRegistrations ?? 1;
1644
- const timeoutMs = opts?.timeoutMs ?? 3e4;
1645
- const intervalMs = opts?.intervalMs ?? 2e3;
1646
- const deadline = Date.now() + timeoutMs;
1647
- const pool = createPool(platformDbUrl);
1648
- try {
1649
- while (Date.now() < deadline) {
1650
- if (((await pool.query(`SELECT COUNT(DISTINCT ws.orchestrator_connection_id)::int AS cnt
1651
- FROM webhook_sources ws
1652
- JOIN platform_connections pc
1653
- ON pc.connection_id = ws.orchestrator_connection_id
1654
- AND pc.status = 'connected'
1655
- WHERE ws.routing_key = $1
1656
- AND ws.orchestrator_connection_id != 'e2e-synthetic'`, [routingKey])).rows[0]?.cnt ?? 0) >= minRegistrations) return;
1657
- await new Promise((r) => setTimeout(r, intervalMs));
1658
- }
1659
- throw new Error(`Timed out waiting for ${minRegistrations} orchestrator registration(s) for routing key ${routingKey} (waited ${timeoutMs}ms)`);
1660
- } finally {
1661
- await pool.end();
1662
- }
1663
- }
1664
- async function seedUniversalGitSourceDirect(databaseUrl, opts) {
1665
- const eventTypeHeader = opts.eventTypeHeader ?? "x-gitea-event";
1666
- const pool = createPool(databaseUrl);
1667
- try {
1668
- await pool.query(`INSERT INTO generic_webhook_sources (
1669
- id, customer_id, name, routing_key,
1670
- verification_method, verification_config,
1671
- event_type_header, dedup_window_seconds,
1672
- max_payload_bytes, rate_limit_rpm, enabled,
1673
- provider_type, git_config
1674
- ) VALUES ($1, $2, $3, $4, 'none', '{}', $6, 300, 10485760, 600, true,
1675
- 'generic', $5::jsonb)
1676
- ON CONFLICT (routing_key) DO UPDATE SET
1677
- customer_id = EXCLUDED.customer_id,
1678
- name = EXCLUDED.name,
1679
- event_type_header = EXCLUDED.event_type_header,
1680
- git_config = EXCLUDED.git_config,
1681
- enabled = true,
1682
- deleted_at = NULL,
1683
- updated_at = NOW()`, [
1684
- opts.sourceId,
1685
- opts.orgId,
1686
- opts.sourceName,
1687
- opts.routingKey,
1688
- JSON.stringify(opts.gitConfig),
1689
- eventTypeHeader
1690
- ]);
1691
- } finally {
1692
- await pool.end();
1693
- }
1694
- }
1695
- /** repo_identifier used for the different-repo isolation hold. */
1696
- const CI_SECURITY_OTHER_REPO = "other/repo";
1697
- async function seedCiSecurityFixturesDirect(databaseUrl, opts) {
1698
- const contextName = opts.contextName ?? "ci-security-env";
1699
- const sourceName = opts.sourceName ?? "ci-security-dashboard-resolver";
1700
- const sourceRoutingKey = opts.sourceRoutingKey ?? `generic:${opts.orgId}:ci-security-dashboard`;
1701
- const pool = createPool(databaseUrl);
1702
- try {
1703
- await pool.query(`INSERT INTO sources (id, provider, name, routing_key, config, customer_id)
1704
- VALUES (gen_random_uuid(), \'generic\', $1, $2, \'{}\', $3)
1705
- ON CONFLICT (routing_key) DO UPDATE SET customer_id = EXCLUDED.customer_id`, [
1706
- sourceName,
1707
- sourceRoutingKey,
1708
- opts.orgId
1709
- ]);
1710
- const envId = (await pool.query(`INSERT INTO contexts (org_id, name, type, enabled)
1711
- VALUES ($1, $2, \'fixed\', true)
1712
- ON CONFLICT (org_id, name) DO UPDATE SET enabled = true
1713
- RETURNING id`, [opts.orgId, contextName])).rows[0].id;
1714
- async function seedPrHold(args) {
1715
- await pool.query(`INSERT INTO execution_runs (
1716
- run_id, workflow_name, provider, repo_identifier,
1717
- ref, sha, delivery_id, status, trust_tier, lock_file_source,
1718
- contributor_username, routing_key, pr_number
1719
- ) VALUES ($1, \'e2e-security-wf\', \'internal\', $4, \'refs/heads/feature\',
1720
- $5, $2, \'pending\', \'unknown\', \'base\', \'unknown-dev\', $3, $6)`, [
1721
- args.runId,
1722
- args.deliveryId,
1723
- opts.runsRoutingKey,
1724
- args.repoIdentifier,
1725
- args.sha,
1726
- args.prNumber
1727
- ]);
1728
- await pool.query(`INSERT INTO execution_jobs (job_id, run_id, job_name, status)
1729
- VALUES ($1, $2, \'security-test-job\', \'pending\')`, [args.jobId, args.runId]);
1730
- return (await pool.query(`INSERT INTO held_runs (org_id, run_id, job_id, context_id, hold_type, queue_type, reason, expires_at)
1731
- VALUES ($1, $2, $3, $4, $5, \'security\', $6, NOW() + INTERVAL \'72 hours\')
1732
- RETURNING id`, [
1733
- opts.orgId,
1734
- args.runId,
1735
- args.jobId,
1736
- args.contextId === void 0 ? envId : args.contextId,
1737
- args.holdType ?? HoldType.enum.security,
1738
- args.reason ?? unknownContributorHoldReason(contextName)
1739
- ])).rows[0].id;
1740
- }
1741
- const heldRunId = await seedPrHold({
1742
- runId: opts.unknownRunId,
1743
- deliveryId: opts.unknownDeliveryId,
1744
- jobId: opts.unknownJobId,
1745
- repoIdentifier: ".",
1746
- prNumber: 1,
1747
- sha: "abc123"
1748
- });
1749
- const secondHeldRunId = await seedPrHold({
1750
- runId: opts.secondPrRunId,
1751
- deliveryId: opts.secondPrDeliveryId,
1752
- jobId: opts.secondPrJobId,
1753
- repoIdentifier: ".",
1754
- prNumber: 2,
1755
- sha: "bbb222"
1756
- });
1757
- const otherRepoHeldRunId = await seedPrHold({
1758
- runId: opts.otherRepoRunId,
1759
- deliveryId: opts.otherRepoDeliveryId,
1760
- jobId: opts.otherRepoJobId,
1761
- repoIdentifier: CI_SECURITY_OTHER_REPO,
1762
- prNumber: 1,
1763
- sha: "ccc333"
1764
- });
1765
- const wfModHeldRunId = await seedPrHold({
1766
- runId: opts.wfModRunId,
1767
- deliveryId: opts.wfModDeliveryId,
1768
- jobId: opts.wfModJobId,
1769
- repoIdentifier: ".",
1770
- prNumber: 3,
1771
- sha: "ddd444",
1772
- holdType: HoldType.enum.security,
1773
- reason: "workflow_modification",
1774
- contextId: null
1775
- });
1776
- const forkPrHeldRunId = await seedPrHold({
1777
- runId: opts.forkPrRunId,
1778
- deliveryId: opts.forkPrDeliveryId,
1779
- jobId: opts.forkPrJobId,
1780
- repoIdentifier: ".",
1781
- prNumber: 4,
1782
- sha: "eee555",
1783
- holdType: HoldType.enum.security,
1784
- reason: "fork_pr",
1785
- contextId: null
1786
- });
1787
- await pool.query(`INSERT INTO execution_runs (
1788
- run_id, workflow_name, provider, repo_identifier,
1789
- ref, sha, delivery_id, status, trust_tier, lock_file_source,
1790
- contributor_username, routing_key, pr_number
1791
- ) VALUES ($1, \'e2e-security-wf\', \'internal\', \'.\', \'refs/heads/feature\',
1792
- \'def456\', $2, \'running\', \'trusted\', \'head\', \'trusted-dev\', $3, 1)`, [
1793
- opts.trustedRunId,
1794
- opts.trustedDeliveryId,
1795
- opts.runsRoutingKey
1796
- ]);
1797
- await pool.query(`INSERT INTO execution_jobs (job_id, run_id, job_name, status)
1798
- VALUES ($1, $2, \'security-test-job\', \'running\')`, [opts.trustedJobId, opts.trustedRunId]);
1799
- return {
1800
- contextName,
1801
- envId,
1802
- heldRunId,
1803
- secondHeldRunId,
1804
- otherRepoHeldRunId,
1805
- wfModHeldRunId,
1806
- forkPrHeldRunId
1807
- };
1808
- } finally {
1809
- await pool.end();
1810
- }
1811
- }
1812
- /**
1813
- * Poll `execution_runs` for the newest run started since `since` whose status
1814
- * is in `statuses`, returning that status. Resolves `{ status: null }` if the
1815
- * deadline passes before any run reaches a target status.
1816
- *
1817
- * Callers wanting "did the run finish?" pass the terminal status set and read
1818
- * the landed status — a terminal failure is reported immediately rather than
1819
- * indistinguishable from a timeout. Used by the cluster reroute tests to gate
1820
- * on a workflow reaching a terminal state after a webhook trigger.
1821
- */
1822
- async function waitForExecutionRunReachesStatusSinceDirect(databaseUrl, opts) {
1823
- const timeoutMs = opts.timeoutMs ?? 24e4;
1824
- const intervalMs = opts.intervalMs ?? 5e3;
1825
- const deadline = Date.now() + timeoutMs;
1826
- const pool = createPool(databaseUrl);
1827
- try {
1828
- while (Date.now() < deadline) {
1829
- const result = await pool.query(`SELECT status FROM execution_runs
1830
- WHERE started_at > $1 AND status = ANY($2)
1831
- ORDER BY started_at DESC
1832
- LIMIT 1`, [opts.since, [...opts.statuses]]);
1833
- if (result.rows.length > 0) return { status: result.rows[0].status };
1834
- await new Promise((r) => setTimeout(r, intervalMs));
1835
- }
1836
- return { status: null };
1837
- } finally {
1838
- await pool.end();
1839
- }
1840
- }
1841
- async function latestExecutionRunByStatusDirect(databaseUrl, opts) {
1842
- const pool = createPool(databaseUrl);
1843
- try {
1844
- const runResult = await pool.query(`SELECT run_id, workflow_name, status FROM execution_runs
1845
- WHERE status = $1
1846
- ORDER BY started_at DESC LIMIT 1`, [opts.status]);
1847
- if (runResult.rows.length === 0) return null;
1848
- const run = runResult.rows[0];
1849
- return {
1850
- run,
1851
- jobs: (await pool.query(`SELECT job_id, job_name, status FROM execution_jobs WHERE run_id = $1`, [run.run_id])).rows
1852
- };
1853
- } finally {
1854
- await pool.end();
1855
- }
1856
- }
1857
- async function waitForLatestExecutionJobStatusDirect(databaseUrl, opts) {
1858
- const terminal = opts.terminalStatuses ?? [
1859
- "success",
1860
- "completed",
1861
- "failed"
1862
- ];
1863
- const timeoutMs = opts.timeoutMs ?? 18e4;
1864
- const intervalMs = opts.intervalMs ?? 3e3;
1865
- const deadline = Date.now() + timeoutMs;
1866
- const pool = createPool(databaseUrl);
1867
- try {
1868
- let status = null;
1869
- let errorMessage = null;
1870
- let runId = null;
1871
- while (Date.now() < deadline) {
1872
- const result = await pool.query(`SELECT j.status, j.error_message, r.run_id
1873
- FROM execution_jobs j
1874
- JOIN execution_runs r ON r.run_id = j.run_id
1875
- WHERE r.workflow_name = $1
1876
- AND r.started_at >= $2
1877
- ORDER BY r.started_at DESC
1878
- LIMIT 1`, [opts.workflowName, opts.since]);
1879
- if (result.rows.length > 0) {
1880
- status = result.rows[0].status;
1881
- errorMessage = result.rows[0].error_message;
1882
- runId = result.rows[0].run_id;
1883
- if (status && terminal.includes(status)) break;
1884
- }
1885
- await new Promise((r) => setTimeout(r, intervalMs));
1886
- }
1887
- return {
1888
- status,
1889
- errorMessage,
1890
- runId
1891
- };
1892
- } finally {
1893
- await pool.end();
1894
- }
1895
- }
1896
- async function describeTableColumnsDirect(databaseUrl, opts) {
1897
- const pool = createPool(databaseUrl);
1898
- try {
1899
- return (await pool.query(`SELECT column_name, data_type FROM information_schema.columns
1900
- WHERE table_name = $1
1901
- ORDER BY ordinal_position`, [opts.tableName])).rows.map((r) => ({
1902
- name: r.column_name,
1903
- dataType: r.data_type
1904
- }));
1905
- } finally {
1906
- await pool.end();
1907
- }
1908
- }
1909
- /**
1910
- * READ-ONLY: return true if a table exists in the public schema.
1911
- */
1912
- async function tableExistsDirect(databaseUrl, opts) {
1913
- const pool = createPool(databaseUrl);
1914
- try {
1915
- return (await pool.query(`SELECT 1 FROM information_schema.tables
1916
- WHERE table_schema = $1 AND table_name = $2`, [opts.schema ?? "public", opts.tableName])).rows.length > 0;
1917
- } finally {
1918
- await pool.end();
1919
- }
1920
- }
1921
- async function insertKiciEventRawDirect(databaseUrl, opts) {
1922
- const expiresIn = opts.expiresIn ?? "1 hour";
1923
- const pool = createPool(databaseUrl);
1924
- try {
1925
- return { id: (await pool.query(`INSERT INTO kici_events (event_name, payload, source_routing_key, chain_depth, expires_at)
1926
- VALUES ($1, $2, $3, $4, NOW() + ($5)::interval)
1927
- RETURNING id`, [
1928
- opts.eventName,
1929
- JSON.stringify(opts.payload),
1930
- opts.sourceRoutingKey ?? null,
1931
- opts.chainDepth ?? 0,
1932
- expiresIn
1933
- ])).rows[0].id };
1934
- } finally {
1935
- await pool.end();
1936
- }
1937
- }
1938
- async function showKiciEventDirect(databaseUrl, opts) {
1939
- const pool = createPool(databaseUrl);
1940
- try {
1941
- return (await pool.query(`SELECT id, event_name, payload, chain_depth, source_routing_key,
1942
- source_repo, processed, expires_at, created_at
1943
- FROM kici_events WHERE id = $1`, [opts.id])).rows[0] ?? null;
1944
- } finally {
1945
- await pool.end();
1946
- }
1947
- }
1948
- /**
1949
- * READ-ONLY: list kici_events with filter hooks used by e2e tests:
1950
- * by `event_name`, minimum `chain_depth`, expiry window. Returns the
1951
- * rows with chain_depth ordered ascending. Callers apply assertions.
1952
- */
1953
- async function listKiciEventsDirect(databaseUrl, opts = {}) {
1954
- const pool = createPool(databaseUrl);
1955
- try {
1956
- const clauses = [];
1957
- const params = [];
1958
- let idx = 1;
1959
- if (opts.eventName !== void 0) {
1960
- clauses.push(`event_name = $${idx}`);
1961
- params.push(opts.eventName);
1962
- idx += 1;
1963
- }
1964
- if (opts.minChainDepth !== void 0) {
1965
- clauses.push(`chain_depth > $${idx}`);
1966
- params.push(opts.minChainDepth);
1967
- idx += 1;
1968
- }
1969
- if (opts.onlyExpired) clauses.push(`expires_at < NOW()`);
1970
- const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
1971
- const limit = Math.max(1, Math.min(1e4, opts.limit ?? 1e3));
1972
- return (await pool.query(`SELECT id, event_name, payload, chain_depth, source_routing_key,
1973
- source_repo, processed, expires_at, created_at
1974
- FROM kici_events
1975
- ${where}
1976
- ORDER BY chain_depth ASC, created_at ASC
1977
- LIMIT ${limit}`, params)).rows;
1978
- } finally {
1979
- await pool.end();
1980
- }
1981
- }
1982
- /**
1983
- * DELETE kici_events by id or event_name. Returns the number of rows
1984
- * deleted. Used by event-routing teardown.
1985
- */
1986
- async function deleteKiciEventsDirect(databaseUrl, opts) {
1987
- if (!opts.id && !opts.eventName) throw new Error("deleteKiciEventsDirect: one of {id, eventName} is required");
1988
- const pool = createPool(databaseUrl);
1989
- try {
1990
- return { deleted: (opts.id ? await pool.query(`DELETE FROM kici_events WHERE id = $1`, [opts.id]) : await pool.query(`DELETE FROM kici_events WHERE event_name = $1`, [opts.eventName])).rowCount ?? 0 };
1991
- } finally {
1992
- await pool.end();
1993
- }
1994
- }
1995
- /**
1996
- * INSERT a kici_events row with an explicit created_at. Lets a test place
1997
- * many events on the exact same timestamp so the catch-up keyset cursor's
1998
- * same-created_at tie handling is genuinely exercised (the default-NOW insert
1999
- * path cannot force ties deterministically). Returns the inserted id.
2000
- */
2001
- async function insertKiciEventAtDirect(databaseUrl, opts) {
2002
- const expiresIn = opts.expiresIn ?? "7 days";
2003
- const pool = createPool(databaseUrl);
2004
- try {
2005
- return { id: (await pool.query(`INSERT INTO kici_events
2006
- (event_name, payload, source_routing_key, chain_depth, processed, created_at, expires_at)
2007
- VALUES ($1, $2::jsonb, $3, $4, false, $5::timestamptz, NOW() + ($6)::interval)
2008
- RETURNING id`, [
2009
- opts.eventName,
2010
- JSON.stringify(opts.payload ?? {}),
2011
- opts.sourceRoutingKey ?? null,
2012
- opts.chainDepth ?? 0,
2013
- opts.createdAt.toISOString(),
2014
- expiresIn
2015
- ])).rows[0].id };
2016
- } finally {
2017
- await pool.end();
2018
- }
2019
- }
2020
- /**
2021
- * Page through unprocessed, non-DLQ kici_events for a given event_name using
2022
- * the same composite `(created_at, id)` keyset cursor + `ORDER BY created_at
2023
- * ASC, id ASC` that EventStore.getUnprocessedSince runs. Keep this SQL in sync
2024
- * with `packages/orchestrator/src/events/event-store.ts`.
2025
- *
2026
- * Returns every id seen across all pages in traversal order (with duplicates
2027
- * preserved so the caller can assert none occur) plus the page count. This is
2028
- * the real-Postgres guard that the keyset cursor pages the entire backlog —
2029
- * including same-created_at ties across a page boundary — with no skip and no
2030
- * duplicate.
2031
- */
2032
- async function paginateUnprocessedEventsKeysetDirect(databaseUrl, opts) {
2033
- const batchSize = Math.max(1, Math.min(1e4, opts.batchSize ?? 100));
2034
- const pool = createPool(databaseUrl);
2035
- try {
2036
- const ids = [];
2037
- let cursor = null;
2038
- let pages = 0;
2039
- for (;;) {
2040
- const params = [opts.eventName];
2041
- let cursorClause = "";
2042
- if (cursor) {
2043
- cursorClause = `AND (created_at, id) > ($2::timestamptz, $3::uuid)`;
2044
- params.push(cursor.createdAt, cursor.id);
2045
- }
2046
- const { rows } = await pool.query(`SELECT id, created_at FROM kici_events
2047
- WHERE event_name = $1 AND processed = false AND dlq_at IS NULL ${cursorClause}
2048
- ORDER BY created_at ASC, id ASC
2049
- LIMIT ${batchSize}`, params);
2050
- if (rows.length === 0) break;
2051
- pages += 1;
2052
- for (const r of rows) ids.push(r.id);
2053
- const last = rows[rows.length - 1];
2054
- cursor = {
2055
- createdAt: new Date(last.created_at).toISOString(),
2056
- id: last.id
2057
- };
2058
- if (rows.length < batchSize) break;
2059
- }
2060
- return {
2061
- ids,
2062
- pages
2063
- };
2064
- } finally {
2065
- await pool.end();
2066
- }
2067
- }
2068
- /**
2069
- * Simulate a NOTIFY on `kici_event_channel` and verify a LISTEN client
2070
- * receives it. Used by event-routing e2e to prove the infrastructure
2071
- * the EventRouter uses for real-time delivery is functional. Owns the
2072
- * pool for the full test to keep the listen/notify correlated.
2073
- */
2074
- async function verifyKiciEventNotifyDirect(databaseUrl, opts) {
2075
- const waitMs = opts.waitMs ?? 1e3;
2076
- const pool = createPool(databaseUrl);
2077
- const client = await pool.connect();
2078
- try {
2079
- const notifications = [];
2080
- client.on("notification", (msg) => {
2081
- if (msg.channel === "kici_event_channel") notifications.push(msg.payload ?? "");
2082
- });
2083
- await client.query("LISTEN kici_event_channel");
2084
- await pool.query(`SELECT pg_notify('kici_event_channel', $1)`, [opts.payload]);
2085
- await new Promise((r) => setTimeout(r, waitMs));
2086
- await client.query("UNLISTEN kici_event_channel");
2087
- return { received: notifications };
2088
- } finally {
2089
- client.release();
2090
- await pool.end();
2091
- }
2092
- }
2093
- /**
2094
- * INSERT a cross_repo_trust row. Returns the new id and allowed_events
2095
- * array. Used by generic-webhook + event-routing e2e until a proper
2096
- * `kici-admin trust` CLI ships.
2097
- */
2098
- async function seedCrossRepoTrustDirect(databaseUrl, opts) {
2099
- const pool = createPool(databaseUrl);
2100
- try {
2101
- const result = await pool.query(`INSERT INTO cross_repo_trust
2102
- (source_repo, source_routing_key, target_repo, target_routing_key, allowed_events)
2103
- VALUES ($1, $2, $3, $4, $5)
2104
- RETURNING id, allowed_events`, [
2105
- opts.sourceRepo,
2106
- opts.sourceRoutingKey,
2107
- opts.targetRepo,
2108
- opts.targetRoutingKey,
2109
- opts.allowedEvents ? JSON.stringify(opts.allowedEvents) : null
2110
- ]);
2111
- return {
2112
- id: result.rows[0].id,
2113
- allowedEvents: result.rows[0].allowed_events
2114
- };
2115
- } finally {
2116
- await pool.end();
2117
- }
2118
- }
2119
- /**
2120
- * READ-ONLY: list cross_repo_trust rows by source_routing_key. Used by
2121
- * generic-webhook e2e to find a trust row it just inserted.
2122
- */
2123
- async function listCrossRepoTrustBySourceRoutingKeyDirect(databaseUrl, opts) {
2124
- const pool = createPool(databaseUrl);
2125
- try {
2126
- return (await pool.query(`SELECT id, source_repo, source_routing_key, target_repo, target_routing_key, allowed_events
2127
- FROM cross_repo_trust WHERE source_routing_key = $1`, [opts.sourceRoutingKey])).rows;
2128
- } finally {
2129
- await pool.end();
2130
- }
2131
- }
2132
- /**
2133
- * DELETE cross_repo_trust rows. Deletes by id, or asserts uniqueness
2134
- * check error on duplicate INSERT (handled by caller). Returns row count.
2135
- */
2136
- async function deleteCrossRepoTrustDirect(databaseUrl, opts) {
2137
- const pool = createPool(databaseUrl);
2138
- try {
2139
- return { deleted: (await pool.query(`DELETE FROM cross_repo_trust WHERE id = $1`, [opts.id])).rowCount ?? 0 };
2140
- } finally {
2141
- await pool.end();
2142
- }
2143
- }
2144
- /**
2145
- * Direct INSERT with duplicate-key detection. Used by event-routing
2146
- * e2e to verify the unique constraint enforces. Throws on duplicate;
2147
- * caller asserts the error message matches /unique/i.
2148
- */
2149
- async function insertCrossRepoTrustStrictDirect(databaseUrl, opts) {
2150
- const pool = createPool(databaseUrl);
2151
- try {
2152
- await pool.query(`INSERT INTO cross_repo_trust (source_repo, source_routing_key, target_repo, target_routing_key)
2153
- VALUES ($1, $2, $3, $4)`, [
2154
- opts.sourceRepo,
2155
- opts.sourceRoutingKey,
2156
- opts.targetRepo,
2157
- opts.targetRoutingKey
2158
- ]);
2159
- } finally {
2160
- await pool.end();
2161
- }
2162
- }
2163
- /**
2164
- * Cleanup helper for workflow_registrations. Accepts id, routingKey,
2165
- * or repoIdentifier filter (exactly one). Returns delete count.
2166
- */
2167
- async function deleteWorkflowRegistrationsDirect(databaseUrl, opts) {
2168
- if ([
2169
- opts.id,
2170
- opts.routingKey,
2171
- opts.repoIdentifier
2172
- ].filter((v) => v !== void 0).length !== 1) throw new Error("deleteWorkflowRegistrationsDirect: exactly one of {id, routingKey, repoIdentifier} required");
2173
- const pool = createPool(databaseUrl);
2174
- try {
2175
- let result;
2176
- if (opts.id) result = await pool.query(`DELETE FROM workflow_registrations WHERE id = $1`, [opts.id]);
2177
- else if (opts.routingKey) result = await pool.query(`DELETE FROM workflow_registrations WHERE routing_key = $1`, [opts.routingKey]);
2178
- else result = await pool.query(`DELETE FROM workflow_registrations WHERE repo_identifier = $1`, [opts.repoIdentifier]);
2179
- return { deleted: result.rowCount ?? 0 };
2180
- } finally {
2181
- await pool.end();
2182
- }
2183
- }
2184
- async function getWorkflowRegistrationByIdDirect(databaseUrl, opts) {
2185
- const pool = createPool(databaseUrl);
2186
- try {
2187
- return (await pool.query(`SELECT id, repo_identifier, workflow_name, routing_key, customer_id,
2188
- trigger_types, disabled, is_global, commit_sha, source_file,
2189
- created_at, updated_at, lock_entry
2190
- FROM workflow_registrations
2191
- WHERE id = $1`, [opts.id])).rows[0] ?? null;
2192
- } finally {
2193
- await pool.end();
2194
- }
2195
- }
2196
- async function listRegistrationsByRoutingKeyDirect(databaseUrl, opts) {
2197
- const pool = createPool(databaseUrl);
2198
- try {
2199
- const globalFilter = opts.onlyGlobal ? `AND is_global = TRUE` : "";
2200
- const result = await pool.query(`SELECT workflow_name, is_global, updated_at
2201
- FROM workflow_registrations
2202
- WHERE routing_key = $1 ${globalFilter}`, [opts.routingKey]);
2203
- let latest = null;
2204
- for (const r of result.rows) {
2205
- const d = r.updated_at ? new Date(r.updated_at) : null;
2206
- if (d && (!latest || d.getTime() > latest.getTime())) latest = d;
2207
- }
2208
- return {
2209
- count: result.rows.length,
2210
- latestUpdatedAt: latest,
2211
- rows: result.rows.map((r) => ({
2212
- workflow_name: r.workflow_name,
2213
- is_global: r.is_global
2214
- }))
2215
- };
2216
- } finally {
2217
- await pool.end();
2218
- }
2219
- }
2220
- /**
2221
- * Poll `workflow_registrations` for at least `minCount` rows for a
2222
- * routing key. Returns the rows or throws on timeout (keeps parity with
2223
- * the forgejo helper pattern it replaces).
2224
- */
2225
- async function waitForRegistrationsByRoutingKeyDirect(databaseUrl, opts) {
2226
- const minCount = opts.minCount ?? 1;
2227
- const timeoutMs = opts.timeoutMs ?? 3e4;
2228
- const intervalMs = opts.intervalMs ?? 1e3;
2229
- const deadline = Date.now() + timeoutMs;
2230
- let rows = [];
2231
- while (Date.now() < deadline) {
2232
- rows = (await listRegistrationsByRoutingKeyDirect(databaseUrl, {
2233
- routingKey: opts.routingKey,
2234
- onlyGlobal: opts.onlyGlobal
2235
- })).rows;
2236
- if (rows.length >= minCount) return rows;
2237
- await new Promise((r) => setTimeout(r, intervalMs));
2238
- }
2239
- return rows;
2240
- }
2241
- /**
2242
- * Wait for `workflow_registrations.updated_at` for a routing key to
2243
- * exceed `baselineUpdatedAt`. Used by forgejo rotated-PAT e2e.
2244
- */
2245
- async function waitForRegistrationsUpdatedAtAdvanceDirect(databaseUrl, opts) {
2246
- const timeoutMs = opts.timeoutMs ?? 3e4;
2247
- const intervalMs = opts.intervalMs ?? 1e3;
2248
- const deadline = Date.now() + timeoutMs;
2249
- let latest = null;
2250
- while (Date.now() < deadline) {
2251
- latest = (await listRegistrationsByRoutingKeyDirect(databaseUrl, { routingKey: opts.routingKey })).latestUpdatedAt;
2252
- if (latest && (!opts.baselineUpdatedAt || latest.getTime() > opts.baselineUpdatedAt.getTime())) return {
2253
- advanced: true,
2254
- latestUpdatedAt: latest
2255
- };
2256
- await new Promise((r) => setTimeout(r, intervalMs));
2257
- }
2258
- return {
2259
- advanced: false,
2260
- latestUpdatedAt: latest
2261
- };
2262
- }
2263
- /**
2264
- * UPDATE a workflow_registrations row's commit_sha. Used by cron-scheduler
2265
- * e2e where the manual-schedule handler rejects null commit SHAs.
2266
- */
2267
- async function updateWorkflowRegistrationCommitShaDirect(databaseUrl, opts) {
2268
- const pool = createPool(databaseUrl);
2269
- try {
2270
- await pool.query(`UPDATE workflow_registrations SET commit_sha = $1 WHERE id = $2`, [opts.commitSha, opts.id]);
2271
- } finally {
2272
- await pool.end();
2273
- }
2274
- }
2275
- /**
2276
- * Lock-entry seeding for the admin-API e2e, which uses a custom
2277
- * shape (cron schedule). Returns the inserted id.
2278
- */
2279
- async function insertWorkflowRegistrationRawDirect(databaseUrl, opts) {
2280
- const pool = createPool(databaseUrl);
2281
- try {
2282
- const idClause = opts.id ? "$7" : "gen_random_uuid()";
2283
- const extras = [];
2284
- if (opts.id) extras.push(opts.id);
2285
- const columns = [];
2286
- const placeholders = [];
2287
- if (opts.isGlobal !== void 0) {
2288
- columns.push("is_global");
2289
- placeholders.push(`$${7 + extras.length}`);
2290
- extras.push(opts.isGlobal);
2291
- }
2292
- if (opts.disabled !== void 0) {
2293
- columns.push("disabled");
2294
- placeholders.push(`$${7 + extras.length}`);
2295
- extras.push(opts.disabled);
2296
- }
2297
- if (opts.commitSha !== void 0) {
2298
- columns.push("commit_sha");
2299
- placeholders.push(`$${7 + extras.length}`);
2300
- extras.push(opts.commitSha);
2301
- }
2302
- const extraColumns = columns.length > 0 ? `, ${columns.join(", ")}` : "";
2303
- const extraPlaceholders = placeholders.length > 0 ? `, ${placeholders.join(", ")}` : "";
2304
- const sql = `INSERT INTO workflow_registrations
2305
- (routing_key, repo_identifier, workflow_name, lock_entry, trigger_types, customer_id${opts.id ? ", id" : ""}${extraColumns})
2306
- VALUES ($1, $2, $3, $4, $5, $6${opts.id ? `, ${idClause}` : ""}${extraPlaceholders})
2307
- ON CONFLICT (routing_key, repo_identifier, workflow_name) DO UPDATE SET
2308
- lock_entry = EXCLUDED.lock_entry,
2309
- trigger_types = EXCLUDED.trigger_types,
2310
- customer_id = EXCLUDED.customer_id
2311
- RETURNING id`;
2312
- return { id: (await pool.query(sql, [
2313
- opts.routingKey,
2314
- opts.repoIdentifier,
2315
- opts.workflowName,
2316
- JSON.stringify(opts.lockEntry),
2317
- opts.triggerTypes,
2318
- opts.customerId,
2319
- ...extras
2320
- ])).rows[0].id };
2321
- } finally {
2322
- await pool.end();
2323
- }
2324
- }
2325
- /**
2326
- * INSERT with a STRICT shape (no ON CONFLICT). Used by registration-schema
2327
- * e2e to prove the unique constraint rejects duplicates. Throws the raw
2328
- * DB error (caller matches /unique/i).
2329
- */
2330
- async function insertWorkflowRegistrationStrictDirect(databaseUrl, opts) {
2331
- const pool = createPool(databaseUrl);
2332
- try {
2333
- return { id: (await pool.query(`INSERT INTO workflow_registrations
2334
- (routing_key, repo_identifier, workflow_name, lock_entry, trigger_types, customer_id)
2335
- VALUES ($1, $2, $3, $4::jsonb, $5, $6)
2336
- RETURNING id`, [
2337
- opts.routingKey,
2338
- opts.repoIdentifier,
2339
- opts.workflowName,
2340
- opts.lockEntryJson ?? "{}",
2341
- opts.triggerTypes,
2342
- opts.customerId
2343
- ])).rows[0]?.id ?? null };
2344
- } finally {
2345
- await pool.end();
2346
- }
2347
- }
2348
- /**
2349
- * READ-ONLY: latest registry_versions.version, or null if the default
2350
- * row is missing. Used by registration-admin-api e2e to bracket a
2351
- * refresh call.
2352
- */
2353
- async function getRegistryVersionDirect(databaseUrl, opts = {}) {
2354
- const pool = createPool(databaseUrl);
2355
- try {
2356
- return (await pool.query(`SELECT version FROM registry_versions WHERE id = $1`, [opts.id ?? "default"])).rows[0]?.version ?? null;
2357
- } finally {
2358
- await pool.end();
2359
- }
2360
- }
2361
- /**
2362
- * UPDATE `registry_versions.version = version + 1` WHERE id (default).
2363
- * Simpler than `bumpRegistryVersionDirect` — used by global-workflow
2364
- * e2e which wants the side-effect (force index refresh) without the
2365
- * return value.
2366
- */
2367
- async function bumpRegistryVersionSimpleDirect(databaseUrl, opts = {}) {
2368
- const pool = createPool(databaseUrl);
2369
- try {
2370
- await pool.query(`UPDATE registry_versions SET version = version + 1 WHERE id = $1`, [opts.id ?? "default"]);
2371
- } finally {
2372
- await pool.end();
2373
- }
2374
- }
2375
- /**
2376
- * Seed cron_last_fired for a registration with an `-INTERVAL` offset so
2377
- * the scheduler fires on the next evaluation. Upsert via ON CONFLICT.
2378
- */
2379
- async function upsertCronLastFiredDirect(databaseUrl, opts) {
2380
- const pool = createPool(databaseUrl);
2381
- try {
2382
- await pool.query(`INSERT INTO cron_last_fired (registration_id, schedule_key, last_fired_at)
2383
- VALUES ($1, $3, NOW() - ($2)::interval)
2384
- ON CONFLICT (registration_id, schedule_key) DO UPDATE SET
2385
- last_fired_at = NOW() - ($2)::interval,
2386
- updated_at = NOW()`, [
2387
- opts.registrationId,
2388
- opts.agoInterval,
2389
- opts.scheduleKey
2390
- ]);
2391
- } finally {
2392
- await pool.end();
2393
- }
2394
- }
2395
- /**
2396
- * READ-ONLY: count cron_last_fired rows for a registration. Used by
2397
- * registration-schema e2e to assert the FK cascade deletes the row.
2398
- */
2399
- async function countCronLastFiredDirect(databaseUrl, opts) {
2400
- const pool = createPool(databaseUrl);
2401
- try {
2402
- return (await pool.query(`SELECT COUNT(*)::int AS cnt FROM cron_last_fired WHERE registration_id = $1`, [opts.registrationId])).rows[0]?.cnt ?? 0;
2403
- } finally {
2404
- await pool.end();
2405
- }
2406
- }
2407
- /**
2408
- * INSERT a cron_last_fired row with an explicit timestamp. Used by
2409
- * registration-schema e2e to set up the FK cascade test.
2410
- */
2411
- async function insertCronLastFiredNowDirect(databaseUrl, opts) {
2412
- const pool = createPool(databaseUrl);
2413
- try {
2414
- await pool.query(`INSERT INTO cron_last_fired (registration_id, schedule_key, last_fired_at) VALUES ($1, $2, NOW())`, [opts.registrationId, opts.scheduleKey]);
2415
- } finally {
2416
- await pool.end();
2417
- }
2418
- }
2419
- /**
2420
- * DELETE cron_last_fired rows for a registration. Teardown helper.
2421
- */
2422
- async function deleteCronLastFiredDirect(databaseUrl, opts) {
2423
- const pool = createPool(databaseUrl);
2424
- try {
2425
- await pool.query(`DELETE FROM cron_last_fired WHERE registration_id = $1`, [opts.registrationId]);
2426
- } finally {
2427
- await pool.end();
2428
- }
2429
- }
2430
- /**
2431
- * DELETE execution_runs by workflow_name. Teardown helper for
2432
- * manual-schedule e2e.
2433
- */
2434
- async function deleteExecutionRunsByWorkflowNameDirect(databaseUrl, opts) {
2435
- const pool = createPool(databaseUrl);
2436
- try {
2437
- return { deleted: (await pool.query(`DELETE FROM execution_runs WHERE workflow_name = $1`, [opts.workflowName])).rowCount ?? 0 };
2438
- } finally {
2439
- await pool.end();
2440
- }
2441
- }
2442
- /**
2443
- * READ-ONLY: SELECT generic_webhook_sources by routing_key.
2444
- * Used by forgejo e2e to assert the source exists with correct git_config.
2445
- */
2446
- async function getGenericWebhookSourceByRoutingKeyDirect(databaseUrl, opts) {
2447
- const pool = createPool(databaseUrl);
2448
- try {
2449
- return (await pool.query(`SELECT id, git_config, customer_id FROM generic_webhook_sources WHERE routing_key = $1`, [opts.routingKey])).rows[0] ?? null;
2450
- } finally {
2451
- await pool.end();
2452
- }
2453
- }
2454
- /**
2455
- * READ-ONLY: list active (enabled=true) generic_webhook_sources.
2456
- * Used by cluster-leader-failover e2e to prove the seeded source exists
2457
- * before a leader crash.
2458
- */
2459
- async function listActiveGenericWebhookSourcesDirect(databaseUrl) {
2460
- const pool = createPool(databaseUrl);
2461
- try {
2462
- return (await pool.query(`SELECT id, customer_id, routing_key FROM generic_webhook_sources WHERE enabled = true`)).rows;
2463
- } finally {
2464
- await pool.end();
2465
- }
2466
- }
2467
- /**
2468
- * UPDATE generic_webhook_sources.verification_config for a source by
2469
- * name + customer_id. Used by the generic-webhook-auth e2e which seeds
2470
- * sources and then writes custom auth configs.
2471
- */
2472
- async function updateGenericWebhookVerificationConfigDirect(databaseUrl, opts) {
2473
- const pool = createPool(databaseUrl);
2474
- try {
2475
- await pool.query(`UPDATE generic_webhook_sources
2476
- SET verification_config = $1
2477
- WHERE name = $2 AND customer_id = $3`, [
2478
- JSON.stringify(opts.verificationConfig),
2479
- opts.name,
2480
- opts.customerId
2481
- ]);
2482
- } finally {
2483
- await pool.end();
2484
- }
2485
- }
2486
- /**
2487
- * DELETE generic_webhook_sources by name list. Teardown for the auth
2488
- * e2e, which seeded 3 sources by name.
2489
- */
2490
- async function deleteGenericWebhookSourcesByNameDirect(databaseUrl, opts) {
2491
- const pool = createPool(databaseUrl);
2492
- try {
2493
- return { deleted: (await pool.query(`DELETE FROM generic_webhook_sources WHERE name = ANY($1::text[])`, [opts.names])).rowCount ?? 0 };
2494
- } finally {
2495
- await pool.end();
2496
- }
2497
- }
2498
- /**
2499
- * UPDATE generic_webhook_sources.deleted_at = NULL for a row by id.
2500
- * Used by the generic-webhook e2e to restore a soft-deleted source
2501
- * after the soft-delete test ran — there is no CLI-level undelete.
2502
- */
2503
- async function restoreSoftDeletedGenericWebhookSourceDirect(databaseUrl, opts) {
2504
- const pool = createPool(databaseUrl);
2505
- try {
2506
- await pool.query(`UPDATE generic_webhook_sources SET deleted_at = NULL WHERE id = $1`, [opts.id]);
2507
- } finally {
2508
- await pool.end();
2509
- }
2510
- }
2511
- async function upsertOrgSettingsGlobalWorkflowsDirect(databaseUrl, opts) {
2512
- const pool = createPool(databaseUrl);
2513
- try {
2514
- await pool.query(`INSERT INTO org_settings (
2515
- customer_id, global_workflows_enabled,
2516
- global_workflow_allowed_repos,
2517
- global_workflow_denied_repos,
2518
- global_workflow_elevated_repos
2519
- ) VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::jsonb)
2520
- ON CONFLICT (customer_id) DO UPDATE SET
2521
- global_workflows_enabled = EXCLUDED.global_workflows_enabled,
2522
- global_workflow_allowed_repos = EXCLUDED.global_workflow_allowed_repos,
2523
- global_workflow_denied_repos = EXCLUDED.global_workflow_denied_repos,
2524
- global_workflow_elevated_repos = EXCLUDED.global_workflow_elevated_repos,
2525
- updated_at = NOW()`, [
2526
- opts.customerId,
2527
- opts.globalWorkflowsEnabled,
2528
- opts.allowedRepos == null ? null : JSON.stringify(opts.allowedRepos),
2529
- opts.deniedRepos == null ? null : JSON.stringify(opts.deniedRepos),
2530
- opts.elevatedRepos == null ? null : JSON.stringify(opts.elevatedRepos)
2531
- ]);
2532
- } finally {
2533
- await pool.end();
2534
- }
2535
- }
2536
- /**
2537
- * UPDATE org_settings.global_workflow_denied_repos for a customer/org id.
2538
- * Assumes the row exists (upsertOrgSettingsGlobalWorkflowsDirect was
2539
- * called earlier in the test).
2540
- */
2541
- async function updateOrgSettingsDeniedReposDirect(databaseUrl, opts) {
2542
- const pool = createPool(databaseUrl);
2543
- try {
2544
- await pool.query(`UPDATE org_settings
2545
- SET global_workflow_denied_repos = $2::jsonb,
2546
- updated_at = NOW()
2547
- WHERE customer_id = $1`, [opts.customerId, opts.deniedRepos == null ? null : JSON.stringify(opts.deniedRepos)]);
2548
- } finally {
2549
- await pool.end();
2550
- }
2551
- }
2552
- /**
2553
- * DELETE org_settings by customer/org id. Teardown helper.
2554
- */
2555
- async function deleteOrgSettingsByCustomerIdDirect(databaseUrl, opts) {
2556
- const pool = createPool(databaseUrl);
2557
- try {
2558
- return { deleted: (await pool.query(`DELETE FROM org_settings WHERE customer_id = $1`, [opts.customerId])).rowCount ?? 0 };
2559
- } finally {
2560
- await pool.end();
2561
- }
2562
- }
2563
- async function getExecutionRunSecurityDirect(databaseUrl, opts) {
2564
- const pool = createPool(databaseUrl);
2565
- try {
2566
- const result = await pool.query(`SELECT run_id, trust_tier, lock_file_source, contributor_username, status
2567
- FROM execution_runs WHERE run_id = $1`, [opts.runId]);
2568
- if (result.rows.length === 0) throw new Error(`execution_runs: row not found (run_id=${opts.runId})`);
2569
- return result.rows[0];
2570
- } finally {
2571
- await pool.end();
2572
- }
2573
- }
2574
- async function getHeldRunByIdDirect(databaseUrl, opts) {
2575
- const pool = createPool(databaseUrl);
2576
- try {
2577
- return (await pool.query(`SELECT id, run_id, hold_type, queue_type, status, reason,
2578
- expires_at, approved_by, resolved_at
2579
- FROM held_runs WHERE id = $1`, [opts.id])).rows[0] ?? null;
2580
- } finally {
2581
- await pool.end();
2582
- }
2583
- }
2584
- /**
2585
- * READ-ONLY: list the recorded approver decisions for a held run, newest
2586
- * first. Approver attribution lives in `held_run_approvals` (one row per
2587
- * decision), not on the `held_runs` row — used by ci-security e2e to prove
2588
- * an approval was stamped with the approving user's sub.
2589
- */
2590
- async function listHeldRunApprovalsDirect(databaseUrl, opts) {
2591
- const pool = createPool(databaseUrl);
2592
- try {
2593
- return (await pool.query(`SELECT id, held_run_id, approver_user_id, decision, created_at
2594
- FROM held_run_approvals WHERE held_run_id = $1
2595
- ORDER BY created_at DESC`, [opts.heldRunId])).rows;
2596
- } finally {
2597
- await pool.end();
2598
- }
2599
- }
2600
- /**
2601
- * READ-ONLY: count held_runs rows matching run_id + queue_type.
2602
- * Used by ci-security e2e to prove no security hold exists for a
2603
- * trusted contributor PR.
2604
- */
2605
- async function countHeldRunsByRunIdDirect(databaseUrl, opts) {
2606
- const pool = createPool(databaseUrl);
2607
- try {
2608
- return (opts.queueType ? await pool.query(`SELECT COUNT(*)::int AS cnt FROM held_runs WHERE run_id = $1 AND queue_type = $2`, [opts.runId, opts.queueType]) : await pool.query(`SELECT COUNT(*)::int AS cnt FROM held_runs WHERE run_id = $1`, [opts.runId])).rows[0]?.cnt ?? 0;
2609
- } finally {
2610
- await pool.end();
2611
- }
2612
- }
2613
- /**
2614
- * Wait for Platform-side `execution_runs.status = <status>` where
2615
- * `created_at > since`. Returns the final status + failure_reason or
2616
- * null if the timeout elapsed. Used by webhook-pipeline (failed) and
2617
- * orchestrator-never-reconnects (timed_out_stale).
2618
- */
2619
- async function waitForPlatformExecutionRunStatusDirect(databaseUrl, opts) {
2620
- const timeoutMs = opts.timeoutMs ?? 3e4;
2621
- const intervalMs = opts.intervalMs ?? 2e3;
2622
- const deadline = Date.now() + timeoutMs;
2623
- const pool = createPool(databaseUrl);
2624
- try {
2625
- while (Date.now() < deadline) {
2626
- const result = await pool.query(`SELECT status, failure_reason FROM execution_runs
2627
- WHERE created_at > $1 AND status = $2
2628
- ORDER BY created_at DESC LIMIT 1`, [opts.since, opts.status]);
2629
- if (result.rows.length > 0) return result.rows[0];
2630
- await new Promise((r) => setTimeout(r, intervalMs));
2631
- }
2632
- return null;
2633
- } finally {
2634
- await pool.end();
2635
- }
2636
- }
2637
- /**
2638
- * Wait for Platform `event_log` to show at least `minDistinctRouted`
2639
- * distinct `routed_to` values since a given timestamp. Used by
2640
- * cluster-round-robin to prove at least 2 orchestrators received
2641
- * deliveries. Returns the observed count (0 if timed out).
2642
- */
2643
- async function waitForPlatformEventLogDistinctRoutedDirect(databaseUrl, opts) {
2644
- const timeoutMs = opts.timeoutMs ?? 6e4;
2645
- const intervalMs = opts.intervalMs ?? 3e3;
2646
- const deadline = Date.now() + timeoutMs;
2647
- const pool = createPool(databaseUrl);
2648
- try {
2649
- let distinct = 0;
2650
- while (Date.now() < deadline) {
2651
- distinct = (await pool.query(`SELECT COUNT(DISTINCT routed_to)::int AS cnt FROM event_log WHERE received_at > $1`, [opts.since])).rows[0]?.cnt ?? 0;
2652
- if (distinct >= opts.minDistinctRouted) return { distinctRouted: distinct };
2653
- await new Promise((r) => setTimeout(r, intervalMs));
2654
- }
2655
- return { distinctRouted: distinct };
2656
- } finally {
2657
- await pool.end();
2658
- }
2659
- }
2660
- async function waitForEventLogRowByDeliveryIdDirect(databaseUrl, opts) {
2661
- const timeoutMs = opts.timeoutMs ?? 1e4;
2662
- const intervalMs = opts.intervalMs ?? 200;
2663
- const deadline = Date.now() + timeoutMs;
2664
- const pool = createPool(databaseUrl);
2665
- try {
2666
- while (Date.now() < deadline) {
2667
- const res = await pool.query(`SELECT org_id, delivery_id, status, source, event, provider, payload_hash,
2668
- payload_omitted, payload_key, payload_size_bytes, matched_count, run_id
2669
- FROM event_log WHERE delivery_id = $1`, [opts.deliveryId]);
2670
- if (res.rowCount && res.rowCount > 0) return res.rows[0];
2671
- await new Promise((r) => setTimeout(r, intervalMs));
2672
- }
2673
- return null;
2674
- } finally {
2675
- await pool.end();
2676
- }
2677
- }
2678
- /**
2679
- * Resolve a Platform `webhook_sources.routing_key` for an org.
2680
- *
2681
- * - With `routingKeyLikePrefix` only: returns the newest match. Note that
2682
- * this picks whichever generic source was registered most recently — if
2683
- * tests have created additional generic sources (e.g. universal-git-forgejo
2684
- * creating `stg-universal-git-forgejo`), the newest may NOT be the
2685
- * `stg-generic` default seeded by `pnpm deploy:stg`.
2686
- * - With `orchDbUrl` + `nameInOrchDb`: looks up the source by name in the
2687
- * orchestrator's `generic_webhook_sources` table, then verifies the
2688
- * resulting routing key is registered in Platform's `webhook_sources`.
2689
- * This is the disambiguating path Bucket-B tests should use when other
2690
- * generic sources may exist alongside the default.
2691
- */
2692
- async function resolvePlatformWebhookSourceRoutingKeyDirect(platformDbUrl, opts) {
2693
- if (opts.orchDbUrl && opts.nameInOrchDb) {
2694
- const orchPool = createPool(opts.orchDbUrl);
2695
- let candidateRoutingKey = null;
2696
- try {
2697
- const id = (await orchPool.query(`SELECT id FROM generic_webhook_sources
2698
- WHERE customer_id = $1 AND name = $2 AND deleted_at IS NULL
2699
- LIMIT 1`, [opts.orgId, opts.nameInOrchDb])).rows[0]?.id;
2700
- if (!id) return null;
2701
- candidateRoutingKey = `generic:${opts.orgId}:${id}`;
2702
- } finally {
2703
- await orchPool.end();
2704
- }
2705
- const platformPool = createPool(platformDbUrl);
2706
- try {
2707
- return (await platformPool.query(`SELECT routing_key FROM webhook_sources
2708
- WHERE org_id = $1 AND routing_key = $2 LIMIT 1`, [opts.orgId, candidateRoutingKey])).rows[0]?.routing_key ?? null;
2709
- } finally {
2710
- await platformPool.end();
2711
- }
2712
- }
2713
- const pool = createPool(platformDbUrl);
2714
- try {
2715
- return (await pool.query(`SELECT routing_key FROM webhook_sources
2716
- WHERE org_id = $1 AND routing_key LIKE $2
2717
- ORDER BY registered_at DESC LIMIT 1`, [opts.orgId, `${opts.routingKeyLikePrefix}%`])).rows[0]?.routing_key ?? null;
2718
- } finally {
2719
- await pool.end();
2720
- }
2721
- }
2722
- /**
2723
- * Idempotent seeding of an E2E regular user + org membership + owner
2724
- * role on the Platform DB. Used by stg-ha-smoke before seeding a user
2725
- * API key. Requires the org to already have an owner role.
2726
- */
2727
- async function ensureOrgOwnerMemberDirect(platformDbUrl, opts) {
2728
- const pool = createPool(platformDbUrl);
2729
- try {
2730
- const ownerRole = await pool.query(`SELECT id FROM roles WHERE org_id = $1 AND is_owner = true LIMIT 1`, [opts.orgId]);
2731
- if (ownerRole.rows.length === 0) throw new Error(`ensureOrgOwnerMemberDirect: no owner role found for org ${opts.orgId}`);
2732
- const ownerRoleId = ownerRole.rows[0].id;
2733
- await pool.query(`INSERT INTO users (idp_sub, email, display_name)
2734
- VALUES ($1, $2, $3)
2735
- ON CONFLICT (idp_sub) DO NOTHING`, [
2736
- opts.idpSub,
2737
- opts.email,
2738
- opts.displayName
2739
- ]);
2740
- await pool.query(`INSERT INTO org_members (org_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [opts.orgId, opts.idpSub]);
2741
- await pool.query(`INSERT INTO role_assignments (org_id, user_id, role_id, assigned_by)
2742
- VALUES ($1, $2, $3, $2)
2743
- ON CONFLICT (org_id, user_id, role_id) DO NOTHING`, [
2744
- opts.orgId,
2745
- opts.idpSub,
2746
- ownerRoleId
2747
- ]);
2748
- return { ownerRoleId };
2749
- } finally {
2750
- await pool.end();
2751
- }
2752
- }
2753
- /**
2754
- * Cleanup peer_credentials by instance_id LIKE pattern. Used by the
2755
- * cluster-peer-credentials e2e before/after each test to wipe its
2756
- * own seeded rows without touching real cluster credentials.
2757
- */
2758
- async function deletePeerCredentialsByInstanceIdLikeDirect(databaseUrl, opts) {
2759
- const pool = createPool(databaseUrl);
2760
- try {
2761
- return { deleted: (await pool.query(`DELETE FROM peer_credentials WHERE instance_id LIKE $1`, [opts.pattern])).rowCount ?? 0 };
2762
- } finally {
2763
- await pool.end();
2764
- }
2765
- }
2766
- /**
2767
- * Insert a peer_credentials row with an explicit expires_at. Used by
2768
- * the "expired credential is not returned" e2e — the store's save()
2769
- * always computes a future expiry, so tests that need a pre-expired
2770
- * row must bypass it.
2771
- */
2772
- async function insertPeerCredentialExpiredDirect(databaseUrl, opts) {
2773
- const pool = createPool(databaseUrl);
2774
- try {
2775
- await pool.query(`INSERT INTO peer_credentials (instance_id, credential_hash, role, routing_keys, expires_at)
2776
- VALUES ($1, $2, $3, $4::text[], $5)`, [
2777
- opts.instanceId,
2778
- opts.credentialHash,
2779
- opts.role,
2780
- Array.from(opts.routingKeys),
2781
- opts.expiresAt
2782
- ]);
2783
- } finally {
2784
- await pool.end();
2785
- }
2786
- }
2787
- /**
2788
- * READ-ONLY: `revoked_at` for a peer_credentials row by hash. Used
2789
- * by the "save revokes old credential" e2e to assert revocation.
2790
- * Returns null when the row is missing entirely (distinct from
2791
- * "present but not revoked").
2792
- */
2793
- async function getPeerCredentialRevokedAtDirect(databaseUrl, opts) {
2794
- const pool = createPool(databaseUrl);
2795
- try {
2796
- const result = await pool.query(`SELECT revoked_at FROM peer_credentials WHERE credential_hash = $1`, [opts.credentialHash]);
2797
- if (result.rows.length === 0) return {
2798
- present: false,
2799
- revokedAt: null
2800
- };
2801
- return {
2802
- present: true,
2803
- revokedAt: result.rows[0].revoked_at
2804
- };
2805
- } finally {
2806
- await pool.end();
2807
- }
2808
- }
2809
- /**
2810
- * READ-ONLY: list active peer_credentials ids EXCLUDING a
2811
- * `instance_id LIKE` pattern. Used by revokeAll e2e to snapshot
2812
- * real cluster credentials it will restore later.
2813
- */
2814
- async function listActivePeerCredentialsExcludingDirect(databaseUrl, opts) {
2815
- const pool = createPool(databaseUrl);
2816
- try {
2817
- return { ids: (await pool.query(`SELECT id FROM peer_credentials
2818
- WHERE revoked_at IS NULL AND instance_id NOT LIKE $1`, [opts.excludeInstanceIdPattern])).rows.map((r) => r.id) };
2819
- } finally {
2820
- await pool.end();
2821
- }
2822
- }
2823
- /**
2824
- * Clear revoked_at on a set of peer_credentials ids. Used by revokeAll
2825
- * e2e to restore real cluster credentials after the destructive test.
2826
- */
2827
- async function clearPeerCredentialsRevokedAtByIdsDirect(databaseUrl, opts) {
2828
- if (opts.ids.length === 0) return { updated: 0 };
2829
- const pool = createPool(databaseUrl);
2830
- try {
2831
- return { updated: (await pool.query(`UPDATE peer_credentials SET revoked_at = NULL WHERE id = ANY($1::uuid[])`, [opts.ids])).rowCount ?? 0 };
2832
- } finally {
2833
- await pool.end();
2834
- }
2835
- }
2836
- /**
2837
- * READ-ONLY: count currently-active (non-revoked, non-expired)
2838
- * peer_credentials rows for a given instance_id. Used by the
2839
- * concurrent-save e2e to assert 1 <= count <= 2.
2840
- */
2841
- async function countActivePeerCredentialsByInstanceDirect(databaseUrl, opts) {
2842
- const pool = createPool(databaseUrl);
2843
- try {
2844
- return (await pool.query(`SELECT count(*)::int AS cnt FROM peer_credentials
2845
- WHERE instance_id = $1 AND revoked_at IS NULL AND expires_at > now()`, [opts.instanceId])).rows[0]?.cnt ?? 0;
2846
- } finally {
2847
- await pool.end();
2848
- }
2849
- }
2850
- /**
2851
- * Terminate every idle backend of the connecting user except our own
2852
- * connection. Mirrors what a Postgres leader demotion does to idle pooled
2853
- * connections — used by resilience tests to verify the pg pool error
2854
- * handlers absorb the termination without a process restart.
2855
- *
2856
- * Returns the number of backends terminated.
2857
- */
2858
- async function terminateIdleDbBackendsDirect(databaseUrl) {
2859
- const pool = createPool(databaseUrl);
2860
- try {
2861
- return (await pool.query(`SELECT pg_terminate_backend(pid)
2862
- FROM pg_stat_activity
2863
- WHERE pid <> pg_backend_pid()
2864
- AND usename = current_user
2865
- AND state = 'idle'`)).rowCount ?? 0;
2866
- } finally {
2867
- await pool.end();
2868
- }
2869
- }
2870
1127
  //#endregion
2871
- export { CI_SECURITY_OTHER_REPO, MIGRATION_HASH_TABLE, PROVIDER_HASH_KEY, REGISTERABLE_TRIGGER_TYPES, apiKeyExistsDirect, bumpRegistryVersionDirect, bumpRegistryVersionSimpleDirect, cleanupExecutionRowsDirect, clearDispatchQueueDirect, clearPeerCredentialsRevokedAtByIdsDirect, computeMigrationsHash, countActivePeerCredentialsByInstanceDirect, countCronLastFiredDirect, countHeldRunsByRunIdDirect, countWebhookSourcesByConnectionIdDirect, createContextTemplateDirect, createDbRole, createJoinTokenDirect, createReadOnlyDbUser, deleteContextDirect, deleteCronLastFiredDirect, deleteCrossRepoTrustDirect, deleteExecutionRunsByWorkflowNameDirect, deleteGenericWebhookSourcesByNameDirect, deleteJoinTokensByCreatedByDirect, deleteKiciEventsDirect, deleteOrgSettingsByCustomerIdDirect, deletePeerCredentialsByInstanceIdLikeDirect, deleteWorkflowRegistrationsDirect, describeTableColumnsDirect, dropAndCreateDatabase, dropDatabaseDirect, emitKiciEventDirect, ensureDatabase, ensureOrgOwnerMemberDirect, findAnyUserApiKeyIdDirect, getExecutionRunSecurityDirect, getGenericWebhookSourceByRoutingKeyDirect, getHeldRunByIdDirect, getPeerCredentialRevokedAtDirect, getRegistryVersionDirect, getWebhookSourceByRoutingKeyDirect, getWorkflowRegistrationByIdDirect, insertCronLastFiredNowDirect, insertCrossRepoTrustStrictDirect, insertKiciEventAtDirect, insertKiciEventRawDirect, insertPeerCredentialExpiredDirect, insertWorkflowRegistrationRawDirect, insertWorkflowRegistrationStrictDirect, isSchemaCurrent, isSchemaCurrentFromFilesDirect, latestExecutionRunByStatusDirect, listActiveGenericWebhookSourcesDirect, listActivePeerCredentialsExcludingDirect, listCheckRunTrackingDirect, listContextsDirect, listCrossRepoTrustBySourceRoutingKeyDirect, listExecutionJobsDirect, listExecutionRunsDirect, listHeldRunApprovalsDirect, listKiciEventsDirect, listQueueDirect, listRegistrationsByRoutingKeyDirect, listRegistrationsDirect, maskDatabaseUrl, paginateUnprocessedEventsKeysetDirect, parseDatabaseUrl, platformConnectionExistsDirect, pollKiciEventsDirect, prunePeerCredentialsDirect, purgeContextsDirect, purgeScopedSecretsDirect, purgeSecretBackendsDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, readStoredMigrationContentHash, registerWorkflowManualDirect, resetRaftStateDirect, resolvePlatformWebhookSourceRoutingKeyDirect, restoreSoftDeletedGenericWebhookSourceDirect, seedApiKeyInlineDirect, seedCiSecurityFixturesDirect, seedContextBindingDirect, seedContextDirect, seedCrossRepoTrustDirect, seedGenericWebhookSourceDirect, seedSourcePrivateKeyDirect, seedSyntheticGithubSourceDirect, seedUniversalGitSourceDirect, seedWebhookSecretDirect, setContextPolicyDirect, setContextSecretDirect, showContextDirect, showExecutionRunDirect, showKiciEventDirect, showQueueEntryDirect, showRegistrationDirect, storeMigrationContentHash, storeMigrationContentHashInTableDirect, tableExistsDirect, terminateIdleDbBackendsDirect, updateGenericWebhookVerificationConfigDirect, updateOrgSettingsDeniedReposDirect, updateSourceRoutingKeyDirect, updateWorkflowRegistrationCommitShaDirect, upsertCronLastFiredDirect, upsertOrgSettingsGlobalWorkflowsDirect, verifyKiciEventNotifyDirect, waitForEventLogRowByDeliveryIdDirect, waitForExecutionRunReachesStatusSinceDirect, waitForLatestExecutionJobStatusDirect, waitForPlatformEventLogDistinctRoutedDirect, waitForPlatformExecutionRunStatusDirect, waitForPlatformRegistrationsDirect, waitForPostgresDirect, waitForRegistrationsByRoutingKeyDirect, waitForRegistrationsUpdatedAtAdvanceDirect, waitForRunCompletionDirect };
1128
+ export { MIGRATION_HASH_TABLE, PROVIDER_HASH_KEY, REGISTERABLE_TRIGGER_TYPES, clearDispatchQueueDirect, computeMigrationsHash, createContextTemplateDirect, createDbRole, createReadOnlyDbUser, deleteContextDirect, dropAndCreateDatabase, emitKiciEventDirect, ensureDatabase, isSchemaCurrent, listCheckRunTrackingDirect, listContextsDirect, listExecutionRunsDirect, listQueueDirect, listRegistrationsDirect, maskDatabaseUrl, parseDatabaseUrl, prunePeerCredentialsDirect, purgeContextsDirect, purgeScopedSecretsDirect, purgeSecretBackendsDirect, purgeStaleExecutionDirect, purgeStaleSourcesDirect, readStoredMigrationContentHash, registerWorkflowManualDirect, resetRaftStateDirect, seedContextBindingDirect, seedContextDirect, setContextPolicyDirect, setContextSecretDirect, showContextDirect, showExecutionRunDirect, showQueueEntryDirect, showRegistrationDirect, storeMigrationContentHash };
2872
1129
 
2873
1130
  //# sourceMappingURL=db-admin.js.map