gencow 0.1.299 → 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/package.json +1 -1
- package/docs/packaging.md +14 -4
- package/lib/cli-artifact-guard.mjs +53 -3
- 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/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/dev-cloud-command.mjs +1 -1
- package/lib/dev-local-command.mjs +19 -56
- package/lib/document-local-converter.mjs +11 -0
- 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/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/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 +10399 -8951
- 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/sso/sso-auth-callback.tsx +37 -5
- package/templateFeature/tools/manifest.json +2 -1
- package/templateFeature/tools/tools.ts +3 -3
- package/runtime/server.mjs +0 -14389
- 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
|
@@ -0,0 +1,1560 @@
|
|
|
1
|
+
import {
|
|
2
|
+
compareFrameworkProjection,
|
|
3
|
+
frameworkAccessRequirements,
|
|
4
|
+
hasFrameworkSchemaTransition,
|
|
5
|
+
missingFrameworkAccess,
|
|
6
|
+
transitionForObservation,
|
|
7
|
+
verifyFrameworkFoundationPostimage,
|
|
8
|
+
verifyFrameworkSchemaPostimage,
|
|
9
|
+
withSecurityStage
|
|
10
|
+
} from "./chunk-K2YZVPJ4.mjs";
|
|
11
|
+
import {
|
|
12
|
+
loadRuntimePostgresSql
|
|
13
|
+
} from "./chunk-PMOJLN2P.mjs";
|
|
14
|
+
import {
|
|
15
|
+
readRuntimeDatabaseSchemaCatalog,
|
|
16
|
+
schemaCatalogRows
|
|
17
|
+
} from "./chunk-YMH4RYSX.mjs";
|
|
18
|
+
import "./chunk-GSLM44EF.mjs";
|
|
19
|
+
import "./chunk-KVLTJFCH.mjs";
|
|
20
|
+
import "./chunk-7KUJ2H2S.mjs";
|
|
21
|
+
import "./chunk-ZXMM7QFP.mjs";
|
|
22
|
+
import "./chunk-PZFMKFHO.mjs";
|
|
23
|
+
import {
|
|
24
|
+
attestPostgresSchemaTarget,
|
|
25
|
+
createPostgresSchemaCancellation,
|
|
26
|
+
withPostgresSchemaReservation
|
|
27
|
+
} from "./chunk-EQCTAET7.mjs";
|
|
28
|
+
import {
|
|
29
|
+
assertLocalPostgresSecurityPolicy,
|
|
30
|
+
observeLocalPostgresSecurityFacts
|
|
31
|
+
} from "./chunk-5MXY3T75.mjs";
|
|
32
|
+
import {
|
|
33
|
+
runtimePostgresClient
|
|
34
|
+
} from "./chunk-F3G4UGV4.mjs";
|
|
35
|
+
import {
|
|
36
|
+
parseRuntimePostgresBinding
|
|
37
|
+
} from "./chunk-FM23RGVI.mjs";
|
|
38
|
+
import "./chunk-U2NRG6KC.mjs";
|
|
39
|
+
import "./chunk-ITH2NEKM.mjs";
|
|
40
|
+
import {
|
|
41
|
+
resolveRuntimePostgresDriverConfig
|
|
42
|
+
} from "./chunk-EAIELFKU.mjs";
|
|
43
|
+
import "./chunk-KX2PRQPS.mjs";
|
|
44
|
+
import {
|
|
45
|
+
inspectRuntimeDatabaseSchemaPlan
|
|
46
|
+
} from "./chunk-3D7MHEUC.mjs";
|
|
47
|
+
import {
|
|
48
|
+
runtimeDatabaseSetupDeadlineReason,
|
|
49
|
+
runtimeDatabaseSetupError,
|
|
50
|
+
runtimeDatabaseSetupInterrupted
|
|
51
|
+
} from "./chunk-SVJCOUI3.mjs";
|
|
52
|
+
import "./chunk-I3GWR43K.mjs";
|
|
53
|
+
import {
|
|
54
|
+
RuntimeDiagnosticError,
|
|
55
|
+
runtimeDiagnostic
|
|
56
|
+
} from "./chunk-AEBW7XZJ.mjs";
|
|
57
|
+
|
|
58
|
+
// ../runtime/dist/adapters/database/postgres-schema-owner.js
|
|
59
|
+
import { randomUUID } from "node:crypto";
|
|
60
|
+
import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
|
|
61
|
+
|
|
62
|
+
// ../runtime/dist/adapters/database/postgres-schema-diagnostic.js
|
|
63
|
+
function sqlState(error) {
|
|
64
|
+
for (let depth = 0; depth < 5 && error && typeof error === "object"; depth++) {
|
|
65
|
+
const state = Reflect.get(error, "errno") ?? Reflect.get(error, "code");
|
|
66
|
+
if (typeof state === "string" && /^[0-9A-Z]{5}$/.test(state))
|
|
67
|
+
return state;
|
|
68
|
+
if ([
|
|
69
|
+
"ERR_POSTGRES_CONNECTION_CLOSED",
|
|
70
|
+
"ERR_POSTGRES_CONNECTION_TIMEOUT",
|
|
71
|
+
"ERR_POSTGRES_CONNECTION_LOST"
|
|
72
|
+
].includes(state))
|
|
73
|
+
return "08006";
|
|
74
|
+
error = Reflect.get(error, "cause");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function classifyPostgresSchemaFailure(error, impact, correlationId, signal) {
|
|
78
|
+
if (impact === "unknown")
|
|
79
|
+
return runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", impact, correlationId);
|
|
80
|
+
const existing = runtimeDiagnostic(error);
|
|
81
|
+
if (existing?.code.startsWith("RUNTIME_DATABASE_SETUP_") || existing?.code.startsWith("RUNTIME_DATABASE_SECURITY_POLICY_") || existing?.code === "RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID")
|
|
82
|
+
return new RuntimeDiagnosticError({ ...existing, dataImpact: impact, correlationId });
|
|
83
|
+
const state = sqlState(error);
|
|
84
|
+
if (state === "57014" && signal.aborted)
|
|
85
|
+
return runtimeDatabaseSetupInterrupted(signal, impact, correlationId);
|
|
86
|
+
const failure = runtimeDatabaseSetupError(state === "42501" ? "RUNTIME_DATABASE_SETUP_AUTHORITY_INVALID" : "RUNTIME_DATABASE_SETUP_FAILED", impact, correlationId);
|
|
87
|
+
if (!state?.startsWith("08"))
|
|
88
|
+
return failure;
|
|
89
|
+
return new RuntimeDiagnosticError({
|
|
90
|
+
...failure.diagnostic,
|
|
91
|
+
retryPrecondition: "Owned cleanup has finished and the captured bindings can reach the original database; inspect the reported effects before restart.",
|
|
92
|
+
nextAction: "Restore database connectivity for the captured bindings. After owned cleanup, inspect any reported committed effects before restarting; preserve data and applied migration history. Do not change valid SQL or grants to repair a connection failure."
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ../runtime/dist/adapters/database/schema-step-execution.js
|
|
97
|
+
import { sql } from "drizzle-orm";
|
|
98
|
+
async function applyGrant(database, grant, roles) {
|
|
99
|
+
const object = grant.object;
|
|
100
|
+
if (object.kind !== "table" && object.kind !== "sequence")
|
|
101
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
102
|
+
const names = object.kind === "table" ? [object.name] : schemaCatalogRows(await database.execute(sql`
|
|
103
|
+
SELECT sequence_relation.relname AS name FROM pg_catalog.pg_class sequence_relation
|
|
104
|
+
JOIN pg_catalog.pg_namespace sequence_namespace ON sequence_namespace.oid=sequence_relation.relnamespace
|
|
105
|
+
JOIN pg_catalog.pg_depend ownership ON ownership.classid='pg_catalog.pg_class'::regclass AND ownership.objid=sequence_relation.oid
|
|
106
|
+
AND ownership.refclassid='pg_catalog.pg_class'::regclass AND ownership.deptype IN ('a','i')
|
|
107
|
+
JOIN pg_catalog.pg_class relation ON relation.oid=ownership.refobjid
|
|
108
|
+
JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace
|
|
109
|
+
JOIN pg_catalog.pg_attribute attribute ON attribute.attrelid=relation.oid AND attribute.attnum=ownership.refobjsubid
|
|
110
|
+
JOIN pg_catalog.pg_attrdef defaults ON defaults.adrelid=relation.oid AND defaults.adnum=attribute.attnum
|
|
111
|
+
JOIN pg_catalog.pg_depend dependency ON dependency.classid='pg_catalog.pg_attrdef'::regclass AND dependency.objid=defaults.oid
|
|
112
|
+
AND dependency.refclassid='pg_catalog.pg_class'::regclass AND dependency.refobjid=sequence_relation.oid
|
|
113
|
+
WHERE sequence_relation.relkind='S' AND sequence_namespace.nspname=${object.schema}
|
|
114
|
+
AND namespace.nspname=${object.schema} AND relation.relname=${object.table} AND attribute.attname=${object.column}
|
|
115
|
+
`)).filter((row) => object.name === void 0 || row.name === object.name).map((row) => row.name);
|
|
116
|
+
if (names.length !== 1)
|
|
117
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
118
|
+
for (const path of grant.paths) {
|
|
119
|
+
const [schema] = schemaCatalogRows(await database.execute(sql`SELECT pg_catalog.has_schema_privilege(${roles[path]},namespace.oid,'USAGE') AS allowed FROM pg_catalog.pg_namespace namespace WHERE namespace.nspname=${object.schema}`));
|
|
120
|
+
if (!schema)
|
|
121
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
122
|
+
if (!schema.allowed)
|
|
123
|
+
await database.execute(sql`GRANT USAGE ON SCHEMA ${sql.identifier(object.schema)} TO ${sql.identifier(roles[path])}`);
|
|
124
|
+
const qualified = sql`${sql.identifier(object.schema)}.${sql.identifier(names[0])}`;
|
|
125
|
+
for (const privilege of grant.privileges) {
|
|
126
|
+
const check = object.kind === "sequence" ? sql`pg_catalog.has_sequence_privilege(${roles[path]},relation.oid,${privilege})` : sql`pg_catalog.has_table_privilege(${roles[path]},relation.oid,${privilege})`;
|
|
127
|
+
const [access] = schemaCatalogRows(await database.execute(sql`SELECT ${check} AS allowed FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace WHERE namespace.nspname=${object.schema} AND relation.relname=${names[0]}`));
|
|
128
|
+
if (!access)
|
|
129
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
130
|
+
if (!access.allowed)
|
|
131
|
+
await database.execute(sql`GRANT ${sql.raw(privilege)} ON ${sql.raw(object.kind === "sequence" ? "SEQUENCE" : "TABLE")} ${qualified} TO ${sql.identifier(roles[path])}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function applyRuntimeDatabaseSchemaStep(database, plan, roles, componentId, stepId) {
|
|
136
|
+
const step = plan.components.find((component) => component.id === componentId)?.steps.find((step2) => step2.id === stepId);
|
|
137
|
+
if (!step)
|
|
138
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
139
|
+
for (const statement of step.statements)
|
|
140
|
+
await database.execute(sql.raw(statement));
|
|
141
|
+
for (const grant of step.grants)
|
|
142
|
+
await applyGrant(database, grant, roles);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ../runtime/dist/adapters/database/postgres-schema-operational.js
|
|
146
|
+
import { randomBytes } from "node:crypto";
|
|
147
|
+
var POSTGRES_FRAMEWORK_SCHEMA_LOCK = "gencow:runtime:framework-schema:v1";
|
|
148
|
+
async function inspect(session, plan, roles) {
|
|
149
|
+
const { drizzle } = await import("drizzle-orm/bun-sql");
|
|
150
|
+
return readRuntimeDatabaseSchemaCatalog(drizzle({ client: runtimePostgresClient(session) }), plan, roles);
|
|
151
|
+
}
|
|
152
|
+
async function inspectPostgresOperationalSchema(operational, plan, signal, requireReleasedSetupLock = false) {
|
|
153
|
+
if (!plan.objects.length)
|
|
154
|
+
return { relations: [], columns: [], constraints: [], indexes: [], sequences: [], access: [] };
|
|
155
|
+
return withPostgresSchemaReservation(operational.application, signal, async (application) => {
|
|
156
|
+
await application.unsafe("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
|
|
157
|
+
try {
|
|
158
|
+
if (requireReleasedSetupLock) {
|
|
159
|
+
const [lock] = await application`
|
|
160
|
+
SELECT pg_catalog.pg_try_advisory_xact_lock(pg_catalog.hashtextextended(${POSTGRES_FRAMEWORK_SCHEMA_LOCK},0)) AS held
|
|
161
|
+
`;
|
|
162
|
+
if (lock?.held !== true)
|
|
163
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown");
|
|
164
|
+
}
|
|
165
|
+
const [actor2] = await application`SELECT current_user AS role, pg_catalog.current_database() AS database`;
|
|
166
|
+
if (!actor2?.role || !actor2.database)
|
|
167
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_FAILED");
|
|
168
|
+
if (operational.application === operational.maintenance)
|
|
169
|
+
return await inspect(application, plan, { application: actor2.role, maintenance: actor2.role });
|
|
170
|
+
const first = randomBytes(8).readBigInt64BE().toString();
|
|
171
|
+
let second = randomBytes(8).readBigInt64BE().toString();
|
|
172
|
+
while (first === second)
|
|
173
|
+
second = randomBytes(8).readBigInt64BE().toString();
|
|
174
|
+
await application`SELECT pg_catalog.pg_advisory_xact_lock(${first}::bigint), pg_catalog.pg_advisory_xact_lock(${second}::bigint)`;
|
|
175
|
+
return await withPostgresSchemaReservation(operational.maintenance, signal, async (maintenance) => {
|
|
176
|
+
await maintenance.unsafe("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
|
|
177
|
+
try {
|
|
178
|
+
const [observed] = await maintenance`
|
|
179
|
+
SELECT current_user AS role, pg_catalog.current_database() AS database,
|
|
180
|
+
pg_catalog.pg_try_advisory_xact_lock(${first}::bigint) AS first,
|
|
181
|
+
pg_catalog.pg_try_advisory_xact_lock(${second}::bigint) AS second
|
|
182
|
+
`;
|
|
183
|
+
if (!observed?.role || observed.database !== actor2.database || observed.first !== false || observed.second !== false)
|
|
184
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
185
|
+
const roles = { application: actor2.role, maintenance: observed.role };
|
|
186
|
+
const appCatalog = await inspect(application, plan, roles);
|
|
187
|
+
const maintenanceCatalog = await inspect(maintenance, plan, roles);
|
|
188
|
+
return {
|
|
189
|
+
...appCatalog,
|
|
190
|
+
access: [
|
|
191
|
+
...appCatalog.access.filter((access) => access.path === "application"),
|
|
192
|
+
...maintenanceCatalog.access.filter((access) => access.path === "maintenance")
|
|
193
|
+
]
|
|
194
|
+
};
|
|
195
|
+
} finally {
|
|
196
|
+
await maintenance.unsafe("ROLLBACK").catch((error) => {
|
|
197
|
+
if (!signal.aborted)
|
|
198
|
+
throw error;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
} finally {
|
|
203
|
+
await application.unsafe("ROLLBACK").catch((error) => {
|
|
204
|
+
if (!signal.aborted)
|
|
205
|
+
throw error;
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ../runtime/dist/adapters/database/postgres-schema-serialization.js
|
|
212
|
+
function active(signal) {
|
|
213
|
+
if (signal.aborted)
|
|
214
|
+
throw runtimeDatabaseSetupInterrupted(signal);
|
|
215
|
+
}
|
|
216
|
+
async function pause(signal) {
|
|
217
|
+
active(signal);
|
|
218
|
+
await new Promise((resolve, reject) => {
|
|
219
|
+
const finish = () => {
|
|
220
|
+
signal.removeEventListener("abort", abort);
|
|
221
|
+
resolve();
|
|
222
|
+
};
|
|
223
|
+
const abort = () => {
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
signal.removeEventListener("abort", abort);
|
|
226
|
+
reject(runtimeDatabaseSetupInterrupted(signal));
|
|
227
|
+
};
|
|
228
|
+
const timer = setTimeout(finish, 25);
|
|
229
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
230
|
+
if (signal.aborted)
|
|
231
|
+
abort();
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
async function acquirePostgresFrameworkSchemaLock(setup, signal) {
|
|
235
|
+
const deadline = performance.now() + 5e3;
|
|
236
|
+
while (true) {
|
|
237
|
+
active(signal);
|
|
238
|
+
const [lock] = await setup`SELECT pg_catalog.pg_try_advisory_xact_lock(pg_catalog.hashtextextended(${POSTGRES_FRAMEWORK_SCHEMA_LOCK},0)) AS held`;
|
|
239
|
+
if (lock?.held === true)
|
|
240
|
+
return;
|
|
241
|
+
if (performance.now() >= deadline)
|
|
242
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_LOCK_TIMEOUT");
|
|
243
|
+
await pause(signal);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ../runtime/dist/adapters/database/postgres-framework-observation.js
|
|
248
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
249
|
+
import { isDeepStrictEqual } from "node:util";
|
|
250
|
+
|
|
251
|
+
// ../runtime/dist/adapters/database/postgres-framework-journal.js
|
|
252
|
+
import { sql as sql2 } from "drizzle-orm";
|
|
253
|
+
function invalidHistory() {
|
|
254
|
+
throw runtimeDatabaseSetupError("RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID");
|
|
255
|
+
}
|
|
256
|
+
async function inspectFrameworkJournalIdentity(database, plan, expectedOwner) {
|
|
257
|
+
if (!plan.journal)
|
|
258
|
+
return { state: "absent" };
|
|
259
|
+
const rows = schemaCatalogRows(await database.execute(sql2`
|
|
260
|
+
SELECT relation.oid IS NOT NULL AS exists,relation.relkind::text AS kind,
|
|
261
|
+
owner.rolname AS owner,relation.relrowsecurity AS "rowSecurity",
|
|
262
|
+
relation.relforcerowsecurity AS "forceRowSecurity",relation.relispartition AS partitioned,
|
|
263
|
+
EXISTS (SELECT 1 FROM pg_catalog.pg_inherits inheritance
|
|
264
|
+
WHERE inheritance.inhrelid=relation.oid OR inheritance.inhparent=relation.oid) AS inherited,
|
|
265
|
+
ARRAY(SELECT rule.rulename::text FROM pg_catalog.pg_rewrite rule
|
|
266
|
+
WHERE rule.ev_class=relation.oid AND rule.rulename <> '_RETURN' ORDER BY rule.rulename) AS rules,
|
|
267
|
+
ARRAY(SELECT policy.polname::text FROM pg_catalog.pg_policy policy
|
|
268
|
+
WHERE policy.polrelid=relation.oid ORDER BY policy.polname) AS policies,
|
|
269
|
+
ARRAY(SELECT trigger.tgname::text FROM pg_catalog.pg_trigger trigger
|
|
270
|
+
WHERE trigger.tgrelid=relation.oid AND NOT trigger.tgisinternal ORDER BY trigger.tgname) AS triggers
|
|
271
|
+
FROM pg_catalog.pg_namespace namespace
|
|
272
|
+
LEFT JOIN pg_catalog.pg_class relation ON relation.relnamespace=namespace.oid
|
|
273
|
+
AND relation.relname=${plan.journal.name}
|
|
274
|
+
LEFT JOIN pg_catalog.pg_roles owner ON owner.oid=relation.relowner
|
|
275
|
+
WHERE namespace.nspname=${plan.journal.schema}
|
|
276
|
+
`));
|
|
277
|
+
const identity = rows[0];
|
|
278
|
+
if (!identity || !identity.exists)
|
|
279
|
+
return { state: "absent" };
|
|
280
|
+
if (identity.kind !== "r" || !identity.owner || expectedOwner !== void 0 && identity.owner !== expectedOwner || identity.rowSecurity !== false || identity.forceRowSecurity !== false || identity.partitioned !== false || identity.inherited !== false || identity.rules?.length !== 0 || identity.policies?.length !== 0 || identity.triggers?.length !== 0)
|
|
281
|
+
return invalidHistory();
|
|
282
|
+
return { state: "present", owner: identity.owner };
|
|
283
|
+
}
|
|
284
|
+
async function readFrameworkJournalObservation(database, plan, catalog, identity, readAsOperational) {
|
|
285
|
+
if (!plan.journal)
|
|
286
|
+
return void 0;
|
|
287
|
+
if (identity.state === "absent")
|
|
288
|
+
return Object.freeze({ state: "absent" });
|
|
289
|
+
if (compareFrameworkProjection(catalog, plan.journal.projection).length)
|
|
290
|
+
return invalidHistory();
|
|
291
|
+
if (readAsOperational && missingFrameworkAccess(catalog, plan.journal.access).length > 0)
|
|
292
|
+
return Object.freeze({ state: "access-unavailable", integrity: "valid", owner: identity.owner });
|
|
293
|
+
const [globalHistory] = schemaCatalogRows(await database.execute(sql2`
|
|
294
|
+
SELECT EXISTS (
|
|
295
|
+
SELECT 1 FROM ${sql2.identifier(plan.journal.schema)}.${sql2.identifier(plan.journal.name)}
|
|
296
|
+
) AS "hasAnyFrameworkRows"
|
|
297
|
+
`));
|
|
298
|
+
if (!globalHistory || typeof globalHistory.hasAnyFrameworkRows !== "boolean")
|
|
299
|
+
return invalidHistory();
|
|
300
|
+
const selectedComponents = [...new Set(plan.features.map((feature) => feature.componentId))];
|
|
301
|
+
if (selectedComponents.length === 0)
|
|
302
|
+
return Object.freeze({
|
|
303
|
+
state: "valid",
|
|
304
|
+
owner: identity.owner,
|
|
305
|
+
hasAnyFrameworkRows: globalHistory.hasAnyFrameworkRows,
|
|
306
|
+
rows: Object.freeze([])
|
|
307
|
+
});
|
|
308
|
+
const selectedIds = sql2.join(selectedComponents.map((componentId) => sql2`(${componentId}::text)`), sql2`, `);
|
|
309
|
+
const rows = schemaCatalogRows(await database.execute(sql2`
|
|
310
|
+
WITH selected_components(component_id) AS (VALUES ${selectedIds}), selected AS (
|
|
311
|
+
SELECT history.component_id AS "componentId",history.migration_id AS "migrationId",
|
|
312
|
+
history.migration_order::text AS "migrationOrder",history.hash,
|
|
313
|
+
history.created_at::text AS "createdAt",history.applied_via AS "appliedVia",
|
|
314
|
+
pg_catalog.row_number() OVER (PARTITION BY history.component_id ORDER BY history.migration_order) AS "componentPosition"
|
|
315
|
+
FROM selected_components component
|
|
316
|
+
CROSS JOIN LATERAL (
|
|
317
|
+
SELECT journal.component_id,journal.migration_id,journal.migration_order,
|
|
318
|
+
journal.hash,journal.created_at,journal.applied_via
|
|
319
|
+
FROM ${sql2.identifier(plan.journal.schema)}.${sql2.identifier(plan.journal.name)} journal
|
|
320
|
+
WHERE journal.component_id=component.component_id
|
|
321
|
+
ORDER BY journal.migration_order
|
|
322
|
+
LIMIT 10001
|
|
323
|
+
) history
|
|
324
|
+
)
|
|
325
|
+
SELECT "componentId","migrationId","migrationOrder",hash,"createdAt","appliedVia",
|
|
326
|
+
"componentPosition"::text AS "componentPosition"
|
|
327
|
+
FROM selected
|
|
328
|
+
WHERE "componentPosition" <= 10001
|
|
329
|
+
ORDER BY "componentId","componentPosition"
|
|
330
|
+
`));
|
|
331
|
+
if (rows.some((row) => !/^[0-9]+$/u.test(row.componentPosition) || Number(row.componentPosition) > 1e4))
|
|
332
|
+
return invalidHistory();
|
|
333
|
+
const selected = new Set(plan.features.map((feature) => feature.componentId));
|
|
334
|
+
const captured = rows.map((row) => {
|
|
335
|
+
if (!row || typeof row !== "object")
|
|
336
|
+
return invalidHistory();
|
|
337
|
+
if (typeof row.componentId !== "string" || row.componentId.length > 63)
|
|
338
|
+
return invalidHistory();
|
|
339
|
+
if (!selected.has(row.componentId))
|
|
340
|
+
return Object.freeze({ componentId: row.componentId });
|
|
341
|
+
const createdAt = typeof row.createdAt === "string" && /^[0-9]+$/u.test(row.createdAt) ? Number(row.createdAt) : Number.NaN;
|
|
342
|
+
const migrationOrder = typeof row.migrationOrder === "string" && /^[0-9]+$/u.test(row.migrationOrder) ? Number(row.migrationOrder) : Number.NaN;
|
|
343
|
+
if (!Number.isSafeInteger(createdAt) || createdAt <= 0 || !Number.isSafeInteger(migrationOrder) || migrationOrder <= 0 || typeof row.migrationId !== "string" || typeof row.hash !== "string" || row.appliedVia !== "baseline" && row.appliedVia !== "migration")
|
|
344
|
+
return invalidHistory();
|
|
345
|
+
return Object.freeze({
|
|
346
|
+
componentId: row.componentId,
|
|
347
|
+
migrationId: row.migrationId,
|
|
348
|
+
migrationOrder,
|
|
349
|
+
hash: row.hash,
|
|
350
|
+
createdAt,
|
|
351
|
+
appliedVia: row.appliedVia
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
return Object.freeze({
|
|
355
|
+
state: "valid",
|
|
356
|
+
owner: identity.owner,
|
|
357
|
+
hasAnyFrameworkRows: globalHistory.hasAnyFrameworkRows,
|
|
358
|
+
rows: Object.freeze(captured)
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ../runtime/dist/adapters/database/postgres-framework-observation.js
|
|
363
|
+
function active2(signal) {
|
|
364
|
+
if (signal.aborted)
|
|
365
|
+
throw runtimeDatabaseSetupInterrupted(signal);
|
|
366
|
+
}
|
|
367
|
+
async function snapshotDatabase(session) {
|
|
368
|
+
const { drizzle } = await import("drizzle-orm/bun-sql");
|
|
369
|
+
const database = drizzle({ client: runtimePostgresClient(session) });
|
|
370
|
+
return {
|
|
371
|
+
async execute(query) {
|
|
372
|
+
return await database.execute(query);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
async function actor(session) {
|
|
377
|
+
const [identity] = await session`
|
|
378
|
+
SELECT current_user AS role, pg_catalog.current_database() AS database
|
|
379
|
+
`;
|
|
380
|
+
if (!identity?.role || !identity.database)
|
|
381
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
382
|
+
return identity;
|
|
383
|
+
}
|
|
384
|
+
function lockKeys() {
|
|
385
|
+
const first = randomBytes2(8).readBigInt64BE().toString();
|
|
386
|
+
let second = randomBytes2(8).readBigInt64BE().toString();
|
|
387
|
+
while (first === second)
|
|
388
|
+
second = randomBytes2(8).readBigInt64BE().toString();
|
|
389
|
+
return [first, second];
|
|
390
|
+
}
|
|
391
|
+
function selectedRag(plan) {
|
|
392
|
+
const rag = plan.features.find((feature) => feature.componentId === "rag");
|
|
393
|
+
return Object.freeze((rag?.targetProjection ?? []).map((table) => Object.freeze({
|
|
394
|
+
schema: table.schema,
|
|
395
|
+
name: table.name
|
|
396
|
+
})));
|
|
397
|
+
}
|
|
398
|
+
async function captureOperationalPair(input) {
|
|
399
|
+
const { operational, plan, runtimePlan, signal, setup, stage } = input;
|
|
400
|
+
const base = await withPostgresSchemaReservation(operational.application, signal, async (application) => {
|
|
401
|
+
active2(signal);
|
|
402
|
+
await application.unsafe("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
|
|
403
|
+
try {
|
|
404
|
+
const applicationActor = await actor(application);
|
|
405
|
+
let applicationCatalog;
|
|
406
|
+
let journalIdentity;
|
|
407
|
+
let applicationJournal;
|
|
408
|
+
let maintenanceActor = applicationActor;
|
|
409
|
+
let maintenanceCatalog;
|
|
410
|
+
if (operational.application === operational.maintenance) {
|
|
411
|
+
const database = await snapshotDatabase(application);
|
|
412
|
+
journalIdentity = await inspectFrameworkJournalIdentity(database, plan);
|
|
413
|
+
applicationCatalog = await readRuntimeDatabaseSchemaCatalog(database, runtimePlan, {
|
|
414
|
+
application: applicationActor.role,
|
|
415
|
+
maintenance: applicationActor.role
|
|
416
|
+
});
|
|
417
|
+
applicationJournal = await readFrameworkJournalObservation(database, plan, applicationCatalog, journalIdentity, true);
|
|
418
|
+
} else {
|
|
419
|
+
const [first, second] = lockKeys();
|
|
420
|
+
await application`SELECT pg_catalog.pg_advisory_xact_lock(${first}::bigint), pg_catalog.pg_advisory_xact_lock(${second}::bigint)`;
|
|
421
|
+
maintenanceCatalog = await withPostgresSchemaReservation(operational.maintenance, signal, async (maintenance) => {
|
|
422
|
+
await maintenance.unsafe("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");
|
|
423
|
+
try {
|
|
424
|
+
const [observed] = await maintenance`
|
|
425
|
+
SELECT current_user AS role, pg_catalog.current_database() AS database,
|
|
426
|
+
pg_catalog.pg_try_advisory_xact_lock(${first}::bigint) AS first,
|
|
427
|
+
pg_catalog.pg_try_advisory_xact_lock(${second}::bigint) AS second
|
|
428
|
+
`;
|
|
429
|
+
if (!observed?.role || observed.database !== applicationActor.database || observed.first !== false || observed.second !== false)
|
|
430
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
431
|
+
maintenanceActor = Object.freeze({ role: observed.role, database: observed.database });
|
|
432
|
+
const database = await snapshotDatabase(application);
|
|
433
|
+
journalIdentity = await inspectFrameworkJournalIdentity(database, plan);
|
|
434
|
+
applicationCatalog = await readRuntimeDatabaseSchemaCatalog(database, runtimePlan, {
|
|
435
|
+
application: applicationActor.role,
|
|
436
|
+
maintenance: maintenanceActor.role
|
|
437
|
+
});
|
|
438
|
+
const servingCatalog = await readRuntimeDatabaseSchemaCatalog(await snapshotDatabase(maintenance), runtimePlan, { application: applicationActor.role, maintenance: maintenanceActor.role });
|
|
439
|
+
applicationJournal = await readFrameworkJournalObservation(database, plan, applicationCatalog, journalIdentity, true);
|
|
440
|
+
return {
|
|
441
|
+
...applicationCatalog,
|
|
442
|
+
access: [
|
|
443
|
+
...applicationCatalog.access.filter((entry) => entry.path === "application"),
|
|
444
|
+
...servingCatalog.access.filter((entry) => entry.path === "maintenance")
|
|
445
|
+
]
|
|
446
|
+
};
|
|
447
|
+
} finally {
|
|
448
|
+
await maintenance.unsafe("ROLLBACK").catch((error) => {
|
|
449
|
+
if (!signal.aborted)
|
|
450
|
+
throw error;
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
if (operational.application === operational.maintenance)
|
|
456
|
+
maintenanceCatalog = applicationCatalog;
|
|
457
|
+
if (!applicationCatalog || !maintenanceCatalog)
|
|
458
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_FAILED");
|
|
459
|
+
const combinedCatalog = {
|
|
460
|
+
...applicationCatalog,
|
|
461
|
+
access: maintenanceCatalog.access
|
|
462
|
+
};
|
|
463
|
+
const journal2 = applicationJournal;
|
|
464
|
+
return Object.freeze({
|
|
465
|
+
target: Object.freeze({
|
|
466
|
+
database: applicationActor.database,
|
|
467
|
+
applicationRole: applicationActor.role,
|
|
468
|
+
maintenanceRole: maintenanceActor.role,
|
|
469
|
+
...setup ? { setupRole: (await actor(setup)).role } : {}
|
|
470
|
+
}),
|
|
471
|
+
catalog: combinedCatalog,
|
|
472
|
+
...journal2 ? { journal: journal2 } : {},
|
|
473
|
+
capabilities: Object.freeze({
|
|
474
|
+
extensions: Object.freeze([...combinedCatalog.extensions ?? []]),
|
|
475
|
+
// Local bindings currently grant no direct RLS-bypass capability.
|
|
476
|
+
// The observed maintenance posture stays in `security.facts` and
|
|
477
|
+
// cannot self-authorize the evaluator's capability exception.
|
|
478
|
+
maintenanceBypassRls: false
|
|
479
|
+
})
|
|
480
|
+
});
|
|
481
|
+
} finally {
|
|
482
|
+
await application.unsafe("ROLLBACK").catch((error) => {
|
|
483
|
+
if (!signal.aborted)
|
|
484
|
+
throw error;
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
const journal = base.journal;
|
|
489
|
+
const security = await observeLocalPostgresSecurityFacts({
|
|
490
|
+
application: operational.application,
|
|
491
|
+
maintenance: operational.maintenance,
|
|
492
|
+
...setup ? { setup } : {},
|
|
493
|
+
stage,
|
|
494
|
+
maintenanceBypassRls: false,
|
|
495
|
+
selectedRag: selectedRag(plan),
|
|
496
|
+
...plan.journal ? {
|
|
497
|
+
frameworkJournal: {
|
|
498
|
+
schema: "drizzle",
|
|
499
|
+
name: "__gencow_framework_migrations",
|
|
500
|
+
...journal?.state === "valid" || journal?.state === "access-unavailable" ? { owner: journal.owner } : {}
|
|
501
|
+
}
|
|
502
|
+
} : {}
|
|
503
|
+
});
|
|
504
|
+
return Object.freeze({ ...base, security });
|
|
505
|
+
}
|
|
506
|
+
async function observePostgresFrameworkSchema(input) {
|
|
507
|
+
const first = await captureOperationalPair(input);
|
|
508
|
+
active2(input.signal);
|
|
509
|
+
const second = await captureOperationalPair(input);
|
|
510
|
+
if (!isDeepStrictEqual(first, second))
|
|
511
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
512
|
+
return second;
|
|
513
|
+
}
|
|
514
|
+
async function observePostgresFrameworkSchemaInTransaction(input) {
|
|
515
|
+
const { session, roles, operational, plan, runtimePlan, signal, stage } = input;
|
|
516
|
+
active2(signal);
|
|
517
|
+
const database = await snapshotDatabase(session);
|
|
518
|
+
const journalIdentity = await inspectFrameworkJournalIdentity(database, plan);
|
|
519
|
+
const catalog = await readRuntimeDatabaseSchemaCatalog(database, runtimePlan, {
|
|
520
|
+
application: roles.application,
|
|
521
|
+
maintenance: roles.maintenance
|
|
522
|
+
});
|
|
523
|
+
const journal = await readFrameworkJournalObservation(database, plan, catalog, journalIdentity, false);
|
|
524
|
+
const security = await observeLocalPostgresSecurityFacts({
|
|
525
|
+
application: operational.application,
|
|
526
|
+
maintenance: operational.maintenance,
|
|
527
|
+
setup: session,
|
|
528
|
+
stage,
|
|
529
|
+
maintenanceBypassRls: false,
|
|
530
|
+
selectedRag: selectedRag(plan),
|
|
531
|
+
...plan.journal ? {
|
|
532
|
+
frameworkJournal: {
|
|
533
|
+
schema: "drizzle",
|
|
534
|
+
name: "__gencow_framework_migrations",
|
|
535
|
+
...journal?.state === "valid" || journal?.state === "access-unavailable" ? { owner: journal.owner } : {}
|
|
536
|
+
}
|
|
537
|
+
} : {}
|
|
538
|
+
});
|
|
539
|
+
return Object.freeze({
|
|
540
|
+
target: Object.freeze({
|
|
541
|
+
database: roles.database,
|
|
542
|
+
applicationRole: roles.application,
|
|
543
|
+
maintenanceRole: roles.maintenance,
|
|
544
|
+
setupRole: roles.setup
|
|
545
|
+
}),
|
|
546
|
+
catalog,
|
|
547
|
+
...journal ? { journal } : {},
|
|
548
|
+
security,
|
|
549
|
+
capabilities: Object.freeze({
|
|
550
|
+
extensions: Object.freeze([...catalog.extensions ?? []]),
|
|
551
|
+
maintenanceBypassRls: false
|
|
552
|
+
})
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ../runtime/dist/adapters/database/postgres-schema-readback.js
|
|
557
|
+
async function frameworkCommitChannelIdentity(anchor) {
|
|
558
|
+
const [identity] = await anchor`
|
|
559
|
+
SELECT session_user AS role,pg_catalog.current_database() AS database,
|
|
560
|
+
pg_catalog.pg_backend_pid()::int AS pid,
|
|
561
|
+
extract(epoch FROM activity.backend_start)::text AS "backendStart"
|
|
562
|
+
FROM pg_catalog.pg_stat_activity activity
|
|
563
|
+
WHERE activity.pid=pg_catalog.pg_backend_pid()
|
|
564
|
+
`;
|
|
565
|
+
return identity?.role && identity.database && identity.pid > 0 && identity.backendStart ? Object.freeze({ ...identity }) : void 0;
|
|
566
|
+
}
|
|
567
|
+
async function captureFrameworkCommitEvidence(input) {
|
|
568
|
+
const [transaction] = await input.setup`
|
|
569
|
+
SELECT pg_catalog.pg_current_xact_id()::text AS xid
|
|
570
|
+
`;
|
|
571
|
+
const channel = await frameworkCommitChannelIdentity(input.anchor);
|
|
572
|
+
if (!transaction?.xid || !/^[0-9]+$/u.test(transaction.xid) || !channel || channel.role !== input.expectedTarget.setupRole || channel.database !== input.expectedTarget.database)
|
|
573
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
574
|
+
return Object.freeze({
|
|
575
|
+
xid: transaction.xid,
|
|
576
|
+
channel,
|
|
577
|
+
expectedTarget: Object.freeze({ ...input.expectedTarget })
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
async function frameworkCommitSettlement(anchor, evidence) {
|
|
581
|
+
try {
|
|
582
|
+
const before = await frameworkCommitChannelIdentity(anchor);
|
|
583
|
+
if (!before || before.role !== evidence.channel.role || before.database !== evidence.channel.database || before.pid !== evidence.channel.pid || before.backendStart !== evidence.channel.backendStart || before.role !== evidence.expectedTarget.setupRole || before.database !== evidence.expectedTarget.database)
|
|
584
|
+
return "unknown";
|
|
585
|
+
const [transaction] = await anchor`
|
|
586
|
+
SELECT pg_catalog.pg_xact_status(${evidence.xid}::pg_catalog.xid8)::text AS status
|
|
587
|
+
`;
|
|
588
|
+
const after = await frameworkCommitChannelIdentity(anchor);
|
|
589
|
+
if (!after || after.role !== evidence.channel.role || after.database !== evidence.channel.database || after.pid !== evidence.channel.pid || after.backendStart !== evidence.channel.backendStart)
|
|
590
|
+
return "unknown";
|
|
591
|
+
if (transaction?.status === "committed")
|
|
592
|
+
return "committed";
|
|
593
|
+
if (transaction?.status === "aborted")
|
|
594
|
+
return "aborted";
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
return "unknown";
|
|
598
|
+
}
|
|
599
|
+
async function readPostgresSchemaCommitOutcome(anchor, operational, plan, framework) {
|
|
600
|
+
const controller = new AbortController();
|
|
601
|
+
const close = () => {
|
|
602
|
+
void anchor.close({ timeout: 0 }).catch(() => {
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
controller.signal.addEventListener("abort", close, { once: true });
|
|
606
|
+
const timer = setTimeout(() => controller.abort(), 5e3);
|
|
607
|
+
let begun = false;
|
|
608
|
+
const channelMatches = async (expected) => {
|
|
609
|
+
const observed = await frameworkCommitChannelIdentity(anchor);
|
|
610
|
+
return Boolean(observed && observed.role === expected.role && observed.database === expected.database && observed.pid === expected.pid && observed.backendStart === expected.backendStart);
|
|
611
|
+
};
|
|
612
|
+
try {
|
|
613
|
+
if (framework && !await channelMatches(framework.expectedChannel))
|
|
614
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
615
|
+
await anchor.unsafe("BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY");
|
|
616
|
+
begun = true;
|
|
617
|
+
if (framework && !await channelMatches(framework.expectedChannel))
|
|
618
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
619
|
+
try {
|
|
620
|
+
await acquirePostgresFrameworkSchemaLock(anchor, controller.signal);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
if (!controller.signal.aborted && !(error instanceof RuntimeDiagnosticError && error.diagnostic.code === "RUNTIME_DATABASE_SETUP_LOCK_TIMEOUT"))
|
|
623
|
+
throw error;
|
|
624
|
+
const failure = runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown");
|
|
625
|
+
throw new RuntimeDiagnosticError({
|
|
626
|
+
...failure.diagnostic,
|
|
627
|
+
retryPrecondition: "Concurrent setup has finished and the original database is responsive; owned readback cleanup must finish before restart.",
|
|
628
|
+
nextAction: "Wait for concurrent setup to finish and verify database availability. After owned cleanup, restart so catalog and access are inspected before any setup replay; do not blindly rerun schema SQL."
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
if (framework && !await channelMatches(framework.expectedChannel))
|
|
632
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
633
|
+
const target = await attestPostgresSchemaTarget(anchor, operational, controller.signal);
|
|
634
|
+
if (framework && (target.database !== framework.expectedTarget.database || target.setupRole !== framework.expectedTarget.setupRole || target.operationalRoles.application !== framework.expectedTarget.applicationRole || target.operationalRoles.maintenance !== framework.expectedTarget.maintenanceRole))
|
|
635
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
636
|
+
if (framework) {
|
|
637
|
+
const observation = await observePostgresFrameworkSchema({
|
|
638
|
+
operational,
|
|
639
|
+
plan: framework.plan,
|
|
640
|
+
runtimePlan: plan,
|
|
641
|
+
signal: controller.signal,
|
|
642
|
+
setup: anchor,
|
|
643
|
+
stage: "readback"
|
|
644
|
+
});
|
|
645
|
+
framework.verify(observation);
|
|
646
|
+
return observation;
|
|
647
|
+
}
|
|
648
|
+
const catalog = await inspectPostgresOperationalSchema(operational, plan, controller.signal);
|
|
649
|
+
if (inspectRuntimeDatabaseSchemaPlan(plan, catalog).some((entry) => entry.steps.length))
|
|
650
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE", "committed");
|
|
651
|
+
return catalog;
|
|
652
|
+
} finally {
|
|
653
|
+
try {
|
|
654
|
+
if (begun)
|
|
655
|
+
await anchor.unsafe("ROLLBACK").catch((error) => {
|
|
656
|
+
if (!controller.signal.aborted)
|
|
657
|
+
throw error;
|
|
658
|
+
});
|
|
659
|
+
} finally {
|
|
660
|
+
clearTimeout(timer);
|
|
661
|
+
controller.signal.removeEventListener("abort", close);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// ../runtime/dist/framework-schema/runtime-plan.js
|
|
667
|
+
function pathAccess(requirements, schema, name) {
|
|
668
|
+
const selected = requirements.filter((entry) => entry.kind === "table" && entry.schema === schema && entry.name === name);
|
|
669
|
+
return {
|
|
670
|
+
paths: [...new Set(selected.flatMap((entry) => [...entry.paths]))],
|
|
671
|
+
privileges: [...new Set(selected.flatMap((entry) => [...entry.privileges]))]
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function projectTable(table, requirements, allowCatalogOnlySequences = false) {
|
|
675
|
+
const access = pathAccess(requirements, table.schema, table.name);
|
|
676
|
+
if (!access.paths.length || !access.privileges.length)
|
|
677
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
678
|
+
const projected = [
|
|
679
|
+
{
|
|
680
|
+
kind: "table",
|
|
681
|
+
schema: table.schema,
|
|
682
|
+
name: table.name,
|
|
683
|
+
columns: table.columns.map(({ name, type, nullable, defaultValue }) => ({
|
|
684
|
+
name,
|
|
685
|
+
type,
|
|
686
|
+
nullable,
|
|
687
|
+
defaultValue
|
|
688
|
+
})),
|
|
689
|
+
constraints: table.constraints.flatMap((constraint) => constraint.kind === "check" ? [] : [
|
|
690
|
+
{
|
|
691
|
+
kind: constraint.kind,
|
|
692
|
+
columns: [...constraint.columns],
|
|
693
|
+
...constraint.target ? { target: constraint.target } : {}
|
|
694
|
+
}
|
|
695
|
+
]),
|
|
696
|
+
rowSecurity: table.rowSecurity,
|
|
697
|
+
paths: access.paths,
|
|
698
|
+
privileges: access.privileges
|
|
699
|
+
}
|
|
700
|
+
];
|
|
701
|
+
for (const index of table.indexes)
|
|
702
|
+
projected.push({
|
|
703
|
+
kind: "index",
|
|
704
|
+
schema: table.schema,
|
|
705
|
+
name: index.name,
|
|
706
|
+
table: table.name,
|
|
707
|
+
keys: index.keys.map((entry) => entry.expression),
|
|
708
|
+
descending: index.keys.filter((entry) => entry.order === "desc").map((entry) => entry.expression),
|
|
709
|
+
predicate: index.predicate
|
|
710
|
+
});
|
|
711
|
+
for (const column of table.columns.filter((entry) => entry.ownedSequence)) {
|
|
712
|
+
const selected = requirements.filter((entry) => entry.kind === "owned-sequence" && entry.schema === table.schema && entry.table === table.name && entry.column === column.name);
|
|
713
|
+
const paths = [...new Set(selected.flatMap((entry) => [...entry.paths]))];
|
|
714
|
+
const privileges = [...new Set(selected.flatMap((entry) => [...entry.privileges]))];
|
|
715
|
+
if (!paths.length || !privileges.length) {
|
|
716
|
+
if (!allowCatalogOnlySequences || selected.length !== 0 || paths.length || privileges.length)
|
|
717
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
718
|
+
}
|
|
719
|
+
projected.push({
|
|
720
|
+
kind: "sequence",
|
|
721
|
+
schema: table.schema,
|
|
722
|
+
creationName: `${table.name}_${column.name}_seq`.slice(0, 63),
|
|
723
|
+
table: table.name,
|
|
724
|
+
column: column.name,
|
|
725
|
+
paths,
|
|
726
|
+
privileges
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
return projected;
|
|
730
|
+
}
|
|
731
|
+
function allFrameworkObjects(plan) {
|
|
732
|
+
const requirements = [
|
|
733
|
+
...plan.features.flatMap((feature) => [...feature.access]),
|
|
734
|
+
...plan.journal ? [...plan.journal.access] : []
|
|
735
|
+
];
|
|
736
|
+
const objects = [];
|
|
737
|
+
for (const feature of plan.features)
|
|
738
|
+
for (const table of feature.targetProjection)
|
|
739
|
+
objects.push(...projectTable(table, requirements));
|
|
740
|
+
if (plan.journal)
|
|
741
|
+
for (const table of plan.journal.projection)
|
|
742
|
+
objects.push(...projectTable(table, requirements, true));
|
|
743
|
+
for (const feature of plan.features)
|
|
744
|
+
objects.push(...feature.adjunctObjects);
|
|
745
|
+
for (const component of plan.customComponents)
|
|
746
|
+
objects.push(...component.objects);
|
|
747
|
+
const seen = /* @__PURE__ */ new Set();
|
|
748
|
+
for (const object of objects) {
|
|
749
|
+
const identity = object.kind === "function" ? `${object.kind}:${object.schema}:${object.name}:()` : object.kind === "trigger" ? `${object.kind}:${object.schema}:${object.table}:${object.name}` : object.kind === "constraint" ? `${object.kind}:${object.schema}:${object.table}:${object.name}` : object.kind === "sequence" && object.name === void 0 ? `${object.kind}:${object.schema}:${object.table}:${object.column}` : `${object.kind}:${object.schema}:${"name" in object ? object.name : ""}`;
|
|
750
|
+
if (seen.has(identity))
|
|
751
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
752
|
+
seen.add(identity);
|
|
753
|
+
}
|
|
754
|
+
return Object.freeze(objects);
|
|
755
|
+
}
|
|
756
|
+
function runtimeSchemaPlanForFramework(plan) {
|
|
757
|
+
const objects = allFrameworkObjects(plan);
|
|
758
|
+
return Object.freeze({
|
|
759
|
+
components: plan.customComponents,
|
|
760
|
+
objects
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ../runtime/dist/framework-schema/migration-execution.js
|
|
765
|
+
var historicalId = "20261013234621_rag_v2_lifecycle_markers";
|
|
766
|
+
var historicalHash = "524d5a6a42b57a9f65e302e90366a777e0554dfb94e10824b710d68328a99330";
|
|
767
|
+
var historicalStatements = [
|
|
768
|
+
'ALTER TABLE "rag_ingest_jobs" ADD COLUMN "retry_revision" integer DEFAULT 0 NOT NULL;',
|
|
769
|
+
'ALTER TABLE "rag_ingest_jobs" ADD COLUMN "writer_fenced_at" timestamp with time zone;',
|
|
770
|
+
'ALTER TABLE "rag_ingest_jobs" ADD COLUMN "finalization_retry_after" timestamp with time zone;',
|
|
771
|
+
'ALTER TABLE "rag_ingest_jobs" ADD COLUMN "finalized_revision" integer;',
|
|
772
|
+
'ALTER TABLE "rag_ingest_jobs" ADD COLUMN "retired_at" timestamp with time zone;',
|
|
773
|
+
'ALTER TABLE "rag_sources" ADD COLUMN "active_ingest_workflow_id" text;'
|
|
774
|
+
];
|
|
775
|
+
function runtimeFrameworkMigrationStatementsForExecution(componentId, migration) {
|
|
776
|
+
if (componentId !== "rag" || migration.migrationId !== historicalId)
|
|
777
|
+
return migration.statements;
|
|
778
|
+
if (migration.hash !== historicalHash || migration.statements.length !== historicalStatements.length || migration.statements.some((statement, index) => statement.trim() !== historicalStatements[index]))
|
|
779
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
780
|
+
return migration.statements.map((statement) => statement.replace(/^\s*ALTER TABLE ("rag_ingest_jobs"|"rag_sources") /u, 'ALTER TABLE "public".$1 '));
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// ../runtime/dist/adapters/database/postgres-framework-transition.js
|
|
784
|
+
import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
|
|
785
|
+
import { sql as sql3 } from "drizzle-orm";
|
|
786
|
+
function invalidComponent() {
|
|
787
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
788
|
+
}
|
|
789
|
+
function invalidHistory2() {
|
|
790
|
+
throw runtimeDatabaseSetupError("RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID");
|
|
791
|
+
}
|
|
792
|
+
function unsatisfiedDependency() {
|
|
793
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_DEPENDENCY_UNSATISFIED");
|
|
794
|
+
}
|
|
795
|
+
function foundationConflict(error) {
|
|
796
|
+
for (let depth = 0; depth < 5 && error && typeof error === "object"; depth++) {
|
|
797
|
+
const state = Reflect.get(error, "errno") ?? Reflect.get(error, "code");
|
|
798
|
+
if ([
|
|
799
|
+
"23505",
|
|
800
|
+
"22P02",
|
|
801
|
+
"42P01",
|
|
802
|
+
"42P07",
|
|
803
|
+
"42703",
|
|
804
|
+
"42804",
|
|
805
|
+
"42809",
|
|
806
|
+
"42830",
|
|
807
|
+
"42883",
|
|
808
|
+
"42P16",
|
|
809
|
+
"42P17"
|
|
810
|
+
].includes(state))
|
|
811
|
+
return true;
|
|
812
|
+
error = Reflect.get(error, "cause");
|
|
813
|
+
}
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
function featureExecutionOrder(plan) {
|
|
817
|
+
const ids = plan.features.map((feature) => feature.componentId);
|
|
818
|
+
const known = new Set(ids);
|
|
819
|
+
if (known.size !== ids.length)
|
|
820
|
+
invalidComponent();
|
|
821
|
+
const edges = plan.dependencies;
|
|
822
|
+
if (!Array.isArray(edges))
|
|
823
|
+
return unsatisfiedDependency();
|
|
824
|
+
for (const edge of edges) {
|
|
825
|
+
if (!edge || !known.has(edge.fromComponentId) || !known.has(edge.componentId) || edge.fromComponentId === edge.componentId || typeof edge.minimumMigrationId !== "string")
|
|
826
|
+
return unsatisfiedDependency();
|
|
827
|
+
const provider = plan.features.find((feature) => feature.componentId === edge.componentId);
|
|
828
|
+
if (!provider?.migrations.migrations.some((migration) => migration.migrationId === edge.minimumMigrationId))
|
|
829
|
+
return unsatisfiedDependency();
|
|
830
|
+
}
|
|
831
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
832
|
+
const visited = /* @__PURE__ */ new Set();
|
|
833
|
+
const ordered = [];
|
|
834
|
+
const visit = (id) => {
|
|
835
|
+
if (visiting.has(id))
|
|
836
|
+
return unsatisfiedDependency();
|
|
837
|
+
if (visited.has(id))
|
|
838
|
+
return;
|
|
839
|
+
visiting.add(id);
|
|
840
|
+
for (const edge of edges)
|
|
841
|
+
if (edge.fromComponentId === id)
|
|
842
|
+
visit(edge.componentId);
|
|
843
|
+
visiting.delete(id);
|
|
844
|
+
visited.add(id);
|
|
845
|
+
ordered.push(id);
|
|
846
|
+
};
|
|
847
|
+
for (const id of ids)
|
|
848
|
+
visit(id);
|
|
849
|
+
return ordered;
|
|
850
|
+
}
|
|
851
|
+
function validateBundle(feature) {
|
|
852
|
+
const bundle = feature.migrations;
|
|
853
|
+
if (!bundle || bundle.componentId !== feature.componentId || !Array.isArray(bundle.migrations) || bundle.migrations.length === 0 || bundle.targetHead !== bundle.migrations.at(-1)?.migrationId)
|
|
854
|
+
return invalidComponent();
|
|
855
|
+
const ids = /* @__PURE__ */ new Set();
|
|
856
|
+
for (const [index, migration] of bundle.migrations.entries()) {
|
|
857
|
+
if (!migration || typeof migration.migrationId !== "string" || ids.has(migration.migrationId) || migration.migrationOrder !== index + 1 || !Number.isSafeInteger(migration.createdAt) || migration.createdAt <= 0 || !/^[0-9a-f]{64}$/u.test(migration.hash) || migration.executionEligibility !== "startup-compatible" && migration.executionEligibility !== "owner-maintenance" || !Array.isArray(migration.statements) || migration.statements.length === 0 || migration.statements.some((statement) => typeof statement !== "string" || !statement.trim()))
|
|
858
|
+
return invalidComponent();
|
|
859
|
+
ids.add(migration.migrationId);
|
|
860
|
+
}
|
|
861
|
+
return bundle.migrations;
|
|
862
|
+
}
|
|
863
|
+
function resolveFeatureTransitions(plan, transitions) {
|
|
864
|
+
if (!Array.isArray(transitions))
|
|
865
|
+
return invalidComponent();
|
|
866
|
+
const expectedOrder = featureExecutionOrder(plan);
|
|
867
|
+
if (transitions.length !== expectedOrder.length)
|
|
868
|
+
return invalidComponent();
|
|
869
|
+
const resolved = [];
|
|
870
|
+
for (const [index, transition] of transitions.entries()) {
|
|
871
|
+
if (!transition || transition.componentId !== expectedOrder[index])
|
|
872
|
+
return invalidComponent();
|
|
873
|
+
const feature = plan.features.find((candidate) => candidate.componentId === transition.componentId);
|
|
874
|
+
if (!feature || !Array.isArray(transition.baselineMigrationIds) || !Array.isArray(transition.appliedMigrationIds) || !Array.isArray(transition.migrationIds))
|
|
875
|
+
return invalidComponent();
|
|
876
|
+
const migrations = validateBundle(feature);
|
|
877
|
+
const baselineIds = transition.baselineMigrationIds;
|
|
878
|
+
const appliedIds = transition.appliedMigrationIds;
|
|
879
|
+
const migrationIds = transition.migrationIds;
|
|
880
|
+
if ([...baselineIds, ...appliedIds, ...migrationIds].some((migrationId) => typeof migrationId !== "string") || baselineIds.length > 0 && appliedIds.length > 0 || baselineIds.length + appliedIds.length + migrationIds.length > migrations.length)
|
|
881
|
+
return invalidHistory2();
|
|
882
|
+
let foundationBootstrap;
|
|
883
|
+
if (transition.foundationBootstrap !== void 0) {
|
|
884
|
+
const admitted = transition.foundationBootstrap;
|
|
885
|
+
const captured = feature.foundationBootstrap;
|
|
886
|
+
const supportedBaselineCount = feature.componentId === "workflow" ? baselineIds.length === 0 : feature.componentId === "rag" && baselineIds.length === 1;
|
|
887
|
+
if (!captured || !admitted || admitted.artifactId !== captured.artifactId || admitted.hash !== captured.hash || !supportedBaselineCount || appliedIds.length !== 0 || baselineIds.some((id, position) => id !== migrations[position]?.migrationId))
|
|
888
|
+
return invalidHistory2();
|
|
889
|
+
if (captured.executionEligibility !== "startup-compatible" || migrations[0]?.executionEligibility !== "startup-compatible")
|
|
890
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_MAINTENANCE_REQUIRED");
|
|
891
|
+
foundationBootstrap = captured;
|
|
892
|
+
}
|
|
893
|
+
const baseline = migrations.slice(0, baselineIds.length);
|
|
894
|
+
const applied = migrations.slice(baselineIds.length, baselineIds.length + appliedIds.length);
|
|
895
|
+
const pending = migrations.slice(baselineIds.length + appliedIds.length, baselineIds.length + appliedIds.length + migrationIds.length);
|
|
896
|
+
if (baseline.some((migration, position) => migration.migrationId !== baselineIds[position]) || applied.some((migration, position) => migration.migrationId !== appliedIds[position]) || pending.some((migration, position) => migration.migrationId !== migrationIds[position]))
|
|
897
|
+
return invalidHistory2();
|
|
898
|
+
resolved.push(Object.freeze({
|
|
899
|
+
componentId: feature.componentId,
|
|
900
|
+
...foundationBootstrap ? { foundationBootstrap } : {},
|
|
901
|
+
baseline,
|
|
902
|
+
migrations: pending
|
|
903
|
+
}));
|
|
904
|
+
}
|
|
905
|
+
return Object.freeze(resolved);
|
|
906
|
+
}
|
|
907
|
+
function validateCustomTransitions(plan, runtimePlan, transitions) {
|
|
908
|
+
if (!Array.isArray(plan.customComponents) || !Array.isArray(runtimePlan?.components) || !Array.isArray(transitions))
|
|
909
|
+
return invalidComponent();
|
|
910
|
+
const customComponents = plan.customComponents;
|
|
911
|
+
const runtimeComponents = runtimePlan.components;
|
|
912
|
+
const admittedTransitions = transitions;
|
|
913
|
+
if (admittedTransitions.length !== customComponents.length)
|
|
914
|
+
return invalidComponent();
|
|
915
|
+
const planById = /* @__PURE__ */ new Map();
|
|
916
|
+
const runtimeById = /* @__PURE__ */ new Map();
|
|
917
|
+
const positions = /* @__PURE__ */ new Map();
|
|
918
|
+
customComponents.forEach((component, index) => {
|
|
919
|
+
planById.set(component.id, component);
|
|
920
|
+
positions.set(component.id, index);
|
|
921
|
+
});
|
|
922
|
+
runtimeComponents.forEach((component) => runtimeById.set(component.id, component));
|
|
923
|
+
if (planById.size !== customComponents.length || runtimeById.size !== runtimeComponents.length)
|
|
924
|
+
return invalidComponent();
|
|
925
|
+
for (const [index, component] of customComponents.entries()) {
|
|
926
|
+
if (!component || typeof component.id !== "string" || !Array.isArray(component.dependsOn))
|
|
927
|
+
return invalidComponent();
|
|
928
|
+
for (const dependency of component.dependsOn) {
|
|
929
|
+
const dependencyPosition = positions.get(dependency);
|
|
930
|
+
if (dependencyPosition === void 0)
|
|
931
|
+
return unsatisfiedDependency();
|
|
932
|
+
if (dependencyPosition >= index)
|
|
933
|
+
return unsatisfiedDependency();
|
|
934
|
+
}
|
|
935
|
+
const runtimeComponent = runtimeById.get(component.id);
|
|
936
|
+
if (!runtimeComponent || !isDeepStrictEqual2(runtimeComponent, component))
|
|
937
|
+
return invalidComponent();
|
|
938
|
+
}
|
|
939
|
+
const resolved = [];
|
|
940
|
+
for (const [index, transition] of admittedTransitions.entries()) {
|
|
941
|
+
const component = customComponents[index];
|
|
942
|
+
if (!transition || !component || transition.componentId !== component.id || !Array.isArray(transition.stepIds))
|
|
943
|
+
return invalidComponent();
|
|
944
|
+
const selected = transition.stepIds;
|
|
945
|
+
if (selected.some((stepId) => typeof stepId !== "string") || new Set(selected).size !== selected.length)
|
|
946
|
+
return invalidComponent();
|
|
947
|
+
const steps = component.steps;
|
|
948
|
+
const expected = steps.filter((step) => selected.includes(step.id));
|
|
949
|
+
if (expected.length !== selected.length || expected.some((step, position) => step.id !== selected[position]))
|
|
950
|
+
return invalidComponent();
|
|
951
|
+
resolved.push(Object.freeze({ componentId: component.id, stepIds: Object.freeze([...selected]) }));
|
|
952
|
+
}
|
|
953
|
+
return Object.freeze(resolved);
|
|
954
|
+
}
|
|
955
|
+
function resolveGrants(plan, roles, grants) {
|
|
956
|
+
if (!Array.isArray(grants))
|
|
957
|
+
return invalidComponent();
|
|
958
|
+
const requirements = frameworkAccessRequirements(plan);
|
|
959
|
+
const admittedGrants = grants;
|
|
960
|
+
let previousRank = -1;
|
|
961
|
+
const seen = /* @__PURE__ */ new Set();
|
|
962
|
+
for (const grant of admittedGrants) {
|
|
963
|
+
if (!grant || !Number.isSafeInteger(grant.requirementIndex))
|
|
964
|
+
return invalidComponent();
|
|
965
|
+
const requirement = requirements[grant.requirementIndex];
|
|
966
|
+
if (!requirement || grant.path !== "application" && grant.path !== "maintenance" || !requirement.paths.includes(grant.path) || !requirement.privileges.includes(grant.privilege) || typeof roles[grant.path] !== "string" || !roles[grant.path].trim())
|
|
967
|
+
return invalidComponent();
|
|
968
|
+
if (requirement.kind === "table" && (typeof requirement.name !== "string" || !requirement.name))
|
|
969
|
+
return invalidComponent();
|
|
970
|
+
if (requirement.kind === "owned-sequence" && (typeof requirement.table !== "string" || !requirement.table || typeof requirement.column !== "string" || !requirement.column))
|
|
971
|
+
return invalidComponent();
|
|
972
|
+
const pathRank = requirement.paths.indexOf(grant.path);
|
|
973
|
+
const privilegeRank = requirement.privileges.indexOf(grant.privilege);
|
|
974
|
+
const rank = grant.requirementIndex * 1e6 + pathRank * 1e3 + privilegeRank;
|
|
975
|
+
const key = `${grant.requirementIndex}\0${grant.path}\0${grant.privilege}`;
|
|
976
|
+
if (seen.has(key) || rank <= previousRank)
|
|
977
|
+
return invalidComponent();
|
|
978
|
+
seen.add(key);
|
|
979
|
+
previousRank = rank;
|
|
980
|
+
}
|
|
981
|
+
return Object.freeze({ grants: Object.freeze([...grants]), requirements });
|
|
982
|
+
}
|
|
983
|
+
function resolveTransition(input) {
|
|
984
|
+
const { plan, runtimePlan, roles, transition } = input;
|
|
985
|
+
if (!plan || plan.kind !== "runtime-framework-schema" || !transition || typeof transition.bootstrapJournal !== "boolean" || !Array.isArray(plan.features) || !Array.isArray(transition.features) || !Array.isArray(transition.customComponents) || !Array.isArray(transition.grants))
|
|
986
|
+
return invalidComponent();
|
|
987
|
+
let bootstrap;
|
|
988
|
+
if (transition.bootstrapJournal) {
|
|
989
|
+
const artifact = plan.journal?.bootstrap;
|
|
990
|
+
if (!artifact || typeof artifact.artifactId !== "string" || !artifact.artifactId || !/^[0-9a-f]{64}$/u.test(artifact.hash) || typeof artifact.sql !== "string" || !artifact.sql.trim())
|
|
991
|
+
return invalidComponent();
|
|
992
|
+
bootstrap = artifact.sql;
|
|
993
|
+
}
|
|
994
|
+
const features = resolveFeatureTransitions(plan, transition.features);
|
|
995
|
+
if (features.some((feature) => feature.migrations.some((migration) => migration.executionEligibility === "owner-maintenance")))
|
|
996
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_MAINTENANCE_REQUIRED");
|
|
997
|
+
const customComponents = validateCustomTransitions(plan, runtimePlan, transition.customComponents);
|
|
998
|
+
const { grants, requirements } = resolveGrants(plan, roles, transition.grants);
|
|
999
|
+
return Object.freeze({
|
|
1000
|
+
...bootstrap ? { bootstrap } : {},
|
|
1001
|
+
features,
|
|
1002
|
+
customComponents,
|
|
1003
|
+
grants,
|
|
1004
|
+
requirements
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
async function applyGrant2(database, requirements, roles, input, markWritesAttempted) {
|
|
1008
|
+
const requirement = requirements[input.requirementIndex];
|
|
1009
|
+
if (!requirement)
|
|
1010
|
+
return invalidComponent();
|
|
1011
|
+
const role = roles[input.path];
|
|
1012
|
+
if (requirement.kind === "schema") {
|
|
1013
|
+
if (input.privilege !== "USAGE")
|
|
1014
|
+
return invalidComponent();
|
|
1015
|
+
const [observed2] = schemaCatalogRows(await database.execute(sql3`
|
|
1016
|
+
SELECT pg_catalog.has_schema_privilege(${role},namespace.oid,'USAGE') AS allowed
|
|
1017
|
+
FROM pg_catalog.pg_namespace namespace WHERE namespace.nspname=${requirement.schema}
|
|
1018
|
+
`));
|
|
1019
|
+
if (!observed2)
|
|
1020
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
1021
|
+
if (!observed2.allowed) {
|
|
1022
|
+
markWritesAttempted();
|
|
1023
|
+
await database.execute(sql3`
|
|
1024
|
+
GRANT USAGE ON SCHEMA ${sql3.identifier(requirement.schema)} TO ${sql3.identifier(role)}
|
|
1025
|
+
`);
|
|
1026
|
+
}
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
let name;
|
|
1030
|
+
let kind;
|
|
1031
|
+
if (requirement.kind === "table") {
|
|
1032
|
+
name = requirement.name;
|
|
1033
|
+
kind = "table";
|
|
1034
|
+
} else {
|
|
1035
|
+
const sequences = schemaCatalogRows(await database.execute(sql3`
|
|
1036
|
+
SELECT sequence_relation.relname AS name
|
|
1037
|
+
FROM pg_catalog.pg_class sequence_relation
|
|
1038
|
+
JOIN pg_catalog.pg_namespace sequence_namespace ON sequence_namespace.oid=sequence_relation.relnamespace
|
|
1039
|
+
JOIN pg_catalog.pg_depend ownership ON ownership.classid='pg_catalog.pg_class'::regclass
|
|
1040
|
+
AND ownership.objid=sequence_relation.oid AND ownership.refclassid='pg_catalog.pg_class'::regclass
|
|
1041
|
+
AND ownership.deptype IN ('a','i')
|
|
1042
|
+
JOIN pg_catalog.pg_class relation ON relation.oid=ownership.refobjid
|
|
1043
|
+
JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace
|
|
1044
|
+
JOIN pg_catalog.pg_attribute attribute ON attribute.attrelid=relation.oid
|
|
1045
|
+
AND attribute.attnum=ownership.refobjsubid
|
|
1046
|
+
JOIN pg_catalog.pg_attrdef defaults ON defaults.adrelid=relation.oid
|
|
1047
|
+
AND defaults.adnum=attribute.attnum
|
|
1048
|
+
JOIN pg_catalog.pg_depend linkage ON linkage.classid='pg_catalog.pg_attrdef'::regclass
|
|
1049
|
+
AND linkage.objid=defaults.oid AND linkage.refclassid='pg_catalog.pg_class'::regclass
|
|
1050
|
+
AND linkage.refobjid=sequence_relation.oid
|
|
1051
|
+
WHERE sequence_relation.relkind='S' AND sequence_namespace.nspname=${requirement.schema}
|
|
1052
|
+
AND namespace.nspname=${requirement.schema} AND relation.relname=${requirement.table}
|
|
1053
|
+
AND attribute.attname=${requirement.column}
|
|
1054
|
+
`));
|
|
1055
|
+
if (sequences.length !== 1)
|
|
1056
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
1057
|
+
name = sequences[0].name;
|
|
1058
|
+
kind = "sequence";
|
|
1059
|
+
}
|
|
1060
|
+
const [observed] = schemaCatalogRows(await database.execute(sql3`
|
|
1061
|
+
SELECT ${kind === "table" ? sql3`pg_catalog.has_table_privilege(${role},relation.oid,${input.privilege})` : sql3`pg_catalog.has_sequence_privilege(${role},relation.oid,${input.privilege})`} AS allowed
|
|
1062
|
+
FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace
|
|
1063
|
+
ON namespace.oid=relation.relnamespace
|
|
1064
|
+
WHERE namespace.nspname=${requirement.schema} AND relation.relname=${name}
|
|
1065
|
+
AND relation.relkind=${kind === "table" ? "r" : "S"}
|
|
1066
|
+
`));
|
|
1067
|
+
if (!observed)
|
|
1068
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
1069
|
+
if (!observed.allowed) {
|
|
1070
|
+
markWritesAttempted();
|
|
1071
|
+
await database.execute(sql3`
|
|
1072
|
+
GRANT ${sql3.raw(input.privilege)} ON ${sql3.raw(kind === "sequence" ? "SEQUENCE" : "TABLE")}
|
|
1073
|
+
${sql3.identifier(requirement.schema)}.${sql3.identifier(name)} TO ${sql3.identifier(role)}
|
|
1074
|
+
`);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
async function insertJournalRow(database, row) {
|
|
1078
|
+
await database.execute(sql3`
|
|
1079
|
+
INSERT INTO ${sql3.identifier("drizzle")}.${sql3.identifier("__gencow_framework_migrations")}
|
|
1080
|
+
(component_id,migration_id,migration_order,hash,created_at,applied_via)
|
|
1081
|
+
VALUES (${row.componentId},${row.migrationId},${row.migrationOrder},${row.hash},${row.createdAt},${row.appliedVia})
|
|
1082
|
+
`);
|
|
1083
|
+
}
|
|
1084
|
+
async function applyPostgresFrameworkTransition(input) {
|
|
1085
|
+
const { database, plan, runtimePlan, roles, transition, observeAfterFoundation, markWritesAttempted } = input;
|
|
1086
|
+
if (!database || typeof database.execute !== "function" || typeof markWritesAttempted !== "function")
|
|
1087
|
+
return invalidComponent();
|
|
1088
|
+
const resolved = resolveTransition({ plan, runtimePlan, roles, transition });
|
|
1089
|
+
const foundations = resolved.features.flatMap((feature) => feature.foundationBootstrap ? [
|
|
1090
|
+
Object.freeze({
|
|
1091
|
+
componentId: feature.componentId,
|
|
1092
|
+
artifactId: feature.foundationBootstrap.artifactId,
|
|
1093
|
+
hash: feature.foundationBootstrap.hash,
|
|
1094
|
+
baselineMigrationIds: Object.freeze(feature.baseline.map((migration) => migration.migrationId))
|
|
1095
|
+
})
|
|
1096
|
+
] : []);
|
|
1097
|
+
if (foundations.length && typeof observeAfterFoundation !== "function")
|
|
1098
|
+
return invalidComponent();
|
|
1099
|
+
if (resolved.bootstrap !== void 0) {
|
|
1100
|
+
markWritesAttempted();
|
|
1101
|
+
await database.execute(sql3.raw(resolved.bootstrap));
|
|
1102
|
+
}
|
|
1103
|
+
for (const feature of resolved.features) {
|
|
1104
|
+
if (!feature.foundationBootstrap)
|
|
1105
|
+
continue;
|
|
1106
|
+
markWritesAttempted();
|
|
1107
|
+
try {
|
|
1108
|
+
await database.execute(sql3.raw(feature.foundationBootstrap.sql));
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
if (foundationConflict(error))
|
|
1111
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
|
|
1112
|
+
throw error;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
if (foundations.length)
|
|
1116
|
+
await observeAfterFoundation(Object.freeze(foundations));
|
|
1117
|
+
for (const feature of resolved.features) {
|
|
1118
|
+
for (const migration of feature.baseline) {
|
|
1119
|
+
markWritesAttempted();
|
|
1120
|
+
await insertJournalRow(database, {
|
|
1121
|
+
componentId: feature.componentId,
|
|
1122
|
+
migrationId: migration.migrationId,
|
|
1123
|
+
migrationOrder: migration.migrationOrder,
|
|
1124
|
+
hash: migration.hash,
|
|
1125
|
+
createdAt: migration.createdAt,
|
|
1126
|
+
appliedVia: "baseline"
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
for (const migration of feature.migrations) {
|
|
1130
|
+
for (const statement of runtimeFrameworkMigrationStatementsForExecution(feature.componentId, migration)) {
|
|
1131
|
+
markWritesAttempted();
|
|
1132
|
+
await database.execute(sql3.raw(statement));
|
|
1133
|
+
}
|
|
1134
|
+
markWritesAttempted();
|
|
1135
|
+
await insertJournalRow(database, {
|
|
1136
|
+
componentId: feature.componentId,
|
|
1137
|
+
migrationId: migration.migrationId,
|
|
1138
|
+
migrationOrder: migration.migrationOrder,
|
|
1139
|
+
hash: migration.hash,
|
|
1140
|
+
createdAt: migration.createdAt,
|
|
1141
|
+
appliedVia: "migration"
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
for (const component of resolved.customComponents)
|
|
1146
|
+
for (const stepId of component.stepIds) {
|
|
1147
|
+
markWritesAttempted();
|
|
1148
|
+
await applyRuntimeDatabaseSchemaStep(database, runtimePlan, roles, component.componentId, stepId);
|
|
1149
|
+
}
|
|
1150
|
+
for (const grant of resolved.grants)
|
|
1151
|
+
await applyGrant2(database, resolved.requirements, roles, grant, markWritesAttempted);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// ../runtime/dist/adapters/database/postgres-schema-owner.js
|
|
1155
|
+
function active3(signal) {
|
|
1156
|
+
if (signal.aborted)
|
|
1157
|
+
throw runtimeDatabaseSetupInterrupted(signal);
|
|
1158
|
+
}
|
|
1159
|
+
function createPostgresSchemaProviderPort(input) {
|
|
1160
|
+
const binding = parseRuntimePostgresBinding(input.binding);
|
|
1161
|
+
const operational = Object.freeze({ ...input.operational });
|
|
1162
|
+
const warnings = input.warnings;
|
|
1163
|
+
const config = binding.kind === "local" && binding.setup ? resolveRuntimePostgresDriverConfig(binding.setup.databaseUrl) : void 0;
|
|
1164
|
+
const frameworkPlan = input.frameworkTargetPlan;
|
|
1165
|
+
const frameworkRuntimePlan = frameworkPlan ? runtimeSchemaPlanForFramework(frameworkPlan) : void 0;
|
|
1166
|
+
async function inspectFrameworkOperational(plan, signal, stage, setupSession) {
|
|
1167
|
+
if (!frameworkRuntimePlan)
|
|
1168
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1169
|
+
return observePostgresFrameworkSchema({
|
|
1170
|
+
operational,
|
|
1171
|
+
plan,
|
|
1172
|
+
runtimePlan: runtimeSchemaPlanForFramework(plan),
|
|
1173
|
+
signal,
|
|
1174
|
+
...setupSession ? { setup: setupSession } : {},
|
|
1175
|
+
stage
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
async function withSetupTransaction(plan, parent, execute, selectedFrameworkPlan, executeFramework) {
|
|
1179
|
+
if (!config)
|
|
1180
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_AUTHORITY_INVALID");
|
|
1181
|
+
active3(parent);
|
|
1182
|
+
const correlationId = randomUUID();
|
|
1183
|
+
const deadline = new AbortController();
|
|
1184
|
+
const signal = AbortSignal.any([parent, deadline.signal]);
|
|
1185
|
+
const timer = setTimeout(() => deadline.abort(runtimeDatabaseSetupDeadlineReason), 3e4);
|
|
1186
|
+
let setupPool, cancellationPool;
|
|
1187
|
+
let setup, channel;
|
|
1188
|
+
let cancellation;
|
|
1189
|
+
let cancellationPending;
|
|
1190
|
+
let cleanupTimer;
|
|
1191
|
+
let forcedClose = false, begun = false, writesAttempted = false, commitDispatched = false;
|
|
1192
|
+
let sqlActive = 0;
|
|
1193
|
+
let receipt, failure;
|
|
1194
|
+
let frameworkCommitEvidence;
|
|
1195
|
+
const forcedClosures = [];
|
|
1196
|
+
const forceClose = () => {
|
|
1197
|
+
if (forcedClose)
|
|
1198
|
+
return;
|
|
1199
|
+
forcedClose = true;
|
|
1200
|
+
for (const resource of [setup, channel, setupPool, cancellationPool])
|
|
1201
|
+
if (resource) {
|
|
1202
|
+
const closing = resource.close({ timeout: 0 });
|
|
1203
|
+
forcedClosures.push(closing);
|
|
1204
|
+
void closing.catch(() => {
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
const armCleanup = () => {
|
|
1209
|
+
cleanupTimer ??= setTimeout(forceClose, 5e3);
|
|
1210
|
+
};
|
|
1211
|
+
const abort = () => {
|
|
1212
|
+
if (!cancellation) {
|
|
1213
|
+
forceClose();
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
armCleanup();
|
|
1217
|
+
if (!commitDispatched && sqlActive > 0) {
|
|
1218
|
+
cancellationPending ??= cancellation.cancel().catch(() => false);
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
1221
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1222
|
+
try {
|
|
1223
|
+
const Constructor = await loadRuntimePostgresSql();
|
|
1224
|
+
active3(signal);
|
|
1225
|
+
const options = {
|
|
1226
|
+
...config.options,
|
|
1227
|
+
max: 1,
|
|
1228
|
+
connectionTimeout: Math.min(Number(config.options.connectionTimeout ?? 5), 5),
|
|
1229
|
+
connection: { ...config.options.connection, application_name: "gencow-framework-setup" }
|
|
1230
|
+
};
|
|
1231
|
+
setupPool = new Constructor(config.url, options);
|
|
1232
|
+
cancellationPool = new Constructor(config.url, {
|
|
1233
|
+
...options,
|
|
1234
|
+
connection: { ...options.connection, application_name: "gencow-framework-cancel" }
|
|
1235
|
+
});
|
|
1236
|
+
setup = await setupPool.reserve({ signal });
|
|
1237
|
+
channel = await cancellationPool.reserve({ signal });
|
|
1238
|
+
active3(signal);
|
|
1239
|
+
await setup.unsafe("BEGIN");
|
|
1240
|
+
begun = true;
|
|
1241
|
+
await setup.unsafe("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
|
|
1242
|
+
const proof = await attestPostgresSchemaTarget(setup, operational, signal);
|
|
1243
|
+
cancellation = await createPostgresSchemaCancellation(setup, channel, proof);
|
|
1244
|
+
if (!await cancellation.matchesTarget())
|
|
1245
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
1246
|
+
if (binding.kind === "local" && binding.setup && "expectedRole" in binding.setup && (binding.setup.expectedRole !== proof.setupRole || binding.setup.expectedDatabase !== proof.database))
|
|
1247
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_AUTHORITY_INVALID");
|
|
1248
|
+
active3(signal);
|
|
1249
|
+
if (proof.setupRole === proof.operationalRoles.application || proof.setupRole === proof.operationalRoles.maintenance)
|
|
1250
|
+
warnings.observe(["shared-setup-role"]);
|
|
1251
|
+
try {
|
|
1252
|
+
warnings.beforeMutation?.();
|
|
1253
|
+
} catch {
|
|
1254
|
+
}
|
|
1255
|
+
await acquirePostgresFrameworkSchemaLock(setup, signal);
|
|
1256
|
+
const { drizzle } = await import("drizzle-orm/bun-sql");
|
|
1257
|
+
const database = drizzle({ client: runtimePostgresClient(setup) });
|
|
1258
|
+
const scoped = {
|
|
1259
|
+
async execute(query) {
|
|
1260
|
+
active3(signal);
|
|
1261
|
+
sqlActive++;
|
|
1262
|
+
try {
|
|
1263
|
+
return await database.execute(query);
|
|
1264
|
+
} finally {
|
|
1265
|
+
sqlActive--;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
};
|
|
1269
|
+
const legacySession = Object.freeze({
|
|
1270
|
+
inspect: async () => {
|
|
1271
|
+
active3(signal);
|
|
1272
|
+
return readRuntimeDatabaseSchemaCatalog(scoped, plan, proof.operationalRoles);
|
|
1273
|
+
},
|
|
1274
|
+
async applyStep(componentId, stepId) {
|
|
1275
|
+
active3(signal);
|
|
1276
|
+
writesAttempted = true;
|
|
1277
|
+
await applyRuntimeDatabaseSchemaStep(scoped, plan, proof.operationalRoles, componentId, stepId);
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
if (selectedFrameworkPlan) {
|
|
1281
|
+
if (selectedFrameworkPlan !== frameworkPlan || !frameworkRuntimePlan || !isDeepStrictEqual3(plan, frameworkRuntimePlan) || !executeFramework)
|
|
1282
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1283
|
+
let transitionAttempted = false;
|
|
1284
|
+
let transactionPostimage;
|
|
1285
|
+
const frameworkSession = Object.freeze({
|
|
1286
|
+
observe: async () => {
|
|
1287
|
+
active3(signal);
|
|
1288
|
+
return observePostgresFrameworkSchemaInTransaction({
|
|
1289
|
+
session: setup,
|
|
1290
|
+
roles: {
|
|
1291
|
+
...proof.operationalRoles,
|
|
1292
|
+
setup: proof.setupRole,
|
|
1293
|
+
database: proof.database
|
|
1294
|
+
},
|
|
1295
|
+
operational,
|
|
1296
|
+
plan: selectedFrameworkPlan,
|
|
1297
|
+
runtimePlan: frameworkRuntimePlan,
|
|
1298
|
+
signal,
|
|
1299
|
+
stage: transitionAttempted ? "precommit" : "prewrite"
|
|
1300
|
+
});
|
|
1301
|
+
},
|
|
1302
|
+
async executeAdmittedTransition(transition) {
|
|
1303
|
+
active3(signal);
|
|
1304
|
+
if (transitionAttempted)
|
|
1305
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1306
|
+
transitionAttempted = true;
|
|
1307
|
+
const fresh = await observePostgresFrameworkSchemaInTransaction({
|
|
1308
|
+
session: setup,
|
|
1309
|
+
roles: {
|
|
1310
|
+
...proof.operationalRoles,
|
|
1311
|
+
setup: proof.setupRole,
|
|
1312
|
+
database: proof.database
|
|
1313
|
+
},
|
|
1314
|
+
operational,
|
|
1315
|
+
plan: selectedFrameworkPlan,
|
|
1316
|
+
runtimePlan: frameworkRuntimePlan,
|
|
1317
|
+
signal,
|
|
1318
|
+
stage: "prewrite"
|
|
1319
|
+
});
|
|
1320
|
+
assertLocalPostgresSecurityPolicy(selectedFrameworkPlan.policy, withSecurityStage(fresh, "prewrite").security, warnings);
|
|
1321
|
+
const admitted = transitionForObservation(selectedFrameworkPlan, fresh);
|
|
1322
|
+
if (!isDeepStrictEqual3(admitted, transition))
|
|
1323
|
+
throw runtimeDatabaseSetupError("RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID");
|
|
1324
|
+
if (hasFrameworkSchemaTransition(admitted))
|
|
1325
|
+
await applyPostgresFrameworkTransition({
|
|
1326
|
+
database: scoped,
|
|
1327
|
+
plan: selectedFrameworkPlan,
|
|
1328
|
+
runtimePlan: frameworkRuntimePlan,
|
|
1329
|
+
roles: proof.operationalRoles,
|
|
1330
|
+
transition: admitted,
|
|
1331
|
+
async observeAfterFoundation(bootstraps) {
|
|
1332
|
+
active3(signal);
|
|
1333
|
+
const foundation = await observePostgresFrameworkSchemaInTransaction({
|
|
1334
|
+
session: setup,
|
|
1335
|
+
roles: {
|
|
1336
|
+
...proof.operationalRoles,
|
|
1337
|
+
setup: proof.setupRole,
|
|
1338
|
+
database: proof.database
|
|
1339
|
+
},
|
|
1340
|
+
operational,
|
|
1341
|
+
plan: selectedFrameworkPlan,
|
|
1342
|
+
runtimePlan: frameworkRuntimePlan,
|
|
1343
|
+
signal,
|
|
1344
|
+
stage: "precommit"
|
|
1345
|
+
});
|
|
1346
|
+
verifyFrameworkFoundationPostimage(selectedFrameworkPlan, foundation, bootstraps);
|
|
1347
|
+
},
|
|
1348
|
+
markWritesAttempted() {
|
|
1349
|
+
writesAttempted = true;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
active3(signal);
|
|
1353
|
+
transactionPostimage = await observePostgresFrameworkSchemaInTransaction({
|
|
1354
|
+
session: setup,
|
|
1355
|
+
roles: {
|
|
1356
|
+
...proof.operationalRoles,
|
|
1357
|
+
setup: proof.setupRole,
|
|
1358
|
+
database: proof.database
|
|
1359
|
+
},
|
|
1360
|
+
operational,
|
|
1361
|
+
plan: selectedFrameworkPlan,
|
|
1362
|
+
runtimePlan: frameworkRuntimePlan,
|
|
1363
|
+
signal,
|
|
1364
|
+
stage: "precommit"
|
|
1365
|
+
});
|
|
1366
|
+
assertLocalPostgresSecurityPolicy(selectedFrameworkPlan.policy, withSecurityStage(transactionPostimage, "precommit").security, warnings);
|
|
1367
|
+
verifyFrameworkSchemaPostimage(selectedFrameworkPlan, transactionPostimage);
|
|
1368
|
+
return transactionPostimage;
|
|
1369
|
+
}
|
|
1370
|
+
});
|
|
1371
|
+
await executeFramework(frameworkSession);
|
|
1372
|
+
if (!transitionAttempted || !transactionPostimage)
|
|
1373
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1374
|
+
} else {
|
|
1375
|
+
if (executeFramework)
|
|
1376
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1377
|
+
await execute(legacySession);
|
|
1378
|
+
}
|
|
1379
|
+
if (selectedFrameworkPlan) {
|
|
1380
|
+
if (!cancellation || !channel)
|
|
1381
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1382
|
+
if (!await cancellation.matchesTarget())
|
|
1383
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
1384
|
+
frameworkCommitEvidence = await captureFrameworkCommitEvidence({
|
|
1385
|
+
setup,
|
|
1386
|
+
anchor: channel,
|
|
1387
|
+
expectedTarget: {
|
|
1388
|
+
database: proof.database,
|
|
1389
|
+
applicationRole: proof.operationalRoles.application,
|
|
1390
|
+
maintenanceRole: proof.operationalRoles.maintenance,
|
|
1391
|
+
setupRole: proof.setupRole
|
|
1392
|
+
}
|
|
1393
|
+
});
|
|
1394
|
+
if (!await cancellation.matchesTarget())
|
|
1395
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_TARGET_MISMATCH");
|
|
1396
|
+
}
|
|
1397
|
+
active3(signal);
|
|
1398
|
+
const commit = setup.unsafe("COMMIT");
|
|
1399
|
+
active3(signal);
|
|
1400
|
+
commitDispatched = true;
|
|
1401
|
+
await commit.execute();
|
|
1402
|
+
begun = false;
|
|
1403
|
+
const impact = writesAttempted ? "committed" : "none";
|
|
1404
|
+
receipt = Object.freeze({ impact });
|
|
1405
|
+
if (selectedFrameworkPlan) {
|
|
1406
|
+
if (!frameworkCommitEvidence)
|
|
1407
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1408
|
+
const observed = await readPostgresSchemaCommitOutcome(channel, operational, plan, {
|
|
1409
|
+
plan: selectedFrameworkPlan,
|
|
1410
|
+
expectedTarget: frameworkCommitEvidence.expectedTarget,
|
|
1411
|
+
expectedChannel: frameworkCommitEvidence.channel,
|
|
1412
|
+
verify(observation) {
|
|
1413
|
+
assertLocalPostgresSecurityPolicy(selectedFrameworkPlan.policy, withSecurityStage(observation, "readback").security, warnings);
|
|
1414
|
+
verifyFrameworkSchemaPostimage(selectedFrameworkPlan, observation);
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
if (!("target" in observed) || !("catalog" in observed))
|
|
1418
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1419
|
+
receipt = Object.freeze({ impact, frameworkObservation: observed });
|
|
1420
|
+
} else {
|
|
1421
|
+
const catalog = await readPostgresSchemaCommitOutcome(channel, operational, plan);
|
|
1422
|
+
receipt = Object.freeze({ impact, operationalCatalog: catalog });
|
|
1423
|
+
}
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
if (commitDispatched) {
|
|
1426
|
+
if (receipt)
|
|
1427
|
+
failure = classifyPostgresSchemaFailure(error, receipt.impact, correlationId, signal);
|
|
1428
|
+
else if (selectedFrameworkPlan) {
|
|
1429
|
+
const settlement = channel && frameworkCommitEvidence ? await frameworkCommitSettlement(channel, frameworkCommitEvidence) : "unknown";
|
|
1430
|
+
if (settlement === "committed" && channel && frameworkCommitEvidence) {
|
|
1431
|
+
begun = false;
|
|
1432
|
+
const impact = writesAttempted ? "committed" : "none";
|
|
1433
|
+
receipt = Object.freeze({ impact });
|
|
1434
|
+
try {
|
|
1435
|
+
const observed = await readPostgresSchemaCommitOutcome(channel, operational, plan, {
|
|
1436
|
+
plan: selectedFrameworkPlan,
|
|
1437
|
+
expectedTarget: frameworkCommitEvidence.expectedTarget,
|
|
1438
|
+
expectedChannel: frameworkCommitEvidence.channel,
|
|
1439
|
+
verify(observation) {
|
|
1440
|
+
assertLocalPostgresSecurityPolicy(selectedFrameworkPlan.policy, withSecurityStage(observation, "readback").security, warnings);
|
|
1441
|
+
verifyFrameworkSchemaPostimage(selectedFrameworkPlan, observation);
|
|
1442
|
+
}
|
|
1443
|
+
});
|
|
1444
|
+
if (!("target" in observed) || !("catalog" in observed))
|
|
1445
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1446
|
+
receipt = Object.freeze({ impact, frameworkObservation: observed });
|
|
1447
|
+
} catch (readbackError) {
|
|
1448
|
+
failure = classifyPostgresSchemaFailure(readbackError, impact, correlationId, signal);
|
|
1449
|
+
}
|
|
1450
|
+
} else if (settlement === "aborted") {
|
|
1451
|
+
begun = false;
|
|
1452
|
+
failure = classifyPostgresSchemaFailure(error, "none", correlationId, signal);
|
|
1453
|
+
} else {
|
|
1454
|
+
failure = runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1455
|
+
}
|
|
1456
|
+
} else {
|
|
1457
|
+
try {
|
|
1458
|
+
if (!channel)
|
|
1459
|
+
throw error;
|
|
1460
|
+
const catalog = await readPostgresSchemaCommitOutcome(channel, operational, plan);
|
|
1461
|
+
receipt = Object.freeze({
|
|
1462
|
+
impact: writesAttempted ? "committed" : "none",
|
|
1463
|
+
operationalCatalog: catalog
|
|
1464
|
+
});
|
|
1465
|
+
} catch {
|
|
1466
|
+
failure = runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
} else {
|
|
1470
|
+
let rollbackConfirmed = !begun;
|
|
1471
|
+
if (begun && setup && !forcedClose) {
|
|
1472
|
+
armCleanup();
|
|
1473
|
+
try {
|
|
1474
|
+
await setup.unsafe("ROLLBACK");
|
|
1475
|
+
rollbackConfirmed = true;
|
|
1476
|
+
begun = false;
|
|
1477
|
+
} catch {
|
|
1478
|
+
rollbackConfirmed = false;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
failure = classifyPostgresSchemaFailure(error, !writesAttempted || rollbackConfirmed ? "none" : "unknown", correlationId, signal);
|
|
1482
|
+
}
|
|
1483
|
+
} finally {
|
|
1484
|
+
armCleanup();
|
|
1485
|
+
await cancellationPending;
|
|
1486
|
+
try {
|
|
1487
|
+
if (!forcedClose) {
|
|
1488
|
+
setup?.release();
|
|
1489
|
+
channel?.release();
|
|
1490
|
+
}
|
|
1491
|
+
await Promise.all([
|
|
1492
|
+
setupPool?.close({ timeout: 0 }),
|
|
1493
|
+
cancellationPool?.close({ timeout: 0 }),
|
|
1494
|
+
...forcedClosures
|
|
1495
|
+
]);
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
failure ??= classifyPostgresSchemaFailure(error, receipt?.impact ?? (writesAttempted ? "unknown" : "none"), correlationId, signal);
|
|
1498
|
+
}
|
|
1499
|
+
clearTimeout(timer);
|
|
1500
|
+
clearTimeout(cleanupTimer);
|
|
1501
|
+
signal.removeEventListener("abort", abort);
|
|
1502
|
+
}
|
|
1503
|
+
if (failure)
|
|
1504
|
+
throw failure;
|
|
1505
|
+
if (!receipt)
|
|
1506
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
|
|
1507
|
+
return receipt;
|
|
1508
|
+
}
|
|
1509
|
+
const legacyPort = Object.freeze({
|
|
1510
|
+
async inspectOperational(plan, parent) {
|
|
1511
|
+
const deadline = new AbortController();
|
|
1512
|
+
const timer = setTimeout(() => deadline.abort(runtimeDatabaseSetupDeadlineReason), 3e4);
|
|
1513
|
+
const signal = AbortSignal.any([parent, deadline.signal]);
|
|
1514
|
+
try {
|
|
1515
|
+
return await inspectPostgresOperationalSchema(operational, plan, signal);
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
throw classifyPostgresSchemaFailure(error, "none", randomUUID(), signal);
|
|
1518
|
+
} finally {
|
|
1519
|
+
clearTimeout(timer);
|
|
1520
|
+
}
|
|
1521
|
+
},
|
|
1522
|
+
withSetupTransaction
|
|
1523
|
+
});
|
|
1524
|
+
if (!frameworkPlan || !frameworkRuntimePlan)
|
|
1525
|
+
return legacyPort;
|
|
1526
|
+
const framework = Object.freeze({
|
|
1527
|
+
async inspectOperational(plan, parent) {
|
|
1528
|
+
if (plan !== frameworkPlan)
|
|
1529
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1530
|
+
const deadline = new AbortController();
|
|
1531
|
+
const timer = setTimeout(() => deadline.abort(runtimeDatabaseSetupDeadlineReason), 3e4);
|
|
1532
|
+
const signal = AbortSignal.any([parent, deadline.signal]);
|
|
1533
|
+
try {
|
|
1534
|
+
const observation = await inspectFrameworkOperational(plan, signal, "preparation");
|
|
1535
|
+
assertLocalPostgresSecurityPolicy(plan.policy, withSecurityStage(observation, "preparation").security, warnings);
|
|
1536
|
+
return observation;
|
|
1537
|
+
} catch (error) {
|
|
1538
|
+
throw classifyPostgresSchemaFailure(error, "none", randomUUID(), signal);
|
|
1539
|
+
} finally {
|
|
1540
|
+
clearTimeout(timer);
|
|
1541
|
+
}
|
|
1542
|
+
},
|
|
1543
|
+
async withSetupTransaction(plan, parent, executeFramework) {
|
|
1544
|
+
if (plan !== frameworkPlan)
|
|
1545
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
|
|
1546
|
+
const receipt = await withSetupTransaction(frameworkRuntimePlan, parent, async () => {
|
|
1547
|
+
}, plan, executeFramework);
|
|
1548
|
+
if (!receipt.frameworkObservation)
|
|
1549
|
+
throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown");
|
|
1550
|
+
return Object.freeze({
|
|
1551
|
+
impact: receipt.impact,
|
|
1552
|
+
operationalObservation: receipt.frameworkObservation
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
});
|
|
1556
|
+
return Object.freeze({ ...legacyPort, framework });
|
|
1557
|
+
}
|
|
1558
|
+
export {
|
|
1559
|
+
createPostgresSchemaProviderPort
|
|
1560
|
+
};
|