@xlinklight/testkit 0.0.0-stage → 7.0.0-rc.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 -0
- package/README.md +169 -3
- package/content/platform-baseline.sql +273 -0
- package/package.json +274 -3
- package/src/acceptance-oracle.d.mts +24 -0
- package/src/acceptance-oracle.mjs +79 -0
- package/src/architecture-database.d.mts +36 -0
- package/src/architecture-database.mjs +64 -0
- package/src/artifact-build.d.mts +3 -0
- package/src/artifact-build.mjs +35 -0
- package/src/artifact-declarations.mjs +24 -0
- package/src/artifact-graphs.mjs +61 -0
- package/src/artifact-lock.mjs +32 -0
- package/src/artifact-observation.mjs +50 -0
- package/src/artifact-publisher.d.mts +30 -0
- package/src/artifact-publisher.mjs +84 -0
- package/src/browser-lifecycle.mjs +45 -0
- package/src/browser-operation-owner.mjs +28 -0
- package/src/cloudflare-browser.d.mts +14 -0
- package/src/cloudflare-browser.mjs +41 -0
- package/src/cloudflare-build.d.mts +19 -0
- package/src/cloudflare-build.mjs +61 -0
- package/src/cloudflare-http.d.mts +5 -0
- package/src/cloudflare-http.mjs +65 -0
- package/src/cloudflare-pages.d.mts +34 -0
- package/src/cloudflare-pages.mjs +170 -0
- package/src/cloudflare-provider-http.d.mts +8 -0
- package/src/cloudflare-provider-http.mjs +32 -0
- package/src/cloudflare-worker-package.d.mts +6 -0
- package/src/cloudflare-worker-package.mjs +24 -0
- package/src/cloudflare-worker-qualification.d.mts +4 -0
- package/src/cloudflare-worker-qualification.mjs +63 -0
- package/src/cloudflare-workers.d.mts +37 -0
- package/src/cloudflare-workers.mjs +90 -0
- package/src/cluster-directory.d.mts +16 -0
- package/src/cluster-directory.mjs +90 -0
- package/src/core-publishing.d.mts +75 -0
- package/src/core-publishing.mjs +214 -0
- package/src/dev-command-runner.mjs +97 -0
- package/src/fixture-path.mjs +19 -0
- package/src/function-admission.d.mts +1 -0
- package/src/function-admission.mjs +58 -0
- package/src/host-artifact.mjs +32 -0
- package/src/host-stop.mjs +15 -0
- package/src/independent-artifact-qualification.mjs +67 -0
- package/src/independent-runtime-qualification.mjs +647 -0
- package/src/isolated-browser-child.mjs +29 -0
- package/src/isolated-browser.mjs +69 -0
- package/src/lifecycle-trace.mjs +32 -0
- package/src/managed-native-fixture.d.mts +84 -0
- package/src/managed-native-fixture.mjs +209 -0
- package/src/native-fixture.mjs +125 -0
- package/src/native-platform.mjs +56 -0
- package/src/operator-accounts.mjs +103 -0
- package/src/operator-vault.d.mts +2 -0
- package/src/operator-vault.mjs +9 -0
- package/src/owned-process.mjs +75 -0
- package/src/owner-build-cli.d.mts +1 -0
- package/src/owner-build-cli.mjs +31 -0
- package/src/owner-database.mjs +215 -0
- package/src/owner-operator-build.d.mts +1 -0
- package/src/owner-operator-build.mjs +33 -0
- package/src/owner-package-build.d.mts +2 -0
- package/src/owner-package-build.mjs +29 -0
- package/src/owner-production-browser.mjs +215 -0
- package/src/owner-production-instances.mjs +41 -0
- package/src/owner-production.d.mts +104 -0
- package/src/owner-production.mjs +338 -0
- package/src/owner-release.mjs +41 -0
- package/src/owner-worker-build.d.mts +3 -0
- package/src/owner-worker-build.mjs +83 -0
- package/src/prebuilt-build.d.mts +8 -0
- package/src/prebuilt-build.mjs +69 -0
- package/src/prebuilt-output.d.mts +2 -0
- package/src/prebuilt-output.mjs +104 -0
- package/src/production-hosts.mjs +38 -0
- package/src/publisher-acceptance-host-cli.mjs +23 -0
- package/src/publisher-acceptance-owner.mjs +116 -0
- package/src/publisher-acceptance-runner.mjs +250 -0
- package/src/publisher-acceptance-service.mjs +49 -0
- package/src/publisher-acceptance.d.mts +61 -0
- package/src/publisher-acceptance.mjs +3 -0
- package/src/publishing-source.d.mts +11 -0
- package/src/publishing-source.mjs +32 -0
- package/src/qualification-function-host.mjs +26 -0
- package/src/qualification-route-owner.mjs +64 -0
- package/src/qualification-transport.mjs +18 -0
- package/src/registry-core-selection.mjs +41 -0
- package/src/release-artifact.d.mts +17 -0
- package/src/release-artifact.mjs +113 -0
- package/src/release-build.d.mts +12 -0
- package/src/release-build.mjs +71 -0
- package/src/release-cli.d.mts +27 -0
- package/src/release-cli.mjs +79 -0
- package/src/release-control.mjs +45 -0
- package/src/release-coordinator.d.mts +9 -0
- package/src/release-coordinator.mjs +222 -0
- package/src/release-credentials.d.mts +8 -0
- package/src/release-credentials.mjs +97 -0
- package/src/release-environment.mjs +60 -0
- package/src/release-mutex.d.mts +10 -0
- package/src/release-mutex.mjs +38 -0
- package/src/release-operator.d.mts +6 -0
- package/src/release-operator.mjs +59 -0
- package/src/release-supabase.d.mts +7 -0
- package/src/release-supabase.mjs +37 -0
- package/src/release-vercel.d.mts +22 -0
- package/src/release-vercel.mjs +51 -0
- package/src/release-writer.d.mts +6 -0
- package/src/release-writer.mjs +172 -0
- package/src/retained-postgres-shutdown.d.mts +51 -0
- package/src/retained-postgres-shutdown.mjs +262 -0
- package/src/schema-snapshot.mjs +51 -0
- package/src/static-ui-artifact.mjs +54 -0
- package/src/static-ui-routes.mjs +3 -0
- package/src/temporary-acquisition.mjs +62 -0
- package/src/temporary-scope.d.mts +47 -0
- package/src/temporary-scope.mjs +268 -0
- package/src/unscoped-read.mjs +14 -0
- package/src/worker-artifact.mjs +214 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
3
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
4
|
+
import {withReleaseControlSession} from './release-control.mjs';
|
|
5
|
+
import {acquireProductionInstance,isProductionAuthorizationRevision} from './owner-production-instances.mjs';
|
|
6
|
+
import {createAcceptanceOracleClient,coreAcceptanceOracleStatements,acceptanceBudgetStatement,acceptanceCommittedStatement} from './acceptance-oracle.mjs';
|
|
7
|
+
const record=(value,keys)=>value!==null&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).sort().join(',')===[...keys].sort().join(',');
|
|
8
|
+
const personalPhases=['personal-first','personal-second'];
|
|
9
|
+
const runIdPattern=/^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/;
|
|
10
|
+
const recoveryLabelPattern=/^[a-f0-9-]{36}$/;
|
|
11
|
+
function productionSteps(providers,verifySeparately){
|
|
12
|
+
if(!Array.isArray(providers)||providers.length>2||providers.some(provider=>!provider||!Array.isArray(provider.steps)||provider.steps.length<1||provider.steps.length>2||provider.steps.some(step=>typeof step!=='function'))||new Set(providers.map(provider=>provider.solutionId)).size!==providers.length||new Set(providers.map(provider=>provider.port)).size!==providers.length)throw Error('RELEASE_PRODUCTION_INPUT_INVALID');
|
|
13
|
+
const preparations=providers.flatMap(provider=>provider.steps.map(prepare=>({provider,prepare})));
|
|
14
|
+
if(typeof verifySeparately!=='boolean'||preparations.length+Number(verifySeparately)>2)throw Error('RELEASE_PRODUCTION_INPUT_INVALID');
|
|
15
|
+
return [{name:'setup'},...personalPhases.flatMap((name,sessionIndex)=>[
|
|
16
|
+
...preparations.map((step,index)=>({...step,name:`${name}-provider-${index+1}`,sessionIndex,acquire:index===0})),
|
|
17
|
+
{name,sessionIndex,acquire:preparations.length===0},
|
|
18
|
+
...(verifySeparately?[{name:`${name}-verify`,sessionIndex,verify:true}]:[]),
|
|
19
|
+
]),...['authorization','browser','cleanup'].map(name=>({name}))];
|
|
20
|
+
}
|
|
21
|
+
export function ownerProductionPhaseNames(providers=[],verifySeparately=false){return Object.freeze(productionSteps(providers,verifySeparately).map(step=>step.name));}
|
|
22
|
+
const delay=(milliseconds,signal)=>new Promise((resolve,reject)=>{signal?.throwIfAborted();const abort=()=>{clearTimeout(timer);reject(signal.reason);},timer=setTimeout(()=>{signal?.removeEventListener('abort',abort);resolve();},milliseconds);signal?.addEventListener('abort',abort,{once:true});});
|
|
23
|
+
const append=(failed,failure,error,message)=>failed?new AggregateError([failure,error],message,{cause:failure}):error;
|
|
24
|
+
function bindPersonalRecovery(state,value,stepCount){
|
|
25
|
+
const invalid=()=>Error('RELEASE_PRODUCTION_PERSONAL_RECOVERY_UNPROVEN');
|
|
26
|
+
if(!record(value,['label','instances','priorRunId','progress'])||!recoveryLabelPattern.test(value.label??'')||value.label===state.label||!runIdPattern.test(value.priorRunId??'')||state.runs.includes(value.priorRunId)||!Array.isArray(value.instances)||value.instances.length!==state.ids.length||!value.progress||Buffer.byteLength(JSON.stringify(value.progress))>65536)throw invalid();
|
|
27
|
+
const {ids,label,runs,queryCount,...baseline}=state;
|
|
28
|
+
const {ids:restored,label:attempt,runs:observed,queryCount:queries,recovery,...checkpoint}=value.progress;
|
|
29
|
+
const history=[...runs,value.priorRunId];
|
|
30
|
+
const step=recovery?.step??0;
|
|
31
|
+
if(!isDeepStrictEqual(checkpoint,baseline)||!Array.isArray(observed)||new Set(observed).size!==observed.length||observed.some(run=>!runIdPattern.test(run))||!isDeepStrictEqual(observed.slice(0,history.length),history)||!Array.isArray(restored)||restored.length!==ids.length||!Number.isSafeInteger(queries)||queries<queryCount||queries>128)throw invalid();
|
|
32
|
+
if(recovery===undefined?attempt!==label||observed.length!==history.length||queries!==queryCount:
|
|
33
|
+
!record(recovery,['step','status'])||recovery.status!=='ready'||!Number.isSafeInteger(step)||step<1||step>stepCount||attempt!==value.label||observed.length!==history.length+step-1)throw invalid();
|
|
34
|
+
const observedIds=new Map();
|
|
35
|
+
for(const [index,prior] of ids.entries()){
|
|
36
|
+
const {context:original,enabled,...identity}=prior;
|
|
37
|
+
const {context,enabled:active,...binding}=restored[index]??{};
|
|
38
|
+
const closed=value.instances.find(item=>item?.instanceId===prior.instance);
|
|
39
|
+
if(!enabled||!closed||closed.sessionIndex!==prior.sessionIndex||closed.releaseDigest!==prior.releaseDigest||!isProductionAuthorizationRevision(closed.closedRevision)||
|
|
40
|
+
!isDeepStrictEqual(binding,identity)||active!==Boolean(recovery)||!context||context.instanceId!==original.instanceId||context.tenantId!==original.tenantId||context.principalId!==original.principalId||context.releaseDigest!==original.releaseDigest||
|
|
41
|
+
!isProductionAuthorizationRevision(context.authorizationRevision)||(!recovery&&context.authorizationRevision!==closed.closedRevision))throw invalid();
|
|
42
|
+
observedIds.set(prior.instance,{id:prior.instance,enabled:false,revision:closed.closedRevision});
|
|
43
|
+
}
|
|
44
|
+
Object.assign(state,{ids:structuredClone(restored),label:value.label,runs:[...observed],queryCount:queries,recovery:{step,status:'running'}});
|
|
45
|
+
return observedIds;
|
|
46
|
+
}
|
|
47
|
+
function productionOperator(value){
|
|
48
|
+
const invalid=()=>{throw Error('RELEASE_PRODUCTION_OPERATOR_INVALID');};
|
|
49
|
+
if(!record(value,['accounts','actors','oracle',...(value?.request===undefined?[]:['request']),...(value?.qualificationJobId===undefined?[]:['qualificationJobId'])])||!value.oracle||typeof value.oracle.query!=='function'||value.request!==undefined&&typeof value.request!=='function'||value.qualificationJobId!==undefined&&(typeof value.qualificationJobId!=='string'||!(/^[a-f0-9]{64}$/).test(value.qualificationJobId))||!Array.isArray(value.accounts)||value.accounts.length!==2||!Array.isArray(value.actors)||value.actors.length!==2)invalid();
|
|
50
|
+
const accounts=value.accounts.map(account=>{if(!record(account,['email','password'])||typeof account.email!=='string'||!/^\S+@\S+\.\S+$/.test(account.email)||/[\0\r\n]/.test(account.email)||Buffer.byteLength(account.email)>254||typeof account.password!=='string'||Buffer.byteLength(account.password)<8||Buffer.byteLength(account.password)>1024||/[\0\r\n]/.test(account.password))invalid();return {email:account.email,password:account.password};});
|
|
51
|
+
const actors=value.actors.map(actor=>{if(!record(actor,['userId'])||typeof actor.userId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/.test(actor.userId))invalid();return {userId:actor.userId};});
|
|
52
|
+
if(new Set(accounts.map(account=>account.email.toLowerCase())).size!==2||new Set(accounts.map(account=>account.password)).size!==2||actors[0].userId===actors[1].userId)invalid();return {accounts,actors,oracle:value.oracle,request:value.request??fetch,qualificationJobId:value.qualificationJobId};
|
|
53
|
+
}
|
|
54
|
+
/** One immutable plan. The operation journal, never this driver,
|
|
55
|
+
* decides whether a phase may execute; an unknown claim cannot be replayed. */
|
|
56
|
+
export function createOwnerProductionPlan(options){
|
|
57
|
+
const {target,solutionId,manifest,execution,browser,providers=[],readResourceJson,browserHost,writeEvidence,expect}=options,operator=productionOperator(options.operator);
|
|
58
|
+
if(!Array.isArray(options.oracleStatements))throw Error('RELEASE_PRODUCTION_INPUT_INVALID');
|
|
59
|
+
const statements=[...coreAcceptanceOracleStatements,...options.oracleStatements];
|
|
60
|
+
createAcceptanceOracleClient({statements,execute:async()=>{throw Error('RELEASE_PROBE_NOT_EXECUTABLE');}});
|
|
61
|
+
if(typeof expect!=='function'||typeof readResourceJson!=='function'||!browserHost||typeof browserHost.open!=='function'||typeof writeEvidence!=='function'||manifest?.solutionId!==solutionId||!execution||!['prepare','assertValue'].every(key=>typeof execution[key]==='function')||!browser||!['prepare','drive','visible','reread'].every(key=>typeof browser[key]==='function')||options.signal!==undefined&&!(options.signal instanceof AbortSignal))throw Error('RELEASE_PRODUCTION_INPUT_INVALID');
|
|
62
|
+
const verifySeparately=execution.verifySeparately??false;
|
|
63
|
+
const steps=productionSteps(providers,verifySeparately),names=steps.map(step=>step.name);
|
|
64
|
+
const providerSteps=steps.filter(step=>step.prepare&&step.sessionIndex===0);
|
|
65
|
+
const recoveryStepCount=1+2*providerSteps.length;
|
|
66
|
+
const core=new URL(target?.coreOrigin);if(core.protocol!=='https:'||core.origin!==target.coreOrigin)throw Error('RELEASE_PRODUCTION_INPUT_INVALID');
|
|
67
|
+
const binding={coreOrigin:core.origin,solutionId,releaseDigest:manifest.releaseDigest,manifestSha256:createHash('sha256').update(JSON.stringify(manifest)).digest('hex')};
|
|
68
|
+
return Object.freeze(steps.map(({name,sessionIndex:selected,acquire,provider,prepare,verify},index)=>Object.freeze({name,async execute({previous,checkpoint,acquisition,browserRecovery,personalRecovery,signal:phaseSignal,workSignal}={}){
|
|
69
|
+
if(typeof checkpoint!=='function')throw Error('RELEASE_PRODUCTION_CHECKPOINT_REQUIRED');
|
|
70
|
+
if(index===0?previous!==undefined:previous?.phase!==names[index-1]||previous?.status!=='completed'||previous?.index!==index-1)throw Error('RELEASE_PRODUCTION_PHASE_ORDER');
|
|
71
|
+
if(previous&&JSON.stringify(previous.binding)!==JSON.stringify(binding))throw Error('RELEASE_PRODUCTION_PHASE_BINDING');
|
|
72
|
+
if(previous&&(previous.schemaVersion!==1||previous.kind!=='owner-production-phase'||!Array.isArray(previous.ids)||previous.ids.length>32||!Array.isArray(previous.runs)||previous.runs.length>128||!Array.isArray(previous.checks)||previous.checks.length>128||!Number.isSafeInteger(previous.queryCount)||previous.queryCount<0||previous.queryCount>128||!Array.isArray(previous.history)||previous.history.length!==index||typeof previous.label!=='string'||!/^[a-f0-9-]{36}$/.test(previous.label)||Buffer.byteLength(JSON.stringify(previous))>65536))throw Error('RELEASE_PRODUCTION_PHASE_STATE');
|
|
73
|
+
if(previous&&(!Array.isArray(previous.actors)||previous.actors.length!==2||previous.actors.some((actor,i)=>actor.principalId!==operator.actors[i].userId||typeof actor.spaceId!=='string'||!actor.spaceId||actor.spaceId.length>128)||previous.actors[0].spaceId===previous.actors[1].spaceId||previous.pending!==undefined||previous.history.some((entry,i)=>entry.phase!==names[i]||!Number.isSafeInteger(entry.http?.work)||!Number.isSafeInteger(entry.http?.cleanup)||entry.http.work<0||entry.http.cleanup<0||entry.http.total!==entry.http.work+entry.http.cleanup||entry.http.total>43)||previous.ids.some(id=>![0,1].includes(id.sessionIndex)||typeof id.instance!=='string'||!id.instance||id.instance.length>128||typeof id.tenant!=='string'||!id.tenant||typeof id.solutionId!=='string'||typeof id.enabled!=='boolean'||!id.context||id.context.instanceId!==id.instance||id.context.principalId!==operator.actors[id.sessionIndex].userId||id.context.tenantId!==id.tenant||id.context.releaseDigest!==id.releaseDigest||!isProductionAuthorizationRevision(id.context.authorizationRevision))||new Set(previous.ids.map(id=>id.instance)).size!==previous.ids.length||previous.runs.some(ref=>typeof ref!=='string'||!ref||ref.length>128)||previous.checks.some(check=>typeof check!=='string'||check.length>1024)))throw Error('RELEASE_PRODUCTION_PHASE_STATE');
|
|
74
|
+
const state=previous?structuredClone(previous):{schemaVersion:1,kind:'owner-production-phase',binding,label:randomUUID(),actors:[],ids:[],runs:[],checks:[],queryCount:0,history:[]};Object.assign(state,{phase:name,index,status:'running'});delete state.proof;
|
|
75
|
+
let recoveryInstances,browserContinuation,browserProvider;
|
|
76
|
+
if(personalRecovery!==undefined){
|
|
77
|
+
if(name!=='personal-second'||!providerSteps.length||verifySeparately||browserRecovery!==undefined||acquisition!==undefined)throw Error('RELEASE_PRODUCTION_PERSONAL_RECOVERY_UNPROVEN');
|
|
78
|
+
recoveryInstances=bindPersonalRecovery(state,personalRecovery,recoveryStepCount);
|
|
79
|
+
}
|
|
80
|
+
const restoreProviders=state.recovery!==undefined&&state.recovery.step<recoveryStepCount;
|
|
81
|
+
if(browserRecovery!==undefined){
|
|
82
|
+
const invalid=()=>Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
83
|
+
const {priorRunId,priorRunLabel,priorCommit,verifiedCheckbox,earlierRunIds=[],providerInstance,recoveryLabel,restartFrom}=browserRecovery??{};
|
|
84
|
+
const optional=['priorRunId','priorRunLabel','priorCommit','verifiedCheckbox','earlierRunIds','providerInstance','recoveryLabel','restartFrom'].filter(key=>browserRecovery[key]!==undefined);
|
|
85
|
+
if(name!=='browser'||acquisition!==undefined||!record(browserRecovery,['progress','instanceId','closedRevision',...optional])||!isProductionAuthorizationRevision(browserRecovery.closedRevision)||providers.length!==(providerInstance===undefined?0:1))throw invalid();
|
|
86
|
+
if(priorRunLabel!==undefined&&(priorRunId===undefined||typeof priorRunLabel!=='string'||!/^browser-[0-9a-f-]{36}$/.test(priorRunLabel)))throw invalid();
|
|
87
|
+
if(priorRunLabel===undefined?priorCommit!==undefined:!isDeepStrictEqual(priorCommit,{results:1,terminal:1,outbox:1}))throw invalid();
|
|
88
|
+
if(verifiedCheckbox!==undefined&&(!priorRunLabel||!record(verifiedCheckbox,['ariaLabel','fingerprint','submissionSha256'])||typeof verifiedCheckbox.ariaLabel!=='string'||!/^[A-Za-z0-9][A-Za-z0-9 .:_\u2026-]{0,127}$/.test(verifiedCheckbox.ariaLabel)||typeof verifiedCheckbox.fingerprint!=='string'||!/^[a-f0-9]{12}$/.test(verifiedCheckbox.fingerprint)||typeof verifiedCheckbox.submissionSha256!=='string'||!/^[a-f0-9]{64}$/.test(verifiedCheckbox.submissionSha256)))throw invalid();
|
|
89
|
+
const {ids,...before}=state,{ids:closed,browserContinuation:continued,...after}=browserRecovery.progress??{};
|
|
90
|
+
const primary=ids.find(id=>id.sessionIndex===0&&id.tenant===state.actors[0].spaceId&&id.solutionId===solutionId);
|
|
91
|
+
if(primary?.instance!==browserRecovery.instanceId)throw invalid();
|
|
92
|
+
if(!Array.isArray(earlierRunIds)||earlierRunIds.length>3||earlierRunIds.length&&priorRunId===undefined)throw invalid();
|
|
93
|
+
if(providerInstance!==undefined){
|
|
94
|
+
const source=ids.find(id=>id.instance===primary.providerInstance);
|
|
95
|
+
if(Boolean(priorRunLabel)===Boolean(recoveryLabel)||recoveryLabel!==undefined&&(typeof recoveryLabel!=='string'||!/^[a-f0-9-]{36}$/.test(recoveryLabel)||recoveryLabel===state.label)||!record(providerInstance,['instanceId','closedRevision','releaseDigest'])||!isProductionAuthorizationRevision(providerInstance.closedRevision)||source?.instance!==providerInstance.instanceId||source.releaseDigest!==providerInstance.releaseDigest||source.sessionIndex!==0||source.tenant!==primary.tenant||source.solutionId!==providers[0].solutionId)throw invalid();
|
|
96
|
+
browserProvider=providerInstance;
|
|
97
|
+
if(restartFrom!==undefined&&(!recoveryLabel||!record(restartFrom,['step','runId'])||!earlierRunIds.includes(restartFrom.runId)||!Number.isSafeInteger(restartFrom.step)||restartFrom.step<1||restartFrom.step>providerSteps.length+1))throw invalid();
|
|
98
|
+
const restarting=restartFrom!==undefined&&isDeepStrictEqual(continued,restartFrom);
|
|
99
|
+
const step=restarting?0:continued?.step??0;
|
|
100
|
+
if(!restarting&&continued!==undefined&&(!record(continued,['step','runId'])||continued.runId!==priorRunId||!Number.isSafeInteger(step)||step<1||step>providerSteps.length+1)||restartFrom!==undefined&&continued===undefined)throw invalid();
|
|
101
|
+
browserContinuation={step,runId:priorRunId};
|
|
102
|
+
}else if(continued!==undefined||recoveryLabel!==undefined||restartFrom!==undefined)throw invalid();
|
|
103
|
+
if(!Number.isSafeInteger(after.queryCount)||after.queryCount<before.queryCount||after.queryCount>128)throw invalid();
|
|
104
|
+
before.queryCount=after.queryCount;
|
|
105
|
+
const originalRuns=priorRunId===undefined?[]:[...earlierRunIds,priorRunId];
|
|
106
|
+
const continuedRuns=Math.max(0,(browserContinuation?.step??0)-1);
|
|
107
|
+
if(!Array.isArray(after.runs)||after.runs.length!==before.runs.length+originalRuns.length+continuedRuns||!isDeepStrictEqual(after.runs.slice(0,before.runs.length+originalRuns.length),[...before.runs,...originalRuns])||new Set(after.runs).size!==after.runs.length||after.runs.some(run=>typeof run!=='string'||!run||run.length>128))throw invalid();
|
|
108
|
+
before.runs=after.runs;
|
|
109
|
+
if(!isDeepStrictEqual(after,before)||!Array.isArray(closed)||closed.length!==ids.length)throw invalid();
|
|
110
|
+
for(const [i,prior] of ids.entries()){
|
|
111
|
+
const {context:original,...binding}=prior;
|
|
112
|
+
const {context,...identity}=closed[i]??{};
|
|
113
|
+
const enabled=Boolean(browserContinuation?.step&&(prior.instance===primary.instance||prior.instance===browserProvider.instanceId));
|
|
114
|
+
if(!isDeepStrictEqual(identity,{...binding,enabled})||!context||context.instanceId!==original.instanceId||context.principalId!==original.principalId||context.tenantId!==original.tenantId||context.releaseDigest!==original.releaseDigest||!isProductionAuthorizationRevision(context.authorizationRevision))throw invalid();
|
|
115
|
+
}
|
|
116
|
+
state.ids=structuredClone(closed);
|
|
117
|
+
state.runs=before.runs;
|
|
118
|
+
state.queryCount=before.queryCount;
|
|
119
|
+
if(browserContinuation)state.browserContinuation=browserContinuation;
|
|
120
|
+
}
|
|
121
|
+
const restoreBrowserProvider=browserContinuation!==undefined&&browserContinuation.step<=providerSteps.length;
|
|
122
|
+
let observedInstance;
|
|
123
|
+
if(acquisition!==undefined){
|
|
124
|
+
const pending={kind:'acquire',sessionIndex:0,spaceId:previous?.actors[0].spaceId,solutionId,releaseDigest:manifest.releaseDigest};
|
|
125
|
+
if(name!=='personal-first'||providers.length||!acquisition||typeof acquisition.instanceId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/.test(acquisition.instanceId))throw Error('RELEASE_PRODUCTION_ACQUISITION_UNPROVEN');
|
|
126
|
+
const {progress,instanceId,restart}=acquisition;
|
|
127
|
+
if(restart===undefined){
|
|
128
|
+
if(!isDeepStrictEqual(progress,{...state,pending}))throw Error('RELEASE_PRODUCTION_ACQUISITION_UNPROVEN');
|
|
129
|
+
state.pending=pending;
|
|
130
|
+
observedInstance={id:instanceId,enabled:true,revision:'1'};
|
|
131
|
+
}else{
|
|
132
|
+
const {ids,pending:submitted,queryCount,runs,...initial}=progress??{};
|
|
133
|
+
const {context,...saved}=ids?.[0]??{};
|
|
134
|
+
const actor=state.actors[0];
|
|
135
|
+
const baseline=structuredClone(state);
|
|
136
|
+
delete baseline.ids;delete baseline.queryCount;delete baseline.runs;
|
|
137
|
+
const exactInstance={sessionIndex:0,tenant:actor.spaceId,instance:instanceId,solutionId,releaseDigest:manifest.releaseDigest,enabled:false};
|
|
138
|
+
const originalSubmit={kind:'submit',instance:instanceId,operationId:execution.operationId,idempotencyKey:'production-'+state.label+'-0'};
|
|
139
|
+
const originalRunId=restart.previousRunId;
|
|
140
|
+
const priorQueryCount=restart.priorQueryCount??state.queryCount+1;
|
|
141
|
+
const originalSubmission=originalRunId===undefined
|
|
142
|
+
?isDeepStrictEqual(runs,[])&&isDeepStrictEqual(submitted,originalSubmit)
|
|
143
|
+
:typeof originalRunId==='string'&&/^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/.test(originalRunId)&&isDeepStrictEqual(runs,[originalRunId])&&submitted===undefined;
|
|
144
|
+
// A prior qualification recovery can have assigned a new label. Only an
|
|
145
|
+
// independently observed exact run can identify that intervening attempt.
|
|
146
|
+
if(originalRunId!==undefined&&originalSubmission&&typeof initial.label==='string'&&/^[a-f0-9-]{36}$/.test(initial.label))baseline.label=initial.label;
|
|
147
|
+
if(!record(restart,['label','closedRevision',...(originalRunId===undefined?[]:['previousRunId']),...(restart.priorQueryCount===undefined?[]:['priorQueryCount'])])||typeof restart.label!=='string'||!/^[a-f0-9-]{36}$/.test(restart.label)||restart.label===state.label||restart.label===baseline.label||!isProductionAuthorizationRevision(restart.closedRevision)||!isDeepStrictEqual(initial,baseline)||ids?.length!==1||!isDeepStrictEqual(saved,exactInstance)||context?.instanceId!==instanceId||context.tenantId!==actor.spaceId||context.principalId!==actor.principalId||context.releaseDigest!==manifest.releaseDigest||!isProductionAuthorizationRevision(context.authorizationRevision)||!Number.isSafeInteger(priorQueryCount)||priorQueryCount<state.queryCount+1||priorQueryCount>128||queryCount!==priorQueryCount||!originalSubmission)throw Error('RELEASE_PRODUCTION_ACQUISITION_UNPROVEN');
|
|
148
|
+
state.label=restart.label;
|
|
149
|
+
observedInstance={id:instanceId,enabled:false,revision:restart.closedRevision};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const signal=AbortSignal.any([options.signal,phaseSignal,workSignal,AbortSignal.timeout(300000)].filter(Boolean));signal.throwIfAborted();let workCalls=0,cleanupCalls=0,cleanupMode=false,closingQueries=false,failed=false,failure,cleaned=false;
|
|
153
|
+
const pending=new Set(),invocations=new Set(),queryFailures=[],revoking=new Set();
|
|
154
|
+
const save=async()=>{const snapshot=JSON.parse(JSON.stringify(state));if(Buffer.byteLength(JSON.stringify(snapshot))>65536)throw Error('RELEASE_PRODUCTION_PHASE_STATE_LIMIT');await checkpoint(snapshot);};
|
|
155
|
+
// Completed progress is acknowledged only after the original sessions close.
|
|
156
|
+
// Reserve their four logout/me calls plus eight calls to authenticate, check
|
|
157
|
+
// and revoke both cleanup sessions, then one list per actor and each disable.
|
|
158
|
+
const cleanupReserve=()=>{const active=state.ids.filter(id=>id.enabled!==false),groups=new Set(active.map(id=>id.sessionIndex));let count=active.length;if(state.pending?.kind==='acquire'){groups.add(state.pending.sessionIndex);count++;}return count?12+groups.size+count:4;};
|
|
159
|
+
const request=async(url,settings)=>{const pathname=new URL(url).pathname,cookie=settings.headers?.cookie;if(pathname==='/api/auth/logout'&&cookie)revoking.add(cookie);const cleanup=cleanupMode||pathname==='/api/auth/logout'||pathname==='/api/me'&&cookie&&revoking.has(cookie);if(workCalls+cleanupCalls>=43||!cleanup&&workCalls>=Math.min(39,43-cleanupReserve()))throw Error('RELEASE_PRODUCTION_HTTP_BUDGET_LIMIT');if(cleanup)cleanupCalls++;else workCalls++;if(pathname==='/api/auth/login')revoking.clear();return operator.request(url,settings);};
|
|
160
|
+
const client=createAcceptanceOracleClient({statements,execute:async({statement,values})=>{state.queryCount++;await save();return operator.oracle.query(statement,values,{signal});}});
|
|
161
|
+
const oracle={query(statement,values){try{if(closingQueries)throw Error('RELEASE_PROBE_CLOSED');signal.throwIfAborted();client.resolve(statement);if(state.queryCount>=128)throw Error('RELEASE_PROBE_COUNT_LIMIT');}catch(error){return Promise.reject(error);}const task=client.query(statement,values,{signal});pending.add(task);task.then(()=>pending.delete(task),error=>{if(error.message!=='ACCEPTANCE_ORACLE_PARAMETERS_INVALID'&&error.message!=='ACCEPTANCE_ORACLE_SCOPE_INVALID')queryFailures.push(error);pending.delete(task);});return task;}};
|
|
162
|
+
const settle=async()=>{closingQueries=true;await Promise.allSettled([...invocations,...pending]);for(const error of queryFailures)if(!failed||error!==failure){failure=append(failed,failure,error,'RELEASE_PRODUCTION_QUERY_CLOSE_UNKNOWN');failed=true;}queryFailures.length=0;};
|
|
163
|
+
const sessionsWork=async(work,cleanup=false)=>{const prior=cleanupMode;cleanupMode=cleanup;try{return await withReleaseControlSession({origin:core.origin,account:operator.accounts[0],signal:cleanup?undefined:signal,request},async first=>withReleaseControlSession({origin:core.origin,account:operator.accounts[1],signal:cleanup?undefined:signal,request},async second=>{
|
|
164
|
+
const sessions=[first,second],me=await Promise.all(sessions.map(async session=>(await session.call('/api/me')).value));
|
|
165
|
+
if(me.some((value,i)=>value?.principalId!==operator.actors[i].userId||value.personalSpace?.role!=='owner'||value.personalSpace?.kind!=='personal'||typeof value.personalSpace.spaceId!=='string'||!value.personalSpace.spaceId||value.personalSpace.spaceId.length>128)||me[0].principalId===me[1].principalId||me[0].personalSpace.spaceId===me[1].personalSpace.spaceId||state.actors.length&&state.actors.some((actor,i)=>actor.principalId!==me[i].principalId||actor.spaceId!==me[i].personalSpace.spaceId))throw Error('RELEASE_PRODUCTION_ACTOR_IDENTITY_FAILED');
|
|
166
|
+
return work(sessions,me);
|
|
167
|
+
}));}finally{cleanupMode=prior;}};
|
|
168
|
+
const drive=async(sessions,me,cleanupOnly=false)=>{
|
|
169
|
+
const releaseFor=value=>value.releaseDigest===manifest.releaseDigest?manifest:{solutionId:value.solutionId,releaseDigest:value.releaseDigest};
|
|
170
|
+
const restore=value=>({...value,principal:state.actors[value.sessionIndex]?.principalId??me[value.sessionIndex].principalId,tenant:value.tenant,instance:value.instance,manifest:releaseFor(value),session:sessions[value.sessionIndex],context:value.context?structuredClone(value.context):undefined});
|
|
171
|
+
const update=id=>{const saved=state.ids.find(value=>value.instance===id.instance);if(saved){saved.context=id.context?structuredClone(id.context):null;if(id.providerInstance)saved.providerInstance=id.providerInstance;}};
|
|
172
|
+
const refresh=async(id,exact=false)=>{const resolved=(await id.session.call('/api/instances/'+id.instance)).value;if(resolved.context?.principalId!==id.principal||resolved.context.instanceId!==id.instance||resolved.context.tenantId!==id.tenant||resolved.context.releaseDigest!==id.manifest.releaseDigest||!isProductionAuthorizationRevision(resolved.context.authorizationRevision)||exact&&resolved.context.authorizationRevision!==id.context.authorizationRevision)throw Error('RELEASE_PRODUCTION_INSTANCE_SCOPE_FAILED');id.context=resolved.context;update(id);await save();return id;};
|
|
173
|
+
const change=async(id,enabled)=>{const summary=(await id.session.call('/api/instances/'+id.instance,{method:'PATCH',body:{enabled,expectedAuthorizationRevision:id.context.authorizationRevision},cleanup:cleanupMode})).value;if(summary.enabled!==enabled||!isProductionAuthorizationRevision(summary.authorizationRevision))throw Error('RELEASE_PRODUCTION_DISABLE_UNKNOWN');const saved=state.ids.find(value=>value.instance===id.instance);if(saved){saved.enabled=enabled;saved.context={...id.context,authorizationRevision:summary.authorizationRevision};}return summary;};
|
|
174
|
+
const closeKnown=async(selected=state.ids)=>{const prior=cleanupMode;cleanupMode=true;const errors=[];try{for(const sessionIndex of new Set(selected.map(value=>value.sessionIndex))){let all;try{all=(await sessions[sessionIndex].call('/api/me/instances',{cleanup:true})).value;if(!Array.isArray(all))throw Error('RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');}catch(error){errors.push(error);continue;}for(const saved of selected.filter(value=>value.sessionIndex===sessionIndex).toReversed()){try{const current=all.find(value=>value.instanceId===saved.instance);if(!current||current.releaseDigest!==saved.releaseDigest||current.spaceId!==saved.tenant||current.solutionId!==saved.solutionId||current.canManage!==true)throw Error('RELEASE_PRODUCTION_INSTANCE_OWNERSHIP_UNKNOWN');if(current.enabled){const id=restore(saved);id.context={...id.context,authorizationRevision:current.authorizationRevision};await change(id,false);}saved.enabled=false;await save();}catch(error){errors.push(error);}}}}finally{cleanupMode=prior;}if(errors.length)throw new AggregateError(errors,'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');};
|
|
175
|
+
if(cleanupOnly){await closeKnown();cleaned=true;return;}
|
|
176
|
+
const invoke=(id,method,input)=>{const task=(async()=>{if(closingQueries)throw Error('RELEASE_PROBE_CLOSED');signal.throwIfAborted();const result=(await id.session.call('/api/instances/'+id.instance+'/invoke',{body:{method,input,expectedAuthorizationRevision:id.context.authorizationRevision}})).value;if(method==='submit'){if(typeof result?.runId!=='string')throw Error('RELEASE_PRODUCTION_RUN_INVALID');if(!state.runs.includes(result.runId))state.runs.push(result.runId);delete state.pending;await save();}return result;})();invocations.add(task);task.then(()=>invocations.delete(task),error=>{invocations.delete(task);if(!['NOT_FOUND','NOT_AUTHORIZED','AUTHORIZATION_CHANGED'].includes(error?.code))queryFailures.push(error);});return task;};
|
|
177
|
+
const completed=async(id,ref)=>{
|
|
178
|
+
// A one-minute scheduler tick plus the worker's own execution can exceed
|
|
179
|
+
// one minute. Poll less often inside the unchanged phase and cleanup limits.
|
|
180
|
+
const deadline=Date.now()+150000;
|
|
181
|
+
for(let poll=0;poll<16;poll++){
|
|
182
|
+
const run=await invoke(id,'getRun',{runId:ref.runId});
|
|
183
|
+
if(run.status==='succeeded')return run;
|
|
184
|
+
if(['failed','cancelled','partial','reconciliation_required'].includes(run.status))throw Error('RELEASE_PRODUCTION_RUN_FAILED');
|
|
185
|
+
const remaining=deadline-Date.now();
|
|
186
|
+
if(remaining<=0)break;
|
|
187
|
+
await delay(Math.min(10000,remaining),signal);
|
|
188
|
+
}
|
|
189
|
+
throw Error('RELEASE_PRODUCTION_RUN_TIMEOUT');
|
|
190
|
+
};
|
|
191
|
+
const submit=async(id,operationId,input,idempotencyKey=randomUUID())=>{state.pending={kind:'submit',instance:id.instance,operationId,idempotencyKey};await save();return invoke(id,'submit',{operationId,input,idempotencyKey});};
|
|
192
|
+
const qualificationLabel=id=>{
|
|
193
|
+
const selected=state.ids.find(value=>value.instance===id.instance&&value.tenant===id.tenant&&value.releaseDigest===id.manifest.releaseDigest);
|
|
194
|
+
if(!selected||selected.context?.principalId!==id.principal)throw Error('RELEASE_PRODUCTION_INSTANCE_SCOPE_FAILED');
|
|
195
|
+
const label=browserContinuation&&browserRecovery.recoveryLabel?browserRecovery.recoveryLabel:state.label;
|
|
196
|
+
return createHash('sha256').update(JSON.stringify([label,selected.instance])).digest('hex');
|
|
197
|
+
};
|
|
198
|
+
const committedRow=async ref=>{
|
|
199
|
+
if(!state.runs.includes(ref.runId))throw Error('RELEASE_PRODUCTION_RUN_SCOPE_FAILED');
|
|
200
|
+
return (await oracle.query(acceptanceCommittedStatement,[ref.runId])).rows[0];
|
|
201
|
+
};
|
|
202
|
+
const fixture={readResourceJson,expect,oracle,checks:state.checks,qualificationLabel,query:(id,queryId,input)=>invoke(id,'query',{queryId,input}),invoke,submit,execute:async(id,operationId,input,key)=>{const ref=await submit(id,operationId,input,key);await completed(id,ref);return ref;},completed,
|
|
203
|
+
async trackRun(id,ref){
|
|
204
|
+
if(typeof ref?.runId!=='string'||!ref.runId||ref.runId.length>128||ref.instanceId!==id.instance)throw Error('RELEASE_PRODUCTION_RUN_INVALID');
|
|
205
|
+
if(!state.runs.includes(ref.runId))state.runs.push(ref.runId);
|
|
206
|
+
await save();
|
|
207
|
+
},
|
|
208
|
+
async assertRunCommitted(ref){
|
|
209
|
+
const row=await committedRow(ref);
|
|
210
|
+
assert.deepEqual(row,{results:1,terminal:1,outbox:1});
|
|
211
|
+
return row;
|
|
212
|
+
},
|
|
213
|
+
async awaitBrowserCommit(ref){
|
|
214
|
+
const deadline=Date.now()+150000;
|
|
215
|
+
// The iframe owns the runtime status reads. Independently poll only the
|
|
216
|
+
// bounded acceptance oracle instead of doubling the same runtime RPC.
|
|
217
|
+
for(let attempt=0;attempt<16;attempt++){
|
|
218
|
+
const row=await committedRow(ref);
|
|
219
|
+
if(isDeepStrictEqual(row,{results:1,terminal:1,outbox:1}))return;
|
|
220
|
+
if(!row||Object.values(row).some(count=>!Number.isSafeInteger(count)||count<0||count>1))throw Error('RELEASE_PRODUCTION_RUN_COMMIT_INVALID');
|
|
221
|
+
const remaining=deadline-Date.now();
|
|
222
|
+
if(remaining<=0)break;
|
|
223
|
+
if(attempt<15)await delay(Math.min(10000,remaining),signal);
|
|
224
|
+
}
|
|
225
|
+
throw Error('RELEASE_PRODUCTION_BROWSER_COMMIT_TIMEOUT');
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
const enable=async(sessionIndex,spaceId,release,links=[])=>{
|
|
229
|
+
state.pending={kind:'acquire',sessionIndex,spaceId,solutionId:release.solutionId,releaseDigest:release.releaseDigest};await save();
|
|
230
|
+
let expected=observedInstance;
|
|
231
|
+
if(state.recovery?.step===0){
|
|
232
|
+
const saved=state.ids.find(id=>id.sessionIndex===sessionIndex&&id.tenant===spaceId&&id.solutionId===release.solutionId&&id.releaseDigest===release.releaseDigest);
|
|
233
|
+
expected=recoveryInstances.get(saved?.instance);
|
|
234
|
+
if(!expected)throw Error('RELEASE_PRODUCTION_PERSONAL_RECOVERY_UNPROVEN');
|
|
235
|
+
}
|
|
236
|
+
return acquireProductionInstance({session:sessions[sessionIndex],principal:me[sessionIndex].principalId,spaceId,release,links,observedInstance:expected,qualificationJobId:operator.qualificationJobId,async onAcquired(value){
|
|
237
|
+
const saved=state.ids.find(id=>id.instance===value.instance);
|
|
238
|
+
if(saved)saved.enabled=true;
|
|
239
|
+
else state.ids.push({sessionIndex,tenant:value.tenant,instance:value.instance,solutionId:release.solutionId,releaseDigest:release.releaseDigest,context:null,enabled:true});
|
|
240
|
+
delete state.pending;await save();
|
|
241
|
+
},refresh});
|
|
242
|
+
};
|
|
243
|
+
const catalogReleases=async session=>{
|
|
244
|
+
const releases=(await session.call('/api/catalog')).value?.releases;
|
|
245
|
+
if(!Array.isArray(releases))throw Error('RELEASE_PRODUCTION_CATALOG_INVALID');
|
|
246
|
+
return releases;
|
|
247
|
+
};
|
|
248
|
+
const identity=async(sessionIndex,spaceId=me[sessionIndex].personalSpace.spaceId)=>{const selected=[];for(const provider of providers){const release=state.providers?.find(value=>value.solutionId===provider.solutionId);if(!/^sha256:[a-f0-9]{64}$/.test(release?.releaseDigest??''))throw Error('RELEASE_PRODUCTION_PROVIDER_REQUIRED');selected.push({definition:provider,id:await enable(sessionIndex,spaceId,release)});}const id=await enable(sessionIndex,spaceId,manifest,selected.map(value=>({port:value.definition.port,providerInstanceId:value.id.instance})));if(selected.length===1){id.providerInstance=selected[0].id.instance;update(id);await save();}for(const current of [...selected.map(value=>value.id),id]){const budget=(await oracle.query(acceptanceBudgetStatement,[current.tenant,current.instance,current.principal])).rows;if(budget.length!==1||budget[0].zero_limit!==true||budget[0].zero_reservation!==true)throw Error('RELEASE_PRODUCTION_ZERO_COST_POLICY_REQUIRED');}return id;};
|
|
249
|
+
const restorePersonal=(sessionIndex,release)=>{
|
|
250
|
+
const saved=state.ids.filter(value=>value.sessionIndex===sessionIndex&&value.tenant===state.actors[sessionIndex].spaceId&&value.solutionId===release?.solutionId&&value.releaseDigest===release.releaseDigest&&value.enabled);
|
|
251
|
+
if(saved.length!==1)throw Error('RELEASE_PRODUCTION_INSTANCE_SCOPE_FAILED');
|
|
252
|
+
return restore(saved[0]);
|
|
253
|
+
};
|
|
254
|
+
const reopenBrowserInstances=async scopes=>{
|
|
255
|
+
const all=(await sessions[0].call('/api/me/instances')).value;
|
|
256
|
+
if(!Array.isArray(all))throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
257
|
+
for(const {instanceId,closedRevision} of scopes){
|
|
258
|
+
const id=restore(state.ids.find(value=>value.instance===instanceId));
|
|
259
|
+
const observed=all.find(value=>value.instanceId===id.instance);
|
|
260
|
+
if(!observed||observed.enabled!==false||observed.canManage!==true||observed.spaceId!==id.tenant||observed.solutionId!==id.manifest.solutionId||observed.releaseDigest!==id.manifest.releaseDigest||observed.authorizationRevision!==closedRevision)throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
261
|
+
id.context.authorizationRevision=observed.authorizationRevision;
|
|
262
|
+
const enabled=await change(id,true);
|
|
263
|
+
id.context={...id.context,authorizationRevision:enabled.authorizationRevision};
|
|
264
|
+
await refresh(id,true);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
const completePersonal=async(id,ref)=>{
|
|
268
|
+
state.personalRuns??=[];state.personalRuns.push({sessionIndex:selected,runId:ref.runId});await save();
|
|
269
|
+
if(selected){const firstId=restorePersonal(0,manifest);assert.notEqual(firstId.instance,id.instance);assert.notEqual(firstId.tenant,id.tenant);const denied=error=>['NOT_FOUND','NOT_AUTHORIZED','AUTHORIZATION_CHANGED'].includes(error.code);await assert.rejects(()=>invoke(firstId,'getRun',{runId:ref.runId}),denied);await assert.rejects(()=>invoke(id,'getRun',{runId:state.personalRuns[0].runId}),denied);state.checks.push('two actual users, distinct personal instances, duplicate delivery, owned SQL/value oracles, one terminal result/event/outbox and foreign RunRef denial');}
|
|
270
|
+
};
|
|
271
|
+
try{
|
|
272
|
+
if(restoreProviders){
|
|
273
|
+
const step=state.recovery.step;
|
|
274
|
+
if(step===0){await identity(0);await identity(1);}
|
|
275
|
+
else{
|
|
276
|
+
const sessionIndex=Math.floor((step-1)/providerSteps.length),definition=providerSteps[(step-1)%providerSteps.length];
|
|
277
|
+
const consumer=restorePersonal(sessionIndex,manifest),source=restorePersonal(sessionIndex,state.providers.find(value=>value.solutionId===definition.provider.solutionId));
|
|
278
|
+
await definition.prepare(fixture,consumer,source);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
else if(name==='setup'){state.actors=me.map(value=>({principalId:value.principalId,spaceId:value.personalSpace.spaceId}));const catalog=providers.length?await catalogReleases(sessions[0]):[];state.providers=providers.map(provider=>{const selected=catalog.filter(value=>value.solutionId===provider.solutionId);if(selected.length!==1)throw Error('RELEASE_PRODUCTION_PROVIDER_REQUIRED');return {solutionId:provider.solutionId,releaseDigest:selected[0].releaseDigest};});await save();}
|
|
282
|
+
else if(prepare){
|
|
283
|
+
const consumer=acquire?await identity(selected):restorePersonal(selected,manifest);
|
|
284
|
+
const source=restorePersonal(selected,state.providers.find(value=>value.solutionId===provider.solutionId));
|
|
285
|
+
await prepare(fixture,consumer,source);
|
|
286
|
+
}
|
|
287
|
+
else if(verify){
|
|
288
|
+
const id=restorePersonal(selected,manifest),check=state.valueCheck;
|
|
289
|
+
if(!record(check,['sessionIndex','instance','data','ref'])||check.sessionIndex!==selected||check.instance!==id.instance||!state.runs.includes(check.ref?.runId)||!check.data||!Object.hasOwn(check.data,'input'))throw Error('RELEASE_PRODUCTION_VALUE_CHECK_UNPROVEN');
|
|
290
|
+
await execution.assertValue(fixture,id,check.data,check.ref);
|
|
291
|
+
delete state.valueCheck;
|
|
292
|
+
await completePersonal(id,check.ref);
|
|
293
|
+
}
|
|
294
|
+
else if(selected!==undefined){
|
|
295
|
+
const id=acquire?await identity(selected):restorePersonal(selected,manifest),data=await execution.prepare(fixture,id,state.label+'-'+selected),key='production-'+state.label+'-'+selected,refs=await Promise.all([submit(id,execution.operationId,data.input,key),submit(id,execution.operationId,data.input,key)]);assert.deepEqual(refs[0],refs[1]);await completed(id,refs[0]);
|
|
296
|
+
if(!verifySeparately)await execution.assertValue(fixture,id,data,refs[0]);
|
|
297
|
+
await fixture.assertRunCommitted(refs[0]);
|
|
298
|
+
if(verifySeparately)state.valueCheck={sessionIndex:selected,instance:id.instance,data,ref:refs[0]};
|
|
299
|
+
else await completePersonal(id,refs[0]);
|
|
300
|
+
}
|
|
301
|
+
else if(name==='authorization'){const matches=me[0].spaces.filter(space=>space.name==='Solution release qualification'&&space.kind==='shared');if(matches.length>1||matches[0]&&matches[0].role!=='owner')throw Error('RELEASE_PRODUCTION_SHARED_OWNERSHIP_UNKNOWN');const shared=matches[0]??(await sessions[0].call('/api/spaces',{body:{name:'Solution release qualification'},expected:[201]})).value;state.sharedSpace=shared.spaceId;await save();await sessions[0].call('/api/spaces/'+shared.spaceId+'/members/'+me[1].principalId,{method:'PATCH',body:{role:'member'}});const sharedId=await identity(0,shared.spaceId);await assert.rejects(()=>sessions[1].call('/api/instances/'+sharedId.instance,{method:'PATCH',body:{enabled:false,expectedAuthorizationRevision:sharedId.context.authorizationRevision}}),error=>error.code==='NOT_AUTHORIZED');state.checks.push('explicit shared space membership cannot disable the owner-managed instance');const secondId=restore(state.ids.find(value=>value.sessionIndex===1&&value.solutionId===solutionId&&value.tenant===state.actors[1].spaceId)),stale={...secondId,context:{...secondId.context}},disabled=await change(secondId,false);await save();await assert.rejects(()=>invoke(stale,'getRun',{runId:state.runs[0]}),error=>['NOT_FOUND','NOT_AUTHORIZED','AUTHORIZATION_CHANGED'].includes(error.code));secondId.context={...secondId.context,authorizationRevision:disabled.authorizationRevision};await change(secondId,true);await refresh(secondId);await assert.rejects(()=>invoke(stale,'query',{queryId:execution.queryId,input:{}}),error=>['NOT_FOUND','NOT_AUTHORIZED','AUTHORIZATION_CHANGED'].includes(error.code));state.checks.push('disable commits revoke the old revision; re-enable increments authority without replay');await closeKnown(state.ids.filter(value=>value.tenant===shared.spaceId));}
|
|
302
|
+
else if(restoreBrowserProvider){
|
|
303
|
+
if(browserContinuation.step===0)await reopenBrowserInstances([browserProvider,browserRecovery]);
|
|
304
|
+
else{
|
|
305
|
+
const definition=providerSteps[browserContinuation.step-1];
|
|
306
|
+
const consumer=restorePersonal(0,manifest),source=restorePersonal(0,state.providers.find(value=>value.solutionId===definition.provider.solutionId));
|
|
307
|
+
await refresh(consumer,true);await refresh(source,true);
|
|
308
|
+
await definition.prepare(fixture,consumer,source);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
else if(name==='browser'){
|
|
312
|
+
const id=restore(state.ids.find(value=>value.sessionIndex===0&&value.solutionId===solutionId&&value.tenant===state.actors[0].spaceId));
|
|
313
|
+
if(browserRecovery&&!browserContinuation)await reopenBrowserInstances([browserRecovery]);
|
|
314
|
+
await refresh(id,browserContinuation!==undefined);
|
|
315
|
+
const {exerciseOwnerProductionBrowser}=await import('./owner-production-browser.mjs');
|
|
316
|
+
const priorSubmission=browserRecovery?.priorRunLabel===undefined?undefined:{runId:browserRecovery.priorRunId,label:browserRecovery.priorRunLabel,commit:browserRecovery.priorCommit,verifiedCheckbox:browserRecovery.verifiedCheckbox};
|
|
317
|
+
state.browser=await exerciseOwnerProductionBrowser({target,id,account:operator.accounts[0],fixture,definition:browser,browserHost,writeEvidence,signal,request,priorSubmission,qualificationJobId:operator.qualificationJobId});
|
|
318
|
+
}
|
|
319
|
+
else{await closeKnown();cleaned=true;}
|
|
320
|
+
}catch(error){failed=true;failure=error;}finally{await settle();if(failed){try{await closeKnown();cleaned=true;}catch(error){failure=append(true,failure,error,'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');}}}
|
|
321
|
+
if(failed)throw failure;
|
|
322
|
+
};
|
|
323
|
+
try{if(acquisition===undefined&&browserRecovery===undefined)await save();await sessionsWork((sessions,me)=>drive(sessions,me));}catch(error){if(!failed){failure=error;failed=true;}else if(error!==failure)failure=append(true,failure,error,'RELEASE_PRODUCTION_PHASE_FAILED');}
|
|
324
|
+
await settle();if(failed&&!cleaned&&state.ids.length)try{await sessionsWork((sessions,me)=>drive(sessions,me,true),true);}catch(error){failure=append(true,failure,error,'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');}
|
|
325
|
+
if(failed)throw failure;signal.throwIfAborted();
|
|
326
|
+
if(restoreProviders)state.recovery={step:state.recovery.step+1,status:'ready'};
|
|
327
|
+
else if(restoreBrowserProvider)state.browserContinuation={...browserContinuation,step:browserContinuation.step+1};
|
|
328
|
+
else{
|
|
329
|
+
delete state.recovery;
|
|
330
|
+
delete state.browserContinuation;
|
|
331
|
+
state.status='completed';state.http={work:workCalls,cleanup:cleanupCalls,total:workCalls+cleanupCalls};state.history.push({phase:name,http:{...state.http}});
|
|
332
|
+
}
|
|
333
|
+
if(name==='cleanup'){if(!state.browser||state.ids.some(id=>id.enabled!==false))throw Error('RELEASE_PRODUCTION_CLOSE_UNKNOWN');state.proof={status:'PASS',productionBootstrap:true,users:2,personalInstances:2,sharedSpace:true,queryCount:state.queryCount,runs:state.runs.length,checks:[...state.checks],browser:state.browser,syntheticInstancesCreated:state.ids.length,syntheticInstancesDisabled:state.ids.length,closure:{status:'closed',activeRequests:0}};}
|
|
334
|
+
try{await save();}catch(error){let original=error;if(!cleaned&&state.ids.length)try{await sessionsWork((sessions,me)=>drive(sessions,me,true),true);}catch(cleanup){original=append(true,original,cleanup,'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');}throw original;}return JSON.parse(JSON.stringify(state));
|
|
335
|
+
}})));
|
|
336
|
+
}
|
|
337
|
+
/** Local execution uses exactly the durable phase plan, without a second path. */
|
|
338
|
+
export async function exerciseOwnerProduction(options){let previous;for(const phase of createOwnerProductionPlan(options))previous=await phase.execute({previous,checkpoint:async()=>{},signal:options.signal});return previous.proof;}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
4
|
+
import {createPublicKey} from 'node:crypto';
|
|
5
|
+
import {releaseJson} from './release-control.mjs';
|
|
6
|
+
import {readOwnerDatabaseCredentials,ownerDatabaseConnections,verifyOwnerDatabaseConnections} from './owner-database.mjs';
|
|
7
|
+
|
|
8
|
+
/** Public platform verifiers are supplied by the owner's composition root. */
|
|
9
|
+
export async function loadOwnerInfrastructure({root,signal,verifyDatabase,verifyRelations,requestMetadata}){
|
|
10
|
+
if([verifyDatabase,verifyRelations,requestMetadata].some(value=>typeof value!=='function'))throw Error('OWNER_DATABASE_VERIFIER_REQUIRED');
|
|
11
|
+
const read=name=>JSON.parse(fs.readFileSync(path.join(root,'deployment',name),'utf8'));
|
|
12
|
+
const target=read('target.json'),config=read('database.json'),contract=read('schema-contract.json');
|
|
13
|
+
const credentials=await readOwnerDatabaseCredentials({root,target:config.target,signal});if(!credentials)throw Error('OWNER_DATABASE_SETUP_REQUIRED');
|
|
14
|
+
const relations=contract.snapshot.relations.filter(item=>['r','p'].includes(item.kind)).map(item=>({name:item.name,privileges:item.acl.filter(acl=>acl.grantee==='platform_runtime'&&['SELECT','INSERT','UPDATE','DELETE'].includes(acl.privilege)).map(acl=>acl.privilege)}));
|
|
15
|
+
if(config.target.projectRef!==target.projectRef||contract.snapshot.schemaName!==config.target.schema||relations.some(item=>!item.privileges.length))throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
16
|
+
await verifyOwnerDatabaseConnections({credentials,connection:config.connection,signal,verify:(pool,expected)=>verifyDatabase(pool,expected,expected.kind==='application'?db=>verifyRelations(db,{schema:config.target.schema,relations}):undefined)});
|
|
17
|
+
const metadata=await requestMetadata(target.coreOrigin+'/api/runtime/keys',{signal,timeoutMs:15000});
|
|
18
|
+
if(!metadata||Object.keys(metadata).join(',')!=='keys'||!Array.isArray(metadata.keys)||!metadata.keys.length||metadata.keys.length>8||new Set(metadata.keys.map(key=>key.keyId)).size!==metadata.keys.length)throw Error('CORE_RUNTIME_TRUST_INVALID');
|
|
19
|
+
const verificationKeys=metadata.keys.map(key=>{if(!key||Object.keys(key).sort().join(',')!=='keyId,publicKey'||typeof key.keyId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9:._/-]{0,255}$/.test(key.keyId)||typeof key.publicKey!=='string'||key.publicKey.length>8192)throw Error('CORE_RUNTIME_TRUST_INVALID');const parsed=createPublicKey(key.publicKey);if(parsed.asymmetricKeyType!=='ed25519'||parsed.export({type:'spki',format:'pem'}).toString()!==key.publicKey)throw Error('CORE_RUNTIME_TRUST_INVALID');return key;});
|
|
20
|
+
return {coreOrigin:target.coreOrigin,database:ownerDatabaseConnections(credentials,config.connection),worker:{id:config.target.solutionId+'-worker'},verificationKeys};
|
|
21
|
+
}
|
|
22
|
+
export async function observeOwnerRuntime({origin,manifest,signal,request=fetch}){
|
|
23
|
+
const base=new URL(manifest?.server?.url);if(base.protocol!=='https:'||base.origin!==origin||base.href!==manifest.server.url||base.username||base.password||base.hash||base.search)throw Error('RELEASE_OWNER_RUNTIME_NOT_READY');
|
|
24
|
+
const body=JSON.stringify(manifest);if(Buffer.byteLength(body)>1048576)throw Error('RELEASE_OWNER_RUNTIME_NOT_READY');
|
|
25
|
+
const roles=['api','worker'];
|
|
26
|
+
const outcomes=await Promise.allSettled(roles.map(async role=>{
|
|
27
|
+
const response=await releaseJson(base.href.replace(/\/$/,'')+(role==='api'?'/health':'/worker-health'),{method:'POST',headers:{'content-type':'application/json'},body}, {signal,request}),value=response.value;
|
|
28
|
+
if(response.status!==200||!response.headers.get('cache-control')?.split(',').some(value=>value.trim().toLowerCase()==='no-store')||value?.protocol!=='link-light.runtime/2'||value.role!==role||value.ready!==true||value.releaseDigest!==manifest.releaseDigest||value.serverDigest!==manifest.artifacts.server||value.resourcesDigest!==manifest.artifacts.resources)throw Error('RELEASE_OWNER_RUNTIME_NOT_READY',{cause:{retryable:response.status!==200||value?.ready!==true}});
|
|
29
|
+
}));
|
|
30
|
+
const failure=outcomes.find(value=>value.status==='rejected');if(failure)throw failure.reason;
|
|
31
|
+
return {status:'FINITE_OWNER_RUNTIME_READY',releaseDigest:manifest.releaseDigest,roles};
|
|
32
|
+
}
|
|
33
|
+
export async function waitOwnerRuntime({maximumWaitMs=180000,pollMs=5000,...options}){
|
|
34
|
+
if(!Number.isSafeInteger(maximumWaitMs)||maximumWaitMs<1||maximumWaitMs>180000||!Number.isSafeInteger(pollMs)||pollMs<1||pollMs>10000)throw Error('RELEASE_OWNER_CONTEXT_INVALID');
|
|
35
|
+
const deadline=Date.now()+maximumWaitMs;
|
|
36
|
+
const signal=AbortSignal.any([...(options.signal?[options.signal]:[]),AbortSignal.timeout(maximumWaitMs)]);
|
|
37
|
+
for(;;){try{return await observeOwnerRuntime({...options,signal});}catch(error){
|
|
38
|
+
if(error.cause?.retryable===false||!(error.cause?.retryable===true||['TypeError','TimeoutError','AbortError'].includes(error.name))||Date.now()>=deadline||options.signal?.aborted)throw error;
|
|
39
|
+
await delay(Math.max(1,Math.min(pollMs,deadline-Date.now())),undefined,{signal});
|
|
40
|
+
}}
|
|
41
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export interface OwnerCloudflareWorkerBuildOptions {root:string;bindingEntry:string;wranglerEntry:string;registration:Parameters<typeof import('@xlinklight/platform/build').prepareWorkerCatalog>[0]['registration'];uiExportNames:readonly string[];resourceEntry:URL;domain:{schema:string;relations:readonly {name:string;privileges:readonly ('SELECT'|'INSERT'|'UPDATE'|'DELETE')[]}[]};compatibilityDate?:string;compatibilityFlags?:readonly string[];signal?:AbortSignal}
|
|
2
|
+
export function prepareOwnerCloudflareWorkerBuild(options:OwnerCloudflareWorkerBuildOptions):Promise<{status:'PASS';entry:string;files:number;bytes:number;serverDigest:string;packageName:string;packageVersion:string;integrity:string;resourcesDigest:string;uiDigest:string}>;
|
|
3
|
+
export function readOwnerCloudflareWorkerBuild(options:{root:string;output?:string;maximumFiles?:number;maximumFileBytes?:number;maximumTotalBytes?:number}):{index:{schemaVersion:1;kind:'cloudflare-worker';entry:string;packageName:string;packageVersion:string;integrity:string;resourcesDigest:string;uiDigest:string;graph:import('./cloudflare-build.mjs').CloudflareBuildResult['metadata'];files:{path:string;byteLength:number;sha256:string}[]};plan:import('./cloudflare-worker-package.mjs').CloudflareWorkerPackage;files:{path:string;role:'control';bytes:Uint8Array}[];payloadBytes:number};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {createVerificationRun} from './temporary-scope.mjs';
|
|
6
|
+
import {bundleCloudflareWorker} from './cloudflare-build.mjs';
|
|
7
|
+
import {parseCloudflareWorkerPackage} from './cloudflare-worker-package.mjs';
|
|
8
|
+
|
|
9
|
+
const fail=()=>Error('OWNER_WORKER_BUILD_INVALID');
|
|
10
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
11
|
+
const canonical=value=>JSON.stringify(value)+'\n';
|
|
12
|
+
function regular(root,relative,maximum=16777216){
|
|
13
|
+
if(typeof relative!=='string'||!relative||/[\\:\0-\x1f\x7f]/.test(relative)||relative.split('/').some(part=>!part||part==='.'||part==='..'))throw fail();
|
|
14
|
+
const selected=path.resolve(root,relative),suffix=path.relative(root,selected),info=fs.lstatSync(selected);
|
|
15
|
+
if(!suffix||suffix.startsWith('..'+path.sep)||path.isAbsolute(suffix)||!info.isFile()||info.isSymbolicLink()||info.size>maximum||fs.realpathSync(selected)!==selected)throw fail();return fs.readFileSync(selected);
|
|
16
|
+
}
|
|
17
|
+
function json(root,relative,maximum=1048576){return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(regular(root,relative,maximum)));}
|
|
18
|
+
function filename(value){return typeof value==='string'&&value&&!/[\\:\0-\x1f\x7f]/.test(value)&&value.split('/').every(part=>part&&part!=='.'&&part!=='..'&&!part.startsWith('.'));}
|
|
19
|
+
|
|
20
|
+
/** Read only a complete original byte-bound local Worker artifact. */
|
|
21
|
+
export function readOwnerCloudflareWorkerBuild({root,output='dist-worker',maximumFiles=8192,maximumFileBytes=16777216,maximumTotalBytes=67108864}){
|
|
22
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||!filename(output)||![maximumFiles,maximumFileBytes,maximumTotalBytes].every(value=>Number.isSafeInteger(value)&&value>0))throw fail();root=fs.realpathSync(root);
|
|
23
|
+
const index=json(root,output+'/worker-build.json',8388608),files=[];let total=0;
|
|
24
|
+
if(index?.schemaVersion!==1||index.kind!=='cloudflare-worker'||index.entry!=='worker.mjs'||!Array.isArray(index.files)||index.files.length<3||index.files.length>maximumFiles)throw fail();
|
|
25
|
+
const names=new Set();for(const record of index.files){if(!filename(record.path)||names.has(record.path)||!Number.isSafeInteger(record.byteLength)||record.byteLength<0||record.byteLength>maximumFileBytes||!/^[a-f0-9]{64}$/.test(record.sha256??''))throw fail();names.add(record.path);const bytes=regular(root,output+'/'+record.path,maximumFileBytes);if(bytes.byteLength!==record.byteLength||sha(bytes)!==record.sha256||(total+=bytes.byteLength)>maximumTotalBytes)throw fail();files.push({path:'server/'+record.path,role:'control',bytes});}
|
|
26
|
+
const control=files.find(file=>file.path==='server/cloudflare-worker.json');if(!control)throw fail();
|
|
27
|
+
const plan=parseCloudflareWorkerPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(control.bytes)),{descriptor:{runtime:{entry:'server/'+index.entry,links:[]}},files:files.map(file=>({path:file.path,role:file.role}))});
|
|
28
|
+
return {index,plan,files,payloadBytes:total};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One source-owned build, sealed raw resources and static/AOT catalog. The
|
|
32
|
+
* real business-library tarball is already complete before this begins. */
|
|
33
|
+
export async function prepareOwnerCloudflareWorkerBuild(options){
|
|
34
|
+
const {root:inputRoot,bindingEntry,registration,uiExportNames,resourceEntry,domain,wranglerEntry,signal,compatibilityDate='2026-11-04',compatibilityFlags=['nodejs_compat']}=options??{};
|
|
35
|
+
if(!registration?.descriptor||!Array.isArray(uiExportNames)||uiExportNames.some(value=>typeof value!=='string')||!(resourceEntry instanceof URL)||resourceEntry.protocol!=='file:')throw fail();
|
|
36
|
+
if(typeof inputRoot!=='string'||!path.isAbsolute(inputRoot)||typeof bindingEntry!=='string'||!path.isAbsolute(bindingEntry)||typeof wranglerEntry!=='string'||!path.isAbsolute(wranglerEntry)||!domain||!/^[a-z][a-z0-9_]{0,62}$/.test(domain.schema??'')||!Array.isArray(domain.relations)||!domain.relations.length||domain.relations.length>128||domain.relations.some(value=>!value||!/^[a-z][a-z0-9_]{0,62}$/.test(value.name??'')||!Array.isArray(value.privileges)||!value.privileges.length||value.privileges.some(name=>!['SELECT','INSERT','UPDATE','DELETE'].includes(name))))throw fail();
|
|
37
|
+
signal?.throwIfAborted();const root=fs.realpathSync(inputRoot),relativeBinding=path.relative(root,bindingEntry).split(path.sep).join('/');regular(root,relativeBinding);
|
|
38
|
+
const metadata=json(root,'package.json',65536),build=json(root,'deployment/generated/package-build.json',65536),archive=regular(root,'deployment/generated/package.tgz',67108864);
|
|
39
|
+
if(build.schemaVersion!==2||build.name!==metadata.name||build.version!==metadata.version||build.integrity!=='sha512-'+createHash('sha512').update(archive).digest('base64'))throw fail();
|
|
40
|
+
regular(root,path.relative(root,fileURLToPath(resourceEntry)).split(path.sep).join('/'));
|
|
41
|
+
if(registration.descriptor.version!==metadata.version)throw fail();
|
|
42
|
+
const [{prepareWorkerCatalog},{metadataDigest},{readPackageResource}]=await Promise.all([import('@xlinklight/platform/build'),import('@xlinklight/platform/worker'),import('@xlinklight/solution-sdk/server')]);
|
|
43
|
+
const resources=registration.resources.map(definition=>({definition,bytes:readPackageResource(resourceEntry,definition,1048576)})),profile=json(root,'deployment/runtime-profile.json'),publisher=json(root,'deployment/publisher.json'),target=json(root,'deployment/target.json'),uiReceipt=regular(root,'deployment/generated/ui.json',1048576);
|
|
44
|
+
const installation={...profile.installation,packages:[{solutionId:registration.descriptor.solutionId,version:metadata.version,packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,uiExportNames,resourceReader:(definition,maximum)=>readPackageResource(resourceEntry,definition,maximum)}]};
|
|
45
|
+
const catalog=prepareWorkerCatalog({registration,installation}),resourcesDigest=metadataDigest(registration.resources),uiDigest='sha256:'+sha(uiReceipt),identity={packageName:metadata.name,packageVersion:metadata.version,integrity:build.integrity,resourcesDigest,uiDigest};
|
|
46
|
+
const scope=createVerificationRun({root,scope:path.join(root,'tmp/worker-build'),label:'worker-build',maximumBytes:67108864,inputDigest:sha(canonical({identity,domain,catalog:catalog.catalogIdentity,compatibilityDate,compatibilityFlags}))}),slot=scope.directory;
|
|
47
|
+
let closed=true,failure,result={status:'FAIL'};
|
|
48
|
+
try{
|
|
49
|
+
const definitions=resources.map(value=>value.definition),imports=[],entries=[];
|
|
50
|
+
for(const [index,item]of resources.entries()){
|
|
51
|
+
const relative='resources/'+item.definition.path;if(!filename(relative))throw fail();const selected=path.join(slot,relative);fs.mkdirSync(path.dirname(selected),{recursive:true});fs.writeFileSync(selected,item.bytes);imports.push('import resource'+index+' from '+JSON.stringify('./'+relative)+';');entries.push('{path:'+JSON.stringify(item.definition.path)+',bytes:new Uint8Array(resource'+index+')}');
|
|
52
|
+
}
|
|
53
|
+
fs.writeFileSync(path.join(slot,'resources.mjs'),imports.join('\n')+'\nimport {createSealedPackageResourceReader,PackageResourceError} from "@xlinklight/solution-sdk/resources-runtime";\nexport const solutionPackageVersion='+JSON.stringify(metadata.version)+';\nconst definitions='+JSON.stringify(definitions)+';\nexport const resourceReader=createSealedPackageResourceReader(['+entries.join(',')+'],{maximumFiles:8192,maximumFileBytes:1048576,maximumTotalBytes:33554432});\nexport function readResourceBytes(name){const definition=definitions.find(value=>value.path===name);if(!definition)throw new PackageResourceError("MISSING_DEFINITION");return resourceReader(definition,1048576);}\n');
|
|
54
|
+
fs.writeFileSync(path.join(slot,'catalog.mjs'),catalog.validatorSource);
|
|
55
|
+
fs.writeFileSync(path.join(slot,'validators.mjs'),'import validators from "./catalog.mjs";\nexport const getSchemaValidator=name=>validators.validators['+JSON.stringify(registration.descriptor.solutionId+'.')+'+name];\n');
|
|
56
|
+
const serializedInstallation={...installation,packages:installation.packages.map(value=>({solutionId:value.solutionId,version:value.version,packageName:value.packageName,packageVersion:value.packageVersion,integrity:value.integrity,uiExportNames:value.uiExportNames}))},bindingImport=path.relative(slot,bindingEntry).split(path.sep).join('/');
|
|
57
|
+
const pinnedPublisher={publisherId:publisher.publisherId,enabled:publisher.enabled,keys:publisher.keys};
|
|
58
|
+
const code='import {serverBinding} from '+JSON.stringify(bindingImport.startsWith('.')?bindingImport:'./'+bindingImport)+';\nimport {createPreparedRuntimeCatalog,createCloudflareRuntimeHandler,verifyIndependentNodeRelations} from "@xlinklight/platform/worker";\nimport validators from "./catalog.mjs";import {resourceReader} from "./resources.mjs";import serverReceipt from "./release-server.json";\nconst installation='+JSON.stringify(serializedInstallation)+';installation.packages[0].resourceReader=resourceReader;\nconst catalog=createPreparedRuntimeCatalog({registration:serverBinding.registration(),installation,validators,catalogIdentity:'+JSON.stringify(catalog.catalogIdentity)+'});\nlet selectedKeys,handler;\nexport default {async fetch(request,env,context){try{if(typeof env.CORE_RUNTIME_KEYS!=="string"||env.CORE_RUNTIME_KEYS.length>65536)throw Error("CORE_KEYS_REQUIRED");if(!handler||selectedKeys!==env.CORE_RUNTIME_KEYS){handler=createCloudflareRuntimeHandler({binding:serverBinding,installation,catalog,bundle:{...'+JSON.stringify(identity)+',serverReceipt},core:{origin:'+JSON.stringify(target.coreOrigin)+',publisher:'+JSON.stringify(pinnedPublisher)+',verificationKeys:JSON.parse(env.CORE_RUNTIME_KEYS)},database:value=>({application:{database:value.API_DATABASE,role:value.API_DATABASE_ROLE},worker:{database:value.WORKER_DATABASE,role:value.WORKER_DATABASE_ROLE}}),readiness:db=>verifyIndependentNodeRelations(db,'+JSON.stringify(domain)+')});selectedKeys=env.CORE_RUNTIME_KEYS;}return await handler.fetch(request,env,context);}catch{return new Response(JSON.stringify({code:"SERVICE_UNAVAILABLE"}),{status:503,headers:{"content-type":"application/json","cache-control":"no-store"}});}}};\n';
|
|
59
|
+
fs.writeFileSync(path.join(slot,'worker.mjs'),code);fs.writeFileSync(path.join(slot,'release-server.json'),'LINK_LIGHT_RECEIPT_NOT_FINAL\n');
|
|
60
|
+
closed=false;let bundled;
|
|
61
|
+
try{bundled=await bundleCloudflareWorker({root:slot,entry:path.join(slot,'worker.mjs'),output:'output',wranglerEntry,compatibilityDate,compatibilityFlags,rules:[{type:'Text',globs:['**/release-server.json'],fallthrough:false},{type:'Data',globs:['**/resources/**'],fallthrough:false}],signal,timeoutMs:60000,maxOutputBytes:65536,maximumFiles:8192,maximumFileBytes:16777216,maximumTotalBytes:33554432});closed=bundled.process.closed&&bundled.process.stdoutEof&&bundled.process.stderrEof&&!bundled.process.stopError;}
|
|
62
|
+
catch(error){const receipt=error.process??error.cause?.cause?.process;closed=receipt?.closed===true&&receipt.stdoutEof===true&&receipt.stderrEof===true&&!receipt.stopError;throw error;}
|
|
63
|
+
if(!closed)throw fail();
|
|
64
|
+
const files=bundled.files.filter(file=>file.path!=='README.md'&&!file.path.endsWith('.map')).map(file=>({path:file.path===bundled.entry?'worker.mjs':file.path,bytes:file.bytes}));
|
|
65
|
+
const main=files.find(file=>file.path==='worker.mjs'),receipt=files.find(file=>file.path==='release-server.json');if(!main||!receipt||Buffer.from(main.bytes).includes(Buffer.from('LINK_LIGHT_RECEIPT_NOT_FINAL')))throw fail();
|
|
66
|
+
const types={'.mjs':'esm','.js':'esm','.json':'text','.wasm':'wasm'},modules=files.map(file=>({path:'server/'+file.path,type:file.path.startsWith('resources/')?'data':types[path.posix.extname(file.path)]}));if(modules.some(value=>!value.type))throw fail();
|
|
67
|
+
const plan={schemaVersion:1,mainModule:'server/worker.mjs',compatibilityDate,compatibilityFlags,modules,receiptPath:'server/release-server.json'};
|
|
68
|
+
files.push({path:'cloudflare-worker.json',bytes:Buffer.from(canonical(plan))});
|
|
69
|
+
const receiptFiles=files.filter(file=>file!==receipt).map(file=>({path:'server/'+file.path,bytes:file.bytes.byteLength,sha256:'sha256:'+sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1);
|
|
70
|
+
receipt.bytes=Buffer.from(canonical({schemaVersion:1,kind:'server',payloadBytes:receiptFiles.reduce((sum,file)=>sum+file.bytes,0),files:receiptFiles}));
|
|
71
|
+
const index={schemaVersion:1,kind:'cloudflare-worker',entry:'worker.mjs',...identity,catalogIdentity:catalog.catalogIdentity,graph:bundled.metadata,files:files.map(file=>({path:file.path,byteLength:file.bytes.byteLength,sha256:sha(file.bytes)})).sort((a,b)=>a.path<b.path?-1:1)};
|
|
72
|
+
if(Buffer.byteLength(canonical(index))>8388608)throw fail();
|
|
73
|
+
parseCloudflareWorkerPackage(plan,{descriptor:{runtime:{entry:plan.mainModule,links:[]}},files:files.map(file=>({path:'server/'+file.path,role:'control'}))});
|
|
74
|
+
const output=path.join(root,'dist-worker');if(fs.existsSync(output)){const old=readOwnerCloudflareWorkerBuild({root}),expected=[...old.index.files.map(file=>file.path),'worker-build.json'].sort(),names=[];
|
|
75
|
+
for(const value of fs.readdirSync(output,{recursive:true})){const selected=path.join(output,value),portable=value.split(path.sep).join('/'),info=fs.lstatSync(selected);if(info.isSymbolicLink()||fs.realpathSync(selected)!==selected)throw fail();if(info.isFile())names.push(portable);else if(!info.isDirectory()||!expected.some(name=>name.startsWith(portable+'/')))throw fail();}
|
|
76
|
+
if(names.sort().join('\n')!==expected.join('\n'))throw fail();for(const file of old.index.files)fs.unlinkSync(path.join(output,file.path));fs.unlinkSync(path.join(output,'worker-build.json'));}
|
|
77
|
+
else fs.mkdirSync(output);
|
|
78
|
+
for(const file of files){const selected=path.join(output,file.path);fs.mkdirSync(path.dirname(selected),{recursive:true});if(fs.realpathSync(path.dirname(selected))!==path.dirname(selected))throw fail();fs.writeFileSync(selected,file.bytes,{flag:'wx'});}fs.writeFileSync(path.join(output,'worker-build.json'),canonical(index),{flag:'wx'});
|
|
79
|
+
scope.checkBudget();result={status:'PASS',entry:index.entry,files:files.length,bytes:files.reduce((sum,file)=>sum+file.bytes.byteLength,0),serverDigest:'sha256:'+sha(receipt.bytes),...identity};
|
|
80
|
+
}catch(error){failure=error;result={status:'FAIL',code:error.message,process:error.process??error.cause?.cause?.process};}
|
|
81
|
+
finally{try{scope.finish({result,closed});}catch(error){if(failure)failure.cleanupError=error;else failure=error;}}
|
|
82
|
+
if(failure){failure.closure={processesClosed:closed,slotRemoved:!fs.existsSync(slot)};throw failure;}return result;
|
|
83
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function preparePrebuiltBuild(options:{root:string;publicEnvironment?:{LINK_LIGHT_UI_HOST_ORIGIN:string;LINK_LIGHT_UI_ORIGIN:string}}):{
|
|
2
|
+
status:'PREBUILT_BUILD_PREPARED';teamId:string;projectId:string;
|
|
3
|
+
producer:{name:'vercel';version:'64.7.0';arguments:string[]};
|
|
4
|
+
};
|
|
5
|
+
export function assertPrebuiltReleaseMarker(marker:unknown,expected:{sha:string;artifactSha256:string;configSha256?:string}):void;
|
|
6
|
+
export interface VerifiedPrebuiltCandidate {readonly teamId:string;readonly projectId:string;readonly sourceSha:string;readonly configSha256:string;readonly artifactSha256:string;readonly deploymentId:string;readonly candidateUrl:string;readonly versionUrl:string;readonly versionAliasVerified:true}
|
|
7
|
+
export function parsePrebuiltCandidateContext(value:string,expected:{teamId:string;projectId:string;sha:string;configSha256:string;artifactSha256:string;deploymentId:string;versionUrl:string}):VerifiedPrebuiltCandidate;
|
|
8
|
+
export function observePrebuiltMarkers(options:{origins:readonly string[];sha:string;artifactSha256:string;configSha256?:string;signal?:AbortSignal;request?:typeof fetch}):Promise<{status:'MARKERS_MATCH';sha:string;artifactSha256:string;configSha256:string}>;
|