@xlinklight/publishing 0.0.0-stage → 3.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 -0
- package/README.md +35 -2
- package/package.json +62 -3
- package/src/acceptance.d.mts +22 -0
- package/src/acceptance.mjs +66 -0
- package/src/client.d.mts +15 -0
- package/src/client.mjs +66 -0
- package/src/index.d.mts +6 -0
- package/src/index.mjs +3 -0
- package/src/node/activation.d.mts +8 -0
- package/src/node/activation.mjs +3 -0
- package/src/node/authorization.d.mts +8 -0
- package/src/node/authorization.mjs +39 -0
- package/src/node/cli.d.mts +20 -0
- package/src/node/cli.mjs +106 -0
- package/src/node/index.d.mts +16 -0
- package/src/node/index.mjs +8 -0
- package/src/node/journal.d.mts +13 -0
- package/src/node/journal.mjs +135 -0
- package/src/node/session.d.mts +23 -0
- package/src/node/session.mjs +101 -0
- package/src/node/solution-package.d.mts +15 -0
- package/src/node/solution-package.mjs +113 -0
- package/src/node/source-error.d.mts +5 -0
- package/src/node/source-error.mjs +9 -0
- package/src/node/workflow.d.mts +35 -0
- package/src/node/workflow.mjs +178 -0
- package/src/package.d.mts +11 -0
- package/src/package.mjs +36 -0
- package/src/protocol.d.mts +27 -0
- package/src/protocol.mjs +50 -0
- package/src/shared/activation.d.mts +5 -0
- package/src/shared/activation.mjs +64 -0
- package/src/worker/activation.d.mts +7 -0
- package/src/worker/activation.mjs +4 -0
- package/src/worker/index.d.mts +6 -0
- package/src/worker/index.mjs +6 -0
- package/src/worker/journal.d.mts +21 -0
- package/src/worker/journal.mjs +151 -0
- package/src/worker/package.d.mts +16 -0
- package/src/worker/package.mjs +32 -0
- package/src/worker/release.d.mts +7 -0
- package/src/worker/release.mjs +21 -0
- package/src/worker/runtime.d.mts +4 -0
- package/src/worker/runtime.mjs +23 -0
- package/src/worker/service.d.mts +41 -0
- package/src/worker/service.mjs +247 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
+
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
3
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
4
|
+
const fail=code=>Error('PUBLISHING_DURABLE_'+code),hash=bytes=>createHash('sha256').update(bytes).digest('hex'),json=value=>JSON.stringify(value);
|
|
5
|
+
const keyValid=key=>typeof key==='string'&&/^[A-Za-z0-9][A-Za-z0-9:._/-]{0,511}$/.test(key),positive=(value,max)=>Number.isSafeInteger(value)&&value>0&&value<=max;
|
|
6
|
+
const usageTables=[
|
|
7
|
+
['publishing_records','records'],['publishing_blobs','blobs'],['publishing_queue'],['publishing_leases'],
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
function initializeUsage(sql,one){
|
|
11
|
+
sql.exec('CREATE TABLE IF NOT EXISTS publishing_usage(id INTEGER PRIMARY KEY CHECK(id=1),bytes INTEGER NOT NULL CHECK(bytes>=0),records INTEGER NOT NULL CHECK(records>=0),blobs INTEGER NOT NULL CHECK(blobs>=0))');
|
|
12
|
+
if(!one('SELECT id FROM publishing_usage WHERE id=1')){
|
|
13
|
+
const records=one('SELECT count(*) n,coalesce(sum(size),0) bytes FROM publishing_records');
|
|
14
|
+
const blobs=one('SELECT count(*) n,coalesce(sum(size),0) bytes FROM publishing_blobs');
|
|
15
|
+
const queue=one('SELECT count(*) n FROM publishing_queue');
|
|
16
|
+
const leases=one('SELECT count(*) n FROM publishing_leases');
|
|
17
|
+
sql.exec('INSERT INTO publishing_usage VALUES(1,?,?,?)',records.bytes+blobs.bytes+(queue.n+leases.n)*1024,records.n,blobs.n);
|
|
18
|
+
}
|
|
19
|
+
// Update accounting in the transaction that changes the protected rows.
|
|
20
|
+
for(const [table,count] of usageTables){
|
|
21
|
+
const bytes=count?['NEW.size','OLD.size']:['1024','1024'];
|
|
22
|
+
for(const [event,sign,amount] of [['INSERT','+',bytes[0]],['DELETE','-',bytes[1]]]){
|
|
23
|
+
const adjustCount=count?`,${count}=${count}${sign}1`:'';
|
|
24
|
+
sql.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_usage_${event.toLowerCase()} AFTER ${event} ON ${table} BEGIN UPDATE publishing_usage SET bytes=bytes${sign}${amount}${adjustCount} WHERE id=1; END`);
|
|
25
|
+
}
|
|
26
|
+
if(count)sql.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_usage_update AFTER UPDATE OF size ON ${table} WHEN OLD.size<>NEW.size BEGIN UPDATE publishing_usage SET bytes=bytes+NEW.size-OLD.size WHERE id=1; END`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The platform owns storage. This adapter owns opaque immutable chunks, real SQL CAS and fenced turns. */
|
|
31
|
+
export async function openPublishingDurableJournal({storage,identity,limits:inputLimits,now=Date.now,leaseMs=60000,increaseMaximumRecordsTo}){
|
|
32
|
+
const limits={...inputLimits};if(!storage?.sql||typeof storage.transactionSync!=='function'||typeof storage.sync!=='function'||typeof identity!=='string'||identity.length<1||identity.length>128||typeof now!=='function'||!positive(leaseMs,300000)||!positive(limits.maximumBytes,1073741824)||!positive(limits.maximumRecords,4096)||!positive(limits.maximumRecordBytes,1048576)||!positive(limits.maximumBlobs,32768)||!positive(limits.maximumBlobBytes,1048576)||!positive(limits.recoveryReserveBytes,limits.maximumBytes))throw fail('INPUT_INVALID');
|
|
33
|
+
if(increaseMaximumRecordsTo!==undefined&&(!positive(increaseMaximumRecordsTo,4096)||increaseMaximumRecordsTo<=limits.maximumRecords))throw fail('INPUT_INVALID');
|
|
34
|
+
const sql=storage.sql,rows=(query,...values)=>sql.exec(query,...values).toArray(),one=(query,...values)=>rows(query,...values)[0],context=new AsyncLocalStorage();let closed=false,running=false,blocked=false;
|
|
35
|
+
const ready=()=>{if(closed)throw fail('CLOSED');},check=signal=>{ready();signal?.throwIfAborted();};
|
|
36
|
+
const read=key=>{const row=one('SELECT revision,payload,checksum FROM publishing_records WHERE key=?',key);if(!row)return; if(hash(row.payload)!==row.checksum)throw fail('CORRUPT');return {revision:row.revision,payload:JSON.parse(row.payload)};};
|
|
37
|
+
const usage=()=>{const row=one('SELECT bytes,records,blobs FROM publishing_usage WHERE id=1');if(!row)throw fail('CORRUPT');return row;};
|
|
38
|
+
const capacity=recovery=>{if(usage().bytes>limits.maximumBytes-(recovery?0:limits.recoveryReserveBytes)||sql.databaseSize>limits.maximumBytes)throw fail('CAPACITY');};
|
|
39
|
+
const transaction=(work,recovery=false)=>storage.transactionSync(()=>{ready();const value=work();capacity(recovery);return value;});
|
|
40
|
+
storage.transactionSync(()=>{
|
|
41
|
+
for(const statement of [
|
|
42
|
+
'CREATE TABLE IF NOT EXISTS publishing_metadata(id INTEGER PRIMARY KEY CHECK(id=1),configuration TEXT NOT NULL)',
|
|
43
|
+
'CREATE TABLE IF NOT EXISTS publishing_records(key TEXT PRIMARY KEY,revision INTEGER NOT NULL,payload TEXT NOT NULL,checksum TEXT NOT NULL,size INTEGER NOT NULL)',
|
|
44
|
+
'CREATE TABLE IF NOT EXISTS publishing_blobs(sha256 TEXT PRIMARY KEY,length INTEGER NOT NULL,bytes BLOB NOT NULL,size INTEGER NOT NULL)',
|
|
45
|
+
'CREATE TABLE IF NOT EXISTS publishing_queue(project TEXT PRIMARY KEY,request TEXT NOT NULL,mode TEXT NOT NULL,advance INTEGER NOT NULL,revision INTEGER NOT NULL,next_at INTEGER NOT NULL,lease_until INTEGER,observations INTEGER NOT NULL,receipt_wake INTEGER NOT NULL DEFAULT 0)',
|
|
46
|
+
'CREATE TABLE IF NOT EXISTS publishing_leases(project TEXT PRIMARY KEY,request TEXT NOT NULL,intent TEXT NOT NULL,revision INTEGER NOT NULL,owner TEXT NOT NULL,until_ms INTEGER NOT NULL)'])sql.exec(statement);
|
|
47
|
+
const configuration=json({schemaVersion:1,identity,limits});
|
|
48
|
+
const expanded=increaseMaximumRecordsTo===undefined?undefined:json({schemaVersion:1,identity,limits:{...limits,maximumRecords:increaseMaximumRecordsTo}});
|
|
49
|
+
const previous=one('SELECT configuration FROM publishing_metadata WHERE id=1');
|
|
50
|
+
if(previous&&previous.configuration!==configuration&&previous.configuration!==expanded)throw fail('IDENTITY_CHANGED');
|
|
51
|
+
if(!previous)sql.exec('INSERT INTO publishing_metadata VALUES(1,?)',configuration);
|
|
52
|
+
if(!rows('PRAGMA table_info(publishing_queue)').some(column=>column.name==='receipt_wake')){
|
|
53
|
+
sql.exec('ALTER TABLE publishing_queue ADD COLUMN receipt_wake INTEGER NOT NULL DEFAULT 0');
|
|
54
|
+
}
|
|
55
|
+
initializeUsage(sql,one);
|
|
56
|
+
if(expanded&&previous?.configuration===expanded)limits.maximumRecords=increaseMaximumRecordsTo;
|
|
57
|
+
else if(expanded&&previous&&usage().records===limits.maximumRecords){
|
|
58
|
+
const busy=one('SELECT 1 FROM publishing_leases WHERE until_ms>? LIMIT 1',now())||
|
|
59
|
+
one('SELECT 1 FROM publishing_queue WHERE lease_until>? LIMIT 1',now());
|
|
60
|
+
if(!busy){
|
|
61
|
+
capacity(true);
|
|
62
|
+
sql.exec('UPDATE publishing_metadata SET configuration=? WHERE id=1',expanded);
|
|
63
|
+
limits.maximumRecords=increaseMaximumRecordsTo;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});capacity(true);await storage.sync();
|
|
67
|
+
const authorize=(authority,key,next)=>{
|
|
68
|
+
if(!authority){if(key.startsWith('project:')||key.startsWith('operation:'))throw fail('AUTHORITY_REQUIRED');return;}
|
|
69
|
+
const project=read('project:'+authority.projectId)?.payload;if(authority.kind==='configure'){if(key!=='project:'+authority.projectId)throw fail('AUTHORITY_REQUIRED');return;}
|
|
70
|
+
if(!project||project.policy.disabled||project.policy.policyRevision!==authority.policyRevision)throw fail('POLICY_CHANGED');
|
|
71
|
+
if(authority.kind==='request'&&project.credentialSha256!==authority.credentialSha256)throw fail('POLICY_CHANGED');
|
|
72
|
+
if(authority.kind==='worker'){
|
|
73
|
+
const lease=one('SELECT * FROM publishing_leases WHERE project=?',authority.projectId),request=project.requests.find(item=>item.intent.requestId===authority.requestId);
|
|
74
|
+
if(!lease||lease.revision!==authority.revision||lease.owner!==authority.owner||lease.request!==authority.requestId||lease.until_ms<=now()||!request||request.intentSha256!==lease.intent||request.intent.policyRevision!==authority.policyRevision)throw fail('LEASE_LOST');
|
|
75
|
+
if(key.startsWith('operation:')&&(next?.binding?.requestId?.startsWith(authority.requestId+'.')!==true||next.binding.content.manifestSha256!==request.intent.package.content.manifestSha256))throw fail('AUTHORITY_REQUIRED');
|
|
76
|
+
}
|
|
77
|
+
if(key.startsWith('project:')&&(key!=='project:'+authority.projectId||!isDeepStrictEqual(project.policy,next?.policy)||project.credentialSha256!==next?.credentialSha256))throw fail('POLICY_CHANGED');
|
|
78
|
+
};
|
|
79
|
+
const enqueueInside=(job,authority)=>{
|
|
80
|
+
if(!job||!keyValid(job.projectId)||!keyValid(job.requestId)||!['perform','observe'].includes(job.mode)||typeof job.continue!=='boolean')throw fail('INPUT_INVALID');authorize(authority,'project:'+job.projectId,read('project:'+job.projectId)?.payload);
|
|
81
|
+
const project=read('project:'+job.projectId)?.payload,item=project?.requests.find(item=>item.intent.requestId===job.requestId);if(!item||item.intent.policyRevision!==project.policy.policyRevision||!queuedState(item.state,job.mode))throw fail('REQUEST_CHANGED');
|
|
82
|
+
const receipt=job.acceptanceReceipt===true;
|
|
83
|
+
if(receipt&&(job.mode!=='observe'||!job.continue||authority?.kind!=='request'))throw fail('AUTHORITY_REQUIRED');
|
|
84
|
+
const previous=one('SELECT * FROM publishing_queue WHERE project=?',job.projectId);
|
|
85
|
+
if(previous?.lease_until>now()){
|
|
86
|
+
if(!receipt||previous.request!==job.requestId)throw fail('BUSY');
|
|
87
|
+
// Keep the active lease intact. Its finish must preserve this wake.
|
|
88
|
+
sql.exec('UPDATE publishing_queue SET receipt_wake=1 WHERE project=?',job.projectId);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const accepted=receipt||job.continue&&previous?.request===job.requestId&&previous.receipt_wake>0;
|
|
92
|
+
sql.exec('INSERT INTO publishing_queue(project,request,mode,advance,revision,next_at,lease_until,observations,receipt_wake) VALUES(?,?,?,?,?,?,NULL,0,?) ON CONFLICT(project) DO UPDATE SET request=excluded.request,mode=excluded.mode,advance=excluded.advance,revision=excluded.revision,next_at=excluded.next_at,lease_until=NULL,observations=0,receipt_wake=excluded.receipt_wake',job.projectId,job.requestId,job.mode,job.continue?1:0,(previous?.revision??0)+1,now(),accepted?2:0);
|
|
93
|
+
};
|
|
94
|
+
const queuedState=(state,mode)=>['queued','deploying'].includes(state)||mode==='observe'&&['unknown','awaiting-acceptance'].includes(state);
|
|
95
|
+
const admissible=row=>{const project=read('project:'+row.project)?.payload,item=project?.requests.find(item=>item.intent.requestId===row.request);return !!item&&!project.policy.disabled&&project.policy.policyRevision===item.intent.policyRevision&&queuedState(item.state,row.mode);};
|
|
96
|
+
const api={
|
|
97
|
+
recordCapacity(){ready();return {used:usage().records,maximum:limits.maximumRecords};},
|
|
98
|
+
async load(key,{signal}={}){check(signal);if(!keyValid(key))throw fail('KEY_INVALID');return read(key);},
|
|
99
|
+
async readBlob({sha256,byteLength},{signal}={}){check(signal);if(!/^[a-f0-9]{64}$/.test(sha256)||!Number.isSafeInteger(byteLength)||byteLength<0||byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');const row=one('SELECT length,bytes FROM publishing_blobs WHERE sha256=?',sha256);if(!row)return;const bytes=new Uint8Array(row.bytes);if(row.length!==byteLength||bytes.length!==byteLength||hash(bytes)!==sha256)throw fail('BLOB_CHANGED');return bytes;},
|
|
100
|
+
async compareAndSet({key,expectedRevision,payload,blobs=[]},{signal,authority=context.getStore(),dispatch}={}){
|
|
101
|
+
check(signal);if(!keyValid(key)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||expectedRevision>=Number.MAX_SAFE_INTEGER||!Array.isArray(blobs)||blobs.length>limits.maximumBlobs)throw fail('RECORD_INVALID');const text=json(payload);if(typeof text!=='string'||Buffer.byteLength(text)+Buffer.byteLength(key)>limits.maximumRecordBytes)throw fail('RECORD_LIMIT');
|
|
102
|
+
const snapshot=JSON.parse(text),parts=blobs.map(({sha256,bytes})=>{if(!/^[a-f0-9]{64}$/.test(sha256)||!(bytes instanceof Uint8Array)||bytes.length>limits.maximumBlobBytes)throw fail('BLOB_INVALID');const owned=new Uint8Array(bytes);if(hash(owned)!==sha256)throw fail('BLOB_INVALID');return {sha256,bytes:owned};});
|
|
103
|
+
const result=transaction(()=>{check(signal);const previous=read(key);if((previous?.revision??0)!==expectedRevision)return 'conflict';authorize(authority,key,snapshot);
|
|
104
|
+
for(const part of parts){const existing=one('SELECT length,bytes FROM publishing_blobs WHERE sha256=?',part.sha256);if(existing){const bytes=new Uint8Array(existing.bytes);if(existing.length!==part.bytes.length||!Buffer.from(bytes).equals(part.bytes))throw fail('BLOB_CHANGED');}else sql.exec('INSERT INTO publishing_blobs VALUES(?,?,?,?)',part.sha256,part.bytes.length,part.bytes.buffer,part.bytes.length+128);}
|
|
105
|
+
const counts=usage();if(counts.blobs>limits.maximumBlobs)throw fail('BLOB_LIMIT');if(!previous&&counts.records>=limits.maximumRecords)throw fail('RECORD_LIMIT');
|
|
106
|
+
sql.exec('INSERT INTO publishing_records VALUES(?,?,?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload,checksum=excluded.checksum,size=excluded.size',key,expectedRevision+1,text,hash(text),Buffer.byteLength(text)+Buffer.byteLength(key)+128);if(dispatch)enqueueInside(dispatch,authority);return 'stored';
|
|
107
|
+
},authority?.mode==='observe');if(result==='stored')await storage.sync();check(signal);return result;
|
|
108
|
+
},
|
|
109
|
+
operationJournal(){return {load:async(id,options)=>{const result=await api.load('operation:'+id,options);if(result&&result.payload.revision!==result.revision)throw fail('CORRUPT');return result?.payload;},compareAndSet:async({expectedRevision,next},options)=>{if(next?.revision!==expectedRevision+1)throw fail('RECORD_INVALID');return api.compareAndSet({key:'operation:'+next.binding.requestId,expectedRevision,payload:next},options);}};},
|
|
110
|
+
async enqueue(job,{signal,authority=context.getStore()}={}){check(signal);transaction(()=>enqueueInside(job,authority),job.mode==='observe');await storage.sync();check(signal);},
|
|
111
|
+
nextWake(){ready();return one('SELECT min(max(next_at,coalesce(lease_until,0))) AS at FROM publishing_queue')?.at??null;},
|
|
112
|
+
async take(){
|
|
113
|
+
ready();if(blocked||running)throw fail('BUSY');let changed=false;
|
|
114
|
+
const result=transaction(()=>{
|
|
115
|
+
const row=one('SELECT * FROM publishing_queue WHERE next_at<=? AND (lease_until IS NULL OR lease_until<=?) ORDER BY next_at,project LIMIT 1',now(),now());
|
|
116
|
+
if(!row)return null;
|
|
117
|
+
changed=true;
|
|
118
|
+
const recovering=row.lease_until!==null,mode=recovering?'observe':row.mode;
|
|
119
|
+
const advance=recovering?row.receipt_wake>0:!!row.advance;
|
|
120
|
+
if(!admissible({...row,mode})){sql.exec('DELETE FROM publishing_queue WHERE project=?',row.project);return null;}
|
|
121
|
+
sql.exec('UPDATE publishing_queue SET revision=revision+1,mode=?,advance=?,lease_until=?,receipt_wake=? WHERE project=?',mode,advance?1:0,now()+leaseMs,row.receipt_wake>0?2:0,row.project);
|
|
122
|
+
return {projectId:row.project,requestId:row.request,revision:row.revision+1,mode,continue:advance,observations:row.observations};
|
|
123
|
+
},true);
|
|
124
|
+
if(changed)await storage.sync();
|
|
125
|
+
return result;
|
|
126
|
+
},
|
|
127
|
+
async finish(job,{again=false,delayMs=1000,mode='observe',advance=job.continue,observations=0}={}){
|
|
128
|
+
if(!Number.isSafeInteger(delayMs)||delayMs<1||delayMs>3600000||!Number.isSafeInteger(observations)||observations<0||observations>128||!['perform','observe'].includes(mode))throw fail('INPUT_INVALID');
|
|
129
|
+
transaction(()=>{
|
|
130
|
+
const row=one('SELECT * FROM publishing_queue WHERE project=?',job.projectId);
|
|
131
|
+
if(!row||row.revision!==job.revision||row.request!==job.requestId)throw fail('LEASE_LOST');
|
|
132
|
+
const receiptArrived=row.receipt_wake===1;
|
|
133
|
+
const nextMode=again?mode:'observe',nextAdvance=advance||receiptArrived;
|
|
134
|
+
if((again||receiptArrived)&&admissible({...row,mode:nextMode})){
|
|
135
|
+
sql.exec('UPDATE publishing_queue SET revision=revision+1,mode=?,advance=?,lease_until=NULL,next_at=?,observations=?,receipt_wake=? WHERE project=?',nextMode,nextAdvance?1:0,now()+delayMs,observations,row.receipt_wake>0?2:0,job.projectId);
|
|
136
|
+
}else sql.exec('DELETE FROM publishing_queue WHERE project=?',job.projectId);
|
|
137
|
+
},true);
|
|
138
|
+
await storage.sync();
|
|
139
|
+
},
|
|
140
|
+
async withIngress(work){ready();if(blocked||running)throw fail('BUSY');running=true;try{return await work();}finally{running=false;}},
|
|
141
|
+
async withProjectLock({projectId,requestId,mode='perform',signal},work){check(signal);if(blocked||running)throw fail('BUSY');running=true;let authority,started=false,confirmed=false,value,failure,failed=false,timer;const controller=new AbortController(),currentSignal=AbortSignal.any([signal,controller.signal].filter(Boolean));
|
|
142
|
+
try{
|
|
143
|
+
authority=transaction(()=>{const project=read('project:'+projectId)?.payload,item=project?.requests.find(item=>item.intent.requestId===requestId),previous=one('SELECT * FROM publishing_leases WHERE project=?',projectId);if(!item||project.policy.disabled||project.policy.policyRevision!==item.intent.policyRevision)throw fail('POLICY_CHANGED');if(previous?.until_ms>now())throw fail('BUSY');const value={kind:'worker',projectId,requestId,policyRevision:project.policy.policyRevision,revision:(previous?.revision??0)+1,owner:randomUUID(),mode};sql.exec('INSERT INTO publishing_leases VALUES(?,?,?,?,?,?) ON CONFLICT(project) DO UPDATE SET request=excluded.request,intent=excluded.intent,revision=excluded.revision,owner=excluded.owner,until_ms=excluded.until_ms',projectId,requestId,item.intentSha256,value.revision,value.owner,now()+leaseMs);return value;},mode==='observe');await storage.sync();check(signal);
|
|
144
|
+
timer=setTimeout(()=>controller.abort(fail('LEASE_LOST')),leaseMs);
|
|
145
|
+
value=await context.run(authority,()=>work({signal:currentSignal,async assertHeld(){check(currentSignal);transaction(()=>authorize(authority,'project:'+projectId,read('project:'+projectId)?.payload),true);},beginOperation(){started=true;confirmed=false;},confirmClosure(closure){confirmed=closure?.status==='closed'&&closure.activeRequests===0;}}));
|
|
146
|
+
}catch(error){failed=true;failure=error;}finally{clearTimeout(timer);try{if(started&&!confirmed){blocked=true;}else if(authority){transaction(()=>{const lease=one('SELECT revision,owner FROM publishing_leases WHERE project=?',projectId);if(lease?.revision===authority.revision&&lease.owner===authority.owner)sql.exec('UPDATE publishing_leases SET until_ms=0 WHERE project=?',projectId);},true);await storage.sync();}}catch(error){blocked=true;failure=failed?new AggregateError([failure,error],'PUBLISHING_DURABLE_CLOSE_FAILED',{cause:failure}):error;failed=true;}finally{running=false;}}
|
|
147
|
+
if(failed)throw failure;return value;
|
|
148
|
+
},
|
|
149
|
+
get blocked(){return blocked;},get running(){return running;},close(){if(running)throw fail('BUSY');closed=true;}
|
|
150
|
+
};return Object.freeze(api);
|
|
151
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type {ArtifactContentIdentity,ArtifactContentManifest,ArtifactContentManifestFile} from '@openge/forge-artifact-publish';
|
|
2
|
+
import type {SolutionPackageDescriptor,SolutionPackageLimits} from '../package.mjs';
|
|
3
|
+
import type {PublishingIntent} from '../protocol.mjs';
|
|
4
|
+
export interface PublishingContentReader {
|
|
5
|
+
readFile(path:string,input:{maximumBytes:number;signal?:AbortSignal}):Promise<Uint8Array>;
|
|
6
|
+
streamFile(path:string,input?:{signal?:AbortSignal}):AsyncIterable<Uint8Array>;
|
|
7
|
+
}
|
|
8
|
+
export interface PreparedPublishingPackage extends PublishingContentReader {
|
|
9
|
+
readonly descriptor:SolutionPackageDescriptor;readonly content:ArtifactContentIdentity;
|
|
10
|
+
readonly manifest:ArtifactContentManifest;readonly manifestBytes:Uint8Array;
|
|
11
|
+
readonly files:readonly ArtifactContentManifestFile[];readonly payloadBytes:number;
|
|
12
|
+
verifyBatch(input?:{cursor?:number;maximumFiles?:number;maximumBytes?:number;signal?:AbortSignal}):Promise<{cursor:number;complete:boolean;verifiedBytes:number}>;
|
|
13
|
+
}
|
|
14
|
+
export const publishingChunkBytes:1048576,publishingReadFileBytes:16777216;
|
|
15
|
+
export interface PublishingPackageRecord {intent:PublishingIntent;manifestByteLength:number;files:{sha256:string;byteLength:number;receivedBytes:number;chunks:{sha256:string;byteLength:number}[]}[]}
|
|
16
|
+
export function openPreparedPublishingPackage(input:{journal:{readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>};item:PublishingPackageRecord;limits:SolutionPackageLimits;signal?:AbortSignal}):Promise<PreparedPublishingPackage>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
|
|
3
|
+
import {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from '../package.mjs';
|
|
4
|
+
const fail=code=>Error('PUBLISHING_PACKAGE_'+code),hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
5
|
+
export const publishingChunkBytes=1048576,publishingReadFileBytes=16777216;
|
|
6
|
+
const checked=signal=>signal?.throwIfAborted();
|
|
7
|
+
function closure(descriptor,manifest){
|
|
8
|
+
const names=new Set(manifest.files.map(file=>file.path)),folded=new Set(),links=new Map(descriptor.runtime.links.map(link=>[link.path,link.target]));
|
|
9
|
+
if(links.size!==descriptor.runtime.links.length)throw fail('RUNTIME_LINK_INVALID');
|
|
10
|
+
for(const file of manifest.files){const lower=file.path.toLowerCase();if(folded.has(lower)||file.path.split('/').some(part=>part.startsWith('.env')||['.git','.npmrc','.ssh','release-private'].includes(part)))throw fail('PLAN_INVALID');folded.add(lower);}
|
|
11
|
+
for(const name of folded)for(let at=name.lastIndexOf('/');at>=0;at=name.lastIndexOf('/',at-1))if(folded.has(name.slice(0,at)))throw fail('PLAN_INVALID');
|
|
12
|
+
if(!names.has(descriptor.runtime.entry)||!names.has(descriptor.ui.entry)||manifest.files.find(file=>file.path==='solution.json')?.role!=='control')throw fail('ENTRY_MISSING');
|
|
13
|
+
const normalize=value=>{const parts=[];for(const part of value.split('/')){if(part==='..'){if(parts.length&&parts.at(-1)!=='..')parts.pop();else parts.push('..');}else if(part&&part!=='.')parts.push(part);}return parts.join('/');};
|
|
14
|
+
const resolve=(input,seen=new Set())=>{if(seen.size>=64||seen.has(input))throw fail('RUNTIME_LINK_INVALID');seen.add(input);const link=[...links.keys()].filter(name=>input===name||input.startsWith(name+'/')).sort((a,b)=>b.length-a.length)[0];if(link){const parent=link.includes('/')?link.slice(0,link.lastIndexOf('/')):'';const target=normalize(parent+'/'+links.get(link)+input.slice(link.length));if(!target.startsWith('server/'))throw fail('RUNTIME_LINK_INVALID');return resolve(target,seen);}if(!names.has(input)&&![...names].some(name=>name.startsWith(input+'/')))throw fail('RUNTIME_LINK_INVALID');};
|
|
15
|
+
for(const link of links.keys()){const lower=link.toLowerCase(),overlap=name=>{name=name.toLowerCase();return name===lower||name.startsWith(lower+'/')||lower.startsWith(name+'/');};if([...names].some(overlap)||[...links.keys()].some(name=>name!==link&&overlap(name)))throw fail('RUNTIME_LINK_INVALID');resolve(link);}
|
|
16
|
+
}
|
|
17
|
+
/** A declaration-only snapshot. Only one bounded chunk is loaded by the stream at a time. */
|
|
18
|
+
export async function openPreparedPublishingPackage({journal,item,limits:inputLimits,signal}){
|
|
19
|
+
const limits=parseSolutionPackageLimits(inputLimits);checked(signal);const manifestBytes=await journal.readBlob({sha256:item.intent.package.content.manifestSha256,byteLength:item.manifestByteLength},{signal});
|
|
20
|
+
if(!manifestBytes||manifestBytes.byteLength>limits.maximumManifestBytes)throw fail('MANIFEST_INVALID');
|
|
21
|
+
let prepared;try{prepared=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(manifestBytes)));}catch{throw fail('MANIFEST_INVALID');}
|
|
22
|
+
if(prepared.content.manifestSha256!==item.intent.package.content.manifestSha256||prepared.bytes.length!==manifestBytes.length||prepared.bytes.some((byte,i)=>byte!==manifestBytes[i]))throw fail('MANIFEST_CHANGED');
|
|
23
|
+
const manifest=structuredClone(prepared.manifest);if(manifest.files.length>limits.maximumFiles)throw fail('CLOSURE');let payloadBytes=0;const sources=new Map(),files=manifest.files.map(file=>{payloadBytes+=file.byteLength;if(file.byteLength>limits.maximumFileBytes)throw fail('BYTE_LIMIT');const source=item.files.find(value=>value.sha256===file.sha256);if(!source||source.receivedBytes!==file.byteLength||!Array.isArray(source.chunks)||source.chunks.some(chunk=>!Number.isSafeInteger(chunk.byteLength)||chunk.byteLength<1||chunk.byteLength>publishingChunkBytes)||source.chunks.reduce((sum,chunk)=>sum+chunk.byteLength,0)!==file.byteLength)throw fail('CLOSURE');sources.set(file.path,structuredClone(source));return Object.freeze({...file,...(file.responseHeaders?{responseHeaders:Object.freeze({...file.responseHeaders})}:{})});});
|
|
24
|
+
if(payloadBytes+manifestBytes.byteLength>limits.maximumTotalBytes)throw fail('BYTE_LIMIT');
|
|
25
|
+
const streamFile=async function*(path,{signal:current=signal}={}){const source=sources.get(path),file=files.find(file=>file.path===path);if(!source)throw fail('CLOSURE');const digest=createHash('sha256');let count=0;for(const chunk of source.chunks){checked(current);const bytes=await journal.readBlob(chunk,{signal:current});checked(current);if(!bytes||bytes.byteLength!==chunk.byteLength||hash(bytes)!==chunk.sha256)throw fail('CHANGED');digest.update(bytes);count+=bytes.length;yield new Uint8Array(bytes);}if(count!==file.byteLength||digest.digest('hex')!==file.sha256)throw fail('CHANGED');};
|
|
26
|
+
const readFile=async(path,{maximumBytes,signal:current=signal}={})=>{if(!Number.isSafeInteger(maximumBytes)||maximumBytes<0||maximumBytes>publishingReadFileBytes)throw fail('BYTE_LIMIT');const file=files.find(file=>file.path===path);if(!file||file.byteLength>maximumBytes)throw fail('BYTE_LIMIT');const result=new Uint8Array(file.byteLength);let offset=0;for await(const bytes of streamFile(path,{signal:current})){result.set(bytes,offset);offset+=bytes.length;}return result;};
|
|
27
|
+
let descriptor;try{descriptor=parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await readFile('solution.json',{maximumBytes:1048576,signal}))));}catch{throw fail('DESCRIPTOR_INVALID');}closure(descriptor,manifest);
|
|
28
|
+
if(['solutionId','publisherId','packageName','version'].some(name=>descriptor[name]!==item.intent.package[name]))throw fail('DESCRIPTOR_INVALID');
|
|
29
|
+
return Object.freeze({descriptor,content:Object.freeze({...prepared.content}),manifest:Object.freeze({...manifest,files:Object.freeze(files)}),manifestBytes:new Uint8Array(manifestBytes),files:Object.freeze(files),payloadBytes,streamFile,readFile,
|
|
30
|
+
async verifyBatch({cursor=0,maximumFiles=1,maximumBytes=limits.maximumFileBytes,signal:current=signal}={}){if(!Number.isSafeInteger(cursor)||cursor<0||cursor>files.length||!Number.isSafeInteger(maximumFiles)||maximumFiles<1||maximumFiles>16||!Number.isSafeInteger(maximumBytes)||maximumBytes<1||maximumBytes>268435456)throw fail('BYTE_LIMIT');const begin=cursor;let bytes=0;while(cursor<files.length&&cursor-begin<maximumFiles){const file=files[cursor];if(bytes+file.byteLength>maximumBytes){if(cursor===begin)throw fail('BYTE_LIMIT');break;}for await(const part of streamFile(file.path,{signal:current}))bytes+=part.byteLength;cursor++;}return {cursor,complete:cursor===files.length,verifiedBytes:bytes};}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type {SolutionReleasePayload,TrustedPublisher,Digest} from '@xlinklight/contracts';
|
|
2
|
+
import type {PublishingConfiguration} from '../protocol.mjs';
|
|
3
|
+
import type {SolutionPackageLimits} from '../package.mjs';
|
|
4
|
+
import type {PreparedPublishingPackage} from './package.mjs';
|
|
5
|
+
/** Exact immutable provider URLs, canonical HTTPS without credentials, query
|
|
6
|
+
* or fragment. Routes are preserved; publisher admission uses their origins. */
|
|
7
|
+
export function preparePublishingRelease(input:{prepared:Pick<PreparedPublishingPackage,'descriptor'|'content'|'manifest'|'manifestBytes'|'payloadBytes'|'readFile'|'streamFile'>;configuration:PublishingConfiguration;serverUrl:string;uiUrl:string;serverReceiptPath:string;uiReceiptPath:string;limits:SolutionPackageLimits;signal?:AbortSignal}):Promise<{payload:Readonly<SolutionReleasePayload>;releaseDigest:Digest;publisher:TrustedPublisher}>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {publicPublisherMetadata,validateSolutionReleasePayload,solutionReleaseDigest} from '@xlinklight/platform/worker';
|
|
3
|
+
import {parsePublishingConfiguration,publishingError} from '../protocol.mjs';
|
|
4
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
5
|
+
import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
|
|
6
|
+
import {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from '../package.mjs';
|
|
7
|
+
const fail=code=>publishingError('RELEASE_'+code);
|
|
8
|
+
function address(value){try{if(typeof value!=='string'||value.length>2048||value.includes('?')||value.includes('#'))throw Error();const url=new URL(value);if(url.protocol!=='https:'||url.href!==value||url.username||url.password)throw Error();return url;}catch{throw fail('URL_INVALID');}}
|
|
9
|
+
/** The service has already verified this immutable lazy snapshot in bounded batches. */
|
|
10
|
+
export async function preparePublishingRelease({prepared,configuration:config,serverUrl,uiUrl,serverReceiptPath,uiReceiptPath,limits:inputLimits,signal:inputSignal}){
|
|
11
|
+
const limits=parseSolutionPackageLimits(inputLimits),signal=AbortSignal.any([inputSignal,AbortSignal.timeout(limits.timeoutMs)].filter(Boolean));signal.throwIfAborted();const configuration=parsePublishingConfiguration(config),server=address(serverUrl),ui=address(uiUrl);
|
|
12
|
+
if(server.origin===configuration.coreOrigin||ui.origin===configuration.coreOrigin||typeof prepared?.readFile!=='function'||typeof serverReceiptPath!=='string'||!serverReceiptPath.startsWith('server/')||typeof uiReceiptPath!=='string'||!uiReceiptPath.startsWith('ui/'))throw fail('BINDING_INVALID');
|
|
13
|
+
const {descriptor}=prepared;if(descriptor.publisherId!==configuration.publisher.publisherId)throw fail('BINDING_INVALID');
|
|
14
|
+
try{if(!(prepared.manifestBytes instanceof Uint8Array)||prepared.manifestBytes.byteLength>limits.maximumManifestBytes||prepared.manifest.files.length>limits.maximumFiles||prepared.manifest.files.some(file=>file.byteLength>limits.maximumFileBytes))throw Error();const canonical=await createArtifactContentManifest(prepared.manifest),total=prepared.manifest.files.reduce((sum,file)=>sum+file.byteLength,0);if(!isDeepStrictEqual(canonical.content,prepared.content)||!Buffer.from(canonical.bytes).equals(prepared.manifestBytes)||total!==prepared.payloadBytes||total+canonical.bytes.byteLength>limits.maximumTotalBytes)throw Error();}catch{throw fail('PACKAGE_INVALID');}
|
|
15
|
+
try{const original=parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await prepared.readFile('solution.json',{maximumBytes:1048576,signal}))));if(!isDeepStrictEqual(original,descriptor))throw Error();}catch{throw fail('PACKAGE_INVALID');}
|
|
16
|
+
const receipt=async(path,role)=>{if(prepared.manifest.files.find(file=>file.path===path)?.role!==role)throw fail('RECEIPT_INVALID');return 'sha256:'+createHash('sha256').update(await prepared.readFile(path,{maximumBytes:1048576,signal})).digest('hex');};
|
|
17
|
+
const uiDigest=await receipt(uiReceiptPath,'asset'),serverDigest=await receipt(serverReceiptPath,'control');signal?.throwIfAborted();
|
|
18
|
+
try{const publisher=publicPublisherMetadata({...configuration.publisher,enabled:true,serverOrigins:[server.origin],uiOrigins:[ui.origin]}),{resourcesDigest,...declarations}=descriptor.release;
|
|
19
|
+
const payload=validateSolutionReleasePayload({schemaVersion:1,solutionId:descriptor.solutionId,publisherId:descriptor.publisherId,version:descriptor.version,sdkApiVersion:descriptor.sdkApiVersion,server:{url:serverUrl,protocolVersion:descriptor.runtime.protocolVersion},ui:{url:uiUrl,integrity:uiDigest,bridgeVersion:descriptor.ui.bridgeVersion},artifacts:{server:serverDigest,resources:resourcesDigest},...declarations},publisher);return {payload,releaseDigest:solutionReleaseDigest(payload),publisher};
|
|
20
|
+
}catch{throw fail('DECLARATIONS_INVALID');}
|
|
21
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type {PublishingDurableJournal,PublishingDurableStorage} from './journal.mjs';
|
|
2
|
+
import type {PublishingService,PublishingWorkerResult} from './service.mjs';
|
|
3
|
+
export interface PublishingDurableContext {storage:PublishingDurableStorage&{getAlarm():Promise<number|null>;setAlarm(time:number):Promise<void>;deleteAlarm():Promise<void>};abort(message:string):void}
|
|
4
|
+
export function createPublishingDurableRuntime(input:{ctx:PublishingDurableContext;journal:PublishingDurableJournal;service:PublishingService;worker:{run(input:{projectId:string;requestId:string;mode:'perform'|'observe';signal:AbortSignal}):Promise<PublishingWorkerResult>};now?:()=>number;limits?:{pollMs:number;jobMs:number;maximumPolls?:number}}):{schedule():Promise<void>;run():Promise<PublishingWorkerResult|{state:'idle'|'busy'}>;alarm():Promise<PublishingWorkerResult|{state:'idle'|'busy'}>;fetch(request:Request):Promise<Response>;status():{running:boolean;blocked:boolean;nextWake:number|null}};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const fail=code=>Error('PUBLISHING_RUNTIME_'+code);
|
|
2
|
+
/** One alarm owns one finite verification batch or original provider operation. */
|
|
3
|
+
export function createPublishingDurableRuntime({ctx,journal,service,worker,now=Date.now,limits={pollMs:1000,jobMs:60000}}){
|
|
4
|
+
const maximumPolls=limits.maximumPolls??18;
|
|
5
|
+
if(!ctx?.storage||typeof ctx.abort!=='function'||typeof service?.handle!=='function'||typeof worker?.run!=='function'||typeof journal?.take!=='function'||!Number.isSafeInteger(limits.pollMs)||limits.pollMs<1||limits.pollMs>30000||!Number.isSafeInteger(limits.jobMs)||limits.jobMs<1||limits.jobMs>300000||!Number.isSafeInteger(maximumPolls)||maximumPolls<1||maximumPolls>128)throw fail('INPUT_INVALID');
|
|
6
|
+
let arming=Promise.resolve(),stepping=false,activeDeadline=0;
|
|
7
|
+
const schedule=()=>{const pending=arming.catch(()=>{}).then(async()=>{const next=journal.nextWake(),previous=await ctx.storage.getAlarm();if(next===null){if(previous!==null){await ctx.storage.deleteAlarm();await ctx.storage.sync();}return;}const wanted=Math.max(now()+1,next,stepping?activeDeadline:0);if(previous===null||previous>wanted)await ctx.storage.setAlarm(wanted);await ctx.storage.sync();});arming=pending;return pending;};
|
|
8
|
+
const reset=()=>{if(journal.blocked)ctx.abort('Publishing transport closure is unconfirmed; observe the durable original claim in a fresh actor');};
|
|
9
|
+
const run=async()=>{
|
|
10
|
+
if(stepping||journal.running)return {state:'busy'};stepping=true;activeDeadline=now()+limits.jobMs;let job,value,failure,failed=false;
|
|
11
|
+
try{job=await journal.take();if(!job)return {state:'idle'};
|
|
12
|
+
try{value=await worker.run({projectId:job.projectId,requestId:job.requestId,mode:job.mode,signal:AbortSignal.timeout(limits.jobMs)});}
|
|
13
|
+
catch(error){failed=true;failure=error;}
|
|
14
|
+
if(!journal.blocked){const progressing=value?.next==='perform'||value?.next==='verify',pending=value?.receipt?.outcome==='pending'&&value.state!=='awaiting-acceptance',observations=pending?(job.observations??0)+(job.mode==='observe'?1:0):0,next=job.continue&&!failed&&(progressing||pending&&observations<maximumPolls);try{await journal.finish(job,{again:!!next,delayMs:limits.pollMs,mode:progressing?'perform':'observe',advance:job.continue,observations});}catch(error){failure=failed?new AggregateError([failure,error],'PUBLISHING_RUNTIME_FINISH_FAILED',{cause:failure}):error;failed=true;}}
|
|
15
|
+
if(failed)throw failure;return value;
|
|
16
|
+
}finally{stepping=false;}
|
|
17
|
+
};
|
|
18
|
+
const owned=async work=>{let value,failure,failed=false;try{value=await work();}catch(error){failed=true;failure=error;}try{await schedule();}catch(error){failure=failed?new AggregateError([failure,error],'PUBLISHING_RUNTIME_SCHEDULE_FAILED',{cause:failure}):error;failed=true;}try{reset();}catch(error){failure=failed?new AggregateError([failure,error],'PUBLISHING_RUNTIME_RESET_FAILED',{cause:failure}):error;failed=true;}if(failed)throw failure;return value;};
|
|
19
|
+
return Object.freeze({schedule,run:()=>owned(run),alarm:()=>owned(run),status:()=>({running:stepping,blocked:journal.blocked,nextWake:journal.nextWake()}),fetch:request=>owned(async()=>{
|
|
20
|
+
if(request.method==='GET'||request.method==='HEAD')return service.handle(request);
|
|
21
|
+
try{return await journal.withIngress(()=>service.handle(request));}catch(error){if(/BUSY$/.test(error.message)){let timer;try{await Promise.race([request.body?.cancel(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(fail('BODY_CLOSE_UNCONFIRMED')),1000);})]);}finally{clearTimeout(timer);}return Response.json({error:{code:'BUSY'}},{status:409});}throw error;}
|
|
22
|
+
})});
|
|
23
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type {PublishingConfiguration} from '../protocol.mjs';
|
|
2
|
+
import type {PublishingIntent} from '../protocol.mjs';
|
|
3
|
+
import type {ArtifactOperationTransport,ArtifactOperationRecord,ArtifactOperationReceipt,ArtifactOperationCapability} from '@openge/forge-artifact-publish';
|
|
4
|
+
import type {PublishingMetadataTransport as ReleaseMetadataTransport} from '../protocol.mjs';
|
|
5
|
+
import type {SolutionPackageLimits} from '../package.mjs';
|
|
6
|
+
import type {PublishingDurableJournal as PublishingJournal,PublishingDispatch} from './journal.mjs';
|
|
7
|
+
import type {PreparedPublishingPackage as PreparedSolutionPackage} from './package.mjs';
|
|
8
|
+
export interface PublishingProjectPolicy {
|
|
9
|
+
schemaVersion:1;configuration:PublishingConfiguration;policyRevision:number;disabled:boolean;
|
|
10
|
+
solutionId:string;packageName:string;limits:SolutionPackageLimits;maximumRequests:number;
|
|
11
|
+
}
|
|
12
|
+
export interface PublishingServiceLimits {requestMs:number;maximumChunkBytes:number;maximumChunks:number}
|
|
13
|
+
export interface PublishingService {handle(request:Request):Promise<Response>}
|
|
14
|
+
export function configurePublishingProject(input:{journal:PublishingJournal;policy:PublishingProjectPolicy;credential:string;expectedRevision:number;allowLoopback?:boolean;signal?:AbortSignal}):Promise<{revision:number}>;
|
|
15
|
+
export function createPublishingService(input:{journal:PublishingJournal;allowLoopback?:boolean;limits?:PublishingServiceLimits;onDispatch?:(input:PublishingDispatch)=>void|Promise<void>}):PublishingService;
|
|
16
|
+
export interface PublishingProjectLease {signal?:AbortSignal;assertHeld():Promise<void>;beginOperation?():void;confirmClosure?(closure:import('@openge/forge-artifact-publish').ArtifactTransportClosure|undefined):void}
|
|
17
|
+
export interface PublishingDeploymentStage {
|
|
18
|
+
name:string;capability:ArtifactOperationCapability;configurationSha256:string;
|
|
19
|
+
/** A pending observation is woken by an authenticated completion receipt. */
|
|
20
|
+
waitForSignal?:boolean;
|
|
21
|
+
/** Synchronous pure factory: no resource or external effect may start before execute/observe. */
|
|
22
|
+
createDeployment(input:{policy:PublishingProjectPolicy;intent:PublishingIntent;prepared:PreparedSolutionPackage;previous:{name:string;output:unknown}[];assertAuthorized():Promise<void>;signal:AbortSignal}):{
|
|
23
|
+
transport:ArtifactOperationTransport;
|
|
24
|
+
/** Synchronously extract a <=64 KiB JSON snapshot already observed inside
|
|
25
|
+
* the transport lifecycle. No additional I/O or asynchronous work. The final
|
|
26
|
+
* activation requires actual acceptance before its owner signs it. */
|
|
27
|
+
readResult(input:{record:ArtifactOperationRecord}):unknown;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export interface PublishingWorkerOptions {
|
|
31
|
+
journal:PublishingJournal;
|
|
32
|
+
/** Actual exclusive cross-process project lock, held through callback closure.
|
|
33
|
+
* Abort/fence the lease if storage ownership or connection is lost. */
|
|
34
|
+
withProjectLock<T>(input:{projectId:string;requestId:string;mode:'perform'|'observe';signal?:AbortSignal},work:(lease:PublishingProjectLease)=>Promise<T>):Promise<T>;
|
|
35
|
+
stages:readonly PublishingDeploymentStage[];allowLoopback?:boolean;
|
|
36
|
+
metadataTransport?:ReleaseMetadataTransport;
|
|
37
|
+
verifyActivation?:typeof import('./activation.mjs').verifyPublishingActivation;
|
|
38
|
+
operationLimits?:{timeoutMilliseconds:number;closeTimeoutMilliseconds:number};
|
|
39
|
+
}
|
|
40
|
+
export interface PublishingWorkerResult {requestId:string;state:string;sideEffects:string;receipt?:ArtifactOperationReceipt;next?:'perform'|'verify'}
|
|
41
|
+
export function createPublishingWorker(input:PublishingWorkerOptions):{run(input:{projectId:string;requestId:string;mode?:'perform'|'observe';signal?:AbortSignal}):Promise<PublishingWorkerResult>};
|