@xlinklight/publishing 3.0.0-rc.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +7 -1
- package/package.json +3 -3
- package/src/node/cli.mjs +107 -106
- package/src/node/source-producer.mjs +88 -0
- package/src/node/workflow.mjs +11 -12
- package/src/worker/journal.d.mts +21 -21
- package/src/worker/journal.mjs +151 -151
- package/src/worker/service.mjs +247 -247
package/src/worker/journal.mjs
CHANGED
|
@@ -1,151 +1,151 @@
|
|
|
1
|
-
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
-
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
3
|
-
import {isDeepStrictEqual} from 'node:util';
|
|
4
|
-
const fail=code=>Error('PUBLISHING_DURABLE_'+code),hash=bytes=>createHash('sha256').update(bytes).digest('hex'),json=value=>JSON.stringify(value);
|
|
5
|
-
const keyValid=key=>typeof key==='string'&&/^[A-Za-z0-9][A-Za-z0-9:._/-]{0,511}$/.test(key),positive=(value,max)=>Number.isSafeInteger(value)&&value>0&&value<=max;
|
|
6
|
-
const usageTables=[
|
|
7
|
-
['publishing_records','records'],['publishing_blobs','blobs'],['publishing_queue'],['publishing_leases'],
|
|
8
|
-
];
|
|
9
|
-
|
|
10
|
-
function initializeUsage(sql,one){
|
|
11
|
-
sql.exec('CREATE TABLE IF NOT EXISTS publishing_usage(id INTEGER PRIMARY KEY CHECK(id=1),bytes INTEGER NOT NULL CHECK(bytes>=0),records INTEGER NOT NULL CHECK(records>=0),blobs INTEGER NOT NULL CHECK(blobs>=0))');
|
|
12
|
-
if(!one('SELECT id FROM publishing_usage WHERE id=1')){
|
|
13
|
-
const records=one('SELECT count(*) n,coalesce(sum(size),0) bytes FROM publishing_records');
|
|
14
|
-
const blobs=one('SELECT count(*) n,coalesce(sum(size),0) bytes FROM publishing_blobs');
|
|
15
|
-
const queue=one('SELECT count(*) n FROM publishing_queue');
|
|
16
|
-
const leases=one('SELECT count(*) n FROM publishing_leases');
|
|
17
|
-
sql.exec('INSERT INTO publishing_usage VALUES(1,?,?,?)',records.bytes+blobs.bytes+(queue.n+leases.n)*1024,records.n,blobs.n);
|
|
18
|
-
}
|
|
19
|
-
// Update accounting in the transaction that changes the protected rows.
|
|
20
|
-
for(const [table,count] of usageTables){
|
|
21
|
-
const bytes=count?['NEW.size','OLD.size']:['1024','1024'];
|
|
22
|
-
for(const [event,sign,amount] of [['INSERT','+',bytes[0]],['DELETE','-',bytes[1]]]){
|
|
23
|
-
const adjustCount=count?`,${count}=${count}${sign}1`:'';
|
|
24
|
-
sql.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_usage_${event.toLowerCase()} AFTER ${event} ON ${table} BEGIN UPDATE publishing_usage SET bytes=bytes${sign}${amount}${adjustCount} WHERE id=1; END`);
|
|
25
|
-
}
|
|
26
|
-
if(count)sql.exec(`CREATE TRIGGER IF NOT EXISTS ${table}_usage_update AFTER UPDATE OF size ON ${table} WHEN OLD.size<>NEW.size BEGIN UPDATE publishing_usage SET bytes=bytes+NEW.size-OLD.size WHERE id=1; END`);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** The platform owns storage. This adapter owns opaque immutable chunks, real SQL CAS and fenced turns. */
|
|
31
|
-
export async function openPublishingDurableJournal({storage,identity,limits:inputLimits,now=Date.now,leaseMs=60000,increaseMaximumRecordsTo}){
|
|
32
|
-
const limits={...inputLimits};if(!storage?.sql||typeof storage.transactionSync!=='function'||typeof storage.sync!=='function'||typeof identity!=='string'||identity.length<1||identity.length>128||typeof now!=='function'||!positive(leaseMs,300000)||!positive(limits.maximumBytes,1073741824)||!positive(limits.maximumRecords,4096)||!positive(limits.maximumRecordBytes,1048576)||!positive(limits.maximumBlobs,32768)||!positive(limits.maximumBlobBytes,1048576)||!positive(limits.recoveryReserveBytes,limits.maximumBytes))throw fail('INPUT_INVALID');
|
|
33
|
-
if(increaseMaximumRecordsTo!==undefined&&(!positive(increaseMaximumRecordsTo,4096)||increaseMaximumRecordsTo<=limits.maximumRecords))throw fail('INPUT_INVALID');
|
|
34
|
-
const sql=storage.sql,rows=(query,...values)=>sql.exec(query,...values).toArray(),one=(query,...values)=>rows(query,...values)[0],context=new AsyncLocalStorage();let closed=false,running=false,blocked=false;
|
|
35
|
-
const ready=()=>{if(closed)throw fail('CLOSED');},check=signal=>{ready();signal?.throwIfAborted();};
|
|
36
|
-
const read=key=>{const row=one('SELECT revision,payload,checksum FROM publishing_records WHERE key=?',key);if(!row)return; if(hash(row.payload)!==row.checksum)throw fail('CORRUPT');return {revision:row.revision,payload:JSON.parse(row.payload)};};
|
|
37
|
-
const usage=()=>{const row=one('SELECT bytes,records,blobs FROM publishing_usage WHERE id=1');if(!row)throw fail('CORRUPT');return row;};
|
|
38
|
-
const capacity=recovery=>{if(usage().bytes>limits.maximumBytes-(recovery?0:limits.recoveryReserveBytes)||sql.databaseSize>limits.maximumBytes)throw fail('CAPACITY');};
|
|
39
|
-
const transaction=(work,recovery=false)=>storage.transactionSync(()=>{ready();const value=work();capacity(recovery);return value;});
|
|
40
|
-
storage.transactionSync(()=>{
|
|
41
|
-
for(const statement of [
|
|
42
|
-
'CREATE TABLE IF NOT EXISTS publishing_metadata(id INTEGER PRIMARY KEY CHECK(id=1),configuration TEXT NOT NULL)',
|
|
43
|
-
'CREATE TABLE IF NOT EXISTS publishing_records(key TEXT PRIMARY KEY,revision INTEGER NOT NULL,payload TEXT NOT NULL,checksum TEXT NOT NULL,size INTEGER NOT NULL)',
|
|
44
|
-
'CREATE TABLE IF NOT EXISTS publishing_blobs(sha256 TEXT PRIMARY KEY,length INTEGER NOT NULL,bytes BLOB NOT NULL,size INTEGER NOT NULL)',
|
|
45
|
-
'CREATE TABLE IF NOT EXISTS publishing_queue(project TEXT PRIMARY KEY,request TEXT NOT NULL,mode TEXT NOT NULL,advance INTEGER NOT NULL,revision INTEGER NOT NULL,next_at INTEGER NOT NULL,lease_until INTEGER,observations INTEGER NOT NULL,receipt_wake INTEGER NOT NULL DEFAULT 0)',
|
|
46
|
-
'CREATE TABLE IF NOT EXISTS publishing_leases(project TEXT PRIMARY KEY,request TEXT NOT NULL,intent TEXT NOT NULL,revision INTEGER NOT NULL,owner TEXT NOT NULL,until_ms INTEGER NOT NULL)'])sql.exec(statement);
|
|
47
|
-
const configuration=json({schemaVersion:1,identity,limits});
|
|
48
|
-
const expanded=increaseMaximumRecordsTo===undefined?undefined:json({schemaVersion:1,identity,limits:{...limits,maximumRecords:increaseMaximumRecordsTo}});
|
|
49
|
-
const previous=one('SELECT configuration FROM publishing_metadata WHERE id=1');
|
|
50
|
-
if(previous&&previous.configuration!==configuration&&previous.configuration!==expanded)throw fail('IDENTITY_CHANGED');
|
|
51
|
-
if(!previous)sql.exec('INSERT INTO publishing_metadata VALUES(1,?)',configuration);
|
|
52
|
-
if(!rows('PRAGMA table_info(publishing_queue)').some(column=>column.name==='receipt_wake')){
|
|
53
|
-
sql.exec('ALTER TABLE publishing_queue ADD COLUMN receipt_wake INTEGER NOT NULL DEFAULT 0');
|
|
54
|
-
}
|
|
55
|
-
initializeUsage(sql,one);
|
|
56
|
-
if(expanded&&previous?.configuration===expanded)limits.maximumRecords=increaseMaximumRecordsTo;
|
|
57
|
-
else if(expanded&&previous&&usage().records===limits.maximumRecords){
|
|
58
|
-
const busy=one('SELECT 1 FROM publishing_leases WHERE until_ms>? LIMIT 1',now())||
|
|
59
|
-
one('SELECT 1 FROM publishing_queue WHERE lease_until>? LIMIT 1',now());
|
|
60
|
-
if(!busy){
|
|
61
|
-
capacity(true);
|
|
62
|
-
sql.exec('UPDATE publishing_metadata SET configuration=? WHERE id=1',expanded);
|
|
63
|
-
limits.maximumRecords=increaseMaximumRecordsTo;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
});capacity(true);await storage.sync();
|
|
67
|
-
const authorize=(authority,key,next)=>{
|
|
68
|
-
if(!authority){if(key.startsWith('project:')||key.startsWith('operation:'))throw fail('AUTHORITY_REQUIRED');return;}
|
|
69
|
-
const project=read('project:'+authority.projectId)?.payload;if(authority.kind==='configure'){if(key!=='project:'+authority.projectId)throw fail('AUTHORITY_REQUIRED');return;}
|
|
70
|
-
if(!project||project.policy.disabled||project.policy.policyRevision!==authority.policyRevision)throw fail('POLICY_CHANGED');
|
|
71
|
-
if(authority.kind==='request'&&project.credentialSha256!==authority.credentialSha256)throw fail('POLICY_CHANGED');
|
|
72
|
-
if(authority.kind==='worker'){
|
|
73
|
-
const lease=one('SELECT * FROM publishing_leases WHERE project=?',authority.projectId),request=project.requests.find(item=>item.intent.requestId===authority.requestId);
|
|
74
|
-
if(!lease||lease.revision!==authority.revision||lease.owner!==authority.owner||lease.request!==authority.requestId||lease.until_ms<=now()||!request||request.intentSha256!==lease.intent||request.intent.policyRevision!==authority.policyRevision)throw fail('LEASE_LOST');
|
|
75
|
-
if(key.startsWith('operation:')&&(next?.binding?.requestId?.startsWith(authority.requestId+'.')!==true||next.binding.content.manifestSha256!==request.intent.package.content.manifestSha256))throw fail('AUTHORITY_REQUIRED');
|
|
76
|
-
}
|
|
77
|
-
if(key.startsWith('project:')&&(key!=='project:'+authority.projectId||!isDeepStrictEqual(project.policy,next?.policy)||project.credentialSha256!==next?.credentialSha256))throw fail('POLICY_CHANGED');
|
|
78
|
-
};
|
|
79
|
-
const enqueueInside=(job,authority)=>{
|
|
80
|
-
if(!job||!keyValid(job.projectId)||!keyValid(job.requestId)||!['perform','observe'].includes(job.mode)||typeof job.continue!=='boolean')throw fail('INPUT_INVALID');authorize(authority,'project:'+job.projectId,read('project:'+job.projectId)?.payload);
|
|
81
|
-
const project=read('project:'+job.projectId)?.payload,item=project?.requests.find(item=>item.intent.requestId===job.requestId);if(!item||item.intent.policyRevision!==project.policy.policyRevision||!queuedState(item.state,job.mode))throw fail('REQUEST_CHANGED');
|
|
82
|
-
const receipt=job.acceptanceReceipt===true;
|
|
83
|
-
if(receipt&&(job.mode!=='observe'||!job.continue||authority?.kind!=='request'))throw fail('AUTHORITY_REQUIRED');
|
|
84
|
-
const previous=one('SELECT * FROM publishing_queue WHERE project=?',job.projectId);
|
|
85
|
-
if(previous?.lease_until>now()){
|
|
86
|
-
if(!receipt||previous.request!==job.requestId)throw fail('BUSY');
|
|
87
|
-
// Keep the active lease intact. Its finish must preserve this wake.
|
|
88
|
-
sql.exec('UPDATE publishing_queue SET receipt_wake=1 WHERE project=?',job.projectId);
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
const accepted=receipt||job.continue&&previous?.request===job.requestId&&previous.receipt_wake>0;
|
|
92
|
-
sql.exec('INSERT INTO publishing_queue(project,request,mode,advance,revision,next_at,lease_until,observations,receipt_wake) VALUES(?,?,?,?,?,?,NULL,0,?) ON CONFLICT(project) DO UPDATE SET request=excluded.request,mode=excluded.mode,advance=excluded.advance,revision=excluded.revision,next_at=excluded.next_at,lease_until=NULL,observations=0,receipt_wake=excluded.receipt_wake',job.projectId,job.requestId,job.mode,job.continue?1:0,(previous?.revision??0)+1,now(),accepted?2:0);
|
|
93
|
-
};
|
|
94
|
-
const queuedState=(state,mode)=>['queued','deploying'].includes(state)||mode==='observe'&&['unknown','awaiting-acceptance'].includes(state);
|
|
95
|
-
const admissible=row=>{const project=read('project:'+row.project)?.payload,item=project?.requests.find(item=>item.intent.requestId===row.request);return !!item&&!project.policy.disabled&&project.policy.policyRevision===item.intent.policyRevision&&queuedState(item.state,row.mode);};
|
|
96
|
-
const api={
|
|
97
|
-
recordCapacity(){ready();return {used:usage().records,maximum:limits.maximumRecords};},
|
|
98
|
-
async load(key,{signal}={}){check(signal);if(!keyValid(key))throw fail('KEY_INVALID');return read(key);},
|
|
99
|
-
async readBlob({sha256,byteLength},{signal}={}){check(signal);if(!/^[a-f0-9]{64}$/.test(sha256)||!Number.isSafeInteger(byteLength)||byteLength<0||byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');const row=one('SELECT length,bytes FROM publishing_blobs WHERE sha256=?',sha256);if(!row)return;const bytes=new Uint8Array(row.bytes);if(row.length!==byteLength||bytes.length!==byteLength||hash(bytes)!==sha256)throw fail('BLOB_CHANGED');return bytes;},
|
|
100
|
-
async compareAndSet({key,expectedRevision,payload,blobs=[]},{signal,authority=context.getStore(),dispatch}={}){
|
|
101
|
-
check(signal);if(!keyValid(key)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||expectedRevision>=Number.MAX_SAFE_INTEGER||!Array.isArray(blobs)||blobs.length>limits.maximumBlobs)throw fail('RECORD_INVALID');const text=json(payload);if(typeof text!=='string'||Buffer.byteLength(text)+Buffer.byteLength(key)>limits.maximumRecordBytes)throw fail('RECORD_LIMIT');
|
|
102
|
-
const snapshot=JSON.parse(text),parts=blobs.map(({sha256,bytes})=>{if(!/^[a-f0-9]{64}$/.test(sha256)||!(bytes instanceof Uint8Array)||bytes.length>limits.maximumBlobBytes)throw fail('BLOB_INVALID');const owned=new Uint8Array(bytes);if(hash(owned)!==sha256)throw fail('BLOB_INVALID');return {sha256,bytes:owned};});
|
|
103
|
-
const result=transaction(()=>{check(signal);const previous=read(key);if((previous?.revision??0)!==expectedRevision)return 'conflict';authorize(authority,key,snapshot);
|
|
104
|
-
for(const part of parts){const existing=one('SELECT length,bytes FROM publishing_blobs WHERE sha256=?',part.sha256);if(existing){const bytes=new Uint8Array(existing.bytes);if(existing.length!==part.bytes.length||!Buffer.from(bytes).equals(part.bytes))throw fail('BLOB_CHANGED');}else sql.exec('INSERT INTO publishing_blobs VALUES(?,?,?,?)',part.sha256,part.bytes.length,part.bytes.buffer,part.bytes.length+128);}
|
|
105
|
-
const counts=usage();if(counts.blobs>limits.maximumBlobs)throw fail('BLOB_LIMIT');if(!previous&&counts.records>=limits.maximumRecords)throw fail('RECORD_LIMIT');
|
|
106
|
-
sql.exec('INSERT INTO publishing_records VALUES(?,?,?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload,checksum=excluded.checksum,size=excluded.size',key,expectedRevision+1,text,hash(text),Buffer.byteLength(text)+Buffer.byteLength(key)+128);if(dispatch)enqueueInside(dispatch,authority);return 'stored';
|
|
107
|
-
},authority?.mode==='observe');if(result==='stored')await storage.sync();check(signal);return result;
|
|
108
|
-
},
|
|
109
|
-
operationJournal(){return {load:async(id,options)=>{const result=await api.load('operation:'+id,options);if(result&&result.payload.revision!==result.revision)throw fail('CORRUPT');return result?.payload;},compareAndSet:async({expectedRevision,next},options)=>{if(next?.revision!==expectedRevision+1)throw fail('RECORD_INVALID');return api.compareAndSet({key:'operation:'+next.binding.requestId,expectedRevision,payload:next},options);}};},
|
|
110
|
-
async enqueue(job,{signal,authority=context.getStore()}={}){check(signal);transaction(()=>enqueueInside(job,authority),job.mode==='observe');await storage.sync();check(signal);},
|
|
111
|
-
nextWake(){ready();return one('SELECT min(max(next_at,coalesce(lease_until,0))) AS at FROM publishing_queue')?.at??null;},
|
|
112
|
-
async take(){
|
|
113
|
-
ready();if(blocked||running)throw fail('BUSY');let changed=false;
|
|
114
|
-
const result=transaction(()=>{
|
|
115
|
-
const row=one('SELECT * FROM publishing_queue WHERE next_at<=? AND (lease_until IS NULL OR lease_until<=?) ORDER BY next_at,project LIMIT 1',now(),now());
|
|
116
|
-
if(!row)return null;
|
|
117
|
-
changed=true;
|
|
118
|
-
const recovering=row.lease_until!==null,mode=recovering?'observe':row.mode;
|
|
119
|
-
const advance=recovering?row.receipt_wake>0:!!row.advance;
|
|
120
|
-
if(!admissible({...row,mode})){sql.exec('DELETE FROM publishing_queue WHERE project=?',row.project);return null;}
|
|
121
|
-
sql.exec('UPDATE publishing_queue SET revision=revision+1,mode=?,advance=?,lease_until=?,receipt_wake=? WHERE project=?',mode,advance?1:0,now()+leaseMs,row.receipt_wake>0?2:0,row.project);
|
|
122
|
-
return {projectId:row.project,requestId:row.request,revision:row.revision+1,mode,continue:advance,observations:row.observations};
|
|
123
|
-
},true);
|
|
124
|
-
if(changed)await storage.sync();
|
|
125
|
-
return result;
|
|
126
|
-
},
|
|
127
|
-
async finish(job,{again=false,delayMs=1000,mode='observe',advance=job.continue,observations=0}={}){
|
|
128
|
-
if(!Number.isSafeInteger(delayMs)||delayMs<1||delayMs>3600000||!Number.isSafeInteger(observations)||observations<0||observations>128||!['perform','observe'].includes(mode))throw fail('INPUT_INVALID');
|
|
129
|
-
transaction(()=>{
|
|
130
|
-
const row=one('SELECT * FROM publishing_queue WHERE project=?',job.projectId);
|
|
131
|
-
if(!row||row.revision!==job.revision||row.request!==job.requestId)throw fail('LEASE_LOST');
|
|
132
|
-
const receiptArrived=row.receipt_wake===1;
|
|
133
|
-
const nextMode=again?mode:'observe',nextAdvance=advance||receiptArrived;
|
|
134
|
-
if((again||receiptArrived)&&admissible({...row,mode:nextMode})){
|
|
135
|
-
sql.exec('UPDATE publishing_queue SET revision=revision+1,mode=?,advance=?,lease_until=NULL,next_at=?,observations=?,receipt_wake=? WHERE project=?',nextMode,nextAdvance?1:0,now()+delayMs,observations,row.receipt_wake>0?2:0,job.projectId);
|
|
136
|
-
}else sql.exec('DELETE FROM publishing_queue WHERE project=?',job.projectId);
|
|
137
|
-
},true);
|
|
138
|
-
await storage.sync();
|
|
139
|
-
},
|
|
140
|
-
async withIngress(work){ready();if(blocked||running)throw fail('BUSY');running=true;try{return await work();}finally{running=false;}},
|
|
141
|
-
async withProjectLock({projectId,requestId,mode='perform',signal},work){check(signal);if(blocked||running)throw fail('BUSY');running=true;let authority,started=false,confirmed=false,value,failure,failed=false,timer;const controller=new AbortController(),currentSignal=AbortSignal.any([signal,controller.signal].filter(Boolean));
|
|
142
|
-
try{
|
|
143
|
-
authority=transaction(()=>{const project=read('project:'+projectId)?.payload,item=project?.requests.find(item=>item.intent.requestId===requestId),previous=one('SELECT * FROM publishing_leases WHERE project=?',projectId);if(!item||project.policy.disabled||project.policy.policyRevision!==item.intent.policyRevision)throw fail('POLICY_CHANGED');if(previous?.until_ms>now())throw fail('BUSY');const value={kind:'worker',projectId,requestId,policyRevision:project.policy.policyRevision,revision:(previous?.revision??0)+1,owner:randomUUID(),mode};sql.exec('INSERT INTO publishing_leases VALUES(?,?,?,?,?,?) ON CONFLICT(project) DO UPDATE SET request=excluded.request,intent=excluded.intent,revision=excluded.revision,owner=excluded.owner,until_ms=excluded.until_ms',projectId,requestId,item.intentSha256,value.revision,value.owner,now()+leaseMs);return value;},mode==='observe');await storage.sync();check(signal);
|
|
144
|
-
timer=setTimeout(()=>controller.abort(fail('LEASE_LOST')),leaseMs);
|
|
145
|
-
value=await context.run(authority,()=>work({signal:currentSignal,async assertHeld(){check(currentSignal);transaction(()=>authorize(authority,'project:'+projectId,read('project:'+projectId)?.payload),true);},beginOperation(){started=true;confirmed=false;},confirmClosure(closure){confirmed=closure?.status==='closed'&&closure.activeRequests===0;}}));
|
|
146
|
-
}catch(error){failed=true;failure=error;}finally{clearTimeout(timer);try{if(started&&!confirmed){blocked=true;}else if(authority){transaction(()=>{const lease=one('SELECT revision,owner FROM publishing_leases WHERE project=?',projectId);if(lease?.revision===authority.revision&&lease.owner===authority.owner)sql.exec('UPDATE publishing_leases SET until_ms=0 WHERE project=?',projectId);},true);await storage.sync();}}catch(error){blocked=true;failure=failed?new AggregateError([failure,error],'PUBLISHING_DURABLE_CLOSE_FAILED',{cause:failure}):error;failed=true;}finally{running=false;}}
|
|
147
|
-
if(failed)throw failure;return value;
|
|
148
|
-
},
|
|
149
|
-
get blocked(){return blocked;},get running(){return running;},close(){if(running)throw fail('BUSY');closed=true;}
|
|
150
|
-
};return Object.freeze(api);
|
|
151
|
-
}
|
|
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
|
+
}
|