@xlinklight/testkit 7.0.0-rc.0 → 8.0.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/LICENSE +21 -21
- package/README.md +171 -169
- package/package.json +11 -4
- package/src/architecture-database.d.mts +36 -36
- package/src/architecture-database.mjs +64 -64
- package/src/artifact-observation.mjs +50 -50
- package/src/browser-lifecycle.mjs +45 -45
- package/src/cloudflare-browser.mjs +41 -41
- package/src/cloudflare-pages.d.mts +34 -34
- package/src/cloudflare-pages.mjs +170 -170
- package/src/cloudflare-provider-http.mjs +32 -32
- package/src/cluster-directory.d.mts +16 -16
- package/src/cluster-directory.mjs +90 -90
- package/src/core-publishing.d.mts +75 -75
- package/src/core-publishing.mjs +214 -214
- package/src/dev-command-runner.mjs +97 -97
- package/src/fixture-path.mjs +19 -19
- package/src/function-admission.d.mts +1 -1
- package/src/function-admission.mjs +58 -58
- package/src/host-artifact.mjs +32 -32
- package/src/host-stop.mjs +15 -15
- package/src/lifecycle-trace.mjs +32 -32
- package/src/managed-native-fixture.d.mts +84 -84
- package/src/managed-native-fixture.mjs +209 -209
- package/src/native-fixture.mjs +125 -125
- package/src/native-platform.mjs +56 -56
- package/src/operator-accounts.mjs +103 -103
- package/src/owned-process.mjs +75 -75
- package/src/owner-build-cli.mjs +3 -4
- package/src/owner-database.mjs +215 -215
- package/src/owner-deployment-definition.mjs +31 -0
- package/src/owner-deployment.d.mts +32 -0
- package/src/owner-deployment.mjs +105 -0
- package/src/owner-operator-build.mjs +63 -33
- package/src/owner-production-browser.mjs +215 -215
- package/src/owner-production-instances.mjs +41 -41
- package/src/owner-production.d.mts +114 -104
- package/src/owner-production.mjs +350 -338
- package/src/owner-worker-build.mjs +83 -83
- package/src/prebuilt-output.d.mts +2 -2
- package/src/prebuilt-output.mjs +104 -104
- package/src/production-hosts.mjs +38 -38
- package/src/publisher-acceptance-host-cli.mjs +12 -5
- package/src/release-build.mjs +71 -71
- package/src/release-control.mjs +45 -45
- package/src/release-coordinator.d.mts +9 -9
- package/src/release-coordinator.mjs +222 -222
- package/src/release-credentials.d.mts +8 -8
- package/src/release-credentials.mjs +97 -97
- package/src/release-mutex.mjs +38 -38
- package/src/release-operator.d.mts +6 -6
- package/src/release-operator.mjs +59 -59
- package/src/release-supabase.d.mts +7 -7
- package/src/release-supabase.mjs +37 -37
- package/src/release-vercel.d.mts +22 -22
- package/src/release-vercel.mjs +51 -51
- package/src/release-writer.d.mts +6 -6
- package/src/release-writer.mjs +172 -172
- package/src/retained-postgres-shutdown.d.mts +51 -51
- package/src/retained-postgres-shutdown.mjs +262 -262
- package/src/temporary-acquisition.mjs +62 -62
- package/src/temporary-scope.d.mts +47 -47
- package/src/temporary-scope.mjs +268 -268
- package/src/worker-artifact.mjs +214 -214
package/src/release-vercel.mjs
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
|
-
import { captureCli } from "./release-cli.mjs";
|
|
5
|
-
|
|
6
|
-
export function createVercelReleaseClient(root) {
|
|
7
|
-
if (typeof root !== "string" || !path.isAbsolute(root)) throw Error("VERCEL_ROOT_INVALID");
|
|
8
|
-
root = fs.realpathSync(root);
|
|
9
|
-
const require = createRequire(path.join(root, "package.json")), packageFile = require.resolve("vercel/package.json");
|
|
10
|
-
const metadata = JSON.parse(fs.readFileSync(packageFile, "utf8")), bin = metadata.bin?.vc;
|
|
11
|
-
if (metadata.version !== "64.7.0" || typeof bin !== "string" || path.isAbsolute(bin) || bin.split(/[\\/]/).includes("..")) throw Error("VERCEL_BIN_INVALID");
|
|
12
|
-
const cli = { executable: process.execPath, args: [path.resolve(path.dirname(packageFile), bin)] };
|
|
13
|
-
async function command(args, { signal, input, maxOutputBytes = 262144, timeoutMs = 30000 } = {}) {
|
|
14
|
-
return captureCli(cli.executable, [...cli.args, ...args, "--non-interactive"], { cwd: root, signal, input, maxOutputBytes, timeoutMs });
|
|
15
|
-
}
|
|
16
|
-
async function api(endpoint, { body, method = body === undefined ? "GET" : "POST", signal } = {}) {
|
|
17
|
-
if (typeof endpoint !== "string" || !endpoint.startsWith("/") || endpoint.startsWith("//") || /[\r\n\0]/.test(endpoint)
|
|
18
|
-
|| !["GET", "POST", "PATCH"].includes(method)) throw Error("VERCEL_REQUEST_INVALID");
|
|
19
|
-
const result = await command(["api", endpoint, "--raw", ...(method === "GET" ? [] : ["--method", method]), ...(body === undefined ? [] : ["--input", "-"])], {
|
|
20
|
-
signal, input: body === undefined ? undefined : JSON.stringify(body),
|
|
21
|
-
});
|
|
22
|
-
let value;
|
|
23
|
-
try { value = JSON.parse(result.stdout.toString("utf8")); } catch { throw Error("VERCEL_RESPONSE_INVALID"); }
|
|
24
|
-
if (!value || value.error) throw Error("VERCEL_RESPONSE_FAILED");
|
|
25
|
-
return value;
|
|
26
|
-
}
|
|
27
|
-
return Object.freeze({command,api});
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function readVercelDeploymentAlias({teamId,productionUrl},deploymentId,{client,signal}) {
|
|
31
|
-
const hostname=new URL(productionUrl).hostname;
|
|
32
|
-
const team=`?teamId=${encodeURIComponent(teamId)}`;
|
|
33
|
-
const [candidate,alias]=await Promise.all([
|
|
34
|
-
client.api(`/v13/deployments/${encodeURIComponent(deploymentId)}${team}`,{signal}),
|
|
35
|
-
client.api(`/v4/aliases/${encodeURIComponent(hostname)}${team}`,{signal}),
|
|
36
|
-
]);
|
|
37
|
-
return {candidate,alias,hostname};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export async function observeStagedVercelDeployment({root,config,prebuilt,signal,client=createVercelReleaseClient(root)}) {
|
|
41
|
-
const {projectId,teamId}=config.vercel;
|
|
42
|
-
const {deploymentId,deploymentUrl,sourceSha}=prebuilt;
|
|
43
|
-
const {candidate,alias,hostname}=await readVercelDeploymentAlias(config.vercel,deploymentId,{client,signal});
|
|
44
|
-
const origin=typeof candidate.url==='string'&&/^https:\/\//u.test(candidate.url)?candidate.url:`https://${candidate.url}`;
|
|
45
|
-
const sha=candidate.gitSource?.sha??candidate.meta?.githubCommitSha;
|
|
46
|
-
if(candidate.id!==deploymentId||candidate.projectId!==projectId||candidate.ownerId!==teamId||origin!==deploymentUrl||sha!==sourceSha
|
|
47
|
-
||candidate.target!=='production'||candidate.source!=='cli'||candidate.readyState!=='READY'||candidate.readySubstate!=='STAGED'
|
|
48
|
-
||alias.alias!==hostname||alias.projectId!==projectId||!/^dpl_[A-Za-z0-9]+$/u.test(alias.deploymentId??'')||alias.deploymentId===deploymentId)throw Error('VERCEL_STAGED_DEPLOYMENT_UNPROVEN');
|
|
49
|
-
return {deploymentId,projectId,teamId,url:origin,sha,state:candidate.readyState,substate:candidate.readySubstate,
|
|
50
|
-
productionDeploymentId:alias.deploymentId,observedAt:new Date().toISOString()};
|
|
51
|
-
}
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { captureCli } from "./release-cli.mjs";
|
|
5
|
+
|
|
6
|
+
export function createVercelReleaseClient(root) {
|
|
7
|
+
if (typeof root !== "string" || !path.isAbsolute(root)) throw Error("VERCEL_ROOT_INVALID");
|
|
8
|
+
root = fs.realpathSync(root);
|
|
9
|
+
const require = createRequire(path.join(root, "package.json")), packageFile = require.resolve("vercel/package.json");
|
|
10
|
+
const metadata = JSON.parse(fs.readFileSync(packageFile, "utf8")), bin = metadata.bin?.vc;
|
|
11
|
+
if (metadata.version !== "64.7.0" || typeof bin !== "string" || path.isAbsolute(bin) || bin.split(/[\\/]/).includes("..")) throw Error("VERCEL_BIN_INVALID");
|
|
12
|
+
const cli = { executable: process.execPath, args: [path.resolve(path.dirname(packageFile), bin)] };
|
|
13
|
+
async function command(args, { signal, input, maxOutputBytes = 262144, timeoutMs = 30000 } = {}) {
|
|
14
|
+
return captureCli(cli.executable, [...cli.args, ...args, "--non-interactive"], { cwd: root, signal, input, maxOutputBytes, timeoutMs });
|
|
15
|
+
}
|
|
16
|
+
async function api(endpoint, { body, method = body === undefined ? "GET" : "POST", signal } = {}) {
|
|
17
|
+
if (typeof endpoint !== "string" || !endpoint.startsWith("/") || endpoint.startsWith("//") || /[\r\n\0]/.test(endpoint)
|
|
18
|
+
|| !["GET", "POST", "PATCH"].includes(method)) throw Error("VERCEL_REQUEST_INVALID");
|
|
19
|
+
const result = await command(["api", endpoint, "--raw", ...(method === "GET" ? [] : ["--method", method]), ...(body === undefined ? [] : ["--input", "-"])], {
|
|
20
|
+
signal, input: body === undefined ? undefined : JSON.stringify(body),
|
|
21
|
+
});
|
|
22
|
+
let value;
|
|
23
|
+
try { value = JSON.parse(result.stdout.toString("utf8")); } catch { throw Error("VERCEL_RESPONSE_INVALID"); }
|
|
24
|
+
if (!value || value.error) throw Error("VERCEL_RESPONSE_FAILED");
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
return Object.freeze({command,api});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function readVercelDeploymentAlias({teamId,productionUrl},deploymentId,{client,signal}) {
|
|
31
|
+
const hostname=new URL(productionUrl).hostname;
|
|
32
|
+
const team=`?teamId=${encodeURIComponent(teamId)}`;
|
|
33
|
+
const [candidate,alias]=await Promise.all([
|
|
34
|
+
client.api(`/v13/deployments/${encodeURIComponent(deploymentId)}${team}`,{signal}),
|
|
35
|
+
client.api(`/v4/aliases/${encodeURIComponent(hostname)}${team}`,{signal}),
|
|
36
|
+
]);
|
|
37
|
+
return {candidate,alias,hostname};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function observeStagedVercelDeployment({root,config,prebuilt,signal,client=createVercelReleaseClient(root)}) {
|
|
41
|
+
const {projectId,teamId}=config.vercel;
|
|
42
|
+
const {deploymentId,deploymentUrl,sourceSha}=prebuilt;
|
|
43
|
+
const {candidate,alias,hostname}=await readVercelDeploymentAlias(config.vercel,deploymentId,{client,signal});
|
|
44
|
+
const origin=typeof candidate.url==='string'&&/^https:\/\//u.test(candidate.url)?candidate.url:`https://${candidate.url}`;
|
|
45
|
+
const sha=candidate.gitSource?.sha??candidate.meta?.githubCommitSha;
|
|
46
|
+
if(candidate.id!==deploymentId||candidate.projectId!==projectId||candidate.ownerId!==teamId||origin!==deploymentUrl||sha!==sourceSha
|
|
47
|
+
||candidate.target!=='production'||candidate.source!=='cli'||candidate.readyState!=='READY'||candidate.readySubstate!=='STAGED'
|
|
48
|
+
||alias.alias!==hostname||alias.projectId!==projectId||!/^dpl_[A-Za-z0-9]+$/u.test(alias.deploymentId??'')||alias.deploymentId===deploymentId)throw Error('VERCEL_STAGED_DEPLOYMENT_UNPROVEN');
|
|
49
|
+
return {deploymentId,projectId,teamId,url:origin,sha,state:candidate.readyState,substate:candidate.readySubstate,
|
|
50
|
+
productionDeploymentId:alias.deploymentId,observedAt:new Date().toISOString()};
|
|
51
|
+
}
|
package/src/release-writer.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export interface ReleaseWriterContext {readonly teamId:string;readonly projectId:string;readonly scope:string;readonly sha:string;readonly ownerId:string;readonly generation:number}
|
|
2
|
-
export type RetainedAcceptanceCutover='predecessor-unchanged'|'cutover-verified';
|
|
3
|
-
export function isRetainedAcceptanceCutover(value:unknown):value is RetainedAcceptanceCutover;
|
|
4
|
-
export function validateReleaseWriter(value:unknown):ReleaseWriterContext;
|
|
5
|
-
export function releaseWriterSettled(report:unknown,context:ReleaseWriterContext,options?:{completionRequired?:boolean}):boolean;
|
|
6
|
-
export function releaseWriterSql(context:ReleaseWriterContext,operation:'observe'|'register'|'acquire'|'uncertain'|'release'|'retire-idle',report?:unknown):string;
|
|
1
|
+
export interface ReleaseWriterContext {readonly teamId:string;readonly projectId:string;readonly scope:string;readonly sha:string;readonly ownerId:string;readonly generation:number}
|
|
2
|
+
export type RetainedAcceptanceCutover='predecessor-unchanged'|'cutover-verified';
|
|
3
|
+
export function isRetainedAcceptanceCutover(value:unknown):value is RetainedAcceptanceCutover;
|
|
4
|
+
export function validateReleaseWriter(value:unknown):ReleaseWriterContext;
|
|
5
|
+
export function releaseWriterSettled(report:unknown,context:ReleaseWriterContext,options?:{completionRequired?:boolean}):boolean;
|
|
6
|
+
export function releaseWriterSql(context:ReleaseWriterContext,operation:'observe'|'register'|'acquire'|'uncertain'|'release'|'retire-idle',report?:unknown):string;
|
package/src/release-writer.mjs
CHANGED
|
@@ -1,172 +1,172 @@
|
|
|
1
|
-
import assert from 'node:assert/strict';
|
|
2
|
-
import {isDeepStrictEqual} from 'node:util';
|
|
3
|
-
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
4
|
-
|
|
5
|
-
export function validateReleaseWriter(context){
|
|
6
|
-
assert(context&&Object.keys(context).sort().join(',')==='generation,ownerId,projectId,scope,sha,teamId'&&/^team_[A-Za-z0-9]+$/.test(context.teamId)&&/^prj_[A-Za-z0-9]+$/.test(context.projectId)&&/^[a-z][a-z0-9-]{1,95}$/.test(context.scope)&&/^[a-f0-9]{40}$/.test(context.sha)&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(context.ownerId)&&Number.isSafeInteger(context.generation)&&context.generation>=0,'RELEASE_WRITER_CONTEXT_INVALID');
|
|
7
|
-
return context;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function validateStagedPublication(selection){
|
|
11
|
-
assert(selection&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(selection.runId??'')
|
|
12
|
-
&&/^[a-f0-9]{40}$/.test(selection.sha??'')&&/^[a-f0-9]{64}$/.test(selection.configSha256??'')
|
|
13
|
-
&&/^[a-f0-9]{64}$/.test(selection.artifactSha256??'')
|
|
14
|
-
&&/^dpl_[A-Za-z0-9]+$/.test(selection.deploymentId??''),'RELEASE_STAGED_SELECTION_INVALID');
|
|
15
|
-
return selection;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function canObserveStagedDeployment(report){
|
|
19
|
-
const {prebuilt,effects,recovery}=report;
|
|
20
|
-
return report.command==='recover'&&report.ok===true&&report.processes?.status==='closed'
|
|
21
|
-
&&[report.runId,report.slotId].every(id=>typeof id==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(id))
|
|
22
|
-
&&recovery?.reportExists===true&&recovery.observation?.owner==='inactive'&&recovery.observation?.processes==='closed'
|
|
23
|
-
&&effects?.deploymentCreate==='accepted'&&effects.deploymentPromote==='not-attempted'
|
|
24
|
-
&&(effects.developmentPush??'not-attempted')==='not-attempted'&&(effects.releasePush??'not-attempted')==='not-attempted'
|
|
25
|
-
&&(effects.versionAliasAssign??'not-attempted')==='not-attempted'&&report.completion===undefined
|
|
26
|
-
&&prebuilt?.createEffect==='accepted'&&prebuilt.promoteEffect==='not-attempted'
|
|
27
|
-
&&(prebuilt.versionAlias?.effect??'not-attempted')==='not-attempted'
|
|
28
|
-
&&prebuilt.acceptanceVerified===false&&prebuilt.promotionVerified===false
|
|
29
|
-
&&prebuilt.sourceSha===report.candidateSha&&prebuilt.configSha256===report.configSha256
|
|
30
|
-
&&/^[a-f0-9]{64}$/.test(prebuilt.configSha256??'')&&/^[a-f0-9]{64}$/.test(prebuilt.artifactSha256??'')
|
|
31
|
-
&&/^dpl_[A-Za-z0-9]+$/.test(prebuilt.deploymentId??'')&&typeof prebuilt.deploymentUrl==='string'&&prebuilt.deploymentUrl.startsWith('https://');
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function failedStagedDeployment(report,context){
|
|
35
|
-
const candidate=report.deployment,failure=report.recovery?.deploymentFailure;
|
|
36
|
-
return canObserveStagedDeployment(report)&&candidate?.projectId===context.projectId&&candidate.sha===context.sha
|
|
37
|
-
&&candidate.id===report.prebuilt.deploymentId&&candidate.url===report.prebuilt.deploymentUrl
|
|
38
|
-
&&failure?.deploymentId===candidate.id&&failure.state===candidate.state&&failure.publicationStage==='deployment'
|
|
39
|
-
&&typeof failure.observedAt==='string'&&Number.isFinite(Date.parse(failure.observedAt))
|
|
40
|
-
&&(candidate.state==='BLOCKED'?failure.providerBlockCode==='TEAM_ACCESS_REQUIRED':['ERROR','CANCELED','CANCELLED'].includes(candidate.state));
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function matchesRetainedStagingReport(recovered,original,receipt){
|
|
44
|
-
if(!(canObserveStagedDeployment(recovered)&&original?.schemaVersion===2&&original.command==='publish'&&original.ok===false
|
|
45
|
-
&&original.processes?.status==='closed'&&original.completion===undefined
|
|
46
|
-
&&typeof original.error?.code==='string'&&original.error.code===receipt.errorCode
|
|
47
|
-
&&['runId','slotId','sourceRoot','configPath','candidateSha','configSha256'].every(field=>original[field]===recovered[field])
|
|
48
|
-
&&isDeepStrictEqual(original.prebuilt,recovered.prebuilt)&&isDeepStrictEqual(original.effects,recovered.effects)
|
|
49
|
-
&&Array.isArray(original.steps)&&original.steps.every(step=>typeof step?.name==='string'&&!/^(admission:promote|promote|completion)(:|$)/.test(step.name))))return false;
|
|
50
|
-
const acceptance=original.steps.filter(step=>/^acceptance(:|$)/.test(step.name));
|
|
51
|
-
if(original.stage==='deployment')return acceptance.length===0;
|
|
52
|
-
const error=original.error.details;
|
|
53
|
-
return original.stage==='acceptance'&&original.error.code==='ACCEPTANCE_FAILED'&&error?.step==='acceptance:1'&&error.exitCode===1&&error.termination==='exit'
|
|
54
|
-
&&acceptance.length===2&&acceptance[0].name==='acceptance:0'&&acceptance[0].ok===true&&acceptance[0].exitCode===0
|
|
55
|
-
&&acceptance[1].name==='acceptance:1'&&acceptance[1].ok===false&&acceptance[1].exitCode===1;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function isRetainedAcceptanceCutover(value){
|
|
59
|
-
return value==='predecessor-unchanged'||value==='cutover-verified';
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
function isRetainedStaging(report,context){
|
|
63
|
-
const stage=report.recovery?.retainedStage;
|
|
64
|
-
return canObserveStagedDeployment(report)&&stage?.deploymentId===report.prebuilt.deploymentId&&stage.url===report.prebuilt.deploymentUrl
|
|
65
|
-
&&stage.sha===context.sha&&stage.teamId===context.teamId&&stage.projectId===context.projectId&&stage.state==='READY'&&stage.substate==='STAGED'
|
|
66
|
-
&&(stage.publicationStage==='deployment'&&stage.applicationCutover===undefined
|
|
67
|
-
||stage.publicationStage==='acceptance'&&isRetainedAcceptanceCutover(stage.applicationCutover))
|
|
68
|
-
&&/^dpl_[A-Za-z0-9]+$/.test(stage.productionDeploymentId??'')&&stage.productionDeploymentId!==stage.deploymentId
|
|
69
|
-
&&typeof stage.observedAt==='string'&&Number.isFinite(Date.parse(stage.observedAt));
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export function recoverFailedStagedDeployment(recovered,status,context){
|
|
73
|
-
const detail=status?.error?.details;
|
|
74
|
-
if(status?.schemaVersion!==2||status.command!=='status'||status.ok!==false||status.stage!=='deployment'
|
|
75
|
-
||status.error?.code!=='DEPLOYMENT_FAILED'||!detail||status.processes?.status!=='closed'
|
|
76
|
-
||status.recovery?.reportExists===false||status.recovery?.observation?.owner!=='inactive'||status.recovery.observation.processes!=='closed'
|
|
77
|
-
||['runId','slotId','sourceRoot','configPath','candidateSha','configSha256'].some(field=>status[field]!==recovered[field])
|
|
78
|
-
||!isDeepStrictEqual(status.prebuilt,recovered.prebuilt)||!isDeepStrictEqual(status.effects,recovered.effects)
|
|
79
|
-
||status.completion!==undefined)return recovered;
|
|
80
|
-
const {deploymentId,state,publicationStage,observedAt,providerBlockCode}=detail;
|
|
81
|
-
const deploymentFailure={deploymentId,state,publicationStage,observedAt,...(providerBlockCode==='TEAM_ACCESS_REQUIRED'?{providerBlockCode}:{})};
|
|
82
|
-
const settlement={...recovered,deployment:status.deployment,recovery:{...recovered.recovery,deploymentFailure}};
|
|
83
|
-
return failedStagedDeployment(settlement,context)?settlement:recovered;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** A process exit or PID absence cannot settle a remote mutation. Only public
|
|
87
|
-
* publisher observations of the exact candidate and closed scope may release. */
|
|
88
|
-
export function releaseWriterSettled(report,context,{completionRequired=false}={}){
|
|
89
|
-
validateReleaseWriter(context);
|
|
90
|
-
if(!report||report.schemaVersion!==2||!['publish','verify','recover'].includes(report.command)||report.candidateSha!==context.sha||report.processes?.status!=='closed'||!report.effects)return false;
|
|
91
|
-
const effects=['deploymentCreate','deploymentPromote','versionAliasAssign'].map(key=>report.effects[key]??'not-attempted');
|
|
92
|
-
if(effects.some(effect=>!['accepted','not-attempted'].includes(effect)))return false;
|
|
93
|
-
const [created,promoted,aliased]=effects;
|
|
94
|
-
const completion=report.completion;
|
|
95
|
-
if(completionRequired&&(report.ok||promoted==='accepted')&&completion?.status!=='completed')return false;
|
|
96
|
-
if(completion){
|
|
97
|
-
if(!['not-started','completed'].includes(completion.status)||completion.status==='not-started'&&promoted==='accepted')return false;
|
|
98
|
-
if(completion.status==='completed'){
|
|
99
|
-
const identity=completion.context;
|
|
100
|
-
if(!identity||identity.teamId!==context.teamId||identity.projectId!==context.projectId||identity.sourceSha!==context.sha||identity.deploymentId!==report.deployment?.id
|
|
101
|
-
||identity.configSha256!==report.configSha256||identity.artifactSha256!==report.prebuilt?.artifactSha256)return false;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
if(report.command==='recover')return report.ok===true&&(effects.every(effect=>effect==='not-attempted')||failedStagedDeployment(report,context)||isRetainedStaging(report,context));
|
|
105
|
-
if(created==='accepted'&&(!report.deployment||report.deployment.projectId!==context.projectId||report.deployment.sha!==context.sha||!['READY','ERROR','CANCELED'].includes(report.deployment.state)))return false;
|
|
106
|
-
if(promoted==='accepted'&&report.prebuilt?.promotionVerified!==true||aliased==='accepted'&&report.prebuilt?.versionAlias?.verified!==true)return false;
|
|
107
|
-
if(report.ok&&(report.prebuilt?.sourceSha!==context.sha||report.prebuilt.acceptanceVerified!==true||report.prebuilt.promotionVerified!==true))return false;
|
|
108
|
-
return report.command==='publish'||report.ok===true;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function receipt(report){
|
|
112
|
-
if(report===undefined)return null;
|
|
113
|
-
const failure=report.command==='recover'&&report.effects?.deploymentCreate==='accepted'?report.recovery?.deploymentFailure:undefined;
|
|
114
|
-
const retainedStage=report.command==='recover'&&report.effects?.deploymentCreate==='accepted'?report.recovery?.retainedStage:undefined;
|
|
115
|
-
const value={command:report.command,ok:report.ok===true,runId:report.runId??null,sha:report.candidateSha??null,processes:report.processes?.status??'unknown',effects:report.effects?Object.fromEntries(['deploymentCreate','deploymentPromote','versionAliasAssign'].map(key=>[key,report.effects[key]??'not-attempted'])):null,completion:report.completion?.status??null,errorCode:report.error?.code??null,...(failure?{deploymentFailure:failure}:{}),...(retainedStage?{retainedStage}:{})};
|
|
116
|
-
assert(Buffer.byteLength(JSON.stringify(value))<=4096&&(!value.runId||/^[a-zA-Z0-9-]{1,128}$/.test(value.runId))&&(!value.sha||/^[a-f0-9]{40}$/.test(value.sha))&&(!value.errorCode||/^[A-Z_]{1,128}$/.test(value.errorCode)),'RELEASE_WRITER_RECEIPT_INVALID');
|
|
117
|
-
return value;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** Short atomic metadata transactions in the existing protected operator Vault.
|
|
121
|
-
* The durable held/uncertain row has no timeout and is never stolen by age/PID.
|
|
122
|
-
* This is operator coordination, not authority to access application data. */
|
|
123
|
-
export function releaseWriterSql(context,operation,report){
|
|
124
|
-
validateReleaseWriter(context);assert(['observe','register','acquire','uncertain','release','retire-idle'].includes(operation),'RELEASE_WRITER_OPERATION_INVALID');
|
|
125
|
-
if(!['observe','register','retire-idle'].includes(operation))assert(context.generation>0,'RELEASE_WRITER_GENERATION_INVALID');
|
|
126
|
-
if(operation==='release')assert(releaseWriterSettled(report,context),'RELEASE_WRITER_UNSETTLED');
|
|
127
|
-
const name='link-light/publication-writer/v2/'+context.teamId+'/'+context.scope,ownership='link-light-publication-writer/v2',encoded=Buffer.from(JSON.stringify({schemaVersion:2,...context,phase:['register','release','retire-idle'].includes(operation)?'idle':operation==='uncertain'?'uncertain':'held',receipt:receipt(report)})).toString('base64');
|
|
128
|
-
const select=`SELECT decrypted_secret::jsonb AS writer_state FROM vault.decrypted_secrets WHERE name='${name}';`;
|
|
129
|
-
const validState=`IF jsonb_typeof(previous) IS DISTINCT FROM 'object' OR octet_length(previous::text)>8192 THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
130
|
-
IF (SELECT array_agg(key ORDER BY key) FROM jsonb_object_keys(previous) key) IS DISTINCT FROM ARRAY['generation','ownerId','phase','projectId','receipt','schemaVersion','scope','sha','teamId']::text[]
|
|
131
|
-
OR previous->'schemaVersion' IS DISTINCT FROM '2'::jsonb OR previous->>'teamId' IS DISTINCT FROM '${context.teamId}' OR previous->>'scope' IS DISTINCT FROM '${context.scope}'
|
|
132
|
-
OR jsonb_typeof(previous->'generation') IS DISTINCT FROM 'number' OR coalesce(previous->>'generation','') !~ '^[1-9][0-9]{0,15}$' THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
133
|
-
IF (previous->>'generation')::numeric>=9007199254740991 THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
134
|
-
IF coalesce(previous->>'phase','') NOT IN ('held','uncertain','idle')
|
|
135
|
-
OR coalesce(previous->>'ownerId','') !~ '^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$'
|
|
136
|
-
OR coalesce(previous->>'projectId','') !~ '^prj_[A-Za-z0-9]+$' OR coalesce(previous->>'sha','') !~ '^[a-f0-9]{40}$'
|
|
137
|
-
OR jsonb_typeof(previous->'receipt') NOT IN ('object','null') THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;`;
|
|
138
|
-
if(operation==='observe')return `/* release-writer:observe */\nDO $guard$ DECLARE previous jsonb; BEGIN ${vaultIsolationGuard} IF (SELECT count(*) FROM vault.secrets WHERE name='${name}')>1 OR EXISTS(SELECT 1 FROM vault.secrets WHERE name='${name}' AND description IS DISTINCT FROM '${ownership}') THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF; SELECT decrypted_secret::jsonb INTO previous FROM vault.decrypted_secrets WHERE name='${name}'; IF FOUND THEN ${validState} END IF; END $guard$;\n${select}`;
|
|
139
|
-
const same=['ownerId','projectId','sha'].map(key=>`previous->>'${key}' IS DISTINCT FROM '${context[key]}'`).join(' OR ');
|
|
140
|
-
const exact=`IF ${same} OR (previous->>'generation')::bigint<>${context.generation} THEN RAISE EXCEPTION 'RELEASE_WRITER_GENERATION_INVALID'; END IF;`;
|
|
141
|
-
const transition=operation==='register'?`
|
|
142
|
-
IF previous->>'phase' IN ('held','uncertain') THEN
|
|
143
|
-
IF ${same} THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;${exact}
|
|
144
|
-
next_value:=jsonb_set(next_value,'{phase}','"uncertain"'::jsonb);
|
|
145
|
-
ELSE
|
|
146
|
-
${context.generation===0?'':exact}
|
|
147
|
-
END IF;
|
|
148
|
-
next_value:=jsonb_set(next_value,'{generation}',to_jsonb((previous->>'generation')::bigint+1));`:
|
|
149
|
-
operation==='retire-idle'?`
|
|
150
|
-
IF previous->>'phase'<>'idle' THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;
|
|
151
|
-
IF ${same} THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
152
|
-
${context.generation===0?'':exact}
|
|
153
|
-
next_value:=jsonb_set(previous,'{generation}',to_jsonb((previous->>'generation')::bigint+1));`:
|
|
154
|
-
`${exact}
|
|
155
|
-
${operation==='acquire'?`IF previous->>'phase'='uncertain' THEN next_value:=previous; END IF;`:`IF previous->>'phase'='idle' THEN RAISE EXCEPTION 'RELEASE_WRITER_NOT_HELD'; END IF;`}
|
|
156
|
-
${operation==='release'?`next_value:=jsonb_set(next_value,'{generation}',to_jsonb(${context.generation}::bigint+1));`:''}`;
|
|
157
|
-
return `/* release-writer:${operation} */\nDO $writer$ DECLARE stored record; previous jsonb; next_value jsonb:=convert_from(decode('${encoded}','base64'),'UTF8')::jsonb; BEGIN
|
|
158
|
-
IF NOT pg_try_advisory_xact_lock(hashtextextended('${name}',0)) THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;
|
|
159
|
-
${vaultIsolationGuard}
|
|
160
|
-
IF (SELECT count(*) FROM vault.secrets WHERE name='${name}')>1 THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
161
|
-
SELECT id,description,decrypted_secret INTO stored FROM vault.decrypted_secrets WHERE name='${name}';
|
|
162
|
-
IF FOUND THEN
|
|
163
|
-
IF stored.description IS DISTINCT FROM '${ownership}' THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
164
|
-
previous:=stored.decrypted_secret::jsonb;
|
|
165
|
-
${validState}
|
|
166
|
-
${transition}
|
|
167
|
-
PERFORM vault.update_secret(stored.id,next_value::text,'${name}','${ownership}');
|
|
168
|
-
ELSE
|
|
169
|
-
${operation==='register'&&context.generation===0?`next_value:=jsonb_set(next_value,'{generation}','1'::jsonb);PERFORM vault.create_secret(next_value::text,'${name}','${ownership}');`:`RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP';`}
|
|
170
|
-
END IF;
|
|
171
|
-
END $writer$;\n${select}`;
|
|
172
|
-
}
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
3
|
+
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
4
|
+
|
|
5
|
+
export function validateReleaseWriter(context){
|
|
6
|
+
assert(context&&Object.keys(context).sort().join(',')==='generation,ownerId,projectId,scope,sha,teamId'&&/^team_[A-Za-z0-9]+$/.test(context.teamId)&&/^prj_[A-Za-z0-9]+$/.test(context.projectId)&&/^[a-z][a-z0-9-]{1,95}$/.test(context.scope)&&/^[a-f0-9]{40}$/.test(context.sha)&&/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(context.ownerId)&&Number.isSafeInteger(context.generation)&&context.generation>=0,'RELEASE_WRITER_CONTEXT_INVALID');
|
|
7
|
+
return context;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function validateStagedPublication(selection){
|
|
11
|
+
assert(selection&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(selection.runId??'')
|
|
12
|
+
&&/^[a-f0-9]{40}$/.test(selection.sha??'')&&/^[a-f0-9]{64}$/.test(selection.configSha256??'')
|
|
13
|
+
&&/^[a-f0-9]{64}$/.test(selection.artifactSha256??'')
|
|
14
|
+
&&/^dpl_[A-Za-z0-9]+$/.test(selection.deploymentId??''),'RELEASE_STAGED_SELECTION_INVALID');
|
|
15
|
+
return selection;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function canObserveStagedDeployment(report){
|
|
19
|
+
const {prebuilt,effects,recovery}=report;
|
|
20
|
+
return report.command==='recover'&&report.ok===true&&report.processes?.status==='closed'
|
|
21
|
+
&&[report.runId,report.slotId].every(id=>typeof id==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(id))
|
|
22
|
+
&&recovery?.reportExists===true&&recovery.observation?.owner==='inactive'&&recovery.observation?.processes==='closed'
|
|
23
|
+
&&effects?.deploymentCreate==='accepted'&&effects.deploymentPromote==='not-attempted'
|
|
24
|
+
&&(effects.developmentPush??'not-attempted')==='not-attempted'&&(effects.releasePush??'not-attempted')==='not-attempted'
|
|
25
|
+
&&(effects.versionAliasAssign??'not-attempted')==='not-attempted'&&report.completion===undefined
|
|
26
|
+
&&prebuilt?.createEffect==='accepted'&&prebuilt.promoteEffect==='not-attempted'
|
|
27
|
+
&&(prebuilt.versionAlias?.effect??'not-attempted')==='not-attempted'
|
|
28
|
+
&&prebuilt.acceptanceVerified===false&&prebuilt.promotionVerified===false
|
|
29
|
+
&&prebuilt.sourceSha===report.candidateSha&&prebuilt.configSha256===report.configSha256
|
|
30
|
+
&&/^[a-f0-9]{64}$/.test(prebuilt.configSha256??'')&&/^[a-f0-9]{64}$/.test(prebuilt.artifactSha256??'')
|
|
31
|
+
&&/^dpl_[A-Za-z0-9]+$/.test(prebuilt.deploymentId??'')&&typeof prebuilt.deploymentUrl==='string'&&prebuilt.deploymentUrl.startsWith('https://');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function failedStagedDeployment(report,context){
|
|
35
|
+
const candidate=report.deployment,failure=report.recovery?.deploymentFailure;
|
|
36
|
+
return canObserveStagedDeployment(report)&&candidate?.projectId===context.projectId&&candidate.sha===context.sha
|
|
37
|
+
&&candidate.id===report.prebuilt.deploymentId&&candidate.url===report.prebuilt.deploymentUrl
|
|
38
|
+
&&failure?.deploymentId===candidate.id&&failure.state===candidate.state&&failure.publicationStage==='deployment'
|
|
39
|
+
&&typeof failure.observedAt==='string'&&Number.isFinite(Date.parse(failure.observedAt))
|
|
40
|
+
&&(candidate.state==='BLOCKED'?failure.providerBlockCode==='TEAM_ACCESS_REQUIRED':['ERROR','CANCELED','CANCELLED'].includes(candidate.state));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function matchesRetainedStagingReport(recovered,original,receipt){
|
|
44
|
+
if(!(canObserveStagedDeployment(recovered)&&original?.schemaVersion===2&&original.command==='publish'&&original.ok===false
|
|
45
|
+
&&original.processes?.status==='closed'&&original.completion===undefined
|
|
46
|
+
&&typeof original.error?.code==='string'&&original.error.code===receipt.errorCode
|
|
47
|
+
&&['runId','slotId','sourceRoot','configPath','candidateSha','configSha256'].every(field=>original[field]===recovered[field])
|
|
48
|
+
&&isDeepStrictEqual(original.prebuilt,recovered.prebuilt)&&isDeepStrictEqual(original.effects,recovered.effects)
|
|
49
|
+
&&Array.isArray(original.steps)&&original.steps.every(step=>typeof step?.name==='string'&&!/^(admission:promote|promote|completion)(:|$)/.test(step.name))))return false;
|
|
50
|
+
const acceptance=original.steps.filter(step=>/^acceptance(:|$)/.test(step.name));
|
|
51
|
+
if(original.stage==='deployment')return acceptance.length===0;
|
|
52
|
+
const error=original.error.details;
|
|
53
|
+
return original.stage==='acceptance'&&original.error.code==='ACCEPTANCE_FAILED'&&error?.step==='acceptance:1'&&error.exitCode===1&&error.termination==='exit'
|
|
54
|
+
&&acceptance.length===2&&acceptance[0].name==='acceptance:0'&&acceptance[0].ok===true&&acceptance[0].exitCode===0
|
|
55
|
+
&&acceptance[1].name==='acceptance:1'&&acceptance[1].ok===false&&acceptance[1].exitCode===1;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isRetainedAcceptanceCutover(value){
|
|
59
|
+
return value==='predecessor-unchanged'||value==='cutover-verified';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isRetainedStaging(report,context){
|
|
63
|
+
const stage=report.recovery?.retainedStage;
|
|
64
|
+
return canObserveStagedDeployment(report)&&stage?.deploymentId===report.prebuilt.deploymentId&&stage.url===report.prebuilt.deploymentUrl
|
|
65
|
+
&&stage.sha===context.sha&&stage.teamId===context.teamId&&stage.projectId===context.projectId&&stage.state==='READY'&&stage.substate==='STAGED'
|
|
66
|
+
&&(stage.publicationStage==='deployment'&&stage.applicationCutover===undefined
|
|
67
|
+
||stage.publicationStage==='acceptance'&&isRetainedAcceptanceCutover(stage.applicationCutover))
|
|
68
|
+
&&/^dpl_[A-Za-z0-9]+$/.test(stage.productionDeploymentId??'')&&stage.productionDeploymentId!==stage.deploymentId
|
|
69
|
+
&&typeof stage.observedAt==='string'&&Number.isFinite(Date.parse(stage.observedAt));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function recoverFailedStagedDeployment(recovered,status,context){
|
|
73
|
+
const detail=status?.error?.details;
|
|
74
|
+
if(status?.schemaVersion!==2||status.command!=='status'||status.ok!==false||status.stage!=='deployment'
|
|
75
|
+
||status.error?.code!=='DEPLOYMENT_FAILED'||!detail||status.processes?.status!=='closed'
|
|
76
|
+
||status.recovery?.reportExists===false||status.recovery?.observation?.owner!=='inactive'||status.recovery.observation.processes!=='closed'
|
|
77
|
+
||['runId','slotId','sourceRoot','configPath','candidateSha','configSha256'].some(field=>status[field]!==recovered[field])
|
|
78
|
+
||!isDeepStrictEqual(status.prebuilt,recovered.prebuilt)||!isDeepStrictEqual(status.effects,recovered.effects)
|
|
79
|
+
||status.completion!==undefined)return recovered;
|
|
80
|
+
const {deploymentId,state,publicationStage,observedAt,providerBlockCode}=detail;
|
|
81
|
+
const deploymentFailure={deploymentId,state,publicationStage,observedAt,...(providerBlockCode==='TEAM_ACCESS_REQUIRED'?{providerBlockCode}:{})};
|
|
82
|
+
const settlement={...recovered,deployment:status.deployment,recovery:{...recovered.recovery,deploymentFailure}};
|
|
83
|
+
return failedStagedDeployment(settlement,context)?settlement:recovered;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A process exit or PID absence cannot settle a remote mutation. Only public
|
|
87
|
+
* publisher observations of the exact candidate and closed scope may release. */
|
|
88
|
+
export function releaseWriterSettled(report,context,{completionRequired=false}={}){
|
|
89
|
+
validateReleaseWriter(context);
|
|
90
|
+
if(!report||report.schemaVersion!==2||!['publish','verify','recover'].includes(report.command)||report.candidateSha!==context.sha||report.processes?.status!=='closed'||!report.effects)return false;
|
|
91
|
+
const effects=['deploymentCreate','deploymentPromote','versionAliasAssign'].map(key=>report.effects[key]??'not-attempted');
|
|
92
|
+
if(effects.some(effect=>!['accepted','not-attempted'].includes(effect)))return false;
|
|
93
|
+
const [created,promoted,aliased]=effects;
|
|
94
|
+
const completion=report.completion;
|
|
95
|
+
if(completionRequired&&(report.ok||promoted==='accepted')&&completion?.status!=='completed')return false;
|
|
96
|
+
if(completion){
|
|
97
|
+
if(!['not-started','completed'].includes(completion.status)||completion.status==='not-started'&&promoted==='accepted')return false;
|
|
98
|
+
if(completion.status==='completed'){
|
|
99
|
+
const identity=completion.context;
|
|
100
|
+
if(!identity||identity.teamId!==context.teamId||identity.projectId!==context.projectId||identity.sourceSha!==context.sha||identity.deploymentId!==report.deployment?.id
|
|
101
|
+
||identity.configSha256!==report.configSha256||identity.artifactSha256!==report.prebuilt?.artifactSha256)return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if(report.command==='recover')return report.ok===true&&(effects.every(effect=>effect==='not-attempted')||failedStagedDeployment(report,context)||isRetainedStaging(report,context));
|
|
105
|
+
if(created==='accepted'&&(!report.deployment||report.deployment.projectId!==context.projectId||report.deployment.sha!==context.sha||!['READY','ERROR','CANCELED'].includes(report.deployment.state)))return false;
|
|
106
|
+
if(promoted==='accepted'&&report.prebuilt?.promotionVerified!==true||aliased==='accepted'&&report.prebuilt?.versionAlias?.verified!==true)return false;
|
|
107
|
+
if(report.ok&&(report.prebuilt?.sourceSha!==context.sha||report.prebuilt.acceptanceVerified!==true||report.prebuilt.promotionVerified!==true))return false;
|
|
108
|
+
return report.command==='publish'||report.ok===true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function receipt(report){
|
|
112
|
+
if(report===undefined)return null;
|
|
113
|
+
const failure=report.command==='recover'&&report.effects?.deploymentCreate==='accepted'?report.recovery?.deploymentFailure:undefined;
|
|
114
|
+
const retainedStage=report.command==='recover'&&report.effects?.deploymentCreate==='accepted'?report.recovery?.retainedStage:undefined;
|
|
115
|
+
const value={command:report.command,ok:report.ok===true,runId:report.runId??null,sha:report.candidateSha??null,processes:report.processes?.status??'unknown',effects:report.effects?Object.fromEntries(['deploymentCreate','deploymentPromote','versionAliasAssign'].map(key=>[key,report.effects[key]??'not-attempted'])):null,completion:report.completion?.status??null,errorCode:report.error?.code??null,...(failure?{deploymentFailure:failure}:{}),...(retainedStage?{retainedStage}:{})};
|
|
116
|
+
assert(Buffer.byteLength(JSON.stringify(value))<=4096&&(!value.runId||/^[a-zA-Z0-9-]{1,128}$/.test(value.runId))&&(!value.sha||/^[a-f0-9]{40}$/.test(value.sha))&&(!value.errorCode||/^[A-Z_]{1,128}$/.test(value.errorCode)),'RELEASE_WRITER_RECEIPT_INVALID');
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Short atomic metadata transactions in the existing protected operator Vault.
|
|
121
|
+
* The durable held/uncertain row has no timeout and is never stolen by age/PID.
|
|
122
|
+
* This is operator coordination, not authority to access application data. */
|
|
123
|
+
export function releaseWriterSql(context,operation,report){
|
|
124
|
+
validateReleaseWriter(context);assert(['observe','register','acquire','uncertain','release','retire-idle'].includes(operation),'RELEASE_WRITER_OPERATION_INVALID');
|
|
125
|
+
if(!['observe','register','retire-idle'].includes(operation))assert(context.generation>0,'RELEASE_WRITER_GENERATION_INVALID');
|
|
126
|
+
if(operation==='release')assert(releaseWriterSettled(report,context),'RELEASE_WRITER_UNSETTLED');
|
|
127
|
+
const name='link-light/publication-writer/v2/'+context.teamId+'/'+context.scope,ownership='link-light-publication-writer/v2',encoded=Buffer.from(JSON.stringify({schemaVersion:2,...context,phase:['register','release','retire-idle'].includes(operation)?'idle':operation==='uncertain'?'uncertain':'held',receipt:receipt(report)})).toString('base64');
|
|
128
|
+
const select=`SELECT decrypted_secret::jsonb AS writer_state FROM vault.decrypted_secrets WHERE name='${name}';`;
|
|
129
|
+
const validState=`IF jsonb_typeof(previous) IS DISTINCT FROM 'object' OR octet_length(previous::text)>8192 THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
130
|
+
IF (SELECT array_agg(key ORDER BY key) FROM jsonb_object_keys(previous) key) IS DISTINCT FROM ARRAY['generation','ownerId','phase','projectId','receipt','schemaVersion','scope','sha','teamId']::text[]
|
|
131
|
+
OR previous->'schemaVersion' IS DISTINCT FROM '2'::jsonb OR previous->>'teamId' IS DISTINCT FROM '${context.teamId}' OR previous->>'scope' IS DISTINCT FROM '${context.scope}'
|
|
132
|
+
OR jsonb_typeof(previous->'generation') IS DISTINCT FROM 'number' OR coalesce(previous->>'generation','') !~ '^[1-9][0-9]{0,15}$' THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
133
|
+
IF (previous->>'generation')::numeric>=9007199254740991 THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;
|
|
134
|
+
IF coalesce(previous->>'phase','') NOT IN ('held','uncertain','idle')
|
|
135
|
+
OR coalesce(previous->>'ownerId','') !~ '^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$'
|
|
136
|
+
OR coalesce(previous->>'projectId','') !~ '^prj_[A-Za-z0-9]+$' OR coalesce(previous->>'sha','') !~ '^[a-f0-9]{40}$'
|
|
137
|
+
OR jsonb_typeof(previous->'receipt') NOT IN ('object','null') THEN RAISE EXCEPTION 'RELEASE_WRITER_STATE_INVALID'; END IF;`;
|
|
138
|
+
if(operation==='observe')return `/* release-writer:observe */\nDO $guard$ DECLARE previous jsonb; BEGIN ${vaultIsolationGuard} IF (SELECT count(*) FROM vault.secrets WHERE name='${name}')>1 OR EXISTS(SELECT 1 FROM vault.secrets WHERE name='${name}' AND description IS DISTINCT FROM '${ownership}') THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF; SELECT decrypted_secret::jsonb INTO previous FROM vault.decrypted_secrets WHERE name='${name}'; IF FOUND THEN ${validState} END IF; END $guard$;\n${select}`;
|
|
139
|
+
const same=['ownerId','projectId','sha'].map(key=>`previous->>'${key}' IS DISTINCT FROM '${context[key]}'`).join(' OR ');
|
|
140
|
+
const exact=`IF ${same} OR (previous->>'generation')::bigint<>${context.generation} THEN RAISE EXCEPTION 'RELEASE_WRITER_GENERATION_INVALID'; END IF;`;
|
|
141
|
+
const transition=operation==='register'?`
|
|
142
|
+
IF previous->>'phase' IN ('held','uncertain') THEN
|
|
143
|
+
IF ${same} THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;${exact}
|
|
144
|
+
next_value:=jsonb_set(next_value,'{phase}','"uncertain"'::jsonb);
|
|
145
|
+
ELSE
|
|
146
|
+
${context.generation===0?'':exact}
|
|
147
|
+
END IF;
|
|
148
|
+
next_value:=jsonb_set(next_value,'{generation}',to_jsonb((previous->>'generation')::bigint+1));`:
|
|
149
|
+
operation==='retire-idle'?`
|
|
150
|
+
IF previous->>'phase'<>'idle' THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;
|
|
151
|
+
IF ${same} THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
152
|
+
${context.generation===0?'':exact}
|
|
153
|
+
next_value:=jsonb_set(previous,'{generation}',to_jsonb((previous->>'generation')::bigint+1));`:
|
|
154
|
+
`${exact}
|
|
155
|
+
${operation==='acquire'?`IF previous->>'phase'='uncertain' THEN next_value:=previous; END IF;`:`IF previous->>'phase'='idle' THEN RAISE EXCEPTION 'RELEASE_WRITER_NOT_HELD'; END IF;`}
|
|
156
|
+
${operation==='release'?`next_value:=jsonb_set(next_value,'{generation}',to_jsonb(${context.generation}::bigint+1));`:''}`;
|
|
157
|
+
return `/* release-writer:${operation} */\nDO $writer$ DECLARE stored record; previous jsonb; next_value jsonb:=convert_from(decode('${encoded}','base64'),'UTF8')::jsonb; BEGIN
|
|
158
|
+
IF NOT pg_try_advisory_xact_lock(hashtextextended('${name}',0)) THEN RAISE EXCEPTION 'RELEASE_WRITER_BUSY'; END IF;
|
|
159
|
+
${vaultIsolationGuard}
|
|
160
|
+
IF (SELECT count(*) FROM vault.secrets WHERE name='${name}')>1 THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
161
|
+
SELECT id,description,decrypted_secret INTO stored FROM vault.decrypted_secrets WHERE name='${name}';
|
|
162
|
+
IF FOUND THEN
|
|
163
|
+
IF stored.description IS DISTINCT FROM '${ownership}' THEN RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP'; END IF;
|
|
164
|
+
previous:=stored.decrypted_secret::jsonb;
|
|
165
|
+
${validState}
|
|
166
|
+
${transition}
|
|
167
|
+
PERFORM vault.update_secret(stored.id,next_value::text,'${name}','${ownership}');
|
|
168
|
+
ELSE
|
|
169
|
+
${operation==='register'&&context.generation===0?`next_value:=jsonb_set(next_value,'{generation}','1'::jsonb);PERFORM vault.create_secret(next_value::text,'${name}','${ownership}');`:`RAISE EXCEPTION 'RELEASE_WRITER_OWNERSHIP';`}
|
|
170
|
+
END IF;
|
|
171
|
+
END $writer$;\n${select}`;
|
|
172
|
+
}
|
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
2
|
-
|
|
3
|
-
export interface RetainedPostgresShutdownOptions {
|
|
4
|
-
dataDirectory: string;
|
|
5
|
-
pgCtl: string;
|
|
6
|
-
signal?: AbortSignal;
|
|
7
|
-
/** Normal shutdown defaults to 60000 ms; explicit shorter fault bounds remain supported (1..60000). */
|
|
8
|
-
terminationGraceMs?: number;
|
|
9
|
-
/** Optional owned identity capture, included in the same shutdown boundary. */
|
|
10
|
-
beforeStop?: (child: ChildProcess) => Promise<void> | void;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface RetainedPostgresShutdownState {
|
|
14
|
-
pid?: number;
|
|
15
|
-
closed: boolean;
|
|
16
|
-
exitCode: number | null;
|
|
17
|
-
signalCode: string | null;
|
|
18
|
-
error?: string;
|
|
19
|
-
stopMethod: "owned-postgres-pg-ctl-fast";
|
|
20
|
-
stopError: string | null;
|
|
21
|
-
stopErrors: string[];
|
|
22
|
-
normalPostgresStopped: boolean;
|
|
23
|
-
pendingStart: boolean;
|
|
24
|
-
controlPid?: number;
|
|
25
|
-
controlClosed: boolean;
|
|
26
|
-
controlExitCode: number | null;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export interface RetainedPostgresOriginalFailure {
|
|
30
|
-
readonly stage: string;
|
|
31
|
-
readonly error: unknown;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Direct producer/controller closure only; an outer owner verifies its job. */
|
|
35
|
-
export function startRetainedPostgres(
|
|
36
|
-
executable: string,
|
|
37
|
-
args: readonly string[],
|
|
38
|
-
options: RetainedPostgresShutdownOptions & Omit<SpawnOptions, "signal" | "shell"> & { onSpawn?: () => void },
|
|
39
|
-
): {
|
|
40
|
-
child: ChildProcess;
|
|
41
|
-
state: RetainedPostgresShutdownState;
|
|
42
|
-
completion: Promise<RetainedPostgresShutdownState>;
|
|
43
|
-
stop(): Promise<void>;
|
|
44
|
-
getOriginalFailures(): readonly RetainedPostgresOriginalFailure[];
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
/** Bind before initialise/start so the installed exit hook uses the same stop. */
|
|
48
|
-
export function bindEmbeddedPostgresShutdown(
|
|
49
|
-
instance: { start(): Promise<void>; stop(): Promise<void> },
|
|
50
|
-
options: RetainedPostgresShutdownOptions,
|
|
51
|
-
): { state: RetainedPostgresShutdownState; stop(): Promise<void>; getOriginalFailures(): readonly RetainedPostgresOriginalFailure[] };
|
|
1
|
+
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export interface RetainedPostgresShutdownOptions {
|
|
4
|
+
dataDirectory: string;
|
|
5
|
+
pgCtl: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
/** Normal shutdown defaults to 60000 ms; explicit shorter fault bounds remain supported (1..60000). */
|
|
8
|
+
terminationGraceMs?: number;
|
|
9
|
+
/** Optional owned identity capture, included in the same shutdown boundary. */
|
|
10
|
+
beforeStop?: (child: ChildProcess) => Promise<void> | void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface RetainedPostgresShutdownState {
|
|
14
|
+
pid?: number;
|
|
15
|
+
closed: boolean;
|
|
16
|
+
exitCode: number | null;
|
|
17
|
+
signalCode: string | null;
|
|
18
|
+
error?: string;
|
|
19
|
+
stopMethod: "owned-postgres-pg-ctl-fast";
|
|
20
|
+
stopError: string | null;
|
|
21
|
+
stopErrors: string[];
|
|
22
|
+
normalPostgresStopped: boolean;
|
|
23
|
+
pendingStart: boolean;
|
|
24
|
+
controlPid?: number;
|
|
25
|
+
controlClosed: boolean;
|
|
26
|
+
controlExitCode: number | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RetainedPostgresOriginalFailure {
|
|
30
|
+
readonly stage: string;
|
|
31
|
+
readonly error: unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Direct producer/controller closure only; an outer owner verifies its job. */
|
|
35
|
+
export function startRetainedPostgres(
|
|
36
|
+
executable: string,
|
|
37
|
+
args: readonly string[],
|
|
38
|
+
options: RetainedPostgresShutdownOptions & Omit<SpawnOptions, "signal" | "shell"> & { onSpawn?: () => void },
|
|
39
|
+
): {
|
|
40
|
+
child: ChildProcess;
|
|
41
|
+
state: RetainedPostgresShutdownState;
|
|
42
|
+
completion: Promise<RetainedPostgresShutdownState>;
|
|
43
|
+
stop(): Promise<void>;
|
|
44
|
+
getOriginalFailures(): readonly RetainedPostgresOriginalFailure[];
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Bind before initialise/start so the installed exit hook uses the same stop. */
|
|
48
|
+
export function bindEmbeddedPostgresShutdown(
|
|
49
|
+
instance: { start(): Promise<void>; stop(): Promise<void> },
|
|
50
|
+
options: RetainedPostgresShutdownOptions,
|
|
51
|
+
): { state: RetainedPostgresShutdownState; stop(): Promise<void>; getOriginalFailures(): readonly RetainedPostgresOriginalFailure[] };
|