@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,135 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
5
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
6
|
+
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
7
|
+
import {GeneratedArtifactError,generatedArtifactErrorCodes} from '@openge/forge-generated-artifacts';
|
|
8
|
+
import {publishingError,protocolRecord,publishingRequestId,publishingDigest} from '../protocol.mjs';
|
|
9
|
+
|
|
10
|
+
const fail=code=>publishingError('JOURNAL_'+code);
|
|
11
|
+
const keyValid=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
|
|
12
|
+
const recordBytes=(key,revision,payload)=>Buffer.byteLength('{"key":'+JSON.stringify(key)+',"revision":'+revision+',"payload":'+payload+'}');
|
|
13
|
+
function storageFailure(error){
|
|
14
|
+
if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_'))throw error;
|
|
15
|
+
throw fail([5,6].includes(error?.errcode)?'BUSY':'STORAGE_UNKNOWN');
|
|
16
|
+
}
|
|
17
|
+
function checkedLimits(value){
|
|
18
|
+
if(!protocolRecord(value,['maximumBytes','maximumRecords','maximumRecordBytes','maximumBlobs','maximumBlobBytes','minimumFreeBytes'])||!Object.values(value).every(Number.isSafeInteger)||value.maximumBytes<65536||value.maximumBytes>1073741824||value.maximumRecords<1||value.maximumRecords>4096||value.maximumRecordBytes<1||value.maximumRecordBytes>1048576||value.maximumBlobs<1||value.maximumBlobs>32768||value.maximumBlobBytes<1||value.maximumBlobBytes>134217728||value.minimumFreeBytes<0)throw fail('LIMIT_INVALID');return {...value};
|
|
19
|
+
}
|
|
20
|
+
const occupied=error=>error instanceof GeneratedArtifactError&&error.code===generatedArtifactErrorCodes.destinationOccupied&&error.details.cleanupFailed!==true;
|
|
21
|
+
async function capacity(root,limits){
|
|
22
|
+
const info=await fs.statfs(root,{bigint:true});
|
|
23
|
+
if(info.bavail*info.bsize<BigInt(limits.minimumFreeBytes)+BigInt(limits.maximumBytes)*2n+65536n)throw fail('CAPACITY_REQUIRED');
|
|
24
|
+
}
|
|
25
|
+
async function markerBytes(file){
|
|
26
|
+
const before=await fs.lstat(file,{bigint:true});
|
|
27
|
+
if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||before.size>4096n||await fs.realpath(file)!==file)throw fail('OWNERSHIP_INVALID');
|
|
28
|
+
const body=await fs.readFile(file),after=await fs.lstat(file,{bigint:true});
|
|
29
|
+
if(body.byteLength>4096||['dev','ino','size','mtimeNs','ctimeNs'].some(key=>before[key]!==after[key]))throw fail('OWNERSHIP_INVALID');
|
|
30
|
+
try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(body));}catch{throw fail('OWNERSHIP_INVALID');}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
|
|
34
|
+
export async function openPublishingJournal({root,directory,filesystem,limits,signal}){
|
|
35
|
+
signal?.throwIfAborted();limits=checkedLimits(limits);
|
|
36
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||!filesystem||typeof filesystem.ensureDirectory!=='function'||typeof filesystem.publishBytes!=='function')throw fail('INPUT_INVALID');
|
|
37
|
+
root=path.resolve(root);const rootInfo=await fs.lstat(root,{bigint:true});
|
|
38
|
+
if(!rootInfo.isDirectory()||rootInfo.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('BOUNDARY');
|
|
39
|
+
try{directory=validatePortableRelativePath(directory);}catch{throw fail('BOUNDARY');}
|
|
40
|
+
await capacity(root,limits);signal?.throwIfAborted();
|
|
41
|
+
try{await filesystem.ensureDirectory(root,directory);}catch{throw fail('PERSISTENCE_UNKNOWN');}
|
|
42
|
+
const absolute=path.join(root,...directory.split('/')),markerFile=path.join(absolute,'owner.json'),databaseFile=path.join(absolute,'journal.sqlite');
|
|
43
|
+
const context={schemaVersion:1,root:{dev:String(rootInfo.dev),ino:String(rootInfo.ino)},directory,limits};
|
|
44
|
+
let marker;
|
|
45
|
+
try{marker=await markerBytes(markerFile);}catch(error){
|
|
46
|
+
if(error.code!=='ENOENT')throw error;
|
|
47
|
+
if((await fs.readdir(absolute)).length)throw fail('OCCUPIED');
|
|
48
|
+
const value={...context,ownerId:randomUUID()};
|
|
49
|
+
try{await filesystem.publishBytes(root,directory+'/owner.json',new TextEncoder().encode(JSON.stringify(value)+'\n'),{mode:'exclusive'});}
|
|
50
|
+
catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
|
|
51
|
+
marker=await markerBytes(markerFile);
|
|
52
|
+
}
|
|
53
|
+
if(!protocolRecord(marker,['schemaVersion','root','directory','limits','ownerId'])||!publishingRequestId(marker.ownerId)||!isDeepStrictEqual({...marker,ownerId:undefined},{...context,ownerId:undefined}))throw fail('CONTEXT_CHANGED');
|
|
54
|
+
const allowed=new Set(['owner.json','journal.sqlite','journal.sqlite-journal']);let retained=0;
|
|
55
|
+
for(const name of await fs.readdir(absolute)){
|
|
56
|
+
if(!allowed.has(name))throw fail('OCCUPIED');const file=path.join(absolute,name),info=await fs.lstat(file);
|
|
57
|
+
if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||await fs.realpath(file)!==file)throw fail('BOUNDARY');retained+=info.size;
|
|
58
|
+
}
|
|
59
|
+
if(retained>limits.maximumBytes*2+65536)throw fail('BYTE_LIMIT');
|
|
60
|
+
try{await fs.lstat(databaseFile);}catch(error){
|
|
61
|
+
if(error.code!=='ENOENT')throw error;
|
|
62
|
+
try{await filesystem.publishBytes(root,directory+'/journal.sqlite',new Uint8Array(),{mode:'exclusive'});}
|
|
63
|
+
catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
|
|
64
|
+
}
|
|
65
|
+
signal?.throwIfAborted();let database;
|
|
66
|
+
try{
|
|
67
|
+
database=new DatabaseSync(databaseFile,{enableForeignKeyConstraints:true,enableDoubleQuotedStringLiterals:false,allowExtension:false});
|
|
68
|
+
const tables=database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND substr(name,1,7)<>'sqlite_' ORDER BY name").all().map(row=>row.name);
|
|
69
|
+
if(tables.length===0){
|
|
70
|
+
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;');
|
|
71
|
+
database.exec('BEGIN IMMEDIATE');
|
|
72
|
+
try{
|
|
73
|
+
database.exec('CREATE TABLE journal_metadata (id INTEGER PRIMARY KEY CHECK(id=1),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_records (key TEXT PRIMARY KEY,revision INTEGER NOT NULL CHECK(revision>0),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_blobs (sha256 TEXT PRIMARY KEY,byte_length INTEGER NOT NULL CHECK(byte_length>=0),bytes BLOB NOT NULL) STRICT;');
|
|
74
|
+
database.prepare('INSERT INTO journal_metadata(id,payload) VALUES(1,?)').run(JSON.stringify(marker));database.exec('COMMIT');
|
|
75
|
+
}catch(error){try{database.exec('ROLLBACK');}catch{}throw error;}
|
|
76
|
+
}else if(tables.join(',')!=='journal_blobs,journal_metadata,journal_records')throw fail('OWNERSHIP_INVALID');
|
|
77
|
+
const stored=database.prepare('SELECT payload FROM journal_metadata WHERE id=1').get();
|
|
78
|
+
if(!stored||!isDeepStrictEqual(JSON.parse(stored.payload),marker))throw fail('OWNERSHIP_INVALID');
|
|
79
|
+
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA foreign_keys=ON;PRAGMA trusted_schema=OFF;PRAGMA temp_store=MEMORY;PRAGMA busy_timeout=0;');
|
|
80
|
+
const pages=Math.floor(limits.maximumBytes/4096);database.exec('PRAGMA max_page_count='+pages);
|
|
81
|
+
if(Number(database.prepare('PRAGMA page_size').get().page_size)!==4096||Number(database.prepare('PRAGMA max_page_count').get().max_page_count)!==pages)throw fail('BYTE_LIMIT');
|
|
82
|
+
await filesystem.ensureDirectory(root,directory);signal?.throwIfAborted();
|
|
83
|
+
}catch(error){try{database?.close();}catch{}storageFailure(error);}
|
|
84
|
+
let closed=false;
|
|
85
|
+
const ready=()=>{if(closed)throw fail('CLOSED');};
|
|
86
|
+
const load=async(key,{signal}={})=>{
|
|
87
|
+
ready();signal?.throwIfAborted();if(!keyValid(key))throw fail('KEY_INVALID');
|
|
88
|
+
const row=database.prepare('SELECT revision,payload FROM journal_records WHERE key=?').get(key);
|
|
89
|
+
if(!row)return undefined;
|
|
90
|
+
if(!Number.isSafeInteger(row.revision)||row.revision<1||recordBytes(key,row.revision,row.payload)>limits.maximumRecordBytes)throw fail('RECORD_INVALID');
|
|
91
|
+
let payload;try{payload=JSON.parse(row.payload);}catch{throw fail('RECORD_INVALID');}
|
|
92
|
+
return {revision:row.revision,payload};
|
|
93
|
+
};
|
|
94
|
+
const readBlob=async({sha256,byteLength},{signal}={})=>{
|
|
95
|
+
ready();signal?.throwIfAborted();if(!publishingDigest(sha256)||!Number.isSafeInteger(byteLength)||byteLength<0||byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
|
|
96
|
+
const row=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(sha256);
|
|
97
|
+
if(!row)return undefined;
|
|
98
|
+
if(row.byte_length!==byteLength||row.bytes.byteLength!==byteLength||createHash('sha256').update(row.bytes).digest('hex')!==sha256)throw fail('BLOB_INVALID');return new Uint8Array(row.bytes);
|
|
99
|
+
};
|
|
100
|
+
const compareAndSet=async({key,expectedRevision,payload,blobs=[]},{signal}={})=>{
|
|
101
|
+
ready();signal?.throwIfAborted();if(!keyValid(key)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||expectedRevision===Number.MAX_SAFE_INTEGER)throw fail('RECORD_INVALID');
|
|
102
|
+
let encoded;try{encoded=JSON.stringify(payload);}catch{throw fail('RECORD_INVALID');}
|
|
103
|
+
if(typeof encoded!=='string')throw fail('RECORD_INVALID');if(recordBytes(key,expectedRevision+1,encoded)>limits.maximumRecordBytes)throw fail('BYTE_LIMIT');
|
|
104
|
+
if(!Array.isArray(blobs)||blobs.length>limits.maximumBlobs)throw fail('BLOB_LIMIT');
|
|
105
|
+
const snapshots=[];let blobBytes=0;
|
|
106
|
+
for(const blob of blobs){
|
|
107
|
+
if(!protocolRecord(blob,['sha256','bytes'])||!publishingDigest(blob.sha256)||!(blob.bytes instanceof Uint8Array)||blob.bytes.byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
|
|
108
|
+
blobBytes+=blob.bytes.byteLength;if(blobBytes>limits.maximumBytes)throw fail('BYTE_LIMIT');
|
|
109
|
+
const bytes=new Uint8Array(blob.bytes);if(createHash('sha256').update(bytes).digest('hex')!==blob.sha256)throw fail('BLOB_INVALID');snapshots.push({sha256:blob.sha256,bytes});
|
|
110
|
+
}
|
|
111
|
+
await capacity(root,limits);ready();signal?.throwIfAborted();
|
|
112
|
+
try{database.exec('BEGIN IMMEDIATE');}catch(error){storageFailure(error);}
|
|
113
|
+
try{
|
|
114
|
+
const row=database.prepare('SELECT revision FROM journal_records WHERE key=?').get(key);
|
|
115
|
+
if((row?.revision??0)!==expectedRevision){database.exec('ROLLBACK');return 'conflict';}
|
|
116
|
+
if(!row&&Number(database.prepare('SELECT count(*) AS amount FROM journal_records').get().amount)>=limits.maximumRecords)throw fail('RECORD_LIMIT');
|
|
117
|
+
for(const blob of snapshots){
|
|
118
|
+
const existing=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(blob.sha256);
|
|
119
|
+
if(existing){if(existing.byte_length!==blob.bytes.byteLength||!Buffer.from(existing.bytes).equals(blob.bytes))throw fail('BLOB_INVALID');}
|
|
120
|
+
else database.prepare('INSERT INTO journal_blobs(sha256,byte_length,bytes) VALUES(?,?,?)').run(blob.sha256,blob.bytes.byteLength,blob.bytes);
|
|
121
|
+
}
|
|
122
|
+
if(Number(database.prepare('SELECT count(*) AS amount FROM journal_blobs').get().amount)>limits.maximumBlobs)throw fail('BLOB_LIMIT');
|
|
123
|
+
database.prepare('INSERT INTO journal_records(key,revision,payload) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(key,expectedRevision+1,encoded);
|
|
124
|
+
database.exec('COMMIT');return 'stored';
|
|
125
|
+
}catch(error){try{database.exec('ROLLBACK');}catch{}storageFailure(error);}
|
|
126
|
+
};
|
|
127
|
+
return Object.freeze({
|
|
128
|
+
load,readBlob,compareAndSet,
|
|
129
|
+
operationJournal(){return {
|
|
130
|
+
async load(requestId,context){if(!keyValid(requestId))throw fail('KEY_INVALID');const record=await load('operation:'+requestId,context);if(record&&record.payload?.revision!==record.revision)throw fail('RECORD_INVALID');return record?.payload;},
|
|
131
|
+
async compareAndSet({expectedRevision,next},context){if(!next?.binding||!keyValid(next.binding.requestId)||next.revision!==expectedRevision+1)throw fail('RECORD_INVALID');return compareAndSet({key:'operation:'+next.binding.requestId,expectedRevision,payload:next},context);},
|
|
132
|
+
};},
|
|
133
|
+
close(){if(!closed){database.close();closed=true;}},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type {ArtifactOperationOptions,ArtifactOperationReceipt} from '@openge/forge-artifact-publish';
|
|
2
|
+
import type {PublishingConfiguration,PublishingIntent,PublishingStatus} from '../protocol.mjs';
|
|
3
|
+
import type {PublishingClientOptions} from '../client.mjs';
|
|
4
|
+
import type {PublishingJournal} from './journal.mjs';
|
|
5
|
+
import type {PreparedSolutionPackage,SolutionPackageLimits} from './solution-package.mjs';
|
|
6
|
+
export interface PublishingSessionResult {receipt:ArtifactOperationReceipt;status?:PublishingStatus}
|
|
7
|
+
export interface PublishingSession {
|
|
8
|
+
freeze(input:{intent:PublishingIntent;prepared:Pick<PreparedSolutionPackage,'files'|'manifestBytes'>;signal?:AbortSignal}):Promise<{requestId:string;content:{manifestSha256:string}}>;
|
|
9
|
+
read(input:{requestId:string;signal?:AbortSignal}):Promise<{intent:PublishingIntent;prepared:PreparedSolutionPackage}>;
|
|
10
|
+
create(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
11
|
+
observe(input:{requestId:string;stage?:'create'|'commit';signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
12
|
+
upload(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
13
|
+
queue(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
14
|
+
/** Source-free controls use the immutable original intent, without reading payload blobs. */
|
|
15
|
+
status(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
16
|
+
resume(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
17
|
+
recover(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
18
|
+
abandon(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
19
|
+
}
|
|
20
|
+
export function createPublishingSession(input:Omit<PublishingClientOptions,'limits'>&{
|
|
21
|
+
journal:PublishingJournal;configuration:PublishingConfiguration;packageLimits:SolutionPackageLimits;
|
|
22
|
+
pathCaseSensitivity:'case-sensitive'|'case-insensitive';clientLimits?:PublishingClientOptions['limits'];operationLimits?:Omit<ArtifactOperationOptions,'signal'>;
|
|
23
|
+
}):PublishingSession;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {bindArtifactOperation,performArtifactOperation,observeArtifactOperation} from '@openge/forge-artifact-publish';
|
|
3
|
+
import {createPublishingClient} from '../client.mjs';
|
|
4
|
+
import {parsePublishingConfiguration,parsePublishingIntent,publishingIntentBytes,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
|
|
5
|
+
import {verifySolutionPackageBytes} from './solution-package.mjs';
|
|
6
|
+
|
|
7
|
+
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const encoded=value=>new TextEncoder().encode(JSON.stringify(value));
|
|
9
|
+
const fail=code=>publishingError(code);
|
|
10
|
+
const operationDefaults={timeoutMilliseconds:30000,closeTimeoutMilliseconds:2000};
|
|
11
|
+
function checkBinding(intent,prepared,configuration){
|
|
12
|
+
const item=intent.package,descriptor=prepared.descriptor;
|
|
13
|
+
if(intent.projectId!==configuration.projectId||item.publisherId!==configuration.publisher.publisherId||['solutionId','publisherId','packageName','version'].some(key=>item[key]!==descriptor[key])||item.fileCount!==prepared.files.length||item.totalBytes!==prepared.payloadBytes||item.content.manifestSha256!==prepared.content.manifestSha256)throw fail('PACKAGE_BINDING_INVALID');
|
|
14
|
+
}
|
|
15
|
+
function transportFor({client,intent,manifestBytes,target,configurationSha256,stage}){
|
|
16
|
+
const pending=new Set(),controller=new AbortController();let status,closed=false;
|
|
17
|
+
const run=(signal,execute)=>{
|
|
18
|
+
if(closed)throw fail('TRANSPORT_CLOSED');
|
|
19
|
+
const promise=Promise.resolve().then(()=>execute(AbortSignal.any([signal,controller.signal])));pending.add(promise);const settled=()=>pending.delete(promise);promise.then(settled,settled);return promise;
|
|
20
|
+
};
|
|
21
|
+
return {transport:{
|
|
22
|
+
target,capability:stage==='create'?'artifact-upload':'deployment-create',configurationSha256,
|
|
23
|
+
async execute(_binding,context){await run(context.signal,async signal=>{status=await(stage==='create'?client.createRequest({intent,manifestBytes,signal}):client.queueRequest({intent,signal}));});return {state:'accepted',reference:intent.requestId};},
|
|
24
|
+
async observe(binding,_reference,context){
|
|
25
|
+
try{await run(context.signal,async signal=>{status=await client.getStatus({intent,signal});});}
|
|
26
|
+
catch(error){if(error.code==='PUBLISHING_REQUEST_NOT_FOUND')return {state:'absent',fingerprint:binding.fingerprint};throw error;}
|
|
27
|
+
const state=stage==='create'?'succeeded':status.state==='uploading'?'pending':status.state==='unknown'?'unknown':['failed','abandoned','superseded'].includes(status.state)?'failed':'succeeded';
|
|
28
|
+
return {state,fingerprint:binding.fingerprint,reference:intent.requestId};
|
|
29
|
+
},
|
|
30
|
+
async close({timeoutMilliseconds}){
|
|
31
|
+
closed=true;controller.abort();let timer;
|
|
32
|
+
try{await Promise.race([Promise.allSettled([...pending]),new Promise(resolve=>{timer=setTimeout(resolve,timeoutMilliseconds);})]);}
|
|
33
|
+
finally{clearTimeout(timer);}
|
|
34
|
+
return {status:pending.size?'unconfirmed':'closed',activeRequests:pending.size};
|
|
35
|
+
},
|
|
36
|
+
},status:()=>status};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A project session holds no deployment-provider credential and never evaluates payloads. */
|
|
40
|
+
export function createPublishingSession({journal,configuration,credential,allowLoopback=false,request,clientLimits,verifyActivation,packageLimits,pathCaseSensitivity,operationLimits=operationDefaults}){
|
|
41
|
+
const config=parsePublishingConfiguration(configuration,{allowLoopback}),configurationSha256=hash(encoded(config)),selectedLimits={...packageLimits},selectedOperations={...operationLimits},selectedClientLimits=clientLimits?{...clientLimits}:undefined;
|
|
42
|
+
if(!journal||['load','compareAndSet','readBlob','operationJournal'].some(name=>typeof journal[name]!=='function')||!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity))throw fail('SESSION_INPUT_INVALID');
|
|
43
|
+
const client=createPublishingClient({configuration:config,credential,allowLoopback,...(request?{request}:{}),...(selectedClientLimits?{limits:selectedClientLimits}:{}),...(verifyActivation?{verifyActivation}:{})});
|
|
44
|
+
const key=requestId=>{if(!publishingRequestId(requestId))throw fail('REQUEST_ID_INVALID');return 'request:'+requestId;};
|
|
45
|
+
const metadata=async({requestId,signal})=>{
|
|
46
|
+
const record=await journal.load(key(requestId),{signal});if(!record)throw fail('FROZEN_REQUEST_MISSING');const saved=record.payload;
|
|
47
|
+
if(record.revision!==1||!protocolRecord(saved,['schemaVersion','configuration','intent','manifestByteLength'])||saved.schemaVersion!==1||!Number.isSafeInteger(saved.manifestByteLength)||saved.manifestByteLength<1||saved.manifestByteLength>1048576)throw fail('FROZEN_REQUEST_INVALID');
|
|
48
|
+
if(hash(encoded(parsePublishingConfiguration(saved.configuration,{allowLoopback})))!==configurationSha256)throw fail('CONFIGURATION_CHANGED');
|
|
49
|
+
const intent=parsePublishingIntent(saved.intent);if(intent.requestId!==requestId||intent.projectId!==config.projectId||intent.package.publisherId!==config.publisher.publisherId)throw fail('FROZEN_REQUEST_INVALID');return {intent,saved};
|
|
50
|
+
};
|
|
51
|
+
const read=async({requestId,signal})=>{
|
|
52
|
+
const {intent,saved}=await metadata({requestId,signal});
|
|
53
|
+
const manifestBytes=await journal.readBlob({sha256:intent.package.content.manifestSha256,byteLength:saved.manifestByteLength},{signal});if(!manifestBytes)throw fail('FROZEN_BYTES_MISSING');
|
|
54
|
+
let manifest;try{manifest=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(manifestBytes));}catch{throw fail('FROZEN_REQUEST_INVALID');}
|
|
55
|
+
if(!Array.isArray(manifest?.files)||manifest.files.length!==intent.package.fileCount)throw fail('FROZEN_REQUEST_INVALID');
|
|
56
|
+
const files=[];
|
|
57
|
+
for(const file of manifest.files){const bytes=await journal.readBlob({sha256:file.sha256,byteLength:file.byteLength},{signal});if(!bytes)throw fail('FROZEN_BYTES_MISSING');files.push({path:file.path,bytes});}
|
|
58
|
+
const prepared=await verifySolutionPackageBytes({files,manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);return {intent,prepared};
|
|
59
|
+
};
|
|
60
|
+
const operation=async(mode,{requestId,signal,stage='create'})=>{
|
|
61
|
+
if(!['create','commit'].includes(stage))throw fail('SESSION_INPUT_INVALID');
|
|
62
|
+
const {intent,saved}=await metadata({requestId,signal}),frozen=mode==='create'?await read({requestId,signal}):undefined,intentBytes=publishingIntentBytes(intent);
|
|
63
|
+
const target={provider:'link-light-publishing',namespace:config.projectId,endpoint:config.serviceUrl};
|
|
64
|
+
const binding=await bindArtifactOperation({requestId:requestId+'.'+stage,content:intent.package.content,...(intent.provenance?{provenance:intent.provenance}:{}),target,capability:stage==='create'?'artifact-upload':'deployment-create',configurationSha256,inputs:[{name:'intent.json',sha256:hash(intentBytes),byteLength:intentBytes.byteLength},{name:'content-manifest.json',sha256:intent.package.content.manifestSha256,byteLength:saved.manifestByteLength}]});
|
|
65
|
+
const current=transportFor({client,intent,manifestBytes:frozen?.prepared.manifestBytes,target,configurationSha256,stage});
|
|
66
|
+
const receipt=await(mode==='create'?performArtifactOperation:observeArtifactOperation)(current.transport,binding,journal.operationJournal(),{...selectedOperations,signal});
|
|
67
|
+
return {receipt,...(current.status()?{status:current.status()}:{})};
|
|
68
|
+
};
|
|
69
|
+
return Object.freeze({
|
|
70
|
+
async freeze({intent:input,prepared:inputPackage,signal}){
|
|
71
|
+
const intent=parsePublishingIntent(input);key(intent.requestId);
|
|
72
|
+
if(await journal.load(key(intent.requestId),{signal}))throw fail('REQUEST_EXISTS');
|
|
73
|
+
const prepared=await verifySolutionPackageBytes({files:inputPackage.files,manifestBytes:inputPackage.manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);
|
|
74
|
+
const files=new Map(prepared.manifest.files.map(file=>[file.path,file]));
|
|
75
|
+
const blobs=[{sha256:prepared.content.manifestSha256,bytes:prepared.manifestBytes},...prepared.files.map(file=>({sha256:files.get(file.path).sha256,bytes:file.bytes}))];
|
|
76
|
+
const result=await journal.compareAndSet({key:key(intent.requestId),expectedRevision:0,payload:{schemaVersion:1,configuration:config,intent,manifestByteLength:prepared.manifestBytes.byteLength},blobs},{signal});
|
|
77
|
+
if(result!=='stored')throw fail('REQUEST_EXISTS');return {requestId:intent.requestId,content:prepared.content};
|
|
78
|
+
},
|
|
79
|
+
read,
|
|
80
|
+
create:input=>operation('create',{...input,stage:'create'}),
|
|
81
|
+
observe:input=>operation('observe',input),
|
|
82
|
+
queue:input=>operation('create',{...input,stage:'commit'}),
|
|
83
|
+
async status({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.getStatus({intent,signal});},
|
|
84
|
+
async resume({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.resumeRequest({intent,signal});},
|
|
85
|
+
async recover({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.recoverRequest({intent,signal});},
|
|
86
|
+
async upload({requestId,signal}){
|
|
87
|
+
const {intent,prepared}=await read({requestId,signal}),manifest=new Map(prepared.manifest.files.map(file=>[file.path,file])),bodies=new Map(prepared.files.map(file=>[file.path,file.bytes]));
|
|
88
|
+
const checked=async()=>{
|
|
89
|
+
const status=await client.getStatus({intent,signal}),seen=new Map();
|
|
90
|
+
for(const file of status.missingFiles){const original=manifest.get(file.path);if(!original||original.sha256!==file.sha256||original.byteLength!==file.byteLength||file.receivedBytes>=file.byteLength||seen.has(file.sha256)&&seen.get(file.sha256)!==file.receivedBytes)throw fail('STATUS_BINDING_INVALID');seen.set(file.sha256,file.receivedBytes);}return status;
|
|
91
|
+
};
|
|
92
|
+
const status=await checked();if(status.state!=='uploading')return status;const done=new Set(),chunkBytes=selectedClientLimits?.maximumChunkBytes??262144;
|
|
93
|
+
for(const file of status.missingFiles){
|
|
94
|
+
if(done.has(file.sha256))continue;done.add(file.sha256);const bytes=bodies.get(file.path);
|
|
95
|
+
for(let offset=file.receivedBytes;offset<file.byteLength;offset+=chunkBytes)await client.uploadChunk({requestId,file,offset,bytes:bytes.subarray(offset,Math.min(offset+chunkBytes,file.byteLength)),signal});
|
|
96
|
+
}
|
|
97
|
+
return checked();
|
|
98
|
+
},
|
|
99
|
+
async abandon({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.abandonRequest({intent,signal});},
|
|
100
|
+
});
|
|
101
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type {ArtifactContentIdentity,ArtifactContentManifest,ArtifactContentManifestFile} from '@openge/forge-artifact-publish';
|
|
2
|
+
import type {SolutionPackageDescriptor,SolutionPackageLimits} from '../package.mjs';
|
|
3
|
+
export type {SolutionPackageLimits} from '../package.mjs';
|
|
4
|
+
export type SolutionPackageFilePlan=Omit<Extract<ArtifactContentManifestFile,{role:'asset'}>,'byteLength'|'sha256'>|Omit<Extract<ArtifactContentManifestFile,{role:'control'}>,'byteLength'|'sha256'>;
|
|
5
|
+
export interface PreparedSolutionPackage {
|
|
6
|
+
descriptor:SolutionPackageDescriptor;content:ArtifactContentIdentity;manifest:ArtifactContentManifest;manifestBytes:Uint8Array;
|
|
7
|
+
files:{path:string;bytes:Uint8Array}[];payloadBytes:number;
|
|
8
|
+
readFile(path:string,input:{maximumBytes:number;signal?:AbortSignal}):Promise<Uint8Array>;
|
|
9
|
+
streamFile(path:string,input?:{signal?:AbortSignal}):AsyncIterable<Uint8Array>;
|
|
10
|
+
}
|
|
11
|
+
interface PackageInput {root:string;pathCaseSensitivity:'case-sensitive'|'case-insensitive';limits:SolutionPackageLimits;signal?:AbortSignal}
|
|
12
|
+
export function prepareSolutionPackage(input:PackageInput&{files:readonly SolutionPackageFilePlan[]}):Promise<PreparedSolutionPackage>;
|
|
13
|
+
export function prepareSolutionPackageBytes(input:Omit<PackageInput,'root'>&{files:readonly (SolutionPackageFilePlan&{bytes:Uint8Array})[]}):Promise<PreparedSolutionPackage>;
|
|
14
|
+
export function verifySolutionPackage(input:PackageInput&{manifestBytes:Uint8Array;expectedContent:ArtifactContentIdentity}):Promise<PreparedSolutionPackage>;
|
|
15
|
+
export function verifySolutionPackageBytes(input:Omit<PackageInput,'root'>&{files:readonly {path:string;bytes:Uint8Array}[];manifestBytes:Uint8Array;expectedContent:ArtifactContentIdentity}):Promise<PreparedSolutionPackage>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {calculateBytesIntegrity} from '@openge/forge-artifact-integrity';
|
|
4
|
+
import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
|
|
5
|
+
import {captureArtifactFiles,verifyArtifactFiles} from '@openge/forge-artifact-publish/node';
|
|
6
|
+
import {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from '../package.mjs';
|
|
7
|
+
|
|
8
|
+
const failure=code=>Error('PUBLISHING_PACKAGE_'+code);
|
|
9
|
+
const compare=(a,b)=>a<b?-1:a>b?1:0;
|
|
10
|
+
const check=signal=>signal.throwIfAborted();
|
|
11
|
+
function runtimeClosure(descriptor,files,pathCaseSensitivity){
|
|
12
|
+
const names=new Set(files),links=new Map(),fold=value=>pathCaseSensitivity==='case-insensitive'?value.toLowerCase():value;
|
|
13
|
+
const overlaps=(first,second)=>first===second||first.startsWith(second+'/')||second.startsWith(first+'/');
|
|
14
|
+
for(const link of descriptor.runtime.links){
|
|
15
|
+
const name=fold(link.path);
|
|
16
|
+
if(files.some(file=>overlaps(fold(file),name))||[...links.keys()].some(file=>overlaps(fold(file),name)))throw failure('RUNTIME_LINK_INVALID');
|
|
17
|
+
links.set(link.path,link.target);
|
|
18
|
+
}
|
|
19
|
+
const resolve=(input,visited=new Set())=>{
|
|
20
|
+
if(visited.size>64||visited.has(input))throw failure('RUNTIME_LINK_INVALID');visited.add(input);
|
|
21
|
+
const match=[...links.keys()].filter(name=>input===name||input.startsWith(name+'/')).sort((a,b)=>b.length-a.length)[0];
|
|
22
|
+
if(match){const target=path.posix.normalize(path.posix.join(path.posix.dirname(match),links.get(match),input.slice(match.length)));if(!target.startsWith('server/'))throw failure('RUNTIME_LINK_INVALID');return resolve(target,visited);}
|
|
23
|
+
if(!names.has(input)&&!files.some(name=>name.startsWith(input+'/')))throw failure('RUNTIME_LINK_INVALID');return input;
|
|
24
|
+
};
|
|
25
|
+
for(const name of links.keys())resolve(name);
|
|
26
|
+
if(!names.has(descriptor.runtime.entry)||!names.has(descriptor.ui.entry))throw failure('ENTRY_MISSING');
|
|
27
|
+
}
|
|
28
|
+
function packageNames(files,pathCaseSensitivity){
|
|
29
|
+
if(!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity))throw failure('INPUT_INVALID');
|
|
30
|
+
const names=files.map(file=>file.path),folded=names.map(name=>pathCaseSensitivity==='case-insensitive'?name.toLowerCase():name);
|
|
31
|
+
const paths=new Set(folded),collision=folded.some(name=>{for(let slash=name.lastIndexOf('/');slash>=0;slash=name.lastIndexOf('/',slash-1))if(paths.has(name.slice(0,slash)))return true;return false;});
|
|
32
|
+
if(paths.size!==folded.length||collision||names.some(name=>name.split('/').some(part=>part.startsWith('.env')||['.git','.npmrc','.ssh','release-private'].includes(part)))||files.find(file=>file.path==='solution.json')?.role!=='control')throw failure('PLAN_INVALID');return names;
|
|
33
|
+
}
|
|
34
|
+
function completed(prepared,captured,pathCaseSensitivity,total){
|
|
35
|
+
let descriptor;try{descriptor=parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(captured.find(file=>file.path==='solution.json').bytes)));}catch{throw failure('DESCRIPTOR_INVALID');}
|
|
36
|
+
runtimeClosure(descriptor,packageNames(prepared.manifest.files,pathCaseSensitivity),pathCaseSensitivity);
|
|
37
|
+
const files=captured.sort((a,b)=>compare(a.path,b.path));
|
|
38
|
+
const streamFile=async function*(path,{signal}={}){const file=files.find(file=>file.path===path),declared=prepared.manifest.files.find(file=>file.path===path);if(!file||!declared)throw failure('CLOSURE');const digest=createHash('sha256');let count=0;for(let offset=0;offset<file.bytes.length;offset+=1048576){signal?.throwIfAborted();const bytes=new Uint8Array(file.bytes.subarray(offset,Math.min(offset+1048576,file.bytes.length)));digest.update(bytes);count+=bytes.length;yield bytes;}if(count!==declared.byteLength||digest.digest('hex')!==declared.sha256)throw failure('CHANGED');};
|
|
39
|
+
const readFile=async(path,{maximumBytes,signal}={})=>{const declared=prepared.manifest.files.find(file=>file.path===path);if(!Number.isSafeInteger(maximumBytes)||maximumBytes<0||maximumBytes>16777216||!declared||declared.byteLength>maximumBytes)throw failure('BYTE_LIMIT');const bytes=new Uint8Array(declared.byteLength);let offset=0;for await(const part of streamFile(path,{signal})){bytes.set(part,offset);offset+=part.length;}return bytes;};
|
|
40
|
+
return {descriptor,content:prepared.content,manifest:prepared.manifest,manifestBytes:prepared.bytes,files,payloadBytes:total,streamFile,readFile};
|
|
41
|
+
}
|
|
42
|
+
async function capturedPackage(declared,captured,pathCaseSensitivity,selected,current,total){
|
|
43
|
+
const byPath=new Map(captured.map(file=>[file.path,file])),manifestFiles=[];
|
|
44
|
+
if(byPath.size!==captured.length||declared.length!==captured.length)throw failure('CLOSURE');
|
|
45
|
+
for(const file of declared){const capturedFile=byPath.get(file.path);if(!capturedFile)throw failure('CLOSURE');const bytes=capturedFile.bytes,integrity=await calculateBytesIntegrity(bytes);check(current);manifestFiles.push({...file,byteLength:bytes.byteLength,sha256:integrity.sha256});}
|
|
46
|
+
const prepared=await createArtifactContentManifest({schemaVersion:1,files:manifestFiles});check(current);
|
|
47
|
+
if(prepared.bytes.byteLength>selected.maximumManifestBytes||total+prepared.bytes.byteLength>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');return completed(prepared,captured,pathCaseSensitivity,total);
|
|
48
|
+
}
|
|
49
|
+
async function canonicalManifest(manifestBytes,expectedContent,limits){
|
|
50
|
+
if(!(manifestBytes instanceof Uint8Array)||manifestBytes.byteLength>limits.maximumManifestBytes||!expectedContent||Object.keys(expectedContent).join(',')!=='manifestSha256'||!/^[a-f0-9]{64}$/.test(expectedContent.manifestSha256??''))throw failure('MANIFEST_INVALID');
|
|
51
|
+
const snapshot=new Uint8Array(manifestBytes);let manifest;
|
|
52
|
+
try{manifest=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(snapshot)));}catch{throw failure('MANIFEST_INVALID');}
|
|
53
|
+
if(manifest.content.manifestSha256!==expectedContent.manifestSha256||manifest.bytes.byteLength!==snapshot.byteLength||manifest.bytes.some((byte,index)=>byte!==snapshot[index]))throw failure('MANIFEST_CHANGED');return manifest;
|
|
54
|
+
}
|
|
55
|
+
/** Capture exact artifact bytes, independently of source control or a deployment. */
|
|
56
|
+
export async function prepareSolutionPackage({root,files,pathCaseSensitivity,limits,signal}){
|
|
57
|
+
signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits);
|
|
58
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity)||!Array.isArray(files)||!files.length||files.length>selected.maximumFiles)throw failure('INPUT_INVALID');
|
|
59
|
+
let declared;
|
|
60
|
+
try{declared=(await createArtifactContentManifest({schemaVersion:1,files:files.map(file=>({...file,byteLength:0,sha256:'0'.repeat(64)}))})).manifest.files;}catch{throw failure('PLAN_INVALID');}
|
|
61
|
+
if(files.some(file=>Object.keys(file).sort().join(',')!==(file.role==='asset'?'path,responseHeaders,role':'path,role')))throw failure('PLAN_INVALID');
|
|
62
|
+
packageNames(declared,pathCaseSensitivity);
|
|
63
|
+
return captureSolution({root,files,pathCaseSensitivity,selected,signal});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function captureSolution({root,files,pathCaseSensitivity,selected,signal,manifestBytes,expectedContent}){
|
|
67
|
+
const options={sources:[{rootDirectory:root,closure:'exact',files:files.map(file=>({...file,sourcePath:file.path}))}],pathCaseSensitivity,maxFiles:selected.maximumFiles,maxEntries:selected.maximumFiles*8,maxFileBytes:selected.maximumFileBytes,maxTotalBytes:selected.maximumTotalBytes,maxManifestBytes:selected.maximumManifestBytes,timeoutMilliseconds:selected.timeoutMs,...(signal?{signal}:{})};
|
|
68
|
+
let captured;
|
|
69
|
+
try{captured=await(manifestBytes?verifyArtifactFiles({...options,manifestBytes,expectedContent}):captureArtifactFiles(options));}
|
|
70
|
+
catch(error){signal?.throwIfAborted();throw failure(({INVALID_PLAN:'PLAN_INVALID',INVALID_SOURCE:'CLOSURE',INTEGRITY_MISMATCH:'CHANGED',BUDGET_EXCEEDED:'BYTE_LIMIT',CLOSURE_UNCONFIRMED:'CLOSE_FAILED'})[error.code]??'CAPTURE_FAILED');}
|
|
71
|
+
return completed({manifest:captured.manifest,content:captured.content,bytes:captured.manifestBytes},captured.manifest.files.map(file=>({path:file.path,bytes:captured.readFile(file.path)})),pathCaseSensitivity,captured.payloadByteLength);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Compose already-captured components without staging a second directory tree. */
|
|
75
|
+
export async function prepareSolutionPackageBytes({files,pathCaseSensitivity,limits,signal}){
|
|
76
|
+
signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits),deadline=AbortSignal.timeout(selected.timeoutMs),current=signal?AbortSignal.any([signal,deadline]):deadline;
|
|
77
|
+
if(!Array.isArray(files)||!files.length||files.length>selected.maximumFiles)throw failure('INPUT_INVALID');
|
|
78
|
+
const captured=[],plan=[];let total=0;
|
|
79
|
+
for(const file of files){
|
|
80
|
+
if(!file||!(file.bytes instanceof Uint8Array)||Object.keys(file).sort().join(',')!==(file.role==='asset'?'bytes,path,responseHeaders,role':'bytes,path,role'))throw failure('PLAN_INVALID');
|
|
81
|
+
if(file.bytes.byteLength>selected.maximumFileBytes)throw failure('BYTE_LIMIT');total+=file.bytes.byteLength;if(total>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
|
|
82
|
+
captured.push({path:file.path,bytes:new Uint8Array(file.bytes)});const {bytes,...declaration}=file;void bytes;plan.push({...declaration,byteLength:0,sha256:'0'.repeat(64)});
|
|
83
|
+
}
|
|
84
|
+
let declared;try{declared=(await createArtifactContentManifest({schemaVersion:1,files:plan})).manifest.files;}catch{throw failure('PLAN_INVALID');}
|
|
85
|
+
packageNames(declared,pathCaseSensitivity);return capturedPackage(declared,captured,pathCaseSensitivity,selected,current,total);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function verifySolutionPackage({root,manifestBytes,expectedContent,pathCaseSensitivity,limits,signal}){
|
|
89
|
+
const selected=parseSolutionPackageLimits(limits),manifest=await canonicalManifest(manifestBytes,expectedContent,selected);
|
|
90
|
+
packageNames(manifest.manifest.files,pathCaseSensitivity);
|
|
91
|
+
return captureSolution({root,files:manifest.manifest.files.map(({path,role,responseHeaders})=>({path,role,...(role==='asset'?{responseHeaders}:{})})),pathCaseSensitivity,selected,signal,manifestBytes:manifest.bytes,expectedContent});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Validate opaque received bytes without importing or executing the payload. */
|
|
95
|
+
export async function verifySolutionPackageBytes({files,manifestBytes,expectedContent,pathCaseSensitivity,limits,signal}){
|
|
96
|
+
signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits),deadline=AbortSignal.timeout(selected.timeoutMs),current=signal?AbortSignal.any([signal,deadline]):deadline;
|
|
97
|
+
if(!Array.isArray(files)||files.length<1||files.length>selected.maximumFiles)throw failure('CLOSURE');
|
|
98
|
+
const captured=[],seen=new Set();let total=0;
|
|
99
|
+
for(const file of files){
|
|
100
|
+
if(!file||Object.keys(file).sort().join(',')!=='bytes,path'||typeof file.path!=='string'||!(file.bytes instanceof Uint8Array)||seen.has(file.path))throw failure('CLOSURE');
|
|
101
|
+
if(file.bytes.byteLength>selected.maximumFileBytes)throw failure('BYTE_LIMIT');total+=file.bytes.byteLength;if(total>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
|
|
102
|
+
seen.add(file.path);captured.push({path:file.path,bytes:new Uint8Array(file.bytes)});
|
|
103
|
+
}
|
|
104
|
+
const prepared=await canonicalManifest(manifestBytes,expectedContent,selected);check(current);
|
|
105
|
+
if(total+prepared.bytes.byteLength>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
|
|
106
|
+
if(prepared.manifest.files.length!==captured.length)throw failure('CLOSURE');
|
|
107
|
+
const byPath=new Map(captured.map(file=>[file.path,file]));
|
|
108
|
+
for(const declared of prepared.manifest.files){
|
|
109
|
+
const file=byPath.get(declared.path);if(!file)throw failure('CLOSURE');
|
|
110
|
+
if(file.bytes.byteLength!==declared.byteLength||(await calculateBytesIntegrity(file.bytes)).sha256!==declared.sha256)throw failure('CHANGED');check(current);
|
|
111
|
+
}
|
|
112
|
+
return completed(prepared,captured,pathCaseSensitivity,total);
|
|
113
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Only a source owner that observed its process lifecycle may assert closure.
|
|
2
|
+
* The original cause stays private; CLI diagnostics emit only the stable code. */
|
|
3
|
+
export class PublishingSourceError extends Error {
|
|
4
|
+
constructor({cause,processesClosed}){
|
|
5
|
+
if(typeof processesClosed!=='boolean')throw TypeError('PUBLISHING_SOURCE_CLOSURE_REQUIRED');
|
|
6
|
+
const code='PUBLISHING_SOURCE_PREPARATION_'+(processesClosed?'FAILED':'UNKNOWN');
|
|
7
|
+
super(code,{cause});this.name='PublishingSourceError';this.code=code;this.processesClosed=processesClosed;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type {PublishingConfiguration,PublishingProject} from '../protocol.mjs';
|
|
2
|
+
import type {PublishingClientLimits} from '../client.mjs';
|
|
3
|
+
import type {PublishingJournal} from './journal.mjs';
|
|
4
|
+
import type {PreparedSolutionPackage} from './solution-package.mjs';
|
|
5
|
+
import type {PublishingMetadataTransport as ReleaseMetadataTransport} from '../protocol.mjs';
|
|
6
|
+
export interface PublishingSourceProducer {
|
|
7
|
+
prepare(input:{root:string;project:PublishingProject;signal?:AbortSignal;requestId:string}):Promise<{prepared:PreparedSolutionPackage;processesClosed:true}>;
|
|
8
|
+
}
|
|
9
|
+
export interface PublishingWorkflowOptions {
|
|
10
|
+
root:string;journal:PublishingJournal;configuration:PublishingConfiguration;credential:string;
|
|
11
|
+
allowLoopback?:boolean;request?:typeof fetch;clientLimits?:PublishingClientLimits;
|
|
12
|
+
pathCaseSensitivity?:'case-sensitive'|'case-insensitive';metadataTransport?:ReleaseMetadataTransport;
|
|
13
|
+
operationLimits?:{timeoutMilliseconds:number;closeTimeoutMilliseconds:number};
|
|
14
|
+
}
|
|
15
|
+
export interface PublishingWorkflowResult {
|
|
16
|
+
requestId?:string;
|
|
17
|
+
state:'empty'|'checked'|'preparation-unknown'|'preparation-failed'|'uploading'|'queued'|'deploying'|'registered'|'awaiting-acceptance'|'active'|'failed'|'unknown'|'abandoned'|'superseded';
|
|
18
|
+
active:boolean;sideEffects?:'none'|'pending'|'unknown'|'closed';timedOut?:true;
|
|
19
|
+
}
|
|
20
|
+
export interface PublishingSourceOptions {producer?:string;newPreparation?:boolean;signal?:AbortSignal}
|
|
21
|
+
export interface PublishingPublishOptions extends PublishingSourceOptions {
|
|
22
|
+
/** 0 (default) returns immediately; positive values bound read-only status polling after submission. */
|
|
23
|
+
waitMs?:number;
|
|
24
|
+
/** Status polling interval, 1–30000ms; defaults to 1000ms. */
|
|
25
|
+
pollMs?:number;
|
|
26
|
+
}
|
|
27
|
+
export interface PublishingWorkflow {
|
|
28
|
+
check(input?:PublishingSourceOptions):Promise<PublishingWorkflowResult>;
|
|
29
|
+
publish(input?:PublishingPublishOptions):Promise<PublishingWorkflowResult>;
|
|
30
|
+
status(input?:{signal?:AbortSignal}):Promise<PublishingWorkflowResult>;
|
|
31
|
+
recover(input?:{signal?:AbortSignal}):Promise<PublishingWorkflowResult>;
|
|
32
|
+
verify(input?:{signal?:AbortSignal}):Promise<PublishingWorkflowResult>;
|
|
33
|
+
abandon(input?:{signal?:AbortSignal}):Promise<PublishingWorkflowResult>;
|
|
34
|
+
}
|
|
35
|
+
export function createPublishingWorkflow(input:PublishingWorkflowOptions):PublishingWorkflow;
|