@xlinklight/publishing 3.3.0 → 3.3.1

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.
Files changed (80) hide show
  1. package/README.md +1 -1
  2. package/dist/src/acceptance-delivery-binding.js +59 -0
  3. package/dist/src/acceptance.js +79 -0
  4. package/dist/src/client.js +146 -0
  5. package/dist/src/index.js +3 -0
  6. package/dist/src/node/acceptance-delivery.js +88 -0
  7. package/dist/src/node/activation.js +3 -0
  8. package/dist/src/node/authorization.js +76 -0
  9. package/dist/src/node/cli.js +20 -0
  10. package/dist/src/node/index.js +9 -0
  11. package/dist/src/node/journal.js +282 -0
  12. package/dist/src/node/publishing-command.js +220 -0
  13. package/dist/src/node/session.js +223 -0
  14. package/dist/src/node/solution-package.js +217 -0
  15. package/dist/src/node/source-error.js +15 -0
  16. package/dist/src/node/source-producer.js +145 -0
  17. package/dist/src/node/workflow.js +455 -0
  18. package/dist/src/package.js +74 -0
  19. package/dist/src/protocol.js +105 -0
  20. package/dist/src/shared/activation.js +111 -0
  21. package/dist/src/shared/records.js +26 -0
  22. package/dist/src/worker/activation.js +10 -0
  23. package/dist/src/worker/index.js +6 -0
  24. package/dist/src/worker/journal.js +301 -0
  25. package/dist/src/worker/package.js +116 -0
  26. package/dist/src/worker/release.js +59 -0
  27. package/dist/src/worker/runtime.js +98 -0
  28. package/dist/src/worker/service.js +494 -0
  29. package/package.json +17 -14
  30. package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -2
  31. package/{src/client.d.mts → types/client.d.ts} +1 -1
  32. package/{src/index.d.mts → types/index.d.ts} +6 -6
  33. package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
  34. package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
  35. package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
  36. package/types/node/index.d.ts +17 -0
  37. package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
  38. package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
  39. package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
  40. package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
  41. package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
  42. package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
  43. package/types/worker/index.d.ts +6 -0
  44. package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
  45. package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
  46. package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
  47. package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
  48. package/src/acceptance-delivery-binding.mjs +0 -49
  49. package/src/acceptance.mjs +0 -67
  50. package/src/client.mjs +0 -74
  51. package/src/index.mjs +0 -3
  52. package/src/node/acceptance-delivery.mjs +0 -70
  53. package/src/node/activation.mjs +0 -3
  54. package/src/node/authorization.mjs +0 -49
  55. package/src/node/cli.mjs +0 -12
  56. package/src/node/index.d.mts +0 -17
  57. package/src/node/index.mjs +0 -9
  58. package/src/node/journal.mjs +0 -135
  59. package/src/node/publishing-command.mjs +0 -104
  60. package/src/node/session.mjs +0 -134
  61. package/src/node/solution-package.mjs +0 -113
  62. package/src/node/source-error.mjs +0 -9
  63. package/src/node/source-producer.mjs +0 -103
  64. package/src/node/workflow.mjs +0 -320
  65. package/src/package.mjs +0 -36
  66. package/src/protocol.mjs +0 -50
  67. package/src/shared/activation.mjs +0 -64
  68. package/src/worker/activation.mjs +0 -4
  69. package/src/worker/index.d.mts +0 -6
  70. package/src/worker/index.mjs +0 -6
  71. package/src/worker/journal.mjs +0 -151
  72. package/src/worker/package.mjs +0 -32
  73. package/src/worker/release.mjs +0 -21
  74. package/src/worker/runtime.mjs +0 -23
  75. package/src/worker/service.mjs +0 -251
  76. /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
  77. /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
  78. /package/{src/package.d.mts → types/package.d.ts} +0 -0
  79. /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
  80. /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
@@ -1,151 +0,0 @@
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
- }
@@ -1,32 +0,0 @@
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
- }
@@ -1,21 +0,0 @@
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
- }
@@ -1,23 +0,0 @@
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
- }
@@ -1,251 +0,0 @@
1
- import {createHash,timingSafeEqual} from 'node:crypto';
2
- import {createArtifactContentManifest,bindArtifactOperation,performArtifactOperation,observeArtifactOperation,ArtifactOperationError} from '@openge/forge-artifact-publish';
3
- import {parsePublishingConfiguration,parsePublishingIntent,parsePublishingStatus,publishingIntentBytes,publishingIdentifier,publishingDigest,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
4
- import {parseSolutionPackageLimits} from '../package.mjs';
5
- import {openPreparedPublishingPackage} from './package.mjs';
6
- import {verifyPublishingActivation} from './activation.mjs';
7
-
8
- const hash=bytes=>createHash('sha256').update(bytes).digest('hex'),encode=value=>new TextEncoder().encode(JSON.stringify(value));
9
- const fail=code=>publishingError(code),key=id=>'project:'+id;
10
- const publicErrors={NOT_AUTHORIZED:403,PROJECT_DISABLED:403,POLICY_CHANGED:409,CONFLICT:409,REQUEST_NOT_FOUND:404,QUOTA_PAUSED:409,INVALID_INPUT:400,UNKNOWN_EFFECTS:409,BUSY:409,NOT_READY:409};
11
- const defaults={requestMs:30000,maximumChunkBytes:262144,maximumChunks:4096};
12
- function policyInput(value,allowLoopback){
13
- if(!protocolRecord(value,['schemaVersion','configuration','policyRevision','disabled','solutionId','packageName','limits','maximumRequests'])||value.schemaVersion!==1||!Number.isSafeInteger(value.policyRevision)||value.policyRevision<1||typeof value.disabled!=='boolean'||!publishingIdentifier(value.solutionId)||!/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(value.packageName??'')||!Number.isSafeInteger(value.maximumRequests)||value.maximumRequests<1||value.maximumRequests>64)throw fail('INVALID_INPUT');
14
- return {...value,configuration:parsePublishingConfiguration(value.configuration,{allowLoopback}),limits:parseSolutionPackageLimits(value.limits)};
15
- }
16
- function projectRecord(record,allowLoopback){
17
- if(!record||!protocolRecord(record.payload,['schemaVersion','policy','credentialSha256','requests'])||record.payload.schemaVersion!==1||!publishingDigest(record.payload.credentialSha256)||!Array.isArray(record.payload.requests))throw fail('UNKNOWN_EFFECTS');
18
- const state=record.payload;state.policy=policyInput(state.policy,allowLoopback);
19
- if(state.requests.length>state.policy.maximumRequests||state.requests.some(item=>!protocolRecord(item,['intent','manifestByteLength','intentSha256','state','sideEffects','files'],['activation','error','execution','validation'])||!publishingRequestId(item.intent?.requestId)||!publishingDigest(item.intentSha256)||!Array.isArray(item.files)))throw fail('UNKNOWN_EFFECTS');
20
- return {revision:record.revision,state};
21
- }
22
- export async function configurePublishingProject({journal,policy:input,credential,expectedRevision,allowLoopback=false,signal}){
23
- const policy=policyInput(input,allowLoopback);
24
- if(typeof credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(credential)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0)throw fail('INVALID_INPUT');
25
- const stored=await journal.load(key(policy.configuration.projectId),{signal});
26
- if((stored?.revision??0)!==expectedRevision)throw fail('CONFLICT');let requests=[];
27
- if(stored){
28
- const previous=projectRecord(stored,allowLoopback).state;
29
- if(policy.policyRevision!==previous.policy.policyRevision+1||policy.maximumRequests<previous.requests.length||['solutionId','packageName'].some(name=>policy[name]!==previous.policy[name])||policy.configuration.publisher.publisherId!==previous.policy.configuration.publisher.publisherId)throw fail('CONFLICT');requests=previous.requests;
30
- }else if(policy.policyRevision!==1)throw fail('INVALID_INPUT');
31
- const result=await journal.compareAndSet({key:key(policy.configuration.projectId),expectedRevision,payload:{schemaVersion:1,policy,credentialSha256:hash(credential),requests}},{signal,authority:{kind:'configure',projectId:policy.configuration.projectId}});if(result!=='stored')throw fail('CONFLICT');return {revision:expectedRevision+1};
32
- }
33
- async function bodyBytes(request,maximum,signal){
34
- const declared=request.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>maximum))throw fail('INVALID_INPUT');
35
- if(!request.body)throw fail('INVALID_INPUT');const reader=request.body.getReader(),chunks=[];let total=0;
36
- const cancel=()=>{reader.cancel().catch(()=>{});};signal.addEventListener('abort',cancel,{once:true});
37
- try{
38
- for(;;){signal.throwIfAborted();const {done,value}=await reader.read();signal.throwIfAborted();if(done)break;total+=value.byteLength;if(total>maximum)throw fail('INVALID_INPUT');chunks.push(value);}
39
- }catch(error){try{await reader.cancel();}catch{}throw error;}
40
- finally{signal.removeEventListener('abort',cancel);reader.releaseLock();}
41
- const bytes=new Uint8Array(total);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}return bytes;
42
- }
43
- async function jsonBody(request,signal){
44
- if(request.headers.get('content-type')!=='application/json')throw fail('INVALID_INPUT');
45
- const bytes=await bodyBytes(request,1056768,signal);try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));}catch{throw fail('INVALID_INPUT');}
46
- }
47
- function json(value,status=200){const bytes=encode(value);if(bytes.byteLength>1048576)throw fail('QUOTA_PAUSED');return new Response(bytes,{status,headers:{'content-type':'application/json','cache-control':'no-store','x-content-type-options':'nosniff'}});}
48
- const blocking=request=>!['active','abandoned','superseded'].includes(request.state)&&!(request.state==='failed'&&request.sideEffects==='closed');
49
- async function manifestFor(journal,item,signal){
50
- const bytes=await journal.readBlob({sha256:item.intent.package.content.manifestSha256,byteLength:item.manifestByteLength},{signal});if(!bytes)throw fail('UNKNOWN_EFFECTS');
51
- try{return (await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)))).manifest;}catch{throw fail('UNKNOWN_EFFECTS');}
52
- }
53
- async function assembled(journal,file,signal,extra){
54
- const digest=createHash('sha256');let count=0;for(const chunk of file.chunks){signal.throwIfAborted();const value=await journal.readBlob(chunk,{signal});if(!value||value.byteLength!==chunk.byteLength||hash(value)!==chunk.sha256)throw fail('UNKNOWN_EFFECTS');digest.update(value);count+=value.byteLength;}if(count!==file.receivedBytes)throw fail('UNKNOWN_EFFECTS');if(extra)digest.update(extra);return digest.digest('hex');
55
- }
56
- async function preparedFor(journal,item,policy,signal){
57
- return openPreparedPublishingPackage({journal,item,limits:policy.limits,signal});
58
- }
59
-
60
- /** HTTP admission and upload queue only. A separately fenced worker owns deployments. */
61
- export function createPublishingService({journal,allowLoopback=false,limits=defaults,onDispatch}){
62
- if(!journal||['load','compareAndSet','readBlob'].some(name=>typeof journal[name]!=='function')||onDispatch!==undefined&&typeof onDispatch!=='function'||!protocolRecord(limits,['requestMs','maximumChunkBytes','maximumChunks'])||Object.values(limits).some(value=>!Number.isSafeInteger(value)||value<1)||limits.requestMs>300000||limits.maximumChunkBytes>1048576||limits.maximumChunks>32768)throw fail('INVALID_INPUT');
63
- const selected={...limits};
64
- const statusFor=async(item,signal)=>{
65
- const manifest=await manifestFor(journal,item,signal),files=new Map(item.files.map(file=>[file.sha256,file]));
66
- return parsePublishingStatus({schemaVersion:1,requestId:item.intent.requestId,projectId:item.intent.projectId,intentSha256:item.intentSha256,state:item.state,sideEffects:item.sideEffects,missingFiles:item.state==='uploading'?manifest.files.filter(file=>(files.get(file.sha256)?.receivedBytes??0)<file.byteLength).map(file=>({path:file.path,sha256:file.sha256,byteLength:file.byteLength,receivedBytes:files.get(file.sha256)?.receivedBytes??0})):[],...(item.activation?{activation:item.activation}:{}),...(item.error?{error:item.error}:{})});
67
- };
68
- const authority=current=>({kind:'request',projectId:current.state.policy.configuration.projectId,policyRevision:current.state.policy.policyRevision,credentialSha256:current.state.credentialSha256});
69
- const save=async(current,blobs,signal,dispatch)=>{
70
- const result=await journal.compareAndSet({key:key(current.state.policy.configuration.projectId),expectedRevision:current.revision,payload:current.state,blobs},{signal,authority:authority(current),...(dispatch?{dispatch}:{})});if(result!=='stored')throw fail('CONFLICT');
71
- };
72
- const authorize=async(request,signal)=>{
73
- const header=request.headers.get('authorization'),id=request.headers.get('x-link-light-project-id');
74
- if(!/^Bearer [A-Za-z0-9_-]{32,4096}$/.test(header??'')||!publishingIdentifier(id))throw fail('NOT_AUTHORIZED');
75
- const stored=await journal.load(key(id),{signal});
76
- if(!stored)throw fail('NOT_AUTHORIZED');
77
- const found=projectRecord(stored,allowLoopback);
78
- if(!timingSafeEqual(Buffer.from(hash(header.slice(7)),'hex'),Buffer.from(found.state.credentialSha256,'hex')))throw fail('NOT_AUTHORIZED');
79
- if(found.state.policy.disabled)throw fail('PROJECT_DISABLED');
80
- if(new URL(request.url).origin!==found.state.policy.configuration.serviceUrl)throw fail('NOT_AUTHORIZED');return found;
81
- };
82
- const handle=async request=>{
83
- const signal=AbortSignal.any([request.signal,AbortSignal.timeout(selected.requestMs)]);
84
- try{
85
- const current=await authorize(request,signal),{state}=current,{policy}=state,url=new URL(request.url);
86
- if(request.method==='GET'&&url.pathname==='/v1/project'&&!url.search)return json({schemaVersion:1,configuration:policy.configuration,policyRevision:policy.policyRevision,solutionId:policy.solutionId,packageName:policy.packageName,limits:policy.limits});
87
- if(request.method==='GET'&&url.pathname==='/v1/project/release'&&!url.search){
88
- const selected=state.requests.find(blocking)??state.requests.findLast(item=>item.state!=='abandoned');
89
- return json({schemaVersion:1,intent:selected?.intent??null});
90
- }
91
- if(request.method==='POST'&&url.pathname==='/v1/requests'&&!url.search){
92
- const body=await jsonBody(request,signal);if(!protocolRecord(body,['intent','manifest']))throw fail('INVALID_INPUT');const intent=parsePublishingIntent(body.intent),item=intent.package;
93
- if(intent.projectId!==policy.configuration.projectId||item.publisherId!==policy.configuration.publisher.publisherId||item.solutionId!==policy.solutionId||item.packageName!==policy.packageName)throw fail('NOT_AUTHORIZED');
94
- if(intent.policyRevision!==policy.policyRevision)throw fail('POLICY_CHANGED');
95
- const manifest=await createArtifactContentManifest(body.manifest);
96
- if(manifest.content.manifestSha256!==item.content.manifestSha256||manifest.manifest.files.length!==item.fileCount||manifest.manifest.files.reduce((sum,file)=>sum+file.byteLength,0)!==item.totalBytes||item.fileCount>policy.limits.maximumFiles||manifest.bytes.byteLength>policy.limits.maximumManifestBytes||item.totalBytes+manifest.bytes.byteLength>policy.limits.maximumTotalBytes||manifest.manifest.files.some(file=>file.byteLength>policy.limits.maximumFileBytes))throw fail('INVALID_INPUT');
97
- const intentSha256=hash(publishingIntentBytes(intent)),existing=state.requests.find(request=>request.intent.requestId===intent.requestId);
98
- if(existing){if(existing.intentSha256!==intentSha256)throw fail('CONFLICT');return json(await statusFor(existing,signal));}
99
- if(state.requests.some(blocking)||state.requests.some(request=>request.state!=='abandoned'&&request.intent.package.version===item.version))throw fail('CONFLICT');
100
- if(state.requests.length>=policy.maximumRequests)throw fail('QUOTA_PAUSED');
101
- const files=new Map();for(const file of manifest.manifest.files){const previous=files.get(file.sha256);if(previous&&previous.byteLength!==file.byteLength)throw fail('INVALID_INPUT');files.set(file.sha256,{sha256:file.sha256,byteLength:file.byteLength,receivedBytes:0,chunks:[]});}
102
- const created={intent,manifestByteLength:manifest.bytes.byteLength,intentSha256,state:'uploading',sideEffects:'none',files:[...files.values()]};
103
- const response=json(parsePublishingStatus({schemaVersion:1,requestId:intent.requestId,projectId:intent.projectId,intentSha256,state:'uploading',sideEffects:'none',missingFiles:manifest.manifest.files.filter(file=>file.byteLength).map(file=>({path:file.path,sha256:file.sha256,byteLength:file.byteLength,receivedBytes:0}))}),201);
104
- state.requests.push(created);await save(current,[{sha256:manifest.content.manifestSha256,bytes:manifest.bytes}],signal);return response;
105
- }
106
- const route=/^\/v1\/requests\/([a-f0-9-]{36})(?:\/(commit|abandon|resume|recover|files\/([a-f0-9]{64})))?$/.exec(url.pathname);
107
- if(!route||!publishingRequestId(route[1]))throw fail('REQUEST_NOT_FOUND');const item=state.requests.find(item=>item.intent.requestId===route[1]);if(!item)throw fail('REQUEST_NOT_FOUND');
108
- if(request.method==='GET'&&!route[2]&&!url.search)return json(await statusFor(item,signal));
109
- if(request.method==='POST'&&route[2]==='abandon'&&!url.search){
110
- if(!protocolRecord(await jsonBody(request,signal),[]))throw fail('INVALID_INPUT');if(item.state==='abandoned'&&item.sideEffects==='closed')return json(await statusFor(item,signal));if(item.state!=='uploading'||item.sideEffects!=='none')throw fail('UNKNOWN_EFFECTS');item.state='abandoned';item.sideEffects='closed';await save(current,[],signal);return json(await statusFor(item,signal));
111
- }
112
- if(item.intent.policyRevision!==policy.policyRevision)throw fail('POLICY_CHANGED');
113
- if(request.method==='POST'&&['resume','recover'].includes(route[2])&&!url.search){
114
- const body=await jsonBody(request,signal);if(!protocolRecord(body,['intent'])||hash(publishingIntentBytes(body.intent))!==item.intentSha256)throw fail('CONFLICT');
115
- if(route[2]==='resume'&&item.state==='unknown')throw fail('UNKNOWN_EFFECTS');
116
- if(['queued','deploying','unknown'].includes(item.state)||route[2]==='recover'&&item.state==='awaiting-acceptance'){
117
- if(!onDispatch)throw fail('NOT_READY');
118
- const dispatch={projectId:policy.configuration.projectId,requestId:item.intent.requestId,mode:route[2]==='recover'||item.state==='deploying'?'observe':'perform',continue:route[2]!=='recover'};await journal.enqueue(dispatch,{signal,authority:authority(current)});await onDispatch(dispatch);
119
- }
120
- return json(await statusFor(item,signal));
121
- }
122
- if(request.method==='PUT'&&route[3]){
123
- if(request.headers.get('content-type')!=='application/octet-stream'||url.searchParams.size!==1||!/^\d{1,9}$/.test(url.searchParams.get('offset')??''))throw fail('INVALID_INPUT');
124
- if(item.state!=='uploading'||item.sideEffects!=='none')throw fail('NOT_READY');const file=item.files.find(file=>file.sha256===route[3]);if(!file)throw fail('INVALID_INPUT');
125
- const offset=Number(url.searchParams.get('offset'));if(offset>file.receivedBytes||item.files.reduce((sum,file)=>sum+file.chunks.length,0)>=selected.maximumChunks)throw fail('INVALID_INPUT');
126
- const bytes=await bodyBytes(request,Math.min(selected.maximumChunkBytes,file.byteLength-offset),signal);if(!bytes.byteLength)throw fail('INVALID_INPUT');const sha256=hash(bytes);
127
- if(offset<file.receivedBytes){let previous=0;for(const chunk of file.chunks){if(previous===offset&&chunk.byteLength===bytes.byteLength&&chunk.sha256===sha256)return json({schemaVersion:1,sha256:file.sha256,receivedBytes:offset+bytes.byteLength});previous+=chunk.byteLength;}throw fail('CONFLICT');}
128
- if(offset+bytes.byteLength===file.byteLength&&await assembled(journal,file,signal,bytes)!==file.sha256)throw fail('INVALID_INPUT');
129
- file.chunks.push({sha256,byteLength:bytes.byteLength});file.receivedBytes+=bytes.byteLength;await save(current,[{sha256,bytes}],signal);return json({schemaVersion:1,sha256:file.sha256,receivedBytes:file.receivedBytes});
130
- }
131
- if(request.method==='POST'&&route[2]==='commit'&&!url.search){
132
- const body=await jsonBody(request,signal);if(!protocolRecord(body,['intent'])||hash(publishingIntentBytes(body.intent))!==item.intentSha256)throw fail('CONFLICT');
133
- if(item.state!=='uploading')return json(await statusFor(item,signal));if(item.files.some(file=>file.receivedBytes!==file.byteLength))throw fail('NOT_READY');
134
- await preparedFor(journal,item,policy,signal);
135
- item.validation={manifestSha256:item.intent.package.content.manifestSha256,intentSha256:item.intentSha256,policySha256:hash(encode(policy)),cursor:0};item.state='queued';item.sideEffects='pending';const dispatch={projectId:policy.configuration.projectId,requestId:item.intent.requestId,mode:'perform',continue:true};await save(current,[],signal,dispatch);
136
- await onDispatch?.(dispatch);return json(await statusFor(item,signal));
137
- }
138
- throw fail('REQUEST_NOT_FOUND');
139
- }catch(error){
140
- const code=Object.keys(publicErrors).find(code=>error.code==='PUBLISHING_'+code)??(error.code==='PUBLISHING_JOURNAL_BUSY'?'BUSY':/^PUBLISHING_(?:PACKAGE|INTENT|CONFIGURATION)_/.test(error.message??'')||error.name==='ArtifactPublicationError'?'INVALID_INPUT':'UNKNOWN_EFFECTS');
141
- return json({error:{code}},publicErrors[code]);
142
- }
143
- };
144
- return Object.freeze({handle});
145
- }
146
-
147
- /** One explicitly invoked worker operation. The host supplies a real distributed
148
- * project lock and an installed deployment adapter; uploaded code stays opaque.
149
- * Factories and readResult are read-only. Each external step has its own public
150
- * Foundation operation; recovering a step never dispatches a later step. */
151
- export function createPublishingWorker({journal,withProjectLock,stages:inputStages,allowLoopback=false,metadataTransport,verifyActivation=verifyPublishingActivation,operationLimits={timeoutMilliseconds:300000,closeTimeoutMilliseconds:5000}}){
152
- if(!journal||['load','compareAndSet','readBlob','operationJournal'].some(name=>typeof journal[name]!=='function')||typeof withProjectLock!=='function'||!Array.isArray(inputStages)||!inputStages.length||inputStages.length>20
153
- ||inputStages.some(stage=>!protocolRecord(stage,['name','capability','configurationSha256','createDeployment'],['waitForSignal'])||!publishingIdentifier(stage.name)||!['artifact-upload','deployment-create','deployment-ready','activation'].includes(stage.capability)||!publishingDigest(stage.configurationSha256)||typeof stage.createDeployment!=='function'||Object.hasOwn(stage,'waitForSignal')&&(stage.waitForSignal!==true||stage.capability!=='deployment-ready'))
154
- ||new Set(inputStages.map(stage=>stage.name)).size!==inputStages.length||inputStages.at(-1).capability!=='activation')throw fail('INVALID_INPUT');
155
- const limits={...operationLimits},stages=inputStages.map(stage=>({...stage})),planSha256=hash(encode(stages.map(({name,capability,configurationSha256,waitForSignal})=>({name,capability,configurationSha256,waitForSignal}))));
156
- if(!protocolRecord(limits,['timeoutMilliseconds','closeTimeoutMilliseconds'])||Object.values(limits).some(value=>!Number.isSafeInteger(value)||value<1||value>300000))throw fail('INVALID_INPUT');
157
- return Object.freeze({async run({projectId,requestId,mode='perform',signal}){
158
- if(!publishingIdentifier(projectId)||!publishingRequestId(requestId)||!['perform','observe'].includes(mode))throw fail('INVALID_INPUT');
159
- const deadline=AbortSignal.any([signal,AbortSignal.timeout(limits.timeoutMilliseconds)].filter(Boolean));
160
- return withProjectLock({projectId,requestId,mode,signal:deadline},async lock=>{
161
- if(!lock||typeof lock.assertHeld!=='function')throw fail('INVALID_INPUT');
162
- const currentSignal=AbortSignal.any([deadline,lock.signal].filter(Boolean));
163
- const load=async()=>{
164
- currentSignal.throwIfAborted();await lock.assertHeld();
165
- const current=projectRecord(await journal.load(key(projectId),{signal:currentSignal}),allowLoopback),item=current.state.requests.find(item=>item.intent.requestId===requestId);
166
- if(!item)throw fail('REQUEST_NOT_FOUND');if(current.state.policy.disabled)throw fail('PROJECT_DISABLED');
167
- if(item.intent.policyRevision!==current.state.policy.policyRevision)throw fail('POLICY_CHANGED');return {...current,item};
168
- };
169
- const initial=await load(),intent=parsePublishingIntent(initial.item.intent),configuration=initial.state.policy.configuration,intentSha256=hash(publishingIntentBytes(intent)),configurationSha256=hash(encode(configuration));
170
- if(initial.item.intentSha256!==intentSha256||intent.projectId!==projectId)throw fail('UNKNOWN_EFFECTS');
171
- const assertAuthorized=async()=>{
172
- const current=await load();if(current.item.intentSha256!==intentSha256||hash(encode(current.state.policy.configuration))!==configurationSha256)throw fail('POLICY_CHANGED');return current;
173
- };
174
- const save=async(state,sideEffects,execution,activation)=>{
175
- const current=await assertAuthorized();current.item.state=state;current.item.sideEffects=sideEffects;
176
- current.item.execution=execution;
177
- if(activation!==undefined)current.item.activation=activation;else delete current.item.activation;
178
- const stored=await journal.compareAndSet({key:key(projectId),expectedRevision:current.revision,payload:current.state},{signal:currentSignal});if(stored!=='stored')throw fail('CONFLICT');
179
- };
180
- if(['uploading','abandoned','superseded'].includes(initial.item.state))throw fail('NOT_READY');
181
- const prepared=await preparedFor(journal,initial.item,initial.state.policy,currentSignal),validation=initial.item.validation;
182
- if(!validation||validation.manifestSha256!==intent.package.content.manifestSha256||validation.intentSha256!==intentSha256||validation.policySha256!==hash(encode(initial.state.policy))||!Number.isSafeInteger(validation.cursor)||validation.cursor<0||validation.cursor>prepared.files.length)throw fail('UNKNOWN_EFFECTS');
183
- if(validation.cursor<prepared.files.length){
184
- const result=await prepared.verifyBatch({cursor:validation.cursor,maximumFiles:1,maximumBytes:initial.state.policy.limits.maximumFileBytes,signal:currentSignal}),current=await assertAuthorized();
185
- if(current.item.validation?.cursor!==validation.cursor)throw fail('CONFLICT');current.item.validation={...validation,cursor:result.cursor};
186
- if(await journal.compareAndSet({key:key(projectId),expectedRevision:current.revision,payload:current.state},{signal:currentSignal})!=='stored')throw fail('CONFLICT');
187
- return {requestId,state:current.item.state,sideEffects:current.item.sideEffects,next:'verify'};
188
- }
189
- const originalExecution=structuredClone(initial.item.execution??{schemaVersion:1,planSha256,completed:[]}),execution=structuredClone(originalExecution);
190
- if(!protocolRecord(execution,['schemaVersion','planSha256','completed'])||execution.schemaVersion!==1||execution.planSha256!==planSha256||!Array.isArray(execution.completed)||execution.completed.length>stages.length
191
- ||execution.completed.some((item,index)=>!protocolRecord(item,['name','output'])||item.name!==stages[index].name)||encode(execution).byteLength>262144)throw fail('POLICY_CHANGED');
192
- if(mode==='perform'&&['active','failed','unknown'].includes(initial.item.state))throw fail('RECOVERY_REQUIRED');
193
- if(mode==='perform'&&execution.completed.length===stages.length)throw fail('RECOVERY_REQUIRED');
194
- const index=Math.min(execution.completed.length,stages.length-1),stage=stages[index],operationId=requestId+'.'+stage.name,operationJournal=journal.operationJournal();
195
- const existing=await operationJournal.load(operationId,{signal:currentSignal});
196
- if(mode==='perform'&&existing)throw fail('RECOVERY_REQUIRED');
197
- if(mode==='observe'&&!existing){if(execution.completed.length)return {requestId,state:initial.item.state,sideEffects:initial.item.sideEffects,next:'perform'};throw fail('RECOVERY_REQUIRED');}
198
- const previous=execution.completed.slice(0,index),previousBytes=encode(previous);
199
- const selected=stage.createDeployment({policy:structuredClone(initial.state.policy),intent:structuredClone(intent),prepared,previous:structuredClone(previous),assertAuthorized:async()=>{await assertAuthorized();},signal:currentSignal});
200
- if(!selected||typeof selected.then==='function'||typeof selected.readResult!=='function'||!selected.transport||['execute','observe','close'].some(name=>typeof selected.transport[name]!=='function')||selected.transport.capability!==stage.capability||selected.transport.configurationSha256!==stage.configurationSha256){
201
- if(selected instanceof Promise)selected.catch(()=>{});await save('unknown','unknown',originalExecution);throw fail('INVALID_INPUT');
202
- }
203
- const binding=await bindArtifactOperation({requestId:operationId,content:intent.package.content,...(intent.provenance?{provenance:intent.provenance}:{}),target:selected.transport.target,capability:stage.capability,configurationSha256:stage.configurationSha256,inputs:[{name:'intent.json',sha256:intentSha256,byteLength:publishingIntentBytes(intent).byteLength},{name:'project-policy.json',sha256:hash(encode(initial.state.policy)),byteLength:encode(initial.state.policy).byteLength},{name:'previous-results.json',sha256:hash(previousBytes),byteLength:previousBytes.byteLength}]});
204
- const transport={...selected.transport,
205
- async execute(bound,context){await assertAuthorized();const result=await selected.transport.execute(bound,context);await assertAuthorized();return result;},
206
- async observe(bound,reference,context){await assertAuthorized();const result=await selected.transport.observe(bound,reference,context);await assertAuthorized();return result;},
207
- close:options=>selected.transport.close(options),
208
- };
209
- if(mode==='perform')await save('deploying','pending',execution);
210
- try{
211
- lock.beginOperation?.();
212
- const receipt=await(mode==='perform'?performArtifactOperation:observeArtifactOperation)(transport,binding,operationJournal,{...limits,signal:currentSignal});
213
- lock.confirmClosure?.(receipt.closure);
214
- await assertAuthorized();let state='unknown',sideEffects='unknown',activation;
215
- if(receipt.journalState==='confirmed'&&receipt.closure.status==='closed'&&receipt.closure.activeRequests===0){
216
- if(receipt.outcome==='succeeded'){
217
- const output=selected.readResult({record:receipt.record});
218
- if(output&&typeof output.then==='function'){if(output instanceof Promise)output.catch(()=>{});throw fail('INVALID_INPUT');}
219
- const encoded=JSON.stringify(output);
220
- if(typeof encoded!=='string'||Buffer.byteLength(encoded)>65536)throw fail('INVALID_INPUT');
221
- const snapshot=JSON.parse(encoded);
222
- if(index===stages.length-1){
223
- activation=snapshot;await verifyActivation({configuration,intent,activation,allowLoopback,...(metadataTransport?{metadataTransport}:{}),signal:currentSignal});
224
- await assertAuthorized();state='active';sideEffects='closed';
225
- }else{state='deploying';sideEffects='pending';}
226
- if(execution.completed.length===index)execution.completed.push({name:stage.name,output:snapshot});
227
- else if(hash(encode(execution.completed[index].output))!==hash(encode(snapshot)))throw fail('UNKNOWN_EFFECTS');
228
- if(encode(execution).byteLength>262144)throw fail('QUOTA_PAUSED');
229
- }else if(receipt.outcome==='failed'){state='failed';sideEffects='closed';}
230
- else if(receipt.outcome==='pending'){state=stage.waitForSignal?'awaiting-acceptance':'deploying';sideEffects='pending';}
231
- }
232
- await save(state,sideEffects,execution,activation);return {requestId,state,sideEffects,receipt,...(state==='deploying'&&receipt.outcome==='succeeded'?{next:'perform'}:{})};
233
- }catch(error){
234
- if(error instanceof ArtifactOperationError)lock.confirmClosure?.(error.receipt?.closure);
235
- // A changed policy may also refuse this diagnostic write; never replace
236
- // the original error or use the failure path to grant final authority.
237
- try{
238
- const current=await assertAuthorized(),saved=current.item.execution??{schemaVersion:1,planSha256,completed:[]};
239
- // A lost outer CAS acknowledgement must not downgrade a cursor that the
240
- // store already advanced. Recovery can observe that committed result.
241
- if(hash(encode(saved))===hash(encode(originalExecution))){
242
- const receipt=error instanceof ArtifactOperationError?error.receipt:undefined;
243
- const rejected=error.code==='PROVIDER_REJECTED'&&receipt?.outcome==='failed'&&receipt.record.binding.fingerprint===binding.fingerprint&&receipt.record.writeState==='rejected'&&receipt.journalState==='confirmed'&&receipt.closure.status==='closed'&&receipt.closure.activeRequests===0;
244
- await save(rejected?'failed':'unknown',rejected?'closed':'unknown',originalExecution);
245
- }
246
- }catch{}
247
- throw error;
248
- }
249
- });
250
- }});
251
- }
File without changes