gencow 0.1.298 → 0.2.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/bin/gencow.mjs +0 -6
- package/core/index.js +261 -1447
- package/core/package.json +1 -1
- package/dashboard/assets/{index-BnBn8uo4.js → index-DYqUzCmS.js} +3 -3
- package/dashboard/assets/index-OH2xW1ZG.css +2 -0
- package/dashboard/index.html +2 -2
- package/docs/packaging.md +14 -4
- package/lib/cli-artifact-guard.mjs +53 -3
- package/lib/cli-command-runner.d.mts +11 -0
- package/lib/cli-dev-runtime.mjs +1 -0
- package/lib/cli-project-runtime.mjs +26 -14
- package/lib/codegen-command.mjs +16 -0
- package/lib/coding-guardrails.mjs +2 -0
- package/lib/component-readme.mjs +4 -4
- package/lib/dashboard-artifact.mjs +65 -0
- package/lib/dashboard-assets.mjs +20 -0
- package/lib/db-command.mjs +121 -80
- package/lib/db-migration-command-steps.mjs +19 -16
- package/lib/db-push-command.mjs +1 -1
- package/lib/deploy-codegen-preflight.mjs +1 -0
- package/lib/deploy-cron-manifest-diagnostic.mjs +93 -0
- package/lib/deploy-failure-diagnostic.mjs +4 -43
- package/lib/deploy-route-target-rejection-diagnostic.mjs +43 -0
- package/lib/dev-cloud-command.mjs +1 -1
- package/lib/dev-local-command.mjs +19 -56
- package/lib/document-local-converter.mjs +11 -0
- package/lib/jobs-command.mjs +33 -1
- package/lib/local-dashboard-plan.mjs +60 -0
- package/lib/local-database-commands.mjs +127 -0
- package/lib/local-development-migrations.mjs +157 -0
- package/lib/local-drizzle-database.config.mjs +10 -0
- package/lib/local-runtime-features.mjs +12 -0
- package/lib/rag-selection.mjs +7 -0
- package/lib/readme-codegen.mjs +2 -2
- package/lib/runtime-local-worker.mjs +116 -0
- package/lib/runtime-mode.mjs +3 -0
- package/lib/standalone-codegen-adapter.mjs +91 -0
- package/lib/ts-codegen-import-extension.mjs +228 -19
- package/package.json +16 -9
- package/runtime/config.mjs +218 -2
- package/runtime/dependency-lock.mjs +5 -1
- package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
- package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
- package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
- package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
- package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
- package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
- package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
- package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
- package/runtime/engine/chunk-5575APCJ.mjs +215 -0
- package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
- package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
- package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
- package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
- package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
- package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
- package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
- package/runtime/engine/chunk-6W653LXI.mjs +13 -0
- package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
- package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
- package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
- package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
- package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
- package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
- package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
- package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
- package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
- package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
- package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
- package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
- package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
- package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
- package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
- package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
- package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
- package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
- package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
- package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
- package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
- package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
- package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
- package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
- package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
- package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
- package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
- package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
- package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
- package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
- package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
- package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
- package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
- package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
- package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
- package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
- package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
- package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
- package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
- package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
- package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
- package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
- package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
- package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
- package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
- package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
- package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
- package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
- package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
- package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
- package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
- package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
- package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
- package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
- package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
- package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
- package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
- package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
- package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
- package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
- package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
- package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
- package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
- package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
- package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
- package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
- package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
- package/runtime/engine/chunk-YRHM272W.mjs +528 -0
- package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
- package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
- package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
- package/runtime/engine/composition.mjs +325 -0
- package/runtime/engine/document-local.mjs +504 -0
- package/runtime/engine/graph.json +4134 -0
- package/runtime/engine/index.mjs +265 -0
- package/runtime/engine/local-postgres-support.mjs +69 -0
- package/runtime/engine/local.mjs +3275 -0
- package/runtime/engine/pglite-directory-lock.mjs +8 -0
- package/runtime/engine/rag.mjs +11 -0
- package/runtime/engine/search.mjs +18 -0
- package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
- package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
- package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
- package/runtime/framework-migrations/manifest.json +56 -0
- package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
- package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
- package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
- package/runtime/runtime-metadata.json +27 -0
- package/runtime/tooling.mjs +10549 -10543
- package/scripts/bundle-runtime-config.mjs +23 -0
- package/scripts/bundle-runtime.mjs +100 -0
- package/scripts/bundle-runtime.test.mjs +33 -0
- package/scripts/bundle-shared.mjs +3 -0
- package/scripts/copy-dashboard.mjs +16 -0
- package/scripts/pre-publish-check.mjs +23 -11
- package/templateFeature/ai/ai-embedding-result.ts +82 -0
- package/templateFeature/ai/ai-facade.ts +24 -7
- package/templateFeature/ai/ai-provider.ts +17 -1
- package/templateFeature/ai/ai.ts +1 -0
- package/templateFeature/ai/manifest.json +4 -3
- package/templateFeature/reranker/manifest.json +1 -1
- package/templateFeature/reranker/reranker.ts +4 -3
- package/templateFeature/sso/sso-auth-callback.tsx +37 -5
- package/templateFeature/tools/manifest.json +2 -1
- package/templateFeature/tools/tools.ts +3 -3
- package/dashboard/assets/index-C6-BpKKR.css +0 -2
- package/runtime/server.mjs +0 -14320
- package/scripts/bundle-server.mjs +0 -223
- package/server/config.js +0 -1
- package/server/index.js +0 -1
- package/server/package.json +0 -6
package/core/index.js
CHANGED
|
@@ -654,11 +654,11 @@ function resolveRealtimeQueryScopeHash(params) {
|
|
|
654
654
|
const objectResult = params.result && typeof params.result === "object" && !Array.isArray(params.result) ? params.result : null;
|
|
655
655
|
const resultScope = objectResult && "scope" in objectResult ? objectResult.scope : void 0;
|
|
656
656
|
const def = getRealtimeSubscriptionDef(params.query);
|
|
657
|
-
const
|
|
657
|
+
const scope2 = resultScope !== void 0 ? resultScope : def?.scope?.(params.args);
|
|
658
658
|
return buildRealtimeQueryScopeHash({
|
|
659
659
|
query: params.query,
|
|
660
660
|
subscriptionKey: params.subscriptionKey,
|
|
661
|
-
scope
|
|
661
|
+
scope: scope2
|
|
662
662
|
});
|
|
663
663
|
}
|
|
664
664
|
function resetRealtimeSubscriptionRegistryForTests() {
|
|
@@ -2123,17 +2123,17 @@ var JobAdmissionError = class extends Error {
|
|
|
2123
2123
|
status;
|
|
2124
2124
|
retryAfterMs;
|
|
2125
2125
|
details;
|
|
2126
|
-
constructor(
|
|
2126
|
+
constructor(code2, message, options = {}) {
|
|
2127
2127
|
super(message);
|
|
2128
2128
|
this.name = "JobAdmissionError";
|
|
2129
|
-
this.code =
|
|
2130
|
-
this.status = options.status ?? getJobAdmissionStatus(
|
|
2129
|
+
this.code = code2;
|
|
2130
|
+
this.status = options.status ?? getJobAdmissionStatus(code2);
|
|
2131
2131
|
this.retryAfterMs = options.retryAfterMs;
|
|
2132
2132
|
this.details = options.details;
|
|
2133
2133
|
}
|
|
2134
2134
|
};
|
|
2135
|
-
function getJobAdmissionStatus(
|
|
2136
|
-
switch (
|
|
2135
|
+
function getJobAdmissionStatus(code2) {
|
|
2136
|
+
switch (code2) {
|
|
2137
2137
|
case "job_payload_too_large":
|
|
2138
2138
|
return 413;
|
|
2139
2139
|
case "job_min_delay_violation":
|
|
@@ -2194,449 +2194,76 @@ function getMsUntilNextMinute(date = /* @__PURE__ */ new Date()) {
|
|
|
2194
2194
|
next.setUTCMinutes(next.getUTCMinutes() + 1);
|
|
2195
2195
|
return Math.max(1e3, next.getTime() - date.getTime());
|
|
2196
2196
|
}
|
|
2197
|
-
function isJobAdmissionKillSwitchActive(env,
|
|
2197
|
+
function isJobAdmissionKillSwitchActive(env, scope2) {
|
|
2198
2198
|
const raw = env.GENCOW_JOB_ADMISSION_KILL_SWITCH ?? env.GENCOW_JOB_KILL_SWITCH ?? env.GENCOW_PLATFORM_JOB_KILL_SWITCH;
|
|
2199
2199
|
if (!raw) return false;
|
|
2200
2200
|
const normalized = raw.split(",").map((item) => item.trim().toLowerCase()).filter(Boolean);
|
|
2201
2201
|
if (normalized.length === 0) return false;
|
|
2202
2202
|
if (normalized.some((item) => item === "1" || item === "true" || item === "all")) return true;
|
|
2203
|
-
const wanted =
|
|
2203
|
+
const wanted = scope2.toLowerCase();
|
|
2204
2204
|
return normalized.some((item) => wanted === item || wanted.startsWith(`${item}:`));
|
|
2205
2205
|
}
|
|
2206
2206
|
|
|
2207
|
-
// ../core/src/workflow.ts
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
}
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
"
|
|
2224
|
-
"
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
"max_retries",
|
|
2232
|
-
"max_attempts",
|
|
2233
|
-
"command_protocol",
|
|
2234
|
-
// tryInsertWorkflowV2Run writes it on every start, so the capability must prove it exists.
|
|
2235
|
-
"idempotency_key"
|
|
2236
|
-
];
|
|
2237
|
-
const outboxColumns = ["id", "run_id", "kind", "available_at", "status"];
|
|
2238
|
-
const runColumnList = sql.join(
|
|
2239
|
-
runColumns.map((column) => sql`${column}`),
|
|
2240
|
-
sql`, `
|
|
2241
|
-
);
|
|
2242
|
-
const outboxColumnList = sql.join(
|
|
2243
|
-
outboxColumns.map((column) => sql`${column}`),
|
|
2244
|
-
sql`, `
|
|
2245
|
-
);
|
|
2246
|
-
const result = await db.execute(sql`
|
|
2247
|
-
SELECT
|
|
2248
|
-
(
|
|
2249
|
-
SELECT COUNT(*)::int
|
|
2250
|
-
FROM information_schema.columns
|
|
2251
|
-
WHERE table_schema = 'public'
|
|
2252
|
-
AND table_name = '_gencow_workflow_runs_v2'
|
|
2253
|
-
AND column_name IN (${runColumnList})
|
|
2254
|
-
) AS run_column_count,
|
|
2255
|
-
(
|
|
2256
|
-
SELECT COUNT(*)::int
|
|
2257
|
-
FROM information_schema.columns
|
|
2258
|
-
WHERE table_schema = 'public'
|
|
2259
|
-
AND table_name = '_gencow_workflow_outbox_v2'
|
|
2260
|
-
AND column_name IN (${outboxColumnList})
|
|
2261
|
-
) AS outbox_column_count
|
|
2262
|
-
`);
|
|
2263
|
-
const row = rows(result)[0];
|
|
2264
|
-
return numberFrom(row?.run_column_count) === runColumns.length && numberFrom(row?.outbox_column_count) === outboxColumns.length;
|
|
2265
|
-
}
|
|
2266
|
-
|
|
2267
|
-
// ../core/src/workflow-admission.ts
|
|
2268
|
-
import { sql as sql2 } from "drizzle-orm";
|
|
2269
|
-
var DEFAULT_WORKFLOW_PENDING_PER_APP = 1e3;
|
|
2270
|
-
var DEFAULT_WORKFLOW_PARKED_PER_APP = 1e4;
|
|
2271
|
-
var DEFAULT_WORKFLOW_RUNNING_PER_APP = 50;
|
|
2272
|
-
var DEFAULT_WORKFLOW_PENDING_PER_NAME = 300;
|
|
2273
|
-
var DEFAULT_WORKFLOW_STARTS_PER_MINUTE_PER_APP = 120;
|
|
2274
|
-
var DEFAULT_WORKFLOW_PAYLOAD_MAX_BYTES = 64 * 1024;
|
|
2275
|
-
var WORKFLOW_ADMISSION_ENV_KEYS = [
|
|
2276
|
-
"GENCOW_JOB_ADMISSION_ENABLED",
|
|
2277
|
-
"GENCOW_JOB_ADMISSION_KILL_SWITCH",
|
|
2278
|
-
"GENCOW_JOB_KILL_SWITCH",
|
|
2279
|
-
"GENCOW_PLATFORM_JOB_KILL_SWITCH",
|
|
2280
|
-
"GENCOW_WORKFLOW_PENDING_PER_APP",
|
|
2281
|
-
"GENCOW_WORKFLOW_PARKED_PER_APP",
|
|
2282
|
-
"GENCOW_WORKFLOW_RUNNING_PER_APP",
|
|
2283
|
-
"GENCOW_WORKFLOW_PENDING_PER_NAME",
|
|
2284
|
-
"GENCOW_WORKFLOW_STARTS_PER_MINUTE_PER_APP",
|
|
2285
|
-
"GENCOW_WORKFLOW_STARTS_PER_MINUTE_PER_NAME",
|
|
2286
|
-
"GENCOW_WORKFLOW_PAYLOAD_MAX_BYTES",
|
|
2287
|
-
"GENCOW_JOB_PENDING_PER_APP",
|
|
2288
|
-
"GENCOW_JOB_CREATES_PER_MINUTE_PER_APP",
|
|
2289
|
-
"GENCOW_JOB_PAYLOAD_MAX_BYTES"
|
|
2290
|
-
];
|
|
2291
|
-
function rows2(result) {
|
|
2292
|
-
if (Array.isArray(result)) return result;
|
|
2293
|
-
if (result && typeof result === "object" && Array.isArray(result.rows)) {
|
|
2294
|
-
return result.rows;
|
|
2295
|
-
}
|
|
2296
|
-
return [];
|
|
2297
|
-
}
|
|
2298
|
-
function numberFrom2(value) {
|
|
2299
|
-
const parsed = Number(value ?? 0);
|
|
2300
|
-
return Number.isFinite(parsed) ? parsed : 0;
|
|
2301
|
-
}
|
|
2302
|
-
function isMissingAdmissionSchemaError(error) {
|
|
2303
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
2304
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
2305
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
2306
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2307
|
-
return code === "42P01" || causeCode === "42P01" || message.includes('relation "_gencow_job_admission_buckets" does not exist') || message.includes("relation _gencow_job_admission_buckets does not exist");
|
|
2308
|
-
}
|
|
2309
|
-
function isMissingWorkflowV2SchemaError(error) {
|
|
2310
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
2311
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
2312
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
2313
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2314
|
-
return code === "42P01" || code === "42703" || causeCode === "42P01" || causeCode === "42703" || message.includes('relation "_gencow_workflow_runs_v2" does not exist') || message.includes("relation _gencow_workflow_runs_v2 does not exist");
|
|
2315
|
-
}
|
|
2316
|
-
function isWorkflowAdmissionEnabled(env) {
|
|
2317
|
-
if ((env.GENCOW_JOB_ADMISSION_ENABLED ?? "").trim().toLowerCase() === "false") return false;
|
|
2318
|
-
if (env.GENCOW_APP_NAME) return true;
|
|
2319
|
-
return WORKFLOW_ADMISSION_ENV_KEYS.some((key) => env[key] != null && env[key] !== "");
|
|
2320
|
-
}
|
|
2321
|
-
function resolveWorkflowAdmissionPolicy(env) {
|
|
2322
|
-
return {
|
|
2323
|
-
pendingPerApp: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_PENDING_PER_APP") ?? readPositiveIntegerEnv(env, "GENCOW_JOB_PENDING_PER_APP") ?? DEFAULT_WORKFLOW_PENDING_PER_APP,
|
|
2324
|
-
parkedPerApp: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_PARKED_PER_APP") ?? DEFAULT_WORKFLOW_PARKED_PER_APP,
|
|
2325
|
-
runningPerApp: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_RUNNING_PER_APP") ?? DEFAULT_WORKFLOW_RUNNING_PER_APP,
|
|
2326
|
-
pendingPerName: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_PENDING_PER_NAME") ?? DEFAULT_WORKFLOW_PENDING_PER_NAME,
|
|
2327
|
-
startsPerMinutePerApp: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_STARTS_PER_MINUTE_PER_APP") ?? readPositiveIntegerEnv(env, "GENCOW_JOB_CREATES_PER_MINUTE_PER_APP") ?? DEFAULT_WORKFLOW_STARTS_PER_MINUTE_PER_APP,
|
|
2328
|
-
startsPerMinutePerName: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_STARTS_PER_MINUTE_PER_NAME") ?? readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_STARTS_PER_MINUTE_PER_APP") ?? readPositiveIntegerEnv(env, "GENCOW_JOB_CREATES_PER_MINUTE_PER_APP") ?? DEFAULT_WORKFLOW_STARTS_PER_MINUTE_PER_APP,
|
|
2329
|
-
payloadMaxBytes: readPositiveIntegerEnv(env, "GENCOW_WORKFLOW_PAYLOAD_MAX_BYTES") ?? readPositiveIntegerEnv(env, "GENCOW_JOB_PAYLOAD_MAX_BYTES") ?? DEFAULT_WORKFLOW_PAYLOAD_MAX_BYTES
|
|
2330
|
-
};
|
|
2331
|
-
}
|
|
2332
|
-
async function countWorkflowV2Backlog(db, workflowName) {
|
|
2333
|
-
const result = await db.execute(sql2`
|
|
2334
|
-
SELECT
|
|
2335
|
-
COALESCE(SUM(CASE WHEN status IN ('queued', 'running') THEN 1 ELSE 0 END), 0)::int AS pending,
|
|
2336
|
-
COALESCE(SUM(CASE WHEN status IN ('waiting', 'sleeping') THEN 1 ELSE 0 END), 0)::int AS parked,
|
|
2337
|
-
COALESCE(SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END), 0)::int AS running,
|
|
2338
|
-
COALESCE(SUM(CASE WHEN status IN ('queued', 'running') AND workflow_name = ${workflowName} THEN 1 ELSE 0 END), 0)::int AS pending_by_name
|
|
2339
|
-
FROM _gencow_workflow_runs_v2
|
|
2340
|
-
WHERE completed_at IS NULL
|
|
2341
|
-
`);
|
|
2342
|
-
const row = rows2(result)[0];
|
|
2343
|
-
return {
|
|
2344
|
-
pending: numberFrom2(row?.pending),
|
|
2345
|
-
parked: numberFrom2(row?.parked),
|
|
2346
|
-
running: numberFrom2(row?.running),
|
|
2347
|
-
pendingByName: numberFrom2(row?.pending_by_name)
|
|
2348
|
-
};
|
|
2349
|
-
}
|
|
2350
|
-
async function countWorkflowV1Backlog(db, workflowName) {
|
|
2351
|
-
const result = await db.execute(sql2`
|
|
2352
|
-
SELECT
|
|
2353
|
-
COALESCE(SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END), 0)::int AS pending,
|
|
2354
|
-
COALESCE(SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END), 0)::int AS running,
|
|
2355
|
-
COALESCE(SUM(CASE WHEN status = 'pending' AND name = ${workflowName} THEN 1 ELSE 0 END), 0)::int AS pending_by_name
|
|
2356
|
-
FROM _gencow_workflows
|
|
2357
|
-
`);
|
|
2358
|
-
const row = rows2(result)[0];
|
|
2359
|
-
return {
|
|
2360
|
-
pending: numberFrom2(row?.pending),
|
|
2361
|
-
parked: 0,
|
|
2362
|
-
running: numberFrom2(row?.running),
|
|
2363
|
-
pendingByName: numberFrom2(row?.pending_by_name)
|
|
2364
|
-
};
|
|
2365
|
-
}
|
|
2366
|
-
async function countWorkflowBacklog(db, workflowName, requireV2 = false) {
|
|
2367
|
-
try {
|
|
2368
|
-
return await countWorkflowV2Backlog(db, workflowName);
|
|
2369
|
-
} catch (error) {
|
|
2370
|
-
if (!isMissingWorkflowV2SchemaError(error) || requireV2) throw error;
|
|
2371
|
-
return countWorkflowV1Backlog(db, workflowName);
|
|
2372
|
-
}
|
|
2373
|
-
}
|
|
2374
|
-
async function consumeWorkflowRateBucket(db, scope, limit, now) {
|
|
2375
|
-
try {
|
|
2376
|
-
const result = await db.execute(sql2`
|
|
2377
|
-
INSERT INTO _gencow_job_admission_buckets (scope, bucket_start, count, updated_at)
|
|
2378
|
-
VALUES (${scope}, date_trunc('minute', ${now.toISOString()}::timestamptz), 1, NOW())
|
|
2379
|
-
ON CONFLICT (scope, bucket_start) DO UPDATE
|
|
2380
|
-
SET count = _gencow_job_admission_buckets.count + 1,
|
|
2381
|
-
updated_at = NOW()
|
|
2382
|
-
WHERE _gencow_job_admission_buckets.count < ${limit}
|
|
2383
|
-
RETURNING count
|
|
2384
|
-
`);
|
|
2385
|
-
return rows2(result).length > 0;
|
|
2386
|
-
} catch (error) {
|
|
2387
|
-
if (!isMissingAdmissionSchemaError(error)) throw error;
|
|
2388
|
-
throw new JobAdmissionError(
|
|
2389
|
-
"job_admission_disabled",
|
|
2390
|
-
"workflow admission bucket schema is not initialized"
|
|
2391
|
-
);
|
|
2392
|
-
}
|
|
2393
|
-
}
|
|
2394
|
-
async function acquireWorkflowStartAdmissionLock(db) {
|
|
2395
|
-
await db.execute(sql2`SELECT pg_advisory_xact_lock(hashtextextended('workflow:create', 0))`);
|
|
2396
|
-
}
|
|
2397
|
-
async function applyWorkflowStartAdmission(options) {
|
|
2398
|
-
const env = options.env ?? (typeof process === "undefined" ? {} : process.env);
|
|
2399
|
-
if (!isWorkflowAdmissionEnabled(env)) return;
|
|
2400
|
-
if (isJobAdmissionKillSwitchActive(env, `workflow:create:name:${options.workflowName}`)) {
|
|
2401
|
-
throw new JobAdmissionError("job_admission_disabled", "workflow start admission is disabled");
|
|
2402
|
-
}
|
|
2403
|
-
const policy = resolveWorkflowAdmissionPolicy(env);
|
|
2404
|
-
const payloadBytes = jsonByteLength(options.args);
|
|
2405
|
-
if (payloadBytes > policy.payloadMaxBytes) {
|
|
2406
|
-
throw new JobAdmissionError("job_payload_too_large", "workflow start payload is too large", {
|
|
2407
|
-
details: { limitBytes: policy.payloadMaxBytes, payloadBytes }
|
|
2408
|
-
});
|
|
2409
|
-
}
|
|
2410
|
-
await acquireWorkflowStartAdmissionLock(options.db);
|
|
2411
|
-
const counts = await countWorkflowBacklog(options.db, options.workflowName, options.requireV2);
|
|
2412
|
-
if (counts.pending >= policy.pendingPerApp) {
|
|
2413
|
-
throw new JobAdmissionError("job_backlog_limit_exceeded", "workflow pending backlog limit exceeded", {
|
|
2414
|
-
details: { limit: policy.pendingPerApp, pending: counts.pending }
|
|
2415
|
-
});
|
|
2416
|
-
}
|
|
2417
|
-
if (counts.parked >= policy.parkedPerApp) {
|
|
2418
|
-
throw new JobAdmissionError(
|
|
2419
|
-
"workflow_parked_capacity_exceeded",
|
|
2420
|
-
"workflow sleeping/waiting limit exceeded",
|
|
2421
|
-
{
|
|
2422
|
-
details: {
|
|
2423
|
-
limit: policy.parkedPerApp,
|
|
2424
|
-
parked: counts.parked,
|
|
2425
|
-
stage: "admission",
|
|
2426
|
-
stateChanged: false,
|
|
2427
|
-
retryable: true,
|
|
2428
|
-
retryCondition: "Retry after sleeping or waiting runs complete, are signalled, or are cancelled.",
|
|
2429
|
-
nextAction: "Cancel or signal parked runs, or raise GENCOW_WORKFLOW_PARKED_PER_APP; no workflow was started."
|
|
2430
|
-
}
|
|
2431
|
-
}
|
|
2432
|
-
);
|
|
2433
|
-
}
|
|
2434
|
-
if (counts.running >= policy.runningPerApp) {
|
|
2435
|
-
throw new JobAdmissionError("job_backlog_limit_exceeded", "workflow running backlog limit exceeded", {
|
|
2436
|
-
details: { limit: policy.runningPerApp, running: counts.running }
|
|
2437
|
-
});
|
|
2438
|
-
}
|
|
2439
|
-
if (counts.pendingByName >= policy.pendingPerName) {
|
|
2440
|
-
throw new JobAdmissionError(
|
|
2441
|
-
"job_backlog_limit_exceeded",
|
|
2442
|
-
"workflow name pending backlog limit exceeded",
|
|
2443
|
-
{
|
|
2444
|
-
details: {
|
|
2445
|
-
limit: policy.pendingPerName,
|
|
2446
|
-
pending: counts.pendingByName,
|
|
2447
|
-
workflowName: options.workflowName
|
|
2448
|
-
}
|
|
2449
|
-
}
|
|
2450
|
-
);
|
|
2451
|
-
}
|
|
2452
|
-
const now = options.now?.() ?? /* @__PURE__ */ new Date();
|
|
2453
|
-
const consumed = await consumeWorkflowRateBucket(
|
|
2454
|
-
options.db,
|
|
2455
|
-
"workflow:create",
|
|
2456
|
-
policy.startsPerMinutePerApp,
|
|
2457
|
-
now
|
|
2458
|
-
);
|
|
2459
|
-
if (!consumed) {
|
|
2460
|
-
throw new JobAdmissionError("job_rate_limited", "workflow start rate limit exceeded", {
|
|
2461
|
-
retryAfterMs: getMsUntilNextMinute(now),
|
|
2462
|
-
details: { limit: policy.startsPerMinutePerApp }
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
const nameConsumed = await consumeWorkflowRateBucket(
|
|
2466
|
-
options.db,
|
|
2467
|
-
`workflow:create:name:${options.workflowName}`,
|
|
2468
|
-
policy.startsPerMinutePerName,
|
|
2469
|
-
now
|
|
2470
|
-
);
|
|
2471
|
-
if (!nameConsumed) {
|
|
2472
|
-
throw new JobAdmissionError("job_rate_limited", "workflow name start rate limit exceeded", {
|
|
2473
|
-
retryAfterMs: getMsUntilNextMinute(now),
|
|
2474
|
-
details: { limit: policy.startsPerMinutePerName, workflowName: options.workflowName }
|
|
2475
|
-
});
|
|
2476
|
-
}
|
|
2477
|
-
}
|
|
2478
|
-
async function runWorkflowAdmissionCriticalSection(db, callback) {
|
|
2479
|
-
if (db.transaction) {
|
|
2480
|
-
return db.transaction(callback);
|
|
2207
|
+
// ../core/src/workflow-host-adapter-diagnostic.ts
|
|
2208
|
+
var code = "WORKFLOW_HOST_ADAPTER_MISSING";
|
|
2209
|
+
var errorName = "WorkflowHostAdapterMissingError";
|
|
2210
|
+
var workflowHostAdapterPresentation = Object.freeze({
|
|
2211
|
+
status: 500,
|
|
2212
|
+
message: "Workflow operations are not bound to this host context.",
|
|
2213
|
+
stateImpact: "The workflow operation was not dispatched. Earlier application or middleware effects may remain."
|
|
2214
|
+
});
|
|
2215
|
+
var nextAction = "For local development, check `gencow --version`, install a compatible Gencow CLI, then restart with `gencow dev --local`. For hosted apps, verify the app's Core version is supported by its serving host.";
|
|
2216
|
+
var WorkflowHostAdapterMissingError = class extends Error {
|
|
2217
|
+
name = errorName;
|
|
2218
|
+
code = code;
|
|
2219
|
+
status = workflowHostAdapterPresentation.status;
|
|
2220
|
+
correlationId = `rpc_workflow_${crypto.randomUUID()}`;
|
|
2221
|
+
// Older Server builds may only carry their generic public diagnosis fields.
|
|
2222
|
+
publicDiagnostic = Object.freeze({
|
|
2223
|
+
failedStage: "workflow-dispatch",
|
|
2224
|
+
stateChanged: "unknown",
|
|
2225
|
+
retryable: false,
|
|
2226
|
+
// Older CLI renderers show this field but ignore the raw error message.
|
|
2227
|
+
retryPrecondition: `${workflowHostAdapterPresentation.stateImpact} Before retrying, verify those effects. For local development, check \`gencow --version\`, install a compatible CLI, then restart with \`gencow dev --local\`.`
|
|
2228
|
+
});
|
|
2229
|
+
constructor() {
|
|
2230
|
+
super(`${code}: ${workflowHostAdapterPresentation.message} ${workflowHostAdapterPresentation.stateImpact} ${nextAction}`);
|
|
2481
2231
|
}
|
|
2482
|
-
|
|
2483
|
-
}
|
|
2484
|
-
|
|
2485
|
-
// ../core/src/workflow-json.ts
|
|
2486
|
-
import { sql as sql3 } from "drizzle-orm";
|
|
2487
|
-
function workflowJsonb(value) {
|
|
2488
|
-
const json = JSON.stringify(value ?? {});
|
|
2489
|
-
return sql3`${json}::text::jsonb`;
|
|
2490
|
-
}
|
|
2232
|
+
};
|
|
2491
2233
|
|
|
2492
|
-
// ../core/src/workflow-
|
|
2493
|
-
|
|
2494
|
-
var
|
|
2495
|
-
function
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
}
|
|
2507
|
-
function rows3(result) {
|
|
2508
|
-
if (Array.isArray(result)) return result;
|
|
2509
|
-
const nested = result?.rows;
|
|
2510
|
-
return Array.isArray(nested) ? nested : [];
|
|
2511
|
-
}
|
|
2512
|
-
async function hashWorkflowIdempotencyKey(db, workflowName, userId, key) {
|
|
2513
|
-
const hashed = rows3(
|
|
2514
|
-
await db.execute(sql4`
|
|
2515
|
-
SELECT encode(sha256(convert_to(
|
|
2516
|
-
${workflowName} || chr(31) || ${userId ?? "anon"} || chr(31) || ${key},
|
|
2517
|
-
'UTF8')), 'hex') AS key_hash
|
|
2518
|
-
`)
|
|
2519
|
-
);
|
|
2520
|
-
return String(hashed[0]?.key_hash ?? "");
|
|
2521
|
-
}
|
|
2522
|
-
function deduplicatedWorkflowStart(workflowName, existing) {
|
|
2523
|
-
return {
|
|
2524
|
-
id: existing.id,
|
|
2525
|
-
name: workflowName,
|
|
2526
|
-
status: existing.status === "running" ? "running" : "pending",
|
|
2527
|
-
scheduledJobId: `start:${existing.id}`,
|
|
2528
|
-
deduplicated: true
|
|
2529
|
-
};
|
|
2530
|
-
}
|
|
2531
|
-
function isWorkflowIdempotencyConflict(error) {
|
|
2532
|
-
const source = error?.cause ?? error;
|
|
2533
|
-
const { code, constraint, message } = source ?? {};
|
|
2534
|
-
return code === "23505" && `${constraint ?? ""} ${message ?? ""}`.includes("idempotency");
|
|
2535
|
-
}
|
|
2536
|
-
async function findLiveWorkflowIdempotentRun(options) {
|
|
2537
|
-
const keyHash = await hashWorkflowIdempotencyKey(options.db, options.workflowName, options.userId, options.key);
|
|
2538
|
-
const found = rows3(
|
|
2539
|
-
await options.db.execute(sql4`
|
|
2540
|
-
SELECT id, status FROM _gencow_workflow_runs_v2
|
|
2541
|
-
WHERE idempotency_key = ${keyHash} AND completed_at IS NULL AND cancel_requested_at IS NULL LIMIT 1
|
|
2542
|
-
`)
|
|
2543
|
-
)[0];
|
|
2544
|
-
return found ? { id: String(found.id), status: String(found.status) } : null;
|
|
2545
|
-
}
|
|
2546
|
-
async function lookupWorkflowIdempotentStart(options) {
|
|
2547
|
-
const keyHash = await hashWorkflowIdempotencyKey(options.db, options.workflowName, options.userId, options.key);
|
|
2548
|
-
await options.db.execute(sql4`SELECT pg_advisory_xact_lock(hashtextextended(${keyHash}, 0))`);
|
|
2549
|
-
await options.db.execute(sql4`
|
|
2550
|
-
UPDATE _gencow_workflow_runs_v2
|
|
2551
|
-
SET idempotency_key = NULL
|
|
2552
|
-
WHERE idempotency_key = ${keyHash} AND (completed_at IS NOT NULL OR cancel_requested_at IS NOT NULL)
|
|
2553
|
-
`);
|
|
2554
|
-
const found = rows3(
|
|
2555
|
-
await options.db.execute(sql4`
|
|
2556
|
-
SELECT id, status FROM _gencow_workflow_runs_v2 WHERE idempotency_key = ${keyHash} LIMIT 1
|
|
2557
|
-
`)
|
|
2558
|
-
)[0];
|
|
2559
|
-
return {
|
|
2560
|
-
keyHash,
|
|
2561
|
-
existing: found ? { id: String(found.id), status: String(found.status) } : null
|
|
2234
|
+
// ../core/src/workflow-operations.ts
|
|
2235
|
+
var workflowOperationsKey = /* @__PURE__ */ Symbol.for("@gencow/core/workflow-operations");
|
|
2236
|
+
var workflowScopeKey = /* @__PURE__ */ Symbol.for("@gencow/core/workflow-operations-scope");
|
|
2237
|
+
function scope() {
|
|
2238
|
+
return Reflect.get(globalThis, workflowScopeKey);
|
|
2239
|
+
}
|
|
2240
|
+
async function runWithWorkflowOperations(context, callback) {
|
|
2241
|
+
const operations = context && typeof context === "object" ? findWorkflowOperations(context) : void 0;
|
|
2242
|
+
const carrier = scope();
|
|
2243
|
+
if (!operations || !carrier) return callback(operations, () => {
|
|
2244
|
+
});
|
|
2245
|
+
const invocation = { operations, contexts: /* @__PURE__ */ new WeakSet() };
|
|
2246
|
+
const admitContext = (value) => {
|
|
2247
|
+
if (invocation.operations && value && typeof value === "object") invocation.contexts.add(value);
|
|
2562
2248
|
};
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
// ../core/src/workflow-payload-policy.ts
|
|
2570
|
-
var CHECKPOINT_MODE_ENV = "GENCOW_WORKFLOW_CHECKPOINT_LIMIT_MODE";
|
|
2571
|
-
var CHECKPOINT_SOFT_LIMIT_ENV = "GENCOW_WORKFLOW_CHECKPOINT_SOFT_LIMIT_BYTES";
|
|
2572
|
-
var CHECKPOINT_HARD_LIMIT_ENV = "GENCOW_WORKFLOW_CHECKPOINT_HARD_LIMIT_BYTES";
|
|
2573
|
-
var DEFAULT_SOFT_LIMIT_BYTES = 64 * 1024;
|
|
2574
|
-
var DEFAULT_HARD_LIMIT_BYTES = 256 * 1024;
|
|
2575
|
-
var BOOT_ENV_SNAPSHOT = {
|
|
2576
|
-
mode: process.env[CHECKPOINT_MODE_ENV],
|
|
2577
|
-
softLimitBytes: process.env[CHECKPOINT_SOFT_LIMIT_ENV],
|
|
2578
|
-
hardLimitBytes: process.env[CHECKPOINT_HARD_LIMIT_ENV]
|
|
2579
|
-
};
|
|
2580
|
-
var ERROR_CODES = {
|
|
2581
|
-
args: "workflow_args_too_large",
|
|
2582
|
-
signal: "workflow_signal_payload_too_large"
|
|
2583
|
-
};
|
|
2584
|
-
var WorkflowPayloadPolicyError = class extends Error {
|
|
2585
|
-
errorCode;
|
|
2586
|
-
code;
|
|
2587
|
-
status = 413;
|
|
2588
|
-
kind;
|
|
2589
|
-
sizeBytes;
|
|
2590
|
-
hardLimitBytes;
|
|
2591
|
-
constructor(params) {
|
|
2592
|
-
const errorCode = ERROR_CODES[params.kind];
|
|
2593
|
-
super(
|
|
2594
|
-
`${errorCode}: Workflow "${params.workflowName}" ${params.kind} payload is ${params.sizeBytes} bytes, exceeding the ${params.hardLimitBytes} byte hard limit. Store large values in an app table/storage object and pass only an id/reference/count/checksum.`
|
|
2595
|
-
);
|
|
2596
|
-
this.name = "WorkflowPayloadPolicyError";
|
|
2597
|
-
this.errorCode = errorCode;
|
|
2598
|
-
this.code = errorCode;
|
|
2599
|
-
this.kind = params.kind;
|
|
2600
|
-
this.sizeBytes = params.sizeBytes;
|
|
2601
|
-
this.hardLimitBytes = params.hardLimitBytes;
|
|
2249
|
+
admitContext(context);
|
|
2250
|
+
try {
|
|
2251
|
+
return await carrier.run(invocation, () => callback(operations, admitContext));
|
|
2252
|
+
} finally {
|
|
2253
|
+
invocation.operations = void 0;
|
|
2602
2254
|
}
|
|
2603
|
-
};
|
|
2604
|
-
function normalizeLimit(value, fallback) {
|
|
2605
|
-
if (!value?.trim()) return fallback;
|
|
2606
|
-
const parsed = Number(value);
|
|
2607
|
-
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
|
|
2608
2255
|
}
|
|
2609
|
-
function
|
|
2610
|
-
|
|
2256
|
+
function findWorkflowOperations(context) {
|
|
2257
|
+
const invocation = scope()?.getStore();
|
|
2258
|
+
if (invocation?.operations && invocation.contexts.has(context)) return invocation.operations;
|
|
2259
|
+
return context[workflowOperationsKey];
|
|
2611
2260
|
}
|
|
2612
|
-
function
|
|
2613
|
-
|
|
2614
|
-
return {
|
|
2615
|
-
mode: normalizeMode(env.mode),
|
|
2616
|
-
softLimitBytes: Math.min(normalizeLimit(env.softLimitBytes, DEFAULT_SOFT_LIMIT_BYTES), hardLimitBytes),
|
|
2617
|
-
hardLimitBytes
|
|
2618
|
-
};
|
|
2261
|
+
function getWorkflowOperations(context) {
|
|
2262
|
+
return requireWorkflowOperations(findWorkflowOperations(context));
|
|
2619
2263
|
}
|
|
2620
|
-
function
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
const sizeBytes = new TextEncoder().encode(serializedJson).byteLength;
|
|
2624
|
-
const level = sizeBytes > config.hardLimitBytes ? "hard_limit" : sizeBytes > config.softLimitBytes ? "soft_limit" : "ok";
|
|
2625
|
-
if (level !== "ok") {
|
|
2626
|
-
(params.logger ?? console).warn(
|
|
2627
|
-
`[workflow] ${params.workflowName} ${params.kind} workflow payload ${level} (sizeBytes=${sizeBytes}, softLimitBytes=${config.softLimitBytes}, hardLimitBytes=${config.hardLimitBytes}, mode=${config.mode}, errorCode=${level === "hard_limit" ? ERROR_CODES[params.kind] : "none"})`
|
|
2628
|
-
);
|
|
2629
|
-
}
|
|
2630
|
-
const enforced = config.mode === "enforce" || config.mode === "platform_enforce" && params.workflowName.startsWith("__gencow.");
|
|
2631
|
-
if (enforced && sizeBytes > config.hardLimitBytes) {
|
|
2632
|
-
throw new WorkflowPayloadPolicyError({
|
|
2633
|
-
workflowName: params.workflowName,
|
|
2634
|
-
kind: params.kind,
|
|
2635
|
-
sizeBytes,
|
|
2636
|
-
hardLimitBytes: config.hardLimitBytes
|
|
2637
|
-
});
|
|
2638
|
-
}
|
|
2639
|
-
return sizeBytes;
|
|
2264
|
+
function requireWorkflowOperations(operations) {
|
|
2265
|
+
if (!operations) throw new WorkflowHostAdapterMissingError();
|
|
2266
|
+
return operations;
|
|
2640
2267
|
}
|
|
2641
2268
|
|
|
2642
2269
|
// ../core/src/workflow.ts
|
|
@@ -2711,98 +2338,11 @@ function normalizeConcurrency(concurrency) {
|
|
|
2711
2338
|
}
|
|
2712
2339
|
return Math.floor(concurrency);
|
|
2713
2340
|
}
|
|
2714
|
-
function isMissingWorkflowV2SchemaError2(error) {
|
|
2715
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
2716
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
2717
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
2718
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2719
|
-
return code === "42P01" || code === "42703" || causeCode === "42P01" || causeCode === "42703" || message.includes('relation "_gencow_workflow_runs_v2" does not exist') || message.includes("relation _gencow_workflow_runs_v2 does not exist") || message.includes('relation "_gencow_workflow_outbox_v2" does not exist') || message.includes("relation _gencow_workflow_outbox_v2 does not exist") || message.includes('column "max_active_duration_ms"') || message.includes('column "retry_count"') || message.includes('column "user_id"');
|
|
2720
|
-
}
|
|
2721
2341
|
var COMMAND_PROTOCOL_1_WORKFLOW_NAMES = /* @__PURE__ */ new Set(["__gencow.documents.ingest.run"]);
|
|
2722
2342
|
function defaultWorkflowCommandProtocol(workflowName, env = typeof process !== "undefined" ? process.env : {}) {
|
|
2723
2343
|
if (COMMAND_PROTOCOL_1_WORKFLOW_NAMES.has(workflowName)) return 1;
|
|
2724
2344
|
return env.GENCOW_WORKFLOW_COMMAND_PROTOCOL_DEFAULT === "1" ? 1 : 2;
|
|
2725
2345
|
}
|
|
2726
|
-
async function tryInsertWorkflowV2Run(options) {
|
|
2727
|
-
try {
|
|
2728
|
-
if (!await hasWorkflowV2StartSchema(options.db)) return false;
|
|
2729
|
-
await options.db.execute(sql5`
|
|
2730
|
-
WITH inserted_run AS (
|
|
2731
|
-
INSERT INTO _gencow_workflow_runs_v2 (
|
|
2732
|
-
id,
|
|
2733
|
-
workflow_name,
|
|
2734
|
-
workflow_version,
|
|
2735
|
-
args_json,
|
|
2736
|
-
user_id,
|
|
2737
|
-
max_active_duration_ms,
|
|
2738
|
-
lifecycle_deadline_at,
|
|
2739
|
-
retry_count,
|
|
2740
|
-
max_retries,
|
|
2741
|
-
max_attempts,
|
|
2742
|
-
command_protocol,
|
|
2743
|
-
idempotency_key
|
|
2744
|
-
)
|
|
2745
|
-
VALUES (
|
|
2746
|
-
${options.workflowId},
|
|
2747
|
-
${options.workflowName},
|
|
2748
|
-
${options.workflowVersion ?? null},
|
|
2749
|
-
${workflowJsonb(options.args)},
|
|
2750
|
-
${options.userId},
|
|
2751
|
-
${options.maxActiveDurationMs},
|
|
2752
|
-
CASE
|
|
2753
|
-
WHEN ${options.lifecycleTimeoutMs}::bigint IS NULL THEN NULL
|
|
2754
|
-
ELSE NOW() + (${options.lifecycleTimeoutMs}::bigint * INTERVAL '1 millisecond')
|
|
2755
|
-
END,
|
|
2756
|
-
0,
|
|
2757
|
-
${options.maxRetries},
|
|
2758
|
-
${options.maxRetries + 1},
|
|
2759
|
-
${options.commandProtocol ?? defaultWorkflowCommandProtocol(options.workflowName)},
|
|
2760
|
-
${options.idempotencyKeyHash ?? null}
|
|
2761
|
-
)
|
|
2762
|
-
RETURNING id
|
|
2763
|
-
),
|
|
2764
|
-
inserted_outbox AS (
|
|
2765
|
-
INSERT INTO _gencow_workflow_outbox_v2 (
|
|
2766
|
-
id,
|
|
2767
|
-
run_id,
|
|
2768
|
-
kind,
|
|
2769
|
-
available_at,
|
|
2770
|
-
status
|
|
2771
|
-
)
|
|
2772
|
-
SELECT
|
|
2773
|
-
'start:' || inserted_run.id,
|
|
2774
|
-
inserted_run.id,
|
|
2775
|
-
'wake_run',
|
|
2776
|
-
NOW(),
|
|
2777
|
-
'pending'
|
|
2778
|
-
FROM inserted_run
|
|
2779
|
-
ON CONFLICT (id) DO NOTHING
|
|
2780
|
-
RETURNING id
|
|
2781
|
-
),
|
|
2782
|
-
wake_notified AS (
|
|
2783
|
-
SELECT pg_notify(${WORKFLOW_WAKE_SIGNAL_CHANNEL}, ${WORKFLOW_WAKE_SIGNAL_PAYLOAD})
|
|
2784
|
-
FROM inserted_outbox
|
|
2785
|
-
)
|
|
2786
|
-
SELECT inserted_run.id
|
|
2787
|
-
FROM inserted_run
|
|
2788
|
-
LEFT JOIN wake_notified ON TRUE
|
|
2789
|
-
`);
|
|
2790
|
-
return true;
|
|
2791
|
-
} catch (error) {
|
|
2792
|
-
if (isMissingWorkflowV2SchemaError2(error)) return false;
|
|
2793
|
-
throw error;
|
|
2794
|
-
}
|
|
2795
|
-
}
|
|
2796
|
-
async function tryDeleteWorkflowV2Run(db, workflowId) {
|
|
2797
|
-
try {
|
|
2798
|
-
await db.execute(sql5`
|
|
2799
|
-
DELETE FROM _gencow_workflow_runs_v2
|
|
2800
|
-
WHERE id = ${workflowId}
|
|
2801
|
-
`);
|
|
2802
|
-
} catch (error) {
|
|
2803
|
-
if (!isMissingWorkflowV2SchemaError2(error)) throw error;
|
|
2804
|
-
}
|
|
2805
|
-
}
|
|
2806
2346
|
function getWorkflowResumeActionName(name) {
|
|
2807
2347
|
return `${WORKFLOW_RESUME_ACTION_PREFIX}.${name}`;
|
|
2808
2348
|
}
|
|
@@ -2831,14 +2371,17 @@ async function validateWorkflowStartInput(schema, value) {
|
|
|
2831
2371
|
throw new GencowValidationError("Validation failed");
|
|
2832
2372
|
}
|
|
2833
2373
|
function composeWorkflowStartMiddleware(options) {
|
|
2834
|
-
return
|
|
2374
|
+
return (initialContext, initialInput) => runWithWorkflowOperations(initialContext, async (operations, admitContext) => {
|
|
2835
2375
|
let lastIndex = -1;
|
|
2836
2376
|
const validationIndex = Math.min(Math.max(0, options.inputValidationIndex), options.middlewares.length);
|
|
2837
2377
|
const run = async (index, context, input) => {
|
|
2838
2378
|
if (index <= lastIndex) throw new Error("next() called multiple times in the same middleware");
|
|
2839
2379
|
lastIndex = index;
|
|
2380
|
+
admitContext(context);
|
|
2840
2381
|
const validatedInput = index === validationIndex ? await validateWorkflowStartInput(options.inputSchema, input) : input;
|
|
2841
|
-
if (index === options.middlewares.length)
|
|
2382
|
+
if (index === options.middlewares.length) {
|
|
2383
|
+
return options.handler(context, validatedInput, requireWorkflowOperations(operations));
|
|
2384
|
+
}
|
|
2842
2385
|
return await options.middlewares[index]({
|
|
2843
2386
|
context,
|
|
2844
2387
|
input: validatedInput,
|
|
@@ -2849,85 +2392,11 @@ function composeWorkflowStartMiddleware(options) {
|
|
|
2849
2392
|
)
|
|
2850
2393
|
});
|
|
2851
2394
|
};
|
|
2852
|
-
return
|
|
2853
|
-
};
|
|
2395
|
+
return run(0, initialContext, initialInput);
|
|
2396
|
+
});
|
|
2854
2397
|
}
|
|
2855
|
-
async function startWorkflowRun(ctx, args, def,
|
|
2856
|
-
|
|
2857
|
-
const resumeAction = getWorkflowResumeActionName(def.name);
|
|
2858
|
-
const ownerId = ctx.auth.getUserIdentity()?.id ?? null;
|
|
2859
|
-
const persistedArgs = serializeWorkflowValue(args ?? {});
|
|
2860
|
-
assertWorkflowPayloadWithinLimit({ workflowName: def.name, kind: "args", serializedValue: persistedArgs });
|
|
2861
|
-
const realtimeToken = createWorkflowRealtimeToken();
|
|
2862
|
-
const idempotencyKey = ownerId ? normalizeWorkflowIdempotencyKey(def.idempotencyKey?.(args, ctx)) : null;
|
|
2863
|
-
let insertedWorkflowV2 = false;
|
|
2864
|
-
let deduplicated = null;
|
|
2865
|
-
try {
|
|
2866
|
-
await runWorkflowAdmissionCriticalSection(ctx.unsafeDb, async (db) => {
|
|
2867
|
-
let idempotencyKeyHash = null;
|
|
2868
|
-
if (idempotencyKey !== null) {
|
|
2869
|
-
if (!await hasWorkflowV2StartSchema(db)) {
|
|
2870
|
-
throw new GencowValidationError(
|
|
2871
|
-
`Workflow ${def.name}: idempotencyKey needs the Workflow V2 tables. Redeploy so the app schema is upgraded, then start again.`
|
|
2872
|
-
);
|
|
2873
|
-
}
|
|
2874
|
-
const lookup = await lookupWorkflowIdempotentStart({
|
|
2875
|
-
db,
|
|
2876
|
-
workflowName: def.name,
|
|
2877
|
-
userId: ownerId,
|
|
2878
|
-
key: idempotencyKey
|
|
2879
|
-
});
|
|
2880
|
-
if (lookup.existing) {
|
|
2881
|
-
deduplicated = deduplicatedWorkflowStart(def.name, lookup.existing);
|
|
2882
|
-
return;
|
|
2883
|
-
}
|
|
2884
|
-
idempotencyKeyHash = lookup.keyHash;
|
|
2885
|
-
}
|
|
2886
|
-
await applyWorkflowStartAdmission({ db, workflowName: def.name, args: persistedArgs });
|
|
2887
|
-
insertedWorkflowV2 = await tryInsertWorkflowV2Run({
|
|
2888
|
-
db,
|
|
2889
|
-
workflowId,
|
|
2890
|
-
workflowName: def.name,
|
|
2891
|
-
workflowVersion: def.version ?? null,
|
|
2892
|
-
args: persistedArgs,
|
|
2893
|
-
userId: ownerId,
|
|
2894
|
-
maxActiveDurationMs: def.maxActiveDurationMs,
|
|
2895
|
-
lifecycleTimeoutMs: def.lifecycleTimeoutMs,
|
|
2896
|
-
maxRetries: def.maxRetries,
|
|
2897
|
-
idempotencyKeyHash
|
|
2898
|
-
});
|
|
2899
|
-
const legacyArgs = insertedWorkflowV2 ? serializeWorkflowValue(void 0) : persistedArgs;
|
|
2900
|
-
await db.execute(sql5`
|
|
2901
|
-
INSERT INTO _gencow_workflows (
|
|
2902
|
-
id, name, args, realtime_token, status, retry_count, max_retries, max_duration_ms, user_id
|
|
2903
|
-
) VALUES (
|
|
2904
|
-
${workflowId}, ${def.name}, ${workflowJsonb(legacyArgs)}, ${realtimeToken}, 'pending', 0,
|
|
2905
|
-
${def.maxRetries}, ${def.maxActiveDurationMs}, ${ownerId}
|
|
2906
|
-
)
|
|
2907
|
-
`);
|
|
2908
|
-
});
|
|
2909
|
-
if (deduplicated) return deduplicated;
|
|
2910
|
-
return {
|
|
2911
|
-
id: workflowId,
|
|
2912
|
-
name: def.name,
|
|
2913
|
-
status: "pending",
|
|
2914
|
-
scheduledJobId: insertedWorkflowV2 ? `start:${workflowId}` : ctx.scheduler.runAfter(0, resumeAction, { workflowId })
|
|
2915
|
-
};
|
|
2916
|
-
} catch (error) {
|
|
2917
|
-
await ctx.unsafeDb.execute(sql5`DELETE FROM _gencow_workflows WHERE id = ${workflowId}`);
|
|
2918
|
-
if (insertedWorkflowV2) await tryDeleteWorkflowV2Run(ctx.unsafeDb, workflowId);
|
|
2919
|
-
if (idempotencyKey !== null && isWorkflowIdempotencyConflict(error)) {
|
|
2920
|
-
const winner = await findLiveWorkflowIdempotentRun({
|
|
2921
|
-
db: ctx.unsafeDb,
|
|
2922
|
-
workflowName: def.name,
|
|
2923
|
-
userId: ownerId,
|
|
2924
|
-
key: idempotencyKey
|
|
2925
|
-
});
|
|
2926
|
-
if (winner) return deduplicatedWorkflowStart(def.name, winner);
|
|
2927
|
-
if (conflictRetries > 0) return startWorkflowRun(ctx, args, def, conflictRetries - 1);
|
|
2928
|
-
}
|
|
2929
|
-
throw error;
|
|
2930
|
-
}
|
|
2398
|
+
async function startWorkflowRun(ctx, args, def, operations = getWorkflowOperations(ctx)) {
|
|
2399
|
+
return operations.start(ctx, { definition: def, args });
|
|
2931
2400
|
}
|
|
2932
2401
|
function createWorkflowMetadata(options) {
|
|
2933
2402
|
const { definition } = options;
|
|
@@ -2942,7 +2411,7 @@ function createWorkflowMetadata(options) {
|
|
|
2942
2411
|
middlewares,
|
|
2943
2412
|
inputSchema: hasStandardSchema4(definition.argsSchema) ? definition.argsSchema : void 0,
|
|
2944
2413
|
inputValidationIndex: options.inputValidationIndex ?? 0,
|
|
2945
|
-
handler:
|
|
2414
|
+
handler: (ctx, args, operations) => startWorkflowRun(ctx, args, definition, operations)
|
|
2946
2415
|
});
|
|
2947
2416
|
const explicitStart = {
|
|
2948
2417
|
kind: "mutation",
|
|
@@ -3253,765 +2722,38 @@ function validateWorkflowStepOptions(stepName, options) {
|
|
|
3253
2722
|
}
|
|
3254
2723
|
|
|
3255
2724
|
// ../core/src/workflows-api.ts
|
|
3256
|
-
import { sql as sql8 } from "drizzle-orm";
|
|
3257
|
-
|
|
3258
|
-
// ../core/src/workflows-signal-record.ts
|
|
3259
|
-
import { sql as sql6 } from "drizzle-orm";
|
|
3260
|
-
function rowsFromResult(result) {
|
|
3261
|
-
if (Array.isArray(result)) return result;
|
|
3262
|
-
if (result && typeof result === "object" && Array.isArray(result.rows)) {
|
|
3263
|
-
return result.rows;
|
|
3264
|
-
}
|
|
3265
|
-
return [];
|
|
3266
|
-
}
|
|
3267
|
-
function isMissingWorkflowV2SignalSchemaError(error) {
|
|
3268
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
3269
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
3270
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
3271
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
3272
|
-
return code === "42P01" || code === "42703" || causeCode === "42P01" || causeCode === "42703" || (code === "23503" || causeCode === "23503") && message.includes("_gencow_workflow_signals_v2") || message.includes('relation "_gencow_workflow_signals_v2" does not exist') || message.includes("relation _gencow_workflow_signals_v2 does not exist") || message.includes('relation "_gencow_workflow_runs_v2" does not exist') || message.includes("relation _gencow_workflow_runs_v2 does not exist") || message.includes('relation "_gencow_workflow_outbox_v2" does not exist') || message.includes("relation _gencow_workflow_outbox_v2 does not exist") || message.includes('relation "_gencow_workflow_steps_v2" does not exist') || message.includes("relation _gencow_workflow_steps_v2 does not exist");
|
|
3273
|
-
}
|
|
3274
|
-
var WAKES_PARKED_WAIT = sql6.raw(`(run.status = 'waiting'
|
|
3275
|
-
AND (run.current_step_key IS NULL
|
|
3276
|
-
OR starts_with(run.current_step_key, 'wait:' || inserted.event_name || '#'))
|
|
3277
|
-
AND NOT EXISTS (
|
|
3278
|
-
SELECT 1 FROM _gencow_workflow_timers_v2 expired
|
|
3279
|
-
WHERE expired.run_id = run.id AND expired.kind = 'wait_timeout'
|
|
3280
|
-
AND expired.status = 'pending' AND expired.fire_at <= NOW()
|
|
3281
|
-
AND (
|
|
3282
|
-
EXISTS (SELECT 1 FROM _gencow_workflow_steps_v2 parked
|
|
3283
|
-
WHERE parked.run_id = expired.run_id AND parked.step_key = expired.command_key
|
|
3284
|
-
AND parked.status = 'pending')
|
|
3285
|
-
OR (run.command_protocol = 1
|
|
3286
|
-
AND expired.dedupe_key = run.current_step_key || ':timeout')
|
|
3287
|
-
)))`);
|
|
3288
|
-
async function tryRecordWorkflowV2Signal(options) {
|
|
3289
|
-
const eventName = options.event.normalize("NFC");
|
|
3290
|
-
try {
|
|
3291
|
-
const result = await options.db.execute(sql6`
|
|
3292
|
-
WITH eligible_run AS (
|
|
3293
|
-
SELECT id
|
|
3294
|
-
FROM _gencow_workflow_runs_v2
|
|
3295
|
-
WHERE id = ${options.workflowId}
|
|
3296
|
-
AND status IN ('queued', 'running', 'sleeping', 'waiting')
|
|
3297
|
-
AND completed_at IS NULL
|
|
3298
|
-
AND cancel_requested_at IS NULL
|
|
3299
|
-
FOR UPDATE
|
|
3300
|
-
), inserted AS (
|
|
3301
|
-
INSERT INTO _gencow_workflow_signals_v2 (
|
|
3302
|
-
id,
|
|
3303
|
-
run_id,
|
|
3304
|
-
event_name,
|
|
3305
|
-
payload_json,
|
|
3306
|
-
idempotency_key
|
|
3307
|
-
)
|
|
3308
|
-
SELECT
|
|
3309
|
-
${options.signalId},
|
|
3310
|
-
eligible_run.id,
|
|
3311
|
-
${eventName},
|
|
3312
|
-
${workflowJsonb(options.payload)},
|
|
3313
|
-
${options.idempotencyKey ?? options.signalId}
|
|
3314
|
-
FROM eligible_run
|
|
3315
|
-
ON CONFLICT (run_id, event_name, idempotency_key) DO NOTHING
|
|
3316
|
-
RETURNING id, run_id, event_name
|
|
3317
|
-
),
|
|
3318
|
-
queued_run AS (
|
|
3319
|
-
-- SET expressions run on the newest row version after any concurrent commit. A wait that parks
|
|
3320
|
-
-- while this statement is blocked on the run lock is therefore still woken; a WHERE on status
|
|
3321
|
-
-- would be judged against the statement snapshot and miss it.
|
|
3322
|
-
UPDATE _gencow_workflow_runs_v2 run
|
|
3323
|
-
SET
|
|
3324
|
-
status = CASE WHEN ${WAKES_PARKED_WAIT} THEN 'queued' ELSE run.status END,
|
|
3325
|
-
runnable_at = CASE WHEN ${WAKES_PARKED_WAIT} THEN NOW() ELSE run.runnable_at END,
|
|
3326
|
-
lease_owner = CASE WHEN ${WAKES_PARKED_WAIT} THEN NULL ELSE run.lease_owner END,
|
|
3327
|
-
lease_expires_at = CASE WHEN ${WAKES_PARKED_WAIT} THEN NULL ELSE run.lease_expires_at END,
|
|
3328
|
-
heartbeat_at = CASE WHEN ${WAKES_PARKED_WAIT} THEN NULL ELSE run.heartbeat_at END,
|
|
3329
|
-
updated_at = CASE WHEN ${WAKES_PARKED_WAIT} THEN NOW() ELSE run.updated_at END
|
|
3330
|
-
FROM inserted
|
|
3331
|
-
WHERE run.id = inserted.run_id
|
|
3332
|
-
AND run.completed_at IS NULL
|
|
3333
|
-
AND run.cancel_requested_at IS NULL
|
|
3334
|
-
RETURNING run.id, (run.status = 'queued') AS woken
|
|
3335
|
-
),
|
|
3336
|
-
wake_outbox AS (
|
|
3337
|
-
INSERT INTO _gencow_workflow_outbox_v2 (
|
|
3338
|
-
id,
|
|
3339
|
-
run_id,
|
|
3340
|
-
kind,
|
|
3341
|
-
available_at,
|
|
3342
|
-
status
|
|
3343
|
-
)
|
|
3344
|
-
SELECT
|
|
3345
|
-
'signal:' || inserted.id,
|
|
3346
|
-
inserted.run_id,
|
|
3347
|
-
'wake_signal',
|
|
3348
|
-
NOW(),
|
|
3349
|
-
'pending'
|
|
3350
|
-
FROM inserted
|
|
3351
|
-
JOIN queued_run ON queued_run.id = inserted.run_id AND queued_run.woken
|
|
3352
|
-
ON CONFLICT (id) DO NOTHING
|
|
3353
|
-
RETURNING id
|
|
3354
|
-
),
|
|
3355
|
-
wake_notified AS (
|
|
3356
|
-
SELECT pg_notify(${WORKFLOW_WAKE_SIGNAL_CHANNEL}, ${WORKFLOW_WAKE_SIGNAL_PAYLOAD})
|
|
3357
|
-
FROM wake_outbox
|
|
3358
|
-
)
|
|
3359
|
-
SELECT 1
|
|
3360
|
-
FROM inserted
|
|
3361
|
-
LEFT JOIN wake_notified ON TRUE
|
|
3362
|
-
`);
|
|
3363
|
-
if (rowsFromResult(result).length > 0) return "accepted";
|
|
3364
|
-
if (options.idempotencyKey) {
|
|
3365
|
-
const prior = await options.db.execute(sql6`
|
|
3366
|
-
SELECT 1 FROM _gencow_workflow_signals_v2
|
|
3367
|
-
WHERE run_id = ${options.workflowId}
|
|
3368
|
-
AND event_name = ${eventName}
|
|
3369
|
-
AND idempotency_key = ${options.idempotencyKey}
|
|
3370
|
-
LIMIT 1
|
|
3371
|
-
`);
|
|
3372
|
-
if (rowsFromResult(prior).length > 0) return "duplicate";
|
|
3373
|
-
}
|
|
3374
|
-
return "rejected";
|
|
3375
|
-
} catch (error) {
|
|
3376
|
-
if (isMissingWorkflowV2SignalSchemaError(error)) return "absent";
|
|
3377
|
-
throw error;
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
|
|
3381
|
-
// ../core/src/workflow-public-read-model.ts
|
|
3382
|
-
function parseJsonField(value) {
|
|
3383
|
-
if (typeof value !== "string") return value;
|
|
3384
|
-
try {
|
|
3385
|
-
return JSON.parse(value);
|
|
3386
|
-
} catch {
|
|
3387
|
-
return value;
|
|
3388
|
-
}
|
|
3389
|
-
}
|
|
3390
|
-
function toIsoString(value) {
|
|
3391
|
-
if (typeof value === "number" && !Number.isFinite(value)) return String(/* @__PURE__ */ new Date(NaN));
|
|
3392
|
-
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : String(value);
|
|
3393
|
-
const parsed = new Date(value);
|
|
3394
|
-
return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : String(value);
|
|
3395
|
-
}
|
|
3396
|
-
function toOptionalIsoString(value) {
|
|
3397
|
-
if (typeof value === "number" && !Number.isFinite(value)) return toIsoString(value);
|
|
3398
|
-
return value ? toIsoString(value) : null;
|
|
3399
|
-
}
|
|
3400
|
-
function publicWorkflowErrorCode(code) {
|
|
3401
|
-
if (!code) return null;
|
|
3402
|
-
return code === "active_timeout" ? "workflow_active_timeout" : code;
|
|
3403
|
-
}
|
|
3404
|
-
function publicV1WorkflowStatus(status, errorCode) {
|
|
3405
|
-
return status === "failed" && errorCode === "cancelled" ? "cancelled" : status;
|
|
3406
|
-
}
|
|
3407
|
-
var PUBLIC_ERROR_SUMMARIES = {
|
|
3408
|
-
workflow_error: "A workflow step failed.",
|
|
3409
|
-
workflow_step_timeout: "A workflow step exceeded its timeout.",
|
|
3410
|
-
workflow_step_options_invalid: "A workflow step has invalid options.",
|
|
3411
|
-
workflow_active_timeout: "The workflow exceeded its maximum active duration.",
|
|
3412
|
-
workflow_nondeterministic: "The workflow code changed in a way that no longer matches this run's history.",
|
|
3413
|
-
definition_missing: "The workflow definition is not deployed.",
|
|
3414
|
-
cancelled: "The workflow was cancelled."
|
|
3415
|
-
};
|
|
3416
|
-
var ERROR_DETAIL_MAX_CHARS = 300;
|
|
3417
|
-
var SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
3418
|
-
function looksLikeDriverFailure(body, message) {
|
|
3419
|
-
return body?.name === "DrizzleQueryError" || (message?.startsWith("Failed query:") ?? false);
|
|
3420
|
-
}
|
|
3421
|
-
function publicStepError(errorJson) {
|
|
3422
|
-
if (errorJson === null || errorJson === void 0) return null;
|
|
3423
|
-
const body = errorJson && typeof errorJson === "object" ? errorJson : null;
|
|
3424
|
-
const message = typeof errorJson === "string" ? errorJson : body && typeof body.message === "string" ? body.message : null;
|
|
3425
|
-
const driverCode = body && typeof body.code === "string" ? body.code : null;
|
|
3426
|
-
if (driverCode && SQLSTATE.test(driverCode) || looksLikeDriverFailure(body, message)) {
|
|
3427
|
-
return "The step failed.";
|
|
3428
|
-
}
|
|
3429
|
-
return message ? message.slice(0, ERROR_DETAIL_MAX_CHARS) : null;
|
|
3430
|
-
}
|
|
3431
|
-
function summarizeWorkflowError(rawCode, errorJson) {
|
|
3432
|
-
const errorCode = publicWorkflowErrorCode(rawCode);
|
|
3433
|
-
if (!errorCode && (errorJson === null || errorJson === void 0)) {
|
|
3434
|
-
return { error: null, errorCode: null, errorDetail: null };
|
|
3435
|
-
}
|
|
3436
|
-
const error = errorCode && PUBLIC_ERROR_SUMMARIES[errorCode] || "The workflow failed.";
|
|
3437
|
-
const body = errorJson && typeof errorJson === "object" ? errorJson : null;
|
|
3438
|
-
const message = typeof errorJson === "string" ? errorJson : body && typeof body.message === "string" ? body.message : null;
|
|
3439
|
-
const driverCode = body && typeof body.code === "string" ? body.code : null;
|
|
3440
|
-
const userThrown = errorCode === "workflow_error" && !(driverCode && SQLSTATE.test(driverCode)) && !looksLikeDriverFailure(body, message);
|
|
3441
|
-
return {
|
|
3442
|
-
error,
|
|
3443
|
-
errorCode,
|
|
3444
|
-
errorDetail: userThrown && message ? message.slice(0, ERROR_DETAIL_MAX_CHARS) : null
|
|
3445
|
-
};
|
|
3446
|
-
}
|
|
3447
|
-
function publicV2Status(status) {
|
|
3448
|
-
if (status === "completed" || status === "failed" || status === "cancelled") return status;
|
|
3449
|
-
if (status === "running") return "running";
|
|
3450
|
-
return "pending";
|
|
3451
|
-
}
|
|
3452
|
-
function publicV2DerivedStatus(status) {
|
|
3453
|
-
if (status === "queued" || status === "waiting" || status === "sleeping") return status;
|
|
3454
|
-
return publicV2Status(status);
|
|
3455
|
-
}
|
|
3456
|
-
function mapV2WorkflowSummary(row) {
|
|
3457
|
-
const summary = summarizeWorkflowError(
|
|
3458
|
-
row.status === "cancelled" ? "cancelled" : row.error_code,
|
|
3459
|
-
parseJsonField(row.error_json)
|
|
3460
|
-
);
|
|
3461
|
-
return {
|
|
3462
|
-
id: row.id,
|
|
3463
|
-
name: row.workflow_name,
|
|
3464
|
-
status: publicV2Status(row.status),
|
|
3465
|
-
derivedStatus: publicV2DerivedStatus(row.status),
|
|
3466
|
-
currentStep: row.current_step_key,
|
|
3467
|
-
error: summary.error,
|
|
3468
|
-
errorCode: summary.errorCode,
|
|
3469
|
-
errorDetail: summary.errorDetail,
|
|
3470
|
-
retryCount: row.retry_count,
|
|
3471
|
-
maxRetries: row.max_retries,
|
|
3472
|
-
maxDurationMs: Number(row.max_active_duration_ms),
|
|
3473
|
-
startedAt: toIsoString(row.created_at),
|
|
3474
|
-
updatedAt: toIsoString(row.updated_at),
|
|
3475
|
-
completedAt: toOptionalIsoString(row.completed_at)
|
|
3476
|
-
};
|
|
3477
|
-
}
|
|
3478
|
-
var BRANCH_STEP_KEY = /^parallel#\d+\/b\d+$/;
|
|
3479
|
-
function publicV2StepKind(row) {
|
|
3480
|
-
if (row.command_kind === "sleep" || row.command_kind === "wait") return row.command_kind;
|
|
3481
|
-
if (row.command_kind !== "step") return void 0;
|
|
3482
|
-
return BRANCH_STEP_KEY.test(row.step_key) ? "branch" : "step";
|
|
3483
|
-
}
|
|
3484
|
-
function mapV2WorkflowStep(row) {
|
|
3485
|
-
const error = parseJsonField(row.error_json);
|
|
3486
|
-
return {
|
|
3487
|
-
name: row.step_key,
|
|
3488
|
-
kind: publicV2StepKind(row),
|
|
3489
|
-
status: row.status === "running" || row.status === "failed" || row.status === "completed" || row.status === "cancelled" ? row.status : row.status === "skipped" ? "completed" : "pending",
|
|
3490
|
-
output: row.output_codec === "envelope" ? deserializeWorkflowValue(parseJsonField(row.output_json)) : parseJsonField(row.output_json),
|
|
3491
|
-
error: publicStepError(error),
|
|
3492
|
-
startedAt: toOptionalIsoString(row.started_at),
|
|
3493
|
-
updatedAt: toIsoString(row.updated_at),
|
|
3494
|
-
completedAt: toOptionalIsoString(row.completed_at)
|
|
3495
|
-
};
|
|
3496
|
-
}
|
|
3497
|
-
|
|
3498
|
-
// ../core/src/workflows-cancel-api.ts
|
|
3499
|
-
import { sql as sql7 } from "drizzle-orm";
|
|
3500
|
-
function rowsOf(result) {
|
|
3501
|
-
if (Array.isArray(result)) return result;
|
|
3502
|
-
const rows4 = result?.rows;
|
|
3503
|
-
return Array.isArray(rows4) ? rows4 : [];
|
|
3504
|
-
}
|
|
3505
|
-
function buildWorkflowCancelDefinition() {
|
|
3506
|
-
return {
|
|
3507
|
-
name: "workflows.cancel",
|
|
3508
|
-
argsSchema: { id: v.string() },
|
|
3509
|
-
isPublic: true,
|
|
3510
|
-
handler: async (ctx, args) => {
|
|
3511
|
-
const viewerId = ctx.auth.requireAuth().id;
|
|
3512
|
-
const notFound = { ok: false, workflowId: args.id, status: "not_found" };
|
|
3513
|
-
let run;
|
|
3514
|
-
try {
|
|
3515
|
-
run = rowsOf(
|
|
3516
|
-
await ctx.unsafeDb.execute(
|
|
3517
|
-
sql7`SELECT id, user_id, status, completed_at FROM _gencow_workflow_runs_v2 WHERE id = ${args.id} LIMIT 1`
|
|
3518
|
-
)
|
|
3519
|
-
)[0];
|
|
3520
|
-
} catch (error) {
|
|
3521
|
-
const wrapped = error;
|
|
3522
|
-
if (wrapped?.code !== "42P01" && wrapped?.cause?.code !== "42P01") throw error;
|
|
3523
|
-
}
|
|
3524
|
-
if (!run) {
|
|
3525
|
-
const legacy = await ctx.unsafeDb.execute(sql7`SELECT id, status FROM _gencow_workflows WHERE id = ${args.id} AND user_id = ${viewerId} LIMIT 1`).then((result) => rowsOf(result)[0] ?? null).catch(() => null);
|
|
3526
|
-
if (!legacy) return notFound;
|
|
3527
|
-
const finished = legacy.status === "completed" || legacy.status === "failed";
|
|
3528
|
-
return finished ? { ok: true, workflowId: args.id, status: "already_terminal" } : { ok: false, workflowId: args.id, status: "not_cancellable" };
|
|
3529
|
-
}
|
|
3530
|
-
if (!run.user_id || run.user_id !== viewerId) return notFound;
|
|
3531
|
-
if (run.completed_at !== null || ["completed", "failed", "cancelled"].includes(run.status)) {
|
|
3532
|
-
return { ok: true, workflowId: run.id, status: "already_terminal" };
|
|
3533
|
-
}
|
|
3534
|
-
const updated = rowsOf(
|
|
3535
|
-
await ctx.unsafeDb.execute(sql7`
|
|
3536
|
-
WITH marked AS (
|
|
3537
|
-
UPDATE _gencow_workflow_runs_v2
|
|
3538
|
-
SET cancel_requested_at = COALESCE(cancel_requested_at, NOW()), updated_at = NOW(),
|
|
3539
|
-
idempotency_key = NULL
|
|
3540
|
-
WHERE id = ${run.id} AND user_id = ${viewerId} AND completed_at IS NULL
|
|
3541
|
-
RETURNING id
|
|
3542
|
-
)
|
|
3543
|
-
SELECT id, pg_notify(${WORKFLOW_WAKE_SIGNAL_CHANNEL}, ${WORKFLOW_WAKE_SIGNAL_PAYLOAD}) FROM marked
|
|
3544
|
-
`)
|
|
3545
|
-
);
|
|
3546
|
-
if (updated.length === 0) return { ok: true, workflowId: run.id, status: "already_terminal" };
|
|
3547
|
-
return { ok: true, workflowId: run.id, status: "cancel_requested" };
|
|
3548
|
-
}
|
|
3549
|
-
};
|
|
3550
|
-
}
|
|
3551
|
-
|
|
3552
|
-
// ../core/src/workflows-api.ts
|
|
3553
|
-
var WORKFLOW_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed", "cancelled"]);
|
|
3554
|
-
var WORKFLOW_DERIVED_PENDING_STATUSES = /* @__PURE__ */ new Set(["queued", "waiting", "sleeping"]);
|
|
3555
|
-
function rowsFromResult2(result) {
|
|
3556
|
-
if (Array.isArray(result)) return result;
|
|
3557
|
-
if (result && typeof result === "object" && Array.isArray(result.rows)) {
|
|
3558
|
-
return result.rows;
|
|
3559
|
-
}
|
|
3560
|
-
return [];
|
|
3561
|
-
}
|
|
3562
|
-
function mapWorkflowSummary(row) {
|
|
3563
|
-
return {
|
|
3564
|
-
id: row.id,
|
|
3565
|
-
name: row.name,
|
|
3566
|
-
status: publicV1WorkflowStatus(row.status, row.error_code),
|
|
3567
|
-
derivedStatus: deriveWorkflowStatus(publicV1WorkflowStatus(row.status, row.error_code), row.current_step),
|
|
3568
|
-
currentStep: row.current_step,
|
|
3569
|
-
error: row.error,
|
|
3570
|
-
errorCode: publicWorkflowErrorCode(row.error_code),
|
|
3571
|
-
retryCount: row.retry_count,
|
|
3572
|
-
maxRetries: row.max_retries,
|
|
3573
|
-
maxDurationMs: Number(row.max_duration_ms),
|
|
3574
|
-
startedAt: toIsoString(row.started_at),
|
|
3575
|
-
updatedAt: toIsoString(row.updated_at),
|
|
3576
|
-
completedAt: toOptionalIsoString(row.completed_at)
|
|
3577
|
-
};
|
|
3578
|
-
}
|
|
3579
|
-
function mapJoinedWorkflowSummary(row) {
|
|
3580
|
-
if (!row.v2_id) return mapWorkflowSummary(row);
|
|
3581
|
-
return mapV2WorkflowSummary({
|
|
3582
|
-
id: row.v2_id,
|
|
3583
|
-
workflow_name: row.v2_name,
|
|
3584
|
-
status: row.v2_status,
|
|
3585
|
-
args_json: null,
|
|
3586
|
-
result_json: null,
|
|
3587
|
-
error_json: row.v2_error_json,
|
|
3588
|
-
error_code: row.v2_error_code,
|
|
3589
|
-
current_step_key: row.v2_current_step,
|
|
3590
|
-
retry_count: row.v2_retry_count,
|
|
3591
|
-
max_retries: row.v2_max_retries,
|
|
3592
|
-
max_active_duration_ms: row.v2_max_duration_ms,
|
|
3593
|
-
created_at: row.v2_created_at,
|
|
3594
|
-
updated_at: row.v2_updated_at,
|
|
3595
|
-
completed_at: row.v2_completed_at,
|
|
3596
|
-
user_id: null
|
|
3597
|
-
});
|
|
3598
|
-
}
|
|
3599
|
-
function mapWorkflowStep(row) {
|
|
3600
|
-
return {
|
|
3601
|
-
name: row.step_name,
|
|
3602
|
-
status: row.status,
|
|
3603
|
-
output: deserializeWorkflowValue(parseJsonField(row.output)),
|
|
3604
|
-
error: row.error,
|
|
3605
|
-
startedAt: toOptionalIsoString(row.started_at),
|
|
3606
|
-
updatedAt: toIsoString(row.updated_at),
|
|
3607
|
-
completedAt: toOptionalIsoString(row.completed_at)
|
|
3608
|
-
};
|
|
3609
|
-
}
|
|
3610
|
-
function normalizeListLimit(limit) {
|
|
3611
|
-
if (limit == null) return 20;
|
|
3612
|
-
if (!Number.isFinite(limit)) {
|
|
3613
|
-
throw new GencowValidationError(`Argument "limit": expected a finite number, got ${limit}`);
|
|
3614
|
-
}
|
|
3615
|
-
return Math.max(1, Math.min(100, Math.floor(limit)));
|
|
3616
|
-
}
|
|
3617
|
-
function normalizeStatus(status) {
|
|
3618
|
-
if (status == null) return void 0;
|
|
3619
|
-
if (!WORKFLOW_STATUSES.has(status)) {
|
|
3620
|
-
throw new GencowValidationError(`Argument "status": expected one of pending, running, completed, failed`);
|
|
3621
|
-
}
|
|
3622
|
-
return status;
|
|
3623
|
-
}
|
|
3624
|
-
function normalizeDerivedStatus(status) {
|
|
3625
|
-
if (status == null) return void 0;
|
|
3626
|
-
if (WORKFLOW_DERIVED_PENDING_STATUSES.has(status)) {
|
|
3627
|
-
return status;
|
|
3628
|
-
}
|
|
3629
|
-
return normalizeStatus(status);
|
|
3630
|
-
}
|
|
3631
|
-
async function ensureWorkflowRealtimeToken(db, workflowId, currentToken) {
|
|
3632
|
-
if (currentToken && currentToken.trim() !== "") return currentToken;
|
|
3633
|
-
const nextToken = createWorkflowRealtimeToken();
|
|
3634
|
-
const updateResult = await db.execute(sql8`
|
|
3635
|
-
UPDATE _gencow_workflows
|
|
3636
|
-
SET realtime_token = ${nextToken}
|
|
3637
|
-
WHERE id = ${workflowId}
|
|
3638
|
-
AND (realtime_token IS NULL OR realtime_token = '')
|
|
3639
|
-
RETURNING realtime_token
|
|
3640
|
-
`);
|
|
3641
|
-
const updatedToken = rowsFromResult2(updateResult)[0]?.realtime_token ?? null;
|
|
3642
|
-
if (updatedToken && updatedToken.trim() !== "") return updatedToken;
|
|
3643
|
-
const rereadResult = await db.execute(sql8`
|
|
3644
|
-
SELECT realtime_token
|
|
3645
|
-
FROM _gencow_workflows
|
|
3646
|
-
WHERE id = ${workflowId}
|
|
3647
|
-
LIMIT 1
|
|
3648
|
-
`);
|
|
3649
|
-
const rereadToken = rowsFromResult2(rereadResult)[0]?.realtime_token ?? null;
|
|
3650
|
-
return rereadToken && rereadToken.trim() !== "" ? rereadToken : null;
|
|
3651
|
-
}
|
|
3652
|
-
async function loadWorkflowSignalTarget(db, workflowId) {
|
|
3653
|
-
try {
|
|
3654
|
-
const result = await db.execute(sql8`
|
|
3655
|
-
SELECT
|
|
3656
|
-
id,
|
|
3657
|
-
name,
|
|
3658
|
-
status,
|
|
3659
|
-
current_step,
|
|
3660
|
-
user_id
|
|
3661
|
-
FROM _gencow_workflows
|
|
3662
|
-
WHERE id = ${workflowId}
|
|
3663
|
-
LIMIT 1
|
|
3664
|
-
`);
|
|
3665
|
-
return rowsFromResult2(result)[0] ?? null;
|
|
3666
|
-
} catch (error) {
|
|
3667
|
-
if (isMissingWorkflowV1Table(error)) return null;
|
|
3668
|
-
throw error;
|
|
3669
|
-
}
|
|
3670
|
-
}
|
|
3671
|
-
function isMissingWorkflowV2PayloadSchemaError(error) {
|
|
3672
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
3673
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
3674
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
3675
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
3676
|
-
return code === "42P01" || causeCode === "42P01" || message.includes('relation "_gencow_workflow_runs_v2" does not exist') || message.includes("relation _gencow_workflow_runs_v2 does not exist") || message.includes('relation "_gencow_workflow_steps_v2" does not exist') || message.includes("relation _gencow_workflow_steps_v2 does not exist");
|
|
3677
|
-
}
|
|
3678
|
-
function isMissingWorkflowV1Table(error) {
|
|
3679
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
3680
|
-
const message = `${error instanceof Error ? error.message : String(error)} ${cause instanceof Error ? cause.message : String(cause ?? "")}`;
|
|
3681
|
-
return /relation "?_gencow_workflows"? does not exist|relation "?_gencow_workflow_steps"? does not exist|relation "?_gencow_workflow_events"? does not exist/.test(
|
|
3682
|
-
message
|
|
3683
|
-
);
|
|
3684
|
-
}
|
|
3685
|
-
async function loadWorkflowV2Run(db, workflowId) {
|
|
3686
|
-
try {
|
|
3687
|
-
const result = await db.execute(sql8`
|
|
3688
|
-
SELECT id, workflow_name, status, args_json, result_json, error_json, error_code,
|
|
3689
|
-
current_step_key, retry_count, max_retries, max_active_duration_ms,
|
|
3690
|
-
created_at, updated_at, completed_at, user_id
|
|
3691
|
-
FROM _gencow_workflow_runs_v2
|
|
3692
|
-
WHERE id = ${workflowId}
|
|
3693
|
-
LIMIT 1
|
|
3694
|
-
`);
|
|
3695
|
-
return rowsFromResult2(result)[0] ?? null;
|
|
3696
|
-
} catch (error) {
|
|
3697
|
-
if (isMissingWorkflowV2PayloadSchemaError(error)) return null;
|
|
3698
|
-
throw error;
|
|
3699
|
-
}
|
|
3700
|
-
}
|
|
3701
|
-
function isMissingWorkflowV2JournalColumnError(error) {
|
|
3702
|
-
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
3703
|
-
const cause = error && typeof error === "object" && "cause" in error ? error.cause : null;
|
|
3704
|
-
const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
3705
|
-
return code === "42703" || causeCode === "42703";
|
|
3706
|
-
}
|
|
3707
|
-
async function loadWorkflowV2Steps(db, workflowId) {
|
|
3708
|
-
try {
|
|
3709
|
-
try {
|
|
3710
|
-
const stepResult = await db.execute(sql8`
|
|
3711
|
-
SELECT step_key, status, command_kind, output_json, output_codec, error_json, started_at, updated_at, completed_at
|
|
3712
|
-
FROM _gencow_workflow_steps_v2
|
|
3713
|
-
WHERE run_id = ${workflowId}
|
|
3714
|
-
AND (command_kind IS NULL OR command_kind = 'step')
|
|
3715
|
-
ORDER BY step_index ASC, COALESCE(started_at, updated_at) ASC, step_key ASC
|
|
3716
|
-
`);
|
|
3717
|
-
return rowsFromResult2(stepResult);
|
|
3718
|
-
} catch (error) {
|
|
3719
|
-
if (!isMissingWorkflowV2JournalColumnError(error)) throw error;
|
|
3720
|
-
const stepResult = await db.execute(sql8`
|
|
3721
|
-
SELECT step_key, status, output_json, error_json, started_at, updated_at, completed_at
|
|
3722
|
-
FROM _gencow_workflow_steps_v2
|
|
3723
|
-
WHERE run_id = ${workflowId}
|
|
3724
|
-
ORDER BY step_index ASC, COALESCE(started_at, updated_at) ASC, step_key ASC
|
|
3725
|
-
`);
|
|
3726
|
-
return rowsFromResult2(stepResult);
|
|
3727
|
-
}
|
|
3728
|
-
} catch (error) {
|
|
3729
|
-
if (isMissingWorkflowV2PayloadSchemaError(error)) return [];
|
|
3730
|
-
throw error;
|
|
3731
|
-
}
|
|
3732
|
-
}
|
|
3733
|
-
async function mirrorWorkflowV2SignalToV1(options) {
|
|
3734
|
-
try {
|
|
3735
|
-
await options.db.execute(sql8`
|
|
3736
|
-
INSERT INTO _gencow_workflow_events (id, workflow_id, event_name, payload)
|
|
3737
|
-
SELECT ${options.signalId}, workflow.id, ${options.event}, NULL
|
|
3738
|
-
FROM _gencow_workflows workflow
|
|
3739
|
-
WHERE workflow.id = ${options.workflowId}
|
|
3740
|
-
ON CONFLICT (id) DO NOTHING
|
|
3741
|
-
`);
|
|
3742
|
-
} catch (error) {
|
|
3743
|
-
if (!isMissingWorkflowV1Table(error)) {
|
|
3744
|
-
console.warn("Workflow V1 signal mirror failed", { signalId: options.signalId });
|
|
3745
|
-
}
|
|
3746
|
-
}
|
|
3747
|
-
}
|
|
3748
|
-
async function loadWorkflowSnapshot(db, workflowId, options) {
|
|
3749
|
-
const v2Run = await loadWorkflowV2Run(db, workflowId);
|
|
3750
|
-
let workflowResult;
|
|
3751
|
-
try {
|
|
3752
|
-
workflowResult = await db.execute(sql8`
|
|
3753
|
-
SELECT
|
|
3754
|
-
id,
|
|
3755
|
-
name,
|
|
3756
|
-
args,
|
|
3757
|
-
status,
|
|
3758
|
-
current_step,
|
|
3759
|
-
result,
|
|
3760
|
-
error,
|
|
3761
|
-
error_code,
|
|
3762
|
-
retry_count,
|
|
3763
|
-
max_retries,
|
|
3764
|
-
max_duration_ms,
|
|
3765
|
-
started_at,
|
|
3766
|
-
updated_at,
|
|
3767
|
-
completed_at,
|
|
3768
|
-
realtime_token,
|
|
3769
|
-
user_id
|
|
3770
|
-
FROM _gencow_workflows
|
|
3771
|
-
WHERE id = ${workflowId}
|
|
3772
|
-
LIMIT 1
|
|
3773
|
-
`);
|
|
3774
|
-
} catch (error) {
|
|
3775
|
-
if (!v2Run || !isMissingWorkflowV1Table(error)) throw error;
|
|
3776
|
-
workflowResult = [];
|
|
3777
|
-
}
|
|
3778
|
-
const row = rowsFromResult2(workflowResult)[0] ?? null;
|
|
3779
|
-
if (!v2Run && !row) return null;
|
|
3780
|
-
const viewerUserId = options?.viewerUserId ?? null;
|
|
3781
|
-
const ownerId = v2Run ? v2Run.user_id : row?.user_id;
|
|
3782
|
-
if (options?.requireViewerMatch && ownerId && ownerId !== viewerUserId) {
|
|
3783
|
-
return null;
|
|
3784
|
-
}
|
|
3785
|
-
const realtimeToken = row ? await ensureWorkflowRealtimeToken(db, workflowId, row.realtime_token) : v2Run?.id ?? null;
|
|
3786
|
-
if (!realtimeToken) return null;
|
|
3787
|
-
const v2Steps = v2Run ? await loadWorkflowV2Steps(db, workflowId) : [];
|
|
3788
|
-
let steps = v2Steps.map(mapV2WorkflowStep);
|
|
3789
|
-
if (steps.length === 0) {
|
|
3790
|
-
let stepsResult;
|
|
3791
|
-
try {
|
|
3792
|
-
stepsResult = await db.execute(sql8`
|
|
3793
|
-
SELECT
|
|
3794
|
-
step_name,
|
|
3795
|
-
status,
|
|
3796
|
-
output,
|
|
3797
|
-
error,
|
|
3798
|
-
started_at,
|
|
3799
|
-
updated_at,
|
|
3800
|
-
completed_at
|
|
3801
|
-
FROM _gencow_workflow_steps
|
|
3802
|
-
WHERE workflow_id = ${workflowId}
|
|
3803
|
-
ORDER BY COALESCE(started_at, updated_at) ASC, step_name ASC
|
|
3804
|
-
`);
|
|
3805
|
-
} catch (error) {
|
|
3806
|
-
if (!v2Run || !isMissingWorkflowV1Table(error)) throw error;
|
|
3807
|
-
stepsResult = [];
|
|
3808
|
-
}
|
|
3809
|
-
steps = rowsFromResult2(stepsResult).map(mapWorkflowStep);
|
|
3810
|
-
}
|
|
3811
|
-
return {
|
|
3812
|
-
...v2Run ? mapV2WorkflowSummary(v2Run) : mapWorkflowSummary(row),
|
|
3813
|
-
args: deserializeWorkflowValue(parseJsonField(v2Run ? v2Run.args_json : row.args)),
|
|
3814
|
-
result: v2Run ? parseJsonField(v2Run.result_json) : deserializeWorkflowValue(parseJsonField(row.result)),
|
|
3815
|
-
steps,
|
|
3816
|
-
realtimeKey: getWorkflowRealtimeKey(workflowId, realtimeToken)
|
|
3817
|
-
};
|
|
3818
|
-
}
|
|
3819
|
-
function buildWorkflowBuiltinDefinitions() {
|
|
3820
|
-
const get = {
|
|
3821
|
-
key: "workflows.get",
|
|
3822
|
-
argsSchema: { id: v.string() },
|
|
3823
|
-
isPublic: true,
|
|
3824
|
-
handler: async (ctx, args) => {
|
|
3825
|
-
return loadWorkflowSnapshot(ctx.unsafeDb, args.id, {
|
|
3826
|
-
viewerUserId: ctx.auth.getUserIdentity()?.id ?? null,
|
|
3827
|
-
requireViewerMatch: true
|
|
3828
|
-
});
|
|
3829
|
-
}
|
|
3830
|
-
};
|
|
3831
|
-
const signal = {
|
|
3832
|
-
name: "workflows.signal",
|
|
3833
|
-
argsSchema: {
|
|
3834
|
-
id: v.string(),
|
|
3835
|
-
event: v.string(),
|
|
3836
|
-
payload: v.optional(v.any()),
|
|
3837
|
-
idempotencyKey: v.optional(v.string())
|
|
3838
|
-
},
|
|
3839
|
-
isPublic: true,
|
|
3840
|
-
handler: async (ctx, args) => {
|
|
3841
|
-
const normalizedEvent = args.event.trim();
|
|
3842
|
-
if (!normalizedEvent) {
|
|
3843
|
-
throw new GencowValidationError(`Argument "event": expected a non-empty string`);
|
|
3844
|
-
}
|
|
3845
|
-
const v2Run = await loadWorkflowV2Run(ctx.unsafeDb, args.id);
|
|
3846
|
-
const workflow2 = await loadWorkflowSignalTarget(ctx.unsafeDb, args.id);
|
|
3847
|
-
const viewerUserId = ctx.auth.getUserIdentity()?.id ?? null;
|
|
3848
|
-
const ownerId = v2Run ? v2Run.user_id : workflow2?.user_id;
|
|
3849
|
-
if (!v2Run && !workflow2 || ownerId && ownerId !== viewerUserId) {
|
|
3850
|
-
return {
|
|
3851
|
-
ok: false,
|
|
3852
|
-
workflowId: args.id,
|
|
3853
|
-
event: normalizedEvent,
|
|
3854
|
-
scheduledJobId: null
|
|
3855
|
-
};
|
|
3856
|
-
}
|
|
3857
|
-
const workflowId = v2Run?.id ?? workflow2.id;
|
|
3858
|
-
const workflowName = v2Run?.workflow_name ?? workflow2.name;
|
|
3859
|
-
if (v2Run ? v2Run.status === "completed" || v2Run.status === "failed" || v2Run.status === "cancelled" || v2Run.completed_at !== null : workflow2.status === "completed" || workflow2.status === "failed") {
|
|
3860
|
-
return {
|
|
3861
|
-
ok: false,
|
|
3862
|
-
workflowId,
|
|
3863
|
-
event: normalizedEvent,
|
|
3864
|
-
scheduledJobId: null
|
|
3865
|
-
};
|
|
3866
|
-
}
|
|
3867
|
-
const persistedPayload = serializeWorkflowValue(args.payload);
|
|
3868
|
-
assertWorkflowPayloadWithinLimit({
|
|
3869
|
-
workflowName,
|
|
3870
|
-
kind: "signal",
|
|
3871
|
-
serializedValue: persistedPayload
|
|
3872
|
-
});
|
|
3873
|
-
const signalId = crypto.randomUUID();
|
|
3874
|
-
const idempotencyKey = normalizeWorkflowIdempotencyKey(args.idempotencyKey);
|
|
3875
|
-
if (v2Run) {
|
|
3876
|
-
const recordedV2 = await tryRecordWorkflowV2Signal({
|
|
3877
|
-
db: ctx.unsafeDb,
|
|
3878
|
-
workflowId,
|
|
3879
|
-
event: normalizedEvent,
|
|
3880
|
-
signalId,
|
|
3881
|
-
payload: persistedPayload,
|
|
3882
|
-
idempotencyKey
|
|
3883
|
-
});
|
|
3884
|
-
if (recordedV2 === "duplicate") {
|
|
3885
|
-
return { ok: true, workflowId, event: normalizedEvent, scheduledJobId: null, deduplicated: true };
|
|
3886
|
-
}
|
|
3887
|
-
if (recordedV2 !== "accepted") {
|
|
3888
|
-
return { ok: false, workflowId, event: normalizedEvent, scheduledJobId: null };
|
|
3889
|
-
}
|
|
3890
|
-
if (workflow2) {
|
|
3891
|
-
await mirrorWorkflowV2SignalToV1({
|
|
3892
|
-
db: ctx.unsafeDb,
|
|
3893
|
-
workflowId,
|
|
3894
|
-
event: normalizedEvent,
|
|
3895
|
-
signalId
|
|
3896
|
-
});
|
|
3897
|
-
}
|
|
3898
|
-
} else {
|
|
3899
|
-
await ctx.unsafeDb.execute(sql8`
|
|
3900
|
-
INSERT INTO _gencow_workflow_events (
|
|
3901
|
-
id,
|
|
3902
|
-
workflow_id,
|
|
3903
|
-
event_name,
|
|
3904
|
-
payload
|
|
3905
|
-
)
|
|
3906
|
-
VALUES (
|
|
3907
|
-
${signalId},
|
|
3908
|
-
${workflowId},
|
|
3909
|
-
${normalizedEvent},
|
|
3910
|
-
${workflowJsonb(persistedPayload)}
|
|
3911
|
-
)
|
|
3912
|
-
`);
|
|
3913
|
-
}
|
|
3914
|
-
let scheduledJobId = null;
|
|
3915
|
-
if (workflow2?.status === "pending" && workflow2.current_step?.startsWith("wait:")) {
|
|
3916
|
-
try {
|
|
3917
|
-
scheduledJobId = ctx.scheduler.runAfter(0, getWorkflowResumeActionName(workflowName), {
|
|
3918
|
-
workflowId
|
|
3919
|
-
});
|
|
3920
|
-
} catch {
|
|
3921
|
-
scheduledJobId = null;
|
|
3922
|
-
}
|
|
3923
|
-
}
|
|
3924
|
-
return {
|
|
3925
|
-
ok: true,
|
|
3926
|
-
workflowId,
|
|
3927
|
-
event: normalizedEvent,
|
|
3928
|
-
scheduledJobId
|
|
3929
|
-
};
|
|
3930
|
-
}
|
|
3931
|
-
};
|
|
3932
|
-
const list = {
|
|
3933
|
-
key: "workflows.list",
|
|
3934
|
-
argsSchema: {
|
|
3935
|
-
limit: v.optional(v.number()),
|
|
3936
|
-
status: v.optional(v.string())
|
|
3937
|
-
},
|
|
3938
|
-
isPublic: false,
|
|
3939
|
-
handler: async (ctx, args) => {
|
|
3940
|
-
const userId = ctx.auth.requireAuth().id;
|
|
3941
|
-
const limit = normalizeListLimit(args.limit);
|
|
3942
|
-
const requestedStatus = normalizeDerivedStatus(args.status);
|
|
3943
|
-
const v1Derived = sql8`CASE WHEN w.status = 'pending' AND w.current_step LIKE 'sleep#%' THEN 'sleeping'
|
|
3944
|
-
WHEN w.status = 'pending' AND w.current_step LIKE 'wait:%' THEN 'waiting'
|
|
3945
|
-
WHEN w.status = 'pending' THEN 'queued'
|
|
3946
|
-
WHEN w.status = 'failed' AND w.error_code = 'cancelled' THEN 'cancelled' ELSE w.status END`;
|
|
3947
|
-
const effectiveStatus = sql8`CASE WHEN v.id IS NOT NULL THEN
|
|
3948
|
-
CASE WHEN v.status IN ('queued', 'waiting', 'sleeping') THEN 'pending'
|
|
3949
|
-
ELSE v.status END
|
|
3950
|
-
ELSE CASE WHEN w.status = 'failed' AND w.error_code = 'cancelled' THEN 'cancelled' ELSE w.status END END`;
|
|
3951
|
-
const effectiveDerived = sql8`CASE WHEN v.id IS NOT NULL THEN
|
|
3952
|
-
v.status
|
|
3953
|
-
ELSE ${v1Derived} END`;
|
|
3954
|
-
const statusForFilter = requestedStatus === "pending" ? effectiveStatus : effectiveDerived;
|
|
3955
|
-
const v1StatusForFilter = requestedStatus === "pending" ? sql8`w.status` : v1Derived;
|
|
3956
|
-
try {
|
|
3957
|
-
const result = await ctx.unsafeDb.execute(sql8`
|
|
3958
|
-
SELECT w.*, v.id AS v2_id, v.workflow_name AS v2_name,
|
|
3959
|
-
v.status AS v2_status, v.error_json AS v2_error_json,
|
|
3960
|
-
v.error_code AS v2_error_code, v.current_step_key AS v2_current_step,
|
|
3961
|
-
v.retry_count AS v2_retry_count, v.max_retries AS v2_max_retries,
|
|
3962
|
-
v.max_active_duration_ms AS v2_max_duration_ms,
|
|
3963
|
-
v.created_at AS v2_created_at, v.updated_at AS v2_updated_at,
|
|
3964
|
-
v.completed_at AS v2_completed_at
|
|
3965
|
-
FROM _gencow_workflows w
|
|
3966
|
-
FULL OUTER JOIN _gencow_workflow_runs_v2 v ON v.id = w.id
|
|
3967
|
-
WHERE (CASE WHEN v.id IS NOT NULL THEN v.user_id ELSE w.user_id END) = ${userId}
|
|
3968
|
-
AND (${requestedStatus ?? null}::text IS NULL OR ${statusForFilter} = ${requestedStatus ?? null})
|
|
3969
|
-
ORDER BY COALESCE(v.created_at, w.started_at) DESC, COALESCE(v.id, w.id) DESC
|
|
3970
|
-
LIMIT ${limit}
|
|
3971
|
-
`);
|
|
3972
|
-
return rowsFromResult2(result).map(mapJoinedWorkflowSummary);
|
|
3973
|
-
} catch (error) {
|
|
3974
|
-
if (isMissingWorkflowV1Table(error)) {
|
|
3975
|
-
const v2StatusForFilter = requestedStatus === "pending" ? sql8`CASE WHEN status IN ('queued', 'waiting', 'sleeping') THEN 'pending' ELSE status END` : sql8`status`;
|
|
3976
|
-
const result2 = await ctx.unsafeDb.execute(sql8`
|
|
3977
|
-
SELECT id, workflow_name, status, args_json, result_json, error_json, error_code,
|
|
3978
|
-
current_step_key, retry_count, max_retries, max_active_duration_ms,
|
|
3979
|
-
created_at, updated_at, completed_at, user_id
|
|
3980
|
-
FROM _gencow_workflow_runs_v2
|
|
3981
|
-
WHERE user_id = ${userId}
|
|
3982
|
-
AND (${requestedStatus ?? null}::text IS NULL OR ${v2StatusForFilter} = ${requestedStatus ?? null})
|
|
3983
|
-
ORDER BY created_at DESC, id DESC
|
|
3984
|
-
LIMIT ${limit}
|
|
3985
|
-
`);
|
|
3986
|
-
return rowsFromResult2(result2).map(mapV2WorkflowSummary);
|
|
3987
|
-
}
|
|
3988
|
-
if (!isMissingWorkflowV2PayloadSchemaError(error)) throw error;
|
|
3989
|
-
const result = await ctx.unsafeDb.execute(sql8`
|
|
3990
|
-
SELECT w.* FROM _gencow_workflows w
|
|
3991
|
-
WHERE w.user_id = ${userId}
|
|
3992
|
-
AND (${requestedStatus ?? null}::text IS NULL OR ${v1StatusForFilter} = ${requestedStatus ?? null})
|
|
3993
|
-
ORDER BY w.started_at DESC, w.id DESC
|
|
3994
|
-
LIMIT ${limit}
|
|
3995
|
-
`);
|
|
3996
|
-
return rowsFromResult2(result).map(mapWorkflowSummary);
|
|
3997
|
-
}
|
|
3998
|
-
}
|
|
3999
|
-
};
|
|
4000
|
-
const definitions = Object.freeze({
|
|
4001
|
-
get: Object.freeze(get),
|
|
4002
|
-
list: Object.freeze(list),
|
|
4003
|
-
signal: Object.freeze(signal),
|
|
4004
|
-
cancel: Object.freeze(buildWorkflowCancelDefinition())
|
|
4005
|
-
});
|
|
4006
|
-
return definitions;
|
|
4007
|
-
}
|
|
4008
2725
|
function createWorkflowBuiltinDefinitions() {
|
|
4009
|
-
return
|
|
2726
|
+
return Object.freeze({
|
|
2727
|
+
get: Object.freeze({
|
|
2728
|
+
key: "workflows.get",
|
|
2729
|
+
argsSchema: { id: v.string() },
|
|
2730
|
+
isPublic: true,
|
|
2731
|
+
handler: (ctx, args) => getWorkflowOperations(ctx).get(ctx, args)
|
|
2732
|
+
}),
|
|
2733
|
+
list: Object.freeze({
|
|
2734
|
+
key: "workflows.list",
|
|
2735
|
+
argsSchema: { limit: v.optional(v.number()), status: v.optional(v.string()) },
|
|
2736
|
+
isPublic: false,
|
|
2737
|
+
handler: (ctx, args) => getWorkflowOperations(ctx).list(ctx, args)
|
|
2738
|
+
}),
|
|
2739
|
+
signal: Object.freeze({
|
|
2740
|
+
name: "workflows.signal",
|
|
2741
|
+
argsSchema: { id: v.string(), event: v.string(), payload: v.optional(v.any()), idempotencyKey: v.optional(v.string()) },
|
|
2742
|
+
isPublic: true,
|
|
2743
|
+
handler: (ctx, args) => getWorkflowOperations(ctx).signal(ctx, args)
|
|
2744
|
+
}),
|
|
2745
|
+
cancel: Object.freeze({
|
|
2746
|
+
name: "workflows.cancel",
|
|
2747
|
+
argsSchema: { id: v.string() },
|
|
2748
|
+
isPublic: true,
|
|
2749
|
+
handler: (ctx, args) => getWorkflowOperations(ctx).cancel(ctx, args)
|
|
2750
|
+
})
|
|
2751
|
+
});
|
|
4010
2752
|
}
|
|
4011
2753
|
function registerWorkflowsApi() {
|
|
4012
2754
|
const registeredDefinitions = globalThis.__gencow_workflowsApiRegistered;
|
|
4013
2755
|
if (registeredDefinitions) return registeredDefinitions;
|
|
4014
|
-
const definitions =
|
|
2756
|
+
const definitions = createWorkflowBuiltinDefinitions();
|
|
4015
2757
|
queryRegistry.set(definitions.get.key, definitions.get);
|
|
4016
2758
|
queryRegistry.set(definitions.list.key, definitions.list);
|
|
4017
2759
|
mutationRegistry.push(definitions.signal);
|
|
@@ -4020,6 +2762,79 @@ function registerWorkflowsApi() {
|
|
|
4020
2762
|
return definitions;
|
|
4021
2763
|
}
|
|
4022
2764
|
|
|
2765
|
+
// ../core/src/workflow-payload-policy.ts
|
|
2766
|
+
var CHECKPOINT_MODE_ENV = "GENCOW_WORKFLOW_CHECKPOINT_LIMIT_MODE";
|
|
2767
|
+
var CHECKPOINT_SOFT_LIMIT_ENV = "GENCOW_WORKFLOW_CHECKPOINT_SOFT_LIMIT_BYTES";
|
|
2768
|
+
var CHECKPOINT_HARD_LIMIT_ENV = "GENCOW_WORKFLOW_CHECKPOINT_HARD_LIMIT_BYTES";
|
|
2769
|
+
var DEFAULT_SOFT_LIMIT_BYTES = 64 * 1024;
|
|
2770
|
+
var DEFAULT_HARD_LIMIT_BYTES = 256 * 1024;
|
|
2771
|
+
var BOOT_ENV_SNAPSHOT = {
|
|
2772
|
+
mode: process.env[CHECKPOINT_MODE_ENV],
|
|
2773
|
+
softLimitBytes: process.env[CHECKPOINT_SOFT_LIMIT_ENV],
|
|
2774
|
+
hardLimitBytes: process.env[CHECKPOINT_HARD_LIMIT_ENV]
|
|
2775
|
+
};
|
|
2776
|
+
var ERROR_CODES = {
|
|
2777
|
+
args: "workflow_args_too_large",
|
|
2778
|
+
signal: "workflow_signal_payload_too_large"
|
|
2779
|
+
};
|
|
2780
|
+
var WorkflowPayloadPolicyError = class extends Error {
|
|
2781
|
+
errorCode;
|
|
2782
|
+
code;
|
|
2783
|
+
status = 413;
|
|
2784
|
+
kind;
|
|
2785
|
+
sizeBytes;
|
|
2786
|
+
hardLimitBytes;
|
|
2787
|
+
constructor(params) {
|
|
2788
|
+
const errorCode = ERROR_CODES[params.kind];
|
|
2789
|
+
super(
|
|
2790
|
+
`${errorCode}: Workflow "${params.workflowName}" ${params.kind} payload is ${params.sizeBytes} bytes, exceeding the ${params.hardLimitBytes} byte hard limit. Store large values in an app table/storage object and pass only an id/reference/count/checksum.`
|
|
2791
|
+
);
|
|
2792
|
+
this.name = "WorkflowPayloadPolicyError";
|
|
2793
|
+
this.errorCode = errorCode;
|
|
2794
|
+
this.code = errorCode;
|
|
2795
|
+
this.kind = params.kind;
|
|
2796
|
+
this.sizeBytes = params.sizeBytes;
|
|
2797
|
+
this.hardLimitBytes = params.hardLimitBytes;
|
|
2798
|
+
}
|
|
2799
|
+
};
|
|
2800
|
+
function normalizeLimit(value, fallback) {
|
|
2801
|
+
if (!value?.trim()) return fallback;
|
|
2802
|
+
const parsed = Number(value);
|
|
2803
|
+
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
|
|
2804
|
+
}
|
|
2805
|
+
function normalizeMode(value) {
|
|
2806
|
+
return value === "platform_enforce" || value === "enforce" ? value : "observe";
|
|
2807
|
+
}
|
|
2808
|
+
function resolveWorkflowPayloadPolicyConfig(env = BOOT_ENV_SNAPSHOT) {
|
|
2809
|
+
const hardLimitBytes = normalizeLimit(env.hardLimitBytes, DEFAULT_HARD_LIMIT_BYTES);
|
|
2810
|
+
return {
|
|
2811
|
+
mode: normalizeMode(env.mode),
|
|
2812
|
+
softLimitBytes: Math.min(normalizeLimit(env.softLimitBytes, DEFAULT_SOFT_LIMIT_BYTES), hardLimitBytes),
|
|
2813
|
+
hardLimitBytes
|
|
2814
|
+
};
|
|
2815
|
+
}
|
|
2816
|
+
function assertWorkflowPayloadWithinLimit(params) {
|
|
2817
|
+
const config = params.config ?? resolveWorkflowPayloadPolicyConfig();
|
|
2818
|
+
const serializedJson = JSON.stringify(params.serializedValue) ?? "null";
|
|
2819
|
+
const sizeBytes = new TextEncoder().encode(serializedJson).byteLength;
|
|
2820
|
+
const level = sizeBytes > config.hardLimitBytes ? "hard_limit" : sizeBytes > config.softLimitBytes ? "soft_limit" : "ok";
|
|
2821
|
+
if (level !== "ok") {
|
|
2822
|
+
(params.logger ?? console).warn(
|
|
2823
|
+
`[workflow] ${params.workflowName} ${params.kind} workflow payload ${level} (sizeBytes=${sizeBytes}, softLimitBytes=${config.softLimitBytes}, hardLimitBytes=${config.hardLimitBytes}, mode=${config.mode}, errorCode=${level === "hard_limit" ? ERROR_CODES[params.kind] : "none"})`
|
|
2824
|
+
);
|
|
2825
|
+
}
|
|
2826
|
+
const enforced = config.mode === "enforce" || config.mode === "platform_enforce" && params.workflowName.startsWith("__gencow.");
|
|
2827
|
+
if (enforced && sizeBytes > config.hardLimitBytes) {
|
|
2828
|
+
throw new WorkflowPayloadPolicyError({
|
|
2829
|
+
workflowName: params.workflowName,
|
|
2830
|
+
kind: params.kind,
|
|
2831
|
+
sizeBytes,
|
|
2832
|
+
hardLimitBytes: config.hardLimitBytes
|
|
2833
|
+
});
|
|
2834
|
+
}
|
|
2835
|
+
return sizeBytes;
|
|
2836
|
+
}
|
|
2837
|
+
|
|
4023
2838
|
// ../core/src/authorization-error.ts
|
|
4024
2839
|
var GencowAuthorizationError = class extends Error {
|
|
4025
2840
|
code = "APP_AUTHORIZATION_DENIED";
|
|
@@ -4367,11 +3182,11 @@ function defineConfig(config) {
|
|
|
4367
3182
|
}
|
|
4368
3183
|
|
|
4369
3184
|
// ../core/src/rls-context-key.ts
|
|
4370
|
-
import { sql
|
|
3185
|
+
import { sql } from "drizzle-orm";
|
|
4371
3186
|
function sessionSettingSqlForKey(sessionKey) {
|
|
4372
3187
|
const guc = sessionKeyToGucName(sessionKey);
|
|
4373
3188
|
const escaped = guc.replace(/'/g, "''");
|
|
4374
|
-
return
|
|
3189
|
+
return sql.raw(`current_setting('${escaped}', true)`);
|
|
4375
3190
|
}
|
|
4376
3191
|
function rlsContextKey(key) {
|
|
4377
3192
|
return sessionSettingSqlForKey(key);
|
|
@@ -4380,11 +3195,11 @@ function rlsContextKeys() {
|
|
|
4380
3195
|
return (key) => rlsContextKey(key);
|
|
4381
3196
|
}
|
|
4382
3197
|
function eqRlsContextColumn(column, key) {
|
|
4383
|
-
return
|
|
3198
|
+
return sql`${column} = ${rlsContextKey(key)}`;
|
|
4384
3199
|
}
|
|
4385
3200
|
|
|
4386
3201
|
// ../core/src/rls-define-table.ts
|
|
4387
|
-
import { sql as
|
|
3202
|
+
import { sql as sql2 } from "drizzle-orm";
|
|
4388
3203
|
import { getTableName } from "drizzle-orm";
|
|
4389
3204
|
import { pgPolicy } from "drizzle-orm/pg-core";
|
|
4390
3205
|
var ALL_COMMANDS = ["select", "insert", "update", "delete"];
|
|
@@ -4396,22 +3211,22 @@ function escapeSqlStringLiteral(value) {
|
|
|
4396
3211
|
return value.replace(/'/g, "''");
|
|
4397
3212
|
}
|
|
4398
3213
|
function sqlStringLiteral(value) {
|
|
4399
|
-
return
|
|
3214
|
+
return sql2.raw(`'${escapeSqlStringLiteral(value)}'`);
|
|
4400
3215
|
}
|
|
4401
3216
|
function andExprs(exprs) {
|
|
4402
|
-
if (exprs.length === 0) return
|
|
3217
|
+
if (exprs.length === 0) return sql2`true`;
|
|
4403
3218
|
if (exprs.length === 1) return exprs[0];
|
|
4404
|
-
return
|
|
4405
|
-
exprs.map((e) =>
|
|
4406
|
-
|
|
3219
|
+
return sql2.join(
|
|
3220
|
+
exprs.map((e) => sql2`(${e})`),
|
|
3221
|
+
sql2` AND `
|
|
4407
3222
|
);
|
|
4408
3223
|
}
|
|
4409
3224
|
function orExprs(exprs) {
|
|
4410
|
-
if (exprs.length === 0) return
|
|
3225
|
+
if (exprs.length === 0) return sql2`false`;
|
|
4411
3226
|
if (exprs.length === 1) return exprs[0];
|
|
4412
|
-
return
|
|
4413
|
-
exprs.map((e) =>
|
|
4414
|
-
|
|
3227
|
+
return sql2.join(
|
|
3228
|
+
exprs.map((e) => sql2`(${e})`),
|
|
3229
|
+
sql2` OR `
|
|
4415
3230
|
);
|
|
4416
3231
|
}
|
|
4417
3232
|
function combinedExprForCommand(constraints, command) {
|
|
@@ -4447,20 +3262,20 @@ var TableRlsBuilder = class _TableRlsBuilder {
|
|
|
4447
3262
|
constraints = [];
|
|
4448
3263
|
readPublicSelect = false;
|
|
4449
3264
|
matchColumn(column, keySql, options) {
|
|
4450
|
-
const expr =
|
|
3265
|
+
const expr = sql2`${column} = ${keySql}`;
|
|
4451
3266
|
this.constraints.push({ commands: normalizeCommands(options?.commands), expr });
|
|
4452
3267
|
return this;
|
|
4453
3268
|
}
|
|
4454
3269
|
sessionEq(keySql, value, options) {
|
|
4455
|
-
const expr =
|
|
3270
|
+
const expr = sql2`${keySql} = ${sqlStringLiteral(stringifySessionValue(value))}`;
|
|
4456
3271
|
this.constraints.push({ commands: normalizeCommands(options?.commands), expr });
|
|
4457
3272
|
return this;
|
|
4458
3273
|
}
|
|
4459
3274
|
sessionIn(keySql, values, options) {
|
|
4460
3275
|
const literals = values.map((v2) => stringifySessionValue(v2));
|
|
4461
|
-
const expr = literals.length === 0 ?
|
|
3276
|
+
const expr = literals.length === 0 ? sql2`false` : sql2`${keySql} IN (${sql2.join(
|
|
4462
3277
|
literals.map((v2) => sqlStringLiteral(v2)),
|
|
4463
|
-
|
|
3278
|
+
sql2`, `
|
|
4464
3279
|
)})`;
|
|
4465
3280
|
this.constraints.push({ commands: normalizeCommands(options?.commands), expr });
|
|
4466
3281
|
return this;
|
|
@@ -4499,17 +3314,17 @@ var TableRlsBuilder = class _TableRlsBuilder {
|
|
|
4499
3314
|
return this.sessionCompare(keySql, "<", n, options);
|
|
4500
3315
|
}
|
|
4501
3316
|
sessionCompare(keySql, op, n, options) {
|
|
4502
|
-
const bound =
|
|
3317
|
+
const bound = sql2.raw(String(n));
|
|
4503
3318
|
const expr = (() => {
|
|
4504
3319
|
switch (op) {
|
|
4505
3320
|
case ">=":
|
|
4506
|
-
return
|
|
3321
|
+
return sql2`(${keySql})::numeric >= ${bound}`;
|
|
4507
3322
|
case ">":
|
|
4508
|
-
return
|
|
3323
|
+
return sql2`(${keySql})::numeric > ${bound}`;
|
|
4509
3324
|
case "<=":
|
|
4510
|
-
return
|
|
3325
|
+
return sql2`(${keySql})::numeric <= ${bound}`;
|
|
4511
3326
|
case "<":
|
|
4512
|
-
return
|
|
3327
|
+
return sql2`(${keySql})::numeric < ${bound}`;
|
|
4513
3328
|
}
|
|
4514
3329
|
})();
|
|
4515
3330
|
this.constraints.push({ commands: normalizeCommands(options?.commands), expr });
|
|
@@ -4548,7 +3363,7 @@ var TableRlsBuilder = class _TableRlsBuilder {
|
|
|
4548
3363
|
policies.push(
|
|
4549
3364
|
pgPolicy(this.policyName(command, counters[command]++), {
|
|
4550
3365
|
for: "select",
|
|
4551
|
-
using:
|
|
3366
|
+
using: sql2`true`
|
|
4552
3367
|
})
|
|
4553
3368
|
);
|
|
4554
3369
|
continue;
|
|
@@ -4612,7 +3427,7 @@ import { pgTable } from "drizzle-orm/pg-core";
|
|
|
4612
3427
|
var pgBaseTable = pgTable;
|
|
4613
3428
|
|
|
4614
3429
|
// ../core/src/rls-db.ts
|
|
4615
|
-
import { sql as
|
|
3430
|
+
import { sql as sql3 } from "drizzle-orm";
|
|
4616
3431
|
|
|
4617
3432
|
// ../core/src/rls-set-config-statement.ts
|
|
4618
3433
|
function buildRlsSetConfigStatement(pairs) {
|
|
@@ -4678,24 +3493,24 @@ function createRlsUnsupportedError(reason = "relations") {
|
|
|
4678
3493
|
nextAction: "EDIT_AND_CHECK"
|
|
4679
3494
|
});
|
|
4680
3495
|
}
|
|
4681
|
-
function assertRlsScopeMayEnter(
|
|
3496
|
+
function assertRlsScopeMayEnter(scope2) {
|
|
4682
3497
|
const active = activeRlsExecution.getStore();
|
|
4683
|
-
if (active?.active && active.scope !==
|
|
3498
|
+
if (active?.active && active.scope !== scope2) {
|
|
4684
3499
|
throw createRlsScopeConflictError();
|
|
4685
3500
|
}
|
|
4686
3501
|
}
|
|
4687
|
-
function currentRlsExecution(
|
|
3502
|
+
function currentRlsExecution(scope2) {
|
|
4688
3503
|
const active = activeRlsExecution.getStore();
|
|
4689
3504
|
if (!active?.active) return void 0;
|
|
4690
|
-
if (active.scope !==
|
|
3505
|
+
if (active.scope !== scope2) throw createRlsScopeConflictError();
|
|
4691
3506
|
return active;
|
|
4692
3507
|
}
|
|
4693
|
-
function matchingRlsExecutionClient(
|
|
3508
|
+
function matchingRlsExecutionClient(scope2) {
|
|
4694
3509
|
const active = activeRlsExecution.getStore();
|
|
4695
|
-
return active?.active && active.scope ===
|
|
3510
|
+
return active?.active && active.scope === scope2 ? active.client : void 0;
|
|
4696
3511
|
}
|
|
4697
|
-
async function runWithRlsScope(
|
|
4698
|
-
const active = { scope, client, active: true, holdsQueue };
|
|
3512
|
+
async function runWithRlsScope(scope2, client, work, holdsQueue = false) {
|
|
3513
|
+
const active = { scope: scope2, client, active: true, holdsQueue };
|
|
4699
3514
|
return activeRlsExecution.run(active, async () => {
|
|
4700
3515
|
try {
|
|
4701
3516
|
return await work();
|
|
@@ -4765,9 +3580,9 @@ function bindToStore(value, store) {
|
|
|
4765
3580
|
contextBoundBuilders.add(proxy);
|
|
4766
3581
|
return proxy;
|
|
4767
3582
|
}
|
|
4768
|
-
function runWithRlsTransactionScope(
|
|
4769
|
-
assertRlsScopeMayEnter(
|
|
4770
|
-
return runWithRlsScope(
|
|
3583
|
+
function runWithRlsTransactionScope(scope2, tx, work) {
|
|
3584
|
+
assertRlsScopeMayEnter(scope2);
|
|
3585
|
+
return runWithRlsScope(scope2, tx.session?.client, work);
|
|
4771
3586
|
}
|
|
4772
3587
|
function createRlsRelationalQueryRegistry(query2, session, baseSession) {
|
|
4773
3588
|
const scopedRegistry = /* @__PURE__ */ Object.create(null);
|
|
@@ -4860,7 +3675,7 @@ function transactionConfigSql(config) {
|
|
|
4860
3675
|
if (typeof value.deferrable !== "boolean") return null;
|
|
4861
3676
|
chunks.push(value.deferrable ? "deferrable" : "not deferrable");
|
|
4862
3677
|
}
|
|
4863
|
-
return chunks.length > 0 ?
|
|
3678
|
+
return chunks.length > 0 ? sql3.raw(`SET TRANSACTION ${chunks.join(", ")}`) : null;
|
|
4864
3679
|
}
|
|
4865
3680
|
async function applyTransactionConfig(tx, config) {
|
|
4866
3681
|
const statement = transactionConfigSql(config);
|
|
@@ -4900,8 +3715,8 @@ async function injectRlsVarsOnTx(tx, rls, onTransactionContextFailure) {
|
|
|
4900
3715
|
try {
|
|
4901
3716
|
const pairs = rlsSetConfigPairs(rls);
|
|
4902
3717
|
if (pairs.length > 0) {
|
|
4903
|
-
const calls = pairs.map(([name, value]) =>
|
|
4904
|
-
await tx.execute(
|
|
3718
|
+
const calls = pairs.map(([name, value]) => sql3`set_config(${name}::text, ${value}::text, true)`);
|
|
3719
|
+
await tx.execute(sql3`select ${sql3.join(calls, sql3`, `)}`);
|
|
4905
3720
|
}
|
|
4906
3721
|
} catch (error) {
|
|
4907
3722
|
try {
|
|
@@ -4911,11 +3726,11 @@ async function injectRlsVarsOnTx(tx, rls, onTransactionContextFailure) {
|
|
|
4911
3726
|
throw error;
|
|
4912
3727
|
}
|
|
4913
3728
|
}
|
|
4914
|
-
async function withRlsLeasedConnection(leased, rls, fn,
|
|
3729
|
+
async function withRlsLeasedConnection(leased, rls, fn, scope2) {
|
|
4915
3730
|
try {
|
|
4916
3731
|
await leased.query("begin");
|
|
4917
3732
|
await applyRlsSessionVars(leased, rls);
|
|
4918
|
-
const result =
|
|
3733
|
+
const result = scope2 ? await runWithRlsScope(scope2, leased, () => fn(leased)) : await fn(leased);
|
|
4919
3734
|
await leased.query("commit");
|
|
4920
3735
|
return result;
|
|
4921
3736
|
} catch (e) {
|
|
@@ -4938,10 +3753,10 @@ function isBunSqlClient(client) {
|
|
|
4938
3753
|
}
|
|
4939
3754
|
async function readConnectionIdentity(client) {
|
|
4940
3755
|
if (!isBunSqlClient(client)) return client;
|
|
4941
|
-
const
|
|
3756
|
+
const rows = await client.unsafe(
|
|
4942
3757
|
"select pg_backend_pid()::text as pid, current_database()::text as db"
|
|
4943
3758
|
);
|
|
4944
|
-
const row = Array.isArray(
|
|
3759
|
+
const row = Array.isArray(rows) ? rows[0] : void 0;
|
|
4945
3760
|
if (!row || typeof row.pid !== "string" || typeof row.db !== "string") {
|
|
4946
3761
|
throw createRlsUnsupportedError("session");
|
|
4947
3762
|
}
|
|
@@ -4976,14 +3791,14 @@ async function withOuterConnectionExclusive(ref, work) {
|
|
|
4976
3791
|
if (outerConnectionQueues.get(key) === tail) outerConnectionQueues.delete(key);
|
|
4977
3792
|
}
|
|
4978
3793
|
}
|
|
4979
|
-
async function withRlsConnection(session, rls, reuseOuterConnection,
|
|
4980
|
-
assertRlsScopeMayEnter(
|
|
3794
|
+
async function withRlsConnection(session, rls, reuseOuterConnection, scope2, fn, queueKey) {
|
|
3795
|
+
assertRlsScopeMayEnter(scope2);
|
|
4981
3796
|
if (reuseOuterConnection) {
|
|
4982
3797
|
const c2 = session.client;
|
|
4983
3798
|
return withOuterConnectionExclusive(
|
|
4984
3799
|
queueKey ?? { client: c2 },
|
|
4985
3800
|
() => runWithRlsScope(
|
|
4986
|
-
|
|
3801
|
+
scope2,
|
|
4987
3802
|
c2,
|
|
4988
3803
|
async () => {
|
|
4989
3804
|
await applyRlsSessionVars(c2, rls);
|
|
@@ -4994,7 +3809,7 @@ async function withRlsConnection(session, rls, reuseOuterConnection, scope, fn,
|
|
|
4994
3809
|
);
|
|
4995
3810
|
}
|
|
4996
3811
|
const c = session.client;
|
|
4997
|
-
const runInner = async (client) => runWithRlsScope(
|
|
3812
|
+
const runInner = async (client) => runWithRlsScope(scope2, client, async () => {
|
|
4998
3813
|
await applyRlsSessionVars(client, rls);
|
|
4999
3814
|
return fn(client);
|
|
5000
3815
|
});
|
|
@@ -5006,7 +3821,7 @@ async function withRlsConnection(session, rls, reuseOuterConnection, scope, fn,
|
|
|
5006
3821
|
}
|
|
5007
3822
|
if (typeof c.connect === "function" && typeof c.query === "function") {
|
|
5008
3823
|
const leased = await c.connect();
|
|
5009
|
-
return withRlsLeasedConnection(leased, rls, fn,
|
|
3824
|
+
return withRlsLeasedConnection(leased, rls, fn, scope2);
|
|
5010
3825
|
}
|
|
5011
3826
|
return runInner(c);
|
|
5012
3827
|
}
|
|
@@ -5050,8 +3865,8 @@ function createPreparedQueryClientExecutors(params) {
|
|
|
5050
3865
|
params.prepareArgs
|
|
5051
3866
|
);
|
|
5052
3867
|
}
|
|
5053
|
-
async function runPreparedQueryWithRls(session, rls, reuseOuterConnection,
|
|
5054
|
-
const active = currentRlsExecution(
|
|
3868
|
+
async function runPreparedQueryWithRls(session, rls, reuseOuterConnection, scope2, queueKey, runOnClient, placeholderValues) {
|
|
3869
|
+
const active = currentRlsExecution(scope2);
|
|
5055
3870
|
if (active && (active.holdsQueue || !reuseOuterConnection)) {
|
|
5056
3871
|
return runOnClient(active.client, placeholderValues);
|
|
5057
3872
|
}
|
|
@@ -5059,12 +3874,12 @@ async function runPreparedQueryWithRls(session, rls, reuseOuterConnection, scope
|
|
|
5059
3874
|
session,
|
|
5060
3875
|
rls,
|
|
5061
3876
|
reuseOuterConnection,
|
|
5062
|
-
|
|
3877
|
+
scope2,
|
|
5063
3878
|
(client) => runOnClient(client, placeholderValues),
|
|
5064
3879
|
queueKey
|
|
5065
3880
|
);
|
|
5066
3881
|
}
|
|
5067
|
-
function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs, rls, reuseOuterConnection,
|
|
3882
|
+
function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs, rls, reuseOuterConnection, scope2, queueKey) {
|
|
5068
3883
|
const clientExecutors = createPreparedQueryClientExecutors({
|
|
5069
3884
|
pq,
|
|
5070
3885
|
baseSession,
|
|
@@ -5075,7 +3890,7 @@ function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs,
|
|
|
5075
3890
|
session,
|
|
5076
3891
|
rls,
|
|
5077
3892
|
reuseOuterConnection,
|
|
5078
|
-
|
|
3893
|
+
scope2,
|
|
5079
3894
|
queueKey,
|
|
5080
3895
|
clientExecutors.execute,
|
|
5081
3896
|
placeholderValues
|
|
@@ -5085,25 +3900,25 @@ function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs,
|
|
|
5085
3900
|
session,
|
|
5086
3901
|
rls,
|
|
5087
3902
|
reuseOuterConnection,
|
|
5088
|
-
|
|
3903
|
+
scope2,
|
|
5089
3904
|
queueKey,
|
|
5090
3905
|
clientExecutors.all,
|
|
5091
3906
|
placeholderValues
|
|
5092
3907
|
);
|
|
5093
3908
|
}
|
|
5094
3909
|
}
|
|
5095
|
-
function wrapSession(session, rls, reuseOuterConnection,
|
|
3910
|
+
function wrapSession(session, rls, reuseOuterConnection, scope2, queueKey) {
|
|
5096
3911
|
return new Proxy(session, {
|
|
5097
3912
|
get(sTarget, sProp, sRecv) {
|
|
5098
3913
|
if (sProp === "client") {
|
|
5099
|
-
return matchingRlsExecutionClient(
|
|
3914
|
+
return matchingRlsExecutionClient(scope2) ?? Reflect.get(sTarget, sProp, sRecv);
|
|
5100
3915
|
}
|
|
5101
3916
|
if (sProp === "prepareQuery") {
|
|
5102
3917
|
return (...args) => {
|
|
5103
3918
|
const prepareQuery = Reflect.get(sTarget, sProp, sRecv);
|
|
5104
3919
|
if (typeof prepareQuery !== "function") throw createRlsUnsupportedError("session");
|
|
5105
3920
|
const pq = Reflect.apply(prepareQuery, sRecv, args);
|
|
5106
|
-
wrapPreparedQuery(pq, sRecv, sTarget, prepareQuery, args, rls, reuseOuterConnection,
|
|
3921
|
+
wrapPreparedQuery(pq, sRecv, sTarget, prepareQuery, args, rls, reuseOuterConnection, scope2, queueKey);
|
|
5107
3922
|
return pq;
|
|
5108
3923
|
};
|
|
5109
3924
|
}
|
|
@@ -5115,12 +3930,12 @@ function wrapSession(session, rls, reuseOuterConnection, scope, queueKey) {
|
|
|
5115
3930
|
function createRlsDb(db, rls, options = {}) {
|
|
5116
3931
|
return createRlsDbInScope(db, rls, options, createRlsScopeToken());
|
|
5117
3932
|
}
|
|
5118
|
-
function wrapSharedConnectionCallbackTx(tx, rls, options,
|
|
3933
|
+
function wrapSharedConnectionCallbackTx(tx, rls, options, scope2, queueKey) {
|
|
5119
3934
|
const session = tx?.session ?? tx?._?.session;
|
|
5120
3935
|
if (!session || typeof session !== "object") return tx;
|
|
5121
|
-
return createRlsDbInScope(tx, rls, options,
|
|
3936
|
+
return createRlsDbInScope(tx, rls, options, scope2, queueKey);
|
|
5122
3937
|
}
|
|
5123
|
-
function createRlsDbInScope(db, rls, options,
|
|
3938
|
+
function createRlsDbInScope(db, rls, options, scope2, inheritedQueueKey) {
|
|
5124
3939
|
const reuseOuterConnection = isDrizzleTransactionDb(db);
|
|
5125
3940
|
const database = db;
|
|
5126
3941
|
const baseSession = database.session ?? database._?.session;
|
|
@@ -5136,7 +3951,7 @@ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
|
|
|
5136
3951
|
queueKey,
|
|
5137
3952
|
() => injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure)
|
|
5138
3953
|
) : injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure);
|
|
5139
|
-
const wrappedSession = wrapSession(baseSession, rls, reuseOuterConnection,
|
|
3954
|
+
const wrappedSession = wrapSession(baseSession, rls, reuseOuterConnection, scope2, queueKey);
|
|
5140
3955
|
const baseQuery = Reflect.get(db, "query", db);
|
|
5141
3956
|
const scopedQuery = baseQuery && typeof baseQuery === "object" ? createRlsRelationalQueryRegistry(baseQuery, wrappedSession, baseSession) : baseQuery;
|
|
5142
3957
|
return new Proxy(db, {
|
|
@@ -5162,7 +3977,7 @@ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
|
|
|
5162
3977
|
}
|
|
5163
3978
|
if (prop === "transaction") {
|
|
5164
3979
|
return async (callback, ...rest) => {
|
|
5165
|
-
assertRlsScopeMayEnter(
|
|
3980
|
+
assertRlsScopeMayEnter(scope2);
|
|
5166
3981
|
let callbackStarted = false;
|
|
5167
3982
|
const configStatement = transactionConfigSql(rest[0]);
|
|
5168
3983
|
const transactionArgs = configStatement ? [] : rest;
|
|
@@ -5172,8 +3987,8 @@ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
|
|
|
5172
3987
|
if (configStatement) await tx.execute(configStatement);
|
|
5173
3988
|
await injectScopeOnTx(tx);
|
|
5174
3989
|
callbackStarted = true;
|
|
5175
|
-
const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options,
|
|
5176
|
-
return await runWithRlsTransactionScope(
|
|
3990
|
+
const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options, scope2, queueKey) : tx;
|
|
3991
|
+
return await runWithRlsTransactionScope(scope2, tx, () => callback(handle));
|
|
5177
3992
|
},
|
|
5178
3993
|
...transactionArgs
|
|
5179
3994
|
);
|
|
@@ -5191,15 +4006,15 @@ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
|
|
|
5191
4006
|
}
|
|
5192
4007
|
if (prop === "transactionWithCharacteristics") {
|
|
5193
4008
|
return async (characteristics, callback) => {
|
|
5194
|
-
assertRlsScopeMayEnter(
|
|
4009
|
+
assertRlsScopeMayEnter(scope2);
|
|
5195
4010
|
return await target.transaction(async (tx) => {
|
|
5196
4011
|
await applyTransactionConfig(tx, {
|
|
5197
4012
|
...characteristics?.isolationLevel ? { isolationLevel: characteristics.isolationLevel } : {},
|
|
5198
4013
|
...characteristics?.readOnly ? { accessMode: "read only" } : {}
|
|
5199
4014
|
});
|
|
5200
4015
|
await injectScopeOnTx(tx);
|
|
5201
|
-
const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options,
|
|
5202
|
-
return runWithRlsTransactionScope(
|
|
4016
|
+
const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options, scope2, queueKey) : tx;
|
|
4017
|
+
return runWithRlsTransactionScope(scope2, tx, () => callback(handle));
|
|
5203
4018
|
});
|
|
5204
4019
|
};
|
|
5205
4020
|
}
|
|
@@ -5673,9 +4488,9 @@ function resolveCrudRealtimeConfig(input) {
|
|
|
5673
4488
|
if (policy !== "public" && policy !== "authorized") {
|
|
5674
4489
|
throw new Error(`[createCrud] realtime.policy must be "public" or "authorized" when list realtime is enabled`);
|
|
5675
4490
|
}
|
|
5676
|
-
const
|
|
4491
|
+
const scope2 = config.scope;
|
|
5677
4492
|
const scopeFromRow = config.scopeFromRow;
|
|
5678
|
-
if (typeof
|
|
4493
|
+
if (typeof scope2 !== "function" || typeof scopeFromRow !== "function") {
|
|
5679
4494
|
throw new Error(`[createCrud] realtime scope and scopeFromRow are required when list realtime is enabled`);
|
|
5680
4495
|
}
|
|
5681
4496
|
const authorize = config.authorize;
|
|
@@ -5690,7 +4505,7 @@ function resolveCrudRealtimeConfig(input) {
|
|
|
5690
4505
|
resourceIdentity: explicitResourceIdentity,
|
|
5691
4506
|
explicitScopedList: true,
|
|
5692
4507
|
authorize,
|
|
5693
|
-
scope: (args) => normalizeCrudScope(
|
|
4508
|
+
scope: (args) => normalizeCrudScope(scope2(args), "realtime.scope"),
|
|
5694
4509
|
scopeFromRow: async ({ row, ctx }) => normalizeCrudScope(await scopeFromRow({ row, ctx }), "realtime.scopeFromRow")
|
|
5695
4510
|
};
|
|
5696
4511
|
}
|
|
@@ -5769,7 +4584,7 @@ function buildRowOutputValidator(columns) {
|
|
|
5769
4584
|
}
|
|
5770
4585
|
|
|
5771
4586
|
// ../core/src/createCrud.cursor.ts
|
|
5772
|
-
import { sql as
|
|
4587
|
+
import { sql as sql4 } from "drizzle-orm";
|
|
5773
4588
|
function normalizeOrderDir(raw) {
|
|
5774
4589
|
const d = typeof raw === "string" ? raw.toLowerCase() : "";
|
|
5775
4590
|
return d === "asc" ? "asc" : "desc";
|
|
@@ -5802,16 +4617,16 @@ function buildTupleComparePredicate(columns, values, direction) {
|
|
|
5802
4617
|
if (columns.length !== values.length || columns.length === 0) {
|
|
5803
4618
|
throw new Error("cursor column count mismatch");
|
|
5804
4619
|
}
|
|
5805
|
-
const opToken = direction === "asc" ?
|
|
5806
|
-
const colTuple =
|
|
5807
|
-
columns.map((c) =>
|
|
5808
|
-
|
|
4620
|
+
const opToken = direction === "asc" ? sql4`>` : sql4`<`;
|
|
4621
|
+
const colTuple = sql4.join(
|
|
4622
|
+
columns.map((c) => sql4`${c}`),
|
|
4623
|
+
sql4`, `
|
|
5809
4624
|
);
|
|
5810
|
-
const valTuple =
|
|
5811
|
-
values.map((val) =>
|
|
5812
|
-
|
|
4625
|
+
const valTuple = sql4.join(
|
|
4626
|
+
values.map((val) => sql4`${val}`),
|
|
4627
|
+
sql4`, `
|
|
5813
4628
|
);
|
|
5814
|
-
return
|
|
4629
|
+
return sql4`(${colTuple}) ${opToken} (${valTuple})`;
|
|
5815
4630
|
}
|
|
5816
4631
|
|
|
5817
4632
|
// ../core/src/createCrud.ts
|
|
@@ -5900,21 +4715,21 @@ function buildCrud(table, options, procedure) {
|
|
|
5900
4715
|
}
|
|
5901
4716
|
return await fn(db);
|
|
5902
4717
|
}
|
|
5903
|
-
function resolveListRealtimeBucket(
|
|
4718
|
+
function resolveListRealtimeBucket(scope2) {
|
|
5904
4719
|
if (!crudRealtime.listEnabled) return null;
|
|
5905
4720
|
return {
|
|
5906
4721
|
policy: crudRealtime.listPolicy,
|
|
5907
4722
|
resourceIdentity: crudRealtime.resourceIdentity,
|
|
5908
|
-
scope,
|
|
4723
|
+
scope: scope2,
|
|
5909
4724
|
subscriptionKey: buildCrudListSubscriptionKey({
|
|
5910
4725
|
policy: crudRealtime.listPolicy,
|
|
5911
4726
|
resourceIdentity: crudRealtime.resourceIdentity,
|
|
5912
|
-
scope
|
|
4727
|
+
scope: scope2
|
|
5913
4728
|
}),
|
|
5914
4729
|
scopeHash: buildCrudListScopeHash({
|
|
5915
4730
|
policy: crudRealtime.listPolicy,
|
|
5916
4731
|
resourceIdentity: crudRealtime.resourceIdentity,
|
|
5917
|
-
scope
|
|
4732
|
+
scope: scope2
|
|
5918
4733
|
})
|
|
5919
4734
|
};
|
|
5920
4735
|
}
|
|
@@ -5924,14 +4739,14 @@ function buildCrud(table, options, procedure) {
|
|
|
5924
4739
|
let firstError;
|
|
5925
4740
|
for (const row of input.rows) {
|
|
5926
4741
|
if (row == null) continue;
|
|
5927
|
-
let
|
|
4742
|
+
let scope2;
|
|
5928
4743
|
try {
|
|
5929
|
-
|
|
4744
|
+
scope2 = await crudRealtime.scopeFromRow({ row, ctx });
|
|
5930
4745
|
} catch (error) {
|
|
5931
4746
|
firstError ??= error;
|
|
5932
4747
|
continue;
|
|
5933
4748
|
}
|
|
5934
|
-
const bucket = resolveListRealtimeBucket(
|
|
4749
|
+
const bucket = resolveListRealtimeBucket(scope2);
|
|
5935
4750
|
if (!bucket || seen.has(bucket.scopeHash)) continue;
|
|
5936
4751
|
seen.add(bucket.scopeHash);
|
|
5937
4752
|
invalidateCrudRealtime(ctx, {
|
|
@@ -6112,19 +4927,19 @@ function buildCrud(table, options, procedure) {
|
|
|
6112
4927
|
policy: crudRealtime.listPolicy,
|
|
6113
4928
|
args: listDef.inputSchema,
|
|
6114
4929
|
subscriptionKey: (args) => {
|
|
6115
|
-
const
|
|
4930
|
+
const scope2 = crudRealtime.scope(args);
|
|
6116
4931
|
return buildCrudListSubscriptionKey({
|
|
6117
4932
|
policy: crudRealtime.listPolicy,
|
|
6118
4933
|
resourceIdentity: crudRealtime.resourceIdentity,
|
|
6119
|
-
scope
|
|
4934
|
+
scope: scope2
|
|
6120
4935
|
});
|
|
6121
4936
|
},
|
|
6122
4937
|
scope: (args) => {
|
|
6123
|
-
const
|
|
4938
|
+
const scope2 = crudRealtime.scope(args);
|
|
6124
4939
|
return {
|
|
6125
4940
|
policy: crudRealtime.listPolicy,
|
|
6126
4941
|
resourceIdentity: crudRealtime.resourceIdentity,
|
|
6127
|
-
scope
|
|
4942
|
+
scope: scope2
|
|
6128
4943
|
};
|
|
6129
4944
|
},
|
|
6130
4945
|
authorize: async (ctx, args) => {
|
|
@@ -6448,7 +5263,6 @@ export {
|
|
|
6448
5263
|
isUnreadAfterCursor,
|
|
6449
5264
|
isWakeAppDeferredResult,
|
|
6450
5265
|
jsonByteLength,
|
|
6451
|
-
loadWorkflowSnapshot,
|
|
6452
5266
|
mutation,
|
|
6453
5267
|
normalizeRealtimeChannelEpoch,
|
|
6454
5268
|
normalizeRealtimeQuerySubscriptionEpoch,
|