@xlinklight/publishing 3.0.0-rc.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/package.json +3 -3
- package/src/node/cli.mjs +106 -106
- package/src/worker/journal.d.mts +21 -21
- package/src/worker/journal.mjs +151 -151
- package/src/worker/service.mjs +247 -247
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 zopenge
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zopenge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xlinklight/publishing",
|
|
3
|
-
"version": "3.0.0
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"@openge/forge-artifact-publish": "0.4.1",
|
|
46
46
|
"@openge/forge-generated-artifacts": "0.2.0",
|
|
47
47
|
"@openge/forge-path-safety": "0.1.0",
|
|
48
|
-
"@xlinklight/contracts": "3.0.0
|
|
48
|
+
"@xlinklight/contracts": "3.0.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@xlinklight/platform": "5.0.0
|
|
51
|
+
"@xlinklight/platform": "5.0.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependenciesMeta": {
|
|
54
54
|
"@xlinklight/platform": {
|
package/src/node/cli.mjs
CHANGED
|
@@ -1,106 +1,106 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import fs from 'node:fs/promises';
|
|
3
|
-
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import {fileURLToPath} from 'node:url';
|
|
6
|
-
import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
7
|
-
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
8
|
-
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
|
-
import {openPublishingJournal} from './journal.mjs';
|
|
10
|
-
import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
11
|
-
import {createPublishingWorkflow} from './workflow.mjs';
|
|
12
|
-
|
|
13
|
-
const commands=['credentials','check','publish','status','recover','verify','abandon'];
|
|
14
|
-
const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
|
|
15
|
-
const fail=code=>publishingError(code);
|
|
16
|
-
function parse(args){
|
|
17
|
-
if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
|
|
18
|
-
if(args.length===1&&args[0]==='--help')return {command:'help'};
|
|
19
|
-
const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
|
|
20
|
-
const selected={command},seen=new Set();
|
|
21
|
-
for(let index=1;index<args.length;index++){
|
|
22
|
-
const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
|
|
23
|
-
if(['--root','--state','--producer'].includes(flag)){
|
|
24
|
-
const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
|
|
25
|
-
}else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
|
|
26
|
-
else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
|
|
27
|
-
else if(flag==='--wait-ms'&&command==='publish'){
|
|
28
|
-
const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
|
|
29
|
-
}
|
|
30
|
-
else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
|
|
31
|
-
else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
|
|
32
|
-
else throw fail('CLI_ARGUMENT_INVALID');
|
|
33
|
-
}
|
|
34
|
-
if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
|
|
35
|
-
if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
|
|
36
|
-
for(const key of ['state','producer'])if(selected[key]!==undefined){try{if(validatePortableRelativePath(selected[key])!==selected[key]||key==='producer'&&!selected[key].endsWith('.mjs'))throw Error();}catch{throw fail('CLI_ARGUMENT_INVALID');}}
|
|
37
|
-
return selected;
|
|
38
|
-
}
|
|
39
|
-
async function credentialInput(stdin,signal,timeoutMilliseconds){
|
|
40
|
-
if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
|
|
41
|
-
if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
|
|
42
|
-
const chunks=[];let bytes=0,timer,abort,data,end,error,close;
|
|
43
|
-
let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
|
|
44
|
-
try{
|
|
45
|
-
if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
|
|
46
|
-
await new Promise((resolve,reject)=>{
|
|
47
|
-
let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
|
|
48
|
-
data=value=>{if(settled)return;if(!(value instanceof Uint8Array)&&typeof value!=='string')return rejectOnce('CREDENTIAL_INPUT_INVALID');const chunk=Buffer.from(value);bytes+=chunk.byteLength;if(bytes>16384)return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT');chunks.push(chunk);};
|
|
49
|
-
end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
|
|
50
|
-
stdin.on('data',data);stdin.once('end',end);stdin.once('error',error);stdin.once('close',close);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(()=>rejectOnce('CREDENTIAL_INPUT_TIMEOUT'),timeoutMilliseconds);stdin.resume();
|
|
51
|
-
});
|
|
52
|
-
let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
|
|
53
|
-
if(!protocolRecord(value,['configuration','credential'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
|
|
54
|
-
}catch(error){if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))throw error;throw fail(signal?.aborted?'CREDENTIAL_INPUT_CANCELLED':'CREDENTIAL_INPUT_INVALID');}
|
|
55
|
-
finally{
|
|
56
|
-
clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
|
|
57
|
-
for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
|
|
58
|
-
// Explicit credential input is owned by this call, including blocked pipes.
|
|
59
|
-
stdin.destroy();let closureTimer;
|
|
60
|
-
try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
|
|
61
|
-
finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
function diagnostic(error){
|
|
65
|
-
const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Bounded one-shot CLI. No token, private producer cause, provider output or
|
|
69
|
-
* environment is returned. Callers own private storage ACLs and backup policy. */
|
|
70
|
-
async function executeCommand(selected,options){
|
|
71
|
-
let journal;
|
|
72
|
-
try{
|
|
73
|
-
const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
|
|
74
|
-
const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
|
|
75
|
-
if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
|
|
76
|
-
signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
|
|
77
|
-
if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
|
|
78
|
-
const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
|
|
79
|
-
journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
|
|
80
|
-
const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
|
|
81
|
-
if(input){
|
|
82
|
-
const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
|
|
83
|
-
return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
|
|
84
|
-
}
|
|
85
|
-
const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
|
|
86
|
-
const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
|
|
87
|
-
const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
|
|
88
|
-
const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
|
|
89
|
-
return {exitCode,output:result};
|
|
90
|
-
}finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export async function runPublishingCommand(args,options={}){
|
|
94
|
-
let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
|
|
95
|
-
if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:'deployment/publishing.mjs',stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
|
|
96
|
-
try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
async function main(){
|
|
100
|
-
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
101
|
-
try{const result=await runPublishingCommand(process.argv.slice(2),{signal:controller.signal});process.stdout.write(JSON.stringify(result.output)+'\n');process.exitCode=result.exitCode;}
|
|
102
|
-
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// A producer can import the same public Node entry while the command is running.
|
|
106
|
-
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
7
|
+
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
8
|
+
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
|
+
import {openPublishingJournal} from './journal.mjs';
|
|
10
|
+
import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
11
|
+
import {createPublishingWorkflow} from './workflow.mjs';
|
|
12
|
+
|
|
13
|
+
const commands=['credentials','check','publish','status','recover','verify','abandon'];
|
|
14
|
+
const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
|
|
15
|
+
const fail=code=>publishingError(code);
|
|
16
|
+
function parse(args){
|
|
17
|
+
if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
|
|
18
|
+
if(args.length===1&&args[0]==='--help')return {command:'help'};
|
|
19
|
+
const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
|
|
20
|
+
const selected={command},seen=new Set();
|
|
21
|
+
for(let index=1;index<args.length;index++){
|
|
22
|
+
const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
|
|
23
|
+
if(['--root','--state','--producer'].includes(flag)){
|
|
24
|
+
const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
|
|
25
|
+
}else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
|
|
26
|
+
else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
|
|
27
|
+
else if(flag==='--wait-ms'&&command==='publish'){
|
|
28
|
+
const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
|
|
29
|
+
}
|
|
30
|
+
else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
|
|
31
|
+
else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
|
|
32
|
+
else throw fail('CLI_ARGUMENT_INVALID');
|
|
33
|
+
}
|
|
34
|
+
if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
|
|
35
|
+
if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
|
|
36
|
+
for(const key of ['state','producer'])if(selected[key]!==undefined){try{if(validatePortableRelativePath(selected[key])!==selected[key]||key==='producer'&&!selected[key].endsWith('.mjs'))throw Error();}catch{throw fail('CLI_ARGUMENT_INVALID');}}
|
|
37
|
+
return selected;
|
|
38
|
+
}
|
|
39
|
+
async function credentialInput(stdin,signal,timeoutMilliseconds){
|
|
40
|
+
if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
|
|
41
|
+
if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
|
|
42
|
+
const chunks=[];let bytes=0,timer,abort,data,end,error,close;
|
|
43
|
+
let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
|
|
44
|
+
try{
|
|
45
|
+
if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
|
|
46
|
+
await new Promise((resolve,reject)=>{
|
|
47
|
+
let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
|
|
48
|
+
data=value=>{if(settled)return;if(!(value instanceof Uint8Array)&&typeof value!=='string')return rejectOnce('CREDENTIAL_INPUT_INVALID');const chunk=Buffer.from(value);bytes+=chunk.byteLength;if(bytes>16384)return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT');chunks.push(chunk);};
|
|
49
|
+
end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
|
|
50
|
+
stdin.on('data',data);stdin.once('end',end);stdin.once('error',error);stdin.once('close',close);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(()=>rejectOnce('CREDENTIAL_INPUT_TIMEOUT'),timeoutMilliseconds);stdin.resume();
|
|
51
|
+
});
|
|
52
|
+
let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
|
|
53
|
+
if(!protocolRecord(value,['configuration','credential'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
|
|
54
|
+
}catch(error){if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))throw error;throw fail(signal?.aborted?'CREDENTIAL_INPUT_CANCELLED':'CREDENTIAL_INPUT_INVALID');}
|
|
55
|
+
finally{
|
|
56
|
+
clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
|
|
57
|
+
for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
|
|
58
|
+
// Explicit credential input is owned by this call, including blocked pipes.
|
|
59
|
+
stdin.destroy();let closureTimer;
|
|
60
|
+
try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
|
|
61
|
+
finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function diagnostic(error){
|
|
65
|
+
const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Bounded one-shot CLI. No token, private producer cause, provider output or
|
|
69
|
+
* environment is returned. Callers own private storage ACLs and backup policy. */
|
|
70
|
+
async function executeCommand(selected,options){
|
|
71
|
+
let journal;
|
|
72
|
+
try{
|
|
73
|
+
const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
|
|
74
|
+
const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
|
|
75
|
+
if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
|
|
76
|
+
signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
|
|
77
|
+
if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
|
|
78
|
+
const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
|
|
79
|
+
journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
|
|
80
|
+
const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
|
|
81
|
+
if(input){
|
|
82
|
+
const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
|
|
83
|
+
return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
|
|
84
|
+
}
|
|
85
|
+
const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
|
|
86
|
+
const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
|
|
87
|
+
const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
|
|
88
|
+
const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
|
|
89
|
+
return {exitCode,output:result};
|
|
90
|
+
}finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function runPublishingCommand(args,options={}){
|
|
94
|
+
let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
|
|
95
|
+
if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:'deployment/publishing.mjs',stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
|
|
96
|
+
try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function main(){
|
|
100
|
+
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
101
|
+
try{const result=await runPublishingCommand(process.argv.slice(2),{signal:controller.signal});process.stdout.write(JSON.stringify(result.output)+'\n');process.exitCode=result.exitCode;}
|
|
102
|
+
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A producer can import the same public Node entry while the command is running.
|
|
106
|
+
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
package/src/worker/journal.d.mts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
-
import type {ArtifactOperationJournal,ArtifactTransportClosure} from '@openge/forge-artifact-publish';
|
|
3
|
-
export interface PublishingDurableStorage {readonly sql:{readonly databaseSize:number;exec(query:string,...values:(string|number|ArrayBuffer|null)[]):{toArray():Record<string,unknown>[]}};transactionSync<T>(work:()=>T):T;sync():Promise<void>}
|
|
4
|
-
export interface PublishingDurableLimits {maximumBytes:number;maximumRecords:number;maximumRecordBytes:number;maximumBlobs:number;maximumBlobBytes:number;recoveryReserveBytes:number}
|
|
5
|
-
export interface PublishingDispatch {projectId:string;requestId:string;mode:'perform'|'observe';continue:boolean;acceptanceReceipt?:true}
|
|
6
|
-
export interface PublishingQueueLease extends PublishingDispatch {revision:number;observations:number}
|
|
7
|
-
export interface PublishingMutationAuthority {kind:'configure'|'request'|'worker';projectId:string;requestId?:string;policyRevision?:number;credentialSha256?:string;revision?:number;owner?:string;mode?:'perform'|'observe'}
|
|
8
|
-
export interface PublishingDurableJournal {
|
|
9
|
-
recordCapacity():{used:number;maximum:number};
|
|
10
|
-
load(key:string,options?:{signal?:AbortSignal}):Promise<{revision:number;payload:JsonValue}|undefined>;
|
|
11
|
-
readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>;
|
|
12
|
-
compareAndSet(input:{key:string;expectedRevision:number;payload:JsonValue;blobs?:readonly {sha256:string;bytes:Uint8Array}[]},options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority;dispatch?:PublishingDispatch}):Promise<'stored'|'conflict'>;
|
|
13
|
-
operationJournal():ArtifactOperationJournal;
|
|
14
|
-
enqueue(input:PublishingDispatch,options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority}):Promise<void>;
|
|
15
|
-
nextWake():number|null;take():Promise<PublishingQueueLease|null>;
|
|
16
|
-
finish(job:PublishingQueueLease,options?:{again?:boolean;delayMs?:number;mode?:'perform'|'observe';advance?:boolean;observations?:number}):Promise<void>;
|
|
17
|
-
withIngress<T>(work:()=>Promise<T>):Promise<T>;
|
|
18
|
-
withProjectLock<T>(input:{projectId:string;requestId:string;mode?:'perform'|'observe';signal?:AbortSignal},work:(lease:{signal:AbortSignal;assertHeld():Promise<void>;beginOperation():void;confirmClosure(closure:ArtifactTransportClosure|undefined):void})=>Promise<T>):Promise<T>;
|
|
19
|
-
readonly blocked:boolean;readonly running:boolean;close():void;
|
|
20
|
-
}
|
|
21
|
-
export function openPublishingDurableJournal(input:{storage:PublishingDurableStorage;identity:string;limits:PublishingDurableLimits;now?:()=>number;leaseMs?:number;increaseMaximumRecordsTo?:number}):Promise<PublishingDurableJournal>;
|
|
1
|
+
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
+
import type {ArtifactOperationJournal,ArtifactTransportClosure} from '@openge/forge-artifact-publish';
|
|
3
|
+
export interface PublishingDurableStorage {readonly sql:{readonly databaseSize:number;exec(query:string,...values:(string|number|ArrayBuffer|null)[]):{toArray():Record<string,unknown>[]}};transactionSync<T>(work:()=>T):T;sync():Promise<void>}
|
|
4
|
+
export interface PublishingDurableLimits {maximumBytes:number;maximumRecords:number;maximumRecordBytes:number;maximumBlobs:number;maximumBlobBytes:number;recoveryReserveBytes:number}
|
|
5
|
+
export interface PublishingDispatch {projectId:string;requestId:string;mode:'perform'|'observe';continue:boolean;acceptanceReceipt?:true}
|
|
6
|
+
export interface PublishingQueueLease extends PublishingDispatch {revision:number;observations:number}
|
|
7
|
+
export interface PublishingMutationAuthority {kind:'configure'|'request'|'worker';projectId:string;requestId?:string;policyRevision?:number;credentialSha256?:string;revision?:number;owner?:string;mode?:'perform'|'observe'}
|
|
8
|
+
export interface PublishingDurableJournal {
|
|
9
|
+
recordCapacity():{used:number;maximum:number};
|
|
10
|
+
load(key:string,options?:{signal?:AbortSignal}):Promise<{revision:number;payload:JsonValue}|undefined>;
|
|
11
|
+
readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>;
|
|
12
|
+
compareAndSet(input:{key:string;expectedRevision:number;payload:JsonValue;blobs?:readonly {sha256:string;bytes:Uint8Array}[]},options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority;dispatch?:PublishingDispatch}):Promise<'stored'|'conflict'>;
|
|
13
|
+
operationJournal():ArtifactOperationJournal;
|
|
14
|
+
enqueue(input:PublishingDispatch,options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority}):Promise<void>;
|
|
15
|
+
nextWake():number|null;take():Promise<PublishingQueueLease|null>;
|
|
16
|
+
finish(job:PublishingQueueLease,options?:{again?:boolean;delayMs?:number;mode?:'perform'|'observe';advance?:boolean;observations?:number}):Promise<void>;
|
|
17
|
+
withIngress<T>(work:()=>Promise<T>):Promise<T>;
|
|
18
|
+
withProjectLock<T>(input:{projectId:string;requestId:string;mode?:'perform'|'observe';signal?:AbortSignal},work:(lease:{signal:AbortSignal;assertHeld():Promise<void>;beginOperation():void;confirmClosure(closure:ArtifactTransportClosure|undefined):void})=>Promise<T>):Promise<T>;
|
|
19
|
+
readonly blocked:boolean;readonly running:boolean;close():void;
|
|
20
|
+
}
|
|
21
|
+
export function openPublishingDurableJournal(input:{storage:PublishingDurableStorage;identity:string;limits:PublishingDurableLimits;now?:()=>number;leaseMs?:number;increaseMaximumRecordsTo?:number}):Promise<PublishingDurableJournal>;
|