@milaboratories/pl-deployments 1.2.1 → 1.2.2
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/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ wd: ${r.opts.cwd}`),s.info(" spawning child process"),it.spawn(r.cmd,r.args,r.o
|
|
|
4
4
|
URL: ${r}
|
|
5
5
|
Save to: ${t}`);const{body:i,statusCode:o}=await ot.request(r);if(e.statusCode=o,o!=200){const n=await st.text(i);throw e.errorMsg=`failed to download archive: ${o}, response: ${n.slice(0,1e3)}`,s.error(e.errorMsg),new Error(e.errorMsg)}return e.tmpPath=t+".tmp",await U.Readable.toWeb(i).pipeTo(U.Writable.toWeb(D.createWriteStream(e.tmpPath))),e.wroteTmp=!0,e.tmpExisted=await w.fileExists(e.tmpPath),await m.rename(e.tmpPath,t),e.renamed=!0,e.newExisted=await w.fileExists(t),e}catch(i){const o=`downloadArchive: error ${JSON.stringify(i)} occurred, state: ${JSON.stringify(e)}`;throw s.error(o),new Error(o)}}const yt=".ok";async function $t(s,r,t,e){if(s.info("extracting archive..."),s.info(` archive path: '${r}'`),s.info(` target dir: '${e}'`),!await w.fileExists(r)){const o=`Platforma Backend binary archive not found at '${r}'`;throw s.error(o),new Error(o)}const i=h.join(e,yt);if(await w.fileExists(i)){s.info(`Platforma Backend binaries unpack skipped: '${e}' exists`);return}switch(await w.fileExists(e)&&(s.info(`Removing previous incompletely unpacked folder: '${e}'`),await m.rm(e,{recursive:!0})),s.info(` creating target dir '${e}'`),await m.mkdir(e,{recursive:!0}),s.info(`Unpacking Platforma Backend archive:
|
|
6
6
|
Archive: ${r}
|
|
7
|
-
Target dir: ${e}`),t){case"tgz":await ut.x({file:r,cwd:e,gzip:!0});break;case"zip":await at(r,e);break;default:w.assertNever(t)}await m.writeFile(i,"ok"),s.info(" ... unpack done.")}const Pt={linux:"tgz",macos:"tgz",windows:"zip"};function E(){return"1.
|
|
7
|
+
Target dir: ${e}`),t){case"tgz":await ut.x({file:r,cwd:e,gzip:!0});break;case"zip":await at(r,e);break;default:w.assertNever(t)}await m.writeFile(i,"ok"),s.info(" ... unpack done.")}const Pt={linux:"tgz",macos:"tgz",windows:"zip"};function E(){return"1.24.0"}function vt(){return{type:"Download",version:E()}}async function St(s,r,t){switch(t.type){case"Download":const e=await gt(s,r,"pl",`pl-${t.version}`,F.arch(),F.platform());return h.join(e.baseName,"binaries",Ct[k(F.platform())]);case"Local":return t.path;default:w.assertNever(t)}}const Ct={linux:"platforma",macos:"platforma",windows:"platforma.exe"};function M(s){return h.join(s,"pl_pid")}async function Et(s){if(!await w.fileExists(s))return;const r=await m.readFile(s);return Number(r.toString())}async function At(s,r){await m.writeFile(s,JSON.stringify(r))}function bt(){return{}}function Ft(s,r,t){return s[r]=t,t}async function R(s,r){const t=bt();try{return await r((i,o)=>Ft(t,i,o),t)}catch(e){throw s.error(`error ${e} while doing traced operation, state: ${JSON.stringify(t)}`),e}}const J="config-local.yaml";class L{constructor(r,t,e,i,o,n,c,a){f(this,"instance");f(this,"pid");f(this,"nRuns",0);f(this,"lastRunHistory",{});f(this,"wasStopped",!1);this.logger=r,this.workingDir=t,this.startOptions=e,this.initialStartHistory=i,this.onClose=o,this.onError=n,this.onCloseAndError=c,this.onCloseAndErrorNoStop=a}async start(){await R(this.logger,async(r,t)=>{this.wasStopped=!1;const e=ht(this.logger,this.startOptions);e.on("error",o=>{this.logger.error(`error '${o}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`),this.onError!==void 0&&this.onError(this),this.onCloseAndError!==void 0&&this.onCloseAndError(this),this.onCloseAndErrorNoStop!==void 0&&!this.wasStopped&&this.onCloseAndErrorNoStop(this)}),e.on("close",()=>{this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`),this.onClose!==void 0&&this.onClose(this),this.onCloseAndError!==void 0&&this.onCloseAndError(this),this.onCloseAndErrorNoStop!==void 0&&!this.wasStopped&&this.onCloseAndErrorNoStop(this)}),r("started",!0);const i=r("pidFile",M(this.workingDir));r("pid",w.notEmpty(e.pid)),r("pidWritten",await At(i,w.notEmpty(e.pid))),this.nRuns++,this.instance=e,this.pid=e.pid,this.lastRunHistory=t})}stop(){this.wasStopped=!0,H(w.notEmpty(this.pid))}async waitStopped(){await q(w.notEmpty(this.pid),15e3)}stopped(){return this.wasStopped}async isAlive(){return await x(w.notEmpty(this.pid))}debugInfo(){return{lastRunHistory:this.lastRunHistory,nRuns:this.nRuns,pid:this.pid,workingDir:this.workingDir,initialStartHistory:this.initialStartHistory,wasStopped:this.wasStopped}}}async function Dt(s,r){const t={plBinary:vt(),spawnOptions:{},closeOld:!0,...r};return await R(s,async(e,i)=>{e("startOptions",{...t,config:"too wordy"});const o=h.resolve(t.workingDir);t.closeOld&&e("closeOld",await Ot(s,o));const n=h.join(o,J);s.info(`writing configuration '${n}'...`),await m.writeFile(n,t.config);const c=h.join(o,"binaries"),a=await St(s,c,t.plBinary),u={cmd:e("binaryPath",h.join("binaries",a)),args:["--config",n],opts:{env:{...process.env},cwd:o,stdio:["pipe","ignore","inherit"],windowsHide:!0,...t.spawnOptions}};e("processOpts",{cmd:u.cmd,args:u.args,cwd:u.opts.cwd});const d=new L(s,t.workingDir,u,i,t.onClose,t.onError,t.onCloseAndError,t.onCloseAndErrorNoStop);return await d.start(),d})}async function Ot(s,r){return await R(s,async(t,e)=>{const i=t("pidFilePath",M(r)),o=t("pid",await Et(i)),n=t("wasAlive",await x(o));return o!==void 0&&n&&(t("stopped",H(o)),t("waitStopped",await q(o,1e4))),e})}const xt={keepaliveInterval:6e4,keepaliveCountMax:10};class A{constructor(r,t){f(this,"config");f(this,"homeDir");f(this,"forwardedServers",[]);this.logger=r,this.client=t}static async init(r,t){const e={...xt,...t},i=new A(r,new S.Client);return await i.connect(e),i}getForwardedServers(){return this.forwardedServers}getFullHostName(){var r,t;return`${(r=this.config)==null?void 0:r.host}:${(t=this.config)==null?void 0:t.port}`}getUserName(){var r;return(r=this.config)==null?void 0:r.username}async connect(r){return this.config=r,await kt(this.client,r)}async exec(r){return new Promise((t,e)=>{this.client.exec(r,(i,o)=>{if(i)return e(`ssh.exec: ${r}, error occurred: ${i}`);let n="",c="";o.on("close",a=>{a===0?t({stdout:n,stderr:c}):e(new Error(`Command ${r} exited with code ${a}`))}).on("data",a=>{n+=a.toString()}).stderr.on("data",a=>{c+=a.toString()})})})}static async getAuthTypes(r,t){return new Promise(e=>{let i="";const o=new S.Client;o.on("ready",()=>{o.end();const n=this.extractAuthMethods(i);e(n.length===0?["publickey","password"]:n)}),o.on("error",()=>{o.end(),e(["publickey","password"])}),o.connect({host:r,port:t,username:new Date().getTime().toString(),debug:n=>{i+=`${n}
|
|
8
8
|
`}})})}static extractAuthMethods(r){const t=r.match(/Inbound: Received USERAUTH_FAILURE \((.+)\)/);return t&&t[1]?t[1].split(",").map(e=>e.trim()):[]}async forwardPort(r,t){const e=`ssh.forward:${r.localPort}:${r.remotePort}.id_${O.randomBytes(1).toString("hex")}`;t=t??this.config;const i=new w.RetryablePromise(o=>new Promise((n,c)=>{const a=new S.Client;a.on("ready",()=>{this.logger.info(`${e}.client.ready`),n(a)}),a.on("error",l=>{this.logger.info(`${e}.client.error: ${l}`),o.reset(),c(l)}),a.on("close",()=>{this.logger.info(`${e}.client.closed`),o.reset()}),a.connect(t)}));return await i.ensure(),new Promise((o,n)=>{const c=j.createServer({pauseOnConnect:!0},async a=>{const l=`${e}.sock_${O.randomBytes(1).toString("hex")}`;let u;try{u=await i.ensure()}catch(y){this.logger.info(`${l}.persistentClient.catch: ${y}`),a.end();return}u.setNoDelay(!0),a.setNoDelay(!0);let d;try{d=await Rt(this.logger,u,"127.0.0.1",0,"127.0.0.1",r.remotePort)}catch(y){this.logger.error(`${l}.forwardOut.err: ${y}`),a.end();return}a.pipe(d),d.pipe(a),a.resume(),d.on("error",y=>{this.logger.error(`${l}.stream.error: ${y}`),a.end(),d.end()}),d.on("close",()=>{a.end(),d.end()}),a.on("close",()=>{this.logger.info(`${l}.localSocket: closed`),a.end(),d.end()})});c.listen(r.localPort,"127.0.0.1",()=>{this.logger.info(`${e}.server: started listening`),this.forwardedServers.push(c),o({server:c})}),c.on("error",a=>{c.close(),n(new Error(`${e}.server: error: ${JSON.stringify(a)}`))}),c.on("close",()=>{this.logger.info(`${e}.server: closed ${JSON.stringify(r)}`),this.forwardedServers=this.forwardedServers.filter(a=>a!==c)})})}closeForwardedPorts(){this.logger.info("[SSH] Closing all forwarded ports..."),this.forwardedServers.forEach(r=>{const t=r.address();if(t&&typeof t!="string"){const e=t;this.logger.info(`[SSH] Closing port forward for server ${e.address}:${e.port}`)}r.close()}),this.forwardedServers=[]}static async checkHostAvailability(r){return new Promise(t=>{ct.lookup(r,e=>{t(!e)})})}static async isPassphraseRequiredForKey(r){return new Promise((t,e)=>{try{return S.utils.parseKey(r)instanceof Error&&t(!0),t(!1)}catch(i){console.log("Error parsing privateKey"),e(new Error(`ssh.isPassphraseRequiredForKey: err ${i}`))}})}async uploadFile(r,t){return await this.withSftp(async e=>new Promise((i,o)=>{e.fastPut(r,t,n=>{if(n){const c=new Error(`ssh.uploadFile: err: ${n}, localPath: ${r}, remotePath: ${t}`);return o(c)}i(!0)})}))}async withSftp(r){return new Promise((t,e)=>{this.client.sftp((i,o)=>{if(i)return e(new Error(`ssh.withSftp: sftp err: ${i}`));r(o).then(t).catch(n=>{e(new Error(`ssh.withSftp.callback: err ${n}`))}).finally(()=>{o==null||o.end()})})})}async writeFileOnTheServer(r,t,e=432){return this.withSftp(async i=>this.writeFile(i,r,t,e))}async getForderStructure(r,t,e={files:[],directories:[]}){return new Promise((i,o)=>{r.readdir(t,async(n,c)=>{if(n)return o(n);for(const a of c){const l=`${t}/${a.filename}`;if(a.attrs.isDirectory()){e.directories.push(l);try{await this.getForderStructure(r,l,e)}catch(u){return o(u)}}else e.files.push(l)}i(e)})})}rmdir(r,t){return new Promise((e,i)=>{r.rmdir(t,o=>o?i(o):e(!0))})}unlink(r,t){return new Promise((e,i)=>{r.unlink(t,o=>o?i(o):e(!0))})}async deleteFolder(r){return this.withSftp(async t=>{try{const e=await this.getForderStructure(t,r);this.logger.info("ssh.deleteFolder list of files and directories"),this.logger.info(`ssh.deleteFolder list of files: ${e.files}`),this.logger.info(`ssh.deleteFolder list of directories: ${e.directories}`);for(const i of e.files)this.logger.info(`ssh.deleteFolder unlink file ${i}`),await this.unlink(t,i);e.directories.sort((i,o)=>o.length-i.length);for(const i of e.directories)this.logger.info(`ssh.deleteFolder rmdir ${i}`),await this.rmdir(t,i);return await this.rmdir(t,r),!0}catch(e){this.logger.error(e);const i=e instanceof Error?e.message:"";throw new Error(`ssh.deleteFolder: path: ${r}, message: ${i}`)}})}async readFile(r){return this.withSftp(async t=>new Promise((e,i)=>{t.readFile(r,(o,n)=>{if(o)return i(new Error(`ssh.readFile: err occurred ${o}`));e(n.toString())})}))}async chmod(r,t){return this.withSftp(async e=>new Promise((i,o)=>{e.chmod(r,t,n=>n?o(new Error(`ssh.chmod: ${n}, path: ${r}, mode: ${t}`)):i(void 0))}))}async checkFileExists(r){return this.withSftp(async t=>new Promise((e,i)=>{t.stat(r,(o,n)=>{if(o)return(o==null?void 0:o.code)===2?e(!1):i(new Error(`ssh.checkFileExists: err ${o}`));e(n.isFile())})}))}async checkPathExists(r){return this.withSftp(async t=>new Promise((e,i)=>{t.stat(r,(o,n)=>{if(o)return o.code===2?e({exists:!1,isFile:!1,isDirectory:!1}):i(new Error(`ssh.checkPathExists: ${o}`));e({exists:!0,isFile:n.isFile(),isDirectory:n.isDirectory()})})}))}async writeFile(r,t,e,i=432){return new Promise((o,n)=>{r.writeFile(t,e,{mode:i},c=>{if(c)return n(new Error(`ssh.writeFile: err ${c}, remotePath: ${t}`));o(!0)})})}uploadFileUsingExistingSftp(r,t,e,i=432){return new Promise((o,n)=>{m.readFile(t).then(async c=>{this.writeFile(r,e,c,i).then(()=>{o(void 0)}).catch(a=>{const l=`uploadFileUsingExistingSftp: error ${a} occurred`;this.logger.error(l),n(new Error(l))})})})}async __uploadDirectory(r,t,e,i=432){return new Promise((o,n)=>{D.readdir(t,async(c,a)=>{if(c)return n(new Error(`ssh.__uploadDir: err ${c}, localDir: ${t}, remoteDir: ${e}`));try{await this.__createRemoteDirectory(r,e);for(const l of a){const u=h.join(t,l),d=`${e}/${l}`;D.lstatSync(u).isDirectory()?await this.__uploadDirectory(r,u,d,i):await this.uploadFileUsingExistingSftp(r,u,d,i)}o()}catch(l){const u=`ssh.__uploadDir: catched err ${l}`;this.logger.error(u),n(new Error(u))}})})}async uploadDirectory(r,t,e=432){return new Promise((i,o)=>{this.withSftp(async n=>{try{await this.__uploadDirectory(n,r,t,e),i()}catch(c){o(new Error(`ssh.uploadDirectory: ${c}`))}})})}__createRemoteDirectory(r,t){return new Promise((e,i)=>{const o=t.split("/");let n="";const c=a=>{if(a>=o.length)return e();n+=`${o[a]}/`,r.stat(n,l=>{l?r.mkdir(n,u=>{if(u)return i(new Error(`ssh.__createRemDir: err ${u}, remotePath: ${t}`));c(a+1)}):c(a+1)})};c(0)})}ensureRemoteDirCreated(r,t=493){return this.withSftp(async e=>{const i=r.split("/");let o="";for(const n of i){o+=`${n}/`;try{await new Promise((c,a)=>{e.stat(o,l=>{if(!l)return c();e.mkdir(o,{mode:t},u=>{if(u)return a(new Error(`ssh.createRemoteDir: err ${u}, remotePath: ${r}`));c()})})})}catch(c){throw console.error(`Failed to create directory: ${o}`,c),c}}})}async downloadFile(r,t){return this.withSftp(async e=>new Promise((i,o)=>{e.fastGet(r,t,n=>{if(n)return o(new Error(`ssh.downloadFile: err ${n}, remotePath: ${r}, localPath: ${t}`));i(!0)})}))}close(){this.closeForwardedPorts(),this.client.end()}}async function kt(s,r,t,e){return new Promise((i,o)=>{s.on("ready",()=>{i(s)}),s.on("error",n=>{o(new Error(`ssh.connect: error occurred: ${n}`))}),s.on("close",()=>{}),s.connect(r),s.setNoDelay(!0)})}async function Rt(s,r,t,e,i,o){return new Promise((n,c)=>{r.forwardOut(t,e,i,o,(a,l)=>a?(s.error(`forwardOut.error: ${a}`),c(a)):n(l))})}const Nt="minio-2024-12-18T13-15-44Z",Bt="supervisord-0.7.3",Ut="supervisord_0.7.3_Linux_64-bit";function g(s){return h.join(s,".platforma_ssh")}function b(s){return h.join(g(s),"binaries")}function It(s,r){return h.join(b(s),`pl-${E()}-${v(r)}`)}function G(s,r){return h.join(It(s,r),"binaries")}function I(s,r){return h.join(G(s,r),"platforma")}function _t(s,r){return h.join(G(s,r),"free-port")}function W(s,r){return h.join(b(s),`minio-2024-12-18T13-15-44Z-${v(r)}`)}function Tt(s,r){return h.join(W(s,r),"minio")}function jt(s,r){return h.join(b(s),`supervisord-0.7.3-${v(r)}`,Ut)}function V(s,r){return h.join(jt(s,r),"supervisord")}function K(s){return h.join(g(s),"supervisor.conf")}function _(s){return h.join(g(s),"connection.txt")}async function Ht(s,r,t){const e=await N(s,r,t,"--daemon");if(e.stderr)throw new Error(`Can not run ssh Platforma ${e.stderr}`)}async function qt(s,r,t){const e=await N(s,r,t,"ctl shutdown");if(e.stderr)throw new Error(`Can not stop ssh Platforma ${e.stderr}`)}async function zt(s,r,t,e){let i;try{i=await N(r,t,e,"ctl status")}catch(a){return{execError:String(a),allAlive:!1}}if(i.stderr)return s.info(`supervisord ctl status: stderr occurred: ${i.stderr}, stdout: ${i.stdout}`),{rawResult:i,allAlive:!1};const o=T(i.stdout,"platforma"),n=T(i.stdout,"minio"),c={rawResult:i,platforma:o,minio:n,allAlive:o&&n};return c.allAlive||(c.minio||s.warn("Minio is not running on the server"),c.platforma||s.warn("Platforma is not running on the server")),c}function Mt(s,r,t,e,i,o,n){const c=Object.entries(r).map(([u,d])=>`${u}="${d}"`).join(","),a=O.randomBytes(16).toString("hex"),l=t;return`
|
|
9
9
|
[supervisord]
|
|
10
10
|
logfile=${e}/supervisord.log
|
package/dist/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-deployments",
|
|
3
|
-
"version": "1.2.
|
|
4
|
-
"pl-version": "1.
|
|
3
|
+
"version": "1.2.2",
|
|
4
|
+
"pl-version": "1.24.0",
|
|
5
5
|
"description": "MiLaboratories Platforma Backend code service run wrapper",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"utility-types": "^3.11.0",
|
|
40
40
|
"vite": "^5.4.11",
|
|
41
41
|
"vitest": "^2.1.8",
|
|
42
|
-
"@milaboratories/
|
|
43
|
-
"@milaboratories/
|
|
42
|
+
"@milaboratories/platforma-build-configs": "1.0.2",
|
|
43
|
+
"@milaboratories/eslint-config": "^1.0.1"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"decompress": "^4.2.1",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"undici": "~7.2.3",
|
|
51
51
|
"yaml": "^2.6.1",
|
|
52
52
|
"zod": "~3.23.8",
|
|
53
|
-
"@milaboratories/
|
|
54
|
-
"@milaboratories/
|
|
53
|
+
"@milaboratories/ts-helpers": "^1.1.4",
|
|
54
|
+
"@milaboratories/pl-config": "^1.4.3"
|
|
55
55
|
},
|
|
56
56
|
"scripts": {
|
|
57
57
|
"type-check": "tsc --noEmit --composite false",
|